@exodus/stasis 1.0.0-beta.15 → 1.0.0-beta.17

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.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/bin/stasis.js +26 -11
  3. package/package.json +10 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +113 -233
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +50 -166
  11. package/src/cmd/bundle-options.js +110 -167
  12. package/src/cmd/bundle.js +861 -1344
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +46 -27
  15. package/src/cmd/output.js +17 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +10 -23
  18. package/src/define.js +34 -97
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +10 -25
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +9 -33
  37. package/src/metro-resolver.js +20 -47
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +2 -5
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +90 -220
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +109 -313
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +136 -283
  50. package/src/sixel.js +18 -41
  51. package/src/table.js +14 -35
  52. package/src/validate-notes.d.ts +3 -2
  53. package/src/validate-notes.js +25 -19
  54. package/src/validate.d.ts +38 -11
  55. package/src/validate.js +478 -512
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +88 -121
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +167 -110
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +75 -231
  67. package/src/installed-commits.js +0 -184
package/src/cmd/build.js CHANGED
@@ -6,7 +6,7 @@ import { spawnSync } from 'node:child_process'
6
6
 
7
7
  import { Bundle } from '@exodus/stasis-core/bundle'
8
8
  import { State } from '@exodus/stasis-core/state'
9
- import { toPosix } from '@exodus/stasis-core/util'
9
+ import { CONFIG_FILE, isPlainObject, JS_EXTENSIONS, toPosix } from '@exodus/stasis-core/util'
10
10
  import { StasisEsbuild } from '@exodus/stasis-plugins/esbuild'
11
11
  import { bundleDirHost } from '@exodus/stasis-plugins/metro-native'
12
12
  import { assetsDestFiles } from '@preventive/rn/assets-dest.js'
@@ -21,26 +21,19 @@ import { writeFile } from './output.js'
21
21
 
22
22
  export { bundleFromLockfile }
23
23
 
