@exodus/stasis 1.0.0-beta.12 → 1.0.0-beta.14

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.
@@ -15,6 +15,7 @@ import {
15
15
  } from './resolve-typescript.js'
16
16
  import { diskHost } from '@exodus/stasis-core/host'
17
17
  import { createNodeResolver } from './resolve-node.js'
18
+ import { untouchedMemo } from './vfs-bundle/lazy.js'
18
19
 
19
20
  // Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
20
21
  // redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
@@ -141,15 +142,24 @@ function matchRedirect(map, relPath) {
141
142
  return undefined
142
143
  }
143
144
 
145
+ // What readJson gives for each manifest a resolver reads, read once, as for a tree that holds still:
146
+ // but one whose reading read what a lazy tree does not hold yet (`host.touches`) read again, or with
147
+ // `host.retouch` taken as read again (untouchedMemo's). Each resolver reads its own, so a build on the
148
+ // disk reads each manifest as it is then.
149
+ function manifestReader(host) {
150
+ const manifests = untouchedMemo(host.touches, { retouch: host.retouch })
151
+ return (path) => manifests(path, () => readJson(path, host))
152
+ }
153
+
144
154
  // The package.json closest to `path` as Metro finds a module's package (getPackageForModule, through
145
155
  // metro-file-map's hierarchicalLookup): at the path itself where it is a directory, else above it,
146
156
  // none past a `node_modules` segment. A nested package.json (`dist/esm/package.json`, or a subpath
