@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/resolve.ts ADDED
@@ -0,0 +1,560 @@
1
+ /**
2
+ * Version selection and the dependency closure walk.
3
+ *
4
+ * This is the part that decides *what* ends up in a bundle. Its only side
5
+ * effect is asking the `Registry` service for metadata, which makes the whole
6
+ * of it testable against a fake registry with no network at all.
7
+ *
8
+ * The walk is breadth-first in waves: resolve the current frontier
9
+ * concurrently, collect the newly discovered edges, repeat. Wave-based BFS
10
+ * gives real parallelism without a dynamic worker pool, and because each wave
11
+ * merges its results serially there is no shared mutable state being written
12
+ * from more than one fiber.
13
+ *
14
+ * One subtlety worth calling out: metadata is cached across walks, but each
15
+ * walk still traverses the full graph. That is what lets `per-spec` layout ask
16
+ * "what does *this* root version depend on" many times over while the network
17
+ * is touched exactly once per package.
18
+ */
19
+ import * as Effect from "effect/Effect";
20
+ import semver from "semver";
21
+
22
+ import { parseDependencyTarget } from "./dependency-range.js";
23
+ import { EdgeKind } from "./enums/edge-kind.js";
24
+ import { Phase } from "./enums/phase.js";
25
+ import type { BundlerError } from "./errors.js";
26
+ import { NoMatchingVersionsError, VersionNotFoundError } from "./errors.js";
27
+ import type { ResolveOptions } from "./options.js";
28
+ import { isIncluded } from "./platform.js";
29
+ import * as Progress from "./progress.js";
30
+ import type { PackageManifest, Packument } from "./registry.js";
31
+ import { Registry } from "./registry.js";
32
+ import type { PackageSpec, Selector } from "./spec.js";
33
+ import { formatSelector, formatSpec } from "./spec.js";
34
+
35
+ /** A single justification for including a package. */
36
+ export type Reason =
37
+ | { readonly _tag: "Root"; readonly spec: string }
38
+ | { readonly _tag: "Edge"; readonly from: string; readonly kind: EdgeKind };
39
+
40
+ /** `name@version` — the identity of a resolved package throughout the engine. */
41
+ export type PackageKey = string;
42
+
43
+ /** One package, pinned to one version, with every reason it was pulled in. */
44
+ export type ResolvedPackage = {
45
+ readonly name: string;
46
+ readonly version: string;
47
+ readonly manifest: PackageManifest;
48
+ readonly reasons: ReadonlyArray<Reason>;
49
+ };
50
+
51
+ /** Something we could not include, reported rather than thrown. */
52
+ export type ResolutionWarning = {
53
+ readonly message: string;
54
+ /** `name@version` of the package whose manifest contained the problem. */
55
+ readonly from?: string | undefined;
56
+ };
57
+
58
+ /** What one requested spec expanded to. */
59
+ export type RootResolution = {
60
+ readonly spec: PackageSpec;
61
+ /** The concrete versions the spec selected — more than one under `--all-versions`. */
62
+ readonly versions: ReadonlyArray<string>;
63
+ /** Closure per selected version, keyed by version. Drives `per-spec` layout. */
64
+ readonly closures: ReadonlyMap<string, ReadonlyArray<PackageKey>>;
65
+ /** Union of every per-version closure. */
66
+ readonly closure: ReadonlyArray<PackageKey>;
67
+ };
68
+
69
+ /** The complete result of resolving every requested spec. */
70
+ export type Resolution = {
71
+ readonly roots: ReadonlyArray<RootResolution>;
72
+ /** The deduplicated union of every closure, sorted by name then version. */
73
+ readonly packages: ReadonlyArray<ResolvedPackage>;
74
+ readonly warnings: ReadonlyArray<ResolutionWarning>;
75
+ };
76
+
77
+ /** One pending item on the BFS frontier. */
78
+ export type Task = {
79
+ readonly name: string;
80
+ readonly selector: Selector;
81
+ readonly reason: Reason;
82
+ /** Optional edges tolerate resolution failure; required ones do not. */
83
+ readonly tolerateFailure: boolean;
84
+ };
85
+
86
+ export const packageKey = (name: string, version: string): PackageKey => `${name}@${version}`;
87
+
88
+ /** Index of a resolution by `name@version`, for lookups during bundling. */
89
+ export const indexPackages = (resolution: Resolution): ReadonlyMap<PackageKey, ResolvedPackage> =>
90
+ new Map(resolution.packages.map((pkg) => [packageKey(pkg.name, pkg.version), pkg]));
91
+
92
+ /* -------------------------------------------------------------------------- */
93
+ /* Version selection */
94
+ /* -------------------------------------------------------------------------- */
95
+
96
+ /**
97
+ * Turns a selector into the concrete version(s) it names.
98
+ *
99
+ * `all` controls whether a range collapses to its best match — npm's behaviour,
100
+ * and what you always want for a transitive dependency — or expands to every
101
+ * satisfying published version, which is what `--all-versions` is for.
102
+ */
103
+ export const selectVersions = (
104
+ packument: Packument,
105
+ selector: Selector,
106
+ options: {
107
+ readonly all: boolean;
108
+ readonly maxVersions?: number | undefined;
109
+ readonly includePrerelease: boolean;
110
+ },
111
+ ): ReadonlyArray<string> => {
112
+ const available = Object.keys(packument.versions);
113
+
114
+ switch (selector._tag) {
115
+ case "Exact": {
116
+ if (!Object.hasOwn(packument.versions, selector.version)) {
117
+ throw new VersionNotFoundError(
118
+ packument.name,
119
+ selector.version,
120
+ sortVersions(available),
121
+ );
122
+ }
123
+ return [selector.version];
124
+ }
125
+
126
+ case "Tag": {
127
+ const version = packument.distTags[selector.tag];
128
+ if (version === undefined || !Object.hasOwn(packument.versions, version)) {
129
+ throw new NoMatchingVersionsError(
130
+ packument.name,
131
+ selector.tag,
132
+ sortVersions(available),
133
+ );
134
+ }
135
+ return [version];
136
+ }
137
+
138
+ case "Range": {
139
+ const satisfying = available
140
+ .filter((version) =>
141
+ semver.satisfies(version, selector.range, {
142
+ loose: true,
143
+ includePrerelease: options.includePrerelease,
144
+ }),
145
+ )
146
+ .toSorted(semver.rcompare);
147
+
148
+ const [best] = satisfying;
149
+ if (best === undefined) {
150
+ throw new NoMatchingVersionsError(
151
+ packument.name,
152
+ selector.range,
153
+ sortVersions(available),
154
+ );
155
+ }
156
+
157
+ if (!options.all) return [best];
158
+
159
+ return options.maxVersions !== undefined && options.maxVersions > 0
160
+ ? satisfying.slice(0, options.maxVersions)
161
+ : satisfying;
162
+ }
163
+ }
164
+ };
165
+
166
+ const sortVersions = (versions: ReadonlyArray<string>): ReadonlyArray<string> =>
167
+ versions.toSorted((a, b) =>
168
+ semver.valid(a) && semver.valid(b) ? semver.compare(a, b) : a.localeCompare(b),
169
+ );
170
+
171
+ /* -------------------------------------------------------------------------- */
172
+ /* Walk state */
173
+ /* -------------------------------------------------------------------------- */
174
+
175
+ /**
176
+ * State shared across every walk in a run.
177
+ *
178
+ * Caching packuments and expanded edges here is what makes repeated walks
179
+ * cheap: the second walk over `react@18.2.0` costs no network at all.
180
+ */
181
+ type WalkState = {
182
+ readonly resolved: Map<PackageKey, ResolvedPackage>;
183
+ readonly edges: Map<PackageKey, ReadonlyArray<Task>>;
184
+ readonly packuments: Map<string, Packument>;
185
+ readonly warnings: Array<ResolutionWarning>;
186
+ /** Warnings are deduplicated — the same skipped edge appears in many walks. */
187
+ readonly warningKeys: Set<string>;
188
+ };
189
+
190
+ const makeWalkState = (): WalkState => ({
191
+ resolved: new Map(),
192
+ edges: new Map(),
193
+ packuments: new Map(),
194
+ warnings: [],
195
+ warningKeys: new Set(),
196
+ });
197
+
198
+ const addWarning = (state: WalkState, warning: ResolutionWarning): void => {
199
+ const key = `${warning.from ?? ""}|${warning.message}`;
200
+ if (state.warningKeys.has(key)) return;
201
+ state.warningKeys.add(key);
202
+ state.warnings.push(warning);
203
+ };
204
+
205
+ /**
206
+ * Fetches a packument, reusing anything already seen in this run.
207
+ *
208
+ * Two fibers in the same wave can race here and both fetch. That is one
209
+ * duplicated GET at worst, and de-racing it would cost more complexity than it
210
+ * saves.
211
+ */
212
+ const getPackument = (
213
+ state: WalkState,
214
+ name: string,
215
+ ): Effect.Effect<Packument, BundlerError, Registry> =>
216
+ Effect.gen(function* () {
217
+ const cached = state.packuments.get(name);
218
+ if (cached !== undefined) return cached;
219
+ const registry = yield* Registry;
220
+ const packument = yield* registry.packument(name);
221
+ state.packuments.set(name, packument);
222
+ return packument;
223
+ });
224
+
225
+ /**
226
+ * Re-fails a thrown selection error into the Effect error channel.
227
+ *
228
+ * `selectVersions` throws `BundlerError` subclasses and nothing else, so this
229
+ * narrows rather than casting; anything unexpected is rethrown as a defect,
230
+ * which is what an unexpected exception actually is.
231
+ */
232
+ const asBundlerError = (error: unknown): BundlerError => {
233
+ if (error instanceof VersionNotFoundError || error instanceof NoMatchingVersionsError) {
234
+ return error;
235
+ }
236
+ throw error;
237
+ };
238
+
239
+ /* -------------------------------------------------------------------------- */
240
+ /* Edge expansion */
241
+ /* -------------------------------------------------------------------------- */
242
+
243
+ /** Expands one resolved manifest into the edges that follow from it. */
244
+ export const edgesOf = (
245
+ manifest: PackageManifest,
246
+ options: ResolveOptions,
247
+ ): {
248
+ readonly tasks: ReadonlyArray<Task>;
249
+ readonly warnings: ReadonlyArray<ResolutionWarning>;
250
+ } => {
251
+ const from = packageKey(manifest.name, manifest.version);
252
+ const tasks: Array<Task> = [];
253
+ const warnings: Array<ResolutionWarning> = [];
254
+
255
+ const add = (
256
+ entries: Readonly<Record<string, string>> | undefined,
257
+ kind: EdgeKind,
258
+ tolerateFailure: boolean,
259
+ skip?: (name: string) => boolean,
260
+ ): void => {
261
+ if (entries === undefined) return;
262
+ for (const [name, raw] of Object.entries(entries)) {
263
+ if (skip?.(name)) continue;
264
+ const target = parseDependencyTarget(name, raw);
265
+ if (target._tag === "Unsupported") {
266
+ warnings.push({
267
+ from,
268
+ message:
269
+ `Skipped ${name}@${target.raw} (${target.reason}) — it cannot be fetched from a ` +
270
+ `registry. Vendor it separately if the offline install needs it.`,
271
+ });
272
+ continue;
273
+ }
274
+ tasks.push({
275
+ name: target.name,
276
+ selector: target.selector,
277
+ reason: { _tag: "Edge", from, kind },
278
+ tolerateFailure,
279
+ });
280
+ }
281
+ };
282
+
283
+ // Runtime dependencies are non-negotiable.
284
+ add(manifest.dependencies, EdgeKind.Prod, false);
285
+
286
+ // Optional dependencies are allowed to be missing — npm tolerates a 404 here
287
+ // and so must we, or one unpublished platform package fails the whole run.
288
+ if (options.scope.optional) {
289
+ add(manifest.optionalDependencies, EdgeKind.Optional, true);
290
+ }
291
+
292
+ if (options.scope.peer) {
293
+ const meta = manifest.peerDependenciesMeta ?? {};
294
+ add(
295
+ manifest.peerDependencies,
296
+ EdgeKind.Peer,
297
+ false,
298
+ (name) => meta[name]?.optional === true,
299
+ );
300
+ }
301
+
302
+ return { tasks, warnings };
303
+ };
304
+
305
+ /** Edges for a package, computed once and cached. */
306
+ const edgesFor = (
307
+ state: WalkState,
308
+ manifest: PackageManifest,
309
+ options: ResolveOptions,
310
+ ): ReadonlyArray<Task> => {
311
+ const key = packageKey(manifest.name, manifest.version);
312
+ const cached = state.edges.get(key);
313
+ if (cached !== undefined) return cached;
314
+
315
+ const { tasks, warnings } = edgesOf(manifest, options);
316
+ for (const warning of warnings) addWarning(state, warning);
317
+ state.edges.set(key, tasks);
318
+ return tasks;
319
+ };
320
+
321
+ /* -------------------------------------------------------------------------- */
322
+ /* The walk */
323
+ /* -------------------------------------------------------------------------- */
324
+
325
+ /**
326
+ * Resolves everything reachable from `seeds`, returning the closure.
327
+ *
328
+ * `state` is mutated with newly resolved packages and warnings; the returned
329
+ * array is scoped to *this* walk, which is what makes per-root-version
330
+ * closures possible.
331
+ */
332
+ const walk = (
333
+ state: WalkState,
334
+ seeds: ReadonlyArray<Task>,
335
+ options: ResolveOptions,
336
+ ): Effect.Effect<ReadonlyArray<PackageKey>, BundlerError, Registry | Progress.Progress> =>
337
+ Effect.gen(function* () {
338
+ const discovered = new Set<PackageKey>();
339
+ // Guards against re-resolving the same (name, selector) pair. Large trees
340
+ // ask for `tslib@^2` hundreds of times, and this is also what terminates
341
+ // dependency cycles.
342
+ const attempted = new Set<string>();
343
+ let frontier: ReadonlyArray<Task> = seeds;
344
+
345
+ while (frontier.length > 0) {
346
+ const wave: Array<Task> = [];
347
+ for (const task of frontier) {
348
+ const id = `${task.name} ${formatSelector(task.selector)}`;
349
+ if (attempted.has(id)) continue;
350
+ attempted.add(id);
351
+ wave.push(task);
352
+ }
353
+ if (wave.length === 0) break;
354
+
355
+ const results = yield* Effect.forEach(
356
+ wave,
357
+ (task) => resolveTask(state, task, options),
358
+ { concurrency: options.concurrency },
359
+ );
360
+
361
+ const next: Array<Task> = [];
362
+
363
+ // Merged serially: every mutation of `state` happens on one fiber.
364
+ for (const result of results) {
365
+ if (result === null) continue;
366
+
367
+ for (const { manifest, reason } of result) {
368
+ const key = packageKey(manifest.name, manifest.version);
369
+ const existing = state.resolved.get(key);
370
+
371
+ if (existing === undefined) {
372
+ state.resolved.set(key, {
373
+ name: manifest.name,
374
+ version: manifest.version,
375
+ manifest,
376
+ reasons: [reason],
377
+ });
378
+
379
+ yield* Progress.emit({
380
+ _tag: "PackageResolved",
381
+ name: manifest.name,
382
+ version: manifest.version,
383
+ resolvedCount: state.resolved.size,
384
+ pendingCount: next.length,
385
+ });
386
+
387
+ if (manifest.deprecated !== undefined && manifest.deprecated !== "") {
388
+ addWarning(state, {
389
+ from: key,
390
+ message: `${key} is deprecated: ${manifest.deprecated}`,
391
+ });
392
+ }
393
+ } else if (!hasReason(existing.reasons, reason)) {
394
+ state.resolved.set(key, {
395
+ ...existing,
396
+ reasons: [...existing.reasons, reason],
397
+ });
398
+ }
399
+
400
+ // Expand regardless of whether the package is new. A package resolved
401
+ // during an earlier walk still has to contribute its subtree to
402
+ // *this* walk's closure; `attempted` stops that from looping.
403
+ if (!discovered.has(key)) {
404
+ discovered.add(key);
405
+ next.push(...edgesFor(state, manifest, options));
406
+ }
407
+ }
408
+ }
409
+
410
+ frontier = next;
411
+ }
412
+
413
+ return [...discovered];
414
+ });
415
+
416
+ const hasReason = (reasons: ReadonlyArray<Reason>, candidate: Reason): boolean =>
417
+ reasons.some((reason) => {
418
+ if (reason._tag === "Root" && candidate._tag === "Root")
419
+ return reason.spec === candidate.spec;
420
+ if (reason._tag === "Edge" && candidate._tag === "Edge") {
421
+ return reason.from === candidate.from && reason.kind === candidate.kind;
422
+ }
423
+ return false;
424
+ });
425
+
426
+ /**
427
+ * Resolves one task to its manifest(s).
428
+ *
429
+ * Returns `null` when an optional edge could not be resolved — the caller
430
+ * treats that as "skip quietly", which is what npm does for
431
+ * `optionalDependencies`.
432
+ */
433
+ const resolveTask = (
434
+ state: WalkState,
435
+ task: Task,
436
+ options: ResolveOptions,
437
+ ): Effect.Effect<
438
+ ReadonlyArray<{ readonly manifest: PackageManifest; readonly reason: Reason }> | null,
439
+ BundlerError,
440
+ Registry
441
+ > =>
442
+ Effect.gen(function* () {
443
+ const packument = yield* getPackument(state, task.name);
444
+
445
+ // Transitive edges always collapse to a single best match; only root specs
446
+ // ever fan out, and those arrive here already pinned to an exact version.
447
+ const versions = yield* Effect.try({
448
+ try: () =>
449
+ selectVersions(packument, task.selector, {
450
+ all: false,
451
+ includePrerelease: options.includePrerelease,
452
+ }),
453
+ catch: asBundlerError,
454
+ });
455
+
456
+ return versions.flatMap((version) => {
457
+ const manifest = packument.versions[version];
458
+ if (manifest === undefined) return [];
459
+
460
+ // Platform narrowing only ever applies to optional edges. Filtering a
461
+ // required dependency by platform would produce a bundle that cannot
462
+ // install anywhere.
463
+ if (
464
+ task.reason._tag === "Edge" &&
465
+ task.reason.kind === EdgeKind.Optional &&
466
+ !isIncluded(manifest, options.scope.platforms)
467
+ ) {
468
+ return [];
469
+ }
470
+
471
+ return { manifest, reason: task.reason };
472
+ });
473
+ }).pipe(
474
+ Effect.catch((error) => {
475
+ // A required edge that cannot be resolved is fatal. An optional one is
476
+ // recorded and skipped, matching how npm treats `optionalDependencies`.
477
+ if (!task.tolerateFailure) return Effect.fail(error);
478
+ return Effect.sync(() => {
479
+ addWarning(state, {
480
+ message:
481
+ `Optional dependency ${task.name}@${formatSelector(task.selector)} could not be ` +
482
+ `resolved and was skipped: ${error.message}`,
483
+ });
484
+ return null;
485
+ });
486
+ }),
487
+ );
488
+
489
+ /* -------------------------------------------------------------------------- */
490
+ /* Entry point */
491
+ /* -------------------------------------------------------------------------- */
492
+
493
+ /**
494
+ * Resolves every requested spec.
495
+ *
496
+ * Each selected root *version* is walked separately so `per-spec` layout has an
497
+ * exact closure per tarball, while all walks share one cache, so a package
498
+ * reached from twenty roots is fetched once.
499
+ */
500
+ export const resolve = (
501
+ specs: ReadonlyArray<PackageSpec>,
502
+ options: ResolveOptions,
503
+ ): Effect.Effect<Resolution, BundlerError, Registry | Progress.Progress> =>
504
+ Effect.gen(function* () {
505
+ yield* Progress.emit({ _tag: "PhaseStarted", phase: Phase.Resolve, total: specs.length });
506
+
507
+ const state = makeWalkState();
508
+ const roots: Array<RootResolution> = [];
509
+
510
+ for (const spec of specs) {
511
+ const packument = yield* getPackument(state, spec.name);
512
+
513
+ const versions = yield* Effect.try({
514
+ try: () =>
515
+ selectVersions(packument, spec.selector, {
516
+ all: options.allVersions,
517
+ maxVersions: options.maxVersions,
518
+ includePrerelease: options.includePrerelease,
519
+ }),
520
+ catch: asBundlerError,
521
+ });
522
+
523
+ const closures = new Map<string, ReadonlyArray<PackageKey>>();
524
+ const union = new Set<PackageKey>();
525
+
526
+ for (const version of versions) {
527
+ const closure = yield* walk(
528
+ state,
529
+ [
530
+ {
531
+ name: spec.name,
532
+ selector: { _tag: "Exact", version },
533
+ reason: { _tag: "Root", spec: formatSpec(spec) },
534
+ tolerateFailure: false,
535
+ },
536
+ ],
537
+ options,
538
+ );
539
+ closures.set(version, closure);
540
+ for (const key of closure) union.add(key);
541
+ }
542
+
543
+ roots.push({ spec, versions, closures, closure: [...union] });
544
+ }
545
+
546
+ yield* Progress.emit({ _tag: "PhaseCompleted", phase: Phase.Resolve });
547
+
548
+ return {
549
+ roots,
550
+ packages: [...state.resolved.values()].toSorted(compareResolved),
551
+ warnings: state.warnings,
552
+ };
553
+ });
554
+
555
+ const compareResolved = (a: ResolvedPackage, b: ResolvedPackage): number => {
556
+ if (a.name !== b.name) return a.name < b.name ? -1 : 1;
557
+ return semver.valid(a.version) && semver.valid(b.version)
558
+ ? semver.compare(a.version, b.version)
559
+ : a.version.localeCompare(b.version);
560
+ };
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Schemas for JSON nobody controls.
3
+ *
4
+ * Registry responses, lockfiles and hand-edited package.json files all arrive
5
+ * as untyped JSON, and the rule at every one of those boundaries is the same:
6
+ * drop what cannot be understood, keep the rest. A bundler that rejects a
7
+ * packument because one published version carries a field it has never seen is
8
+ * useless against exactly the private registries it exists to serve.
9
+ *
10
+ * Effect Schema does the narrowing, which is what keeps those boundaries free
11
+ * of casts and hand-rolled `typeof` ladders. What this module adds on top of
12
+ * the stock combinators is that tolerance: `Schema.Record(String, String)`
13
+ * fails the whole record over one numeric value, where the wire format wants
14
+ * that entry skipped and its neighbours kept.
15
+ */
16
+ import * as Effect from "effect/Effect";
17
+ import * as Option from "effect/Option";
18
+ import * as Schema from "effect/Schema";
19
+ import * as Getter from "effect/SchemaGetter";
20
+
21
+ import { isRecord } from "../utils/is-record.js";
22
+
23
+ /**
24
+ * An optional field that goes *absent* rather than failing when it is
25
+ * malformed.
26
+ *
27
+ * This is the difference between "we do not understand this field" and "we do
28
+ * not understand this document". An `os: "linux"` where an array was expected
29
+ * costs the platform filter one signal; it should not cost the run the package.
30
+ */
31
+ export const tolerant = <S extends Schema.Top>(schema: S) =>
32
+ Schema.optional(
33
+ Schema.UndefinedOr(schema).pipe(
34
+ Schema.catchDecoding(() => Effect.succeed(Option.some(undefined))),
35
+ ),
36
+ );
37
+
38
+ /**
39
+ * Keeps only the string-valued members of an untyped object.
40
+ *
41
+ * `{ "lodash": "^4.0.0", "broken": 3 }` decodes to `{ "lodash": "^4.0.0" }`.
42
+ * Per-entry rather than whole-record tolerance, because one unreadable edge in
43
+ * a dependency block is no reason to forget the others.
44
+ */
45
+ export const StringRecordSchema = Schema.Record(Schema.String, Schema.Unknown).pipe(
46
+ Schema.decodeTo(Schema.Record(Schema.String, Schema.String), {
47
+ decode: Getter.transform((raw: Record<string, unknown>) => {
48
+ const out: Record<string, string> = {};
49
+ for (const [key, value] of Object.entries(raw)) {
50
+ if (typeof value === "string") out[key] = value;
51
+ }
52
+ return out;
53
+ }),
54
+ encode: Getter.passthroughSubtype(),
55
+ }),
56
+ );
57
+
58
+ /** The same per-entry tolerance for a list: `["linux", 7]` decodes to `["linux"]`. */
59
+ export const StringArraySchema = Schema.Array(Schema.Unknown).pipe(
60
+ Schema.decodeTo(Schema.Array(Schema.String), {
61
+ decode: Getter.transform((raw: ReadonlyArray<unknown>) =>
62
+ raw.flatMap((entry) => (typeof entry === "string" ? entry : [])),
63
+ ),
64
+ encode: Getter.passthroughSubtype(),
65
+ }),
66
+ );
67
+
68
+ /**
69
+ * `peerDependenciesMeta`, normalised.
70
+ *
71
+ * Only `optional` is read, and only its `true` is meaningful — npm writes the
72
+ * flag as a boolean, a hand-edited file may carry anything, and every other
73
+ * value means "not optional".
74
+ */
75
+ export const OptionalFlagRecordSchema = Schema.Record(Schema.String, Schema.Unknown).pipe(
76
+ Schema.decodeTo(Schema.Record(Schema.String, Schema.Struct({ optional: Schema.Boolean })), {
77
+ decode: Getter.transform((raw: Record<string, unknown>) => {
78
+ const out: Record<string, { optional: boolean }> = {};
79
+ for (const [key, value] of Object.entries(raw)) {
80
+ if (isRecord(value)) out[key] = { optional: value["optional"] === true };
81
+ }
82
+ return out;
83
+ }),
84
+ encode: Getter.passthroughSubtype(),
85
+ }),
86
+ );
87
+
88
+ /*
89
+ * The `Optional…` variants below decode an empty result to `undefined`.
90
+ *
91
+ * Absent has to stay absent. `dependencies: {}` and no `dependencies` at all
92
+ * read the same to the resolver, but the first one travels into a bundle
93
+ * manifest claiming the registry published an empty block — a difference
94
+ * somebody diffing two manifests has to explain.
95
+ */
96
+
97
+ const absentWhenEmpty = <T extends Record<string, unknown>>(value: T): T | undefined =>
98
+ Object.keys(value).length > 0 ? value : undefined;
99
+
100
+ export const OptionalStringRecordSchema = StringRecordSchema.pipe(
101
+ Schema.decodeTo(Schema.UndefinedOr(Schema.Record(Schema.String, Schema.String)), {
102
+ decode: Getter.transform(absentWhenEmpty<Record<string, string>>),
103
+ encode: Getter.transform((value: Record<string, string> | undefined) => value ?? {}),
104
+ }),
105
+ );
106
+
107
+ export const OptionalStringArraySchema = StringArraySchema.pipe(
108
+ Schema.decodeTo(Schema.UndefinedOr(Schema.Array(Schema.String)), {
109
+ decode: Getter.transform((value: ReadonlyArray<string>) =>
110
+ value.length > 0 ? value : undefined,
111
+ ),
112
+ encode: Getter.transform((value: ReadonlyArray<string> | undefined) => value ?? []),
113
+ }),
114
+ );
115
+
116
+ export const OptionalFlagRecordOrAbsentSchema = OptionalFlagRecordSchema.pipe(
117
+ Schema.decodeTo(
118
+ Schema.UndefinedOr(
119
+ Schema.Record(Schema.String, Schema.Struct({ optional: Schema.Boolean })),
120
+ ),
121
+ {
122
+ decode: Getter.transform(
123
+ absentWhenEmpty<Record<string, { readonly optional: boolean }>>,
124
+ ),
125
+ encode: Getter.transform(
126
+ (value: Record<string, { readonly optional: boolean }> | undefined) => value ?? {},
127
+ ),
128
+ },
129
+ ),
130
+ );