@packall/core 0.0.1 → 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 (157) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +58 -0
  3. package/dist/archive-6sqTn1C4.js +274 -0
  4. package/dist/archive-6sqTn1C4.js.map +1 -0
  5. package/dist/archive.d.ts +64 -0
  6. package/dist/archive.d.ts.map +1 -0
  7. package/dist/{Bundle.d.ts → bundle.d.ts} +56 -38
  8. package/dist/bundle.d.ts.map +1 -0
  9. package/dist/{DependencyRange.d.ts → dependency-range.d.ts} +2 -2
  10. package/dist/dependency-range.d.ts.map +1 -0
  11. package/dist/{Download.d.ts → download.d.ts} +9 -8
  12. package/dist/download.d.ts.map +1 -0
  13. package/dist/enums/artifact-kind.d.ts +8 -0
  14. package/dist/enums/artifact-kind.d.ts.map +1 -0
  15. package/dist/enums/edge-kind.d.ts +29 -0
  16. package/dist/enums/edge-kind.d.ts.map +1 -0
  17. package/dist/enums/input-file-kind.d.ts +12 -0
  18. package/dist/enums/input-file-kind.d.ts.map +1 -0
  19. package/dist/enums/layout.d.ts +23 -0
  20. package/dist/enums/layout.d.ts.map +1 -0
  21. package/dist/enums/lockfile-format.d.ts +9 -0
  22. package/dist/enums/lockfile-format.d.ts.map +1 -0
  23. package/dist/enums/phase.d.ts +11 -0
  24. package/dist/enums/phase.d.ts.map +1 -0
  25. package/dist/{Errors.d.ts → errors.d.ts} +49 -7
  26. package/dist/errors.d.ts.map +1 -0
  27. package/dist/index.d.ts +46 -28
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +2121 -1060
  30. package/dist/index.js.map +1 -1
  31. package/dist/input-file.d.ts +77 -0
  32. package/dist/input-file.d.ts.map +1 -0
  33. package/dist/integrity.d.ts +80 -0
  34. package/dist/integrity.d.ts.map +1 -0
  35. package/dist/layout.d.ts +87 -0
  36. package/dist/layout.d.ts.map +1 -0
  37. package/dist/locked-resolve.d.ts +47 -0
  38. package/dist/locked-resolve.d.ts.map +1 -0
  39. package/dist/lockfile/bun.d.ts +3 -0
  40. package/dist/lockfile/bun.d.ts.map +1 -0
  41. package/dist/lockfile/detect.d.ts +31 -0
  42. package/dist/lockfile/detect.d.ts.map +1 -0
  43. package/dist/lockfile/json.d.ts +23 -0
  44. package/dist/lockfile/json.d.ts.map +1 -0
  45. package/dist/lockfile/names.d.ts +16 -0
  46. package/dist/lockfile/names.d.ts.map +1 -0
  47. package/dist/lockfile/npm.d.ts +3 -0
  48. package/dist/lockfile/npm.d.ts.map +1 -0
  49. package/dist/lockfile/parse.d.ts +23 -0
  50. package/dist/lockfile/parse.d.ts.map +1 -0
  51. package/dist/lockfile/pnpm.d.ts +20 -0
  52. package/dist/lockfile/pnpm.d.ts.map +1 -0
  53. package/dist/lockfile/tree-builder.d.ts +70 -0
  54. package/dist/lockfile/tree-builder.d.ts.map +1 -0
  55. package/dist/lockfile/types.d.ts +70 -0
  56. package/dist/lockfile/types.d.ts.map +1 -0
  57. package/dist/{Manifest.d.ts → manifest.d.ts} +7 -15
  58. package/dist/manifest.d.ts.map +1 -0
  59. package/dist/node/archiver.d.ts +5 -0
  60. package/dist/node/archiver.d.ts.map +1 -0
  61. package/dist/node/index.d.ts +13 -0
  62. package/dist/node/index.d.ts.map +1 -0
  63. package/dist/node/index.js +55 -0
  64. package/dist/node/index.js.map +1 -0
  65. package/dist/{Options.d.ts → options.d.ts} +12 -30
  66. package/dist/options.d.ts.map +1 -0
  67. package/dist/{Platform.d.ts → platform.d.ts} +14 -19
  68. package/dist/platform.d.ts.map +1 -0
  69. package/dist/{Progress.d.ts → progress.d.ts} +10 -9
  70. package/dist/progress.d.ts.map +1 -0
  71. package/dist/{Registry.d.ts → registry.d.ts} +42 -44
  72. package/dist/registry.d.ts.map +1 -0
  73. package/dist/{Resolve.d.ts → resolve.d.ts} +25 -26
  74. package/dist/resolve.d.ts.map +1 -0
  75. package/dist/schemas/lenient.d.ts +38 -0
  76. package/dist/schemas/lenient.d.ts.map +1 -0
  77. package/dist/schemas/package-json.d.ts +44 -0
  78. package/dist/schemas/package-json.d.ts.map +1 -0
  79. package/dist/{Spec.d.ts → spec.d.ts} +4 -4
  80. package/dist/spec.d.ts.map +1 -0
  81. package/dist/types/value-of.d.ts +9 -0
  82. package/dist/types/value-of.d.ts.map +1 -0
  83. package/dist/utils/is-record.d.ts +8 -0
  84. package/dist/utils/is-record.d.ts.map +1 -0
  85. package/package.json +13 -11
  86. package/src/archive.ts +95 -0
  87. package/src/bundle.ts +736 -0
  88. package/src/dependency-range.ts +121 -0
  89. package/src/download.ts +155 -0
  90. package/src/enums/artifact-kind.ts +9 -0
  91. package/src/enums/edge-kind.ts +32 -0
  92. package/src/enums/input-file-kind.ts +13 -0
  93. package/src/enums/layout.ts +25 -0
  94. package/src/enums/lockfile-format.ts +10 -0
  95. package/src/enums/phase.ts +12 -0
  96. package/src/errors.ts +300 -0
  97. package/src/index.ts +146 -35
  98. package/src/input-file.ts +324 -0
  99. package/src/integrity.ts +165 -0
  100. package/src/layout.ts +137 -0
  101. package/src/locked-resolve.ts +471 -0
  102. package/src/lockfile/bun.ts +214 -0
  103. package/src/lockfile/detect.ts +80 -0
  104. package/src/lockfile/json.ts +131 -0
  105. package/src/lockfile/names.ts +20 -0
  106. package/src/lockfile/npm.ts +328 -0
  107. package/src/lockfile/parse.ts +56 -0
  108. package/src/lockfile/pnpm.ts +230 -0
  109. package/src/lockfile/tree-builder.ts +166 -0
  110. package/src/lockfile/types.ts +74 -0
  111. package/src/manifest.ts +129 -0
  112. package/src/node/archiver.ts +85 -0
  113. package/src/node/index.ts +13 -0
  114. package/src/options.ts +103 -0
  115. package/src/platform.ts +178 -0
  116. package/src/progress.ts +105 -0
  117. package/src/registry.ts +116 -0
  118. package/src/resolve.ts +560 -0
  119. package/src/schemas/lenient.ts +130 -0
  120. package/src/schemas/package-json.ts +28 -0
  121. package/src/spec.ts +182 -0
  122. package/src/types/value-of.ts +8 -0
  123. package/src/utils/is-record.ts +8 -0
  124. package/dist/Archive.d.ts +0 -32
  125. package/dist/Archive.d.ts.map +0 -1
  126. package/dist/Bundle.d.ts.map +0 -1
  127. package/dist/DependencyRange.d.ts.map +0 -1
  128. package/dist/Download.d.ts.map +0 -1
  129. package/dist/Errors.d.ts.map +0 -1
  130. package/dist/InputFile.d.ts +0 -46
  131. package/dist/InputFile.d.ts.map +0 -1
  132. package/dist/Integrity.d.ts +0 -48
  133. package/dist/Integrity.d.ts.map +0 -1
  134. package/dist/Layout.d.ts +0 -53
  135. package/dist/Layout.d.ts.map +0 -1
  136. package/dist/Manifest.d.ts.map +0 -1
  137. package/dist/Options.d.ts.map +0 -1
  138. package/dist/Platform.d.ts.map +0 -1
  139. package/dist/Progress.d.ts.map +0 -1
  140. package/dist/Registry.d.ts.map +0 -1
  141. package/dist/Resolve.d.ts.map +0 -1
  142. package/dist/Spec.d.ts.map +0 -1
  143. package/src/Archive.ts +0 -92
  144. package/src/Bundle.ts +0 -570
  145. package/src/DependencyRange.ts +0 -115
  146. package/src/Download.ts +0 -132
  147. package/src/Errors.ts +0 -216
  148. package/src/InputFile.ts +0 -229
  149. package/src/Integrity.ts +0 -122
  150. package/src/Layout.ts +0 -103
  151. package/src/Manifest.ts +0 -133
  152. package/src/Options.ts +0 -123
  153. package/src/Platform.ts +0 -182
  154. package/src/Progress.ts +0 -106
  155. package/src/Registry.ts +0 -121
  156. package/src/Resolve.ts +0 -528
  157. package/src/Spec.ts +0 -186
