@packall/core 0.0.1

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 (51) hide show
  1. package/dist/Archive.d.ts +32 -0
  2. package/dist/Archive.d.ts.map +1 -0
  3. package/dist/Bundle.d.ts +123 -0
  4. package/dist/Bundle.d.ts.map +1 -0
  5. package/dist/DependencyRange.d.ts +26 -0
  6. package/dist/DependencyRange.d.ts.map +1 -0
  7. package/dist/Download.d.ts +35 -0
  8. package/dist/Download.d.ts.map +1 -0
  9. package/dist/Errors.d.ts +124 -0
  10. package/dist/Errors.d.ts.map +1 -0
  11. package/dist/InputFile.d.ts +46 -0
  12. package/dist/InputFile.d.ts.map +1 -0
  13. package/dist/Integrity.d.ts +48 -0
  14. package/dist/Integrity.d.ts.map +1 -0
  15. package/dist/Layout.d.ts +53 -0
  16. package/dist/Layout.d.ts.map +1 -0
  17. package/dist/Manifest.d.ts +82 -0
  18. package/dist/Manifest.d.ts.map +1 -0
  19. package/dist/Options.d.ts +100 -0
  20. package/dist/Options.d.ts.map +1 -0
  21. package/dist/Platform.d.ts +69 -0
  22. package/dist/Platform.d.ts.map +1 -0
  23. package/dist/Progress.d.ts +107 -0
  24. package/dist/Progress.d.ts.map +1 -0
  25. package/dist/Registry.d.ts +106 -0
  26. package/dist/Registry.d.ts.map +1 -0
  27. package/dist/Resolve.d.ts +105 -0
  28. package/dist/Resolve.d.ts.map +1 -0
  29. package/dist/Spec.d.ts +62 -0
  30. package/dist/Spec.d.ts.map +1 -0
  31. package/dist/index.d.ts +36 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +1766 -0
  34. package/dist/index.js.map +1 -0
  35. package/package.json +38 -0
  36. package/src/Archive.ts +92 -0
  37. package/src/Bundle.ts +570 -0
  38. package/src/DependencyRange.ts +115 -0
  39. package/src/Download.ts +132 -0
  40. package/src/Errors.ts +216 -0
  41. package/src/InputFile.ts +229 -0
  42. package/src/Integrity.ts +122 -0
  43. package/src/Layout.ts +103 -0
  44. package/src/Manifest.ts +133 -0
  45. package/src/Options.ts +123 -0
  46. package/src/Platform.ts +182 -0
  47. package/src/Progress.ts +106 -0
  48. package/src/Registry.ts +121 -0
  49. package/src/Resolve.ts +528 -0
  50. package/src/Spec.ts +186 -0
  51. package/src/index.ts +44 -0
