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

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 (67) hide show
  1. package/README.md +1 -1
  2. package/bin/stasis.js +19 -6
  3. package/package.json +10 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +113 -233
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +50 -166
  11. package/src/cmd/bundle-options.js +110 -167
  12. package/src/cmd/bundle.js +853 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +18 -22
  15. package/src/cmd/output.js +15 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +10 -23
  18. package/src/define.js +34 -97
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +10 -25
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +9 -33
  37. package/src/metro-resolver.js +20 -47
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +2 -5
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +90 -220
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +109 -313
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +136 -283
  50. package/src/sixel.js +18 -41
  51. package/src/table.js +14 -35
  52. package/src/validate-notes.d.ts +3 -2
  53. package/src/validate-notes.js +25 -19
  54. package/src/validate.d.ts +38 -11
  55. package/src/validate.js +478 -512
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +77 -121
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +167 -110
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +75 -231
  67. package/src/installed-commits.js +0 -184
@@ -4,83 +4,52 @@ import { pathToFileURL } from 'node:url'
4
4
 
5
5
  import { isAssetFile } from '@preventive/rn/metro-assets.js'
6
6
  import { createMetroResolver, defaults as metroDefaults } from '@preventive/rn/metro-resolver.js'
7
- import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
7
+ import { memoized, toPosix } from '@exodus/stasis-core/util'
8
8
  import {
9
9
  fromOutputSource,
10
10
  inNodeModules,
11
11
  isDir,
12
- isFile,
12
+ isSourceFile,
13
13
  locatePackage,
14
14
  nearestPackage,
15
- readJson,
15
+ readManifest,
16
16
  resolveTypescriptFallback,
17
17
  tsconfigOutputsOf,
18
18
  typescriptSiblings,
19
19
  } from './resolve-typescript.js'
20
20
  import { diskHost } from '@exodus/stasis-core/host'
21
- import { metroHost, scanResolution } from './metro-resolver.js'
22
- import { createNodeResolver } from './resolve-node.js'
23
- import { untouchedMemo } from './vfs-bundle/lazy.js'
21
+ import { metroHost, scanResolution, stripTypeDeclaration } from './metro-resolver.js'
22
+ import { RELATIVE_REQUEST, createNodeResolver } from './resolve-node.js'
23
+ import { hostMemo } from './vfs-bundle/lazy.js'
24
24
 
25
- // Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
26
- // redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
27
- // resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
28
- // delegated to Node's algorithm, under a bundler's conditions rather than Node's (see
29
- // resolveConditions). Under `metro`, Metro's own resolution instead: metro-resolver's steps, as
30
- // @preventive/rn takes them (viaMetro).
31
- // No user code is executed (only package.json is stat/read).
32
- //
33
- // Returns, for each specifier:
34
- // { url } resolved to a file, by its real path (file: URL string; see fileResolution)
35
- // { empty } a browser/react-native field mapped it to `false` (empty module)
36
- // { builtin } a Node builtin: a `node:` specifier, or a builtin name no installed package resolves
37
- // null unresolved
38
- //
39
- // Browser and React Native targets have no Node builtins, so a bare builtin name (`buffer`,
40
- // `events`, `util`, `process`, ...) resolves to the installed npm package of that name, as esbuild
41
- // (platform browser), webpack 5 (target web) and Metro bundle it. Where nothing is installed it
42
- // stays a builtin, as the --metro-resolver adapter reports Metro's miss on one (metro-resolver.js),
43
- // rather than an unresolved edge: Metro and webpack fail the build there.
25
+ // Legacy package fields (`react-native`/`browser`/`main`, their redirect maps) and platform suffixes, as Metro resolves
26
+ // them: -> { url } | { empty } (mapped to `false`) | { builtin } | null. Targets without Node builtins take a bare builtin
27
+ // name (`buffer`) for the installed package so named, as esbuild, webpack 5 and Metro do, else for the builtin.
44
28
 
45
- // First mainFields entry that's a non-empty string, else `index` (object-valued fields are redirect maps).
46
- function packageEntry(pkg, mainFields) {
47
- for (const name of mainFields) {
48
- if (typeof pkg?.[name] === 'string' && pkg[name].length > 0) return pkg[name]
49
- }
50
- return 'index'
51
- }
29
+ // Object-valued fields are redirect maps, never an entry.
30
+ const packageEntry = (pkg, mainFields) =>
31
+ mainFields.map((name) => pkg[name]).find((entry) => typeof entry === 'string' && entry.length > 0) ?? 'index'
52
32
 
