@exodus/stasis-plugins 1.0.0-rc.0 → 1.0.0-rc.10

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/metro.js CHANGED
@@ -4,25 +4,26 @@ import { spawnSync } from 'node:child_process'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { createRequire } from 'node:module'
6
6
  import { dirname, isAbsolute, join, resolve } from 'node:path'
7
- import { fileURLToPath, pathToFileURL } from 'node:url'
7
+ import { fileURLToPath } from 'node:url'
8
8
 
9
- import { assertCodeUtf8, classifyOrThrow, resolvePluginState } from './plugins.js'
9
+ import { PluginState, fileURL, resolvePluginState } from './plugins.js'
10
10
  import { AUTO_INCLUDES, FILE_STAT, RN_CORE_INCLUDE_FILES, bundleDirHost, looksNative, metroAssetFiles, nativeInputs } from './metro-native.js'
11
11
  import { diskHost } from '@exodus/stasis-core/host'
12
12
  import { State } from '@exodus/stasis-core/state'
13
13
  // realReadFileSync throughout: the plugin's own reads, which --fs must not record as the program's.
14
14
  import { inScope, realReadFileSync } from '@exodus/stasis-core/state-util'
15
- import { classifyExtension, classifyFormat, isPathWithin, nodeExtFormat, splitNodeModulesPath } from '@exodus/stasis-core/util'
15
+ import { classifyExtension, classifyFormat, isPathWithin, metroFormat, splitNodeModulesPath } from '@exodus/stasis-core/util'
16
16
 
17
17
  const require = createRequire(import.meta.url)
18
18
 
19
19
  const TRANSFORMER = fileURLToPath(new URL('./metro-transformer.js', import.meta.url))
20
20
 
21
- // A graph module's absolute path, or undefined for a virtual one (require.context's ?ctx=, __prelude__).
22
- function diskPath(module) {
23
- const modPath = module?.path
24
- return typeof modPath === 'string' && isAbsolute(modPath) && existsSync(modPath) ? modPath : undefined
25
- }
21
+ // An absolute path on disk, else undefined: a virtual module's (require.context's ?ctx=, __prelude__), an unresolved
22
+ // edge's.
23
+ const diskPath = (path) => (typeof path === 'string' && isAbsolute(path) && existsSync(path) ? path : undefined)
24
+
25
+ // Metro's asset module, whose files (its `scales` and `hash`) Metro reads to build it and copies out with it.
26
+ const isAsset = (module) => module.output?.[0]?.type === 'js/module/asset'
26
27
 
27
28
  // Metro's `graph.entryPoints` is a Set, an Array before ~0.71.
28
29
  const entrySet = ({ entryPoints }) => new Set(entryPoints instanceof Set || Array.isArray(entryPoints) ? entryPoints : [])
