@exodus/stasis 1.0.0-beta.8 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +7 -2
  2. package/bin/stasis.js +263 -446
  3. package/package.json +38 -13
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1718 -908
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +24 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  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 +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +221 -475
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +170 -235
  44. package/src/resolve-node.js +33 -46
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +241 -278
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +54 -46
  57. package/src/vfs-bundle/github.js +115 -92
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +434 -259
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +25 -51
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
package/bin/stasis.js CHANGED
@@ -1,13 +1,12 @@
1
1
  #!/usr/bin/env node
2
2
 
3
- import { spawn } from 'node:child_process'
4
- import { once } from 'node:events'
5
3
  import { fileURLToPath } from 'node:url'
6
4
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path'
7
5
  import { existsSync, realpathSync } from 'node:fs'
8
- import { homedir, constants as osConstants } from 'node:os'
6
+ import { homedir } from 'node:os'
9
7
  import assert from 'node:assert/strict'
10
- import { parseBrotliQuality, parseLeadingOptions, parseResourcesOption } from '@exodus/stasis-core/util'
8
+ import { parseLeadingOptions, valueFlagsOf } from '@exodus/stasis-core/util'
9
+ import { addCli, brotliQualityOption, extractCli, parseRunOptions, pruneCli, runProgram, setEnv, setRunEnv } from '@exodus/stasis-core/cli'
11
10
  import pkg from '../package.json' with { type: 'json' }
12
11
 
13
12
  const argv = [...process.argv]
@@ -18,116 +17,55 @@ const jsname = argv.shift()
18
17
  const pathsEqual = (a, b) => a === b || (existsSync(a) && realpathSync(a) === b)
19
18
  assert(basename(jsname) === 'stasis' || pathsEqual(jsname, fileURLToPath(import.meta.url)))
20
19
 
