@exodus/stasis-core 1.0.0-beta.2 → 1.0.0-beta.3

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.
package/src/state.js CHANGED
@@ -9,17 +9,15 @@ import { brotliCompressSync, brotliDecompressSync } from 'node:zlib'
9
9
  import { Config } from './config.js'
10
10
  import { Bundle } from './bundle.js'
11
11
  import { Lockfile } from './lockfile.js'
12
+ import { parseShard, serializeShard } from './shard.js'
12
13
  import { canonicalizePath, sha512integrity, readFileSyncMaybe, noupsert } from './state-util.js'
13
14
  import { brotliOptions } from './brotli.js'
14
- import { CODE_EXTENSIONS, classifyExtension, fileMapToObject, isStatFormat, moduleFileKey, objectToMaps, sortPaths, splitNodeModulesPath } from './util.js'
15
+ import { CODE_EXTENSIONS, canObserveExecuteBits, classifyFormat, fileMapToObject, hasNodeModulesSegment, isBinaryPlist, isStatFormat, moduleFileKey, narrowExecutable, objectToMaps, observeExecutable, pathExt, reconcileFormat, sortPaths, splitNodeModulesPath } from './util.js'
16
+ import { readModuleManifest } from './bundle-util.js'
15
17
  import corePackage from './package.cjs'
16
18
 
17
- // Object-destructure off the namespace rather than `import { ... } from 'node:fs'`:
18
- // the destructured `const` captures function values at this module's eval time, so
19
- // stasis keeps writing through the real fs even after --mock (loaded after us) calls
20
- // module.syncBuiltinESMExports() to refresh node:fs's ESM wrapper for user code.
21
- // Direct ESM destructured imports are live bindings and would re-resolve to the
22
- // mocked names when state.write() fires on beforeExit.
19
+ // Destructure off the namespace: captures the real fns at eval time, so writes survive --mock's
20
+ // syncBuiltinESMExports() remock of node:fs.
23
21
  const { existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } = fs
24
22
 
25
23
  const FILE_CONFIG = 'stasis.config.json'
@@ -32,51 +30,20 @@ function readPackageJSON(pkgAbsolute) {
32
30
  return JSON.parse(buf.toString())
33
31
  }
34
32
 
35
- // This stasis-core copy's own version, via src/package.cjs (a CommonJS re-export of
36
- // package.json -- bundler-safe, unlike a runtime fs read or `import ... with`). A child
37
- // (sidecar) State must EXACTLY match its parent's version (enforced in the constructor's
38
- // parent branch): a sidecar shares the parent's maps by reference and reads its private
39
- // fields, so a version skew between two @exodus/stasis-core copies in one process would
40
- // be unsound.
33
+ // Via src/package.cjs: a bundler-safe re-export of package.json.
41
34
  const VERSION = corePackage.version
42
35
 
43
- // Set `format` for `file` in a formats map, applying the weak-stat-record priority
44
- // rule shared by the LIVE map writers (addFsStat, addImport -- addFile/addFsDir drop
45
- // a stale stat record in place before their own set) and the lockfile merge
46
- // (#mergedFormats): a payload-free 'stat:*' record (addFsStat) YIELDS to a real
47
- // format for the same file and never displaces one. Both directions arise
48
- // legitimately in one capture: an import may reveal the real format of a path that
49
- // was first only stat'd, and -- the reverse -- a stat may land on a path addImport
50
- // already format-attested at RESOLVE time with no byte record for addFsStat's
51
- // content skip to key off (stasis-core's own preload-cached modules are exactly
52
- // that shape: the resolve hook records 'module', the load hook never fires, and a
53
- // bundler's enhanced-resolve then stats the file). Everything else keeps noupsert's
54
- // conflict-is-fatal stance: two divergent REAL formats, or a stat kind flip
55
- // (stat:file vs stat:directory).
36
+ const CAN_OBSERVE_EXECUTE_BITS = canObserveExecuteBits()
37
+
38
+ // A weak 'stat:*' yields to a real format; two real formats or a stat kind flip are fatal.
56
39
  function upsertFormat(map, file, format) {
57
- const existing = map.get(file)
58
- if (existing !== undefined && existing !== format) {
59
- if (isStatFormat(existing) && !isStatFormat(format)) {
60
- map.set(file, format)
61
- return
62
- }
63
- if (isStatFormat(format) && !isStatFormat(existing)) return
64
- }
65
- noupsert(map, file, format)
40
+ const currentFormat = map.get(file)
41
+ map.set(file, currentFormat === undefined ? format : reconcileFormat(format, currentFormat, file))
66
42
  }
67
43
 
68
44
  // TODO: stricter format validation
69
45
 
70
- // Process-wide registry of every live State, kept on globalThis (not a module-local
71
- // variable) so it is shared across DUPLICATE stasis-core copies in one process -- e.g. a
72
- // stasis bundle that carries its own stasis-core alongside the outer loader's. A
73
- // cross-realm `Symbol.for` key makes every state.js copy reach the same Set. Two roles:
74
- // - the preload (top-level) State is the unique member flagged isPreload, found by
75
- // State.preload; constructing a second preload (from ANY copy) is rejected, so the
76
- // "one top-level state" invariant holds process-wide; and
77
- // - write-target collision detection (#claimWritePath) scans every member's claimed
78
- // paths, so no two live States write the same lockfile/bundle/resourcesBundle path --
79
- // across copies, AND whether or not a preload exists.
46
+ // On globalThis via `Symbol.for` so the registry is shared across duplicate stasis-core copies.
80
47
  const STATES_KEY = Symbol.for('@exodus/stasis-core/states')
