@exodus/stasis 1.0.0-beta.9 → 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 (67) hide show
  1. package/README.md +6 -2
  2. package/bin/stasis.js +222 -334
  3. package/package.json +38 -14
  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 +1664 -1001
  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 +211 -492
  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 +152 -249
  44. package/src/resolve-node.js +29 -45
  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 +240 -282
  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 +50 -46
  57. package/src/vfs-bundle/github.js +114 -94
  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 +418 -277
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +24 -55
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
  67. package/src/installed-commits.js +0 -182
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]
@@ -20,22 +19,25 @@ assert(basename(jsname) === 'stasis' || pathsEqual(jsname, fileURLToPath(import.
20
19
 
21
20
  const HELP = `Usage:
22
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 ...
23
- stasis bundle [--scope=(node_modules|full)] [--conditions=cond1,cond2] [--mainFields=field1,field2] [--metro [--metro-resolver] --platforms=ios,android] [--jsx] [--flow] [--typescript [--tsconfig=path/to/tsconfig.json]] [--resources=ext,ext] [--package-json] [--lockfile=path/to/stasis.lock.json] [--brotli-quality=0..11] [--add] [--output=(path|-)] path/to/file.(js|ts|jsx|tsx) ...
24
- stasis bundle [--mapping=path/to/remappings(.txt|.toml)] [--manifests] [--add] [--output=(path|-)] path/to/(file.sol|dir) ...
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) ...
25
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 ...
26
25
  stasis bundle [--add] [--output=(path|-)] path/to/file.(php|sh|bash) ...
27
- 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) ...]
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) ...]
28
28
  stasis add path/to/(file|dir) ...
29
- 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]
30
- 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
31
31
  stasis diff --stat [--imports] path/to/(lockfile|bundle) path/to/(lockfile|bundle)
32
32
  stasis prune [path/to/project]
33
- stasis audit [--why|--why-deep] [--why-full] [--reason=consumer] [--repo-advisories] path/to/(lockfile|bundle) ...
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
34
36
  stasis sbom --format=(spdx|cyclonedx) [--output=(path|-)] path/to/(lockfile|bundle) ...
35
37
  stasis --version
36
38
 
37
39
  Each command's options: https://github.com/PreventiveMeasures/stasis/blob/main/doc/<command>.md
38
- (run, bundle, github-bundle, build, extract, diff, prune, audit, sbom; add is in bundle.md)`
40
+ (run, bundle, github-bundle, build, extract, diff, prune, audit, validate, sbom; add is in bundle.md)`
39
41
 
40
42
  // The help, on stderr. Exits 0 when asked for (--help), 1 when printed for want of a command.
41
43
  function usage(asked = false) {
@@ -49,10 +51,21 @@ function fail(message) {
49
51
  process.exit(1)
50
52
  }
51
53
 
52
- function setEnv(name, value) {
53
- const env = process.env[name]
54
- if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
55
- 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
+ }
56
69
  }
57
70
 
58
71
  // The per-user cache directory, as each platform names it (XDG ignores a relative path).
@@ -71,86 +84,22 @@ if (command === '-v' || command === '--version') {
71
84
  } else if (command === '-h' || command === '--help') {
72
85
  usage(true)
73
86
  } else if (command === 'run') {
74
- const options = {
75
- lock: { type: 'string', default: 'none' },
76
- bundle: { type: 'string', default: 'none' },
77
- 'bundle-file': { type: 'string' },
78
- 'resources-bundle-file': { type: 'string' },
79
- debug: { type: 'boolean' },
80
- dependencies: { type: 'boolean' },
81
- 'child-process': { type: 'boolean' },
82
- 'package-json': { type: 'boolean' },
83
- mock: { type: 'boolean' },
84
- import: { type: 'string', multiple: true },
85
- fs: { type: 'string' },
86
- resources: { type: 'string' },
87
- 'brotli-quality': { type: 'string' },
88
- }
89
- const values = parseLeadingOptions(argv, options, {
90
- valueFlags: ['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--import', '--resources', '--brotli-quality'],
91
- onError: fail,
92
- })
93
- if (argv.length === 0) fail('Nothing to run: no path to file given')
94
- if (!['none', 'ignore', 'add', 'replace', 'frozen'].includes(values.lock)) fail('Error: invalid --lock value')
95
- const lock = values.lock
96
- const scope = values.dependencies ? 'node_modules' : 'full'
97
- const bundle = values.bundle
98
- const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
99
- const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
100
- const debug = values.debug ? '1' : ''
101
- if (!['none', 'ignore', 'add', 'replace', 'load', 'frozen'].includes(bundle)) fail('Error: invalid --bundle value')
102
- if (bundleFile && bundle === 'none') fail('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
103
- // --resources-bundle-file needs an active bundle mode (unlike --bundle-file, inert under ignore).
104
- if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) fail('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
105
- if (bundle === 'load' && lock !== 'frozen' && lock !== 'none' && lock !== 'ignore') fail('Error: --bundle=load is incompatible with --lock=(add|replace)')
106
- if (lock === 'none' && bundle === 'none') fail('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
87
+ const run = parseRunOptions(argv, { options: { 'package-json': { type: 'boolean' }, mock: { type: 'boolean' } }, fail })
88
+ const { values, bundle, bundleFile, resourcesBundleFile } = run
107
89
  if (values.mock && bundle === 'load') fail('Error: --mock is for capturing imports while building a bundle; not compatible with --bundle=load')
108
- // --fs requires a bundle mode (add|replace|load); `sync` patches the sync fs readers,
109
- // `async` adds their callback + fs.promises counterparts on top.
110
- if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) fail("Error: --fs must be 'sync' or 'async'")
111
- if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) fail('Error: --fs requires --bundle=(add|replace|load)')
112
- const captureFs = values.fs ?? ''
113
- // --resources: comma-separated extension/filename allowlist for `--fs` captures.
114
- const resources = values.resources ?? ''
115
- let brotliQuality
116
- if (values['brotli-quality'] !== undefined) {
117
- try {
118
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
119
- } catch (cause) {
120
- fail(`Error: ${cause.message}`)
121
- }
122
- }
123
- // --import: extra preload module(s) passed through to the spawned node. Node resolves each
124
- // against the project cwd; they ride AFTER stasis's own loader import.
125
- const imports = values.import ?? []
126
- if (imports.some((s) => s === '')) fail('Error: --import requires a module specifier (e.g. --import=./instrument.mjs)')
127
90
  // Not a usage error: plain instrumentation/setup preloads still work under the mock; only ones
128
91
  // that need the denied surfaces (spawning helper processes, network) die, and they do so loudly.
129
- if (values.mock && imports.length > 0) {
92
+ if (values.mock && run.imports.length > 0) {
130
93
  console.warn("[stasis] Warning: --import preloads run under --mock's side-effect denials; a preload that spawns helper processes will fail there")
131
94
  }
132
- // --child-process: forward forked-child (e.g. Metro worker) capture to the root via per-pid shards.
133
- const childProcess = values['child-process'] ? '1' : ''
134
95
  // --package-json: auto-include every bundled module's package.json. Only meaningful while WRITING
135
96
  // a bundle (add|replace) -- there's nothing to fold the manifests into otherwise.
136
97
  if (values['package-json'] && bundle !== 'add' && bundle !== 'replace') {
137
98
  fail('Error: --package-json requires --bundle=(add|replace)')
138
99
  }
139
100
  const packageJSON = values['package-json'] ? '1' : ''
140
- 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 }) })
141
- if (debug) console.warn(`[stasis] Warning: stasis debug mode active`)
142
- setEnv('EXODUS_STASIS_LOCK', lock)
143
- setEnv('EXODUS_STASIS_SCOPE', scope)
144
- setEnv('EXODUS_STASIS_BUNDLE', bundle)
145
- setEnv('EXODUS_STASIS_BUNDLE_FILE', bundleFile)
146
- setEnv('EXODUS_STASIS_RESOURCES_BUNDLE_FILE', resourcesBundleFile)
147
- setEnv('EXODUS_STASIS_DEBUG', debug)
148
- setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
101
+ setRunEnv('stasis', run, { ...(packageJSON && { packageJSON: true }), ...(values.mock && { mock: true }) })
149
102
  setEnv('EXODUS_STASIS_PACKAGE_JSON', packageJSON)
150
- setEnv('EXODUS_STASIS_FS', captureFs)
151
- setEnv('EXODUS_STASIS_RESOURCES', resources)
152
- // Only set when given; an unconditional setEnv('') would conflict with an ambient value.
153
- if (brotliQuality !== undefined) setEnv('EXODUS_STASIS_BROTLI_QUALITY', String(brotliQuality))
154
103
  // --mock: capture imports by running user code with side-effects denied (fail-closed).
155
104
  // --permission blocks fs writes/child procs/workers/addons/inspector at the kernel level;
156
105
  // src/mock.js neutralizes network + timers in JS (no --allow-* for those). Reads stay open
@@ -177,228 +126,44 @@ if (command === '-v' || command === '--version') {
177
126
  // import map matches a non-mock run; native addons still can't load (--allow-addons off).
178
127
  nodeArgs.push('--conditions=node-addons')
179
128
  }
180
- // --mock uses stasis's loader-mock entry (composes the mock before installing the hooks).
181
- const loaderEntry = values.mock ? '../src/loader-mock.js' : '@exodus/stasis-core/loader'
182
- nodeArgs.push('--import', import.meta.resolve(loaderEntry))
183
- // Passthrough preloads ride after the loader (and after --mock's denials), so they evaluate
184
- // under its hooks; their module graphs pass through uncaptured unless the app graph reaches
185
- // them -- then they're promoted into the capture (see core hooks.js).
186
- for (const specifier of imports) nodeArgs.push('--import', specifier)
187
- const child = spawn(process.execPath, [...nodeArgs, ...argv], { stdio: 'inherit' })
188
- const [code, signal] = await once(child, 'close')
189
- // code is null when the child died from a signal; report 128+signo (shell convention) instead of the implicit 0
190
- 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 })
191
135
  } else if (command === 'bundle') {
192
- const options = {
193
- mapping: { type: 'string' },
194
- manifests: { type: 'boolean' },
195
- output: { type: 'string', short: 'o' },
196
- scope: { type: 'string' },
197
- lockfile: { type: 'string' },
198
- conditions: { type: 'string' },
199
- mainFields: { type: 'string' },
200
- metro: { type: 'boolean' },
201
- 'metro-resolver': { type: 'boolean' },
202
- platforms: { type: 'string', multiple: true },
203
- jsx: { type: 'boolean' },
204
- flow: { type: 'boolean' },
205
- typescript: { type: 'boolean' },
206
- tsconfig: { type: 'string' },
207
- resources: { type: 'string' },
208
- 'package-json': { type: 'boolean' },
209
- cargo: { type: 'boolean' },
210
- 'cargo-features': { type: 'string', multiple: true },
211
- 'cargo-no-default-features': { type: 'boolean' },
212
- 'cargo-all-features': { type: 'boolean' },
213
- 'cargo-target': { type: 'string' },
214
- 'cargo-manifests': { type: 'boolean' },
215
- 'brotli-quality': { type: 'string' },
216
- add: { type: 'boolean' },
217
- }
218
- const values = parseLeadingOptions(argv, options, {
219
- valueFlags: ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--resources', '--tsconfig', '--cargo-features', '--cargo-target', '--brotli-quality', '-o'],
220
- onError: fail,
221
- })
222
- if (argv.length === 0) fail('Nothing to bundle: no entry file given')
223
- // A directory entry stands for the .sol files under it (Solidity only); an extensionless path
224
- // that doesn't exist is a missing one (skipped with a warning).
225
- const { directoryEntryError, isSolidityEntry } = await import('../src/cmd/bundle.js')
226
- const dirError = directoryEntryError(argv)
227
- if (dirError !== null) fail(`Error: ${dirError}`)
228
- const allSol = argv.every((f) => isSolidityEntry(f))
229
- const allPhp = argv.every((f) => f.endsWith('.php'))
230
- const allJs = argv.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f))
231
- const allBash = argv.every((f) => /\.(?:sh|bash)$/u.test(f))
232
- const allRust = argv.every((f) => f.endsWith('.rs'))
233
- if (!allSol && !allPhp && !allJs && !allBash && !allRust) {
234
- fail('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')
235
- }
236
- if (values.mapping && !allSol) fail('Error: --mapping is only valid for .sol bundles')
237
- // --manifests: carry the Solidity build's description files (foundry.toml, remappings.txt, ...).
238
- const manifests = Boolean(values.manifests)
239
- if (manifests && !allSol) fail('Error: --manifests is only valid for .sol bundles')
240
- // --cargo: take the Rust feature/dependency resolution from `cargo metadata` (runs cargo; opt-in).
241
- const cargo = Boolean(values.cargo)
242
- if (cargo && !allRust) fail('Error: --cargo is only valid for Rust bundles')
243
- // --cargo-features / --cargo-no-default-features / --cargo-all-features: cargo's own feature flags
244
- // for the entries' packages (`pkg/feat` targets one, or a dependency). --cargo-features is
245
- // repeatable and/or comma-separated; parseFeatureList is the one splitter (the resolver reuses it).
246
- const { parseFeatureList } = await import('../src/loaders/cargo.js')
247
- const cargoFeatures = parseFeatureList(values['cargo-features'] ?? [])
248
- if (values['cargo-features'] !== undefined && cargoFeatures.length === 0) {
249
- fail('Error: --cargo-features must list at least one feature (e.g. --cargo-features=serde,app/tls)')
250
- }
251
- const cargoNoDefaultFeatures = Boolean(values['cargo-no-default-features'])
252
- const cargoAllFeatures = Boolean(values['cargo-all-features'])
253
- // --cargo-target=<triple|host>: the build's target, whose cfgs (from `rustc --print cfg`) decide
254
- // `#[cfg(unix)]`-style code. A triple is letters, digits, `-`, `_` and `.` (`x86_64-unknown-linux-gnu`).
255
- const cargoTarget = values['cargo-target'] ?? null
256
- if (cargoTarget !== null && !/^[\w.-]+$/u.test(cargoTarget)) {
257
- fail('Error: --cargo-target must be a target triple or "host" (e.g. --cargo-target=aarch64-apple-darwin)')
258
- }
259
- // --cargo-manifests: carry each bundled package's Cargo.toml and build script, the workspace
260
- // Cargo.toml, Cargo.lock and .cargo/config.toml too (the Rust counterpart of --package-json).
261
- const cargoManifests = Boolean(values['cargo-manifests'])
262
- if (!allRust) {
263
- const given = { 'cargo-features': cargoFeatures.length > 0, 'cargo-no-default-features': cargoNoDefaultFeatures, 'cargo-all-features': cargoAllFeatures, 'cargo-target': cargoTarget !== null, 'cargo-manifests': cargoManifests }
264
- for (const [flag, on] of Object.entries(given)) if (on) fail(`Error: --${flag} is only valid for Rust bundles`)
265
- }
266
- if (values.scope && !allJs) fail('Error: --scope is only valid for JS bundles')
267
- if (values.scope && !['node_modules', 'full'].includes(values.scope)) {
268
- fail('Error: --scope must be node_modules or full')
269
- }
270
- if (values.lockfile && !allJs) fail('Error: --lockfile is only valid for JS bundles')
271
- // --mainFields/--metro always emit a full-scope bundle, so they'd silently ignore --scope.
272
- if (values.scope !== undefined && (values.mainFields !== undefined || values.metro)) {
273
- fail('Error: --scope is not supported with --mainFields or --metro')
274
- }
275
- // --conditions: extra exports/imports resolution conditions merged onto Node's defaults;
276
- // they don't honour legacy `mainFields` or platform suffixes (see --mainFields).
277
- if (values.conditions !== undefined && !allJs) fail('Error: --conditions is only valid for JS bundles')
278
- const conditions = values.conditions === undefined
279
- ? []
280
- : values.conditions.split(',').map((s) => s.trim()).filter(Boolean)
281
- if (values.conditions !== undefined && conditions.length === 0) {
282
- fail('Error: --conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
283
- }
284
- // --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
285
- if (values.flow && !allJs) fail('Error: --flow is only valid for JS bundles')
286
- const flow = Boolean(values.flow)
287
- // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
288
- // extensionless) lands on its on-disk TS source (./x.ts, .mts, .cts); an existing .js always wins.
289
- if (values.typescript && !allJs) fail('Error: --typescript is only valid for JS bundles')
290
- const typescript = Boolean(values.typescript)
291
- // --tsconfig: the config whose compilerOptions.paths aliases --typescript honours (default: the
292
- // tsconfig.json beside each importing file's package.json). Meaningless without --typescript.
293
- if (values.tsconfig !== undefined && !typescript) fail('Error: --tsconfig is only valid with --typescript')
294
- // --mainFields: legacy package entry fields (e.g. react-native,browser,main) for the non-exports resolver.
295
- if (values.mainFields !== undefined && !allJs) fail('Error: --mainFields is only valid for JS bundles')
296
- const mainFields = values.mainFields === undefined
297
- ? undefined
298
- : values.mainFields.split(',').map((s) => s.trim()).filter(Boolean)
299
- if (values.mainFields !== undefined && mainFields.length === 0) {
300
- fail('Error: --mainFields must list at least one field (e.g. --mainFields=react-native,browser,main)')
301
- }
302
- // --metro: resolve like Metro/RN (its own conditions + mainFields, platform suffixes per
303
- // --platforms target). --platforms is repeatable and/or comma-separated; the values union.
304
- const metro = Boolean(values.metro)
305
- // --metro-resolver: resolve through the project's own metro-resolver instead of the built-in
306
- // approximation. Only meaningful alongside --metro (enforced below and in classifyEntries).
307
- const metroResolver = Boolean(values['metro-resolver'])
308
- const platforms = [...new Set((values.platforms ?? []).flatMap((p) => p.split(',')).map((s) => s.trim()).filter(Boolean))]
309
- // A platform name becomes an edge key: reject '/' (parsers reject it) and '*' (reserved placeholder).
310
- for (const p of platforms) {
311
- if (p === '*' || p.includes('/')) fail(`Error: invalid --platforms value '${p}' (a platform name can't contain '/' or be '*')`)
312
- }
313
- if ((metro || platforms.length > 0) && !allJs) fail('Error: --metro is only valid for JS bundles')
314
- // --jsx: parse React Native's JSX-in-.js source in the static scanner (off by default; oxc,
315
- // like tsc, auto-enables JSX for .jsx/.tsx only). Orthogonal to the resolver, so it pairs with
316
- // plain/--mainFields/--metro alike -- JS-only, since no other entry language is scanned.
317
- const jsx = Boolean(values.jsx)
318
- if (jsx && !allJs) fail('Error: --jsx is only valid for JS bundles')
319
- // --package-json: fold each bundled module's package.json into the bundle. JS-only (only JS
320
- // modules carry an npm package.json; the sol/php/bash/rust bucketizers have no such manifest).
321
- const packageJSON = Boolean(values['package-json'])
322
- if (packageJSON && !allJs) fail('Error: --package-json is only valid for JS bundles')
323
- // --resources: comma-separated extension/filename allowlist for assets reached through the graph
324
- // (e.g. --resources=png,svg). They're carried as resources instead of failing "can't carry" --
325
- // for graphs that aren't fully loadable in JS (Metro consumes such assets). JS-only.
326
- if (values.resources !== undefined && !allJs) fail('Error: --resources is only valid for JS bundles')
327
- const resources = values.resources === undefined
328
- ? []
329
- : values.resources.split(',').map((s) => s.trim()).filter(Boolean)
330
- if (values.resources !== undefined && resources.length === 0) {
331
- fail('Error: --resources must list at least one extension or filename (e.g. --resources=png,svg)')
332
- }
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
333
140
  try {
334
- 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 })
335
147
  } catch (cause) {
336
148
  fail(`Error: ${cause.message}`)
337
149
  }
338
- if (metro) {
339
- if (conditions.length > 0) fail("Error: --conditions can't be combined with --metro (it sets its own conditions)")
340
- if (mainFields !== undefined) fail("Error: --mainFields can't be combined with --metro (it sets its own mainFields)")
341
- if (platforms.length === 0) fail('Error: --metro requires --platforms (e.g. --platforms=ios,android)')
342
- } else if (platforms.length > 0) {
343
- fail('Error: --platforms is only valid with --metro')
344
- }
345
- if (metroResolver && !metro) fail('Error: --metro-resolver is only valid with --metro')
346
- // metro-resolver can't substitute .js -> .ts, so --typescript would silently not apply -- reject it.
347
- if (typescript && metroResolver) fail("Error: --typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)")
348
- // --brotli-quality: valid for every entry language (no allJs gate).
349
- let brotliQuality
350
- if (values['brotli-quality'] !== undefined) {
351
- try {
352
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
353
- } catch (cause) {
354
- fail(`Error: ${cause.message}`)
355
- }
356
- }
357
- // --add merges into the existing bundle at --output, so it can't target write-only stdout.
358
- const add = Boolean(values.add)
359
- if (add && values.output === '-') fail('Error: --add cannot be combined with --output=-')
360
150
  const { bundleCommand } = await import('../src/cmd/bundle.js')
361
- await bundleCommand({
362
- cwd: process.cwd(),
363
- entries: argv,
364
- mappingFile: values.mapping,
365
- manifests,
366
- output: values.output,
367
- scope: values.scope,
368
- lockfile: values.lockfile,
369
- conditions,
370
- mainFields,
371
- metro,
372
- metroResolver,
373
- platforms,
374
- jsx,
375
- flow,
376
- typescript,
377
- tsconfig: values.tsconfig,
378
- resources,
379
- packageJSON,
380
- cargo,
381
- cargoFeatures,
382
- cargoNoDefaultFeatures,
383
- cargoAllFeatures,
384
- cargoTarget,
385
- cargoManifests,
386
- brotliQuality,
387
- add,
388
- })
151
+ await bundleCommand({ cwd, ...plan })
389
152
  } else if (command === 'github-bundle') {
390
- const values = parseLeadingOptions(argv, {
153
+ const options = {
391
154
  github: { type: 'string' },
392
155
  sha: { type: 'string' },
393
156
  tag: { type: 'string' },
394
157
  directory: { type: 'string' },
395
158
  'package-manager': { type: 'string' },
396
159
  'package-manager-version': { type: 'string' },
160
+ 'no-lazy': { type: 'boolean' },
397
161
  mapping: { type: 'string' },
398
162
  manifests: { type: 'boolean' },
399
163
  output: { type: 'string', short: 'o' },
400
164
  scope: { type: 'string' },
401
165
  lockfile: { type: 'string' },
166
+ 'lockfile-only': { type: 'boolean' },
402
167
  conditions: { type: 'string' },
403
168
  mainFields: { type: 'string' },
404
169
  metro: { type: 'boolean' },
@@ -408,21 +173,46 @@ if (command === '-v' || command === '--version') {
408
173
  typescript: { type: 'boolean' },
409
174
  tsconfig: { type: 'string' },
410
175
  resources: { type: 'string' },
176
+ define: { type: 'string', multiple: true },
411
177
  'package-json': { type: 'boolean' },
412
178
  'brotli-quality': { type: 'string' },
413
179
  generate: { type: 'string', multiple: true },
414
- }, {
415
- valueFlags: ['--github', '--sha', '--tag', '--directory', '--package-manager', '--package-manager-version', '--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--platforms', '--tsconfig', '--resources', '--brotli-quality', '--generate', '-o'],
416
- onError: fail,
417
- })
418
- if (values.github === undefined) fail('Error: github-bundle requires --github=owner/name, the repo to bundle')
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')
419
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
+ }
420
208
  // Whether each option applies to the entries is buildGitHubBundle's to say.
421
209
  const list = (value) => [value ?? []].flat().flatMap((v) => v.split(',')).map((s) => s.trim()).filter(Boolean)
422
- let brotliQuality
423
- 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')
424
214
  try {
425
- brotliQuality = parseBrotliQuality('--brotli-quality', values['brotli-quality'])
215
+ define = parseDefineFlags(null, values.define)
426
216
  } catch (cause) {
427
217
  fail(`Error: ${cause.message}`)
428
218
  }
@@ -432,17 +222,21 @@ if (command === '-v' || command === '--version') {
432
222
  setCacheDir(userCacheDir())
433
223
  const { githubBundleCommand } = await import('../src/cmd/github-bundle.js')
434
224
  await githubBundleCommand({
435
- github: values.github,
225
+ github,
436
226
  sha: values.sha,
437
227
  tag: values.tag,
438
228
  directory: values.directory,
229
+ path,
439
230
  packageManager: values['package-manager'],
440
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,
441
234
  entries: argv.length === 0 ? undefined : argv,
442
235
  mappingFile: values.mapping,
443
236
  manifests: Boolean(values.manifests),
444
237
  output: values.output,
445
238
  lockfile: values.lockfile,
239
+ lockfileOnly,
446
240
  scope: values.scope,
447
241
  conditions: list(values.conditions),
448
242
  mainFields: values.mainFields === undefined ? undefined : list(values.mainFields),
@@ -452,37 +246,38 @@ if (command === '-v' || command === '--version') {
452
246
  flow: Boolean(values.flow),
453
247
  typescript: Boolean(values.typescript),
454
248
  tsconfig: values.tsconfig,
455
- resources: list(values.resources),
249
+ resources: values.resources === undefined ? undefined : list(values.resources),
250
+ define,
456
251
  packageJSON: Boolean(values['package-json']),
457
- 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),
458
254
  brotliQuality,
459
255
  })
460
256
  } else if (command === 'add') {
461
- // add packs the listed files (no resolver), taking split targets + resource allowlist from
462
- // stasis.config.json; it takes no flags.
463
- if (argv.length === 0) fail('Nothing to add: no file given')
464
- if (argv.some((a) => a.startsWith('-'))) fail('Error: add takes no options; its targets and resource allowlist come from stasis.config.json')
465
- const { addCommand } = await import('@exodus/stasis-core/add')
466
- // Let addCommand's runtime errors propagate as-is; wrapping in fail() would bury the cause.
467
- addCommand({ cwd: process.cwd(), entries: argv, logLabel: 'stasis' })
257
+ await import('../src/run-installed.js')
258
+ await addCli(argv, { label: 'stasis', fail })
468
259
  } else if (command === 'build') {
469
260
  const options = {
470
261
  output: { type: 'string', short: 'o' },
471
262
  format: { type: 'string' },
472
263
  platform: { type: 'string' },
473
264
  babel: { type: 'boolean' },
265
+ flow: { type: 'boolean' },
474
266
  minify: { type: 'boolean' },
475
267
  sourcemap: { type: 'boolean' },
476
268
  // Repeatable esbuild passthroughs (--define=K=V, --external=PATTERN, --loader=.ext:name).
477
269
  define: { type: 'string', multiple: true },
478
270
  external: { type: 'string', multiple: true },
479
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' },
480
276
  }
481
- const values = parseLeadingOptions(argv, options, {
482
- valueFlags: ['--output', '-o', '--format', '--platform', '--define', '--external', '--loader'],
483
- onError: fail,
484
- })
277
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
485
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')
486
281
  if (argv.length > 2) fail('Error: build takes a bundle or lockfile and an optional entry point')
487
282
  // esbuild output knobs; the import graph itself is fixed by the artifact, not these.
488
283
  if (values.format !== undefined && !['esm', 'cjs', 'iife'].includes(values.format)) {
@@ -522,21 +317,17 @@ if (command === '-v' || command === '--version') {
522
317
  format: values.format,
523
318
  platform: values.platform,
524
319
  babel: Boolean(values.babel),
320
+ flow: Boolean(values.flow),
525
321
  minify: values.minify,
526
322
  sourcemap: values.sourcemap,
527
323
  define,
528
324
  external: values.external ?? [],
529
325
  loader,
326
+ metro: values.metro,
327
+ assetsDest: values['assets-dest'],
530
328
  })
531
329
  } else if (command === 'extract') {
532
- const options = {
533
- output: { type: 'string', short: 'o' },
534
- }
535
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--output', '-o'], onError: fail })
536
- if (argv.length === 0) fail('Nothing to extract: no bundle file given')
537
- if (argv.length > 1) fail('Error: extract takes exactly one bundle file')
538
- const { extractCommand } = await import('@exodus/stasis-core/extract')
539
- extractCommand({ cwd: process.cwd(), bundleFile: argv[0], output: values.output, logLabel: 'stasis' })
330
+ await extractCli(argv, { label: 'stasis', fail })
540
331
  } else if (command === 'diff') {
541
332
  const options = {
542
333
  stat: { type: 'boolean' },
@@ -553,34 +344,131 @@ if (command === '-v' || command === '--version') {
553
344
  // Exit non-zero when the artifacts differ, so it composes in CI.
554
345
  process.exitCode = differences ? 1 : 0
555
346
  } else if (command === 'prune') {
556
- if (argv.length > 1) fail('Error: prune takes at most one path argument')
557
- const root = argv[0] ? resolve(argv[0]) : process.cwd()
558
- const { prune } = await import('@exodus/stasis-core/prune')
559
- const { removed, validated } = prune({ root })
560
- console.warn(`[stasis] prune: validated ${validated.length} file(s), removed ${removed.length} file(s)`)
347
+ await pruneCli(argv, { label: 'stasis', fail })
561
348
  } else if (command === 'audit') {
562
- 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: fail })
563
- if (argv.length === 0) fail('Nothing to audit: no path to file given')
564
- const repoAdvisories = Boolean(values['repo-advisories'])
565
- if (repoAdvisories && !process.env.GITHUB_TOKEN) fail('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
+ }
566
381
  // A Soldeer package's and a GitHub repo's advisories are their repository's, asked of GitHub with
567
- // GITHUB_TOKEN where it is set; the client asks nothing for any other package by itself.
568
- 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 })
569
384
  // Upstream caches what it looks up (a package's GitHub repo, a month each) only where told to, and
570
385
  // answers from it without asking: a per-user directory, never one shared with less trusted jobs.
571
386
  const { setCacheDir } = await import('@preventive/upstream/npm.js')
572
387
  setCacheDir(userCacheDir())
573
- const { audit, printAuditReport } = await import('../src/audit.js')
574
- const files = argv.map((f) => resolve(f))
575
- const report = await audit(files, { why: Boolean(values.why), whyDeep: Boolean(values['why-deep']), whyFull: Boolean(values['why-full']), reason: values.reason, repoAdvisories, github })
576
- printAuditReport(report)
577
- 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'] })
578
466
  } else if (command === 'sbom') {
579
467
  const options = {
580
468
  format: { type: 'string' },
581
469
  output: { type: 'string', short: 'o' },
582
470
  }
583
- const values = parseLeadingOptions(argv, options, { valueFlags: ['--format', '--output', '-o'], onError: fail })
471
+ const values = parseLeadingOptions(argv, options, { valueFlags: valueFlagsOf(options), onError: fail })
584
472
  if (!values.format) fail('Error: stasis sbom requires --format=(spdx|cyclonedx)')
585
473
  if (!['spdx', 'cyclonedx'].includes(values.format)) fail('Error: --format must be spdx or cyclonedx')
586
474
  if (argv.length === 0) fail('Nothing to export: no lockfile or bundle given')