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

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.
@@ -6,7 +6,9 @@ import { once } from 'node:events'
6
6
  import { fileURLToPath } from 'node:url'
7
7
  import { basename, resolve } from 'node:path'
8
8
  import { existsSync, realpathSync } from 'node:fs'
9
+ import { constants as osConstants } from 'node:os'
9
10
  import assert from 'node:assert/strict'
11
+ import { parseBrotliQuality } from '../src/util.js'
10
12
  import pkg from '../package.json' with { type: 'json' }
11
13
 
12
14
  const argv = [...process.argv]
@@ -19,7 +21,7 @@ assert(basename(jsname) === 'stasis-core' || pathsEqual(jsname, fileURLToPath(im
19
21
 
20
22
  function usage(prefix = '') {
21
23
  console.error(`${prefix}\nUsage:
22
- stasis-core run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|frozen|ignore)] [--bundle-file=path/to/bundle.br] [--resources-bundle-file=path/to/resources.br] [--dependencies] [--child-process] [--fs=(sync|async)] [--resources=ext,ext] path/to/file.js ...
24
+ stasis-core run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|frozen|ignore)] [--bundle-file=path/to/bundle.br] [--resources-bundle-file=path/to/resources.br] [--dependencies] [--child-process] [--fs=(sync|async)] [--resources=ext,ext] [--brotli-quality=0..11] path/to/file.js ...
23
25
  stasis-core prune [path/to/project]
24
26
  `.trim())
25
27
  process.exit(1)
@@ -38,7 +40,7 @@ if (command === '-v' || command === '--version') {
38
40
  process.exit(0)
39
41
  } else if (command === 'run') {
40
42
  const flags = []
41
- const valueFlags = new Set(['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--resources'])
43
+ const valueFlags = new Set(['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--resources', '--brotli-quality'])
42
44
  while (argv.length > 0 && (argv[0].startsWith('-') || valueFlags.has(flags.at(-1)))) {
43
45
  flags.push(argv.shift())
44
46
  }
@@ -53,6 +55,7 @@ if (command === '-v' || command === '--version') {
53
55
  'child-process': { type: 'boolean' },
54
56
  fs: { type: 'string' },
55
57
  resources: { type: 'string' },
58
+ 'brotli-quality': { type: 'string' },
56
59
  }
57
60
 
58
61
  let values
@@ -87,10 +90,19 @@ if (command === '-v' || command === '--version') {
87
90
  // --resources: comma-separated extension/filename allowlist for `--fs` resource captures
88
91
  // (e.g. png,svg,LICENSE). The child's Config validates each entry via parseResourcesOption.
89
92
  const resources = values.resources ?? ''
93
+ // --brotli-quality: bundle compression quality (0..11; unset = brotli's default 11).
94
+ let brotliQuality
95
+ if (values['brotli-quality'] !== undefined) {
96
+ try {
97
+ brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
98
+ } catch (cause) {
99
+ usage(`Error: ${cause.message}`)
100
+ }
101
+ }
90
102
  // --child-process: forward forked-child (e.g. Metro transform worker) capture to the root
91
103
  // via per-pid shards. Opt-in -- it stands up a process-coordination channel, off by default.
92
104
  const childProcess = values['child-process'] ? '1' : ''
93
- console.warn('[stasis-core] Running stasis with config:', { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...(values.fs && { fs: values.fs }), ...(resources && { resources }) })
105
+ console.warn('[stasis-core] Running stasis with config:', { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...(values.fs && { fs: values.fs }), ...(resources && { resources }), ...(brotliQuality !== undefined && { brotliQuality }) })
94
106
  if (debug) console.warn(`[stasis-core] Warning: stasis debug mode active`)
95
107
  setEnv('EXODUS_STASIS_LOCK', lock)
96
108
  setEnv('EXODUS_STASIS_SCOPE', scope)
@@ -101,10 +113,14 @@ if (command === '-v' || command === '--version') {
101
113
  setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
102
114
  setEnv('EXODUS_STASIS_FS', captureFs)
103
115
  setEnv('EXODUS_STASIS_RESOURCES', resources)
116
+ // Only set when given, so an ambient EXODUS_STASIS_BROTLI_QUALITY still passes through
117
+ // to the child (an unconditional setEnv('') would reject it as a conflict).
118
+ if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
104
119
  const nodeArgs = ['--import', import.meta.resolve('../src/loader.js')]
105
120
  const child = spawn(process.execPath, [...nodeArgs, ...argv], { stdio: 'inherit' })
106
- const [code] = await once(child, 'close')
107
- process.exitCode = code
121
+ const [code, signal] = await once(child, 'close')
122
+ // code is null when the child died from a signal; report 128+signo (shell convention) instead of the implicit 0
123
+ process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
108
124
  } else if (command === 'prune') {
109
125
  if (argv.length > 1) usage('Error: prune takes at most one path argument')
110
126
  const root = argv[0] ? resolve(argv[0]) : process.cwd()
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/stasis-core",
3
- "version": "1.0.0-beta.0",
3
+ "version": "1.0.0-beta.2",
4
4
  "description": "Zero-dependency stasis runtime",
5
5
  "type": "module",
6
6
  "exports": {
package/src/brotli.js CHANGED
@@ -1,21 +1,28 @@
1
1
  import { constants as zlibConstants } from 'node:zlib'
2
2
 
3
- import { assert } from './util.js'
3
+ import { assert, isBrotliQuality, parseBrotliQuality } from './util.js'
4
4
 
5
5
  // Brotli's default quality is 11 (max) and the encoder is superlinear in input
6
- // size, so on a multi-MB source bundle it dominates write time. Tests that
7
- // bundle real-world dependency trees can override this via the env var to keep
8
- // runs fast; the output is still a valid .br at any quality. Production code
9
- // pays the default cost in exchange for the best ratio.
6
+ // size, so on a multi-MB source bundle it dominates write time. The quality is
7
+ // tunable via `quality` (an integer 0..11, typically config.brotliQuality) or the
8
+ // env var -- which must agree when both are set; the output is still a valid .br
9
+ // at any quality. Production code pays the default cost for the best ratio.
10
10
  //
11
11
  // Kept out of `util.js` so that importing the generic helpers there (`sortPaths`,
12
12
  // `assertRealPathWithinBase`, …) doesn't transitively load `node:zlib`. Only the
13
13
  // code that actually compresses a bundle (`state.js`, `stasis bundle`) reaches
14
14
  // for this, and that code already imports zlib directly.
15
- export function brotliOptions() {
15
+ export function brotliOptions(quality) {
16
+ if (quality !== undefined) {
17
+ assert(isBrotliQuality(quality), `brotli quality must be an integer 0..11, got ${quality}`)
18
+ }
16
19
  const raw = process.env.EXODUS_STASIS_BROTLI_QUALITY
17
- if (!raw) return undefined
18
- const n = Number(raw)
19
- assert(Number.isInteger(n) && n >= 0 && n <= 11, `EXODUS_STASIS_BROTLI_QUALITY must be an integer 0..11, got ${raw}`)
20
- return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: n } }
20
+ if (raw) {
21
+ const n = parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', raw)
22
+ assert(quality === undefined || quality === n,
23
+ `brotli quality ${quality} conflicts with EXODUS_STASIS_BROTLI_QUALITY=${raw}`)
24
+ quality = n
25
+ }
26
+ if (quality === undefined) return undefined
27
+ return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: quality } }
21
28
  }
package/src/bundle.js CHANGED
@@ -113,7 +113,13 @@ export class Bundle {
113
113
  for (const [file, format] of Object.entries(json.formats)) {
114
114
  assert(!posixPathEscapes(file))
115
115
  assert(KNOWN_FORMATS.has(format), `unknown format '${format}' for ${file}`)
116
- formats.set(file, format)
116
+ // The project root's `directory` listing is keyed '.' -- bundles written before
117
+ // that normalization keyed it '' (see moduleFileKey), which no lookup ever hits
118
+ // again at load. Normalize on parse so those artifacts keep serving; the alias
119
+ // makes '' and '.' the SAME key, so both appearing is a duplicate -- fail closed.
120
+ const key = file === '' ? '.' : file
121
+ assert(!formats.has(key), `duplicate format key '${key}'`)
122
+ formats.set(key, format)
117
123
  }
118
124
 
119
125
  const modules = new Map()
@@ -125,7 +131,7 @@ export class Bundle {
125
131
  assert(typeof json.modules === 'object' && json.modules !== null)
126
132
  for (const [dir, info] of Object.entries(json.modules)) {
127
133
  assert(dir.includes('node_modules'))
128
- assert(!dir.startsWith('..'))
134
+ assert(!posixPathEscapes(dir))
129
135
  assert(info?.name && info.version && info.files)
130
136
  modules.set(dir, normalize(info))
131
137
  }
@@ -134,7 +140,7 @@ export class Bundle {
134
140
  assert(json.sources && typeof json.sources === 'object')
135
141
  for (const [dir, info] of Object.entries(json.sources)) {
136
142
  assert(!dir.includes('node_modules'))
137
- assert(!dir.startsWith('..'))
143
+ assert(!posixPathEscapes(dir))
138
144
  assert(info?.name && info.version && info.files)
139
145
  modules.set(dir, normalize(info))
140
146
  }
@@ -166,15 +172,18 @@ export class Bundle {
166
172
  assert(json.sources === undefined)
167
173
  }
168
174
  for (const [, { files }] of modules) {
169
- for (const rel of Object.keys(files)) assert(!rel.startsWith('..'))
175
+ // posixPathEscapes (not a '..' prefix check) so a mid-path escape or an
176
+ // absolute path fails too, matching Lockfile.parse. rel === '' (a
177
+ // `directory` capture keyed at a module root) normalizes to '.' and passes.
178
+ for (const rel of Object.keys(files)) assert(!posixPathEscapes(rel))
170
179
  }
171
180
  } else {
172
181
  // v0 legacy: flat sources at top level, regrouped by inferred module dir.
173
182
  assert(json.sources)
174
183
  for (const [path, content] of Object.entries(json.sources)) {
175
- assert(!path.startsWith('..'))
184
+ assert(!posixPathEscapes(path))
176
185
  const { dir, rel, name } = inferModuleDir(path)
177
- assert(!dir.startsWith('..') && !rel.startsWith('..'))
186
+ assert(!posixPathEscapes(dir) && !posixPathEscapes(rel))
178
187
  if (!modules.has(dir)) modules.set(dir, { name, version: null, files: Object.create(null) })
179
188
  modules.get(dir).files[rel] = content
180
189
  }
package/src/config.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import assert from 'node:assert/strict'
2
2
 
3
3
  import { canonicalizePath } from './state-util.js'
4
- import { extSetsEqual, parseResourcesOption } from './util.js'
4
+ import { extSetsEqual, isBrotliQuality, parseBrotliQuality, parseResourcesOption } from './util.js'
5
5
 
6
6
  const VALID_SCOPE = new Set(['node_modules', 'full'])
7
7
  const VALID_LOCK = new Set(['none', 'ignore', 'add', 'replace', 'frozen'])
@@ -16,7 +16,14 @@ export const DEFAULT_LOCK = 'add'
16
16
  export const DEFAULT_BUNDLE = 'none'
17
17
  export const DEFAULT_SCOPE = 'full'
18
18
 
19
- const envBool = (value) => Boolean(value && value !== '0')
19
+ // Strict boolean env parsing: ''/'0'/'false' -> false, '1'/'true' -> true. Anything else
20
+ // ('no', 'off', ...) throws -- a truthiness parse would read those as *enabling* the
21
+ // toggle, and a misconfigured env var should fail loudly, not silently flip a feature on.
22
+ const envBool = (name, value) => {
23
+ if (value === '' || value === '0' || value === 'false') return false
24
+ if (value === '1' || value === 'true') return true
25
+ throw new RangeError(`${name} must be ''/'0'/'false' or '1'/'true' (got '${value}')`)
26
+ }
20
27
 
21
28
  // EXODUS_STASIS_RESOURCES is a comma-separated extension list; split + trim + drop
22
29
  // empties so '' and ' png , svg ' normalize predictably (parseResourcesOption then
@@ -79,10 +86,12 @@ export class Config {
79
86
  #resources
80
87
  #debug
81
88
  #childProcess
89
+ #shardSignalFlush
82
90
  #fs
91
+ #brotliQuality
83
92
 
84
93
  // Options match the CLI flags (scope/lock/lockFile/bundle/bundleFile/resourcesBundleFile/debug/
85
- // resources/childProcess/fs).
94
+ // resources/childProcess/fs/brotliQuality).
86
95
  // Env vars take effect at construction time; if both env and an option are set they must
87
96
  // agree. Likewise, any explicit constructor option is treated as authoritative: a later
88
97
  // `loadConfig` call (which reads stasis.config.json) must agree with it -- the alternative
@@ -90,9 +99,9 @@ export class Config {
90
99
  // was a footgun the CLI couldn't detect, since the flag was happily accepted
91
100
  // and then quietly ignored.
92
101
  constructor(options = {}) {
93
- const { scope, lock, lockFile, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess, fs, ...rest } = options
102
+ const { scope, lock, lockFile, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess, fs, brotliQuality, ...rest } = options
94
103
  assert.equal(Object.keys(rest).length, 0, `Unknown Config options: ${Object.keys(rest).join(', ')}`)
95
- this.#explicit = { scope, lock, lockFile, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess, fs }
104
+ this.#explicit = { scope, lock, lockFile, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess, fs, brotliQuality }
96
105
 
97
106
  this.#env = {
98
107
  scope: process.env.EXODUS_STASIS_SCOPE || undefined,
@@ -104,7 +113,9 @@ export class Config {
104
113
  debug: process.env.EXODUS_STASIS_DEBUG || undefined,
105
114
  resources: process.env.EXODUS_STASIS_RESOURCES || undefined,
106
115
  childProcess: process.env.EXODUS_STASIS_CHILD_PROCESS || undefined,
116
+ shardSignalFlush: process.env.EXODUS_STASIS_SHARD_SIGNAL_FLUSH || undefined,
107
117
  fs: process.env.EXODUS_STASIS_FS || undefined,
118
+ brotliQuality: process.env.EXODUS_STASIS_BROTLI_QUALITY || undefined,
108
119
  }
109
120
 
110
121
  try {
@@ -121,12 +132,15 @@ export class Config {
121
132
  assert.equal(this.#env.resourcesBundleFile, resourcesBundleFile)
122
133
  }
123
134
  if (this.#env.debug !== undefined && debug !== undefined) {
124
- assert.equal(envBool(this.#env.debug), debug)
135
+ assert.equal(envBool('EXODUS_STASIS_DEBUG', this.#env.debug), debug)
125
136
  }
126
137
  if (this.#env.childProcess !== undefined && childProcess !== undefined) {
127
- assert.equal(envBool(this.#env.childProcess), childProcess)
138
+ assert.equal(envBool('EXODUS_STASIS_CHILD_PROCESS', this.#env.childProcess), childProcess)
128
139
  }
129
140
  if (this.#env.fs !== undefined && fs !== undefined) assert.equal(this.#env.fs, fs)
141
+ if (this.#env.brotliQuality !== undefined && brotliQuality !== undefined) {
142
+ assert.equal(parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', this.#env.brotliQuality), brotliQuality)
143
+ }
130
144
  // Compare parsed sets, not the raw strings: ['png','svg'] and 'svg,png' are the
131
145
  // same allowlist. An empty/unset env var is "no env opinion" (handled by `||
132
146
  // undefined` above), so this only fires on two genuinely different non-empty lists.
@@ -146,10 +160,19 @@ export class Config {
146
160
  this.#bundle = this.#env.bundle || bundle || DEFAULT_BUNDLE
147
161
  this.#bundleFile = this.#env.bundleFile || bundleFile || undefined
148
162
  this.#resourcesBundleFile = this.#env.resourcesBundleFile || resourcesBundleFile || undefined
149
- this.#debug = this.#env.debug !== undefined ? envBool(this.#env.debug) : (debug ?? false)
150
- this.#childProcess = this.#env.childProcess !== undefined ? envBool(this.#env.childProcess) : (childProcess ?? false)
163
+ this.#debug = this.#env.debug !== undefined ? envBool('EXODUS_STASIS_DEBUG', this.#env.debug) : (debug ?? false)
164
+ this.#childProcess = this.#env.childProcess !== undefined ? envBool('EXODUS_STASIS_CHILD_PROCESS', this.#env.childProcess) : (childProcess ?? false)
165
+ // Env-only (no option, no stasis.config.json key): shard-channel plumbing a parent
166
+ // process sets for its descendants, not a user-facing knob -- see the getter.
167
+ this.#shardSignalFlush = this.#env.shardSignalFlush !== undefined
168
+ ? envBool('EXODUS_STASIS_SHARD_SIGNAL_FLUSH', this.#env.shardSignalFlush)
169
+ : false
151
170
  // env wins over the option, like scope/lock/bundle; undefined means "fs untouched" (off).
152
171
  this.#fs = this.#env.fs || fs || undefined
172
+ // env wins over the option; no `||` chaining -- 0 is a valid quality and falsy.
173
+ this.#brotliQuality = this.#env.brotliQuality !== undefined
174
+ ? parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', this.#env.brotliQuality)
175
+ : brotliQuality
153
176
  // env wins over the option (it's the process-wide signal); parseResourcesOption
154
177
  // normalizes both to a Set of lowercase extensions/filenames, or empty when neither set.
155
178
  this.#resources = parseResourcesOption(
@@ -168,6 +191,11 @@ export class Config {
168
191
  assert.ok(VALID_BUNDLE.has(this.#bundle), `Invalid bundle: ${this.#bundle}`)
169
192
  assert.equal(typeof this.#debug, 'boolean', 'debug must be a boolean')
170
193
  assert.equal(typeof this.#childProcess, 'boolean', 'childProcess must be a boolean')
194
+ // A write-side knob; like bundleFile, inert-but-harmless under read-only modes
195
+ // (the same stasis.config.json serves capture and load runs).
196
+ if (this.#brotliQuality !== undefined && !isBrotliQuality(this.#brotliQuality)) {
197
+ throw new RangeError(`brotliQuality must be an integer 0..11 (got ${JSON.stringify(this.#brotliQuality)})`)
198
+ }
171
199
  if (this.#fs !== undefined) {
172
200
  assert.ok(VALID_FS.has(this.#fs), `Invalid fs: ${this.#fs}`)
173
201
  // --fs patches the fs readers to capture into the bundle (add/replace) or serve them
@@ -246,6 +274,7 @@ export class Config {
246
274
  debug = this.#debug,
247
275
  childProcess = this.#childProcess,
248
276
  fs = this.#fs,
277
+ brotliQuality = this.#brotliQuality,
249
278
  resources,
250
279
  ...rest
251
280
  } = JSON.parse(json)
@@ -261,6 +290,7 @@ export class Config {
261
290
  this.#debug = debug
262
291
  this.#childProcess = childProcess
263
292
  this.#fs = fs
293
+ this.#brotliQuality = brotliQuality
264
294
  if (resources !== undefined) this.#resources = parseResourcesOption('stasis.config.json', resources)
265
295
  this.#checkInvariants()
266
296
 
@@ -270,9 +300,12 @@ export class Config {
270
300
  if (this.#env.bundle !== undefined) assert.equal(this.#bundle, this.#env.bundle)
271
301
  if (this.#env.bundleFile !== undefined) assert.equal(this.#bundleFile, this.#env.bundleFile)
272
302
  if (this.#env.resourcesBundleFile !== undefined) assert.equal(this.#resourcesBundleFile, this.#env.resourcesBundleFile)
273
- if (this.#env.debug !== undefined) assert.equal(this.#debug, envBool(this.#env.debug))
274
- if (this.#env.childProcess !== undefined) assert.equal(this.#childProcess, envBool(this.#env.childProcess))
303
+ if (this.#env.debug !== undefined) assert.equal(this.#debug, envBool('EXODUS_STASIS_DEBUG', this.#env.debug))
304
+ if (this.#env.childProcess !== undefined) assert.equal(this.#childProcess, envBool('EXODUS_STASIS_CHILD_PROCESS', this.#env.childProcess))
275
305
  if (this.#env.fs !== undefined) assert.equal(this.#fs, this.#env.fs)
306
+ if (this.#env.brotliQuality !== undefined) {
307
+ assert.equal(this.#brotliQuality, parseBrotliQuality('EXODUS_STASIS_BROTLI_QUALITY', this.#env.brotliQuality))
308
+ }
276
309
  if (this.#env.resources !== undefined) {
277
310
  assert.ok(extSetsEqual(this.#resources, parseResourcesOption('env', envList(this.#env.resources))),
278
311
  'resources in stasis.config.json must match EXODUS_STASIS_RESOURCES')
@@ -288,6 +321,7 @@ export class Config {
288
321
  if (this.#explicit.debug !== undefined) assert.equal(this.#debug, this.#explicit.debug)
289
322
  if (this.#explicit.childProcess !== undefined) assert.equal(this.#childProcess, this.#explicit.childProcess)
290
323
  if (this.#explicit.fs !== undefined) assert.equal(this.#fs, this.#explicit.fs)
324
+ if (this.#explicit.brotliQuality !== undefined) assert.equal(this.#brotliQuality, this.#explicit.brotliQuality)
291
325
  if (this.#explicit.resources !== undefined) {
292
326
  assert.ok(extSetsEqual(this.#resources, parseResourcesOption('options', this.#explicit.resources)),
293
327
  'resources in stasis.config.json must match the resources option')
@@ -338,6 +372,21 @@ export class Config {
338
372
  return this.#childProcess
339
373
  }
340
374
 
375
+ // Opt-in (EXODUS_STASIS_SHARD_SIGNAL_FLUSH, env-only): a capturing CHILD flushes its
376
+ // shard when ended by SIGTERM, then re-delivers the signal (hooks.js). Set on
377
+ // process.env by StasisMetro's capture wiring, so every capturing child the build forks
378
+ // after config time inherits it -- Metro's transform workers are the intended audience:
379
+ // jest-worker force-kills a worker whose event loop doesn't drain within 500ms of its
380
+ // END message, which would otherwise silently drop the worker's shard.
381
+ // Deliberately NOT a global default (a signal listener changes a child's default-kill
382
+ // disposition -- the user's domain in arbitrary children) and NOT a user option: it is
383
+ // channel plumbing like EXODUS_STASIS_SHARD_DIR/_KEY, but parsed strictly through
384
+ // envBool like every other boolean toggle so '0'/'false' disable rather than enable.
385
+ // Not attested (not in `values`), like childProcess.
386
+ get shardSignalFlush() {
387
+ return this.#shardSignalFlush
388
+ }
389
+
341
390
  // The --fs hook mode: 'sync' patches the sync fs readers, 'async' additionally patches
342
391
  // their async (callback + fs.promises) counterparts, undefined leaves fs untouched. Set via
343
392
  // --fs / EXODUS_STASIS_FS / "fs" in stasis.config.json; the runtime loader (hooks.js) reads
@@ -347,6 +396,13 @@ export class Config {
347
396
  return this.#fs
348
397
  }
349
398
 
399
+ // Brotli quality (integer 0..11) for bundle writes; undefined -> brotli's default (11,
400
+ // max). State.write() forwards this to brotliOptions(). Not serialized -- a how-to-write
401
+ // flag like debug/fs; the bundle's decompressed content is identical at any quality.
402
+ get brotliQuality() {
403
+ return this.#brotliQuality
404
+ }
405
+
350
406
  get values() {
351
407
  return { scope: this.#scope }
352
408
  }
package/src/fs.js CHANGED
@@ -2,7 +2,8 @@
2
2
  // the filesystem readers
3
3
  // fs.readFileSync, fs.readdirSync, fs.lstatSync, fs.statSync so that, alongside the
4
4
  // module graph the loader hooks already capture, a program's explicit file/directory
5
- // reads are recorded into the bundle (bundle=add|replace) and served back from it
5
+ // reads -- and the KIND (file vs directory) of the paths it lstat/stats -- are
6
+ // recorded into the bundle (bundle=add|replace) and served back from it
6
7
  // (bundle=load). Alongside the readers, the existence/canonical-path PROBES existsSync /
7
8
  // accessSync / realpathSync are served (load mode) so a tool that checks a file before
8
9
  // reading it finds a bundle-only file -- see the existsSync/accessSync/realpathSync bullet.
@@ -31,17 +32,27 @@
31
32
  // - readFileSync: the optional second argument (an `encoding` string, or an
32
33
  // options object with `encoding`) is honoured; the raw bytes are what we
33
34
  // capture/serve and `encoding` is applied on the way out.
34
- // - lstatSync / statSync: serve-only, bundle=load, single-argument form. For a
35
- // recorded path they return a Stats-like object whose isFile()/isDirectory() come
35
+ // - lstatSync / statSync: single-argument form, captured AND served -- but ONLY the
36
+ // path's kind, i.e. the type getters isFile()/isDirectory(); full Stats fields are
37
+ // never attested. CAPTURE (bundle=add|replace): the real call runs first, so the
38
+ // caller always gets the genuine Stats (and genuine errors); the observed kind is
39
+ // then recorded as a PAYLOAD-FREE stat record ('stat:file'/'stat:directory' in
40
+ // `formats` -- no bytes, no hash), so a stat-ONLY path -- never read, readdir'd,
41
+ // or imported -- still answers at load. A path that is neither a regular file nor
42
+ // a directory (a symlink under lstat, a socket, a FIFO, ...) isn't modelled and
43
+ // records nothing. SERVE (bundle=load): for a recorded path they return a
44
+ // Stats-like object whose isFile()/isDirectory() come
36
45
  // from the bundle (the common existence check); every other member is the real
37
46
  // stat while the file is still on disk, and a benign synthetic default (0 / epoch
38
47
  // / file-or-dir mode) once it's gone -- so fs wrappers that read more than
39
48
  // isFile()/isDirectory() (graceful-fs reads stats.uid/gid) keep working under
40
- // bundle=load instead of re-throwing ENOENT. Not patched in capture mode (the file
41
- // is on disk there, so the real Stats is correct), except to report a skipped
42
- // source-map sidecar as absent (next bullet). statSync vs lstatSync differ only in
43
- // symlink following, which matters solely for that on-disk passthrough -- each falls
44
- // back to its own real implementation.
49
+ // bundle=load instead of re-throwing ENOENT. A skipped
50
+ // source-map sidecar is reported absent in both modes (next bullet). statSync vs
51
+ // lstatSync differ only in symlink following, which matters for the real-call
52
+ // paths (passthrough, capture, present-on-disk serve) -- each uses its own real
53
+ // implementation, and a stat of an in-root symlink records the TARGET's kind
54
+ // under the requested path (keyed exactly like a byte read of that path would
55
+ // be) while an lstat of one records nothing.
45
56
  // - existsSync / accessSync / realpathSync (+ their async/promise forms under =async):
46
57
  // existence/canonical-path PROBES, serve-only and bundle=load only. A path the bundle
47
58
  // records answers existent / accessible (read-only: F_OK/R_OK, while W_OK/X_OK defer) /
@@ -57,7 +68,9 @@
57
68
  // module loader). Because these are serve-only (never captured), a file that is ONLY
58
69
  // existence-probed -- never read or imported -- isn't recorded, so its probe falls
59
70
  // through to disk on load; babel.config.js is fine because it is also require()d, hence
60
- // recorded. realpathSync returns the real (symlink-resolved) path while the file is on
71
+ // recorded. (An lstatSync/statSync of a path, by contrast, DOES record its kind -- see
72
+ // the lstat/stat bullet above -- after which these probes answer from that stat record
73
+ // too, since they consult the same getFsStatFamily.) realpathSync returns the real (symlink-resolved) path while the file is on
61
74
  // disk, and falls back to the LEXICALLY-resolved request path once it's bundle-only (a
62
75
  // symlink in a surviving ancestor dir is not re-resolved -- moot for the absent-config
63
76
  // case, but a canonicalize-then-compare under a symlinked ancestor could diverge between
@@ -392,11 +405,31 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
392
405
  return realReaddirSync(path, options)
393
406
  }
394
407
 
408
+ // Capture-side stat recording, shared by the sync/async lstat/stat wrappers: record
409
+ // the path's KIND (file vs directory) as a payload-free stat record (state.addFsStat),
410
+ // so the type getters -- lstatSync(x).isFile()/.isDirectory(), the common existence-
411
+ // and-kind check -- of a stat-ONLY path answer from the bundle at load. Only those two
412
+ // kinds are modelled (the serve shim's contract); a symlink (under lstat), socket,
413
+ // FIFO, or device records nothing. The caller has already received (or will receive)
414
+ // the REAL Stats -- recording never alters what the program sees. Guards mirror the
415
+ // byte readers: a path whose real location escapes the root (in-tree symlink pointing
416
+ // out) is not attested, a file whose bytes a write-mode sidecar already carries is
417
+ // skipped, and a recording conflict (a kind flip mid-run) taints the capture via
418
+ // markAborted so nothing inconsistent is written.
419
+ const captureStat = (state, abs, stats) => {
420
+ const isDir = stats.isDirectory()
421
+ if (!isDir && !stats.isFile()) return
422
+ const url = pathToFileURL(abs).toString()
423
+ if (!realContained(state.root, abs) || state.attestedBySidecar(url)) return
424
+ try { state.addFsStat(url, isDir ? 'directory' : 'file') } catch (err) { markAborted(err) }
425
+ }
426
+
395
427
  fs.lstatSync = function lstatSync(path, options) {
396
428
  const state = getState()
397
- // Serve-only, single-argument form. Capture mode is left to the real lstatSync
398
- // (the file is on disk, so its Stats is correct and complete) -- the lone exception
399
- // being a skipped source-map sidecar, reported absent in both modes.
429
+ // Single-argument form. Serve (bundle=load) the bundle-backed type getters for a
430
+ // recorded path; capture (bundle=add|replace) the observed kind via captureStat,
431
+ // handing the caller the REAL Stats (and real errors, e.g. ENOENT) untouched.
432
+ // A skipped source-map sidecar is reported absent in both modes.
400
433
  if (state && options == null) {
401
434
  const abs = toAbsPath(path)
402
435
  if (abs !== null && withinRoot(state.root, abs)) {
@@ -404,6 +437,13 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
404
437
  if (state.config.loadBundle) {
405
438
  const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
406
439
  if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
440
+ } else if (state.config.writeBundle && !isLoadingModule()) {
441
+ // (Node's loader stats module paths through internal bindings, not this
442
+ // public API, but skip during a load window anyway, symmetric with
443
+ // readFileSync/readdirSync.)
444
+ const stats = realLstatSync(path)
445
+ captureStat(state, abs, stats)
446
+ return stats
407
447
  }
408
448
  }
409
449
  }
@@ -413,7 +453,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
413
453
  // statSync mirrors lstatSync exactly; the only difference is symlink following,
414
454
  // which is moot for a bundle-served path (there is no link to follow once the
415
455
  // bytes come from the bundle) but matters for the passthrough/present-on-disk
416
- // case, so it falls back to the real statSync rather than lstatSync.
456
+ // case AND for capture -- a statSync of an in-root symlink records the TARGET's
457
+ // kind (keyed at the requested path, like a byte read of it), while an lstatSync
458
+ // of it records nothing (a symlink isn't modelled) -- so each uses its own real
459
+ // implementation.
417
460
  fs.statSync = function statSync(path, options) {
418
461
  const state = getState()
419
462
  if (state && options == null) {
@@ -423,6 +466,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
423
466
  if (state.config.loadBundle) {
424
467
  const kind = state.getFsStatFamily(pathToFileURL(abs).toString())
425
468
  if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
469
+ } else if (state.config.writeBundle && !isLoadingModule()) {
470
+ const stats = realStatSync(path)
471
+ captureStat(state, abs, stats)
472
+ return stats
426
473
  }
427
474
  }
428
475
  }
@@ -597,8 +644,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
597
644
  return realReaddirP(path, options)
598
645
  }
599
646
 
600
- // lstat/stat are serve-only (like their sync siblings); capture is left to the real
601
- // call. bundleStats's field fallback is synchronous, so it uses the sync real stat.
647
+ // lstat/stat capture and serve exactly like their sync siblings: serve the
648
+ // bundle-backed type getters, or record the real call's observed kind via
649
+ // captureStat while handing the caller the real Stats. bundleStats's field
650
+ // fallback is synchronous, so it uses the sync real stat.
602
651
  fs.lstat = function lstat(path, options, callback) {
603
652
  const cb = typeof options === 'function' ? options : callback
604
653
  // "single-argument" form: fn(path, cb) OR fn(path, null/undefined, cb). graceful-fs
@@ -610,6 +659,13 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
610
659
  if (t?.mode === 'serve') {
611
660
  const kind = t.state.getFsStatFamily(t.url)
612
661
  if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realLstatSync, path, kind === 'directory'))); return }
662
+ } else if (t?.mode === 'capture') {
663
+ realLstat(path, (err, stats) => {
664
+ if (err) return cb(err) // faithful error on the user's original path; nothing recorded
665
+ captureStat(t.state, t.abs, stats)
666
+ cb(null, stats)
667
+ })
668
+ return
613
669
  }
614
670
  return realLstat(path, options, callback)
615
671
  }
@@ -625,6 +681,13 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
625
681
  if (t?.mode === 'serve') {
626
682
  const kind = t.state.getFsStatFamily(t.url)
627
683
  if (kind !== undefined) { queueMicrotask(() => cb(null, bundleStats(realStatSync, path, kind === 'directory'))); return }
684
+ } else if (t?.mode === 'capture') {
685
+ realStat(path, (err, stats) => {
686
+ if (err) return cb(err)
687
+ captureStat(t.state, t.abs, stats)
688
+ cb(null, stats)
689
+ })
690
+ return
628
691
  }
629
692
  return realStat(path, options, callback)
630
693
  }
@@ -635,6 +698,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
635
698
  if (t?.mode === 'serve') {
636
699
  const kind = t.state.getFsStatFamily(t.url)
637
700
  if (kind !== undefined) return bundleStats(realLstatSync, path, kind === 'directory')
701
+ } else if (t?.mode === 'capture') {
702
+ const stats = await realLstatP(path)
703
+ captureStat(t.state, t.abs, stats)
704
+ return stats
638
705
  }
639
706
  return realLstatP(path, options)
640
707
  }
@@ -645,6 +712,10 @@ export function installFsHooks({ async: patchAsync, getState, markAborted, isLoa
645
712
  if (t?.mode === 'serve') {
646
713
  const kind = t.state.getFsStatFamily(t.url)
647
714
  if (kind !== undefined) return bundleStats(realStatSync, path, kind === 'directory')
715
+ } else if (t?.mode === 'capture') {
716
+ const stats = await realStatP(path)
717
+ captureStat(t.state, t.abs, stats)
718
+ return stats
648
719
  }
649
720
  return realStatP(path, options)
650
721
  }