@exodus/stasis 1.0.0-beta.13 → 1.0.0-beta.15

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 (46) hide show
  1. package/README.md +5 -1
  2. package/bin/stasis.js +191 -149
  3. package/package.json +31 -7
  4. package/src/audit.js +224 -90
  5. package/src/babel.js +44 -37
  6. package/src/bundle-reader.js +24 -4
  7. package/src/cmd/build.js +218 -8
  8. package/src/cmd/bundle-options.js +31 -25
  9. package/src/cmd/bundle.js +1147 -311
  10. package/src/cmd/github-bundle.js +17 -9
  11. package/src/cmd/output.js +10 -3
  12. package/src/cmd/tokens.js +73 -0
  13. package/src/define.js +5 -0
  14. package/src/diff.js +2 -2
  15. package/src/flow.js +42 -0
  16. package/src/installed-commits.js +4 -2
  17. package/src/loaders/bash.js +2 -27
  18. package/src/loaders/cargo.js +6 -6
  19. package/src/loaders/foundry.js +4 -6
  20. package/src/loaders/paths.js +4 -15
  21. package/src/loaders/php.js +3 -5
  22. package/src/loaders/rust.js +19 -39
  23. package/src/loaders/solidity-ownership.js +4 -15
  24. package/src/loaders/solidity.js +4 -67
  25. package/src/metro-assets.js +65 -0
  26. package/src/metro-resolver.js +76 -123
  27. package/src/parse.js +7 -3
  28. package/src/resolve-fields.js +133 -366
  29. package/src/resolve-node.js +9 -7
  30. package/src/resolve-typescript.js +102 -30
  31. package/src/scan.js +154 -54
  32. package/src/sixel.js +333 -0
  33. package/src/table.js +116 -0
  34. package/src/validate-notes.d.ts +18 -0
  35. package/src/validate-notes.js +66 -0
  36. package/src/validate.d.ts +132 -0
  37. package/src/validate.js +1349 -0
  38. package/src/vfs-bundle/entries.js +5 -2
  39. package/src/vfs-bundle/github.js +68 -19
  40. package/src/vfs-bundle/glob.js +420 -0
  41. package/src/vfs-bundle/lazy.js +128 -0
  42. package/src/vfs-bundle/prisma.js +102 -29
  43. package/src/vfs-bundle/tree.js +238 -75
  44. package/src/vfs-bundle/yarnclean.js +100 -0
  45. package/src/vfs-bundle.js +16 -7
  46. package/src/why.js +9 -7
@@ -1,9 +1,12 @@
1
1
  import { isBuiltin } from 'node:module'
2
- import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve as resolvePath } from 'node:path'
2
+ import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
3
3
  import { pathToFileURL } from 'node:url'
4
4
 
5
+ import { isAssetFile } from '@preventive/rn/metro-assets.js'
6
+ import { createMetroResolver, defaults as metroDefaults } from '@preventive/rn/metro-resolver.js'
5
7
  import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
