@exodus/stasis-plugins 1.0.0-rc.11 → 1.0.0-rc.13

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@exodus/stasis-plugins",
3
- "version": "1.0.0-rc.11",
3
+ "version": "1.0.0-rc.13",
4
4
  "description": "Bundler plugins (webpack, esbuild, Rollup, Metro) for @exodus/stasis-core",
5
5
  "type": "module",
6
6
  "exports": {
@@ -36,6 +36,6 @@
36
36
  },
37
37
  "homepage": "https://github.com/PreventiveMeasures/stasis#readme",
38
38
  "dependencies": {
39
- "@exodus/stasis-core": "1.0.0-rc.11"
39
+ "@exodus/stasis-core": "1.0.0-rc.13"
40
40
  }
41
41
  }
package/src/esbuild.js CHANGED
@@ -4,8 +4,7 @@ import assert from 'node:assert/strict'
4
4
 
5
5
  import { Bundle } from '@exodus/stasis-core/bundle'
6
6
  import { PluginState, assertCodeUtf8, assertPersistableAttributes, fileURL, ownOrResolvedState, unsupportedExtension } from './plugins.js'
7
- // Pre-patch snapshot, not `import { readFile }`: under --fs=async that builtin is patched, and
8
- // this plugin loads after, so a direct import would route esbuild's reads through the capture hook.
7
+ // Not `import { readFile }`: --fs=async patches that builtin before this plugin loads.
9
8
  import { realReadFile } from '@exodus/stasis-core/state-util'
10
9
  import { EMPTY_MODULE_PATH, classifyExtension, isPlainObject, memoized } from '@exodus/stasis-core/util'
11
10
 
@@ -13,14 +12,13 @@ import { EMPTY_MODULE_PATH, classifyExtension, isPlainObject, memoized } from '@
13
12
  const RESOLVE_OPTIONS = ['absWorkingDir', 'alias', 'conditions', 'external', 'mainFields', 'nodePaths',
14
13
  'packages', 'platform', 'preserveSymlinks', 'resolveExtensions', 'tsconfig', 'tsconfigRaw']
15
14
 
16
- // A stylesheet's imports, whose URL's query and fragment (`./icons.svg#check`) esbuild keeps as the result's suffix.
15
+ // esbuild keeps a stylesheet URL's query and fragment (`./icons.svg#check`) as the result's suffix.
17
16
  const CSS_RESOLVE_KINDS = new Set(['import-rule', 'composes-from', 'url-token'])
18
17
  const urlSuffix = (specifier) => {
19
18
  const at = specifier.search(/[?#]/u)
20
19
  return at === -1 ? '' : specifier.slice(at)
21
20
  }
22
21
 
23
- // One import of `specifier` as `kind` would issue it, as the probe's stdin.
24
22
  function probeSource(specifier, kind) {
25
23
  const quoted = JSON.stringify(specifier)
26
24
  if (kind === 'require-call' || kind === 'require-resolve') return { contents: `require(${quoted})`, loader: 'js' }
@@ -30,8 +28,7 @@ function probeSource(specifier, kind) {
30
28
  return { contents: `import ${quoted}`, loader: 'js' }
31
29
  }
32
30
 
33
- // A `browser` map key or a path, loosened past esbuild's matching (bare, plus each resolve extension, plus `/index`,
34
- // with or without './'): equal loose keys are a SUPERSET of esbuild's matches -- only a probe decides.
31
+ // Looser than esbuild's matching (extensions, `/index`, './'): a SUPERSET of its matches; a probe decides.
35
32
  function looseBrowserKey(path) {
36
33
  const parts = path.replaceAll('\\', '/').split('/').filter((part) => part !== '' && part !== '.')
37
34
  const stem = (part) => part.replace(/\..*$/su, '')
@@ -40,7 +37,6 @@ function looseBrowserKey(path) {
40
37
  return parts.join('/')
41
38
  }
42
39
 
43
- // The loose keys a directory's package.json `browser` map sends to `false` (esbuild's "disabled").
44
40
  async function browserFalseKeys(dir) {
45
41
  const browser = await realReadFile(join(dir, 'package.json'), 'utf8')
46
42
  .then((text) => JSON.parse(text)?.browser)
@@ -56,11 +52,9 @@ export class StasisEsbuild {
56
52
  #transform
57
53
  #resource
58
54
  #platform
59
- #emptyModule // URL of the empty module disabled imports point at, once capture recorded it
55
+ #emptyModule
60
56
 
61
- // Only for load mode: `loaders` per-extension overrides (RN's '.js' -> 'jsx'), `transform(source, { path, loader })`
62
- // a code rewrite (`stasis build --platform=hermes`), `resource(source, { path })` a module for a resource no loader
63
- // names (`stasis build --metro`'s asset module), `platform` the one a --metro per-platform edge resolves for.
57
+ // The second argument is for load mode only.
64
58
  constructor(options = {}, { loaders, transform, resource, platform } = {}) {
65
59
  this.#stasis = new PluginState('StasisEsbuild', 'esbuild', ownOrResolvedState('StasisEsbuild', options))
66
60
  this.#loaders = loaders ?? new Map()
@@ -69,23 +63,19 @@ export class StasisEsbuild {
69
63
  this.#platform = platform
70
64
  }
71
65
 
72
- // A configured override, else from the extension (.cjs/.mjs/.cts/.mts drop their module letter, .css keeps it).
73
66
  #loaderFor(path) {
74
67
  const ext = extname(path)
75
68
  return this.#loaders.get(ext) ?? ext.slice(1).replace(/^[cm](?=[jt]s$)/u, '')
76
69
  }
77
70
 
78
- // dir -> Promise<[{ dir, keys }]>: every directory from `dir` up whose `browser` map disables something, nearest
79
- // first. A superset, as esbuild consults only the nearest map.
71
+ // A superset: esbuild consults only the nearest `browser` map.
80
72
  #browserFalseScopes = memoized((dir) => {
81
73
  const parent = dirname(dir)
82
74
  return Promise.all([browserFalseKeys(dir), parent === dir ? [] : this.#browserFalseScopes(parent)])
83
75
  .then(([keys, above]) => (keys.size > 0 ? [{ dir, keys }, ...above] : above))
84
76
  })
85
77
 
86
- // Whether some `browser` map `false` entry could match this resolution: the resolved path (and, for a relative
87
- // specifier, the path it names) under each map's dir, or a bare specifier as is or as './<importer dir>/<specifier>'
88
- // (a Browserify quirk esbuild keeps).
78
+ // A bare specifier may also match as './<importer dir>/<specifier>', a Browserify quirk esbuild keeps.
89
79
  async #mayBeDisabled(path, specifier, resolveDir) {
90
80
  const isPackagePath = !isAbsolute(specifier) && !/^\.\.?(?:\/|$)/u.test(specifier)
91
81
  const paths = isPackagePath ? [path] : [path, resolvePath(resolveDir, specifier)]
@@ -98,8 +88,6 @@ export class StasisEsbuild {
98
88
  })
99
89
  }
100
90
 
101
- // esbuild's own verdict: a one-import build with the build's resolve options and every load stubbed empty, whose
102
- // metafile still names a disabled module `(disabled):<path>`. -> that path (absolute), or null
103
91
  #probeDisabled = memoized(({ specifier, kind, resolveDir, build: { esbuild, initialOptions } }) => {
104
92
  const options = Object.fromEntries(RESOLVE_OPTIONS.filter((k) => initialOptions[k] !== undefined).map((k) => [k, initialOptions[k]]))
105
93
  const cwd = initialOptions.absWorkingDir ?? process.cwd()
@@ -118,9 +106,7 @@ export class StasisEsbuild {
118
106
  }, () => null)
119
107
  }, ({ specifier, kind, resolveDir }) => JSON.stringify([kind, resolveDir, specifier]))
120
108
 
121
- // A `browser` field `false` makes esbuild resolve an import to an empty "disabled" module, but its resolve API
122
- // drops that flag: a bare name comes back namespace-less, a file as its plain path, which a probe confirms where a
123
- // `false` entry could match.
109
+ // esbuild's resolve API drops the "disabled" flag: a bare name comes back namespace-less, a file as its plain path.
124
110
  async #isDisabled(res, specifier, { kind, resolveDir }, build) {
125
111
  if (res.external) return false
126
112
  if (res.namespace === '') return true
@@ -145,15 +131,13 @@ export class StasisEsbuild {
145
131
  })
