@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,324 @@
1
+ import { ambientOutName, classifyDtsExport, mixedDtsExportError } from "../entries/ambient-dts.js";
2
+ import { createEntryName, resolveToTypeScript } from "../entries/extract.js";
3
+ import { ConfigValidationError } from "../errors.js";
4
+ import { PackageJsonFormat } from "@effected/package-json";
5
+
6
+ // src/manifest/transform.ts
7
+ const isDualKey = (dual, exportKey) => typeof dual === "boolean" ? dual : dual.has(exportKey);
8
+ /**
9
+ * Package.json fields that are never wanted in a published manifest: they describe
10
+ * how the package is BUILT/DEVELOPED, not how it is CONSUMED. The bundler reads
11
+ * everything it needs from the source manifest before transforms run (entry
12
+ * detection, `publishConfig.targets` for the byte-variant groups, catalog
13
+ * resolution), so dropping these from the emitted manifest is always safe.
14
+ */
15
+ const NON_PUBLISHED_FIELDS = [
16
+ "devDependencies",
17
+ "bundleDependencies",
18
+ "bundledDependencies",
19
+ "scripts",
20
+ "publishConfig",
21
+ "packageManager",
22
+ "devEngines"
23
+ ];
24
+ /**
25
+ * The default `transform` applied to every package's manifest when its
26
+ * build config does not provide one of its own. Strips the build/dev-only
27
+ * fields in `NON_PUBLISHED_FIELDS` from the emitted package.json.
28
+ *
29
+ * This is the pattern nearly every package repeated by hand (inherited from
30
+ * rslib-builder); `defineBuild` now applies it automatically so a package needs a
31
+ * `transform` only when it has genuinely custom manifest work to do (e.g. silk
32
+ * promoting workspace deps to peerDependencies). A custom transform REPLACES this
33
+ * default — re-export it and call it from a custom transform to keep the stripping.
34
+ *
35
+ * `targetGroup` is accepted (so this is assignable wherever the full transform
36
+ * signature is expected) but unused; the strip is identical for every group.
37
+ *
38
+ * `options.drop` names further top-level keys (for example `dependencies`) to delete after the
39
+ * standard stripping.
40
+ *
41
+ * Pure: the supplied `pkg` is NOT mutated — a shallow copy with the fields removed
42
+ * is returned, so external callers invoking this from a custom transform keep their
43
+ * input intact.
44
+ * @public
45
+ */
46
+ function defaultManifestTransform({ pkg }, options = {}) {
47
+ const out = { ...pkg };
48
+ for (const field of NON_PUBLISHED_FIELDS) delete out[field];
49
+ for (const key of options.drop ?? []) delete out[key];
50
+ return out;
51
+ }
52
+ const stripLeadingDotSlash = (p) => p.startsWith("./") ? p.slice(2) : p;
53
+ const sameSource = (a, b) => stripLeadingDotSlash(a) === stripLeadingDotSlash(b);
54
+ /**
55
+ * Whether a target names the exe source, in source form or in the built form the entry pass resolves to it
56
+ * (`./dist/bin.js` for `./src/bin.ts`). The entry pass leaves both out of the JS build, so both must point at the SEA.
57
+ */
58
+ const namesExeSource = (target, source) => sameSource(target, source) || sameSource(resolveToTypeScript(target), source);
59
+ /** The export-path ("./bin/<file>") and files-entry ("bin/<file>") forms for a SEA. */
60
+ const exeRelPath = (r) => {
61
+ const filesEntry = `${r.dir}/${r.fileName}`;
62
+ return {
63
+ exportPath: `./${filesEntry}`,
64
+ filesEntry
65
+ };
66
+ };
67
+ /** Rewrite exports values that equal the exe source to a plain SEA-path string. */
68
+ const rewriteExeExports = (exports, r) => {
69
+ const { exportPath } = exeRelPath(r);
70
+ if (typeof exports === "string") return namesExeSource(exports, r.source) ? exportPath : exports;
71
+ if (exports && typeof exports === "object") {
72
+ const out = {};
73
+ for (const [key, value] of Object.entries(exports)) out[key] = typeof value === "string" && namesExeSource(value, r.source) ? exportPath : value;
74
+ return out;
75
+ }
76
+ return exports;
77
+ };
78
+ /**
79
+ * Built .js output basename for an export, derived from the entry NAME (the basename
80
+ * the build actually emits) rather than the source path. The entry namer flattens
81
+ * nested subpaths to a dash-joined basename (e.g. `./commitlint` to `commitlint.js`,
82
+ * `./changesets/markdownlint` to `changesets-markdownlint.js`), so the declared path
83
+ * always matches the file tsdown emits. The build never sets exportsAsIndexes, so the
84
+ * manifest mirrors the flat (false) naming here.
85
+ */
86
+ const toBuiltJs = (exportKey, subdirExports) => subdirExports?.has(exportKey) ? `./${createEntryName(exportKey, false)}/index.js` : `./${createEntryName(exportKey, false)}.js`;
87
+ const toBuiltDts = (exportKey, subdirExports) => toBuiltJs(exportKey, subdirExports).replace(/\.js$/, ".d.ts");
88
+ const toBuiltCjs = (exportKey, subdirExports) => toBuiltJs(exportKey, subdirExports).replace(/\.js$/, ".cjs");
89
+ const isDeclarationFile = (p) => p.endsWith(".d.ts") || p.endsWith(".d.cts") || p.endsWith(".d.mts");
90
+ const isTs = (p) => !isDeclarationFile(p) && (p.endsWith(".ts") || p.endsWith(".tsx"));
91
+ /**
92
+ * Whether the entry pass builds `p` into a JS entry: a TS source, or a `./dist/<name>.js` reference it resolves to
93
+ * `./src/<name>.ts` (see `resolveToTypeScript`). Either way the emitted file is named after the export KEY, so the
94
+ * manifest rewrites both forms to the same conditions.
95
+ */
96
+ const isBuildSource = (p) => isTs(resolveToTypeScript(p));
97
+ /**
98
+ * Build the conditions object for a TS export target (adds require when dual-format). `emitDts`
99
+ * gates the `types` condition: when `false` (the build's dts pass was skipped, see issue #198),
100
+ * omitting `types` avoids pointing the published manifest at a declaration file that was never
101
+ * written. Defaults to `true` (current behavior, byte-identical).
102
+ *
103
+ * The trailing `default` condition mirrors the ESM artifact so `require(esm)` resolves on the
104
+ * Node range every published package supports (engines >=24.11.0): Node's require() matches
105
+ * `node`/`require`/`default` but never `import`, so an import-only map dies with
106
+ * ERR_PACKAGE_PATH_NOT_EXPORTED even where require(esm) works. Dual-format entries keep their
107
+ * dedicated CJS artifact under `require`, which wins over `default` by condition order.
108
+ */
109
+ const tsConditions = (exportKey, dual, subdirExports, emitDts = true) => ({
110
+ ...emitDts ? { types: toBuiltDts(exportKey, subdirExports) } : {},
111
+ import: toBuiltJs(exportKey, subdirExports),
112
+ ...dual ? { require: toBuiltCjs(exportKey, subdirExports) } : {},
113
+ default: toBuiltJs(exportKey, subdirExports)
114
+ });
115
+ /**
116
+ * A `./public/<path>` export value points into the staged `public/` dir, whose CONTENTS `copyPublicDir`
117
+ * copies into the package root (only the `public/` segment is dropped; substructure is kept). So the
118
+ * published manifest value drops that same `public/` segment: `./public/tsconfig/ecma.json` becomes
119
+ * `./tsconfig/ecma.json`, resolving the file copyPublicDir placed at `<pkg>/tsconfig/ecma.json`.
120
+ * Non-strings and non-public values pass through unchanged.
121
+ */
122
+ function stripPublicPrefix(value) {
123
+ return typeof value === "string" && value.startsWith("./public/") ? `./${value.slice(9)}` : value;
124
+ }
125
+ /** The conditions the entry pass reads a source from, in its order (`resolveSourcePath` in `entries/extract.ts`). */
126
+ const ENTRY_SOURCE_CONDITIONS = [
127
+ "import",
128
+ "default",
129
+ "types"
130
+ ];
131
+ /** Every string target under an export value, at any depth. */
132
+ const stringTargets = (value) => typeof value === "string" ? [value] : value !== null && typeof value === "object" ? Object.values(value).flatMap(stringTargets) : [];
133
+ /** Whether `value`, at any depth, holds a build source (a TS source or a `./dist/*.js` reference). */
134
+ const holdsTsSource = (value) => stringTargets(value).some(isBuildSource);
135
+ const conditionObjectError = (exportKey, reason) => new ConfigValidationError({
136
+ path: `exports."${exportKey}"`,
137
+ reason
138
+ });
139
+ /**
140
+ * The TS source a condition-object export value names, when it names one the manifest can rewrite;
141
+ * `undefined` when it holds no TS source at all (it passes through as authored).
142
+ *
143
+ * The entry pass builds a condition object from ONE source, the first of `import`, `default` and
144
+ * `types` that is set, and names the output after the export KEY (`"./foo": { "import": "./src/foo.ts" }`
145
+ * emits `foo.js`). So a condition object whose every condition is one of those three, each naming that
146
+ * same TS source, maps unambiguously onto the export key's own conditions and is rewritten exactly as
147
+ * the bare-string form is. Any other shape holding a TS source is refused with a
148
+ * {@link ConfigValidationError} rather than rewritten, because the manifest would point at files the
149
+ * build never writes: two different sources (only the first is built), a condition the entry pass
150
+ * does not read (`node`, `browser`, `require`, ...; write the bare string and configure dual output
151
+ * instead of a hand-written `require`), or a nested condition object.
152
+ */
153
+ const conditionObjectSource = (exportKey, value) => {
154
+ if (value === null || typeof value !== "object" || !holdsTsSource(value)) return void 0;
155
+ const conditions = value;
156
+ const sources = /* @__PURE__ */ new Set();
157
+ for (const [condition, target] of Object.entries(conditions)) {
158
+ if (!ENTRY_SOURCE_CONDITIONS.includes(condition) || typeof target !== "string") throw conditionObjectError(exportKey, `a condition object holding a TypeScript source may use only flat ${ENTRY_SOURCE_CONDITIONS.join("/")} conditions; "${condition}" is not one the build reads its entry from`);
159
+ sources.add(target);
160
+ }
161
+ const [source] = sources;
162
+ if (sources.size !== 1 || typeof source !== "string" || !isBuildSource(source)) throw conditionObjectError(exportKey, "every condition of a condition object holding a TypeScript source must name that one source; the build emits one entry per export key");
163
+ return source;
164
+ };
165
+ /**
166
+ * Refuse a build source holding a `*`. The entry pass builds one entry per export key from one literal source path,
167
+ * so a pattern such as `./dist/*.js` or `./src/*.ts` names no file it can build, and the files a consumer would
168
+ * resolve through it are never written. A `*` in the export KEY over a literal build source is refused too: the output
169
+ * is named after the key, so it would be named with the `*` in it.
170
+ */
171
+ const assertNoWildcardSource = (exportKey, value) => {
172
+ const targets = stringTargets(value);
173
+ const pattern = targets.find((target) => target.includes("*") && isBuildSource(target));
174
+ if (pattern !== void 0) throw conditionObjectError(exportKey, `"${pattern}" is a pattern over build sources; the build emits one entry per export key from one source, so list each subpath with its own source`);
175
+ const source = exportKey.includes("*") ? targets.find(isBuildSource) : void 0;
176
+ if (source !== void 0) throw conditionObjectError(exportKey, `a pattern export key cannot name the build source "${source}"; the build names each entry's output after its key, so give the subpath a literal key`);
177
+ };
178
+ /**
179
+ * Refuse, before any build work, every subpath export {@link transformExports} would refuse as an
180
+ * unbuildable condition object (see {@link conditionObjectSource}), every build source written as a
181
+ * `*` pattern, and, for an exe build, every condition object naming the exe source. `Bundler.build`
182
+ * calls it beside the ambient `.d.ts` validation, so the refusal is a {@link ConfigValidationError} up
183
+ * front rather than a throw from inside the JS pass's manifest plugin; the transform keeps its own
184
+ * throws as a backstop. Walks the same keys the transform rewrites, skipping `.json`/`.d.ts` keys and
185
+ * ambient exports; a mixed `.d.ts` export is left to `extractAmbientDts`, which runs first.
186
+ *
187
+ * The exe source is compiled into the SEA and left out of the JS pass, and only a bare-string export of
188
+ * it is rewritten to the binary's path, so a condition object naming it would point at JS the build
189
+ * never writes.
190
+ *
191
+ * @internal
192
+ */
193
+ function assertBuildableConditionExports(exports, options = {}) {
194
+ if (exports === null || typeof exports !== "object") return;
195
+ const { exeSource } = options;
196
+ for (const [key, value] of Object.entries(exports)) {
197
+ if (key === "./package.json" || key.endsWith(".json") || isDeclarationFile(key)) continue;
198
+ if (exeSource !== void 0 && value !== null && typeof value === "object" && stringTargets(value).some((target) => namesExeSource(target, exeSource))) throw conditionObjectError(key, `the exe source "${exeSource}" is compiled into the binary, not a JS entry; export it as a bare string so the manifest points at the binary`);
199
+ if (classifyDtsExport(value).kind !== "none") continue;
200
+ assertNoWildcardSource(key, value);
201
+ conditionObjectSource(key, value);
202
+ }
203
+ }
204
+ /**
205
+ * Rewrite an exports map: TS string targets become a types/import conditions object.
206
+ * Each TS condition also gets a `require` entry when `dual` is `true` (uniform) or when
207
+ * the export key is in the `dual` Set (per-entry).
208
+ *
209
+ * The output path is derived from the export KEY via the shared entry-name function,
210
+ * never from the source path, so the manifest target always matches the emitted file.
211
+ *
212
+ * Export keys in `subdirExports` are built into an isolated `<key>/index.*` subdir (e.g. an
213
+ * RSPress `./runtime`), so their conditions gain an `/index` segment.
214
+ *
215
+ * `emitDts` gates the `types` condition on every GENERATED (non-ambient) TS export: pass `false`
216
+ * when the build's dts pass was skipped (issue #198) so the manifest does not point at a `.d.ts`
217
+ * that was never written. Defaults to `true`. Ambient `.d.ts` exports (hand-authored, copied
218
+ * verbatim regardless of the dts pass) are unaffected — their `types` condition is always kept.
219
+ *
220
+ * A condition-object value whose flat `import`/`default`/`types` conditions all name one TS source
221
+ * (`"./foo": { "import": "./src/foo.ts" }`) is rewritten like the bare string, named after the export
222
+ * key as the entry pass names it. Any other condition object holding a TS source throws
223
+ * {@link ConfigValidationError}, since its targets would never be built; one holding none passes
224
+ * through as authored.
225
+ *
226
+ * A subpath target written as the built path, `./dist/foo.js`, is a build source too: the entry pass
227
+ * builds it from `./src/foo.ts` and names the output after the export key, so it is rewritten exactly
228
+ * as `./src/foo.ts` would be. A build source holding a `*` (`./dist/*.js`, `./src/*.ts`) throws
229
+ * {@link ConfigValidationError}, since the build emits one entry per key from one literal source.
230
+ * @public
231
+ */
232
+ function transformExports(exports, dual = false, subdirExports, emitDts = true) {
233
+ if (typeof exports === "string") return isTs(exports) ? tsConditions(".", isDualKey(dual, "."), subdirExports, emitDts) : stripPublicPrefix(exports);
234
+ if (exports && typeof exports === "object") {
235
+ const out = {};
236
+ for (const [key, value] of Object.entries(exports)) {
237
+ if (key === "./package.json" || key.endsWith(".json") || isDeclarationFile(key)) {
238
+ out[key] = stripPublicPrefix(value);
239
+ continue;
240
+ }
241
+ const cls = classifyDtsExport(value);
242
+ if (cls.kind === "mixed") throw mixedDtsExportError(key, value);
243
+ if (cls.kind === "ambient") {
244
+ out[key] = { types: `./${ambientOutName(key, cls.source)}` };
245
+ continue;
246
+ }
247
+ assertNoWildcardSource(key, value);
248
+ if (typeof value === "string" && isBuildSource(value) || conditionObjectSource(key, value) !== void 0) out[key] = tsConditions(key, isDualKey(dual, key), subdirExports, emitDts);
249
+ else out[key] = transformExports(value, dual, subdirExports, emitDts);
250
+ }
251
+ return out;
252
+ }
253
+ return exports;
254
+ }
255
+ /**
256
+ * Rewrite bin: TS targets, and `./dist/*.js` targets the entry pass builds from `./src/*.ts`, to
257
+ * bin/[command].js (string to bin/cli.js); strip leading ./ otherwise.
258
+ *
259
+ * @public
260
+ */
261
+ function transformBin(bin) {
262
+ if (typeof bin === "string") return isBuildSource(bin) ? "bin/cli.js" : stripLeadingDotSlash(bin);
263
+ if (bin && typeof bin === "object") {
264
+ const out = {};
265
+ for (const [command, p] of Object.entries(bin)) out[command] = isBuildSource(p) ? `bin/${command}.js` : stripLeadingDotSlash(p);
266
+ return out;
267
+ }
268
+ return bin;
269
+ }
270
+ /**
271
+ * FINAL guard: strip leading ./ from bin paths (npm 11.x drops ./-prefixed bins).
272
+ *
273
+ * @public
274
+ */
275
+ function normalizeBinPaths(bin) {
276
+ if (typeof bin === "string") return stripLeadingDotSlash(bin);
277
+ if (bin && typeof bin === "object") {
278
+ const out = {};
279
+ for (const [command, p] of Object.entries(bin)) out[command] = stripLeadingDotSlash(p);
280
+ return out;
281
+ }
282
+ return bin;
283
+ }
284
+ /**
285
+ * Apply the full standard manifest transform (excluding catalog resolution, done upstream).
286
+ *
287
+ * @public
288
+ */
289
+ function transformManifest(pkg, options = {}) {
290
+ const { publishConfig, scripts, ...rest } = pkg;
291
+ const isPrivate = !(publishConfig?.access === "public");
292
+ let result = {
293
+ ...rest,
294
+ private: isPrivate
295
+ };
296
+ if (options.exeRewrite) {
297
+ const r = options.exeRewrite;
298
+ const { exportPath, filesEntry } = exeRelPath(r);
299
+ if (result.exports !== void 0 && result.exports !== null) result.exports = rewriteExeExports(result.exports, r);
300
+ if (typeof result.bin === "string") {
301
+ if (namesExeSource(result.bin, r.source)) result.bin = exportPath;
302
+ } else if (result.bin && typeof result.bin === "object") {
303
+ const nextBin = {};
304
+ for (const [cmd, val] of Object.entries(result.bin)) nextBin[cmd] = namesExeSource(val, r.source) ? exportPath : val;
305
+ result.bin = nextBin;
306
+ }
307
+ const files = Array.isArray(result.files) ? result.files.slice() : [];
308
+ if (!files.includes(filesEntry)) files.push(filesEntry);
309
+ result.files = files;
310
+ }
311
+ if (result.exports !== void 0 && result.exports !== null) {
312
+ const original = result.exports;
313
+ const transformed = transformExports(original, options.dual ?? false, options.subdirExports, options.emitDts ?? true);
314
+ const asMap = typeof original === "string" ? { ".": transformed } : { ...transformed };
315
+ if (!("./package.json" in asMap)) asMap["./package.json"] = "./package.json";
316
+ result.exports = asMap;
317
+ }
318
+ if (result.bin) result.bin = transformBin(result.bin);
319
+ if (options.transform) result = options.transform(result);
320
+ if (result.bin) result.bin = normalizeBinPaths(result.bin);
321
+ return PackageJsonFormat.sortValue(result);
322
+ }
323
+
324
+ export { assertBuildableConditionExports, defaultManifestTransform, normalizeBinPaths, transformBin, transformExports, transformManifest };
@@ -0,0 +1,241 @@
1
+ import { MetaGenerationError } from "../errors.js";
2
+ import { tsconfigSyncOptions } from "../tsconfig/sync-options.js";
3
+ import { createMessageSuppressor } from "./message-suppressor.js";
4
+ import { existsSync, realpathSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { createHash } from "node:crypto";
8
+ import { TsconfigLoaderSync } from "@effected/tsconfig-json";
9
+ import { Extractor, ExtractorConfig, ExtractorLogLevel } from "@microsoft/api-extractor";
10
+ import { TSDocConfigFile } from "@microsoft/tsdoc-config";
11
+
12
+ // src/meta/api-extractor.ts
13
+ /** messageIds that become a hard build error in CI (they corrupt the .api.json). */
14
+ const CI_FATAL_MESSAGE_IDS = /* @__PURE__ */ new Set(["ae-forgotten-export"]);
15
+ /**
16
+ * Derive the extractor-scoped tsconfig for ONE api-extractor run and return its path (#354).
17
+ *
18
+ * The compile tsconfig's `include` covers `src/**` — necessary for the dts-emit pass, poison for
19
+ * the extractor: a hand-authored `src/*.d.ts` shim matched by that glob survives api-extractor's
20
+ * .d.ts root filter, and a self-name import inside it resolves through the SOURCE manifest's
21
+ * `exports` to raw `.ts` sources under `src/`, putting non-declaration files in the Program and
22
+ * firing an unsuppressable `ae-wrong-input-file-type` on every build. The derived config keeps the
23
+ * base's `compilerOptions` (via an absolute-path `extends`) but replaces the input set with exactly
24
+ * what the extractor's Program should hold: the entry `.d.ts` (`files`) plus the `types/*.d.ts`
25
+ * legacy typings — the same effective roots as before minus everything under `src/`.
26
+ *
27
+ * The same failure class has a second route (#771): a self-name import (`import type * as Root from
28
+ * "@scope/pkg"`) inside an emitted per-module `.d.ts` resolves, from a declarations tree with no
29
+ * package.json, via TS package self-reference through the SOURCE manifest's `exports` into raw `.ts`
30
+ * (`ae-wrong-input-file-type`, or an `Unable to follow symbol` crash). Run B therefore supplies `paths`
31
+ * mapping each own export specifier to its declarations file, which wins over self-reference.
32
+ *
33
+ * Best-effort, mirroring `writeDtsEmitTsconfig`: a base that does not exist (e.g. a synthetic test
34
+ * path) gets no variant — the original path is returned unchanged. The filename is deterministic
35
+ * per (pid, base, entry) via a content hash (the two joined paths overflow a filename), so repeated
36
+ * calls within a process overwrite the same file; cross-process temp files are left for the OS to
37
+ * reap, consistent with the other tmpdir tsconfig writers.
38
+ */
39
+ function writeApiExtractorTsconfig(options) {
40
+ const absBase = isAbsolute(options.tsconfigPath) ? options.tsconfigPath : resolve(options.tsconfigPath);
41
+ if (!existsSync(absBase)) return options.tsconfigPath;
42
+ const entryDts = isAbsolute(options.entryDtsPath) ? options.entryDtsPath : resolve(options.cwd, options.entryDtsPath);
43
+ const ownPaths = options.paths ?? {};
44
+ const hasPaths = Object.keys(ownPaths).length > 0;
45
+ const cfg = {
46
+ extends: absBase,
47
+ files: [entryDts],
48
+ include: [join(options.cwd, "types/*.d.ts")],
49
+ ...hasPaths ? { compilerOptions: { paths: {
50
+ ...readBasePaths(absBase),
51
+ ...ownPaths
52
+ } } } : {}
53
+ };
54
+ const hash = createHash("sha256").update(`${absBase}\0${entryDts}${hasPaths ? `\0${JSON.stringify(ownPaths)}` : ""}`).digest("hex").slice(0, 16);
55
+ const path = join(tmpdir(), `tsconfig-api-extractor-${process.pid}-${hash}.json`);
56
+ writeFileSync(path, `${JSON.stringify(cfg, null, " ")}\n`, "utf-8");
57
+ return path;
58
+ }
59
+ /**
60
+ * The base tsconfig's effective `compilerOptions.paths`, with every relative target made absolute.
61
+ *
62
+ * A `compilerOptions.paths` in the derived config replaces the inherited one wholesale, so the base's
63
+ * mappings must be re-emitted, and they must keep resolving where they did. TypeScript resolves a
64
+ * relative target against `baseUrl` when one is in effect, and otherwise against the directory of the
65
+ * config that declared `paths`. Re-emitted verbatim from the derived config in the tmpdir, a target such
66
+ * as `./src/*` would resolve under the tmpdir instead. The chain is resolved with the same tsc-parity
67
+ * loader the portable-tsconfig resolver uses (`extends`, JSONC, an absolutized `baseUrl`, `pathsBase`),
68
+ * so `paths` inherited from further up the chain are kept too. Best-effort: a base that cannot be
69
+ * resolved contributes no paths.
70
+ */
71
+ function readBasePaths(absBase) {
72
+ let resolved;
73
+ try {
74
+ resolved = TsconfigLoaderSync.resolve(absBase, tsconfigSyncOptions);
75
+ } catch {
76
+ return {};
77
+ }
78
+ const paths = resolved.compilerOptions.paths;
79
+ if (paths === void 0) return {};
80
+ const anchor = resolved.compilerOptions.baseUrl ?? resolved.pathsBase ?? dirname(absBase);
81
+ return Object.fromEntries(Object.entries(paths).map(([key, targets]) => [key, targets.map((target) => isAbsolute(target) ? target : resolve(anchor, target))]));
82
+ }
83
+ /**
84
+ * Map an API Extractor message to a collector DiagnosticInput, or undefined if not warn/error.
85
+ *
86
+ * Location (`file`/`line`/`column`) is preserved: diagnostics now come from a per-module declaration
87
+ * run (see generateMeta's two-input split), where each `.d.ts.map` references only its own source, so
88
+ * positions resolve to the true source declaration. Reverts the systems#154 mitigation. See systems#162.
89
+ */
90
+ function mapExtractorMessage(message) {
91
+ const isError = message.logLevel === ExtractorLogLevel.Error;
92
+ const isWarning = message.logLevel === ExtractorLogLevel.Warning;
93
+ if (!isError && !isWarning) return void 0;
94
+ return {
95
+ source: "api-extractor",
96
+ level: isError ? "error" : "warn",
97
+ text: message.text,
98
+ ...message.messageId !== void 0 ? { code: message.messageId } : {},
99
+ ...message.sourceFilePath !== void 0 ? { file: message.sourceFilePath } : {},
100
+ ...message.sourceFileLine !== void 0 ? { line: message.sourceFileLine } : {},
101
+ ...message.sourceFileColumn !== void 0 ? { column: message.sourceFileColumn } : {}
102
+ };
103
+ }
104
+ /**
105
+ * A path with its symlinks resolved. A tail that does not exist is kept on its deepest ancestor that does, so a missing
106
+ * file cannot read as outside a package whose own path resolved through a link.
107
+ */
108
+ const canonicalPath = (path) => {
109
+ try {
110
+ return realpathSync.native(path);
111
+ } catch {
112
+ const parent = dirname(path);
113
+ return parent === path ? path : join(canonicalPath(parent), basename(path));
114
+ }
115
+ };
116
+ /**
117
+ * Whether `path` belongs to the package at `cwd` rather than to something it imports: its realpath lies inside the
118
+ * package, and outside the package's `node_modules`. A workspace link realpaths to the sibling's own directory, and a
119
+ * dependency installed as a real directory under `node_modules` is no more the package's own source than a linked one.
120
+ * The one rule both own-vs-foreign judgements of `ae-wrong-input-file-type` read.
121
+ */
122
+ const isOwnPath = (path, cwd) => {
123
+ const fromPackage = relative(canonicalPath(cwd), canonicalPath(resolve(cwd, path)));
124
+ if (fromPackage === ".." || fromPackage.startsWith(`..${sep}`) || isAbsolute(fromPackage)) return false;
125
+ return !fromPackage.split(sep).includes("node_modules");
126
+ };
127
+ /**
128
+ * Whether a message says API Extractor followed an import to a `.ts` file outside this package, or into its
129
+ * `node_modules`. That is what a workspace link to a sibling's source, or a dependency shipping its sources, looks like,
130
+ * and the model does not change. The same message about the package's own file stays a warning: it means the package's
131
+ * own declarations reached its source.
132
+ */
133
+ function isForeignInputFileMessage(message, cwd) {
134
+ if (message.messageId !== "ae-wrong-input-file-type" || message.sourceFilePath === void 0) return false;
135
+ return !isOwnPath(message.sourceFilePath, cwd);
136
+ }
137
+ /** A TypeScript source that is not a declaration file: what the declaration program must never hold. */
138
+ const isTsSource = (path) => /\.[cm]?tsx?$/.test(path) && !ExtractorConfig.hasDtsFileExtension(path);
139
+ /**
140
+ * Every TypeScript source of the package's own that reached a declaration program, in the program's own path form (the
141
+ * form API Extractor's messages carry): a non-declaration `.ts`/`.tsx`/`.mts`/`.cts` whose realpath lies inside `cwd`
142
+ * and outside its `node_modules`.
143
+ *
144
+ * API Extractor reports `ae-wrong-input-file-type` for only the FIRST non-declaration file of its program, so when a
145
+ * sibling's source sorts first, the one message names the sibling and an own-source leak behind it goes unseen. The
146
+ * program's file list holds every one, whatever the order.
147
+ */
148
+ function ownSourceInputFiles(program, cwd) {
149
+ return program.getSourceFiles().map(({ fileName }) => resolve(cwd, fileName)).filter((path) => isTsSource(path) && isOwnPath(path, cwd));
150
+ }
151
+ /** Run API Extractor over a single entry's .d.ts, writing the .api.json (and optionally tsdoc-metadata.json). Throws on failure. */
152
+ function runApiExtractor(options) {
153
+ const suppressor = createMessageSuppressor(options.suppressWarnings);
154
+ const tsdocConfigFile = TSDocConfigFile.loadForFolder(dirname(options.tsdocConfigPath));
155
+ const namedOwnInputs = /* @__PURE__ */ new Set();
156
+ const extractorConfig = ExtractorConfig.prepare({
157
+ configObject: {
158
+ projectFolder: options.cwd,
159
+ mainEntryPointFilePath: options.entryDtsPath,
160
+ enumMemberOrder: "preserve",
161
+ compiler: { tsconfigFilePath: writeApiExtractorTsconfig({
162
+ cwd: options.cwd,
163
+ tsconfigPath: options.tsconfigPath,
164
+ entryDtsPath: options.entryDtsPath,
165
+ paths: options.selfReferencePaths
166
+ }) },
167
+ docModel: options.emitDocModel === false ? { enabled: false } : {
168
+ enabled: true,
169
+ apiJsonFilePath: options.apiJsonPath,
170
+ includeForgottenExports: true
171
+ },
172
+ ...options.tsdocMetadataPath !== void 0 ? { tsdocMetadata: {
173
+ enabled: true,
174
+ tsdocMetadataFilePath: options.tsdocMetadataPath
175
+ } } : {},
176
+ dtsRollup: { enabled: false },
177
+ apiReport: { enabled: false },
178
+ messages: {
179
+ extractorMessageReporting: {
180
+ default: { logLevel: "warning" },
181
+ "ae-internal-missing-underscore": { logLevel: "none" },
182
+ ...options.ci === true ? Object.fromEntries([...CI_FATAL_MESSAGE_IDS].map((id) => [id, { logLevel: "error" }])) : {}
183
+ },
184
+ tsdocMessageReporting: { default: { logLevel: "warning" } }
185
+ }
186
+ },
187
+ packageJsonFullPath: options.packageJsonPath,
188
+ configObjectFullPath: void 0,
189
+ tsdocConfigFile
190
+ });
191
+ const result = Extractor.invoke(extractorConfig, {
192
+ localBuild: true,
193
+ showVerboseMessages: false,
194
+ messageCallback: (message) => {
195
+ if (message.messageId === "ae-wrong-input-file-type" && message.sourceFilePath !== void 0) namedOwnInputs.add(canonicalPath(resolve(options.cwd, message.sourceFilePath)));
196
+ if (suppressor.matches(message.messageId, message.text) || isForeignInputFileMessage(message, options.cwd)) {
197
+ if (options.onSuppressed !== void 0) {
198
+ const entry = mapExtractorMessage(message);
199
+ if (entry !== void 0) options.onSuppressed(entry);
200
+ }
201
+ message.logLevel = ExtractorLogLevel.None;
202
+ message.handled = true;
203
+ return;
204
+ }
205
+ if (message.messageId === "console-compiler-version-notice" || message.messageId === "console-preamble") {
206
+ message.logLevel = ExtractorLogLevel.None;
207
+ message.handled = true;
208
+ }
209
+ if (options.onMessage !== void 0) {
210
+ const entry = mapExtractorMessage(message);
211
+ if (entry !== void 0) {
212
+ const ciFatal = options.ci !== true && entry.level === "warn" && entry.code !== void 0 && CI_FATAL_MESSAGE_IDS.has(entry.code);
213
+ options.onMessage(ciFatal ? {
214
+ ...entry,
215
+ ciFatal: true
216
+ } : entry);
217
+ message.handled = true;
218
+ }
219
+ }
220
+ }
221
+ });
222
+ for (const file of ownSourceInputFiles(result.compilerState.program, options.cwd)) {
223
+ if (namedOwnInputs.has(canonicalPath(file))) continue;
224
+ const code = "ae-wrong-input-file-type";
225
+ const entry = {
226
+ source: "api-extractor",
227
+ level: "warn",
228
+ code,
229
+ text: `The package's own source "${relative(canonicalPath(options.cwd), canonicalPath(file))}" reached the declaration program; API Extractor expects to analyze compiler outputs with the .d.ts file extension.`,
230
+ file
231
+ };
232
+ if (suppressor.matches(code, entry.text)) options.onSuppressed?.(entry);
233
+ else options.onMessage?.(entry);
234
+ }
235
+ if (!result.succeeded) throw new MetaGenerationError({
236
+ entry: options.entryDtsPath,
237
+ reason: `API Extractor reported ${result.errorCount} error(s) and ${result.warningCount} warning(s)`
238
+ });
239
+ }
240
+
241
+ export { isForeignInputFileMessage, mapExtractorMessage, ownSourceInputFiles, runApiExtractor, writeApiExtractorTsconfig };
@@ -0,0 +1,22 @@
1
+ // src/meta/bundle-config.ts
2
+ /**
3
+ * The options the meta pass takes, from the decoded `[package.bundle]` table. The table names a renderer, and the
4
+ * caller passes the generator it resolved to; a table that asks for none needs none.
5
+ */
6
+ function bundleMetaOptionsOf(config, generate) {
7
+ const { name, tagline, description, registries, openGraph } = config;
8
+ return {
9
+ ...name !== void 0 ? { name } : {},
10
+ ...tagline !== void 0 ? { tagline } : {},
11
+ ...description !== void 0 ? { description } : {},
12
+ ...registries !== void 0 ? { registries: registries === false ? false : registries.map((r) => ({ ...r })) } : {},
13
+ ...openGraph !== void 0 ? { openGraph: {
14
+ ...openGraph.images !== void 0 ? { images: openGraph.images.map((image) => ({ ...image })) } : {},
15
+ ...openGraph.themeColor !== void 0 ? { themeColor: openGraph.themeColor } : {},
16
+ ...openGraph.cacheSalt !== void 0 ? { cacheSalt: openGraph.cacheSalt } : {},
17
+ ...generate !== void 0 ? { generate } : {}
18
+ } } : {}
19
+ };
20
+ }
21
+
22
+ export { bundleMetaOptionsOf };