@effected/bundler 0.0.0-stage → 0.1.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 +450 -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 +261 -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 +427 -0
  20. package/config/EffectedConfigFile.js +160 -0
  21. package/config/merge.js +20 -0
  22. package/config/plugins.js +84 -0
  23. package/config-validation/ConfigValidator.js +67 -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 +3919 -0
  38. package/index.js +58 -0
  39. package/internal/causeMessage.js +57 -0
  40. package/journal/BuildJournal.js +108 -0
  41. package/jsx/config.js +51 -0
  42. package/manifest/emit-manifest.js +88 -0
  43. package/manifest/export-patterns.js +58 -0
  44. package/manifest/transform.js +323 -0
  45. package/meta/BundleManifest.js +208 -0
  46. package/meta/ManifestSource.js +37 -0
  47. package/meta/api-extractor.js +241 -0
  48. package/meta/config.js +24 -0
  49. package/meta/generate.js +246 -0
  50. package/meta/merge-models.js +43 -0
  51. package/meta/message-suppressor.js +43 -0
  52. package/meta/og-image.js +137 -0
  53. package/meta/og-satori.js +140 -0
  54. package/meta/optimistic.js +32 -0
  55. package/meta/run-pass.js +117 -0
  56. package/meta/scrub-declaration-maps.js +63 -0
  57. package/meta/tsconfig-resolver.js +55 -0
  58. package/meta/tsdoc-config.js +47 -0
  59. package/meta/tsdoctor-config.js +22 -0
  60. package/meta/tsdoctor-manifest.js +134 -0
  61. package/meta/tsdoctor-source.js +94 -0
  62. package/package.json +85 -5
  63. package/passes/build-target-groups.js +346 -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 +39 -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 +155 -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 +18 -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,98 @@
