@exodus/stasis 1.0.0-beta.2 → 1.0.0-beta.5

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 (45) hide show
  1. package/README.md +23 -3
  2. package/bin/stasis.js +375 -170
  3. package/package.json +44 -11
  4. package/src/audit-corrections.js +68 -0
  5. package/src/audit.js +243 -59
  6. package/src/babel-worker.cjs +65 -0
  7. package/src/babel.js +131 -0
  8. package/src/bundle-from-lockfile.js +12 -18
  9. package/src/bundle-reader.js +77 -0
  10. package/src/cmd/build.js +95 -128
  11. package/src/cmd/bundle.js +877 -641
  12. package/src/cmd/diff.js +2 -19
  13. package/src/cmd/github-bundle.js +39 -0
  14. package/src/cmd/output.js +36 -0
  15. package/src/cmd/sbom.js +4 -18
  16. package/src/diff.js +67 -124
  17. package/src/json-stream.js +283 -0
  18. package/src/loader-mock.js +8 -15
  19. package/src/loaders/bash.js +49 -116
  20. package/src/loaders/cargo.js +1699 -0
  21. package/src/loaders/foundry.js +923 -0
  22. package/src/loaders/paths.js +33 -0
  23. package/src/loaders/php.js +339 -394
  24. package/src/loaders/rust.js +3254 -242
  25. package/src/loaders/solidity-ownership.js +531 -0
  26. package/src/loaders/solidity.js +412 -162
  27. package/src/loaders/toml.js +68 -0
  28. package/src/metro-resolver.js +150 -0
  29. package/src/mock.js +57 -165
  30. package/src/parse.js +4 -16
  31. package/src/resolve-fields.js +331 -0
  32. package/src/resolve-node.js +416 -0
  33. package/src/resolve-typescript.js +427 -0
  34. package/src/rollup.js +5 -0
  35. package/src/sbom.js +64 -92
  36. package/src/scan.js +234 -156
  37. package/src/vfs-bundle/entries.js +140 -0
  38. package/src/vfs-bundle/github.js +193 -0
  39. package/src/vfs-bundle/soldeer.js +125 -0
  40. package/src/vfs-bundle/tree.js +606 -0
  41. package/src/vfs-bundle.js +74 -0
  42. package/src/why.js +434 -0
  43. package/src/apis/npm/index.js +0 -36
  44. package/src/apis/npm/semver.cjs +0 -44
  45. package/src/cmd/extract.js +0 -193