package/src/bundle.ts ADDED
@@ -0,0 +1,736 @@
1
+ /**
2
+ * End-to-end orchestration: specs in, tarballs out.
3
+ *
4
+ * Two properties this module is responsible for — see `notes/requirements.md`
5
+ * § FR-5 and § NFR-9 for why they are requirements, and the mechanisms below
6
+ * for why the code reads as it does:
7
+ *
8
+ * 1. **Nothing is written outside the output directory.** Every intermediate
9
+ * file lives in a scoped temp directory obtained from
10
+ * `makeTempDirectoryScoped`, so the scope closing — on success, on failure,
11
+ * or on Ctrl-C — takes the whole staging tree with it. The working
12
+ * directory is never touched.
13
+ *
14
+ * 2. **Each package is downloaded exactly once**, no matter how many bundles
15
+ * it ends up in. Per-spec archives are assembled by hard-linking out of one
16
+ * shared download tree, so `per-spec` costs extra disk in the *output*, not
17
+ * extra network.
18
+ */
19
+ import type * as Crypto from "effect/Crypto";
20
+ import * as Effect from "effect/Effect";
21
+ import * as FileSystem from "effect/FileSystem";
22
+ import * as Path from "effect/Path";
23
+ import type { PlatformError } from "effect/PlatformError";
24
+ import type { Scope } from "effect/Scope";
25
+
26
+ import type { Archiver } from "./archive.js";
27
+ import { createArchive } from "./archive.js";
28
+ import { downloadAll } from "./download.js";
29
+ import { ArtifactKind } from "./enums/artifact-kind.js";
30
+ import { Layout } from "./enums/layout.js";
31
+ import { Phase } from "./enums/phase.js";
32
+ import type { BundlerError } from "./errors.js";
33
+ import { OutputError } from "./errors.js";
34
+ import {
35
+ importGuide,
36
+ MANIFEST_FILE,
37
+ packagePath,
38
+ perSpecArchiveName,
39
+ README_FILE,
40
+ singleArchiveName,
41
+ } from "./layout.js";
42
+ import type { LockedResolveOptions } from "./locked-resolve.js";
43
+ import { resolveLocked } from "./locked-resolve.js";
44
+ import type { LockedTree } from "./lockfile/types.js";
45
+ import { buildManifest, serializeManifest } from "./manifest.js";
46
+ import type { BundleOptions } from "./options.js";
47
+ import * as Progress from "./progress.js";
48
+ import { Registry } from "./registry.js";
49
+ import type { PackageKey, Resolution, ResolvedPackage, RootResolution } from "./resolve.js";
50
+ import { indexPackages, resolve } from "./resolve.js";
51
+ import type { PackageSpec } from "./spec.js";
52
+ import { formatSpec } from "./spec.js";
53
+
54
+ /** One thing written to the output directory. */
55
+ export type BundleArtifact = {
56
+ readonly kind: ArtifactKind;
57
+ readonly path: string;
58
+ readonly bytes: number;
59
+ readonly packageCount: number;
60
+ /** Which spec this artifact covers. Absent for `single` and `dir`. */
61
+ readonly spec?: string | undefined;
62
+ readonly version?: string | undefined;
63
+ };
64
+
65
+ /** The outcome of a bundle run. */
66
+ export type BundleResult = {
67
+ readonly resolution: Resolution;
68
+ readonly artifacts: ReadonlyArray<BundleArtifact>;
69
+ /** Total bytes downloaded from the registry. */
70
+ readonly downloadedBytes: number;
71
+ /** Packages the registry advertised no usable checksum for. */
72
+ readonly unverified: ReadonlyArray<string>;
73
+ readonly dryRun: boolean;
74
+ };
75
+
76
+ /** Everything `bundle` needs beyond the user-facing options. */
77
+ export type BundleContext = BundleOptions & {
78
+ /** Recorded in the manifest so a bundle can be traced to the tool that built it. */
79
+ readonly toolVersion: string;
80
+ };
81
+
82
+ /**
83
+ * A summary of what a resolution would produce, for deciding whether the
84
+ * chosen layout is still the right one.
85
+ */
86
+ export type PlanSummary = {
87
+ /** Distinct packages in the deduplicated union. */
88
+ readonly uniquePackages: number;
89
+ /** How many archives `per-spec` layout would emit. */
90
+ readonly perSpecArchives: number;
91
+ /**
92
+ * Total package entries across all per-spec archives, counting shared
93
+ * dependencies once per archive they appear in. The gap between this and
94
+ * `uniquePackages` is exactly what `single` layout would save.
95
+ */
96
+ readonly perSpecEntries: number;
97
+ };
98
+
99
+ /**
100
+ * The files a run will write, known before anything is downloaded.
101
+ *
102
+ * `dir` layout is the odd one: it merges a package tree into `outDir`, and
103
+ * package paths are `name/-/name-version.tgz` — the same package at the same
104
+ * version is the same bytes, so an overlap there is idempotent rather than
105
+ * destructive. Only the two summary files are genuinely replaced, and those are
106
+ * the ones worth guarding.
107
+ */
108
+ export type PlannedOutput = {
109
+ readonly file: string;
110
+ /** The root this file belongs to, when one file corresponds to one spec. */
111
+ readonly name?: string | undefined;
112
+ readonly version?: string | undefined;
113
+ };
114
+
115
+ type BundleEnv =
116
+ | Registry
117
+ | Progress.Progress
118
+ | FileSystem.FileSystem
119
+ | Path.Path
120
+ | Crypto.Crypto
121
+ | Archiver;
122
+
123
+ type EmitInput = {
124
+ readonly resolution: Resolution;
125
+ readonly options: BundleContext;
126
+ readonly packagesDir: string;
127
+ readonly report: { readonly sizes: ReadonlyMap<string, number> };
128
+ readonly registryInfo: { readonly kind: string; readonly url: string };
129
+ };
130
+
131
+ /** One archive `per-spec` layout will write: a root, at one of its versions. */
132
+ type PerSpecTarget = {
133
+ readonly root: RootResolution;
134
+ readonly version: string;
135
+ };
136
+
137
+ /**
138
+ * The archives `per-spec` emits — one per distinct root package version.
139
+ *
140
+ * Roots are *specs*, and several specs can name one package: `react`,
141
+ * `react@latest` and `react@19.2.8` are three ways of asking for the same
142
+ * thing, and after resolution they are indistinguishable. Without this they
143
+ * were three archives — the same bytes, under the same file name, written over
144
+ * each other. The run then reported three artifacts and three times the size
145
+ * for one file on disk, and the duplication ratio it computes to decide whether
146
+ * to ask about the layout counted them too, so the tool would offer to
147
+ * deduplicate a bundle it had duplicated itself.
148
+ *
149
+ * Keyed by name and version rather than by the archive's file name. A scoped
150
+ * name is flattened to make a file name, so `@foo/bar` and `foo-bar` can spell
151
+ * the same one — and those are two different packages, which should collide
152
+ * loudly rather than being merged here.
153
+ *
154
+ * Roots only. The packages *inside* an archive were deduplicated by resolution
155
+ * long before this, which is why the same closure fetched from twenty specs is
156
+ * fetched once.
157
+ */
158
+ const perSpecTargets = (resolution: Resolution): ReadonlyArray<PerSpecTarget> => {
159
+ const seen = new Set<string>();
160
+
161
+ return resolution.roots.flatMap((root) =>
162
+ root.versions.flatMap((version) => {
163
+ const key = `${root.spec.name}@${version}`;
164
+ if (seen.has(key)) return [];
165
+
166
+ seen.add(key);
167
+ return { root, version };
168
+ }),
169
+ );
170
+ };
171
+
172
+ /** Computes the plan summary for a resolution. */
173
+ export const summarize = (resolution: Resolution): PlanSummary => {
174
+ let perSpecArchives = 0;
175
+ let perSpecEntries = 0;
176
+ for (const { root, version } of perSpecTargets(resolution)) {
177
+ perSpecArchives += 1;
178
+ perSpecEntries += (root.closures.get(version) ?? []).length;
179
+ }
180
+ return {
181
+ uniquePackages: resolution.packages.length,
182
+ perSpecArchives,
183
+ perSpecEntries,
184
+ };
185
+ };
186
+
187
+ /** Replaces the layout on a set of options. */
188
+ export const withLayout = <T extends BundleOptions>(options: T, layout: Layout): T => ({
189
+ ...options,
190
+ layout,
191
+ });
192
+
193
+ /**
194
+ * Checks the registry is reachable, then resolves every spec.
195
+ *
196
+ * Split out from `bundle` so a caller can inspect the plan — how many packages,
197
+ * how many archives — and act on it before any bytes move. The CLI uses this to
198
+ * offer a different layout when a run turns out to be much larger than
199
+ * expected.
200
+ */
201
+ export const plan = (
202
+ specs: ReadonlyArray<PackageSpec>,
203
+ options: BundleOptions,
204
+ ): Effect.Effect<Resolution, BundlerError, Registry | Progress.Progress> =>
205
+ Effect.gen(function* () {
206
+ yield* preflight;
207
+ return yield* resolve(specs, options);
208
+ });
209
+
210
+ /**
211
+ * The lockfile counterpart of `plan`.
212
+ *
213
+ * Same preflight, same `Resolution` out; the difference is entirely in how the
214
+ * package set is arrived at. Kept as a separate entry point rather than an
215
+ * option on `plan` because the two take genuinely different inputs — a set of
216
+ * specs to satisfy versus a graph to reproduce — and blurring that is how a
217
+ * "pinned" run quietly starts resolving ranges again.
218
+ */
219
+ export const planLocked = (
220
+ lockfile: LockedTree,
221
+ options: BundleOptions & LockedResolveOptions,
222
+ ): Effect.Effect<Resolution, BundlerError, Registry | Progress.Progress> =>
223
+ Effect.gen(function* () {
224
+ yield* preflight;
225
+ return yield* resolveLocked(lockfile, options);
226
+ });
227
+
228
+ const preflight: Effect.Effect<void, BundlerError, Registry | Progress.Progress> = Effect.gen(
229
+ function* () {
230
+ const registry = yield* Registry;
231
+ yield* Progress.emit({ _tag: "PhaseStarted", phase: Phase.Preflight });
232
+ yield* registry.preflight;
233
+ yield* Progress.emit({ _tag: "PhaseCompleted", phase: Phase.Preflight });
234
+ },
235
+ );
236
+
237
+ /**
238
+ * Resolves, downloads and packages a set of specs.
239
+ *
240
+ * Under `dryRun` this stops after resolution and reports the plan — useful for
241
+ * checking what a command *would* pull before committing to a multi-gigabyte
242
+ * download over a slow VPN.
243
+ */
244
+ export const bundle = (
245
+ specs: ReadonlyArray<PackageSpec>,
246
+ options: BundleContext,
247
+ ): Effect.Effect<BundleResult, BundlerError | PlatformError, BundleEnv> =>
248
+ Effect.gen(function* () {
249
+ const resolution = yield* plan(specs, options);
250
+ return yield* bundleResolved(resolution, options);
251
+ });
252
+
253
+ /** `bundle`, pinned to a lockfile. */
254
+ export const bundleLocked = (
255
+ lockfile: LockedTree,
256
+ options: BundleContext & LockedResolveOptions,
257
+ ): Effect.Effect<BundleResult, BundlerError | PlatformError, BundleEnv> =>
258
+ Effect.gen(function* () {
259
+ const resolution = yield* planLocked(lockfile, options);
260
+ return yield* bundleResolved(resolution, options);
261
+ });
262
+
263
+ /**
264
+ * Downloads and packages an already-computed resolution.
265
+ *
266
+ * Everything from here on touches the disk, and all of it happens inside
267
+ * `Effect.scoped` — so the staging tree's lifetime is exactly this call,
268
+ * including when it fails partway through or the user hits Ctrl-C.
269
+ */
270
+ export const bundleResolved = (
271
+ resolution: Resolution,
272
+ options: BundleContext,
273
+ ): Effect.Effect<BundleResult, BundlerError | PlatformError, BundleEnv> =>
274
+ Effect.gen(function* () {
275
+ if (options.dryRun) {
276
+ return {
277
+ resolution,
278
+ artifacts: [],
279
+ downloadedBytes: 0,
280
+ unverified: [],
281
+ dryRun: true,
282
+ };
283
+ }
284
+ return yield* Effect.scoped(runBundle(resolution, options));
285
+ });
286
+
287
+ /**
288
+ * The files a run will write.
289
+ *
290
+ * Computed before anything is downloaded, so a collision is reported in the
291
+ * first second rather than after a twenty-minute transfer.
292
+ */
293
+ export const plannedOutputs = (
294
+ resolution: Resolution,
295
+ options: BundleContext,
296
+ ): ReadonlyArray<PlannedOutput> => {
297
+ if (options.layout === Layout.Dir) return [{ file: MANIFEST_FILE }, { file: README_FILE }];
298
+ if (options.layout === Layout.Single) {
299
+ return [{ file: singleArchiveName(options.archiveName ?? "bundle") }];
300
+ }
301
+ return perSpecTargets(resolution).map(({ root, version }) => ({
302
+ file: perSpecArchiveName(root.spec.name, version),
303
+ name: root.spec.name,
304
+ version,
305
+ }));
306
+ };
307
+
308
+ const runBundle = (
309
+ resolution: Resolution,
310
+ options: BundleContext,
311
+ ): Effect.Effect<BundleResult, BundlerError | PlatformError, BundleEnv | Scope> =>
312
+ Effect.gen(function* () {
313
+ const fs = yield* FileSystem.FileSystem;
314
+ const path = yield* Path.Path;
315
+ const registry = yield* Registry;
316
+
317
+ yield* prepareOutputDir(resolution, options);
318
+
319
+ const staging = yield* fs.makeTempDirectoryScoped({ prefix: "packall-" });
320
+ const packagesDir = path.join(staging, "packages");
321
+ yield* fs.makeDirectory(packagesDir, { recursive: true });
322
+
323
+ const report = yield* downloadAll(resolution.packages, packagesDir, {
324
+ concurrency: options.concurrency,
325
+ verifyIntegrity: options.verifyIntegrity,
326
+ });
327
+
328
+ yield* Progress.emit({ _tag: "PhaseStarted", phase: Phase.Archive });
329
+
330
+ const input: EmitInput = {
331
+ resolution,
332
+ options,
333
+ packagesDir,
334
+ report,
335
+ registryInfo: {
336
+ kind: registry.kind,
337
+ url: registry.registryFor(resolution.roots[0]?.spec.name ?? ""),
338
+ },
339
+ };
340
+
341
+ const artifacts = yield* emit(input, staging);
342
+
343
+ yield* Progress.emit({ _tag: "PhaseCompleted", phase: Phase.Archive });
344
+ yield* Progress.emit({ _tag: "PhaseStarted", phase: Phase.Done });
345
+
346
+ return {
347
+ resolution,
348
+ artifacts,
349
+ downloadedBytes: report.totalBytes,
350
+ unverified: report.unverified,
351
+ dryRun: false,
352
+ };
353
+ });
354
+
355
+ /* -------------------------------------------------------------------------- */
356
+ /* Emitters */
357
+ /* -------------------------------------------------------------------------- */
358
+
359
+ const emit = (
360
+ input: EmitInput,
361
+ staging: string,
362
+ ): Effect.Effect<
363
+ ReadonlyArray<BundleArtifact>,
364
+ BundlerError | PlatformError,
365
+ FileSystem.FileSystem | Path.Path | Progress.Progress | Archiver
366
+ > => {
367
+ switch (input.options.layout) {
368
+ case Layout.Single:
369
+ return emitSingle(input);
370
+ case Layout.Dir:
371
+ return emitDirectory(input);
372
+ case Layout.PerSpec:
373
+ return emitPerSpec(input, staging);
374
+ }
375
+ };
376
+
377
+ /** One tarball containing the deduplicated union of every closure. */
378
+ const emitSingle = (
379
+ input: EmitInput,
380
+ ): Effect.Effect<
381
+ ReadonlyArray<BundleArtifact>,
382
+ BundlerError | PlatformError,
383
+ FileSystem.FileSystem | Path.Path | Progress.Progress | Archiver
384
+ > =>
385
+ Effect.gen(function* () {
386
+ const path = yield* Path.Path;
387
+
388
+ const archiveName = singleArchiveName(input.options.archiveName ?? "bundle");
389
+ // Declined at the prompt, and it is the run's only output.
390
+ if (input.options.skipExisting?.has(archiveName) === true) return [];
391
+
392
+ yield* writeBundleMetadata({
393
+ dir: input.packagesDir,
394
+ resolution: input.resolution,
395
+ included: input.resolution.packages,
396
+ options: input.options,
397
+ registryInfo: input.registryInfo,
398
+ sizes: input.report.sizes,
399
+ });
400
+
401
+ const outPath = path.join(input.options.outDir, archiveName);
402
+
403
+ const result = yield* createArchive({
404
+ cwd: input.packagesDir,
405
+ entries: yield* topLevelEntries(input.packagesDir),
406
+ outPath,
407
+ });
408
+
409
+ return [
410
+ {
411
+ kind: ArtifactKind.Archive,
412
+ path: result.path,
413
+ bytes: result.bytes,
414
+ packageCount: input.resolution.packages.length,
415
+ },
416
+ ];
417
+ });
418
+
419
+ /** The raw npm-layout tree, no archive. */
420
+ const emitDirectory = (
421
+ input: EmitInput,
422
+ ): Effect.Effect<
423
+ ReadonlyArray<BundleArtifact>,
424
+ BundlerError | PlatformError,
425
+ FileSystem.FileSystem | Path.Path
426
+ > =>
427
+ Effect.gen(function* () {
428
+ const fs = yield* FileSystem.FileSystem;
429
+
430
+ yield* writeBundleMetadata({
431
+ dir: input.packagesDir,
432
+ resolution: input.resolution,
433
+ included: input.resolution.packages,
434
+ options: input.options,
435
+ registryInfo: input.registryInfo,
436
+ sizes: input.report.sizes,
437
+ });
438
+
439
+ // The staging tree is about to be deleted with its scope, so this is a
440
+ // real copy rather than a move — `copy` also works across devices, which
441
+ // matters because the temp dir often lives on a different filesystem.
442
+ yield* fs.copy(input.packagesDir, input.options.outDir, { overwrite: true }).pipe(
443
+ Effect.mapError(
444
+ (cause) =>
445
+ new OutputError(input.options.outDir, "could not write output tree", {
446
+ cause,
447
+ }),
448
+ ),
449
+ );
450
+
451
+ const bytes = [...input.report.sizes.values()].reduce((a, b) => a + b, 0);
452
+
453
+ return [
454
+ {
455
+ kind: ArtifactKind.Directory,
456
+ path: input.options.outDir,
457
+ bytes,
458
+ packageCount: input.resolution.packages.length,
459
+ },
460
+ ];
461
+ });
462
+
463
+ /**
464
+ * One tarball per resolved root *version*.
465
+ *
466
+ * Under `--all-versions react@^18` this produces `react-18.0.0.tgz`,
467
+ * `react-18.1.0.tgz` and so on, each independently importable — which is the
468
+ * whole reason to prefer this layout.
469
+ */
470
+ const emitPerSpec = (
471
+ input: EmitInput,
472
+ staging: string,
473
+ ): Effect.Effect<
474
+ ReadonlyArray<BundleArtifact>,
475
+ BundlerError | PlatformError,
476
+ FileSystem.FileSystem | Path.Path | Progress.Progress | Archiver
477
+ > =>
478
+ Effect.gen(function* () {
479
+ const fs = yield* FileSystem.FileSystem;
480
+ const path = yield* Path.Path;
481
+ const index = indexPackages(input.resolution);
482
+ const artifacts: Array<BundleArtifact> = [];
483
+
484
+ let counter = 0;
485
+ for (const { root, version } of perSpecTargets(input.resolution)) {
486
+ // Declined at the prompt: the existing file stays, and this archive is
487
+ // simply never built. Skipping the staging work too, not just the write.
488
+ if (
489
+ input.options.skipExisting?.has(perSpecArchiveName(root.spec.name, version)) ===
490
+ true
491
+ ) {
492
+ continue;
493
+ }
494
+
495
+ const included = includedPackages(index, root.closures.get(version) ?? []);
496
+
497
+ const rootDir = path.join(staging, "roots", String(counter++));
498
+ yield* fs.makeDirectory(rootDir, { recursive: true });
499
+
500
+ for (const pkg of included) {
501
+ const parts = packagePath(pkg.name, pkg.version).split("/");
502
+ const source = path.join(input.packagesDir, ...parts);
503
+ const target = path.join(rootDir, ...parts);
504
+ yield* fs.makeDirectory(path.dirname(target), { recursive: true });
505
+ yield* linkOrCopy(source, target);
506
+ }
507
+
508
+ yield* writeBundleMetadata({
509
+ dir: rootDir,
510
+ resolution: {
511
+ ...input.resolution,
512
+ roots: [{ ...root, versions: [version] }],
513
+ },
514
+ included,
515
+ options: input.options,
516
+ registryInfo: input.registryInfo,
517
+ sizes: input.report.sizes,
518
+ });
519
+
520
+ const outPath = path.join(
521
+ input.options.outDir,
522
+ perSpecArchiveName(root.spec.name, version),
523
+ );
524
+
525
+ const result = yield* createArchive({
526
+ cwd: rootDir,
527
+ entries: yield* topLevelEntries(rootDir),
528
+ outPath,
529
+ });
530
+
531
+ artifacts.push({
532
+ kind: ArtifactKind.Archive,
533
+ path: result.path,
534
+ bytes: result.bytes,
535
+ packageCount: included.length,
536
+ spec: formatSpec(root.spec),
537
+ version,
538
+ });
539
+ }
540
+
541
+ return artifacts;
542
+ });
543
+
544
+ /* -------------------------------------------------------------------------- */
545
+ /* Helpers */
546
+ /* -------------------------------------------------------------------------- */
547
+
548
+ const includedPackages = (
549
+ index: ReadonlyMap<PackageKey, ResolvedPackage>,
550
+ closure: ReadonlyArray<PackageKey>,
551
+ ): ReadonlyArray<ResolvedPackage> => closure.flatMap((key) => index.get(key) ?? []);
552
+
553
+ /**
554
+ * Hard-links a file, falling back to a copy.
555
+ *
556
+ * Hard links make `per-spec` layout nearly free in the staging tree. They fail
557
+ * across devices and on some Windows configurations, so the copy fallback is
558
+ * not optional.
559
+ */
560
+ const linkOrCopy = (
561
+ source: string,
562
+ target: string,
563
+ ): Effect.Effect<void, PlatformError, FileSystem.FileSystem> =>
564
+ Effect.gen(function* () {
565
+ const fs = yield* FileSystem.FileSystem;
566
+ yield* fs.link(source, target).pipe(Effect.catch(() => fs.copyFile(source, target)));
567
+ });
568
+
569
+ /** Writes the manifest and import guide into a staging directory. */
570
+ const writeBundleMetadata = (input: {
571
+ readonly dir: string;
572
+ readonly resolution: Resolution;
573
+ readonly included: ReadonlyArray<ResolvedPackage>;
574
+ readonly options: BundleContext;
575
+ readonly registryInfo: { readonly kind: string; readonly url: string };
576
+ readonly sizes: ReadonlyMap<string, number>;
577
+ }): Effect.Effect<void, PlatformError, FileSystem.FileSystem | Path.Path> =>
578
+ Effect.gen(function* () {
579
+ const fs = yield* FileSystem.FileSystem;
580
+ const path = yield* Path.Path;
581
+
582
+ const createdAt = new Date();
583
+ const manifest = buildManifest({
584
+ resolution: input.resolution,
585
+ included: input.included,
586
+ options: input.options,
587
+ registry: input.registryInfo,
588
+ toolVersion: input.options.toolVersion,
589
+ sizes: input.sizes,
590
+ createdAt,
591
+ });
592
+
593
+ yield* fs.writeFileString(path.join(input.dir, MANIFEST_FILE), serializeManifest(manifest));
594
+ yield* fs.writeFileString(
595
+ path.join(input.dir, README_FILE),
596
+ importGuide({
597
+ packageCount: input.included.length,
598
+ createdAt: createdAt.toISOString(),
599
+ toolVersion: input.options.toolVersion,
600
+ }),
601
+ );
602
+ });
603
+
604
+ /** Sorted top-level entries of a directory, used as the tar entry list. */
605
+ const topLevelEntries = (
606
+ dir: string,
607
+ ): Effect.Effect<ReadonlyArray<string>, PlatformError, FileSystem.FileSystem> =>
608
+ Effect.gen(function* () {
609
+ const fs = yield* FileSystem.FileSystem;
610
+ const entries = yield* fs.readDirectory(dir);
611
+ return entries.toSorted();
612
+ });
613
+
614
+ /**
615
+ * Two different packages must not want the same file name.
616
+ *
617
+ * Most of what this used to catch is now impossible: an archive is named for
618
+ * the spec, `@types-react@19.2.18.tgz`, and an unscoped npm name may not begin
619
+ * with `@`, so it cannot spell a scoped one. What survives is **two scoped
620
+ * packages whose scope boundary falls in a different place**, because that
621
+ * boundary is the one character the file name drops:
622
+ *
623
+ * @a/b-c -> @a-b-c@1.0.0.tgz
624
+ * @a-b/c -> @a-b-c@1.0.0.tgz
625
+ *
626
+ * Pathological rather than plausible — it needs somebody to hold the `@a-b`
627
+ * scope as well as `@a`, and both packages in one run at one version. It is
628
+ * kept anyway because of what it costs to be wrong: they are *different
629
+ * packages*, so deduplicating them would be wrong, and writing both is worse —
630
+ * the second lands on the first and the run reports two artifacts for the one
631
+ * file that survived. A bundle short a package, called complete, found at the
632
+ * far end of an air gap by somebody who cannot go and fetch the missing one.
633
+ *
634
+ * Nothing else would catch it. The overwrite check below compares this run's
635
+ * planned files against what is *already on disk*, and both of these are new.
636
+ *
637
+ * So it refuses, and names both specs. Not silently renamed: an archive whose
638
+ * name nobody chose is a file somebody has to identify later.
639
+ *
640
+ * Unconditional, unlike the overwrite check: `--force` is permission to replace
641
+ * what was already in the directory, not to let one run overwrite itself.
642
+ */
643
+ const assertDistinctOutputs = (
644
+ resolution: Resolution,
645
+ options: BundleContext,
646
+ ): Effect.Effect<void, OutputError> =>
647
+ Effect.gen(function* () {
648
+ const owners = new Map<string, Array<string>>();
649
+
650
+ // Over `plannedOutputs` rather than the per-spec targets, so this asks
651
+ // about the layout that is actually running. `single` writes one archive
652
+ // and `dir` two summary files, neither of which can collide — and a check
653
+ // that refused those would make its own advice impossible to take.
654
+ for (const planned of plannedOutputs(resolution, options)) {
655
+ const claimed = owners.get(planned.file);
656
+ const spec =
657
+ planned.name === undefined ? planned.file : `${planned.name}@${planned.version}`;
658
+
659
+ if (claimed === undefined) owners.set(planned.file, [spec]);
660
+ else claimed.push(spec);
661
+ }
662
+
663
+ const collisions = [...owners].filter(([, specs]) => specs.length > 1);
664
+ if (collisions.length === 0) return;
665
+
666
+ const described = collisions
667
+ .map(([file, specs]) => `${specs.join(" and ")} would both be ${file}`)
668
+ .join("; ");
669
+
670
+ return yield* Effect.fail(
671
+ new OutputError(
672
+ options.outDir,
673
+ `two packages want the same archive name — ${described}. The \`/\` in a ` +
674
+ `scope becomes a \`-\` to make a file name, so \`@a/b-c\` and \`@a-b/c\` ` +
675
+ `meet. Use --layout single, or bundle them into separate --out ` +
676
+ `directories.`,
677
+ ),
678
+ );
679
+ });
680
+
681
+ /**
682
+ * Fails if the run would overwrite something, unless `--force`.
683
+ *
684
+ * The guard is on the *files this run writes*, not on whether the directory has
685
+ * anything in it. An output directory accumulating bundles is the normal way to
686
+ * use this — bundling `esbuild` into an `out/` that already holds `tsdown` is
687
+ * not a conflict, and refusing it made `--out` a single-use directory and the
688
+ * default `.` unusable.
689
+ *
690
+ * Checked before anything is downloaded. Discovering the collision *after* a
691
+ * twenty-minute download would be a uniquely irritating way to fail — which is
692
+ * also why `assertDistinctOutputs` runs from here rather than at emit time.
693
+ */
694
+ const prepareOutputDir = (
695
+ resolution: Resolution,
696
+ options: BundleContext,
697
+ ): Effect.Effect<void, OutputError | PlatformError, FileSystem.FileSystem | Path.Path> =>
698
+ Effect.gen(function* () {
699
+ const fs = yield* FileSystem.FileSystem;
700
+ const path = yield* Path.Path;
701
+ const outDir = options.outDir;
702
+
703
+ yield* assertDistinctOutputs(resolution, options);
704
+
705
+ if (!options.force) {
706
+ const clashes: Array<string> = [];
707
+ for (const planned of plannedOutputs(resolution, options)) {
708
+ if (options.skipExisting?.has(planned.file) === true) continue;
709
+ if (options.overwrite?.has(planned.file) === true) continue;
710
+ const exists = yield* fs
711
+ .exists(path.join(outDir, planned.file))
712
+ .pipe(Effect.orElseSucceed(() => false));
713
+ if (exists) clashes.push(planned.file);
714
+ }
715
+
716
+ if (clashes.length > 0) {
717
+ return yield* Effect.fail(
718
+ new OutputError(
719
+ outDir,
720
+ `would overwrite ${clashes.length} existing file${clashes.length === 1 ? "" : "s"} ` +
721
+ `(${clashes.slice(0, 3).join(", ")}${clashes.length > 3 ? ", …" : ""}). ` +
722
+ `Pass --force true to replace ${clashes.length === 1 ? "it" : "them"}, or choose a different --out.`,
723
+ ),
724
+ );
725
+ }
726
+ }
727
+
728
+ yield* fs
729
+ .makeDirectory(outDir, { recursive: true })
730
+ .pipe(
731
+ Effect.mapError(
732
+ (cause) =>
733
+ new OutputError(outDir, "could not create output directory", { cause }),
734
+ ),
735
+ );
736
+ });