@@ -81,54 +82,46 @@ let metroDefault
81
82
  function metroDefaultSerializer() {
82
83
  if (metroDefault) return metroDefault
83
84
  const M = 'metro'
84
- const load = (dir) => ['DeltaBundler/Serializers/baseJSBundle', 'lib/bundleToString'].map((lib) => {
85
- const mod = require(`${M}/${dir}/${lib}`)
86
- return mod.default ?? mod
87
- })
88
- let baseJSBundle, bundleToString
89
- try {
90
- [baseJSBundle, bundleToString] = load('src')
91
- } catch {
85
+ let cause
86
+ for (const dir of ['src', 'private']) {
92
87
  try {
93
- [baseJSBundle, bundleToString] = load('private')
94
- } catch (cause) {
95
- throw new Error(
96
- "StasisMetro: couldn't load Metro's default serializer (tried metro/src and " +
97
- 'metro/private). Pass your existing customSerializer to withStasis()/customSerializer() instead.',
98
- { cause }
99
- )
88
+ const [baseJSBundle, bundleToString] = ['DeltaBundler/Serializers/baseJSBundle', 'lib/bundleToString'].map((lib) => {
89
+ const mod = require(`${M}/${dir}/${lib}`)
90
+ return mod.default ?? mod
91
+ })
92
+ metroDefault = (entryPoint, preModules, graph, options) => bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code
93
+ return metroDefault
94
+ } catch (error) {
95
+ cause = error
100
96
  }
101
97
  }
102
- metroDefault = (entryPoint, preModules, graph, options) => bundleToString(baseJSBundle(entryPoint, preModules, graph, options)).code
103
- return metroDefault
98
+ throw new Error(
99
+ "StasisMetro: couldn't load Metro's default serializer (tried metro/src and metro/private)",
100
+ { cause }
101
+ )
104
102
  }
105
103
 
106
104
  // Hooks Metro's serializer, which runs once in the main process with the full graph (a worker's State could never
107
105
  // be merged); ./metro-transformer.js is the worker half. Under bundle=load it asserts each edge against the bundle.
108
106
  // Prefer withStasis: serializerHook never sees preModules, and only withStasis can drop Metro's transform cache.
109
107
  export class StasisMetro {
110
- #seen = new Set()
108
+ #stasis
111
109
  #realRoot
112
110
  #bundleDirs
113
- #state
114
- #resources
115
111
  // Snapshotted so a later chdir can't skew capture.
116
112
  #projectDir = process.cwd()
117
- #ran = false
118
113
  #ownsConfig
119
114
 
120
115
  constructor(options = {}, { ownsConfig = false } = {}) {
121
- const { state } = resolvePluginState('StasisMetro', options, process.cwd())
122
- this.#state = state
116
+ this.#stasis = new PluginState('StasisMetro', 'metro', resolvePluginState('StasisMetro', options, process.cwd()).state)
117
+ const { state } = this.#stasis
123
118
  this.#ownsConfig = ownsConfig
124
119
  // The worker toolchain is only ever loaded in workers, so a writing capture needs --child-process.
125
120
  if (state && (state.config.writeLockfile || state.config.writeBundle)) {
126
121
  assert.ok(
127
122
  state.config.childProcess,
128
- 'StasisMetro: child-process capture must be enabled -- Metro transforms in worker processes, ' +
129
- `and without it the toolchain they load (${WORKER_TOOLCHAIN}) ` +
130
- 'is never attested. Enable it: `stasis run --child-process ...`, EXODUS_STASIS_CHILD_PROCESS=1, ' +
131
- 'or "childProcess": true in stasis.config.json.'
123
+ 'StasisMetro: child-process capture must be enabled (--child-process, EXODUS_STASIS_CHILD_PROCESS=1, ' +
124
+ 'or "childProcess": true in stasis.config.json)'
132
125
  )
133
126
  // Opt the children into the loader's SIGTERM shard flush, else jest-worker's forceExit drops a shard. Keyed on
134
127
  // the preload's mode, which the shard channel follows; `||=` honours an explicit opt-out.
@@ -137,13 +130,12 @@ export class StasisMetro {
137
130
  process.env.EXODUS_STASIS_SHARD_SIGNAL_FLUSH ||= '1'
138
131
  }
139
132
  }
140
- this.#resources = state?.config.resources ?? new Set()
141
133
  }
142
134
 
143
135
  // Whether the build relies on Metro really transforming files (capture, frozen and load all do), which a cached
144
136
  // transform would skip.
145
137
  get needsTransforms() {
146
- const config = this.#state?.config
138
+ const config = this.#stasis.state?.config
147
139
  return config !== undefined && (config.useLockfile || config.bundle)
148
140
  }
149
141
 
@@ -152,57 +144,68 @@ export class StasisMetro {
152
144
  throw new TypeError('StasisMetro.customSerializer(base?): base must be a function or omitted')
153
145
  }
154
146
  // Inert: the base as is, never loading Metro's internals.
155
- if (!this.#state) return baseSerializer
147
+ if (!this.#stasis.state) return baseSerializer
156
148
  return (entryPoint, preModules, graph, options) => {
157
149
  this.#run(graph, preModules)
158
150
  return (baseSerializer ?? metroDefaultSerializer())(entryPoint, preModules, graph, options)
159
151
  }
160
152
  }
161
153
 
162
- serializerHook = (graph, _delta) => {
163
- this.#run(graph)
164
- }
154
+ serializerHook = (graph) => this.#run(graph)
165
155
 
166
156
  #run(graph, preModules) {
167
- if (!this.#state) return
157
+ const stasis = this.#stasis
158
+ if (!stasis.state) return
168
159
  // Before the one-shot guard: load records nothing, and may re-serialize under a dev server.
169
- if (this.#state.config.loadBundle) {
160
+ if (stasis.state.config.loadBundle) {
170
161
  this.#assertEdges(graph, preModules)
171
162
  return
172
163
  }
173
- if (this.#ran) {
174
- throw new Error(
175
- 'StasisMetro: watch/dev-server rebuilds are not supported for capture -- use a one-shot `metro build`'
176
- )
177
- }
178
- this.#ran = true
164
+ const refusal = stasis.startBuild('StasisMetro: watch/dev-server rebuilds are not supported for capture -- use a one-shot `metro build`')
165
+ if (refusal) throw new Error(refusal)
179
166
  // Nothing here can detect a cache hit, so say it once rather than silently under-attest.
180
167
  if (!this.#ownsConfig && this.needsTransforms) {
181
168
  console.warn(
182
- "[stasis] StasisMetro: wired without withStasis(), so Metro's transform cache is outside " +
183
- `stasis's control -- a cached transform skips the worker and the toolchain it loads ` +
184
- `(${WORKER_TOOLCHAIN}) goes unattested. Wrap your config in withStasis(), or set ` +
185
- '`cacheStores: []` yourself for every stasis build.'
169
+ "[stasis] StasisMetro: wired without withStasis(), so Metro's transform cache may leave " +
170
+ `${WORKER_TOOLCHAIN} unattested: wrap your config in withStasis(), or set \`cacheStores: []\``
186
171
  )
187
172
  }
188
173
  this.#capture(graph, preModules)
189
- // The preload writes itself; a failed build never reaches serialization.
190
- if (this.#state !== State.preload) this.#state.write()
174
+ // A failed build never reaches serialization.
175
+ if (stasis.ownsWrite) stasis.state.write()
191
176
  }
192
177
 
193
178
  #capture(graph, preModules) {
179
+ const stasis = this.#stasis
194
180
  const entries = entrySet(graph)
195
- const platform = graph.transformOptions?.platform ?? null
196
- if (preModules) this.#captureModules(preModules, entries, platform)
197
- this.#captureModules(graph.dependencies.values(), entries, platform)
181
+ const platform = graph.transformOptions?.platform
182
+ for (const module of [...(preModules ?? []), ...graph.dependencies.values()]) {
183
+ const modPath = diskPath(module?.path)
184
+ if (modPath === undefined) continue
185
+ const kind = stasis.classify(modPath)
186
+ for (const [specifier, target] of this.#edges(module)) stasis.addImport(modPath, specifier, target)
187
+ if (!this.#captureRead(modPath, kind, entries.has(modPath))) continue
188
+ for (const { file } of this.#consumedResources(module, modPath)) this.#captureRead(file, 'resource')
189
+ if (!isAsset(module)) continue
190
+ // An asset's files: it and its other scales (metroAssetFiles, Metro's own rule for `platform`), by the name Metro
191
+ // reads each by, with the bytes it reads there, so a load holds that name to them; no import names one, so no
192
+ // edge. One linked from outside the project is passed over, as is one of a kind unknown (the module was refused).
193
+ for (const read of metroAssetFiles(modPath, platform)) {
194
+ const readKind = classifyExtension(read, stasis.state.config.resources)
195
+ if (readKind !== 'unknown' && this.#realWithin(read) !== null) this.#captureRead(read, readKind)
196
+ }
197
+ }
198
198
  this.#captureAutoIncludes()
199
199
  this.#captureTransformPlugins()
200
200
  // Last, past what is already captured: the native build inputs no module graph carries.
201
201
  this.#captureNativeModules()
202
202
  }
203
203
 
204
- #recordCapture(full, source, { format, resource, inferFormat = true, reason = 'metro' }) {
205
- this.#state.addFile(pathToFileURL(full).toString(), { source, format: format ?? undefined, resource, inferFormat, reason })
204
+ // Marks `file` seen and records it, its bytes `source` as read from disk (addFile re-reads it to assert them), as
205
+ // addFile `options` say.
206
+ #record(file, source, options) {
207
+ this.#stasis.seen.add(file)
208
+ this.#stasis.state.addFile(fileURL(file), { source, inferFormat: false, reason: 'metro', ...options })
206
209
  }
207
210
 
208
211
  // Each of AUTO_INCLUDES resolving within the project root, tagged by the shared classifier so it agrees with any
@@ -215,11 +218,10 @@ export class StasisMetro {
215
218
  } catch {
216
219
  continue
217
220
  }
218
- if (this.#seen.has(modPath) || !this.#within(modPath)) continue
219
- this.#seen.add(modPath)
221
+ if (this.#stasis.seen.has(modPath) || !this.#within(modPath)) continue
220
222
  const source = realReadFileSync(modPath)
221
223
  const format = classifyFormat(modPath, { content: source })
222
- this.#recordCapture(modPath, source, { format, resource: format === undefined, inferFormat: false, reason: 'run' })
224
+ this.#record(modPath, source, { format: format ?? undefined, resource: format === undefined, reason: 'run' })
223
225
  }
224
226
  }
225
227
 
@@ -227,56 +229,46 @@ export class StasisMetro {
227
229
  // for it, so a capture loads them all, as the loader then records with their imports, and records each under `run`.
228
230
  #captureTransformPlugins() {
229
231
  for (const file of metroTransformPluginFiles(this.#projectDir)) {
230
- if (this.#seen.has(file) || !this.#within(file)) continue
231
- this.#seen.add(file)
232
+ if (this.#stasis.seen.has(file) || !this.#within(file)) continue
232
233
  try {
233
234
  require(file)
234
235
  } catch { /* one that can't load can't run under Metro either: its bytes are still recorded */ }
235
- this.#recordCapture(file, realReadFileSync(file), { reason: 'run' })
236
+ this.#record(file, realReadFileSync(file), { inferFormat: true, reason: 'run' })
236
237
  }
237
238
  }
238
239
 
239
240
  // The native build inputs of the deps autolinking reports, of those the graph reached that ship native code
240
241
  // (integrated by hand), and of RN core, which config names only as reactNativePath. One outside the root is skipped.
241
242
  #captureNativeModules() {
243
+ const { seen, state } = this.#stasis
242
244
  const config = loadReactNativeConfig(this.#projectDir)
243
245
  if (!config) return
244
246
  const roots = new Set()
245
247
  for (const dep of Object.values(config.dependencies ?? {})) {
246
248
  if (isNativeDependency(dep) && typeof dep.root === 'string' && isAbsolute(dep.root)) roots.add(dep.root)
247
249
  }
248
- for (const root of this.#reachedNativePackageRoots()) roots.add(root)
250
+ // RN core is walked as reactNativePath.
251
+ const reached = seen.values().map((abs) => splitNodeModulesPath(abs)).filter((nm) => nm && nm.name !== 'react-native')
252
+ for (const root of new Set(reached.map((nm) => nm.dir))) if (looksNative(root, diskHost)) roots.add(root)
249
253
  const rnPath = typeof config.reactNativePath === 'string' && isAbsolute(config.reactNativePath) ? config.reactNativePath : null
250
254
  if (rnPath !== null) roots.add(rnPath)
251
- for (const root of roots) if (this.#within(root)) this.#captureNativeTree(root)
252
- // RN core's `.js` build scripts, which the walk leaves to Metro but its graph never has.
253
- if (rnPath !== null && this.#within(rnPath)) for (const file of RN_CORE_INCLUDE_FILES) this.#captureNativeFile(join(rnPath, file))
254
- }
255
-
256
- #captureNativeFile(full) {
257
- if (this.#seen.has(full)) return
258
- let source
259
- try {
260
- source = realReadFileSync(full)
261
- } catch {
262
- return
255
+ for (const root of roots) {
256
+ if (!this.#within(root)) continue
257
+ // In the format nativeInputs gives (a codegen source's generic, as Metro's code has, so none is inferred).
258
+ const inputs = nativeInputs(root, diskHost, { resources: state.config.resources, skip: (file) => seen.has(file) })
259
+ for (const { file, source, action, format } of inputs) this.#record(file, source, { format, resource: action === 'resource' })
263
260
  }
264
- this.#seen.add(full)
265
- const format = classifyFormat(full, { content: source })
266
- this.#recordCapture(full, source, { format, resource: format === undefined })
267
- }
268
-
269
- // RN core is walked as reactNativePath.
270
- #reachedNativePackageRoots() {
271
- const reached = this.#seen.values().map((abs) => splitNodeModulesPath(abs)).filter((nm) => nm && nm.name !== 'react-native')
272
- return [...new Set(reached.map((nm) => nm.dir))].filter((root) => looksNative(root, diskHost))
273
- }
274
-
275
- // In the format nativeInputs gives (none for a codegen source, as Metro's code has none, so none is inferred).
276
- #captureNativeTree(root) {
277
- for (const { file, source, action, format } of nativeInputs(root, diskHost, { resources: this.#resources, skip: (f) => this.#seen.has(f) })) {
278
- this.#seen.add(file)
279
- this.#recordCapture(file, source, { format, resource: action === 'resource', inferFormat: false })
261
+ // RN core's `.js` build scripts, which the walk leaves to Metro but its graph never has, typed as the loader would.
262
+ if (rnPath === null || !this.#within(rnPath)) return
263
+ for (const file of RN_CORE_INCLUDE_FILES.map((rel) => join(rnPath, rel))) {
264
+ if (seen.has(file)) continue
265
+ let source
266
+ try {
267
+ source = realReadFileSync(file)
268
+ } catch {
269
+ continue
270
+ }
271
+ this.#record(file, source, { inferFormat: true })
280
272
  }
281
273
  }
282
274
 
@@ -285,55 +277,39 @@ export class StasisMetro {
285
277
  #assertEdges(graph, preModules) {
286
278
  const platform = graph.transformOptions?.platform ?? undefined
287
279
  for (const module of [...(preModules ?? []), ...graph.dependencies.values()]) {
288
- const modPath = diskPath(module)
280
+ const modPath = diskPath(module?.path)
289
281
  if (modPath === undefined) continue
290
- const url = pathToFileURL(modPath).toString()
291
- for (const [specifier, target] of this.#edges(module)) this.#state.assertImport(url, specifier, target, { platform })
282
+ const url = fileURL(modPath)
283
+ for (const [specifier, target] of this.#edges(module)) this.#stasis.state.assertImport(url, specifier, fileURL(target), { platform })
292
284
  for (const files of this.#consumedResources(module, modPath)) {
293
285
  this.#assertOnDisk(files, { what: `which a Babel plugin inlines into '${modPath}'`, servedBy: ['sync', 'async'] })
294
286
  }
295
- this.#assertAssetFiles(module, modPath, platform ?? null)
287
+ if (isAsset(module)) this.#assertAssetFiles(modPath, platform)
296
288
  }
297
289
  }
298
290
 
299
291
  // A module's edges, keyed as the source wrote them (`stasisAsWritten`, where Babel rewrote one), to code and resource
300
292
  // targets alike. One the source doesn't write (`stasisInserted`: a Babel helper, Metro's asyncRequire) is no edge.
301
- #edges(module) {
302
- const edges = []
293
+ * #edges(module) {
303
294
  for (const dep of module.dependencies?.values?.() ?? []) {
304
295
  if (dep?.data?.stasisInserted === true) continue
305
- const target = dep?.absolutePath
306
- if (typeof target !== 'string' || !isAbsolute(target) || !existsSync(target)) continue
307
- if (classifyExtension(target, this.#resources) === 'unknown') continue
296
+ const target = diskPath(dep?.absolutePath)
297
+ if (target === undefined || classifyExtension(target, this.#stasis.state.config.resources) === 'unknown') continue
308
298
  for (const specifier of dep.data?.stasisAsWritten ?? [dep.data?.name]) {
309
- if (typeof specifier === 'string') edges.push([specifier, pathToFileURL(target).toString()])
299
+ if (typeof specifier === 'string') yield [specifier, target]
310
300
  }
311
301
  }
312
- return edges
313
- }
314
-
315
- #captureModules(modules, entries, platform) {
316
- for (const module of modules) {
317
- const modPath = diskPath(module)
318
- if (modPath === undefined) continue
319
- const kind = classifyOrThrow('StasisMetro', modPath, this.#resources)
320
- const url = pathToFileURL(modPath).toString()
321
- for (const [specifier, target] of this.#edges(module)) this.#state.addImport(url, specifier, target)
322
- if (!this.#captureRead(modPath, kind, entries.has(modPath))) continue
323
- for (const { file } of this.#consumedResources(module, modPath)) this.#captureRead(file, 'resource')
324
- this.#captureAssetFiles(module, modPath, platform)
325
- }
326
302
  }
327
303
 
328
304
  #within(path) {
329
- return isPathWithin(this.#state.root, path)
305
+ return isPathWithin(this.#stasis.state.root, path)
330
306
  }
331
307
 
332
308
  #realWithin(path) {
333
309
  let real
334
310
  try {
335
311
  real = diskHost.realpath(path)
336
- this.#realRoot ??= diskHost.realpath(this.#state.root)
312
+ this.#realRoot ??= diskHost.realpath(this.#stasis.state.root)
337
313
  } catch {
338
314
  return null
339
315
  }
@@ -349,84 +325,54 @@ export class StasisMetro {
349
325
  const read = resolve(dirname(modPath), specifier)
350
326
  const file = diskHost.stat(read)?.isFile() ? this.#realWithin(read) : null
351
327
  if (file === null) continue
352
- if (classifyOrThrow('StasisMetro', file, this.#resources, `'${file}', which a Babel plugin inlines into '${modPath}'`) === 'code') continue
328
+ if (this.#stasis.classify(file, `'${file}', which a Babel plugin inlines into '${modPath}'`) === 'code') continue
353
329
  yield { file, read }
354
330
  }
355
331
  }
356
332
 
357
- // Capture `path` once, as the `kind` classifyExtension gives it: code with only the format its name gives
358
- // (nodeExtFormat), as Metro transforms it from source. From disk: addFile re-reads it to assert the bytes.
359
- // -> whether it was new
333
+ // Capture `path` once, as the `kind` classifyExtension gives it: code in the format Metro builds it in
334
+ // (metroFormat), as Metro transforms it from source. -> whether it was new
360
335
  #captureRead(path, kind, isEntry = false) {
361
- if (this.#seen.has(path)) return false
362
- this.#seen.add(path)
363
- const source = realReadFileSync(path)
364
- if (kind === 'code') assertCodeUtf8('StasisMetro', path, source)
365
- const format = kind === 'code' ? nodeExtFormat(path) : undefined
366
- const resource = kind === 'resource'
367
- this.#state.addFile(pathToFileURL(path).toString(), { source, format, isEntry, resource, inferFormat: false, reason: 'metro' })
336
+ if (!this.#stasis.claim(path)) return false
337
+ const format = kind === 'code' ? metroFormat(path) : undefined
338
+ this.#stasis.addFile(path, realReadFileSync(path), kind, isEntry, { format, inferFormat: false })
368
339
  return true
369
340
  }
370
341
 
371
- // The files Metro reads to build the asset module `module` (its `scales` and `hash`) and copies out with it: it
372
- // and its other scales (metroAssetFiles, Metro's own rule for `platform`). No import names one, so no edge.
373
- #assetFiles(module, modPath, platform) {
374
- return module.output?.[0]?.type === 'js/module/asset' ? metroAssetFiles(modPath, platform, this.#assetDirHost()) : []
375
- }
376
-
377
- // Where Metro lists an asset's files: on disk, but under load with --fs=async, which serves the listing, the
378
- // bundle's (a file added on disk since is none of the asset's; one gone from disk holds no drift).
379
- #assetDirHost() {
380
- const state = this.#state
381
- if (!state.config.loadBundle || state.config.fs !== 'async') return diskHost
382
- return {
383
- readdir: (dir) => state.getFsDirFamily(pathToFileURL(dir).toString())?.map((name) => ({ name })) ?? diskHost.readdir(dir),
384
- stat: (path) => diskHost.stat(path) ?? (state.getFsStatFamily(pathToFileURL(path).toString()) === 'file' ? FILE_STAT : null),
385
- }
386
- }
387
-
388
- #bundleDirHost() {
389
- return (this.#bundleDirs ??= bundleDirHost(this.#state))
390
- }
391
-
392
- // By the name Metro reads each by, with the bytes it reads there, so a load holds that name to them. One linked
393
- // from outside the project is passed over, as is one of a kind unknown (the module itself was refused).
394
- #captureAssetFiles(module, modPath, platform) {
395
- for (const read of this.#assetFiles(module, modPath, platform)) {
396
- const kind = classifyExtension(read, this.#resources)
397
- if (kind !== 'unknown' && this.#realWithin(read) !== null) this.#captureRead(read, kind)
398
- }
399
- }
400
-
401
342
  // Metro reads an asset's files from disk, past the stasis transformer: each must be the bundle's under that name (a
402
343
  // scale added since the capture, or one a symlink redirects, is drift), and each the bundle carries must still be
403
- // there (one gone builds another asset) -- unless --fs=async serves them.
404
- #assertAssetFiles(module, modPath, platform) {
405
- const read = this.#assetFiles(module, modPath, platform)
344
+ // there (one gone builds another asset) -- unless --fs=async serves them, and their listing too: then a file added
345
+ // on disk since is none of the asset's, and one gone from disk holds no drift.
346
+ #assertAssetFiles(modPath, platform) {
347
+ const { state } = this.#stasis
348
+ const listed = state.config.fs !== 'async' ? diskHost : {
349
+ readdir: (dir) => state.getFsDirFamily(fileURL(dir))?.map((name) => ({ name })) ?? diskHost.readdir(dir),
350
+ stat: (path) => diskHost.stat(path) ?? (state.getFsStatFamily(fileURL(path)) === 'file' ? FILE_STAT : null),
351
+ }
352
+ const read = metroAssetFiles(modPath, platform, listed)
406
353
  if (read.length === 0) return
407
354
  const what = `a file of the asset '${modPath}' Metro builds`
408
355
  for (const path of read) {
409
356
  if (diskHost.stat(path)?.isFile()) this.#assertOnDisk({ file: path, read: path }, { what, servedBy: ['async'] })
410
357
  }
411
- if (!inScope(this.#state, pathToFileURL(modPath).toString())) return
412
- for (const file of metroAssetFiles(modPath, platform, this.#bundleDirHost())) {
358
+ if (!inScope(state, fileURL(modPath))) return
359
+ for (const file of metroAssetFiles(modPath, platform, (this.#bundleDirs ??= bundleDirHost(state)))) {
413
360
  if (read.includes(file)) continue
414
- throw new Error(`StasisMetro: '${file}', ${what} as the bundle carries it, is gone -- Metro would build the asset without it under load; restore it`)
361
+ throw new Error(`StasisMetro: '${file}', ${what} as the bundle carries it, is gone; restore it`)
415
362
  }
416
363
  }
417
364
 
418
365
  // `read`, a file Metro reads from disk past the stasis transformer, held to the bundle's bytes for `file` where in
419
366
  // scope (getFile throws on one it doesn't carry) -- unless --fs, in a mode of `servedBy`, serves it by the path read.
420
367
  #assertOnDisk({ file, read }, { what, servedBy }) {
421
- const state = this.#state
422
- const url = pathToFileURL(file).toString()
368
+ const { state } = this.#stasis
369
+ const url = fileURL(file)
423
370
  if (!inScope(state, url)) return
424
- if (servedBy.includes(state.config.fs) && state.getFsFileFamily(pathToFileURL(read).toString()) !== undefined) return
371
+ if (servedBy.includes(state.config.fs) && state.getFsFileFamily(fileURL(read)) !== undefined) return
425
372
  const { source } = state.getFile(url)
426
373
  if (realReadFileSync(file).equals(Buffer.isBuffer(source) ? source : Buffer.from(source))) return
427
374
  throw new Error(
428
- `StasisMetro: '${file}', ${what}, differs on disk from the bundle -- ` +
429
- 'Metro\'s build reads it from disk under load; restore it, or run with --fs to serve it from the bundle'
375
+ `StasisMetro: '${file}', ${what}, differs on disk from the bundle: restore it, or run with --fs`
430
376
  )
431
377
  }
432
378
  }
@@ -444,8 +390,7 @@ export function withStasis(config = {}, options = {}) {
444
390
  const stores = config.cacheStores
445
391
  if (active && (typeof stores === 'function' || stores?.length > 0)) {
446
392
  console.warn(
447
- '[stasis] StasisMetro: ignoring the `cacheStores` in your Metro config for this build -- a cached ' +
448
- 'transform skips the worker, leaving the toolchain it loads unattested'
393
+ '[stasis] StasisMetro: ignoring the `cacheStores` in your Metro config for this build'
449
394
  )
450
395
  }
451
396
  // Metro hands `transformer` to each worker's transformer as is.
package/src/plugins.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import assert from 'node:assert/strict'
2
2
  import { isUtf8 } from 'node:buffer'
3
+ import { pathToFileURL } from 'node:url'
3
4
 
4
5
  import { DEFAULT_LOCK, assertKnownKeys, assertOption } from '@exodus/stasis-core/config'
5
6
  import { ensureStateForLoader, isLoaderInstalled } from '@exodus/stasis-core/hooks'
@@ -101,42 +102,28 @@ export function resolvePluginState(label, options, cwd) {
101
102
  throw new Error(`${label}: bundle='${bundle}' conflicts with active preload bundle='${pc.bundleMode}'`)
102
103
  }
103
104
  if (bundleFile !== undefined && bundleFile !== pc.bundleFile) return sidecar(pc.bundleMode)
104
- assertOptionsMatchConfig(pc, options)
105
- return { state: ambient, isNoop: false }
106
- }
107
-
108
- if (bundle === undefined || bundle === 'none' || bundle === 'ignore') {
109
- // 'ignore' and the preload's 'none' both mean no bundle, so the field leaves the cross-check; the assert pins
110
- // that to today's no-bundle modes, so that a future one can't silently mask a disagreement.
105
+ } else if (bundle === undefined || bundle === 'none' || bundle === 'ignore') {
106
+ // 'ignore' and the preload's 'none' both mean no bundle; the assert pins that to today's no-bundle modes, so
107
+ // that a future one can't silently mask a disagreement.
111
108
  assert.ok(pc.bundleMode === 'none' || pc.bundleMode === 'ignore',
112
109
  `unexpected preload bundleMode='${pc.bundleMode}' in the no-bundle branch`)
113
- const { bundle: _b, ...rest } = options
114
- assertOptionsMatchConfig(pc, rest)
115
- return { state: ambient, isNoop: false }
116
- }
117
- if (!bundleFile) {
118
- throw new Error(`${label}: bundle='${bundle}' alongside a preload without bundle requires an explicit bundleFile`)
110
+ } else {
111
+ if (!bundleFile) {
112
+ throw new Error(`${label}: bundle='${bundle}' alongside a preload without bundle requires an explicit bundleFile`)
113
+ }
114
+ return sidecar(bundle)
119
115
  }
120
- return sidecar(bundle)
116
+ // The bundle field is settled above, and leaves the cross-check.
117
+ assertOptionsMatchConfig(pc, { ...options, bundle: undefined })
118
+ return { state: ambient, isNoop: false }
121
119
  }
122
120
 
123
121
  // A State the caller owns (`stasis build`'s), else resolvePluginState's; a foreign copy's State fails the instanceof.
124
122
  export const ownOrResolvedState = (label, options) =>
125
123
  (options instanceof State ? options : resolvePluginState(label, options, process.cwd()).state)
126
124
 
127
- // Dedupe is by path, so a rebuild with new bytes would emit them while the bundle and lockfile keep the old ones.
128
- export const rebuildRefused = (label) =>
129
- `${label}: watch/rebuild is not supported for capture -- run a one-shot build (rebuilds would silently attest stale content)`
130
-
131
125
  export const unsupportedExtension = (label, what) =>
132
- `${label}: unsupported extension for ${what} -- add its extension or filename to the plugin's resources option or stop importing it`
133
-
134
- // A file's kind (code|resource), or a throw naming it as `what` where it's neither.
135
- export function classifyOrThrow(label, path, resources, what = `'${path}'`) {
136
- const kind = classifyExtension(path, resources)
137
- if (kind === 'unknown') throw new Error(unsupportedExtension(label, what))
138
- return kind
139
- }
126
+ `${label}: unsupported extension for ${what}; add its extension or filename to the plugin's resources option`
140
127
 
141
128
  // Refuse non-UTF-8 code rather than silently encode it as a resource.
142
129
  export function assertCodeUtf8(label, path, source) {
@@ -148,13 +135,65 @@ export function assertPersistableAttributes(attrs) {
148
135
  for (const k of Object.keys(attrs)) assert.equal(k, 'type', `unsupported import attribute: ${k}`)
149
136
  }
150
137
 
151
- // `state.getImport(...)`, or undefined where the bundle attests no such edge: an EXTERNAL at capture, which the
152
- // bundler resolves as without us (file BYTES still fail closed where the plugin loads them).
153
- export function attestedImport(state, parentURL, specifier, options) {
154
- try {
155
- return state.getImport(parentURL, specifier, options)
156
- } catch (err) {
157
- if (err?.code === 'ERR_MODULE_NOT_FOUND') return undefined
158
- throw err
138
+ export const fileURL = (path) => pathToFileURL(path).toString()
139
+
140
+ // The lifecycle every bundler plugin shares over the State it runs against (null: inert), by file path: a one-shot
141
+ // capture deduped by path, its edges and files recorded, edges looked up at load, and the write.
142
+ export class PluginState {
143
+ seen = new Set()
144
+ #builds = 0
145
+
146
+ constructor(label, reason, state) {
147
+ this.label = label
148
+ this.reason = reason
149
+ this.state = state
150
+ }
151
+
152
+ // Dedupe is by path, so a rebuild with new bytes would emit them while the bundle and lockfile keep the old ones.
153
+ // -> `refusal` for each build after the first
154
+ startBuild(refusal = `${this.label}: watch/rebuild is not supported for capture -- run a one-shot build`) {
155
+ this.#builds += 1
156
+ if (this.#builds === 1) return undefined
157
+ return refusal
158
+ }
159
+
160
+ // A file's kind (code|resource), or a throw naming it as `what` where it's neither.
161
+ classify(path, what = `'${path}'`) {
162
+ const kind = classifyExtension(path, this.state.config.resources)
163
+ if (kind === 'unknown') throw new Error(unsupportedExtension(this.label, what))
164
+ return kind
165
+ }
166
+
167
+ // Whether `path` is new to this plugin, marking it seen.
168
+ claim(path) {
169
+ if (this.seen.has(path)) return false
170
+ this.seen.add(path)
171
+ return true
172
+ }
173
+
174
+ // `options` go on to State#addFile as given (Metro's format and inferFormat).
175
+ addFile(path, source, kind, isEntry, options) {
176
+ if (kind === 'code') assertCodeUtf8(this.label, path, source)
177
+ this.state.addFile(fileURL(path), { source, isEntry, resource: kind === 'resource', reason: this.reason, ...options })
178
+ }
179
+
180
+ addImport(importer, specifier, target, importAttributes) {
181
+ this.state.addImport(fileURL(importer), specifier, fileURL(target), { importAttributes })
182
+ }
183
+
184
+ // `state.getImport(...)`, or undefined where the bundle attests no such edge: an EXTERNAL at capture, which the
185
+ // bundler resolves as without us (file BYTES still fail closed where the plugin loads them).
186
+ attestedImport(importer, specifier, options) {
187
+ try {
188
+ return this.state.getImport(fileURL(importer), specifier, options)
189
+ } catch (err) {
190
+ if (err?.code === 'ERR_MODULE_NOT_FOUND') return undefined
191
+ throw err
192
+ }
193
+ }
194
+
195
+ // The preload writes itself.
196
+ get ownsWrite() {
197
+ return this.state !== State.preload
159
198
  }
160
199
  }