@@ -0,0 +1,331 @@
1
+ import { isBuiltin } from 'node:module'
2
+ import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
3
+ import { pathToFileURL } from 'node:url'
4
+
5
+ import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
6
+ import {
7
+ isDir,
8
+ isFile,
9
+ locatePackage,
10
+ nearestPackage,
11
+ readJson,
12
+ resolveTypescriptFallback,
13
+ typescriptSiblings,
14
+ } from './resolve-typescript.js'
15
+ import { diskHost } from '@exodus/stasis-core/host'
16
+
17
+ // Static module resolver for legacy package fields (`react-native`/`browser`/`main` + browser-spec
18
+ // redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
19
+ // resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
20
+ // delegated to Node. No user code is executed (only package.json is stat/read).
21
+ //
22
+ // Returns, for each specifier:
23
+ // { url } resolved to a real file (file: URL string)
24
+ // { empty } a browser/react-native field mapped it to `false` (empty module)
25
+ // { builtin } a Node builtin
26
+ // null unresolved
27
+
28
+ // Metro divergence toggle. When a package's browser map maps its OWN entry to `false` (under
29
+ // Metro's matching rules, which include bare keys like {"buf": false} for main "./buf.js"),
30
+ // Metro's `getPackageEntryPoint` ignores the non-string replacement and keeps `main`. The
31
+ // `--metro` resolver matches that by default; flip this to `false` to fail closed instead:
32
+ // a `false` match on the entry then yields an EMPTY module. Note the off state is deliberately
33
+ // stricter than both tools -- for a bare-key `false`, Metro keeps `main` and esbuild would not
34
+ // match the entry at all -- it exists as an escape hatch, not an esbuild-parity mode. This only
35
+ // affects the `--metro` path; the `--mainFields` path always empties (matching esbuild).
36
+ // Tests can override per-resolver via createFieldResolver's `metroKeepEntryOnBrowserFalse`.
37
+ const METRO_KEEP_ENTRY_ON_BROWSER_FALSE = true
38
+
39
+ // First mainFields entry that's a non-empty string, else `index` (object-valued fields are redirect maps).
40
+ function packageEntry(pkg, mainFields) {
41
+ for (const name of mainFields) {
42
+ if (typeof pkg?.[name] === 'string' && pkg[name].length > 0) return pkg[name]
43
+ }
44
+ return 'index'
45
+ }
46
+
47
+ // Merge object-valued mainFields (browser-spec maps) into one redirect map. Iterate in REVERSE
48
+ // so earlier mainFields win on conflict. Keys are verbatim: `./x` relative vs bare `x` (kept bare).
49
+ function mergeRedirectMap(pkg, mainFields) {
50
+ const map = new Map()
51
+ for (let i = mainFields.length - 1; i >= 0; i--) {
52
+ const field = pkg?.[mainFields[i]]
53
+ if (!field || typeof field !== 'object') continue
54
+ for (const [key, value] of Object.entries(field)) {
55
+ if (typeof value !== 'string' && value !== false) continue
56
+ map.set(key, value)
57
+ }
58
+ }
59
+ return map
60
+ }
61
+
62
+ // Metro's entry-variant list for `main` (getPackageEntryPoint, metro-resolver
63
+ // PackageResolve.js): the main spelling and its ./-toggled twin, each expanded to
64
+ // [self, +'.js', +'.json', ext-stripped]. ORDER MATTERS -- the first variant with ANY mapping
65
+ // (string or false) decides, so this must reproduce Metro's list exactly, duplicates included.
66
+ function metroEntryVariants(main) {
67
+ const toggled = main.startsWith('./') ? main.slice(2) : `./${main}`
68
+ return [main, toggled].flatMap((v) => [v, `${v}.js`, `${v}.json`, v.replace(/\.(?:js|json)$/u, '')])
69
+ }
70
+
71
+ // Resolve the package ENTRY (from mainFields) through the package's own redirect map.
72
+ // Returns { entry } (the redirected or original entry to resolve) or { empty: true }.
73
+ // Both halves of the entry semantics -- WHICH keys match, and what `false` means -- live here
74
+ // so no caller can get one without the other:
75
+ // - metro: Metro's getPackageEntryPoint. First matching variant (Metro's order) wins; a string
76
+ // redirects; `false` (any non-string) keeps `main`, unless the keep-on-false toggle is off,
77
+ // in which case it fails closed to an empty module (see METRO_KEEP_ENTRY_ON_BROWSER_FALSE).
78
+ // - default (--mainFields): esbuild-shaped candidates; `false` empties the entry, matching
79
+ // esbuild. The extension-STRIPPED bare spelling is not probed: for an extensioned main,
80
+ // esbuild treats it as a bare module name, not the entry. (For an extensionless main the
81
+ // `bare` candidate covers it -- esbuild does match that spelling; verified empirically.)
82
+ function resolveEntryThroughMap(map, main, opts) {
83
+ if (map.size === 0) return { entry: main }
84
+ let cands
85
+ if (opts.metro) {
86
+ cands = metroEntryVariants(main)
87
+ } else {
88
+ const bare = main.replace(/^\.\//u, '')
89
+ const stripped = bare.replace(/\.(?:js|json)$/u, '')
90
+ cands = [
91
+ `./${bare}`, bare,
92
+ `./${stripped}`,
93
+ `./${stripped}.js`, `${stripped}.js`,
94
+ `./${stripped}.json`, `${stripped}.json`,
95
+ ]
96
+ }
97
+ for (const cand of cands) {
98
+ const v = map.get(cand)
99
+ if (typeof v === 'string') return { entry: v }
100
+ if (v === false) {
101
+ if (opts.metro && opts.metroKeepEntryOnBrowserFalse) return { entry: main }
102
+ return { empty: true }
103
+ }
104
+ }
105
+ return { entry: main }
106
+ }
107
+
108
+ const fileResolution = (path) => ({ url: pathToFileURL(path).toString() })
109
+
110
+ // Match a package-relative path (`./x`) against the redirect map, trying `.js`/`.json` appended.
111
+ function matchRedirect(map, relPath) {
112
+ if (map.size === 0) return undefined
113
+ for (const cand of [relPath, `${relPath}.js`, `${relPath}.json`]) {
114
+ if (map.has(cand)) return map.get(cand)
115
+ }
116
+ return undefined
117
+ }
118
+
119
+ // Probe `base` for a source file in platform order: bare name first, then per ext
120
+ // `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
121
+ // disables suffixes. Under metro, every SUFFIXED candidate first passes through the candidate's
122
+ // own package redirect map -- mirroring Metro's resolveSourceFileForExt, which runs
123
+ // redirectModulePath on each non-bare candidate: `false` short-circuits the whole probe to an
124
+ // empty module (e.g. browser { "./index.ios.js": false }), and a string redirect re-lands the
125
+ // candidate package-root-relative. Returns a path, { empty: true } (metro only), or null.
126
+ function resolveSourceFile(base, opts) {
127
+ // A path that literally names a `.d.ts` names no runtime module (types are erased). Probe its
128
+ // declaration-free stem instead, so an entry field pointing at `dist/index.d.ts` lands on the real
129
+ // `dist/index.js` beside it rather than bundling the declaration -- or failing the package
130
+ // outright by falling back to a different index. The probe below still refuses a literal hit.
131
+ base = stripTypeDeclaration(base)
132
+ // Candidates share base's directory, hence its package scope; resolve it lazily, once.
133
+ let scope
134
+ const redirectCandidate = (p) => {
135
+ if (scope === undefined) {
136
+ const pkg = nearestPackage(base, opts.host)
137
+ scope = pkg ? { pkgDir: pkg.pkgDir, map: mergeRedirectMap(pkg.pkg, opts.mainFields) } : null
138
+ }
139
+ if (!scope || scope.map.size === 0) return p
140
+ const rel = `./${toPosix(relative(scope.pkgDir, p))}`
141
+ const r = matchRedirect(scope.map, rel)
142
+ if (r === false) return false
143
+ if (typeof r === 'string') return isAbsolute(r) ? r : resolvePath(scope.pkgDir, r)
144
+ return p
145
+ }
146
+ // `derived` marks a candidate that is not the literal base; Metro redirect-checks those only.
147
+ const probePath = (p, derived) => {
148
+ if (opts.metro && derived) {
149
+ const r = redirectCandidate(p)
150
+ if (r === false) return { empty: true }
151
+ p = r
152
+ }
153
+ // A `.d.ts` is types-only, erased at runtime: never a resolution target, so a package whose
154
+ // entry field points at one falls through to its real `.js` instead of bundling the declaration.
155
+ if (isTypeDeclaration(p)) return null
156
+ return isFile(p, opts.host) ? p : null
157
+ }
158
+ // `suffix` is everything appended to `base`.
159
+ const probe = (suffix) => probePath(`${base}${suffix}`, suffix !== '')
160
+ const tryExt = (sourceExt) => {
161
+ if (opts.platform) {
162
+ const hit = probe(`.${opts.platform}${sourceExt}`)
163
+ if (hit) return hit
164
+ }
165
+ if (opts.preferNative && sourceExt !== '') {
166
+ const hit = probe(`.native${sourceExt}`)
167
+ if (hit) return hit
168
+ }
169
+ return probe(sourceExt)
170
+ }
171
+ const bare = tryExt('')
172
+ if (bare) return bare
173
+ // --typescript: tsc's extension substitution. A base naming a JS output extension probes its TS
174
+ // source siblings once the literal file (the bare probe above) is absent, so the on-disk `.js`
175
+ // always wins over its `.ts` twin. Literal siblings only -- no platform suffixes (tsc has none);
176
+ // extensionless bases keep going through the appended-extension loop below (sourceExts carries
177
+ // ts, and tsx under --jsx). Placed before that loop so `x.js` -> `x.ts` beats a pathological
178
+ // `x.js.<ext>`, matching tsc's candidate order.
179
+ if (opts.typescript) {
180
+ for (const cand of typescriptSiblings(base, { tsx: opts.sourceExts.includes('tsx') })) {
181
+ const hit = probePath(cand, true)
182
+ if (hit) return hit
183
+ }
184
+ }
185
+ for (const ext of opts.sourceExts) {
186
+ const hit = tryExt(`.${ext}`)
187
+ if (hit) return hit
188
+ }
189
+ return null
190
+ }
191
+
192
+ // Resolve absolute `base` as a file (ext probing) else as a directory (package.json `main` via
193
+ // mainFields + entry redirect, else `index`). `exports` is NOT consulted — Node applies it only to
194
+ // bare package-name imports, not to a path landing on a directory.
195
+ function resolveFileOrDir(base, opts) {
196
+ // resolveSourceFile yields a path, { empty: true } (a metro candidate-redirect hit), or null.
197
+ const asResolution = (hit) => (hit == null ? null : typeof hit === 'string' ? fileResolution(hit) : hit)
198
+ const file = asResolution(resolveSourceFile(base, opts))
199
+ if (file) return file
200
+ if (isDir(base, opts.host)) {
201
+ const dpkg = readJson(join(base, 'package.json'), opts.host)
202
+ if (dpkg) {
203
+ const r = resolveEntryThroughMap(mergeRedirectMap(dpkg, opts.mainFields), packageEntry(dpkg, opts.mainFields), opts)
204
+ if (r.empty) return { empty: true }
205
+ // Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
206
+ // (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
207
+ const entryBase = join(base, r.entry)
208
+ const inner = asResolution(resolveSourceFile(entryBase, opts) ?? resolveSourceFile(join(entryBase, 'index'), opts))
209
+ if (inner) return inner
210
+ }
211
+ const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
212
+ if (index) return index
213
+ }
214
+ return null
215
+ }
216
+
217
+ // Build a resolver bound to options: `conditions` gates `exports` packages (delegated to Node),
218
+ // `mainFields`/`platform`/`preferNative`/`sourceExts` drive the legacy-field + suffix probing.
219
+ // `metro` opts into Metro's package-entry + candidate-redirect semantics (see
220
+ // resolveEntryThroughMap and resolveSourceFile); leave it off for the esbuild-parity
221
+ // `--mainFields` path. `typescript` adds tsc's extension substitution (a missing `x.js` probes
222
+ // its `x.ts` sibling; see resolveSourceFile) plus the shared miss fallback (see below), and
223
+ // `typescriptPaths` (a loadTsconfigPaths matcher) its tsconfig alias mapping.
224
+ // `metroKeepEntryOnBrowserFalse` overrides the module-level toggle
225
+ // (METRO_KEEP_ENTRY_ON_BROWSER_FALSE) per resolver -- primarily so tests can cover both branches.
226
+ // `host` is the filesystem view (@exodus/stasis-core/host), the real disk by default.
227
+ export function createFieldResolver({
228
+ conditions = [],
229
+ mainFields = ['main'],
230
+ platform = null,
231
+ preferNative = false,
232
+ sourceExts = ['js', 'json', 'ts'],
233
+ metro = false,
234
+ typescript = false,
235
+ typescriptPaths = null,
236
+ metroKeepEntryOnBrowserFalse = METRO_KEEP_ENTRY_ON_BROWSER_FALSE,
237
+ host = diskHost,
238
+ } = {}) {
239
+ const opts = { platform, preferNative, sourceExts, mainFields, metro, typescript, metroKeepEntryOnBrowserFalse, host }
240
+ // `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
241
+ // delegation matches Node resolving from THAT file; falls back to configured `conditions`.
242
+ const resolve = function resolve(parentFile, specifier, callConditions) {
243
+ const conds = new Set(callConditions ?? conditions)
244
+ const viaNode = (spec) => {
245
+ try {
246
+ return fileResolution(host.resolve(parentFile, spec, conds))
247
+ } catch {
248
+ return null
249
+ }
250
+ }
251
+ // `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them.
252
+ if (specifier.startsWith('#')) return viaNode(specifier)
253
+
254
+ let spec = specifier
255
+ // Redirect via the IMPORTER's browser/react-native map, BEFORE the builtin check on purpose:
256
+ // a map entry can disable or shim a builtin (`{"crypto": false}` / `"crypto-browserify"`).
257
+ const imp = nearestPackage(parentFile, host)
258
+ if (imp) {
259
+ const map = mergeRedirectMap(imp.pkg, mainFields)
260
+ let r
261
+ if (spec.startsWith('.') || isAbsolute(spec)) {
262
+ const abs = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
263
+ r = matchRedirect(map, `./${toPosix(relative(imp.pkgDir, abs))}`)
264
+ } else {
265
+ r = map.get(spec) // a bare specifier (`mod`, `mod/sub`) matches the map's bare keys
266
+ }
267
+ if (r === false) return { empty: true }
268
+ if (typeof r === 'string') {
269
+ // Browser-map targets are relative to the PACKAGE ROOT, not the importing file; a
270
+ // bare-module target re-enters resolution below.
271
+ if (r.startsWith('.') || isAbsolute(r)) {
272
+ return resolveFileOrDir(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r), opts)
273
+ }
274
+ spec = r
275
+ }
276
+ }
277
+
278
+ // A builtin the browser map did not remap resolves to the builtin itself.
279
+ if (isBuiltin(spec)) return { builtin: true }
280
+
281
+ if (spec.startsWith('.') || isAbsolute(spec)) {
282
+ const base = isAbsolute(spec) ? spec : resolvePath(dirname(parentFile), spec)
283
+ return resolveFileOrDir(base, opts)
284
+ }
285
+
286
+ const loc = locatePackage(dirname(parentFile), spec, host)
287
+ if (!loc) return null
288
+ const pkg = readJson(join(loc.pkgDir, 'package.json'), host) ?? {}
289
+ // `exports` wins over mainFields; Node's algorithm resolves it (with conditions) correctly.
290
+ if (pkg.exports != null) return viaNode(spec)
291
+ // A bare package import resolves its directory via the same dir algorithm as any other.
292
+ if (loc.subpath === '') return resolveFileOrDir(loc.pkgDir, opts)
293
+ const sub = `./${loc.subpath}`
294
+ const r = matchRedirect(mergeRedirectMap(pkg, mainFields), sub)
295
+ if (r === false) return { empty: true }
296
+ const target = typeof r === 'string' ? r : sub
297
+ return resolveFileOrDir(join(loc.pkgDir, target), opts)
298
+ }
299
+ if (!typescript) return resolve
300
+ // --typescript: when the whole field flow leaves the specifier unresolved, give tsc's mapping
301
+ // the same shot the scanner's fallback gets, via the shared dispatcher. On this path it covers
302
+ // the layers the field resolver delegates to Node -- `exports`-bearing packages and `#` subpath
303
+ // imports, whose targets may name compiled files existing only as TS source -- plus tsconfig
304
+ // `paths` aliases; misses only, so no field/redirect/suffix resolution is ever overridden.
305
+ // (Relative paths re-probe tsc-style too -- redundant after resolveSourceFile, but harmless.)
306
+ return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
307
+ const resolved = resolve(parentFile, specifier, callConditions)
308
+ if (resolved) return resolved
309
+ const hit = resolveTypescriptFallback(parentFile, specifier, {
310
+ conditions: new Set(callConditions ?? conditions),
311
+ tsx: sourceExts.includes('tsx'),
312
+ paths: typescriptPaths,
313
+ host,
314
+ })
315
+ return hit == null ? null : fileResolution(hit)
316
+ }
317
+ }
318
+
319
+ // True when `format` is an ESM family (drives the base condition set, mirroring scan).
320
+ function isModuleFormat(format) {
321
+ return format === 'module' || format === 'module-typescript'
322
+ }
323
+
324
+ // Condition set for a parent of the given format: Node's format-driven base (matching scan's
325
+ // #conditionsFor) plus extras. Order is irrelevant (Node membership-tests against exports key order).
326
+ export function resolveConditions(format, extras = []) {
327
+ const base = isModuleFormat(format)
328
+ ? ['node', 'import', 'module-sync', 'node-addons']
329
+ : ['node', 'require', 'module-sync', 'node-addons']
330
+ return [...new Set([...base, ...extras])]
331
+ }