@exodus/stasis-core 1.0.0-beta.14 → 1.0.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/hooks.js CHANGED
@@ -16,7 +16,6 @@ const { mkdtempSync, opendirSync, readFileSync, renameSync, rmSync, statSync, wr
16
16
 
17
17
  const CJS_FORMATS = new Set(['commonjs', 'commonjs-typescript'])
18
18
 
19
- // The trust gate's refusal for a bundle-served file whose attested format Node can't execute, by kind.
20
19
  function refuseNonNodeFormat(format, url) {
21
20
  if (SOURCE_LANGUAGE_FORMATS.has(format)) {
22
21
  throw new Error(`[stasis] cannot execute a '${format}' bundle: ${format} bundles are produced for external analysis, not for 'stasis run --bundle=load' (${url})`)
@@ -57,21 +56,26 @@ const TRAILING_SAME_LINE = /(?:[ \t]|\/\*(?:[^*\n\r\u2028\u2029]|\*(?!\/))*\*\/)
57
56
  // A directive string followed by one of these heads a multi-line expression, not a directive (ASI gotcha).
58
57
  const EXPR_CONTINUATION = new Set(['.', '[', '(', '`', '+', '-', '*', '/', '%', ',', '?', ':', '=', '<', '>', '&', '|', '^'])
59
58
  const KEYWORD_CONTINUATION = /(?:instanceof|in)\b/uy
60
- function skipSticky(re, source, i) {
59
+ function matchEnd(re, source, i) {
61
60
  re.lastIndex = i
62
- re.exec(source)
63
- return re.lastIndex
61
+ return re.test(source) ? re.lastIndex : -1
64
62
  }
65
63
  function newStatementAfterBreak(source, pos) {
66
- const afterBreak = skipSticky(WS_COMMENTS, source, pos)
64
+ const afterBreak = matchEnd(WS_COMMENTS, source, pos)
67
65
  if (afterBreak >= source.length) return true
68
66
  if (EXPR_CONTINUATION.has(source[afterBreak])) return false
69
- KEYWORD_CONTINUATION.lastIndex = afterBreak
70
- return !KEYWORD_CONTINUATION.test(source)
67
+ return matchEnd(KEYWORD_CONTINUATION, source, afterBreak) === -1
68
+ }
69
+ function endsDirective(source, pos) {
70
+ const c = source[pos]
71
+ if (c === undefined || c === ';' || c === '}') return true
72
+ if (c === '/' && source[pos + 1] === '/') return true
73
+ // A `/*` here spans a newline: like a line break it can end the directive.
74
+ if (c === '/' && source[pos + 1] === '*') return newStatementAfterBreak(source, pos)
75
+ return (c === '\n' || c === '\r' || c === '\u2028' || c === '\u2029') && newStatementAfterBreak(source, pos)
71
76
  }
72
77
 
73
- // Insert CJS_REQUIRE_REPAIR AFTER the Directive Prologue with a leading ';', so a `'use strict'`
74
- // stays strict and a leading string EXPRESSION isn't split mid-expression.
78
+ // AFTER the Directive Prologue, with a leading ';': a `'use strict'` stays strict, a leading string EXPRESSION whole.
75
79
  function repairCjsRequire(source) {
76
80
  if (typeof source !== 'string') return source
77
81
  let i = 0
@@ -80,20 +84,8 @@ function repairCjsRequire(source) {
80
84
  i = nl === -1 ? source.length : nl + 1
81
85
  }
82
86
  for (;;) {
83
- const afterWs = skipSticky(WS_COMMENTS, source, i)
84
- STRING_LITERAL.lastIndex = afterWs
85
- if (STRING_LITERAL.exec(source) === null) break
86
- const afterStr = STRING_LITERAL.lastIndex
87
- const afterTrail = skipSticky(TRAILING_SAME_LINE, source, afterStr)
88
- const c = source[afterTrail]
89
- let isDirective
90
- if (c === undefined || c === ';' || c === '}') isDirective = true
91
- else if (c === '/' && source[afterTrail + 1] === '/') isDirective = true
92
- // A `/*` here is a newline-spanning block comment: like a line break it can end the directive.
93
- else if (c === '/' && source[afterTrail + 1] === '*') isDirective = newStatementAfterBreak(source, afterTrail)
94
- else if (c === '\n' || c === '\r' || c === '\u2028' || c === '\u2029') isDirective = newStatementAfterBreak(source, afterTrail)
95
- else isDirective = false
96
- if (!isDirective) break
87
+ const afterStr = matchEnd(STRING_LITERAL, source, matchEnd(WS_COMMENTS, source, i))
88
+ if (afterStr === -1 || !endsDirective(source, matchEnd(TRAILING_SAME_LINE, source, afterStr))) break
97
89
  i = afterStr
98
90
  }
99
91
  return `${source.slice(0, i)};${CJS_REQUIRE_REPAIR}${source.slice(i)}`
@@ -104,57 +96,33 @@ let state
104
96
  let createdShardDir
105
97
  let createdShardPub
106
98
  let createdShardPubId
107
- // True once artifacts are written; the load hook asserts on it so a late first load can't ship unattested.
99
+ // Latched once artifacts are written, so a late first load can't ship unattested.
108
100
  let saved = false
109
- // Serialized shard text a child last wrote, so a second flush skips an identical re-write.
110
101
  let lastShardWritten
111
- // Set when stasis's own capture/verification rejects something; when set, nothing is written.
102
+ // Set when stasis's own capture/verification rejects something: then nothing is written.
112
103
  let aborted = false
113
104
  // >0 while Node's loader reads a module's source; the --fs hook skips reads taken then.
114
105
  let loadingModule = 0
115
- // True until the first non-builtin load hook fires (entry detection).
116
106
  let entryUnseen = true
117
- // True until the first parent-less resolution -- the CLI entry. Extra preloads (`stasis run
118
- // --import tsx`) resolve against a DIRECTORY parent (the cwd URL, '/'-terminated -- never a
119
- // loadable module) and load BEFORE it: they are runner infrastructure like stasis's own loader.
120
- // Capturing them would misfile the first preload as the entry (initState from ITS package root)
121
- // and pollute the artifact with toolchain files; gating them would break --bundle=load (the
122
- // preload itself must keep loading from disk). Any OTHER pre-entry parent (an [eval] wrapper's
123
- // import) falls through to the normal path and fails closed on assert.ok(state), like a run
124
- // without preloads.
107
+ // Until the CLI entry resolves, preloads (`--import tsx`) resolve from a DIRECTORY parent: runner infrastructure,
108
+ // neither captured (it would misfile the entry) nor gated (a preload loads from disk under --bundle=load).
125
109
  let entryUnresolved = true
126
- // The runner-infrastructure module graph: every URL the preload phase resolved or loaded, plus
127
- // its post-entry descendants (a transformer lazy-loading a plugin). Members pass both hooks
128
- // through unobserved -- but NOT unforgotten:
129
- // - infraSources stashes each infra load's raw {source, format} and infraEdges its outgoing
130
- // resolutions, so that when the APP graph reaches an infra module (its load hook can never
131
- // re-fire -- the module instance is cached) it is PROMOTED into the capture with the exact
132
- // bytes that executed, its own edges replayed transitively. Without promotion the artifact
133
- // would ship a dangling edge and a frozen replay would never verify the file.
134
- // - under --bundle=load, an app edge landing on an infra URL means the cached disk-loaded
135
- // instance shadows the attested bundle bytes: allowed only when they are identical.
110
+ // The infrastructure graph passes both hooks unobserved; its loads and edges are kept for when the app reaches it.
136
111
  const infraUrls = new Set()
137
112
  const infraSources = new Map()
138
113
  const infraEdges = new Map()
139
- // URLs the bundle=load load hook actually served, so the CJS shim can detect a require() that
140
- // executed an attested file from DISK instead (a transplanted require.extensions handler, e.g.
141
- // tsx's '.ts' pipeline, reads and compiles the file itself -- the load hook never fires).
114
+ // So the CJS shim detects an attested file a transplanted require.extensions handler (tsx's) ran from DISK.
142
115
  const servedFromBundle = new Set()
143
116
 
144
- // EXODUS_STASIS_PID = the root stasis's pid; on mismatch we're a child and must not write the
145
- // bundle/lockfile (root owns the artifact; a 2nd writer races). A forked child also relaxes assertEntry.
117
+ // A child (pid mismatch) must not write the artifacts: the root owns them, and a 2nd writer races.
146
118
  const OWN_PID = String(process.pid)
147
- if (!process.env.EXODUS_STASIS_PID) process.env.EXODUS_STASIS_PID = OWN_PID
119
+ process.env.EXODUS_STASIS_PID ||= OWN_PID
148
120
  const isChildProcess = process.env.EXODUS_STASIS_PID !== OWN_PID
149
121
  const forkedChild = isChildProcess && process.channel !== undefined
150
122
 
151
123
  // stasis-core's own package root, so State's backfill captures edges loaded before our hooks registered.
152
124
  const PRELOAD_ROOT = (() => {
153
- try {
154
- return dirname(findPackageJSON(import.meta.url))
155
- } catch {
156
- return undefined
157
- }
125
+ try { return dirname(findPackageJSON(import.meta.url)) } catch { return undefined }
158
126
  })()
159
127
 
160
128
  // A capture step whose rejection must never be written, even if user code swallows the throw.
@@ -167,7 +135,6 @@ function recording(fn) {
167
135
  }
168
136
  }
169
137
 
170
- // nextLoad with `loadingModule` held, so the --fs hook skips the loader's own read of the source.
171
138
  function loadCounted(nextLoad, url, context) {
172
139
  loadingModule++
173
140
  try {
@@ -178,13 +145,12 @@ function loadCounted(nextLoad, url, context) {
178
145
  }
179
146
 
180
147
  const toBuffer = (source) => (Buffer.isBuffer(source) ? source : Buffer.from(source))
148
+ // Node's CJS loader may return source=null and read the file from disk itself.
149
+ const sourceOrDisk = (source, url) => source ?? readFileSync(fileURLToPath(url))
181
150
 
182
- // Child-process capture forwarding (shards), opt-in via --child-process: a capturing child writes a
183
- // signed per-pid shard the root verifies against its own public key before merging. Trust rests on
184
- // that signature, not the dir being secret; shards carry NO bytes (the root re-reads from disk).
185
-
151
+ // --child-process: trust rests on a shard's signature under a key the root minted; shards carry NO bytes.
186
152
  function shardForwardingEnabled() {
187
- return Boolean(state) && state.config.childProcess && (state.config.writeLockfile || state.config.writeBundle)
153
+ return state.config.childProcess && (state.config.writeLockfile || state.config.writeBundle)
188
154
  }
189
155
 
190
156
  function clearShardEnv() {
@@ -198,13 +164,11 @@ function removeShardDir() {
198
164
  }
199
165
 
200
166
  function writeChildShard() {
201
- if (!shardForwardingEnabled()) return
202
167
  const dir = process.env.EXODUS_STASIS_SHARD_DIR
203
168
  const keyB64 = process.env.EXODUS_STASIS_SHARD_KEY
204
169
  if (!dir || !keyB64) return
205
170
  try {
206
- // Sign the exact snapshot string, never a re-stringify, so verify is independent of JSON key
207
- // order; temp + rename so the merge never reads a half-written shard.
171
+ // Sign the exact string, never a re-stringify; temp + rename so the merge never reads half a shard.
208
172
  const shard = state.shardSnapshot()
209
173
  if (shard === lastShardWritten) return
210
174
  const privateKey = createPrivateKey({ key: Buffer.from(keyB64, 'base64'), format: 'der', type: 'pkcs8' })
@@ -215,26 +179,22 @@ function writeChildShard() {
215
179
  writeFileSync(tmpPath, JSON.stringify({ shard, signature }))
216
180
  renameSync(tmpPath, join(dir, `${pubId}-${unique}.json`))
217
181
  lastShardWritten = shard
218
- } catch {
219
- // Best-effort: a child that can't snapshot/sign/write just doesn't contribute.
220
- }
182
+ } catch { /* best-effort: a child that can't snapshot/sign/write just doesn't contribute */ }
221
183
  }
222
184
 
223
- // Cap shard count + size so a hostile/runaway set can't OOM the root.
185
+ // So a hostile/runaway shard set can't OOM the root.
224
186
  const MAX_SHARDS = 4096
225
187
  const MAX_SHARD_BYTES = 64 * 1024 * 1024
226
188
 
227
- // Merge children's shards from `dir`: verify each envelope against our own PUBLIC key, not one from
228
- // the filename. opendir streams the listing so memory stays bounded.
189
+ // Verified against our own PUBLIC key, not one from the filename; opendir keeps memory bounded.
229
190
  function mergeChildShards(dir) {
230
191
  let handle
231
192
  try { handle = opendirSync(dir) } catch { return }
232
193
  const prefix = `${createdShardPubId}-`
233
194
  let count = 0
234
195
  try {
235
- let dirent
236
- while ((dirent = handle.readSync()) !== null) {
237
- const name = dirent.name
196
+ for (let dirent = handle.readSync(); dirent !== null; dirent = handle.readSync()) {
197
+ const { name } = dirent
238
198
  if (!name.startsWith(prefix) || !name.endsWith('.json')) continue
239
199
  if (++count > MAX_SHARDS) break
240
200
  const path = join(dir, name)
@@ -244,91 +204,73 @@ function mergeChildShards(dir) {
244
204
  if (typeof shard !== 'string' || typeof signature !== 'string') continue
245
205
  if (!verify(null, Buffer.from(shard), createdShardPub, Buffer.from(signature, 'base64url'))) continue
246
206
  state.mergeShard(shard)
247
- } catch {
248
- // A malformed/partial shard is skipped; the rest merge.
249
- }
207
+ } catch { /* a malformed/partial shard is skipped */ }
250
208
  }
251
209
  } finally {
252
210
  try { handle.closeSync() } catch { /* best-effort */ }
253
211
  }
254
212
  }
255
213
 
256
- // Install the --fs reader patches. Must run AFTER stasis's own fs snapshots so they never redirect
257
- // stasis's own reads.
258
- function installFsHooksFromConfig() {
259
- const fsMode = state.config.fs
260
- if (!fsMode) return
261
- installFsHooks({
262
- async: fsMode === 'async',
263
- getState: () => state,
264
- isLoadingModule: () => loadingModule > 0,
265
- // Warn on the first taint so the silent discard (reads succeed, exit 0, no artifact) has a clue.
266
- markAborted: (err) => {
267
- if (!aborted) console.warn(`[stasis] --fs: capture aborted, no bundle/lockfile will be written -- ${err?.message ?? err}`)
268
- aborted = true
269
- },
270
- })
271
- }
272
-
273
214
  function initState(root) {
274
215
  state = new State(root, { preload: true, preloadRoot: PRELOAD_ROOT })
275
216
 
276
- installFsHooksFromConfig()
217
+ // AFTER stasis's own fs snapshots, so they never redirect its own reads.
218
+ if (state.config.fs) {
219
+ installFsHooks({
220
+ async: state.config.fs === 'async',
221
+ getState: () => state,
222
+ isLoadingModule: () => loadingModule > 0,
223
+ // Warned, else the discard is silent: reads succeed, exit 0, no artifact.
224
+ markAborted: (err) => {
225
+ if (!aborted) console.warn(`[stasis] --fs: capture aborted, no bundle/lockfile will be written -- ${err?.message ?? err}`)
226
+ aborted = true
227
+ },
228
+ })
229
+ }
277
230
 
278
- // Root + opt-in only, before any child can fork: ALWAYS mint our own dir (OS tmpdir, mkdtemp 0700)
279
- // and keypair, overwriting any inherited/attacker-set env, so we merge only shards we can verify.
231
+ // ALWAYS mint our own dir and keypair, overwriting any inherited/attacker-set env: we merge only what we verify.
280
232
  if (!isChildProcess && shardForwardingEnabled()) {
281
233
  try {
282
234
  const { publicKey, privateKey } = generateKeyPairSync('ed25519')
283
235
  createdShardDir = mkdtempSync(join(tmpdir(), 'stasis-shard-'))
284
236
  createdShardPub = publicKey
285
- createdShardPubId = publicKey.export({ format: 'jwk' }).x // base64url(raw public key)
237
+ createdShardPubId = publicKey.export({ format: 'jwk' }).x
286
238
  process.env.EXODUS_STASIS_SHARD_DIR = createdShardDir
287
239
  // Rides process.env so every transitive descendant inherits; do NOT scrub it downstream.
288
240
  process.env.EXODUS_STASIS_SHARD_KEY = privateKey.export({ type: 'pkcs8', format: 'der' }).toString('base64')
289
241
  } catch {
290
- // Best-effort: clear any inherited (possibly attacker-set) dir/key so descendants don't fall
291
- // back to a channel we never minted.
242
+ // Descendants must not fall back to an inherited channel we never minted.
292
243
  removeShardDir()
293
244
  createdShardDir = createdShardPub = createdShardPubId = undefined
294
245
  clearShardEnv()
295
246
  }
296
247
  } else if (!isChildProcess) {
297
- // Non-capturing root: shed any inherited (possibly attacker-set) shard env.
298
248
  clearShardEnv()
299
249
  }
300
250
 
301
- // Persist on exit unless `aborted` -- deliberately NOT gated on exit code, so a clean capture
302
- // exiting non-zero still persists. Must stay fully synchronous for `exit` to host it.
251
+ // NOT gated on exit code: a clean capture exiting non-zero still persists. Fully synchronous for `exit`.
303
252
  const save = () => {
304
- const writing = state.config.writeLockfile || state.config.writeBundle
305
- // A child forwards a shard instead of writing the artifact (root owns it; a 2nd writer races).
306
253
  if (isChildProcess) {
307
- if (writing && !aborted) writeChildShard()
254
+ if (shardForwardingEnabled() && !aborted) writeChildShard()
308
255
  return
309
256
  }
310
257
  try {
311
258
  if (aborted) return
312
259
  if (createdShardDir) mergeChildShards(createdShardDir)
313
- // write() self-gates the artifact writes, but also VERIFIES in read-only frozen modes, so it
314
- // must run in every mode.
260
+ // In every mode: write() also VERIFIES in read-only frozen modes.
315
261
  state.write()
316
- // Latch only in write modes: a read-only run persists nothing, so a later first load (e.g. a
317
- // require() from another exit handler) is still attested and must not trip the load hook.
318
- if (writing) saved = true
262
+ // A read-only run persists nothing, so a later first load (another exit handler's) is still attested.
263
+ if (state.config.writeLockfile || state.config.writeBundle) saved = true
319
264
  } finally {
320
265
  removeShardDir()
321
266
  }
322
267
  }
323
268
 
324
- // `exit` alone, NOT the beforeExit/exit pair: it runs after every beforeExit handler, so one flush
325
- // there sees strictly more. A process that never reaches `exit` writes nothing.
269
+ // `exit` alone: it runs after every beforeExit handler, so one flush there sees strictly more.
326
270
  process.on('exit', save)
327
271
 
328
- // config.shardSignalFlush (opt-in): flush the shard when a capturing CHILD is ended by SIGTERM
329
- // (jest-worker's forceExit bypasses `exit`), then re-deliver the signal -- unless user code owns
330
- // SIGTERM, then only flush. `userOwnedSigterm` is snapshotted at registration: a `once` that
331
- // already ran is invisible to listenerCount. Must fit forceExit's 500ms window.
272
+ // jest-worker's forceExit bypasses `exit` (500ms window). SIGTERM is re-delivered unless user code owns it,
273
+ // snapshotted now: a `once` that already ran is invisible to listenerCount.
332
274
  if (isChildProcess && shardForwardingEnabled() && state.config.shardSignalFlush) {
333
275
  const userOwnedSigterm = process.listenerCount('SIGTERM') > 0
334
276
  process.once('SIGTERM', () => {
@@ -341,7 +283,6 @@ function initState(root) {
341
283
  }
342
284
  }
343
285
 
344
- // Init from the package root of `url` (the entry), exactly as its live load would.
345
286
  function initStateFromPackage(url) {
346
287
  const pkg = findPackageJSON(url)
347
288
  assert.equal(basename(pkg), 'package.json')
@@ -351,49 +292,34 @@ function initStateFromPackage(url) {
351
292
  function load(url, context, nextLoad) {
352
293
  assert.equal(typeof url, 'string')
353
294
 
354
- // Runner-infrastructure passthrough (see entryUnresolved): a preload's module graph loads
355
- // before the entry (or lazily after, from an infra parent). Stash the raw result so a later
356
- // app-graph edge can promote the module with the exact bytes that executed.
357
- if ((entryUnresolved || infraUrls.has(url)) && !url.startsWith('node:')) {
358
- infraUrls.add(url)
359
- const result = loadCounted(nextLoad, url, context)
360
- if (!infraSources.has(url)) infraSources.set(url, { source: result.source, format: result.format })
361
- return result
362
- }
363
-
364
295
  if (url.startsWith('node:')) {
365
296
  const result = nextLoad(url, context)
366
297
  assert.equal(result.format, 'builtin')
367
298
  return result
368
299
  }
369
300
 
301
+ // Stashed so a later app edge can promote the module with the exact bytes that executed.
302
+ if (entryUnresolved || infraUrls.has(url)) {
303
+ infraUrls.add(url)
304
+ const result = loadCounted(nextLoad, url, context)
305
+ if (!infraSources.has(url)) infraSources.set(url, { source: result.source, format: result.format })
306
+ return result
307
+ }
308
+
370
309
  if (state?.config.loadBundle) {
371
- // node_modules scope serves only nm deps; gate on inNodeModules(), not a raw substring (symlinks).
372
310
  if (!inScope(state, url)) return nextLoad(url, context)
373
311
  const { source, format } = state.getFile(url)
374
- // Cross-check format only when the resolve chain set it; the formats map is itself attested
375
- // against the lockfile at construction. A transforming preload (`stasis run --import tsx`)
376
- // legitimately asks for an attested '-typescript' file as its post-erasure family -- serve
377
- // the chain's view then (the transformer above us turns the raw source into it).
378
- let serveFormat = format
379
- if (context.format != null) {
380
- if (context.format === erasedTypeScriptFormat(format)) serveFormat = context.format
381
- else assert.equal(format, context.format)
382
- }
383
- // Trust gate: only serve a file whose attested format Node can execute; everything else fails closed.
312
+ // A transforming preload (`--import tsx`) asks for a '-typescript' file as its post-erasure family.
313
+ if (context.format != null && context.format !== erasedTypeScriptFormat(format)) assert.equal(format, context.format)
384
314
  if (!NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
385
315
  servedFromBundle.add(url)
386
- // node:59666: a load-hook-supplied CJS source gets a re-invented require() missing .cache/.extensions.
387
- return { source: CJS_FORMATS.has(format) ? repairCjsRequire(source) : source, format: serveFormat, shortCircuit: true }
316
+ return { source: CJS_FORMATS.has(format) ? repairCjsRequire(source) : source, format: context.format ?? format, shortCircuit: true }
388
317
  }
389
318
 
390
319
  const result = loadCounted(nextLoad, url, context)
391
- let { source } = result
392
320
  const { format } = result
393
321
  assert.notEqual(format, 'builtin')
394
-
395
- // Node's CJS loader may return source=null and read from disk itself; capture it for the bundle
396
- if (source == null && format === 'commonjs') source = readFileSync(fileURLToPath(url))
322
+ const source = format === 'commonjs' ? sourceOrDisk(result.source, url) : result.source
397
323
 
398
324
  const isEntry = entryUnseen
399
325
  entryUnseen = false
@@ -405,67 +331,49 @@ function load(url, context, nextLoad) {
405
331
  return result
406
332
  }
407
333
 
408
- // Fold a runner-infrastructure module into the capture: an app-graph edge reached a module the
409
- // preload phase already executed, so its load hook can never re-fire (the instance is cached) and
410
- // skipping it would ship a dangling edge a frozen replay never verifies. addFile re-verifies the
411
- // stashed bytes against disk (and against the lockfile/bundle in frozen modes), and the module's
412
- // own remembered resolutions replay transitively so its dependencies aren't dangling either.
334
+ // The app reached a module a preload executed, whose load hook can't re-fire: else a dangling edge ships.
413
335
  function promoteInfraUrl(url, { isEntry = false } = {}) {
414
336
  if (!infraUrls.delete(url)) return
415
337
  const stashed = infraSources.get(url)
338
+ if (stashed === undefined) return
416
339
  infraSources.delete(url)
417
- // Same disk fallback as the live load path: Node's CJS loader may return source=null.
418
- const source = stashed?.source ?? readFileSync(fileURLToPath(url))
419
- recording(() => state.addFile(url, { source, format: stashed?.format ?? undefined, isEntry }))
340
+ const source = sourceOrDisk(stashed.source, url)
341
+ recording(() => state.addFile(url, { source, format: stashed.format ?? undefined, isEntry }))
420
342
  const edges = infraEdges.get(url)
421
343
  infraEdges.delete(url)
422
344
  for (const [specifier, edge] of edges ?? []) {
423
345
  recording(() => state.addImport(url, specifier, edge.url, edge.context))
424
- if (infraSources.has(edge.url)) promoteInfraUrl(edge.url)
425
- else infraUrls.delete(edge.url) // resolved but never loaded: a live load would capture it
346
+ promoteInfraUrl(edge.url)
426
347
  }
427
348
  }
428
349
 
429
- // Under --bundle=load, an app edge landing on a module the preload phase already loaded means the
430
- // CACHED disk-loaded instance shadows whatever the hooks would serve from the bundle: allowed
431
- // only when the executed bytes and the attested bytes are identical, else fail closed.
350
+ // A preload's CACHED disk-loaded instance shadows what the hooks would serve: allowed only for identical bytes.
432
351
  function assertInfraMatchesBundle(url) {
433
352
  if (!infraUrls.has(url)) return
434
353
  const stashed = infraSources.get(url)
435
354
  if (stashed === undefined) { infraUrls.delete(url); return } // resolved but never loaded: the hooks will serve it
436
- const executed = toBuffer(stashed.source ?? readFileSync(fileURLToPath(url)))
355
+ const executed = toBuffer(sourceOrDisk(stashed.source, url))
437
356
  if (!executed.equals(toBuffer(state.getFile(url).source))) {
438
- throw new Error(
439
- `[stasis] cannot serve '${url}' from the bundle: a preload already executed it from disk ` +
440
- `before the entry, and those bytes differ from the attested ones -- refusing the divergent ` +
441
- `cached instance`
442
- )
357
+ throw new Error(`[stasis] cannot serve '${url}' from the bundle: a preload already executed it from disk ` +
358
+ 'before the entry, and those bytes differ from the attested ones -- refusing the divergent cached instance')
443
359
  }
444
360
  }
445
361
 
446
362
  function resolve(specifier, context, nextResolve) {
447
- // Runner-infrastructure passthrough (see entryUnresolved): a preload's graph resolves from a
448
- // DIRECTORY parent (the cwd URL Node uses for each `--import` specifier -- a directory is never
449
- // a loadable module, so this cannot shadow an app parent) or from a module already tracked as
450
- // infrastructure. The first parent-less resolution is still the entry, and any other pre-entry
451
- // parent (an [eval] wrapper's import) falls through to fail closed below. Each passed-through
452
- // edge is remembered -- not recorded -- so promoteInfraUrl can replay it if the app graph
453
- // reaches this module later.
454
- const infraParent = context.parentURL !== undefined
455
- && (infraUrls.has(context.parentURL) || (entryUnresolved && context.parentURL.endsWith('/')))
456
- if (infraParent) {
363
+ const { parentURL, conditions, importAttributes } = context
364
+ // A DIRECTORY parent can't shadow an app parent; any other pre-entry parent ([eval]'s import) fails closed below.
365
+ if (parentURL !== undefined && (infraUrls.has(parentURL) || (entryUnresolved && parentURL.endsWith('/')))) {
457
366
  const res = nextResolve(specifier)
458
367
  if (!res.url.startsWith('node:')) {
459
368
  infraUrls.add(res.url)
460
- if (infraUrls.has(context.parentURL)) {
461
- // Last-write-wins per specifier, like observeResolution: only the final target can be the
462
- // one a cached instance pins.
463
- nestedMap(infraEdges, context.parentURL).set(specifier, { url: res.url, context: { conditions: context.conditions, format: res.format, importAttributes: context.importAttributes } })
369
+ if (infraUrls.has(parentURL)) {
370
+ // Last-write-wins: only the final target can be the one a cached instance pins.
371
+ nestedMap(infraEdges, parentURL).set(specifier, { url: res.url, context: { conditions, format: res.format, importAttributes } })
464
372
  }
465
373
  }
466
374
  return res
467
375
  }
468
- if (entryUnresolved && !context.parentURL) entryUnresolved = false
376
+ if (entryUnresolved && !parentURL) entryUnresolved = false
469
377
 
470
378
  if (isBuiltin(specifier)) {
471
379
  const res = nextResolve(specifier)
@@ -473,37 +381,31 @@ function resolve(specifier, context, nextResolve) {
473
381
  return res
474
382
  }
475
383
 
476
- if (context.importAttributes !== undefined) {
384
+ if (importAttributes !== undefined) {
477
385
  const expectedAttrs = Object.create(null) // saving not supported yet; enforce expected attrs
478
- if (extname(specifier) === '.json' && context.importAttributes?.type) expectedAttrs.type = 'json'
479
- assert.deepStrictEqual(context.importAttributes, expectedAttrs)
386
+ if (extname(specifier) === '.json' && importAttributes?.type) expectedAttrs.type = 'json'
387
+ assert.deepStrictEqual(importAttributes, expectedAttrs)
480
388
  }
481
389
 
482
- const { parentURL, conditions, importAttributes } = context
483
-
484
390
  // Full-scope load serves the entry from the bundle, so state must exist before nextResolve.
485
391
  if (!state && !parentURL && process.env.EXODUS_STASIS_BUNDLE === 'load'
486
- && process.env.EXODUS_STASIS_SCOPE !== 'node_modules') {
487
- initState(process.cwd())
488
- }
392
+ && process.env.EXODUS_STASIS_SCOPE !== 'node_modules') initState(process.cwd())
489
393
 
490
394
  if (state?.config.loadBundle) {
491
- // nm scope defers non-nm parents to Node's resolver; gate on inNodeModules() to cover symlinks.
395
+ // inNodeModules(), not a raw substring: a symlinked workspace source is read from disk.
492
396
  if (!state.config.full && !(parentURL && state.inNodeModules(parentURL))) return nextResolve(specifier)
493
- // A bare specifier with a parent resolves from the recorded import map; otherwise skip
494
- // nextResolve so the entry needn't be on disk.
397
+ // The entry skips nextResolve, so it needn't be on disk.
398
+ let url
399
+ let format
495
400
  if (parentURL && !specifier.startsWith('file:')) {
496
- const { url, format } = state.getImport(parentURL, specifier, { conditions, importAttributes })
497
- // Friendlier error at resolve time; the load gate is the load-bearing one.
498
- if (format != null && !NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
499
- assertInfraMatchesBundle(url)
500
- return { url, format, importAttributes: undefined, shortCircuit: true }
401
+ ({ url, format } = state.getImport(parentURL, specifier, { conditions, importAttributes }))
402
+ } else {
403
+ url = specifier.startsWith('file:') ? specifier : pathToFileURL(resolvePath(process.cwd(), specifier)).toString()
404
+ // A forked child's main module isn't a declared CLI entry (getFile still fails closed).
405
+ if (!parentURL && state.config.full && !forkedChild) state.assertEntry(url)
406
+ format = state.getFormat(url)
501
407
  }
502
- const url = specifier.startsWith('file:') ? specifier : pathToFileURL(resolvePath(process.cwd(), specifier)).toString()
503
- // A forked child's main module isn't a declared CLI entry, so skip assertEntry (getFile still
504
- // fails closed on anything unattested).
505
- if (!parentURL && state.config.full && !forkedChild) state.assertEntry(url)
506
- const format = state.getFormat(url)
408
+ // Friendlier error at resolve time; the load gate is the load-bearing one.
507
409
  if (format != null && !NODE_FORMATS.has(format)) refuseNonNodeFormat(format, url)
508
410
  assertInfraMatchesBundle(url)
509
411
  return { url, format, importAttributes: undefined, shortCircuit: true }
@@ -514,8 +416,6 @@ function resolve(specifier, context, nextResolve) {
514
416
 
515
417
  assert.equal(res.importAttributes, undefined) // unsupported yet
516
418
  if (parentURL) assert.ok(state)
517
- // The app graph reached a module the preload phase already loaded: fold it (and transitively
518
- // its own graph) into the capture, since its load hook can never re-fire.
519
419
  if (infraUrls.has(url)) {
520
420
  if (infraSources.has(url)) {
521
421
  // The ENTRY itself was preloaded (a wrapper importing the app): init from its package root.
@@ -524,27 +424,25 @@ function resolve(specifier, context, nextResolve) {
524
424
  if (isEntry) entryUnseen = false
525
425
  promoteInfraUrl(url, { isEntry })
526
426
  } else {
527
- // Resolved during the preload phase but never loaded: the app's own load will capture it.
427
+ // Never loaded: the app's own load will capture it.
528
428
  infraUrls.delete(url)
529
429
  }
530
430
  }
531
- // Parent-less = the entry: recorded via addFile/promotion above, never as an edge (addImport
532
- // requires a parent, and state can exist here after an entry promotion).
431
+ // The entry is recorded by addFile/promotion, never as an edge.
533
432
  if (state && parentURL) recording(() => state.addImport(parentURL, specifier, url, { conditions, format, importAttributes }))
534
433
  return res
535
434
  }
536
435
 
537
436
  let installed = false
538
437
 
539
- // Exported so plugins.js can detect "under the stasis loader" before the lazy initState fires.
438
+ // So plugins.js can detect the loader before the lazy initState fires.
540
439
  export function isLoaderInstalled() {
541
440
  return installed
542
441
  }
543
442
 
544
- // For plugins.js when a plugin constructor runs ahead of the load hook.
443
+ // For a plugin constructor run ahead of the load hook.
545
444
  export function ensureStateForLoader() {
546
- if (state) return
547
- initState(process.cwd())
445
+ if (!state) initState(process.cwd())
548
446
  }
549
447
 
550
448
  // Separate from the --import entry points so a host can compose setup before the hooks register.
@@ -553,11 +451,10 @@ export function install() {
553
451
  installed = true
554
452
  registerHooks({ load, resolve })
555
453
  patchCjsResolution()
556
- // The --fs reader patches are deferred to initState (their mode may come from stasis.config.json).
454
+ // The --fs patches wait for initState: their mode may come from stasis.config.json.
557
455
  }
558
456
 
559
- // registerHooks doesn't intercept the require() the ESM->CJS translator builds for a CJS module (it
560
- // resolves through Module._resolveFilename against disk), so shim that to resolve from the import map.
457
+ // registerHooks doesn't intercept the require() the ESM->CJS translator builds, which resolves against disk.
561
458
  function patchCjsResolution() {
562
459
  const original = Module._resolveFilename
563
460
  Module._resolveFilename = function (request, parent, ...rest) {
@@ -566,7 +463,7 @@ function patchCjsResolution() {
566
463
  if (typeof parent?.filename === 'string') {
567
464
  const parentURL = pathToFileURL(parent.filename).toString()
568
465
  if (inScope(state, parentURL)) {
569
- // Module._resolveFilename resolves for require(), whose target settles a divergent edge.
466
+ // For require(), whose target settles a divergent edge.
570
467
  const resolved = state.resolveBundled(parentURL, request, { conditions: ['require'] })
571
468
  if (resolved !== undefined) {
572
469
  assertInfraMatchesBundle(pathToFileURL(resolved).toString())
@@ -574,10 +471,8 @@ function patchCjsResolution() {
574
471
  }
575
472
  }
576
473
  } else if (isAbsolute(request)) {
577
- // NO parent, absolute request: Node's ESM<->CJS interop re-enters the CJS loader with hooks
578
- // SKIPPED, so this shim is the only interception point. hasFsFileContent (not a dir/stat
579
- // record) keeps a listing or payload-free stat from hijacking resolution. Node 24.14-24.17
580
- // re-resolve here every commonjs-sync eval; the no-parent shape survives on >=24.18 too.
474
+ // Node's ESM<->CJS interop re-enters the CJS loader with hooks SKIPPED (every commonjs-sync eval on
475
+ // 24.14-24.17), so only this shim intercepts. hasFsFileContent: a listing or stat record never resolves.
581
476
  const url = pathToFileURL(request).toString()
582
477
  if (inScope(state, url) && state.hasFsFileContent(url)) {
583
478
  assertInfraMatchesBundle(url)
@@ -593,12 +488,8 @@ function patchCjsResolution() {
593
488
  return resolved
594
489
  }
595
490
 
596
- // Module._load's cache fast path can skip _resolveFilename, so a second require() of the same
597
- // target goes unrecorded: force it through the PROPERTY (our shim) to observe the edge. This is
598
- // also the one spot that sees every ACTUAL CJS execution, hook-served or not, so it anchors the
599
- // executed-file reconciliation for transplanted require.extensions handlers (a transforming
600
- // preload's CJS pipeline, e.g. `--import tsx` compiling .ts, reads and compiles files itself --
601
- // the load hook chain never fires for them).
491
+ // Module._load's cache fast path can skip _resolveFilename. It also sees every ACTUAL CJS execution, so it
492
+ // catches transplanted require.extensions handlers (`--import tsx` compiling .ts) the load hooks never see.
602
493
  const originalLoad = Module._load
603
494
  Module._load = function (request, parent, ...rest) {
604
495
  let resolvedUrl
@@ -608,23 +499,15 @@ function patchCjsResolution() {
608
499
  if (typeof resolved === 'string' && isAbsolute(resolved)) resolvedUrl = pathToFileURL(resolved).toString()
609
500
  }
610
501
  if (resolvedUrl !== undefined && !state.config.loadBundle) {
611
- // A require() executes its target: remember it so write() can attest/verify anything the
612
- // load hook never saw, and fold in a module the preload phase already executed.
613
502
  state.observeExecution(resolvedUrl)
614
- if (infraSources.has(resolvedUrl)) promoteInfraUrl(resolvedUrl)
615
- else infraUrls.delete(resolvedUrl)
503
+ promoteInfraUrl(resolvedUrl)
616
504
  }
617
505
  const result = originalLoad.call(this, request, parent, ...rest)
618
- // Under --bundle=load, an attested source the load hook never served just executed from DISK
619
- // (a transplanted require.extensions handler bypasses the hook chain): fail closed -- after
620
- // the fact, but before anything can trust the run.
506
+ // An attested source the load hook never served ran from DISK: fail closed, before anything trusts the run.
621
507
  if (resolvedUrl !== undefined && state.config.loadBundle
622
508
  && !servedFromBundle.has(resolvedUrl) && state.isBundledSource(resolvedUrl)) {
623
- throw new Error(
624
- `[stasis] '${resolvedUrl}' executed from disk, bypassing the attested bundle -- a ` +
625
- `require() pipeline transplanted by a preload (e.g. tsx compiling CJS TypeScript) ` +
626
- `cannot serve bundle bytes and is refused under --bundle=load`
627
- )
509
+ throw new Error(`[stasis] '${resolvedUrl}' executed from disk, bypassing the attested bundle -- a require() pipeline ` +
510
+ 'transplanted by a preload (e.g. tsx compiling CJS TypeScript) cannot serve bundle bytes and is refused under --bundle=load')
628
511
  }
629
512
  return result
630
513
  }