The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { constants as fsConstants } from "node:fs"; |
| 2 | import { builtinModules } from "node:module"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as FileSystem from "effect/FileSystem"; |
| 5 | import * as Path from "effect/Path"; |
| 6 | import { ChildProcess } from "effect/process"; |
| 7 | import type { ChildProcessSpawner } from "effect/process/ChildProcessSpawner"; |
| 8 | import * as Schema from "effect/Schema"; |
| 9 | import { parseAllDocuments, parse as parseYaml } from "yaml"; |
| 10 | import { exec } from "../Util/exec.ts"; |
| 11 | import { sha256, sha256Object } from "../Util/sha256.ts"; |
| 12 | import { BundleError } from "./Bundle.ts"; |
| 13 | |
| 14 | export interface InstalledPackageFile { |
| 15 | readonly path: string; |
| 16 | readonly content: Uint8Array<ArrayBufferLike>; |
| 17 | /** Complete Unix mode, including the file type bits. */ |
| 18 | readonly mode?: number; |
| 19 | } |
| 20 | |
| 21 | type JsonRecord = Record<string, unknown>; |
| 22 | |
| 23 | export type PackageInstall = ReadonlyArray<string> | Readonly<Record<string, string>>; |
| 24 | |
| 25 | export type NpmInstallRunner = ( |
| 26 | directory: string, |
| 27 | args: ReadonlyArray<string>, |
| 28 | ) => Effect.Effect<void, unknown>; |
| 29 | |
| 30 | export interface ResolveInstallTargetsOptions { |
| 31 | readonly cwd: string; |
| 32 | /** Normalized package-root → requested version map (from {@link normalizeInstallTargets}). */ |
| 33 | readonly requested: Readonly<Record<string, string>>; |
| 34 | } |
| 35 | |
| 36 | export type PackageOverride = string | PackageOverrideMap; |
| 37 | |
| 38 | export interface PackageOverrideMap { |
| 39 | readonly [dependencyName: string]: PackageOverride; |
| 40 | } |
| 41 | |
| 42 | export type PackageOverrides = Readonly<Record<string, PackageOverride>>; |
| 43 | |
| 44 | export interface PackageInstallPlan { |
| 45 | readonly resolved: Readonly<Record<string, string>>; |
| 46 | readonly overrides: PackageOverrides; |
| 47 | } |
| 48 | |
| 49 | export interface PackageInstallIdentity extends PackageInstallPlan { |
| 50 | readonly lockfile?: { |
| 51 | readonly name: string; |
| 52 | readonly hash: string; |
| 53 | }; |
| 54 | } |
| 55 | |
| 56 | export interface HashPackageInstallIdentityOptions { |
| 57 | readonly bundleHash: string; |
| 58 | readonly identity: PackageInstallIdentity; |
| 59 | readonly architecture: "x86_64" | "arm64"; |
| 60 | } |
| 61 | |
| 62 | export interface InstallResolvedPackagesOptions { |
| 63 | /** Package-root → concrete npm version map (from {@link resolveInstallTargets}). */ |
| 64 | readonly resolved: Readonly<Record<string, string>>; |
| 65 | /** Locked parent-package → child-package versions used to pin transitives. */ |
| 66 | readonly overrides?: PackageOverrides; |
| 67 | readonly architecture: "x86_64" | "arm64"; |
| 68 | readonly runNpmInstall?: NpmInstallRunner; |
| 69 | } |
| 70 | |
| 71 | export interface InstallPackagesOptions { |
| 72 | readonly cwd: string; |
| 73 | readonly install?: PackageInstall; |
| 74 | readonly architecture: "x86_64" | "arm64"; |
| 75 | readonly runNpmInstall?: NpmInstallRunner; |
| 76 | } |
| 77 | |
| 78 | interface PackageJson { |
| 79 | readonly dependencies?: Record<string, string>; |
| 80 | readonly optionalDependencies?: Record<string, string>; |
| 81 | readonly devDependencies?: Record<string, string>; |
| 82 | readonly catalog?: Record<string, string>; |
| 83 | readonly catalogs?: Record<string, Record<string, string>>; |
| 84 | readonly workspaces?: unknown; |
| 85 | } |
| 86 | |
| 87 | interface CatalogSource { |
| 88 | readonly catalog?: Record<string, string>; |
| 89 | readonly catalogs?: Record<string, Record<string, string>>; |
| 90 | } |
| 91 | |
| 92 | const builtins = new Set(builtinModules.flatMap((name) => [name, `node:${name}`])); |
| 93 | |
| 94 | /** |
| 95 | * Unix mode for symlink entries in the ZIP archive. Effect's FileSystem |
| 96 | * exposes `readLink` but not `lstat`, so the symlink type bits must be |
| 97 | * synthesized after identifying a link. The permission bits are conventional |
| 98 | * for symlinks and are ignored by Unix filesystems. |
| 99 | */ |
| 100 | const symbolicLinkMode = fsConstants.S_IFLNK | 0o777; |
| 101 | |
| 102 | const incompatibleVersionPrefixes = ["workspace:", "file:", "link:", "portal:", "patch:"] as const; |
| 103 | |
| 104 | const lockfileNames = [ |
| 105 | "bun.lock", |
| 106 | "bun.lockb", |
| 107 | "package-lock.json", |
| 108 | "pnpm-lock.yaml", |
| 109 | "yarn.lock", |
| 110 | ] as const; |
| 111 | |
| 112 | /** |
| 113 | * Parses a module specifier into its package root, or `undefined` when the |
| 114 | * specifier is not a bare package import (relative path, builtin, glob, subpath |
| 115 | * imports, etc.). |
| 116 | */ |
| 117 | export function parsePackageRoot(specifier: string): string | undefined { |
| 118 | const root = parsePackageRootFromSpecifier(specifier); |
| 119 | return root === specifier ? root : undefined; |
| 120 | } |
| 121 | |
| 122 | /** |
| 123 | * Parses a bare package specifier or subpath import into its package root. |
| 124 | */ |
| 125 | export function parsePackageRootFromSpecifier(specifier: string): string | undefined { |
| 126 | if ( |
| 127 | specifier.length === 0 || |
| 128 | builtins.has(specifier) || |
| 129 | specifier.startsWith(".") || |
| 130 | specifier.startsWith("/") || |
| 131 | specifier.startsWith("\\") || |
| 132 | specifier.includes("*") || |
| 133 | specifier.includes("?") || |
| 134 | specifier.includes(":") || |
| 135 | specifier.includes("\0") |
| 136 | ) { |
| 137 | return undefined; |
| 138 | } |
| 139 | |
| 140 | const segments = specifier.split("/"); |
| 141 | if (specifier.startsWith("@")) { |
| 142 | return segments.length >= 2 ? `${segments[0]}/${segments[1]}` : undefined; |
| 143 | } |
| 144 | return segments[0]; |
| 145 | } |
| 146 | |
| 147 | /** Whether `moduleId` is `root` itself or a subpath import of it. */ |
| 148 | export function matchesPackageRoot(moduleId: string, root: string): boolean { |
| 149 | return moduleId === root || moduleId.startsWith(`${root}/`); |
| 150 | } |
| 151 | |
| 152 | export function npmInstallArgs(architecture: "x86_64" | "arm64"): ReadonlyArray<string> { |
| 153 | return npmCommandArgs("ci", architecture); |
| 154 | } |
| 155 | |
| 156 | export function npmLockfileArgs(architecture: "x86_64" | "arm64"): ReadonlyArray<string> { |
| 157 | return [...npmCommandArgs("install", architecture), "--package-lock-only", "--ignore-scripts"]; |
| 158 | } |
| 159 | |
| 160 | export function npmPlainInstallArgs(architecture: "x86_64" | "arm64"): ReadonlyArray<string> { |
| 161 | return npmCommandArgs("install", architecture); |
| 162 | } |
| 163 | |
| 164 | const npmCommandArgs = ( |
| 165 | command: "ci" | "install", |
| 166 | architecture: "x86_64" | "arm64", |
| 167 | ): ReadonlyArray<string> => { |
| 168 | const npmArchitecture = architecture === "arm64" ? "arm64" : "x64"; |
| 169 | return [ |
| 170 | command, |
| 171 | "--force", |
| 172 | "--platform=linux", |
| 173 | "--os=linux", |
| 174 | `--arch=${npmArchitecture}`, |
| 175 | `--cpu=${npmArchitecture}`, |
| 176 | "--libc=glibc", |
| 177 | ]; |
| 178 | }; |
| 179 | |
| 180 | /** |
| 181 | * Normalizes and validates a `build.install` declaration to a |
| 182 | * package-root → requested-version map. Array entries default to `"*"`. |
| 183 | */ |
| 184 | export function normalizeInstallTargets( |
| 185 | install: PackageInstall | undefined, |
| 186 | ): Effect.Effect<Record<string, string>, BundleError> { |
| 187 | if (!install) return Effect.succeed({}); |
| 188 | const entries: ReadonlyArray<readonly [string, string]> = Array.isArray(install) |
| 189 | ? install.map((dep) => [dep, "*"] as const) |
| 190 | : Object.entries(install); |
| 191 | |
| 192 | const requested: Record<string, string> = {}; |
| 193 | for (const [dep, version] of entries) { |
| 194 | const root = parsePackageRoot(dep); |
| 195 | if (root === undefined) { |
| 196 | return Effect.fail( |
| 197 | BundleError.make({ |
| 198 | message: `Invalid package name '${dep}' in build.install. Use a package root like 'sharp', not a subpath or bare specifier.`, |
| 199 | }), |
| 200 | ); |
| 201 | } |
| 202 | requested[root] = version; |
| 203 | } |
| 204 | return Effect.succeed(requested); |
| 205 | } |
| 206 | |
| 207 | /** |
| 208 | * Resolves the npm-compatible version for every requested package, reading the |
| 209 | * nearest source `package.json` and pnpm/Bun catalogs. Does not run npm. |
| 210 | */ |
| 211 | export function resolveInstallTargets( |
| 212 | options: ResolveInstallTargetsOptions, |
| 213 | ): Effect.Effect< |
| 214 | Record<string, string>, |
| 215 | BundleError, |
| 216 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 217 | > { |
| 218 | return resolvePackageInstallPlan(options).pipe(Effect.map((plan) => ({ ...plan.resolved }))); |
| 219 | } |
| 220 | |
| 221 | export function resolvePackageInstallPlan( |
| 222 | options: ResolveInstallTargetsOptions, |
| 223 | ): Effect.Effect< |
| 224 | PackageInstallPlan, |
| 225 | BundleError, |
| 226 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 227 | > { |
| 228 | const packageNames = Object.keys(options.requested).sort(); |
| 229 | if (packageNames.length === 0) { |
| 230 | return Effect.succeed({ resolved: {}, overrides: {} }); |
| 231 | } |
| 232 | |
| 233 | return Effect.gen(function* () { |
| 234 | const sourcePackageJson = yield* readSourcePackageJson(options.cwd); |
| 235 | const resolved: Record<string, string> = {}; |
| 236 | for (const packageName of packageNames) { |
| 237 | resolved[packageName] = yield* resolveInstallVersion( |
| 238 | options.cwd, |
| 239 | sourcePackageJson, |
| 240 | packageName, |
| 241 | options.requested[packageName], |
| 242 | ); |
| 243 | } |
| 244 | const lockfilePath = yield* findUp(options.cwd, lockfileNames); |
| 245 | if (lockfilePath === undefined) { |
| 246 | return { resolved, overrides: {} }; |
| 247 | } |
| 248 | return yield* pinInstallVersionsFromLockfile({ |
| 249 | cwd: options.cwd, |
| 250 | lockfilePath, |
| 251 | packageJson: sourcePackageJson, |
| 252 | requested: options.requested, |
| 253 | resolved, |
| 254 | }); |
| 255 | }).pipe(Effect.mapError(toBundleError)); |
| 256 | } |
| 257 | |
| 258 | /** |
| 259 | * Resolves the package install identity used by Lambda diffing. The lockfile |
| 260 | * fingerprint makes range-preserving dependency updates trigger a new artifact. |
| 261 | */ |
| 262 | export function resolvePackageInstallIdentity( |
| 263 | options: ResolveInstallTargetsOptions, |
| 264 | ): Effect.Effect< |
| 265 | PackageInstallIdentity, |
| 266 | BundleError, |
| 267 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 268 | > { |
| 269 | return Effect.gen(function* () { |
| 270 | const plan = yield* resolvePackageInstallPlan(options); |
| 271 | if (Object.keys(plan.resolved).length === 0) { |
| 272 | return plan; |
| 273 | } |
| 274 | const lockfile = yield* readNearestLockfileFingerprint(options.cwd); |
| 275 | return { ...plan, lockfile }; |
| 276 | }); |
| 277 | } |
| 278 | |
| 279 | export function hashPackageInstallIdentity( |
| 280 | options: HashPackageInstallIdentityOptions, |
| 281 | ): Effect.Effect<string> { |
| 282 | return sha256Object({ |
| 283 | bundle: options.bundleHash, |
| 284 | install: options.identity.resolved, |
| 285 | overrides: options.identity.overrides, |
| 286 | lockfile: options.identity.lockfile, |
| 287 | architecture: options.architecture, |
| 288 | }); |
| 289 | } |
| 290 | |
| 291 | /** |
| 292 | * Installs already-resolved dependencies into an isolated npm artifact targeting |
| 293 | * Linux and the function's architecture, returning the artifact's files. |
| 294 | */ |
| 295 | export function installResolvedPackages( |
| 296 | options: InstallResolvedPackagesOptions, |
| 297 | ): Effect.Effect< |
| 298 | ReadonlyArray<InstalledPackageFile>, |
| 299 | BundleError, |
| 300 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 301 | > { |
| 302 | const packageNames = Object.keys(options.resolved).sort(); |
| 303 | if (packageNames.length === 0) return Effect.succeed([]); |
| 304 | |
| 305 | const runInstall = ( |
| 306 | directory: string, |
| 307 | args: ReadonlyArray<string>, |
| 308 | ): Effect.Effect<void, BundleError, ChildProcessSpawner> => |
| 309 | options.runNpmInstall === undefined |
| 310 | ? runNpmInstall(directory, args) |
| 311 | : options.runNpmInstall(directory, args).pipe(Effect.mapError(toBundleError)); |
| 312 | |
| 313 | return Effect.gen(function* () { |
| 314 | const fileSystem = yield* FileSystem.FileSystem; |
| 315 | const pathService = yield* Path.Path; |
| 316 | |
| 317 | return yield* Effect.acquireUseRelease( |
| 318 | fileSystem.makeTempDirectory({ prefix: "alchemy-lambda-packages-" }), |
| 319 | (directory) => |
| 320 | Effect.gen(function* () { |
| 321 | const hasOverrides = |
| 322 | options.overrides !== undefined && Object.keys(options.overrides).length > 0; |
| 323 | const manifest = JSON.stringify( |
| 324 | { |
| 325 | private: true, |
| 326 | dependencies: options.resolved, |
| 327 | ...(hasOverrides ? { overrides: options.overrides } : {}), |
| 328 | }, |
| 329 | null, |
| 330 | 2, |
| 331 | ); |
| 332 | yield* fileSystem.writeFileString( |
| 333 | pathService.join(directory, "package.json"), |
| 334 | `${manifest}\n`, |
| 335 | ); |
| 336 | if (hasOverrides) { |
| 337 | // Generate a lock so `npm ci` reproduces the override-pinned graph. |
| 338 | yield* runInstall(directory, npmLockfileArgs(options.architecture)); |
| 339 | yield* runInstall(directory, npmInstallArgs(options.architecture)); |
| 340 | } else { |
| 341 | yield* runInstall(directory, npmPlainInstallArgs(options.architecture)); |
| 342 | } |
| 343 | return yield* readArtifactFiles(directory); |
| 344 | }), |
| 345 | (directory) => fileSystem.remove(directory, { recursive: true }).pipe(Effect.ignore), |
| 346 | ); |
| 347 | }).pipe(Effect.mapError(toBundleError)); |
| 348 | } |
| 349 | |
| 350 | /** |
| 351 | * Convenience flow for callers that do not need to defer installation. |
| 352 | */ |
| 353 | export function installPackages( |
| 354 | options: InstallPackagesOptions, |
| 355 | ): Effect.Effect< |
| 356 | ReadonlyArray<InstalledPackageFile>, |
| 357 | BundleError, |
| 358 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 359 | > { |
| 360 | return Effect.gen(function* () { |
| 361 | const requested = yield* normalizeInstallTargets(options.install); |
| 362 | const plan = yield* resolvePackageInstallPlan({ |
| 363 | cwd: options.cwd, |
| 364 | requested, |
| 365 | }); |
| 366 | return yield* installResolvedPackages({ |
| 367 | ...plan, |
| 368 | architecture: options.architecture, |
| 369 | runNpmInstall: options.runNpmInstall, |
| 370 | }); |
| 371 | }); |
| 372 | } |
| 373 | |
| 374 | const runNpmInstall = ( |
| 375 | directory: string, |
| 376 | args: ReadonlyArray<string>, |
| 377 | ): Effect.Effect<void, BundleError, ChildProcessSpawner> => |
| 378 | Effect.sync(() => |
| 379 | ChildProcess.setCwd( |
| 380 | ChildProcess.make("npm", args, { |
| 381 | shell: false, |
| 382 | env: { ...process.env }, |
| 383 | }), |
| 384 | directory, |
| 385 | ), |
| 386 | ).pipe( |
| 387 | Effect.flatMap(exec), |
| 388 | Effect.scoped, |
| 389 | Effect.mapError((cause) => { |
| 390 | const message = cause instanceof Error ? cause.message : String(cause); |
| 391 | return BundleError.make({ |
| 392 | message: message.includes("ENOENT") |
| 393 | ? "Failed to run 'npm install' for build.install: 'npm' was not found on PATH. build.install shells out to npm (even in Bun/pnpm projects), so Node.js/npm must be installed." |
| 394 | : `Failed to run 'npm install' for build.install: ${message}`, |
| 395 | cause, |
| 396 | }); |
| 397 | }), |
| 398 | Effect.flatMap(({ exitCode, stderr }) => |
| 399 | exitCode === 0 |
| 400 | ? Effect.void |
| 401 | : Effect.fail( |
| 402 | BundleError.make({ |
| 403 | message: `npm install for build.install failed with exit code ${exitCode}: ${stderr}`, |
| 404 | }), |
| 405 | ), |
| 406 | ), |
| 407 | ); |
| 408 | |
| 409 | const printBunBinaryLockfile = ( |
| 410 | lockfilePath: string, |
| 411 | ): Effect.Effect<string, BundleError, ChildProcessSpawner> => |
| 412 | Effect.sync(() => |
| 413 | ChildProcess.make("bun", [lockfilePath], { |
| 414 | shell: false, |
| 415 | env: { ...process.env }, |
| 416 | }), |
| 417 | ).pipe( |
| 418 | Effect.flatMap(exec), |
| 419 | Effect.scoped, |
| 420 | Effect.mapError((cause) => { |
| 421 | const message = cause instanceof Error ? cause.message : String(cause); |
| 422 | return BundleError.make({ |
| 423 | message: message.includes("ENOENT") |
| 424 | ? `Failed to inspect legacy Bun lockfile '${lockfilePath}': 'bun' was not found on PATH. Reading a binary bun.lockb shells out to bun; install Bun or migrate to the text-based bun.lock format.` |
| 425 | : `Failed to inspect legacy Bun lockfile '${lockfilePath}'`, |
| 426 | cause, |
| 427 | }); |
| 428 | }), |
| 429 | Effect.flatMap(({ exitCode, stdout, stderr }) => |
| 430 | exitCode === 0 |
| 431 | ? Effect.succeed(stdout) |
| 432 | : Effect.fail( |
| 433 | BundleError.make({ |
| 434 | message: `Failed to inspect legacy Bun lockfile '${lockfilePath}': bun exited with code ${exitCode}: ${stderr}`, |
| 435 | }), |
| 436 | ), |
| 437 | ), |
| 438 | ); |
| 439 | |
| 440 | const readSourcePackageJson = (cwd: string) => |
| 441 | Effect.gen(function* () { |
| 442 | const fs = yield* FileSystem.FileSystem; |
| 443 | const path = yield* Path.Path; |
| 444 | const content = yield* fs.readFileString(path.join(cwd, "package.json")); |
| 445 | return yield* Effect.try({ |
| 446 | try: () => JSON.parse(content) as PackageJson, |
| 447 | catch: (cause) => |
| 448 | BundleError.make({ |
| 449 | message: `Failed to parse package.json for Lambda externals from '${cwd}'`, |
| 450 | cause, |
| 451 | }), |
| 452 | }); |
| 453 | }).pipe( |
| 454 | Effect.mapError((cause) => |
| 455 | BundleError.make({ |
| 456 | message: `Failed to read package.json for Lambda externals from '${cwd}'`, |
| 457 | cause, |
| 458 | }), |
| 459 | ), |
| 460 | ); |
| 461 | |
| 462 | const resolveInstallVersion = ( |
| 463 | cwd: string, |
| 464 | packageJson: PackageJson, |
| 465 | packageName: string, |
| 466 | installVersion: string | undefined, |
| 467 | ) => |
| 468 | Effect.gen(function* () { |
| 469 | let version = installVersion; |
| 470 | if (version === undefined || version === "" || version === "*") { |
| 471 | version = |
| 472 | packageJson.dependencies?.[packageName] ?? |
| 473 | packageJson.optionalDependencies?.[packageName] ?? |
| 474 | packageJson.devDependencies?.[packageName] ?? |
| 475 | "*"; |
| 476 | } |
| 477 | |
| 478 | if (version.startsWith("catalog:")) { |
| 479 | return yield* resolveCatalogVersion(cwd, packageName, version); |
| 480 | } |
| 481 | |
| 482 | for (const prefix of incompatibleVersionPrefixes) { |
| 483 | if (version.startsWith(prefix)) { |
| 484 | return yield* BundleError.make({ |
| 485 | message: `External package '${packageName}' uses '${version}', which cannot be installed in an isolated Lambda artifact. Pin an npm-compatible version in package.json or build.install.`, |
| 486 | }); |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | return version; |
| 491 | }); |
| 492 | |
| 493 | const pinInstallVersionsFromLockfile = (options: { |
| 494 | readonly cwd: string; |
| 495 | readonly lockfilePath: string; |
| 496 | readonly packageJson: PackageJson; |
| 497 | readonly requested: Readonly<Record<string, string>>; |
| 498 | readonly resolved: Readonly<Record<string, string>>; |
| 499 | }): Effect.Effect< |
| 500 | PackageInstallPlan, |
| 501 | BundleError, |
| 502 | FileSystem.FileSystem | Path.Path | ChildProcessSpawner |
| 503 | > => |
| 504 | Effect.gen(function* () { |
| 505 | const fs = yield* FileSystem.FileSystem; |
| 506 | const path = yield* Path.Path; |
| 507 | const lockfileName = path.basename(options.lockfilePath); |
| 508 | const lockfileDirectory = path.dirname(options.lockfilePath); |
| 509 | const importer = path.relative(lockfileDirectory, options.cwd).replaceAll("\\", "/"); |
| 510 | const candidates = Object.keys(options.resolved).filter((packageName) => { |
| 511 | const requested = options.requested[packageName]; |
| 512 | const declared = declaredPackageVersion(options.packageJson, packageName); |
| 513 | return ( |
| 514 | declared !== undefined && |
| 515 | (requested === undefined || requested === "" || requested === "*" || requested === declared) |
| 516 | ); |
| 517 | }); |
| 518 | if (candidates.length === 0) { |
| 519 | return { resolved: { ...options.resolved }, overrides: {} }; |
| 520 | } |
| 521 | |
| 522 | const content = |
| 523 | lockfileName === "bun.lockb" |
| 524 | ? yield* printBunBinaryLockfile(options.lockfilePath) |
| 525 | : yield* fs.readFileString(options.lockfilePath).pipe( |
| 526 | Effect.mapError((cause) => |
| 527 | BundleError.make({ |
| 528 | message: `Failed to read package-manager lockfile for Lambda externals from '${options.cwd}'`, |
| 529 | cause, |
| 530 | }), |
| 531 | ), |
| 532 | ); |
| 533 | const plan = yield* Effect.try({ |
| 534 | try: () => |
| 535 | parseLockedInstallPlan({ |
| 536 | name: lockfileName === "bun.lockb" ? "yarn.lock" : lockfileName, |
| 537 | content, |
| 538 | importer, |
| 539 | candidates, |
| 540 | packageJson: options.packageJson, |
| 541 | resolved: Object.fromEntries( |
| 542 | Object.entries(options.resolved).filter( |
| 543 | ([packageName]) => !candidates.includes(packageName), |
| 544 | ), |
| 545 | ), |
| 546 | }), |
| 547 | catch: (cause) => |
| 548 | BundleError.make({ |
| 549 | message: `Failed to resolve locked Lambda package versions from '${options.lockfilePath}'`, |
| 550 | cause, |
| 551 | }), |
| 552 | }); |
| 553 | |
| 554 | for (const packageName of candidates) { |
| 555 | if (plan.resolved[packageName] === undefined) { |
| 556 | return yield* BundleError.make({ |
| 557 | message: `Could not resolve a locked version for '${packageName}' from '${options.lockfilePath}'. Pin an exact npm-compatible version in build.install or refresh the package-manager lockfile.`, |
| 558 | }); |
| 559 | } |
| 560 | } |
| 561 | |
| 562 | return plan; |
| 563 | }); |
| 564 | |
| 565 | interface LockParseOptions { |
| 566 | readonly name: string; |
| 567 | readonly content: string; |
| 568 | readonly importer: string; |
| 569 | readonly candidates: ReadonlyArray<string>; |
| 570 | readonly packageJson: PackageJson; |
| 571 | readonly resolved: Readonly<Record<string, string>>; |
| 572 | } |
| 573 | |
| 574 | type MutablePackageOverride = string | MutablePackageOverrideMap; |
| 575 | interface MutablePackageOverrideMap { |
| 576 | [dependencyName: string]: MutablePackageOverride; |
| 577 | } |
| 578 | type MutablePackageOverrides = Record<string, MutablePackageOverride>; |
| 579 | |
| 580 | interface LockedGraphRoot<Node> { |
| 581 | readonly node: Node; |
| 582 | readonly rootSelector: string; |
| 583 | } |
| 584 | |
| 585 | interface LockedGraphDependency<Node> { |
| 586 | readonly dependencyName: string; |
| 587 | readonly installSpec: string; |
| 588 | readonly node?: Node; |
| 589 | } |
| 590 | |
| 591 | /** |
| 592 | * Builds npm `overrides` pinning every dependency name reachable from each |
| 593 | * root. npm override keys apply to the whole subtree below the matched |
| 594 | * package (most-specific rule wins), so a name that resolves to a single |
| 595 | * version anywhere under the root needs one flat rule. Nested rules are only |
| 596 | * emitted along the branches where the lockfile resolves the same name to |
| 597 | * different versions, which keeps the overrides object proportional to the |
| 598 | * dependency graph instead of to its (potentially exponential) path count. |
| 599 | */ |
| 600 | const addLockedGraphOverrides = <Node>( |
| 601 | overrides: MutablePackageOverrides, |
| 602 | roots: ReadonlyArray<LockedGraphRoot<Node>>, |
| 603 | nodeId: (node: Node) => unknown, |
| 604 | dependencies: (node: Node) => ReadonlyArray<LockedGraphDependency<Node>>, |
| 605 | ): void => { |
| 606 | const edgeMemo = new Map<unknown, ReadonlyArray<LockedGraphDependency<Node>>>(); |
| 607 | const edgesOf = (node: Node): ReadonlyArray<LockedGraphDependency<Node>> => { |
| 608 | const id = nodeId(node); |
| 609 | let edges = edgeMemo.get(id); |
| 610 | if (edges === undefined) { |
| 611 | edges = dependencies(node); |
| 612 | edgeMemo.set(id, edges); |
| 613 | } |
| 614 | return edges; |
| 615 | }; |
| 616 | |
| 617 | // name → set of install specs observed anywhere in the subtree (memoized). |
| 618 | const specsMemo = new Map<unknown, ReadonlyMap<string, ReadonlySet<string>>>(); |
| 619 | const specsOf = (start: Node): ReadonlyMap<string, ReadonlySet<string>> => { |
| 620 | const startId = nodeId(start); |
| 621 | const memoized = specsMemo.get(startId); |
| 622 | if (memoized !== undefined) return memoized; |
| 623 | const specs = new Map<string, Set<string>>(); |
| 624 | const visited = new Set<unknown>([startId]); |
| 625 | const queue: Node[] = [start]; |
| 626 | while (queue.length > 0) { |
| 627 | const node = queue.pop()!; |
| 628 | for (const edge of edgesOf(node)) { |
| 629 | let set = specs.get(edge.dependencyName); |
| 630 | if (set === undefined) { |
| 631 | set = new Set(); |
| 632 | specs.set(edge.dependencyName, set); |
| 633 | } |
| 634 | set.add(edge.installSpec); |
| 635 | if (edge.node === undefined) continue; |
| 636 | const childId = nodeId(edge.node); |
| 637 | if (visited.has(childId)) continue; |
| 638 | visited.add(childId); |
| 639 | queue.push(edge.node); |
| 640 | } |
| 641 | } |
| 642 | specsMemo.set(startId, specs); |
| 643 | return specs; |
| 644 | }; |
| 645 | |
| 646 | const asOverrideMap = ( |
| 647 | parent: MutablePackageOverrideMap, |
| 648 | dependencyName: string, |
| 649 | ): MutablePackageOverrideMap => { |
| 650 | const existing = parent[dependencyName]; |
| 651 | if (typeof existing === "object") return existing; |
| 652 | const record: MutablePackageOverrideMap = {}; |
| 653 | if (typeof existing === "string") record["."] = existing; |
| 654 | parent[dependencyName] = record; |
| 655 | return record; |
| 656 | }; |
| 657 | |
| 658 | // Resolves the still-conflicted names inside `node`'s subtree, nesting only |
| 659 | // as deep as required to disambiguate. Names that stay ambiguous along an |
| 660 | // identical override path are left unpinned (npm overrides cannot express |
| 661 | // them); everything else is pinned exactly. |
| 662 | const resolveConflicts = ( |
| 663 | out: MutablePackageOverrideMap, |
| 664 | node: Node, |
| 665 | conflicted: ReadonlySet<string>, |
| 666 | path: ReadonlySet<unknown>, |
| 667 | ): void => { |
| 668 | const still = new Set<string>(); |
| 669 | const specs = specsOf(node); |
| 670 | for (const name of conflicted) { |
| 671 | const set = specs.get(name); |
| 672 | if (set === undefined) continue; |
| 673 | if (set.size === 1) { |
| 674 | const spec = [...set][0]!; |
| 675 | const existing = out[name]; |
| 676 | if (existing === undefined) out[name] = spec; |
| 677 | else if (typeof existing === "object" && existing["."] === undefined) { |
| 678 | existing["."] = spec; |
| 679 | } |
| 680 | } else { |
| 681 | still.add(name); |
| 682 | } |
| 683 | } |
| 684 | if (still.size === 0) return; |
| 685 | for (const edge of edgesOf(node)) { |
| 686 | // Pin the direct occurrence of a name that stays conflicted deeper down. |
| 687 | if (still.has(edge.dependencyName)) { |
| 688 | const record = asOverrideMap(out, edge.dependencyName); |
| 689 | if (record["."] === undefined) record["."] = edge.installSpec; |
| 690 | } |
| 691 | if (edge.node === undefined) continue; |
| 692 | const childId = nodeId(edge.node); |
| 693 | if (path.has(childId)) continue; |
| 694 | const childSpecs = specsOf(edge.node); |
| 695 | if (![...still].some((name) => childSpecs.has(name))) continue; |
| 696 | const record = asOverrideMap(out, edge.dependencyName); |
| 697 | if (record["."] === undefined) record["."] = edge.installSpec; |
| 698 | resolveConflicts(record, edge.node, still, new Set([...path, childId])); |
| 699 | } |
| 700 | }; |
| 701 | |
| 702 | for (const { node, rootSelector } of roots) { |
| 703 | const existing = overrides[rootSelector]; |
| 704 | const rootMap: MutablePackageOverrideMap = typeof existing === "object" ? existing : {}; |
| 705 | if (typeof existing === "string") rootMap["."] = existing; |
| 706 | const specs = specsOf(node); |
| 707 | if (specs.size === 0) continue; |
| 708 | overrides[rootSelector] = rootMap; |
| 709 | const conflicted = new Set<string>(); |
| 710 | for (const [name, set] of specs) { |
| 711 | if (set.size === 1) rootMap[name] = [...set][0]!; |
| 712 | else conflicted.add(name); |
| 713 | } |
| 714 | if (conflicted.size > 0) { |
| 715 | resolveConflicts(rootMap, node, conflicted, new Set([nodeId(node)])); |
| 716 | } |
| 717 | } |
| 718 | }; |
| 719 | |
| 720 | const parseLockedInstallPlan = (options: LockParseOptions): PackageInstallPlan => { |
| 721 | switch (options.name) { |
| 722 | case "package-lock.json": |
| 723 | return parsePackageLock(options); |
| 724 | case "pnpm-lock.yaml": |
| 725 | return parsePnpmLock(options); |
| 726 | case "bun.lock": |
| 727 | return parseBunLock(options); |
| 728 | case "yarn.lock": |
| 729 | return parseYarnLock(options); |
| 730 | default: |
| 731 | return { resolved: { ...options.resolved }, overrides: {} }; |
| 732 | } |
| 733 | }; |
| 734 | |
| 735 | const parsePackageLock = (options: { |
| 736 | readonly content: string; |
| 737 | readonly importer: string; |
| 738 | readonly candidates: ReadonlyArray<string>; |
| 739 | readonly packageJson: PackageJson; |
| 740 | readonly resolved: Readonly<Record<string, string>>; |
| 741 | }): PackageInstallPlan => { |
| 742 | const lockfile = asRecord(JSON.parse(options.content)); |
| 743 | const packages = asRecord(lockfile?.packages); |
| 744 | const dependencies = asRecord(lockfile?.dependencies); |
| 745 | const importerKey = options.importer === "." ? "" : options.importer; |
| 746 | const importer = asRecord(packages?.[importerKey]); |
| 747 | const resolved = { ...options.resolved }; |
| 748 | const overrides: MutablePackageOverrides = {}; |
| 749 | const roots: Array<LockedGraphRoot<string>> = []; |
| 750 | |
| 751 | for (const packageName of options.candidates) { |
| 752 | const importerSpec = dependencyValue(importer, packageName); |
| 753 | const declared = declaredPackageVersion(options.packageJson, packageName); |
| 754 | if (importerSpec !== undefined && declared !== undefined && importerSpec !== declared) { |
| 755 | continue; |
| 756 | } |
| 757 | |
| 758 | for (const packagePath of nodeModulesLookupPaths(importerKey, packageName)) { |
| 759 | const version = stringValue(asRecord(packages?.[packagePath])?.version); |
| 760 | if (version !== undefined) { |
| 761 | const entry = asRecord(packages?.[packagePath]); |
| 762 | resolved[packageName] = npmLockedInstallSpec(packageName, entry, version); |
| 763 | roots.push({ |
| 764 | node: packagePath, |
| 765 | rootSelector: `${stringValue(entry?.name) ?? packageName}@${version}`, |
| 766 | }); |
| 767 | break; |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | if (resolved[packageName] === options.resolved[packageName] && importerKey === "") { |
| 772 | const entry = asRecord(dependencies?.[packageName]); |
| 773 | const version = stringValue(entry?.version); |
| 774 | if (version !== undefined) { |
| 775 | resolved[packageName] = npmLockedInstallSpec(packageName, entry, version); |
| 776 | } |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | if (packages !== undefined) { |
| 781 | addLockedGraphOverrides( |
| 782 | overrides, |
| 783 | roots, |
| 784 | (packagePath) => packagePath, |
| 785 | (packagePath) => { |
| 786 | const value = packages[packagePath]; |
| 787 | const entry = asRecord(value); |
| 788 | if (entry === undefined) return []; |
| 789 | return Object.keys(dependencySpecifiers(entry)).flatMap( |
| 790 | (dependencyName): ReadonlyArray<LockedGraphDependency<string>> => { |
| 791 | const childPath = resolvePackageLockDependencyPath( |
| 792 | packages, |
| 793 | packagePath, |
| 794 | dependencyName, |
| 795 | ); |
| 796 | if (childPath === undefined) return []; |
| 797 | const child = asRecord(packages[childPath]); |
| 798 | const childVersion = stringValue(child?.version); |
| 799 | if (childVersion === undefined) return []; |
| 800 | return [ |
| 801 | { |
| 802 | dependencyName, |
| 803 | installSpec: npmLockedInstallSpec(dependencyName, child, childVersion), |
| 804 | node: childPath, |
| 805 | }, |
| 806 | ]; |
| 807 | }, |
| 808 | ); |
| 809 | }, |
| 810 | ); |
| 811 | } else if (dependencies !== undefined) { |
| 812 | addPackageLockV1Overrides(dependencies, overrides, options.candidates); |
| 813 | } |
| 814 | return { resolved, overrides }; |
| 815 | }; |
| 816 | |
| 817 | /** |
| 818 | * pnpm 12 writes `pnpm-lock.yaml` as multiple YAML documents: pnpm's own |
| 819 | * environment lock (`packageManagerDependencies`) first, then the project |
| 820 | * lockfile. The project lockfile is always the last document. |
| 821 | */ |
| 822 | const parsePnpmLockDocument = (content: string): unknown => { |
| 823 | const last = parseAllDocuments(content).at(-1); |
| 824 | if (last?.errors.length) throw last.errors[0]; |
| 825 | return last?.toJS(); |
| 826 | }; |
| 827 | |
| 828 | const parsePnpmLock = (options: { |
| 829 | readonly content: string; |
| 830 | readonly importer: string; |
| 831 | readonly candidates: ReadonlyArray<string>; |
| 832 | readonly packageJson: PackageJson; |
| 833 | readonly resolved: Readonly<Record<string, string>>; |
| 834 | }): PackageInstallPlan => { |
| 835 | const lockfile = asRecord(parsePnpmLockDocument(options.content)); |
| 836 | const importers = asRecord(lockfile?.importers); |
| 837 | const importerKey = options.importer === "" ? "." : options.importer; |
| 838 | const importer = |
| 839 | asRecord(importers?.[importerKey]) ?? (importerKey === "." ? lockfile : undefined); |
| 840 | const resolved = { ...options.resolved }; |
| 841 | const overrides: MutablePackageOverrides = {}; |
| 842 | const packages = asRecord(lockfile?.snapshots) ?? asRecord(lockfile?.packages) ?? {}; |
| 843 | const roots: Array<LockedGraphRoot<string>> = []; |
| 844 | |
| 845 | for (const packageName of options.candidates) { |
| 846 | const entry = dependencyEntry(importer, packageName); |
| 847 | const record = asRecord(entry); |
| 848 | const specifier = stringValue(record?.specifier); |
| 849 | const declared = declaredPackageVersion(options.packageJson, packageName); |
| 850 | if (specifier !== undefined && declared !== undefined && specifier !== declared) { |
| 851 | continue; |
| 852 | } |
| 853 | const rawVersion = typeof entry === "string" ? entry : stringValue(record?.version); |
| 854 | const installSpec = pnpmInstallSpec(packageName, rawVersion); |
| 855 | if (installSpec !== undefined) { |
| 856 | resolved[packageName] = installSpec; |
| 857 | const packageKey = findPnpmPackageKey(packages, packageName, rawVersion); |
| 858 | const root = packageKey === undefined ? undefined : parsePnpmPackageKey(packageKey); |
| 859 | if (packageKey !== undefined && root !== undefined) { |
| 860 | roots.push({ |
| 861 | node: packageKey, |
| 862 | rootSelector: `${root.name}@${root.version}`, |
| 863 | }); |
| 864 | } |
| 865 | } |
| 866 | } |
| 867 | |
| 868 | addLockedGraphOverrides( |
| 869 | overrides, |
| 870 | roots, |
| 871 | (packageKey) => packageKey, |
| 872 | (packageKey) => { |
| 873 | const value = packages[packageKey]; |
| 874 | const parent = parsePnpmPackageKey(packageKey); |
| 875 | const entry = asRecord(value); |
| 876 | if (parent === undefined || entry === undefined) return []; |
| 877 | return Object.entries(dependencySpecifiers(entry)).flatMap( |
| 878 | ([dependencyName, dependencyEntryValue]): ReadonlyArray<LockedGraphDependency<string>> => { |
| 879 | const rawVersion = |
| 880 | typeof dependencyEntryValue === "string" |
| 881 | ? dependencyEntryValue |
| 882 | : stringValue(asRecord(dependencyEntryValue)?.version); |
| 883 | const installSpec = pnpmInstallSpec(dependencyName, rawVersion); |
| 884 | if (installSpec === undefined) return []; |
| 885 | const childKey = findPnpmPackageKey(packages, dependencyName, rawVersion); |
| 886 | return [{ dependencyName, installSpec, node: childKey }]; |
| 887 | }, |
| 888 | ); |
| 889 | }, |
| 890 | ); |
| 891 | return { resolved, overrides }; |
| 892 | }; |
| 893 | |
| 894 | const parseBunLock = (options: { |
| 895 | readonly content: string; |
| 896 | readonly importer: string; |
| 897 | readonly candidates: ReadonlyArray<string>; |
| 898 | readonly packageJson: PackageJson; |
| 899 | readonly resolved: Readonly<Record<string, string>>; |
| 900 | }): PackageInstallPlan => { |
| 901 | const lockfile = asRecord(parseJsonc(options.content)); |
| 902 | const packages = asRecord(lockfile?.packages); |
| 903 | const workspaces = asRecord(lockfile?.workspaces); |
| 904 | const importerKey = options.importer === "." ? "" : options.importer; |
| 905 | const workspace = asRecord(workspaces?.[importerKey]); |
| 906 | const workspaceName = stringValue(workspace?.name); |
| 907 | const resolved = { ...options.resolved }; |
| 908 | const overrides: MutablePackageOverrides = {}; |
| 909 | const roots: Array<LockedGraphRoot<string>> = []; |
| 910 | if (packages === undefined) return { resolved, overrides }; |
| 911 | |
| 912 | for (const packageName of options.candidates) { |
| 913 | const declared = declaredPackageVersion(options.packageJson, packageName); |
| 914 | const workspaceSpecifier = dependencyValue(workspace, packageName); |
| 915 | if ( |
| 916 | declared === undefined || |
| 917 | workspaceSpecifier === undefined || |
| 918 | workspaceSpecifier !== declared |
| 919 | ) |
| 920 | continue; |
| 921 | const expectedName = npmAliasName(packageName, declared); |
| 922 | const direct = findBunPackageDescriptor( |
| 923 | packages, |
| 924 | [...(workspaceName === undefined ? [] : [`${workspaceName}/${packageName}`]), packageName], |
| 925 | expectedName, |
| 926 | ); |
| 927 | if (direct !== undefined) { |
| 928 | resolved[packageName] = lockedInstallSpec(packageName, direct.name, direct.version); |
| 929 | roots.push({ |
| 930 | node: direct.key, |
| 931 | rootSelector: `${direct.name}@${direct.version}`, |
| 932 | }); |
| 933 | } |
| 934 | } |
| 935 | |
| 936 | addLockedGraphOverrides( |
| 937 | overrides, |
| 938 | roots, |
| 939 | (packageKey) => packageKey, |
| 940 | (packageKey) => { |
| 941 | const value = packages[packageKey]; |
| 942 | const parent = parseBunPackageDescriptor(value); |
| 943 | const metadata = Array.isArray(value) ? asRecord(value[2]) : undefined; |
| 944 | if (parent === undefined || metadata === undefined) return []; |
| 945 | return Object.entries(dependencySpecifiers(metadata)).flatMap( |
| 946 | ([dependencyName, dependencySpecifier]): ReadonlyArray<LockedGraphDependency<string>> => { |
| 947 | if (typeof dependencySpecifier !== "string") return []; |
| 948 | const expectedName = npmAliasName(dependencyName, dependencySpecifier); |
| 949 | const child = findBunPackageDescriptor( |
| 950 | packages, |
| 951 | [`${packageKey}/${dependencyName}`, dependencyName], |
| 952 | expectedName, |
| 953 | ); |
| 954 | if (child === undefined) return []; |
| 955 | return [ |
| 956 | { |
| 957 | dependencyName, |
| 958 | installSpec: lockedInstallSpec(dependencyName, child.name, child.version), |
| 959 | node: child.key, |
| 960 | }, |
| 961 | ]; |
| 962 | }, |
| 963 | ); |
| 964 | }, |
| 965 | ); |
| 966 | return { resolved, overrides }; |
| 967 | }; |
| 968 | |
| 969 | const parseYarnLock = (options: { |
| 970 | readonly content: string; |
| 971 | readonly candidates: ReadonlyArray<string>; |
| 972 | readonly packageJson: PackageJson; |
| 973 | readonly resolved: Readonly<Record<string, string>>; |
| 974 | }): PackageInstallPlan => { |
| 975 | const entries = parseYarnEntries(options.content); |
| 976 | const resolved = { ...options.resolved }; |
| 977 | const overrides: MutablePackageOverrides = {}; |
| 978 | const roots: Array<LockedGraphRoot<YarnLockEntry>> = []; |
| 979 | for (const packageName of options.candidates) { |
| 980 | const specifier = declaredPackageVersion(options.packageJson, packageName); |
| 981 | if (specifier === undefined) continue; |
| 982 | const entry = findYarnEntry(entries, packageName, specifier); |
| 983 | if (entry !== undefined) { |
| 984 | const actualName = yarnResolutionName(entry.resolution) ?? packageName; |
| 985 | resolved[packageName] = lockedInstallSpec(packageName, actualName, entry.version); |
| 986 | roots.push({ |
| 987 | node: entry, |
| 988 | rootSelector: `${actualName}@${entry.version}`, |
| 989 | }); |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | addLockedGraphOverrides( |
| 994 | overrides, |
| 995 | roots, |
| 996 | (entry) => entry, |
| 997 | (entry) => |
| 998 | Object.entries(entry.dependencies).flatMap( |
| 999 | ([dependencyName, dependencySpecifier]): ReadonlyArray< |
| 1000 | LockedGraphDependency<YarnLockEntry> |
| 1001 | > => { |
| 1002 | const child = findYarnEntry(entries, dependencyName, dependencySpecifier); |
| 1003 | if (child === undefined) return []; |
| 1004 | const actualName = yarnResolutionName(child.resolution) ?? dependencyName; |
| 1005 | return [ |
| 1006 | { |
| 1007 | dependencyName, |
| 1008 | installSpec: lockedInstallSpec(dependencyName, actualName, child.version), |
| 1009 | node: child, |
| 1010 | }, |
| 1011 | ]; |
| 1012 | }, |
| 1013 | ), |
| 1014 | ); |
| 1015 | return { resolved, overrides }; |
| 1016 | }; |
| 1017 | |
| 1018 | const dependencySpecifiers = (entry: JsonRecord): JsonRecord => ({ |
| 1019 | ...asRecord(entry.dependencies), |
| 1020 | ...asRecord(entry.optionalDependencies), |
| 1021 | ...asRecord(entry.peerDependencies), |
| 1022 | }); |
| 1023 | |
| 1024 | const lockedInstallSpec = (dependencyName: string, actualName: string, version: string): string => |
| 1025 | actualName === dependencyName ? version : `npm:${actualName}@${version}`; |
| 1026 | |
| 1027 | const npmLockedInstallSpec = ( |
| 1028 | dependencyName: string, |
| 1029 | entry: JsonRecord | undefined, |
| 1030 | version: string, |
| 1031 | ): string => lockedInstallSpec(dependencyName, stringValue(entry?.name) ?? dependencyName, version); |
| 1032 | |
| 1033 | const resolvePackageLockDependencyPath = ( |
| 1034 | packages: JsonRecord, |
| 1035 | packagePath: string, |
| 1036 | dependencyName: string, |
| 1037 | ): string | undefined => { |
| 1038 | let current = packagePath; |
| 1039 | while (true) { |
| 1040 | const candidate = `${current}/node_modules/${dependencyName}`; |
| 1041 | if (packages[candidate] !== undefined) return candidate; |
| 1042 | const marker = current.lastIndexOf("/node_modules/"); |
| 1043 | if (marker === -1) break; |
| 1044 | current = current.slice(0, marker); |
| 1045 | } |
| 1046 | const rootCandidate = `node_modules/${dependencyName}`; |
| 1047 | return packages[rootCandidate] === undefined ? undefined : rootCandidate; |
| 1048 | }; |
| 1049 | |
| 1050 | const addPackageLockV1Overrides = ( |
| 1051 | dependencies: JsonRecord, |
| 1052 | overrides: MutablePackageOverrides, |
| 1053 | rootNames: ReadonlyArray<string>, |
| 1054 | ): void => { |
| 1055 | type Node = { |
| 1056 | readonly entry: JsonRecord; |
| 1057 | readonly scopes: ReadonlyArray<JsonRecord>; |
| 1058 | }; |
| 1059 | const roots = rootNames.flatMap((rootName): ReadonlyArray<LockedGraphRoot<Node>> => { |
| 1060 | const entry = asRecord(dependencies[rootName]); |
| 1061 | const version = stringValue(entry?.version); |
| 1062 | return entry === undefined || version === undefined |
| 1063 | ? [] |
| 1064 | : [ |
| 1065 | { |
| 1066 | node: { entry, scopes: [dependencies] }, |
| 1067 | rootSelector: `${stringValue(entry.name) ?? rootName}@${version}`, |
| 1068 | }, |
| 1069 | ]; |
| 1070 | }); |
| 1071 | addLockedGraphOverrides( |
| 1072 | overrides, |
| 1073 | roots, |
| 1074 | ({ entry }) => entry, |
| 1075 | ({ entry, scopes }) => { |
| 1076 | const nested = asRecord(entry.dependencies) ?? {}; |
| 1077 | const requires = asRecord(entry.requires) ?? {}; |
| 1078 | return Object.keys(requires).flatMap( |
| 1079 | (dependencyName): ReadonlyArray<LockedGraphDependency<Node>> => { |
| 1080 | const child = [nested, ...scopes] |
| 1081 | .map((scope) => asRecord(scope[dependencyName])) |
| 1082 | .find((candidate) => candidate !== undefined); |
| 1083 | const version = stringValue(child?.version); |
| 1084 | if (child === undefined || version === undefined) return []; |
| 1085 | return [ |
| 1086 | { |
| 1087 | dependencyName, |
| 1088 | installSpec: npmLockedInstallSpec(dependencyName, child, version), |
| 1089 | node: { entry: child, scopes: [nested, ...scopes] }, |
| 1090 | }, |
| 1091 | ]; |
| 1092 | }, |
| 1093 | ); |
| 1094 | }, |
| 1095 | ); |
| 1096 | }; |
| 1097 | |
| 1098 | const pnpmInstallSpec = ( |
| 1099 | dependencyName: string, |
| 1100 | rawVersion: string | undefined, |
| 1101 | ): string | undefined => { |
| 1102 | if ( |
| 1103 | rawVersion === undefined || |
| 1104 | rawVersion.startsWith("link:") || |
| 1105 | rawVersion.startsWith("workspace:") || |
| 1106 | rawVersion.startsWith("file:") |
| 1107 | ) { |
| 1108 | return undefined; |
| 1109 | } |
| 1110 | let version = rawVersion.startsWith("/") ? rawVersion.slice(1) : rawVersion; |
| 1111 | const peerSuffix = version.indexOf("("); |
| 1112 | if (peerSuffix !== -1) version = version.slice(0, peerSuffix); |
| 1113 | if (version.startsWith("npm:")) { |
| 1114 | const descriptor = parsePackageDescriptor(version.slice("npm:".length)); |
| 1115 | return descriptor === undefined |
| 1116 | ? undefined |
| 1117 | : lockedInstallSpec(dependencyName, descriptor.name, descriptor.version); |
| 1118 | } |
| 1119 | if (version.startsWith(`${dependencyName}@`)) { |
| 1120 | version = version.slice(dependencyName.length + 1); |
| 1121 | } |
| 1122 | return version; |
| 1123 | }; |
| 1124 | |
| 1125 | const findPnpmPackageKey = ( |
| 1126 | packages: JsonRecord, |
| 1127 | dependencyName: string, |
| 1128 | rawVersion: string | undefined, |
| 1129 | ): string | undefined => { |
| 1130 | if (rawVersion === undefined) return undefined; |
| 1131 | let version = rawVersion.startsWith("/") ? rawVersion.slice(1) : rawVersion; |
| 1132 | let actualName = dependencyName; |
| 1133 | if (version.startsWith("npm:")) { |
| 1134 | const descriptor = parsePackageDescriptor(version.slice("npm:".length)); |
| 1135 | if (descriptor === undefined) return undefined; |
| 1136 | actualName = descriptor.name; |
| 1137 | version = descriptor.version; |
| 1138 | } else if (version.startsWith(`${dependencyName}@`)) { |
| 1139 | version = version.slice(dependencyName.length + 1); |
| 1140 | } |
| 1141 | const candidate = `${actualName}@${version}`; |
| 1142 | if (packages[candidate] !== undefined) return candidate; |
| 1143 | const legacyCandidate = `/${candidate}`; |
| 1144 | return packages[legacyCandidate] === undefined ? undefined : legacyCandidate; |
| 1145 | }; |
| 1146 | |
| 1147 | const parsePnpmPackageKey = (packageKey: string): { name: string; version: string } | undefined => { |
| 1148 | let descriptor = packageKey.startsWith("/") ? packageKey.slice(1) : packageKey; |
| 1149 | const peerSuffix = descriptor.indexOf("("); |
| 1150 | if (peerSuffix !== -1) descriptor = descriptor.slice(0, peerSuffix); |
| 1151 | return parsePackageDescriptor(descriptor); |
| 1152 | }; |
| 1153 | |
| 1154 | const parsePackageDescriptor = ( |
| 1155 | descriptor: string, |
| 1156 | ): { name: string; version: string } | undefined => { |
| 1157 | const separator = descriptor.lastIndexOf("@"); |
| 1158 | if (separator <= 0 || separator === descriptor.length - 1) return undefined; |
| 1159 | return { |
| 1160 | name: descriptor.slice(0, separator), |
| 1161 | version: descriptor.slice(separator + 1), |
| 1162 | }; |
| 1163 | }; |
| 1164 | |
| 1165 | const npmAliasName = (dependencyName: string, specifier: string): string => { |
| 1166 | if (!specifier.startsWith("npm:")) return dependencyName; |
| 1167 | return parsePackageDescriptor(specifier.slice("npm:".length))?.name ?? dependencyName; |
| 1168 | }; |
| 1169 | |
| 1170 | const findBunPackageDescriptor = ( |
| 1171 | packages: JsonRecord, |
| 1172 | candidateKeys: ReadonlyArray<string>, |
| 1173 | expectedName: string, |
| 1174 | ): { key: string; name: string; version: string } | undefined => { |
| 1175 | for (const candidateKey of candidateKeys) { |
| 1176 | const descriptor = parseBunPackageDescriptor(packages[candidateKey]); |
| 1177 | if (descriptor?.name === expectedName) return { key: candidateKey, ...descriptor }; |
| 1178 | } |
| 1179 | const matches = Object.entries(packages) |
| 1180 | .map(([key, value]) => { |
| 1181 | const descriptor = parseBunPackageDescriptor(value); |
| 1182 | return descriptor === undefined ? undefined : { key, ...descriptor }; |
| 1183 | }) |
| 1184 | .filter( |
| 1185 | (entry): entry is { key: string; name: string; version: string } => |
| 1186 | entry?.name === expectedName, |
| 1187 | ); |
| 1188 | return matches.length === 1 ? matches[0] : undefined; |
| 1189 | }; |
| 1190 | |
| 1191 | interface YarnLockEntry { |
| 1192 | readonly selectors: ReadonlyArray<string>; |
| 1193 | readonly version: string; |
| 1194 | readonly resolution?: string; |
| 1195 | readonly dependencies: Readonly<Record<string, string>>; |
| 1196 | } |
| 1197 | |
| 1198 | /** |
| 1199 | * Parses a yarn lockfile into a top-level record. Yarn berry lockfiles are |
| 1200 | * valid YAML; the frozen v1 format (`key "value"` pairs without colons) gets |
| 1201 | * a small dedicated parser so no yarn dependency is required. |
| 1202 | */ |
| 1203 | const parseYarnLockfile = (content: string): JsonRecord => { |
| 1204 | if (!content.includes("# yarn lockfile v1")) { |
| 1205 | try { |
| 1206 | const parsed = asRecord(parseYaml(content)); |
| 1207 | if (parsed !== undefined) return parsed; |
| 1208 | } catch { |
| 1209 | // Fall through to the v1 parser for YAML-incompatible files. |
| 1210 | } |
| 1211 | } |
| 1212 | return parseYarnV1Lockfile(content); |
| 1213 | }; |
| 1214 | |
| 1215 | const parseYarnV1Lockfile = (content: string): JsonRecord => { |
| 1216 | const root: JsonRecord = {}; |
| 1217 | const stack: Array<{ indent: number; node: JsonRecord }> = [{ indent: -1, node: root }]; |
| 1218 | for (const rawLine of content.split("\n")) { |
| 1219 | const line = rawLine.replace(/\r$/, ""); |
| 1220 | const text = line.trim(); |
| 1221 | if (text === "" || text.startsWith("#")) continue; |
| 1222 | const indent = line.length - line.trimStart().length; |
| 1223 | while (stack.length > 1 && indent <= stack[stack.length - 1]!.indent) { |
| 1224 | stack.pop(); |
| 1225 | } |
| 1226 | const parent = stack[stack.length - 1]!.node; |
| 1227 | if (text.endsWith(":")) { |
| 1228 | // Block header: an entry selector list or a nested map like |
| 1229 | // `dependencies:`. Individual selectors may be quoted. |
| 1230 | const key = text |
| 1231 | .slice(0, -1) |
| 1232 | .split(",") |
| 1233 | .map((selector) => stripYarnQuotes(selector.trim())) |
| 1234 | .join(", "); |
| 1235 | const child: JsonRecord = {}; |
| 1236 | parent[key] = child; |
| 1237 | stack.push({ indent, node: child }); |
| 1238 | } else { |
| 1239 | // `key "value"` pair; the key itself may be quoted (scoped packages). |
| 1240 | let key: string; |
| 1241 | let rest: string; |
| 1242 | if (text.startsWith('"')) { |
| 1243 | const end = text.indexOf('"', 1); |
| 1244 | if (end === -1) continue; |
| 1245 | key = text.slice(1, end); |
| 1246 | rest = text.slice(end + 1).trim(); |
| 1247 | } else { |
| 1248 | const separator = text.indexOf(" "); |
| 1249 | if (separator === -1) continue; |
| 1250 | key = text.slice(0, separator); |
| 1251 | rest = text.slice(separator + 1).trim(); |
| 1252 | } |
| 1253 | parent[key] = stripYarnQuotes(rest); |
| 1254 | } |
| 1255 | } |
| 1256 | return root; |
| 1257 | }; |
| 1258 | |
| 1259 | const stripYarnQuotes = (value: string): string => |
| 1260 | value.startsWith('"') && value.endsWith('"') && value.length >= 2 ? value.slice(1, -1) : value; |
| 1261 | |
| 1262 | const parseYarnEntries = (content: string): ReadonlyArray<YarnLockEntry> => |
| 1263 | Object.entries(parseYarnLockfile(content)).flatMap( |
| 1264 | ([selectorList, value]): ReadonlyArray<YarnLockEntry> => { |
| 1265 | if (selectorList === "__metadata") return []; |
| 1266 | const entry = asRecord(value); |
| 1267 | const version = stringValue(entry?.version); |
| 1268 | if (version === undefined) return []; |
| 1269 | const dependencies = Object.fromEntries( |
| 1270 | Object.entries({ |
| 1271 | ...asRecord(entry?.dependencies), |
| 1272 | ...asRecord(entry?.optionalDependencies), |
| 1273 | }).filter((item): item is [string, string] => typeof item[1] === "string"), |
| 1274 | ); |
| 1275 | return [ |
| 1276 | { |
| 1277 | selectors: selectorList.split(",").map((selector) => selector.trim()), |
| 1278 | version, |
| 1279 | resolution: stringValue(entry?.resolution), |
| 1280 | dependencies, |
| 1281 | }, |
| 1282 | ]; |
| 1283 | }, |
| 1284 | ); |
| 1285 | |
| 1286 | const findYarnEntry = ( |
| 1287 | entries: ReadonlyArray<YarnLockEntry>, |
| 1288 | dependencyName: string, |
| 1289 | specifier: string, |
| 1290 | ): YarnLockEntry | undefined => { |
| 1291 | const expected = `${dependencyName}@${specifier}`; |
| 1292 | const berryExpected = specifier.startsWith("npm:") |
| 1293 | ? expected |
| 1294 | : `${dependencyName}@npm:${specifier}`; |
| 1295 | return entries.find((entry) => |
| 1296 | entry.selectors.some((selector) => selector === expected || selector === berryExpected), |
| 1297 | ); |
| 1298 | }; |
| 1299 | |
| 1300 | const yarnResolutionName = (resolution: string | undefined): string | undefined => { |
| 1301 | if (resolution === undefined) return undefined; |
| 1302 | const npmMarker = resolution.indexOf("@npm:"); |
| 1303 | return npmMarker === -1 ? undefined : resolution.slice(0, npmMarker); |
| 1304 | }; |
| 1305 | |
| 1306 | const dependencyEntry = (importer: JsonRecord | undefined, packageName: string): unknown => |
| 1307 | asRecord(importer?.dependencies)?.[packageName] ?? |
| 1308 | asRecord(importer?.optionalDependencies)?.[packageName] ?? |
| 1309 | asRecord(importer?.devDependencies)?.[packageName]; |
| 1310 | |
| 1311 | const dependencyValue = ( |
| 1312 | importer: JsonRecord | undefined, |
| 1313 | packageName: string, |
| 1314 | ): string | undefined => stringValue(dependencyEntry(importer, packageName)); |
| 1315 | |
| 1316 | const declaredPackageVersion = ( |
| 1317 | packageJson: PackageJson, |
| 1318 | packageName: string, |
| 1319 | ): string | undefined => |
| 1320 | packageJson.dependencies?.[packageName] ?? |
| 1321 | packageJson.optionalDependencies?.[packageName] ?? |
| 1322 | packageJson.devDependencies?.[packageName]; |
| 1323 | |
| 1324 | const nodeModulesLookupPaths = (importer: string, packageName: string): ReadonlyArray<string> => { |
| 1325 | const paths: string[] = []; |
| 1326 | let current = importer; |
| 1327 | while (true) { |
| 1328 | paths.push( |
| 1329 | current === "" ? `node_modules/${packageName}` : `${current}/node_modules/${packageName}`, |
| 1330 | ); |
| 1331 | if (current === "") break; |
| 1332 | const separator = current.lastIndexOf("/"); |
| 1333 | current = separator === -1 ? "" : current.slice(0, separator); |
| 1334 | } |
| 1335 | return paths; |
| 1336 | }; |
| 1337 | |
| 1338 | const parseBunPackageDescriptor = ( |
| 1339 | value: unknown, |
| 1340 | ): { name: string; version: string } | undefined => { |
| 1341 | if (!Array.isArray(value) || typeof value[0] !== "string") { |
| 1342 | return undefined; |
| 1343 | } |
| 1344 | return parsePackageDescriptor(value[0]); |
| 1345 | }; |
| 1346 | |
| 1347 | /** |
| 1348 | * Parses `bun.lock` JSONC (comments + trailing commas) without relying on the |
| 1349 | * Bun runtime, so lockfile pinning also works when alchemy runs under Node. |
| 1350 | */ |
| 1351 | const parseJsonc = (content: string): unknown => JSON.parse(stripJsonc(content)); |
| 1352 | |
| 1353 | const stripJsonc = (content: string): string => { |
| 1354 | let out = ""; |
| 1355 | let i = 0; |
| 1356 | const length = content.length; |
| 1357 | while (i < length) { |
| 1358 | const char = content[i]!; |
| 1359 | if (char === '"') { |
| 1360 | out += char; |
| 1361 | i++; |
| 1362 | while (i < length) { |
| 1363 | const stringChar = content[i]!; |
| 1364 | out += stringChar; |
| 1365 | i++; |
| 1366 | if (stringChar === "\\") { |
| 1367 | if (i < length) { |
| 1368 | out += content[i]; |
| 1369 | i++; |
| 1370 | } |
| 1371 | } else if (stringChar === '"') { |
| 1372 | break; |
| 1373 | } |
| 1374 | } |
| 1375 | continue; |
| 1376 | } |
| 1377 | if (char === "/" && content[i + 1] === "/") { |
| 1378 | while (i < length && content[i] !== "\n") i++; |
| 1379 | continue; |
| 1380 | } |
| 1381 | if (char === "/" && content[i + 1] === "*") { |
| 1382 | i += 2; |
| 1383 | while (i < length && !(content[i] === "*" && content[i + 1] === "/")) i++; |
| 1384 | i += 2; |
| 1385 | continue; |
| 1386 | } |
| 1387 | if (char === ",") { |
| 1388 | // Drop the comma when the next significant token closes the container. |
| 1389 | let j = i + 1; |
| 1390 | while (j < length) { |
| 1391 | const nextChar = content[j]!; |
| 1392 | if (nextChar === "/" && content[j + 1] === "/") { |
| 1393 | while (j < length && content[j] !== "\n") j++; |
| 1394 | } else if (nextChar === "/" && content[j + 1] === "*") { |
| 1395 | j += 2; |
| 1396 | while (j < length && !(content[j] === "*" && content[j + 1] === "/")) j++; |
| 1397 | j += 2; |
| 1398 | } else if ( |
| 1399 | nextChar === " " || |
| 1400 | nextChar === "\t" || |
| 1401 | nextChar === "\n" || |
| 1402 | nextChar === "\r" |
| 1403 | ) { |
| 1404 | j++; |
| 1405 | } else { |
| 1406 | break; |
| 1407 | } |
| 1408 | } |
| 1409 | if (content[j] === "}" || content[j] === "]") { |
| 1410 | i++; |
| 1411 | continue; |
| 1412 | } |
| 1413 | out += char; |
| 1414 | i++; |
| 1415 | continue; |
| 1416 | } |
| 1417 | out += char; |
| 1418 | i++; |
| 1419 | } |
| 1420 | return out; |
| 1421 | }; |
| 1422 | |
| 1423 | const asRecord = (value: unknown): JsonRecord | undefined => |
| 1424 | typeof value === "object" && value !== null && !Array.isArray(value) |
| 1425 | ? (value as JsonRecord) |
| 1426 | : undefined; |
| 1427 | |
| 1428 | const stringValue = (value: unknown): string | undefined => |
| 1429 | typeof value === "string" ? value : undefined; |
| 1430 | |
| 1431 | const resolveCatalogVersion = (cwd: string, packageName: string, version: string) => |
| 1432 | Effect.gen(function* () { |
| 1433 | const fs = yield* FileSystem.FileSystem; |
| 1434 | const workspacePath = yield* findUp(cwd, ["pnpm-workspace.yaml"]); |
| 1435 | if (workspacePath !== undefined) { |
| 1436 | const content = yield* fs.readFileString(workspacePath); |
| 1437 | const workspace = parseYaml(content) as CatalogSource; |
| 1438 | const resolved = resolveCatalogEntry(packageName, version, workspace); |
| 1439 | if (resolved === undefined) { |
| 1440 | return yield* BundleError.make({ |
| 1441 | message: `Could not resolve catalog version for '${packageName}' (${version}) from ${workspacePath}. Pin an npm-compatible version explicitly.`, |
| 1442 | }); |
| 1443 | } |
| 1444 | return resolved; |
| 1445 | } |
| 1446 | |
| 1447 | const bunResolved = yield* resolveBunCatalogVersion(cwd, packageName, version); |
| 1448 | if (bunResolved !== undefined) { |
| 1449 | return bunResolved; |
| 1450 | } |
| 1451 | |
| 1452 | return yield* BundleError.make({ |
| 1453 | message: `Could not resolve catalog version for '${packageName}' (${version}): no pnpm-workspace.yaml or Bun catalog found. Pin an npm-compatible version explicitly.`, |
| 1454 | }); |
| 1455 | }); |
| 1456 | |
| 1457 | const findUp = ( |
| 1458 | cwd: string, |
| 1459 | filenames: ReadonlyArray<string>, |
| 1460 | ): Effect.Effect<string | undefined, BundleError, FileSystem.FileSystem | Path.Path> => |
| 1461 | Effect.gen(function* () { |
| 1462 | const fs = yield* FileSystem.FileSystem; |
| 1463 | const path = yield* Path.Path; |
| 1464 | for (const filename of filenames) { |
| 1465 | const candidate = path.join(cwd, filename); |
| 1466 | if (yield* fs.exists(candidate).pipe(Effect.mapError(toBundleError))) { |
| 1467 | return candidate; |
| 1468 | } |
| 1469 | } |
| 1470 | const parent = path.dirname(cwd); |
| 1471 | if (parent === cwd) { |
| 1472 | return undefined; |
| 1473 | } |
| 1474 | return yield* findUp(parent, filenames); |
| 1475 | }); |
| 1476 | |
| 1477 | const readNearestLockfileFingerprint = ( |
| 1478 | cwd: string, |
| 1479 | ): Effect.Effect< |
| 1480 | PackageInstallIdentity["lockfile"], |
| 1481 | BundleError, |
| 1482 | FileSystem.FileSystem | Path.Path |
| 1483 | > => |
| 1484 | Effect.gen(function* () { |
| 1485 | const fs = yield* FileSystem.FileSystem; |
| 1486 | const path = yield* Path.Path; |
| 1487 | const lockfilePath = yield* findUp(cwd, lockfileNames); |
| 1488 | if (lockfilePath === undefined) { |
| 1489 | return undefined; |
| 1490 | } |
| 1491 | const content = yield* fs.readFile(lockfilePath); |
| 1492 | return { |
| 1493 | name: path.basename(lockfilePath), |
| 1494 | hash: yield* sha256(content), |
| 1495 | }; |
| 1496 | }).pipe( |
| 1497 | Effect.mapError((cause) => |
| 1498 | BundleError.make({ |
| 1499 | message: `Failed to read package-manager lockfile for Lambda externals from '${cwd}'`, |
| 1500 | cause, |
| 1501 | }), |
| 1502 | ), |
| 1503 | ); |
| 1504 | |
| 1505 | const resolveBunCatalogVersion = (cwd: string, packageName: string, version: string) => |
| 1506 | Effect.gen(function* () { |
| 1507 | const fs = yield* FileSystem.FileSystem; |
| 1508 | const path = yield* Path.Path; |
| 1509 | let currentDir = cwd; |
| 1510 | while (true) { |
| 1511 | const packagePath = path.join(currentDir, "package.json"); |
| 1512 | if (yield* fs.exists(packagePath)) { |
| 1513 | const content = yield* fs.readFileString(packagePath); |
| 1514 | const manifest = JSON.parse(content) as PackageJson; |
| 1515 | const source = parseBunCatalogSource(manifest); |
| 1516 | if (source !== undefined) { |
| 1517 | const resolved = resolveCatalogEntry(packageName, version, source); |
| 1518 | if (resolved === undefined) { |
| 1519 | return yield* BundleError.make({ |
| 1520 | message: `Could not resolve catalog version for '${packageName}' (${version}) from ${packagePath}. Pin an npm-compatible version explicitly.`, |
| 1521 | }); |
| 1522 | } |
| 1523 | return resolved; |
| 1524 | } |
| 1525 | } |
| 1526 | |
| 1527 | const parent = path.dirname(currentDir); |
| 1528 | if (parent === currentDir) { |
| 1529 | return undefined; |
| 1530 | } |
| 1531 | currentDir = parent; |
| 1532 | } |
| 1533 | }); |
| 1534 | |
| 1535 | const parseBunCatalogSource = (manifest: PackageJson): CatalogSource | undefined => { |
| 1536 | const workspaceSource = parseBunWorkspacesCatalogSource(manifest.workspaces); |
| 1537 | const catalog = workspaceSource?.catalog ?? manifest.catalog; |
| 1538 | const catalogs = |
| 1539 | manifest.catalogs !== undefined || workspaceSource?.catalogs !== undefined |
| 1540 | ? { ...manifest.catalogs, ...workspaceSource?.catalogs } |
| 1541 | : undefined; |
| 1542 | return catalog !== undefined || catalogs !== undefined ? { catalog, catalogs } : undefined; |
| 1543 | }; |
| 1544 | |
| 1545 | const parseBunWorkspacesCatalogSource = (workspaces: unknown): CatalogSource | undefined => { |
| 1546 | if (typeof workspaces !== "object" || workspaces === null || Array.isArray(workspaces)) { |
| 1547 | return undefined; |
| 1548 | } |
| 1549 | const record = workspaces as PackageJson; |
| 1550 | if (record.catalog === undefined && record.catalogs === undefined) { |
| 1551 | return undefined; |
| 1552 | } |
| 1553 | return { |
| 1554 | catalog: record.catalog, |
| 1555 | catalogs: record.catalogs, |
| 1556 | }; |
| 1557 | }; |
| 1558 | |
| 1559 | const resolveCatalogEntry = ( |
| 1560 | packageName: string, |
| 1561 | version: string, |
| 1562 | source: CatalogSource, |
| 1563 | ): string | undefined => { |
| 1564 | const catalogName = version.slice("catalog:".length).trim(); |
| 1565 | let catalog: Record<string, string> | undefined; |
| 1566 | if (catalogName === "" || catalogName === "default") { |
| 1567 | catalog = source.catalog ?? source.catalogs?.default; |
| 1568 | } else { |
| 1569 | catalog = source.catalogs?.[catalogName]; |
| 1570 | } |
| 1571 | return catalog?.[packageName]; |
| 1572 | }; |
| 1573 | |
| 1574 | const readArtifactFiles = (directory: string) => |
| 1575 | Effect.gen(function* () { |
| 1576 | const fs = yield* FileSystem.FileSystem; |
| 1577 | const path = yield* Path.Path; |
| 1578 | const relativePaths = yield* fs.readDirectory(directory, { |
| 1579 | recursive: true, |
| 1580 | }); |
| 1581 | const files: InstalledPackageFile[] = []; |
| 1582 | for (const relativePath of [...relativePaths].sort((a, b) => a.localeCompare(b))) { |
| 1583 | const absolutePath = path.join(directory, relativePath); |
| 1584 | const linkTarget = yield* fs |
| 1585 | .readLink(absolutePath) |
| 1586 | .pipe(Effect.orElseSucceed(() => undefined)); |
| 1587 | if (linkTarget !== undefined) { |
| 1588 | files.push({ |
| 1589 | path: relativePath.replaceAll("\\", "/"), |
| 1590 | content: yield* Effect.sync(() => new TextEncoder().encode(linkTarget)), |
| 1591 | mode: symbolicLinkMode, |
| 1592 | }); |
| 1593 | continue; |
| 1594 | } |
| 1595 | const stat = yield* fs.stat(absolutePath); |
| 1596 | if (stat.type !== "File") continue; |
| 1597 | files.push({ |
| 1598 | path: relativePath.replaceAll("\\", "/"), |
| 1599 | content: yield* fs.readFile(absolutePath), |
| 1600 | mode: stat.mode, |
| 1601 | }); |
| 1602 | } |
| 1603 | return files; |
| 1604 | }).pipe( |
| 1605 | Effect.mapError((cause) => |
| 1606 | BundleError.make({ |
| 1607 | message: "Failed to read installed Lambda external packages", |
| 1608 | cause, |
| 1609 | }), |
| 1610 | ), |
| 1611 | ); |
| 1612 | |
| 1613 | function toBundleError(cause: unknown): BundleError { |
| 1614 | return Schema.is(BundleError)(cause) |
| 1615 | ? cause |
| 1616 | : BundleError.make({ |
| 1617 | message: cause instanceof Error ? cause.message : String(cause), |
| 1618 | cause, |
| 1619 | }); |
| 1620 | } |