@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,134 @@
1
+ import { MANIFEST_SPEC } from "./BundleManifest.js";
2
+
3
+ // src/meta/tsdoctor-manifest.ts
4
+ const first = (...values) => values.find((v) => v !== void 0);
5
+ /**
6
+ * `owner/repo` from any of the GitHub URL spellings a `repository.url` carries (https, `git+https`,
7
+ * `git@`, `ssh://`, `git://`, the `github:` shorthand), or `undefined` for anything else.
8
+ *
9
+ * @public
10
+ */
11
+ function githubOwnerRepo(url) {
12
+ const match = /^(?:git\+)?(?:https?:\/\/|git:\/\/|ssh:\/\/(?:git@)?|git@)?(?:www\.)?github\.com[/:]([^/]{1,214})\/([^/]{1,214}?)(?:\.git)?\/?$/i.exec(url.trim()) ?? /^github:([^/]{1,214})\/([^/]{1,214}?)(?:\.git)?$/i.exec(url.trim());
13
+ if (match === null) return void 0;
14
+ const owner = match[1];
15
+ const repo = match[2];
16
+ if (owner === void 0 || repo === void 0 || owner.length === 0 || repo.length === 0) return void 0;
17
+ return {
18
+ owner,
19
+ repo
20
+ };
21
+ }
22
+ function unscopedName(name) {
23
+ const slash = name.lastIndexOf("/");
24
+ return slash >= 0 ? name.slice(slash + 1) : name;
25
+ }
26
+ /**
27
+ * The package's human page on a registry, or `undefined` when no real page can be derived. npmjs
28
+ * has a well-known page; GitHub Packages pages hang off the repository, so they need a parseable
29
+ * `repository.url` and are omitted rather than emitted as a dead link when it is missing.
30
+ */
31
+ /** Strip trailing slashes without a `/\/+$/` regex, which backtracks polynomially on slash runs (CodeQL js/polynomial-redos). */
32
+ function stripTrailingSlashes(value) {
33
+ let end = value.length;
34
+ while (end > 0 && value.charCodeAt(end - 1) === 47) end -= 1;
35
+ return value.slice(0, end);
36
+ }
37
+ function packagePageUrl(registry, packageName, repository) {
38
+ const host = stripTrailingSlashes(registry);
39
+ if (host === "https://registry.npmjs.org") return `https://www.npmjs.com/package/${packageName}`;
40
+ if (/^https?:\/\/npm\.pkg\.github\.com$/i.test(host)) {
41
+ const gh = repository !== void 0 ? githubOwnerRepo(repository.url) : void 0;
42
+ return gh === void 0 ? void 0 : `https://github.com/${gh.owner}/${gh.repo}/pkgs/npm/${unscopedName(packageName)}`;
43
+ }
44
+ return `${host}/package/${packageName}`;
45
+ }
46
+ function projectIdentityOf(project) {
47
+ if (project === void 0) return void 0;
48
+ if (project.name === void 0 && project.tagline === void 0) return void 0;
49
+ return {
50
+ ...project.name !== void 0 ? { name: project.name } : {},
51
+ ...project.tagline !== void 0 ? { tagline: project.tagline } : {}
52
+ };
53
+ }
54
+ /**
55
+ * Derive the registries block from the build's targets. Only for a public
56
+ * package: a private one is published nowhere.
57
+ *
58
+ * @public
59
+ */
60
+ function registriesFromTargets(input) {
61
+ if (input.isPrivate) return [];
62
+ const out = [];
63
+ for (const t of input.targets) {
64
+ const url = packagePageUrl(t.registry, input.packageName, input.repository);
65
+ if (url !== void 0) out.push({
66
+ type: "npm",
67
+ name: t.name,
68
+ url
69
+ });
70
+ }
71
+ return out;
72
+ }
73
+ /**
74
+ * Flatten the three authoring tiers into the emitted manifest. Pure.
75
+ *
76
+ * @remarks
77
+ * Config beats leaf beats project per FIELD; the project tier is emitted
78
+ * nested, never flattened, because the consumer's provenance ranking depends
79
+ * on telling the tiers apart. Returns `undefined` when there is nothing to
80
+ * say, so a package with no metadata emits no file. An `sbom` pointer is
81
+ * never written here — the release action upserts it at publish.
82
+ *
83
+ * @public
84
+ */
85
+ function composeTsdoctorManifest(input) {
86
+ const { config, leaf, project } = input;
87
+ const images = [
88
+ ...input.generatedImage !== void 0 ? [input.generatedImage] : [],
89
+ ...config?.openGraph?.images ?? [],
90
+ ...leaf?.openGraph?.images ?? [],
91
+ ...project?.openGraph?.images ?? []
92
+ ];
93
+ const themeColor = first(config?.openGraph?.themeColor, leaf?.openGraph?.themeColor, project?.openGraph?.themeColor);
94
+ const openGraph = images.length > 0 || themeColor !== void 0 ? {
95
+ ...images.length > 0 ? { images } : {},
96
+ ...themeColor !== void 0 ? { themeColor } : {}
97
+ } : void 0;
98
+ const registries = config?.registries === false ? void 0 : first(config?.registries, leaf?.registries) ?? registriesFromTargets(input);
99
+ const name = first(config?.name, leaf?.name);
100
+ const tagline = first(config?.tagline, leaf?.tagline);
101
+ const description = first(config?.description, leaf?.description);
102
+ const projectIdentity = projectIdentityOf(project);
103
+ const manifest = {
104
+ spec: 1,
105
+ ...name !== void 0 ? { name } : {},
106
+ ...tagline !== void 0 ? { tagline } : {},
107
+ ...description !== void 0 ? { description } : {},
108
+ ...projectIdentity !== void 0 ? { project: projectIdentity } : {},
109
+ ...openGraph !== void 0 ? { openGraph } : {},
110
+ ...registries !== void 0 && registries.length > 0 ? { registries } : {}
111
+ };
112
+ return Object.keys(manifest).length > 1 ? manifest : void 0;
113
+ }
114
+ /**
115
+ * What the generator sees. Built from the same tiers as the manifest.
116
+ *
117
+ * @public
118
+ */
119
+ function ogImageInfoOf(input) {
120
+ const { config, leaf, project } = input;
121
+ const tagline = first(config?.tagline, leaf?.tagline, project?.tagline);
122
+ const description = first(config?.description, leaf?.description);
123
+ const projectIdentity = projectIdentityOf(project);
124
+ return {
125
+ name: first(config?.name, leaf?.name) ?? input.packageName,
126
+ packageName: input.packageName,
127
+ version: input.version,
128
+ ...tagline !== void 0 ? { tagline } : {},
129
+ ...description !== void 0 ? { description } : {},
130
+ ...projectIdentity !== void 0 ? { project: projectIdentity } : {}
131
+ };
132
+ }
133
+
134
+ export { composeTsdoctorManifest, githubOwnerRepo, ogImageInfoOf, registriesFromTargets };
@@ -0,0 +1,94 @@
1
+ import { TSDOCTOR_MANIFEST_FILENAME } from "./BundleManifest.js";
2
+ import { decodeManifestSource } from "./ManifestSource.js";
3
+ import { Data, Effect, Layer } from "effect";
4
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
5
+ import { join, resolve } from "node:path";
6
+ import * as NodeFileSystem from "@effect/platform-node/NodeFileSystem";
7
+ import * as NodePath from "@effect/platform-node/NodePath";
8
+ import { WorkspaceDiscovery, WorkspaceRootNotFoundError, Workspaces } from "@effected/workspaces";
9
+
10
+ // src/meta/tsdoctor-source.ts
11
+ /**
12
+ * A present `tsdoctor.json` source file that could not be parsed or decoded. Absence is never
13
+ * this error — a missing source tier is the normal case.
14
+ *
15
+ * @public
16
+ */
17
+ var TsdoctorSourceError = class extends Data.TaggedError("TsdoctorSourceError") {
18
+ get message() {
19
+ return `Invalid ${TSDOCTOR_MANIFEST_FILENAME} at ${this.path}`;
20
+ }
21
+ };
22
+ /** Bound once: the platform layer is stateless and layers memoize by reference. */
23
+ const platform = Layer.mergeAll(NodeFileSystem.layer, NodePath.layer);
24
+ /** The canonical absolute form of a directory, so a relative or symlinked `cwd` compares equal to the discovered root. */
25
+ function canonical(dir) {
26
+ const absolute = resolve(dir);
27
+ try {
28
+ return realpathSync(absolute);
29
+ } catch {
30
+ return absolute;
31
+ }
32
+ }
33
+ /** `Effect.runPromise` rejects with the failure itself or with a `FiberFailure` wrapping it; check both. */
34
+ function isRootNotFound(cause) {
35
+ if (cause instanceof WorkspaceRootNotFoundError) return true;
36
+ return typeof cause === "object" && cause !== null && "_tag" in cause && cause._tag === "WorkspaceRootNotFoundError";
37
+ }
38
+ /**
39
+ * The workspace root containing `cwd`, or the reason discovery failed. A package outside any
40
+ * workspace is the `root: undefined` case with no failure. Mirrors the `WorkspaceDiscovery`
41
+ * invocation in `changesets/next-versions.ts`.
42
+ */
43
+ async function findWorkspaceRoot(cwd) {
44
+ try {
45
+ const packages = await Effect.runPromise(Effect.gen(function* () {
46
+ return yield* (yield* WorkspaceDiscovery).listPackages();
47
+ }).pipe(Effect.provide(Workspaces.layer({ cwd }).pipe(Layer.provide(platform)))));
48
+ return { root: packages[0]?.isRootWorkspace ? packages[0].path : void 0 };
49
+ } catch (cause) {
50
+ if (isRootNotFound(cause)) return { root: void 0 };
51
+ return {
52
+ root: void 0,
53
+ failure: cause instanceof Error ? cause.message : String(cause)
54
+ };
55
+ }
56
+ }
57
+ async function readSource(path) {
58
+ if (!existsSync(path)) return void 0;
59
+ let parsed;
60
+ try {
61
+ parsed = JSON.parse(readFileSync(path, "utf-8"));
62
+ } catch (cause) {
63
+ throw new TsdoctorSourceError({
64
+ path,
65
+ cause
66
+ });
67
+ }
68
+ const result = await Effect.runPromise(Effect.result(decodeManifestSource(parsed, path)));
69
+ if (result._tag === "Failure") throw new TsdoctorSourceError({
70
+ path,
71
+ cause: result.failure
72
+ });
73
+ return result.success;
74
+ }
75
+ /**
76
+ * Read the leaf (`<cwd>/tsdoctor.json`) and project (`<workspaceRoot>/tsdoctor.json`)
77
+ * source tiers. Absence is normal; a present file that does not decode throws
78
+ * {@link TsdoctorSourceError}. A package that IS the workspace root reads its file once, as the
79
+ * leaf, and has no project tier.
80
+ *
81
+ * @public
82
+ */
83
+ async function loadTsdoctorSources(cwd) {
84
+ const leafDir = canonical(cwd);
85
+ const leaf = await readSource(join(leafDir, TSDOCTOR_MANIFEST_FILENAME));
86
+ const { root, failure } = await findWorkspaceRoot(leafDir);
87
+ return {
88
+ leaf,
89
+ project: root !== void 0 && canonical(root) !== leafDir ? await readSource(join(root, TSDOCTOR_MANIFEST_FILENAME)) : void 0,
90
+ ...failure !== void 0 ? { discoveryFailure: failure } : {}
91
+ };
92
+ }
93
+
94
+ export { TsdoctorSourceError, loadTsdoctorSources };
package/package.json CHANGED
@@ -1,6 +1,86 @@
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.1.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.1.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/npm": "^0.31.0",
51
+ "@effected/package-json": "^0.31.0",
52
+ "@effected/semver": "^0.22.0",
53
+ "@effected/toml": "^0.19.1",
54
+ "@effected/tsconfig-json": "^0.20.2",
55
+ "@effected/walker": "^0.26.0",
56
+ "@effected/workspaces": "^0.44.0",
57
+ "@effected/yaml": "^0.29.0",
58
+ "@jridgewell/sourcemap-codec": "^1.6.0",
59
+ "@microsoft/api-extractor": "^7.60.1",
60
+ "@microsoft/tsdoc": "~0.17.1",
61
+ "@microsoft/tsdoc-config": "~0.18.3",
62
+ "@tsdown/exe": "^0.23.4",
63
+ "jiti": "~2.7.0",
64
+ "rolldown": "^1.2.16",
65
+ "rolldown-plugin-dts": "^0.30.0",
66
+ "tsdown": "^0.23.4"
67
+ },
68
+ "peerDependencies": {
69
+ "@resvg/resvg-js": "^2.6.2",
70
+ "@types/node": "^26.6.0",
71
+ "effect": "~4.1.0",
72
+ "satori": "^0.63.2",
73
+ "typescript": "7.1.0-beta || 7.1.1-rc || >=7.1.0 <8"
74
+ },
75
+ "peerDependenciesMeta": {
76
+ "@resvg/resvg-js": {
77
+ "optional": true
78
+ },
79
+ "satori": {
80
+ "optional": true
81
+ }
82
+ },
83
+ "engines": {
84
+ "node": ">=24.11.0"
85
+ }
86
+ }
@@ -0,0 +1,346 @@
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
+ sourceDir: options.cwd,
142
+ dual: options.dualExports ?? js.format.includes("cjs"),
143
+ emitDts: options.emitDts !== false,
144
+ ...options.subdirExports !== void 0 ? { subdirExports: options.subdirExports } : {},
145
+ ...options.exeRewrite !== void 0 ? { exeRewrite: options.exeRewrite } : {}
146
+ }) : void 0;
147
+ await timed(group.id, "js", () => build({
148
+ config: false,
149
+ cwd: options.cwd,
150
+ entry: jsEntry,
151
+ outDir: partOutDir,
152
+ format: js.format,
153
+ platform: js.platform,
154
+ sourcemap: js.sourcemap,
155
+ minify: js.minify,
156
+ unbundle: js.unbundle,
157
+ clean: isBase ? js.clean : false,
158
+ fixedExtension: js.fixedExtension,
159
+ dts: js.dts,
160
+ define: js.define,
161
+ ...timingChecks,
162
+ ...instrument(group.id),
163
+ ...part.css !== void 0 ? { css: part.css } : {},
164
+ ...isBase && options.copy?.length ? { copy: copyEntriesFor(options.copy, partOutDir) } : {},
165
+ ...partExternals?.length || partBundle?.length ? { deps: {
166
+ ...partExternals?.length ? { neverBundle: partExternals } : {},
167
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {}
168
+ } } : {},
169
+ ...js.cjsDefault !== void 0 ? { cjsDefault: js.cjsDefault } : {},
170
+ plugins: [
171
+ ...manifestPlugin ? [manifestPlugin] : [],
172
+ ...js.format.includes("cjs") ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
173
+ ...options.extraPlugins ?? [],
174
+ ...metricsPlugins(group.id, "js", js.format.includes("cjs"))
175
+ ]
176
+ }));
177
+ const dtsNeverBundle = [...partExternals ?? [], ...partDtsExternals ?? []];
178
+ if (options.emitDts === false || Object.keys(dts.entry).length === 0) continue;
179
+ const dtsDeps = dtsNeverBundle.length > 0 || dts.bundledPackages || partBundle?.length ? { deps: {
180
+ ...dtsNeverBundle.length > 0 ? { neverBundle: dtsNeverBundle } : {},
181
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {},
182
+ ...dts.bundledPackages ? partBundleNodeModules ? { dts: { alwaysBundle: dts.bundledPackages } } : {
183
+ neverBundle: true,
184
+ dts: { alwaysBundle: dts.bundledPackages }
185
+ } : {}
186
+ } } : {};
187
+ const stubEntries = /* @__PURE__ */ new Map();
188
+ const readSource = (src) => {
189
+ try {
190
+ return readFileSync(isAbsolute(src) ? src : join(options.cwd, src), "utf-8");
191
+ } catch {
192
+ return;
193
+ }
194
+ };
195
+ const baseSrc = dts.entry[STUB_BASE_ENTRY];
196
+ if (baseSrc !== void 0 && Object.keys(dts.entry).length > 1) {
197
+ const baseSource = readSource(baseSrc);
198
+ const base = baseSource !== void 0 ? collectExportNames(baseSource) : void 0;
199
+ if (base?.complete === true) for (const [entryName, entrySource] of Object.entries(dts.entry)) {
200
+ if (entryName === STUB_BASE_ENTRY || entryName.includes("/")) continue;
201
+ const source = readSource(entrySource);
202
+ if (source === void 0) continue;
203
+ const analysis = analyzeReexportBarrel(source);
204
+ if (!analysis.isPureNamedReexportBarrel) continue;
205
+ const all = [...analysis.valueNames, ...analysis.typeNames];
206
+ if (all.length === 0 || !all.every((n) => base.names.has(n))) continue;
207
+ stubEntries.set(entryName, {
208
+ valueNames: analysis.valueNames,
209
+ typeNames: analysis.typeNames
210
+ });
211
+ }
212
+ }
213
+ await timed(group.id, "dts", async () => {
214
+ for (const [entryName, entrySource] of Object.entries(dts.entry)) {
215
+ const stub = stubEntries.get(entryName);
216
+ if (stub !== void 0) {
217
+ const variants = [{
218
+ file: `${entryName}.d.ts`,
219
+ spec: `./${STUB_BASE_ENTRY}.js`
220
+ }];
221
+ if (dts.format.includes("cjs")) variants.push({
222
+ file: `${entryName}.d.cts`,
223
+ spec: `./${STUB_BASE_ENTRY}.cjs`
224
+ });
225
+ for (const variant of variants) {
226
+ const content = renderReexportStub({
227
+ valueNames: stub.valueNames,
228
+ typeNames: stub.typeNames,
229
+ baseSpecifier: variant.spec
230
+ });
231
+ writeFileSync(join(partOutDir, variant.file), content, "utf-8");
232
+ collector?.recordEmitted(group.id, "dts", {
233
+ path: variant.file,
234
+ bytes: Buffer.byteLength(content)
235
+ });
236
+ }
237
+ continue;
238
+ }
239
+ await build({
240
+ config: false,
241
+ cwd: options.cwd,
242
+ entry: { [entryName]: entrySource },
243
+ outDir: partOutDir,
244
+ format: dts.format,
245
+ platform: dts.platform,
246
+ sourcemap: dts.sourcemap,
247
+ unbundle: dts.unbundle,
248
+ clean: false,
249
+ fixedExtension: dts.fixedExtension,
250
+ dts: dts.dts,
251
+ define: dts.define,
252
+ ...timingChecks,
253
+ ...instrument(group.id),
254
+ ...dtsDeps,
255
+ plugins: [
256
+ ...dts.format.includes("cjs") ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
257
+ ...options.extraPlugins ?? [],
258
+ ...metricsPlugins(group.id, "dts", dts.format.includes("cjs"))
259
+ ]
260
+ });
261
+ }
262
+ });
263
+ if (js.isProd && options.emitDeclarations === true && Object.keys(decl.entry).length > 0) {
264
+ const partDeclDir = part.outSubdir !== void 0 ? join(decl.outDir, part.outSubdir) : decl.outDir;
265
+ try {
266
+ await build({
267
+ config: false,
268
+ cwd: options.cwd,
269
+ entry: decl.entry,
270
+ outDir: partDeclDir,
271
+ format: decl.format,
272
+ platform: decl.platform,
273
+ sourcemap: decl.sourcemap,
274
+ unbundle: decl.unbundle,
275
+ clean: isBase,
276
+ fixedExtension: decl.fixedExtension,
277
+ dts: decl.dts,
278
+ define: decl.define,
279
+ ...timingChecks,
280
+ logLevel: "silent",
281
+ ...dtsNeverBundle.length > 0 || decl.bundledPackages || partBundle?.length ? { deps: {
282
+ ...dtsNeverBundle.length > 0 ? { neverBundle: dtsNeverBundle } : {},
283
+ ...partBundle?.length ? { alwaysBundle: partBundle } : {},
284
+ ...decl.bundledPackages ? partBundleNodeModules ? { dts: { alwaysBundle: decl.bundledPackages } } : {
285
+ neverBundle: true,
286
+ dts: { alwaysBundle: decl.bundledPackages }
287
+ } : {}
288
+ } } : {},
289
+ ...options.extraPlugins !== void 0 ? { plugins: [...options.extraPlugins] } : {}
290
+ });
291
+ } catch (err) {
292
+ collector?.recordWarning(group.id, {
293
+ source: "tsdown",
294
+ level: "warn",
295
+ text: `Could not emit per-module declarations for API Extractor diagnostics: ${String(err)}`
296
+ });
297
+ }
298
+ }
299
+ }
300
+ const looseOutDir = outDirFor(options.cwd, group.id);
301
+ const isProdGroup = group.id !== "dev";
302
+ const looseDeps = {
303
+ ...options.externals?.length ? { neverBundle: options.externals } : {},
304
+ ...options.bundle?.length ? { alwaysBundle: options.bundle } : {}
305
+ };
306
+ for (const lf of options.looseFiles ?? []) {
307
+ const hasCjs = lf.format === "cjs";
308
+ await timed(group.id, "loose", () => build({
309
+ config: false,
310
+ cwd: options.cwd,
311
+ entry: { [lf.entryName]: lf.source },
312
+ outDir: looseOutDir,
313
+ format: [lf.format],
314
+ platform: "node",
315
+ sourcemap: !isProdGroup,
316
+ minify: isProdGroup && (options.minify ?? false),
317
+ unbundle: false,
318
+ clean: false,
319
+ fixedExtension: lf.fixedExtension,
320
+ dts: false,
321
+ define: {
322
+ "process.env.__PACKAGE_VERSION__": JSON.stringify(options.version),
323
+ ...options.define
324
+ },
325
+ ...timingChecks,
326
+ ...instrument(group.id),
327
+ ...Object.keys(looseDeps).length > 0 ? { deps: looseDeps } : {},
328
+ ...hasCjs ? { cjsDefault: true } : {},
329
+ plugins: [
330
+ ...hasCjs ? [nodeBuiltinDefaultInterop(), cjsDefaultInterop()] : [],
331
+ ...options.extraPlugins ?? [],
332
+ ...metricsPlugins(group.id, "loose", hasCjs)
333
+ ]
334
+ }));
335
+ }
336
+ const groupOutDir = outDirFor(options.cwd, group.id);
337
+ copyPublicDir(publicDir, groupOutDir);
338
+ if (ambient.length > 0) copyAmbientDts({
339
+ ambient,
340
+ srcCwd: options.cwd,
341
+ outDir: groupOutDir
342
+ });
343
+ }
344
+ }
345
+
346
+ export { buildTargetGroups };