147
- // directory's own) is one. -> { pkgDir, pkg } or null
148
- function metroPackageScope(path, host) {
157
+ // directory's own) is one, read by `read`. -> { pkgDir, pkg } or null
158
+ function metroPackageScope(path, host, read = readJson) {
149
159
  for (let dir = isDir(path, host) ? path : dirname(path); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
150
160
  const pkgPath = join(dir, 'package.json')
151
161
  if (isFile(pkgPath, host)) {
152
- const pkg = readJson(pkgPath, host)
162
+ const pkg = read(pkgPath, host)
153
163
  if (pkg) return { pkgDir: dir, pkg }
154
164
  }
155
165
  if (dirname(dir) === dir) break
@@ -162,7 +172,7 @@ function metroPackageScope(path, host) {
162
172
  // taken as package-relative, as Metro takes it, even where it names another package.
163
173
  // -> the path, redirected where the map says so, or false (an empty module)
164
174
  function metroRedirect(path, opts) {
165
- const scope = metroPackageScope(path, opts.host)
175
+ const scope = metroPackageScope(path, opts.host, opts.read)
166
176
  if (!scope) return path
167
177
  const rel = path === scope.pkgDir ? '' : toPosix(relative(scope.pkgDir, path))
168
178
  const r = matchRedirect(mergeRedirectMap(scope.pkg, opts.mainFields), `./${rel}`)
@@ -179,15 +189,18 @@ function parseBare(spec) {
179
189
  return { name: parts.slice(0, n).join('/'), firstPart: parts[0], subpath: parts.length > n ? `./${parts.slice(n).join('/')}` : '.' }
180
190
  }
181
191
 
182
- // Metro's default assetExts and assetResolutions (metro-config's defaults).
192
+ // Metro's default sourceExts, in the order its resolver probes them, and its default assetExts and
193
+ // assetResolutions (metro-config's defaults).
194
+ export const METRO_SOURCE_EXTS = ['js', 'jsx', 'json', 'ts', 'tsx']
183
195
  export const METRO_ASSET_EXTS = new Set(['bmp', 'gif', 'jpg', 'jpeg', 'png', 'psd', 'svg', 'webp', 'xml', 'm4v', 'mov', 'mp4', 'mpeg', 'mpg', 'webm', 'aac', 'aiff', 'caf', 'm4a', 'mp3', 'wav', 'html', 'pdf', 'yaml', 'yml', 'otf', 'ttf', 'zip'])
184
196
  const METRO_ASSET_RESOLUTIONS = ['1', '1.5', '2', '3', '4']
185
197
 
186
- // Metro's isAssetFile: any of the file name's dot-suffixes (`png`, or `tar.gz` and `gz`) an asset extension.
187
- function isMetroAssetFile(path) {
198
+ // Metro's isAssetFile: any of the file name's dot-suffixes (`png`, or `tar.gz` and `gz`) one of
199
+ // `assetExts` (Metro's defaults, else the project's).
200
+ export function isMetroAssetFile(path, assetExts = METRO_ASSET_EXTS) {
188
201
  const name = basename(path)
189
202
  for (let i = name.length - 1; i >= 0; i--) {
190
- if (name[i] === '.' && METRO_ASSET_EXTS.has(name.slice(i + 1))) return true
203
+ if (name[i] === '.' && assetExts.has(name.slice(i + 1))) return true
191
204
  }
192
205
  return false
193
206
  }
@@ -306,6 +319,15 @@ function metroExportsMap(exportsField) {
306
319
  return keys.some((key) => key.startsWith('.')) ? null : new Map([['.', flat]])
307
320
  }
308
321
 
322
+ // metroExportsMap of each `exports` object, as each resolver's manifests hold one (manifestReader),
323
+ // made once: a package's many imports each read it.
324
+ const exportsMaps = new WeakMap()
325
+ function metroExportsMapOf(exportsField) {
326
+ if (exportsField === null || typeof exportsField !== 'object') return metroExportsMap(exportsField)
327
+ if (!exportsMaps.has(exportsField)) exportsMaps.set(exportsField, metroExportsMap(exportsField))
328
+ return exportsMaps.get(exportsField)
329
+ }
330
+
309
331
  // Metro's relative specifier (isRelativeImport): `.`, `..`, or one starting `./` or `../`.
310
332
  const METRO_RELATIVE = /^\.\.?(?:\/|$)/u
311
333
 
@@ -323,12 +345,12 @@ function resolveSourceFile(base, opts) {
323
345
  // outright by falling back to a different index. The probe below still refuses a literal hit.
324
346
  base = stripTypeDeclaration(base)
325
347
  // Metro resolves an asset by its own rule, scale variants and all, not as a source file.
326
- if (opts.metro && isMetroAssetFile(base)) return metroAsset(base, opts.host)
348
+ if (opts.metro && isMetroAssetFile(base, opts.assetExts)) return metroAsset(base, opts.host)
327
349
  // Candidates share base's directory, hence its package scope; resolve it lazily, once.
328
350
  let scope
329
351
  const redirectCandidate = (p) => {
330
352
  if (scope === undefined) {
331
- const pkg = nearestPackage(base, opts.host)
353
+ const pkg = nearestPackage(base, opts.host, opts.read)
332
354
  scope = pkg ? { pkgDir: pkg.pkgDir, map: mergeRedirectMap(pkg.pkg, opts.mainFields) } : null
333
355
  }
334
356
  if (!scope || scope.map.size === 0) return p
@@ -397,7 +419,7 @@ function resolveFileOrDir(base, opts) {
397
419
  const file = asResolution(resolveSourceFile(base, opts))
398
420
  if (file) return file
399
421
  if (isDir(base, opts.host)) {
400
- const dpkg = readJson(join(base, 'package.json'), opts.host)
422
+ const dpkg = opts.read(join(base, 'package.json'))
401
423
  if (dpkg) {
402
424
  const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields), opts)
403
425
  if (r.empty) return { empty: true }
@@ -419,26 +441,31 @@ function resolveFileOrDir(base, opts) {
419
441
  // packages (delegated to Node's algorithm), `mainFields`/`platform`/`preferNative`/`sourceExts`
420
442
  // drive the legacy-field + suffix probing.
421
443
  // `metro` opts into Metro's package-entry + candidate-redirect semantics (see
422
- // resolveEntryThroughMap and resolveSourceFile); leave it off for the esbuild-parity
423
- // `--mainFields` path. `typescript` adds tsc's extension substitution (a missing `x.js` probes
444
+ // resolveEntryThroughMap and resolveSourceFile), and its asset rule for `assetExts` (Metro's
445
+ // defaults, else the project's); leave it off for the esbuild-parity `--mainFields` path. `typescript` adds tsc's extension substitution (a missing `x.js` probes
424
446
  // its `x.ts` sibling; see resolveSourceFile) plus the shared miss fallback (see below), and
425
447
  // `typescriptPaths` (a tsconfig paths matcher; see resolveTypescriptFallback) its tsconfig alias mapping.
426
448
  // `metroKeepEntryOnBrowserFalse` overrides the module-level toggle
427
449
  // (METRO_KEEP_ENTRY_ON_BROWSER_FALSE) per resolver -- primarily so tests can cover both branches.
428
- // `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default.
450
+ // `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default. `kept`, a Map
451
+ // kept across a lazy tree's rounds, keeps there each resolution that read nothing the tree does not
452
+ // hold yet (untouchedMemo's `across`), for the rounds after.
429
453
  export function createFieldResolver({
430
454
  conditions = [],
431
455
  mainFields = ['main'],
432
456
  platform = null,
433
457
  preferNative = false,
434
- sourceExts = ['js', 'jsx', 'json', 'ts', 'tsx'],
458
+ sourceExts = METRO_SOURCE_EXTS,
435
459
  metro = false,
460
+ assetExts = METRO_ASSET_EXTS,
436
461
  typescript = false,
437
462
  typescriptPaths = null,
438
463
  metroKeepEntryOnBrowserFalse = METRO_KEEP_ENTRY_ON_BROWSER_FALSE,
439
464
  host = diskHost,
465
+ kept,
440
466
  } = {}) {
441
- const opts = { platform, preferNative, sourceExts, mainFields, metro, typescript, metroKeepEntryOnBrowserFalse, host }
467
+ const read = manifestReader(host)
468
+ const opts = { platform, preferNative, sourceExts, mainFields, metro, assetExts, typescript, metroKeepEntryOnBrowserFalse, host, read }
442
469
  // An importer in node_modules gets no --typescript mapping (inNodeModules), wherever its import lands.
443
470
  const fromNodeModules = { ...opts, typescript: false }
444
471
  // Node answers a builtin name with the builtin itself, so an `exports`-bearing package named like
@@ -451,7 +478,7 @@ export function createFieldResolver({
451
478
  // else that file itself, no probing; null where it names none.
452
479
  const metroTargetFile = (pkgDir, target) => {
453
480
  const path = join(pkgDir, target)
454
- const asset = isMetroAssetFile(path) ? metroAsset(path, host) : null
481
+ const asset = isMetroAssetFile(path, assetExts) ? metroAsset(path, host) : null
455
482
  if (asset !== null) return fileResolution(asset, host)
456
483
  return isFile(path, host) && !isTypeDeclaration(path) ? fileResolution(path, host) : null
457
484
  }
@@ -460,7 +487,7 @@ export function createFieldResolver({
460
487
  // or with one not starting `#`; null where it names none. With no such package or no `imports`
461
488
  // in it, Metro fails the specifier, with no file-based fallback.
462
489
  const viaMetroImports = (parentFile, specifier, conds) => {
463
- const scope = metroPackageScope(parentFile, host)
490
+ const scope = metroPackageScope(parentFile, host, read)
464
491
  const imports = scope?.pkg.imports
465
492
  if (imports == null) throw new MetroFailure(`No "imports" for ${specifier} from ${parentFile}`)
466
493
  const keys = Object.keys(imports)
@@ -484,13 +511,13 @@ export function createFieldResolver({
484
511
  }
485
512
  // The file `subpath` names through the package at `pkgDir`'s `exports` field, as Metro maps it.
486
513
  const viaExports = (pkgDir, exportsField, subpath) => {
487
- const map = metroExportsMap(exportsField)
514
+ const map = metroExportsMapOf(exportsField)
488
515
  const target = map === null ? null : metroMapTarget(map, subpath, conds, { exports: true })
489
516
  return target === null ? null : metroTargetFile(pkgDir, target)
490
517
  }
491
518
  const viaPackage = (spec) => {
492
519
  const { name, firstPart, subpath } = parseBare(spec)
493
- const own = nearestPackage(parentFile, host)
520
+ const own = nearestPackage(parentFile, host, read)
494
521
  if (own?.pkg.exports != null && own.pkg.name === name) {
495
522
  const hit = viaExports(own.pkgDir, own.pkg.exports, subpath)
496
523
  if (hit) return hit
@@ -501,7 +528,7 @@ export function createFieldResolver({
501
528
  if (isDir(subpath !== '.' || name !== firstPart ? join(nm, firstPart) : nm, host)) {
502
529
  const target = metroRedirect(join(nm, spec), opts)
503
530
  if (target === false) return { empty: true }
504
- const scope = metroPackageScope(target, host)
531
+ const scope = metroPackageScope(target, host, read)
505
532
  const hit = (scope?.pkg.exports != null && viaExports(scope.pkgDir, scope.pkg.exports, target === scope.pkgDir ? '.' : `./${toPosix(relative(scope.pkgDir, target))}`)) || viaPath(target)
506
533
  if (hit) return hit
507
534
  // A package there whose entry resolves to nothing ends the lookup: Metro throws on it
@@ -515,7 +542,7 @@ export function createFieldResolver({
515
542
  return viaPath(isAbsolute(specifier) ? specifier : resolvePath(dirname(parentFile), specifier))
516
543
  }
517
544
  let spec = specifier
518
- const imp = nearestPackage(parentFile, host)
545
+ const imp = nearestPackage(parentFile, host, read)
519
546
  const r = imp ? matchRedirect(mergeRedirectMap(imp.pkg, mainFields), spec) : undefined
520
547
  if (r === false) return { empty: true }
521
548
  if (typeof r === 'string') {
@@ -543,7 +570,7 @@ export function createFieldResolver({
543
570
  const viaPackage = (spec) => {
544
571
  const loc = locatePackage(dirname(parentFile), spec, host)
545
572
  if (!loc) return null
546
- const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
573
+ const pkg = read(join(loc.pkgDir, 'package.json')) ?? {}
547
574
  // `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
548
575
  if (pkg.exports != null) return viaNode(spec)
549
576
  // A bare package import resolves its directory via the same dir algorithm as any other.
@@ -569,7 +596,7 @@ export function createFieldResolver({
569
596
  let spec = specifier
570
597
  // Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
571
598
  // a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
572
- const imp = nearestPackage(parentFile, host)
599
+ const imp = nearestPackage(parentFile, host, read)
573
600
  if (imp) {
574
601
  const map = mergeRedirectMap(imp.pkg, mainFields)
575
602
  let r
@@ -600,25 +627,30 @@ export function createFieldResolver({
600
627
  if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
601
628
  return viaPackage(spec)
602
629
  }
603
- if (!typescript) return resolve
630
+ // Each resolution made once for each directory, specifier and conditions: a file's directory is all
631
+ // of it resolving from it reads (its package, the node_modules above it, its tsconfig `paths`).
632
+ // Kept as the resolver's manifests are (manifestReader), and in `kept` across rounds.
633
+ const resolutions = untouchedMemo(host.touches, { retouch: host.retouch, across: kept })
634
+ const once = (resolveFn) => (parentFile, specifier, callConditions) => resolutions(`${dirname(parentFile)}\0${specifier}\0${[...callConditions ?? conditions].join('\0')}`, () => resolveFn(parentFile, specifier, callConditions))
635
+ if (!typescript) return once(resolve)
604
636
  // --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
605
637
  // the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
606
638
  // the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
607
639
  // imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
608
640
  // `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
609
641
  // (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
610
- return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
642
+ return once(function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
611
643
  const resolved = resolve(parentFile, specifier, callConditions)
612
644
  if (resolved) return resolved
613
645
  // Under --metro an asset is Metro's asset rule's to resolve (resolveSourceFile), as tsc never does.
614
- if (metro && isMetroAssetFile(specifier)) return null
646
+ if (metro && isMetroAssetFile(specifier, assetExts)) return null
615
647
  const hit = resolveTypescriptFallback(parentFile, specifier, {
616
648
  conditions: new Set(callConditions ?? conditions),
617
649
  paths: typescriptPaths,
618
650
  host,
619
651
  })
620
652
  return hit == null ? null : fileResolution(hit, host)
621
- }
653
+ })
622
654
  }
623
655
 
624
656
  // True when `format` is an ESM family (drives the base condition set, mirroring scan).
@@ -3,6 +3,7 @@ import { basename, dirname, isAbsolute, join, normalize, resolve } from 'node:pa
3
3
  import { fileURLToPath, pathToFileURL } from 'node:url'
4
4
 
5
5
  import { packageJSONStat, packageJSONText } from '@exodus/stasis-core/bundle-util'
6
+ import { untouchedMemo } from './vfs-bundle/lazy.js'
6
7
 
7
8
  // Node's CommonJS resolution (`createRequire(parent).resolve(spec, { conditions })`) over a
8
9
  // `host` (@exodus/stasis-core/host), mirroring lib/internal/modules/cjs/loader.js and
@@ -87,7 +88,11 @@ function parsePackageName(specifier, base) {
87
88
  return { packageName, packageSubpath: `.${separatorIndex === -1 ? '' : specifier.slice(separatorIndex)}`, isScoped }
88
89
  }
89
90
 
91
+ // `host.touches`, where it has one, counts the reads it makes of what a tree does not hold yet
92
+ // (vfs-bundle/tree.js's vfsHost of a lazy tree): what is read with none is cached alone, or with
93
+ // `host.retouch`, what is read with some too (untouchedMemo's `retouch`).
90
94
  export function createNodeResolver(host) {
95
+ const touches = host.touches ?? (() => 0)
91
96
  // package.json reads, memoized per path; a malformed manifest, or one there that can't be read,
92
97
  // throws ERR_INVALID_PACKAGE_CONFIG on every access.
93
98
  const parsePackage = (pjsonPath) => {
@@ -110,10 +115,9 @@ export function createNodeResolver(host) {
110
115
  const map = (value) => (typeof value === 'string' || (typeof value === 'object' && value !== null) ? value : undefined)
111
116
  return { exists: true, path: pjsonPath, name: string(data.name), main: string(data.main), exports: map(data.exports), imports: map(data.imports) }
112
117
  }
113
- const pkgCache = new Map()
118
+ const packages = untouchedMemo(touches, { retouch: host.retouch })
114
119
  const readPackage = (pjsonPath) => {
115
- let pkg = pkgCache.get(pjsonPath)
116
- if (pkg === undefined) pkgCache.set(pjsonPath, pkg = parsePackage(pjsonPath))
120
+ const pkg = packages(pjsonPath, () => parsePackage(pjsonPath))
117
121
  if (pkg instanceof Error) throw pkg
118
122
  return pkg
119
123
  }
@@ -401,7 +405,7 @@ export function createNodeResolver(host) {
401
405
  }
402
406
 
403
407
  // Node's Module._pathCache: the tree is immutable for the build.
404
- const memo = new Map()
408
+ const memo = untouchedMemo(touches, { retouch: host.retouch })
405
409
 
406
410
  return {
407
411
  // `conditions`: `require.resolve`'s own by default. A builtin returns its id, as it does.
@@ -411,9 +415,7 @@ export function createNodeResolver(host) {
411
415
  parentFile = resolve(parentFile)
412
416
  if (!(conditions instanceof Set)) conditions = new Set(conditions)
413
417
  const key = `${dirname(parentFile)}\0${request}\0${[...conditions].join(',')}${builtins ? '' : '\0nobuiltins'}`
414
- let hit = memo.get(key)
415
- if (hit === undefined) memo.set(key, hit = resolveFilename(parentFile, request, conditions, builtins))
416
- return hit
418
+ return memo(key, () => resolveFilename(parentFile, request, conditions, builtins))
417
419
  },
418
420
  }
419
421
  }
@@ -103,13 +103,13 @@ export function locatePackage(fromDir, spec, host = diskHost) {
103
103
  }
104
104
 
105
105
  // Nearest package.json at/above `file`'s dir — the package whose fields (browser/RN map, imports)
106
- // govern the file's own imports.
107
- export function nearestPackage(file, host = diskHost) {
106
+ // govern the file's own imports. `read` reads a manifest, as readJson does.
107
+ export function nearestPackage(file, host = diskHost, read = readJson) {
108
108
  let dir = dirname(file)
109
109
  while (true) {
110
110
  const pkgPath = join(dir, 'package.json')
111
111
  if (isFile(pkgPath, host)) {
112
- const pkg = readJson(pkgPath, host)
112
+ const pkg = read(pkgPath, host)
113
113
  if (pkg) return { pkgDir: dir, pkg }
114
114
  }
115
115
  const parent = dirname(dir)