@@ -0,0 +1,121 @@
1
+ /**
2
+ * The registry seam.
3
+ *
4
+ * This is the **only** place in the engine that knows a registry exists.
5
+ * Everything downstream — range resolution, the dependency walk, layout,
6
+ * archiving — is expressed against these three operations, so swapping npm for
7
+ * something else means implementing this interface and nothing more.
8
+ *
9
+ * `@packall/registry-npm` provides the implementation that speaks the plain
10
+ * npm registry protocol, which is what Artifactory, Nexus, Verdaccio, GitHub
11
+ * Packages and registry.npmjs.org all serve.
12
+ */
13
+ import * as Context from "effect/Context"
14
+ import type * as Effect from "effect/Effect"
15
+ import type { BundlerError } from "./Errors.js"
16
+
17
+ /**
18
+ * A single published version, as the registry describes it.
19
+ *
20
+ * This is a narrowed view of a package.json — only the fields that affect what
21
+ * has to be downloaded. Unknown fields are ignored rather than rejected,
22
+ * because registries add metadata over time and a bundler that breaks on new
23
+ * metadata is worse than useless.
24
+ */
25
+ export interface PackageManifest {
26
+ readonly name: string
27
+ readonly version: string
28
+
29
+ readonly dependencies?: Readonly<Record<string, string>> | undefined
30
+ readonly optionalDependencies?: Readonly<Record<string, string>> | undefined
31
+ readonly peerDependencies?: Readonly<Record<string, string>> | undefined
32
+ readonly peerDependenciesMeta?:
33
+ | Readonly<Record<string, { readonly optional?: boolean | undefined }>>
34
+ | undefined
35
+ readonly devDependencies?: Readonly<Record<string, string>> | undefined
36
+ readonly bundleDependencies?: ReadonlyArray<string> | undefined
37
+
38
+ /** Platform constraints, used when `--platform` narrows optional deps. */
39
+ readonly os?: ReadonlyArray<string> | undefined
40
+ readonly cpu?: ReadonlyArray<string> | undefined
41
+ readonly libc?: ReadonlyArray<string> | undefined
42
+
43
+ readonly deprecated?: string | undefined
44
+
45
+ readonly dist: PackageDist
46
+ }
47
+
48
+ /** Where the tarball lives and how to prove it arrived intact. */
49
+ export interface PackageDist {
50
+ readonly tarball: string
51
+ /** SRI string, e.g. `sha512-...`. Preferred over `shasum`. */
52
+ readonly integrity?: string | undefined
53
+ /** Legacy hex sha1. Still the only checksum on very old versions. */
54
+ readonly shasum?: string | undefined
55
+ readonly unpackedSize?: number | undefined
56
+ readonly fileCount?: number | undefined
57
+ }
58
+
59
+ /** Everything the registry knows about one package. */
60
+ export interface Packument {
61
+ readonly name: string
62
+ /** `{ latest: "1.2.3", next: "2.0.0-beta.1" }` */
63
+ readonly distTags: Readonly<Record<string, string>>
64
+ /** Every published version, keyed by version string. */
65
+ readonly versions: Readonly<Record<string, PackageManifest>>
66
+ }
67
+
68
+ /** The set of operations a registry backend has to provide. */
69
+ export interface RegistryService {
70
+ /** Short identifier for the manifest and for error messages, e.g. `"npm"`. */
71
+ readonly kind: string
72
+
73
+ /**
74
+ * The registry URL that will actually be used for a given package, after
75
+ * per-scope configuration is applied. Used for reporting only.
76
+ */
77
+ readonly registryFor: (packageName: string) => string
78
+
79
+ /**
80
+ * Cheap liveness check, run once before any real work.
81
+ *
82
+ * This is what turns "hangs forever behind a dead VPN" into a five-second
83
+ * error naming the host we could not reach.
84
+ */
85
+ readonly preflight: Effect.Effect<void, BundlerError>
86
+
87
+ /**
88
+ * Full metadata for a package. Implementations are expected to memoise:
89
+ * the dependency walk asks for the same popular packages repeatedly.
90
+ */
91
+ readonly packument: (packageName: string) => Effect.Effect<Packument, BundlerError>
92
+
93
+ /** Fetches the tarball bytes for one published version. */
94
+ readonly download: (manifest: PackageManifest) => Effect.Effect<Uint8Array, BundlerError>
95
+ }
96
+
97
+ /**
98
+ * Service tag for the registry backend.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * import { Effect } from "effect"
103
+ * import { Registry } from "@packall/core"
104
+ *
105
+ * const program = Effect.gen(function*() {
106
+ * const registry = yield* Registry
107
+ * return yield* registry.packument("lodash")
108
+ * })
109
+ * ```
110
+ */
111
+ export class Registry extends Context.Service<Registry, RegistryService>()(
112
+ "@packall/core/Registry"
113
+ ) {}
114
+
115
+ /** Extracts the dist-tag mapping, defaulting sensibly when a registry omits it. */
116
+ export const resolveDistTag = (packument: Packument, tag: string): string | undefined =>
117
+ packument.distTags[tag]
118
+
119
+ /** All published version strings, in registry order. */
120
+ export const publishedVersions = (packument: Packument): ReadonlyArray<string> =>
121
+ Object.keys(packument.versions)
package/src/Resolve.ts ADDED
@@ -0,0 +1,528 @@
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
+ import { parseDependencyTarget } from "./DependencyRange.js"
22
+ import type { BundlerError } from "./Errors.js"
23
+ import { NoMatchingVersionsError, VersionNotFoundError } from "./Errors.js"
24
+ import type { ResolveOptions } from "./Options.js"
25
+ import { isIncluded } from "./Platform.js"
26
+ import type { Packument, PackageManifest } from "./Registry.js"
27
+ import { Registry } from "./Registry.js"
28
+ import * as Progress from "./Progress.js"
29
+ import type { PackageSpec, Selector } from "./Spec.js"
30
+ import { formatSelector, formatSpec } from "./Spec.js"
31
+
32
+ /** Why a package is in the bundle. */
33
+ export type EdgeKind = "prod" | "optional" | "peer"
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
+ export const packageKey = (name: string, version: string): PackageKey => `${name}@${version}`
44
+
45
+ /** One package, pinned to one version, with every reason it was pulled in. */
46
+ export interface ResolvedPackage {
47
+ readonly name: string
48
+ readonly version: string
49
+ readonly manifest: PackageManifest
50
+ readonly reasons: ReadonlyArray<Reason>
51
+ }
52
+
53
+ /** Something we could not include, reported rather than thrown. */
54
+ export interface ResolutionWarning {
55
+ readonly message: string
56
+ /** `name@version` of the package whose manifest contained the problem. */
57
+ readonly from?: string | undefined
58
+ }
59
+
60
+ /** What one requested spec expanded to. */
61
+ export interface RootResolution {
62
+ readonly spec: PackageSpec
63
+ /** The concrete versions the spec selected — more than one under `--all-versions`. */
64
+ readonly versions: ReadonlyArray<string>
65
+ /** Closure per selected version, keyed by version. Drives `per-spec` layout. */
66
+ readonly closures: ReadonlyMap<string, ReadonlyArray<PackageKey>>
67
+ /** Union of every per-version closure. */
68
+ readonly closure: ReadonlyArray<PackageKey>
69
+ }
70
+
71
+ /** The complete result of resolving every requested spec. */
72
+ export interface Resolution {
73
+ readonly roots: ReadonlyArray<RootResolution>
74
+ /** The deduplicated union of every closure, sorted by name then version. */
75
+ readonly packages: ReadonlyArray<ResolvedPackage>
76
+ readonly warnings: ReadonlyArray<ResolutionWarning>
77
+ }
78
+
79
+ /** Index of a resolution by `name@version`, for lookups during bundling. */
80
+ export const indexPackages = (
81
+ resolution: Resolution
82
+ ): ReadonlyMap<PackageKey, ResolvedPackage> =>
83
+ new Map(resolution.packages.map((p) => [packageKey(p.name, p.version), p]))
84
+
85
+ /* -------------------------------------------------------------------------- */
86
+ /* Version selection */
87
+ /* -------------------------------------------------------------------------- */
88
+
89
+ /**
90
+ * Turns a selector into the concrete version(s) it names.
91
+ *
92
+ * `all` controls whether a range collapses to its best match — npm's behaviour,
93
+ * and what you always want for a transitive dependency — or expands to every
94
+ * satisfying published version, which is what `--all-versions` is for.
95
+ */
96
+ export const selectVersions = (
97
+ packument: Packument,
98
+ selector: Selector,
99
+ options: {
100
+ readonly all: boolean
101
+ readonly maxVersions?: number | undefined
102
+ readonly includePrerelease: boolean
103
+ }
104
+ ): ReadonlyArray<string> => {
105
+ const available = Object.keys(packument.versions)
106
+
107
+ switch (selector._tag) {
108
+ case "Exact": {
109
+ if (!Object.hasOwn(packument.versions, selector.version)) {
110
+ throw new VersionNotFoundError(packument.name, selector.version, sortVersions(available))
111
+ }
112
+ return [selector.version]
113
+ }
114
+
115
+ case "Tag": {
116
+ const version = packument.distTags[selector.tag]
117
+ if (version === undefined || !Object.hasOwn(packument.versions, version)) {
118
+ throw new NoMatchingVersionsError(packument.name, selector.tag, sortVersions(available))
119
+ }
120
+ return [version]
121
+ }
122
+
123
+ case "Range": {
124
+ const satisfying = available
125
+ .filter((v) =>
126
+ semver.satisfies(v, selector.range, {
127
+ loose: true,
128
+ includePrerelease: options.includePrerelease
129
+ })
130
+ )
131
+ .sort(semver.rcompare)
132
+
133
+ if (satisfying.length === 0) {
134
+ throw new NoMatchingVersionsError(packument.name, selector.range, sortVersions(available))
135
+ }
136
+
137
+ if (!options.all) return [satisfying[0]!]
138
+
139
+ return options.maxVersions !== undefined && options.maxVersions > 0
140
+ ? satisfying.slice(0, options.maxVersions)
141
+ : satisfying
142
+ }
143
+ }
144
+ }
145
+
146
+ const sortVersions = (versions: ReadonlyArray<string>): ReadonlyArray<string> =>
147
+ [...versions].sort((a, b) =>
148
+ semver.valid(a) && semver.valid(b) ? semver.compare(a, b) : a.localeCompare(b)
149
+ )
150
+
151
+ /* -------------------------------------------------------------------------- */
152
+ /* Walk state */
153
+ /* -------------------------------------------------------------------------- */
154
+
155
+ /** One pending item on the BFS frontier. */
156
+ export interface Task {
157
+ readonly name: string
158
+ readonly selector: Selector
159
+ readonly reason: Reason
160
+ /** Optional edges tolerate resolution failure; required ones do not. */
161
+ readonly tolerateFailure: boolean
162
+ }
163
+
164
+ /**
165
+ * State shared across every walk in a run.
166
+ *
167
+ * Caching packuments and expanded edges here is what makes repeated walks
168
+ * cheap: the second walk over `react@18.2.0` costs no network at all.
169
+ */
170
+ interface WalkState {
171
+ readonly resolved: Map<PackageKey, ResolvedPackage>
172
+ readonly edges: Map<PackageKey, ReadonlyArray<Task>>
173
+ readonly packuments: Map<string, Packument>
174
+ readonly warnings: Array<ResolutionWarning>
175
+ /** Warnings are deduplicated — the same skipped edge appears in many walks. */
176
+ readonly warningKeys: Set<string>
177
+ }
178
+
179
+ const makeWalkState = (): WalkState => ({
180
+ resolved: new Map(),
181
+ edges: new Map(),
182
+ packuments: new Map(),
183
+ warnings: [],
184
+ warningKeys: new Set()
185
+ })
186
+
187
+ const addWarning = (state: WalkState, warning: ResolutionWarning): void => {
188
+ const key = `${warning.from ?? ""}|${warning.message}`
189
+ if (state.warningKeys.has(key)) return
190
+ state.warningKeys.add(key)
191
+ state.warnings.push(warning)
192
+ }
193
+
194
+ /**
195
+ * Fetches a packument, reusing anything already seen in this run.
196
+ *
197
+ * Two fibers in the same wave can race here and both fetch. That is one
198
+ * duplicated GET at worst, and de-racing it would cost more complexity than it
199
+ * saves.
200
+ */
201
+ const getPackument = (
202
+ state: WalkState,
203
+ name: string
204
+ ): Effect.Effect<Packument, BundlerError, Registry> =>
205
+ Effect.gen(function*() {
206
+ const cached = state.packuments.get(name)
207
+ if (cached !== undefined) return cached
208
+ const registry = yield* Registry
209
+ const packument = yield* registry.packument(name)
210
+ state.packuments.set(name, packument)
211
+ return packument
212
+ })
213
+
214
+ /* -------------------------------------------------------------------------- */
215
+ /* Edge expansion */
216
+ /* -------------------------------------------------------------------------- */
217
+
218
+ /** Expands one resolved manifest into the edges that follow from it. */
219
+ export const edgesOf = (
220
+ manifest: PackageManifest,
221
+ options: ResolveOptions
222
+ ): {
223
+ readonly tasks: ReadonlyArray<Task>
224
+ readonly warnings: ReadonlyArray<ResolutionWarning>
225
+ } => {
226
+ const from = packageKey(manifest.name, manifest.version)
227
+ const tasks: Array<Task> = []
228
+ const warnings: Array<ResolutionWarning> = []
229
+
230
+ const add = (
231
+ entries: Readonly<Record<string, string>> | undefined,
232
+ kind: EdgeKind,
233
+ tolerateFailure: boolean,
234
+ skip?: (name: string) => boolean
235
+ ): void => {
236
+ if (entries === undefined) return
237
+ for (const [name, raw] of Object.entries(entries)) {
238
+ if (skip?.(name)) continue
239
+ const target = parseDependencyTarget(name, raw)
240
+ if (target._tag === "Unsupported") {
241
+ warnings.push({
242
+ from,
243
+ message:
244
+ `Skipped ${name}@${target.raw} (${target.reason}) — it cannot be fetched from a ` +
245
+ `registry. Vendor it separately if the offline install needs it.`
246
+ })
247
+ continue
248
+ }
249
+ tasks.push({
250
+ name: target.name,
251
+ selector: target.selector,
252
+ reason: { _tag: "Edge", from, kind },
253
+ tolerateFailure
254
+ })
255
+ }
256
+ }
257
+
258
+ // Runtime dependencies are non-negotiable.
259
+ add(manifest.dependencies, "prod", false)
260
+
261
+ // Optional dependencies are allowed to be missing — npm tolerates a 404 here
262
+ // and so must we, or one unpublished platform package fails the whole run.
263
+ if (options.scope.optional) {
264
+ add(manifest.optionalDependencies, "optional", true)
265
+ }
266
+
267
+ if (options.scope.peer) {
268
+ const meta = manifest.peerDependenciesMeta ?? {}
269
+ add(manifest.peerDependencies, "peer", false, (name) => meta[name]?.optional === true)
270
+ }
271
+
272
+ return { tasks, warnings }
273
+ }
274
+
275
+ /** Edges for a package, computed once and cached. */
276
+ const edgesFor = (
277
+ state: WalkState,
278
+ manifest: PackageManifest,
279
+ options: ResolveOptions
280
+ ): ReadonlyArray<Task> => {
281
+ const key = packageKey(manifest.name, manifest.version)
282
+ const cached = state.edges.get(key)
283
+ if (cached !== undefined) return cached
284
+
285
+ const { tasks, warnings } = edgesOf(manifest, options)
286
+ for (const warning of warnings) addWarning(state, warning)
287
+ state.edges.set(key, tasks)
288
+ return tasks
289
+ }
290
+
291
+ /* -------------------------------------------------------------------------- */
292
+ /* The walk */
293
+ /* -------------------------------------------------------------------------- */
294
+
295
+ /**
296
+ * Resolves everything reachable from `seeds`, returning the closure.
297
+ *
298
+ * `state` is mutated with newly resolved packages and warnings; the returned
299
+ * array is scoped to *this* walk, which is what makes per-root-version
300
+ * closures possible.
301
+ */
302
+ const walk = (
303
+ state: WalkState,
304
+ seeds: ReadonlyArray<Task>,
305
+ options: ResolveOptions
306
+ ): Effect.Effect<ReadonlyArray<PackageKey>, BundlerError, Registry | Progress.Progress> =>
307
+ Effect.gen(function*() {
308
+ const discovered = new Set<PackageKey>()
309
+ // Guards against re-resolving the same (name, selector) pair. Large trees
310
+ // ask for `tslib@^2` hundreds of times, and this is also what terminates
311
+ // dependency cycles.
312
+ const attempted = new Set<string>()
313
+ let frontier: ReadonlyArray<Task> = seeds
314
+
315
+ while (frontier.length > 0) {
316
+ const wave: Array<Task> = []
317
+ for (const task of frontier) {
318
+ const id = `${task.name} ${formatSelector(task.selector)}`
319
+ if (attempted.has(id)) continue
320
+ attempted.add(id)
321
+ wave.push(task)
322
+ }
323
+ if (wave.length === 0) break
324
+
325
+ const results = yield* Effect.forEach(
326
+ wave,
327
+ (task) => resolveTask(state, task, options),
328
+ { concurrency: options.concurrency }
329
+ )
330
+
331
+ const next: Array<Task> = []
332
+
333
+ // Merged serially: every mutation of `state` happens on one fiber.
334
+ for (const result of results) {
335
+ if (result === null) continue
336
+
337
+ for (const { manifest, reason } of result) {
338
+ const key = packageKey(manifest.name, manifest.version)
339
+ const isNew = !state.resolved.has(key)
340
+
341
+ if (isNew) {
342
+ state.resolved.set(key, {
343
+ name: manifest.name,
344
+ version: manifest.version,
345
+ manifest,
346
+ reasons: [reason]
347
+ })
348
+
349
+ yield* Progress.emit({
350
+ _tag: "PackageResolved",
351
+ name: manifest.name,
352
+ version: manifest.version,
353
+ resolvedCount: state.resolved.size,
354
+ pendingCount: next.length
355
+ })
356
+
357
+ if (manifest.deprecated !== undefined && manifest.deprecated !== "") {
358
+ addWarning(state, { from: key, message: `${key} is deprecated: ${manifest.deprecated}` })
359
+ }
360
+ } else {
361
+ const existing = state.resolved.get(key)!
362
+ if (!hasReason(existing.reasons, reason)) {
363
+ state.resolved.set(key, { ...existing, reasons: [...existing.reasons, reason] })
364
+ }
365
+ }
366
+
367
+ // Expand regardless of whether the package is new. A package resolved
368
+ // during an earlier walk still has to contribute its subtree to
369
+ // *this* walk's closure; `attempted` stops that from looping.
370
+ if (!discovered.has(key)) {
371
+ discovered.add(key)
372
+ next.push(...edgesFor(state, manifest, options))
373
+ }
374
+ }
375
+ }
376
+
377
+ frontier = next
378
+ }
379
+
380
+ return [...discovered]
381
+ })
382
+
383
+ const hasReason = (reasons: ReadonlyArray<Reason>, candidate: Reason): boolean =>
384
+ reasons.some((reason) => {
385
+ if (reason._tag === "Root" && candidate._tag === "Root") return reason.spec === candidate.spec
386
+ if (reason._tag === "Edge" && candidate._tag === "Edge") {
387
+ return reason.from === candidate.from && reason.kind === candidate.kind
388
+ }
389
+ return false
390
+ })
391
+
392
+ /**
393
+ * Resolves one task to its manifest(s).
394
+ *
395
+ * Returns `null` when an optional edge could not be resolved — the caller
396
+ * treats that as "skip quietly", which is what npm does for
397
+ * `optionalDependencies`.
398
+ */
399
+ const resolveTask = (
400
+ state: WalkState,
401
+ task: Task,
402
+ options: ResolveOptions
403
+ ): Effect.Effect<
404
+ ReadonlyArray<{ manifest: PackageManifest; reason: Reason }> | null,
405
+ BundlerError,
406
+ Registry
407
+ > =>
408
+ Effect.gen(function*() {
409
+ const packument = yield* getPackument(state, task.name)
410
+
411
+ // Transitive edges always collapse to a single best match; only root specs
412
+ // ever fan out, and those arrive here already pinned to an exact version.
413
+ const versions = yield* Effect.try({
414
+ try: () =>
415
+ selectVersions(packument, task.selector, {
416
+ all: false,
417
+ includePrerelease: options.includePrerelease
418
+ }),
419
+ catch: (error) => error as BundlerError
420
+ })
421
+
422
+ const out: Array<{ manifest: PackageManifest; reason: Reason }> = []
423
+ for (const version of versions) {
424
+ const manifest = packument.versions[version]
425
+ if (manifest === undefined) continue
426
+
427
+ // Platform narrowing only ever applies to optional edges. Filtering a
428
+ // required dependency by platform would produce a bundle that cannot
429
+ // install anywhere.
430
+ if (
431
+ task.reason._tag === "Edge" &&
432
+ task.reason.kind === "optional" &&
433
+ !isIncluded(manifest, options.scope.platforms)
434
+ ) {
435
+ continue
436
+ }
437
+
438
+ out.push({ manifest, reason: task.reason })
439
+ }
440
+ return out
441
+ }).pipe(
442
+ Effect.catch((error) => {
443
+ // A required edge that cannot be resolved is fatal. An optional one is
444
+ // recorded and skipped, matching how npm treats `optionalDependencies`.
445
+ if (!task.tolerateFailure) return Effect.fail(error)
446
+ return Effect.sync(() => {
447
+ addWarning(state, {
448
+ message:
449
+ `Optional dependency ${task.name}@${formatSelector(task.selector)} could not be ` +
450
+ `resolved and was skipped: ${error.message}`
451
+ })
452
+ return null
453
+ })
454
+ })
455
+ )
456
+
457
+ /* -------------------------------------------------------------------------- */
458
+ /* Entry point */
459
+ /* -------------------------------------------------------------------------- */
460
+
461
+ /**
462
+ * Resolves every requested spec.
463
+ *
464
+ * Each selected root *version* is walked separately so `per-spec` layout has an
465
+ * exact closure per tarball, while all walks share one cache, so a package
466
+ * reached from twenty roots is fetched once.
467
+ */
468
+ export const resolve = (
469
+ specs: ReadonlyArray<PackageSpec>,
470
+ options: ResolveOptions
471
+ ): Effect.Effect<Resolution, BundlerError, Registry | Progress.Progress> =>
472
+ Effect.gen(function*() {
473
+ yield* Progress.emit({ _tag: "PhaseStarted", phase: "resolve", total: specs.length })
474
+
475
+ const state = makeWalkState()
476
+ const roots: Array<RootResolution> = []
477
+
478
+ for (const spec of specs) {
479
+ const packument = yield* getPackument(state, spec.name)
480
+
481
+ const versions = yield* Effect.try({
482
+ try: () =>
483
+ selectVersions(packument, spec.selector, {
484
+ all: options.allVersions,
485
+ maxVersions: options.maxVersions,
486
+ includePrerelease: options.includePrerelease
487
+ }),
488
+ catch: (error) => error as BundlerError
489
+ })
490
+
491
+ const closures = new Map<string, ReadonlyArray<PackageKey>>()
492
+ const union = new Set<PackageKey>()
493
+
494
+ for (const version of versions) {
495
+ const closure = yield* walk(
496
+ state,
497
+ [
498
+ {
499
+ name: spec.name,
500
+ selector: { _tag: "Exact", version },
501
+ reason: { _tag: "Root", spec: formatSpec(spec) },
502
+ tolerateFailure: false
503
+ }
504
+ ],
505
+ options
506
+ )
507
+ closures.set(version, closure)
508
+ for (const key of closure) union.add(key)
509
+ }
510
+
511
+ roots.push({ spec, versions, closures, closure: [...union] })
512
+ }
513
+
514
+ yield* Progress.emit({ _tag: "PhaseCompleted", phase: "resolve" })
515
+
516
+ return {
517
+ roots,
518
+ packages: [...state.resolved.values()].sort(compareResolved),
519
+ warnings: state.warnings
520
+ }
521
+ })
522
+
523
+ const compareResolved = (a: ResolvedPackage, b: ResolvedPackage): number => {
524
+ if (a.name !== b.name) return a.name < b.name ? -1 : 1
525
+ return semver.valid(a.version) && semver.valid(b.version)
526
+ ? semver.compare(a.version, b.version)
527
+ : a.version.localeCompare(b.version)
528
+ }