@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
package/package.json CHANGED
@@ -1,6 +1,87 @@
1
1
  {
2
- "name": "@effected/bundler",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@effected/bundler",
3
+ "version": "0.2.0",
4
+ "private": false,
5
+ "description": "The kit's build pipeline: effected.toml config, tsdown JS and declaration passes, API Extractor meta, SEA, GitHub Action bundles and build journals.",
6
+ "keywords": [
7
+ "bundler",
8
+ "build",
9
+ "tsdown",
10
+ "rolldown",
11
+ "api-extractor",
12
+ "effect",
13
+ "effected"
14
+ ],
15
+ "homepage": "https://github.com/spencerbeggs/effected/tree/main/packages/bundler#readme",
16
+ "bugs": {
17
+ "url": "https://github.com/spencerbeggs/effected/issues"
18
+ },
19
+ "repository": {
20
+ "type": "git",
21
+ "url": "git+https://github.com/spencerbeggs/effected.git",
22
+ "directory": "packages/bundler"
23
+ },
24
+ "license": "MIT",
25
+ "author": {
26
+ "name": "C. Spencer Beggs",
27
+ "email": "spencer@beggs.codes",
28
+ "url": "https://spencerbeg.gs"
29
+ },
30
+ "sideEffects": false,
31
+ "type": "module",
32
+ "exports": {
33
+ ".": {
34
+ "types": "./index.d.ts",
35
+ "import": "./index.js",
36
+ "default": "./index.js"
37
+ },
38
+ "./package.json": "./package.json"
39
+ },
40
+ "dependencies": {
41
+ "@effect/platform-node": "~4.1.2",
42
+ "@effected/changesets": "0.2.0",
43
+ "@effected/config-file": "^0.26.0",
44
+ "@effected/env": "^0.11.0",
45
+ "@effected/files": "^0.2.0",
46
+ "@effected/glob": "^0.20.0",
47
+ "@effected/images": "^0.9.0",
48
+ "@effected/jsonc": "^0.24.0",
49
+ "@effected/jsonl": "^0.18.0",
50
+ "@effected/manifest": "^0.1.0",
51
+ "@effected/npm": "^0.32.0",
52
+ "@effected/package-json": "^0.31.1",
53
+ "@effected/semver": "^0.22.0",
54
+ "@effected/toml": "^0.19.1",
55
+ "@effected/tsconfig-json": "^0.20.2",
56
+ "@effected/walker": "^0.26.0",
57
+ "@effected/workspaces": "^0.44.1",
58
+ "@effected/yaml": "^0.29.0",
59
+ "@jridgewell/sourcemap-codec": "^1.6.0",
60
+ "@microsoft/api-extractor": "^7.60.1",
61
+ "@microsoft/tsdoc": "~0.17.1",
62
+ "@microsoft/tsdoc-config": "~0.18.3",
63
+ "@tsdown/exe": "^0.23.4",
64
+ "jiti": "~2.7.0",
65
+ "rolldown": "^1.2.16",
66
+ "rolldown-plugin-dts": "^0.30.0",
67
+ "tsdown": "^0.23.4"
68
+ },
69
+ "peerDependencies": {
70
+ "@resvg/resvg-js": "^2.6.2",
71
+ "@types/node": "^26.6.0",
72
+ "effect": "~4.1.0",
73
+ "satori": "^0.63.2",
74
+ "typescript": "7.1.0-beta || 7.1.1-rc || >=7.1.0 <8"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@resvg/resvg-js": {
78
+ "optional": true
79
+ },
80
+ "satori": {
81
+ "optional": true
82
+ }
83
+ },
84
+ "engines": {
85
+ "node": ">=24.11.0"
86
+ }
87
+ }
@@ -0,0 +1,347 @@
1
+ import { packageNameOf, resolveBundledSiblings, siblingPaths } from "../dts/bundled-siblings.js";
2
+ import { analyzeReexportBarrel, collectExportNames, renderReexportStub } from "../dts/reexport-stub.js";
3
+ import { writeDtsEmitTsconfig } from "../dts/resolved-tsconfig.js";
4
+ import { extractAmbientDts } from "../entries/ambient-dts.js";
5
+ import { emitManifest } from "../manifest/emit-manifest.js";
6
+ import { buildMetricsPlugin } from "../report/metrics-plugin.js";
7
+ import { createTimer } from "../report/timer.js";
8
+ import { createTsdownLogger } from "../report/tsdown-logger.js";
9
+ import { cjsDefaultInterop } from "./cjs-default-interop.js";
10
+ import { nodeBuiltinDefaultInterop } from "./node-builtin-default-interop.js";
11
+ import { copyAmbientDts, copyPublicDir } from "./sync-public.js";
12
+ import { deriveDeclarationsPassOptions, deriveDtsPassOptions, deriveTargetGroupOptions, outDirFor } from "./target-groups.js";
13
+ import { readFileSync, writeFileSync } from "node:fs";
14
+ import { dirname, isAbsolute, join } from "node:path";
15
+
16
+ // src/passes/build-target-groups.ts
17
+ /**
18
+ * Entry name of the conventional primary (".") export, which `createEntryName` maps to "index". It is
19
+ * the re-export-stub base: a secondary entry that re-exports a subset of it gets a thin stub pointing
20
+ * here instead of a self-contained rollup.
21
+ */
22
+ const STUB_BASE_ENTRY = "index";
23
+ /** The configured copy entries as tsdown takes them for one group, with each `to` anchored to that group's outDir. */
24
+ const copyEntriesFor = (entries, outDir) => entries.map((entry) => {
25
+ if (typeof entry === "string") return entry;
26
+ return {
27
+ from: entry.from,
28
+ ...entry.to !== void 0 ? { to: join(outDir, entry.to) } : {},
29
+ ...entry.flatten !== void 0 ? { flatten: entry.flatten } : {}
30
+ };
31
+ });
32
+ /**
33
+ * Run tsdown.build() per TargetGroup. Composable so the escape hatch gets multi-group too.
34
+ *
35
+ * Each group runs TWO passes to the SAME outDir:
36
+ * 1. JS pass — per-module JS (`unbundle: true`, `dts: false`), with the `emitManifest` plugin
37
+ * and the `public/` copy. Default `clean: true` gives it a fresh outDir.
38
+ * 2. dts pass — bundled declarations only (`unbundle: false`, `dts: { emitDtsOnly: true }`,
39
+ * `clean: false`). No manifest plugin, no copy, no sourcemaps. `clean: false` is load-bearing:
40
+ * it must NOT wipe the JS the first pass just wrote.
41
+ *
42
+ * Why two passes: tsdown's `unbundle` maps to rolldown `output.preserveModules` for the whole
43
+ * build (JS and the dts plugin share it), so a single pass cannot give per-module JS + bundled
44
+ * dts. Per-module dts breaks type portability (TS2883); bundling the JS re-bundles workspace
45
+ * consumers. The split keeps per-module JS AND rolled-up, self-contained declarations.
46
+ *
47
+ * **The JS pass's `unbundle` flips to `false` for a `bundleNodeModules` partition** (see
48
+ * `DerivedTsdownOptions` in `target-groups.ts`), so that partition's JS pass ALSO bundles
49
+ * instead of preserving modules — a per-module preserveModules JS pass writes every inlined
50
+ * node_modules dependency to its own sibling file (mirroring its `node_modules/...` path),
51
+ * which `npm pack` then strips, breaking the "self-contained" promise `bundleNodeModules`
52
+ * already makes. Scoped to that flag alone; every other build's JS pass is unaffected.
53
+ * @public
54
+ */
55
+ async function buildTargetGroups(options) {
56
+ const build = options.build ?? (await import("tsdown")).build;
57
+ const publicDir = join(options.cwd, "public");
58
+ let pkgForAmbient = {};
59
+ try {
60
+ pkgForAmbient = JSON.parse(readFileSync(join(options.cwd, "package.json"), "utf-8"));
61
+ } catch {}
62
+ const ambient = extractAmbientDts(pkgForAmbient, {});
63
+ const dtsEmitTsconfigPath = writeDtsEmitTsconfig(options.tsconfigPath);
64
+ const bundledSiblings = options.emitDts === false ? [] : await resolveBundledSiblings(options.cwd, [...options.bundledPackages ?? [], ...(options.overrides ?? []).flatMap((override) => override.bundledPackages ?? [])]);
65
+ const emitTsconfigFor = (bundled) => {
66
+ const packages = new Set(bundled?.map(packageNameOf));
67
+ const siblings = bundledSiblings.filter((sibling) => packages.has(sibling.name));
68
+ return siblings.length > 0 ? writeDtsEmitTsconfig(options.tsconfigPath, { paths: siblingPaths(siblings) }) : dtsEmitTsconfigPath;
69
+ };
70
+ const collector = options.collector;
71
+ const verbose = options.verbose ?? false;
72
+ const instrument = (groupId) => collector === void 0 ? {} : {
73
+ logLevel: "silent",
74
+ customLogger: createTsdownLogger(collector, groupId)
75
+ };
76
+ const metricsPlugins = (groupId, pass, suppressMixedExports = false) => collector === void 0 ? [] : [buildMetricsPlugin(collector, groupId, pass, verbose, suppressMixedExports)];
77
+ const timingChecks = { checks: { pluginTimings: verbose } };
78
+ const timed = async (groupId, pass, run) => {
79
+ options.onPass?.(pass);
80
+ const timer = createTimer();
81
+ try {
82
+ await run();
83
+ } finally {
84
+ if (collector !== void 0) collector.recordPassTiming(groupId, pass, timer.elapsed());
85
+ }
86
+ };
87
+ for (const group of options.groups) {
88
+ if (collector !== void 0) collector.registerGroup(group.id, Object.keys(options.entry));
89
+ const partitions = [{
90
+ entry: options.entry,
91
+ ...options.format !== void 0 ? { format: options.format } : {},
92
+ ...options.externals !== void 0 ? { externals: options.externals } : {},
93
+ ...options.bundle !== void 0 ? { bundle: options.bundle } : {},
94
+ ...options.bundleNodeModules !== void 0 ? { bundleNodeModules: options.bundleNodeModules } : {},
95
+ ...options.bundledPackages !== void 0 ? { bundledPackages: options.bundledPackages } : {},
96
+ ...options.dtsExternals !== void 0 ? { dtsExternals: options.dtsExternals } : {}
97
+ }, ...options.overrides ?? []];
98
+ for (let p = 0; p < partitions.length; p++) {
99
+ const part = partitions[p];
100
+ if (part === void 0) continue;
101
+ const isBase = p === 0;
102
+ const partExternals = part.externals;
103
+ const partBundle = part.bundle;
104
+ const partBundleNodeModules = part.bundleNodeModules;
105
+ const partBundledPackages = part.bundledPackages;
106
+ const partDtsExternals = part.dtsExternals;
107
+ const deriveInput = {
108
+ group: group.id,
109
+ cwd: options.cwd,
110
+ version: options.version,
111
+ entry: part.entry,
112
+ tsconfigPath: emitTsconfigFor(partBundledPackages),
113
+ devManifest: options.devManifest,
114
+ ...partExternals !== void 0 ? { externals: partExternals } : {},
115
+ ...partBundleNodeModules !== void 0 ? { bundleNodeModules: partBundleNodeModules } : {},
116
+ ...partBundledPackages !== void 0 ? { bundledPackages: partBundledPackages } : {},
117
+ ...part.format !== void 0 ? { format: part.format } : {},
118
+ ...options.minify !== void 0 ? { minify: options.minify } : {},
119
+ ...options.define !== void 0 ? { define: options.define } : {},
120
+ ...part.platform !== void 0 ? { platform: part.platform } : {}
121
+ };
122
+ const js = deriveTargetGroupOptions(deriveInput);
123
+ const dts = deriveDtsPassOptions(deriveInput);
124
+ const decl = deriveDeclarationsPassOptions(deriveInput);
125
+ const partOutDir = part.outSubdir !== void 0 ? join(js.outDir, part.outSubdir) : js.outDir;
126
+ const targetGroup = {
127
+ id: group.id,
128
+ name: group.name,
129
+ isProd: js.isProd
130
+ };
131
+ const srcDir = dirname(Object.values(part.entry)[0] ?? "");
132
+ const jsEntry = part.outSubdir !== void 0 ? [
133
+ `${srcDir}/**/*.{ts,tsx,mts,cts}`,
134
+ `!${srcDir}/**/*.{test,spec}.{ts,tsx,mts,cts}`,
135
+ `!${srcDir}/**/*.d.{ts,cts,mts}`
136
+ ] : js.entry;
137
+ const manifestPlugin = isBase ? emitManifest({
138
+ targetGroup,
139
+ devManifest: options.devManifest,
140
+ drop: options.drop,
141
+ ...options.set !== void 0 ? { set: options.set } : {},
142
+ sourceDir: options.cwd,
143
+ dual: options.dualExports ?? js.format.includes("cjs"),
144
+ emitDts: options.emitDts !== false,
145
+ ...options.subdirExports !== void 0 ? { subdirExports: options.subdirExports } : {},
146
+ ...options.exeRewrite !== void 0 ? { exeRewrite: options.exeRewrite } : {}
147
+ }) : void 0;
148
+ await timed(group.id, "js", () => build({
149
+ config: false,
150
+ cwd: options.cwd,
151
+ entry: jsEntry,
152
+ outDir: partOutDir,
153
+ format: js.format,
154
+ platform: js.platform,
155
+ sourcemap: js.sourcemap,
156
+ minify: js.minify,
157
+ unbundle: js.unbundle,
158
+ clean: isBase ? js.clean : false,
159
+ fixedExtension: js.fixedExtension,
160
+ dts: js.dts,
161
+ define: js.define,
162
+ ...timingChecks,
163
+ ...instrument(group.id),
164
+ ...part.css !== void 0 ? { css: part.css } : {},
165
+ ...isBase && options.copy?.length ? { copy: copyEntriesFor(options.copy, partOutDir) } : {},
166
+ ...partExternals?.length || partBundle?.length ? { deps: {
167
+ ...partExternals?.length ? { neverBundle: partExternals } : {},
168
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {}
169
+ } } : {},
170
+ ...js.cjsDefault !== void 0 ? { cjsDefault: js.cjsDefault } : {},
171
+ plugins: [
172
+ ...manifestPlugin ? [manifestPlugin] : [],
173
+ ...js.format.includes("cjs") ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
174
+ ...options.extraPlugins ?? [],
175
+ ...metricsPlugins(group.id, "js", js.format.includes("cjs"))
176
+ ]
177
+ }));
178
+ const dtsNeverBundle = [...partExternals ?? [], ...partDtsExternals ?? []];
179
+ if (options.emitDts === false || Object.keys(dts.entry).length === 0) continue;
180
+ const dtsDeps = dtsNeverBundle.length > 0 || dts.bundledPackages || partBundle?.length ? { deps: {
181
+ ...dtsNeverBundle.length > 0 ? { neverBundle: dtsNeverBundle } : {},
182
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {},
183
+ ...dts.bundledPackages ? partBundleNodeModules ? { dts: { alwaysBundle: dts.bundledPackages } } : {
184
+ neverBundle: true,
185
+ dts: { alwaysBundle: dts.bundledPackages }
186
+ } : {}
187
+ } } : {};
188
+ const stubEntries = /* @__PURE__ */ new Map();
189
+ const readSource = (src) => {
190
+ try {
191
+ return readFileSync(isAbsolute(src) ? src : join(options.cwd, src), "utf-8");
192
+ } catch {
193
+ return;
194
+ }
195
+ };
196
+ const baseSrc = dts.entry[STUB_BASE_ENTRY];
197
+ if (baseSrc !== void 0 && Object.keys(dts.entry).length > 1) {
198
+ const baseSource = readSource(baseSrc);
199
+ const base = baseSource !== void 0 ? collectExportNames(baseSource) : void 0;
200
+ if (base?.complete === true) for (const [entryName, entrySource] of Object.entries(dts.entry)) {
201
+ if (entryName === STUB_BASE_ENTRY || entryName.includes("/")) continue;
202
+ const source = readSource(entrySource);
203
+ if (source === void 0) continue;
204
+ const analysis = analyzeReexportBarrel(source);
205
+ if (!analysis.isPureNamedReexportBarrel) continue;
206
+ const all = [...analysis.valueNames, ...analysis.typeNames];
207
+ if (all.length === 0 || !all.every((n) => base.names.has(n))) continue;
208
+ stubEntries.set(entryName, {
209
+ valueNames: analysis.valueNames,
210
+ typeNames: analysis.typeNames
211
+ });
212
+ }
213
+ }
214
+ await timed(group.id, "dts", async () => {
215
+ for (const [entryName, entrySource] of Object.entries(dts.entry)) {
216
+ const stub = stubEntries.get(entryName);
217
+ if (stub !== void 0) {
218
+ const variants = [{
219
+ file: `${entryName}.d.ts`,
220
+ spec: `./${STUB_BASE_ENTRY}.js`
221
+ }];
222
+ if (dts.format.includes("cjs")) variants.push({
223
+ file: `${entryName}.d.cts`,
224
+ spec: `./${STUB_BASE_ENTRY}.cjs`
225
+ });
226
+ for (const variant of variants) {
227
+ const content = renderReexportStub({
228
+ valueNames: stub.valueNames,
229
+ typeNames: stub.typeNames,
230
+ baseSpecifier: variant.spec
231
+ });
232
+ writeFileSync(join(partOutDir, variant.file), content, "utf-8");
233
+ collector?.recordEmitted(group.id, "dts", {
234
+ path: variant.file,
235
+ bytes: Buffer.byteLength(content)
236
+ });
237
+ }
238
+ continue;
239
+ }
240
+ await build({
241
+ config: false,
242
+ cwd: options.cwd,
243
+ entry: { [entryName]: entrySource },
244
+ outDir: partOutDir,
245
+ format: dts.format,
246
+ platform: dts.platform,
247
+ sourcemap: dts.sourcemap,
248
+ unbundle: dts.unbundle,
249
+ clean: false,
250
+ fixedExtension: dts.fixedExtension,
251
+ dts: dts.dts,
252
+ define: dts.define,
253
+ ...timingChecks,
254
+ ...instrument(group.id),
255
+ ...dtsDeps,
256
+ plugins: [
257
+ ...dts.format.includes("cjs") ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
258
+ ...options.extraPlugins ?? [],
259
+ ...metricsPlugins(group.id, "dts", dts.format.includes("cjs"))
260
+ ]
261
+ });
262
+ }
263
+ });
264
+ if (js.isProd && options.emitDeclarations === true && Object.keys(decl.entry).length > 0) {
265
+ const partDeclDir = part.outSubdir !== void 0 ? join(decl.outDir, part.outSubdir) : decl.outDir;
266
+ try {
267
+ await build({
268
+ config: false,
269
+ cwd: options.cwd,
270
+ entry: decl.entry,
271
+ outDir: partDeclDir,
272
+ format: decl.format,
273
+ platform: decl.platform,
274
+ sourcemap: decl.sourcemap,
275
+ unbundle: decl.unbundle,
276
+ clean: isBase,
277
+ fixedExtension: decl.fixedExtension,
278
+ dts: decl.dts,
279
+ define: decl.define,
280
+ ...timingChecks,
281
+ logLevel: "silent",
282
+ ...dtsNeverBundle.length > 0 || decl.bundledPackages || partBundle?.length ? { deps: {
283
+ ...dtsNeverBundle.length > 0 ? { neverBundle: dtsNeverBundle } : {},
284
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {},
285
+ ...decl.bundledPackages ? partBundleNodeModules ? { dts: { alwaysBundle: decl.bundledPackages } } : {
286
+ neverBundle: true,
287
+ dts: { alwaysBundle: decl.bundledPackages }
288
+ } : {}
289
+ } } : {},
290
+ ...options.extraPlugins !== void 0 ? { plugins: [...options.extraPlugins] } : {}
291
+ });
292
+ } catch (err) {
293
+ collector?.recordWarning(group.id, {
294
+ source: "tsdown",
295
+ level: "warn",
296
+ text: `Could not emit per-module declarations for API Extractor diagnostics: ${String(err)}`
297
+ });
298
+ }
299
+ }
300
+ }
301
+ const looseOutDir = outDirFor(options.cwd, group.id);
302
+ const isProdGroup = group.id !== "dev";
303
+ const looseDeps = {
304
+ ...options.externals?.length ? { neverBundle: options.externals } : {},
305
+ ...options.bundle?.length ? { alwaysBundle: options.bundle } : {}
306
+ };
307
+ for (const lf of options.looseFiles ?? []) {
308
+ const hasCjs = lf.format === "cjs";
309
+ await timed(group.id, "loose", () => build({
310
+ config: false,
311
+ cwd: options.cwd,
312
+ entry: { [lf.entryName]: lf.source },
313
+ outDir: looseOutDir,
314
+ format: [lf.format],
315
+ platform: "node",
316
+ sourcemap: !isProdGroup,
317
+ minify: isProdGroup && (options.minify ?? false),
318
+ unbundle: false,
319
+ clean: false,
320
+ fixedExtension: lf.fixedExtension,
321
+ dts: false,
322
+ define: {
323
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
324
+ ...options.define
325
+ },
326
+ ...timingChecks,
327
+ ...instrument(group.id),
328
+ ...Object.keys(looseDeps).length > 0 ? { deps: looseDeps } : {},
329
+ ...hasCjs ? { cjsDefault: true } : {},
330
+ plugins: [
331
+ ...hasCjs ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
332
+ ...options.extraPlugins ?? [],
333
+ ...metricsPlugins(group.id, "loose", hasCjs)
334
+ ]
335
+ }));
336
+ }
337
+ const groupOutDir = outDirFor(options.cwd, group.id);
338
+ copyPublicDir(publicDir, groupOutDir);
339
+ if (ambient.length > 0) copyAmbientDts({
340
+ ambient,
341
+ srcCwd: options.cwd,
342
+ outDir: groupOutDir
343
+ });
344
+ }
345
+ }
346
+
347
+ export { buildTargetGroups };
@@ -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 };