146
132
  }
147
133
 
148
- // A failed build mustn't overwrite the user's good file.
149
134
  if (stasis.ownsWrite) {
150
135
  onEnd((result) => {
151
136
  if (result.errors.length === 0) state.write()
152
137
  })
153
138
  }
154
139
 
155
- // Load mode resolves through the bundle's import map: the file may not be on disk. namespace 'file' with the
156
- // original path (esbuild doesn't stat a plugin's) keeps the output (banners, asset names, maps) a capture's.
140
+ // namespace 'file' with the original path (esbuild doesn't stat a plugin's) keeps the output a capture's.
157
141
  if (loadBundle) {
158
142
  onResolve({ filter: /$/ }, ({ path: specifier, importer, kind: resolveKind, with: attrs }) => {
159
143
  const isEntry = resolveKind === 'entry-point'
@@ -163,15 +147,13 @@ export class StasisEsbuild {
163
147
  url = specifier.startsWith('file:') ? specifier : fileURL(resolvePath(process.cwd(), specifier))
164
148
  if (state.config.full) state.assertEntry(url)
165
149
  } else {
166
- // Looked up even for a built-in's name: a browser build records `fs` where a `browser` field disables it or
167
- // a package by that name serves it. KNOWN GAP: a Node-loader-captured bundle keys an attributed edge under
168
- // specific conditions, which this `*` lookup won't match.
150
+ // Even for a built-in's name: a browser build records `fs` where a `browser` field disables it or a package
151
+ // serves it. KNOWN GAP: a Node-loader capture keys an attributed edge under conditions a `*` lookup misses.
169
152
  url = stasis.attestedImport(importer, specifier, { importAttributes: attrs, platform: this.#platform })?.url
170
153
  if (url === undefined) return undefined
171
154
  }
172
155
  const format = state.getFormat(url)
173
156
  const kind = url === emptyModuleURL ? 'empty' : Bundle.isResourceFormat(format) ? 'resource' : 'code'
174
- // A stylesheet URL's query and fragment, which the emitted URL carries, as esbuild's own resolution keeps them.
175
157
  const suffix = CSS_RESOLVE_KINDS.has(resolveKind) ? urlSuffix(specifier) : ''
176
158
  return { path: fileURLToPath(url), namespace: 'file', ...(suffix && { suffix }), pluginData: { isEntry, kind } }
177
159
  })
@@ -191,7 +173,7 @@ export class StasisEsbuild {
191
173
  }
192
174
  return undefined
193
175
  }
194
- // But a stylesheet URL's own query and fragment, esbuild's suffix of it, which load mode reads off the specifier.
176
+ // Load mode can only read a stylesheet URL's suffix back off the specifier.
195
177
  assert.ok(res.suffix === '' || (CSS_RESOLVE_KINDS.has(args.kind) && res.suffix === urlSuffix(specifier)),
196
178
  `StasisEsbuild: a sibling plugin set res.suffix='${res.suffix}' on '${specifier}', which stasis can't persist`)
197
179
 
@@ -199,8 +181,7 @@ export class StasisEsbuild {
199
181
  if (res.namespace === 'file' && !res.external) {
200
182
  kind = classifyExtension(res.path, state.config.resources)
201
183
  if (kind === 'unknown') return { errors: [{ text: unsupportedExtension('StasisEsbuild', `'${res.path}'`) }] }
202
- // Resources too: load mode resolves every specifier through this map, so one with no edge would fall through
203
- // to esbuild's disk resolver, unattested.
184
+ // Resources too: load mode resolves every specifier through this map, else via esbuild's disk resolver.
204
185
  if (!isEntry) stasis.addImport(args.importer, specifier, res.path, attrs)
205
186
  }
206
187
  return { ...res, pluginData: { ...res.pluginData, isEntry, kind } }
@@ -214,7 +195,6 @@ export class StasisEsbuild {
214
195
  // getFile verifies the hash and throws on a file the bundle doesn't carry: no disk fallback.
215
196
  if (loadBundle) {
216
197
  const { source } = state.getFile(fileURL(path))
217
- // esbuild's own loader for disabled modules, which a CSS @import, `composes` or url() accepts too.
218
198
  if (kind === 'empty') return { contents: source, loader: 'empty' }
219
199
  if (kind === 'resource') {
220
200
  const override = this.#loaders.get(extname(path))
@@ -4,15 +4,11 @@ import { createRequire } from 'node:module'
4
4
 
5
5
  import { upsert } from '@exodus/stasis-core/util'
6
6
 
7
- // Stands in for the project's Babel transformer under ./metro-transformer.js, to keep each import as WRITTEN: Metro
8
- // names a dependency by the specifier Babel leaves, so a rewrite (babel-plugin-module-resolver's) would leave it only
9
- // that. An added plugin records each specifier in its `pre` (Babel runs every `pre` before any visitor) and reads it
10
- // again once Babel is done; one a plugin consumed, with nothing left naming its module, is kept apart.
7
+ // Wraps the project's Babel transformer to keep each import as WRITTEN: Metro names a dependency by the specifier
8
+ // Babel leaves, so a rewrite (babel-plugin-module-resolver's) would lose it. Babel runs every `pre` before any visitor.
11
9
 
12
10
  const require = createRequire(import.meta.url)
13
11
 
14
- // Per worker transform: `babelTransformerPath` the project's, `asWritten` each specifier Babel left -> the ones
15
- // written, and `consumed` each one a plugin consumed, as Babel last left it.
16
12
  export const transformContext = new AsyncLocalStorage()
17
13
 
18
14
  // The nodes Metro's collectDependencies takes a specifier from.
@@ -29,7 +25,7 @@ function isDependency(node) {
29
25
  callee.property.type === 'Identifier' && REQUIRE_MEMBERS.has(callee.property.name)
30
26
  }
31
27
 
32
- // A literal, a template with no substitutions, or a `+` of such, which collectDependencies evaluates as a literal.
28
+ // collectDependencies evaluates a `+` of literals as a literal.
33
29
  function constantString(node) {
34
30
  if (node?.type === 'StringLiteral') return node.value
35
31
  if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0].value.cooked ?? undefined
@@ -44,8 +40,7 @@ const specifierOf = (node) => constantString(node.type === 'CallExpression' ? no
44
40
 
45
41
  const TYPE_KINDS = new Set(['type', 'typeof'])
46
42
 
47
- // A declaration of types alone, which Babel may erase: Flow's or TypeScript's `import type`, `export type ... from`,
48
- // or one whose every specifier is a type (which TypeScript's `onlyRemoveTypeImports` keeps as `import {} from`).
43
+ // Babel may erase it, but TypeScript's `onlyRemoveTypeImports` keeps one of type specifiers as `import {} from`.
49
44
  function typesOnly(node) {
50
45
  if (TYPE_KINDS.has(node.importKind ?? node.exportKind)) return true
51
46
  const specifiers = node.specifiers ?? []
@@ -78,8 +73,7 @@ function asWrittenPlugin({ types: t }) {
78
73
  if (written !== undefined) slots.push({ node, written, types: node.type !== 'CallExpression' && typesOnly(node) })
79
74
  else if (node.type === 'CallExpression' && node.arguments.length > 0) evaluate = true
80
75
  })
81
- // Metro also takes an argument Babel evaluates to a string with confidence (`const name = './x'; require(name)`),
82
- // which only a path, with its scope, can evaluate.
76
+ // Metro also takes an argument Babel confidently evaluates to a string (`const name = './x'; require(name)`).
83
77
  if (!evaluate) return
84
78
  file.path.traverse({
85
79
  CallExpression(path) {
@@ -107,9 +101,8 @@ export function transform(args) {
107
101
  const slots = []
108
102
  const kept = new Set()
109
103
  Object.assign(context, { slots, kept })
110
- // Each specifier as Babel left it in the node that held it as written, but an erased types-only declaration's. A
111
- // node a plugin replaced (lowered to a require, or split in two) names the same module, its specifier as rewritten
112
- // before; one gone from the output with no node there naming its module was consumed.
104
+ // A node a plugin replaced (lowered to a require, or split in two) names the same module; one gone from the output
105
+ // with no node there naming its module was consumed.
113
106
  const collect = (result) => {
114
107
  const left = result?.ast && context.types ? dependenciesLeft(context.types, result.ast) : null
115
108
  for (const { node, written, types } of slots) {
@@ -124,7 +117,6 @@ export function transform(args) {
124
117
  }
125
118
  return result
126
119
  }
127
- // Sync or async, as the project's transformer is.
128
120
  const result = require(context.babelTransformerPath).transform({ ...args, plugins: [...(args.plugins ?? []), asWrittenPlugin] })
129
121
  return typeof result?.then === 'function' ? result.then(collect) : collect(result)
130
122
  }
@@ -5,12 +5,9 @@ import { readJson } from '@exodus/stasis-core/bundle-util'
5
5
  import { diskHost } from '@exodus/stasis-core/host'
6
6
  import { CODE_EXTENSIONS, classifyFormat, isAutoExcludedDir, isBinaryPlist, isDotEnvFile, isExcludedNativeFile, isNativeArtifact, metroFormat, nameFormat, pathExt, toPosix, upsert } from '@exodus/stasis-core/util'
7
7
 
8
- // The native build inputs of a React Native app's packages, shared by the Metro plugin's capture and `stasis bundle
9
- // --metro` so the two carry the same files. `fs` is a host: readdir(dir) -> Dirent[] (throws where `dir` isn't one),
10
- // readFile(file) -> Buffer, stat(path) -> Stats, or null where nothing is there.
8
+ // Shared by the Metro plugin's capture and `stasis bundle --metro` so the two carry the same files.
11
9
 
12
- // Files a React Native build requires that neither Metro's graph nor a run's loader carries, resolved from the project
13
- // root: setup_env.sh, which the React Native CLI runs as every command starts (`react-native config` included).
10
+ // Neither Metro's graph nor a run's loader carries setup_env.sh, which the RN CLI runs as every command starts.
14
11
  export const AUTO_INCLUDES = ['@react-native-community/cli/setup_env.sh']
15
12
 
16
13
  export function listing(dir, fs) {
@@ -21,34 +18,30 @@ export function listing(dir, fs) {
21
18
  }
22
19
  }
23
20
 
24
- // RN core build scripts the native walk would defer to Metro as `.js`, but Metro never sees them (RN's podspecs
25
- // invoke them at pod-install). Project-relative, so react-native's `exports` can't hide them.
21
+ // RN's podspecs run these at pod-install, so Metro never sees them; joined to RN's path, as its `exports` hides them.
26
22
  export const RN_CORE_INCLUDE_FILES = ['sdks/hermes-engine/utils/replace_hermes_version.js']
27
23
 
28
24
  // By name: RN scatters podspecs in subdirs `react-native config` misses.
29
25
  const isPodspec = (name) => name.endsWith('.podspec') || name.endsWith('.podspec.json')
30
26
 
31
- // The off-platform top-level dir of a native package, which no build on this host compiles.
32
27
  export function isExcludedNativeDir(name, { win32 = process.platform === 'win32' } = {}) {
33
28
  return !win32 && name === 'windows'
34
29
  }
35
30
 
36
- // Nested packages (attested separately) and regenerated build output, on top of the shared set.
31
+ // Nested packages are attested separately; the rest is regenerated build output.
37
32
  const NATIVE_BUILD_OUTPUT_DIRS = new Set(['node_modules', 'build', '.gradle', '.cxx', 'Pods', 'DerivedData'])
38
33
  const isSkippedNativeWalkDir = (name) => NATIVE_BUILD_OUTPUT_DIRS.has(name) || isAutoExcludedDir(name) || isNativeArtifact(name)
39
34
 
40
- // A native capture's view of a file by name: { action: 'code', format } for a native build input, 'skip' for noise
41
- // or a JS-family file by extension (Metro owns those), else 'resource'.
42
35
  export function classifyNativeCapture(name, { win32 = process.platform === 'win32', content } = {}) {
43
36
  // `.env` files carry secrets: an automated capture must never sweep them in.
44
37
  if (isExcludedNativeFile(name, { win32 }) || isDotEnvFile(name)) return { action: 'skip' }
45
- // Name-matched code is a native build input even where its tag is a Node format the JS graph would own.
38
+ // Metro owns JS-family files, but name-matched code is a native build input even where its tag is a Node format.
46
39
  if (nameFormat(name) === undefined && CODE_EXTENSIONS.has(pathExt(name))) return { action: 'skip' }
47
40
  const format = classifyFormat(name, { content })
48
41
  return format === undefined ? { action: 'resource' } : { action: 'code', format }
49
42
  }
50
43
 
51
- // classifyNativeCapture refined by the bytes, which only ever demote; a 'resource' gets its format from its bytes.
44
+ // The bytes only ever demote classifyNativeCapture's verdict.
52
45
  export function refineNativeCapture(classified, name, content, resources = new Set()) {
53
46
  // A compiled tool (Hermes' `hermesc`), never source.
54
47
  if (pathExt(name) === '' && Buffer.isBuffer(content) && !isUtf8(content)) return { action: 'skip' }
@@ -56,9 +49,7 @@ export function refineNativeCapture(classified, name, content, resources = new S
56
49
  return classified
57
50
  }
58
51
 
59
- // A file name as Metro's AssetPaths reads it (parsePlatformFilePath, then parseBaseName) for `platform` (a name or
60
- // null): its asset, `${name}.${type}` less any scale (`a@2x.png` is `a.png`'s), and its platform where it names
61
- // `platform` (`a.ios.png`; `a.android.png` is an asset of its own). -> null for a name with no type
52
+ // As Metro's AssetPaths: `a@2x.png` is `a.png`'s, as is `a.ios.png` for ios, but `a.android.png` is its own asset.
62
53
  const METRO_PLATFORM_FILE = /^(.+?)(?:\.([^.]+))?\.([^.]+)$/u
63
54
  const METRO_ASSET_SCALE = /^(.+?)(?:@[\d.]+x)?$/u
64
55
  function parseMetroAssetName(name, platform) {
@@ -70,10 +61,8 @@ function parseMetroAssetName(name, platform) {
70
61
  return { asset: `${root}.${type}`, platform: ofPlatform ? platform : null }
71
62
  }
72
63
 
73
- // A file's stat for metroAssetFiles, where a listing names one the disk lacks.
74
64
  export const FILE_STAT = { isFile: () => true }
75
65
 
76
- // The files `state` (a loaded State) carries, as a directory listing of them (metroAssetFiles' host).
77
66
  export function bundleDirHost(state) {
78
67
  const dirs = Map.groupBy([...state.sources.keys(), ...state.resources.keys()], (rel) => posix.dirname(rel))
79
68
  return {
@@ -82,9 +71,7 @@ export function bundleDirHost(state) {
82
71
  }
83
72
  }
84
73
 
85
- // Metro's record of the asset module `path` (getAbsoluteAssetRecord): the files it reads to build it and copies out
86
- // with it, each of the asset's name and type at any scale in its directory, those for `platform` where it has any,
87
- // else those for none. -> absolute paths
74
+ // As Metro's getAbsoluteAssetRecord: the files it reads to build the asset module and copies out with it.
88
75
  export function metroAssetFiles(path, platform = null, host = diskHost) {
89
76
  const own = parseMetroAssetName(basename(path), platform)
90
77
  if (own === null) return []
@@ -98,7 +85,6 @@ export function metroAssetFiles(path, platform = null, host = diskHost) {
98
85
  return byPlatform.get(platform) ?? byPlatform.get(null) ?? []
99
86
  }
100
87
 
101
- // Whether the package at `root` ships native code: an ios/ or android/ dir, or a podspec under it.
102
88
  export function looksNative(root, fs) {
103
89
  return fs.stat(join(root, 'ios')) !== null || fs.stat(join(root, 'android')) !== null || hasPodspec(root, fs)
104
90
  }
@@ -108,13 +94,10 @@ function hasPodspec(dir, fs) {
108
94
  (ent.isFile() ? isPodspec(ent.name) : ent.isDirectory() && !isSkippedNativeWalkDir(ent.name) && hasPodspec(join(dir, ent.name), fs)))
109
95
  }
110
96
 
111
- // A spec React Native's codegen parses (its filterJSFile): a JS or TS module named `Native…` or `…NativeComponent`,
112
- // but a type declaration.
97
+ // As React Native codegen's filterJSFile.
113
98
  const isCodegenSpec = (name) => /^(?:Native.+|.+NativeComponent)/u.test(name) && /\.(?:jsx?|tsx?)$/u.test(name) && !name.endsWith('.d.ts')
114
99
 
115
- // Each native build input of the package at `root`, walked whole (a podspec may compile `cpp/` beside `ios/`) but
116
- // build output, prebuilt binaries, an off-platform top-level dir, symlinks and what the shared classifier skips; and
117
- // its codegen specs, as code Metro's format names. -> yields { file, source, action: 'code' | 'resource', format }
100
+ // Walked whole: a podspec may compile `cpp/` beside `ios/`.
118
101
  export function* nativeInputs(root, fs, { resources = new Set(), skip = () => false } = {}) {
119
102
  yield* walk(root, true)
120
103
  for (const dir of codegenSources(root, fs)) yield* sources(dir)
@@ -145,16 +128,13 @@ export function* nativeInputs(root, fs, { resources = new Set(), skip = () => fa
145
128
  }
146
129
  }
147
130
 
148
- // The dirs the package's `codegenConfig` names as its JS sources (`jsSrcsDir`, or each of its `libraries`'), each
149
- // reached through no symlink, as the walk follows none: codegen parses the specs there for the native code a build
150
- // compiles, and `react-native config` reads them for the components they declare. -> the absolute dirs
151
131
  function codegenSources(root, fs) {
152
132
  const config = readJson(join(root, 'package.json'), fs)?.codegenConfig
153
133
  const named = [config?.jsSrcsDir, ...(Array.isArray(config?.libraries) ? config.libraries.map((library) => library?.jsSrcsDir) : [])]
154
134
  return named.filter((dir) => typeof dir === 'string' && dir !== '').map((dir) => packageDir(root, dir, fs)).filter((dir) => dir !== null)
155
135
  }
156
136
 
157
- // The directory `rel` names in the package at `root`, each step a directory entry (not a link, not `..`), else null.
137
+ // Through no link, as the walk follows none.
158
138
  function packageDir(root, rel, fs) {
159
139
  let dir = root
160
140
  for (const name of relative(root, join(root, rel)).split(sep)) {
@@ -165,12 +145,10 @@ function packageDir(root, rel, fs) {
165
145
  return dir
166
146
  }
167
147
 
168
- // A package name as npm takes one (`name` or `@scope/name`), which a path can't climb out with.
148
+ // `name` or `@scope/name`, which a path can't climb out with.
169
149
  const PACKAGE_NAME = /^(?:@[^/\\@.][^/\\]*\/)?[^/\\@.][^/\\]*$/u
170
150
 
171
- // The app's packages `react-native config` reads, as data rather than by running the CLI: each name its package.json
172
- // lists under dependencies, peerDependencies or devDependencies, in the nearest node_modules up from `projectDir` that
173
- // holds it. What a react-native.config.js changes, being code, isn't seen. -> the package dirs
151
+ // As `react-native config` reads them, but as data: what a react-native.config.js changes isn't seen.
174
152
  export function linkedPackages(projectDir, fs) {
175
153
  const manifest = readJson(join(projectDir, 'package.json'), fs)
176
154
  const listed = (field) => (manifest?.[field] && typeof manifest[field] === 'object' ? Object.keys(manifest[field]) : [])
@@ -190,7 +168,6 @@ export function linkedPackages(projectDir, fs) {
190
168
  return dirs
191
169
  }
192
170
 
193
- // Those of linkedPackages a native build links: those that ship native code.
194
171
  export function linkedNativePackages(projectDir, fs) {
195
172
  return linkedPackages(projectDir, fs).filter((dir) => looksNative(dir, fs))
196
173
  }
@@ -8,16 +8,12 @@ import { servedByBundle } from '@exodus/stasis-core/state-util'
8
8
  import { upsert } from '@exodus/stasis-core/util'
9
9
  import { transformContext } from './metro-babel-transformer.js'
10
10
 
11
- // The worker half of StasisMetro, wired by withStasis() as `transformerPath` around the project's transformer. It
12
- // keeps each import as written for the serializer (./metro-babel-transformer.js), and is the LOAD half: a per-worker
13
- // seam, as load only reads an immutable bundle, replacing Metro's `data` with the bundle's hash-verified bytes. Metro
14
- // reads and hashes each file before this runs, so sources must stay on disk: attested bytes, fail closed on drift.
11
+ // StasisMetro's worker half, wired by withStasis() as `transformerPath`. Under load it replaces Metro's `data` with the
12
+ // bundle's verified bytes; Metro reads and hashes each file before this runs, so sources must stay on disk.
15
13
 
16
14
  const require = createRequire(import.meta.url)
17
15
 
18
- // The project's transformer: the `transformerPath` withStasis() replaced, else EXODUS_STASIS_METRO_BASE_TRANSFORMER,
19
- // else Metro's default, a name resolved from the project root first, as Metro requires it from its own dir. This
20
- // transformer itself (wired by hand as well) means Metro's default.
16
+ // From the project root first, as Metro requires its default from its own dir; this transformer itself means that.
21
17
  const bases = new Map()
22
18
  function baseOf(config, projectRoot = process.cwd()) {
23
19
  const path = config?.stasisBaseTransformerPath ?? (process.env.EXODUS_STASIS_METRO_BASE_TRANSFORMER || 'metro-transform-worker')
@@ -31,8 +27,8 @@ function baseOf(config, projectRoot = process.cwd()) {
31
27
 
32
28
  const baseConfig = ({ stasisBaseTransformerPath: _, ...config } = {}) => config
33
29
 
34
- // The worker's load State, null outside load (a pass-through, so wiring this permanently is safe). A failure is
35
- // cached and rethrown on every call, never passed through after the first. It never writes, so claims no write path.
30
+ // Null outside load, so wiring this permanently is safe. A failure is rethrown on every call, never passed through.
31
+ // It never writes, so claims no write path.
36
32
  let loaded
37
33
  function getLoadState() {
38
34
  if (loaded === undefined) {
@@ -52,9 +48,7 @@ const BABEL_TRANSFORMER = fileURLToPath(new URL('./metro-babel-transformer.js',
52
48
  // Metro resolves a configured Babel transformer; its default stays a name, which the base requires from its own dir.
53
49
  const resolveBabelTransformer = (base, path) => (isAbsolute(path) ? path : createRequire(base.file).resolve(path))
54
50
 
55
- // Each dependency as the source wrote it: `stasisAsWritten` where Babel rewrote its specifier (several written apart
56
- // may be rewritten alike), `stasisInserted` where no specifier in the source names it (a Babel helper, Metro's
57
- // asyncRequire). The imports a Babel plugin consumed ride on the module's first output's data, as `stasisConsumed`.
51
+ // Read by StasisMetro's serializer in the main process; several specifiers written apart may be rewritten alike.
58
52
  function withAsWritten(result, { asWritten, consumed }) {
59
53
  if (!Array.isArray(result?.dependencies)) return result
60
54
  const dependencies = result.dependencies.map((dep) => {
@@ -88,7 +82,7 @@ export async function transform(config, projectRoot, filename, data, options) {
88
82
  return withAsWritten(result, context)
89
83
  }
90
84
 
91
- // The base's key, marked by the load State transform() goes by, so a load result never shares a disk build's entry.
85
+ // So a load result never shares a disk build's cache entry.
92
86
  export function getCacheKey(config, opts) {
93
87
  const { transformer } = baseOf(config, opts?.projectRoot)
94
88
  const baseKey = typeof transformer.getCacheKey === 'function' ? transformer.getCacheKey(baseConfig(config), opts) : ''
package/src/metro.js CHANGED
@@ -10,7 +10,7 @@ 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
- // realReadFileSync throughout: the plugin's own reads, which --fs must not record as the program's.
13
+ // realReadFileSync: 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
15
  import { classifyExtension, classifyFormat, isPathWithin, metroFormat, splitNodeModulesPath } from '@exodus/stasis-core/util'
16
16
 
@@ -18,18 +18,14 @@ const require = createRequire(import.meta.url)
18
18
 
19
19
  const TRANSFORMER = fileURLToPath(new URL('./metro-transformer.js', import.meta.url))
20
20
 
21
- // An absolute path on disk, else undefined: a virtual module's (require.context's ?ctx=, __prelude__), an unresolved
22
- // edge's.
23
21
  const diskPath = (path) => (typeof path === 'string' && isAbsolute(path) && existsSync(path) ? path : undefined)
24
22
 
25
- // Metro's asset module, whose files (its `scales` and `hash`) Metro reads to build it and copies out with it.
26
23
  const isAsset = (module) => module.output?.[0]?.type === 'js/module/asset'
27
24
 
28
25
  // Metro's `graph.entryPoints` is a Set, an Array before ~0.71.
29
26
  const entrySet = ({ entryPoints }) => new Set(entryPoints instanceof Set || Array.isArray(entryPoints) ? entryPoints : [])
30
27
 
31
- // The files Metro's transform worker hashes into its cache key for its transform plugins: from the project, else
32
- // through metro and its transform worker (a pnpm install links metro-transform-plugins only beside them).
28
+ // A pnpm install links metro-transform-plugins only beside metro and its transform worker.
33
29
  function metroTransformPluginFiles(projectDir) {
34
30
  for (const chain of [['metro-transform-plugins'], ['metro', 'metro-transform-worker', 'metro-transform-plugins']]) {
35
31
  let file
@@ -46,7 +42,7 @@ function metroTransformPluginFiles(projectDir) {
46
42
 
47
43
  const WORKER_TOOLCHAIN = 'babel.config.js, @babel/core, the RN preset + plugins'
48
44
 
49
- // `react-native config`'s output, or null without the RN CLI; a failing CLI throws, as under-attesting breaks frozen runs.
45
+ // Null without the RN CLI; a failing CLI throws, as under-attesting breaks frozen runs.
50
46
  function loadReactNativeConfig(projectDir) {
51
47
  let cliPath
52
48
  try {
@@ -101,8 +97,6 @@ function metroDefaultSerializer() {
101
97
  )
102
98
  }
103
99
 
104
- // Hooks Metro's serializer, which runs once in the main process with the full graph (a worker's State could never
105
- // be merged); ./metro-transformer.js is the worker half. Under bundle=load it asserts each edge against the bundle.
106
100
  // Prefer withStasis: serializerHook never sees preModules, and only withStasis can drop Metro's transform cache.
107
101
  export class StasisMetro {
108
102
  #stasis
@@ -132,8 +126,6 @@ export class StasisMetro {
132
126
  }
133
127
  }
134
128
 
135
- // Whether the build relies on Metro really transforming files (capture, frozen and load all do), which a cached
136
- // transform would skip.
137
129
  get needsTransforms() {
138
130
  const config = this.#stasis.state?.config
139
131
  return config !== undefined && (config.useLockfile || config.bundle)
@@ -143,7 +135,6 @@ export class StasisMetro {
143
135
  if (baseSerializer !== undefined && typeof baseSerializer !== 'function') {
144
136
  throw new TypeError('StasisMetro.customSerializer(base?): base must be a function or omitted')
145
137
  }
146
- // Inert: the base as is, never loading Metro's internals.
147
138
  if (!this.#stasis.state) return baseSerializer
148
139
  return (entryPoint, preModules, graph, options) => {
149
140
  this.#run(graph, preModules)
@@ -163,7 +154,6 @@ export class StasisMetro {
163
154
  }
164
155
  const refusal = stasis.startBuild('StasisMetro: watch/dev-server rebuilds are not supported for capture -- use a one-shot `metro build`')
165
156
  if (refusal) throw new Error(refusal)
166
- // Nothing here can detect a cache hit, so say it once rather than silently under-attest.
167
157
  if (!this.#ownsConfig && this.needsTransforms) {
168
158
  console.warn(
169
159
  "[stasis] StasisMetro: wired without withStasis(), so Metro's transform cache may leave " +
@@ -187,9 +177,7 @@ export class StasisMetro {
187
177
  if (!this.#captureRead(modPath, kind, entries.has(modPath))) continue
188
178
  for (const { file } of this.#consumedResources(module, modPath)) this.#captureRead(file, 'resource')
189
179
  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).
180
+ // Under the name Metro reads each by, so a load holds that name to its bytes; no import names one, so no edge.
193
181
  for (const read of metroAssetFiles(modPath, platform)) {
194
182
  const readKind = classifyExtension(read, stasis.state.config.resources)
195
183
  if (readKind !== 'unknown' && this.#realWithin(read) !== null) this.#captureRead(read, readKind)
@@ -197,19 +185,16 @@ export class StasisMetro {
197
185
  }
198
186
  this.#captureAutoIncludes()
199
187
  this.#captureTransformPlugins()
200
- // Last, past what is already captured: the native build inputs no module graph carries.
188
+ // Last: it skips what is already captured.
201
189
  this.#captureNativeModules()
202
190
  }
203
191
 
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.
192
+ // `source` must be the bytes on disk: addFile re-reads the file to assert them.
206
193
  #record(file, source, options) {
207
194
  this.#stasis.seen.add(file)
208
195
  this.#stasis.state.addFile(fileURL(file), { source, inferFormat: false, reason: 'metro', ...options })
209
196
  }
210
197
 
211
- // Each of AUTO_INCLUDES resolving within the project root, tagged by the shared classifier so it agrees with any
212
- // other path meeting the file (setup_env.sh is 'shell'), else a resource.
213
198
  #captureAutoIncludes() {
214
199
  for (const specifier of AUTO_INCLUDES) {
215
200
  let modPath
@@ -225,20 +210,18 @@ export class StasisMetro {
225
210
  }
226
211
  }
227
212
 
228
- // Metro's worker hashes every transform plugin into its cache key, but loads each only as the build's options call
229
- // for it, so a capture loads them all, as the loader then records with their imports, and records each under `run`.
213
+ // Metro hashes every transform plugin into its cache key but loads only those the build calls for: load them all.
230
214
  #captureTransformPlugins() {
231
215
  for (const file of metroTransformPluginFiles(this.#projectDir)) {
232
216
  if (this.#stasis.seen.has(file) || !this.#within(file)) continue
233
217
  try {
234
218
  require(file)
235
- } catch { /* one that can't load can't run under Metro either: its bytes are still recorded */ }
219
+ } catch { /* can't run under Metro either; its bytes are still recorded */ }
236
220
  this.#record(file, realReadFileSync(file), { inferFormat: true, reason: 'run' })
237
221
  }
238
222
  }
239
223
 
240
- // The native build inputs of the deps autolinking reports, of those the graph reached that ship native code
241
- // (integrated by hand), and of RN core, which config names only as reactNativePath. One outside the root is skipped.
224
+ // Reached packages that ship native code count too: they may be integrated by hand, without autolinking.
242
225
  #captureNativeModules() {
243
226
  const { seen, state } = this.#stasis
244
227
  const config = loadReactNativeConfig(this.#projectDir)
@@ -254,11 +237,10 @@ export class StasisMetro {
254
237
  if (rnPath !== null) roots.add(rnPath)
255
238
  for (const root of roots) {
256
239
  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
240
  const inputs = nativeInputs(root, diskHost, { resources: state.config.resources, skip: (file) => seen.has(file) })
259
241
  for (const { file, source, action, format } of inputs) this.#record(file, source, { format, resource: action === 'resource' })
260
242
  }
261
- // RN core's `.js` build scripts, which the walk leaves to Metro but its graph never has, typed as the loader would.
243
+ // RN core's `.js` build scripts: the walk leaves them to Metro, but its graph never has them.
262
244
  if (rnPath === null || !this.#within(rnPath)) return
263
245
  for (const file of RN_CORE_INCLUDE_FILES.map((rel) => join(rnPath, rel))) {
264
246
  if (seen.has(file)) continue
@@ -272,8 +254,7 @@ export class StasisMetro {
272
254
  }
273
255
  }
274
256
 
275
- // bundle=load: Metro resolved every import itself, so each edge must be the one the bundle attests, for the
276
- // platform Metro builds.
257
+ // Metro resolved every import itself, so each edge must be the one the bundle attests.
277
258
  #assertEdges(graph, preModules) {
278
259
  const platform = graph.transformOptions?.platform ?? undefined
279
260
  for (const module of [...(preModules ?? []), ...graph.dependencies.values()]) {
@@ -288,8 +269,7 @@ export class StasisMetro {
288
269
  }
289
270
  }
290
271
 
291
- // A module's edges, keyed as the source wrote them (`stasisAsWritten`, where Babel rewrote one), to code and resource
292
- // targets alike. One the source doesn't write (`stasisInserted`: a Babel helper, Metro's asyncRequire) is no edge.
272
+ // A `stasisInserted` dependency (a Babel helper, Metro's asyncRequire) is none the source wrote.
293
273
  * #edges(module) {
294
274
  for (const dep of module.dependencies?.values?.() ?? []) {
295
275
  if (dep?.data?.stasisInserted === true) continue
@@ -316,9 +296,7 @@ export class StasisMetro {
316
296
  return this.#within(real) && isPathWithin(this.#realRoot, real) ? real : null
317
297
  }
318
298
 
319
- // The resources a Babel plugin inlined in transforming `module` (`stasisConsumed`, `require('./messages.po')`): no
320
- // module of Metro's, so no edge, but build inputs. One naming code (babel-plugin-lodash's split imports) is passed
321
- // over. -> each as { file: its real path within the root, read: the path read }
299
+ // Babel-inlined resources (`require('./messages.po')`) are build inputs but no Metro module, so no edge.
322
300
  * #consumedResources(module, modPath) {
323
301
  for (const specifier of module.output?.[0]?.data?.stasisConsumed ?? []) {
324
302
  if (typeof specifier !== 'string' || !(isAbsolute(specifier) || /^\.\.?\//u.test(specifier))) continue
@@ -330,8 +308,6 @@ export class StasisMetro {
330
308
  }
331
309
  }
332
310
 
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
335
311
  #captureRead(path, kind, isEntry = false) {
336
312
  if (!this.#stasis.claim(path)) return false
337
313
  const format = kind === 'code' ? metroFormat(path) : undefined
@@ -339,10 +315,8 @@ export class StasisMetro {
339
315
  return true
340
316
  }
341
317
 
342
- // Metro reads an asset's files from disk, past the stasis transformer: each must be the bundle's under that name (a
343
- // scale added since the capture, or one a symlink redirects, is drift), and each the bundle carries must still be
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.
318
+ // Metro reads an asset's files from disk, past the stasis transformer, so a scale added, redirected or gone is drift
319
+ // -- unless --fs=async serves them and their listing: then one added on disk since is none of the asset's.
346
320
  #assertAssetFiles(modPath, platform) {
347
321
  const { state } = this.#stasis
348
322
  const listed = state.config.fs !== 'async' ? diskHost : {
@@ -362,8 +336,7 @@ export class StasisMetro {
362
336
  }
363
337
  }
364
338
 
365
- // `read`, a file Metro reads from disk past the stasis transformer, held to the bundle's bytes for `file` where in
366
- // scope (getFile throws on one it doesn't carry) -- unless --fs, in a mode of `servedBy`, serves it by the path read.
339
+ // Metro reads `read` from disk past the stasis transformer; getFile throws on a `file` the bundle doesn't carry.
367
340
  #assertOnDisk({ file, read }, { what, servedBy }) {
368
341
  const { state } = this.#stasis
369
342
  const url = fileURL(file)
@@ -377,16 +350,13 @@ export class StasisMetro {
377
350
  }
378
351
  }
379
352
 
380
- // A new Metro config whose customSerializer captures the graph and preModules while the existing serializer (else
381
- // Metro's default) still produces the bundle, and whose transformer runs through ./metro-transformer.js.
382
353
  export function withStasis(config = {}, options = {}) {
383
354
  const stasis = new StasisMetro(options, { ownsConfig: true })
384
355
  const existing = config.serializer?.customSerializer ?? undefined
385
- // Metro's transform cache decides which modules Metro loads: a hit skips the worker, so its toolchain goes
386
- // unattested and a frozen run passes vacuously, and the default store is shared with every other Metro run. Dropped
387
- // under load too: an enabled cache resolves its cache-key files, which a bundle can't know, failing getImport.
356
+ // A transform cache hit skips the worker, so its toolchain goes unattested and a frozen run passes vacuously.
357
+ // Dropped under load too: an enabled cache resolves its cache-key files, which a bundle can't know.
388
358
  const active = stasis.needsTransforms
389
- // `undefined` is Metro's own default store; an array or a factory is the user's, so replacing it is announced.
359
+ // `undefined` is Metro's own default store; an array or a factory is the user's.
390
360
  const stores = config.cacheStores
391
361
  if (active && (typeof stores === 'function' || stores?.length > 0)) {
392
362
  console.warn(
package/src/plugins.js CHANGED
@@ -31,9 +31,7 @@ export function assertOptionsMatchConfig(config, options) {
31
31
  }
32
32
  }
33
33
 
34
- // The State a bundler plugin runs against, given its options and the ambient preload: { state: null, isNoop: true }
35
- // (inert: register no hooks), else { state, isNoop: false }. The lockfile is always the preload's; only the bundle
36
- // may split off, to a sidecar State at its own bundleFile.
34
+ // A null `state` is inert. Only the bundle may split off from the preload, to a sidecar State at its own bundleFile.
37
35
  export function resolvePluginState(label, options, cwd) {
38
36
  validatePluginOptions(label, options)
39
37
  const { lock, bundle, bundleFile, resourcesBundleFile, resources } = options
@@ -103,8 +101,7 @@ export function resolvePluginState(label, options, cwd) {
103
101
  }
104
102
  if (bundleFile !== undefined && bundleFile !== pc.bundleFile) return sidecar(pc.bundleMode)
105
103
  } 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.
104
+ // The assert pins today's no-bundle modes, so a future one can't silently mask a disagreement.
108
105
  assert.ok(pc.bundleMode === 'none' || pc.bundleMode === 'ignore',
109
106
  `unexpected preload bundleMode='${pc.bundleMode}' in the no-bundle branch`)
110
107
  } else {
@@ -118,14 +115,13 @@ export function resolvePluginState(label, options, cwd) {
118
115
  return { state: ambient, isNoop: false }
119
116
  }
120
117
 
121
- // A State the caller owns (`stasis build`'s), else resolvePluginState's; a foreign copy's State fails the instanceof.
118
+ // `stasis build` passes its own State; a foreign stasis-core copy's State fails the instanceof.
122
119
  export const ownOrResolvedState = (label, options) =>
123
120
  (options instanceof State ? options : resolvePluginState(label, options, process.cwd()).state)
124
121
 
125
122
  export const unsupportedExtension = (label, what) =>
126
123
  `${label}: unsupported extension for ${what}; add its extension or filename to the plugin's resources option`
127
124
 
128
- // Refuse non-UTF-8 code rather than silently encode it as a resource.
129
125
  export function assertCodeUtf8(label, path, source) {
130
126
  assert.ok(isUtf8(source), `${label}: code-classified file has non-UTF-8 bytes: ${path}`)
131
127
  }
@@ -137,8 +133,6 @@ export function assertPersistableAttributes(attrs) {
137
133
 
138
134
  export const fileURL = (path) => pathToFileURL(path).toString()
139
135
 
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
136
  export class PluginState {
143
137
  seen = new Set()
144
138
  #builds = 0
@@ -150,28 +144,24 @@ export class PluginState {
150
144
  }
151
145
 
152
146
  // 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
147
  startBuild(refusal = `${this.label}: watch/rebuild is not supported for capture -- run a one-shot build`) {
155
148
  this.#builds += 1
156
149
  if (this.#builds === 1) return undefined
157
150
  return refusal
158
151
  }
159
152
 
160
- // A file's kind (code|resource), or a throw naming it as `what` where it's neither.
161
153
  classify(path, what = `'${path}'`) {
162
154
  const kind = classifyExtension(path, this.state.config.resources)
163
155
  if (kind === 'unknown') throw new Error(unsupportedExtension(this.label, what))
164
156
  return kind
165
157
  }
166
158
 
167
- // Whether `path` is new to this plugin, marking it seen.
168
159
  claim(path) {
169
160
  if (this.seen.has(path)) return false
170
161
  this.seen.add(path)
171
162
  return true
172
163
  }
173
164
 
174
- // `options` go on to State#addFile as given (Metro's format and inferFormat).
175
165
  addFile(path, source, kind, isEntry, options) {
176
166
  if (kind === 'code') assertCodeUtf8(this.label, path, source)
177
167
  this.state.addFile(fileURL(path), { source, isEntry, resource: kind === 'resource', reason: this.reason, ...options })
@@ -181,8 +171,7 @@ export class PluginState {
181
171
  this.state.addImport(fileURL(importer), specifier, fileURL(target), { importAttributes })
182
172
  }
183
173
 
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).
174
+ // No attested edge: an EXTERNAL at capture (file BYTES still fail closed where the plugin loads them).
186
175
  attestedImport(importer, specifier, options) {
187
176
  try {
188
177
  return this.state.getImport(fileURL(importer), specifier, options)
package/src/rollup.js CHANGED
@@ -6,12 +6,10 @@ import { fileURLToPath } from 'node:url'
6
6
 
7
7
  import { Bundle } from '@exodus/stasis-core/bundle'
8
8
  import { PluginState, assertPersistableAttributes, fileURL, ownOrResolvedState } from './plugins.js'
9
- // Pre-patch snapshot, not `import { readFile }`: under --fs=async that builtin is patched, and
10
- // this plugin loads after, so a direct import would route rollup's reads through the capture hook.
9
+ // Not `import { readFile }`: --fs=async patches that builtin before this plugin loads.
11
10
  import { inScope, realReadFile, servedByBundle } from '@exodus/stasis-core/state-util'
12
11
  import { isPathWithin } from '@exodus/stasis-core/util'
13
12
 
14
- // An on-disk file by its absolute path, not a sibling plugin's virtual module (\0-prefixed or relative) or no importer.
15
13
  const isDiskId = (id) => Boolean(id) && isAbsolute(id) && !id.startsWith('\0')
16
14
 
17
15
  // Rollup chains resolveId/load hooks first-non-null-wins, so this plugin goes FIRST in `plugins`: listed later, a
@@ -27,7 +25,7 @@ export class StasisRollup {
27
25
  'StasisRollup takes a single options argument')
28
26
  this.#stasis = new PluginState('StasisRollup', 'rollup', ownOrResolvedState('StasisRollup', options))
29
27
  const { state } = this.#stasis
30
- if (!state) return // inert: rollup sees only `name`
28
+ if (!state) return
31
29
 
32
30
  // Rollup binds `this` to its PluginContext, so a hook gets it as `ctx` and the instance via the closure.
33
31
  const plugin = this
@@ -37,8 +35,7 @@ export class StasisRollup {
37
35
  this.resolveId = hook(this.#resolveId)
38
36
  this.load = hook(this.#load)
39
37
 
40
- // A warm `cache:` object reuses modules and resolutions WITHOUT calling resolveId/load, so they'd go unattested
41
- // at capture and unverified at load. Rollup still builds a fresh cache for this run.
38
+ // A warm `cache:` skips resolveId/load, leaving modules unattested at capture and unverified at load.
42
39
  this.options = (inputOptions) => {
43
40
  if (typeof inputOptions.cache !== 'object' || inputOptions.cache === null) return null
44
41
  console.warn(
@@ -64,8 +61,7 @@ export class StasisRollup {
64
61
  )
65
62
  }
66
63
 
67
- // A '?'/'#'-suffixed variant of an on-disk path ('./icon.svg?url') feeds the file's bytes to the build under a key
68
- // that can't be persisted, so skipping it would leave a build input unattested. A wholly virtual id is skippable.
64
+ // './icon.svg?url' feeds the file's bytes in under a key that can't be persisted, so skipping it isn't safe.
69
65
  #refuseSuffixedOnDisk(id) {
70
66
  const stripped = id.split(/[?#]/u, 1)[0]
71
67
  if (stripped !== id && existsSync(stripped)) {
@@ -75,19 +71,16 @@ export class StasisRollup {
75
71
  }
76
72
  }
77
73
 
78
- // An on-disk id under the project root.
79
74
  #inRoot(id) {
80
75
  return isDiskId(id) && isPathWithin(this.#stasis.state.root, id)
81
76
  }
82
77
 
83
78
  async #resolveId(ctx, source, importer, opts) {
84
- // Left to the user's external config. SECURITY: never consult getImport for a builtin, so a tampered bundle
85
- // can't redirect `fs`.
79
+ // SECURITY: never consult getImport for a builtin, so a tampered bundle can't redirect `fs`.
86
80
  if (isBuiltin(source)) return null
87
81
  const { isEntry, attributes: attrs = {} } = opts
88
82
  const stasis = this.#stasis
89
83
 
90
- // Load mode resolves through the bundle's import map: the file may not be on disk.
91
84
  if (stasis.state.config.loadBundle) {
92
85
  if (isEntry) {
93
86
  // Rollup defaults isEntry to !importer, so this covers bare sibling probes too: the load hook asserts entries
@@ -109,7 +102,6 @@ export class StasisRollup {
109
102
  return { id: path }
110
103
  }
111
104
 
112
- // Capture: the remaining resolveId hooks and rollup's own algorithm, passed through with the edge recorded.
113
105
  const resolution = await ctx.resolve(source, importer, { ...opts, skipSelf: true })
114
106
  if (!resolution || resolution.external) return resolution
115
107
  const { id } = resolution
@@ -120,8 +112,7 @@ export class StasisRollup {
120
112
  }
121
113
  stasis.classify(id)
122
114
 
123
- // Code and resource targets alike, but never for an entry, flagged from the graph in buildEnd (opts.isEntry is
124
- // a sibling's probe too), nor an out-of-root importer, which load mode defers too.
115
+ // Entries are flagged from the graph in buildEnd: opts.isEntry is a sibling's probe too.
125
116
  if (!isEntry && this.#inRoot(importer)) {
126
117
  assertPersistableAttributes(attrs)
127
118
  if (!this.#inRoot(id)) {
@@ -137,12 +128,10 @@ export class StasisRollup {
137
128
  async #load(ctx, id) {
138
129
  const stasis = this.#stasis
139
130
  const { state } = stasis
140
- // getFile verifies the hash and throws on a file the bundle doesn't carry: no disk fallback. Ids other plugins
141
- // resolved land here too.
131
+ // getFile verifies the hash and throws on a file the bundle doesn't carry: no disk fallback.
142
132
  if (state.config.loadBundle) {
143
133
  if (!isDiskId(id) || !servedByBundle(state, id)) return null
144
134
  const url = fileURL(id)
145
- // The graph's isEntry: a sibling's resolve() probe carries isEntry too but never loads.
146
135
  if (state.config.full && ctx.getModuleInfo(id)?.isEntry) state.assertEntry(url)
147
136
  const { source, format } = state.getFile(url)
148
137
  if (Bundle.isResourceFormat(format)) this.#refuseResourceLoad(id)
@@ -163,14 +152,12 @@ export class StasisRollup {
163
152
  if (!this.#inRoot(id)) {
164
153
  throw new Error(`StasisRollup: module is outside the project root and can't be attested: ${id}`)
165
154
  }
166
- // Rollup loads an id once per build.
167
155
  if (stasis.claim(id)) stasis.addFile(id, source, kind)
168
156
  // A resource is the user's asset plugin's to load; code is served as recorded (transform hooks still run after).
169
157
  return kind === 'resource' ? null : source.toString('utf8')
170
158
  }
171
159
 
172
- // Flags the graph's real entries (resolveId's opts.isEntry would take a sibling's bare probe for one), then writes
173
- // a standalone or sidecar State on a clean build. buildEnd, not closeBundle, which only bundle.close() fires.
160
+ // buildEnd, not closeBundle, which only bundle.close() fires.
174
161
  async #buildEnd(ctx, error) {
175
162
  if (error) return
176
163
  const stasis = this.#stasis
@@ -179,7 +166,6 @@ export class StasisRollup {
179
166
  const info = ctx.getModuleInfo(id)
180
167
  return Boolean(info?.isEntry) && !info.isExternal
181
168
  })
182
- // addFile re-verifies the bytes, and refuses a RESOURCE entry, as StasisEsbuild does.
183
169
  const sources = await Promise.all(entryIds.map((id) => realReadFile(id)))
184
170
  for (const [i, id] of entryIds.entries()) stasis.addFile(id, sources[i], stasis.classify(id), true)
185
171
  if (stasis.ownsWrite) stasis.state.write()
package/src/webpack.js CHANGED
@@ -9,15 +9,12 @@ import { upsert } from '@exodus/stasis-core/util'
9
9
 
10
10
  const require = createRequire(import.meta.url)
11
11
 
12
- // The package.json "imports" subpaths ('#app/abc.js') babel-plugin-module-resolver rewrote, by (importer, rewritten
13
- // request) -> the '#'-specifiers (several aliases can collide on one key). Shared by the one patch and every instance.
14
12
  const subpathOriginals = new Map()
15
13
  const edgeKey = (importerAbsolute, request) => `${importerAbsolute}\u0000${request}`
16
14
 
17
15
  const PATCHED = Symbol('stasis.modresolver.patched')
18
16
 
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.
17
+ // webpack's resolver needs only existence and size; fs.Stats derives is*() from `mode` and dates from the *Ms fields.
21
18
  function bundleStat(size, isDir = false) {
22
19
  return Object.assign(Object.create(Stats.prototype), {
23
20
  mode: isDir ? 0o040755 : 0o100644,
@@ -45,16 +42,14 @@ export class StasisWebpack {
45
42
  else this.#applyCaptureMode(compiler)
46
43
  }
47
44
 
48
- // As `stasis run --bundle=load`: an in-scope path comes from the bundle (getFile re-verifies the hash), never from
49
- // disk. The bundle is the FAMILY: this State, then its parent where it is a sidecar (one shared lockfile). KNOWN
50
- // LIMITATION: a package.json the resolver reads that no family bundle carries fails closed (tests/webpack.test.js).
45
+ // KNOWN LIMITATION: a package.json the resolver reads that no family bundle carries fails closed.
51
46
  #applyLoadMode(compiler) {
52
47
  const { state } = this.#stasis
53
48
  const orig = compiler.inputFileSystem
54
49
  const served = (p) => typeof p === 'string' && p !== '' && servedByBundle(state, p)
55
50
  const family = state.parent ? [state, state.parent] : [state]
56
51
  const ownerOf = (url) => family.find((s) => s.getFsStat(url) !== undefined)
57
- // `answer(bytes)` to the callback, or getFile's throw on a miss: the fail-closed gate.
52
+ // getFile's throw on a miss is the fail-closed gate.
58
53
  const fromBundle = (p, callback, answer) => {
59
54
  const url = fileURL(p)
60
55
  try {
@@ -90,7 +85,6 @@ export class StasisWebpack {
90
85
  compiler.hooks.normalModuleFactory.tap('Stasis', (nmf) => {
91
86
  nmf.hooks.beforeResolve.tap('Stasis', (data) => {
92
87
  const issuer = data.contextInfo?.issuer
93
- // An entry is absolute already, and an out-of-scope parent webpack's to resolve.
94
88
  if (!issuer || !served(issuer)) return
95
89
  // SECURITY: never consult getImport for a builtin, so a tampered bundle can't redirect `fs`.
96
90
  if (isBuiltin(data.request)) return
@@ -103,8 +97,7 @@ export class StasisWebpack {
103
97
  }
104
98
 
105
99
  // webpack 4's enhanced-resolve has no imports field, so babel-plugin-module-resolver rewrites '#app/abc.js' before
106
- // the parser and afterResolve sees only the rewrite. Wrapping its rewrite chokepoint (v5's lib/mapPath default, or
107
- // v3/v4's lib/utils.mapPathString) records the original, so the edge is keyed by the portable specifier.
100
+ // the parser and afterResolve sees only the rewrite; the edge must be keyed by the portable original.
108
101
  #patchModuleResolver() {
109
102
  const paths = [this.#stasis.state.root, process.cwd()]
110
103
  for (const [sub, prop] of [['babel-plugin-module-resolver/lib/mapPath', 'default'], ['babel-plugin-module-resolver/lib/utils', 'mapPathString']]) {
@@ -180,7 +173,6 @@ export class StasisWebpack {
180
173
  )
181
174
  })
182
175
 
183
- // A failed build mustn't overwrite a good lockfile.
184
176
  if (stasis.ownsWrite) {
185
177
  compiler.hooks.done.tap('Stasis', (stats) => {
186
178
  if (stats.hasErrors()) return
@@ -191,8 +183,7 @@ export class StasisWebpack {
191
183
  }
192
184
  }
193
185
 
194
- // A single flush at beforeExit, with exit as the sync backstop for process.exit(). KNOWN LIMITATION: a signal death
195
- // bypasses it, as it does the preload's write.
186
+ // exit is the sync backstop for process.exit(). KNOWN LIMITATION: a signal death bypasses both, as the preload's.
196
187
  #deferWrite() {
197
188
  this.#deferredWriteDirty = true
198
189
  if (this.#deferredWriteArmed) return