21
- function usage(prefix = '') {
22
- console.error(`${prefix}\nUsage:
20
+ const HELP = `Usage:
23
21
  stasis run --lock=(add|replace|frozen|ignore) [--bundle=(add|replace|load|frozen|ignore)] [--bundle-file=path/to/bundle.br] [--resources-bundle-file=path/to/resources.br] [--dependencies] [--child-process] [--package-json] [--mock] [--import=module ...] [--fs=(sync|async)] [--resources=ext,ext] [--brotli-quality=0..11] path/to/file.js ...
24
- (--import forwards extra preload modules (repeatable) to the node process running the entry,
25
- e.g. --import=./instrument.mjs for a setup/instrumentation preload; a preload's own module
26
- graph is runner infrastructure like stasis's loader itself, so it stays out of the
27
- lockfile/bundle -- except modules the app graph also reaches, which are attested like any
28
- other app code; with --mock, preloads run under the mock's side-effect denials, so a preload
29
- that spawns helper processes cannot work there)
30
- stasis bundle [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
31
- (Solidity: a directory stands for every .sol file under it (a missing or empty one is skipped) --
32
- "stasis bundle src test script" is what "forge build" compiles, "stasis bundle contracts" what
33
- Hardhat does; imports resolve through the remappings "forge build" uses (remappings.txt,
34
- foundry.toml's profile, FOUNDRY_PROFILE, lib/ auto-detection incl. dependencies' own configs),
35
- else a root remappings.txt, then node_modules by file path; --mapping instead takes exactly the
36
- remappings that one file lists; an import must reach a .sol file inside the project, and a
37
- dependency's only other dependencies' files; --manifests also carries foundry.toml,
38
- remappings.txt, foundry.lock, soldeer.lock, .gitmodules and package.json of the project and its
39
- bundled dependencies, as written: RPC/Etherscan keys and URL credentials in them included)
40
- stasis bundle [--add] [--output=(path|-)] path/to/file.php ...
41
- stasis bundle [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--package-json] [--lockfile=path/to/stasis.lock.json] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
42
- stasis bundle --metro [--metro-resolver] --platforms=ios,android [--platforms=web] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--package-json] [--lockfile=path/to/stasis.lock.json] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
43
- stasis bundle [--add] [--output=(path|-)] path/to/file.(sh|bash) ...
22
+ stasis bundle [--deptree] [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] [--babel|--babel-aliases=path/to/aliases.json] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--define=K=V ...] [--package-json] [--lockfile=path/to/stasis.lock.json [--lockfile-only]] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
23
+ stasis bundle [--deptree] [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
44
24
  stasis bundle [--cargo] [--cargo-features=a,b,pkg/c] [--cargo-no-default-features] [--cargo-all-features] [--cargo-target=(triple|host)] [--cargo-manifests] [--add] [--output=(path|-)] path/to/file.rs ...
45
- (Rust: each crate's Cargo features are resolved from Cargo.toml/Cargo.lock like "cargo build" of the
46
- entries' packages, so #[cfg(feature = ...)] code that is off stays out -- by cargo's own resolver
47
- when there is a Cargo.lock (version 3 or 4; an older one stops the build), --cargo-target and every
48
- locked package in-tree, by replaying the manifests otherwise (said, with why); --cargo takes the resolution
49
- from "cargo metadata" instead -- it runs cargo, so only on a project you trust; the --cargo-*
50
- feature flags are cargo's --features / --no-default-features / --all-features for those packages;
51
- --cargo-target asks rustc for the target's cfgs so #[cfg(unix)]-style code for other targets stays
52
- out too, otherwise it is all kept; --cargo-manifests also bundles each bundled package's Cargo.toml
53
- and build script (a vendored crate's .cargo-checksum.json too), the workspace Cargo.toml, Cargo.lock
54
- and cargo configs, as written: tokens and URL credentials in them included)
55
- (writes to stasis.code.br by default, a JS bundle's in the project root its paths are relative to,
56
- where stasis run --bundle=load finds it; --output=- streams to stdout; --add merges into an
57
- existing bundle instead of replacing it (not with --output=-); --brotli-quality=0..11, default 9;
58
- --jsx parses JSX in .js/.cjs/.mjs files, e.g. React Native source (.jsx/.tsx files need no flag;
59
- put JSX-in-TS in a .tsx file);
60
- --flow strips Flow types from .js/.cjs/.mjs sources oxc can't parse (needs the optional flow-remove-types dep);
61
- --typescript resolves TS the way tsc does: an import of ./x.js lands on ./x.ts when no .js is on disk
62
- (likewise .mjs/.cjs -> .mts/.cts, extensionless ./x -> ./x.ts, incl. exports/imports/main targets),
63
- honouring tsconfig compilerOptions.paths aliases (from the tsconfig.json beside the importing
64
- file's package.json -- its workspace package's in a monorepo, else the project's -- or --tsconfig=path);
65
- never from or into node_modules (by real path, so linked workspace packages still are); not with --metro-resolver; implied when every entry is TS and each relative ./x.js-style import
66
- in them exists only as its TS source (otherwise a failing import it would resolve names it);
67
- --resources carries reached assets (e.g. --resources=png,svg) as resources instead of failing to bundle them;
68
- --package-json auto-includes each bundled module's package.json, even ones the scan never reached)
69
- stasis github-bundle --github=owner/name [--sha=commit|--tag=name] [--directory=path] [--package-manager=(pnpm|yarn1|npm|soldeer)] [--package-manager-version=version] [--generate=prisma] [--lockfile=path/to/stasis.lock.json] [--output=(path|-)] [stasis bundle's options for the entries] [path/in/repo/to/(file.(js|ts|jsx|tsx)|file.sol|dir) ...]
70
- (bundles a GitHub repo at a commit, or the one --tag names, its default branch's head without
71
- either, as "stasis bundle" bundles a clone of it once installed: the tree is fetched (with
72
- GITHUB_TOKEN where set) and held to its git tree id, and the dependencies are laid out in memory
73
- from the lockfile alone, as "pnpm install --frozen-lockfile --ignore-scripts" (pnpm 9, 10, 11 or
74
- 12), "yarn install --frozen-lockfile --ignore-scripts" (yarn 1.22), "npm ci --ignore-scripts"
75
- (npm 10.9.3 to 10.9.9, or 11.11.1 to 11.21.0) or "soldeer install" (0.12, for .sol entries)
76
- would: nothing is installed, no package script runs, and every tarball and zip is held to the
77
- lockfile, all cached where "stasis audit" caches. Without --package-manager, the one whose
78
- lockfile installs --directory (or the repo's root), if only one's does; at
79
- --package-manager-version, else at the root package.json's packageManager pin, else pnpm
80
- 10.33.4, yarn 1.22.22, npm 11.21.0 (which no packageManager pins) or Soldeer 0.12.0. The entries
81
- are paths in --directory, or in the repo; without them, the JS files its package.json names as
82
- main, exports and bin, resolved as the build resolves them (--conditions, --mainFields, --metro
83
- --platforms, --typescript), or for Soldeer its .sol files directly in it, under contracts/, and
84
- under its source directory (foundry.toml's src, else src/), but tests, scripts, mocks and
85
- dependency or build directories; its paths, and the directory its repo names, are
86
- --directory's, or of a JS bundle, the innermost package's at or above it holding every file it
87
- bundles, the project root's where one is outside; not with --metro-resolver, --cargo* or --add;
88
- --generate=prisma first writes, for each project with a "prisma-client" generator, the Prisma
89
- Client its "prisma generate" would (Prisma 7.4.0 to 7.10.0), with the optional
90
- @prisma/client-generator-ts 7.10.0 dependency: nothing of the repo runs, its schema and config
91
- are read as data, and its prisma for its version alone;
92
- writes to owner-name.<commit's first 7>.stasis.code.br by default,
93
- owner-name.<--directory, its / made ->.<commit's first 7>.stasis.code.br with --directory, each
94
- character outside [A-Za-z0-9._-] made _, and a directory too deep to fit in 255 characters cut,
95
- with a hash of it; --output=- streams to stdout)
25
+ stasis bundle [--add] [--output=(path|-)] path/to/file.(php|sh|bash) ...
26
+ stasis bundle [--deptree] [--babel] [--metro-resolver] [--cargo] [--cargo-target=(triple|host)] [--lockfile=path/to/stasis.lock.json [--lockfile-only]] [--brotli-quality=0..11] [--add] [--output=(path|-)] [entry ...] (the entries' options from stasis.config.json's entries)
27
+ stasis github-bundle (owner/name[/path]|--github=owner/name [--directory=path]) [--sha=commit|--tag=name] [--package-manager=(pnpm|yarn1|npm|soldeer) [--package-manager-version=version]] [--no-lazy] [--generate=prisma|--no-generate] [--lockfile=path/to/stasis.lock.json] [--lockfile-only] [--output=(path|-)] [stasis bundle's options for the entries] [path/in/repo/to/(file.(js|ts|jsx|tsx)|file.sol|dir) ...]
96
28
  stasis add path/to/(file|dir) ...
97
- (adds the listed files to the project's bundle(s) with no dependency resolution;
98
- a directory expands to its files. Requires a stasis.config.json (all fields optional).)
99
- stasis build --output=(dir|file.js) [--format=(esm|cjs|iife)] [--platform=(node|browser|neutral|hermes)] [--babel] [--minify] [--sourcemap] [--define=K=V ...] [--external=pkg ...] [--loader=.ext:name ...] path/to/(stasis.code.br|stasis.lock.json) [entry]
100
- (--platform=hermes downlevels every file for Hermes (classes, let/const, arrows, ...; via esbuild + Babel)
101
- and defaults --format to iife; --babel instead transforms every file with the project's own
102
- babel.config.(js|cjs|mjs|json); both resolve @babel/core and plugins from the project's dev deps)
103
- stasis extract [--output=path/to/dir] path/to/bundle.stasis.code.br
29
+ stasis build --output=(dir|file.js) [--format=(esm|cjs|iife)] [--platform=(node|browser|neutral|hermes)] [--babel|--flow] [--minify] [--sourcemap] [--define=K=V ...] [--external=pkg ...] [--loader=.ext:name ...] [--metro=(ios|android|...) [--assets-dest=dir]] path/to/(stasis.code.br|stasis.lock.json) [entry]
30
+ stasis extract [--output=path/to/dir] [--lock=(frozen|add|replace|ignore|none)] path/to/bundle.stasis.code.br
104
31
  stasis diff --stat [--imports] path/to/(lockfile|bundle) path/to/(lockfile|bundle)
105
32
  stasis prune [path/to/project]
106
- stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories] path/to/file ...
107
- (audits the dependencies the files hold: npm packages by npm's advisories, vendored crates and
108
- Composer packages by OSV's, and Soldeer packages and GitHub repos (Foundry's lib/) by those their
109
- GitHub repository publishes, asked with GITHUB_TOKEN where it is set; a Composer dev version is
110
- listed as not audited, no database having one;
111
- --why lists, per advisory, the cross-module import paths that pull an npm package in,
112
- prefixed by the bundle consumer that imports each chain at the top level, e.g. "run: a -> b -> c";
113
- it skips chains whose full tail is already listed as its own chain -- --why-deep keeps them all;
114
- --why-full spells every chain out instead of collapsing repeated tails to "a -> b -> ... -> d";
115
- --reason=consumer shows only advisories related to that consumer, and with --why only its chains;
116
- --repo-advisories also asks each package's GitHub repository for the advisories its maintainers
117
- published there, before GitHub reviews them into the databases above; it needs a token in
118
- GITHUB_TOKEN, and asks the repository each package's artifact records, else the one the
119
- package.json a bundle carries of an npm package names, else looks one up and caches it for a
120
- month in the user cache dir, e.g. ~/.cache/stasis)
33
+ stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories|--no-repo-advisories] path/to/(lockfile|bundle) ...
34
+ stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories|--no-repo-advisories] (the bundle stasis bundle builds of stasis.config.json's entries, not written)
35
+ stasis validate [--github=owner/name] [--sha=commit] [--directory=path] [--only-deps] [--lockfile=path | --no-lockfile] [--allow-unverified] [--show-valid] path/to/bundle
121
36
  stasis sbom --format=(spdx|cyclonedx) [--output=(path|-)] path/to/(lockfile|bundle) ...
122
- (streams to stdout by default; --output=- is explicit stdout)
123
- `.trim())
37
+ stasis --version
38
+
39
+ Each command's options: https://github.com/PreventiveMeasures/stasis/blob/main/doc/<command>.md
40
+ (run, bundle, github-bundle, build, extract, diff, prune, audit, validate, sbom; add is in bundle.md)`
41
+
42
+ // The help, on stderr. Exits 0 when asked for (--help), 1 when printed for want of a command.
43
+ function usage(asked = false) {
44
+ console.error(HELP)
45
+ process.exit(asked ? 0 : 1)
46
+ }
47
+
48
+ // A usage error: the message and where the help is, never the help itself.
49
+ function fail(message) {
50
+ console.error(`${message}\nRun 'stasis --help' for usage.`)
124
51
  process.exit(1)
125
52
  }
126
53
 
127
- function setEnv(name, value) {
128
- const env = process.env[name]
129
- if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
130
- process.env[name] = value === undefined ? '' : value
54
+ // `build()`'s result, what it warns (console.warn's) held meanwhile: dropped where it succeeds, said
55
+ // where it fails, before its error is.
56
+ async function warningsOnFailure(build) {
57
+ const warn = console.warn
58
+ const held = []
59
+ console.warn = (...args) => held.push(args)
60
+ try {
61
+ return await build()
62
+ } catch (error) {
63
+ console.warn = warn
64
+ for (const args of held) console.warn(...args)
65
+ throw error
66
+ } finally {
67
+ console.warn = warn
68
+ }
131
69
  }
132
70
 
133
71
  // The per-user cache directory, as each platform names it (XDG ignores a relative path).
@@ -143,87 +81,25 @@ const command = argv.shift()
143
81
  if (command === '-v' || command === '--version') {
144
82
  console.log(`v${pkg.version}`)
145
83
  process.exit(0)
84
+ } else if (command === '-h' || command === '--help') {
85
+ usage(true)
146
86
  } else if (command === 'run') {
147
- const options = {
148
- lock: { type: 'string', default: 'none' },
149
- bundle: { type: 'string', default: 'none' },
150
- 'bundle-file': { type: 'string' },
151
- 'resources-bundle-file': { type: 'string' },
152
- debug: { type: 'boolean' },
153
- dependencies: { type: 'boolean' },
154
- 'child-process': { type: 'boolean' },
155
- 'package-json': { type: 'boolean' },
156
- mock: { type: 'boolean' },
157
- import: { type: 'string', multiple: true },
158
- fs: { type: 'string' },
159
- resources: { type: 'string' },
160
- 'brotli-quality': { type: 'string' },
161
- }
162
- const values = parseLeadingOptions(argv, options, {
163
- valueFlags: ['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--import', '--resources', '--brotli-quality'],
164
- onError: usage,
165
- })
166
- if (argv.length === 0) usage('Nothing to run: no path to file given')
167
- if (!['none', 'ignore', 'add', 'replace', 'frozen'].includes(values.lock)) usage('Error: invalid --lock value')
168
- const lock = values.lock
169
- const scope = values.dependencies ? 'node_modules' : 'full'
170
- const bundle = values.bundle
171
- const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
172
- const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
173
- const debug = values.debug ? '1' : ''
174
- if (!['none', 'ignore', 'add', 'replace', 'load', 'frozen'].includes(bundle)) usage('Error: invalid --bundle value')
175
- if (bundleFile && bundle === 'none') usage('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
176
- // --resources-bundle-file needs an active bundle mode (unlike --bundle-file, inert under ignore).
177
- if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) usage('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
178
- if (bundle === 'load' && lock !== 'frozen' && lock !== 'none' && lock !== 'ignore') usage('Error: --bundle=load is incompatible with --lock=(add|replace)')
179
- if (lock === 'none' && bundle === 'none') usage('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
180
- if (values.mock && bundle === 'load') usage('Error: --mock is for capturing imports while building a bundle; not compatible with --bundle=load')
181
- // --fs requires a bundle mode (add|replace|load); `sync` patches the sync fs readers,
182
- // `async` adds their callback + fs.promises counterparts on top.
183
- if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) usage("Error: --fs must be 'sync' or 'async'")
184
- if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) usage('Error: --fs requires --bundle=(add|replace|load)')
185
- const captureFs = values.fs ?? ''
186
- // --resources: comma-separated extension/filename allowlist for `--fs` captures.
187
- const resources = values.resources ?? ''
188
- let brotliQuality
189
- if (values['brotli-quality'] !== undefined) {
190
- try {
191
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
192
- } catch (cause) {
193
- usage(`Error: ${cause.message}`)
194
- }
195
- }
196
- // --import: extra preload module(s) passed through to the spawned node. Node resolves each
197
- // against the project cwd; they ride AFTER stasis's own loader import.
198
- const imports = values.import ?? []
199
- if (imports.some((s) => s === '')) usage('Error: --import requires a module specifier (e.g. --import=./instrument.mjs)')
87
+ const run = parseRunOptions(argv, { options: { 'package-json': { type: 'boolean' }, mock: { type: 'boolean' } }, fail })
88
+ const { values, bundle, bundleFile, resourcesBundleFile } = run
89
+ if (values.mock && bundle === 'load') fail('Error: --mock is for capturing imports while building a bundle; not compatible with --bundle=load')
200
90
  // Not a usage error: plain instrumentation/setup preloads still work under the mock; only ones
201
91
  // that need the denied surfaces (spawning helper processes, network) die, and they do so loudly.
202
- if (values.mock && imports.length > 0) {
92
+ if (values.mock && run.imports.length > 0) {
203
93
  console.warn("[stasis] Warning: --import preloads run under --mock's side-effect denials; a preload that spawns helper processes will fail there")
204
94
  }
205
- // --child-process: forward forked-child (e.g. Metro worker) capture to the root via per-pid shards.
206
- const childProcess = values['child-process'] ? '1' : ''
207
95
  // --package-json: auto-include every bundled module's package.json. Only meaningful while WRITING
208
96
  // a bundle (add|replace) -- there's nothing to fold the manifests into otherwise.
209
97
  if (values['package-json'] && bundle !== 'add' && bundle !== 'replace') {
210
- usage('Error: --package-json requires --bundle=(add|replace)')
98
+ fail('Error: --package-json requires --bundle=(add|replace)')
211
99
  }
212
100
  const packageJSON = values['package-json'] ? '1' : ''
213
- console.warn('[stasis] Running stasis with config:', { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...(packageJSON && { packageJSON: true }), ...(values.mock && { mock: true }), ...(imports.length > 0 && { import: imports }), ...(values.fs && { fs: values.fs }), ...(resources && { resources }), ...(brotliQuality !== undefined && { brotliQuality }) })
214
- if (debug) console.warn(`[stasis] Warning: stasis debug mode active`)
215
- setEnv('EXODUS_STASIS_LOCK', lock)
216
- setEnv('EXODUS_STASIS_SCOPE', scope)
217
- setEnv('EXODUS_STASIS_BUNDLE', bundle)
218
- setEnv('EXODUS_STASIS_BUNDLE_FILE', bundleFile)
219
- setEnv('EXODUS_STASIS_RESOURCES_BUNDLE_FILE', resourcesBundleFile)
220
- setEnv('EXODUS_STASIS_DEBUG', debug)
221
- setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
101
+ setRunEnv('stasis', run, { ...(packageJSON && { packageJSON: true }), ...(values.mock && { mock: true }) })
222
102
  setEnv('EXODUS_STASIS_PACKAGE_JSON', packageJSON)
223
- setEnv('EXODUS_STASIS_FS', captureFs)
224
- setEnv('EXODUS_STASIS_RESOURCES', resources)
225
- // Only set when given; an unconditional setEnv('') would conflict with an ambient value.
226
- if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
227
103
  // --mock: capture imports by running user code with side-effects denied (fail-closed).
228
104
  // --permission blocks fs writes/child procs/workers/addons/inspector at the kernel level;
229
105
  // src/mock.js neutralizes network + timers in JS (no --allow-* for those). Reads stay open
@@ -240,7 +116,7 @@ if (command === '-v' || command === '--version') {
240
116
  while (!existsSync(p) && dirname(p) !== p) p = dirname(p)
241
117
  // Refuse write access to the filesystem root -- it would disable the --permission layer everywhere.
242
118
  if (p === dirname(p)) {
243
- usage(`Error: no existing parent directory for ${flag}=${file}; create one first or choose a path under an existing directory`)
119
+ fail(`Error: no existing parent directory for ${flag}=${file}; create one first or choose a path under an existing directory`)
244
120
  }
245
121
  if (!writeAllow.includes(p)) writeAllow.push(p)
246
122
  }
@@ -250,228 +126,44 @@ if (command === '-v' || command === '--version') {
250
126
  // import map matches a non-mock run; native addons still can't load (--allow-addons off).
251
127
  nodeArgs.push('--conditions=node-addons')
252
128
  }
253
- // --mock uses stasis's loader-mock entry (composes the mock before installing the hooks).
254
- const loaderEntry = values.mock ? '../src/loader-mock.js' : '@exodus/stasis-core/loader'
255
- nodeArgs.push('--import', import.meta.resolve(loaderEntry))
256
- // Passthrough preloads ride after the loader (and after --mock's denials), so they evaluate
257
- // under its hooks; their module graphs pass through uncaptured unless the app graph reaches
258
- // them -- then they're promoted into the capture (see core hooks.js).
259
- for (const specifier of imports) nodeArgs.push('--import', specifier)
260
- const child = spawn(process.execPath, [...nodeArgs, ...argv], { stdio: 'inherit' })
261
- const [code, signal] = await once(child, 'close')
262
- // code is null when the child died from a signal; report 128+signo (shell convention) instead of the implicit 0
263
- process.exitCode = code ?? 128 + (osConstants.signals[signal] ?? 0)
129
+ // Before the loader, whose State reads the install through it.
130
+ nodeArgs.push('--import', import.meta.resolve('../src/run-installed.js'))
131
+ // --mock uses stasis's loader-mock entry (composes the mock before installing the hooks), whose
132
+ // denials the --import preloads then run under.
133
+ const loader = import.meta.resolve(values.mock ? '../src/loader-mock.js' : '@exodus/stasis-core/loader')
134
+ await runProgram(argv, { nodeArgs, loader, imports: run.imports })
264
135
  } else if (command === 'bundle') {
265
- const options = {
266
- mapping: { type: 'string' },
267
- manifests: { type: 'boolean' },
268
- output: { type: 'string', short: 'o' },
269
- scope: { type: 'string' },
270
- lockfile: { type: 'string' },
271
- conditions: { type: 'string' },
272
- mainFields: { type: 'string' },
273
- metro: { type: 'boolean' },
274
- 'metro-resolver': { type: 'boolean' },
275
- platforms: { type: 'string', multiple: true },
276
- jsx: { type: 'boolean' },
277
- flow: { type: 'boolean' },
278
- typescript: { type: 'boolean' },
279
- tsconfig: { type: 'string' },
280
- resources: { type: 'string' },
281
- 'package-json': { type: 'boolean' },
282
- cargo: { type: 'boolean' },
283
- 'cargo-features': { type: 'string', multiple: true },
284
- 'cargo-no-default-features': { type: 'boolean' },
285
- 'cargo-all-features': { type: 'boolean' },
286
- 'cargo-target': { type: 'string' },
287
- 'cargo-manifests': { type: 'boolean' },
288
- 'brotli-quality': { type: 'string' },
289
- add: { type: 'boolean' },
290
- }
291
- const values = parseLeadingOptions(argv, options, {
292
- valueFlags: ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--resources', '--tsconfig', '--cargo-features', '--cargo-target', '--brotli-quality', '-o'],
293
- onError: usage,
294
- })
295
- if (argv.length === 0) usage('Nothing to bundle: no entry file given')
296
- // A directory entry stands for the .sol files under it (Solidity only); an extensionless path
297
- // that doesn't exist is a missing one (skipped with a warning).
298
- const { directoryEntryError, isSolidityEntry } = await import('../src/cmd/bundle.js')
299
- const dirError = directoryEntryError(argv)
300
- if (dirError !== null) usage(`Error: ${dirError}`)
301
- const allSol = argv.every((f) => isSolidityEntry(f))
302
- const allPhp = argv.every((f) => f.endsWith('.php'))
303
- const allJs = argv.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f))
304
- const allBash = argv.every((f) => /\.(?:sh|bash)$/u.test(f))
305
- const allRust = argv.every((f) => f.endsWith('.rs'))
306
- if (!allSol && !allPhp && !allJs && !allBash && !allRust) {
307
- usage('Error: bundle entries must all be .sol, all be .php, all be .js/.cjs/.mjs/.ts/.cts/.mts/.jsx/.tsx, all be .sh/.bash, or all be .rs')
308
- }
309
- if (values.mapping && !allSol) usage('Error: --mapping is only valid for .sol bundles')
310
- // --manifests: carry the Solidity build's description files (foundry.toml, remappings.txt, ...).
311
- const manifests = Boolean(values.manifests)
312
- if (manifests && !allSol) usage('Error: --manifests is only valid for .sol bundles')
313
- // --cargo: take the Rust feature/dependency resolution from `cargo metadata` (runs cargo; opt-in).
314
- const cargo = Boolean(values.cargo)
315
- if (cargo && !allRust) usage('Error: --cargo is only valid for Rust bundles')
316
- // --cargo-features / --cargo-no-default-features / --cargo-all-features: cargo's own feature flags
317
- // for the entries' packages (`pkg/feat` targets one, or a dependency). --cargo-features is
318
- // repeatable and/or comma-separated; parseFeatureList is the one splitter (the resolver reuses it).
319
- const { parseFeatureList } = await import('../src/loaders/cargo.js')
320
- const cargoFeatures = parseFeatureList(values['cargo-features'] ?? [])
321
- if (values['cargo-features'] !== undefined && cargoFeatures.length === 0) {
322
- usage('Error: --cargo-features must list at least one feature (e.g. --cargo-features=serde,app/tls)')
323
- }
324
- const cargoNoDefaultFeatures = Boolean(values['cargo-no-default-features'])
325
- const cargoAllFeatures = Boolean(values['cargo-all-features'])
326
- // --cargo-target=<triple|host>: the build's target, whose cfgs (from `rustc --print cfg`) decide
327
- // `#[cfg(unix)]`-style code. A triple is letters, digits, `-`, `_` and `.` (`x86_64-unknown-linux-gnu`).
328
- const cargoTarget = values['cargo-target'] ?? null
329
- if (cargoTarget !== null && !/^[\w.-]+$/u.test(cargoTarget)) {
330
- usage('Error: --cargo-target must be a target triple or "host" (e.g. --cargo-target=aarch64-apple-darwin)')
331
- }
332
- // --cargo-manifests: carry each bundled package's Cargo.toml and build script, the workspace
333
- // Cargo.toml, Cargo.lock and .cargo/config.toml too (the Rust counterpart of --package-json).
334
- const cargoManifests = Boolean(values['cargo-manifests'])
335
- if (!allRust) {
336
- const given = { 'cargo-features': cargoFeatures.length > 0, 'cargo-no-default-features': cargoNoDefaultFeatures, 'cargo-all-features': cargoAllFeatures, 'cargo-target': cargoTarget !== null, 'cargo-manifests': cargoManifests }
337
- for (const [flag, on] of Object.entries(given)) if (on) usage(`Error: --${flag} is only valid for Rust bundles`)
338
- }
339
- if (values.scope && !allJs) usage('Error: --scope is only valid for JS bundles')
340
- if (values.scope && !['node_modules', 'full'].includes(values.scope)) {
341
- usage('Error: --scope must be node_modules or full')
342
- }
343
- if (values.lockfile && !allJs) usage('Error: --lockfile is only valid for JS bundles')
344
- // --mainFields/--metro always emit a full-scope bundle, so they'd silently ignore --scope.
345
- if (values.scope !== undefined && (values.mainFields !== undefined || values.metro)) {
346
- usage('Error: --scope is not supported with --mainFields or --metro')
347
- }
348
- // --conditions: extra exports/imports resolution conditions merged onto Node's defaults;
349
- // they don't honour legacy `mainFields` or platform suffixes (see --mainFields).
350
- if (values.conditions !== undefined && !allJs) usage('Error: --conditions is only valid for JS bundles')
351
- const conditions = values.conditions === undefined
352
- ? []
353
- : values.conditions.split(',').map((s) => s.trim()).filter(Boolean)
354
- if (values.conditions !== undefined && conditions.length === 0) {
355
- usage('Error: --conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
356
- }
357
- // --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
358
- if (values.flow && !allJs) usage('Error: --flow is only valid for JS bundles')
359
- const flow = Boolean(values.flow)
360
- // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
361
- // extensionless) lands on its on-disk TS source (./x.ts, .mts, .cts); an existing .js always wins.
362
- if (values.typescript && !allJs) usage('Error: --typescript is only valid for JS bundles')
363
- const typescript = Boolean(values.typescript)
364
- // --tsconfig: the config whose compilerOptions.paths aliases --typescript honours (default: the
365
- // tsconfig.json beside each importing file's package.json). Meaningless without --typescript.
366
- if (values.tsconfig !== undefined && !typescript) usage('Error: --tsconfig is only valid with --typescript')
367
- // --mainFields: legacy package entry fields (e.g. react-native,browser,main) for the non-exports resolver.
368
- if (values.mainFields !== undefined && !allJs) usage('Error: --mainFields is only valid for JS bundles')
369
- const mainFields = values.mainFields === undefined
370
- ? undefined
371
- : values.mainFields.split(',').map((s) => s.trim()).filter(Boolean)
372
- if (values.mainFields !== undefined && mainFields.length === 0) {
373
- usage('Error: --mainFields must list at least one field (e.g. --mainFields=react-native,browser,main)')
374
- }
375
- // --metro: resolve like Metro/RN (its own conditions + mainFields, platform suffixes per
376
- // --platforms target). --platforms is repeatable and/or comma-separated; the values union.
377
- const metro = Boolean(values.metro)
378
- // --metro-resolver: resolve through the project's own metro-resolver instead of the built-in
379
- // approximation. Only meaningful alongside --metro (enforced below and in classifyEntries).
380
- const metroResolver = Boolean(values['metro-resolver'])
381
- const platforms = [...new Set((values.platforms ?? []).flatMap((p) => p.split(',')).map((s) => s.trim()).filter(Boolean))]
382
- // A platform name becomes an edge key: reject '/' (parsers reject it) and '*' (reserved placeholder).
383
- for (const p of platforms) {
384
- if (p === '*' || p.includes('/')) usage(`Error: invalid --platforms value '${p}' (a platform name can't contain '/' or be '*')`)
385
- }
386
- if ((metro || platforms.length > 0) && !allJs) usage('Error: --metro is only valid for JS bundles')
387
- // --jsx: parse React Native's JSX-in-.js source in the static scanner (off by default; oxc,
388
- // like tsc, auto-enables JSX for .jsx/.tsx only). Orthogonal to the resolver, so it pairs with
389
- // plain/--mainFields/--metro alike -- JS-only, since no other entry language is scanned.
390
- const jsx = Boolean(values.jsx)
391
- if (jsx && !allJs) usage('Error: --jsx is only valid for JS bundles')
392
- // --package-json: fold each bundled module's package.json into the bundle. JS-only (only JS
393
- // modules carry an npm package.json; the sol/php/bash/rust bucketizers have no such manifest).
394
- const packageJSON = Boolean(values['package-json'])
395
- if (packageJSON && !allJs) usage('Error: --package-json is only valid for JS bundles')
396
- // --resources: comma-separated extension/filename allowlist for assets reached through the graph
397
- // (e.g. --resources=png,svg). They're carried as resources instead of failing "can't carry" --
398
- // for graphs that aren't fully loadable in JS (Metro consumes such assets). JS-only.
399
- if (values.resources !== undefined && !allJs) usage('Error: --resources is only valid for JS bundles')
400
- const resources = values.resources === undefined
401
- ? []
402
- : values.resources.split(',').map((s) => s.trim()).filter(Boolean)
403
- if (values.resources !== undefined && resources.length === 0) {
404
- usage('Error: --resources must list at least one extension or filename (e.g. --resources=png,svg)')
405
- }
136
+ const { BUNDLE_FLAGS, bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
137
+ const values = parseLeadingOptions(argv, BUNDLE_FLAGS, { valueFlags: valueFlagsOf(BUNDLE_FLAGS), onError: fail })
138
+ const cwd = process.cwd()
139
+ let plan
406
140
  try {
407
- parseResourcesOption('--resources', resources) // validate early for a clean usage error (code exts / bad chars rejected)
141
+ // stasis.config.json's `bundle`, where it is an object: its entries' options, and with no entry
142
+ // given, the entries.
143
+ const config = readConfigEntries(cwd)
144
+ const entries = argv.length > 0 ? argv : [...(config?.values() ?? [])].map(({ entry }) => entry)
145
+ if (entries.length === 0) fail('Nothing to bundle: no entry file given')
146
+ plan = bundlePlan({ cwd, entries, values, config })
408
147
  } catch (cause) {
409
- usage(`Error: ${cause.message}`)
410
- }
411
- if (metro) {
412
- if (conditions.length > 0) usage("Error: --conditions can't be combined with --metro (it sets its own conditions)")
413
- if (mainFields !== undefined) usage("Error: --mainFields can't be combined with --metro (it sets its own mainFields)")
414
- if (platforms.length === 0) usage('Error: --metro requires --platforms (e.g. --platforms=ios,android)')
415
- } else if (platforms.length > 0) {
416
- usage('Error: --platforms is only valid with --metro')
417
- }
418
- if (metroResolver && !metro) usage('Error: --metro-resolver is only valid with --metro')
419
- // metro-resolver can't substitute .js -> .ts, so --typescript would silently not apply -- reject it.
420
- if (typescript && metroResolver) usage("Error: --typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)")
421
- // --brotli-quality: valid for every entry language (no allJs gate).
422
- let brotliQuality
423
- if (values['brotli-quality'] !== undefined) {
424
- try {
425
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
426
- } catch (cause) {
427
- usage(`Error: ${cause.message}`)
428
- }
148
+ fail(`Error: ${cause.message}`)
429
149
  }
430
- // --add merges into the existing bundle at --output, so it can't target write-only stdout.
431
- const add = Boolean(values.add)
432
- if (add && values.output === '-') usage('Error: --add cannot be combined with --output=-')
433
150
  const { bundleCommand } = await import('../src/cmd/bundle.js')
434
- await bundleCommand({
435
- cwd: process.cwd(),
436
- entries: argv,
437
- mappingFile: values.mapping,
438
- manifests,
439
- output: values.output,
440
- scope: values.scope,
441
- lockfile: values.lockfile,
442
- conditions,
443
- mainFields,
444
- metro,
445
- metroResolver,
446
- platforms,
447
- jsx,
448
- flow,
449
- typescript,
450
- tsconfig: values.tsconfig,
451
- resources,
452
- packageJSON,
453
- cargo,
454
- cargoFeatures,
455
- cargoNoDefaultFeatures,
456
- cargoAllFeatures,
457
- cargoTarget,
458
- cargoManifests,
459
- brotliQuality,
460
- add,
461
- })
151
+ await bundleCommand({ cwd, ...plan })
462
152
  } else if (command === 'github-bundle') {
463
- const values = parseLeadingOptions(argv, {
153
+ const options = {
464
154
  github: { type: 'string' },
465
155
  sha: { type: 'string' },
466
156
  tag: { type: 'string' },
467
157
  directory: { type: 'string' },
468
158
  'package-manager': { type: 'string' },
469
159
  'package-manager-version': { type: 'string' },
160
+ 'no-lazy': { type: 'boolean' },
470
161
  mapping: { type: 'string' },
471
162
  manifests: { type: 'boolean' },
472
163
  output: { type: 'string', short: 'o' },
473
164
  scope: { type: 'string' },
474
165
  lockfile: { type: 'string' },
166
+ 'lockfile-only': { type: 'boolean' },
475
167
  conditions: { type: 'string' },
476
168
  mainFields: { type: 'string' },
477
169
  metro: { type: 'boolean' },
@@ -481,23 +173,48 @@ if (command === '-v' || command === '--version') {
481
173
  typescript: { type: 'boolean' },
482
174
  tsconfig: { type: 'string' },
483
175
  resources: { type: 'string' },
176
+ define: { type: 'string', multiple: true },
484
177
  'package-json': { type: 'boolean' },
485
178
  'brotli-quality': { type: 'string' },
486
179
  generate: { type: 'string', multiple: true },
487
- }, {
488
- valueFlags: ['--github', '--sha', '--tag', '--directory', '--package-manager', '--package-manager-version', '--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--tsconfig', '--resources', '--brotli-quality', '--generate', '-o'],
489
- onError: usage,
490
- })
491
- if (values.github === undefined) usage('Error: github-bundle requires --github=owner/name, the repo to bundle')
492
- if (values.sha !== undefined && values.tag !== undefined) usage('Error: github-bundle takes --sha or --tag, not both')
180
+ 'no-generate': { type: 'boolean' },
181
+ }
182
+ const parse = (args) => parseLeadingOptions(args, options, { valueFlags: valueFlagsOf(options), onError: fail })
183
+ // The repo as `owner/name[/path]`, for --github=owner/name [--directory=path]: the first argument
184
+ // that is no option, where no --github comes before it, with options on either side of it. The
185
+ // path is a directory, or a file: an entry of the nearest project above it (buildGitHubBundle's).
186
+ const rest = [...argv]
187
+ const bare = parse(rest).github === undefined && rest.length > 0 ? argv.splice(argv.length - rest.length, 1)[0] : undefined
188
+ const values = parse(argv)
189
+ let { github } = values
190
+ let path
191
+ if (bare !== undefined) {
192
+ if (github !== undefined || values.directory !== undefined) fail('Error: github-bundle takes owner/name[/path] or --github=owner/name [--directory=path], not both')
193
+ const [owner, name, ...segments] = bare.split('/')
194
+ if (name === undefined) fail(`Error: github-bundle: '${bare}' is not owner/name[/path], the repo to bundle`)
195
+ github = `${owner}/${name}`
196
+ path = segments.join('/') || undefined
197
+ }
198
+ if (github === undefined) fail('Error: github-bundle requires the repo to bundle: owner/name[/path], or --github=owner/name')
199
+ if (values.sha !== undefined && values.tag !== undefined) fail('Error: github-bundle takes --sha or --tag, not both')
200
+ if (values.generate !== undefined && values['no-generate']) fail('Error: github-bundle takes --generate or --no-generate, not both')
201
+ const lockfileOnly = Boolean(values['lockfile-only'])
202
+ if (lockfileOnly) {
203
+ // Before anything is fetched.
204
+ const { lockfileOnlyError } = await import('../src/cmd/output.js')
205
+ const refused = lockfileOnlyError({ lockfile: values.lockfile, output: values.output, brotliQuality: values['brotli-quality'], named: true })
206
+ if (refused !== null) fail(`Error: github-bundle: ${refused}`)
207
+ }
493
208
  // Whether each option applies to the entries is buildGitHubBundle's to say.
494
209
  const list = (value) => [value ?? []].flat().flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean)
495
- let brotliQuality
496
- if (values['brotli-quality'] !== undefined) {
210
+ const brotliQuality = brotliQualityOption(values['brotli-quality'], fail)
211
+ let define
212
+ if (values.define !== undefined) {
213
+ const { parseDefineFlags } = await import('../src/define.js')
497
214
  try {
498
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
215
+ define = parseDefineFlags(null, values.define)
499
216
  } catch (cause) {
500
- usage(`Error: ${cause.message}`)
217
+ fail(`Error: ${cause.message}`)
501
218
  }
502
219
  }
503
220
  // Tarballs, zips and GitHub trees are cached where `stasis audit` caches.
@@ -505,17 +222,21 @@ if (command === '-v' || command === '--version') {
505
222
  setCacheDir(userCacheDir())
506
223
  const { githubBundleCommand } = await import('../src/cmd/github-bundle.js')
507
224
  await githubBundleCommand({
508
- github: values.github,
225
+ github,
509
226
  sha: values.sha,
510
227
  tag: values.tag,
511
228
  directory: values.directory,
229
+ path,
512
230
  packageManager: values['package-manager'],
513
231
  packageManagerVersion: values['package-manager-version'],
232
+ // Lazy where the tree can be, unless --no-lazy or stasis.config.json's lazyDependencies says not.
233
+ lazy: values['no-lazy'] ? false : undefined,
514
234
  entries: argv.length === 0 ? undefined : argv,
515
235
  mappingFile: values.mapping,
516
236
  manifests: Boolean(values.manifests),
517
237
  output: values.output,
518
238
  lockfile: values.lockfile,
239
+ lockfileOnly,
519
240
  scope: values.scope,
520
241
  conditions: list(values.conditions),
521
242
  mainFields: values.mainFields === undefined ? undefined : list(values.mainFields),
@@ -525,65 +246,66 @@ if (command === '-v' || command === '--version') {
525
246
  flow: Boolean(values.flow),
526
247
  typescript: Boolean(values.typescript),
527
248
  tsconfig: values.tsconfig,
528
- resources: list(values.resources),
249
+ resources: values.resources === undefined ? undefined : list(values.resources),
250
+ define,
529
251
  packageJSON: Boolean(values['package-json']),
530
- generate: list(values.generate),
252
+ // Detected without either, unless stasis.config.json's generatePrisma says not.
253
+ generate: values['no-generate'] ? [] : values.generate === undefined ? undefined : list(values.generate),
531
254
  brotliQuality,
532
255
  })
533
256
  } else if (command === 'add') {
534
- // add packs the listed files (no resolver), taking split targets + resource allowlist from
535
- // stasis.config.json; it takes no flags.
536
- if (argv.length === 0) usage('Nothing to add: no file given')
537
- if (argv.some((a) => a.startsWith('-'))) usage('Error: add takes no options; its targets and resource allowlist come from stasis.config.json')
538
- const { addCommand } = await import('@exodus/stasis-core/add')
539
- // Let addCommand's runtime errors propagate as-is; wrapping in usage() would bury the cause.
540
- addCommand({ cwd: process.cwd(), entries: argv, logLabel: 'stasis' })
257
+ await import('../src/run-installed.js')
258
+ await addCli(argv, { label: 'stasis', fail })
541
259
  } else if (command === 'build') {
542
260
  const options = {
543
261
  output: { type: 'string', short: 'o' },
544
262
  format: { type: 'string' },
545
263
  platform: { type: 'string' },
546
264
  babel: { type: 'boolean' },
265
+ flow: { type: 'boolean' },
547
266
  minify: { type: 'boolean' },
548
267
  sourcemap: { type: 'boolean' },
549
268
  // Repeatable esbuild passthroughs (--define=K=V, --external=PATTERN, --loader=.ext:name).
550
269
  define: { type: 'string', multiple: true },
551
270
  external: { type: 'string', multiple: true },
552
271
  loader: { type: 'string', multiple: true },
272
+ // --metro=PLATFORM builds as Metro builds for PLATFORM (its per-platform edges, its asset modules);
273
+ // --assets-dest=DIR copies the assets' files out as `react-native bundle --assets-dest` does.
274
+ metro: { type: 'string' },
275
+ 'assets-dest': { type: 'string' },
553
276
  }
554
- const values = parseLeadingOptions(argv, options, {
555
- valueFlags: ['--output', '-o', '--format', '--platform', '--define', '--external', '--loader'],
556
- onError: usage,
557
- })
558
- if (argv.length === 0) usage('Nothing to build: no bundle or lockfile given')
559
- if (argv.length > 2) usage('Error: build takes a bundle or lockfile and an optional entry point')
277
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
278
+ if (argv.length === 0) fail('Nothing to build: no bundle or lockfile given')
279
+ if (values.metro !== undefined && !/^[^/,]+$/u.test(values.metro)) fail(`Error: --metro takes one platform to build for, e.g. --metro=ios (got '${values.metro}')`)
280
+ if (values.flow && values.babel) fail('Error: --flow and --babel don\'t combine: the project\'s Babel config compiles Flow itself')
281
+ if (argv.length > 2) fail('Error: build takes a bundle or lockfile and an optional entry point')
560
282
  // esbuild output knobs; the import graph itself is fixed by the artifact, not these.
561
283
  if (values.format !== undefined && !['esm', 'cjs', 'iife'].includes(values.format)) {
562
- usage('Error: --format must be esm, cjs, or iife')
284
+ fail('Error: --format must be esm, cjs, or iife')
563
285
  }
564
286
  if (values.platform !== undefined && !['node', 'browser', 'neutral', 'hermes'].includes(values.platform)) {
565
- usage('Error: --platform must be node, browser, neutral, or hermes')
287
+ fail('Error: --platform must be node, browser, neutral, or hermes')
566
288
  }
567
289
  // Hermes has no import/export; --format defaults to iife under --platform=hermes (see buildCommand).
568
290
  if (values.platform === 'hermes' && values.format === 'esm') {
569
- usage('Error: --platform=hermes cannot emit ESM; use --format=iife (the hermes default) or cjs')
291
+ fail('Error: --platform=hermes cannot emit ESM; use --format=iife (the hermes default) or cjs')
570
292
  }
571
- if (!values.output) usage('Error: --output is required (a .js/.cjs/.mjs file, or a directory)')
293
+ if (!values.output) fail('Error: --output is required (a .js/.cjs/.mjs file, or a directory)')
572
294
  // build can't stream to stdout; without this, --output=- would create a dir literally named `-`.
573
- if (values.output === '-') usage('Error: stasis build cannot stream to stdout; --output must be a .js/.cjs/.mjs file or a directory')
295
+ if (values.output === '-') fail('Error: stasis build cannot stream to stdout; --output must be a .js/.cjs/.mjs file or a directory')
574
296
  // --define=KEY=VALUE -> esbuild define map; VALUE is forwarded verbatim and must be valid JS
575
297
  // (a JSON literal or an identifier), e.g. --define=DEBUG=false.
576
298
  const define = {}
577
299
  for (const entry of values.define ?? []) {
578
300
  const eq = entry.indexOf('=')
579
- if (eq <= 0) usage(`Error: --define must be KEY=VALUE (got '${entry}')`)
301
+ if (eq <= 0) fail(`Error: --define must be KEY=VALUE (got '${entry}')`)
580
302
  define[entry.slice(0, eq)] = entry.slice(eq + 1)
581
303
  }
582
304
  // --loader=.ext:NAME -> esbuild loader override for that extension (e.g. --loader=.js:jsx).
583
305
  const loader = {}
584
306
  for (const entry of values.loader ?? []) {
585
307
  const colon = entry.indexOf(':')
586
- if (colon <= 0 || !entry.startsWith('.')) usage(`Error: --loader must be .EXT:LOADER (got '${entry}')`)
308
+ if (colon <= 0 || !entry.startsWith('.')) fail(`Error: --loader must be .EXT:LOADER (got '${entry}')`)
587
309
  loader[entry.slice(0, colon)] = entry.slice(colon + 1)
588
310
  }
589
311
  const { buildCommand } = await import('../src/cmd/build.js')
@@ -595,68 +317,161 @@ if (command === '-v' || command === '--version') {
595
317
  format: values.format,
596
318
  platform: values.platform,
597
319
  babel: Boolean(values.babel),
320
+ flow: Boolean(values.flow),
598
321
  minify: values.minify,
599
322
  sourcemap: values.sourcemap,
600
323
  define,
601
324
  external: values.external ?? [],
602
325
  loader,
326
+ metro: values.metro,
327
+ assetsDest: values['assets-dest'],
603
328
  })
604
329
  } else if (command === 'extract') {
605
- const options = {
606
- output: { type: 'string', short: 'o' },
607
- }
608
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--output', '-o'], onError: usage })
609
- if (argv.length === 0) usage('Nothing to extract: no bundle file given')
610
- if (argv.length > 1) usage('Error: extract takes exactly one bundle file')
611
- const { extractCommand } = await import('@exodus/stasis-core/extract')
612
- extractCommand({ cwd: process.cwd(), bundleFile: argv[0], output: values.output, logLabel: 'stasis' })
330
+ await extractCli(argv, { label: 'stasis', fail })
613
331
  } else if (command === 'diff') {
614
332
  const options = {
615
333
  stat: { type: 'boolean' },
616
334
  imports: { type: 'boolean' },
617
335
  }
618
- const values = parseLeadingOptions(argv, options, { onError: usage })
336
+ const values = parseLeadingOptions(argv, options, { onError: fail })
619
337
  // --stat is required for now (it reports what changed, not the content); bare `stasis diff`
620
338
  // is reserved for a future content-level diff.
621
- if (!values.stat) usage('Error: stasis diff currently requires --stat')
622
- if (argv.length !== 2) usage('Error: stasis diff takes exactly two files (lockfile or bundle)')
339
+ if (!values.stat) fail('Error: stasis diff currently requires --stat')
340
+ if (argv.length !== 2) fail('Error: stasis diff takes exactly two files (lockfile or bundle)')
623
341
  // --imports also diffs the resolution graphs (added/removed/redirected edges); off by default (verbose).
624
342
  const { diffCommand } = await import('../src/cmd/diff.js')
625
343
  const { differences } = diffCommand({ cwd: process.cwd(), left: argv[0], right: argv[1], stat: true, imports: values.imports })
626
344
  // Exit non-zero when the artifacts differ, so it composes in CI.
627
345
  process.exitCode = differences ? 1 : 0
628
346
  } else if (command === 'prune') {
629
- if (argv.length > 1) usage('Error: prune takes at most one path argument')
630
- const root = argv[0] ? resolve(argv[0]) : process.cwd()
631
- const { prune } = await import('@exodus/stasis-core/prune')
632
- const { removed, validated } = prune({ root })
633
- console.warn(`[stasis] prune: validated ${validated.length} file(s), removed ${removed.length} file(s)`)
347
+ await pruneCli(argv, { label: 'stasis', fail })
634
348
  } else if (command === 'audit') {
635
- const values = parseLeadingOptions(argv, { why: { type: 'boolean' }, 'why-deep': { type: 'boolean' }, 'why-full': { type: 'boolean' }, reason: { type: 'string' }, 'repo-advisories': { type: 'boolean' } }, { valueFlags: ['--reason'], onError: usage })
636
- if (argv.length === 0) usage('Nothing to audit: no path to file given')
637
- const repoAdvisories = Boolean(values['repo-advisories'])
638
- if (repoAdvisories && !process.env.GITHUB_TOKEN) usage('Error: --repo-advisories requires a GitHub token in GITHUB_TOKEN')
349
+ const options = { why: { type: 'boolean' }, 'why-deep': { type: 'boolean' }, 'why-full': { type: 'boolean' }, reason: { type: 'string' }, 'repo-advisories': { type: 'boolean' }, 'no-repo-advisories': { type: 'boolean' } }
350
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
351
+ if (values['repo-advisories'] && values['no-repo-advisories']) fail('Error: --repo-advisories and --no-repo-advisories: give one')
352
+ // With no file, the bundle a bare `stasis bundle` would write of the entries stasis.config.json's
353
+ // `entries` names, planned (and refused) as it plans them, and built after the checks below.
354
+ let plan
355
+ if (argv.length === 0) {
356
+ const cwd = process.cwd()
357
+ const { bundlePlan, readConfigEntries } = await import('../src/cmd/bundle-options.js')
358
+ try {
359
+ const config = readConfigEntries(cwd)
360
+ const entries = [...(config?.values() ?? [])].map(({ entry }) => entry)
361
+ if (entries.length === 0) fail('Nothing to audit: no path to file given, nor entries in stasis.config.json to bundle')
362
+ plan = { cwd, ...bundlePlan({ cwd, entries, values: {}, config }) }
363
+ } catch (cause) {
364
+ fail(`Error: ${cause.message}`)
365
+ }
366
+ }
367
+ // Each package's GitHub repository is asked for its advisories, a request a package, unless
368
+ // --no-repo-advisories: with githubToken's token, as GitHub's anonymous rate wouldn't last a project.
369
+ // Without one, they are not asked, which a line above the table says; --repo-advisories fails instead.
370
+ const token = (await import('../src/cmd/tokens.js')).githubToken()
371
+ if (values['repo-advisories'] && !token) fail('Error: --repo-advisories requires a GitHub token in GITHUB_TOKEN')
372
+ const repoAdvisories = !values['no-repo-advisories'] && Boolean(token)
373
+ const tokenless = !values['no-repo-advisories'] && !token
374
+ // Built as `stasis bundle` builds it, but neither written nor compressed, nor its warnings said
375
+ // unless it fails (its error is, as ever).
376
+ let files = argv.map((f) => resolve(f))
377
+ if (plan !== undefined) {
378
+ const { buildCommandBundle } = await import('../src/cmd/bundle.js')
379
+ files = [await warningsOnFailure(() => buildCommandBundle(plan))]
380
+ }
639
381
  // A Soldeer package's and a GitHub repo's advisories are their repository's, asked of GitHub with
640
- // GITHUB_TOKEN where it is set; the client asks nothing for any other package by itself.
641
- const github = (await import('@preventive/upstream/github.js')).createClient({ token: process.env.GITHUB_TOKEN || null })
382
+ // githubToken's token where there is one; the client asks nothing for any other package by itself.
383
+ const github = (await import('@preventive/upstream/github.js')).createClient({ token })
642
384
  // Upstream caches what it looks up (a package's GitHub repo, a month each) only where told to, and
643
385
  // answers from it without asking: a per-user directory, never one shared with less trusted jobs.
644
386
  const { setCacheDir } = await import('@preventive/upstream/npm.js')
645
387
  setCacheDir(userCacheDir())
646
- const { audit, printAuditReport } = await import('../src/audit.js')
647
- const files = argv.map((f) => resolve(f))
648
- const report = await audit(files, { why: Boolean(values.why), whyDeep: Boolean(values['why-deep']), whyFull: Boolean(values['why-full']), reason: values.reason, repoAdvisories, github })
649
- printAuditReport(report)
650
- process.exitCode = report.rows.length === 0 ? 0 : 1
388
+ const { AuditError, audit, printAuditReport } = await import('../src/audit.js')
389
+ // With no file, the package manager's lockfile installing the project too, or each JS one its
390
+ // stasis.config.json names in its `lockfiles`: their packages the bundle doesn't hold checked for
391
+ // malware (npm's registry alone), their being found or refused told, not failed.
392
+ let lockfile = null
393
+ if (plan !== undefined) {
394
+ try {
395
+ lockfile = await (await import('../src/validate.js')).lockedNpmPackages(plan.cwd)
396
+ } catch (cause) {
397
+ console.error(`Lockfile not checked for malware: ${cause.message}`)
398
+ }
399
+ }
400
+ let report
401
+ try {
402
+ // --reason audits that consumer's packages alone; one no file records is refused before any is asked about.
403
+ // OSV is asked about npm packages too, never a private one (upstream checks each name is public).
404
+ report = await audit(files, { why: Boolean(values.why), whyDeep: Boolean(values['why-deep']), whyFull: Boolean(values['why-full']), reason: values.reason, repoAdvisories, github, osv: true, lockfile })
405
+ } catch (cause) {
406
+ if (cause instanceof AuditError) fail(`Error: ${cause.message}`)
407
+ throw cause
408
+ }
409
+ // Each advisory's source as an icon, where the terminal draws sixel images, sized to its cells.
410
+ const { capabilities, logos } = await import('../src/sixel.js')
411
+ const terminal = await capabilities()
412
+ const notes = tokenless ? ['Repository advisories require GITHUB_TOKEN; continuing without them'] : []
413
+ printAuditReport(report, { icons: terminal.sixel && logos(terminal.cell, terminal.background), notes })
414
+ // Malware npm's registry tells of in any dependency fails it too, whatever --reason.
415
+ process.exitCode = report.rows.length === 0 && report.npmMalware.length === 0 ? 0 : 1
416
+ } else if (command === 'validate') {
417
+ // Exits 0 where the bundle is valid, 1 where it is invalid, 2 where a file it was to check went
418
+ // unverified (unless --allow-unverified), and 3 where it refused the bundle, or failed.
419
+ const refuse = (message) => {
420
+ console.error(message)
421
+ process.exit(3)
422
+ }
423
+ const misused = (message) => refuse(`${message}\nRun 'stasis --help' for usage.`)
424
+ const values = parseLeadingOptions(argv, {
425
+ github: { type: 'string' },
426
+ sha: { type: 'string' },
427
+ directory: { type: 'string' },
428
+ 'only-deps': { type: 'boolean' },
429
+ lockfile: { type: 'string', multiple: true },
430
+ 'no-lockfile': { type: 'boolean' },
431
+ 'allow-unverified': { type: 'boolean' },
432
+ 'show-valid': { type: 'boolean' },
433
+ }, {
434
+ valueFlags: ['--github', '--sha', '--directory', '--lockfile'],
435
+ onError: misused,
436
+ })
437
+ if (argv.length !== 1) misused('Error: stasis validate takes one bundle')
438
+ if (values.lockfile !== undefined && values['no-lockfile']) misused('Error: --lockfile and --no-lockfile: give one')
439
+ // The repository is read with githubToken's token and the packages with withNpmToken's, as
440
+ // `stasis github-bundle` reads them; its trees and the packages fetched are cached where
441
+ // `stasis audit` caches, each held to its id or integrity as it is read.
442
+ const { createClient } = await import('@preventive/upstream/github.js')
443
+ const { setCacheDir } = await import('@preventive/upstream/npm.js')
444
+ setCacheDir(userCacheDir())
445
+ const { githubToken, withNpmToken } = await import('../src/cmd/tokens.js')
446
+ const { ValidateError, exitCodeOf, validate, printValidationReport } = await import('../src/validate.js')
447
+ let report
448
+ try {
449
+ // Its dependencies alone only with --only-deps, and held to no lockfile only with --no-lockfile: a
450
+ // bundle with no repository or commit to read its own code or its lockfile of is refused otherwise.
451
+ report = await withNpmToken(undefined, () => validate(resolve(argv[0]), {
452
+ client: createClient({ token: githubToken() }),
453
+ github: values.github,
454
+ sha: values.sha,
455
+ directory: values.directory,
456
+ own: !values['only-deps'],
457
+ lockfile: values['no-lockfile'] ? false : values.lockfile?.map((path) => resolve(path)) ?? true,
458
+ }))
459
+ } catch (cause) {
460
+ if (cause instanceof ValidateError) misused(`Error: ${cause.message}`)
461
+ refuse(`Error: ${cause.message}`)
462
+ }
463
+ // In colour where each stream takes colours: a terminal's, or CI's log.
464
+ printValidationReport(report, { showValid: values['show-valid'] })
465
+ process.exitCode = exitCodeOf(report, { allowUnverified: values['allow-unverified'] })
651
466
  } else if (command === 'sbom') {
652
467
  const options = {
653
468
  format: { type: 'string' },
654
469
  output: { type: 'string', short: 'o' },
655
470
  }
656
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--format', '--output', '-o'], onError: usage })
657
- if (!values.format) usage('Error: stasis sbom requires --format=(spdx|cyclonedx)')
658
- if (!['spdx', 'cyclonedx'].includes(values.format)) usage('Error: --format must be spdx or cyclonedx')
659
- if (argv.length === 0) usage('Nothing to export: no lockfile or bundle given')
471
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
472
+ if (!values.format) fail('Error: stasis sbom requires --format=(spdx|cyclonedx)')
473
+ if (!['spdx', 'cyclonedx'].includes(values.format)) fail('Error: --format must be spdx or cyclonedx')
474
+ if (argv.length === 0) fail('Nothing to export: no lockfile or bundle given')
660
475
  const { sbomCommand } = await import('../src/cmd/sbom.js')
661
476
  sbomCommand({
662
477
  cwd: process.cwd(),
@@ -664,6 +479,8 @@ if (command === '-v' || command === '--version') {
664
479
  format: values.format,
665
480
  output: values.output,
666
481
  })
667
- } else {
482
+ } else if (command === undefined) {
668
483
  usage()
484
+ } else {
485
+ fail(`Error: unknown command '${command}'`)
669
486
  }