6
8
  import {
9
+ fromOutputSource,
7
10
  inNodeModules,
8
11
  isDir,
9
12
  isFile,
@@ -11,17 +14,20 @@ import {
11
14
  nearestPackage,
12
15
  readJson,
13
16
  resolveTypescriptFallback,
17
+ tsconfigOutputsOf,
14
18
  typescriptSiblings,
15
19
  } from './resolve-typescript.js'
16
20
  import { diskHost } from '@exodus/stasis-core/host'
21
+ import { metroHost, scanResolution } from './metro-resolver.js'
17
22
  import { createNodeResolver } from './resolve-node.js'
23
+ import { untouchedMemo } from './vfs-bundle/lazy.js'
18
24
 
19
25
  // Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
20
26
  // redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
21
27
  // resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
22
28
  // delegated to Node's algorithm, under a bundler's conditions rather than Node's (see
23
- // resolveConditions); under `metro`, metro-resolver's own steps around them (viaMetro) and its own
24
- // reading of `exports` and `imports` maps (metroMapTarget).
29
+ // resolveConditions). Under `metro`, Metro's own resolution instead: metro-resolver's steps, as
30
+ // @preventive/rn takes them (viaMetro).
25
31
  // No user code is executed (only package.json is stat/read).
26
32
  //
27
33
  // Returns, for each specifier:
@@ -36,17 +42,6 @@ import { createNodeResolver } from './resolve-node.js'
36
42
  // stays a builtin, as the --metro-resolver adapter reports Metro's miss on one (metro-resolver.js),
37
43
  // rather than an unresolved edge: Metro and webpack fail the build there.
38
44
 
39
- // Metro divergence toggle. When a package's browser map maps its OWN entry to `false` (under
40
- // Metro's matching rules, which include bare keys like {"buf": false} for main "./buf.js"),
41
- // Metro's `getPackageEntryPoint` ignores the non-string replacement and keeps `main`. The
42
- // `--metro` resolver matches that by default; flip this to `false` to fail closed instead:
43
- // a `false` match on the entry then yields an EMPTY module. Note the off state is deliberately
44
- // stricter than both tools -- for a bare-key `false`, Metro keeps `main` and esbuild would not
45
- // match the entry at all -- it exists as an escape hatch, not an esbuild-parity mode. This only
46
- // affects the `--metro` path; the `--mainFields` path always empties (matching esbuild).
47
- // Tests can override per-resolver via createFieldResolver's `metroKeepEntryOnBrowserFalse`.
48
- const METRO_KEEP_ENTRY_ON_BROWSER_FALSE = true
49
-
50
45
  // First mainFields entry that's a non-empty string, else `index` (object-valued fields are redirect maps).
51
46
  function packageEntry(pkg, mainFields) {
52
47
  for (const name of mainFields) {
@@ -70,48 +65,25 @@ function mergeRedirectMap(pkg, mainFields) {
70
65
  return map
71
66
  }
72
67
 
73
- // Metro's entry-variant list for `main` (getPackageEntryPoint, metro-resolver
74
- // PackageResolve.js): the main spelling and its ./-toggled twin, each expanded to
75
- // [self, +'.js', +'.json', ext-stripped]. ORDER MATTERS -- the first variant with ANY mapping
76
- // (string or false) decides, so this must reproduce Metro's list exactly, duplicates included.
77
- function metroEntryVariants(main) {
78
- const toggled = main.startsWith('./') ? main.slice(2) : `./${main}`
79
- return [main, toggled].flatMap((v) => [v, `${v}.js`, `${v}.json`, v.replace(/\.(?:js|json)$/u, '')])
80
- }
81
-
82
- // Resolve the package ENTRY (from mainFields) through the package's own redirect map.
83
- // Returns { entry } (the redirected or original entry to resolve) or { empty: true }.
84
- // Both halves of the entry semantics -- WHICH keys match, and what `false` means -- live here
85
- // so no caller can get one without the other:
86
- // - metro: Metro's getPackageEntryPoint. First matching variant (Metro's order) wins; a string
87
- // redirects; `false` (any non-string) keeps `main`, unless the keep-on-false toggle is off,
88
- // in which case it fails closed to an empty module (see METRO_KEEP_ENTRY_ON_BROWSER_FALSE).
89
- // - default (--mainFields): esbuild-shaped candidates; `false` empties the entry, matching
90
- // esbuild. The extension-STRIPPED bare spelling is not probed: for an extensioned main,
91
- // esbuild treats it as a bare module name, not the entry. (For an extensionless main the
92
- // `bare` candidate covers it -- esbuild does match that spelling; verified empirically.)
93
- function resolveEntryThroughMap(map, main, opts) {
68
+ // Resolve the package ENTRY (from mainFields) through the package's own redirect map, as esbuild
69
+ // does. Returns { entry } (the redirected or original entry to resolve) or { empty: true }: a string
70
+ // redirects, `false` empties the entry. The extension-STRIPPED bare spelling is not probed: for an
71
+ // extensioned main, esbuild treats it as a bare module name, not the entry. (For an extensionless
72
+ // main the `bare` candidate covers it -- esbuild does match that spelling; verified empirically.)
73
+ function resolveEntryThroughMap(map, main) {
94
74
  if (map.size === 0) return { entry: main }
95
- let cands
96
- if (opts.metro) {
97
- cands = metroEntryVariants(main)
98
- } else {
99
- const bare = main.replace(/^\.\//u, '')
100
- const stripped = bare.replace(/\.(?:js|json)$/u, '')
101
- cands = [
102
- `./${bare}`, bare,
103
- `./${stripped}`,
104
- `./${stripped}.js`, `${stripped}.js`,
105
- `./${stripped}.json`, `${stripped}.json`,
106
- ]
107
- }
75
+ const bare = main.replace(/^\.\//u, '')
76
+ const stripped = bare.replace(/\.(?:js|json)$/u, '')
77
+ const cands = [
78
+ `./${bare}`, bare,
79
+ `./${stripped}`,
80
+ `./${stripped}.js`, `${stripped}.js`,
81
+ `./${stripped}.json`, `${stripped}.json`,
82
+ ]
108
83
  for (const cand of cands) {
109
84
  const v = map.get(cand)
110
85
  if (typeof v === 'string') return { entry: v }
111
- if (v === false) {
112
- if (opts.metro && opts.metroKeepEntryOnBrowserFalse) return { entry: main }
113
- return { empty: true }
114
- }
86
+ if (v === false) return { empty: true }
115
87
  }
116
88
  return { entry: main }
117
89
  }
@@ -119,9 +91,8 @@ function resolveEntryThroughMap(map, main, opts) {
119
91
  // A resolved file by its REAL path (through `host`, so a Vfs host's links are followed too), as Node,
120
92
  // Metro and esbuild record one: under pnpm's isolated layout `node_modules/debug` links into
121
93
  // `node_modules/.pnpm/debug@x/node_modules/debug`, whose own imports (a sibling `ms`) resolve only
122
- // from where it really lies. Probing stays on the path as reached, so a candidate and the package
123
- // scope read from it (resolveSourceFile's metro redirect) are one spelling; only the hit is
124
- // realpathed. null where the file has no real path (gone since it was probed).
94
+ // from where it really lies. Probing stays on the path as reached; only the hit is realpathed. null
95
+ // where the file has no real path (gone since it was probed).
125
96
  function fileResolution(path, host) {
126
97
  let real
127
98
  try {
@@ -141,217 +112,57 @@ function matchRedirect(map, relPath) {
141
112
  return undefined
142
113
  }
143
114
 
144
- // The package.json closest to `path` as Metro finds a module's package (getPackageForModule, through
145
- // metro-file-map's hierarchicalLookup): at the path itself where it is a directory, else above it,
146
- // 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) {
149
- for (let dir = isDir(path, host) ? path : dirname(path); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
150
- const pkgPath = join(dir, 'package.json')
151
- if (isFile(pkgPath, host)) {
152
- const pkg = readJson(pkgPath, host)
153
- if (pkg) return { pkgDir: dir, pkg }
154
- }
155
- if (dirname(dir) === dir) break
156
- }
157
- return null
158
- }
159
-
160
- // Metro's redirectModulePath for an absolute `path`: the browser/react-native map of the package
161
- // closest to it (metroPackageScope), matched by the path's package-relative spelling. A string is
162
- // taken as package-relative, as Metro takes it, even where it names another package.
163
- // -> the path, redirected where the map says so, or false (an empty module)
164
- function metroRedirect(path, opts) {
165
- const scope = metroPackageScope(path, opts.host)
166
- if (!scope) return path
167
- const rel = path === scope.pkgDir ? '' : toPosix(relative(scope.pkgDir, path))
168
- const r = matchRedirect(mergeRedirectMap(scope.pkg, opts.mainFields), `./${rel}`)
169
- if (r === false) return false
170
- if (typeof r === 'string') return isAbsolute(r) ? normalize(r) : join(scope.pkgDir, r)
171
- return path
172
- }
173
-
174
- // A bare specifier's package name, first segment and `exports` subpath ('.' or './x'), as Metro
175
- // parses one (parseBareSpecifier).
176
- function parseBare(spec) {
177
- const parts = spec.split('/')
178
- const n = spec.startsWith('@') && parts.length > 1 ? 2 : 1
179
- return { name: parts.slice(0, n).join('/'), firstPart: parts[0], subpath: parts.length > n ? `./${parts.slice(n).join('/')}` : '.' }
180
- }
181
-
182
- // Metro's default assetExts and assetResolutions (metro-config's defaults).
183
- 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
- const METRO_ASSET_RESOLUTIONS = ['1', '1.5', '2', '3', '4']
185
-
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) {
188
- const name = basename(path)
189
- for (let i = name.length - 1; i >= 0; i--) {
190
- if (name[i] === '.' && METRO_ASSET_EXTS.has(name.slice(i + 1))) return true
191
- }
192
- return false
193
- }
194
-
195
- // Metro's own resolveAsset (metro's DependencyGraph): `assetName` with `ext` in `dirPath`, and its
196
- // scale variants (`a@1x.png` ... `a@4x.png`), those that exist, by real path. -> the paths, or null
197
- export function metroAssetCandidates(dirPath, assetName, ext, host = diskHost) {
198
- const base = join(dirPath, assetName)
199
- const files = [`${base}${ext}`, ...METRO_ASSET_RESOLUTIONS.map((r) => `${base}@${r}x${ext}`)]
200
- .filter((p) => isFile(p, host))
201
- .map((p) => host.realpath(p))
202
- return files.length > 0 ? files : null
203
- }
204
-
205
- // The file Metro takes for an asset of several (getArrayLowestItem): the lowest path.
206
- export const lowestPath = (paths) => paths.reduce((lowest, p) => (p < lowest ? p : lowest))
207
-
208
- // Metro's asset resolution of `path` (resolveFile's, through metro-resolver's resolveAsset): the
209
- // lowest of it and its scale variants, so `./a.png` lands on `a@3x.png` where only that exists;
210
- // nothing for a path naming a scale variant itself (`./a@2x.png`), which Metro refuses.
211
- function metroAsset(path, host) {
212
- const ext = extname(path)
213
- const name = basename(path, ext)
214
- if (/@\d+(?:\.\d+)?x$/u.test(name)) return null
215
- const files = metroAssetCandidates(dirname(path), name, ext, host)
216
- return files === null ? null : lowestPath(files)
115
+ // What readJson gives for each manifest a resolver reads, read once, as for a tree that holds still:
116
+ // but one whose reading read what a lazy tree does not hold yet (`host.touches`) read again, or with
117
+ // `host.retouch` taken as read again (untouchedMemo's). Each resolver reads its own, so a build on the
118
+ // disk reads each manifest as it is then.
119
+ function manifestReader(host) {
120
+ const manifests = untouchedMemo(host.touches, { retouch: host.retouch })
121
+ return (path) => manifests(path, () => readJson(path, host))
217
122
  }
218
123
 
219
- // --metro: metro-resolver's own reading of an `exports` or `imports` map (PackageExportsResolve,
220
- // PackageImportsResolve and their utils), which Node's differs from. Each entry reduces by the
221
- // conditions (reduceConditionalExport): an object to the first of its keys `conds` holds, again
222
- // until a string or null, so a fallback array, whose indices no condition names, to null. The whole
223
- // map is refused where an entry reduces to a value not starting `./` (reduceExportsLikeMap), as
224
- // Metro refuses it: a bare or `../` target anywhere fails every specifier the map serves. A
225
- // specifier takes its own entry, else (where that reduces to null as well) the pattern whose base
226
- // before its `*` is longest, then the longest (matchSubpathFromExportsLike). Each miss -- the map
227
- // refused, the specifier unmatched, its target null or naming no file -- is Metro's cue to fall
228
- // back to file-based resolution, which the callers take.
229
-
230
- // Metro failing a resolution outright, where a miss falls back: on a map value it can't reduce (a
231
- // number or boolean, where its reduceConditionalExport throws), or a `#` specifier from a package
232
- // with no `imports` (resolve.js throws before its fallback).
233
- class MetroFailure extends Error {}
234
-
235
- // reduceConditionalExport: the string or null `value` reduces to under `conds`, or 'no-match'.
236
- function metroReduceConditional(value, conds) {
237
- let reduced = value
238
- while (reduced != null && typeof reduced !== 'string') {
239
- if (typeof reduced !== 'object') throw new MetroFailure(`Can't reduce ${JSON.stringify(reduced)} by conditions`)
240
- let match = 'default' in reduced ? 'no-match' : null
241
- for (const name in reduced) {
242
- if (conds.has(name)) {
243
- match = reduced[name]
244
- break
245
- }
246
- }
247
- reduced = match
124
+ // React Native's Metro config defaults: the extensions its resolver probes, in order, those it
125
+ // takes as assets, and the scales an asset's files are of.
126
+ export const METRO_SOURCE_EXTS = metroDefaults.sourceExts
127
+ export const METRO_ASSET_EXTS = new Set(metroDefaults.assetExts)
128
+ export const METRO_ASSET_RESOLUTIONS = metroDefaults.assetResolutions
129
+ // The conditions Metro asserts itself, by the kind of import.
130
+ const METRO_OWN_CONDITIONS = new Set(['default', 'import', 'require'])
131
+
132
+ // --metro --typescript: `view` (a metroHost over `host`) with tsc's extension substitution, as
133
+ // resolveSourceFile's: a file named for a JS output that is absent (`native.js`) is the first of its TS
134
+ // source siblings on disk (`native.ts`), unless that lies in node_modules by its real path, else an
135
+ // unbuilt output's source (`dist/native.js` -> `src/native.ts`; fromOutputSource). So Metro's own
136
+ // steps -- the entry its mainFields pick, a browser-map or `exports` target, the path itself, each
137
+ // platform file it tries -- land on the source of a compiled file that exists only as that source.
138
+ function typescriptView(view, { outputs, host }) {
139
+ const sibling = (path) => typescriptSiblings(path).find((candidate) => view.isFile(candidate)) ?? null
140
+ const source = (path) => {
141
+ const pick = sibling(path) ?? fromOutputSource(path, (input) => (view.isFile(input) ? input : sibling(input)), { outputs, host })
142
+ return pick === null || inNodeModules(pick, host) ? null : pick
248
143
  }
249
- return reduced
250
- }
251
-
252
- // matchSubpathPattern: what `pattern`'s `*` stands for in `subpath`, else null.
253
- function metroPatternMatch(pattern, subpath) {
254
- const [base, trailer] = pattern.split('*')
255
- if (subpath.startsWith(base) && (trailer.length === 0 || (subpath.endsWith(trailer) && subpath.length >= pattern.length))) {
256
- return subpath.slice(base.length, subpath.length - trailer.length)
144
+ const substituted = (path) => (view.isFile(path) || view.isDirectory(path) ? null : source(path))
145
+ return {
146
+ ...view,
147
+ isFile: (path) => view.isFile(path) || substituted(path) !== null,
148
+ realpath: (path) => view.realpath(substituted(path) ?? path),
257
149
  }
258
- return null
259
150
  }
260
151
 
261
- // The target `subpath` takes in `map` (a Map of a package map's entries) under `conds`, each `*` its
262
- // match, as Metro maps it; null where it takes none. An `exports` target holding an empty, `.`,
263
- // `..` or `node_modules` segment is refused besides (findInvalidPathSegment).
264
- function metroMapTarget(map, subpath, conds, { exports = false } = {}) {
265
- // isSubpathDefinedInExportsLike: listed, as itself or by a one-`*` pattern, before conditions apply.
266
- if (!map.has(subpath) && ![...map.keys()].some((key) => key.split('*').length === 2 && metroPatternMatch(key, subpath) !== null)) return null
267
- const reduced = new Map()
268
- for (const [key, value] of map) {
269
- const target = metroReduceConditional(value, conds)
270
- if (target !== 'no-match') reduced.set(key, target)
271
- }
272
- if ([...reduced.values()].some((target) => target != null && !target.startsWith('./'))) return null
273
- let target = reduced.get(subpath)
274
- let match = null
275
- if (target == null) {
276
- const patterns = [...reduced.keys()].filter((key) => key.includes('*')).toSorted((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length)
277
- for (const key of patterns) {
278
- match = metroPatternMatch(key, subpath)
279
- if (match !== null) {
280
- target = reduced.get(key)
281
- break
282
- }
283
- }
284
- }
285
- if (target == null) return null
286
- if (exports && target.slice(2).split(/[\\/]/u).some((segment) => ['', '.', '..', 'node_modules'].includes(segment))) return null
287
- // The match as a replacement pattern, as Metro's replaceAll takes it: a `$&` in it is the `*`.
288
- return match === null ? target : target.replaceAll('*', match)
289
- }
290
-
291
- // normalizeExportsField: an `exports` field as Metro's Map of subpaths, null where it refuses it --
292
- // an array to its first `./` string (or first value), each subpath's legacy array to its first item.
293
- function metroExportsMap(exportsField) {
294
- if (typeof exportsField === 'string') return new Map([['.', exportsField]])
295
- let root = exportsField
296
- if (Array.isArray(exportsField)) root = exportsField.every((value) => typeof value === 'string') ? exportsField.find((value) => value.startsWith('./')) : exportsField[0]
297
- if (root == null || Array.isArray(root)) return null
298
- if (typeof root === 'string') return new Map([['.', root]])
299
- const flat = {}
300
- for (const [key, value] of Object.entries(root)) {
301
- if (Array.isArray(value) && (value.length === 0 || Array.isArray(value[0]))) return null
302
- flat[key] = Array.isArray(value) ? value[0] : value
303
- }
304
- const keys = Object.keys(root)
305
- if (keys.every((key) => key.startsWith('.') || key.startsWith('#'))) return new Map(Object.entries(flat))
306
- return keys.some((key) => key.startsWith('.')) ? null : new Map([['.', flat]])
307
- }
308
-
309
- // Metro's relative specifier (isRelativeImport): `.`, `..`, or one starting `./` or `../`.
310
- const METRO_RELATIVE = /^\.\.?(?:\/|$)/u
311
-
312
152
  // Probe `base` for a source file in platform order: bare name first, then per ext
313
153
  // `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
314
- // disables suffixes. Under metro, every SUFFIXED candidate first passes through the candidate's
315
- // own package redirect map -- mirroring Metro's resolveSourceFileForExt, which runs
316
- // redirectModulePath on each non-bare candidate: `false` short-circuits the whole probe to an
317
- // empty module (e.g. browser { "./index.ios.js": false }), and a string redirect re-lands the
318
- // candidate package-root-relative. Returns a path, { empty: true } (metro only), or null.
154
+ // disables suffixes. Returns a path, or null.
319
155
  function resolveSourceFile(base, opts) {
320
156
  // A path that literally names a `.d.ts` names no runtime module (types are erased). Probe its
321
157
  // declaration-free stem instead, so an entry field pointing at `dist/index.d.ts` lands on the real
322
158
  // `dist/index.js` beside it rather than bundling the declaration -- or failing the package
323
159
  // outright by falling back to a different index. The probe below still refuses a literal hit.
324
160
  base = stripTypeDeclaration(base)
325
- // 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)
327
- // Candidates share base's directory, hence its package scope; resolve it lazily, once.
328
- let scope
329
- const redirectCandidate = (p) => {
330
- if (scope === undefined) {
331
- const pkg = nearestPackage(base, opts.host)
332
- scope = pkg ? { pkgDir: pkg.pkgDir, map: mergeRedirectMap(pkg.pkg, opts.mainFields) } : null
333
- }
334
- if (!scope || scope.map.size === 0) return p
335
- const rel = `./${toPosix(relative(scope.pkgDir, p))}`
336
- const r = matchRedirect(scope.map, rel)
337
- if (r === false) return false
338
- if (typeof r === 'string') return isAbsolute(r) ? r : resolvePath(scope.pkgDir, r)
339
- return p
340
- }
341
- // `derived` marks a candidate that is not the literal base; Metro redirect-checks those only.
342
- const probePath = (p, derived) => {
343
- if (opts.metro && derived) {
344
- const r = redirectCandidate(p)
345
- if (r === false) return { empty: true }
346
- p = r
347
- }
348
- // A `.d.ts` is types-only, erased at runtime: never a resolution target, so a package whose
349
- // entry field points at one falls through to its real `.js` instead of bundling the declaration.
350
- if (isTypeDeclaration(p)) return null
351
- return isFile(p, opts.host) ? p : null
352
- }
161
+ // A `.d.ts` is types-only, erased at runtime: never a resolution target, so a package whose
162
+ // entry field points at one falls through to its real `.js` instead of bundling the declaration.
163
+ const probePath = (p) => (!isTypeDeclaration(p) && isFile(p, opts.host) ? p : null)
353
164
  // `suffix` is everything appended to `base`.
354
- const probe = (suffix) => probePath(`${base}${suffix}`, suffix !== '')
165
+ const probe = (suffix) => probePath(`${base}${suffix}`)
355
166
  const tryExt = (sourceExt) => {
356
167
  if (opts.platform) {
357
168
  const hit = probe(`.${opts.platform}${sourceExt}`)
@@ -376,15 +187,24 @@ function resolveSourceFile(base, opts) {
376
187
  // `typescript` for an importer there.
377
188
  if (opts.typescript) {
378
189
  for (const cand of typescriptSiblings(base)) {
379
- const hit = probePath(cand, true)
190
+ const hit = probePath(cand)
380
191
  if (hit === null) continue
381
- return typeof hit === 'string' && inNodeModules(hit, opts.host) ? null : hit
192
+ return inNodeModules(hit, opts.host) ? null : hit
382
193
  }
383
194
  }
384
195
  for (const ext of opts.sourceExts) {
385
196
  const hit = tryExt(`.${ext}`)
386
197
  if (hit) return hit
387
198
  }
199
+ // --typescript: an unbuilt output's source, probed the same way (fromOutputSource), never in
200
+ // node_modules. Not for a directory: resolveFileOrDir probes its index, which maps.
201
+ if (opts.typescript && !isDir(base, opts.host)) {
202
+ const source = (input) => {
203
+ const hit = resolveSourceFile(input, { ...opts, outputs: null })
204
+ return hit === null || inNodeModules(hit, opts.host) ? null : hit
205
+ }
206
+ return fromOutputSource(base, source, opts)
207
+ }
388
208
  return null
389
209
  }
390
210
 
@@ -392,22 +212,20 @@ function resolveSourceFile(base, opts) {
392
212
  // mainFields + entry redirect, else `index`). `exports` is NOT consulted — Node applies it only to
393
213
  // bare package-name imports, not to a path landing on a directory.
394
214
  function resolveFileOrDir(base, opts) {
395
- // resolveSourceFile yields a path, { empty: true } (a metro candidate-redirect hit), or null.
396
- const asResolution = (hit) => (hit == null ? null : typeof hit === 'string' ? fileResolution(hit, opts.host) : hit)
215
+ const asResolution = (hit) => (hit === null ? null : fileResolution(hit, opts.host))
397
216
  const file = asResolution(resolveSourceFile(base, opts))
398
217
  if (file) return file
399
218
  if (isDir(base, opts.host)) {
400
- const dpkg = readJson(join(base, 'package.json'), opts.host)
219
+ const dpkg = opts.read(join(base, 'package.json'))
401
220
  if (dpkg) {
402
- const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields), opts)
221
+ const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields))
403
222
  if (r.empty) return { empty: true }
404
223
  // Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
405
224
  // (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
406
- // Metro's resolvePackageEntryPoint has no such fallback: it throws (InvalidPackageError).
407
225
  const entryBase = join(base, r.entry)
408
- const inner = asResolution(resolveSourceFile(entryBase, opts) ?? resolveSourceFile(join(entryBase, 'index'), opts))
226
+ const entryOpts = { ...opts, pkgDir: base } // the package naming the entry, for its unbuilt output
227
+ const inner = asResolution(resolveSourceFile(entryBase, entryOpts) ?? resolveSourceFile(join(entryBase, 'index'), entryOpts))
409
228
  if (inner) return inner
410
- if (opts.metro) return null
411
229
  }
412
230
  const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
413
231
  if (index) return index
@@ -418,113 +236,65 @@ function resolveFileOrDir(base, opts) {
418
236
  // Build a resolver bound to options: `conditions` (a resolveConditions set) gates `exports`
419
237
  // packages (delegated to Node's algorithm), `mainFields`/`platform`/`preferNative`/`sourceExts`
420
238
  // drive the legacy-field + suffix probing.
421
- // `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
424
- // its `x.ts` sibling; see resolveSourceFile) plus the shared miss fallback (see below), and
425
- // `typescriptPaths` (a tsconfig paths matcher; see resolveTypescriptFallback) its tsconfig alias mapping.
426
- // `metroKeepEntryOnBrowserFalse` overrides the module-level toggle
427
- // (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.
239
+ // `metro` resolves as Metro does instead (viaMetro), taking `assetExts` as assets, at the scales
240
+ // `assetResolutions` (Metro's defaults, else the project's, each); leave it off for the
241
+ // esbuild-parity `--mainFields` path. `typescript` adds
242
+ // tsc's extension substitution (a missing `x.js` probes its `x.ts` sibling) and unbuilt outputs'
243
+ // sources (see resolveSourceFile; under `metro`, typescriptView) plus the shared miss fallback (see
244
+ // below), and `typescriptPaths` (a tsconfig paths matcher, with the packages' layouts; see
245
+ // resolveTypescriptFallback) its tsconfig alias mapping.
246
+ // `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default. `kept`, a Map
247
+ // kept across a lazy tree's rounds, keeps there each resolution that read nothing the tree does not
248
+ // hold yet (untouchedMemo's `across`), for the rounds after.
429
249
  export function createFieldResolver({
430
250
  conditions = [],
431
251
  mainFields = ['main'],
432
252
  platform = null,
433
253
  preferNative = false,
434
- sourceExts = ['js', 'jsx', 'json', 'ts', 'tsx'],
254
+ sourceExts = METRO_SOURCE_EXTS,
435
255
  metro = false,
256
+ assetExts = METRO_ASSET_EXTS,
257
+ assetResolutions = METRO_ASSET_RESOLUTIONS,
436
258
  typescript = false,
437
259
  typescriptPaths = null,
438
- metroKeepEntryOnBrowserFalse = METRO_KEEP_ENTRY_ON_BROWSER_FALSE,
439
260
  host = diskHost,
261
+ kept,
440
262
  } = {}) {
441
- const opts = { platform, preferNative, sourceExts, mainFields, metro, typescript, metroKeepEntryOnBrowserFalse, host }
263
+ const read = manifestReader(host)
264
+ const outputs = typescript ? typescriptPaths?.outputs ?? tsconfigOutputsOf({ host }) : null
265
+ const opts = { platform, preferNative, sourceExts, mainFields, typescript, outputs, host, read }
442
266
  // An importer in node_modules gets no --typescript mapping (inNodeModules), wherever its import lands.
443
267
  const fromNodeModules = { ...opts, typescript: false }
444
268
  // Node answers a builtin name with the builtin itself, so an `exports`-bearing package named like
445
269
  // one (see the header) resolves through this instead, with builtins off; built on first use.
446
270
  let packageResolver
447
271
  const nodeResolver = () => (packageResolver ??= createNodeResolver(host))
448
- // --metro: the file a package-map target (`exports`, `imports`; a path from `pkgDir`) names, as
449
- // Metro takes it (PackageExportsResolve, PackageImportsResolve): an asset as an asset, its scale
450
- // variants included, so `"./logo": "./logo.png"` reaches `logo@3x.png` where only that exists,
451
- // else that file itself, no probing; null where it names none.
452
- const metroTargetFile = (pkgDir, target) => {
453
- const path = join(pkgDir, target)
454
- const asset = isMetroAssetFile(path) ? metroAsset(path, host) : null
455
- if (asset !== null) return fileResolution(asset, host)
456
- return isFile(path, host) && !isTypeDeclaration(path) ? fileResolution(path, host) : null
457
- }
458
- // --metro: the file a `#` specifier names through the `imports` of the package closest to the
459
- // importer, as Metro maps it (resolvePackageTargetFromImports), which refuses a map with no keys
460
- // or with one not starting `#`; null where it names none. With no such package or no `imports`
461
- // in it, Metro fails the specifier, with no file-based fallback.
462
- const viaMetroImports = (parentFile, specifier, conds) => {
463
- const scope = metroPackageScope(parentFile, host)
464
- const imports = scope?.pkg.imports
465
- if (imports == null) throw new MetroFailure(`No "imports" for ${specifier} from ${parentFile}`)
466
- const keys = Object.keys(imports)
467
- if (keys.length === 0 || !keys.every((key) => key.startsWith('#'))) return null
468
- const target = metroMapTarget(new Map(Object.entries(imports)), specifier, conds)
469
- return target === null ? null : metroTargetFile(scope.pkgDir, target)
470
- }
471
-
472
- // --metro: metro-resolver's own steps (its resolve.js), so the two resolve alike where they can.
473
- // A path takes the redirect of the package closest to it, then resolves as a file or directory
474
- // (resolveModulePath). A bare specifier takes the importer's redirect, then the importer's own
475
- // `exports` where it names its own package, then, in each node_modules up from the importer, the
476
- // package there (resolveModuleFromTargetPath): the redirect of the package closest to the
477
- // candidate path -- a nested package.json counts -- then the `exports` of the one closest to where
478
- // that lands, else that path as a file or directory. Metro falls back so from any `exports` miss,
479
- // which keeps `main` and the browser map in play where `exports` serves no condition it asserts.
480
- const viaMetro = (parentFile, specifier, conds, fileOpts) => {
481
- const viaPath = (abs) => {
482
- const target = metroRedirect(abs, opts)
483
- return target === false ? { empty: true } : resolveFileOrDir(target, fileOpts)
272
+ // --metro: Metro's own resolution, @preventive/rn's, over `host` as stasis reads it (metroHost). Metro
273
+ // asserts `default` and `import` or `require` by the kind of import itself, and takes the rest of an
274
+ // importer's conditions as its `conditionNames`: one resolver for each such set, made on first use.
275
+ // Off web it prefers `.native` files (preferNative). --typescript resolves what that misses again,
276
+ // over the view of tsc's extension substitution (typescriptView), but for an importer in
277
+ // node_modules (inNodeModules), so it never overrides what Metro resolves. A builtin it fails to
278
+ // resolve, one the importer's browser map doesn't remap, is a builtin (see the header).
279
+ const metroResolvers = new Map()
280
+ const metroResolver = (conditionNames, substituting) => {
281
+ const key = `${substituting}\0${conditionNames.join('\0')}`
282
+ if (!metroResolvers.has(key)) {
283
+ const view = metroHost(host, mainFields)
284
+ metroResolvers.set(key, createMetroResolver({ host: substituting ? typescriptView(view, opts) : view, sourceExts, assetExts, assetResolutions, mainFields, conditionNames, conditionsByPlatform: {}, preferNativePlatform: preferNative }))
484
285
  }
485
- // The file `subpath` names through the package at `pkgDir`'s `exports` field, as Metro maps it.
486
- const viaExports = (pkgDir, exportsField, subpath) => {
487
- const map = metroExportsMap(exportsField)
488
- const target = map === null ? null : metroMapTarget(map, subpath, conds, { exports: true })
489
- return target === null ? null : metroTargetFile(pkgDir, target)
490
- }
491
- const viaPackage = (spec) => {
492
- const { name, firstPart, subpath } = parseBare(spec)
493
- const own = nearestPackage(parentFile, host)
494
- if (own?.pkg.exports != null && own.pkg.name === name) {
495
- const hit = viaExports(own.pkgDir, own.pkg.exports, subpath)
496
- if (hit) return hit
497
- }
498
- for (let dir = dirname(parentFile); ; dir = dirname(dir)) {
499
- const nm = join(dir, 'node_modules')
500
- // The shallowest directory the package can be in must exist (resolveFromNodeModulesPath).
501
- if (isDir(subpath !== '.' || name !== firstPart ? join(nm, firstPart) : nm, host)) {
502
- const target = metroRedirect(join(nm, spec), opts)
503
- if (target === false) return { empty: true }
504
- const scope = metroPackageScope(target, host)
505
- const hit = (scope?.pkg.exports != null && viaExports(scope.pkgDir, scope.pkg.exports, target === scope.pkgDir ? '.' : `./${toPosix(relative(scope.pkgDir, target))}`)) || viaPath(target)
506
- if (hit) return hit
507
- // A package there whose entry resolves to nothing ends the lookup: Metro throws on it
508
- // (InvalidPackageError). Anything else that misses gives way to the next node_modules up.
509
- if (isFile(join(target, 'package.json'), host)) return null
510
- }
511
- if (dirname(dir) === dir) return null
512
- }
513
- }
514
- if (METRO_RELATIVE.test(specifier) || isAbsolute(specifier)) {
515
- return viaPath(isAbsolute(specifier) ? specifier : resolvePath(dirname(parentFile), specifier))
516
- }
517
- let spec = specifier
518
- const imp = nearestPackage(parentFile, host)
519
- const r = imp ? matchRedirect(mergeRedirectMap(imp.pkg, mainFields), spec) : undefined
520
- if (r === false) return { empty: true }
521
- if (typeof r === 'string') {
522
- if (METRO_RELATIVE.test(r) || isAbsolute(r)) return viaPath(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r))
523
- spec = r
286
+ return metroResolvers.get(key)
287
+ }
288
+ const viaMetro = (parentFile, specifier, conds) => {
289
+ const conditionNames = [...conds].filter((name) => !METRO_OWN_CONDITIONS.has(name))
290
+ const request = { platform, isESMImport: conds.has('import') }
291
+ let resolution = metroResolver(conditionNames, false)(parentFile, specifier, request)
292
+ if (resolution === null && typescript && !inNodeModules(parentFile, host)) resolution = metroResolver(conditionNames, true)(parentFile, specifier, request)
293
+ const remapped = () => {
294
+ const imp = nearestPackage(parentFile, host, read)
295
+ return imp !== null && matchRedirect(mergeRedirectMap(imp.pkg, mainFields), specifier) !== undefined
524
296
  }
525
- // A builtin the importer's map did not remap: as for the field resolver (see the header).
526
- if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
527
- return viaPackage(spec)
297
+ return scanResolution(resolution, resolution === null && isBuiltin(specifier) && !remapped())
528
298
  }
529
299
  // `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
530
300
  // delegation matches Node resolving from THAT file; falls back to configured `conditions`.
@@ -543,7 +313,7 @@ export function createFieldResolver({
543
313
  const viaPackage = (spec) => {
544
314
  const loc = locatePackage(dirname(parentFile), spec, host)
545
315
  if (!loc) return null
546
- const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
316
+ const pkg = read(join(loc.pkgDir, 'package.json')) ?? {}
547
317
  // `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
548
318
  if (pkg.exports != null) return viaNode(spec)
549
319
  // A bare package import resolves its directory via the same dir algorithm as any other.
@@ -554,22 +324,14 @@ export function createFieldResolver({
554
324
  const target = typeof r === 'string' ? r : sub
555
325
  return resolveFileOrDir(join(loc.pkgDir, target), fileOpts)
556
326
  }
557
- // `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them,
558
- // Metro's own under --metro, which falls back to file-based resolution where `imports` misses.
559
- if (metro) {
560
- try {
561
- return (specifier.startsWith('#') && viaMetroImports(parentFile, specifier, conds)) || viaMetro(parentFile, specifier, conds, fileOpts)
562
- } catch (error) {
563
- if (error instanceof MetroFailure) return null
564
- throw error
565
- }
566
- }
327
+ if (metro) return viaMetro(parentFile, specifier, conds)
328
+ // `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them.
567
329
  if (specifier.startsWith('#')) return viaNode(specifier)
568
330
 
569
331
  let spec = specifier
570
332
  // Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
571
333
  // a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
572
- const imp = nearestPackage(parentFile, host)
334
+ const imp = nearestPackage(parentFile, host, read)
573
335
  if (imp) {
574
336
  const map = mergeRedirectMap(imp.pkg, mainFields)
575
337
  let r
@@ -600,25 +362,30 @@ export function createFieldResolver({
600
362
  if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
601
363
  return viaPackage(spec)
602
364
  }
603
- if (!typescript) return resolve
365
+ // Each resolution made once for each directory, specifier and conditions: a file's directory is all
366
+ // of it resolving from it reads (its package, the node_modules above it, its tsconfig `paths`).
367
+ // Kept as the resolver's manifests are (manifestReader), and in `kept` across rounds.
368
+ const resolutions = untouchedMemo(host.touches, { retouch: host.retouch, across: kept })
369
+ const once = (resolveFn) => (parentFile, specifier, callConditions) => resolutions(`${dirname(parentFile)}\0${specifier}\0${[...callConditions ?? conditions].join('\0')}`, () => resolveFn(parentFile, specifier, callConditions))
370
+ if (!typescript) return once(resolve)
604
371
  // --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
605
372
  // the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
606
373
  // the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
607
374
  // imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
608
375
  // `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
609
376
  // (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
610
- return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
377
+ return once(function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
611
378
  const resolved = resolve(parentFile, specifier, callConditions)
612
379
  if (resolved) return resolved
613
- // Under --metro an asset is Metro's asset rule's to resolve (resolveSourceFile), as tsc never does.
614
- if (metro && isMetroAssetFile(specifier)) return null
380
+ // Under --metro an asset is Metro's asset rule's to resolve, as tsc never does.
381
+ if (metro && isAssetFile(specifier, assetExts)) return null
615
382
  const hit = resolveTypescriptFallback(parentFile, specifier, {
616
383
  conditions: new Set(callConditions ?? conditions),
617
384
  paths: typescriptPaths,
618
385
  host,
619
386
  })
620
387
  return hit == null ? null : fileResolution(hit, host)
621
- }
388
+ })
622
389
  }
623
390
 
624
391
  // True when `format` is an ESM family (drives the base condition set, mirroring scan).