53
- // Merge object-valued mainFields (browser-spec maps) into one redirect map. Iterate in REVERSE
54
- // so earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x` (kept bare).
33
+ // Earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x`.
55
34
  function mergeRedirectMap(pkg, mainFields) {
56
35
  const map = new Map()
57
- for (let i = mainFields.length - 1; i >= 0; i--) {
58
- const field = pkg?.[mainFields[i]]
36
+ for (const name of mainFields.toReversed()) {
37
+ const field = pkg?.[name]
59
38
  if (!field || typeof field !== 'object') continue
60
39
  for (const [key, value] of Object.entries(field)) {
61
- if (typeof value !== 'string' && value !== false) continue
62
- map.set(key, value)
40
+ if (typeof value === 'string' || value === false) map.set(key, value)
63
41
  }
64
42
  }
65
43
  return map
66
44
  }
67
45
 
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.)
46
+ // As esbuild maps the package entry: the extension-stripped bare spelling is no candidate, esbuild taking it as a
47
+ // bare module name (an extensionless main's is `bare` itself, which it matches).
73
48
  function resolveEntryThroughMap(map, main) {
74
49
  if (map.size === 0) return { entry: main }
75
50
  const bare = main.replace(/^\.\//u, '')
76
51
  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
- ]
83
- for (const cand of cands) {
52
+ for (const cand of [`./${bare}`, bare, `./${stripped}`, `./${stripped}.js`, `${stripped}.js`, `./${stripped}.json`, `${stripped}.json`]) {
84
53
  const v = map.get(cand)
85
54
  if (typeof v === 'string') return { entry: v }
86
55
  if (v === false) return { empty: true }
@@ -88,53 +57,30 @@ function resolveEntryThroughMap(map, main) {
88
57
  return { entry: main }
89
58
  }
90
59
 
91
- // A resolved file by its REAL path (through `host`, so a Vfs host's links are followed too), as Node,
92
- // Metro and esbuild record one: under pnpm's isolated layout `node_modules/debug` links into
93
- // `node_modules/.pnpm/debug@x/node_modules/debug`, whose own imports (a sibling `ms`) resolve only
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).
60
+ // By real path, as Node, Metro and esbuild record a file: under pnpm a package's imports resolve only from where it lies.
96
61
  function fileResolution(path, host) {
97
- let real
98
62
  try {
99
- real = host.realpath(path)
63
+ return { url: pathToFileURL(host.realpath(path)).toString() }
100
64
  } catch {
101
65
  return null
102
66
  }
103
- return { url: pathToFileURL(real).toString() }
104
67
  }
105
68
 
106
- // Match a package-relative path (`./x`) against the redirect map, trying `.js`/`.json` appended.
107
- function matchRedirect(map, relPath) {
108
- if (map.size === 0) return undefined
109
- for (const cand of [relPath, `${relPath}.js`, `${relPath}.json`]) {
110
- if (map.has(cand)) return map.get(cand)
111
- }
112
- return undefined
113
- }
69
+ // Map keys are strings, so a miss gets undefined.
70
+ const matchRedirect = (map, relPath) => map.get([relPath, `${relPath}.js`, `${relPath}.json`].find((cand) => map.has(cand)))
114
71
 
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.
72
+ // Each resolver reads its own manifests, so a build on the disk reads each as it is then.
119
73
  function manifestReader(host) {
120
- const manifests = untouchedMemo(host.touches, { retouch: host.retouch })
121
- return (path) => manifests(path, () => readJson(path, host))
74
+ const manifests = hostMemo(host)
75
+ return (path) => manifests(path, () => readManifest(path, host))
122
76
  }
123
77
 
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
78
  export const METRO_SOURCE_EXTS = metroDefaults.sourceExts
127
79
  export const METRO_ASSET_EXTS = new Set(metroDefaults.assetExts)
128
80
  export const METRO_ASSET_RESOLUTIONS = metroDefaults.assetResolutions
129
- // The conditions Metro asserts itself, by the kind of import.
130
81
  const METRO_OWN_CONDITIONS = new Set(['default', 'import', 'require'])
131
82
 
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.
83
+ // --metro --typescript: an absent JS output is its first TS sibling on disk, else an unbuilt output's source.
138
84
  function typescriptView(view, { outputs, host }) {
139
85
  const sibling = (path) => typescriptSiblings(path).find((candidate) => view.isFile(candidate)) ?? null
140
86
  const source = (path) => {
@@ -149,55 +95,26 @@ function typescriptView(view, { outputs, host }) {
149
95
  }
150
96
  }
151
97
 
152
- // Probe `base` for a source file in platform order: bare name first, then per ext
153
- // `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
154
- // disables suffixes. Returns a path, or null.
155
98
  function resolveSourceFile(base, opts) {
156
- // A path that literally names a `.d.ts` names no runtime module (types are erased). Probe its
157
- // declaration-free stem instead, so an entry field pointing at `dist/index.d.ts` lands on the real
158
- // `dist/index.js` beside it rather than bundling the declaration -- or failing the package
159
- // outright by falling back to a different index. The probe below still refuses a literal hit.
99
+ // An entry field naming `dist/index.d.ts` lands on the `dist/index.js` beside it.
160
100
  base = stripTypeDeclaration(base)
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)
164
- // `suffix` is everything appended to `base`.
165
- const probe = (suffix) => probePath(`${base}${suffix}`)
166
- const tryExt = (sourceExt) => {
167
- if (opts.platform) {
168
- const hit = probe(`.${opts.platform}${sourceExt}`)
169
- if (hit) return hit
170
- }
171
- if (opts.preferNative && sourceExt !== '') {
172
- const hit = probe(`.native${sourceExt}`)
173
- if (hit) return hit
174
- }
175
- return probe(sourceExt)
176
- }
101
+ const probe = (suffix) => (isSourceFile(`${base}${suffix}`, opts.host) ? `${base}${suffix}` : null)
102
+ const tryExt = (ext) => (opts.platform && probe(`.${opts.platform}${ext}`))
103
+ || (opts.preferNative && ext !== '' && probe(`.native${ext}`))
104
+ || probe(ext)
177
105
  const bare = tryExt('')
178
106
  if (bare) return bare
179
- // --typescript: tsc's extension substitution. A base naming a JS output extension probes its TS
180
- // source siblings once the literal file (the bare probe above) is absent, so the on-disk `.js`
181
- // always wins over its `.ts` twin. Literal siblings only -- no platform suffixes (tsc has none);
182
- // extensionless bases keep going through the appended-extension loop below (sourceExts carries
183
- // ts and tsx). Placed before that loop so `x.js` -> `x.ts` beats a pathological
184
- // `x.js.<ext>`, matching tsc's candidate order. Never into node_modules: where tsc's pick, the
185
- // first sibling on disk, lies there by its real path, nothing maps (inNodeModules), as the shared
186
- // fallback refuses its own -- never a later sibling tsc wouldn't pick. The resolver drops
187
- // `typescript` for an importer there.
107
+ // tsc's substitution comes once the literal file is absent, before the appended extensions, as tsc orders them.
108
+ // Its pick, the first sibling on disk, maps nothing in node_modules, never to a later sibling.
188
109
  if (opts.typescript) {
189
- for (const cand of typescriptSiblings(base)) {
190
- const hit = probePath(cand)
191
- if (hit === null) continue
192
- return inNodeModules(hit, opts.host) ? null : hit
193
- }
110
+ const sibling = typescriptSiblings(base).find((candidate) => isSourceFile(candidate, opts.host))
111
+ if (sibling !== undefined) return inNodeModules(sibling, opts.host) ? null : sibling
194
112
  }
195
113
  for (const ext of opts.sourceExts) {
196
114
  const hit = tryExt(`.${ext}`)
197
115
  if (hit) return hit
198
116
  }
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.
117
+ // Not for a directory: resolveFileOrDir probes its index, which maps.
201
118
  if (opts.typescript && !isDir(base, opts.host)) {
202
119
  const source = (input) => {
203
120
  const hit = resolveSourceFile(input, { ...opts, outputs: null })
@@ -208,10 +125,8 @@ function resolveSourceFile(base, opts) {
208
125
  return null
209
126
  }
210
127
 
211
- // Resolve absolute `base` as a file (ext probing) else as a directory (package.json `main` via
212
- // mainFields + entry redirect, else `index`). `exports` is NOT consulted — Node applies it only to
213
- // bare package-name imports, not to a path landing on a directory.
214
- function resolveFileOrDir(base, opts) {
128
+ // `exports` is not consulted: Node applies it only to bare package names.
129
+ function resolveFileOrDir(base, opts, tried) {
215
130
  const asResolution = (hit) => (hit === null ? null : fileResolution(hit, opts.host))
216
131
  const file = asResolution(resolveSourceFile(base, opts))
217
132
  if (file) return file
@@ -220,12 +135,12 @@ function resolveFileOrDir(base, opts) {
220
135
  if (dpkg) {
221
136
  const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields))
222
137
  if (r.empty) return { empty: true }
223
- // Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
224
- // (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
138
+ // Node's LOAD_AS_DIRECTORY: `main` as a file, else as a directory index; a broken one falls back to the index.
225
139
  const entryBase = join(base, r.entry)
226
140
  const entryOpts = { ...opts, pkgDir: base } // the package naming the entry, for its unbuilt output
227
141
  const inner = asResolution(resolveSourceFile(entryBase, entryOpts) ?? resolveSourceFile(join(entryBase, 'index'), entryOpts))
228
142
  if (inner) return inner
143
+ tried.push(entryBase)
229
144
  }
230
145
  const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
231
146
  if (index) return index
@@ -233,19 +148,7 @@ function resolveFileOrDir(base, opts) {
233
148
  return null
234
149
  }
235
150
 
236
- // Build a resolver bound to options: `conditions` (a resolveConditions set) gates `exports`
237
- // packages (delegated to Node's algorithm), `mainFields`/`platform`/`preferNative`/`sourceExts`
238
- // drive the legacy-field + suffix probing.
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.
151
+ // `kept`: a Map kept across a lazy tree's rounds (untouchedMemo's `across`).
249
152
  export function createFieldResolver({
250
153
  conditions = [],
251
154
  mainFields = ['main'],
@@ -263,74 +166,61 @@ export function createFieldResolver({
263
166
  const read = manifestReader(host)
264
167
  const outputs = typescript ? typescriptPaths?.outputs ?? tsconfigOutputsOf({ host }) : null
265
168
  const opts = { platform, preferNative, sourceExts, mainFields, typescript, outputs, host, read }
266
- // An importer in node_modules gets no --typescript mapping (inNodeModules), wherever its import lands.
169
+ // An importer in node_modules gets no --typescript mapping, wherever its import lands.
267
170
  const fromNodeModules = { ...opts, typescript: false }
268
- // Node answers a builtin name with the builtin itself, so an `exports`-bearing package named like
269
- // one (see the header) resolves through this instead, with builtins off; built on first use.
171
+ // Node answers a builtin name with the builtin, so a package named like one resolves through this, builtins off.
270
172
  let packageResolver
271
173
  const nodeResolver = () => (packageResolver ??= createNodeResolver(host))
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 }))
285
- }
286
- return metroResolvers.get(key)
287
- }
174
+ // --typescript resolves Metro's misses again over typescriptView, never from node_modules, so it never overrides Metro.
175
+ const metroResolver = memoized(({ conditionNames, substituting }) => {
176
+ const view = metroHost(host, mainFields)
177
+ return createMetroResolver({ host: substituting ? typescriptView(view, opts) : view, sourceExts, assetExts, assetResolutions, mainFields, conditionNames, conditionsByPlatform: {}, preferNativePlatform: preferNative })
178
+ }, ({ conditionNames, substituting }) => `${substituting}\0${conditionNames.join('\0')}`)
288
179
  const viaMetro = (parentFile, specifier, conds) => {
289
180
  const conditionNames = [...conds].filter((name) => !METRO_OWN_CONDITIONS.has(name))
290
181
  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)
182
+ let resolution = metroResolver({ conditionNames, substituting: false })(parentFile, specifier, request)
183
+ if (resolution === null && typescript && !inNodeModules(parentFile, host)) resolution = metroResolver({ conditionNames, substituting: true })(parentFile, specifier, request)
293
184
  const remapped = () => {
294
185
  const imp = nearestPackage(parentFile, host, read)
295
186
  return imp !== null && matchRedirect(mergeRedirectMap(imp.pkg, mainFields), specifier) !== undefined
296
187
  }
297
188
  return scanResolution(resolution, resolution === null && isBuiltin(specifier) && !remapped())
298
189
  }
299
- // `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
300
- // delegation matches Node resolving from THAT file; falls back to configured `conditions`.
301
- const resolve = function resolve(parentFile, specifier, callConditions) {
190
+ // `callConditions`: scan's, by the parent's format. What a miss tried goes in `tried`, the missTargets.
191
+ const resolve = function resolve(parentFile, specifier, callConditions, tried) {
302
192
  const fileOpts = typescript && inNodeModules(parentFile, host) ? fromNodeModules : opts
303
193
  const conds = new Set(callConditions ?? conditions)
194
+ const probe = (base) => {
195
+ const hit = resolveFileOrDir(base, fileOpts, tried)
196
+ if (hit === null) tried.push(base)
197
+ return hit
198
+ }
304
199
  const viaNode = (spec) => {
305
200
  try {
306
201
  if (!isBuiltin(spec)) return fileResolution(host.resolve(parentFile, spec, conds), host)
307
202
  return fileResolution(nodeResolver().resolve(parentFile, spec, conds, { builtins: false }), host)
308
- } catch {
203
+ } catch (error) {
204
+ if (typeof error.target === 'string') tried.push(error.target)
309
205
  return null
310
206
  }
311
207
  }
312
- // A bare specifier (`mod`, `mod/sub`) through node_modules.
313
208
  const viaPackage = (spec) => {
314
209
  const loc = locatePackage(dirname(parentFile), spec, host)
315
210
  if (!loc) return null
316
211
  const pkg = read(join(loc.pkgDir, 'package.json')) ?? {}
317
- // `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
318
212
  if (pkg.exports != null) return viaNode(spec)
319
- // A bare package import resolves its directory via the same dir algorithm as any other.
320
- if (loc.subpath === '') return resolveFileOrDir(loc.pkgDir, fileOpts)
213
+ if (loc.subpath === '') return probe(loc.pkgDir)
321
214
  const sub = `./${loc.subpath}`
322
215
  const r = matchRedirect(mergeRedirectMap(pkg, mainFields), sub)
323
216
  if (r === false) return { empty: true }
324
- const target = typeof r === 'string' ? r : sub
325
- return resolveFileOrDir(join(loc.pkgDir, target), fileOpts)
217
+ return probe(join(loc.pkgDir, typeof r === 'string' ? r : sub))
326
218
  }
327
219
  if (metro) return viaMetro(parentFile, specifier, conds)
328
- // `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them.
329
220
  if (specifier.startsWith('#')) return viaNode(specifier)
330
221
 
331
222
  let spec = specifier
332
- // Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
333
- // a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
223
+ // The importer's map applies before the builtin check: it can disable or shim a builtin (`{"crypto": false}`).
334
224
  const imp = nearestPackage(parentFile, host, read)
335
225
  if (imp) {
336
226
  const map = mergeRedirectMap(imp.pkg, mainFields)
@@ -339,65 +229,45 @@ export function createFieldResolver({
339
229
  const abs = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
340
230
  r = matchRedirect(map, `./${toPosix(relative(imp.pkgDir, abs))}`)
341
231
  } else {
342
- r = map.get(spec) // a bare specifier (`mod`, `mod/sub`) matches the map's bare keys
232
+ r = map.get(spec)
343
233
  }
344
234
  if (r === false) return { empty: true }
345
235
  if (typeof r === 'string') {
346
- // Browser-map targets are relative to the PACKAGE ROOT, not the importing file; a
347
- // bare-module target re-enters resolution below.
348
- if (r.startsWith('.') || isAbsolute(r)) {
349
- return resolveFileOrDir(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r), fileOpts)
350
- }
236
+ // A path target is relative to the package root, not the importing file; a bare one is resolved below.
237
+ if (r.startsWith('.') || isAbsolute(r)) return probe(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r))
351
238
  spec = r
352
239
  }
353
240
  }
354
-
355
- if (spec.startsWith('.') || isAbsolute(spec)) {
356
- const base = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
357
- return resolveFileOrDir(base, fileOpts)
358
- }
359
-
360
- // A builtin the browser map did not remap: its `node:` form names the builtin itself; a bare
361
- // name is the installed package of that name (see the header), the builtin where none resolves.
241
+ if (spec.startsWith('.') || isAbsolute(spec)) return probe(isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec))
362
242
  if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
363
243
  return viaPackage(spec)
364
244
  }
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)
371
- // --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
372
- // the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
373
- // the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
374
- // imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
375
- // `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
376
- // (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
377
- return once(function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
378
- const resolved = resolve(parentFile, specifier, callConditions)
379
- if (resolved) return resolved
245
+ // --typescript: a miss of the whole field flow, and only a miss, gets the scanner's fallback too.
246
+ const resolveWithTypescriptFallback = (parentFile, specifier, callConditions, tried) => {
247
+ const resolved = resolve(parentFile, specifier, callConditions, tried)
380
248
  // Under --metro an asset is Metro's asset rule's to resolve, as tsc never does.
381
- if (metro && isAssetFile(specifier, assetExts)) return null
382
- const hit = resolveTypescriptFallback(parentFile, specifier, {
383
- conditions: new Set(callConditions ?? conditions),
384
- paths: typescriptPaths,
385
- host,
386
- })
387
- return hit == null ? null : fileResolution(hit, host)
249
+ if (resolved || !typescript || (metro && isAssetFile(specifier, assetExts))) return resolved
250
+ const conds = new Set(callConditions ?? conditions)
251
+ const hit = resolveTypescriptFallback(parentFile, specifier, { conditions: conds, paths: typescriptPaths, host })
252
+ if (hit != null) return fileResolution(hit, host)
253
+ const aliased = typescriptPaths !== null && !RELATIVE_REQUEST.test(specifier) && !isAbsolute(specifier) && !specifier.startsWith('#') && !inNodeModules(parentFile, host)
254
+ if (aliased) tried.push(...typescriptPaths.matchPaths(specifier, parentFile))
255
+ return null
256
+ }
257
+ // Once per directory (all a file's resolving reads), specifier and conditions, kept as the manifests are and in `kept`.
258
+ const resolutions = hostMemo(host, { across: kept })
259
+ const of = (parentFile, specifier, callConditions) => resolutions(`${dirname(parentFile)}\0${specifier}\0${[...callConditions ?? conditions].join('\0')}`, () => {
260
+ const tried = []
261
+ return { resolution: resolveWithTypescriptFallback(parentFile, specifier, callConditions, tried), tried }
262
+ })
263
+ return Object.assign((parentFile, specifier, callConditions) => of(parentFile, specifier, callConditions).resolution, {
264
+ missTargets: (parentFile, specifier, callConditions) => of(parentFile, specifier, callConditions).tried,
388
265
  })
389
266
  }
390
267
 
391
- // True when `format` is an ESM family (drives the base condition set, mirroring scan).
392
- function isModuleFormat(format) {
393
- return format === 'module' || format === 'module-typescript'
394
- }
395
-
396
- // Condition set for a parent of the given format, as scan's #conditionSet gives a custom resolver:
397
- // `import` or `require` by format, `default` (which Node's resolver matches anyway), plus extras.
398
- // A bundler's base, not Node's: esbuild, webpack and Metro assert `import`/`require` and
399
- // `default`, never `node`, so an `exports` map listing `node` first can't win over the extras.
400
- // Order is irrelevant (Node membership-tests against exports key order).
268
+ // As scan's #conditionSet gives a custom resolver: a bundler's base, not Node's. esbuild, webpack and Metro assert
269
+ // `import`/`require` and `default`, never `node`, so an `exports` map listing `node` first can't win over the extras.
401
270
  export function resolveConditions(format, extras = []) {
402
- return [...new Set([isModuleFormat(format) ? 'import' : 'require', 'default', ...extras])]
271
+ const esm = format === 'module' || format === 'module-typescript'
272
+ return [...new Set([esm ? 'import' : 'require', 'default', ...extras])]
403
273
  }