@exodus/stasis-core 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.js ADDED
@@ -0,0 +1,426 @@
1
+ import assert from 'node:assert/strict'
2
+
3
+ import { canonicalizePath } from './state-util.js'
4
+ import { extSetsEqual, parseResourcesOption } from './util.js'
5
+
6
+ const VALID_SCOPE = new Set(['node_modules', 'full'])
7
+ const VALID_LOCK = new Set(['none', 'ignore', 'add', 'replace', 'frozen'])
8
+ const VALID_BUNDLE = new Set(['none', 'ignore', 'add', 'replace', 'load', 'frozen'])
9
+ const VALID_FS = new Set(['sync', 'async'])
10
+
11
+ // The defaults Config applies when neither env nor options specify a value.
12
+ // Exported so callers (plugins.js error messages) can reference the same source of
13
+ // truth instead of hardcoding the literal -- a default drift then surfaces at one
14
+ // place, not silently in a user-facing message.
15
+ export const DEFAULT_LOCK = 'add'
16
+ export const DEFAULT_BUNDLE = 'none'
17
+ export const DEFAULT_SCOPE = 'full'
18
+
19
+ const envBool = (value) => Boolean(value && value !== '0')
20
+
21
+ // EXODUS_STASIS_RESOURCES is a comma-separated extension list; split + trim + drop
22
+ // empties so '' and ' png , svg ' normalize predictably (parseResourcesOption then
23
+ // validates each entry). An empty/unset env var means "no allowlist".
24
+ const envList = (value) => value.split(',').map((s) => s.trim()).filter(Boolean)
25
+
26
+ const OPTION_KEYS = ['scope', 'lock', 'bundle', 'bundleFile', 'resourcesBundleFile', 'debug', 'resources', 'childProcess']
27
+
28
+ // Plugins accept the same options as Config but want to validate without constructing one,
29
+ // since constructing State has side effects. Mirror Config's per-field validation.
30
+ export function validatePluginOptions(label, options) {
31
+ const rest = { ...options }
32
+ for (const key of OPTION_KEYS) delete rest[key]
33
+ assert.equal(Object.keys(rest).length, 0, `Unknown ${label} options: ${Object.keys(rest).join(', ')}`)
34
+ const { scope, lock, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess } = options
35
+ if (scope !== undefined) assert.ok(VALID_SCOPE.has(scope), `Invalid scope: ${scope}`)
36
+ if (lock !== undefined) assert.ok(VALID_LOCK.has(lock), `Invalid lock: ${lock}`)
37
+ if (bundle !== undefined) assert.ok(VALID_BUNDLE.has(bundle), `Invalid bundle: ${bundle}`)
38
+ if (bundleFile !== undefined) assert.equal(typeof bundleFile, 'string', 'bundleFile must be a string')
39
+ if (resourcesBundleFile !== undefined) assert.equal(typeof resourcesBundleFile, 'string', 'resourcesBundleFile must be a string')
40
+ if (debug !== undefined) assert.equal(typeof debug, 'boolean', 'debug must be a boolean')
41
+ if (childProcess !== undefined) assert.equal(typeof childProcess, 'boolean', 'childProcess must be a boolean')
42
+ // parseResourcesOption is the validator: it throws on a non-array, non-string entries,
43
+ // malformed extensions, or a code extension (those are always tracked, never resources).
44
+ if (resources !== undefined) parseResourcesOption(label, resources)
45
+ }
46
+
47
+ // When a plugin runs against a State that already exists (preload path), the active Config
48
+ // is authoritative. Any options the plugin was given must agree with it.
49
+ export function assertOptionsMatchConfig(config, options) {
50
+ const { scope, lock, bundle, bundleFile, resourcesBundleFile, debug, childProcess } = options
51
+ // `resources` is intentionally NOT cross-checked here: it's a Set (needs set-equality,
52
+ // which assert.equal can't express) and is coordinated explicitly in resolvePluginState
53
+ // before this runs -- don't "fix" the omission with assert.equal(config.resources, ...).
54
+ try {
55
+ if (scope !== undefined) assert.equal(config.scope, scope)
56
+ if (lock !== undefined) assert.equal(config.lock, lock)
57
+ if (bundle !== undefined) assert.equal(config.bundleMode, bundle)
58
+ if (bundleFile !== undefined) assert.equal(config.bundleFile, bundleFile)
59
+ if (resourcesBundleFile !== undefined) assert.equal(config.resourcesBundleFile, resourcesBundleFile)
60
+ if (debug !== undefined) assert.equal(config.debug, debug)
61
+ if (childProcess !== undefined) assert.equal(config.childProcess, childProcess)
62
+ } catch (cause) {
63
+ // Re-throw with the underlying assertion message folded into the top-level
64
+ // text -- a plugin author hitting this gets the offending field's name and
65
+ // expected/actual values without having to inspect err.cause.
66
+ throw new Error(`Plugin options conflict with active stasis state: ${cause.message}`, { cause })
67
+ }
68
+ }
69
+
70
+ export class Config {
71
+ #env
72
+ #explicit
73
+ #scope
74
+ #lock
75
+ #lockFile
76
+ #bundle
77
+ #bundleFile
78
+ #resourcesBundleFile
79
+ #resources
80
+ #debug
81
+ #childProcess
82
+ #fs
83
+
84
+ // Options match the CLI flags (scope/lock/lockFile/bundle/bundleFile/resourcesBundleFile/debug/
85
+ // resources/childProcess/fs).
86
+ // Env vars take effect at construction time; if both env and an option are set they must
87
+ // agree. Likewise, any explicit constructor option is treated as authoritative: a later
88
+ // `loadConfig` call (which reads stasis.config.json) must agree with it -- the alternative
89
+ // (silently overwriting `--scope=full` with the file's `"scope":"node_modules"`)
90
+ // was a footgun the CLI couldn't detect, since the flag was happily accepted
91
+ // and then quietly ignored.
92
+ constructor(options = {}) {
93
+ const { scope, lock, lockFile, bundle, bundleFile, resourcesBundleFile, debug, resources, childProcess, fs, ...rest } = options
94
+ 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 }
96
+
97
+ this.#env = {
98
+ scope: process.env.EXODUS_STASIS_SCOPE || undefined,
99
+ lock: process.env.EXODUS_STASIS_LOCK || undefined,
100
+ lockFile: process.env.EXODUS_STASIS_LOCK_FILE || undefined,
101
+ bundle: process.env.EXODUS_STASIS_BUNDLE || undefined,
102
+ bundleFile: process.env.EXODUS_STASIS_BUNDLE_FILE || undefined,
103
+ resourcesBundleFile: process.env.EXODUS_STASIS_RESOURCES_BUNDLE_FILE || undefined,
104
+ debug: process.env.EXODUS_STASIS_DEBUG || undefined,
105
+ resources: process.env.EXODUS_STASIS_RESOURCES || undefined,
106
+ childProcess: process.env.EXODUS_STASIS_CHILD_PROCESS || undefined,
107
+ fs: process.env.EXODUS_STASIS_FS || undefined,
108
+ }
109
+
110
+ try {
111
+ if (this.#env.scope !== undefined && scope !== undefined) assert.equal(this.#env.scope, scope)
112
+ if (this.#env.lock !== undefined && lock !== undefined) assert.equal(this.#env.lock, lock)
113
+ if (this.#env.lockFile !== undefined && lockFile !== undefined) {
114
+ assert.equal(this.#env.lockFile, lockFile)
115
+ }
116
+ if (this.#env.bundle !== undefined && bundle !== undefined) assert.equal(this.#env.bundle, bundle)
117
+ if (this.#env.bundleFile !== undefined && bundleFile !== undefined) {
118
+ assert.equal(this.#env.bundleFile, bundleFile)
119
+ }
120
+ if (this.#env.resourcesBundleFile !== undefined && resourcesBundleFile !== undefined) {
121
+ assert.equal(this.#env.resourcesBundleFile, resourcesBundleFile)
122
+ }
123
+ if (this.#env.debug !== undefined && debug !== undefined) {
124
+ assert.equal(envBool(this.#env.debug), debug)
125
+ }
126
+ if (this.#env.childProcess !== undefined && childProcess !== undefined) {
127
+ assert.equal(envBool(this.#env.childProcess), childProcess)
128
+ }
129
+ if (this.#env.fs !== undefined && fs !== undefined) assert.equal(this.#env.fs, fs)
130
+ // Compare parsed sets, not the raw strings: ['png','svg'] and 'svg,png' are the
131
+ // same allowlist. An empty/unset env var is "no env opinion" (handled by `||
132
+ // undefined` above), so this only fires on two genuinely different non-empty lists.
133
+ if (this.#env.resources !== undefined && resources !== undefined) {
134
+ assert.ok(
135
+ extSetsEqual(parseResourcesOption('env', envList(this.#env.resources)), parseResourcesOption('options', resources)),
136
+ 'resources option does not match EXODUS_STASIS_RESOURCES'
137
+ )
138
+ }
139
+ } catch (cause) {
140
+ throw new Error('Config options can not override stasis env', { cause })
141
+ }
142
+
143
+ this.#scope = this.#env.scope || scope || DEFAULT_SCOPE
144
+ this.#lock = this.#env.lock || lock || DEFAULT_LOCK
145
+ this.#lockFile = this.#env.lockFile || lockFile || undefined
146
+ this.#bundle = this.#env.bundle || bundle || DEFAULT_BUNDLE
147
+ this.#bundleFile = this.#env.bundleFile || bundleFile || undefined
148
+ 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)
151
+ // env wins over the option, like scope/lock/bundle; undefined means "fs untouched" (off).
152
+ this.#fs = this.#env.fs || fs || undefined
153
+ // env wins over the option (it's the process-wide signal); parseResourcesOption
154
+ // normalizes both to a Set of lowercase extensions/filenames, or empty when neither set.
155
+ this.#resources = parseResourcesOption(
156
+ 'resources',
157
+ this.#env.resources !== undefined ? envList(this.#env.resources) : resources
158
+ )
159
+
160
+ this.#checkInvariants()
161
+ }
162
+
163
+ // Per-field validation + cross-field invariants. Constructor (options path) and
164
+ // loadConfig (disk path) both call this so the rules live in one place.
165
+ #checkInvariants() {
166
+ assert.ok(VALID_SCOPE.has(this.#scope), `Invalid scope: ${this.#scope}`)
167
+ assert.ok(VALID_LOCK.has(this.#lock), `Invalid lock: ${this.#lock}`)
168
+ assert.ok(VALID_BUNDLE.has(this.#bundle), `Invalid bundle: ${this.#bundle}`)
169
+ assert.equal(typeof this.#debug, 'boolean', 'debug must be a boolean')
170
+ assert.equal(typeof this.#childProcess, 'boolean', 'childProcess must be a boolean')
171
+ if (this.#fs !== undefined) {
172
+ assert.ok(VALID_FS.has(this.#fs), `Invalid fs: ${this.#fs}`)
173
+ // --fs patches the fs readers to capture into the bundle (add/replace) or serve them
174
+ // from it (load); with any other bundle mode it has nothing to record into or read from.
175
+ // Mirrors the CLI's "--fs requires --bundle=(add|replace|load)" guard.
176
+ if (this.#bundle !== 'add' && this.#bundle !== 'replace' && this.#bundle !== 'load') {
177
+ throw new RangeError(`fs requires bundle=(add|replace|load) (got bundle='${this.#bundle}')`)
178
+ }
179
+ }
180
+ if (this.#bundleFile !== undefined) assert.equal(typeof this.#bundleFile, 'string', 'bundleFile must be a string')
181
+ if (this.#lockFile !== undefined) {
182
+ assert.equal(typeof this.#lockFile, 'string', 'lockFile must be a string')
183
+ // lockFile is only meaningful when there IS a lockfile. Lock modes that opt out
184
+ // (none / ignore) would silently ignore the path -- catch the misconfig explicitly.
185
+ if (this.#lock === 'none' || this.#lock === 'ignore') {
186
+ throw new RangeError(`lockFile requires an active lock mode (got lock='${this.#lock}')`)
187
+ }
188
+ }
189
+ if (this.#resourcesBundleFile !== undefined) {
190
+ assert.equal(typeof this.#resourcesBundleFile, 'string', 'resourcesBundleFile must be a string')
191
+ // The split is only meaningful when there IS a bundle to split. With bundle=none / ignore the
192
+ // option would be silently inert -- catch the misconfiguration explicitly instead.
193
+ if (this.#bundle === 'none' || this.#bundle === 'ignore') {
194
+ throw new RangeError(`resourcesBundleFile requires an active bundle mode (got bundle='${this.#bundle}')`)
195
+ }
196
+ }
197
+
198
+ // Cross-path collision checks: the three write targets (lockFile, bundleFile,
199
+ // resourcesBundleFile) must each name a distinct on-disk file. Canonicalize via
200
+ // resolve() + realpathSync so './x.br' vs 'x.br', and two symlinks to the same
201
+ // inode, both compare equal -- a raw string compare would let `./out/x.br` and
202
+ // `out/x.br` slip past and the second writer would silently clobber the first.
203
+ const claimed = new Map()
204
+ for (const [label, value] of [
205
+ ['lockFile', this.#lockFile],
206
+ ['bundleFile', this.#bundleFile],
207
+ ['resourcesBundleFile', this.#resourcesBundleFile],
208
+ ]) {
209
+ if (value === undefined) continue
210
+ const canonical = canonicalizePath(value)
211
+ if (claimed.has(canonical)) {
212
+ throw new RangeError(`${label} '${value}' targets the same file as ${claimed.get(canonical)}; each must be a distinct path`)
213
+ }
214
+ claimed.set(canonical, label)
215
+ }
216
+
217
+ // bundle=load needs a trust root for source bytes: frozen pins each file's sha512 in
218
+ // the lockfile and we cross-check it on load; otherwise the bundle is itself
219
+ // authoritative -- lock=none with no lockfile on disk, or lock=ignore with a lockfile
220
+ // deliberately bypassed.
221
+ // WARNING: the lockfile attests source bytes, entries, module identity, and
222
+ // (when it records them) resolutions and loader formats. Lockfiles predating
223
+ // a given attestation cover only what they recorded (bytes at minimum).
224
+ if (this.#bundle === 'load' && this.#lock !== 'frozen' && this.#lock !== 'none' && this.#lock !== 'ignore') {
225
+ throw new RangeError('bundle=load is incompatible with lock=(add|replace)')
226
+ }
227
+
228
+ // bundle=frozen places no constraint on lock: unlike load it never *serves* the
229
+ // bundle's bytes, it reads each file from disk and verifies it against the bundle's
230
+ // own recorded bytes/resolutions/formats (the bundle is itself the trust root, so it
231
+ // needs no sibling lockfile -- it "operates as a lockfile"). It composes with any lock
232
+ // mode, and (being a real bundle) satisfies the "needs a lockfile or a bundle" rule
233
+ // below -- which only rejects leaving both unset.
234
+ if (this.#lock === 'none' && this.#bundle === 'none') {
235
+ throw new RangeError('stasis needs a lockfile or a bundle: set lock or bundle')
236
+ }
237
+ }
238
+
239
+ loadConfig(json) {
240
+ const {
241
+ scope = this.#scope,
242
+ lock = this.#lock,
243
+ bundle = this.#bundle,
244
+ bundleFile = this.#bundleFile,
245
+ resourcesBundleFile = this.#resourcesBundleFile,
246
+ debug = this.#debug,
247
+ childProcess = this.#childProcess,
248
+ fs = this.#fs,
249
+ resources,
250
+ ...rest
251
+ } = JSON.parse(json)
252
+ assert.equal(Object.keys(rest).length, 0)
253
+ this.#scope = scope
254
+ this.#lock = lock
255
+ this.#bundle = bundle
256
+ // Coerce '' -> undefined to match the constructor: an empty-string path is "unset"
257
+ // everywhere downstream (State consumes bundleFile truthily), but #checkInvariants would
258
+ // otherwise resolve('') -> cwd and claim it as a write target.
259
+ this.#bundleFile = bundleFile || undefined
260
+ this.#resourcesBundleFile = resourcesBundleFile || undefined
261
+ this.#debug = debug
262
+ this.#childProcess = childProcess
263
+ this.#fs = fs
264
+ if (resources !== undefined) this.#resources = parseResourcesOption('stasis.config.json', resources)
265
+ this.#checkInvariants()
266
+
267
+ try {
268
+ if (this.#env.scope !== undefined) assert.equal(this.#scope, this.#env.scope)
269
+ if (this.#env.lock !== undefined) assert.equal(this.#lock, this.#env.lock)
270
+ if (this.#env.bundle !== undefined) assert.equal(this.#bundle, this.#env.bundle)
271
+ if (this.#env.bundleFile !== undefined) assert.equal(this.#bundleFile, this.#env.bundleFile)
272
+ 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))
275
+ if (this.#env.fs !== undefined) assert.equal(this.#fs, this.#env.fs)
276
+ if (this.#env.resources !== undefined) {
277
+ assert.ok(extSetsEqual(this.#resources, parseResourcesOption('env', envList(this.#env.resources))),
278
+ 'resources in stasis.config.json must match EXODUS_STASIS_RESOURCES')
279
+ }
280
+ // Explicit constructor options are equally authoritative: an explicit
281
+ // `--scope=full` shouldn't be silently overridden by an on-disk
282
+ // `{"scope":"node_modules"}`. The asserts mirror the env block above.
283
+ if (this.#explicit.scope !== undefined) assert.equal(this.#scope, this.#explicit.scope)
284
+ if (this.#explicit.lock !== undefined) assert.equal(this.#lock, this.#explicit.lock)
285
+ if (this.#explicit.bundle !== undefined) assert.equal(this.#bundle, this.#explicit.bundle)
286
+ if (this.#explicit.bundleFile !== undefined) assert.equal(this.#bundleFile, this.#explicit.bundleFile)
287
+ if (this.#explicit.resourcesBundleFile !== undefined) assert.equal(this.#resourcesBundleFile, this.#explicit.resourcesBundleFile)
288
+ if (this.#explicit.debug !== undefined) assert.equal(this.#debug, this.#explicit.debug)
289
+ if (this.#explicit.childProcess !== undefined) assert.equal(this.#childProcess, this.#explicit.childProcess)
290
+ if (this.#explicit.fs !== undefined) assert.equal(this.#fs, this.#explicit.fs)
291
+ if (this.#explicit.resources !== undefined) {
292
+ assert.ok(extSetsEqual(this.#resources, parseResourcesOption('options', this.#explicit.resources)),
293
+ 'resources in stasis.config.json must match the resources option')
294
+ }
295
+ } catch (cause) {
296
+ throw new Error('Flags/env can not override stasis.config.json', { cause })
297
+ }
298
+ }
299
+
300
+ get bundleFile() {
301
+ return this.#bundleFile
302
+ }
303
+
304
+ // When set, State reads/writes the lockfile at this exact path instead of
305
+ // discovering `stasis.lock.json` at the project root. Set via the CLI,
306
+ // `EXODUS_STASIS_LOCK_FILE`, or direct State construction; bundler plugins
307
+ // can't set it (they always share the ambient lockfile). Unset -> default
308
+ // discovery applies.
309
+ get lockFile() {
310
+ return this.#lockFile
311
+ }
312
+
313
+ // When set, State.write() emits resources to this file and code-only to bundleFile;
314
+ // bundle=load reads both. Unset is the default unified-bundle behavior.
315
+ get resourcesBundleFile() {
316
+ return this.#resourcesBundleFile
317
+ }
318
+
319
+ // The parsed `resources` allowlist: a Set of lowercase extensions or extensionless
320
+ // filenames that classifyExtension treats as asset payloads. Drives both the plugins'
321
+ // per-import classification and State's `--fs` capture, so the two share one list.
322
+ // Empty Set when no allowlist was configured (option or EXODUS_STASIS_RESOURCES).
323
+ get resources() {
324
+ return this.#resources
325
+ }
326
+
327
+ get debug() {
328
+ return this.#debug
329
+ }
330
+
331
+ // Opt-in (CLI --child-process / EXODUS_STASIS_CHILD_PROCESS / "childProcess": true in
332
+ // stasis.config.json): enable cross-process capture forwarding. A forked child (e.g. a
333
+ // Metro transform worker) writes a shard of what it captured into a root-owned dir, and
334
+ // the root merges it before writing -- so files only a child loads (a worker's babel
335
+ // toolchain) are attested. Off by default: the shard dir is a process-coordination channel,
336
+ // so it's only created when explicitly enabled. Not attested (not in `values`), like debug.
337
+ get childProcess() {
338
+ return this.#childProcess
339
+ }
340
+
341
+ // The --fs hook mode: 'sync' patches the sync fs readers, 'async' additionally patches
342
+ // their async (callback + fs.promises) counterparts, undefined leaves fs untouched. Set via
343
+ // --fs / EXODUS_STASIS_FS / "fs" in stasis.config.json; the runtime loader (hooks.js) reads
344
+ // this on State init to decide whether (and how) to install the fs hooks. Not serialized --
345
+ // a how-to-run flag like debug/childProcess, not an attested property of the bundle.
346
+ get fs() {
347
+ return this.#fs
348
+ }
349
+
350
+ get values() {
351
+ return { scope: this.#scope }
352
+ }
353
+
354
+ get bundle() {
355
+ return this.#bundle !== 'none' && this.#bundle !== 'ignore'
356
+ }
357
+
358
+ get bundleMode() {
359
+ return this.#bundle
360
+ }
361
+
362
+ get ignoreBundle() {
363
+ return this.#bundle === 'ignore'
364
+ }
365
+
366
+ get writeBundle() {
367
+ return this.#bundle === 'add' || this.#bundle === 'replace'
368
+ }
369
+
370
+ get replaceBundle() {
371
+ return this.#bundle === 'replace'
372
+ }
373
+
374
+ get loadBundle() {
375
+ return this.#bundle === 'load'
376
+ }
377
+
378
+ // bundle=frozen: the bundle is a read-only attestation, like a frozen lockfile.
379
+ // It is loaded (its bytes/resolutions/entries/modules become the attested set) but
380
+ // never rewritten, and every file/resolution observed from disk is checked against
381
+ // it. Distinct from load (which serves bytes from the bundle instead of reading disk)
382
+ // and from add (which loads-then-rewrites and tolerates new files).
383
+ get frozenBundle() {
384
+ return this.#bundle === 'frozen'
385
+ }
386
+
387
+ get full() {
388
+ return this.#scope === 'full'
389
+ }
390
+
391
+ get frozen() {
392
+ return this.#lock === 'frozen'
393
+ }
394
+
395
+ get useLockfile() {
396
+ return this.#lock !== 'none' && this.#lock !== 'ignore'
397
+ }
398
+
399
+ get ignoreLockfile() {
400
+ return this.#lock === 'ignore'
401
+ }
402
+
403
+ get writeLockfile() {
404
+ return this.#lock === 'add' || this.#lock === 'replace'
405
+ }
406
+
407
+ get replaceLockfile() {
408
+ return this.#lock === 'replace'
409
+ }
410
+
411
+ get scope() {
412
+ return this.#scope
413
+ }
414
+
415
+ get lock() {
416
+ return this.#lock
417
+ }
418
+
419
+ get json() {
420
+ const data = { scope: this.#scope, lock: this.#lock, bundle: this.#bundle }
421
+ // resources persists like scope/lock/bundle (a project-level declaration), but only
422
+ // when non-empty so configs without an allowlist serialize byte-identically as before.
423
+ if (this.#resources.size > 0) data.resources = [...this.#resources].toSorted()
424
+ return JSON.stringify(data, undefined, 2) + '\n'
425
+ }
426
+ }