@effected/bundler 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/Bundler.js +498 -0
  2. package/BundlerError.js +39 -0
  3. package/LICENSE +21 -0
  4. package/README.md +84 -2
  5. package/action/ActionBuilder.js +108 -0
  6. package/action/ActionBundle.js +272 -0
  7. package/action/ActionErrors.js +83 -0
  8. package/action/ActionValidation.js +195 -0
  9. package/action/ActionYml.js +366 -0
  10. package/action/PersistLocal.js +186 -0
  11. package/action/entries.js +23 -0
  12. package/action/ignore-stub-plugin.js +25 -0
  13. package/action/import-check.js +134 -0
  14. package/assets/Inter-SemiBold.ttf +0 -0
  15. package/assets/LICENSE-Inter.txt +92 -0
  16. package/catalog/resolve-catalogs.js +32 -0
  17. package/changesets/next-versions.js +50 -0
  18. package/config/ActionConfig.js +102 -0
  19. package/config/BuildConfig.js +438 -0
  20. package/config/EffectedConfigFile.js +171 -0
  21. package/config/merge.js +20 -0
  22. package/config/plugins.js +84 -0
  23. package/config-validation/ConfigValidator.js +73 -0
  24. package/dts/bundled-siblings.js +108 -0
  25. package/dts/parse.js +28 -0
  26. package/dts/reexport-stub.js +94 -0
  27. package/dts/relative-imports.js +33 -0
  28. package/dts/resolved-tsconfig.js +238 -0
  29. package/entries/ambient-dts.js +108 -0
  30. package/entries/export-paths.js +16 -0
  31. package/entries/extract.js +79 -0
  32. package/entries/package-json-entries.js +19 -0
  33. package/errors.js +37 -0
  34. package/exe/build.js +55 -0
  35. package/exe/config.js +54 -0
  36. package/exe/filename.js +13 -0
  37. package/index.d.ts +3619 -0
  38. package/index.js +57 -0
  39. package/internal/causeMessage.js +57 -0
  40. package/journal/BuildJournal.js +107 -0
  41. package/jsx/config.js +44 -0
  42. package/manifest/built-condition.js +120 -0
  43. package/manifest/emit-manifest.js +93 -0
  44. package/manifest/export-patterns.js +56 -0
  45. package/manifest/manifest-set.js +101 -0
  46. package/manifest/transform.js +324 -0
  47. package/meta/api-extractor.js +241 -0
  48. package/meta/bundle-config.js +22 -0
  49. package/meta/bundle-manifest.js +134 -0
  50. package/meta/bundle-source.js +106 -0
  51. package/meta/config.js +24 -0
  52. package/meta/generate.js +249 -0
  53. package/meta/merge-models.js +43 -0
  54. package/meta/message-suppressor.js +43 -0
  55. package/meta/og-image.js +137 -0
  56. package/meta/og-satori.js +140 -0
  57. package/meta/optimistic.js +32 -0
  58. package/meta/run-pass.js +124 -0
  59. package/meta/scrub-declaration-maps.js +63 -0
  60. package/meta/tsconfig-resolver.js +55 -0
  61. package/meta/tsdoc-config.js +47 -0
  62. package/package.json +86 -5
  63. package/passes/build-target-groups.js +347 -0
  64. package/passes/cjs-default-interop.js +98 -0
  65. package/passes/loose-files.js +57 -0
  66. package/passes/node-builtin-default-interop.js +79 -0
  67. package/passes/strip-maps.js +40 -0
  68. package/passes/sync-public.js +100 -0
  69. package/passes/target-groups.js +112 -0
  70. package/report/ci-annotations.js +36 -0
  71. package/report/collector.js +140 -0
  72. package/report/issues-artifact.js +149 -0
  73. package/report/metrics-plugin.js +76 -0
  74. package/report/schema.js +77 -0
  75. package/report/timer.js +19 -0
  76. package/report/tsdown-logger.js +58 -0
  77. package/targets/binding.js +19 -0
  78. package/targets/config.js +21 -0
  79. package/targets/resolve-targets.js +165 -0
  80. package/tsconfig/sync-options.js +20 -0
  81. package/tsdoc-metadata.json +11 -0
