@exodus/stasis-core 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/LICENSE +21 -0
- package/README.md +9 -0
- package/bin/stasis-core.js +116 -0
- package/package.json +50 -0
- package/src/brotli.js +21 -0
- package/src/bundle.js +256 -0
- package/src/config.js +426 -0
- package/src/fs.js +712 -0
- package/src/hooks.js +826 -0
- package/src/loader.js +6 -0
- package/src/lockfile.js +152 -0
- package/src/package.cjs +1 -0
- package/src/prune.js +532 -0
- package/src/state-util.js +64 -0
- package/src/state.js +2375 -0
- package/src/util.js +210 -0
package/src/util.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import * as fs from 'node:fs'
|
|
2
|
+
import { basename, isAbsolute, join, posix, relative } from 'node:path'
|
|
3
|
+
|
|
4
|
+
// Snapshot realpathSync at module-eval, BEFORE `stasis run --fs` patches fs.realpathSync.
|
|
5
|
+
// The patch + syncBuiltinESMExports() repoint a LIVE `import { realpathSync }` binding to the
|
|
6
|
+
// bundle-serving wrapper, which (by design, for user code) does NOT throw ENOENT for a
|
|
7
|
+
// recorded-but-absent path -- which would silently defeat assertRealPathWithinBase's reliance
|
|
8
|
+
// on that throw (see its comment). Stasis's own reads must stay on the genuine builtin, so we
|
|
9
|
+
// snapshot here exactly like state.js / state-util.js / fs.js do for the other patched readers.
|
|
10
|
+
const { realpathSync } = fs
|
|
11
|
+
|
|
12
|
+
const sep = '/'
|
|
13
|
+
|
|
14
|
+
// The full, finite universe of `format` strings stasis knows. Lockfile and bundle
|
|
15
|
+
// parsers reject any value outside this set so a tampered or forward-incompatible
|
|
16
|
+
// artifact fails closed at the schema boundary, not at a later string compare.
|
|
17
|
+
// Categories:
|
|
18
|
+
// Executable by Node's loader — module, commonjs, json, *-typescript
|
|
19
|
+
// Source languages (analysis-only, not runnable by Node) — solidity, php, bash, rust
|
|
20
|
+
// Resources (asset payloads) — resource (raw UTF-8), resource:base64 (binary)
|
|
21
|
+
// Filesystem captures (`stasis run --fs`) — directory (a JSON-serialized,
|
|
22
|
+
// sorted `fs.readdirSync` listing; a resource-like raw-UTF-8 payload)
|
|
23
|
+
// Adding a new format is a deliberate schema change: list it here AND extend
|
|
24
|
+
// hooks.js's executable allowlist if Node should serve it from a bundle.
|
|
25
|
+
export const KNOWN_FORMATS = new Set([
|
|
26
|
+
'module',
|
|
27
|
+
'commonjs',
|
|
28
|
+
'json',
|
|
29
|
+
'module-typescript',
|
|
30
|
+
'commonjs-typescript',
|
|
31
|
+
'solidity',
|
|
32
|
+
'php',
|
|
33
|
+
'bash',
|
|
34
|
+
'rust',
|
|
35
|
+
'resource',
|
|
36
|
+
'resource:base64',
|
|
37
|
+
'directory',
|
|
38
|
+
])
|
|
39
|
+
|
|
40
|
+
// File extensions whose bytes are JS-shaped code -- Node's loader and the
|
|
41
|
+
// lockfile/bundle format machinery can attest them (module/commonjs/json/
|
|
42
|
+
// *-typescript) and `bundle=load` can round-trip them as modules. This is the
|
|
43
|
+
// SINGLE source of truth for "is this a code file", shared so the two capture
|
|
44
|
+
// paths can't disagree: bundler plugins classify module-graph imports against it
|
|
45
|
+
// (classifyExtension), parseResourcesOption refuses to admit any of these into a
|
|
46
|
+
// `resources` allowlist (a code file is never an asset payload), and State both
|
|
47
|
+
// classifies `--fs` reads and guards `resource:true` against it. Dot-less +
|
|
48
|
+
// lowercase, matching pathExt. Drift here was the root of a lockfile/bundle
|
|
49
|
+
// desync: `.jsx`/`.tsx` were code to the plugins but missing from the fs-capture's
|
|
50
|
+
// own set, so an fs-read tagged a `.jsx` 'resource' while the import tagged it code.
|
|
51
|
+
export const CODE_EXTENSIONS = new Set(['js', 'mjs', 'cjs', 'ts', 'jsx', 'tsx', 'json', 'mts', 'cts'])
|
|
52
|
+
|
|
53
|
+
// Lowercased, dot-less extension of a path, or '' if none.
|
|
54
|
+
export function pathExt(filePath) {
|
|
55
|
+
const m = /\.([^./\\]+)$/.exec(filePath)
|
|
56
|
+
return m ? m[1].toLowerCase() : ''
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Validates + normalizes a `resources` allowlist (plugin option, --resources flag,
|
|
60
|
+
// EXODUS_STASIS_RESOURCES, or stasis.config.json) into a Set of lowercase entries. Each
|
|
61
|
+
// entry is either a bare extension (`png`, `.png`) or an extensionless filename
|
|
62
|
+
// (`LICENSE`, `Makefile`, `license-mit`); classifyExtension matches a file by its
|
|
63
|
+
// extension, falling back to its basename when it has none. A dotted entry like
|
|
64
|
+
// `data.bin` is rejected -- a file that HAS an extension is keyed by it, so the entry
|
|
65
|
+
// would never match; declare the extension (`bin`) instead. Code extensions are rejected
|
|
66
|
+
// too (always tracked). Throwing here surfaces misconfigurations immediately rather than
|
|
67
|
+
// as silent capture drift. `resources` may be an array (option / config) or undefined.
|
|
68
|
+
export function parseResourcesOption(label, resources) {
|
|
69
|
+
if (resources === undefined) return new Set()
|
|
70
|
+
if (!Array.isArray(resources)) {
|
|
71
|
+
throw new TypeError(`${label}: resources must be an array of extension/filename strings`)
|
|
72
|
+
}
|
|
73
|
+
const out = new Set()
|
|
74
|
+
for (const entry of resources) {
|
|
75
|
+
if (typeof entry !== 'string') {
|
|
76
|
+
throw new TypeError(`${label}: resources entry must be a string, got ${typeof entry}`)
|
|
77
|
+
}
|
|
78
|
+
const clean = entry.toLowerCase().replace(/^\./, '')
|
|
79
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(clean)) {
|
|
80
|
+
throw new Error(`${label}: resources entry '${entry}' is not a valid extension or filename (use e.g. 'png' or 'LICENSE')`)
|
|
81
|
+
}
|
|
82
|
+
if (CODE_EXTENSIONS.has(clean)) {
|
|
83
|
+
throw new Error(`${label}: resources entry '${entry}' is a code extension; remove it (code extensions are always tracked)`)
|
|
84
|
+
}
|
|
85
|
+
out.add(clean)
|
|
86
|
+
}
|
|
87
|
+
return out
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Classifies a file against the code set + a parsed resources allowlist. Returns 'code'
|
|
91
|
+
// (track with its loader format), 'resource' (track with a 'resource'/'resource:base64'
|
|
92
|
+
// format -- the encoding is chosen from content), or 'unknown' (caller must reject). A
|
|
93
|
+
// file is keyed by its extension, or -- when it has none (LICENSE, Makefile, a dotless
|
|
94
|
+
// name) -- by its basename, so a resources entry can be an extension or an extensionless
|
|
95
|
+
// filename. The 'unknown' path forces every non-JS asset to be declared explicitly -- no
|
|
96
|
+
// silent attestation widening. The SINGLE classifier for both capture paths: bundler
|
|
97
|
+
// plugins run it on module-graph imports, State runs it on `--fs` reads, so the two
|
|
98
|
+
// can't drift.
|
|
99
|
+
export function classifyExtension(filePath, resources) {
|
|
100
|
+
const ext = pathExt(filePath)
|
|
101
|
+
if (CODE_EXTENSIONS.has(ext)) return 'code'
|
|
102
|
+
if (resources.has(ext || basename(filePath).toLowerCase())) return 'resource'
|
|
103
|
+
return 'unknown'
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Set-equality for parsed resources allowlists (lowercase extension/filename sets).
|
|
107
|
+
// Coordinates a plugin's `resources` option against an active preload's, and the env
|
|
108
|
+
// var against an explicit option in Config.
|
|
109
|
+
export function extSetsEqual(a, b) {
|
|
110
|
+
if (a.size !== b.size) return false
|
|
111
|
+
for (const ext of a) if (!b.has(ext)) return false
|
|
112
|
+
return true
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Flat project-relative key for the file `rel` inside module dir `dir`, inverse of
|
|
116
|
+
// the bucketing State/Bundle apply. The `rel === ''` branch is reached only by a
|
|
117
|
+
// `directory` capture whose path IS a module root (e.g. `fs.readdirSync` of a
|
|
118
|
+
// package dir, or of the project root): the listing is keyed at the bucket itself,
|
|
119
|
+
// so the flat key is the dir (or '' for the workspace root) — never `${dir}/`,
|
|
120
|
+
// which a trailing-slash join would wrongly produce and break the round-trip. For
|
|
121
|
+
// every ordinary file `rel` is a real basename, so this matches the historical
|
|
122
|
+
// `dir === '.' ? rel : `${dir}/${rel}`` exactly.
|
|
123
|
+
export function moduleFileKey(dir, rel) {
|
|
124
|
+
if (rel === '') return dir === '.' ? '' : dir
|
|
125
|
+
return dir === '.' ? rel : `${dir}/${rel}`
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Resolve `baseDir/relPath` through symlinks and confirm the real target stays
|
|
129
|
+
// within `realBase` (the caller-resolved real path of baseDir). Throws on a
|
|
130
|
+
// symlink that escapes the bundle root: a crafted in-tree symlink
|
|
131
|
+
// (`link.sh -> /etc/passwd`, or a symlinked directory) must not pull an
|
|
132
|
+
// external file into a self-contained, attestable bundle. The textual path
|
|
133
|
+
// guards elsewhere don't catch this because they never resolve symlinks.
|
|
134
|
+
// realpathSync surfaces ENOENT for a missing path, which the loaders' disk
|
|
135
|
+
// walks already handle as "missing".
|
|
136
|
+
export function assertRealPathWithinBase(realBase, baseDir, relPath) {
|
|
137
|
+
const real = realpathSync(join(baseDir, relPath))
|
|
138
|
+
const rel = relative(realBase, real).split(/[\\/]/u).join('/')
|
|
139
|
+
if (rel.startsWith('..') || isAbsolute(rel)) {
|
|
140
|
+
throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function assert(condition, msg) {
|
|
145
|
+
if (!condition) throw new Error(msg)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function sortPaths(a, b) {
|
|
149
|
+
const [al, bl] = [a.split(sep), b.split(sep)]
|
|
150
|
+
while (al.length > 0 && al[0] === bl[0]) {
|
|
151
|
+
al.shift()
|
|
152
|
+
bl.shift()
|
|
153
|
+
}
|
|
154
|
+
if (al.length === 0 && bl.length === 0) return 0
|
|
155
|
+
|
|
156
|
+
// First process each file in dir, then subdirs
|
|
157
|
+
if (al.length < 2) return bl.length < 2 && al > bl ? 1 : -1
|
|
158
|
+
if (bl.length < 2) return 1
|
|
159
|
+
|
|
160
|
+
// * comes first
|
|
161
|
+
if (al[0] === '*') return -1
|
|
162
|
+
if (bl[0] === '*') return 1
|
|
163
|
+
|
|
164
|
+
// node_modules comes last
|
|
165
|
+
if (al[0] === 'node_modules') return 1
|
|
166
|
+
if (bl[0] === 'node_modules') return -1
|
|
167
|
+
|
|
168
|
+
// Prefer example/ over example-something/
|
|
169
|
+
const [an, bn] = [al, bl].map((list) => list.join(String.fromCodePoint(0)))
|
|
170
|
+
if (an < bn) return -1
|
|
171
|
+
if (an > bn) return 1
|
|
172
|
+
throw new Error('Unreachable')
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
export const isPlainObject = (x) => x && [null, Object.prototype].includes(Object.getPrototypeOf(x))
|
|
176
|
+
|
|
177
|
+
export const fromEntries = (entries) => Object.setPrototypeOf(Object.fromEntries(entries), null)
|
|
178
|
+
|
|
179
|
+
export const fileSetToObject = (set) => [...set].toSorted((a, b) => sortPaths(a, b))
|
|
180
|
+
|
|
181
|
+
export const fileMapToObject = (map) => fromEntries(
|
|
182
|
+
[...map]
|
|
183
|
+
.toSorted((a, b) => sortPaths(a[0], b[0]))
|
|
184
|
+
.map(([k, v]) => [k, v instanceof Map ? fileMapToObject(v) : v])
|
|
185
|
+
)
|
|
186
|
+
|
|
187
|
+
export const objectToMaps = (obj) => new Map(
|
|
188
|
+
Object.entries(obj).map(([k, v]) => [k, isPlainObject(v) ? objectToMaps(v) : v])
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
// True when a POSIX, project-relative path escapes the root once normalized:
|
|
192
|
+
// a leading `..`, an absolute path, or a mid-path `..` that pops above the
|
|
193
|
+
// root (`a/../../x`). Plain `startsWith('..')` only catches the leading case,
|
|
194
|
+
// so it's not enough for paths that later get resolved against the root.
|
|
195
|
+
export function posixPathEscapes(path) {
|
|
196
|
+
const normalized = posix.normalize(path)
|
|
197
|
+
return normalized === '..' || normalized.startsWith('../') || posix.isAbsolute(normalized)
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
export function splitNodeModulesPath(path) {
|
|
201
|
+
const marker = 'node_modules/'
|
|
202
|
+
const idx = path.lastIndexOf(marker)
|
|
203
|
+
if (idx === -1) return null
|
|
204
|
+
const after = idx + marker.length
|
|
205
|
+
const parts = path.slice(after).split('/')
|
|
206
|
+
const pkgLen = parts[0].startsWith('@') ? 2 : 1
|
|
207
|
+
if (parts.length <= pkgLen || parts.slice(0, pkgLen).some((p) => !p)) return null
|
|
208
|
+
const name = parts.slice(0, pkgLen).join('/')
|
|
209
|
+
return { dir: path.slice(0, after) + name, rel: parts.slice(pkgLen).join('/'), name }
|
|
210
|
+
}
|