1
+ // src/passes/cjs-default-interop.ts
2
+ /**
3
+ * The interop footer appended to a CJS ENTRY chunk that has a default export
4
+ * alongside named exports. It reassigns `module.exports` to the default value
5
+ * and re-attaches every named export as an own property of it.
6
+ *
7
+ * This is the rslib `cjsInterop: true` equivalent. rolldown's `output.exports`
8
+ * cannot natively produce `module.exports = <default>` while ALSO keeping named
9
+ * exports: for a default+named module both `"auto"` and `"named"` emit
10
+ * `exports.default = <default>` (verified against rolldown 1.1.0), so an
11
+ * ESM consumer doing `import(x).default` receives the `{ default, ...named }`
12
+ * wrapper object rather than the default value. The footer restores the rslib
13
+ * behavior so `import(x).default === <default>` and `require(x) === <default>`
14
+ * (with named exports attached as properties of it).
15
+ *
16
+ * Why this matters concretely: markdownlint-cli2 resolves a `customRules`
17
+ * specifier to a file path, `await import(fileURL)`, and reads `module.default`,
18
+ * expecting it to be the rules ARRAY (it then `.flat()`s it). silk's
19
+ * `./changesets/markdownlint` subpath default-exports the rules array plus five
20
+ * named rule objects; without this footer `import(...).default` is the wrapper
21
+ * object, whose `.names` is undefined, and markdownlint-cli2 aborts with
22
+ * "Property 'names' of custom rule at index 0 is incorrect: 'undefined'".
23
+ *
24
+ * Limitation — PRIMITIVE defaults: promotion only happens when the default value
25
+ * is an object or function, because named exports are re-attached to it as own
26
+ * properties (a primitive cannot carry properties). When a cjs entry chunk has a
27
+ * primitive default (`export default "x"` / `42` / `true`) ALONGSIDE named exports,
28
+ * `module.exports` is left as the `{ default, ...named }` wrapper and the footer
29
+ * emits a one-line `console.warn` so the no-op is observable rather than silent.
30
+ * This case does not occur in the suite today (every promoted default — the
31
+ * markdownlint rules array, the commitlint config objects — is an object), and a
32
+ * default-ONLY primitive is unaffected: rolldown already emits `module.exports =
33
+ * <primitive>` for it (no named exports, so this plugin never fires).
34
+ */
35
+ const INTEROP_FOOTER = [
36
+ "",
37
+ "// __cjs_default_interop__ (rslib cjsInterop parity): make module.exports the",
38
+ "// default export with named exports attached, so import(x).default is the value.",
39
+ "if (typeof module !== \"undefined\" && module.exports && module.exports.default !== void 0) {",
40
+ " const __cjsDefault = module.exports.default;",
41
+ " if (__cjsDefault !== null && (typeof __cjsDefault === \"object\" || typeof __cjsDefault === \"function\")) {",
42
+ " for (const __cjsKey of Object.keys(module.exports)) {",
43
+ " if (__cjsKey === \"default\" || __cjsKey === \"__esModule\") continue;",
44
+ " try {",
45
+ " Object.defineProperty(__cjsDefault, __cjsKey, {",
46
+ " value: module.exports[__cjsKey],",
47
+ " enumerable: true,",
48
+ " configurable: true,",
49
+ " writable: true",
50
+ " });",
51
+ " } catch {}",
52
+ " }",
53
+ " module.exports = __cjsDefault;",
54
+ " } else {",
55
+ " // Primitive default + named exports: cannot attach named props to a primitive,",
56
+ " // so module.exports stays the wrapper. Surface the no-op instead of hiding it.",
57
+ " if (typeof console !== \"undefined\")",
58
+ " console.warn(\"[savvy:cjs-default-interop] primitive default export left as a {default,...named} wrapper; import().default is NOT the primitive value\");",
59
+ " }",
60
+ "}"
61
+ ].join("\n");
62
+ /**
63
+ * Rolldown plugin: append the CJS default-interop footer to ENTRY chunks of the
64
+ * `cjs` format that export a default alongside named exports.
65
+ *
66
+ * Gated tightly so it never touches the wrong chunk:
67
+ * - format must be `cjs` (ESM is untouched; `import().default` on ESM is already correct);
68
+ * - the chunk must be an ENTRY chunk — never a SHARED chunk. Shared chunks are required by
69
+ * entry chunks via their named bindings (e.g. `require_changesets.changesets_exports.X`);
70
+ * reassigning a shared chunk's `module.exports` to its own default would break those reads
71
+ * (many bundled vendor chunks carry an `exports.default`);
72
+ * - the chunk must export a `default` AND at least one named export. A default-only chunk
73
+ * already gets `module.exports = <default>` from rolldown, and a named-only chunk has no
74
+ * default to promote.
75
+ *
76
+ * The emitted footer is also self-guarded (`module.exports.default !== void 0`), so it is a
77
+ * runtime no-op whenever the static gate is ever too generous.
78
+ * @public
79
+ */
80
+ function cjsDefaultInterop() {
81
+ return {
82
+ name: "savvy:cjs-default-interop",
83
+ renderChunk(code, chunk, outputOptions) {
84
+ if (outputOptions.format !== "cjs") return null;
85
+ if (!chunk.isEntry) return null;
86
+ const exportsList = chunk.exports;
87
+ if (!Array.isArray(exportsList)) return null;
88
+ if (!exportsList.includes("default")) return null;
89
+ if (!exportsList.some((name) => name !== "default")) return null;
90
+ return {
91
+ code: `${code}\n${INTEROP_FOOTER}\n`,
92
+ map: null
93
+ };
94
+ }
95
+ };
96
+ }
97
+
98
+ export { cjsDefaultInterop };
@@ -0,0 +1,57 @@
1
+ import { ConfigValidationError } from "../errors.js";
2
+ import { basename, extname } from "node:path";
3
+
4
+ // src/passes/loose-files.ts
5
+ /** Extension to its implied format; `.js` is ambiguous (undefined). */
6
+ const EXT_FORMAT = {
7
+ ".mjs": "esm",
8
+ ".cjs": "cjs",
9
+ ".js": void 0
10
+ };
11
+ /**
12
+ * Resolve a `looseFiles` map into normalized build descriptors. Pure (no filesystem):
13
+ * a missing `source` is surfaced later by tsdown's entry resolution. Throws
14
+ * {@link ConfigValidationError} on any structural problem so the bundler's ConfigValidator
15
+ * surfaces it as a typed, fast-fail config error.
16
+ * @public
17
+ */
18
+ function normalizeLooseFiles(files) {
19
+ const out = [];
20
+ for (const [outFile, raw] of Object.entries(files)) {
21
+ if (basename(outFile) !== outFile) throw new ConfigValidationError({
22
+ path: `looseFiles."${outFile}"`,
23
+ reason: "a loose file must be a root-level filename with no path separator"
24
+ });
25
+ const ext = extname(outFile);
26
+ if (!(ext in EXT_FORMAT)) throw new ConfigValidationError({
27
+ path: `looseFiles."${outFile}"`,
28
+ reason: `unsupported output extension "${ext}" — use .mjs, .cjs, or .js`
29
+ });
30
+ const source = typeof raw === "string" ? raw : raw.source;
31
+ const explicit = typeof raw === "string" ? void 0 : raw.format;
32
+ const inferred = EXT_FORMAT[ext];
33
+ if (inferred !== void 0 && explicit !== void 0 && explicit !== inferred) throw new ConfigValidationError({
34
+ path: `looseFiles."${outFile}".format`,
35
+ reason: `format "${explicit}" contradicts the "${ext}" extension (which implies "${inferred}")`
36
+ });
37
+ if (inferred === void 0 && explicit === void 0) throw new ConfigValidationError({
38
+ path: `looseFiles."${outFile}".format`,
39
+ reason: "a \".js\" output is format-ambiguous — set format: \"esm\""
40
+ });
41
+ const format = inferred ?? explicit;
42
+ if (ext === ".js" && format === "cjs") throw new ConfigValidationError({
43
+ path: `looseFiles."${outFile}"`,
44
+ reason: "a CJS file named \".js\" is not supported yet — name it \".cjs\""
45
+ });
46
+ out.push({
47
+ outFile,
48
+ entryName: basename(outFile, ext),
49
+ source,
50
+ format,
51
+ fixedExtension: ext !== ".js"
52
+ });
53
+ }
54
+ return out;
55
+ }
56
+
57
+ export { normalizeLooseFiles };
@@ -0,0 +1,79 @@
1
+ import { builtinModules } from "node:module";
2
+
3
+ // src/passes/node-builtin-default-interop.ts
4
+ /**
5
+ * The set of Node built-in module names (without the `node:` prefix), e.g. `path`,
6
+ * `process`, `fs`. Used to decide whether a BARE import specifier names a builtin.
7
+ */
8
+ const BUILTIN_NAMES = new Set(builtinModules);
9
+ /** True when `spec` resolves to a Node built-in module (either `node:x` or a bare builtin name). */
10
+ function isNodeBuiltin(spec) {
11
+ if (spec.startsWith("node:")) return true;
12
+ return BUILTIN_NAMES.has(spec);
13
+ }
14
+ /**
15
+ * Rewrite a default import / default re-export of a Node built-in into the
16
+ * equivalent NAMESPACE form, so rolldown's CJS codegen produces correct interop.
17
+ *
18
+ * Why this exists — a rolldown 1.1.0 codegen defect (verified against the latest
19
+ * published rolldown 1.1.0 / tsdown 0.22.2, with no newer release to upgrade to):
20
+ *
21
+ * ```ts
22
+ * // SOURCE (e.g. vfile's lib/minproc.js)
23
+ * export {default as minproc} from 'node:process'
24
+ * // ...consumed as minproc.cwd()
25
+ *
26
+ * // rolldown CJS OUTPUT (BROKEN)
27
+ * let node_process = require("node:process");
28
+ * node_process.default.cwd() // <- require("node:process").default is undefined
29
+ * ```
30
+ *
31
+ * For a default import of an EXTERNAL Node builtin, rolldown emits a bare
32
+ * `require("node:x")` WITHOUT its `__toESM` interop wrapper, yet still accesses
33
+ * `.default` — which is `undefined` on a builtin's CJS export object, so the call
34
+ * throws `Cannot read properties of undefined (reading 'cwd')` at runtime. NAMED
35
+ * imports are unaffected (`(0, node_process.cwd)()` reads a real property), and a
36
+ * NAMESPACE import is handled correctly: rolldown wraps it as
37
+ * `node_process = __toESM(require("node:process"), 1)`, which synthesizes `.default`
38
+ * and copies every own property, so member access works. This transform converts the
39
+ * broken default form into the working namespace form BEFORE codegen, so it is immune
40
+ * to minification and applies identically to per-module and bundled output.
41
+ *
42
+ * rolldown exposes no Rollup-style `output.interop` knob to fix this at the output
43
+ * layer, which is why the correction happens here on the source.
44
+ *
45
+ * Rewrites (the two static forms that occur in practice, anchored to statement start):
46
+ *
47
+ * ```ts
48
+ * import NAME from "node:x" -> import * as NAME from "node:x"
49
+ * export { default as NAME } from "node:x" -> export * as NAME from "node:x"
50
+ * import NAME, { a, b } from "node:x" -> import * as NAME from "node:x"; import { a, b } from "node:x"
51
+ * ```
52
+ *
53
+ * The namespace binding NAME carries the builtin's named exports (`NAME.cwd`,
54
+ * `NAME.join`, ...), which is exactly how a default import of a builtin is consumed
55
+ * in practice. ESM output is unaffected at runtime (a namespace import of a builtin
56
+ * resolves to the same members), so the plugin is safe to attach to dual builds.
57
+ * @public
58
+ */
59
+ function nodeBuiltinDefaultInterop() {
60
+ const DEFAULT_REEXPORT = /(^|\n)([ \t]*)export\s*\{\s*default\s+as\s+([A-Za-z_$][\w$]*)\s*\}\s*from\s*(["'])([^"']+)\4/g;
61
+ const DEFAULT_WITH_NAMED = /(^|\n)([ \t]*)import\s+([A-Za-z_$][\w$]*)\s*,\s*(\{[^}]*\})\s*from\s*(["'])([^"']+)\5/g;
62
+ const DEFAULT_IMPORT = /(^|\n)([ \t]*)import\s+([A-Za-z_$][\w$]*)\s+from\s*(["'])([^"']+)\4/g;
63
+ return {
64
+ name: "savvy:node-builtin-default-interop",
65
+ transform(code) {
66
+ if (!code.includes("node:") && !code.includes("from")) return null;
67
+ let out = code;
68
+ out = out.replace(DEFAULT_REEXPORT, (match, lead, indent, name, quote, spec) => isNodeBuiltin(spec) ? `${lead}${indent}export * as ${name} from ${quote}${spec}${quote}` : match);
69
+ out = out.replace(DEFAULT_WITH_NAMED, (match, lead, indent, name, named, quote, spec) => isNodeBuiltin(spec) ? `${lead}${indent}import * as ${name} from ${quote}${spec}${quote};\n${indent}import ${named} from ${quote}${spec}${quote}` : match);
70
+ out = out.replace(DEFAULT_IMPORT, (match, lead, indent, name, quote, spec) => isNodeBuiltin(spec) ? `${lead}${indent}import * as ${name} from ${quote}${spec}${quote}` : match);
71
+ return out === code ? null : {
72
+ code: out,
73
+ map: null
74
+ };
75
+ }
76
+ };
77
+ }
78
+
79
+ export { nodeBuiltinDefaultInterop };
@@ -0,0 +1,39 @@
1
+ import { Result } from "effect";
2
+ import { rmSync } from "node:fs";
3
+ import { join, resolve } from "node:path";
4
+ import { GlobPattern, GlobPatternOptions } from "@effected/glob";
5
+ import { descendSync } from "@effected/walker";
6
+ import { nodeWalkerSyncOps } from "@effected/walker/node-sync";
7
+
8
+ // src/passes/strip-maps.ts
9
+ /** `.d.ts.map` / `.d.cts.map` at any depth, dot-directories included. */
10
+ const STRIPPABLE_MAPS = Result.getOrThrow(GlobPattern.compileResult("**/*.d.{ts,cts}.map", GlobPatternOptions.make({ dot: true })));
11
+ /**
12
+ * Remove declaration source-map files (`.d.ts.map` / `.d.cts.map`) from a built `pkg`
13
+ * directory, returning the removed paths.
14
+ *
15
+ * The dts pass emits these next to each `.d.ts` (the resolved dts tsconfig sets
16
+ * `declarationMap: true`) because API Extractor reads them during meta generation to
17
+ * resolve original-source positions. But they are dead weight in a PUBLISHED package —
18
+ * they reference `.ts` sources the tarball does not ship — and they leak local source
19
+ * paths, so the prod build strips them AFTER meta generation has consumed them. The dev
20
+ * build keeps them (it is never published, and `savvy build --target meta` reads them).
21
+ *
22
+ * Recurses, but skips `node_modules` so it does not traverse a self-contained bundle's
23
+ * vendored tree — only the package's own emitted declarations carry maps worth stripping.
24
+ * @public
25
+ */
26
+ function removeDeclarationMaps(pkgDir) {
27
+ return Result.getOrThrow(descendSync(STRIPPABLE_MAPS, {
28
+ cwd: resolve(pkgDir),
29
+ prune: ["node_modules"],
30
+ onUnreadable: "skip",
31
+ ...nodeWalkerSyncOps
32
+ })).map((rel) => {
33
+ const full = join(pkgDir, rel);
34
+ rmSync(full, { force: true });
35
+ return full;
36
+ });
37
+ }
38
+
39
+ export { removeDeclarationMaps };
@@ -0,0 +1,100 @@
1
+ import { findRelativeSpecifiers } from "../dts/relative-imports.js";
2
+ import { ConfigValidationError } from "../errors.js";
3
+ import { Result } from "effect";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { GlobPattern, GlobPatternOptions } from "@effected/glob";
7
+ import { descendSync } from "@effected/walker";
8
+ import { nodeWalkerSyncOps } from "@effected/walker/node-sync";
9
+
10
+ // src/passes/sync-public.ts
11
+ /** Every file at any depth, dotfiles included. */
12
+ const EVERY_FILE = Result.getOrThrow(GlobPattern.compileResult("**", GlobPatternOptions.make({ dot: true })));
13
+ /**
14
+ * Every file path under `dir`, relative to it (POSIX separators, sorted). Nothing is pruned, so a
15
+ * `public/.well-known/` or `public/node_modules/` asset still copies; symlinked directories are not entered.
16
+ */
17
+ function listFilesRel(dir) {
18
+ return Result.getOrThrow(descendSync(EVERY_FILE, {
19
+ cwd: resolve(dir),
20
+ prune: [],
21
+ ...nodeWalkerSyncOps
22
+ }));
23
+ }
24
+ /** True when both files exist with identical size and bytes. Size is checked first so the byte read is skipped for the common changed case. */
25
+ function sameBytes(a, b) {
26
+ if (statSync(a).size !== statSync(b).size) return false;
27
+ return readFileSync(a).equals(readFileSync(b));
28
+ }
29
+ /** Throw the standard public-asset collision error for a destination-relative path. */
30
+ function throwPublicCollision(rel) {
31
+ throw new ConfigValidationError({
32
+ path: `public/${rel}`,
33
+ reason: `public asset "${rel}" collides with a built output at the package root — rename or remove it`
34
+ });
35
+ }
36
+ /**
37
+ * Copy the CONTENTS of `sourceDir` into `outDir`, additively.
38
+ *
39
+ * Each `sourceDir/<rel>` copies to `outDir/<rel>` — only the `public/` directory itself is dropped;
40
+ * the substructure under it is preserved (`public/tsconfig/ecma.json` becomes `<pkg>/tsconfig/ecma.json`,
41
+ * NOT `<pkg>/ecma.json`). The published manifest mirrors this drop via `transformExports`, which strips
42
+ * a leading `public/` from export values. This function NEVER deletes: `outDir` is the shared package
43
+ * root that the JS/dts passes own, so deleting "files not in source" would wipe the build product.
44
+ * Stale-asset pruning on a non-clean rebuild is therefore out of scope (a full build's `clean: true` handles it).
45
+ *
46
+ * Collision guard: when a destination already exists, identical bytes mean a prior copy of the same
47
+ * asset (skipped); anything else — differing bytes, a directory where a file is needed, or a file
48
+ * where a parent directory is needed — means a built output occupies that path, so it throws
49
+ * {@link ConfigValidationError} rather than clobbering it or surfacing a raw fs error.
50
+ * @public
51
+ */
52
+ function copyPublicDir(sourceDir, outDir) {
53
+ if (!existsSync(sourceDir)) return;
54
+ for (const rel of listFilesRel(sourceDir)) {
55
+ const src = join(sourceDir, rel);
56
+ const dst = join(outDir, rel);
57
+ if (existsSync(dst)) {
58
+ if (statSync(dst).isFile() && sameBytes(src, dst)) continue;
59
+ throwPublicCollision(rel);
60
+ }
61
+ try {
62
+ mkdirSync(dirname(dst), { recursive: true });
63
+ copyFileSync(src, dst);
64
+ } catch (err) {
65
+ const code = err.code;
66
+ if (code === "ENOTDIR" || code === "EEXIST" || code === "EISDIR") throwPublicCollision(rel);
67
+ throw err;
68
+ }
69
+ }
70
+ }
71
+ /**
72
+ * Copy each ambient `.d.ts` export's source verbatim into `outDir/<outName>`, byte-stable (an
73
+ * unchanged file keeps its timestamp). The copy is NOT compiled or bundled, so the build owns two
74
+ * fast-fail checks: the source must exist, and it must be self-contained — a relative
75
+ * import/export/reference would not resolve once the file is flattened to the package root.
76
+ *
77
+ * Throws {@link ConfigValidationError} on a missing source or any relative specifier.
78
+ * @public
79
+ */
80
+ function copyAmbientDts(options) {
81
+ for (const a of options.ambient) {
82
+ const src = join(options.srcCwd, a.source);
83
+ if (!existsSync(src)) throw new ConfigValidationError({
84
+ path: `exports."${a.exportKey}"`,
85
+ reason: `ambient .d.ts source not found: ${a.source}`
86
+ });
87
+ const relativeSpecifiers = findRelativeSpecifiers(readFileSync(src, "utf-8"), a.source);
88
+ if (relativeSpecifiers.length > 0) throw new ConfigValidationError({
89
+ path: `exports."${a.exportKey}"`,
90
+ reason: `ambient .d.ts "${a.source}" has relative import(s) [${relativeSpecifiers.join(", ")}] that cannot resolve after a verbatim copy — use bare package specifiers or self-contained declare module/global blocks`
91
+ });
92
+ const dst = join(options.outDir, a.outName);
93
+ if (!existsSync(dst) || !sameBytes(src, dst)) {
94
+ mkdirSync(dirname(dst), { recursive: true });
95
+ copyFileSync(src, dst);
96
+ }
97
+ }
98
+ }
99
+
100
+ export { copyAmbientDts, copyPublicDir };
@@ -0,0 +1,112 @@
1
+ import { join } from "node:path";
2
+
3
+ // src/passes/target-groups.ts
4
+ /** The `file://` URL of the TypeScript module this package resolves (its own pinned dependency). */
5
+ const typescriptModuleUrl = () => import.meta.resolve("typescript");
6
+ /**
7
+ * Build the {@link DtsPassDtsOptions} for a resolved tsconfig path.
8
+ *
9
+ * @public
10
+ */
11
+ const dtsPassDtsOptions = (tsconfig) => ({
12
+ tsconfig,
13
+ emitDtsOnly: true,
14
+ generator: "tsgo",
15
+ tsgo: { moduleUrl: typescriptModuleUrl() }
16
+ });
17
+ /**
18
+ * The output dir for a group: `dist/prod/\<group\>/pkg`, or `dist/dev/pkg` for the unused dev group.
19
+ *
20
+ * @public
21
+ */
22
+ const outDirFor = (cwd, group) => group === "dev" ? join(cwd, "dist/dev/pkg") : join(cwd, "dist/prod", group, "pkg");
23
+ /**
24
+ * Per-module declarations dir for a prod group: a sibling of `pkg/`, NOT published, used only as
25
+ * API Extractor's diagnostics-run input so locations resolve to per-file source. Kept (not stripped)
26
+ * as a cacheable, inspectable build artifact (issue #162).
27
+ *
28
+ * @public
29
+ */
30
+ const declarationsDirFor = (cwd, group) => join(cwd, "dist/prod", group, "declarations");
31
+ /**
32
+ * Derive the JS-pass tsdown options for one TargetGroup (per-module JS, no dts).
33
+ *
34
+ * @public
35
+ */
36
+ function deriveTargetGroupOptions(options) {
37
+ const isProd = options.group !== "dev";
38
+ const format = options.format ?? ["esm"];
39
+ const hasCjs = format.includes("cjs");
40
+ return {
41
+ outDir: outDirFor(options.cwd, options.group),
42
+ sourcemap: !isProd,
43
+ minify: isProd && (options.minify ?? false),
44
+ format,
45
+ unbundle: !(options.bundleNodeModules ?? false),
46
+ clean: true,
47
+ platform: options.platform ?? "node",
48
+ fixedExtension: false,
49
+ entry: options.entry,
50
+ dts: false,
51
+ define: {
52
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
53
+ ...options.define
54
+ },
55
+ isProd,
56
+ ...hasCjs ? { cjsDefault: true } : {}
57
+ };
58
+ }
59
+ /**
60
+ * Derive the dts-pass tsdown options for one TargetGroup (bundled declarations only).
61
+ *
62
+ * @public
63
+ */
64
+ function deriveDtsPassOptions(options) {
65
+ const isProd = options.group !== "dev";
66
+ const format = options.format ?? ["esm"];
67
+ const entry = Object.fromEntries(Object.entries(options.entry).filter(([name]) => !name.startsWith("bin/")));
68
+ return {
69
+ outDir: outDirFor(options.cwd, options.group),
70
+ sourcemap: false,
71
+ format,
72
+ unbundle: false,
73
+ clean: false,
74
+ platform: "node",
75
+ fixedExtension: false,
76
+ entry,
77
+ dts: dtsPassDtsOptions(options.tsconfigPath),
78
+ define: {
79
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
80
+ ...options.define
81
+ },
82
+ isProd,
83
+ ...options.bundledPackages !== void 0 ? { bundledPackages: options.bundledPackages } : {}
84
+ };
85
+ }
86
+ /**
87
+ * Derive the per-module declarations pass (API Extractor diagnostics input). Mirrors
88
+ * {@link deriveDtsPassOptions} but `unbundle: true` (preserveModules → 1:1 source positions),
89
+ * esm-only (AE reads the `.d.ts` entry only), into the `declarations/` sibling dir. Bin entries
90
+ * are dropped (no exports).
91
+ * @internal
92
+ */
93
+ function deriveDeclarationsPassOptions(options) {
94
+ const entry = Object.fromEntries(Object.entries(options.entry).filter(([name]) => !name.startsWith("bin/")));
95
+ return {
96
+ outDir: declarationsDirFor(options.cwd, options.group),
97
+ sourcemap: false,
98
+ format: ["esm"],
99
+ unbundle: true,
100
+ platform: "node",
101
+ fixedExtension: false,
102
+ entry,
103
+ dts: dtsPassDtsOptions(options.tsconfigPath),
104
+ define: {
105
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
106
+ ...options.define
107
+ },
108
+ ...options.bundledPackages !== void 0 ? { bundledPackages: options.bundledPackages } : {}
109
+ };
110
+ }
111
+
112
+ export { declarationsDirFor, deriveDeclarationsPassOptions, deriveDtsPassOptions, deriveTargetGroupOptions, dtsPassDtsOptions, outDirFor };
@@ -0,0 +1,36 @@
1
+ // src/report/ci-annotations.ts
2
+ /** Removes C0 and C1 controls and DEL, which reach stdout raw here, keeping the line breaks the escapes below map. */
3
+ const stripControls = (s) => Array.from(s).filter((char) => {
4
+ const code = char.charCodeAt(0);
5
+ return code === 10 || code === 13 || !(code < 32 || code >= 127 && code <= 159);
6
+ }).join("");
7
+ /** A workflow command's message. */
8
+ const escapeData = (s) => stripControls(s).replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
9
+ /** A workflow command's property value, where `:` ends the list and `,` starts the next property. */
10
+ const escapeProperty = (s) => escapeData(s).replace(/:/g, "%3A").replace(/,/g, "%2C");
11
+ /**
12
+ * Render a build report as GitHub Actions workflow-command annotations, one `::error` or `::warning`
13
+ * line per diagnostic. Suppressed diagnostics are never annotated. Pure.
14
+ *
15
+ * @remarks
16
+ * The text is a diagnostic's, so it is untrusted: control characters are removed, so it cannot repaint a terminal, and
17
+ * property values have `:` and `,` escaped, so a file name cannot forge a property or end the list.
18
+ *
19
+ * @public
20
+ */
21
+ function renderCiAnnotations(report) {
22
+ const lines = [];
23
+ for (const g of report.targetGroups) {
24
+ for (const e of g.errors) {
25
+ const loc = e.file !== void 0 ? `,file=${escapeProperty(e.file)}${e.line !== void 0 ? `,line=${e.line}` : ""}` : "";
26
+ lines.push(`::error title=${escapeProperty(report.package)} (${escapeProperty(g.id)})${loc}::${escapeData(e.text)}`);
27
+ }
28
+ for (const w of g.warnings) {
29
+ const loc = w.file !== void 0 ? `,file=${escapeProperty(w.file)}${w.line !== void 0 ? `,line=${w.line}` : ""}` : "";
30
+ lines.push(`::warning title=${escapeProperty(report.package)} (${escapeProperty(g.id)})${loc}::${escapeData(w.text)}`);
31
+ }
32
+ }
33
+ return lines;
34
+ }
35
+
36
+ export { renderCiAnnotations };
@@ -0,0 +1,140 @@
1
+ import { BuildReport, DiagnosticEntry, EmittedFile, PassReport, ReportTimings, TargetGroupReport } from "./schema.js";
2
+ import { Context } from "effect";
3
+
4
+ // src/report/collector.ts
5
+ /**
6
+ * Stateful build-event accumulator. The write surface is synchronous so it can be called directly
7
+ * from tsdown's customLogger and API Extractor's messageCallback (both invoked synchronously).
8
+ * `snapshot` builds the immutable BuildReport the Effect render pipeline consumes.
9
+ * @public
10
+ */
11
+ var BuildCollector = class {
12
+ groups = /* @__PURE__ */ new Map();
13
+ group(groupId) {
14
+ let g = this.groups.get(groupId);
15
+ if (g === void 0) {
16
+ g = {
17
+ id: groupId,
18
+ entries: [],
19
+ passes: /* @__PURE__ */ new Map(),
20
+ warnings: [],
21
+ errors: [],
22
+ suppressed: [],
23
+ seenPaths: /* @__PURE__ */ new Set(),
24
+ seenDiagnostics: /* @__PURE__ */ new Set(),
25
+ seenSuppressed: /* @__PURE__ */ new Set()
26
+ };
27
+ this.groups.set(groupId, g);
28
+ }
29
+ return g;
30
+ }
31
+ pass(groupId, pass) {
32
+ const g = this.group(groupId);
33
+ let p = g.passes.get(pass);
34
+ if (p === void 0) {
35
+ p = {
36
+ files: [],
37
+ ms: 0
38
+ };
39
+ g.passes.set(pass, p);
40
+ }
41
+ return p;
42
+ }
43
+ registerGroup(groupId, entries) {
44
+ this.group(groupId).entries = [...entries];
45
+ }
46
+ recordEmitted(groupId, pass, file) {
47
+ const g = this.group(groupId);
48
+ if (g.seenPaths.has(file.path)) return;
49
+ g.seenPaths.add(file.path);
50
+ this.pass(groupId, pass).files.push({
51
+ path: file.path,
52
+ bytes: file.bytes,
53
+ ...file.gzip !== void 0 ? { gzip: file.gzip } : {}
54
+ });
55
+ }
56
+ recordPassTiming(groupId, pass, ms) {
57
+ this.pass(groupId, pass).ms += ms;
58
+ }
59
+ recordWarning(groupId, entry) {
60
+ const g = this.group(groupId);
61
+ const key = diagnosticKey(entry);
62
+ if (g.seenDiagnostics.has(key)) return;
63
+ g.seenDiagnostics.add(key);
64
+ g.warnings.push(toEntry(entry));
65
+ }
66
+ recordError(groupId, entry) {
67
+ const g = this.group(groupId);
68
+ const key = diagnosticKey(entry);
69
+ if (g.seenDiagnostics.has(key)) return;
70
+ g.seenDiagnostics.add(key);
71
+ g.errors.push(toEntry(entry));
72
+ }
73
+ recordSuppressed(groupId, entry) {
74
+ const g = this.group(groupId);
75
+ const key = diagnosticKey(entry);
76
+ if (g.seenSuppressed.has(key)) return;
77
+ g.seenSuppressed.add(key);
78
+ g.suppressed.push(toEntry(entry));
79
+ }
80
+ snapshot(packageName) {
81
+ const targetGroups = [];
82
+ for (const g of this.groups.values()) {
83
+ const passes = [];
84
+ let totalMs = 0;
85
+ for (const [id, p] of g.passes) {
86
+ const files = p.files.map((f) => new EmittedFile({
87
+ path: f.path,
88
+ bytes: f.bytes,
89
+ ...f.gzip !== void 0 ? { gzip: f.gzip } : {}
90
+ }));
91
+ passes.push(new PassReport({
92
+ id,
93
+ files,
94
+ ms: p.ms
95
+ }));
96
+ totalMs += p.ms;
97
+ }
98
+ targetGroups.push(new TargetGroupReport({
99
+ id: g.id,
100
+ entries: [...g.entries],
101
+ passes,
102
+ warnings: [...g.warnings],
103
+ errors: [...g.errors],
104
+ suppressed: [...g.suppressed],
105
+ timings: new ReportTimings({ totalMs })
106
+ }));
107
+ }
108
+ return [new BuildReport({
109
+ package: packageName,
110
+ targetGroups
111
+ })];
112
+ }
113
+ };
114
+ function diagnosticKey(input) {
115
+ return [
116
+ input.source,
117
+ input.level,
118
+ input.code ?? "",
119
+ input.text,
120
+ input.file ?? "",
121
+ String(input.line ?? ""),
122
+ String(input.column ?? "")
123
+ ].join("\0");
124
+ }
125
+ function toEntry(input) {
126
+ return new DiagnosticEntry({
127
+ source: input.source,
128
+ level: input.level,
129
+ text: input.text,
130
+ ...input.code !== void 0 ? { code: input.code } : {},
131
+ ...input.ciFatal !== void 0 ? { ciFatal: input.ciFatal } : {},
132
+ ...input.file !== void 0 ? { file: input.file } : {},
133
+ ...input.line !== void 0 ? { line: input.line } : {},
134
+ ...input.column !== void 0 ? { column: input.column } : {}
135
+ });
136
+ }
137
+ /** @public */
138
+ var BuildCollectorTag = class extends Context.Service()("@effected/bundler/BuildCollector") {};
139
+
140
+ export { BuildCollector, BuildCollectorTag };