@@ -0,0 +1,84 @@
1
+ import { causeMessage } from "../internal/causeMessage.js";
2
+ import { Effect, Predicate, Schema } from "effect";
3
+ import { resolve } from "node:path";
4
+ import { createJiti } from "jiti";
5
+
6
+ // src/config/plugins.ts
7
+ /**
8
+ * A module named in `package.build.plugins` could not be loaded as a rolldown plugin.
9
+ *
10
+ * @public
11
+ */
12
+ var PluginLoadError = class extends Schema.TaggedError()("PluginLoadError", {
13
+ /** The module's resolved path. */
14
+ path: Schema.String,
15
+ /** What was wrong with it. */
16
+ reason: Schema.String
17
+ }) {
18
+ get message() {
19
+ return `Failed to load plugin ${this.path}: ${this.reason}`;
20
+ }
21
+ };
22
+ /**
23
+ * The default importer's jiti, with the options the schema config loader uses, so a `.ts` module loads.
24
+ *
25
+ * @remarks
26
+ * Built per load because `moduleCache` and `fsCache` are off and the importer's base path is the module's own.
27
+ */
28
+ const importWithJiti = (path) => createJiti(path, {
29
+ interopDefault: true,
30
+ moduleCache: false,
31
+ fsCache: false
32
+ }).import(path);
33
+ const isPlugin = (value) => typeof value === "object" && Predicate.hasProperty(value, "name") && Predicate.isString(value.name);
34
+ /** Turns a module's default export into its plugin. */
35
+ const pluginOf = (path, value) => {
36
+ if (!Predicate.hasProperty(value, "default")) return Effect.fail(new PluginLoadError({
37
+ path,
38
+ reason: "the module has no default export"
39
+ }));
40
+ const exported = value.default;
41
+ if (isPlugin(exported)) return Effect.succeed(exported);
42
+ if (typeof exported !== "function") return Effect.fail(new PluginLoadError({
43
+ path,
44
+ reason: "the default export is not a rolldown plugin or a factory of one"
45
+ }));
46
+ return Effect.try({
47
+ try: () => exported(),
48
+ catch: (cause) => new PluginLoadError({
49
+ path,
50
+ reason: `the default export factory threw: ${causeMessage(cause) ?? String(cause)}`
51
+ })
52
+ }).pipe(Effect.flatMap((made) => isPlugin(made) ? Effect.succeed(made) : Effect.fail(new PluginLoadError({
53
+ path,
54
+ reason: "the default export factory did not return a rolldown plugin"
55
+ }))));
56
+ };
57
+ /**
58
+ * Loads the rolldown plugins named in `package.build.plugins`, in order.
59
+ *
60
+ * @remarks
61
+ * Each module path resolves against `cwd`, so a bare `build/plugin.ts` is a file in the package rather than a
62
+ * package name. A module's default export is a plugin, or a factory of one that is called once. Loading runs
63
+ * the module's code, and stops at the first module that fails.
64
+ *
65
+ * @param options - `cwd` is the package directory and `modules` the paths to load. `importModule` replaces the
66
+ * default importer, jiti, which loads TypeScript directly.
67
+ *
68
+ * @public
69
+ */
70
+ const loadPlugins = Effect.fn("loadPlugins")(function* (options) {
71
+ const importModule = options.importModule ?? importWithJiti;
72
+ return yield* Effect.forEach(options.modules, (module) => {
73
+ const path = resolve(options.cwd, module);
74
+ return Effect.tryPromise({
75
+ try: () => importModule(path),
76
+ catch: (cause) => new PluginLoadError({
77
+ path,
78
+ reason: causeMessage(cause) ?? String(cause)
79
+ })
80
+ }).pipe(Effect.flatMap((value) => pluginOf(path, value)));
81
+ });
82
+ });
83
+
84
+ export { PluginLoadError, loadPlugins };
@@ -0,0 +1,73 @@
1
+ import { ConfigValidationError } from "../errors.js";
2
+ import { normalizeExeOptions } from "../exe/config.js";
3
+ import { normalizeLooseFiles } from "../passes/loose-files.js";
4
+ import { resolveTargets } from "../targets/resolve-targets.js";
5
+ import { Context, Effect, FileSystem, Layer } from "effect";
6
+
7
+ // src/config-validation/ConfigValidator.ts
8
+ const VALID_SYNTAX_KINDS = /* @__PURE__ */ new Set([
9
+ "block",
10
+ "inline",
11
+ "modifier"
12
+ ]);
13
+ /** The synchronous rule set; throws ConfigValidationError on the first violation. */
14
+ function check(input) {
15
+ if (input.targets !== void 0 && Object.keys(input.targets).length > 0) resolveTargets({
16
+ targets: input.targets,
17
+ baseName: input.baseName
18
+ });
19
+ if (input.exe !== void 0) {
20
+ const specs = normalizeExeOptions(input.exe, input.osCpu ?? {
21
+ os: [],
22
+ cpu: []
23
+ });
24
+ for (const spec of specs) {
25
+ if (spec.fileName.trim() === "") throw new ConfigValidationError({
26
+ path: "exe.fileName",
27
+ reason: "an exe binary needs a non-empty fileName"
28
+ });
29
+ if (spec.targets.length === 0) throw new ConfigValidationError({
30
+ path: `exe.${spec.fileName}.targets`,
31
+ reason: "no targets: the package declares no os/cpu and the exe config states none"
32
+ });
33
+ }
34
+ }
35
+ if (input.meta !== void 0) {
36
+ if (!input.hasExports) throw new ConfigValidationError({
37
+ path: "meta",
38
+ reason: "meta requires an exports map to extract an api-model from"
39
+ });
40
+ for (const tag of input.meta.tsdoc?.tagDefinitions ?? []) if (!VALID_SYNTAX_KINDS.has(tag.syntaxKind)) throw new ConfigValidationError({
41
+ path: "meta.tsdoc.tagDefinitions",
42
+ reason: `tag "${tag.tagName}" has an invalid syntaxKind "${tag.syntaxKind}"`
43
+ });
44
+ }
45
+ }
46
+ /** The rules after `meta.localPaths`, which the layer checks against the filesystem between the two. */
47
+ function checkLooseFiles(input) {
48
+ if (input.looseFiles !== void 0) normalizeLooseFiles(input.looseFiles);
49
+ }
50
+ /**
51
+ * Fast-fail config validator; runs first in the bundler over the resolved config.
52
+ *
53
+ * @public
54
+ */
55
+ var ConfigValidator = class extends Context.Service()("@savvy-web/tsdown-plugins/ConfigValidator") {
56
+ static layer = Layer.effect(this, Effect.gen(function* () {
57
+ const fs = yield* FileSystem.FileSystem;
58
+ const checkLocalPaths = (paths) => Effect.forEach(paths, (p) => fs.stat(p).pipe(Effect.option, Effect.flatMap((info) => info._tag === "Some" && info.value.type !== "Directory" ? Effect.fail(new ConfigValidationError({
59
+ path: "meta.localPaths",
60
+ reason: `"${p}" exists but is not a directory`
61
+ })) : Effect.void)));
62
+ const run = (rules) => Effect.try({
63
+ try: rules,
64
+ catch: (e) => e instanceof ConfigValidationError ? e : new ConfigValidationError({
65
+ path: "config",
66
+ reason: String(e)
67
+ })
68
+ });
69
+ return { validate: (input) => run(() => check(input)).pipe(Effect.andThen(checkLocalPaths(input.meta?.localPaths ?? [])), Effect.andThen(run(() => checkLooseFiles(input)))) };
70
+ }));
71
+ };
72
+
73
+ export { ConfigValidator };
@@ -0,0 +1,108 @@
1
+ import { ConfigValidationError } from "../errors.js";
2
+ import { Effect, Layer } from "effect";
3
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
4
+ import { dirname, join, relative, sep } from "node:path";
5
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
6
+ import * as NodePath from "@effect/platform-node/NodePath";
7
+ import { WorkspaceRoot } from "@effected/workspaces";
8
+
9
+ // src/dts/bundled-siblings.ts
10
+ /** The package a `bundledPackages` entry belongs to: an entry may name a subpath, since tsdown matches them exactly. */
11
+ const packageNameOf = (entry) => entry.split("/").slice(0, entry.startsWith("@") ? 2 : 1).join("/");
12
+ /** Bound once: the platform layer is stateless and layers memoize by reference. */
13
+ const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
14
+ const rootLayer = WorkspaceRoot.layer.pipe(Layer.provide(platform));
15
+ /** The workspace root above `cwd`, canonical; absent for a package outside any workspace. */
16
+ const findWorkspaceRoot = (cwd) => Effect.runPromise(Effect.gen(function* () {
17
+ return yield* (yield* WorkspaceRoot).find(cwd);
18
+ }).pipe(Effect.provide(rootLayer), Effect.map((root) => realpathSync(root)), Effect.catch(() => Effect.void.pipe(Effect.as(void 0)))));
19
+ /**
20
+ * The directory `name` links to when that is a sibling: the first `node_modules/<name>` found from `cwd` up to the
21
+ * root, realpathed into the root and outside any `node_modules`. A registry package and a `file:` link to another
22
+ * checkout both fail that, and are inlined the ordinary way.
23
+ */
24
+ const siblingDirOf = (name, cwd, root) => {
25
+ let dir = realpathSync(cwd);
26
+ for (;;) {
27
+ const link = join(dir, "node_modules", name);
28
+ if (existsSync(link)) {
29
+ const target = realpathSync(link);
30
+ const segments = relative(root, target).split(sep);
31
+ return segments[0] === ".." || segments.includes("node_modules") ? void 0 : target;
32
+ }
33
+ if (dir === root || dirname(dir) === dir) return void 0;
34
+ dir = dirname(dir);
35
+ }
36
+ };
37
+ /** The group a sibling's `targets.json` names canonical, by the meta pass's rule; `npm` when it has none to read. */
38
+ const canonicalGroupOf = (siblingDir, name) => {
39
+ try {
40
+ const { groups } = JSON.parse(readFileSync(join(siblingDir, "dist", "prod", "targets.json"), "utf-8"));
41
+ return (groups.find((group) => group.name === name) ?? groups[0])?.id ?? "npm";
42
+ } catch {
43
+ return "npm";
44
+ }
45
+ };
46
+ /** Nested subpaths of the sibling's emitted manifest, each to its absolute declaration file. */
47
+ const nestedExportsOf = (pkgDir, name) => {
48
+ let exportsMap;
49
+ try {
50
+ exportsMap = JSON.parse(readFileSync(join(pkgDir, "package.json"), "utf-8")).exports;
51
+ } catch {
52
+ return {};
53
+ }
54
+ if (typeof exportsMap !== "object" || exportsMap === null) return {};
55
+ const nested = {};
56
+ for (const [key, value] of Object.entries(exportsMap)) {
57
+ const types = value?.types;
58
+ if (/^\.\/[^*]*\/[^*]*$/.test(key) && typeof types === "string") nested[`${name}${key.slice(1)}`] = join(pkgDir, types);
59
+ }
60
+ return nested;
61
+ };
62
+ /**
63
+ * Finds the workspace siblings among `names` and locates each one's built declarations.
64
+ *
65
+ * @remarks
66
+ * Names that are not siblings are left out, and nothing is read when `names` is empty. An entry naming a subpath
67
+ * locates the package it belongs to.
68
+ *
69
+ * @throws {@link ConfigValidationError} when a sibling has no built `index.d.ts`.
70
+ * @public
71
+ */
72
+ async function resolveBundledSiblings(cwd, names) {
73
+ if (names.length === 0) return [];
74
+ const root = await findWorkspaceRoot(cwd);
75
+ if (root === void 0) return [];
76
+ const siblings = [];
77
+ for (const name of new Set(names.map(packageNameOf))) {
78
+ const siblingDir = siblingDirOf(name, cwd, root);
79
+ if (siblingDir === void 0) continue;
80
+ const pkgDir = join(siblingDir, "dist", "prod", canonicalGroupOf(siblingDir, name), "pkg");
81
+ if (!existsSync(join(pkgDir, "index.d.ts"))) throw new ConfigValidationError({
82
+ path: "bundledPackages",
83
+ reason: `"${name}" is a workspace sibling with no built declarations at ${join(pkgDir, "index.d.ts")}. Build ${name} first; a turbo build task that inlines a sibling's types needs dependsOn: ["^build"] in that package's own turbo.json.`
84
+ });
85
+ siblings.push({
86
+ name,
87
+ pkgDir,
88
+ nestedExports: nestedExportsOf(pkgDir, name)
89
+ });
90
+ }
91
+ return siblings;
92
+ }
93
+ /**
94
+ * The tsconfig `paths` map resolving each sibling, and nothing else, to its built declarations.
95
+ *
96
+ * @public
97
+ */
98
+ function siblingPaths(siblings) {
99
+ const paths = {};
100
+ for (const { name, pkgDir, nestedExports } of siblings) {
101
+ paths[name] = [join(pkgDir, "index.d.ts")];
102
+ paths[`${name}/*`] = [join(pkgDir, "*.d.ts")];
103
+ for (const [subpath, file] of Object.entries(nestedExports)) paths[subpath] = [file];
104
+ }
105
+ return paths;
106
+ }
107
+
108
+ export { packageNameOf, resolveBundledSiblings, siblingPaths };
package/dts/parse.js ADDED
@@ -0,0 +1,28 @@
1
+ import { ScriptKind } from "typescript/ast";
2
+ import { API } from "typescript/sync";
3
+
4
+ // src/dts/parse.ts
5
+ /**
6
+ * One lazily-started TypeScript API client for this process. TypeScript 7.1's compiler API lives
7
+ * behind a Go server, so every parse goes through a client; constructing one per call would spawn
8
+ * a process per file. An un-closed client does not hold the Node process open, so the singleton is
9
+ * never explicitly closed — it dies with the process.
10
+ */
11
+ let client;
12
+ /**
13
+ * Parse `source` as a TypeScript module and hand its syntax tree to `use`, releasing the server-side
14
+ * retention afterwards. Pure parsing — no I/O, no type information. The tree must not escape `use`.
15
+ *
16
+ * @internal
17
+ */
18
+ function withParsedSource(fileName, source, use) {
19
+ client ??= new API();
20
+ const retained = client.createSourceFile(fileName, source, { scriptKind: ScriptKind.TS });
21
+ try {
22
+ return use(retained.sourceFile);
23
+ } finally {
24
+ retained.dispose();
25
+ }
26
+ }
27
+
28
+ export { withParsedSource };
@@ -0,0 +1,94 @@
1
+ import { withParsedSource } from "./parse.js";
2
+ import { ModifierFlags, isBindingElement, isClassDeclaration, isEnumDeclaration, isExportDeclaration, isFunctionDeclaration, isIdentifier, isInterfaceDeclaration, isModuleDeclaration, isNamedExports, isNamespaceExport, isTypeAliasDeclaration, isVariableStatement } from "typescript/ast";
3
+
4
+ // src/dts/reexport-stub.ts
5
+ /**
6
+ * Analyze an entry source as a candidate pure re-export barrel: classify its re-exported names into
7
+ * value vs type-only and report whether it is expressible as a thin stub. Pure parsing — no I/O.
8
+ *
9
+ * @public
10
+ */
11
+ function analyzeReexportBarrel(source, fileName = "entry.ts") {
12
+ return withParsedSource(fileName, source, (sf) => analyzeBarrel(sf));
13
+ }
14
+ function analyzeBarrel(sf) {
15
+ const valueNames = [];
16
+ const typeNames = [];
17
+ let pure = true;
18
+ for (const stmt of sf.statements) {
19
+ if (isExportDeclaration(stmt) && stmt.moduleSpecifier !== void 0) {
20
+ const clause = stmt.exportClause;
21
+ if (clause !== void 0 && isNamedExports(clause)) {
22
+ for (const el of clause.elements) (stmt.isTypeOnly || el.isTypeOnly ? typeNames : valueNames).push(el.name.text);
23
+ continue;
24
+ }
25
+ pure = false;
26
+ continue;
27
+ }
28
+ pure = false;
29
+ }
30
+ return {
31
+ valueNames,
32
+ typeNames,
33
+ isPureNamedReexportBarrel: pure
34
+ };
35
+ }
36
+ /**
37
+ * Collect every name a module exports (named re-exports, namespace re-exports, and local `export`
38
+ * declarations). Used to test whether a barrel's re-exports are a strict subset of a base entry, so
39
+ * a stub re-exporting from that base resolves every symbol. Pure parsing — no I/O.
40
+ *
41
+ * @public
42
+ */
43
+ function collectExportNames(source, fileName = "entry.ts") {
44
+ return withParsedSource(fileName, source, (sf) => collectNames(sf));
45
+ }
46
+ function collectNames(sf) {
47
+ const names = /* @__PURE__ */ new Set();
48
+ let complete = true;
49
+ const addBindingName = (name) => {
50
+ if (isIdentifier(name)) names.add(name.text);
51
+ else for (const el of name.elements) if (isBindingElement(el) && el.name !== void 0) addBindingName(el.name);
52
+ };
53
+ for (const stmt of sf.statements) {
54
+ if (isExportDeclaration(stmt)) {
55
+ const clause = stmt.exportClause;
56
+ if (clause === void 0) {
57
+ if (stmt.moduleSpecifier !== void 0) complete = false;
58
+ continue;
59
+ }
60
+ if (isNamespaceExport(clause)) {
61
+ names.add(clause.name.text);
62
+ continue;
63
+ }
64
+ for (const el of clause.elements) names.add(el.name.text);
65
+ continue;
66
+ }
67
+ if (((stmt.modifierFlags ?? 0) & ModifierFlags.Export) === 0) continue;
68
+ if (isVariableStatement(stmt)) {
69
+ for (const decl of stmt.declarationList.declarations) if (decl.name !== void 0) addBindingName(decl.name);
70
+ } else if ((isFunctionDeclaration(stmt) || isClassDeclaration(stmt) || isInterfaceDeclaration(stmt) || isTypeAliasDeclaration(stmt) || isEnumDeclaration(stmt) || isModuleDeclaration(stmt)) && stmt.name !== void 0 && isIdentifier(stmt.name)) names.add(stmt.name.text);
71
+ }
72
+ return {
73
+ names,
74
+ complete
75
+ };
76
+ }
77
+ /**
78
+ * Render a thin re-export-stub `.d.ts`/`.d.cts` body: named re-exports of `valueNames` and
79
+ * `typeNames` from `baseSpecifier` (the published file of the base entry, e.g. `./index.js` for the
80
+ * ESM `.d.ts` or `./index.cjs` for the CJS `.d.cts`). Names are sorted so the output is
81
+ * deterministic. Returns the empty string when there is nothing to re-export.
82
+ *
83
+ * @public
84
+ */
85
+ function renderReexportStub(options) {
86
+ const sortedValues = [...options.valueNames].sort();
87
+ const sortedTypes = [...options.typeNames].sort();
88
+ const lines = [];
89
+ if (sortedValues.length > 0) lines.push(`export { ${sortedValues.join(", ")} } from "${options.baseSpecifier}";`);
90
+ if (sortedTypes.length > 0) lines.push(`export type { ${sortedTypes.join(", ")} } from "${options.baseSpecifier}";`);
91
+ return lines.length > 0 ? `${lines.join("\n")}\n` : "";
92
+ }
93
+
94
+ export { analyzeReexportBarrel, collectExportNames, renderReexportStub };
@@ -0,0 +1,33 @@
1
+ import { withParsedSource } from "./parse.js";
2
+ import { isExportDeclaration, isExternalModuleReference, isImportDeclaration, isImportEqualsDeclaration, isImportTypeNode, isLiteralTypeNode, isStringLiteral } from "typescript/ast";
3
+
4
+ // src/dts/relative-imports.ts
5
+ const isRelative = (s) => s.startsWith("./") || s.startsWith("../");
6
+ /**
7
+ * Find every relative module specifier in a declaration source: static `import`/`export … from`,
8
+ * `import("…")` type nodes, and `/// <reference path="…" />`. Pure parsing — no I/O.
9
+ *
10
+ * A non-empty result means the file is NOT self-contained and would break when copied verbatim to a
11
+ * flattened output location, so the ambient-copy step rejects it.
12
+ * @public
13
+ */
14
+ function findRelativeSpecifiers(source, fileName = "ambient.d.ts") {
15
+ return withParsedSource(fileName, source, (sf) => {
16
+ const found = /* @__PURE__ */ new Set();
17
+ for (const ref of sf.referencedFiles) if (isRelative(ref.fileName)) found.add(ref.fileName);
18
+ const visit = (node) => {
19
+ if ((isImportDeclaration(node) || isExportDeclaration(node)) && node.moduleSpecifier !== void 0 && isStringLiteral(node.moduleSpecifier)) {
20
+ if (isRelative(node.moduleSpecifier.text)) found.add(node.moduleSpecifier.text);
21
+ } else if (isImportTypeNode(node) && isLiteralTypeNode(node.argument) && isStringLiteral(node.argument.literal)) {
22
+ if (isRelative(node.argument.literal.text)) found.add(node.argument.literal.text);
23
+ } else if (isImportEqualsDeclaration(node) && isExternalModuleReference(node.moduleReference) && isStringLiteral(node.moduleReference.expression)) {
24
+ if (isRelative(node.moduleReference.expression.text)) found.add(node.moduleReference.expression.text);
25
+ }
26
+ node.forEachChild(visit);
27
+ };
28
+ visit(sf);
29
+ return [...found];
30
+ });
31
+ }
32
+
33
+ export { findRelativeSpecifiers };
@@ -0,0 +1,238 @@
1
+ import { tsconfigSyncOptions } from "../tsconfig/sync-options.js";
2
+ import { Result } from "effect";
3
+ import { existsSync, realpathSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, isAbsolute, join, resolve } from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import { GlobPattern, GlobPatternOptions } from "@effected/glob";
8
+ import { TsconfigLoaderSync } from "@effected/tsconfig-json";
9
+
10
+ // src/dts/resolved-tsconfig.ts
11
+ /**
12
+ * The dts-pass deltas layered over whatever the package's own tsconfig declares. The shared
13
+ * `ecma.json` base sets `composite`/`incremental` true and points `tsBuildInfoFile` at a build
14
+ * info file; the declaration pass must never skip emit on stale build info, so all three are
15
+ * forced off here. `declarationMap` is forced on for the emitted maps. `declaration` and
16
+ * `emitDeclarationOnly` are forced on/off respectively because this pass's entire job is
17
+ * emitting declarations — it cannot honor a consumer's `declaration: false`; TypeScript's
18
+ * emitter asserts (`Debug Failure` in `getSourceMappingURL`) when `declarationMap` is
19
+ * requested without `declaration`.
20
+ *
21
+ * @internal
22
+ */
23
+ const DTS_OVERLAY = {
24
+ declaration: true,
25
+ declarationMap: true,
26
+ emitDeclarationOnly: false,
27
+ composite: false,
28
+ incremental: false,
29
+ tsBuildInfoFile: void 0
30
+ };
31
+ /**
32
+ * The compiler options used when a package has no own `tsconfig.json` — today's synthesized
33
+ * defaults, preserved verbatim. The e2e `leaf` / `leaf-escape` fixtures build without one, so
34
+ * absence is a supported case, not an error.
35
+ *
36
+ * @internal
37
+ */
38
+ function fallbackCompilerOptions(cwd) {
39
+ return {
40
+ declaration: true,
41
+ emitDeclarationOnly: false,
42
+ rootDir: cwd,
43
+ outDir: join(cwd, "dist"),
44
+ declarationDir: join(cwd, "dist"),
45
+ typeRoots: [join(cwd, "node_modules/@types"), join(cwd, "types")],
46
+ types: ["node"]
47
+ };
48
+ }
49
+ /**
50
+ * Build the portable absolute-path tsconfig object for the dts pass.
51
+ *
52
+ * @remarks
53
+ * Resolves the package's own `<cwd>/tsconfig.json` (which extends the shared
54
+ * `ecma.json` base) through `@effected/tsconfig-json`'s `TsconfigLoaderSync`, so the
55
+ * result carries the package's real effective options — target, module, lib, strict,
56
+ * jsx — with `${configDir}` already substituted to absolute paths. Only the dts-pass
57
+ * overlay (composite/incremental/tsBuildInfoFile forced off, declarationMap forced on)
58
+ * and an explicit jsx override are layered on top.
59
+ *
60
+ * `include`/`exclude` are NOT taken from the resolved config. The shared base includes
61
+ * `__test__` and `lib` sources, which have no business in a declaration program; the
62
+ * narrow list below is dts-pass-specific and deliberately held fixed.
63
+ *
64
+ * @public
65
+ */
66
+ function buildResolvedTsconfig(options) {
67
+ const cwd = options.cwd;
68
+ const ownConfig = join(cwd, "tsconfig.json");
69
+ let base;
70
+ if (existsSync(ownConfig)) try {
71
+ base = { ...TsconfigLoaderSync.resolve(ownConfig, tsconfigSyncOptions).compilerOptions };
72
+ } catch (error) {
73
+ const message = error instanceof Error ? error.message : String(error);
74
+ throw new Error(`Cannot resolve tsconfig at ${ownConfig}: ${message}`, { cause: error });
75
+ }
76
+ else base = fallbackCompilerOptions(cwd);
77
+ return {
78
+ compilerOptions: {
79
+ ...base,
80
+ ...DTS_OVERLAY,
81
+ ...options.jsx !== void 0 ? { jsx: options.jsx } : {},
82
+ ...options.jsxImportSource !== void 0 ? { jsxImportSource: options.jsxImportSource } : {}
83
+ },
84
+ include: [
85
+ join(cwd, "src/**/*.ts"),
86
+ join(cwd, "src/**/*.mts"),
87
+ join(cwd, "src/**/*.tsx"),
88
+ join(cwd, "types/*.d.ts"),
89
+ join(cwd, "package.json")
90
+ ],
91
+ exclude: [join(cwd, "node_modules"), join(cwd, "dist/**/*")]
92
+ };
93
+ }
94
+ /**
95
+ * The base's `files`/`include`/`exclude` (through its whole `extends` chain) as absolute CANONICAL
96
+ * paths under `baseDir`; a base declaring neither `files` nor `include` gets TypeScript's default
97
+ * `**\/*` pinned to `baseDir` explicitly. Paths the base already spelled absolutely (the
98
+ * `writeResolvedTsconfig` output builds them from the package cwd) are canonicalized too, so a
99
+ * symlinked cwd cannot smuggle a non-canonical name past the canonical `extends`. A base the loader
100
+ * cannot resolve contributes nothing (the wrapper then inherits whatever the base declares, as before).
101
+ */
102
+ function absoluteFileSet(configPath, baseDir) {
103
+ let resolved;
104
+ try {
105
+ resolved = TsconfigLoaderSync.resolve(configPath, tsconfigSyncOptions);
106
+ } catch {
107
+ return {};
108
+ }
109
+ const abs = (p) => canonicalGlob(isAbsolute(p) ? p : join(baseDir, p));
110
+ const files = resolved.files?.map(abs);
111
+ const include = resolved.include?.map(abs) ?? (files === void 0 ? [join(baseDir, "**/*")] : void 0);
112
+ const exclude = resolved.exclude?.map(abs);
113
+ return {
114
+ ...files !== void 0 ? { files } : {},
115
+ ...include !== void 0 ? { include } : {},
116
+ ...exclude !== void 0 ? { exclude } : {}
117
+ };
118
+ }
119
+ /**
120
+ * Compiler options the dts program must never inherit, each written as `null`: `customConditions` and `paths`
121
+ * exist to make the TYPECHECK program resolve siblings from source (an export condition, a path alias), while the
122
+ * declaration program must resolve them the way the package manifest says. They are cleared unconditionally rather
123
+ * than only when the base declares them, so nothing about how the base resolves can leave the leak open.
124
+ */
125
+ const DTS_RESET_OPTIONS = {
126
+ customConditions: null,
127
+ paths: null
128
+ };
129
+ /**
130
+ * tsconfig globs have only `*`, `?` and `**`: an extglob's parentheses, or a leading `#` or `!`, are literal
131
+ * text in a directory name, so none of them may end the literal prefix.
132
+ */
133
+ const TSCONFIG_GLOB = GlobPatternOptions.make({
134
+ noext: true,
135
+ nocomment: true,
136
+ nonegate: true
137
+ });
138
+ /**
139
+ * Resolve symlinks in the literal directory prefix of an absolute path or glob (everything before the
140
+ * first segment carrying a glob character), leaving the pattern tail untouched. A pattern the kit rejects,
141
+ * a prefix that does not exist, or one whose spelling the kit changed (an undone escape) is returned unchanged.
142
+ */
143
+ function canonicalGlob(absPath) {
144
+ const compiled = GlobPattern.compileResult(absPath, TSCONFIG_GLOB);
145
+ if (Result.isFailure(compiled)) return absPath;
146
+ const prefix = compiled.success.literalPrefix;
147
+ if (!absPath.startsWith(prefix)) return absPath;
148
+ const tail = absPath.slice(prefix.length);
149
+ let canonicalPrefix;
150
+ try {
151
+ canonicalPrefix = realpathSync.native(prefix);
152
+ } catch {
153
+ return absPath;
154
+ }
155
+ return /^\/*$/.test(tail) ? canonicalPrefix : join(canonicalPrefix, tail);
156
+ }
157
+ /** The longest filename the platforms we build on accept. */
158
+ const MAX_FILE_NAME = 255;
159
+ /**
160
+ * A temp filename deterministic per (pid, key). The key is a path, sanitized into the name when it fits and hashed
161
+ * when it does not: a deep checkout would otherwise fail the write with `ENAMETOOLONG`, and the dts-emit name
162
+ * embeds the already-sanitized bundle name, so it reaches the limit first.
163
+ */
164
+ function tempTsconfigName(prefix, key) {
165
+ const name = `${prefix}-${process.pid}-${key.replace(/[^\w]/g, "_")}.json`;
166
+ if (name.length <= MAX_FILE_NAME) return name;
167
+ return `${prefix}-${process.pid}-${createHash("sha256").update(key).digest("hex").slice(0, 32)}.json`;
168
+ }
169
+ /**
170
+ * Write the resolved tsconfig to a temp file and return its absolute path.
171
+ *
172
+ * @public
173
+ */
174
+ function writeResolvedTsconfig(options) {
175
+ const cfg = buildResolvedTsconfig(options);
176
+ const path = join(tmpdir(), tempTsconfigName("tsconfig-bundle", options.cwd));
177
+ writeFileSync(path, `${JSON.stringify(cfg, null, " ")}\n`, "utf-8");
178
+ return path;
179
+ }
180
+ /**
181
+ * Derive a dts-EMIT variant of an already-written resolved tsconfig that adds
182
+ * `stableTypeOrdering: true`, and return its path. This makes the TypeScript declaration emitter
183
+ * (rolldown-plugin-dts' tsgo generator over this package's `typescript`) order union/type members
184
+ * deterministically, so a multi-union `.d.ts` (e.g. an Effect `Layer.Layer<…>` requirement channel)
185
+ * does not flip member order across otherwise-identical builds (#156). It is kept in a SEPARATE file
186
+ * from the api-extractor tsconfig on purpose: `@microsoft/api-extractor` compiles with its own
187
+ * bundled TypeScript 6, which predates the flag and hard-errors on the unknown compiler option — so
188
+ * only the emit passes ever see it, while the api-extractor compile reads the original clean config.
189
+ *
190
+ * The wrapper is written for the tsgo generator, which opens it as a TypeScript PROJECT and then
191
+ * looks every entry up by the realpath'd module id rolldown hands it — so it has to describe the
192
+ * same file set under the same names:
193
+ *
194
+ * - `extends` names the base by its CANONICAL (symlink-free) path. Root files are resolved relative
195
+ * to the base's directory, and on a symlinked base dir (macOS `/var` resolving to `/private/var`, a linked
196
+ * checkout) a non-canonical name would key them differently from rolldown's ids and every entry
197
+ * would fail with "No TypeScript Go project found".
198
+ * - `files`/`include`/`exclude` are restated as ABSOLUTE paths under the base's directory. A base
199
+ * that declares none would otherwise get TypeScript's default `**\/*` resolved against the
200
+ * wrapper's own directory — the OS temp dir — so the project would be every stray temp file on
201
+ * the machine and never the package's sources.
202
+ *
203
+ * The wrapper also ALWAYS clears `customConditions` and `paths` (written as `null`, which the TypeScript compiler
204
+ * reads as removing an inherited value): the declaration program must resolve sibling packages the way the package
205
+ * manifest says, never through a typecheck-only condition or path alias that would pull source files into the
206
+ * emitted declarations. The one exception is `options.paths`, the bundled workspace siblings resolved to their built
207
+ * declarations, which is the only `paths` map this file ever carries. The only reader of this file is the tsgo
208
+ * declaration generator; nothing in the bundler reads it back through the kit's `TsconfigLoaderSync`, which rejects
209
+ * `null` compiler options.
210
+ *
211
+ * Best-effort: if the base tsconfig cannot be read or parsed (e.g. a synthetic test path that was
212
+ * never written), the original path is returned unchanged — the emit then simply keeps TS's
213
+ * default ordering rather than aborting the build at this layer.
214
+ *
215
+ * @public
216
+ */
217
+ function writeDtsEmitTsconfig(resolvedTsconfigPath, options = {}) {
218
+ const absBase = isAbsolute(resolvedTsconfigPath) ? resolvedTsconfigPath : resolve(resolvedTsconfigPath);
219
+ if (!existsSync(absBase)) return resolvedTsconfigPath;
220
+ const canonicalBase = realpathSync.native(absBase);
221
+ const baseDir = dirname(canonicalBase);
222
+ const paths = options.paths !== void 0 && Object.keys(options.paths).length > 0 ? options.paths : void 0;
223
+ const cfg = {
224
+ extends: canonicalBase,
225
+ compilerOptions: {
226
+ stableTypeOrdering: true,
227
+ ...DTS_RESET_OPTIONS,
228
+ ...paths !== void 0 ? { paths } : {}
229
+ },
230
+ ...absoluteFileSet(canonicalBase, baseDir)
231
+ };
232
+ const key = paths !== void 0 ? `${absBase}:${Object.keys(paths).join(",")}` : absBase;
233
+ const path = join(tmpdir(), tempTsconfigName("tsconfig-dts-emit", key));
234
+ writeFileSync(path, `${JSON.stringify(cfg, null, " ")}\n`, "utf-8");
235
+ return path;
236
+ }
237
+
238
+ export { buildResolvedTsconfig, writeDtsEmitTsconfig, writeResolvedTsconfig };