@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Exodus Movement
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,9 @@
1
+ # <img src="/stasis/logo.svg" alt="" width="39" height="39" valign="bottom" /> `@exodus/stasis-core`
2
+
3
+ A minimal subset of `@exodus/stasis` with just `run` and `prune` commands.
4
+
5
+ See main package [GitHub](https://github.com/ExodusOSS/stasis/tree/main/stasis) or [npm](https://npmjs.com/package/@exodus/stasis) for full README.
6
+
7
+ ## License
8
+
9
+ [MIT](./LICENSE)
@@ -0,0 +1,116 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { spawn } from 'node:child_process'
4
+ import { parseArgs } from 'node:util'
5
+ import { once } from 'node:events'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { basename, resolve } from 'node:path'
8
+ import { existsSync, realpathSync } from 'node:fs'
9
+ import assert from 'node:assert/strict'
10
+ import pkg from '../package.json' with { type: 'json' }
11
+
12
+ const argv = [...process.argv]
13
+ assert(['node', 'node.exe'].includes(basename(argv.shift())))
14
+ assert(['node', 'node.exe'].includes(basename(process.argv0)))
15
+
16
+ const jsname = argv.shift()
17
+ const pathsEqual = (a, b) => a === b || (existsSync(a) && realpathSync(a) === b) // resolve symlinks
18
+ assert(basename(jsname) === 'stasis-core' || pathsEqual(jsname, fileURLToPath(import.meta.url)))
19
+
20
+ function usage(prefix = '') {
21
+ console.error(`${prefix}\nUsage:
22
+ stasis-core 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] [--fs=(sync|async)] [--resources=ext,ext] path/to/file.js ...
23
+ stasis-core prune [path/to/project]
24
+ `.trim())
25
+ process.exit(1)
26
+ }
27
+
28
+ function setEnv(name, value) {
29
+ const env = process.env[name]
30
+ if (env && env !== value) throw new Error(`env conflict: ${name}="${env}", effective: "${value}"`)
31
+ process.env[name] = value === undefined ? '' : value
32
+ }
33
+
34
+ const command = argv.shift()
35
+
36
+ if (command === '-v' || command === '--version') {
37
+ console.log(`v${pkg.version}`)
38
+ process.exit(0)
39
+ } else if (command === 'run') {
40
+ const flags = []
41
+ const valueFlags = new Set(['--bundle', '--bundle-file', '--resources-bundle-file', '--lock', '--resources'])
42
+ while (argv.length > 0 && (argv[0].startsWith('-') || valueFlags.has(flags.at(-1)))) {
43
+ flags.push(argv.shift())
44
+ }
45
+
46
+ const options = {
47
+ lock: { type: 'string', default: 'none' },
48
+ bundle: { type: 'string', default: 'none' },
49
+ 'bundle-file': { type: 'string' },
50
+ 'resources-bundle-file': { type: 'string' },
51
+ debug: { type: 'boolean' },
52
+ dependencies: { type: 'boolean' },
53
+ 'child-process': { type: 'boolean' },
54
+ fs: { type: 'string' },
55
+ resources: { type: 'string' },
56
+ }
57
+
58
+ let values
59
+ try {
60
+ ({ values } = parseArgs({ args: flags, options }))
61
+ } catch (cause) {
62
+ usage(`Error: ${cause.message}`)
63
+ }
64
+ if (argv.length === 0) usage('Nothing to run: no path to file given')
65
+ if (!['none', 'ignore', 'add', 'replace', 'frozen'].includes(values.lock)) usage('Error: invalid --lock value')
66
+ const lock = values.lock
67
+ const scope = values.dependencies ? 'node_modules' : 'full'
68
+ const bundle = values.bundle
69
+ const bundleFile = values['bundle-file'] ? resolve(values['bundle-file']) : ''
70
+ const resourcesBundleFile = values['resources-bundle-file'] ? resolve(values['resources-bundle-file']) : ''
71
+ const debug = values.debug ? '1' : ''
72
+ if (!['none', 'ignore', 'add', 'replace', 'load', 'frozen'].includes(bundle)) usage('Error: invalid --bundle value')
73
+ if (bundleFile && bundle === 'none') usage('Error: --bundle-file requires --bundle=(add|replace|load|frozen|ignore)')
74
+ // Unlike --bundle-file (which is inert-but-harmless under --bundle=ignore, so Config allows
75
+ // it), --resources-bundle-file needs an active bundle: Config rejects bundle=none AND ignore
76
+ // (resourcesBundleFile requires an active bundle mode). Front-run that with a clean usage error.
77
+ if (resourcesBundleFile && (bundle === 'none' || bundle === 'ignore')) usage('Error: --resources-bundle-file requires --bundle=(add|replace|load|frozen)')
78
+ if (bundle === 'load' && lock !== 'frozen' && lock !== 'none' && lock !== 'ignore') usage('Error: --bundle=load is incompatible with --lock=(add|replace)')
79
+ if (lock === 'none' && bundle === 'none') usage('Error: stasis needs a lockfile or a bundle: set --lock or --bundle')
80
+ // --fs monkey-patches the fs readers (readFileSync/readdirSync + lstatSync/statSync)
81
+ // to capture them into the bundle (add|replace) or serve them from it (load); nothing
82
+ // to record/read without one. The mode argument is required: `sync` patches the sync
83
+ // readers, `async` adds their async (callback + fs.promises) counterparts on top.
84
+ if (values.fs !== undefined && !['sync', 'async'].includes(values.fs)) usage("Error: --fs must be 'sync' or 'async'")
85
+ if (values.fs !== undefined && !['add', 'replace', 'load'].includes(bundle)) usage('Error: --fs requires --bundle=(add|replace|load)')
86
+ const captureFs = values.fs ?? ''
87
+ // --resources: comma-separated extension/filename allowlist for `--fs` resource captures
88
+ // (e.g. png,svg,LICENSE). The child's Config validates each entry via parseResourcesOption.
89
+ const resources = values.resources ?? ''
90
+ // --child-process: forward forked-child (e.g. Metro transform worker) capture to the root
91
+ // via per-pid shards. Opt-in -- it stands up a process-coordination channel, off by default.
92
+ const childProcess = values['child-process'] ? '1' : ''
93
+ console.warn('[stasis-core] Running stasis with config:', { lock, scope, bundle, ...(bundleFile && { bundleFile }), ...(resourcesBundleFile && { resourcesBundleFile }), ...(childProcess && { childProcess: true }), ...(values.fs && { fs: values.fs }), ...(resources && { resources }) })
94
+ if (debug) console.warn(`[stasis-core] Warning: stasis debug mode active`)
95
+ setEnv('EXODUS_STASIS_LOCK', lock)
96
+ setEnv('EXODUS_STASIS_SCOPE', scope)
97
+ setEnv('EXODUS_STASIS_BUNDLE', bundle)
98
+ setEnv('EXODUS_STASIS_BUNDLE_FILE', bundleFile)
99
+ setEnv('EXODUS_STASIS_RESOURCES_BUNDLE_FILE', resourcesBundleFile)
100
+ setEnv('EXODUS_STASIS_DEBUG', debug)
101
+ setEnv('EXODUS_STASIS_CHILD_PROCESS', childProcess)
102
+ setEnv('EXODUS_STASIS_FS', captureFs)
103
+ setEnv('EXODUS_STASIS_RESOURCES', resources)
104
+ const nodeArgs = ['--import', import.meta.resolve('../src/loader.js')]
105
+ const child = spawn(process.execPath, [...nodeArgs, ...argv], { stdio: 'inherit' })
106
+ const [code] = await once(child, 'close')
107
+ process.exitCode = code
108
+ } else if (command === 'prune') {
109
+ if (argv.length > 1) usage('Error: prune takes at most one path argument')
110
+ const root = argv[0] ? resolve(argv[0]) : process.cwd()
111
+ const { prune } = await import('../src/prune.js')
112
+ const { removed, validated, minimized } = prune({ root })
113
+ console.warn(`[stasis-core] prune: validated ${validated.length} file(s), removed ${removed.length} file(s), minimized ${minimized.length} package.json file(s)`)
114
+ } else {
115
+ usage()
116
+ }
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@exodus/stasis-core",
3
+ "version": "1.0.0-beta.0",
4
+ "description": "Zero-dependency stasis runtime",
5
+ "type": "module",
6
+ "exports": {
7
+ "./loader": "./src/loader.js",
8
+ "./hooks": "./src/hooks.js",
9
+ "./state": "./src/state.js",
10
+ "./config": "./src/config.js",
11
+ "./bundle": "./src/bundle.js",
12
+ "./lockfile": "./src/lockfile.js",
13
+ "./util": "./src/util.js",
14
+ "./brotli": "./src/brotli.js",
15
+ "./state-util": "./src/state-util.js",
16
+ "./prune": "./src/prune.js"
17
+ },
18
+ "files": [
19
+ "bin/stasis-core.js",
20
+ "src/brotli.js",
21
+ "src/bundle.js",
22
+ "src/config.js",
23
+ "src/fs.js",
24
+ "src/hooks.js",
25
+ "src/loader.js",
26
+ "src/lockfile.js",
27
+ "src/package.cjs",
28
+ "src/prune.js",
29
+ "src/state.js",
30
+ "src/state-util.js",
31
+ "src/util.js"
32
+ ],
33
+ "engines": {
34
+ "node": ">=24.14.0"
35
+ },
36
+ "bin": {
37
+ "stasis-core": "bin/stasis-core.js"
38
+ },
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/ExodusOSS/stasis.git",
42
+ "directory": "stasis-core"
43
+ },
44
+ "author": "Exodus Movement, Inc.",
45
+ "license": "MIT",
46
+ "bugs": {
47
+ "url": "https://github.com/ExodusOSS/stasis/issues"
48
+ },
49
+ "homepage": "https://github.com/ExodusOSS/stasis#readme"
50
+ }
package/src/brotli.js ADDED
@@ -0,0 +1,21 @@
1
+ import { constants as zlibConstants } from 'node:zlib'
2
+
3
+ import { assert } from './util.js'
4
+
5
+ // Brotli's default quality is 11 (max) and the encoder is superlinear in input
6
+ // size, so on a multi-MB source bundle it dominates write time. Tests that
7
+ // bundle real-world dependency trees can override this via the env var to keep
8
+ // runs fast; the output is still a valid .br at any quality. Production code
9
+ // pays the default cost in exchange for the best ratio.
10
+ //
11
+ // Kept out of `util.js` so that importing the generic helpers there (`sortPaths`,
12
+ // `assertRealPathWithinBase`, …) doesn't transitively load `node:zlib`. Only the
13
+ // code that actually compresses a bundle (`state.js`, `stasis bundle`) reaches
14
+ // for this, and that code already imports zlib directly.
15
+ export function brotliOptions() {
16
+ const raw = process.env.EXODUS_STASIS_BROTLI_QUALITY
17
+ if (!raw) return undefined
18
+ const n = Number(raw)
19
+ assert(Number.isInteger(n) && n >= 0 && n <= 11, `EXODUS_STASIS_BROTLI_QUALITY must be an integer 0..11, got ${raw}`)
20
+ return { params: { [zlibConstants.BROTLI_PARAM_QUALITY]: n } }
21
+ }
package/src/bundle.js ADDED
@@ -0,0 +1,256 @@
1
+ import {
2
+ KNOWN_FORMATS,
3
+ assert,
4
+ fileMapToObject,
5
+ fileSetToObject,
6
+ fromEntries,
7
+ isPlainObject,
8
+ moduleFileKey,
9
+ objectToMaps,
10
+ posixPathEscapes,
11
+ sortPaths,
12
+ splitNodeModulesPath,
13
+ } from './util.js'
14
+
15
+ const VERSION = 1
16
+ const LEGACY_VERSION = 0
17
+
18
+ const normalize = ({ name, version, ecosystem, files }) => {
19
+ // `ecosystem` (when present) names the package ecosystem a dependency came from
20
+ // (`npm`, `composer`, `soldeer`); the workspace/top-level buckets omit it.
21
+ assert(ecosystem === undefined || typeof ecosystem === 'string')
22
+ return { name, version, ...(ecosystem === undefined ? {} : { ecosystem }), files: fromEntries(Object.entries(files)) }
23
+ }
24
+
25
+ const inferModuleDir = (path) =>
26
+ splitNodeModulesPath(path) ?? { dir: '.', rel: path, name: null }
27
+
28
+ // Bundle handles the JSON shape of stasis.code.br; callers (State) are responsible
29
+ // for the brotli wrapper around the JSON text. One unified shape carries both code
30
+ // and resources, distinguished per file by `formats[file]` ('resource' = raw UTF-8
31
+ // payload, 'resource:base64' = base64-encoded; everything else is code). On-disk
32
+ // version:
33
+ // v0 — legacy flat layout: top-level `sources` keyed by project-relative path.
34
+ // No entries / modules / formats / imports.
35
+ // v1 — current layout, mirrors stasis.lock.json: per-package buckets under
36
+ // `sources` (workspace) and `modules` (node_modules) with name+version+files,
37
+ // plus `entries`, `formats`, and `imports`.
38
+ // `Bundle.parse` accepts both; offline tooling (stasis extract / diff / audit /
39
+ // sbom) reads v0 -- paths are regrouped by package dir via `inferModuleDir`
40
+ // (best-effort, last-wins); name/version stay null since v0 records neither,
41
+ // which State uses as a marker to skip metadata cross-checks. `stasis run`
42
+ // refuses v0 -- see State's load path. We always serialize v1.
43
+ export class Bundle {
44
+ static VERSION = VERSION
45
+
46
+ // The on-disk version this instance represents. Defaults to VERSION; parse*
47
+ // sets it to whatever the file declared (LEGACY_VERSION for v0 input).
48
+ // Serialization always writes the current VERSION regardless — loading v0 and
49
+ // re-saving promotes the bundle to v1.
50
+ version = VERSION
51
+ config
52
+ entries
53
+ modules
54
+ formats
55
+ imports
56
+ // Informational only (NOT attested): maps each consumer that recorded a bundled file --
57
+ // 'run' (the loader/CLI), 'StasisWebpack', 'StasisMetro', etc. -- to the files it contributed.
58
+ // Present only when a single bundle had MORE THAN ONE consumer (e.g. `run` plus a plugin sharing
59
+ // the same bundleFile); a single-consumer bundle omits it. Never consulted for verification.
60
+ reason
61
+
62
+ constructor({ config = { scope: 'full' }, entries, modules, formats, imports, reason, version = VERSION } = {}) {
63
+ assert([LEGACY_VERSION, VERSION].includes(version))
64
+ assert(['node_modules', 'full'].includes(config.scope))
65
+ this.version = version
66
+ this.config = config
67
+ this.entries = entries ?? new Set()
68
+ this.modules = modules ?? new Map()
69
+ this.formats = formats ?? new Map()
70
+ this.imports = imports ?? new Map()
71
+ this.reason = reason
72
+ }
73
+
74
+ // Flat project-relative view of file contents collected from this.modules.
75
+ // Per-file encoding is signalled by `formats[file]`: 'resource:base64' is a
76
+ // base64 string, everything else (including 'resource' and 'directory') is a
77
+ // raw UTF-8 string.
78
+ get sources() {
79
+ const m = new Map()
80
+ for (const [dir, { files }] of this.modules) {
81
+ for (const [rel, content] of Object.entries(files)) {
82
+ m.set(moduleFileKey(dir, rel), content)
83
+ }
84
+ }
85
+ return m
86
+ }
87
+
88
+ // True for the resource-like, non-executable payload formats. Their bundle
89
+ // content is a raw UTF-8 string ('resource', and 'directory' — a JSON-serialized
90
+ // `fs.readdirSync` listing) or a base64 blob ('resource:base64'). State stores
91
+ // all three in `this.resources` (vs `this.sources` for code) and the loader's
92
+ // executable allowlist rejects them, so this is the single "is this a code file?"
93
+ // discriminator. Only 'resource:base64' is base64-decoded; the others are raw.
94
+ static isResourceFormat(format) {
95
+ return format === 'resource' || format === 'resource:base64' || format === 'directory'
96
+ }
97
+
98
+ // One parser for the unified shape (and legacy v0 code bundles). Resources are just
99
+ // files tagged 'resource'/'resource:base64' in `formats`; State splits them back out
100
+ // by consulting the formats map.
101
+ static parse(text) {
102
+ const json = JSON.parse(text)
103
+ assert(json.version === VERSION || json.version === LEGACY_VERSION)
104
+ assert(['node_modules', 'full'].includes(json.config?.scope))
105
+ assert(isPlainObject(json.formats))
106
+ assert(isPlainObject(json.imports))
107
+
108
+ // Validate `formats` early so downstream branches (hasCode, etc.) can consult
109
+ // the typed Map instead of the raw `json.formats` object -- a missing key like
110
+ // `__proto__` would otherwise short-circuit on the prototype, and an unknown
111
+ // tag would only surface late at a string compare.
112
+ const formats = new Map()
113
+ for (const [file, format] of Object.entries(json.formats)) {
114
+ assert(!posixPathEscapes(file))
115
+ assert(KNOWN_FORMATS.has(format), `unknown format '${format}' for ${file}`)
116
+ formats.set(file, format)
117
+ }
118
+
119
+ const modules = new Map()
120
+ let entries = new Set()
121
+
122
+ if (json.version === VERSION) {
123
+ const full = json.config.scope === 'full'
124
+ if (json.modules !== undefined) {
125
+ assert(typeof json.modules === 'object' && json.modules !== null)
126
+ for (const [dir, info] of Object.entries(json.modules)) {
127
+ assert(dir.includes('node_modules'))
128
+ assert(!dir.startsWith('..'))
129
+ assert(info?.name && info.version && info.files)
130
+ modules.set(dir, normalize(info))
131
+ }
132
+ }
133
+ if (full) {
134
+ assert(json.sources && typeof json.sources === 'object')
135
+ for (const [dir, info] of Object.entries(json.sources)) {
136
+ assert(!dir.includes('node_modules'))
137
+ assert(!dir.startsWith('..'))
138
+ assert(info?.name && info.version && info.files)
139
+ modules.set(dir, normalize(info))
140
+ }
141
+ // A bundle that carries code in full scope must declare at least one entry:
142
+ // empty entries would let `state.assertEntry` skip its check (it short-circuits
143
+ // on entries.size === 0 for v0+no-lockfile compatibility), which a tampered
144
+ // bundle could exploit. A resources-only bundle has no code files and thus no
145
+ // entries -- allowed, since there is nothing for assertEntry to guard.
146
+ let hasCode = false
147
+ for (const [dir, { files }] of modules) {
148
+ for (const rel of Object.keys(files)) {
149
+ // moduleFileKey (not `${dir}/${rel}`): a `directory` capture at a module
150
+ // root keys at rel === '', whose trailing-slash join would miss its
151
+ // resource-format lookup and miscount the listing as code here.
152
+ const fp = moduleFileKey(dir, rel)
153
+ if (!Bundle.isResourceFormat(formats.get(fp))) { hasCode = true; break }
154
+ }
155
+ if (hasCode) break
156
+ }
157
+ if (hasCode) {
158
+ assert(Array.isArray(json.entries) && json.entries.length > 0,
159
+ 'bundle carrying code in scope=full must have at least one entry')
160
+ entries = new Set(json.entries)
161
+ } else {
162
+ assert(json.entries === undefined || (Array.isArray(json.entries) && json.entries.length === 0))
163
+ }
164
+ } else {
165
+ assert(json.entries === undefined)
166
+ assert(json.sources === undefined)
167
+ }
168
+ for (const [, { files }] of modules) {
169
+ for (const rel of Object.keys(files)) assert(!rel.startsWith('..'))
170
+ }
171
+ } else {
172
+ // v0 legacy: flat sources at top level, regrouped by inferred module dir.
173
+ assert(json.sources)
174
+ for (const [path, content] of Object.entries(json.sources)) {
175
+ assert(!path.startsWith('..'))
176
+ const { dir, rel, name } = inferModuleDir(path)
177
+ assert(!dir.startsWith('..') && !rel.startsWith('..'))
178
+ if (!modules.has(dir)) modules.set(dir, { name, version: null, files: Object.create(null) })
179
+ modules.get(dir).files[rel] = content
180
+ }
181
+ }
182
+
183
+ // Resolution edges name project-relative files on both sides; getImport
184
+ // resolves the target against the project root, so a path that escapes the
185
+ // root (including a mid-path `a/../../x`) must be rejected here rather than
186
+ // pulling an out-of-tree file in at load time.
187
+ const imports = objectToMaps(json.imports)
188
+ // An edge target is normally a file string. A `stasis bundle --metro` edge that
189
+ // resolves differently per platform is instead a { platform: file } map (which
190
+ // objectToMaps has turned into a Map). Validate both shapes; reject anything else
191
+ // (e.g. a deeper nesting) so a tampered artifact fails closed at the schema edge.
192
+ const assertTarget = (target) => {
193
+ if (typeof target === 'string') {
194
+ assert(!posixPathEscapes(target))
195
+ return
196
+ }
197
+ assert(target instanceof Map && target.size > 0, 'import target must be a file or a non-empty {platform: file} map')
198
+ for (const [platform, file] of target) {
199
+ assert(typeof platform === 'string' && platform.length > 0 && !platform.includes('/'), `invalid platform key '${platform}'`)
200
+ assert(typeof file === 'string')
201
+ assert(!posixPathEscapes(file))
202
+ }
203
+ }
204
+ for (const [, byParent] of imports) {
205
+ assert(byParent instanceof Map)
206
+ for (const [parent, specifiers] of byParent) {
207
+ assert(!posixPathEscapes(parent))
208
+ assert(specifiers instanceof Map)
209
+ for (const [, target] of specifiers) assertTarget(target)
210
+ }
211
+ }
212
+
213
+ return new Bundle({
214
+ version: json.version,
215
+ config: json.config,
216
+ entries,
217
+ modules,
218
+ formats,
219
+ imports,
220
+ reason: isPlainObject(json.reason) ? json.reason : undefined, // informational, preserved for round-trip
221
+ })
222
+ }
223
+
224
+ #groupedFromModules() {
225
+ const moduleEntries = []
226
+ const sourceEntries = []
227
+ for (const [dir, { name, version, ecosystem, files }] of this.modules) {
228
+ if (Object.keys(files).length === 0) continue
229
+ const inNodeModules = dir.includes('node_modules')
230
+ if (inNodeModules) assert(name && version && files)
231
+ const sorted = fromEntries(Object.entries(files).toSorted((a, b) => sortPaths(a[0], b[0])))
232
+ const target = inNodeModules ? moduleEntries : sourceEntries
233
+ target.push([dir, { name, version, ...(ecosystem === undefined ? {} : { ecosystem }), files: sorted }])
234
+ }
235
+ moduleEntries.sort((a, b) => sortPaths(a[0], b[0]))
236
+ sourceEntries.sort((a, b) => sortPaths(a[0], b[0]))
237
+ return { modules: fromEntries(moduleEntries), sources: fromEntries(sourceEntries) }
238
+ }
239
+
240
+ // One unified on-disk shape for code AND resources. A file is a resource when its
241
+ // `formats` entry is 'resource' (raw UTF-8 content) or 'resource:base64' (binary,
242
+ // base64-encoded); every other format is code carrying a raw UTF-8 source string.
243
+ // A single bundle can therefore hold both; readers split by consulting `formats`.
244
+ serialize() {
245
+ const entries = fileSetToObject(this.entries)
246
+ const { modules, sources } = this.#groupedFromModules()
247
+ const formats = fileMapToObject(this.formats)
248
+ const imports = fileMapToObject(this.imports)
249
+ const data = { version: VERSION, config: this.config }
250
+ if (this.config.scope === 'full') Object.assign(data, { entries, sources })
251
+ Object.assign(data, { modules, formats, imports })
252
+ // Informational provenance, last: only present when set (more than one consumer).
253
+ if (this.reason !== undefined) data.reason = this.reason
254
+ return JSON.stringify(data, undefined, 2)
255
+ }
256
+ }