24
- const JS_EXTS = new Set(['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '.jsx', '.tsx'])
25
-
26
- // Allowlist (not blocklist) of per-file formats `stasis build` accepts, so a bundle
27
- // format added later fails closed here rather than in a cryptic esbuild error.
24
+ // An allowlist, so that a bundle format added later fails closed here rather than in a cryptic esbuild error.
28
25
  const BUILDABLE_FORMATS = new Set([
29
26
  'module', 'commonjs', 'json', 'module-typescript', 'commonjs-typescript',
30
27
  'resource', 'resource:base64', 'directory', 'stat:file', 'stat:directory',
31
28
  ])
32
29
 
33
- // esbuild is an optional peer dep; resolve it from the local install, else fall back
34
- // to a global one.
30
+ // esbuild is an optional peer dependency: the local install's, else a global one.
35
31
  async function importEsbuild() {
36
32
  let mod
37
33
  try {
38
34
  mod = await import('esbuild')
39
35
  } catch (cause) {
40
- // Only a genuine "not installed" miss falls through to the global lookup; surface other failures.
41
- if (cause?.code !== 'ERR_MODULE_NOT_FOUND' && cause?.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
42
- throw cause
43
- }
36
+ if (cause?.code !== 'ERR_MODULE_NOT_FOUND' && cause?.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') throw cause
44
37
  const globalMain = resolveGlobalEsbuild()
45
38
  if (!globalMain) {
46
39
  throw new Error(
@@ -52,41 +45,31 @@ async function importEsbuild() {
52
45
  }
53
46
  mod = await import(pathToFileURL(globalMain).href)
54
47
  }
55
- // A globally-imported CJS copy may land its exports on `default` -- accept both shapes.
48
+ // A globally-imported CJS copy may land its exports on `default`.
56
49
  return typeof mod.build === 'function' ? mod : mod.default
57
50
  }
58
51
 
59
52
  function resolveGlobalEsbuild() {
60
- const probes = [
61
- ['npm', ['root', '-g']],
62
- ['pnpm', ['root', '-g']],
63
- ['yarn', ['global', 'dir']],
64
- ]
65
- for (const [cmd, args] of probes) {
53
+ for (const [cmd, args] of [['npm', ['root', '-g']], ['pnpm', ['root', '-g']], ['yarn', ['global', 'dir']]]) {
66
54
  let out
67
55
  try {
68
56
  out = spawnSync(cmd, args, { encoding: 'utf8' })
69
57
  } catch {
70
58
  continue
71
59
  }
72
- if (!out || out.status !== 0 || !out.stdout) continue
73
- const base = out.stdout.trim()
60
+ const base = out?.status === 0 ? out.stdout?.trim() : undefined
74
61
  if (!base) continue
75
- // `npm/pnpm root -g` print the global node_modules dir; `yarn global dir` prints a
76
- // dir whose node_modules holds the packages. Try both shapes.
62
+ // `npm/pnpm root -g` print the global node_modules; `yarn global dir` a dir whose node_modules holds them.
77
63
  for (const nm of [base, join(base, 'node_modules')]) {
78
64
  if (!existsSync(join(nm, 'esbuild', 'package.json'))) continue
79
65
  try {
80
66
  return createRequire(join(nm, 'noop.js')).resolve('esbuild')
81
- } catch {
82
- }
67
+ } catch { /* try the next */ }
83
68
  }
84
69
  }
85
70
  return undefined
86
71
  }
87
72
 
88
- // Preconditions independent of which entry we build. Per-entry language checks are deferred
89
- // to assertBuildableEntry, once selectEntry has picked one.
90
73
  function assertBuildableArtifact(artifact, label) {
91
74
  if (artifact.config.scope !== 'full') {
92
75
  throw new Error(
@@ -94,117 +77,75 @@ function assertBuildableArtifact(artifact, label) {
94
77
  `node_modules-scope artifacts omit the entry and workspace code, so there is nothing to build.`
95
78
  )
96
79
  }
97
- if (artifact.entries.size === 0) {
98
- throw new Error(`stasis build: ${label} declares no entries to build`)
99
- }
80
+ if (artifact.entries.size === 0) throw new Error(`stasis build: ${label} declares no entries to build`)
100
81
  }
101
82
 
102
- // The entry plus its transitive imports in the recorded graph -- the exact set esbuild loads
103
- // (all conditions buckets; a --metro edge's per-platform targets included).
83
+ // As esbuild loads them: every conditions bucket's edges, every platform's target (a Set visits what is added to it).
104
84
  function reachableFiles(entry, imports) {
105
85
  const seen = new Set([entry])
106
- const stack = [entry]
107
- while (stack.length > 0) {
108
- const parent = stack.pop()
109
- for (const [, byParent] of imports) {
110
- const specifiers = byParent.get(parent)
111
- if (specifiers === undefined) continue
112
- for (const [, target] of specifiers) {
113
- // A plain edge is a file string; a --metro edge is a {platform: file} Map.
114
- const targets = typeof target === 'string' ? [target] : [...target.values()]
115
- for (const file of targets) {
116
- if (!seen.has(file)) {
117
- seen.add(file)
118
- stack.push(file)
119
- }
120
- }
86
+ for (const parent of seen) {
87
+ for (const byParent of imports.values()) {
88
+ for (const target of byParent.get(parent)?.values() ?? []) {
89
+ for (const file of typeof target === 'string' ? [target] : target.values()) seen.add(file)
121
90
  }
122
91
  }
123
92
  }
124
93
  return seen
125
94
  }
126
95
 
127
- // Language checks scoped to the built entry: it must be JS/TS, and every file reachable from
128
- // it must be buildable. A non-JS file elsewhere (another entry, or a `stasis add` attachment)
129
- // isn't reached, so it doesn't block the build. imports/formats are null on a legacy lockfile.
96
+ // Only what the entry reaches must be buildable: another entry or a `stasis add` attachment doesn't block it.
130
97
  function assertBuildableEntry(artifact, entry, label) {
131
- if (!JS_EXTS.has(extname(entry))) {
98
+ if (!JS_EXTENSIONS.has(extname(entry))) {
132
99
  throw new Error(`stasis build only builds JavaScript/TypeScript entries (esbuild); got non-JS entry '${entry}' in ${label}`)
133
100
  }
134
101
  const reachable = reachableFiles(entry, artifact.imports ?? new Map())
135
- // A reachable resource (plugin captures DO record asset edges) stays allowed via BUILDABLE_FORMATS;
136
- // an entry that imports an unbuildable asset fails later at esbuild, not here.
137
102
  for (const [file, format] of artifact.formats ?? new Map()) {
138
- if (!reachable.has(file)) continue
139
- if (!BUILDABLE_FORMATS.has(format)) {
103
+ if (reachable.has(file) && !BUILDABLE_FORMATS.has(format)) {
140
104
  throw new Error(`stasis build only supports JavaScript/TypeScript bundles (esbuild); ${label} carries a '${format}' file (${file})`)
141
105
  }
142
106
  }
143
107
  }
144
108
 
145
- // Pick which recorded entry to build; required only when several are recorded. Matched
146
- // against the recorded project-relative entries (verbatim, `./`-stripped, or cwd-relative).
147
109
  function selectEntry(entryArg, entries, { cwd, root, label }) {
148
110
  const recorded = [...entries]
149
111
  const list = recorded.map((e) => ` ${e}`).join('\n')
150
112
  if (entryArg === undefined) {
151
113
  if (recorded.length === 1) return recorded[0]
152
- // length === 0 is impossible here (assertBuildableArtifact required >= 1 entry).
153
114
  throw new Error(`stasis build: ${label} has ${recorded.length} entry points; pass one as the second argument:\n${list}`)
154
115
  }
155
- const candidates = new Set([
156
- entryArg,
157
- entryArg.replace(/^\.\//u, ''),
158
- relative(root, resolve(cwd, entryArg)).split(sep).join('/'),
159
- ])
116
+ const candidates = new Set([entryArg, entryArg.replace(/^\.\//u, ''), relative(root, resolve(cwd, entryArg)).split(sep).join('/')])
160
117
  const match = recorded.find((e) => candidates.has(e))
161
- if (match === undefined) {
162
- throw new Error(`stasis build: '${entryArg}' is not an entry point of ${label}; available:\n${list}`)
163
- }
118
+ if (match === undefined) throw new Error(`stasis build: '${entryArg}' is not an entry point of ${label}; available:\n${list}`)
164
119
  return match
165
120
  }
166
121
 
167
- // Build a bundle-load State that serves an in-memory Bundle. skipDiscovery does NO
168
- // filesystem discovery (no package.json walk, no on-disk config, no stray stasis.code.br).
122
+ // A bundle-load State serving `bundle`, with no discovery on disk (no package.json, config or stray stasis.code.br).
169
123
  function loadStateForBundle(root, bundle) {
170
124
  const state = new State(root, { bundle: 'load', lock: 'ignore', scope: bundle.config.scope, skipDiscovery: true })
171
- const sources = new Map()
172
- const resources = new Map()
125
+ state.sources = new Map()
126
+ state.resources = new Map()
173
127
  for (const [file, content] of bundle.sources) {
174
- if (Bundle.isResourceFormat(bundle.formats.get(file))) resources.set(file, content)
175
- else sources.set(file, content)
128
+ if (Bundle.isResourceFormat(bundle.formats.get(file))) state.resources.set(file, content)
129
+ else state.sources.set(file, content)
176
130
  }
177
- state.sources = sources
178
- state.resources = resources
179
131
  state.formats = bundle.formats
180
132
  state.imports = bundle.imports
181
133
  state.entries = new Set(bundle.entries)
182
- // Not state.executable either: like state.modules below, the load path never reads it, and every
183
- // consumer narrows against state.modules -- which is empty here -- so copying it would be inert.
184
- // Not state.modules: the load path never reads it (only the capture paths write it).
134
+ // Not state.modules or state.executable: the load path reads neither.
185
135
  return state
186
136
  }
187
137
 
188
- // A file's bytes as the State serves them: a Buffer for a base64 resource, else a string.
189
138
  const asBytes = (source) => (Buffer.isBuffer(source) ? source : Buffer.from(source))
190
139
 
191
- // The bytes the artifact carries for `file` (a path from the State's root, or an absolute one), verified
192
- // by getFile.
140
+ // The bytes the artifact carries for `file`, verified by getFile.
193
141
  const readCarried = (state, file) => asBytes(state.getFile(pathToFileURL(resolve(state.root, file)).toString()).source)
194
142
 
195
- // --metro=PLATFORM's resource hook (StasisEsbuild's `resource`): each resource the build reaches -- in a
196
- // --metro bundle, a Metro asset, as it records an import edge to no other -- served as the module
197
- // Metro builds of it for `platform` (@preventive/rn's assetData and assetModule), from the files of the
198
- // asset the artifact carries in its directory, at its path from the project root. The module's require
199
- // of the asset registry resolves to the file the artifact carries for it (metro-assets.js), an edge
200
- // added to the State's graph: the bundle records none, as Metro adds it past the source. `built`
201
- // collects each asset's data for --assets-dest.
143
+ // Each Metro asset served as the module Metro builds of it, its require of the registry added as Metro adds it.
202
144
  function metroAssetResource(state, platform, built) {
203
145
  const listing = bundleDirHost(state)
204
146
  const registryFor = assetRegistryResolver(platform, state.sources)
205
147
  return (source, { path }) => {
206
148
  const rel = toPosix(state.relative(path))
207
- // The files the artifact carries, the asset's own bytes those the plugin serves it by.
208
149
  const host = {
209
150
  readdir: (dir) => listing.readdir(dir).map(({ name }) => name),
210
151
  readFile: (file) => (file === path ? asBytes(source) : readCarried(state, file)),
@@ -216,13 +157,8 @@ function metroAssetResource(state, platform, built) {
216
157
  }
217
158
  }
218
159
 
219
- // --flow's per-file transform (StasisEsbuild's `transform` hook shape), as `stasis bundle --flow` reads
220
- // a file, and Metro's Babel builds it: a JS-family one gets its Flow types stripped (flow.js), an
221
- // import listing types alone dropped whole, as Babel's Flow transform drops it (a --metro bundle
222
- // records no edge for it) -- one marked `@flow` (hasFlowPragma) whether or not esbuild parses it as it
223
- // is (where `f<T>(x)` is a comparison, not Flow's call), any other only where esbuild can't parse it.
224
- // A file still unparseable fails the build in esbuild: Flow syntax that is code, which stripping
225
- // leaves, or one flow-remove-types itself can't parse, served as it is.
160
+ // --flow, as Metro's Babel builds a file: Flow types stripped from a file marked `@flow`, else only where
161
+ // esbuild can't parse it; what still doesn't parse fails the build in esbuild.
226
162
  function createFlowTransform(esbuild) {
227
163
  return async (source, { path, loader }) => {
228
164
  if (!FLOW_EXTS.has(extname(path))) return undefined
@@ -241,24 +177,12 @@ function createFlowTransform(esbuild) {
241
177
  }
242
178
  }
243
179
 
244
- // Two transform hooks over a file in turn, the second over what the first made of it.
245
180
  const chainTransforms = (first, second) => async (source, file) => {
246
181
  const firstMade = await first(source, file)
247
182
  return (await second(firstMade?.contents ?? source, { ...file, loader: firstMade?.loader ?? file.loader })) ?? firstMade
248
183
  }
249
184
 
250
- const CONFIG_FILE = 'stasis.config.json'
251
-
252
- // A list option as the command line takes one, as an array of strings or one string, each split at commas.
253
- const listOf = (value) => [value].flat().flatMap((v) => v.split(',')).map((v) => v.trim()).filter(Boolean)
254
-
255
- // The options of `entry` in the `entries` of the stasis.config.json the artifact carries at its root
256
- // (`state`'s), read by `stasis build` itself, apart from how `stasis bundle` builds by them: of each
257
- // entry's options, those that say how its code is built -- `jsx` (as --loader=.js:jsx), `flow`,
258
- // `define` (its K=V strings, one or an array) and `metro` with its `platforms` (a list, as on the
259
- // command line); the rest are the bundle's. An entry is named as `stasis bundle` names it, by its path
260
- // from the config's directory. -> { jsx, flow, define, platforms } (`platforms` only under `metro`),
261
- // or null where the artifact carries no config, or it names no such entry
185
+ // `entry`'s options in the stasis.config.json the artifact carries that say how its code is built, or null.
262
186
  function configEntryOptions(state, entry) {
263
187
  if (!state.sources.has(CONFIG_FILE) && !state.resources.has(CONFIG_FILE)) return null
264
188
  let config
@@ -269,13 +193,12 @@ function configEntryOptions(state, entry) {
269
193
  }
270
194
  const entries = config?.entries
271
195
  if (entries === undefined) return null
272
- const isObject = (value) => value !== null && typeof value === 'object' && !Array.isArray(value)
273
- if (!isObject(entries)) throw new Error(`stasis build: the artifact's ${CONFIG_FILE}: entries must be an object`)
196
+ if (!isPlainObject(entries)) throw new Error(`stasis build: the artifact's ${CONFIG_FILE}: entries must be an object`)
274
197
  const name = Object.keys(entries).find((key) => toPosix(relative(state.root, resolve(state.root, key))) === entry)
275
198
  if (name === undefined) return null
276
199
  const what = `the artifact's ${CONFIG_FILE}: entries ${JSON.stringify(name)}`
277
200
  const options = entries[name]
278
- if (!isObject(options)) throw new Error(`stasis build: ${what} must be an object of options`)
201
+ if (!isPlainObject(options)) throw new Error(`stasis build: ${what} must be an object of options`)
279
202
  for (const flag of ['jsx', 'flow', 'metro']) {
280
203
  if (options[flag] !== undefined && typeof options[flag] !== 'boolean') throw new Error(`stasis build: ${what}: ${flag} must be true or false`)
281
204
  }
@@ -294,31 +217,17 @@ function configEntryOptions(state, entry) {
294
217
  }
295
218
  let platforms
296
219
  if (options.metro === true) {
297
- platforms = [...new Set(listOf(strings('platforms')))]
220
+ platforms = [...new Set(strings('platforms').flatMap((v) => v.split(',')).map((v) => v.trim()).filter(Boolean))]
298
221
  if (platforms.length === 0) throw new Error(`stasis build: ${what} sets metro but names no platforms`)
299
222
  }
300
223
  return { name, jsx: options.jsx === true, flow: options.flow === true, define, platforms }
301
224
  }
302
225
 
303
- // Run `stasis build`: run esbuild over one recorded entry, following the artifact's
304
- // recorded import graph EXACTLY (not esbuild's resolver). A specifier the artifact records
305
- // is always followed from the artifact; `external` only steers the specifiers it doesn't.
226
+ // Run `stasis build`: esbuild over one recorded entry, following the artifact's recorded import graph exactly,
227
+ // not esbuild's resolver: `external` only steers the specifiers it doesn't record.
306
228
  export async function buildCommand({
307
- cwd = process.cwd(),
308
- artifact,
309
- entry,
310
- output,
311
- format,
312
- platform = 'node',
313
- babel = false,
314
- flow = false,
315
- minify = false,
316
- sourcemap = false,
317
- define = {},
318
- external = [],
319
- loader = {},
320
- metro,
321
- assetsDest,
229
+ cwd = process.cwd(), artifact, entry, output, format, platform = 'node', babel = false, flow = false, minify = false,
230
+ sourcemap = false, define = {}, external = [], loader = {}, metro, assetsDest,
322
231
  } = {}) {
323
232
  if (!artifact) throw new Error('stasis build: an artifact (bundle or lockfile) is required')
324
233
  if (!output) throw new Error('stasis build: --output is required (a .js/.cjs/.mjs file, or a directory)')
@@ -329,9 +238,7 @@ export async function buildCommand({
329
238
  if (flow && babel) {
330
239
  throw new Error('stasis build: --babel hands the project\'s Babel config each file as it is, Flow included, for it to compile; --flow strips Flow before esbuild without it -- pass one')
331
240
  }
332
- // --platform=hermes is a stasis-level target, not an esbuild platform (esbuild gets
333
- // 'neutral'): every code file is downleveled to Hermes' dialect before the final bundle,
334
- // and the bundle itself must avoid ESM -- Hermes has no import/export.
241
+ // --platform=hermes is stasis's target, esbuild's 'neutral': code downleveled to Hermes' dialect, and no ESM.
335
242
  const hermes = platform === 'hermes'
336
243
  format ??= hermes ? 'iife' : 'esm'
337
244
  if (hermes && format === 'esm') {
@@ -341,21 +248,16 @@ export async function buildCommand({
341
248
  const { kind, artifact: parsed } = parseFileWithKind(artifactAbs)
342
249
  assertBuildableArtifact(parsed, artifact)
343
250
 
344
- // Anchor artifact-relative paths at the artifact's own directory; a lockfile's sources
345
- // are read + verified from there.
251
+ // Paths are the artifact's directory's, where a lockfile's sources are read and verified.
346
252
  const root = dirname(artifactAbs)
347
253
  const selectedEntry = selectEntry(entry, parsed.entries, { cwd, root, label: artifact })
348
254
  assertBuildableEntry(parsed, selectedEntry, artifact)
349
255
 
350
256
  const bundle = kind === 'lockfile' ? bundleFromLockfile(parsed, { root }) : parsed
351
257
  const state = loadStateForBundle(root, bundle)
352
- // Make the entry absolute against the State's root so resolution is independent of process cwd.
353
258
  const entryPoint = resolve(state.root, selectedEntry)
354
259
 
355
- // The entry's options in the stasis.config.json the artifact carries, under the flags given: jsx as
356
- // --loader=.js:jsx, flow as --flow (not under --babel, whose config compiles Flow itself), its define
357
- // under --define's, and metro as --metro for its one platform; of several, --metro picks one, which
358
- // must be one of them.
260
+ // The config's options for the entry, under the flags given (flow not under --babel, whose config compiles it).
359
261
  const configured = configEntryOptions(state, selectedEntry)
360
262
  if (configured !== null) {
361
263
  const taken = []
@@ -385,11 +287,8 @@ export async function buildCommand({
385
287
  }
386
288
  if (taken.length > 0) console.warn(`[stasis] ${selectedEntry}: ${taken.join(' ')}, as ${CONFIG_FILE}'s entries ${JSON.stringify(configured.name)} sets`)
387
289
  }
388
- // --metro, given or the config's, builds as `stasis bundle --metro` reads the files: JSX in .js
389
- // (--loader=.js:jsx, where no --loader names .js), Flow stripped (--flow, not under --babel, whose
390
- // config compiles it), and each of METRO_RELEASE_DEFINE's names defined as Metro's release build
391
- // defines it, where neither --define nor the config gives it a value, as esbuild takes one (JS):
392
- // outside Metro's prelude, `__DEV__` is no global at all.
290
+ // As `stasis bundle --metro` reads the files; METRO_RELEASE_DEFINE's names too, since outside Metro's
291
+ // prelude `__DEV__` is no global at all.
393
292
  if (metro !== undefined) {
394
293
  if (loader['.js'] === undefined) loader = { ...loader, '.js': 'jsx' }
395
294
  if (!babel) flow = true
@@ -402,24 +301,17 @@ export async function buildCommand({
402
301
  }
403
302
 
404
303
  const esbuild = await importEsbuild()
405
- // Per-file code rewrites the plugin applies before esbuild parses a served file:
406
- // --babel runs the project's own babel.config.* over the original source (no esbuild
407
- // pre-transform), and otherwise --platform=hermes uses the built-in downlevel pipeline.
408
- // Both resolve Babel from the project (cwd), never from stasis's own dependencies. --flow
409
- // strips Flow types first, from what esbuild can't parse.
410
304
  let transform
411
305
  if (babel) transform = createBabelConfigTransform({ projectDir: cwd })
412
306
  else if (hermes) transform = createHermesTransform({ projectDir: cwd, esbuild })
413
307
  if (flow) transform = transform === undefined ? createFlowTransform(esbuild) : chainTransforms(createFlowTransform(esbuild), transform)
414
- // --metro=PLATFORM: PLATFORM's target of each per-platform edge, and each asset as Metro builds it.
415
308
  const builtAssets = new Map()
416
309
  const resource = metro === undefined ? undefined : metroAssetResource(state, metro, builtAssets)
417
310
 
418
311
  const outAbs = resolve(cwd, output)
419
312
  const asFile = /\.[cm]?js$/u.test(output)
420
- // Never overwrite a file the artifact attests: esbuild's own overwrite check fires only
421
- // after writing (corrupting a lockfile's hash), so we build write:false and refuse to
422
- // clobber any recorded file before touching disk.
313
+ // Never overwrite a file the artifact attests: esbuild's own overwrite check fires only after writing
314
+ // (corrupting a lockfile's hash), so it builds write:false and each output is checked before any is written.
423
315
  const attested = new Set([...state.sources.keys(), ...state.resources.keys()].map((f) => resolve(state.root, f)))
424
316
 
425
317
  let result
@@ -438,16 +330,13 @@ export async function buildCommand({
438
330
  ...(external.length > 0 ? { external } : {}),
439
331
  ...(Object.keys(define).length > 0 ? { define } : {}),
440
332
  ...(asFile ? { outfile: outAbs } : { outdir: outAbs }),
441
- // Loader overrides go through the plugin: it serves every in-bundle file, so esbuild's
442
- // own `loader` option never sees them. e.g. { '.js': 'jsx' } to parse JSX in .js files.
333
+ // Loaders go through the plugin: it serves every file, so esbuild's own `loader` option never sees them.
443
334
  plugins: [new StasisEsbuild(state, { loaders: new Map(Object.entries(loader)), transform, resource, platform: metro })],
444
335
  })
445
336
  } catch (err) {
446
- // Under logLevel:'silent' esbuild puts the real errors on err.errors; surface them, then fail.
337
+ // Under logLevel:'silent' esbuild puts the real errors on err.errors.
447
338
  if (Array.isArray(err?.errors) && err.errors.length > 0) {
448
- const formatted = await esbuild.formatMessages(err.errors, { kind: 'error', color: false })
449
- for (const line of formatted) process.stderr.write(line)
450
- // A resource the build reaches with no loader for its extension: what builds one.
339
+ for (const line of await esbuild.formatMessages(err.errors, { kind: 'error', color: false })) process.stderr.write(line)
451
340
  const unloaded = err.errors.map((e) => /^No loader is configured for "([^"]+)" files/u.exec(e.text)?.[1]).find(Boolean)
452
341
  if (unloaded !== undefined) {
453
342
  process.stderr.write(
@@ -463,16 +352,12 @@ export async function buildCommand({
463
352
  throw err
464
353
  }
465
354
 
466
- // --assets-dest's copies of the assets built, as `react-native bundle --assets-dest` lays them out for
467
- // the platform (@preventive/rn's assetsDestFiles), from the bytes the artifact carries, in a stable
468
- // order (esbuild loads in parallel).
355
+ // As `react-native bundle --assets-dest` lays them out, in a stable order (esbuild loads in parallel).
469
356
  const assetFiles = assetsDest === undefined
470
357
  ? []
471
358
  : assetsDestFiles([...builtAssets.keys()].toSorted().map((rel) => builtAssets.get(rel)), metro)
472
359
  .map(({ dest, src, contents }) => ({ path: resolve(cwd, assetsDest, dest), contents: contents ?? readCarried(state, src) }))
473
360
  const writes = [...result.outputFiles, ...assetFiles]
474
-
475
- // Refuse to clobber an attested source, checked against the actual output paths before any write.
476
361
  for (const { path } of writes) {
477
362
  if (attested.has(path)) {
478
363
  throw new Error(
@@ -483,8 +368,7 @@ export async function buildCommand({
483
368
  }
484
369
 
485
370
  if (result.warnings.length > 0) {
486
- const formatted = await esbuild.formatMessages(result.warnings, { kind: 'warning', color: false })
487
- for (const line of formatted) process.stderr.write(line)
371
+ for (const line of await esbuild.formatMessages(result.warnings, { kind: 'warning', color: false })) process.stderr.write(line)
488
372
  }
489
373
 
490
374
  for (const { path, contents } of writes) writeFile(path, contents)