@exodus/stasis 1.0.0-beta.8 → 1.0.0-rc.0

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 (66) hide show
  1. package/README.md +7 -2
  2. package/bin/stasis.js +263 -446
  3. package/package.json +38 -13
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1718 -908
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +24 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  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 +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +221 -475
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +170 -235
  44. package/src/resolve-node.js +33 -46
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +241 -278
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +54 -46
  57. package/src/vfs-bundle/github.js +115 -92
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +434 -259
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +25 -51
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
@@ -1,150 +1,75 @@
1
1
  import { createRequire, isBuiltin } from 'node:module'
2
- import { dirname, isAbsolute, join } from 'node:path'
2
+ import { basename, join } from 'node:path'
3
3
  import { pathToFileURL } from 'node:url'
4
4
 
5
+ import { createMetroResolver as createRnMetroResolver, defaults } from '@preventive/rn/metro-resolver.js'
5
6
  import { diskHost } from '@exodus/stasis-core/host'
6
- import { isTypeDeclaration } from '@exodus/stasis-core/util'
7
- import { readJson } from './resolve-typescript.js'
7
+ import { isPlainObject, isTypeDeclaration } from '@exodus/stasis-core/util'
8
+ import { isDir, isSourceFile } from './resolve-typescript.js'
8
9
 
9
- // Adapter that drives the PROJECT's own `metro-resolver` from stasis's static scanner, so
10
- // `stasis bundle --metro --metro-resolver` resolves modules EXACTLY the way that project's
11
- // installed Metro does -- rather than the hand-rolled Metro/RN approximation in
12
- // resolve-fields.js. `metro-resolver` is a leaf of the Metro toolchain (it takes a context of
13
- // filesystem callbacks and does no I/O of its own), so we load whichever copy the project
14
- // already ships and feed it a synchronous, disk-backed ResolutionContext.
15
- //
16
- // Returns, for each specifier, the same shape scan.js expects from a custom resolver:
17
- // { url } resolved to a real file (file: URL string)
18
- // { empty } a browser/react-native field mapped it to `false` (empty module)
19
- // { builtin } a Node builtin (Metro itself has none; we classify a bare-name miss)
20
- // null unresolved
21
- //
22
- // It is deliberately version-agnostic: it never imports metro-resolver internals (the
23
- // `./private/*` subpath), only the public `resolve`. `resolve` applies the browser-field
24
- // redirect via its own bundled helper, so the `redirectModulePath` we place on the context is
25
- // an inert placeholder that satisfies the type but is never consulted for base resolution.
10
+ // Metro's module resolution is @preventive/rn's. What stays stasis's: no `.d.ts` is a module (metroHost), a builtin
11
+ // Metro misses is a builtin, and answers take the shape scan.js expects (scanResolution).
26
12
 
27
- // 'f' | 'd' | null for a path, without throwing.
28
- function pathType(p) {
29
- const s = diskHost.stat(p)
30
- return s?.isFile() ? 'f' : s?.isDirectory() ? 'd' : null
31
- }
13
+ export const stripTypeDeclaration = (name) => name.replace(/\.d\.[mc]?ts$/iu, '')
14
+
15
+ const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
16
+ const DECLARATION = /\.d\.[cm]?ts\b/iu
32
17
 
33
- // A `.d.ts` is types-only, erased at runtime, so the resolver must never land on one: report it as
34
- // non-existent to Metro's filesystem hooks and a package whose entry points at a declaration falls
35
- // through to its real `.js`. Only the RESOLUTION hooks use this -- getPackageForModule's own
36
- // dir-vs-file probe stays on raw pathType (it locates package scopes, never a module target).
37
- const resolvableType = (p) => (isTypeDeclaration(p) ? null : pathType(p))
18
+ // An entry field naming a `.d.ts` names its stem, so the entry lands on the real module beside it.
19
+ function manifestStems(bytes, mainFields) {
20
+ let manifest
21
+ try {
22
+ const text = utf8.decode(bytes)
23
+ if (!DECLARATION.test(text)) return bytes
24
+ manifest = JSON.parse(text)
25
+ } catch {
26
+ return bytes
27
+ }
28
+ if (!isPlainObject(manifest)) return bytes
29
+ const typed = mainFields.filter((field) => typeof manifest[field] === 'string' && isTypeDeclaration(manifest[field]))
30
+ if (typed.length === 0) return bytes
31
+ for (const field of typed) manifest[field] = stripTypeDeclaration(manifest[field])
32
+ return Buffer.from(JSON.stringify(manifest))
33
+ }
38
34
 
