@exodus/stasis 1.0.0-alpha.2 → 1.0.0-beta.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.
- package/README.md +67 -3
- package/bin/stasis.js +322 -17
- package/logo.svg +12 -3
- package/package.json +39 -18
- package/src/audit.js +112 -0
- package/src/bundle-from-lockfile.js +65 -0
- package/src/bundle.js +4 -217
- package/src/cmd/build.js +321 -0
- package/src/cmd/bundle.js +950 -59
- package/src/cmd/diff.js +36 -0
- package/src/cmd/extract.js +193 -0
- package/src/cmd/sbom.js +35 -0
- package/src/diff.js +333 -0
- package/src/esbuild.js +5 -56
- package/src/loader-mock.js +19 -0
- package/src/loader.js +6 -132
- package/src/loaders/bash.js +257 -0
- package/src/loaders/php.js +1058 -0
- package/src/loaders/rust.js +336 -0
- package/src/loaders/solidity.js +70 -49
- package/src/lockfile.js +4 -80
- package/src/metro-transformer.js +6 -0
- package/src/metro.js +5 -0
- package/src/mock.js +310 -0
- package/src/parse.js +53 -0
- package/src/prune.js +4 -162
- package/src/sbom.js +266 -0
- package/src/scan.js +373 -0
- package/src/webpack.js +5 -48
- package/src/config.js +0 -205
- package/src/state.js +0 -440
- package/src/state.util.js +0 -25
- package/src/util.js +0 -60
package/src/cmd/build.js
ADDED
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { createRequire } from 'node:module'
|
|
3
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path'
|
|
4
|
+
import { pathToFileURL } from 'node:url'
|
|
5
|
+
import { spawnSync } from 'node:child_process'
|
|
6
|
+
|
|
7
|
+
import { Bundle } from '@exodus/stasis-core/bundle'
|
|
8
|
+
import { State } from '@exodus/stasis-core/state'
|
|
9
|
+
import { StasisEsbuild } from '@exodus/stasis-plugins/esbuild'
|
|
10
|
+
import { bundleFromLockfile } from '../bundle-from-lockfile.js'
|
|
11
|
+
import { parseFileWithKind } from '../parse.js'
|
|
12
|
+
|
|
13
|
+
// Re-exported so `@exodus/stasis/cmd/build` keeps surfacing the lockfile->bundle
|
|
14
|
+
// reconstruction alongside the command; the implementation lives in its own module.
|
|
15
|
+
export { bundleFromLockfile }
|
|
16
|
+
|
|
17
|
+
// JS/TS entry extensions esbuild can build. esbuild handles JSX/TSX natively (loader
|
|
18
|
+
// 'jsx'/'tsx', derived from the extension by the load plugin), and stasis-core already
|
|
19
|
+
// classifies .jsx/.tsx as code (CODE_EXTENSIONS), so a bundle/lockfile captured by the
|
|
20
|
+
// esbuild/webpack plugins can carry them as entries.
|
|
21
|
+
const JS_EXTS = new Set(['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '.jsx', '.tsx'])
|
|
22
|
+
|
|
23
|
+
// Allowlist (NOT a blocklist) of per-file formats `stasis build` accepts in an artifact:
|
|
24
|
+
// the JS/TS/JSON code formats esbuild builds, plus the non-code payload formats
|
|
25
|
+
// (resource/directory) that are inert unless the SELECTED entry imports them. An allowlist
|
|
26
|
+
// so a new language format added to `stasis bundle` later (e.g. a future `go`) is rejected
|
|
27
|
+
// here by default, rather than slipping through to a cryptic esbuild failure in the build.
|
|
28
|
+
const BUILDABLE_FORMATS = new Set([
|
|
29
|
+
'module', 'commonjs', 'json', 'module-typescript', 'commonjs-typescript',
|
|
30
|
+
'resource', 'resource:base64', 'directory',
|
|
31
|
+
])
|
|
32
|
+
|
|
33
|
+
// esbuild is an OPTIONAL peer dependency: `stasis build` is the only command that
|
|
34
|
+
// needs a bundler, so we don't force every stasis install to pull one in. Resolve it
|
|
35
|
+
// from the local install first (a peer dep hoisted into the project's node_modules, or
|
|
36
|
+
// an npx-provided copy), then fall back to a global install, with an actionable error
|
|
37
|
+
// if neither is present.
|
|
38
|
+
async function importEsbuild() {
|
|
39
|
+
let mod
|
|
40
|
+
try {
|
|
41
|
+
mod = await import('esbuild')
|
|
42
|
+
} catch (cause) {
|
|
43
|
+
// Only a genuine "not installed" miss falls through to the global lookup; a
|
|
44
|
+
// different failure (a corrupt install, a syntax error in esbuild) is surfaced.
|
|
45
|
+
if (cause?.code !== 'ERR_MODULE_NOT_FOUND' && cause?.code !== 'ERR_PACKAGE_PATH_NOT_EXPORTED') {
|
|
46
|
+
throw cause
|
|
47
|
+
}
|
|
48
|
+
const globalMain = resolveGlobalEsbuild()
|
|
49
|
+
if (!globalMain) {
|
|
50
|
+
throw new Error(
|
|
51
|
+
'stasis build requires esbuild, which could not be found.\n' +
|
|
52
|
+
'Install it as a dev dependency (npm i -D esbuild / pnpm add -D esbuild / yarn add -D esbuild) ' +
|
|
53
|
+
'or globally (npm i -g esbuild).',
|
|
54
|
+
{ cause }
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
mod = await import(pathToFileURL(globalMain).href)
|
|
58
|
+
}
|
|
59
|
+
// esbuild ships a CJS module exposing named exports (build, context, ...); Node's
|
|
60
|
+
// interop surfaces them directly. A globally-imported CJS copy may instead land its
|
|
61
|
+
// exports on `default` -- accept both shapes.
|
|
62
|
+
return typeof mod.build === 'function' ? mod : mod.default
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Locate a globally-installed esbuild via the package managers' "global root" commands.
|
|
66
|
+
// Returns the absolute path to esbuild's entry, or undefined when none is installed.
|
|
67
|
+
function resolveGlobalEsbuild() {
|
|
68
|
+
const probes = [
|
|
69
|
+
['npm', ['root', '-g']],
|
|
70
|
+
['pnpm', ['root', '-g']],
|
|
71
|
+
['yarn', ['global', 'dir']],
|
|
72
|
+
]
|
|
73
|
+
for (const [cmd, args] of probes) {
|
|
74
|
+
let out
|
|
75
|
+
try {
|
|
76
|
+
out = spawnSync(cmd, args, { encoding: 'utf8' })
|
|
77
|
+
} catch {
|
|
78
|
+
continue // package manager not installed
|
|
79
|
+
}
|
|
80
|
+
if (!out || out.status !== 0 || !out.stdout) continue
|
|
81
|
+
const base = out.stdout.trim()
|
|
82
|
+
if (!base) continue
|
|
83
|
+
// `npm/pnpm root -g` print the global node_modules dir; `yarn global dir` prints a
|
|
84
|
+
// dir whose node_modules holds the packages. Try both shapes.
|
|
85
|
+
for (const nm of [base, join(base, 'node_modules')]) {
|
|
86
|
+
if (!existsSync(join(nm, 'esbuild', 'package.json'))) continue
|
|
87
|
+
try {
|
|
88
|
+
return createRequire(join(nm, 'noop.js')).resolve('esbuild')
|
|
89
|
+
} catch {
|
|
90
|
+
// keep probing
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return undefined
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// Validate that an artifact is something esbuild can build: full scope (node_modules
|
|
98
|
+
// scope omits the entry and workspace code, so it can't be built on its own), at least
|
|
99
|
+
// one entry, all entries JS/TS, and only buildable per-file formats (see BUILDABLE_FORMATS).
|
|
100
|
+
function assertBuildable(artifact, label) {
|
|
101
|
+
if (artifact.config.scope !== 'full') {
|
|
102
|
+
throw new Error(
|
|
103
|
+
`stasis build requires a full-scope artifact; ${label} is scope='${artifact.config.scope}'. ` +
|
|
104
|
+
`node_modules-scope artifacts omit the entry and workspace code, so there is nothing to build.`
|
|
105
|
+
)
|
|
106
|
+
}
|
|
107
|
+
const entries = [...artifact.entries]
|
|
108
|
+
if (entries.length === 0) {
|
|
109
|
+
throw new Error(`stasis build: ${label} declares no entries to build`)
|
|
110
|
+
}
|
|
111
|
+
for (const entry of entries) {
|
|
112
|
+
if (!JS_EXTS.has(extname(entry))) {
|
|
113
|
+
throw new Error(`stasis build only builds JavaScript/TypeScript entries (esbuild); got non-JS entry '${entry}' in ${label}`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
// artifact.formats is a Map (Bundle) or may be null on a legacy lockfile (an absent map
|
|
117
|
+
// is fine -- nothing to check). Reject any format outside the allowlist: the non-JS
|
|
118
|
+
// LANGUAGE bundlers' formats (Solidity/PHP/Bash/Rust) and anything added later.
|
|
119
|
+
//
|
|
120
|
+
// NOTE: resource formats are IN the allowlist -- deliberately NOT rejected here. A resource
|
|
121
|
+
// is recorded as a FILE but never as an import EDGE, so whether a build hits one depends on
|
|
122
|
+
// the SELECTED entry's own source, not the artifact as a whole -- a code-only entry must
|
|
123
|
+
// build even when the artifact carries assets for OTHER entries. An entry that does import
|
|
124
|
+
// an asset fails at build time (esbuild can't resolve the un-graphed resource).
|
|
125
|
+
for (const [file, format] of artifact.formats ?? new Map()) {
|
|
126
|
+
if (!BUILDABLE_FORMATS.has(format)) {
|
|
127
|
+
throw new Error(`stasis build only supports JavaScript/TypeScript bundles (esbuild); ${label} carries a '${format}' file (${file})`)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Pick which recorded entry to build. The build produces exactly one entry's bundle;
|
|
133
|
+
// `entryArg` selects it. With a single recorded entry the selector is optional (that
|
|
134
|
+
// entry is used); with several it is required, and an absent or unknown one is rejected
|
|
135
|
+
// with the available list. The selector is matched against the artifact's recorded
|
|
136
|
+
// (project-relative) entries -- only those are attested as graph roots, and the load
|
|
137
|
+
// plugin's assertEntry rejects anything else -- accepting the recorded path verbatim, a
|
|
138
|
+
// leading `./` stripped, or a cwd-relative path normalized into the project root.
|
|
139
|
+
function selectEntry(entryArg, entries, { cwd, root, label }) {
|
|
140
|
+
const recorded = [...entries]
|
|
141
|
+
const list = recorded.map((e) => ` ${e}`).join('\n')
|
|
142
|
+
if (entryArg === undefined) {
|
|
143
|
+
if (recorded.length === 1) return recorded[0]
|
|
144
|
+
// length === 0 is impossible here (assertBuildable required >= 1 entry).
|
|
145
|
+
throw new Error(`stasis build: ${label} has ${recorded.length} entry points; pass one as the second argument:\n${list}`)
|
|
146
|
+
}
|
|
147
|
+
const candidates = new Set([
|
|
148
|
+
entryArg,
|
|
149
|
+
entryArg.replace(/^\.\//u, ''),
|
|
150
|
+
relative(root, resolve(cwd, entryArg)).split(sep).join('/'),
|
|
151
|
+
])
|
|
152
|
+
const match = recorded.find((e) => candidates.has(e))
|
|
153
|
+
if (match === undefined) {
|
|
154
|
+
throw new Error(`stasis build: '${entryArg}' is not an entry point of ${label}; available:\n${list}`)
|
|
155
|
+
}
|
|
156
|
+
return match
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// Build a bundle-load State that serves an in-memory Bundle -- the same shape StasisEsbuild's
|
|
160
|
+
// load path reads from (state.sources / state.resources / state.formats / state.imports /
|
|
161
|
+
// state.entries). skipDiscovery anchors the State at `root` and does NO filesystem discovery:
|
|
162
|
+
// no package.json walk, no on-disk config, no stray stasis.code.br read. bundle=load +
|
|
163
|
+
// lock=ignore serve the bundle's own bytes (self-attesting -- the lockfile path already
|
|
164
|
+
// SHA-512-verified them in bundleFromLockfile). We mirror State's on-disk load (split
|
|
165
|
+
// sources/resources by format) and fill the maps from `bundle`.
|
|
166
|
+
function loadStateForBundle(root, bundle) {
|
|
167
|
+
const state = new State(root, { bundle: 'load', lock: 'ignore', scope: bundle.config.scope, skipDiscovery: true })
|
|
168
|
+
const sources = new Map()
|
|
169
|
+
const resources = new Map()
|
|
170
|
+
for (const [file, content] of bundle.sources) {
|
|
171
|
+
if (Bundle.isResourceFormat(bundle.formats.get(file))) resources.set(file, content)
|
|
172
|
+
else sources.set(file, content)
|
|
173
|
+
}
|
|
174
|
+
state.sources = sources
|
|
175
|
+
state.resources = resources
|
|
176
|
+
state.formats = bundle.formats
|
|
177
|
+
state.imports = bundle.imports
|
|
178
|
+
state.entries = new Set(bundle.entries)
|
|
179
|
+
// Not state.modules: the load path (getImport/getFile/getFormat/assertEntry) never reads
|
|
180
|
+
// it -- it's only written by the capture paths. The State's empty-Map default stands.
|
|
181
|
+
return state
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Run the `stasis build` CLI command end-to-end: take a stasis artifact (a `stasis.code.br`
|
|
185
|
+
// bundle, or a `stasis.lock.json` lockfile whose attested files are read + verified from
|
|
186
|
+
// disk) and an entry point, and run esbuild over that one entry, following the artifact's
|
|
187
|
+
// recorded import graph EXACTLY rather than esbuild's own resolver.
|
|
188
|
+
//
|
|
189
|
+
// `entry` selects which recorded entry to build (see selectEntry): optional when the
|
|
190
|
+
// artifact records one, required when it records several. `output` is required: a path
|
|
191
|
+
// ending in `.js`/`.cjs`/`.mjs` writes a single file, anything else a directory.
|
|
192
|
+
//
|
|
193
|
+
// The build runs entirely in memory off the artifact -- no temp files, and no package.json
|
|
194
|
+
// required. The artifact's relative paths anchor at the artifact's OWN directory: a bundle is
|
|
195
|
+
// self-contained (root is just a keying prefix; nothing is read from disk), and a lockfile
|
|
196
|
+
// records its paths relative to where it sits (its project root), so its sources are read +
|
|
197
|
+
// verified from there. A project stasis.config.json is not consulted -- the build is driven
|
|
198
|
+
// by the artifact, not by `stasis run` config.
|
|
199
|
+
//
|
|
200
|
+
// The recorded graph is forced via the stasis esbuild plugin in bundle-load mode: each import
|
|
201
|
+
// resolves to the edge stasis recorded (a specifier the artifact doesn't record is handed back
|
|
202
|
+
// to esbuild, which externalizes it like a built-in/`external`), and each module's bytes come
|
|
203
|
+
// from the artifact -- so the output reflects what stasis attested, not what's on disk.
|
|
204
|
+
//
|
|
205
|
+
// `format` (esm/cjs/iife, default esm), `platform` (node/browser/neutral, default node),
|
|
206
|
+
// `minify`, `sourcemap`, `define` (an esbuild define map), `external` (an array of esbuild
|
|
207
|
+
// external patterns), and `loader` (an esbuild extension->loader map, e.g. { '.js': 'jsx' }
|
|
208
|
+
// to parse JSX in .js files) are forwarded to esbuild; the import graph is fixed by the artifact.
|
|
209
|
+
//
|
|
210
|
+
// `external` is esbuild's native option: it only steers specifiers esbuild itself would
|
|
211
|
+
// resolve -- i.e. the ones the bundle does NOT record (handed back to esbuild as a miss,
|
|
212
|
+
// typically the externals that existed at capture time). It re-declares those so esbuild
|
|
213
|
+
// leaves them as runtime imports instead of trying (and failing) to resolve them on disk.
|
|
214
|
+
// A specifier the artifact DOES record is still followed from the artifact -- the recorded
|
|
215
|
+
// graph wins, so `external` never silently un-inlines an attested edge.
|
|
216
|
+
export async function buildCommand({
|
|
217
|
+
cwd = process.cwd(),
|
|
218
|
+
artifact,
|
|
219
|
+
entry,
|
|
220
|
+
output,
|
|
221
|
+
format = 'esm',
|
|
222
|
+
platform = 'node',
|
|
223
|
+
minify = false,
|
|
224
|
+
sourcemap = false,
|
|
225
|
+
define = {},
|
|
226
|
+
external = [],
|
|
227
|
+
loader = {},
|
|
228
|
+
} = {}) {
|
|
229
|
+
if (!artifact) throw new Error('stasis build: an artifact (bundle or lockfile) is required')
|
|
230
|
+
if (!output) throw new Error('stasis build: --output is required (a .js/.cjs/.mjs file, or a directory)')
|
|
231
|
+
if (!Array.isArray(external)) throw new Error('stasis build: external must be an array of esbuild patterns')
|
|
232
|
+
const artifactAbs = resolve(cwd, artifact)
|
|
233
|
+
const { kind, artifact: parsed } = parseFileWithKind(artifactAbs)
|
|
234
|
+
assertBuildable(parsed, artifact)
|
|
235
|
+
|
|
236
|
+
// Anchor the artifact's relative paths at the artifact's OWN directory. A bundle is
|
|
237
|
+
// self-contained (root is just a keying prefix; nothing is read from disk), and a lockfile
|
|
238
|
+
// records its paths relative to where it sits -- its project root -- so its sources are
|
|
239
|
+
// read + verified from there. No package.json discovery, no project stasis.config.json.
|
|
240
|
+
const root = dirname(artifactAbs)
|
|
241
|
+
const selectedEntry = selectEntry(entry, parsed.entries, { cwd, root, label: artifact })
|
|
242
|
+
|
|
243
|
+
// The Bundle the load State serves, entirely in memory. A bundle artifact is already a
|
|
244
|
+
// parsed Bundle; a lockfile is reconstructed into one by reading + SHA-512-verifying its
|
|
245
|
+
// attested files from disk (bundleFromLockfile). The plugin drives off the in-memory State.
|
|
246
|
+
const bundle = kind === 'lockfile' ? bundleFromLockfile(parsed, { root }) : parsed
|
|
247
|
+
const state = loadStateForBundle(root, bundle)
|
|
248
|
+
// The selected entry is project-relative in the artifact; make it absolute against the
|
|
249
|
+
// State's root so esbuild's entry resolution is independent of the process cwd.
|
|
250
|
+
const entryPoint = resolve(state.root, selectedEntry)
|
|
251
|
+
|
|
252
|
+
const esbuild = await importEsbuild()
|
|
253
|
+
const outAbs = resolve(cwd, output)
|
|
254
|
+
// A `.js`/`.cjs`/`.mjs` --output names a single output file; anything else is a directory.
|
|
255
|
+
const asFile = /\.[cm]?js$/u.test(output)
|
|
256
|
+
// Absolute paths the artifact attests -- esbuild must NEVER overwrite one. A stray
|
|
257
|
+
// `--output=src/x.js` (or `--output=src`/`.` whose computed output basename collides with a
|
|
258
|
+
// recorded source) would otherwise destroy an attested file: esbuild's own "refusing to
|
|
259
|
+
// overwrite input file" check fires only AFTER it has written, and for a lockfile that
|
|
260
|
+
// permanently breaks the file's hash. So we build with write:false and write the outputs
|
|
261
|
+
// ourselves, refusing -- before touching disk -- to clobber any recorded file.
|
|
262
|
+
const attested = new Set([...state.sources.keys(), ...state.resources.keys()].map((f) => resolve(state.root, f)))
|
|
263
|
+
|
|
264
|
+
let result
|
|
265
|
+
try {
|
|
266
|
+
result = await esbuild.build({
|
|
267
|
+
entryPoints: [entryPoint],
|
|
268
|
+
absWorkingDir: state.root,
|
|
269
|
+
bundle: true,
|
|
270
|
+
write: false,
|
|
271
|
+
platform,
|
|
272
|
+
format,
|
|
273
|
+
logLevel: 'silent',
|
|
274
|
+
...(minify ? { minify: true } : {}),
|
|
275
|
+
...(sourcemap ? { sourcemap: true } : {}),
|
|
276
|
+
...(external.length > 0 ? { external } : {}),
|
|
277
|
+
...(Object.keys(define).length > 0 ? { define } : {}),
|
|
278
|
+
...(asFile ? { outfile: outAbs } : { outdir: outAbs }),
|
|
279
|
+
// Per-extension loader overrides drive the stasis plugin's load-mode loader choice
|
|
280
|
+
// (the plugin serves and labels every in-bundle file, so esbuild's own `loader`
|
|
281
|
+
// option never sees them). e.g. { '.js': 'jsx' } to parse JSX in .js files.
|
|
282
|
+
plugins: [new StasisEsbuild(state, { loaders: new Map(Object.entries(loader)) })],
|
|
283
|
+
})
|
|
284
|
+
} catch (err) {
|
|
285
|
+
// esbuild rejects with a BuildFailure carrying a formatted `.errors` array under
|
|
286
|
+
// logLevel:'silent'. Surface those (rather than the bare wrapper) so the user sees the
|
|
287
|
+
// actual resolve/load failure -- including an entry that imports an un-buildable asset
|
|
288
|
+
// -- then fail the command.
|
|
289
|
+
if (Array.isArray(err?.errors) && err.errors.length > 0) {
|
|
290
|
+
const formatted = await esbuild.formatMessages(err.errors, { kind: 'error', color: false })
|
|
291
|
+
for (const line of formatted) process.stderr.write(line)
|
|
292
|
+
throw new Error(`stasis build failed: esbuild reported ${err.errors.length} error(s)`, { cause: err })
|
|
293
|
+
}
|
|
294
|
+
throw err
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// The build succeeded. Refuse to clobber an attested source -- checked against esbuild's
|
|
298
|
+
// ACTUAL output paths (so it covers both `--output` file and directory), BEFORE any write,
|
|
299
|
+
// so a rejected build leaves every recorded file intact.
|
|
300
|
+
for (const file of result.outputFiles) {
|
|
301
|
+
if (attested.has(file.path)) {
|
|
302
|
+
throw new Error(
|
|
303
|
+
`stasis build: refusing to write '${relative(cwd, file.path)}' -- it is a source the artifact records; ` +
|
|
304
|
+
`choose an --output path outside the artifact's own files`
|
|
305
|
+
)
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (result.warnings.length > 0) {
|
|
310
|
+
const formatted = await esbuild.formatMessages(result.warnings, { kind: 'warning', color: false })
|
|
311
|
+
for (const line of formatted) process.stderr.write(line)
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
for (const file of result.outputFiles) {
|
|
315
|
+
mkdirSync(dirname(file.path), { recursive: true })
|
|
316
|
+
writeFileSync(file.path, file.contents)
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
console.warn(`[stasis] Built ${selectedEntry} from ${kind} ${artifact} to ${output}`)
|
|
320
|
+
return { entry: selectedEntry, dir: asFile ? undefined : outAbs, outfile: asFile ? outAbs : undefined }
|
|
321
|
+
}
|