@exodus/stasis-plugins 1.0.0-rc.1 → 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/rollup.js CHANGED
@@ -2,15 +2,14 @@ import assert from 'node:assert/strict'
2
2
  import { existsSync } from 'node:fs'
3
3
  import { isBuiltin } from 'node:module'
4
4
  import { dirname, isAbsolute, resolve as resolvePath } from 'node:path'
5
- import { fileURLToPath, pathToFileURL } from 'node:url'
5
+ import { fileURLToPath } from 'node:url'
6
6
 
7
7
  import { Bundle } from '@exodus/stasis-core/bundle'
8
- import { assertCodeUtf8, assertPersistableAttributes, attestedImport, classifyOrThrow, ownOrResolvedState, rebuildRefused } from './plugins.js'
9
- import { State } from '@exodus/stasis-core/state'
8
+ import { PluginState, assertPersistableAttributes, fileURL, ownOrResolvedState } from './plugins.js'
10
9
  // Pre-patch snapshot, not `import { readFile }`: under --fs=async that builtin is patched, and
11
10
  // this plugin loads after, so a direct import would route rollup's reads through the capture hook.
12
- import { inScope, realReadFile } from '@exodus/stasis-core/state-util'
13
- import { classifyExtension, isPathWithin } from '@exodus/stasis-core/util'
11
+ import { inScope, realReadFile, servedByBundle } from '@exodus/stasis-core/state-util'
12
+ import { isPathWithin } from '@exodus/stasis-core/util'
14
13
 
15
14
  // An on-disk file by its absolute path, not a sibling plugin's virtual module (\0-prefixed or relative) or no importer.
16
15
  const isDiskId = (id) => Boolean(id) && isAbsolute(id) && !id.startsWith('\0')
@@ -18,39 +17,32 @@ const isDiskId = (id) => Boolean(id) && isAbsolute(id) && !id.startsWith('\0')
18
17
  // Rollup chains resolveId/load hooks first-non-null-wins, so this plugin goes FIRST in `plugins`: listed later, a
19
18
  // sibling resolver answers before stasis sees the edge (file BYTES still fail closed at the load hook).