39
- // Metro's `getPackageForModule`: the closest package scope for an absolute candidate path
40
- // (which need not exist). The candidate can be a package DIRECTORY (a bare import lands on
41
- // `<node_modules>/<pkg>`), so probing starts at the path itself, then walks up. `packageRelativePath`
42
- // is '' when the candidate IS the package root -- Metro's exports resolver maps '' to the '.' subpath,
43
- // and a stray '.' there would mismatch the exports key.
44
- function getPackageForModule(absModulePath) {
45
- let dir = pathType(absModulePath) === 'd' ? absModulePath : dirname(absModulePath)
46
- while (true) {
47
- const pkg = readJson(join(dir, 'package.json'))
48
- if (pkg) {
49
- const rel = dir === absModulePath ? '' : absModulePath.slice(dir.length + 1)
50
- return { rootPath: dir, packageJson: pkg, packageRelativePath: rel }
51
- }
52
- const parent = dirname(dir)
53
- if (parent === dir) return null
54
- dir = parent
35
+ // A `.d.ts` is types-only, erased at runtime, so the resolver never lands on one.
36
+ export function metroHost(host, mainFields = defaults.mainFields) {
37
+ return {
38
+ isFile: (path) => isSourceFile(path, host),
39
+ isDirectory: (path) => isDir(path, host),
40
+ realpath: (path) => host.realpath(path),
41
+ readFile: (path) => (basename(path) === 'package.json' ? manifestStems(host.readFile(path), mainFields) : host.readFile(path)),
55
42
  }
56
43
  }
57
44
 
58
- // Build a resolver bound to a platform. `metro-resolver` is required from `projectDir` so we
59
- // honour the version the project's Metro uses; a missing package throws with actionable guidance.
60
- // `sourceExts` are the extensions Metro probes (kept to what a source bundle can carry, so the
61
- // resolver never lands on a file the bundle would reject). `mainFields` drives the browser-field
62
- // spec; `conditionNames` are the extra `exports`/`imports` conditions on top of the ones Metro
63
- // derives itself (default + require|import + platform).
64
- export function createMetroResolver({
65
- projectDir,
66
- platform,
67
- sourceExts = ['js', 'jsx', 'json', 'ts', 'tsx'],
68
- mainFields = ['react-native', 'browser', 'main'],
69
- conditionNames = ['react-native'],
70
- conditionsByPlatform = { web: ['browser'] },
71
- enablePackageExports = true,
72
- host = diskHost,
73
- } = {}) {
74
- // It loads the project's metro-resolver, which reads the disk: never off it.
45
+ // Metro builds an asset of several files into the module of the lowest path (getArrayLowestItem).
46
+ const lowestPath = (paths) => paths.reduce((lowest, path) => (path < lowest ? path : lowest))
47
+
48
+ // `builtin`: whether a specifier Metro failed (null) is a Node builtin.
49
+ export function scanResolution(resolution, builtin) {
50
+ if (resolution === null) return builtin ? { builtin: true } : null
51
+ if (resolution.type === 'empty') return { empty: true }
52
+ const file = resolution.type === 'sourceFile' ? resolution.filePath : lowestPath(resolution.filePaths)
53
+ return { url: pathToFileURL(file).toString() }
54
+ }
55
+
56
+ // `--metro-resolver`: through the project's own `metro-resolver`, given the context Metro's DependencyGraph builds.
57
+ export function createMetroResolver({ projectDir, platform, sourceExts, mainFields, conditionNames, conditionsByPlatform, assetExts, assetResolutions, host = diskHost } = {}) {
75
58
  if (host !== diskHost) throw new Error('createMetroResolver: metro-resolver reads the disk, so it is not supported off disk')
76
- const require = createRequire(join(projectDir, 'noop.js'))
77
- let resolve
59
+ let metroResolver
78
60
  try {
79
- ;({ resolve } = require('metro-resolver'))
61
+ metroResolver = createRequire(join(projectDir, 'noop.js'))('metro-resolver')
80
62
  } catch (cause) {
81
- throw new Error(
82
- `StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver ` +
83
- 'resolves through the project\'s own Metro; install it (it ships with react-native/metro) ' +
84
- 'or drop --metro-resolver to use the built-in resolver.',
85
- { cause }
86
- )
63
+ throw new Error(`StasisMetroResolver: couldn't load 'metro-resolver' from ${projectDir}. --metro-resolver resolves through the `
64
+ + 'project\'s own Metro; install it (it ships with react-native/metro) or drop --metro-resolver to use the built-in resolver.', { cause })
87
65
  }
88
-
89
- // A React Native app has no Node builtins by default; Metro only prefers native suffixes off web.
90
- const base = {
91
- allowHaste: false,
92
- assetExts: new Set(),
93
- customResolverOptions: {},
94
- disableHierarchicalLookup: false,
95
- doesFileExist: (p) => resolvableType(p) === 'f',
96
- extraNodeModules: null,
97
- dev: false,
98
- getPackage: (packageJsonPath) => readJson(packageJsonPath),
99
- getPackageForModule,
100
- fileSystemLookup: (p) => {
101
- const abs = isAbsolute(p) ? p : join(projectDir, p)
102
- const type = resolvableType(abs)
103
- if (!type) return { exists: false }
104
- let realPath = abs
105
- try {
106
- realPath = diskHost.realpath(abs)
107
- } catch { /* keep the lexical path when realpath fails (e.g. a broken symlink) */ }
108
- return { exists: true, type, realPath }
109
- },
110
- mainFields,
111
- nodeModulesPaths: [],
112
- preferNativePlatform: platform !== 'web',
113
- resolveAsset: (dirPath, assetName, ext) => {
114
- const f = join(dirPath, `${assetName}${ext}`)
115
- return pathType(f) === 'f' ? [f] : null
116
- },
117
- resolveHasteModule: () => null,
118
- resolveHastePackage: () => null,
119
- // Inert placeholder: `resolve` redirects via its own bundled helper, never this (see header).
120
- redirectModulePath: (modulePath) => modulePath,
121
- sourceExts,
122
- unstable_conditionNames: conditionNames,
123
- unstable_conditionsByPlatform: conditionsByPlatform,
124
- unstable_enablePackageExports: enablePackageExports,
125
- unstable_incrementalResolution: false,
126
- unstable_logWarning: () => {}, // a static build must not spam on exports fallbacks
127
- }
128
-
129
- return function resolveOne(parentFile, specifier, callConditions) {
130
- // Metro splits `exports` on whether the edge was an ESM import vs a CJS require. scan.js hands
131
- // us the parent's format-derived condition set, so 'import' membership is that signal.
132
- const isESMImport = callConditions instanceof Set ? callConditions.has('import') : false
133
- const context = { ...base, originModulePath: parentFile, isESMImport }
134
- let res
135
- try {
136
- res = resolve(context, specifier, platform)
137
- } catch {
138
- // Metro carries no Node builtins: an unmapped builtin fails to resolve here. The browser-field
139
- // remap of a builtin (`{"crypto": false}` / a shim) is handled inside resolve() before this.
140
- if (isBuiltin(specifier)) return { builtin: true }
141
- return null
142
- }
143
- if (!res) return null
144
- if (res.type === 'empty') return { empty: true }
145
- if (res.type === 'sourceFile') return { url: pathToFileURL(res.filePath).toString() }
146
- // Assets are off (assetExts empty) for a code bundle, but map defensively to the first variant.
147
- if (res.type === 'assetFiles' && res.filePaths?.length) return { url: pathToFileURL(res.filePaths[0]).toString() }
148
- return null
66
+ const resolve = createRnMetroResolver({
67
+ host: metroHost(host, mainFields), sourceExts, assetExts, assetResolutions, mainFields, conditionNames, conditionsByPlatform,
68
+ preferNativePlatform: platform !== 'web', metroResolver,
69
+ })
70
+ // Metro splits `exports` on whether the edge is an ESM import: `import` in scan.js's format-derived conditions.
71
+ return (parentFile, specifier, callConditions) => {
72
+ const isESMImport = callConditions instanceof Set && callConditions.has('import')
73
+ return scanResolution(resolve(parentFile, specifier, { platform, isESMImport }), isBuiltin(specifier))
149
74
  }
150
75
  }
@@ -1,7 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/metro-transformer`. The transformer
2
- // lives in @exodus/stasis-plugins (which depends on @exodus/stasis-core for State; it
3
- // drives load-mode getFile directly). Wire it permanently as Metro's top-level
4
- // `transformerPath`; it only acts under bundle=load (transparent pass-through
5
- // otherwise). See the source for the load asymmetry that lets this run per-worker
6
- // without cross-worker state sync.
7
1
  export * from '@exodus/stasis-plugins/metro-transformer'
package/src/metro.js CHANGED
@@ -1,5 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/metro`. The plugin lives in
2
- // @exodus/stasis-plugins (which depends on @exodus/stasis-core for State /
3
- // resolvePluginState). Internal code uses `@exodus/stasis-plugins/metro` directly;
4
- // this file exists only to back the package's `exports` map.
5
1
  export * from '@exodus/stasis-plugins/metro'
package/src/mock.js CHANGED
@@ -1,29 +1,15 @@
1
- // Imported by src/loader-mock.js (the `stasis run --mock` entry) after the core hooks lib is
2
- // evaluated but before its hooks are installed. Captures the import graph by running user code
3
- // with side-effects denied. Pairs with Node's `--permission` (see bin/stasis.js), which denies fs
4
- // writes/child procs/workers/addons/inspector at the runtime boundary; this file covers what
5
- // `--permission` can't -- there is no `--allow-net`, so the network builtins are neutralized in JS.
6
- //
7
- // FAIL CLOSED, WHOLE MODULE: replace *every* callable on a denied builtin with a thrower, not a
8
- // curated method list -- higher-level clients (axios/undici/ws) fall closed too since they bottom
9
- // out at node:net/tls/dns, and anything unmodelled still throws rather than silently succeeding.
10
- //
11
- // Mechanism: go through `createRequire` to grab the *mutable* CJS exports object -- ESM namespace
12
- // objects freeze their bindings, so mocking them throws "Cannot redefine property". ESM live-bindings
13
- // track CJS mutation for builtins, so importers loading *after* us see the mocks; modules linked
14
- // before (the loader's own state.js) keep their real bindings.
1
+ // `stasis run --mock`'s side-effect denials (loader-mock.js), for what Node's `--permission` (bin/stasis.js) can't
2
+ // deny, the network above all: EVERY callable of a denied builtin throws, so clients bottoming out at it fail closed.
3
+ // Mocked on the mutable CJS exports (ESM namespaces are frozen): importers linked after this see the mocks.
15
4
 
16
5
  import { mock } from 'node:test'
17
6
  import { createRequire, syncBuiltinESMExports } from 'node:module'
18
7
 
19
8
  const require = createRequire(import.meta.url)
20
9
 
21
- // Force lazy init of process.std{in,out,err} before mocking net/tls: they're lazy getters that
22
- // build a net.Socket/tty.WriteStream on first read, which syncBuiltinESMExports() below would
23
- // otherwise trigger through our mock mid-setup. Reading once here caches the real Socket/TTY.
24
- void process.stdin
25
- void process.stdout
26
- void process.stderr
10
+ // process.std{in,out,err} build a net.Socket/tty.WriteStream on first read, which syncBuiltinESMExports() below would
11
+ // otherwise trigger through our mock mid-setup: read once here, they cache the real ones.
12
+ for (const name of ['stdin', 'stdout', 'stderr']) void process[name]
27
13
 
28
14
  const MARKER = '[stasis --mock]'
29
15
 
@@ -35,21 +21,16 @@ const blocked = (label) => {
35
21
  return err
36
22
  }
37
23
 
38
- // A *regular* (constructable) function so both `mod.factory()` and `new mod.Constructor()` throw
39
- // our error; an arrow would make `new` fail with a confusing "is not a constructor".
24
+ // Not an arrow, so `new mod.Constructor()` throws our error too rather than "is not a constructor".
40
25
  const denyFn = (label) => function () { throw blocked(label) }
41
26
 
42
- // Promise-shaped version: rejects instead of sync-throwing, so fire-and-forget callers surface via
43
- // the unhandledRejection trap below rather than crashing the script synchronously.
27
+ // Rejecting, so a fire-and-forget caller meets the unhandledRejection trap below rather than a sync crash.
44
28
  const denyFnAsync = (label) => function () { return Promise.reject(blocked(label)) }
45
29
 
46
- // Replace every own function on `mod` (and one level down on `mod.promises`) with a thrower.
47
- // Promise-shaped surfaces use denyFnAsync so fire-and-forget callers reject quietly -- except
48
- // class-shaped exports (PascalCase): `new Class()` returning a Promise yields the Promise as the
49
- // constructed value, so classes sync-throw to give a clean error in both `new` and call form.
30
+ // Every own function on `mod` and `mod.promises` a thrower, a rejecting one on a promise surface but for a class
31
+ // (PascalCase), which `new` would make the Promise of.
50
32
  const isClassName = (key) => /^[A-Z]/.test(key)
51
- const denyModuleSurface = (specifier, mod, opts = {}) => {
52
- const { prefix = specifier, async: isAsync = specifier.endsWith('/promises') } = opts
33
+ const denyModuleSurface = (prefix, mod, isAsync = prefix.endsWith('/promises')) => {
53
34
  for (const key of Object.getOwnPropertyNames(mod)) {
54
35
  const value = mod[key]
55
36
  if (typeof value === 'function') {
@@ -61,24 +42,16 @@ const denyModuleSurface = (specifier, mod, opts = {}) => {
61
42
  try { mod[key] = impl } catch { /* frozen: leave as-is */ }
62
43
  }
63
44
  } else if (key === 'promises' && value && typeof value === 'object') {
64
- denyModuleSurface(specifier, value, { prefix: `${prefix}.promises`, async: true })
45
+ denyModuleSurface(`${prefix}.promises`, value, true)
65
46
  }
66
47
  }
67
48
  }
68
49
 
69
- // Every callable on these builtins is replaced with a thrower.
70
50
  const DENY_ALL = [
71
51
  // Network surface (no --allow-net counterpart -- JS-mock is the only layer).
72
- 'node:http', 'node:https', 'node:http2',
73
- 'node:net', 'node:dgram', 'node:tls',
74
- 'node:dns', 'node:dns/promises',
75
- // Process/worker/debug: already --permission-denied; duplicated for attributable errors and
76
- // defense in depth against a future --allow-* slip-up or a process.binding bypass.
77
- 'node:child_process',
78
- 'node:worker_threads',
79
- 'node:cluster',
80
- 'node:inspector',
81
- 'node:inspector/promises',
52
+ 'node:http', 'node:https', 'node:http2', 'node:net', 'node:dgram', 'node:tls', 'node:dns', 'node:dns/promises',
53
+ // Already --permission-denied: for attributable errors, and in depth against an --allow-* slip or process.binding.
54
+ 'node:child_process', 'node:worker_threads', 'node:cluster', 'node:inspector', 'node:inspector/promises',
82
55
  // Other side-effect surfaces nothing else covers:
83
56
  'node:repl', // repl.start() opens an interactive stdin loop
84
57
  'node:sqlite', // DatabaseSync can open/create SQLite files (Node 22+)
@@ -98,10 +71,8 @@ for (const specifier of DENY_ALL) {
98
71
  denyModuleSurface(specifier, mod)
99
72
  }
100
73
 
101
- // process method denials. process.exit / process.abort are deliberately left alone -- early
102
- // termination isn't a side effect we should hide. The rest mutate global process state, do real
103
- // I/O, or talk to a parent over IPC; note setUncaughtExceptionCaptureCallback would also disable
104
- // our exitCode=13 cleanup below.
74
+ // What mutates global process state, does real I/O, or talks to a parent over IPC (exit and abort are no side
75
+ // effect to hide); setUncaughtExceptionCaptureCallback would also disable the exitCode=13 cleanup below.
105
76
  const PROCESS_DENY = [
106
77
  'chdir', 'kill', 'umask', 'dlopen', 'binding',
107
78
  'setUid', 'setGid', 'setEuid', 'setEgid', 'setgroups', 'initgroups',
@@ -110,18 +81,13 @@ const PROCESS_DENY = [
110
81
  'setUncaughtExceptionCaptureCallback',
111
82
  ]
112
83
  for (const name of PROCESS_DENY) {
113
- if (typeof process[name] === 'function') {
114
- mock.method(process, name, denyFn(`process.${name}()`))
115
- }
84
+ if (typeof process[name] === 'function') mock.method(process, name, denyFn(`process.${name}()`))
116
85
  }
117
86
 
118
- // process.report.writeReport writes a diagnostic JSON file to disk; deny it too.
119
- if (process.report && typeof process.report.writeReport === 'function') {
120
- mock.method(process.report, 'writeReport', denyFn('process.report.writeReport()'))
121
- }
87
+ // It writes a diagnostic JSON file.
88
+ if (typeof process.report?.writeReport === 'function') mock.method(process.report, 'writeReport', denyFn('process.report.writeReport()'))
122
89
 
123
- // fs writers: --permission blocks these at the kernel level too, but JS-mocking gives cleaner
124
- // errors and stops user code mutating even cwd files (cwd is on --allow-fs-write for the bundle).
90
+ // --permission blocks these too, but mocking gives cleaner errors and covers cwd, on --allow-fs-write for the bundle.
125
91
  // Reads stay real so node_modules resolution keeps working.
126
92
  const fs = require('node:fs')
127
93
  const fsPromises = require('node:fs/promises')
@@ -138,25 +104,16 @@ const FS_WRITERS = [
138
104
  'createWriteStream', 'mkdtemp', 'mkdtempSync',
139
105
  ]
140
106
  for (const name of FS_WRITERS) {
141
- if (typeof fs[name] === 'function') {
142
- mock.method(fs, name, denyFn(`node:fs.${name}()`))
143
- }
144
- if (typeof fsPromises[name] === 'function') {
145
- mock.method(fsPromises, name, denyFnAsync(`node:fs/promises.${name}()`))
146
- }
107
+ if (typeof fs[name] === 'function') mock.method(fs, name, denyFn(`node:fs.${name}()`))
108
+ if (typeof fsPromises[name] === 'function') mock.method(fsPromises, name, denyFnAsync(`node:fs/promises.${name}()`))
147
109
  }
148
110
 
149
- // Refresh the node:fs ESM wrappers so ESM imports after this point see the mocked names;
150
- // bindings stasis already captured (linked before this file ran) keep their real snapshot.
111
+ // ESM imports after this see the mocks; bindings stasis linked before this ran keep their real snapshot.
151
112
  syncBuiltinESMExports()
152
113
 
153
- // Global fetch / WebSocket / EventSource come from undici, not node:http, so handle separately.
154
- // fetch returns a *forever-pending* promise (not a rejection) so an awaiter hangs and the capture
155
- // still drains to write the bundle on beforeExit; WebSocket/EventSource throw from their
156
- // constructors to preserve the synchronous shape.
157
- if (typeof globalThis.fetch === 'function') {
158
- globalThis.fetch = () => new Promise(() => {})
159
- }
114
+ // The global fetch / WebSocket / EventSource are undici's, not node:http's. fetch never settles, so an awaiter
115
+ // hangs and the capture still drains to write the bundle on beforeExit; the others throw from their constructors.
116
+ if (typeof globalThis.fetch === 'function') globalThis.fetch = () => new Promise(() => {})
160
117
  for (const name of ['WebSocket', 'EventSource']) {
161
118
  if (typeof globalThis[name] === 'function') {
162
119
  globalThis[name] = class {
@@ -165,8 +122,7 @@ for (const name of ['WebSocket', 'EventSource']) {
165
122
  }
166
123
  }
167
124
 
168
- // Our denials become unhandledRejections for fire-and-forget callers, which would tear the process
169
- // down before the loader writes the bundle. Swallow *only* our own denials; rethrow everything else.
125
+ // A fire-and-forget caller's denial would tear the process down before the loader writes the bundle.
170
126
  process.on('unhandledRejection', (reason) => {
171
127
  if (reason?.__stasisMock) return
172
128
  throw reason
@@ -178,10 +134,8 @@ process.on('exit', () => {
178
134
  if (process.exitCode === 13) process.exitCode = 0
179
135
  })
180
136
 
181
- // Timers: silently ignored. Callback timers (setTimeout/setInterval/setImmediate) become no-ops;
182
- // promise timers (node:timers/promises) return *forever-pending* promises so `await setTimeout()`
183
- // suspends forever. A pending promise doesn't keep the event loop alive, so the process still
184
- // exits cleanly and the loader's beforeExit hook writes the bundle.
137
+ // Timers are ignored: callback timers are no-ops, and promise timers never settle, which keeps no event loop
138
+ // alive, so the process still exits and the loader's beforeExit hook writes the bundle.
185
139
  const noop = () => undefined
186
140
  const pending = () => new Promise(() => {})
187
141
  const TIMERS = ['setTimeout', 'setInterval', 'setImmediate', 'clearTimeout', 'clearInterval', 'clearImmediate']
@@ -191,10 +145,8 @@ const timers = require('node:timers')
191
145
  for (const name of TIMERS) mock.method(timers, name, noop)
192
146
 
193
147
  const timersPromises = require('node:timers/promises')
194
- mock.method(timersPromises, 'setTimeout', pending)
195
- mock.method(timersPromises, 'setImmediate', pending)
196
- // setInterval returns an async iterable; each `await iter.next()` is forever-pending, so
197
- // `for await (const _ of setInterval(...))` hangs at the first iteration.
148
+ for (const name of ['setTimeout', 'setImmediate']) mock.method(timersPromises, name, pending)
149
+ // An async iterable whose `for await` hangs at the first iteration.
198
150
  mock.method(timersPromises, 'setInterval', () => ({
199
151
  [Symbol.asyncIterator]() {
200
152
  return { next: pending }
package/src/parse.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import { readFileSync } from 'node:fs'
2
- import { brotliDecompressSync } from 'node:zlib'
3
2
 
3
+ import { brotliDecompressStrict } from '@exodus/stasis-core/brotli'
4
4
  import { Bundle } from '@exodus/stasis-core/bundle'
5
5
  import { Lockfile } from '@exodus/stasis-core/lockfile'
6
6
 
7
- // Read a stasis artifact and parse it into a Lockfile or Bundle, reporting its `kind`
8
- // ('lockfile' | 'bundle'). Lockfiles are JSON starting with `{`; bundles are brotli-compressed
9
- // JSON — sniff the leading byte to route to the right parser so its diagnostic surfaces on failure.
7
+ // A stasis artifact by its leading byte: a lockfile's JSON starts with `{`, a bundle is brotli. A Lockfile or Bundle
8
+ // in place of the path is taken as it is.
10
9
  export function parseFileWithKind(file) {
10
+ if (file instanceof Lockfile) return { kind: 'lockfile', artifact: file }
11
+ if (file instanceof Bundle) return { kind: 'bundle', artifact: file }
11
12
  let buf
12
13
  try {
13
14
  buf = readFileSync(file)
@@ -24,9 +25,10 @@ export function parseFileWithKind(file) {
24
25
  }
25
26
  let text
26
27
  try {
27
- text = brotliDecompressSync(buf).toString('utf8')
28
+ text = brotliDecompressStrict(buf).toString('utf8')
28
29
  } catch (cause) {
29
- throw new Error(`Failed to read ${file} as a stasis bundle (not brotli)`, { cause })
30
+ const why = cause.code === 'ERR_TRAILING_JUNK_AFTER_STREAM_END' ? 'bytes after its brotli stream' : 'not brotli'
31
+ throw new Error(`Failed to read ${file} as a stasis bundle (${why})`, { cause })
30
32
  }
31
33
  try {
32
34
  return { kind: 'bundle', artifact: Bundle.parse(text) }
@@ -35,7 +37,6 @@ export function parseFileWithKind(file) {
35
37
  }
36
38
  }
37
39
 
38
- // Thin wrapper over parseFileWithKind that drops the `kind` (for callers like audit/sbom).
39
40
  export function parseFile(file) {
40
41
  return parseFileWithKind(file).artifact
41
42
  }
package/src/prune.js CHANGED
@@ -1,4 +1 @@
1
- // Public-export adapter: backs `@exodus/stasis/prune`. The implementation lives in
2
- // @exodus/stasis-core; internal tooling and tests import `@exodus/stasis-core/prune`
3
- // directly, so this file exists only to back the package's `exports` map.
4
1
  export * from '@exodus/stasis-core/prune'