81
48
  function liveStates() {
82
49
  return (globalThis[STATES_KEY] ??= new Set())
@@ -90,151 +57,76 @@ export class State {
90
57
  formats = new Map()
91
58
  modules = new Map()
92
59
  imports = new Map()
60
+ // Project-relative files carrying a POSIX execute bit; disk is authoritative (a file that lost
61
+ // the bit drops out). Emitted as the artifacts' `executable` list.
62
+ executable = new Set()
93
63
  config
94
64
  root
95
65
  #parent
96
66
 
97
- // True iff this is THE preload (top-level) State. Exposed via `get isPreload()` so
98
- // State.preload can find the unique flagged member of the global registry across copies.
99
67
  #isPreload = false
100
68
 
101
- // This State's claimed write-target paths (canonicalized -> label), for cross-State
102
- // collision detection. Exposed via `claimedWritePathLabel()` so the global scan in
103
- // #claimWritePath can consult States from other stasis-core copies.
69
+ // Claimed write-target paths (canonicalized -> label), for cross-State collision detection.
104
70
  #claims = new Map()
105
71
 
106
- // For a parent: WRITE-mode sidecar States constructed against it -- the lockfile
107
- // CONTRIBUTORS. The unified lockfile (built by the parent's lockData via
108
- // #mergedImports/#mergedFormats) must union the parent's own imports / formats with
109
- // every sidecar's, otherwise resolution edges and format attestations a sidecar
110
- // bundler-plugin observed (sidecar.addImport / addFile populate sidecar-local
111
- // this.imports/this.formats) would never reach the lockfile. Hashes / entries /
112
- // modules are already shared by reference; this closes the same gap for imports and
113
- // formats. Also the set attestedBySidecar consults, so --fs skips re-capturing a
114
- // read the bundler plugin already records here. Unused on sidecars themselves.
72
+ // WRITE-mode sidecars: lockfile CONTRIBUTORS (#mergedImports/#mergedFormats union theirs in).
115
73
  #sidecars = new Set()
116
74
 
117
- // For a parent: LOAD-mode sidecar States -- read-only family members, NOT lockfile
118
- // contributors. A bundler plugin's load-mode sidecar carries the module graph in its
119
- // bundle; getFs*Family consults this set so a --fs read at load of a graph file the
120
- // sidecar carries is served from it (the symmetric counterpart to the #sidecars
121
- // capture-skip). Kept separate from #sidecars precisely so these never enter
122
- // #mergedImports/#mergedFormats -- a load-mode sidecar contributes no resolution edges
123
- // or formats (the lockfile's trust-bearing content) to the unified lockfile (the boundary
124
- // the writeBundle gate on registration enforces; see the constructor and registerReadSidecar).
75
+ // LOAD-mode sidecars: read-only, NOT lockfile contributors (getFs*Family serves bytes from them).
125
76
  #readSidecars = new Set()
126
77
 
127
- // Resolutions attested by the loaded lockfile (conditions -> parent ->
128
- // specifier -> file), or null when no lockfile was loaded / it predates
129
- // resolution attestation. Kept separate from this.imports (the live
130
- // observed/bundle-served map): the lockfile may attest a superset of what a
131
- // given run observes or a given bundle carries.
78
+ // Lockfile-attested resolutions (conditions -> parent -> specifier -> file), or null; may be a
79
+ // superset of what a run observes, so kept apart from this.imports.
132
80
  #lockImports = null
133
81
 
134
- // Loader formats attested by the loaded lockfile (file -> format), or null
135
- // when none was loaded / it predates format attestation. Like #lockImports,
136
- // kept apart from this.formats (the live observed/bundle-served map).
82
+ // Lockfile-attested loader formats (file -> format), or null; kept apart from this.formats.
137
83
  #lockFormats = null
138
84
 
139
- // True iff this State (or, for a sidecar, its parent) loaded a lockfile from
140
- // disk during construction. Drives #mergeBundleMetadata's cross-check-vs-absorb
141
- // branch: with a lockfile, the bundle's metadata must agree with the lockfile's
142
- // attestations; without one, the bundle's metadata is absorbed as the source of
143
- // truth. Sidecars inherit this from the parent at construction time so a sidecar
144
- // bundle is cross-checked against the parent's lockfile attestation rather than
145
- // silently trusted.
85
+ // Loaded a lockfile at construction: #mergeBundleMetadata cross-checks bundle metadata against
86
+ // it instead of absorbing it as source of truth.
146
87
  #lockfileLoaded = false
147
88
 
148
- // Project-relative keys of files/directories THIS process recorded via addFile/addFsDir this
149
- // run (as opposed to the lockfile baseline seeded at construction). shardSnapshot() forwards
150
- // only these, so a forked child's shard carries what it observed -- not a re-ship of the whole
151
- // seeded lockfile.
89
+ // Keys THIS process recorded this run (not the seeded baseline); shardSnapshot forwards only these.
152
90
  #observed = new Set()
153
- // file -> set of consumers that recorded it, for the bundle's informational `reason` field.
154
- // Keyed by consumer ('run' for the loader/CLI; a plugin label like 'StasisMetro' for a plugin
155
- // sharing this State). Populated only when bundling. See #recordReason / #bundleReason.
91
+ // file -> consumers that recorded it, for the bundle's informational `reason` field.
156
92
  #reasonFiles = new Map()
157
- // Supporting state so the bundle `reason` map's "run" entry stays accurate (see #bundleReason):
158
- // files run loaded as a MODULE (#runImported), files run merely fs-READ after a plugin attached
159
- // (#fsReadPostPlugin), and whether a bundler plugin has attached to this State (#pluginAttached).
160
93
  #runImported = new Set()
161
94
  #fsReadPostPlugin = new Set()
162
95
  #pluginAttached = false
163
96
 
164
- // Files, resolutions, and formats attested by a frozen bundle (bundle=frozen),
165
- // or null when no frozen bundle was loaded. A frozen bundle plays the same
166
- // read-only attestation role a frozen lockfile does, but anchored in the
167
- // bundle's own bytes -- so bundle=frozen needs no sibling lockfile. The byte
168
- // check itself is the noupsert of observed disk content into this.sources/
169
- // this.resources (both pre-seeded from the bundle); these sets/maps close the
170
- // attested set so a file, resolution, or format the bundle never recorded is
171
- // rejected. Kept separate from the live this.sources/this.imports/this.formats,
172
- // which addFile/addImport mutate.
97
+ // Attested by a frozen bundle (bundle=frozen), or null: closes the attested set, so anything the
98
+ // bundle never recorded is rejected. Separate from the live maps.
173
99
  #bundleSources = null
174
100
  #bundleResources = null
175
101
  #bundleImports = null
176
102
  #bundleFormats = null
177
103
 
178
- // Lazily-built set of directory paths IMPLIED by the bundle's recorded entries
179
- // (files, resources, directory listings): a recorded `node_modules/dep/index.js`
180
- // proves `node_modules` and `node_modules/dep` exist as directories even though
181
- // neither was readdir'd. getFsStat consults it so
182
- // `fs.statSync('node_modules').isDirectory()` succeeds at bundle=load. Built once
183
- // in load mode, where this.imports / this.sources are immutable after construction.
104
+ // Lazily-built dirs IMPLIED by recorded files, so getFsStat answers isDirectory() at bundle=load.
184
105
  #impliedDirIndex = null
185
106
 
186
- // Capture-time native resolutions (parent URL -> specifier -> resolved URL)
187
- // observed via the Module._resolveFilename shim: require.resolve() and any CJS
188
- // require() that bypasses the resolve hook. write()'s backfill records the edges
189
- // the hook missed (deduped, in-bundle targets only). Populated only during capture.
107
+ // Native resolutions (parent URL -> specifier -> resolved URL) from the Module._resolveFilename
108
+ // shim: require.resolve()/CJS require()s bypassing the resolve hook.
190
109
  #observedResolutions = new Map()
191
110
 
192
- // Node's require-condition set (e.g. ['require', 'node', 'node-addons',
193
- // 'module-sync'], plus any --conditions), captured the first time addImport sees a
194
- // require()-context edge. require()/require.resolve() resolve under THESE conditions
195
- // -- they honor the `require` branch of conditional `exports`, so they're not
196
- // condition-free -- so #backfillObservedResolutions keys the native
197
- // (Module._resolveFilename) edges it recovers under this set rather than the
198
- // wildcard '*'. That matches what the resolve hook records directly (newer Node) and
199
- // unifies them with the require() bucket, so any capture that does at least one
200
- // require() (the common case) yields the same lockfile on every Node version. null
201
- // until observed -- a capture that ONLY require.resolve()s and never require()s
202
- // leaves it null and backfill falls back to '*' (as before this change), which the
203
- // getImport/resolveBundled wildcard fallbacks still match.
111
+ // Node's require-condition set, from the first require()-context addImport;
112
+ // #backfillObservedResolutions keys native edges under it so the lockfile is Node-version-stable.
204
113
  #requireConditions = null
205
114
 
206
- // Absolute path of a package whose source files were loaded by Node BEFORE
207
- // our hooks registered (the preload-cached set). Set by the loader's
208
- // initState to stasis-core's own root; sidecars inherit it from their
209
- // parent so plugin-driven write()s also backfill internal edges. write()'s
210
- // backfill statically parses each file under this root and addImports its
211
- // relative-specifier edges -- recovering the (state.js -> config.js)-shape
212
- // edges that the live resolve hook never observed.
115
+ // Root of a package Node loaded BEFORE our hooks (stasis-core's own); write()'s backfill
116
+ // statically parses files under it to recover edges the resolve hook never observed.
213
117
  #preloadRoot = null
214
118
 
215
- // Per-artifact "last serialized" caches: write() compares the freshly serialized
216
- // JSON text against the cached one for each output (lockfile / unified bundle /
217
- // split code / split resources) and skips both the brotli step and the writeFileSync
218
- // when they match. Brotli at the default quality (11, tunable via
219
- // config.brotliQuality) dominates write cost, and webpack/esbuild watch-mode
220
- // rebuilds call write() on every rebuild whether or not the captured graph
221
- // actually changed -- this cache makes those no-ops fast. Persistent across
222
- // write() calls within one process; null on the first call.
119
+ // Per-artifact "last serialized" caches: write() skips brotli + writeFileSync on unchanged text.
223
120
  #lastLockData = null
224
121
  #lastUnifiedBundle = null
225
122
  #lastCodeBundle = null
226
123
  #lastResourcesBundle = null
227
124
 
228
- // Options:
229
- // preload (boolean) -- register as the unique preload State (exposed via State.preload).
230
- // Only one preload may exist at a time. The stasis loader is the only real caller.
231
- // parent (State) -- run as a sidecar of this parent. Sidecar shares the parent's
232
- // hashes/entries/modules (so addFile updates the unified lockfile through them) but
233
- // manages its own sources/formats/imports/resources and emits its own bundle file.
234
- // write() on a sidecar skips the lockfile (parent owns it) and only writes its bundle.
235
- // All other keys forward to Config.
125
+ // Options: `preload` (the unique preload State) and `parent` (run as a sidecar sharing the
126
+ // parent's hashes/entries/modules, with its own sources/formats/imports/resources and bundle).
127
+ // All other keys forward to Config.
236
128
  constructor(root, options = {}) {
237
- // skipDiscovery: build a caller-populated, in-memory State with NO filesystem discovery -- root is the passed `root` arg, and sources/imports/formats/entries are filled in by the caller after construction (no package.json walk, no on-disk config/lockfile/bundle reads). For artifact-driven tooling like `stasis build`, which serves a parsed bundle (or a lockfile reconstructed + verified in memory) and must not depend on a project's stasis.config.json or read a stray stasis.code.br. Read-only (load/ignore) modes only.
129
+ // skipDiscovery: caller-populated in-memory State, NO filesystem discovery; read-only modes only.
238
130
  const { preload: isPreload = false, parent: parentState, preloadRoot, skipDiscovery = false, ...configOptions } = options
239
131
  this.config = new Config(configOptions)
240
132
  if (isPreload) assert.ok(!State.preload, 'Only one preload Stasis instance is supported')
@@ -242,46 +134,24 @@ export class State {
242
134
  this.#isPreload = isPreload
243
135
 
244
136
  if (parentState) {
245
- // A child (sidecar) shares the parent's maps by reference and inherits its lockfile
246
- // attestation, so the parent MUST be the exact same stasis-core VERSION -- but it
247
- // need NOT be the same module copy. A bundle that carries its OWN stasis-core (e.g.
248
- // a webpack script + StasisWebpack run under `stasis run --bundle=load`) has the
249
- // plugin's copy coordinate with the OUTER loader's preload across the class brand.
250
- // The exact-version match makes that sound; everything the sidecar reads from the
251
- // parent goes through the parent's PUBLIC surface (`version`, `sidecarInheritance`,
252
- // `registerSidecar`, and the shared public maps), never a private field a foreign
253
- // class brand would deny. A version skew is unsound -- reject it with a clear error.
137
+ // A sidecar shares the parent's maps and inherits its attestation, so a version skew is
138
+ // unsound (a different module copy is fine -- it reads only the parent's PUBLIC surface).
254
139
  assert.equal(parentState.version, VERSION,
255
140
  `child State version '${VERSION}' must exactly match parent version '${parentState.version}'`)
256
- // Sidecar mode: short-circuit the on-disk discovery path. Lockfile data is shared by
257
- // reference with the parent; only the sidecar's bundleFile (if any) is parsed here.
258
141
  this.#parent = parentState
259
142
  this.root = parentState.root
260
143
  this.hashes = parentState.hashes
261
144
  this.entries = parentState.entries
262
145
  this.modules = parentState.modules
263
- // Inherit, via the parent's public sidecarInheritance() so it works across copies:
264
- // - preloadRoot, so plugin-driven write()s (StasisWebpack / StasisEsbuild done-hook
265
- // saves) backfill stasis-core's internal edges the same way the parent does;
266
- // - the lockfile attestation maps, so #mergeBundleMetadata cross-checks the sidecar
267
- // bundle against the same attestation the parent loaded -- without this a tampered
268
- // sidecar bundle could redirect a resolution or flip a format (commonjs <->
269
- // module-typescript) for hash-valid bytes, which the byte check alone misses.
146
+ // Public sidecarInheritance() (works across copies): the lockfile attestation must reach the
147
+ // sidecar, else a tampered bundle could redirect a resolution on hash-valid bytes.
270
148
  const inherited = parentState.sidecarInheritance()
271
149
  this.#preloadRoot = inherited.preloadRoot
272
150
  this.#lockImports = inherited.lockImports
273
151
  this.#lockFormats = inherited.lockFormats
274
152
  this.#lockfileLoaded = inherited.lockfileLoaded
275
153
  assert.ok(this.config.bundleFile, 'sidecar State requires bundleFile')
276
- // Claim the bundleFile (and resourcesBundleFile under the split layout) against the
277
- // process-wide registry so two write-intent States anywhere -- whether a sibling
278
- // sidecar or an independent top-level State (a CLI/env run with a custom
279
- // lockfile/bundle path) -- can't silently target the same on-disk file
280
- // (last-write-wins on `beforeExit`). Only writing States claim; read-only modes
281
- // (load / frozen) may legitimately share a path with the writer that produced the
282
- // file. The Config's own pairwise cross-path check (config.js:#checkInvariants)
283
- // already rejects intra-State collisions, so #claimWritePath only fires on
284
- // cross-State conflicts.
154
+ // Only writing States claim, so two write-intent States can't silently target the same file.
285
155
  if (this.config.writeBundle) {
286
156
  this.#claimWritePath(`sidecar bundleFile '${this.config.bundleFile}'`, this.config.bundleFile)
287
157
  if (this.config.resourcesBundleFile) {
@@ -289,26 +159,19 @@ export class State {
289
159
  this.config.resourcesBundleFile)
290
160
  }
291
161
  }
292
- // frozenBundle MUST go through this branch alongside write/load -- it has its
293
- // own attestation snapshot to build, and was previously missed (silently
294
- // skipping parsing made the post-construction frozen-bundle invariant
295
- // unreachable on the sidecar path).
162
+ // frozenBundle MUST go through this branch too -- it has its own attestation snapshot to build.
296
163
  if (this.config.writeBundle || this.config.loadBundle || this.config.frozenBundle) {
297
164
  const sourcesPath = this.config.bundleFile
298
165
  const sources = readFileSyncMaybe(dirname(sourcesPath), basename(sourcesPath))
299
166
  if (sources && !this.config.replaceBundle) {
300
167
  const bundle = Bundle.parse(brotliDecompressSync(sources).toString('utf-8'))
301
- // Same v0 refusal as the main load path: a v0 bundle has no per-file
302
- // formats and no import map, so serving / verifying one through a
303
- // sidecar would silently widen trust.
168
+ // v0 bundle has no per-file formats or import map -- serving one via a sidecar widens trust.
304
169
  assert.equal(bundle.version, Bundle.VERSION,
305
170
  `stasis sidecar requires a v1 bundle; ${sourcesPath} is v${bundle.version}. ` +
306
171
  `Re-bundle with the current stasis or \`bundle=replace\` against a v0-free starting point.`)
307
172
  assert.equal(bundle.config.scope, this.config.scope)
308
- // Cross-check the sidecar bundle's metadata against the parent's lockfile
309
- // (or absorb if no lockfile was loaded). hashes/entries/modules are shared
310
- // with the parent, so #mergeBundleMetadata's writes -- when no lockfile is
311
- // loaded -- propagate into the unified attestation.
173
+ // Cross-check against the parent's lockfile, or absorb if none (shared hashes/entries/
174
+ // modules mean those writes propagate to the parent).
312
175
  this.#mergeBundleMetadata(bundle, { lockfileLoaded: this.#lockfileLoaded })
313
176
  for (const [file, content] of bundle.sources) {
314
177
  if (Bundle.isResourceFormat(bundle.formats.get(file))) this.resources.set(file, content)
@@ -316,9 +179,9 @@ export class State {
316
179
  }
317
180
  this.formats = bundle.formats
318
181
  this.imports = bundle.imports
182
+ this.#absorbExecutable(bundle)
183
+ this.#seedReasonFromBundle(bundle)
319
184
  if (this.config.frozenBundle) {
320
- // Same snapshot the main path takes -- closes the attested set so
321
- // addFile/addImport reject anything the bundle didn't carry.
322
185
  this.#bundleSources = new Set(this.sources.keys())
323
186
  this.#bundleResources = new Set(this.resources.keys())
324
187
  this.#bundleImports = objectToMaps(fileMapToObject(bundle.imports))
@@ -326,7 +189,6 @@ export class State {
326
189
  }
327
190
  }
328
191
 
329
- // Sidecar split-bundle: same shape as the main path's resources-side load.
330
192
  if (this.config.resourcesBundleFile) {
331
193
  const resourcesPath = this.config.resourcesBundleFile
332
194
  const resourcesData = readFileSyncMaybe(dirname(resourcesPath), basename(resourcesPath))
@@ -335,40 +197,18 @@ export class State {
335
197
  }
336
198
  }
337
199
  }
338
- // Mirror the post-discovery invariant from the main path: frozen modes must
339
- // have actually loaded their attestation, otherwise the run would fail open.
340
200
  if (this.config.frozenBundle) {
341
201
  assert.ok(this.#bundleSources !== null, 'No bundle, but attempting to run in frozen bundle mode')
342
202
  }
343
- // Register with the parent AFTER every fallible step (v0 refusal, scope
344
- // equality, #mergeBundleMetadata cross-check, frozenBundle invariant) so a
345
- // throw never leaves a dead reference in the parent's registries.
346
- // Write-mode sidecars are lockfile CONTRIBUTORS -- their addImport / addFile
347
- // observations have to land in the unified lockfile, otherwise a `lock=frozen`
348
- // re-run rejects them as unattested -- so they join #sidecars (which feeds
349
- // #mergedImports/#mergedFormats and attestedBySidecar). Load-mode sidecars are
350
- // CONSUMERS: they must NOT contribute to the parent's lockfile (the bundle has
351
- // its own integrity story, and under `lock=add` with no prior lockfile a
352
- // load-mode sidecar would otherwise silently make the bundle's content the
353
- // lockfile's source of truth), but they DO carry bundle bytes that --fs serves at
354
- // load, so they join the read-only #readSidecars (consulted by getFs*Family only).
355
- // Frozen sidecars join neither: --fs neither captures nor serves in frozen-bundle
356
- // mode (fs.js gates capture on writeBundle and serve on loadBundle), and their
357
- // lockfile cross-check already happened in #mergeBundleMetadata above.
203
+ // Register AFTER every fallible step so a throw leaves no dead reference. Frozen sidecars
204
+ // join neither registry (--fs neither captures nor serves in frozen-bundle mode).
358
205
  if (this.config.writeBundle) parentState.registerSidecar(this)
359
206
  else if (this.config.loadBundle) parentState.registerReadSidecar(this)
360
207
  liveStates().add(this)
361
208
  return
362
209
  }
363
210
 
364
- // skipDiscovery (see the constructor comment): a caller-populated, in-memory State.
365
- // Skip the entire filesystem-discovery path -- anchor at the given root, read nothing --
366
- // and let the caller fill in the maps. Only sound for read-only load/ignore modes:
367
- // there is no on-disk attestation to load or verify, so frozen modes are rejected.
368
211
  if (skipDiscovery) {
369
- // Read-only by contract: a caller-populated in-memory State has no on-disk baseline,
370
- // so neither frozen verification (nothing to verify against) nor write modes (nothing
371
- // discovered to write) are meaningful. `stasis build` uses bundle:'load', lock:'ignore'.
372
212
  assert.ok(!this.config.frozen && !this.config.frozenBundle && !this.config.writeBundle && !this.config.writeLockfile,
373
213
  'skipDiscovery is read-only: incompatible with frozen and write (add/replace) lock/bundle modes')
374
214
  this.root = resolve(root)
@@ -380,9 +220,6 @@ export class State {
380
220
  return
381
221
  }
382
222
 
383
- // Preload-uniqueness invariant must be checked before construction proceeds; the
384
- // actual liveStates() registration happens after construction succeeds so a throw in
385
- // setup can't leave a half-built (and, for a preload, singleton-claiming) State behind.
386
223
  const potentialRoots = []
387
224
  let cursor = root
388
225
  while (cursor) {
@@ -396,8 +233,8 @@ export class State {
396
233
  }
397
234
 
398
235
  if (cursor === process.env.PROJECT_CWD) break // e.g. yarn sets this
399
- if (existsSync(join(cursor, '.git'))) break // don't go higher than the repo root
400
- if (existsSync(join(cursor, 'pnpm-workspace.yaml'))) break // pnpm workspace root
236
+ if (existsSync(join(cursor, '.git'))) break
237
+ if (existsSync(join(cursor, 'pnpm-workspace.yaml'))) break
401
238
  const parent = dirname(cursor)
402
239
  if (!parent || parent === cursor) break
403
240
  cursor = parent
@@ -405,43 +242,24 @@ export class State {
405
242
 
406
243
  // default root is top-level package.json, to opt-in to per-dir create stasis.config.json
407
244
  this.root = potentialRoots.at(-1)
245
+ assert.ok(this.root, `stasis: no package.json found at or above ${resolve(root)}; run stasis from within a project`)
408
246
 
409
247
  let loaded = false
410
248
  let lockfileLoaded = false
411
- // When `config.lockFile` is set, the lockfile lives at that explicit path -- not at
412
- // join(rootDir, FILE_LOCK) for any candidate rootDir. Suppress the per-rootDir read
413
- // for root-detection (so a stale stasis.lock.json at the project root can't shadow
414
- // the explicit one), then substitute the explicit content once root-detection has
415
- // committed to a rootDir below.
249
+ // Explicit lockFile: suppress the per-rootDir probe so a stale project-root lockfile can't
250
+ // shadow it; substituted below.
416
251
  const explicitLockPath = this.config.lockFile
417
- // A construction-time `bundleFile` (a --bundle-file flag or EXODUS_STASIS_BUNDLE_FILE) is
418
- // rootDir-INDEPENDENT: reading it yields the same file at every candidate root. So, exactly
419
- // like explicitLockPath, it must NOT act as a per-rootDir root-detection signal -- if it did,
420
- // the innermost package.json dir would always match first and win, diverging load's root from
421
- // the (outer) root the bundle was captured with. Because every bundle key is stored relative
422
- // to the capture root, that divergence makes every bundled dependency unreachable at load: the
423
- // load hook throws "outside project root" / "not attested", and Node's ESM->CJS translator --
424
- // which re-resolves a required dependency through Module._load(absPath, /* no parent */) -- hits
425
- // native disk resolution for a file the bundle carries but disk (post-prune / never-shipped)
426
- // does not, i.e. `Cannot find module '<abs node_modules path>'`. Root is instead chosen from
427
- // rootDir-DEPENDENT signals (stasis.config.json, the default lockfile/bundle at the dir), then
428
- // the explicit bundle is loaded at the committed root -- or, when nothing else committed, at the
429
- // outermost root post-loop (mirroring explicitLockPath). A `bundleFile` that comes only from
430
- // stasis.config.json is NOT suppressed: it lives at a dir already carrying the config signal, so
431
- // it selects that dir consistently at capture and load alike.
252
+ // A construction-time (flag/env) `bundleFile` is rootDir-INDEPENDENT, so it must NOT be a
253
+ // root-detection signal: picking the innermost dir would diverge load's root from the capture
254
+ // root. A config-only bundleFile is NOT suppressed (its dir already carries the config signal).
432
255
  const explicitBundlePath = this.config.bundleFile
433
256
  for (const rootDir of potentialRoots) {
434
257
  const config = readFileSyncMaybe(rootDir, FILE_CONFIG, 'utf-8')
435
258
  const lockProbe = explicitLockPath ? null : readFileSyncMaybe(rootDir, FILE_LOCK, 'utf-8')
436
- // Read the bundle at the construction-time bundleFile (a --bundle-file flag or
437
- // EXODUS_STASIS_BUNDLE_FILE) or, absent that, the default <rootDir>/stasis.code.br -- used
438
- // to LOAD the bundle once a root is committed. The authoritative path can still change when
439
- // loadConfig() applies a `bundleFile` from stasis.config.json, so it's re-read below.
440
259
  let sourcesPath = this.config.bundleFile || join(rootDir, FILE_CODE)
441
260
  let sources = readFileSyncMaybe(dirname(sourcesPath), basename(sourcesPath))
442
- // Root-SELECTION signal: only the DEFAULT <rootDir>/stasis.code.br counts. An explicit
443
- // (rootDir-independent) bundleFile is suppressed here (see explicitBundlePath above) so it
444
- // can't bias selection to the innermost dir; it is still loaded via `sources` once committed.
261
+ // Root-SELECTION signal: only the DEFAULT <rootDir>/stasis.code.br counts (see
262
+ // explicitBundlePath); an explicit bundleFile is still loaded via `sources`.
445
263
  const bundleProbe = explicitBundlePath ? null : sources
446
264
  if (config !== null || lockProbe !== null || bundleProbe !== null) {
447
265
  if (loaded) throw new Error('Stasis config already loaded')
@@ -450,11 +268,7 @@ export class State {
450
268
 
451
269
  if (config) {
452
270
  this.config.loadConfig(config)
453
- // stasis.config.json may set `bundleFile`, which the probe above (using the
454
- // construction-time value) could not see. Re-resolve against the now-authoritative
455
- // config and re-read, so a config-only bundleFile is honored for load/frozen -- the
456
- // write side (state.write) already resolves bundleFile after loadConfig. This mirrors
457
- // the resourcesBundleFile read below, which is naturally post-loadConfig.
271
+ // stasis.config.json may set a `bundleFile` the probe couldn't see -- re-resolve and re-read.
458
272
  const configuredPath = this.config.bundleFile || join(rootDir, FILE_CODE)
459
273
  if (configuredPath !== sourcesPath) {
460
274
  sourcesPath = configuredPath
@@ -462,9 +276,6 @@ export class State {
462
276
  }
463
277
  }
464
278
 
465
- // Resolve the effective lockfile content + path for this run. With an explicit
466
- // `config.lockFile`, the lockfile is at that exact path (loaded once, not at a
467
- // per-rootDir probe); without one, fall back to `<rootDir>/stasis.lock.json`.
468
279
  const lock = explicitLockPath
469
280
  ? readFileSyncMaybe(dirname(explicitLockPath), basename(explicitLockPath), 'utf-8')
470
281
  : lockProbe
@@ -473,40 +284,22 @@ export class State {
473
284
  lockfileLoaded = this.#absorbLockfile(lock, lockPath)
474
285
  this.#loadBundleArtifacts(sources, sourcesPath, lockfileLoaded)
475
286
 
476
- // The innermost matching rootDir is authoritative (per-dir opt-in, see above), so stop
477
- // scanning once committed. An explicit/config `bundleFile` is rootDir-independent: without
478
- // this break an outer candidate root re-detects the SAME bundle file at its own probe and
479
- // trips the `loaded` guard above -- which crashed bundle=load/frozen in any nested-package
480
- // (monorepo) layout where a leaf package sits under an ancestor that also has a package.json.
287
+ // Innermost matching rootDir wins (per-dir opt-in); without this break an outer root
288
+ // re-detects a rootDir-independent bundleFile and trips `loaded`.
481
289
  break
482
290
  }
483
291
  }
484
292
 
485
- // Explicit lockfile path with no other discovery indicator at any rootDir: the
486
- // discovery loop never set `loaded`, so the lockfile branch above never ran. Process
487
- // the explicit lockfile here against the already-resolved `this.root` (outermost
488
- // package.json) so the run still has its attestation.
293
+ // Explicit lockfile but no discovery indicator: the loop never ran, so absorb here against
294
+ // `this.root` (outermost) so the run still has attestation.
489
295
  if (!loaded && explicitLockPath) {
490
296
  const lock = readFileSyncMaybe(dirname(explicitLockPath), basename(explicitLockPath), 'utf-8')
491
297
  lockfileLoaded = this.#absorbLockfile(lock, explicitLockPath)
492
298
  }
493
299
 
494
- // Explicit (flag/env) bundleFile and/or resourcesBundleFile with no rootDir-dependent
495
- // indicator at any rootDir: like the explicit lockfile above, an explicit bundleFile was
496
- // suppressed as a root-detection signal so it couldn't pull the root down to the innermost
497
- // package, so the loop never loaded it. Load it here against `this.root` (the outermost
498
- // package.json) -- the same root capture commits to when no signal exists -- so its
499
- // capture-root-relative keys line up with how they're looked up. `resourcesBundleFile` is in
500
- // the gate for the resources-only split shape (#absorbResourcesBundle documents it as legal):
501
- // with no code bundle on disk there is no other reason to reach the loader here, yet the
502
- // explicit resources half must still be absorbed. Post-loop, both paths are necessarily
503
- // flag/env: a stasis.config.json could only have set them by also committing the loop.
504
- //
505
- // NB: the outermost root depends on where the upward walk stopped (PROJECT_CWD, .git,
506
- // pnpm-workspace.yaml -- see potentialRoots above). Capture and load must agree on that
507
- // boundary for the keys to line up: e.g. a capture under yarn (PROJECT_CWD set to an inner
508
- // workspace dir) and a bare load of the same bundle (walks up to the repo's .git) commit
509
- // different roots and fail with "outside the project root" / "not attested".
300
+ // Explicit bundleFile suppressed as a root signal above: load against `this.root` (outermost).
301
+ // Capture and load MUST agree on where the upward walk stops (PROJECT_CWD/.git/
302
+ // pnpm-workspace.yaml), else they commit different roots and fail "outside the project root".
510
303
  if (!loaded && (explicitBundlePath || this.config.resourcesBundleFile)) {
511
304
  const sources = explicitBundlePath
512
305
  ? readFileSyncMaybe(dirname(explicitBundlePath), basename(explicitBundlePath))
@@ -514,23 +307,11 @@ export class State {
514
307
  this.#loadBundleArtifacts(sources, explicitBundlePath, lockfileLoaded)
515
308
  }
516
309
 
517
- // Frozen modes must have actually loaded their attestation. Asserting here --
518
- // after the discovery loop -- rather than only inside it closes a fail-open: with
519
- // no stasis files on disk at all the loop body never runs, so a per-rootDir guard
520
- // would never fire, and in node_modules scope the workspace entry sits outside the
521
- // attested zone (its bytes/format/resolutions aren't checked), letting it execute
522
- // unverified. A frozen run with nothing to verify against must fail closed instead.
310
+ // Post-loop: with no stasis files the loop never runs, and a frozen run must fail closed.
523
311
  if (this.config.frozen) assert.ok(lockfileLoaded, 'No lockfile, but attempting to run in frozen mode')
524
312
  if (this.config.frozenBundle) assert.ok(this.#bundleSources !== null, 'No bundle, but attempting to run in frozen bundle mode')
525
313
 
526
- // Claim this State's write targets against the process-wide registry (liveStates),
527
- // so a sidecar OR an independent top-level State -- in this OR another stasis-core
528
- // copy -- can't silently target the same on-disk file. Load / frozen / no-bundle modes
529
- // don't claim (they legitimately read what a previous writer produced). lockFile is
530
- // claimed only by writing top-level States -- sidecars don't write the lockfile, and
531
- // the explicit path may legitimately point at the parent's under unification. The
532
- // State itself is added to liveStates() below, AFTER every fallible step (including
533
- // these claims), so a throw during discovery/parsing/claiming never leaves a dead member.
314
+ // Claim write targets so no other live State (any copy) silently targets the same file.
534
315
  if (this.config.writeBundle && this.config.bundleFile) {
535
316
  this.#claimWritePath(`bundleFile '${this.config.bundleFile}'`, this.config.bundleFile)
536
317
  }
@@ -541,10 +322,6 @@ export class State {
541
322
  this.#claimWritePath(`lockFile '${this.config.lockFile}'`, this.config.lockFile)
542
323
  }
543
324
 
544
- // preloadRoot is opt-in -- only the runtime loader (hooks.js's initState)
545
- // sets it, pointing at stasis-core's own package root. Plain top-level
546
- // States constructed via the CLI / direct API leave it null and skip
547
- // the internal-edges backfill entirely.
548
325
  if (preloadRoot !== undefined) {
549
326
  assert.equal(typeof preloadRoot, 'string', 'preloadRoot must be a string')
550
327
  this.#preloadRoot = preloadRoot
@@ -553,12 +330,8 @@ export class State {
553
330
  liveStates().add(this)
554
331
  }
555
332
 
556
- // Absorb a lockfile's attestation into this State: the run-scope module/hash maps, the
557
- // imports/formats attestation, and the frozen-mode warnings for lockfiles predating those
558
- // attestations. Shared by the discovery loop (a committed rootDir) and the post-loop fallback
559
- // for an explicit `config.lockFile` -- a rootDir-independent path, so it is suppressed as a
560
- // root-detection signal and loaded at the outermost root instead. Returns whether the lockfile
561
- // was actually absorbed (the caller's `lockfileLoaded`).
333
+ // Absorb a lockfile's attestation; returns whether it was actually absorbed. Lockfile.parse
334
+ // requires both imports and formats, so an absorbed lockfile always attests them.
562
335
  #absorbLockfile(lock, lockPath) {
563
336
  if (lock && !this.config.useLockfile && !this.config.ignoreLockfile) {
564
337
  throw new Error(`Unexpected ${lockPath} with config.lock = 'none'`)
@@ -569,7 +342,7 @@ export class State {
569
342
 
570
343
  const includeSources = lockfile.config.scope === 'full' && this.config.full
571
344
  for (const [dir, info] of lockfile.modules) {
572
- if (!dir.includes('node_modules') && !includeSources) continue
345
+ if (!hasNodeModulesSegment(dir) && !includeSources) continue
573
346
  this.modules.set(dir, info)
574
347
  }
575
348
  if (includeSources) this.entries = lockfile.entries
@@ -581,50 +354,26 @@ export class State {
581
354
  }
582
355
  this.#lockImports = lockfile.imports
583
356
  this.#lockFormats = lockfile.formats
584
- // Frozen promises verification, but a lockfile predating resolution
585
- // or format attestation can only vouch for bytes -- those metadata
586
- // (from a bundle OR observed on disk) go unchecked until it's
587
- // regenerated.
588
- if (this.config.frozen && this.#lockImports === null) {
589
- console.warn('[stasis] Warning: lockfile does not attest resolutions; they are trusted as-is. Regenerate the lockfile to enable this check.')
590
- }
591
- if (this.config.frozen && this.#lockFormats === null) {
592
- console.warn('[stasis] Warning: lockfile does not attest formats; they are trusted as-is. Regenerate the lockfile to enable this check.')
593
- }
357
+ // Seeded into the live set (not a separate baseline) so re-reading a file this run can CLEAR
358
+ // a stale exec bit.
359
+ this.#absorbExecutable(lockfile)
594
360
  this.#lockfileLoaded = true
595
361
  return true
596
362
  }
597
363
 
598
- // Gate and load the bundle artifacts for an already-committed root: the unified
599
- // code[+resource] bundle read from `sourcesPath`, plus the split `resourcesBundleFile` when
600
- // one is configured. Shared by the discovery loop and the post-loop explicit-path fallback so
601
- // the mode guards cannot drift between the two. `sources` may be null -- no bundle on disk, or
602
- // a resources-only deployment -- in which case only the resources half applies.
603
- //
604
- // The missing-lockfile guard tests `lockfileLoaded` where the pre-extraction in-loop code
605
- // tested raw lockfile presence; equivalent at this call point, since whenever the guard can
606
- // fire (useLockfile && !replaceLockfile) #absorbLockfile absorbed the lockfile iff it existed.
364
+ // Gate and load the bundle artifacts for a committed root; `sources` may be null (no bundle, or
365
+ // resources-only).
607
366
  #loadBundleArtifacts(sources, sourcesPath, lockfileLoaded) {
608
367
  if (sources && !this.config.writeBundle && !this.config.loadBundle && !this.config.ignoreBundle && !this.config.frozenBundle) {
609
368
  throw new Error(`Unexpected ${sourcesPath} with config.bundle = 'none'`)
610
369
  }
611
- // A frozen bundle is self-attesting -- it verifies disk against the bundle's
612
- // own bytes, so (unlike load/add) it needs no sibling lockfile and is exempt
613
- // from this "a lockfile is required before a bundle's sources can be trusted"
614
- // guard. This is what lets bundle=frozen compose with lock=add (bootstrapping a
615
- // fresh lockfile from the verified run) without a pre-existing lockfile.
370
+ // A frozen bundle is self-attesting, so it needs no sibling lockfile and is exempt here.
616
371
  if (sources && !lockfileLoaded && this.config.useLockfile && !this.config.replaceLockfile && !this.config.frozenBundle) {
617
372
  throw new Error('stasis.lock.json missing, can not use sources')
618
373
  }
619
374
  if (sources && (this.config.writeBundle || this.config.loadBundle || this.config.frozenBundle) && !this.config.replaceBundle) {
620
375
  this.#absorbCodeBundle(sources, sourcesPath, lockfileLoaded)
621
376
  }
622
- // Split-bundle layout: when `resourcesBundleFile` is configured, resources
623
- // live in a separate file. Load it as a standalone Bundle (entries empty,
624
- // imports empty, formats restricted to resource tags) and union into the
625
- // state already absorbed from `bundleFile`. The strict-shape asserts catch
626
- // a writer that accidentally leaked code into the resources file or a
627
- // tampered file claiming entries/imports it shouldn't have.
628
377
  if (this.config.resourcesBundleFile) {
629
378
  const resourcesPath = this.config.resourcesBundleFile
630
379
  const resourcesData = readFileSyncMaybe(dirname(resourcesPath), basename(resourcesPath))
@@ -634,26 +383,20 @@ export class State {
634
383
  }
635
384
  }
636
385
 
637
- // Absorb a unified code+resource bundle's metadata and payloads into this State. Shared by the
638
- // discovery loop (a committed rootDir carrying a stasis signal) and the post-loop fallback that
639
- // loads an explicit (rootDir-independent) bundleFile against the outermost root.
640
386
  #absorbCodeBundle(sources, sourcesPath, lockfileLoaded) {
641
- // One unified bundle carries both code and resources. Split the flat file
642
- // view into this.sources (code) and this.resources (resource payloads --
643
- // raw UTF-8 for 'resource', base64 for 'resource:base64') by format.
644
387
  const bundle = Bundle.parse(brotliDecompressSync(sources).toString('utf-8'))
645
- // `Bundle.parse` accepts v0 for offline tooling (`stasis extract`, `diff`,
646
- // `audit`, `sbom`) -- it has the metadata those commands need. The runtime
647
- // path is stricter: a v0 bundle has no per-file `formats` attestation
648
- // (resources can't be distinguished from code, the loader can't pick
649
- // module-vs-commonjs) and no import map (resolution edges go unchecked),
650
- // so serving / verifying one under `stasis run` would silently widen the
651
- // trust boundary. Refuse it explicitly and point at the upgrade path.
388
+ // Bundle.parse accepts v0 for offline tooling; the runtime refuses it -- v0 has no per-file
389
+ // formats or import map, so serving one widens the trust boundary.
652
390
  assert.equal(bundle.version, Bundle.VERSION,
653
391
  `stasis run requires a v1 bundle; ${sourcesPath} is v${bundle.version}. ` +
654
392
  `Re-bundle with the current stasis (\`stasis bundle\`) or \`stasis run --bundle=replace\` ` +
655
393
  `against a v0-free starting point to upgrade.`)
656
394
  assert.equal(bundle.config.scope, this.config.scope)
395
+ // assertEntry short-circuits on an empty set, so a runnable full-scope code bundle must declare
396
+ // an entry here -- else any bundled file could run as the root. Add-only bundles have none.
397
+ assert.ok(!this.config.full || bundle.entries.size > 0 || !bundle.hasCode,
398
+ `${sourcesPath}: a full-scope bundle carrying code must declare an entry to run ` +
399
+ `(an add-only attestation has none; run a bundle built by \`stasis bundle\`/\`stasis run\`)`)
657
400
  this.#mergeBundleMetadata(bundle, { lockfileLoaded })
658
401
  for (const [file, content] of bundle.sources) {
659
402
  if (Bundle.isResourceFormat(bundle.formats.get(file))) this.resources.set(file, content)
@@ -661,12 +404,11 @@ export class State {
661
404
  }
662
405
  this.formats = bundle.formats
663
406
  this.imports = bundle.imports
407
+ this.#absorbExecutable(bundle)
408
+ this.#seedReasonFromBundle(bundle)
664
409
  if (this.config.frozenBundle) {
665
- // Snapshot the attested sets before addFile/addImport mutate the live maps.
666
- // imports is deep-cloned (this.imports shares bundle.imports's nested Maps,
667
- // which addImport extends); formats is a flat file->string map, so a shallow
668
- // copy suffices. Code and resource file sets are tracked separately to match
669
- // addFile's per-kind frozen-bundle membership check.
410
+ // Snapshot before addFile/addImport mutate the live maps; imports is deep-cloned because
411
+ // this.imports shares bundle.imports's nested Maps.
670
412
  this.#bundleSources = new Set(this.sources.keys())
671
413
  this.#bundleResources = new Set(this.resources.keys())
672
414
  this.#bundleImports = objectToMaps(fileMapToObject(bundle.imports))
@@ -674,18 +416,8 @@ export class State {
674
416
  }
675
417
  }
676
418
 
677
- // Cross-check bundle metadata (entries/modules) with what the lockfile already
678
- // loaded, or absorb it as the source of truth when no lockfile is present.
679
- // v0 bundles infer `name` from path for node_modules buckets but carry no
680
- // version; the workspace "." bucket has no inferable name. We skip entries
681
- // we can't cross-check (no name with lockfile, or no version when populating
682
- // state.modules — addFile later asserts strict name+version equality against
683
- // disk's package.json, which would clash with a null we stashed earlier).
684
- // Note: the path-inferred name for v0 will disagree with the lockfile when a
685
- // dep is installed under an alias (`foo: npm:bar` writes `node_modules/foo`
686
- // with `name: "bar"` in package.json); the strict equality below will fail
687
- // in that case, which is the right call — the v0 bundle has no way to
688
- // attest the real package identity, so we refuse to silently mismatch.
419
+ // Cross-check bundle metadata (entries/modules) against the loaded lockfile, or absorb it as
420
+ // source of truth when none. v0 buckets carry no version, so unverifiable entries are skipped.
689
421
  #mergeBundleMetadata(bundle, { lockfileLoaded }) {
690
422
  if (lockfileLoaded) {
691
423
  if (bundle.entries.size > 0) {
@@ -705,13 +437,8 @@ export class State {
705
437
  assert.ok(Object.hasOwn(lockModule.files, rel), `bundle file ${dir}/${rel} missing in lockfile`)
706
438
  }
707
439
  }
708
- // Resolutions: every edge the bundle could serve must land on the file
709
- // the lockfile attests for that (parent, specifier) -- source hashes
710
- // alone don't close this hole: a tampered bundle could redirect a
711
- // specifier to a *different* hash-valid file. Unknown edges are fatal.
712
- // The lockfile may attest a superset (same stance as the file lists
713
- // above). Lockfiles that predate resolution attestation
714
- // (imports === null) skip the check -- regenerate with lock=replace.
440
+ // Hashes alone don't stop a redirect to a different hash-valid file, so every edge the bundle
441
+ // could serve must match the lockfile's attested target (a lockfile superset is fine).
715
442
  if (this.#lockImports !== null) {
716
443
  for (const [conditions, byParent] of bundle.imports) {
717
444
  for (const [parent, specifiers] of byParent) {
@@ -721,27 +448,14 @@ export class State {
721
448
  }
722
449
  }
723
450
  }
724
- // Formats: the loader picks module<->commonjs and (for *-typescript)
725
- // whether Node strips type syntax purely from this map, so a tampered
726
- // bundle can change how hash-valid bytes parse/run without touching a
727
- // hash. Every format the bundle declares must match the lockfile's. The
728
- // bundle's file set is a subset of the lockfile, so an unattested format
729
- // is fatal here (it can only mean a forged entry).
451
+ // A format flip changes how hash-valid bytes parse (module<->commonjs) without touching a
452
+ // hash, so every bundle format must match the lockfile's; unattested is fatal.
730
453
  if (this.#lockFormats !== null) {
731
454
  for (const [file, format] of bundle.formats) {
732
455
  this.#assertAttestedFormat(this.#lockFormats, file, format, { what: 'bundle', source: 'lockfile' })
733
456
  }
734
- // Inverse direction: if the lockfile tags a file the bundle carries as a
735
- // resource, the bundle MUST declare the matching resource format. Without
736
- // this, a tampered bundle could OMIT the resource tag entirely -- State.load
737
- // would then see no resource format, route the base64 payload through
738
- // `this.sources` (the code path), and hand it to the loader. Caught at the
739
- // loader's NODEJS_FORMATS gate too, but checking here surfaces it as a clean
740
- // bundle/lockfile mismatch rather than as an opaque "unknown format" later.
741
- // (We don't extend this to code formats: doing so would mean asserting
742
- // `formats` is total over `modules`, which is a stronger schema invariant
743
- // than the historical "format may be missing per file" contract -- and the
744
- // code-format hole is closed by the loader allowlist anyway.)
457
+ // Inverse: a lockfile-tagged resource MUST be tagged in the bundle too, else omitting the
458
+ // tag routes the base64 payload through this.sources (code) to the loader.
745
459
  for (const [dir, { files }] of bundle.modules) {
746
460
  for (const rel of Object.keys(files)) {
747
461
  const file = moduleFileKey(dir, rel)
@@ -753,16 +467,12 @@ export class State {
753
467
  }
754
468
  }
755
469
  } else {
756
- // Mutate in place rather than reassigning -- this.entries may be shared by
757
- // reference with a sidecar's parent (the unified-lockfile model), and a
758
- // reassignment would silently fork the shared set.
470
+ // Mutate in place: this.entries may be shared by reference with a sidecar's parent.
759
471
  for (const e of bundle.entries) this.entries.add(e)
760
472
  for (const [dir, info] of bundle.modules) {
761
473
  if (!info.name || !info.version) continue // partial metadata
762
474
  if (this.modules.has(dir)) {
763
- // A unified bundle populates `state.modules` from both its code and resource
764
- // entries; if the same dir is added twice (e.g. legacy duplicated metadata)
765
- // they must agree on name/version.
475
+ // A dir may be added twice (code + resource entries), and both must agree.
766
476
  const existing = this.modules.get(dir)
767
477
  assert.equal(info.name, existing.name, `bundle ${dir} name mismatch`)
768
478
  assert.equal(info.version, existing.version, `bundle ${dir} version mismatch`)
@@ -775,23 +485,15 @@ export class State {
775
485
  }
776
486
  }
777
487
 
778
- // Load the resources side of a split-bundle layout: a standalone Bundle file
779
- // that MUST hold only resource-format files (no entries, no imports, no
780
- // code-format declarations). Unions into the state already absorbed from
781
- // `bundleFile`, extending this.resources, this.formats, and -- under
782
- // frozenBundle -- the attestation snapshots. The shape asserts catch a writer
783
- // that leaked code into the resources file or a tampered file claiming
784
- // metadata it shouldn't carry.
488
+ // Load the resources half of a split-bundle layout: ONLY resource-format files, unioned into the
489
+ // bundleFile state.
785
490
  #absorbResourcesBundle(resourcesData, { lockfileLoaded, resourcesPath }) {
786
491
  const bundle = Bundle.parse(brotliDecompressSync(resourcesData).toString('utf-8'))
787
492
  assert.equal(bundle.version, Bundle.VERSION,
788
493
  `stasis run requires a v1 resources bundle; ${resourcesPath} is v${bundle.version}. ` +
789
494
  `Re-bundle with the current stasis or \`bundle=replace\` against a v0-free starting point to upgrade.`)
790
495
  assert.equal(bundle.config.scope, this.config.scope)
791
- // Resources file MUST NOT declare resolution edges or entry points -- those
792
- // belong to the code bundle. A populated map here means the writer mixed
793
- // halves (or the file was tampered with) and serving it would silently widen
794
- // trust on the code-bundle side's metadata.
496
+ // A populated imports/entries map means mixed halves or tampering -- widens trust on the code side.
795
497
  assert.equal(bundle.imports.size, 0, `resources bundle ${resourcesPath} must have empty imports`)
796
498
  assert.equal(bundle.entries.size, 0, `resources bundle ${resourcesPath} must have empty entries`)
797
499
  for (const [file, format] of bundle.formats) {
@@ -802,19 +504,18 @@ export class State {
802
504
  for (const [file, content] of bundle.sources) {
803
505
  this.resources.set(file, content)
804
506
  }
805
- // Union formats: conflict-free (bundleFile carries code formats, this one carries
806
- // resource formats -- the file sets must be disjoint).
507
+ // Union formats: the two halves' file sets must be disjoint.
807
508
  for (const [file, format] of bundle.formats) {
808
509
  const existing = this.formats.get(file)
809
510
  assert.ok(existing === undefined || existing === format,
810
511
  `format conflict for ${file}: bundleFile declares '${existing}', resourcesBundleFile declares '${format}'`)
811
512
  this.formats.set(file, format)
812
513
  }
514
+ this.#absorbExecutable(bundle)
515
+ this.#seedReasonFromBundle(bundle)
813
516
  if (this.config.frozenBundle) {
814
- // Extend the frozen snapshot. bundleFile's path may not have populated these
815
- // (resources-only deployments are legal -- only the resources file exists),
816
- // so initialize lazily; #bundleSources may stay null in that case, which the
817
- // post-discovery invariant check accepts because #bundleResources is set.
517
+ // Extend the frozen snapshot, init lazily: resources-only deployments are legal, so
518
+ // bundleFile may not have populated these.
818
519
  if (this.#bundleResources === null) this.#bundleResources = new Set()
819
520
  if (this.#bundleFormats === null) this.#bundleFormats = new Map()
820
521
  if (this.#bundleImports === null) this.#bundleImports = objectToMaps(fileMapToObject(this.imports))
@@ -824,17 +525,14 @@ export class State {
824
525
  }
825
526
  }
826
527
 
827
- // Verify one resolution edge against an attestation map (`source`: a loaded
828
- // lockfile, or a frozen bundle's own recorded imports). The final resolution
829
- // is what matters, not how the edge is keyed: the conditions key is matched
830
- // exactly first; on a miss the edge is accepted only when every condition set
831
- // the attestation records for that (parent, specifier) agrees on the same
832
- // target -- this lets a static `stasis bundle` artifact (edges under '*')
833
- // validate against a runtime-generated attestation (precise condition sets),
834
- // and vice versa, while a claim over a condition-divergent attestation stays
835
- // fatal: either target would be served under conditions where the other is
836
- // the attested resolution. Unknown edges are fatal unless the caller opts out
837
- // (see addImport's node_modules-scope carve-out).
528
+ // Union (never replace) an absorbed artifact's `executable` list into the live set: a lockfile
529
+ // seed, or the code half of a split layout, may already have contributed.
530
+ #absorbExecutable(artifact) {
531
+ for (const file of artifact.executable) this.executable.add(file)
532
+ }
533
+
534
+ // Verify one resolution edge against an attestation map: exact conditions key first, else accept
535
+ // only if every condition set agrees on one target. Unknown edges fatal unless tolerateUnknown.
838
536
  #assertAttestedResolution(attestation, conditions, parent, specifier, file, { what, source = 'lockfile', tolerateUnknown = false }) {
839
537
  const edge = `'${specifier}' from ${parent} (${conditions})`
840
538
  let attested = attestation.get(conditions)?.get(parent)?.get(specifier)
@@ -849,21 +547,16 @@ export class State {
849
547
  assert.ok(targets.size === 1, `${what} resolution ${edge} is attested inconsistently across condition sets in the ${source}`)
850
548
  ;[attested] = targets
851
549
  }
852
- // A per-platform edge is a Map<platform, target>; compare it structurally -- a plain
853
- // assert.equal is reference equality, so two identical Maps (the bundle's edge and the
854
- // lockfile's) would never match. A flat string edge stays a plain ===; a Map-vs-string
855
- // (e.g. a per-platform attestation vs a single observed runtime target) is a mismatch.
550
+ // A per-platform edge is a Map<platform, target>: compare structurally (assert.equal is
551
+ // reference equality).
856
552
  const matches = file instanceof Map && attested instanceof Map
857
553
  ? file.size === attested.size && [...file].every(([platform, target]) => attested.get(platform) === target)
858
554
  : file === attested
859
555
  assert.ok(matches, `${what} resolution ${edge} mismatches the ${source}`)
860
556
  }
861
557
 
862
- // Verify one file's loader format against an attestation map (`source`: a
863
- // loaded lockfile, or a frozen bundle's own recorded formats). Callers only
864
- // invoke this for files that must be attested (the attestation is a superset
865
- // of any bundle, and on the disk path the call is gated to the hash-attested
866
- // zone), so an unattested file means a forged/extra entry and is fatal.
558
+ // Verify one file's loader format. Callers only pass files that must be attested, so an
559
+ // unattested file means a forged/extra entry -- fatal.
867
560
  #assertAttestedFormat(attestation, file, format, { what, source = 'lockfile' }) {
868
561
  const attested = attestation.get(file)
869
562
  assert.ok(attested !== undefined, `${what} format for ${file} is not attested by the ${source}`)
@@ -871,39 +564,30 @@ export class State {
871
564
  }
872
565
 
873
566
  assertEntry(url) {
874
- // Skipped silently when no entries info is available (v0 bundle + lock=none/ignore).
875
- // v1 bundles in full scope are required to declare at least one entry at parse time,
876
- // so this fallback only ever triggers for the legacy path.
567
+ // No entry attestation to check against (lock=none/ignore, fresh build) -- #absorbCodeBundle
568
+ // already refuses a runnable code bundle that declares none.
877
569
  if (this.entries.size === 0) return
878
570
  const file = this.#canonicalFile(url)
879
571
  assert.ok(this.entries.has(file), `Unknown entry point: ${file}`)
880
572
  }
881
573
 
882
- // The one preload (top-level) State, or undefined. Scans the process-wide registry
883
- // (shared across stasis-core copies) for the member flagged isPreload.
884
574
  static get preload() {
885
575
  for (const state of liveStates()) if (state.isPreload) return state
886
576
  return undefined
887
577
  }
888
578
 
889
- // True iff this is THE preload (top-level) State. Public so State.preload can identify
890
- // it even when this State came from a different stasis-core copy.
579
+ // Public so State.preload works across copies.
891
580
  get isPreload() {
892
581
  return this.#isPreload
893
582
  }
894
583
 
895
- // The label under which this State claims `canonical` as a write target, or undefined.
896
- // Public so #claimWritePath's collision scan can consult a State from another copy.
584
+ // Public for #claimWritePath's cross-copy collision scan.
897
585
  claimedWritePathLabel(canonical) {
898
586
  return this.#claims.get(canonical)
899
587
  }
900
588
 
901
- // Claim a write target, refusing a path another live State (in ANY copy) already
902
- // claims. Canonicalize so `./x` / `x` / symlinks compare equal. Scans the process-wide
903
- // registry, so collisions are caught across copies and without a preload. Intra-State
904
- // collisions are caught earlier by Config (#checkInvariants), so this only fires
905
- // cross-State. The claim is recorded on this instance; it becomes visible to later
906
- // States once this one is added to liveStates() at the end of construction.
589
+ // Refuse a path another live State (ANY copy) already claims; canonicalized so `./x`/`x`/symlinks
590
+ // compare equal.
907
591
  #claimWritePath(label, value) {
908
592
  if (!value) return
909
593
  const canonical = canonicalizePath(value)
@@ -914,19 +598,13 @@ export class State {
914
598
  this.#claims.set(canonical, label)
915
599
  }
916
600
 
917
- // This State's stasis-core version. Public so a child (sidecar) can verify it
918
- // exactly matches its parent's even when the two are different module copies
919
- // sharing the process-wide registry (see the constructor's parent branch).
601
+ // Public so a sidecar can verify it matches its parent's across copies.
920
602
  get version() {
921
603
  return VERSION
922
604
  }
923
605
 
924
- // The slice of parent state a child (sidecar) inherits. Exposed as a PUBLIC method
925
- // (rather than the child reading the parent's private fields) so a sidecar from a
926
- // different-but-version-matched stasis-core copy -- a bundle carrying its own
927
- // stasis-core, whose plugin sidecars the outer loader's preload -- can read it across
928
- // the class brand. Only ever called by the sidecar constructor, after its version
929
- // assert; the exact-version match guarantees these shapes are compatible.
606
+ // PUBLIC (not private-field reads) so a sidecar from a different copy can read it across the
607
+ // class brand.
930
608
  sidecarInheritance() {
931
609
  return {
932
610
  preloadRoot: this.#preloadRoot,
@@ -936,20 +614,12 @@ export class State {
936
614
  }
937
615
  }
938
616
 
939
- // Register a WRITE-mode child (sidecar) so this parent's unified lockData unions its
940
- // imports/formats (and attestedBySidecar sees its captures). Public (not a direct
941
- // `#sidecars.add`) for the same cross-copy reason as sidecarInheritance: the call runs
942
- // on the parent, touching the parent's own #sidecars, so it works even when the sidecar
943
- // is a foreign-copy instance.
617
+ // WRITE-mode sidecar: this parent's lockData unions its imports/formats. Public (cross-copy).
944
618
  registerSidecar(sidecar) {
945
619
  this.#sidecars.add(sidecar)
946
620
  }
947
621
 
948
- // Register a LOAD-mode child as a read-only family member: getFs*Family serves bundle
949
- // bytes from it (a --fs read at load of a file the sidecar carries) but, unlike
950
- // registerSidecar, it never enters #mergedImports/#mergedFormats, so a load-mode sidecar
951
- // contributes no resolution edges or formats (the lockfile's trust-bearing content) to the
952
- // unified lockfile. Public for the same cross-copy reason as registerSidecar.
622
+ // LOAD-mode sidecar: served by getFs*Family, never a lockfile contributor. Public (cross-copy).
953
623
  registerReadSidecar(sidecar) {
954
624
  this.#readSidecars.add(sidecar)
955
625
  }
@@ -965,22 +635,27 @@ export class State {
965
635
  assert.ok(absolute)
966
636
  const file = relative(this.root, absolute)
967
637
  assert.ok(!file.startsWith('..'))
968
- // The project root itself is keyed '.' -- never '' (path.relative's raw answer).
969
- // Reached only by a `--fs` directory capture/lookup of the root; '.' is what
970
- // join('.', rel === '') re-derives when the lockfile is absorbed at load, so
971
- // recording/looking up under '' would desync write from read (the root listing
972
- // was written under '' yet hashed under '.', failing getFile's integrity check).
638
+ // The project root is keyed '.', never '' -- mixing the two desyncs write from read.
973
639
  return file === '' ? '.' : file
974
640
  }
975
641
 
976
- // A file reached under node_modules whose REAL path lies outside any
977
- // node_modules is a workspace source linked into node_modules (pnpm links a
978
- // workspace dependency in via a symlink). Canonicalize such a URL to its real
979
- // path so it is recorded/looked up as a *source*, not a dependency -- and thus
980
- // excluded from a node_modules-scope bundle. Everything else is returned
981
- // untouched: plain sources, real dependencies, and node_modules -> node_modules
982
- // links (e.g. pnpm's `.pnpm` store) keep their original path.
642
+ // Memoized #canonicalUncached (per URL, State-lifetime): a realpathSync per node_modules URL, and
643
+ // hot callers repeat relentlessly. Sound only because the tree holds still mid-run; the cached
644
+ // result is shared -- never mutate it.
645
+ #canonicalCache = new Map()
646
+
983
647
  #canonical(url) {
648
+ let result = this.#canonicalCache.get(url)
649
+ if (result === undefined) {
650
+ result = this.#canonicalUncached(url)
651
+ this.#canonicalCache.set(url, result)
652
+ }
653
+ return result
654
+ }
655
+
656
+ // A node_modules file whose REAL path is outside node_modules is a linked-in workspace source
657
+ // (pnpm): canonicalize so it's recorded as a source, not a dependency. Everything else passes through.
658
+ #canonicalUncached(url) {
984
659
  const absolute = this.absolute(url)
985
660
  const file = relative(this.root, absolute)
986
661
  if (file.startsWith('..') || !splitNodeModulesPath(file)) return { url, absolute }
@@ -990,27 +665,18 @@ export class State {
990
665
  } catch {
991
666
  return { url, absolute }
992
667
  }
993
- if (real === absolute) return { url, absolute } // not a symlink
668
+ if (real === absolute) return { url, absolute }
994
669
  const realFile = relative(this.root, real)
995
- // Outside the root, or still inside some node_modules (a real dependency,
996
- // e.g. pnpm's `.pnpm` store): leave the recorded path unchanged.
997
670
  if (realFile.startsWith('..') || splitNodeModulesPath(realFile)) return { url, absolute }
998
671
  return { url: pathToFileURL(real).toString(), absolute: real }
999
672
  }
1000
673
 
1001
- // The canonical project-relative path a URL is recorded/looked up under.
1002
674
  #canonicalFile(url) {
1003
675
  return this.relative(this.#canonical(url).absolute)
1004
676
  }
1005
677
 
1006
- // True when `url` resolves (through any workspace symlink) to a file under
1007
- // node_modules -- i.e. a bundled dependency -- as opposed to a workspace source
1008
- // linked into node_modules (which #canonical records as a source). The loader
1009
- // hooks gate on this rather than a raw `/node_modules/` substring, so a
1010
- // symlinked workspace source is read from disk / resolved by Node instead of
1011
- // being served from a node_modules-scope bundle that deliberately omits it.
1012
- // Tolerant: a URL it can't canonicalize (non-file, outside root) is treated as
1013
- // not-a-dependency, so the hook falls back to Node's default handling.
678
+ // True when `url` resolves (through any workspace symlink) into node_modules -- not a raw
679
+ // `/node_modules/` substring test, so a symlinked workspace source is read from disk.
1014
680
  inNodeModules(url) {
1015
681
  let file
1016
682
  try {
@@ -1021,11 +687,8 @@ export class State {
1021
687
  return splitNodeModulesPath(file) !== null
1022
688
  }
1023
689
 
1024
- // Nearest package.json at or above a directory, for addFsDir (`stasis run --fs`
1025
- // readdir captures). Replaces findPackageJSON, which is unreliable for a directory
1026
- // URL (see #locateModule). Walks up using the real fs (the destructured existsSync
1027
- // snapshot), bounded by the project root -- which is always an existing-package.json
1028
- // dir, so an in-root directory always resolves. Returns an absolute package.json path.
690
+ // Nearest package.json at or above a directory (findPackageJSON is unreliable for a directory
691
+ // URL, see #locateModule). Bounded by the project root.
1029
692
  #nearestPackageJsonFor(dirAbsolute) {
1030
693
  let dir = dirAbsolute
1031
694
  while (true) {
@@ -1033,29 +696,17 @@ export class State {
1033
696
  if (existsSync(candidate)) return candidate
1034
697
  if (dir === this.root) break // checked the root's package.json; never escape root
1035
698
  const parent = dirname(dir)
1036
- if (parent === dir) break // filesystem root
699
+ if (parent === dir) break
1037
700
  dir = parent
1038
701
  }
1039
- // Unreachable in practice: state.root is resolved to a dir that has package.json.
702
+ // Unreachable: state.root is resolved to a dir that has package.json.
1040
703
  assert.fail(`no package.json at or above directory ${this.relative(dirAbsolute)}`)
1041
704
  }
1042
705
 
1043
- // Canonicalize `url` and resolve the package bucket that owns it, registering the
1044
- // module (name/version, `npm` ecosystem under node_modules) on first sight. Shared
1045
- // by addFile (code/resource) and addFsDir (directory captures): everything here is
1046
- // independent of a file's bytes or loader format, so both reuse it. Returns the
1047
- // canonical absolute path, the project-relative `file`, the bucket `dir`/`module`,
1048
- // and the nearest package `type` (for addFile's extension inference).
1049
- //
1050
- // `directory: true` (addFsDir): the url names a directory, not a file. Node's
1051
- // findPackageJSON is unreliable for a directory URL -- depending on Node version
1052
- // it returns the PARENT's package.json, `undefined` (at a bucket root), or even a
1053
- // `node_modules/` DIRECTORY path, which readPackageJSON would then read as a file
1054
- // and throw EISDIR. So for a directory we walk up to the nearest package.json
1055
- // ourselves (#nearestPackageJsonFor), which is correct on every Node version.
706
+ // Canonicalize `url` and resolve/register the owning package bucket. `directory: true` walks up
707
+ // ourselves -- Node's findPackageJSON is unreliable for a directory URL (EISDIR, or the parent's).
1056
708
  #locateModule(url, { directory = false } = {}) {
1057
- // Canonicalize first: a workspace source linked into node_modules is recorded
1058
- // under its real (non-node_modules) path so it classifies as a source.
709
+ // Canonicalize first: a linked-in workspace source is recorded under its real path (a source).
1059
710
  const canonical = this.#canonical(url)
1060
711
  url = canonical.url
1061
712
  const absolute = canonical.absolute
@@ -1068,8 +719,7 @@ export class State {
1068
719
  const closestType = closestPkg.type
1069
720
  assert.ok(closestType === undefined || closestType === 'module' || closestType === 'commonjs')
1070
721
 
1071
- // findPackageJSON may land on a `{"type":"module"}`-style sub-bucket
1072
- // marker that lacks name/version.
722
+ // findPackageJSON may land on a `{"type":"module"}` sub-bucket marker lacking name/version.
1073
723
  const nmRoot = splitNodeModulesPath(file)?.dir
1074
724
  let pkgAbsolute, name, version
1075
725
  if (nmRoot) {
@@ -1081,8 +731,7 @@ export class State {
1081
731
  if (closestPkgAbsolute !== pkgAbsolute) {
1082
732
  const message = `Inconsistent data between ${this.relative(closestPkgAbsolute)} and ${this.relative(pkgAbsolute)}`
1083
733
  if (closestPkg.name !== undefined && closestPkg.name !== name) {
1084
- // Allow fake module name subpaths: real module owns the prefix.
1085
- // Npm publish wouldn't accept this anyway, so it's not a conflict.
734
+ // Allow fake module-name subpaths: the real module owns the prefix (npm wouldn't publish this).
1086
735
  assert.ok(closestPkg.name.startsWith(`${name}/`), message)
1087
736
  }
1088
737
 
@@ -1112,10 +761,7 @@ export class State {
1112
761
  const dir = dirname(pkg)
1113
762
  if (nmRoot) assert.equal(dir, nmRoot)
1114
763
  if (!this.modules.has(dir)) {
1115
- // node_modules buckets are installed dependencies; tag them with the `npm`
1116
- // ecosystem so consumers can tell deps from the workspace's own packages
1117
- // without re-deriving it from the path. Workspace/top-level buckets (the
1118
- // scope=full `sources`) carry no ecosystem.
764
+ // Tag node_modules buckets `npm`; workspace/top-level buckets carry no ecosystem.
1119
765
  this.modules.set(dir, nmRoot
1120
766
  ? { name, version, ecosystem: 'npm', files: Object.create(null) }
1121
767
  : { name, version, files: Object.create(null) })
@@ -1127,73 +773,29 @@ export class State {
1127
773
  return { absolute, file, dir, module, closestType }
1128
774
  }
1129
775
 
1130
- // `resource: true` (alias: legacy `isBinary: true`) marks the file as a resource
1131
- // rather than code. Its format is then derived from the bytes: 'resource' for valid
1132
- // UTF-8 (stored raw, human-readable in the bundle) or 'resource:base64' for binary
1133
- // (base64-encoded). Code files keep their inferred loader format.
1134
- //
1135
- // `inferFormat: false` records the bytes WITHOUT inferring or recording any loader
1136
- // format (an existing recorded format, if any, is left intact). addFsFile uses it
1137
- // for `.js`/`.ts`, whose module-vs-commonjs is Node's syntax-detection call (not
1138
- // knowable from bytes): the module loader is the authority, so the fs-read capture
1139
- // must not impose the legacy `commonjs` default and collide with a `module` the
1140
- // loader records for the same file when it is both imported and read.
776
+ // `resource: true` (legacy alias `isBinary: true`): format derived from bytes. `inferFormat: false`
777
+ // records bytes without imposing a loader format (defers module-vs-commonjs to the loader).
1141
778
  addFile(url, { source, format, isEntry, isBinary, resource, inferFormat = true, reason = 'run', fsRead = false } = {}) {
1142
779
  const asResource = resource === true || isBinary === true
1143
- // A resource format must not arrive on the code path: 'resource' /
1144
- // 'resource:base64' identifies asset payloads, which State stores in
1145
- // `this.resources` with content-derived encoding (UTF-8 vs base64). A caller
1146
- // who passes the format string without setting resource:true is asking for
1147
- // a code file tagged as a resource -- nonsense, and exactly the kind of
1148
- // accidental misclassification the per-file format design is meant to
1149
- // catch. The reverse (resource:true with a non-resource format) is rejected
1150
- // below when the content-derived format is checked against any explicit one.
1151
780
  if (!asResource && Bundle.isResourceFormat(format)) {
1152
781
  throw new Error(`addFile: format '${format}' requires resource: true`)
1153
782
  }
1154
- // A payload-free stat record is never a legal addFile format: addFile records
1155
- // CONTENT (bytes + hash), and a content record tagged 'stat:*' would desync the
1156
- // "stat records carry no payload" invariant every consumer relies on. The only
1157
- // producer is addFsStat; a caller passing it here (e.g. a forged child shard
1158
- // replayed by mergeShard) is refused at the recording site.
1159
783
  if (isStatFormat(format)) {
1160
784
  throw new Error(`addFile: format '${format}' is a payload-free stat record; use addFsStat`)
1161
785
  }
1162
- // A resource can't be an entry: entries name code loaded by Node (the module
1163
- // graph's roots), and Bundle.parse / assertEntry validate them as code-shaped
1164
- // paths. A resource entry would land in this.entries -> codeBundle.entries
1165
- // (state.js's split-bundle getter), producing a v1 bundle whose entries refer
1166
- // to files absent from its sources -- structurally valid but semantically
1167
- // broken, and the kind of misclassification that's silent at capture time and
1168
- // surfaces opaquely at the loader's NODEJS_FORMATS gate later.
1169
786
  if (asResource && isEntry) {
1170
787
  throw new Error(`addFile: a resource can't be an entry (resource:true + isEntry:true)`)
1171
788
  }
1172
- // Canonicalize + bucket by the owning package (shared with addFsDir).
1173
789
  const { absolute, file, dir, module, closestType } = this.#locateModule(url)
1174
790
 
1175
- // A payload-free stat record (addFsStat: the path was lstat/stat'd before it was
1176
- // read or imported) is superseded by real content: drop it so the format
1177
- // inference/noupsert below records this file's ACTUAL format instead of
1178
- // conflicting with the weak 'stat:*' tag. The lockfile-baseline counterpart (a
1179
- // prior capture attested the path stat-only, this run reads it) lives in the
1180
- // flip-check relaxation below and #mergedFormats' upgrade rule.
791
+ // Real content supersedes a payload-free stat record: drop it so the noupsert below records the
792
+ // actual format instead of conflicting with 'stat:*'.
1181
793
  if (isStatFormat(this.formats.get(file))) this.formats.delete(file)
1182
794
 
1183
- // A code file can NEVER be recorded as a resource. `resources` -- the only gate
1184
- // that admits an asset payload -- rejects code extensions outright (see
1185
- // parseResourcesOption), so a resource:true call for a code extension means a
1186
- // capture path bypassed that gate. That is exactly how an fs.readFileSync of a
1187
- // `.jsx` got tagged 'resource', desyncing the unified lockfile (resource) from
1188
- // the bundle (code) until it surfaced as an opaque format mismatch at load. Fail
1189
- // at the recording site, where the cause is obvious, instead.
1190
795
  if (asResource && CODE_EXTENSIONS.has(extname(file).slice(1).toLowerCase())) {
1191
796
  throw new Error(`addFile: a code file can't be recorded as a resource: ${file}`)
1192
797
  }
1193
798
 
1194
- // Resources don't get a loader format inferred from extension/package type --
1195
- // their format ('resource' / 'resource:base64') is chosen by content below.
1196
- // inferFormat:false (addFsFile for .js/.ts) skips inference entirely.
1197
799
  if (!asResource && inferFormat) {
1198
800
  const extToFormat = {
1199
801
  __proto__: null,
@@ -1212,21 +814,9 @@ export class State {
1212
814
  if (format != null) assert.equal(format, inferredFormat)
1213
815
  else format = inferredFormat
1214
816
  } else if (format == null) {
1215
- // No `type` in the nearest package.json: Node decides .js/.ts by
1216
- // module-syntax detection, so either variant is legitimate and the
1217
- // caller's reported format wins. When no format was provided at all
1218
- // (e.g. bundler plugins, whose afterResolve/onLoad pass none), defer to
1219
- // a format already recorded for this file THIS session before falling
1220
- // back to the legacy commonjs default. The runtime loader records Node's
1221
- // authoritative module/commonjs choice (hooks.js's load hook), so a
1222
- // later no-format capture of the same file must KEEP a known `module`
1223
- // rather than re-default it to commonjs -- which would both mis-attest
1224
- // the bundle and collide at the noupsert below (and, for a bundler
1225
- // sidecar whose formats merge into the parent's unified lockfile, at
1226
- // #mergedFormats). A sidecar's loader records land in the parent's
1227
- // formats, so consult it too. Only an extension-appropriate code format
1228
- // is reused; a stale resource tag from a conflicting prior capture falls
1229
- // through to the default so the conflict still surfaces at noupsert.
817
+ // No `type`: Node decides .js/.ts by syntax detection, so reuse an extension-appropriate
818
+ // format already recorded this session (the loader's call, or the parent's for a sidecar)
819
+ // rather than re-defaulting to commonjs and mis-attesting.
1230
820
  const variants = {
1231
821
  __proto__: null,
1232
822
  '.js': ['commonjs', 'module'],
@@ -1247,14 +837,9 @@ export class State {
1247
837
  }
1248
838
 
1249
839
  const buf = typeof source === 'string' ? Buffer.from(source) : source
1250
- // Verify a CALLER-PROVIDED source against disk (the loader passes the bytes it is about to
1251
- // execute; this catches a loader serving bytes that differ from the file on disk). When we
1252
- // just read `source` from disk ourselves, that comparison is against the same read -- it is
1253
- // tautological -- so skip the redundant second read.
840
+ // Verify a CALLER-PROVIDED source against disk; tautological when we read it ourselves.
1254
841
  if (!sourceFromDisk) assert.deepStrictEqual(readFileSync(absolute), buf)
1255
842
 
1256
- // Resource format is content-driven: raw UTF-8 stays 'resource' (don't base64
1257
- // bytes that are already text); anything else is 'resource:base64'.
1258
843
  if (asResource) {
1259
844
  const derived = isUtf8(buf) ? 'resource' : 'resource:base64'
1260
845
  if (format != null) assert.equal(format, derived, `resource format mismatch for ${file}`)
@@ -1267,8 +852,7 @@ export class State {
1267
852
  if (this.config.childProcess) this.#observed.add(file) // only a child's shardSnapshot reads it; skip when the channel is off
1268
853
  if (this.config.bundle && reason !== null) {
1269
854
  this.#recordReason(reason, file) // provenance for the bundle's `reason` field (null = not a consumer observation, e.g. backfill)
1270
- // Track HOW 'run' saw this file so #bundleReason can drop files run merely fs-READ after a
1271
- // plugin attached that a plugin actually bundles (e.g. webpack+babel reading app source).
855
+ // Track HOW 'run' saw this file so #bundleReason can drop files run merely fs-READ post-plugin.
1272
856
  if (reason === 'run') {
1273
857
  if (!fsRead) this.#runImported.add(file)
1274
858
  else if (this.#pluginAttached) this.#fsReadPostPlugin.add(file)
@@ -1277,32 +861,20 @@ export class State {
1277
861
  const rel = relative(dir, file)
1278
862
  assert.ok(!rel.startsWith('..'))
1279
863
 
1280
- const inAttestedZone = dir.includes('node_modules') || this.config.full
864
+ const inAttestedZone = hasNodeModulesSegment(dir) || this.config.full
1281
865
  if (this.config.frozen && inAttestedZone) {
1282
- assert.ok(Object.hasOwn(module.files, rel))
866
+ assert.ok(Object.hasOwn(module.files, rel), `File not attested by the frozen lockfile: ${file}`)
1283
867
  }
1284
868
 
1285
- // Frozen bundle: the observed bytes are checked against the bundle by the
1286
- // noupsert into this.sources/this.resources below (both pre-seeded from the
1287
- // bundle); here we close the set, rejecting a file the bundle never recorded
1288
- // (mirrors the lockfile membership check above, anchored in the bundle). The
1289
- // scope carve-out matches the lockfile's: node_modules scope doesn't attest
1290
- // workspace files, so they aren't required to be in the bundle.
869
+ // Close the attested set (bytes are checked by the noupsert below); node_modules scope
870
+ // deliberately doesn't attest workspace files.
1291
871
  if (this.config.frozenBundle && inAttestedZone) {
1292
872
  const attested = asResource ? this.#bundleResources : this.#bundleSources
1293
873
  assert.ok(attested?.has(file), `File not attested by the frozen bundle: ${file}`)
1294
874
  }
1295
875
 
1296
- // Frozen runs verify the format observed on disk against the attestation, the
1297
- // way addImport verifies resolutions: the on-disk format is derived from the
1298
- // file extension + nearest package.json `type`, and `type` is usually not
1299
- // itself hash-attested, so flipping it recategorizes a hash-valid file
1300
- // (commonjs<->module, or .js<->module-typescript) with no hash mismatch.
1301
- // Checked against the lockfile and/or the frozen bundle, each anchored in its
1302
- // own recorded formats. Gated to the same attested zone as the hash check
1303
- // above (the node_modules-scope workspace is deliberately unattested, like
1304
- // its bytes); files with no derived format (binary resources) are skipped via
1305
- // `format != null`.
876
+ // `type` is usually not hash-attested, so a flip recategorizes a hash-valid file
877
+ // (commonjs<->module) with no hash mismatch.
1306
878
  if (this.config.frozen && this.#lockFormats !== null && format != null && inAttestedZone) {
1307
879
  this.#assertAttestedFormat(this.#lockFormats, file, format, { what: 'observed', source: 'lockfile' })
1308
880
  }
@@ -1310,20 +882,11 @@ export class State {
1310
882
  this.#assertAttestedFormat(this.#bundleFormats, file, format, { what: 'observed', source: 'frozen bundle' })
1311
883
  }
1312
884
 
1313
- // A WRITING lock capture (lock=add) must catch a format flip on already-attested bytes EARLY.
1314
- // The lockfile baseline lives in #lockFormats -- separate from this.formats -- so addFile's own
1315
- // noupsert below won't see the clash; it would otherwise surface only later at write(), when
1316
- // #mergedFormats unions the baseline with the session formats and noupsert throws a bare
1317
- // `Conflict for <file>` with no cause or remedy. Detect it here and throw a clear, actionable
1318
- // error instead. (A frozen run rejects it via the format check above; lock=replace discards the
1319
- // baseline, so #lockFormats is null; and bundle=add seeds the bundle's formats into this.formats,
1320
- // so a bundle-side flip already conflicts at the noupsert below. Re-attest a genuine change with
1321
- // --lock=replace / --bundle=replace.)
885
+ // Catch a format flip on already-attested bytes here; at write()'s #mergedFormats it would
886
+ // surface only as a bare `Conflict`.
1322
887
  if (this.config.writeLockfile && this.#lockFormats !== null && format != null && inAttestedZone) {
1323
888
  const attested = this.#lockFormats.get(file)
1324
- // A payload-free 'stat:*' baseline is not a flip: the prior capture attested only
1325
- // the path's existence/kind, and this run observing real content UPGRADES the
1326
- // record (#mergedFormats overwrites the stat record with the real format).
889
+ // A 'stat:*' baseline is not a flip: real content this run UPGRADES the record (#mergedFormats).
1327
890
  assert.ok(attested === undefined || attested === format || isStatFormat(attested),
1328
891
  `format flip for ${file}: lockfile attests '${attested}', observed '${format}' (bytes unchanged) -- re-run with --lock=replace to re-attest`)
1329
892
  }
@@ -1333,7 +896,6 @@ export class State {
1333
896
 
1334
897
  if (this.config.bundle) {
1335
898
  if (asResource) {
1336
- // 'resource' stores the raw UTF-8 string; 'resource:base64' stores base64.
1337
899
  const content = format === 'resource:base64' ? buf.toString('base64') : buf.toString('utf8')
1338
900
  noupsert(this.resources, file, content)
1339
901
  } else {
@@ -1342,77 +904,77 @@ export class State {
1342
904
  }
1343
905
 
1344
906
  if (format) noupsert(this.formats, file, format)
907
+
908
+ this.#recordExecutable(file, absolute)
909
+ }
910
+
911
+ // Observe `file` on disk and record or refute its execute bit; disk wins over whatever a lockfile/
912
+ // bundle seeded, but only a real observation refutes (`undefined` and Windows mean "unknowable").
913
+ // A record touches only this State; a REFUTATION must reach the whole family, else
914
+ // #mergedExecutable's union resurrects the bit from a sibling's seeded entry.
915
+ #recordExecutable(file, absolute) {
916
+ const executable = observeExecutable(absolute)
917
+ if (executable === true) {
918
+ this.executable.add(file)
919
+ return
920
+ }
921
+ if (executable !== false || !CAN_OBSERVE_EXECUTE_BITS) return
922
+ const root = this.#parent ?? this
923
+ if (root.executable.size === 0 && root.sidecars().size === 0) {
924
+ this.executable.delete(file)
925
+ return
926
+ }
927
+ this.executable.delete(file)
928
+ root.executable.delete(file)
929
+ for (const sidecar of root.sidecars()) sidecar.executable.delete(file)
1345
930
  }
1346
931
 
1347
- // Record an `fs.readFileSync` capture (`stasis run --fs`, capture side). `source` is
1348
- // the raw bytes (a Buffer). Classification is the SAME classifyExtension the bundler
1349
- // plugins use (against this.config.resources), so the two capture paths can't disagree:
1350
- // - 'code' (any CODE_EXTENSIONS file) → addFile infers the Node loader format from the
1351
- // extension. .js/.ts defer it (inferFormat:false): module-vs-commonjs is Node's
1352
- // syntax-detection call, the loader is the authority, and forcing a default here
1353
- // would collide (noupsert) with the loader's record when a file is both imported and
1354
- // fs-read. .jsx/.tsx are code but have no Node loader format, so none is imposed.
1355
- // addFile asserts the bytes are UTF-8 -- a non-UTF-8 code file is malformed input,
1356
- // refused there rather than silently re-tagged as a resource.
1357
- // - 'resource' (an extension in the resources allowlist) → a 'resource'/'resource:base64'
1358
- // payload, encoding chosen from the bytes.
1359
- // - 'unknown' (neither code nor an allowlisted resource) → THROW. Recording it as a
1360
- // resource would silently widen the attested set (the exact desync this guards); the
1361
- // --fs hook catches the throw, warns, and writes nothing. Declare the extension in
1362
- // `resources` (the --resources flag / EXODUS_STASIS_RESOURCES / a plugin's resources
1363
- // option) or stop reading it.
1364
- // Routing through addFile means a file that is BOTH imported and fs-read lands in one
1365
- // consistent, deduped entry, hashed and bucketed exactly like every other file.
932
+ // Public so #recordExecutable reaches them across the class brand (duplicate stasis-core copies).
933
+ sidecars() {
934
+ return this.#sidecars
935
+ }
936
+
937
+ // Record an `fs.readFileSync` capture (--fs). classifyFormat routes the bytes: a concrete format
938
+ // is code, null defers to the loader, and undefined (or a binary plist, whose bytes can't be the
939
+ // UTF-8 code its format implies) is a resource IFF allowlisted, else THROW -- an undeclared file
940
+ // would widen the attested set.
1366
941
  addFsFile(url, source) {
1367
942
  assert.ok(Buffer.isBuffer(source), 'addFsFile requires a Buffer source')
1368
943
  const path = fileURLToPath(url)
1369
- const kind = classifyExtension(path, this.config.resources)
1370
- if (kind === 'resource') {
1371
- this.addFile(url, { source, resource: true, fsRead: true })
1372
- return
1373
- }
1374
- const ext = extname(path).toLowerCase()
1375
- if (kind === 'unknown') {
944
+ const format = classifyFormat(path, { content: source })
945
+ if (format === undefined || isBinaryPlist(path, source)) {
946
+ if (this.config.resources.has(pathExt(path) || basename(path).toLowerCase())) {
947
+ this.addFile(url, { source, resource: true, fsRead: true })
948
+ return
949
+ }
1376
950
  throw new Error(
1377
951
  `addFsFile: ${path} is neither code nor a declared resource; ` +
1378
952
  `add its extension or filename to the resources allowlist or stop reading it`
1379
953
  )
1380
954
  }
1381
- this.addFile(url, { source, inferFormat: ext !== '.js' && ext !== '.ts', fsRead: true })
955
+ this.addFile(url, { source, format: format ?? undefined, inferFormat: false, fsRead: true })
1382
956
  }
1383
957
 
1384
- // Record an `fs.readdirSync(path)` capture (single-arg form only). The listing is
1385
- // SORTED so the attested content is reproducible regardless of the OS's directory
1386
- // order, JSON-serialized, and stored as a 'directory'-format payload -- a
1387
- // resource-like file whose integrity (sha512 over the JSON text) lands in the
1388
- // lockfile just like any other content. Buckets/dedups via #locateModule like
1389
- // addFile; the directory's own project-relative path is the key (a readdir of a
1390
- // module root keys the listing at the bucket itself -- see moduleFileKey).
958
+ // Record an `fs.readdirSync` capture: the listing is SORTED for reproducibility and stored as a
959
+ // 'directory'-format payload.
1391
960
  addFsDir(url, names) {
1392
961
  assert.ok(Array.isArray(names) && names.every((n) => typeof n === 'string'),
1393
962
  'addFsDir requires an array of string names')
1394
963
  const { file, dir, module } = this.#locateModule(url, { directory: true })
1395
- // As in addFile: a payload-free stat record (the dir was lstat/stat'd before it
1396
- // was readdir'd) is superseded by the real listing -- drop it before the format
1397
- // noupsert below records 'directory'.
964
+ // As in addFile: a real record supersedes a payload-free stat record.
1398
965
  if (isStatFormat(this.formats.get(file))) this.formats.delete(file)
1399
966
  const content = JSON.stringify(names.toSorted())
1400
967
  const format = 'directory'
1401
968
  const integrity = sha512integrity(content)
1402
969
  noupsert(this.hashes, file, integrity)
1403
970
  if (this.config.childProcess) this.#observed.add(file) // only a child's shardSnapshot reads it; skip when the channel is off
1404
- // Directory captures come only from the loader's --fs, and a plugin never records a readdir
1405
- // listing (plugins only addFile), so a directory key is never in #bundleReason's pluginFiles
1406
- // and can never be dropped from 'run' -- no need to track it in #fsReadPostPlugin.
1407
971
  if (this.config.bundle) this.#recordReason('run', file)
1408
972
  const rel = relative(dir, file)
1409
973
  assert.ok(!rel.startsWith('..'))
1410
974
 
1411
- // Frozen attestation, mirroring addFile: in the attested zone the listing must
1412
- // already be recorded (closed set) and its format/integrity must match.
1413
- const inAttestedZone = dir.includes('node_modules') || this.config.full
975
+ const inAttestedZone = hasNodeModulesSegment(dir) || this.config.full
1414
976
  if (this.config.frozen && inAttestedZone) {
1415
- assert.ok(Object.hasOwn(module.files, rel))
977
+ assert.ok(Object.hasOwn(module.files, rel), `Directory not attested by the frozen lockfile: ${file}`)
1416
978
  }
1417
979
  if (this.config.frozenBundle && inAttestedZone) {
1418
980
  assert.ok(this.#bundleResources?.has(file), `Directory not attested by the frozen bundle: ${file}`)
@@ -1428,52 +990,26 @@ export class State {
1428
990
  assert.equal(module.files[rel], integrity)
1429
991
  if (this.config.bundle) noupsert(this.resources, file, content)
1430
992
  noupsert(this.formats, file, format)
993
+ // A listing is never executable (both artifacts' parsers refuse one in `executable`), so drop
994
+ // any bit a prior content record left on this path.
995
+ this.executable.delete(file)
1431
996
  }
1432
997
 
1433
- // Record an `fs.lstatSync(path)`/`fs.statSync(path)` capture (`stasis run --fs`,
1434
- // capture side, single-arg form): a PAYLOAD-FREE stat record -- `formats[file] =
1435
- // 'stat:file' | 'stat:directory'`, no bytes, no hash, no module-files entry --
1436
- // attesting only that the path existed with that KIND. That is exactly what the
1437
- // load-side type-getter shim needs (bundleStats sources isFile()/isDirectory()
1438
- // from getFsStat), so a stat-ONLY path -- never read, readdir'd, or imported --
1439
- // still answers `lstatSync(x).isDirectory()` (and, transitively, the
1440
- // existsSync/accessSync/realpathSync probes, which consult getFsStatFamily) at
1441
- // bundle=load once it's gone from disk.
1442
- //
1443
- // Skipped when the path already has a content record (bytes or a directory
1444
- // listing, whether captured this run or seeded from the lockfile/bundle): that
1445
- // record already answers getFsStat, and a weak stat record must never sit beside
1446
- // it (check-then-read -- lstatSync before readFileSync -- is the common pattern).
1447
- // A path with a REAL format but no content record -- addImport attests the format
1448
- // of a resolve-hook target whose load hook never fires (a preload-cached module) --
1449
- // is likewise left alone: upsertFormat drops the stat record, the real format
1450
- // wins (a plain noupsert here aborted real captures: enhanced-resolve stat'ing
1451
- // stasis-core's own src/util.js under --fs + a bundler plugin). The REVERSE order
1452
- // (stat first, real format later) is handled by addFile/addFsDir dropping the
1453
- // stale stat record in place, addImport's upsertFormat, and #mergedFormats'
1454
- // upgrade rule. A kind flip WITHIN the surviving stat records (stat'd as a file,
1455
- // later stat'd as a directory) still conflicts and taints the capture, exactly
1456
- // like a mid-run byte conflict.
998
+ // Record a stat capture as a PAYLOAD-FREE record (`formats[file] = 'stat:file'|'stat:directory'`,
999
+ // no bytes/hash/module-files entry), so getFsStat answers isFile()/isDirectory() at load. Skipped
1000
+ // when a content record already exists; upsertFormat lets a real format win, a kind flip is fatal.
1457
1001
  addFsStat(url, kind) {
1458
1002
  assert.ok(kind === 'file' || kind === 'directory', `addFsStat: unsupported kind '${kind}'`)
1459
1003
  const file = this.#canonicalFile(url)
1460
1004
  if (this.hashes.has(file) || this.sources.has(file) || this.resources.has(file)) return
1461
1005
  upsertFormat(this.formats, file, `stat:${kind}`)
1462
- // Forwarded to the root via shardSnapshot's #observed-filtered formats, like
1463
- // every other capture; only a child's shardSnapshot reads it, skip otherwise --
1464
- // and only when a stat record actually landed (upsertFormat yields to an
1465
- // existing real format, and forwarding THAT would ship an entry mergeShard's
1466
- // stat replay ignores).
1006
+ // Only forward when a stat record actually landed -- upsertFormat may have yielded to a real
1007
+ // format, and forwarding THAT would ship an entry mergeShard's stat replay ignores.
1467
1008
  if (this.config.childProcess && isStatFormat(this.formats.get(file))) this.#observed.add(file)
1468
1009
  }
1469
1010
 
1470
- // Serve an `fs.readFileSync` from the bundle (`stasis run --fs`, bundle=load).
1471
- // Returns the raw bytes as a Buffer, or undefined when the path was not captured
1472
- // (the hook then falls back to a real disk read) or names a captured directory (a
1473
- // readFileSync of a directory must fail, not return its listing). Decoding and the
1474
- // lockfile hash check reuse getFile. Note a captured `.js`/`.ts` may have no
1475
- // recorded format (see addFsFile); it's still served from `this.sources` by
1476
- // presence -- the format only governs the module loader, not an fs read.
1011
+ // Serve an `fs.readFileSync` from the bundle: raw bytes, or undefined when uncaptured (the hook
1012
+ // falls back to disk) or a captured directory. Served by presence, not format.
1477
1013
  getFsFile(url) {
1478
1014
  let file
1479
1015
  try { file = this.#canonicalFile(url) } catch { return undefined }
@@ -1483,9 +1019,6 @@ export class State {
1483
1019
  return Buffer.isBuffer(source) ? source : Buffer.from(source, 'utf8')
1484
1020
  }
1485
1021
 
1486
- // Serve an `fs.readdirSync(path)` from the bundle: the sorted listing captured at
1487
- // build time, or undefined when the path was not captured as a directory (the hook
1488
- // falls back to a real disk read). Reuses getFile for the hash check.
1489
1022
  getFsDir(url) {
1490
1023
  let file
1491
1024
  try { file = this.#canonicalFile(url) } catch { return undefined }
@@ -1496,9 +1029,7 @@ export class State {
1496
1029
  return names
1497
1030
  }
1498
1031
 
1499
- // Every ancestor directory implied by the bundle's recorded file/resource/directory
1500
- // keys. A recorded `node_modules/dep/index.js` implies `node_modules/dep` and
1501
- // `node_modules` (and the root, '.'). Built once; load-mode immutable (see field).
1032
+ // Every ancestor directory implied by recorded keys; built once.
1502
1033
  #impliedDirs() {
1503
1034
  if (this.#impliedDirIndex) return this.#impliedDirIndex
1504
1035
  const dirs = new Set(['.'])
@@ -1512,29 +1043,15 @@ export class State {
1512
1043
  }
1513
1044
  for (const key of this.sources.keys()) add(key)
1514
1045
  for (const key of this.resources.keys()) add(key)
1515
- // Payload-free stat records prove existence too: a 'stat:file' at
1516
- // node_modules/dep/index.js implies node_modules and node_modules/dep are
1517
- // directories exactly like a content record would, and a 'stat:directory'
1518
- // likewise implies its own ancestors (the recorded dir itself is answered
1519
- // directly by getFsStat's format branch, not via this index).
1046
+ // Stat records prove existence too, so they imply their ancestor dirs.
1520
1047
  for (const [key, format] of this.formats) if (isStatFormat(format)) add(key)
1521
1048
  this.#impliedDirIndex = dirs
1522
1049
  return dirs
1523
1050
  }
1524
1051
 
1525
- // Classify a captured path for the `fs.lstatSync(x)/statSync(x)` .isFile()/.isDirectory()
1526
- // shim (`stasis run --fs`, bundle=load): 'directory' for a readdir capture, 'file' for
1527
- // a readFileSync capture, the recorded kind for a payload-free stat record
1528
- // ('stat:file'/'stat:directory', an lstat/stat capture of a path never read),
1529
- // 'directory' for an ancestor directory implied by a recorded file (e.g.
1530
- // `node_modules` when the bundle carries `node_modules/dep/index.js`), or
1531
- // undefined when the path wasn't captured (the shim then falls back to a real
1532
- // on-disk lstatSync). A directory lives in this.resources too, so the 'directory'
1533
- // format is checked first; content records are checked before stat records
1534
- // (defensive -- addFsStat never records beside content) and implied dirs come
1535
- // last so an explicit record always wins. NB: 'file' here means "recorded as a
1536
- // file", NOT "the bundle can serve its bytes" -- callers needing the latter
1537
- // (resolution shims, byte-serving skips) must use hasFsFileContent.
1052
+ // Classify a captured path for the stat shim: 'directory', 'file', or undefined (uncaptured -> the
1053
+ // shim falls back to disk). Order matters: 'directory' first, content before stat records, implied
1054
+ // dirs last. NB: 'file' means "recorded", NOT "bytes serveable" (use hasFsFileContent).
1538
1055
  getFsStat(url) {
1539
1056
  let file
1540
1057
  try { file = this.#canonicalFile(url) } catch { return undefined }
@@ -1547,11 +1064,7 @@ export class State {
1547
1064
  return undefined
1548
1065
  }
1549
1066
 
1550
- // True when the bundle carries actual BYTE content for `url` as a file -- code or
1551
- // a resource payload -- as opposed to a directory listing, a payload-free 'stat:*'
1552
- // existence record, or nothing. The CJS-resolution shim (hooks.js) and the
1553
- // sidecar capture-skip route "can the bundle serve this file's bytes?" through
1554
- // this instead of getFsStat, which also answers 'file' for stat-only records.
1067
+ // True when the bundle carries actual BYTE content for `url` (not a directory/stat-only record).
1555
1068
  hasFsFileContent(url) {
1556
1069
  let file
1557
1070
  try { file = this.#canonicalFile(url) } catch { return false }
@@ -1559,40 +1072,17 @@ export class State {
1559
1072
  return this.sources.has(file) || this.resources.has(file)
1560
1073
  }
1561
1074
 
1562
- // --fs <-> bundler-plugin coordination. A StasisWebpack/StasisEsbuild/StasisMetro SIDECAR
1563
- // (its own bundleFile) captures the bundler's MODULE GRAPH into its OWN bundle. But the
1564
- // bundler also reads every module's source through node:fs (webpack's inputFileSystem is
1565
- // graceful-fs -> node:fs), which the --fs hook would otherwise RE-record into THIS
1566
- // (preload/"main") bundle -- copying the whole graph into main and defeating the
1567
- // bundleFile split. So --fs consults the family in two symmetric ways:
1568
- // - CAPTURE (write mode): attestedBySidecar SKIPS recording a read a write-mode sidecar
1569
- // already attests (the graph). Only reads no sidecar owns -- a babel plugin's manual
1570
- // non-JS file reads, etc. -- are recorded into main.
1571
- // - LOAD (load mode): getFs*Family SERVES a graph file from a load-mode sidecar's bundle
1572
- // when main doesn't carry it (a program raw-reading a graph file via --fs at load).
1573
- // The two paths consult DIFFERENT registries because a sidecar is a contributor XOR a
1574
- // consumer (its bundle mode is the parent's): write-mode sidecars (#sidecars) feed the
1575
- // lockfile; load-mode sidecars (#readSidecars) must not. readdir capture has no skip --
1576
- // bundler plugins record files (addFile), never directory LISTINGS (addFsDir), so a
1577
- // sidecar never owns a readdir result; a readdir is a genuine program read for main.
1578
- //
1579
- // attestedBySidecar consults #sidecars (write-mode contributors) and excludes THIS State
1580
- // on purpose: a file only this State has stays subject to --fs's own dedup / byte-conflict
1581
- // detection (addFsFile's noupsert); the skip applies solely to a file a *sidecar* carries.
1075
+ // --fs <-> bundler-plugin coordination: CAPTURE skips a read a write-mode sidecar already attests,
1076
+ // else --fs re-records the bundler's whole module graph into the main bundle and defeats the split.
1582
1077
  attestedBySidecar(url) {
1583
- // hasFsFileContent (not getFsStat): the skip targets a file whose BYTES a sidecar carries
1584
- // (the graph the bundler reads through node:fs). getFsStat would also match a 'directory'
1585
- // implied ancestor of a carried file, or a payload-free 'stat:*' record -- neither of which
1586
- // carries bytes, so matching them would over-skip and leave a genuine read unattested.
1078
+ // hasFsFileContent, not getFsStat: over-skipping on an implied dir or stat-only record would
1079
+ // leave a real read unattested.
1587
1080
  for (const s of this.#sidecars) if (s.hasFsFileContent(url)) return true
1588
1081
  return false
1589
1082
  }
1590
1083
 
1591
- // getFs* variants that also consult load-mode sidecars (#readSidecars; this State first),
1592
- // so a file/dir a sidecar carries in its bundle is served by --fs reads at load even when
1593
- // main doesn't carry it. Only #readSidecars (not #sidecars): write-mode sidecars exist
1594
- // only during capture, where --fs records rather than serves, so they're never consulted
1595
- // here -- and they're kept out of the lockfile-contributing path regardless.
1084
+ // getFs* variants that also consult load-mode sidecars (this State first). Only #readSidecars --
1085
+ // write-mode sidecars only capture.
1596
1086
  getFsFileFamily(url) {
1597
1087
  const own = this.getFsFile(url)
1598
1088
  if (own !== undefined) return own
@@ -1610,27 +1100,17 @@ export class State {
1610
1100
  getFsDirFamily(url) {
1611
1101
  const own = this.getFsDir(url)
1612
1102
  if (own !== undefined) return own
1613
- // The sidecar loop is inert in practice: bundler plugins record files (addFile), never
1614
- // directory LISTINGS (addFsDir), so a sidecar's bundle has no `directory` entry and
1615
- // s.getFsDir always returns undefined. Kept for symmetry with the file/stat families.
1616
1103
  for (const s of this.#readSidecars) { const v = s.getFsDir(url); if (v !== undefined) return v }
1617
1104
  return undefined
1618
1105
  }
1619
1106
 
1620
1107
  getFile(url) {
1621
- // #canonicalFile -> relative() throws a bare assertion if the URL is outside
1622
- // state.root (an absolute path that escapes the project). Wrap it so callers
1623
- // get a contextual message instead of a stack pointing at relative()'s
1624
- // assert.ok(!file.startsWith('..')).
1108
+ // Wrap #canonicalFile so a URL escaping state.root gives a contextual error, not a bare assert.
1625
1109
  let file
1626
1110
  try { file = this.#canonicalFile(url) }
1627
1111
  catch (cause) { throw new Error(`stasis: file is outside the project root: ${url}`, { cause }) }
1628
1112
  const format = this.formats.get(file) // might be undefined e.g. for some bundlers
1629
- // Resources live in this.resources, code in this.sources. Decode per the format:
1630
- // 'resource:base64' is base64, 'resource' is raw UTF-8, code is raw text.
1631
- // A missing entry throws with the URL in context so load-mode callers (the
1632
- // bundler plugins, the run loader) don't have to pre-check existence -- the
1633
- // single getFile call is the fail-closed gate.
1113
+ // A missing entry throws: this single getFile call is the fail-closed gate.
1634
1114
  let source
1635
1115
  if (Bundle.isResourceFormat(format)) {
1636
1116
  source = this.resources.get(file)
@@ -1639,10 +1119,7 @@ export class State {
1639
1119
  } else {
1640
1120
  source = this.sources.get(file)
1641
1121
  if (source === undefined) {
1642
- // Name the stat-record case: the bundle DOES know this path, just not its bytes
1643
- // (an fs.lstatSync/statSync capture attests existence/kind only), so "not
1644
- // attested" would misdiagnose it. Loading it requires a capture that reads or
1645
- // imports it.
1122
+ // Stat-record case: the bundle knows the path but not its bytes -- "not attested" would misdiagnose it.
1646
1123
  if (isStatFormat(format)) {
1647
1124
  throw new Error(
1648
1125
  `stasis: only a payload-free stat record ('${format}') is attested for ${url} -- ` +
@@ -1652,22 +1129,13 @@ export class State {
1652
1129
  throw new Error(`stasis: file not attested in bundle: ${url}`)
1653
1130
  }
1654
1131
  }
1655
- // Without a lockfile the bundle is self-attesting: hashes would be derived
1656
- // from the same source bytes we'd then verify, which is a tautology.
1132
+ // Without a lockfile the bundle is self-attesting -- verifying its hash against its own bytes is a tautology.
1657
1133
  if (this.config.useLockfile) assert.equal(this.hashes.get(file), sha512integrity(source))
1658
1134
  return { source, format }
1659
1135
  }
1660
1136
 
1661
- // The recorded LOADER format for a project-relative file, or undefined. Masks
1662
- // payload-free stat records: 'stat:*' attests existence/kind for the --fs stat and
1663
- // probe shims (getFsStat reads this.formats directly), NOT how bytes parse -- so
1664
- // loader-format consumers must see "no recorded format". Without the mask, a
1665
- // require.resolve()d target that was also stat'd (a resolve-only edge: attested
1666
- // path, no bytes, exactly the supported require.resolve case) came back as format
1667
- // 'stat:file' and the resolve hook's executable-format gate refused a perfectly
1668
- // valid resolution -- and Node itself would choke on the format regardless.
1669
- // getFile deliberately does NOT mask: it needs the stat tag to explain a byte-less
1670
- // load, and bytes smuggled under a 'stat:*' tag must still hit the loader's gate.
1137
+ // The recorded LOADER format, or undefined. Masks 'stat:*' (existence, not how bytes parse) so a
1138
+ // stat'd require.resolve target isn't refused by the resolve hook's format gate; getFile does NOT mask.
1671
1139
  #loaderFormat(file) {
1672
1140
  const format = this.formats.get(file)
1673
1141
  return isStatFormat(format) ? undefined : format
@@ -1687,41 +1155,22 @@ export class State {
1687
1155
  return `${cond} (with: ${JSON.stringify(sorted)})`
1688
1156
  }
1689
1157
 
1690
- // A require()/import() given an already-resolved ABSOLUTE path arrives at the
1691
- // resolve hook with that absolute path AS the specifier -- CJS
1692
- // `require('/repo/node_modules/pkg/index.js')` is the common case (webpack's
1693
- // loader-runner does `require(loader.path)`). Recorded verbatim, that
1694
- // machine-specific absolute path becomes a resolution KEY in the lockfile and
1695
- // bundle: non-portable, and unmatchable on any other machine. Once the target
1696
- // is confirmed inside the project root, renormalize it to a path relative to
1697
- // the IMPORTING FILE's directory -- the same shape a hand-written
1698
- // `require('./x')` / `require('../../pkg/x')` has. The root check is only the
1699
- // gate; the resulting key may itself contain '../' (going up from the importing
1700
- // file), which is expected and fine as long as the target stayed inside root.
1701
- //
1702
- // Keying against the parent makes the key portable AND collision-free: it is
1703
- // always '.'-prefixed, so it can never clash with a bare ('pkg') or
1704
- // root-relative key, and an absolute path naming the same file as a relative
1705
- // import unifies onto the identical key (same value -> noupsert agrees, no
1706
- // throw). Bare/relative specifiers and file: URLs (handled separately by the
1707
- // loader) pass through untouched; an absolute path that escapes the root has no
1708
- // in-root relative form, so it's left as-is. Applied identically in addImport
1709
- // (record) and getImport (lookup) so the key written and the key queried agree.
1158
+ // An already-resolved ABSOLUTE require()/import() target as the specifier would be a
1159
+ // machine-specific lockfile key, so renormalize in-root ones against the IMPORTING FILE's dir.
1160
+ // Must be applied identically in addImport and getImport so keys written and queried agree.
1710
1161
  #canonicalSpecifier(parentURL, specifier) {
1711
- if (typeof specifier !== 'string' || !isAbsolute(specifier)) return specifier
1712
- const fromRoot = relative(this.root, specifier)
1162
+ if (typeof specifier !== 'string') return specifier
1163
+ const path = specifier.startsWith('file:') ? fileURLToPath(specifier) : specifier
1164
+ if (!isAbsolute(path)) return specifier
1165
+ const fromRoot = relative(this.root, path)
1713
1166
  if (fromRoot === '' || fromRoot.startsWith('..')) return specifier // outside the project root
1714
- const rel = relative(dirname(fileURLToPath(parentURL)), specifier)
1167
+ const rel = relative(dirname(fileURLToPath(parentURL)), path)
1715
1168
  return rel.startsWith('.') ? rel : `./${rel}`
1716
1169
  }
1717
1170
 
1718
1171
  addImport(parentURL, specifier, url, { conditions = '*', format, importAttributes } = {}) {
1719
1172
  if (conditions !== '*') assert.ok(Array.isArray(conditions))
1720
- // Capture Node's require-condition set the first time we see a require()-context
1721
- // edge: it carries 'require' and never 'import' (the import set carries 'import'
1722
- // instead). Requiring the absence of 'import' also rejects an import edge a user
1723
- // forced 'require' onto via --conditions. #backfillObservedResolutions reuses this
1724
- // set to key native require.resolve() edges accurately instead of '*' (see field doc).
1173
+ // Capture Node's require-condition set on the first require()-context edge (see #requireConditions).
1725
1174
  if (this.#requireConditions === null && Array.isArray(conditions) &&
1726
1175
  conditions.includes('require') && !conditions.includes('import')) {
1727
1176
  this.#requireConditions = conditions
@@ -1732,22 +1181,12 @@ export class State {
1732
1181
  specifier = this.#canonicalSpecifier(parentURL, specifier)
1733
1182
  const key = this.#conditionsKey(conditions, importAttributes)
1734
1183
 
1735
- // Frozen runs verify resolutions observed from disk against the lockfile,
1736
- // mirroring the bundle-side check: byte hashes can't see a resolution
1737
- // redirected to a *different* attested file (e.g. via an unattested
1738
- // package.json `main` or a symlink). An edge the lockfile attests must
1739
- // match in every scope. Unknown edges are fatal in full scope (the
1740
- // attested file set is closed, so the traversed edge set should be too),
1741
- // but tolerated for workspace parents in node_modules scope -- the
1742
- // workspace is deliberately unattested there, so changed workspace code
1743
- // may legitimately introduce new edges, including into pinned packages.
1744
- const tolerateUnknown = !this.config.full && !parent.includes('node_modules')
1184
+ // Frozen runs verify disk resolutions against the lockfile: hashes can't see a redirect to
1185
+ // another attested file. Unknown edges are tolerated only for workspace parents in nm scope.
1186
+ const tolerateUnknown = !this.config.full && !hasNodeModulesSegment(parent)
1745
1187
  if (this.config.frozen && this.#lockImports !== null) {
1746
1188
  this.#assertAttestedResolution(this.#lockImports, key, parent, specifier, file, { what: 'observed', source: 'lockfile', tolerateUnknown })
1747
1189
  }
1748
- // A frozen bundle attests resolutions the same way (every v1 bundle carries an
1749
- // `imports` map, so #bundleImports is never null once one is loaded). Same
1750
- // redirect protection and node_modules-scope carve-out, anchored in the bundle.
1751
1190
  if (this.config.frozenBundle && this.#bundleImports !== null) {
1752
1191
  this.#assertAttestedResolution(this.#bundleImports, key, parent, specifier, file, { what: 'observed', source: 'frozen bundle', tolerateUnknown })
1753
1192
  }
@@ -1757,10 +1196,7 @@ export class State {
1757
1196
  if (!imports.has(parent)) imports.set(parent, new Map())
1758
1197
  const specifiers = imports.get(parent)
1759
1198
  noupsert(specifiers, specifier, file)
1760
- // upsertFormat (not a bare noupsert): the resolve hook may attest the format of
1761
- // a target the program already lstat/stat'd under --fs (a payload-free
1762
- // 'stat:file' record) -- the real format replaces the weak stat record instead
1763
- // of aborting the capture as a conflict.
1199
+ // upsertFormat, not noupsert: a real format must replace a weak 'stat:*' record from an --fs stat.
1764
1200
  if (format) upsertFormat(this.formats, file, format)
1765
1201
  }
1766
1202
 
@@ -1770,24 +1206,14 @@ export class State {
1770
1206
  const parent = this.#canonicalFile(parentURL)
1771
1207
  specifier = this.#canonicalSpecifier(parentURL, specifier)
1772
1208
  const key = this.#conditionsKey(conditions, importAttributes)
1773
- // Statically-built bundles (e.g. `stasis bundle src/entry.js`) resolve edges
1774
- // offline and store them under the wildcard '*' key, since they can't
1775
- // predict the exact condition set Node will pass at load time. The runtime
1776
- // loader always records the precise conditions Node reported, so the
1777
- // specific lookup wins when a runtime bundle is in play and only static
1778
- // bundles take the wildcard fallback. Mismatches between the resolved file
1779
- // for a given (parent, spec) under the two condition sets remain caller
1780
- // territory -- the static bundle is authoritative for whichever conditions
1781
- // the static resolver used.
1209
+ // Static bundles store edges under '*' (Node's condition set is unpredictable); the runtime
1210
+ // loader records precise conditions, so the specific lookup wins.
1782
1211
  let file = this.imports.get(key)?.get(parent)?.get(specifier)
1783
1212
  if (file === undefined && key !== '*') {
1784
1213
  file = this.imports.get('*')?.get(parent)?.get(specifier)
1785
1214
  }
1786
1215
  if (file === undefined) {
1787
- // The (key, parent, spec) and '*' lookups missed, but the edge may be recorded
1788
- // under a DIFFERENT conditions bucket -- e.g. the esbuild plugin asks with
1789
- // conditions='*' while a Node-loader-captured bundle keyed the edge under
1790
- // 'require, node, ...'. resolveBundled scans every bucket for the recorded edge.
1216
+ // The edge may be recorded under a DIFFERENT conditions bucket -- resolveBundled scans every bucket.
1791
1217
  if (this.config.loadBundle) {
1792
1218
  const abs = this.resolveBundled(parentURL, specifier)
1793
1219
  if (abs !== undefined) {
@@ -1795,51 +1221,27 @@ export class State {
1795
1221
  return { url: pathToFileURL(abs).toString(), format: this.#loaderFormat(f) }
1796
1222
  }
1797
1223
  }
1798
- // Throw with Node's ERR_MODULE_NOT_FOUND shape rather than asserting:
1799
- // plain Node's resolver throws this when a bare or relative specifier
1800
- // can't be found, and ESM dynamic-import callers commonly do
1801
- // `try { await import(x) } catch (e) { if (e.code !== 'ERR_MODULE_NOT_FOUND') throw e }`.
1802
- // A bare assertion produced an ERR_ASSERTION code that re-threw out of
1803
- // those guards.
1224
+ // Node's ERR_MODULE_NOT_FOUND shape, not a bare assert: dynamic-import callers guard on that
1225
+ // code, which ERR_ASSERTION escapes.
1804
1226
  const err = new Error(`Cannot find module '${specifier}' imported from ${parent}`)
1805
1227
  err.code = 'ERR_MODULE_NOT_FOUND'
1806
1228
  throw err
1807
1229
  }
1808
- // A `stasis bundle --metro` artifact records a { platform: file } Map for an
1809
- // edge that resolves differently per platform. Plain `stasis run --bundle=load`
1810
- // has no platform context to pick one, so it can't serve such an edge -- fail
1811
- // closed with a clear error rather than feeding a Map where a path is expected.
1230
+ // A --metro per-platform edge is a { platform: file } Map; plain bundle=load has no platform
1231
+ // context to pick one, so fail closed rather than feed a Map where a path is expected.
1812
1232
  if (typeof file !== 'string') {
1813
1233
  const err = new Error(`Resolution of '${specifier}' from ${parent} is platform-specific (a --metro multi-platform bundle); it can't be loaded by plain node, build a single-platform bundle to load`)
1814
1234
  err.code = 'ERR_STASIS_PLATFORM_SPECIFIC'
1815
1235
  throw err
1816
1236
  }
1817
1237
  const url = pathToFileURL(resolve(this.root, file)).toString()
1818
- // #loaderFormat: might be undefined (e.g. some bundlers record no format), and a
1819
- // payload-free stat record is masked -- a resolve-only edge's target (recorded by
1820
- // require.resolve, never loaded) may carry one, and it is not a loader format.
1821
1238
  const format = this.#loaderFormat(file)
1822
1239
  return { url, format }
1823
1240
  }
1824
1241
 
1825
- // Resolve a CommonJS require() target to a bundled file, returning the absolute
1826
- // path the loader should use (load() then serves its bytes from the bundle), or
1827
- // undefined to defer to Node's native resolution.
1828
- //
1829
- // Node's CommonJS loader resolves require() through Module._resolveFilename, which
1830
- // registerHooks does NOT intercept. When the ESM->CJS translator runs a CJS module we
1831
- // served from the bundle (`import chalk from 'chalk'`, chalk being CJS), that module's
1832
- // nested require()s take this native path and Node resolves them against disk -- so a
1833
- // bundle is not self-contained for a CJS dependency graph once node_modules is
1834
- // pruned/absent. The CJS-loader shim in hooks.js consults this to serve them from the
1835
- // bundle instead.
1836
- //
1837
- // Returns the recorded edge for this (parent, specifier) under ANY conditions bucket --
1838
- // a native require gives no conditions to key on, and divergent targets across buckets
1839
- // are ambiguous, so we defer. EVERY require() edge is recorded at capture, including the
1840
- // sibling requires Node's module cache used to hide from the resolve hook (the
1841
- // Module._load shim in hooks.js observes them) -- so a miss here means the bundle simply
1842
- // doesn't carry the target (an external), and we defer to Node rather than guess.
1242
+ // Resolve a CJS require() target to a bundled absolute path, or undefined to defer to Node (the
1243
+ // hooks.js CJS shim needs this: registerHooks can't intercept Module._resolveFilename). Matches
1244
+ // under ANY conditions bucket, since native require gives none; divergent buckets -> defer.
1843
1245
  resolveBundled(parentURL, specifier) {
1844
1246
  let parent
1845
1247
  try { parent = this.#canonicalFile(parentURL) } catch { return undefined }
@@ -1849,14 +1251,15 @@ export class State {
1849
1251
  const file = byParent.get(parent)?.get(spec)
1850
1252
  if (file !== undefined) matches.add(file)
1851
1253
  }
1852
- return matches.size === 1 ? resolve(this.root, [...matches][0]) : undefined
1254
+ if (matches.size !== 1) return undefined
1255
+ const [only] = matches
1256
+ // Per-platform { platform: file } Map (--metro) has no single path: defer to native, not resolve()'s TypeError.
1257
+ if (typeof only !== 'string') return undefined
1258
+ return resolve(this.root, only)
1853
1259
  }
1854
1260
 
1855
- // Union of the lockfile-attested resolutions and the live map (observed at
1856
- // runtime and/or carried over from a loaded bundle), so a partial lock=add
1857
- // run extends the recorded resolutions without dropping edges it didn't
1858
- // reach. Conflicting targets for the same edge are fatal (add semantics,
1859
- // same as hashes).
1261
+ // Union of lockfile-attested and live resolutions, so a partial lock=add run extends without
1262
+ // dropping edges. Conflicting targets are fatal (add semantics).
1860
1263
  #mergedImports() {
1861
1264
  const merged = new Map()
1862
1265
  const mergeIn = (imports) => {
@@ -1874,23 +1277,13 @@ export class State {
1874
1277
  }
1875
1278
  if (this.#lockImports) mergeIn(this.#lockImports)
1876
1279
  mergeIn(this.imports)
1877
- // Union sidecars' imports too: a bundler-plugin's sidecar records the
1878
- // webpack-graph edges into its own this.imports, and the lockfile must
1879
- // attest those edges so a frozen run can verify them.
1280
+ // Write-mode sidecars too, so the lockfile attests their edges for frozen verify.
1880
1281
  for (const sidecar of this.#sidecars) mergeIn(sidecar.imports)
1881
1282
  return merged
1882
1283
  }
1883
1284
 
1884
- // Union of lockfile-attested and observed/bundle-served formats, same
1885
- // append-only stance as #mergedImports: conflicting formats for one file are
1886
- // fatal (noupsert). Sidecars' formats are unioned in for the same reason.
1887
- // The one exception is a payload-free stat record ('stat:*', addFsStat): it is
1888
- // WEAK by design -- real content observed for the same file (a lock=add re-run
1889
- // READING a path a prior capture only stat'd, or a sidecar bundling a file this
1890
- // run also stat'd) UPGRADES the record instead of conflicting, and a stat record
1891
- // never displaces a real format (upsertFormat, the same rule the live-map
1892
- // writers apply). Two REAL formats -- and two divergent stat kinds (stat:file
1893
- // vs stat:directory) -- stay fatal.
1285
+ // Union of lockfile-attested and observed formats (+ sidecars'), append-only like #mergedImports,
1286
+ // except that a weak 'stat:*' is UPGRADED by real content; two real formats stay fatal.
1894
1287
  #mergedFormats() {
1895
1288
  const merged = new Map()
1896
1289
  if (this.#lockFormats) for (const [file, format] of this.#lockFormats) merged.set(file, format)
@@ -1898,23 +1291,42 @@ export class State {
1898
1291
  for (const sidecar of this.#sidecars) {
1899
1292
  for (const [file, format] of sidecar.formats) upsertFormat(merged, file, format)
1900
1293
  }
1294
+ // A payload-free 'stat:*' must never survive on a file that now carries a content hash: a stat
1295
+ // entry re-seeded from #lockFormats is beyond addFile's delete, and an ambiguous .js/.ts yields
1296
+ // no real format to override it above.
1297
+ for (const [file, format] of merged) {
1298
+ if (isStatFormat(format) && this.hashes.has(file)) merged.delete(file)
1299
+ }
1901
1300
  return merged
1902
1301
  }
1903
1302
 
1303
+ // The executable list the LOCKFILE attests (this State's + write-mode sidecars'), narrowed by
1304
+ // scope to the keys it will SERIALIZE: a non-full-scope lockfile drops its workspace buckets, and
1305
+ // an entry for a dropped bucket writes a lockfile Lockfile.parse then refuses.
1306
+ #mergedExecutable(formats) {
1307
+ const all = new Set(this.executable)
1308
+ for (const sidecar of this.#sidecars) for (const file of sidecar.executable) all.add(file)
1309
+ return narrowExecutable(all, { modules: this.modules, formats, scope: this.config.scope })
1310
+ }
1311
+
1312
+ // The executable list ONE bundle declares, narrowed to that half's own buckets and formats.
1313
+ #bundleExecutable(modules, formats) {
1314
+ return narrowExecutable(this.executable, { modules, formats, scope: this.config.scope })
1315
+ }
1316
+
1904
1317
  get lockData() {
1318
+ const formats = this.#mergedFormats()
1905
1319
  return new Lockfile({
1906
1320
  config: this.config.values,
1907
1321
  entries: this.entries,
1908
1322
  modules: this.modules,
1909
1323
  imports: this.#mergedImports(),
1910
- formats: this.#mergedFormats(),
1324
+ formats,
1325
+ executable: this.#mergedExecutable(formats),
1911
1326
  }).serialize()
1912
1327
  }
1913
1328
 
1914
- // Pair each module's recorded file list with the corresponding content from
1915
- // perFile (state.sources for code, state.resources for resources), dropping
1916
- // modules with no content. Bundle.serialize* then groups them into sources/
1917
- // modules buckets and writes the lockfile-shaped output.
1329
+ // Pair each module's recorded file list with content from perFile, dropping modules with none.
1918
1330
  #bundleModules(perFile) {
1919
1331
  const modules = new Map()
1920
1332
  for (const [dir, info] of this.modules) {
@@ -1933,31 +1345,32 @@ export class State {
1933
1345
  return modules
1934
1346
  }
1935
1347
 
1936
- // A bundler plugin instance has attached to this State (called from resolvePluginState at the
1937
- // plugin's construction). Files this run merely fs-READS *after* this point that a plugin also
1938
- // bundles are the plugin's modules, not run's -- see #bundleReason. Idempotent. Public so it
1939
- // works across stasis-core copies (the plugin may be a foreign-copy instance), like
1940
- // registerSidecar / sidecarInheritance.
1348
+ // Files fs-READ after this point that a plugin also bundles are the plugin's, not run's (see
1349
+ // #bundleReason). Public, cross-copy.
1941
1350
  markPluginAttached() {
1942
1351
  this.#pluginAttached = true
1943
1352
  }
1944
1353
 
1945
- // Record which consumer (`reason`) observed `file`, for the bundle's informational `reason` map.
1946
1354
  #recordReason(reason, file) {
1947
1355
  let set = this.#reasonFiles.get(reason)
1948
1356
  if (set === undefined) this.#reasonFiles.set(reason, set = new Set())
1949
1357
  set.add(file)
1950
1358
  }
1951
1359
 
1952
- // Build the bundle's informational `reason` map, restricted to `bundledFiles` (this bundle's own
1953
- // file set): { consumer: [files] } for each consumer that recorded at least one file in it.
1954
- // Returned ONLY when more than one consumer contributed -- a single-consumer bundle (plain `run`,
1955
- // or a standalone plugin) omits it. Never attested; purely for humans / tooling.
1360
+ // Seed `reason` from an absorbed on-disk bundle so a bundle=add re-run preserves other consumers'
1361
+ // attribution. Called from every absorb site, including the sidecar's inlined one.
1362
+ #seedReasonFromBundle(bundle) {
1363
+ if (!this.config.writeBundle || bundle.reason === undefined) return
1364
+ for (const [consumer, files] of Object.entries(bundle.reason)) {
1365
+ for (const file of files) this.#recordReason(consumer, file)
1366
+ }
1367
+ }
1368
+
1369
+ // The bundle's informational `reason` map, restricted to `bundledFiles`; only when >1 consumer
1370
+ // contributed. Never attested.
1956
1371
  #bundleReason(bundledFiles) {
1957
1372
  const inBundle = bundledFiles instanceof Set ? bundledFiles : new Set(bundledFiles)
1958
- // Files some PLUGIN bundles (any consumer other than 'run'). A file run merely fs-READ (never
1959
- // imported) after a plugin attached, that a plugin also bundles, is the plugin's module -- e.g.
1960
- // webpack+babel reading app source through --fs to transform it -- so 'run' must not claim it.
1373
+ // A file run merely fs-READ post-plugin that a plugin also bundles is the plugin's, not run's.
1961
1374
  const pluginFiles = new Set()
1962
1375
  for (const [who, recorded] of this.#reasonFiles) {
1963
1376
  if (who === 'run') continue
@@ -1968,9 +1381,8 @@ export class State {
1968
1381
 
1969
1382
  const reason = {}
1970
1383
  let consumers = 0
1971
- // Sort consumer keys AND each file list, like every other map in the bundle (sortPaths, via
1972
- // fileMapToObject etc.): the emitted JSON must be byte-reproducible across runs regardless of
1973
- // loader-vs-plugin record order, else #emitBundle's compare-and-skip would see spurious diffs.
1384
+ // Sort keys and file lists: the JSON must be byte-reproducible regardless of record order, else
1385
+ // #emitBundle's compare-and-skip sees spurious diffs.
1974
1386
  for (const who of [...this.#reasonFiles.keys()].toSorted()) {
1975
1387
  const files = []
1976
1388
  for (const file of this.#reasonFiles.get(who)) {
@@ -1983,15 +1395,8 @@ export class State {
1983
1395
  return consumers > 1 ? reason : undefined
1984
1396
  }
1985
1397
 
1986
- // The formats map a bundle artifact declares. Normally `this.formats` as-is; the
1987
- // one adjustment is dropping a payload-free stat record ('stat:*') that the run's
1988
- // UNIFIED attestation upgraded to a real format -- a write-mode sidecar bundling a
1989
- // file this run also stat'd (stat-before-plugin-capture ordering, so addFile's
1990
- // in-place drop never saw it). The lockfile then attests the REAL format
1991
- // (#mergedFormats' upgrade), and a bundle still declaring 'stat:*' for that file
1992
- // would fail its lockfile cross-check at load (#mergeBundleMetadata). Cheap in the
1993
- // common case: with no write-mode sidecars the live map is already consistent
1994
- // (addFile/addFsDir drop superseded stat records in place) and is returned as-is.
1398
+ // The formats a bundle declares: `this.formats`, minus a 'stat:*' the run's unified attestation
1399
+ // upgraded to a real format (else the bundle fails its lockfile cross-check at load).
1995
1400
  #formatsForBundle() {
1996
1401
  if (this.#sidecars.size === 0) return this.formats
1997
1402
  const merged = this.#mergedFormats()
@@ -2006,24 +1411,22 @@ export class State {
2006
1411
  }
2007
1412
 
2008
1413
  get sourceBundle() {
2009
- // One bundle holds both code and resources; merge the two content maps (their key
2010
- // sets are disjoint -- a file is either code or a resource) and let `formats` tag
2011
- // which is which. Resource payloads are already encoded per their format. The
2012
- // disjointness invariant is enforced upstream in addFile via noupsert on
2013
- // this.formats (a file's format is either a resource one or not, and cannot
2014
- // change), so an overlap here would be a real bug -- assert it explicitly at
2015
- // the merge site so the failure is local, not a silently-clobbered value.
1414
+ // One bundle holds code + resources, with `formats` tagging which; the key sets must be
1415
+ // disjoint, asserted so an overlap fails locally rather than silently.
2016
1416
  const contents = new Map(this.sources)
2017
1417
  for (const [file, content] of this.resources) {
2018
1418
  assert.ok(!contents.has(file), `state invariant: file ${file} in both sources and resources`)
2019
1419
  contents.set(file, content)
2020
1420
  }
1421
+ const modules = this.#bundleModules(contents)
1422
+ const formats = this.#formatsForBundle()
2021
1423
  return new Bundle({
2022
1424
  config: this.config.values,
2023
1425
  entries: this.entries,
2024
- modules: this.#bundleModules(contents),
2025
- formats: this.#formatsForBundle(),
1426
+ modules,
1427
+ formats,
2026
1428
  imports: this.imports,
1429
+ executable: this.#bundleExecutable(modules, formats),
2027
1430
  reason: this.#bundleReason(contents.keys()),
2028
1431
  })
2029
1432
  }
@@ -2032,30 +1435,24 @@ export class State {
2032
1435
  return this.sourceBundle.serialize()
2033
1436
  }
2034
1437
 
2035
- // Split-bundle counterparts to `sourceBundle` / `sourceData`. Used by `write()`
2036
- // when `config.resourcesBundleFile` is set so the on-disk layout matches a
2037
- // bundle=load reader. Each is a standalone v1 Bundle (independently parseable);
2038
- // metadata is partitioned, not duplicated -- the code half owns entries/imports
2039
- // and code-format declarations, the resources half owns resource-format
2040
- // declarations and the resource bytes. Both halves declare their per-dir
2041
- // module identity (name/version) so each file is verifiable on its own.
1438
+ // Split-bundle counterparts to sourceBundle/sourceData: the code half owns entries/imports + code
1439
+ // formats, the resources half owns resource formats + bytes. Both declare per-dir module identity
1440
+ // so each file verifies alone.
2042
1441
  get codeBundle() {
2043
- // Resource files don't appear in `this.sources` (addFile routes by format), so
2044
- // restricting #bundleModules to `this.sources` automatically yields the code-only
2045
- // view. Formats and modules are filtered to drop resource-only dirs/files.
2046
- // Payload-free stat records are NOT resource formats, so they ride the code half
2047
- // (like the other content-less metadata, entries/imports) -- the resources half's
2048
- // strict resource-formats-only shape check would reject them.
1442
+ // Stat records ride the code half -- they aren't resource formats, so the resources half's shape
1443
+ // check would reject them.
2049
1444
  const codeFormats = new Map()
2050
1445
  for (const [file, format] of this.#formatsForBundle()) {
2051
1446
  if (!Bundle.isResourceFormat(format)) codeFormats.set(file, format)
2052
1447
  }
1448
+ const modules = this.#bundleModules(this.sources)
2053
1449
  return new Bundle({
2054
1450
  config: this.config.values,
2055
1451
  entries: this.entries,
2056
- modules: this.#bundleModules(this.sources),
1452
+ modules,
2057
1453
  formats: codeFormats,
2058
1454
  imports: this.imports,
1455
+ executable: this.#bundleExecutable(modules, codeFormats),
2059
1456
  reason: this.#bundleReason(this.sources.keys()),
2060
1457
  })
2061
1458
  }
@@ -2065,61 +1462,30 @@ export class State {
2065
1462
  for (const [file, format] of this.formats) {
2066
1463
  if (Bundle.isResourceFormat(format)) resourceFormats.set(file, format)
2067
1464
  }
1465
+ const modules = this.#bundleModules(this.resources)
2068
1466
  return new Bundle({
2069
1467
  config: this.config.values,
2070
- // Resources bundle carries no entries / imports -- those belong to the code half.
2071
- // Bundle.parse accepts an empty entries set when no code is present (the hasCode
2072
- // check sees only resource-format files and waives the requirement).
1468
+ // Resources bundle carries no entries/imports (Bundle.parse waives the entries requirement when no code).
2073
1469
  entries: new Set(),
2074
- modules: this.#bundleModules(this.resources),
1470
+ modules,
2075
1471
  formats: resourceFormats,
2076
1472
  imports: new Map(),
1473
+ executable: this.#bundleExecutable(modules, resourceFormats),
2077
1474
  reason: this.#bundleReason(this.resources.keys()),
2078
1475
  })
2079
1476
  }
2080
1477
 
2081
- // Record a capture-time native resolution (from the Module._resolveFilename
2082
- // shim). Stored verbatim; #backfillObservedResolutions decides at write() which
2083
- // to add. Last-write-wins per (parent, specifier) so duplicates collapse.
1478
+ // Record a native resolution verbatim (last-write-wins per parent+specifier);
1479
+ // #backfillObservedResolutions decides at write() which to add.
2084
1480
  observeResolution(parentURL, specifier, resolvedURL) {
2085
1481
  let byParent = this.#observedResolutions.get(parentURL)
2086
1482
  if (byParent === undefined) this.#observedResolutions.set(parentURL, (byParent = new Map()))
2087
1483
  byParent.set(specifier, resolvedURL)
2088
1484
  }
2089
1485
 
2090
- // Backfill resolution edges the live resolve hook never observed -- require.resolve()
2091
- // (and CJS require()s that resolve natively) on Node versions where they bypass
2092
- // the hook. Records BOTH kinds the hook missed:
2093
- // - under-recorded require()s whose target the bundle carries (Node's module
2094
- // cache hid the require() from the resolve hook -- another module loaded the
2095
- // target first), and
2096
- // - resolve-only edges whose target it does NOT carry: require.resolve() of a
2097
- // module never loaded in-process (an optional-dependency probe, a forked-
2098
- // worker child like worker-farm's, a .node addon). The resolution is real and
2099
- // must be attested so the same require.resolve() returns the same path at
2100
- // load; the file simply has no bytes -- require.resolve returns a path, load()
2101
- // never runs for it, so getFile is never asked to serve it. Bytes are attested
2102
- // only by whoever actually LOADS the file: a fork/worker target (jest-worker's
2103
- // processChild) is loaded in the forked CHILD as its entry, and that child's
2104
- // own capture contributes them via the --child-process shard -- flushed even on
2105
- // SIGTERM under the Metro plugin's opt-in (hooks.js), so a force-killed
2106
- // transform worker still reports. Deliberately NOT seeded here from the parent:
2107
- // attesting bytes this process never loaded would widen the trust set to
2108
- // everything that merely resolves.
2109
- // Guards:
2110
- // - skip out-of-scope targets (mirroring #collectMissingImportedFiles) so a
2111
- // node_modules-scope artifact doesn't attest workspace resolutions it isn't
2112
- // responsible for; an in-bundle target is always in scope, so it's exempt.
2113
- // (Targets escaping the root throw in #canonicalFile -> caught below.)
2114
- // - only edges the hook didn't already record (dedup across all condition
2115
- // buckets), so this never double-records a normal require().
2116
- // Keyed under the observed require-condition set (#requireConditions) -- require()/
2117
- // require.resolve() resolve under those conditions, not condition-free -- so a
2118
- // native-resolve Node (where these edges land here) keys them the same way the
2119
- // resolve hook keys them directly on newer Node. Any capture that does at least one
2120
- // require() thus yields the same lockfile on every version; '*' only when the set was
2121
- // never observed (a capture with no require() at all), which getImport/resolveBundled
2122
- // still match via their wildcard fallback.
1486
+ // Backfill edges the live resolve hook never observed (require.resolve()/native CJS require()).
1487
+ // The resolution is attested but its bytes are NOT seeded -- that would widen trust to everything
1488
+ // that merely resolves. Skips out-of-scope targets and dedups across all condition buckets.
2123
1489
  #backfillObservedResolutions() {
2124
1490
  if (this.#observedResolutions.size === 0) return
2125
1491
  for (const [parentURL, specs] of this.#observedResolutions) {
@@ -2140,31 +1506,39 @@ export class State {
2140
1506
  }
2141
1507
  }
2142
1508
 
1509
+ // Add every bundled module's `<dir>/package.json` (config.packageJSON) even if the run never
1510
+ // reached it, so a load/prune can read each dependency's manifest. The skip keys on bundle
1511
+ // membership, NOT this.hashes (which also holds lockfile-absorbed entries and is shared by
1512
+ // reference across sidecars).
1513
+ includePackageJson() {
1514
+ // Gather first: addFile mutates this.modules, so don't addFile while iterating it.
1515
+ const realRoot = realpathSync(this.root)
1516
+ const toAdd = []
1517
+ for (const [dir, module] of this.modules) {
1518
+ const rel = moduleFileKey(dir, 'package.json')
1519
+ if (this.sources.has(rel) || this.resources.has(rel)) continue // already in this bundle
1520
+ const buf = readModuleManifest({ baseDir: this.root, realBase: realRoot, rel })
1521
+ if (!buf) continue
1522
+ // Only carry a manifest whose on-disk identity still matches the bundled bucket: under
1523
+ // bundle=add a dep may have drifted, and addFile -> #locateModule would crash on it.
1524
+ let pkg
1525
+ try { pkg = JSON.parse(buf.toString()) } catch { continue } // malformed manifest for an untouched bucket: skip
1526
+ if (pkg?.name !== module.name || pkg?.version !== module.version) continue
1527
+ toAdd.push({ rel, buf })
1528
+ }
1529
+ for (const { rel, buf } of toAdd) {
1530
+ this.addFile(pathToFileURL(resolve(this.root, rel)).toString(), { source: buf, reason: null })
1531
+ }
1532
+ }
1533
+
2143
1534
  write() {
2144
- // Backfill observed (native Module._resolveFilename) resolutions BEFORE the
2145
- // stasis-core BFS. On Node's native-resolve versions a resolve-only edge to a
2146
- // stasis-core src/*.js submodule (e.g. require.resolve('@exodus/stasis-core/
2147
- // prune') of a module never loaded) is added only here; running the BFS first
2148
- // would compute its missing-set without that edge, never seed the file, and
2149
- // ship a dangling edge with no bytes -- which a later lock=frozen replay then
2150
- // rejects. Recording it first lets the BFS capture the bytes, matching what the
2151
- // resolve-hook path already records in-line on newer Node. Order is otherwise
2152
- // independent: the BFS doesn't read #observedResolutions, and observe-backfill's
2153
- // `bundled` check sees files loaded during capture (already in this.sources)
2154
- // regardless of when the BFS runs.
1535
+ // BEFORE the stasis-core BFS: a resolve-only edge to a stasis-core submodule is added only here,
1536
+ // and the BFS must see it to seed the file's bytes, else the bundle ships a dangling edge.
2155
1537
  this.#backfillObservedResolutions()
2156
1538
  this.#backfillBeforeWrite()
2157
- // writeFileSync(join(this.root, FILE_CONFIG), this.config.json)
2158
- // Sidecars never write the lockfile -- the parent owns it. They only emit their bundle.
2159
- // A "sidecar" here is one sharing the parent's lockfile data structures; an independent
2160
- // State with its own lockFile path (constructed via the no-parent code path) writes its
2161
- // own lockfile to `config.lockFile` instead of the rootDir default.
2162
- //
2163
- // Per-artifact compare-and-skip: each output's serialized text is compared against the
2164
- // cached previous text and the brotli + writeFileSync are both skipped when they match.
2165
- // Critical for webpack/esbuild watch-mode rebuilds, where compiler.hooks.done fires on
2166
- // every rebuild but the captured graph usually doesn't change. Without this, every
2167
- // rebuild brotli-compresses (quality 11) and rewrites every output.
1539
+ // AFTER the backfills, so buckets they create are covered too.
1540
+ if (this.config.writeBundle && this.config.packageJSON) this.includePackageJson()
1541
+ // Sidecars never write the lockfile (parent owns it); they only emit their bundle.
2168
1542
 
2169
1543
  if (this.config.writeLockfile && !this.#parent) {
2170
1544
  const lockText = this.lockData
@@ -2178,12 +1552,7 @@ export class State {
2178
1552
  if (this.config.writeBundle) {
2179
1553
  const sourcesPath = this.config.bundleFile || join(this.root, FILE_CODE)
2180
1554
  if (this.config.resourcesBundleFile) {
2181
- // Split-bundle layout: code-only to bundleFile, resources-only to resourcesBundleFile.
2182
- // Each is a standalone v1 Bundle (cross-check on load enforces shape). hasContent
2183
- // gates per half so an empty half (no code / no resources) is dropped under replace
2184
- // rather than written as an empty bundle -- see #emitBundle. sources/resources size
2185
- // is the exact emptiness test: a code bundle's entries/imports are non-empty only
2186
- // when sources are (every entry/edge parent is itself an addFile'd source).
1555
+ // hasContent gates each half so an empty one is dropped under bundle=replace.
2187
1556
  this.#lastCodeBundle = this.#emitBundle(
2188
1557
  sourcesPath, this.sources.size > 0, this.#lastCodeBundle, () => this.codeBundle.serialize())
2189
1558
  this.#lastResourcesBundle = this.#emitBundle(
@@ -2197,226 +1566,143 @@ export class State {
2197
1566
  }
2198
1567
  }
2199
1568
 
2200
- // Produce the lockfile-shaped snapshot of everything THIS process captured, for a child
2201
- // process to hand back to the root (which never loaded what only the child loaded -- e.g.
2202
- // a Metro transform worker loading babel.config.js + its babel preset/plugins). Runs the
2203
- // same backfills write() runs so observed native (Module._resolveFilename) resolutions and
2204
- // stasis-core internal edges are materialized first. Content is intentionally omitted: the
2205
- // snapshot carries project-relative paths + the import graph + formats + entries, and the
2206
- // root re-reads each file's bytes from disk when it replays via mergeShard().
1569
+ // Snapshot of what THIS process observed, for a forked child to hand back to the root. Content is
1570
+ // omitted -- the root re-reads bytes from disk.
2207
1571
  shardSnapshot() {
2208
1572
  this.#backfillObservedResolutions()
2209
1573
  this.#backfillBeforeWrite()
2210
- // Forward ONLY what THIS process observed this run -- not the baseline it seeded at construction.
2211
- // On a lock=add re-run the root seeds the same lockfile baseline (and a BUNDLE run seeds the
2212
- // whole bundle graph), so re-shipping it would bloat every worker's shard (toward
2213
- // MAX_SHARD_BYTES, past which mergeChildShards silently drops it) and make the root re-merge it
2214
- // once per worker. #observed holds the files addFile/addFsDir recorded this run; modules, formats
2215
- // AND imports are all filtered to it below. (Lockfile-seeded edges/formats live in
2216
- // #lockImports/#lockFormats, but a bundle load seeds this.imports/this.formats DIRECTLY -- so we
2217
- // filter explicitly rather than rely on which map holds the baseline.) Entries are dropped:
2218
- // mergeShard never marks a merged file as an entry, and this.entries is itself seeded.
2219
- const modules = new Map()
2220
- for (const [dir, info] of this.modules) {
2221
- const files = {}
2222
- for (const rel of Object.keys(info.files)) {
2223
- if (this.#observed.has(moduleFileKey(dir, rel))) files[rel] = info.files[rel]
2224
- }
2225
- if (Object.keys(files).length === 0) continue
2226
- modules.set(dir, info.ecosystem === undefined
2227
- ? { name: info.name, version: info.version, files }
2228
- : { name: info.name, version: info.version, ecosystem: info.ecosystem, files })
2229
- }
2230
- // formats: only observed files. imports: only edges whose PARENT was observed -- a child adds an
2231
- // edge solely from a file it loaded (addImport's parent is addFile'd -> in #observed), so its
2232
- // session edges are kept while bundle-seeded edges (parent never loaded here) are dropped; the
2233
- // root already attests those from its own seed, so dropping them loses nothing.
1574
+ // Only what THIS process observed, never the seeded baseline (shard-size bloat). Entries are
1575
+ // dropped: a child's "entry" is its fork target, not a root's.
1576
+ const files = []
2234
1577
  const formats = new Map()
2235
1578
  for (const file of this.#observed) {
2236
- const fmt = this.formats.get(file)
2237
- if (fmt !== undefined) formats.set(file, fmt)
1579
+ const format = this.formats.get(file)
1580
+ if (format !== undefined) formats.set(file, format)
1581
+ if (this.hashes.has(file)) files.push(file)
2238
1582
  }
1583
+ // Only edges whose PARENT was observed, dropping the bundle-seeded ones the root already attests.
2239
1584
  const imports = new Map()
2240
1585
  for (const [conditions, byParent] of this.imports) {
2241
1586
  let kept
2242
- for (const [parent, specs] of byParent) {
2243
- if (!this.#observed.has(parent)) continue
2244
- if (kept === undefined) { kept = new Map(); imports.set(conditions, kept) }
1587
+ for (const parent of this.#observed) {
1588
+ const specs = byParent.get(parent)
1589
+ if (specs === undefined) continue
1590
+ if (kept === undefined) imports.set(conditions, (kept = new Map()))
2245
1591
  kept.set(parent, specs)
2246
1592
  }
2247
1593
  }
2248
- return new Lockfile({
2249
- config: this.config.values,
2250
- entries: new Set(),
2251
- modules,
2252
- imports,
2253
- formats,
2254
- }).serialize()
2255
- }
2256
-
2257
- // Merge a child process's shardSnapshot() (a serialized lockfile) into this State, as if
2258
- // this process had loaded/read those files itself: replay each file (addFile for code +
2259
- // `--fs` resources, addFsDir for `--fs` directory captures -- re-reading bytes/listings from
2260
- // disk to hash + classify) and addImport each recorded edge. This is how the root attests files and
2261
- // edges that ONLY a forked child observed -- the child runs the loader and captures into
2262
- // its own State but is blocked from writing, so without this its observations are lost.
2263
- // Project-relative paths are shared across the process tree (same root); URLs are
2264
- // reconstructed via resolve(this.root, file). Best-effort per record: a path gone from disk
2265
- // (a transient temp module) or rejected by addFile/addImport (out of this run's scope) is
2266
- // skipped rather than aborting the whole merge -- the root's own capture stays intact.
2267
- mergeShard(lockText) {
2268
- const lf = Lockfile.parse(lockText)
2269
- // A shard must describe the SAME scope as this root (children inherit scope via env, so they
2270
- // always agree). Defense-in-depth: a cross-scope shard is already signature-rejected upstream,
2271
- // but a mismatch here would mean a malformed/foreign shard -- refuse it rather than merge.
2272
- assert.equal(lf.config.scope, this.config.scope, `shard scope "${lf.config.scope}" != root scope "${this.config.scope}"`)
2273
- // Files first (so addFile records bytes/format/module identity), then edges. Merged files
2274
- // are NEVER marked entries: a forked child's "entry" is its fork-target main (e.g. a Metro
2275
- // worker's bootstrap), not a declared entry of the ROOT build -- recording it as one would
2276
- // corrupt the root's entries list. The child's lf.entries is therefore ignored here.
2277
- for (const [dir, info] of lf.modules) {
2278
- for (const rel of Object.keys(info.files)) {
2279
- // moduleFileKey is the exact inverse of how the child bucketed the path -- in particular
2280
- // it yields `dir` (no trailing slash) for a directory captured AT a bucket root (rel==='').
2281
- const file = moduleFileKey(dir, rel)
2282
- // Skip a file the root already attests -- its seeded lockfile baseline or its own capture
2283
- // this run. A child only needs to contribute what the root didn't observe; re-reading an
2284
- // already-recorded file from disk (per worker shard) is the dominant merge cost, and since
2285
- // this loop adds to this.hashes, identical toolchain files from later workers skip too.
2286
- // EXCEPTION: still carry a concrete code format the root LACKS. If the root fs-READ this
2287
- // `.js`/`.ts` (addFsFile records the hash but NO format) while the child IMPORTED it as
2288
- // `module`, dropping the format here would leave the lockfile format-less and make a later
2289
- // frozen run -- where the file loads as a module -- reject the now-unattested format. Fall
2290
- // through so addFile records (and validates) the format; the byte re-read is the only cost.
2291
- if (this.hashes.has(file)) {
2292
- const shardFormat = lf.formats?.get(file)
2293
- if (shardFormat === undefined || (this.formats.get(file) ?? this.#lockFormats?.get(file)) !== undefined) continue
2294
- }
2295
- const absolute = resolve(this.root, file)
2296
- const url = pathToFileURL(absolute).toString()
2297
- const format = lf.formats?.get(file)
2298
- try {
2299
- if (format === 'directory') {
2300
- // A child's `fs.readdirSync` capture (`--fs`): replay as a directory listing (addFile
2301
- // rejects a directory). Re-read the listing from disk so the root's hash is
2302
- // authoritative -- the same disk-is-truth stance as the byte re-reads below. Range-check
2303
- // the path FIRST: addFsDir would reject a traversal, but only AFTER readdirSync already
2304
- // ran on the forged out-of-root path, so a child-forged `..` key can't make us list it.
2305
- const relFromRoot = relative(this.root, absolute)
2306
- if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
2307
- this.addFsDir(url, readdirSync(absolute))
2308
- } else if (format === 'resource' || format === 'resource:base64') {
2309
- // A child's `fs.readFileSync` capture of an asset: addFile needs resource:true for a
2310
- // resource format. The exact 'resource' vs 'resource:base64' tag is content-derived, so
2311
- // addFile re-derives it from the re-read bytes -- we don't pass it (and risk a spurious
2312
- // mismatch), we just mark it a resource.
2313
- this.addFile(url, { resource: true })
2314
- } else if (format === undefined) {
2315
- // Code file the child recorded with NO format -- it fs-READ a `.js`/`.ts` (or
2316
- // `.jsx`/`.tsx`), where addFsFile defers module-vs-commonjs to the loader rather than
2317
- // imposing one (Node's syntax-detection call). Replay the same way (inferFormat:false):
2318
- // record the bytes but impose no format, so we don't bake in the legacy commonjs
2319
- // default and collide -- at the frozen format check, or noupsert -- with the `module`
2320
- // the loader records when that file is later imported. (Babel reading a worker's source
2321
- // `.js` to transform it is exactly this case under `--fs --child-process`.)
2322
- this.addFile(url, { inferFormat: false })
2323
- } else {
2324
- // Code file with a concrete loader format the child recorded (it imported the file, or
2325
- // fs-read an unambiguous `.mjs`/`.cjs`/`.json`). Carry it: without it, a child-only ESM
2326
- // `.js`/`.ts` under a no-`type` package would re-default to commonjs, and the subsequent
2327
- // frozen run -- where the child re-loads it as module -- would reject the mismatch.
2328
- // addFile still asserts the format agrees with an explicit package.json `type` when one
2329
- // exists, so this can't smuggle a wrong format.
2330
- this.addFile(url, { format })
2331
- }
2332
- } catch {
2333
- // A file the child loaded but that's gone/unreadable here, or that addFile rejects
2334
- // (e.g. an out-of-scope path under a different scope): skip it. The edge replay below
2335
- // tolerates the resulting gap the same way.
1594
+ return serializeShard({ scope: this.config.scope, files, formats, imports })
1595
+ }
1596
+
1597
+ // Merge a child's shardSnapshot() as if this process read those files itself: replay each file
1598
+ // (re-reading bytes/listings from disk) and each edge. Best-effort -- a gone/out-of-scope record is
1599
+ // skipped rather than aborting the merge.
1600
+ mergeShard(shardText) {
1601
+ const shard = parseShard(shardText)
1602
+ // Defense-in-depth: cross-scope is signature-rejected upstream, but a mismatch here means a
1603
+ // malformed/foreign shard -- refuse.
1604
+ assert.equal(shard.scope, this.config.scope, `shard scope "${shard.scope}" != root scope "${this.config.scope}"`)
1605
+ // An in-root shard KEY may resolve (through a symlink) OUTSIDE the root on THIS disk, so every
1606
+ // replay re-checks real-path containment -- the same boundary fs.js enforces on live --fs reads.
1607
+ let realRoot
1608
+ const realContained = (absolute) => {
1609
+ if (realRoot === undefined) {
1610
+ try { realRoot = realpathSync(this.root) } catch { realRoot = this.root }
1611
+ }
1612
+ let real
1613
+ try { real = realpathSync(absolute) } catch { return false }
1614
+ const rel = relative(realRoot, real)
1615
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
1616
+ }
1617
+ // Files first, then edges. Merged files are NEVER marked entries -- a child's "entry" is its
1618
+ // fork-target main, not a root entry.
1619
+ for (const file of shard.files) {
1620
+ const absolute = resolve(this.root, file)
1621
+ // Skip a key whose on-disk path escapes the root through a symlink.
1622
+ if (!realContained(absolute)) continue
1623
+ // ABOVE the already-attested fast path below: a child that re-read a file and found no bit
1624
+ // refutes it by OMISSION, so every file the shard RECORDS needs an observation. Re-derived
1625
+ // from THIS process's disk, so the shard cannot inject a forged bit.
1626
+ this.#recordExecutable(file, absolute)
1627
+ // Skip a file the root already attests (the byte re-read dominates merge cost), EXCEPT to
1628
+ // carry a concrete format the root LACKS, else a later frozen run rejects the unattested format.
1629
+ if (this.hashes.has(file)) {
1630
+ const shardFormat = shard.formats.get(file)
1631
+ if (shardFormat === undefined || (this.formats.get(file) ?? this.#lockFormats?.get(file)) !== undefined) continue
1632
+ }
1633
+ const url = pathToFileURL(absolute).toString()
1634
+ const format = shard.formats.get(file)
1635
+ try {
1636
+ if (format === 'directory') {
1637
+ // Range-check FIRST so a child-forged `..` key can't make us list it.
1638
+ const relFromRoot = relative(this.root, absolute)
1639
+ if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
1640
+ this.addFsDir(url, readdirSync(absolute))
1641
+ } else if (format === 'resource' || format === 'resource:base64') {
1642
+ // Let addFile re-derive the exact resource tag from the re-read bytes rather than trusting
1643
+ // the shard's and risking a mismatch.
1644
+ this.addFile(url, { resource: true })
1645
+ } else if (format === undefined) {
1646
+ // No format recorded (an fs-READ .js/.ts): inferFormat:false so we don't bake in the
1647
+ // commonjs default and collide with the `module` the loader records if it's later imported.
1648
+ this.addFile(url, { inferFormat: false })
1649
+ } else {
1650
+ // Carry the child's format, else a child-only ESM .js under a no-`type` package re-defaults
1651
+ // to commonjs and a frozen run rejects the mismatch.
1652
+ this.addFile(url, { format })
2336
1653
  }
1654
+ } catch {
1655
+ // Gone/unreadable, or addFile-rejected (out of scope): skip, like the edge replay below.
2337
1656
  }
2338
1657
  }
2339
- // Payload-free stat records (`--fs` lstat/stat captures) live ONLY in the shard's
2340
- // formats map -- no module-files entry -- so the modules loop above never visits
2341
- // them. Replay each by re-deriving the kind from DISK (the same disk-is-truth
2342
- // stance as the byte/listing re-reads: a shard can't inject a forged kind), via
2343
- // addFsStat so a path the root already attests with content is skipped, exactly
2344
- // as if this process had stat'd it. Range-check the path BEFORE touching disk,
2345
- // like the directory branch above; a path gone from disk (or of an unmodelled
2346
- // kind, e.g. a socket) is skipped, best-effort like every other replay.
2347
- if (lf.formats) {
2348
- let realRoot // resolved once, on the first record: the containment anchor below
2349
- for (const [file, format] of lf.formats) {
2350
- if (!isStatFormat(format)) continue
2351
- const absolute = resolve(this.root, file)
2352
- const relFromRoot = relative(this.root, absolute)
2353
- if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
2354
- try {
2355
- // statSync (follow symlinks), NOT lstatSync: the child's capture followed them
2356
- // -- a statSync of an in-root symlink records the TARGET's kind keyed at the
2357
- // requested path (pnpm's public node_modules/<pkg> links are exactly this
2358
- // shape), and an lstat of a symlink was never recorded at all -- so for every
2359
- // key a legitimate shard can carry, statSync reproduces the recorded kind
2360
- // while lstatSync would report the link itself and silently drop the record.
2361
- const stats = statSync(absolute)
2362
- const kind = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : null
2363
- if (kind === null) continue
2364
- // Because statSync follows links, re-assert the capture side's containment
2365
- // (fs.js captureStat's realContained) before attesting: the REAL location must
2366
- // stay inside the root's real path, so a shard entry keyed at an in-root
2367
- // symlink that points OUT of the tree is skipped, never recorded.
2368
- if (realRoot === undefined) {
2369
- try { realRoot = realpathSync(this.root) } catch { realRoot = this.root }
2370
- }
2371
- const relReal = relative(realRoot, realpathSync(absolute))
2372
- if (relReal !== '' && (relReal.startsWith('..') || isAbsolute(relReal))) continue
2373
- this.addFsStat(pathToFileURL(absolute).toString(), kind)
2374
- } catch {
2375
- // Gone from disk (or a dangling link), or rejected (kind conflict with the
2376
- // root's own capture): skip -- the root's capture stays intact.
2377
- }
1658
+ // Stat records live ONLY in the shard's formats map, so replay each here, re-deriving the kind
1659
+ // from DISK (a shard can't inject a forged kind). Range-check BEFORE touching disk.
1660
+ for (const [file, format] of shard.formats) {
1661
+ if (!isStatFormat(format)) continue
1662
+ const absolute = resolve(this.root, file)
1663
+ const relFromRoot = relative(this.root, absolute)
1664
+ if (relFromRoot.startsWith('..') || isAbsolute(relFromRoot)) continue
1665
+ try {
1666
+ // statSync, NOT lstatSync: the child's capture followed symlinks, so this reproduces the kind
1667
+ // a legitimate shard carries where lstatSync would report the link and drop it.
1668
+ const stats = statSync(absolute)
1669
+ const kind = stats.isDirectory() ? 'directory' : stats.isFile() ? 'file' : null
1670
+ if (kind === null) continue
1671
+ // statSync follows links: a symlink pointing OUT must not attest an external kind under an
1672
+ // in-root key.
1673
+ if (!realContained(absolute)) continue
1674
+ this.addFsStat(pathToFileURL(absolute).toString(), kind)
1675
+ } catch {
1676
+ // Gone/dangling, or a kind conflict with the root's capture: skip.
2378
1677
  }
2379
1678
  }
2380
- if (lf.imports) {
2381
- for (const [conditions, byParent] of lf.imports) {
2382
- // Reverse #conditionsKey: '*' stays '*'; otherwise the key is a ', '-joined condition
2383
- // list, optionally suffixed ' (with: {json})' for import attributes. Toolchain edges
2384
- // (CJS require) carry no attributes; parse them when present so attributed edges merge
2385
- // under the same key the child recorded.
2386
- let condStr = conditions
2387
- let importAttributes
2388
- const withAt = conditions.indexOf(' (with: ')
2389
- if (withAt !== -1) {
2390
- condStr = conditions.slice(0, withAt)
2391
- try { importAttributes = JSON.parse(conditions.slice(withAt + ' (with: '.length, -1)) } catch { /* leave undefined */ }
2392
- }
2393
- const cond = condStr === '*' ? '*' : condStr.split(', ')
2394
- for (const [parent, specs] of byParent) {
2395
- const parentURL = pathToFileURL(resolve(this.root, parent)).toString()
2396
- for (const [specifier, file] of specs) {
2397
- const url = pathToFileURL(resolve(this.root, file)).toString()
2398
- try {
2399
- this.addImport(parentURL, specifier, url, { conditions: cond, importAttributes })
2400
- } catch {
2401
- // Same best-effort stance as addFile above.
2402
- }
1679
+ for (const [conditions, byParent] of shard.imports) {
1680
+ // Reverse #conditionsKey: '*', else a ', '-joined list with an optional ' (with: {json})'
1681
+ // suffix -- parse it so attributed edges merge under the child's key.
1682
+ let condStr = conditions
1683
+ let importAttributes
1684
+ const withAt = conditions.indexOf(' (with: ')
1685
+ if (withAt !== -1) {
1686
+ condStr = conditions.slice(0, withAt)
1687
+ try { importAttributes = JSON.parse(conditions.slice(withAt + ' (with: '.length, -1)) } catch { /* leave undefined */ }
1688
+ }
1689
+ const cond = condStr === '*' ? '*' : condStr.split(', ')
1690
+ for (const [parent, specs] of byParent) {
1691
+ const parentURL = pathToFileURL(resolve(this.root, parent)).toString()
1692
+ for (const [specifier, file] of specs) {
1693
+ const url = pathToFileURL(resolve(this.root, file)).toString()
1694
+ try {
1695
+ this.addImport(parentURL, specifier, url, { conditions: cond, importAttributes })
1696
+ } catch {
1697
+ // Same best-effort stance as addFile above.
2403
1698
  }
2404
1699
  }
2405
1700
  }
2406
1701
  }
2407
1702
  }
2408
1703
 
2409
- // Emit one bundle artifact, returning its new "last serialized" cache value.
2410
- // - empty (hasContent === false) under bundle=replace: this run carries nothing for
2411
- // this artifact, so DELETE any file at `path` rather than write an empty bundle. A
2412
- // `bundle=replace` run is authoritative -- it deliberately ignores the prior on-disk
2413
- // bundle (the constructor skips loading it), so a stale file the run didn't produce
2414
- // must not survive as the "old one". Returning null resets the cache so a later
2415
- // non-empty write() (watch-mode rebuild) re-emits the file.
2416
- // - otherwise (has content, OR empty under add): serialize and write, skipping the
2417
- // brotli + writeFileSync when the text is byte-identical to the last write (the
2418
- // watch-mode compare-and-skip this cache exists for). add keeps emitting an empty
2419
- // bundle so the file always exists -- only replace prunes a not-written artifact.
1704
+ // Emit one bundle artifact, returning its new "last serialized" cache. Empty under bundle=replace
1705
+ // DELETES the file (a replace run is authoritative); unchanged text skips brotli + writeFileSync.
2420
1706
  #emitBundle(path, hasContent, lastText, serialize) {
2421
1707
  if (!hasContent && this.config.replaceBundle) {
2422
1708
  rmSync(path, { force: true })
@@ -2435,54 +1721,23 @@ export class State {
2435
1721
  return this.#parent
2436
1722
  }
2437
1723
 
2438
- // Capture stasis-core's own files + internal edges that the live hooks missed.
2439
- // When app code (or a bundler plugin) imports a stasis-core module, Node had
2440
- // it cached from preload-time -- BEFORE install() registered our hooks -- so
2441
- // the resolve hook records the edge but the load hook never fires, leaving
2442
- // addFile / addImport blind to the file's bytes AND its outgoing edges. This
2443
- // BFS, scoped strictly to the `<root>/.../@exodus/stasis-core/src/<name>.js`
2444
- // shape, walks the graph starting from missing imports targets + already-
2445
- // captured stasis-core files: for each, addFile (asserting the shape),
2446
- // statically scans for relative-`.js` specifiers, resolves them, and
2447
- // addImports each edge. The strict shape allowlist + existsSync gate filter
2448
- // out comment-noise like a `require('../../pkg/x')` sitting in a JSDoc block.
2449
- //
2450
- // Called from write() so every State variant (preload via beforeExit/exit;
2451
- // sidecar / independent plugin States via compiler.hooks.done) gets the
2452
- // same coverage.
1724
+ // Capture stasis-core's own files + internal edges the live hooks missed: for a preload-cached
1725
+ // module the resolve hook records the edge but the load hook never fires. The BFS below is scoped
1726
+ // to the stasis-core src shape.
2453
1727
  #backfillBeforeWrite() {
2454
- // List what the live hooks missed first. An empty list means there's
2455
- // nothing to do -- either the live hooks captured everything (the common
2456
- // case for non-preload runs and for plugin-driven States that don't
2457
- // touch preload-cached modules), or we're a State variant that doesn't
2458
- // observe imports at all.
2459
1728
  const missing = this.#collectMissingImportedFiles()
2460
1729
  if (missing.size === 0) return
2461
1730
 
2462
1731
  const isStasisCoreFile = (file) => STASIS_CORE_FILE_RE.test(`/${file}`)
2463
1732
 
2464
- // Split the uncaptured targets. stasis-core's own preload-cached files are the
2465
- // one case we both can and must reconstruct -- bytes AND transitive edges (the
2466
- // BFS below). Everything else uncaptured is a resolution we attest WITHOUT
2467
- // bundling: require.resolve() of a module never loaded in-process (an optional-
2468
- // dependency probe, a forked-worker child like worker-farm's), or a file Node
2469
- // can't serve from a bundle anyway (a .node addon). Those edges stay in
2470
- // this.imports -- the user needs the resolution pinned even though the bytes are
2471
- // absent -- and we do nothing further with them here. The load-time getFile
2472
- // gate, not this capture-time pass, enforces the trust boundary: an actual load
2473
- // of un-bundled bytes still fails closed there, while require.resolve (which
2474
- // never loads) is served the attested path.
1733
+ // Only stasis-core files are reconstructed; everything else stays a resolution attested without
1734
+ // bytes (the load-time getFile gate, not this pass, enforces the trust boundary).
2475
1735
  const stasisCoreMissing = [...missing].filter((file) => isStasisCoreFile(file))
2476
1736
  if (stasisCoreMissing.length === 0) return
2477
1737
 
2478
1738
  const preloadRel = this.#preloadRoot ? relative(this.root, this.#preloadRoot) : null
2479
1739
  const canBackfill = preloadRel !== null && !preloadRel.startsWith('..')
2480
1740
 
2481
- // We have stasis-core files to reconstruct but no usable preloadRoot (no loader
2482
- // present, or stasis-core is a workspace sibling not under state.root): nothing
2483
- // this method can do, and a stasis-core source going uncaptured IS a real gap --
2484
- // the bundle would be missing part of its own runtime. Fail loud rather than
2485
- // silently ship it.
2486
1741
  assert.ok(canBackfill,
2487
1742
  `state.write() has imports referencing un-captured stasis-core files but no usable preloadRoot ` +
2488
1743
  `(preloadRoot=${this.#preloadRoot ?? 'unset'}). The live load hook missed an in-scope target -- ` +
@@ -2490,29 +1745,14 @@ export class State {
2490
1745
 
2491
1746
  const PRELOAD_CONDITIONS = ['node', 'import', 'module-sync', 'node-addons']
2492
1747
  const stasisAddFile = (file) => {
2493
- // Tight invariant: every backfilled file MUST match the stasis-core
2494
- // source-file shape. The caller pre-filters via isStasisCoreFile, but
2495
- // asserting here keeps the contract local and catches any future code
2496
- // path that forgets.
2497
1748
  assert.ok(isStasisCoreFile(file),
2498
1749
  `state.write() backfill refused: '${file}' is not a stasis-core source file ` +
2499
1750
  `(expected '.../@exodus/stasis-core/src/<name>.js')`)
2500
1751
  this.addFile(pathToFileURL(resolve(this.root, file)).toString(), { reason: null }) // backfill is a write-time self-containment step, not a consumer observation -- don't attribute it
2501
1752
  }
2502
1753
 
2503
- // BFS through stasis-core's module graph. Seed:
2504
- // (a) the missing stasis-core files -- user-code -> stasis-core edges the
2505
- // live load hook missed because Node's module cache short-circuited it.
2506
- // (b) every stasis-core file already in sources -- a static `stasis
2507
- // bundle` pass may have pulled one in via the live hook; we still
2508
- // need to walk its transitive imports.
2509
- //
2510
- // For each queued file: addFile if not yet captured, then scan its
2511
- // source for relative-`.js` specifiers, validate the resolved target,
2512
- // addImport the edge, and queue the target. The single addFile site
2513
- // covers seeds AND transitive targets -- a queued target gets addFile'd
2514
- // on its next pop, no separate inner addFile call needed. BFS converges
2515
- // because the matching file set is finite and `processed` dedups.
1754
+ // Seeded from the missing files + every stasis-core file already in sources, to walk their
1755
+ // transitive imports too.
2516
1756
  const queue = [...stasisCoreMissing]
2517
1757
  for (const file of this.sources.keys()) {
2518
1758
  if (isStasisCoreFile(file)) queue.push(file)
@@ -2537,26 +1777,15 @@ export class State {
2537
1777
  queue.push(targetFile)
2538
1778
  this.addImport(baseURL, specifier, targetURL, { conditions: PRELOAD_CONDITIONS })
2539
1779
  }
2540
- // (1) ESM `from './<name>.js'|'.cjs'\n` -- stasis-core's source import shape
2541
- // (`import ... from` / `export ... from`, single-quoted, basename without `.`).
2542
- // Tight enough to ignore JSDoc / template-literal false positives, narrow enough
2543
- // to reject parent-relative (`../`), subpath (`./dir/file.js`), or extensionless.
2544
- // The `.cjs` arm covers state.js -> ./package.cjs (the version re-export shim).
1780
+ // stasis-core's ESM import shape, tight enough to ignore JSDoc/template-literal false positives.
2545
1781
  for (const m of source.matchAll(/ from '(\.\/[a-zA-Z-]+\.c?js)'\n/g)) recordEdge(m[1])
2546
- // (2) CJS `require('../package.json')` -- the single CommonJS shim
2547
- // (src/package.cjs) re-exporting stasis-core's own package.json so state.js can
2548
- // read its version. Matched exactly (not a general require/`../` relaxation) to
2549
- // stay as tight as the ESM arm.
1782
+ // The src/package.cjs version shim, matched exactly.
2550
1783
  for (const m of source.matchAll(/require\('(\.\.\/package\.json)'\)/g)) recordEdge(m[1])
2551
1784
  }
2552
1785
  }
2553
1786
 
2554
- // Project-relative files referenced by `this.imports` that the live hooks
2555
- // didn't capture into this.sources / this.resources, restricted to the
2556
- // in-scope set (full: everything under state.root; nm: only node_modules).
2557
- // Out-of-scope files are NOT included -- the live hooks correctly skip them
2558
- // (workspace files under nm-scope), and including them would force the
2559
- // backfill caller to wave away false alarms.
1787
+ // Files referenced by this.imports but not captured, restricted to the in-scope set (out-of-scope
1788
+ // files are excluded -- the live hooks correctly skip them).
2560
1789
  #collectMissingImportedFiles() {
2561
1790
  const missing = new Set()
2562
1791
  for (const [, byParent] of this.imports) {
@@ -2564,10 +1793,6 @@ export class State {
2564
1793
  for (const [, file] of specifiers) {
2565
1794
  if (typeof file !== 'string') continue
2566
1795
  if (missing.has(file)) continue
2567
- // Union of three "captured" signals: hashes (addFile ran -- present
2568
- // under any lock mode), sources/resources (bundle pre-seeded -- present
2569
- // under bundle=load even without a lockfile). Any one suffices; a
2570
- // file in NONE of them is the actual missing-from-capture case.
2571
1796
  if (this.hashes.has(file) || this.sources.has(file) || this.resources.has(file)) continue
2572
1797
  const url = pathToFileURL(resolve(this.root, file)).toString()
2573
1798
  if (!this.config.full && !this.inNodeModules(url)) continue
@@ -2579,13 +1804,7 @@ export class State {
2579
1804
  }
2580
1805
  }
2581
1806
 
2582
- // Allowed shape for a backfillable stasis-core path -- a `src/<name>.js` or
2583
- // `src/<name>.cjs` source, or the package's own `package.json` (required by the
2584
- // src/package.cjs version shim). Used by the backfill BFS to reject anything that
2585
- // doesn't look like a real stasis-core file (comment noise, paths escaping `src/`,
2586
- // etc.). Matched against `/${projectRelativeFile}` so the leading-`/` anchor isn't
2587
- // fooled by a file at the project root happening to end in `@exodus/stasis-core/...`.
2588
- // Source basenames are `[a-zA-Z-]+` only -- no `.` in the basename, which is why
2589
- // `state.util.js` was renamed to `state-util.js`.
1807
+ // Backfillable stasis-core paths. Anchored against `/${file}` so a project-root file merely ending
1808
+ // in `@exodus/stasis-core/...` isn't matched.
2590
1809
  const STASIS_CORE_FILE_RE = /\/@exodus\/stasis-core\/(?:src\/[a-zA-Z-]+\.c?js|package\.json)$/
2591
1810