20
19
  export class StasisRollup {
21
- #seen = new Set()
22
- #state
23
- #resources
24
- #captureBuildCount = 0
20
+ #stasis
25
21
 
26
22
  name = 'stasis'
27
23
 
28
24
  constructor(options = {}, unsupported = undefined) {
29
25
  // Transforms run as ordinary rollup plugins after this one: refuse a port's esbuild-style bag, not drop it.
30
26
  assert.equal(unsupported, undefined,
31
- 'StasisRollup takes a single options argument -- there is no esbuild-style { loaders, transform } bag (run transforms as rollup plugins after this one)')
32
- const state = ownOrResolvedState('StasisRollup', options)
33
- this.#state = state
34
- this.#resources = state?.config.resources ?? new Set()
27
+ 'StasisRollup takes a single options argument')
28
+ this.#stasis = new PluginState('StasisRollup', 'rollup', ownOrResolvedState('StasisRollup', options))
29
+ const { state } = this.#stasis
35
30
  if (!state) return // inert: rollup sees only `name`
36
31
 
37
- // Rollup binds `this` to its PluginContext, so the instance arrives via the closure.
32
+ // Rollup binds `this` to its PluginContext, so a hook gets it as `ctx` and the instance via the closure.
38
33
  const plugin = this
39
- this.resolveId = function (source, importer, opts) {
40
- return plugin.#resolveId(this, source, importer, opts)
41
- }
42
- this.load = function (id) {
43
- return plugin.#load(this, id)
34
+ const hook = (method) => function (...args) {
35
+ return method.call(plugin, this, ...args)
44
36
  }
37
+ this.resolveId = hook(this.#resolveId)
38
+ this.load = hook(this.#load)
45
39
 
46
40
  // A warm `cache:` object reuses modules and resolutions WITHOUT calling resolveId/load, so they'd go unattested
47
41
  // at capture and unverified at load. Rollup still builds a fresh cache for this run.
48
42
  this.options = (inputOptions) => {
49
43
  if (typeof inputOptions.cache !== 'object' || inputOptions.cache === null) return null
50
44
  console.warn(
51
- '[stasis] StasisRollup: ignoring the `cache` option for this build -- cached modules ' +
52
- 'bypass the stasis hooks, so their imports and bytes would go unattested at capture and ' +
53
- 'unverified at load'
45
+ '[stasis] StasisRollup: ignoring the `cache` option for this build'
54
46
  )
55
47
  return { ...inputOptions, cache: undefined }
56
48
  }
@@ -58,21 +50,17 @@ export class StasisRollup {
58
50
  if (!state.config.loadBundle) {
59
51
  // Watch rebuilds, and a second rollup() call reusing this instance, re-fire buildStart.
60
52
  this.buildStart = () => {
61
- plugin.#captureBuildCount += 1
62
- if (plugin.#captureBuildCount > 1) throw new Error(rebuildRefused('StasisRollup'))
63
- }
64
- this.buildEnd = function (error) {
65
- return plugin.#buildEnd(this, error)
53
+ const refusal = this.#stasis.startBuild()
54
+ if (refusal) throw new Error(refusal)
66
55
  }
56
+ this.buildEnd = hook(this.#buildEnd)
67
57
  }
68
58
  }
69
59
 
70
60
  // Rollup asset plugins read their files from disk in their own load hook, with no seam for attested bytes.
71
61
  #refuseResourceLoad(path) {
72
62
  throw new Error(
73
- `StasisRollup: bundle=load can't serve resource '${path}' -- rollup asset plugins read ` +
74
- 'from disk directly, so attested replay is not possible; keep sources on disk and use a ' +
75
- 'capture/verify mode instead'
63
+ `StasisRollup: bundle=load can't serve resource '${path}'`
76
64
  )
77
65
  }
78
66
 
@@ -82,15 +70,14 @@ export class StasisRollup {
82
70
  const stripped = id.split(/[?#]/u, 1)[0]
83
71
  if (stripped !== id && existsSync(stripped)) {
84
72
  throw new Error(
85
- `StasisRollup: can't attest suffixed module id '${id}' (the on-disk file '${stripped}' ` +
86
- "with a '?'/'#' suffix) -- stasis can't persist suffixes; disable the plugin minting it " +
87
- 'or import the file directly'
73
+ `StasisRollup: can't attest suffixed module id '${id}' (the on-disk file '${stripped}' with a '?'/'#' suffix)`
88
74
  )
89
75
  }
90
76
  }
91
77
 
92
- #inRoot(path) {
93
- return isPathWithin(this.#state.root, path)
78
+ // An on-disk id under the project root.
79
+ #inRoot(id) {
80
+ return isDiskId(id) && isPathWithin(this.#stasis.state.root, id)
94
81
  }
95
82
 
96
83
  async #resolveId(ctx, source, importer, opts) {
@@ -98,9 +85,10 @@ export class StasisRollup {
98
85
  // can't redirect `fs`.
99
86
  if (isBuiltin(source)) return null
100
87
  const { isEntry, attributes: attrs = {} } = opts
88
+ const stasis = this.#stasis
101
89
 
102
90
  // Load mode resolves through the bundle's import map: the file may not be on disk.
103
- if (this.#state.config.loadBundle) {
91
+ if (stasis.state.config.loadBundle) {
104
92
  if (isEntry) {
105
93
  // Rollup defaults isEntry to !importer, so this covers bare sibling probes too: the load hook asserts entries
106
94
  // from the graph instead. Anchored as rollup's resolver does, else to cwd as the run loader is.
@@ -108,14 +96,14 @@ export class StasisRollup {
108
96
  const base = isDiskId(importer) ? dirname(importer) : process.cwd()
109
97
  return { id: resolvePath(base, source) }
110
98
  }
111
- if (!isDiskId(importer) || !this.#inRoot(importer)) return null
99
+ if (!this.#inRoot(importer)) return null
112
100
  assertPersistableAttributes(attrs)
113
- const attested = attestedImport(this.#state, pathToFileURL(importer).toString(), source, { importAttributes: attrs })
101
+ const attested = stasis.attestedImport(importer, source, { importAttributes: attrs })
114
102
  if (attested === undefined) return null
115
103
  const { url, format } = attested
116
104
  const path = fileURLToPath(url)
117
105
  // An out-of-scope resource comes from disk through the user's asset plugin, as at capture.
118
- if (Bundle.isResourceFormat(format) && inScope(this.#state, url)) this.#refuseResourceLoad(path)
106
+ if (Bundle.isResourceFormat(format) && inScope(stasis.state, url)) this.#refuseResourceLoad(path)
119
107
  // KNOWN GAP: a sibling's resolution metadata (moduleSideEffects, syntheticNamedExports, meta) isn't in the
120
108
  // bundle, so tree-shaking may differ from the capture build's.
121
109
  return { id: path }
@@ -130,32 +118,33 @@ export class StasisRollup {
130
118
  this.#refuseSuffixedOnDisk(id)
131
119
  return resolution
132
120
  }
133
- classifyOrThrow('StasisRollup', id, this.#resources)
121
+ stasis.classify(id)
134
122
 
135
123
  // Code and resource targets alike, but never for an entry, flagged from the graph in buildEnd (opts.isEntry is
136
124
  // a sibling's probe too), nor an out-of-root importer, which load mode defers too.
137
- if (!isEntry && isDiskId(importer) && this.#inRoot(importer)) {
125
+ if (!isEntry && this.#inRoot(importer)) {
138
126
  assertPersistableAttributes(attrs)
139
127
  if (!this.#inRoot(id)) {
140
128
  throw new Error(
141
129
  `StasisRollup: '${source}' imported from ${importer} resolves outside the project root and can't be attested: ${id}`
142
130
  )
143
131
  }
144
- this.#state.addImport(pathToFileURL(importer).toString(), source, pathToFileURL(id).toString(), { importAttributes: attrs })
132
+ stasis.addImport(importer, source, id, attrs)
145
133
  }
146
134
  return resolution
147
135
  }
148
136
 
149
137
  async #load(ctx, id) {
138
+ const stasis = this.#stasis
139
+ const { state } = stasis
150
140
  // getFile verifies the hash and throws on a file the bundle doesn't carry: no disk fallback. Ids other plugins
151
141
  // resolved land here too.
152
- if (this.#state.config.loadBundle) {
153
- if (!isDiskId(id) || !this.#inRoot(id)) return null
154
- const url = pathToFileURL(id).toString()
142
+ if (state.config.loadBundle) {
143
+ if (!isDiskId(id) || !servedByBundle(state, id)) return null
144
+ const url = fileURL(id)
155
145
  // The graph's isEntry: a sibling's resolve() probe carries isEntry too but never loads.
156
- if (this.#state.config.full && ctx.getModuleInfo(id)?.isEntry) this.#state.assertEntry(url)
157
- if (!inScope(this.#state, url)) return null
158
- const { source, format } = this.#state.getFile(url)
146
+ if (state.config.full && ctx.getModuleInfo(id)?.isEntry) state.assertEntry(url)
147
+ const { source, format } = state.getFile(url)
159
148
  if (Bundle.isResourceFormat(format)) this.#refuseResourceLoad(id)
160
149
  return source
161
150
  }
@@ -170,34 +159,29 @@ export class StasisRollup {
170
159
  this.#refuseSuffixedOnDisk(id)
171
160
  return null
172
161
  }
173
- const resource = classifyOrThrow('StasisRollup', id, this.#resources) === 'resource'
162
+ const kind = stasis.classify(id)
174
163
  if (!this.#inRoot(id)) {
175
164
  throw new Error(`StasisRollup: module is outside the project root and can't be attested: ${id}`)
176
165
  }
177
- if (!resource) assertCodeUtf8('StasisRollup', id, source)
178
- if (!this.#seen.has(id)) {
179
- this.#seen.add(id)
180
- this.#state.addFile(pathToFileURL(id).toString(), { source, resource, reason: 'rollup' })
181
- }
166
+ // Rollup loads an id once per build.
167
+ if (stasis.claim(id)) stasis.addFile(id, source, kind)
182
168
  // A resource is the user's asset plugin's to load; code is served as recorded (transform hooks still run after).
183
- return resource ? null : source.toString('utf8')
169
+ return kind === 'resource' ? null : source.toString('utf8')
184
170
  }
185
171
 
186
172
  // Flags the graph's real entries (resolveId's opts.isEntry would take a sibling's bare probe for one), then writes
187
173
  // a standalone or sidecar State on a clean build. buildEnd, not closeBundle, which only bundle.close() fires.
188
174
  async #buildEnd(ctx, error) {
189
175
  if (error) return
176
+ const stasis = this.#stasis
190
177
  const entryIds = [...ctx.getModuleIds()].filter((id) => {
191
- if (!this.#seen.has(id)) return false
178
+ if (!stasis.seen.has(id)) return false
192
179
  const info = ctx.getModuleInfo(id)
193
180
  return Boolean(info?.isEntry) && !info.isExternal
194
181
  })
195
182
  // addFile re-verifies the bytes, and refuses a RESOURCE entry, as StasisEsbuild does.
196
183
  const sources = await Promise.all(entryIds.map((id) => realReadFile(id)))
197
- for (const [i, id] of entryIds.entries()) {
198
- const resource = classifyExtension(id, this.#resources) === 'resource'
199
- this.#state.addFile(pathToFileURL(id).toString(), { source: sources[i], isEntry: true, resource, reason: 'rollup' })
200
- }
201
- if (this.#state !== State.preload) this.#state.write()
184
+ for (const [i, id] of entryIds.entries()) stasis.addFile(id, sources[i], stasis.classify(id), true)
185
+ if (stasis.ownsWrite) stasis.state.write()
202
186
  }
203
187
  }
package/src/webpack.js CHANGED
@@ -1,11 +1,11 @@
1
- import { existsSync } from 'node:fs'
1
+ import { Stats, existsSync } from 'node:fs'
2
2
  import { createRequire, isBuiltin } from 'node:module'
3
3
  import path from 'node:path'
4
- import { fileURLToPath, pathToFileURL } from 'node:url'
4
+ import { fileURLToPath } from 'node:url'
5
5
 
6
- import { assertCodeUtf8, attestedImport, classifyOrThrow, resolvePluginState } from './plugins.js'
7
- import { State } from '@exodus/stasis-core/state'
6
+ import { PluginState, fileURL, resolvePluginState } from './plugins.js'
8
7
  import { realReadFileSync, servedByBundle } from '@exodus/stasis-core/state-util'
8
+ import { upsert } from '@exodus/stasis-core/util'
9
9
 
10
10
  const require = createRequire(import.meta.url)
11
11
 
@@ -17,36 +17,31 @@ const edgeKey = (importerAbsolute, request) => `${importerAbsolute}\u0000${reque
17
17
  const PATCHED = Symbol('stasis.modresolver.patched')
18
18
 
19
19
  // For a bundle-served file under load: webpack's resolver needs only existence and size, the hash attests content.
20
+ // An fs.Stats answers its is*() from the mode, and its dates from the *Ms fields.
20
21
  function bundleStat(size, isDir = false) {
21
- return {
22
- isFile: () => !isDir,
23
- isDirectory: () => isDir,
24
- ...Object.fromEntries(['isSymbolicLink', 'isBlockDevice', 'isCharacterDevice', 'isFIFO', 'isSocket'].map((name) => [name, () => false])),
25
- size,
26
- ...Object.fromEntries(['mtime', 'atime', 'ctime', 'birthtime'].flatMap((name) => [[name, new Date(0)], [`${name}Ms`, 0]])),
22
+ return Object.assign(Object.create(Stats.prototype), {
27
23
  mode: isDir ? 0o040755 : 0o100644,
24
+ size,
25
+ atimeMs: 0, mtimeMs: 0, ctimeMs: 0, birthtimeMs: 0,
28
26
  uid: 0, gid: 0, ino: 0, nlink: 1, rdev: 0, blksize: 4096, blocks: 0, dev: 0,
29
- }
27
+ })
30
28
  }
31
29
 
32
30
  export class StasisWebpack {
33
- #seen = new Set()
34
- #state
35
- #resources
31
+ #stasis
36
32
  // The compilers this instance drives, final by the first `done`: N for a MultiCompiler, whose write is deferred.
37
33
  #captureApplyCount = 0
38
34
  #deferredWriteArmed = false
39
35
  #deferredWriteDirty = false
40
36
 
41
37
  constructor(options = {}) {
42
- const { state } = resolvePluginState('StasisWebpack', options, process.cwd())
43
- this.#state = state
44
- this.#resources = state?.config.resources ?? new Set()
38
+ this.#stasis = new PluginState('StasisWebpack', 'webpack', resolvePluginState('StasisWebpack', options, process.cwd()).state)
45
39
  }
46
40
 
47
41
  apply(compiler) {
48
- if (!this.#state) return
49
- if (this.#state.config.loadBundle) this.#applyLoadMode(compiler)
42
+ const { state } = this.#stasis
43
+ if (!state) return
44
+ if (state.config.loadBundle) this.#applyLoadMode(compiler)
50
45
  else this.#applyCaptureMode(compiler)
51
46
  }
52
47
 
@@ -54,43 +49,33 @@ export class StasisWebpack {
54
49
  // disk. The bundle is the FAMILY: this State, then its parent where it is a sidecar (one shared lockfile). KNOWN
55
50
  // LIMITATION: a package.json the resolver reads that no family bundle carries fails closed (tests/webpack.test.js).
56
51
  #applyLoadMode(compiler) {
57
- const state = this.#state
52
+ const { state } = this.#stasis
58
53
  const orig = compiler.inputFileSystem
59
54
  const served = (p) => typeof p === 'string' && p !== '' && servedByBundle(state, p)
60
55
  const family = state.parent ? [state, state.parent] : [state]
61
56
  const ownerOf = (url) => family.find((s) => s.getFsStat(url) !== undefined)
62
- // Throws on a miss: the fail-closed gate.
63
- const serveFromBundle = (p) => {
64
- const url = pathToFileURL(p).toString()
65
- return (ownerOf(url) ?? state).getFile(url).source
57
+ // `answer(bytes)` to the callback, or getFile's throw on a miss: the fail-closed gate.
58
+ const fromBundle = (p, callback, answer) => {
59
+ const url = fileURL(p)
60
+ try {
61
+ return callback(null, answer((ownerOf(url) ?? state).getFile(url).source))
62
+ } catch (err) {
63
+ return callback(err)
64
+ }
66
65
  }
67
66
 
68
67
  const wrappedReadFile = (p, options, callback) => {
69
68
  if (typeof options === 'function') { callback = options; options = undefined }
70
- if (served(p)) {
71
- try {
72
- const src = serveFromBundle(p)
73
- return callback(null, Buffer.isBuffer(src) ? src : Buffer.from(src))
74
- } catch (err) {
75
- return callback(err)
76
- }
77
- }
69
+ if (served(p)) return fromBundle(p, callback, (src) => (Buffer.isBuffer(src) ? src : Buffer.from(src)))
78
70
  // CachedInputFileSystem.readFile is (path, callback): an undefined middle arg would land in the callback slot.
79
71
  return options === undefined ? orig.readFile(p, callback) : orig.readFile(p, options, callback)
80
72
  }
81
73
  const wrappedStat = (p, callback) => {
82
- if (served(p)) {
83
- // The resolver stat()s the dirs it walks, which have no bundle content but an existence record.
84
- const url = pathToFileURL(p).toString()
85
- if (ownerOf(url)?.getFsStat(url) === 'directory') return callback(null, bundleStat(0, true))
86
- try {
87
- const src = serveFromBundle(p)
88
- return callback(null, bundleStat(typeof src === 'string' ? Buffer.byteLength(src) : src.length))
89
- } catch (err) {
90
- return callback(err)
91
- }
92
- }
93
- return orig.stat(p, callback)
74
+ if (!served(p)) return orig.stat(p, callback)
75
+ // The resolver stat()s the dirs it walks, which have no bundle content but an existence record.
76
+ const url = fileURL(p)
77
+ if (ownerOf(url)?.getFsStat(url) === 'directory') return callback(null, bundleStat(0, true))
78
+ return fromBundle(p, callback, (src) => bundleStat(Buffer.byteLength(src)))
94
79
  }
95
80
  // A Proxy, not Object.assign: CachedInputFileSystem keeps its state on `this`, so forwarded calls keep orig.
96
81
  compiler.inputFileSystem = new Proxy(orig, {
@@ -109,7 +94,7 @@ export class StasisWebpack {
109
94
  if (!issuer || !served(issuer)) return
110
95
  // SECURITY: never consult getImport for a builtin, so a tampered bundle can't redirect `fs`.
111
96
  if (isBuiltin(data.request)) return
112
- const resolved = attestedImport(state, pathToFileURL(issuer).toString(), data.request)
97
+ const resolved = this.#stasis.attestedImport(issuer, data.request)
113
98
  if (resolved === undefined) return
114
99
  // The stat wrapper then reports it exists.
115
100
  data.request = fileURLToPath(resolved.url)
@@ -121,7 +106,7 @@ export class StasisWebpack {
121
106
  // the parser and afterResolve sees only the rewrite. Wrapping its rewrite chokepoint (v5's lib/mapPath default, or
122
107
  // v3/v4's lib/utils.mapPathString) records the original, so the edge is keyed by the portable specifier.
123
108
  #patchModuleResolver() {
124
- const paths = [this.#state.root, process.cwd()]
109
+ const paths = [this.#stasis.state.root, process.cwd()]
125
110
  for (const [sub, prop] of [['babel-plugin-module-resolver/lib/mapPath', 'default'], ['babel-plugin-module-resolver/lib/utils', 'mapPathString']]) {
126
111
  let mod
127
112
  try {
@@ -139,9 +124,7 @@ export class StasisWebpack {
139
124
  const importer = state?.file?.opts?.filename
140
125
  if (typeof before === 'string' && before.startsWith('#') &&
141
126
  typeof after === 'string' && after !== before && typeof importer === 'string') {
142
- const key = edgeKey(path.resolve(importer), after)
143
- const originals = subpathOriginals.get(key) ?? []
144
- if (!originals.includes(before)) subpathOriginals.set(key, [...originals, before])
127
+ upsert(subpathOriginals, edgeKey(path.resolve(importer), after), () => new Set()).add(before)
145
128
  }
146
129
  } catch {
147
130
  // A recorder fault must never break the build: the rewrite already ran.
@@ -154,6 +137,7 @@ export class StasisWebpack {
154
137
  }
155
138
 
156
139
  #applyCaptureMode(compiler) {
140
+ const stasis = this.#stasis
157
141
  this.#captureApplyCount += 1
158
142
  // apply() runs at webpack() construction, before compiler.run(), so before any afterResolve.
159
143
  this.#patchModuleResolver()
@@ -173,43 +157,35 @@ export class StasisWebpack {
173
157
  // No on-disk file to hash: data: URIs, null-loader stubs.
174
158
  const filePath = cd.resourceResolveData?.path
175
159
  if (!filePath || !path.isAbsolute(filePath) || !existsSync(filePath)) return
176
- const kind = classifyOrThrow('StasisWebpack', filePath, this.#resources)
177
- const url = pathToFileURL(filePath).toString()
160
+ const kind = stasis.classify(filePath)
178
161
  // rrd.context.issuer is webpack 4's alone, removed in enhanced-resolve 5.
179
- const dep = data?.dependencies?.[0]
162
+ const dep = data.dependencies?.[0]
180
163
  const issuer = (dep && issuerByDep.get(dep)) ?? data.contextInfo?.issuer ?? cd.resourceResolveData?.context?.issuer
181
164
  const isEntry = !issuer
182
165
  const rawRequest = cd.rawRequest ?? data.rawRequest
183
166
  if (kind === 'code' && !isEntry) {
184
- const issuerAbsolute = path.resolve(issuer)
185
- const parentURL = pathToFileURL(issuerAbsolute).toString()
186
- for (const specifier of subpathOriginals.get(edgeKey(issuerAbsolute, rawRequest)) ?? [rawRequest]) {
187
- this.#state.addImport(parentURL, specifier, url)
167
+ const importer = path.resolve(issuer)
168
+ for (const specifier of subpathOriginals.get(edgeKey(importer, rawRequest)) ?? [rawRequest]) {
169
+ stasis.addImport(importer, specifier, filePath)
188
170
  }
189
171
  }
190
- if (!this.#seen.has(filePath)) {
191
- this.#seen.add(filePath)
192
- const source = realReadFileSync(filePath)
193
- if (kind === 'code') assertCodeUtf8('StasisWebpack', filePath, source)
194
- this.#state.addFile(url, { source, isEntry, resource: kind === 'resource', reason: 'webpack' })
195
- }
172
+ if (stasis.claim(filePath)) stasis.addFile(filePath, realReadFileSync(filePath), kind, isEntry)
196
173
  })
197
174
  })
198
175
 
199
176
  // watchRun fires only under compiler.watch(), before the first build, so this refuses the whole session.
200
177
  compiler.hooks.watchRun.tap('Stasis', () => {
201
178
  throw new Error(
202
- 'StasisWebpack: watch mode is not supported for capture -- ' +
203
- 'run a one-shot build (watch rebuilds would silently attest stale content)'
179
+ 'StasisWebpack: watch mode is not supported for capture -- run a one-shot build'
204
180
  )
205
181
  })
206
182
 
207
- // The preload writes itself; a failed build mustn't overwrite a good lockfile.
208
- if (this.#state !== State.preload) {
183
+ // A failed build mustn't overwrite a good lockfile.
184
+ if (stasis.ownsWrite) {
209
185
  compiler.hooks.done.tap('Stasis', (stats) => {
210
186
  if (stats.hasErrors()) return
211
187
  // `done` fires per child of a MultiCompiler: one write, not N brotli passes over a growing bundle.
212
- if (this.#captureApplyCount === 1) this.#state.write()
188
+ if (this.#captureApplyCount === 1) stasis.state.write()
213
189
  else this.#deferWrite()
214
190
  })
215
191
  }
@@ -223,7 +199,7 @@ export class StasisWebpack {
223
199
  this.#deferredWriteArmed = true
224
200
  const flush = () => {
225
201
  if (!this.#deferredWriteDirty) return
226
- this.#state.write() // on a throw, dirty stays set so exit retries
202
+ this.#stasis.state.write() // on a throw, dirty stays set so exit retries
227
203
  this.#deferredWriteDirty = false
228
204
  }
229
205
  process.on('beforeExit', flush)