"Custom macro" load("@aspect_rules_js//js:defs.bzl", "js_binary", "js_library", "js_run_binary", "js_test") load("@aspect_rules_ts//ts:defs.bzl", "ts_project") load("@bazel_lib//lib:write_source_files.bzl", "write_source_files") load("//tools:oxc_transpiler.bzl", "oxc_transpiler") load("//tools:tsconfig.bzl", "BASE_NODE_TSCONFIG", "BASE_TSCONFIG", "ESNEXT_TSCONFIG", "packages_tsconfig") def ts_compile_node(name, srcs, deps = [], data = [], visibility = None): """Compile TS with prefilled args, specifically for Node tooling. Args: name: target name srcs: src files deps: deps data: add data deps like internal transitive deps visibility: visibility """ esnext_tsconfig = packages_tsconfig(ESNEXT_TSCONFIG) # Type check only with TypeScript 7 (fast, parallel) ts_project( name = "%s-esm-esnext-typecheck" % name, srcs = srcs, declaration = True, tsconfig = esnext_tsconfig, resolve_json_module = True, deps = deps, no_emit = True, ) # Transpile with oxc-transform (fast JS and .d.ts generation) ts_project( name = "%s-esm-esnext" % name, srcs = srcs, declaration = True, tsconfig = esnext_tsconfig, resolve_json_module = True, deps = deps + ["//:node_modules/oxc-transform"], transpiler = oxc_transpiler, declaration_transpiler = oxc_transpiler, ) js_library( name = name, srcs = [":%s-esm-esnext" % name, "package.json"], data = data, visibility = visibility, ) def ts_compile(name, srcs, deps = [], visibility = None, tsconfig = None, package_json = True): """Compile TS with prefilled args. Args: name: target name srcs: src files deps: deps visibility: visibility tsconfig: optional tsconfig dict override (defaults to BASE_TSCONFIG) package_json: whether to include package.json in js_library srcs (default True) """ effective_tsconfig = tsconfig or packages_tsconfig() # Always build ESM bundle # Type check only with TypeScript 7 (fast, parallel) ts_project( name = "%s-esm-typecheck" % name, srcs = srcs, declaration = True, tsconfig = effective_tsconfig, resolve_json_module = True, deps = deps, no_emit = True, ) # Transpile with oxc-transform (fast JS and .d.ts generation) ts_project( name = "%s-esm" % name, srcs = srcs, declaration = True, tsconfig = effective_tsconfig, resolve_json_module = True, deps = deps + ["//:node_modules/oxc-transform"], transpiler = oxc_transpiler, declaration_transpiler = oxc_transpiler, ) js_library( name = name, srcs = [":%s-esm" % name] + (["package.json"] if package_json else []), visibility = visibility, ) def ts_binary(name, data = [], node_options = [], tsconfig_types = [], deps = [], **kwargs): """Create a TS binary with prefilled args. Args: name: target name deps: Gazelle's sibling library dependencies data: data files or dependencies node_options: additional Node.js options tsconfig_types: accepted for gazelle_ts compatibility; ts_binary runs sources directly with Node's type stripping and does not typecheck. **kwargs: additional arguments passed to js_binary """ js_binary( name = name, data = deps + data, node_options = node_options + [ "--experimental-transform-types", ], **kwargs ) def ts_run_binary(name, entry_point = None, args = [], tool = None, chdir = None, srcs = [], outs = [], out_dirs = [], **kwargs): """Runs a TypeScript binary, optionally creating the tool if not provided. Args: name: target name entry_point: entry point script for the binary args: arguments to pass to the binary tool: tool binary label (optional) chdir: working directory to run the binary in (optional) srcs: source files required by the binary outs: output files generated by the binary out_dirs: output directories generated by the binary **kwargs: additional arguments passed to js_run_binary """ if not tool and not entry_point: fail("Either tool or entry_point must be provided to ts_run_binary") if not tool: ts_binary( name = "%s_tool" % name, entry_point = entry_point, chdir = chdir, ) js_run_binary( name = name, tool = tool if tool else ":%s_tool" % name, chdir = chdir, srcs = srcs, outs = outs, out_dirs = out_dirs, args = args, **kwargs ) def generate_src_file(name, src, entry_point = None, tool = None, chdir = None, args = [], data = [], visibility = [], tags = []): """Generate a source file. Args: name: target name args: args to generate src file binary data: dependent data labels src: src file to generate entry_point: generation script entry point visibility: target visibility chdir: whether to chdir to another dir tool: tool binary label tags: tags to apply to the target """ file_ext = src[src.rindex(".") + 1:] tmp_filename = "%s.tmp.%s" % (name, file_ext) # File extensions supported by oxfmt oxfmt_extensions = [ "js", "jsx", "ts", "tsx", "mjs", "cjs", "mts", "cts", "vue", "html", "mjml", "css", "scss", "less", "md", "mdx", "graphql", "gql", "yaml", "yml", "toml", "json", "jsonc", "json5", ] ts_run_binary( name = tmp_filename[:tmp_filename.rindex(".")], outs = [tmp_filename], entry_point = entry_point, tool = tool, # NOTE: assumes that all scripts called here accept `--out` and # also uses fs-extra + minimist. args = args + [ "--out", "$(rootpath %s)" % tmp_filename, ], chdir = chdir, srcs = data + [ "//:node_modules/fs-extra", "//:node_modules/minimist", ], ) # Format the generated file if oxfmt supports this file type if file_ext in oxfmt_extensions: formatted_filename = "%s.formatted.%s" % (name, file_ext) native.genrule( name = "%s_format" % name, srcs = [tmp_filename], outs = [formatted_filename], cmd = "cat $(location %s) | $(location //:oxfmt) --stdin-filepath=$(location %s) > $@" % (tmp_filename, tmp_filename), tools = ["//:oxfmt"], ) final_file = formatted_filename else: final_file = tmp_filename files = {} files[src] = final_file write_source_files( name = name, files = files, visibility = visibility + [ "//:__pkg__", ], suggested_update_target = "//%s:%s" % (native.package_name(), tmp_filename[:tmp_filename.rindex(".")]), tags = tags + ["codegen"], ) def _relative_path(target, start): """Compute the relative path from start directory to target directory. Args: target: target directory path (e.g. "packages/ecma402-abstract") start: start directory path (e.g. "packages/intl-locale") Returns: Relative path string (e.g. "../ecma402-abstract") """ t_pieces = target.split("/") s_pieces = start.split("/") common_len = 0 for tp, sp in zip(t_pieces, s_pieces): if tp == sp: common_len += 1 else: break result = [".."] * (len(s_pieces) - common_len) + t_pieces[common_len:] path = "/".join(result) if result else "." if not path.startswith("."): path = "./" + path return path def _tsconfig_file_impl(ctx): ctx.actions.write( output = ctx.outputs.out, content = ctx.attr.content, ) return [DefaultInfo(files = depset([ctx.outputs.out]))] _tsconfig_file = rule( implementation = _tsconfig_file_impl, attrs = { "content": attr.string(mandatory = True), "out": attr.output(mandatory = True), }, ) def generate_tsconfig_json(name = "tsconfig_json", tsconfig = None, local_only = False): """Generate a tsconfig.json file. Args: name: target name (default: "tsconfig_json") tsconfig: tsconfig JSON content local_only: whether the source file is local developer state and should not be checked into source control """ if tsconfig == None: fail("tsconfig must be provided") content = json.encode_indent(tsconfig, indent = " ") tmp_name = name + "_unformatted" _tsconfig_file( name = tmp_name, content = content, out = tmp_name + ".json", ) native.genrule( name = name + "_generated", srcs = [tmp_name + ".json"], outs = [name + ".generated.json"], cmd = "$(location //:oxfmt) --stdin-filepath=$< < $< > $@", tools = ["//:oxfmt"], visibility = ["//visibility:public"], ) write_source_files( name = name, check_that_out_file_exists = not local_only, diff_test = not local_only, files = {"tsconfig.json": name + "_generated"}, visibility = ["//visibility:public"], ) def generate_ide_tsconfig_json(name = "tsconfig_json", composite = False, project_references = [], tsconfig_types = [], local_only = None): """Generate a tsconfig.json file with the correct extends path based on package depth. This macro calculates the correct relative path to the root tsconfig.json based on the package's location in the repository. It also generates path aliases so that #packages/* imports resolve correctly at any depth. Args: name: target name (default: "tsconfig_json") composite: whether to enable TypeScript composite projects (default: False) project_references: list of Bazel package labels to reference (e.g. ["//packages/ecma402-abstract"]) tsconfig_types: optional compilerOptions.types entries discovered by gazelle_ts local_only: whether the source file is local developer state and should not be checked into source control. Defaults to True for packages. """ package = native.package_name() if local_only == None: local_only = package.startswith("packages/") # Calculate depth: count number of directory levels # Empty string (root) = 0, "docs" = 1, "packages/foo" = 2 depth = len(package.split("/")) if package else 0 # Generate the relative path to repo root: one "../" per level # For packages/foo (depth=2): ../.. # For packages/foo/scripts (depth=3): ../../.. relative_to_root = "/".join([".."] * depth) if depth else "." extends_path = relative_to_root + "/tsconfig.json" compiler_options = { "paths": { "#packages/*": [relative_to_root + "/packages/*"], }, } if composite: compiler_options["composite"] = True if tsconfig_types: compiler_options["types"] = tsconfig_types # Build tsconfig tsconfig = { "extends": extends_path, "compilerOptions": compiler_options, } # Automatically exclude child Bazel sub-packages to avoid double-compilation # in composite project setups. Uses native.subpackages() to discover them. child_excludes = [ "./{subpackage}/**/*".format(subpackage = subpackage) for subpackage in native.subpackages(include = ["*"], allow_empty = True) ] if child_excludes: tsconfig["exclude"] = child_excludes # Convert project_references (Bazel labels) to relative tsconfig paths. # Labels may carry an explicit target (e.g. "//pkg/foo:dist"); strip it # before computing the package-relative path so the tsconfig reference # points at the directory. if project_references: refs = [] for ref in project_references: ref_path = ref.lstrip("/") if ":" in ref_path: ref_path = ref_path.split(":")[0] relative = _relative_path(ref_path, package) refs.append({"path": relative + "/tsconfig.json"}) tsconfig["references"] = refs generate_tsconfig_json( name = name, local_only = local_only, tsconfig = tsconfig, ) def no_internal_imports_test(name, data): """Test that no #packages/ path aliases leak into bundled .js or .d.ts output. Args: name: target name data: list of bundle targets to check (files or directories) """ js_test( name = name, size = "small", args = ["$(rootpath %s)" % d for d in data], data = data + ["//:node_modules/minimist"], entry_point = "//tools:check_no_internal_imports", node_options = ["--experimental-transform-types"], ) def package_exports_test(name, pkg, target_compatible_with = []): """Test that all files referenced in package.json exports actually exist in the npm package. Args: name: target name pkg: label of the npm_package target (e.g. ":pkg") target_compatible_with: constraints of the package build platform """ js_test( name = name, size = "small", args = ["$(rootpath %s)" % pkg], data = [pkg, "//:node_modules/minimist"], entry_point = "//tools:check_package_exports", node_options = ["--experimental-transform-types"], target_compatible_with = target_compatible_with, ) def package_json_test(name, bundles, package_json = "package.json"): """Verify every bare import in `bundles` is declared in `package.json`. rolldown externalizes everything in BUILD.bazel `deps` under `//:node_modules/`. If those packages aren't also declared in `package.json` `dependencies`/`peerDependencies`, the published bundle fails to resolve at consume time — even though every internal test passes (formatjs#6467). Args: name: target name bundles: list of rolldown_bundle targets whose .js output to scan package_json: package.json label (default "package.json") """ js_test( name = name, size = "small", args = ["--pkg", "$(rootpath %s)" % package_json] + ["--bundle=$(rootpath %s)" % b for b in bundles], data = [package_json] + bundles + [ "//:node_modules/minimist", "//:node_modules/oxc-parser", ], entry_point = "//tools:check_package_json", node_options = ["--experimental-transform-types"], )