@exodus/stasis 1.0.0-beta.10 → 1.0.0-beta.12
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/bin/stasis.js +27 -196
- package/package.json +9 -7
- package/src/audit.js +59 -29
- package/src/babel.js +122 -9
- package/src/cmd/bundle-options.js +322 -0
- package/src/cmd/bundle.js +418 -160
- package/src/define.js +276 -0
- package/src/metro-resolver.js +6 -7
- package/src/metro-transformer.js +3 -4
- package/src/resolve-fields.js +271 -5
- package/src/scan.js +20 -7
- package/src/vfs-bundle/github.js +6 -4
- package/src/why.js +5 -3
package/src/babel.js
CHANGED
|
@@ -17,12 +17,17 @@
|
|
|
17
17
|
// no esbuild pre-transform, Babel sees the original source exactly as the project's own
|
|
18
18
|
// toolchain (e.g. Metro) would hand it over.
|
|
19
19
|
//
|
|
20
|
+
// `stasis bundle --metro --babel` takes only the import aliases from that config (see
|
|
21
|
+
// createBabelAliases): the scan still reads each file's own source. `--babel-aliases` takes the same
|
|
22
|
+
// aliases from a JSON file instead, mapped here as the plugin maps them (createAliases), so nothing
|
|
23
|
+
// of the project's runs.
|
|
24
|
+
//
|
|
20
25
|
// Babel is the PROJECT's dev dependency, not stasis's: @babel/core (and, for hermes, the
|
|
21
26
|
// two transform plugins) resolve from the project directory, so the project pins its own
|
|
22
27
|
// Babel toolchain and config semantics.
|
|
23
28
|
import { existsSync } from 'node:fs'
|
|
24
29
|
import { createRequire } from 'node:module'
|
|
25
|
-
import { join } from 'node:path'
|
|
30
|
+
import { dirname, join, relative, resolve } from 'node:path'
|
|
26
31
|
|
|
27
32
|
const require = createRequire(import.meta.url)
|
|
28
33
|
|
|
@@ -61,13 +66,13 @@ const TRANSFORMABLE_LOADERS = new Set(['js', 'ts', 'jsx', 'tsx'])
|
|
|
61
66
|
// Resolved up front on the main thread so a missing install fails with instructions, not a
|
|
62
67
|
// worker crash mid-build. Returns absolute paths: the worker loads @babel/core by path, and
|
|
63
68
|
// plugin paths bypass Babel's own name resolution (which would look in the wrong dir).
|
|
64
|
-
function resolveFromProject(projectDir, deps, flag) {
|
|
69
|
+
function resolveFromProject(projectDir, deps, flag, command = 'stasis build') {
|
|
65
70
|
const projectRequire = createRequire(join(projectDir, 'noop.js'))
|
|
66
71
|
try {
|
|
67
72
|
return deps.map((dep) => projectRequire.resolve(dep))
|
|
68
73
|
} catch (cause) {
|
|
69
74
|
throw new Error(
|
|
70
|
-
|
|
75
|
+
`${command}: ${flag} needs ${deps.join(', ')} installed in the project ` +
|
|
71
76
|
`(e.g. \`npm i -D ${deps.join(' ')}\`); resolution failed from ${projectDir}`,
|
|
72
77
|
{ cause }
|
|
73
78
|
)
|
|
@@ -108,12 +113,7 @@ export function createHermesTransform({ projectDir, esbuild }) {
|
|
|
108
113
|
// the original source. Its output must be esbuild-parseable js -- a config that leaves TS/JSX
|
|
109
114
|
// in place fails the build in Babel or esbuild, which is the project's config to fix.
|
|
110
115
|
export function createBabelConfigTransform({ projectDir }) {
|
|
111
|
-
const configFile =
|
|
112
|
-
.map((name) => join(projectDir, name))
|
|
113
|
-
.find((file) => existsSync(file))
|
|
114
|
-
if (!configFile) {
|
|
115
|
-
throw new Error(`stasis build: --babel found no babel.config.(js|cjs|mjs|json) in ${projectDir}`)
|
|
116
|
-
}
|
|
116
|
+
const configFile = findBabelConfig(projectDir, 'stasis build')
|
|
117
117
|
const [babelPath] = resolveFromProject(projectDir, ['@babel/core'], '--babel')
|
|
118
118
|
const { transformAsync } = require('./babel-worker.cjs')
|
|
119
119
|
return async (source, { path, loader }) => {
|
|
@@ -129,3 +129,116 @@ export function createBabelConfigTransform({ projectDir }) {
|
|
|
129
129
|
return { contents: result.code, loader: 'js' }
|
|
130
130
|
}
|
|
131
131
|
}
|
|
132
|
+
|
|
133
|
+
// The project's babel.config.(js|cjs|mjs|json), the one --babel takes.
|
|
134
|
+
function findBabelConfig(projectDir, command) {
|
|
135
|
+
const configFile = ['babel.config.js', 'babel.config.cjs', 'babel.config.mjs', 'babel.config.json']
|
|
136
|
+
.map((name) => join(projectDir, name))
|
|
137
|
+
.find((file) => existsSync(file))
|
|
138
|
+
if (!configFile) {
|
|
139
|
+
throw new Error(`${command}: --babel found no babel.config.(js|cjs|mjs|json) in ${projectDir}`)
|
|
140
|
+
}
|
|
141
|
+
return configFile
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// The file a plugin item names babel-plugin-module-resolver by resolves into this.
|
|
145
|
+
const MODULE_RESOLVER = /[\\/]node_modules[\\/]babel-plugin-module-resolver[\\/]/u
|
|
146
|
+
|
|
147
|
+
// --babel for `stasis bundle --metro`: the import aliases babel-plugin-module-resolver applies to
|
|
148
|
+
// each file under the project's babel.config.*, loaded as Metro's transformer loads it (its `metro`
|
|
149
|
+
// caller, for `platform`) -- the config is project code, run here. The plugin's own resolvePath (or
|
|
150
|
+
// the config's custom one) maps each specifier, its `cwd` the project's where the config sets none,
|
|
151
|
+
// as Metro started there has it. Every instance the config lists, by name or as a value (`require`d
|
|
152
|
+
// or imported), counts, in order; one a preset adds doesn't.
|
|
153
|
+
// -> (file, specifier) => the specifier the plugin rewrites it to, else null
|
|
154
|
+
export function createBabelAliases({ projectDir, platform }) {
|
|
155
|
+
const configFile = findBabelConfig(projectDir, 'stasis bundle')
|
|
156
|
+
const [babelPath] = resolveFromProject(projectDir, ['@babel/core'], '--babel', 'stasis bundle')
|
|
157
|
+
const babel = require(babelPath)
|
|
158
|
+
const caller = { name: 'metro', bundler: 'metro', platform }
|
|
159
|
+
// The project's own copy, which a config passing the plugin as a value passes; none where the
|
|
160
|
+
// project installs none.
|
|
161
|
+
let projectPlugin
|
|
162
|
+
try {
|
|
163
|
+
projectPlugin = require(createRequire(join(projectDir, 'noop.js')).resolve('babel-plugin-module-resolver'))
|
|
164
|
+
} catch {
|
|
165
|
+
projectPlugin = null
|
|
166
|
+
}
|
|
167
|
+
// The module of a module-resolver plugin item, else null.
|
|
168
|
+
const moduleOf = (plugin) => {
|
|
169
|
+
const resolved = plugin.file?.resolved
|
|
170
|
+
if (resolved !== undefined) return MODULE_RESOLVER.test(resolved) ? require(resolved) : null
|
|
171
|
+
return plugin.value === projectPlugin?.default ? projectPlugin : null
|
|
172
|
+
}
|
|
173
|
+
// file -> [{ resolvePath, options }] of the module-resolver instances its config applies.
|
|
174
|
+
const byFile = new Map()
|
|
175
|
+
const aliasingOf = (file) => {
|
|
176
|
+
if (byFile.has(file)) return byFile.get(file)
|
|
177
|
+
let partial
|
|
178
|
+
try {
|
|
179
|
+
partial = babel.loadPartialConfig({ cwd: projectDir, root: projectDir, configFile, filename: file, caller })
|
|
180
|
+
} catch (cause) {
|
|
181
|
+
throw new Error(`stasis bundle: --babel could not load ${configFile} for ${file}`, { cause })
|
|
182
|
+
}
|
|
183
|
+
const instances = []
|
|
184
|
+
// No partial config: the config ignores the file.
|
|
185
|
+
for (const plugin of partial?.options.plugins ?? []) {
|
|
186
|
+
const module = moduleOf(plugin)
|
|
187
|
+
if (module === null) continue
|
|
188
|
+
const options = { cwd: projectDir, ...plugin.options }
|
|
189
|
+
instances.push({ resolvePath: typeof options.resolvePath === 'function' ? options.resolvePath : module.resolvePath, options })
|
|
190
|
+
}
|
|
191
|
+
byFile.set(file, instances)
|
|
192
|
+
return instances
|
|
193
|
+
}
|
|
194
|
+
return (file, specifier) => {
|
|
195
|
+
for (const { resolvePath, options } of aliasingOf(file)) {
|
|
196
|
+
const mapped = resolvePath(specifier, file, options)
|
|
197
|
+
// The first instance mapping it wins: the plugin marks the path it writes resolved, which
|
|
198
|
+
// later instances leave as it is.
|
|
199
|
+
if (mapped) return typeof mapped === 'string' && mapped !== specifier ? mapped : null
|
|
200
|
+
}
|
|
201
|
+
return null
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// babel-plugin-module-resolver's path tests, as it writes them.
|
|
206
|
+
const isRelativePath = (path) => /^\.?\.\//u.test(path)
|
|
207
|
+
const toLocalPath = (path) => {
|
|
208
|
+
const local = path.replace(/\/index$/u, '')
|
|
209
|
+
return isRelativePath(local) ? local : `./${local}`
|
|
210
|
+
}
|
|
211
|
+
const escapeRegExp = (string) => string.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')
|
|
212
|
+
|
|
213
|
+
// --babel-aliases for `stasis bundle --metro`: the import aliases of `alias`, babel-plugin-module-resolver's
|
|
214
|
+
// `alias` option as data (a JSON file's), mapped as the plugin maps them with `cwd` its own, as
|
|
215
|
+
// createBabelAliases has it: a key starting with `^` or ending with `$` is a regular expression whose
|
|
216
|
+
// groups the value's `\N` take, any other matches the specifier it is or one it starts with and `/`,
|
|
217
|
+
// whose rest the value keeps; the first key matching wins. A value starting with `./` or `../` is a
|
|
218
|
+
// path from `cwd`, written relative to the importing file; any other is the specifier as it is.
|
|
219
|
+
// -> (file, specifier) => the specifier it rewrites it to, else null
|
|
220
|
+
export function createAliases(alias, cwd) {
|
|
221
|
+
const matchers = Object.entries(alias).map(([key, value]) => {
|
|
222
|
+
// As the plugin builds them: a key's own pattern, unflagged (`u` would refuse some it takes).
|
|
223
|
+
if (!key.startsWith('^') && !key.endsWith('$')) return [new RegExp(`^${escapeRegExp(key)}(/.*|)$`), ([, rest]) => `${value}${rest}`]
|
|
224
|
+
const parts = value.split('\\\\')
|
|
225
|
+
return [new RegExp(key), (groups) => parts.map((part) => part.replace(/\\\d+/gu, (n) => groups[n.slice(1)] || '')).join('\\')]
|
|
226
|
+
})
|
|
227
|
+
return (file, specifier) => {
|
|
228
|
+
if (isRelativePath(specifier)) return null
|
|
229
|
+
for (const [regExp, substitute] of matchers) {
|
|
230
|
+
const groups = regExp.exec(specifier)
|
|
231
|
+
if (groups === null) continue
|
|
232
|
+
return rewrite(file, specifier, substitute(groups), cwd)
|
|
233
|
+
}
|
|
234
|
+
return null
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// `mapped`, the alias `specifier` from `file` maps to, as the plugin writes it: none where empty, a
|
|
239
|
+
// relative one (`./`, `../`) a path from `cwd` written relative to `file`, any other as it is.
|
|
240
|
+
function rewrite(file, specifier, mapped, cwd) {
|
|
241
|
+
if (!mapped) return null
|
|
242
|
+
const rewritten = isRelativePath(mapped) ? toLocalPath(relative(dirname(file), resolve(cwd, mapped)).replace(/\\/gu, '/')) : mapped
|
|
243
|
+
return rewritten === specifier ? null : rewritten
|
|
244
|
+
}
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import { isAbsolute, relative, resolve } from 'node:path'
|
|
2
|
+
|
|
3
|
+
import { diskHost } from '@exodus/stasis-core/host'
|
|
4
|
+
import { readFileSyncMaybe } from '@exodus/stasis-core/state-util'
|
|
5
|
+
import { isPlainObject, parseBrotliQuality, parseResourcesOption, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
|
|
6
|
+
import { parseFeatureList } from '../loaders/cargo.js'
|
|
7
|
+
import { parseDefineFlags } from '../define.js'
|
|
8
|
+
import { directoryEntryError, isSolidityEntry } from './bundle.js'
|
|
9
|
+
|
|
10
|
+
const CONFIG_FILE = 'stasis.config.json'
|
|
11
|
+
|
|
12
|
+
// `stasis bundle`'s flags, as parseArgs takes them, and those taking their value as the next argument.
|
|
13
|
+
export const BUNDLE_FLAGS = {
|
|
14
|
+
mapping: { type: 'string' },
|
|
15
|
+
manifests: { type: 'boolean' },
|
|
16
|
+
output: { type: 'string', short: 'o' },
|
|
17
|
+
scope: { type: 'string' },
|
|
18
|
+
lockfile: { type: 'string' },
|
|
19
|
+
conditions: { type: 'string' },
|
|
20
|
+
mainFields: { type: 'string' },
|
|
21
|
+
metro: { type: 'boolean' },
|
|
22
|
+
'metro-resolver': { type: 'boolean' },
|
|
23
|
+
babel: { type: 'boolean' },
|
|
24
|
+
'babel-aliases': { type: 'string' },
|
|
25
|
+
platforms: { type: 'string', multiple: true },
|
|
26
|
+
jsx: { type: 'boolean' },
|
|
27
|
+
flow: { type: 'boolean' },
|
|
28
|
+
typescript: { type: 'boolean' },
|
|
29
|
+
tsconfig: { type: 'string' },
|
|
30
|
+
resources: { type: 'string' },
|
|
31
|
+
'package-json': { type: 'boolean' },
|
|
32
|
+
define: { type: 'string', multiple: true },
|
|
33
|
+
cargo: { type: 'boolean' },
|
|
34
|
+
'cargo-features': { type: 'string', multiple: true },
|
|
35
|
+
'cargo-no-default-features': { type: 'boolean' },
|
|
36
|
+
'cargo-all-features': { type: 'boolean' },
|
|
37
|
+
'cargo-target': { type: 'string' },
|
|
38
|
+
'cargo-manifests': { type: 'boolean' },
|
|
39
|
+
'brotli-quality': { type: 'string' },
|
|
40
|
+
add: { type: 'boolean' },
|
|
41
|
+
}
|
|
42
|
+
export const BUNDLE_VALUE_FLAGS = ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--babel-aliases', '--platforms', '--resources', '--tsconfig', '--define', '--cargo-features', '--cargo-target', '--brotli-quality', '-o']
|
|
43
|
+
|
|
44
|
+
// The flags saying where and how the bundle is written. Every other one says how its entries are
|
|
45
|
+
// built, which stasis.config.json's `entries` sets per entry instead.
|
|
46
|
+
const OUTPUT_FLAGS = new Set(['output', 'lockfile', 'brotli-quality', 'add'])
|
|
47
|
+
// The entry flags taking a list (comma-separated, or repeated), which an entry's options may give as an array.
|
|
48
|
+
const LIST_FLAGS = new Set(['conditions', 'mainFields', 'platforms', 'resources', 'cargo-features'])
|
|
49
|
+
// The entry flags given once per value, which a comma doesn't separate (a define's JSON value may
|
|
50
|
+
// hold one): an entry's options give them as an array, or one as a string.
|
|
51
|
+
const REPEATED_FLAGS = new Set(['define'])
|
|
52
|
+
// The entry flags that run a program -> what they run. Set in stasis.config.json, they take effect
|
|
53
|
+
// only with the same flag given too (a value one, with the same value), as consent: the config can't
|
|
54
|
+
// make a bare `stasis bundle` run anything.
|
|
55
|
+
const CONSENT_FLAGS = new Map([
|
|
56
|
+
['babel', "the project's Babel config"],
|
|
57
|
+
['metro-resolver', "the project's metro-resolver"],
|
|
58
|
+
['flow', "the flow-remove-types the project installs (stasis's peer)"],
|
|
59
|
+
['cargo', "cargo, and what the project's .cargo/config.toml names"],
|
|
60
|
+
['cargo-target', 'rustc'],
|
|
61
|
+
])
|
|
62
|
+
// A flag as given: `--name`, or `--name=value` for one taking a value.
|
|
63
|
+
const flagText = (name, value) => (value === true ? `--${name}` : `--${name}=${value}`)
|
|
64
|
+
|
|
65
|
+
// `entry` as a path relative to `cwd` ('.' for cwd itself), or null where it lies out of it.
|
|
66
|
+
function entryKey(cwd, entry) {
|
|
67
|
+
const rel = relative(resolve(cwd), resolve(cwd, entry))
|
|
68
|
+
return relativeEscapes(rel) ? null : toPosix(rel) || '.'
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// The language `entries` share, one bundle being built from one: which of them they all are in.
|
|
72
|
+
function entriesLanguage(entries, cwd) {
|
|
73
|
+
const dirError = directoryEntryError(entries, cwd)
|
|
74
|
+
if (dirError !== null) throw new Error(dirError)
|
|
75
|
+
const lang = {
|
|
76
|
+
allSol: entries.every((f) => isSolidityEntry(f, cwd)),
|
|
77
|
+
allPhp: entries.every((f) => f.endsWith('.php')),
|
|
78
|
+
allJs: entries.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f)),
|
|
79
|
+
allBash: entries.every((f) => /\.(?:sh|bash)$/u.test(f)),
|
|
80
|
+
allRust: entries.every((f) => f.endsWith('.rs')),
|
|
81
|
+
}
|
|
82
|
+
if (!Object.values(lang).some(Boolean)) {
|
|
83
|
+
throw new 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')
|
|
84
|
+
}
|
|
85
|
+
return lang
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// bundleCommand's options for building `entries` (in `lang`, entriesLanguage's) from the parsed
|
|
89
|
+
// entry flags in `values`. A usage error throws.
|
|
90
|
+
function buildOptions(values, { allSol, allJs, allRust }) {
|
|
91
|
+
if (values.mapping && !allSol) throw new Error('--mapping is only valid for .sol bundles')
|
|
92
|
+
// --manifests: carry the Solidity build's description files (foundry.toml, remappings.txt, ...).
|
|
93
|
+
const manifests = Boolean(values.manifests)
|
|
94
|
+
if (manifests && !allSol) throw new Error('--manifests is only valid for .sol bundles')
|
|
95
|
+
// --cargo: take the Rust feature/dependency resolution from `cargo metadata` (runs cargo; opt-in).
|
|
96
|
+
const cargo = Boolean(values.cargo)
|
|
97
|
+
if (cargo && !allRust) throw new Error('--cargo is only valid for Rust bundles')
|
|
98
|
+
// --cargo-features / --cargo-no-default-features / --cargo-all-features: cargo's own feature flags
|
|
99
|
+
// for the entries' packages (`pkg/feat` targets one, or a dependency). --cargo-features is
|
|
100
|
+
// repeatable and/or comma-separated; parseFeatureList is the one splitter (the resolver reuses it).
|
|
101
|
+
const cargoFeatures = parseFeatureList(values['cargo-features'] ?? [])
|
|
102
|
+
if (values['cargo-features'] !== undefined && cargoFeatures.length === 0) {
|
|
103
|
+
throw new Error('--cargo-features must list at least one feature (e.g. --cargo-features=serde,app/tls)')
|
|
104
|
+
}
|
|
105
|
+
const cargoNoDefaultFeatures = Boolean(values['cargo-no-default-features'])
|
|
106
|
+
const cargoAllFeatures = Boolean(values['cargo-all-features'])
|
|
107
|
+
// --cargo-target=<triple|host>: the build's target, whose cfgs (from `rustc --print cfg`) decide
|
|
108
|
+
// `#[cfg(unix)]`-style code. A triple is letters, digits, `-`, `_` and `.` (`x86_64-unknown-linux-gnu`).
|
|
109
|
+
const cargoTarget = values['cargo-target'] ?? null
|
|
110
|
+
if (cargoTarget !== null && !/^[\w.-]+$/u.test(cargoTarget)) {
|
|
111
|
+
throw new Error('--cargo-target must be a target triple or "host" (e.g. --cargo-target=aarch64-apple-darwin)')
|
|
112
|
+
}
|
|
113
|
+
// --cargo-manifests: carry each bundled package's Cargo.toml and build script, the workspace
|
|
114
|
+
// Cargo.toml, Cargo.lock and .cargo/config.toml too (the Rust counterpart of --package-json).
|
|
115
|
+
const cargoManifests = Boolean(values['cargo-manifests'])
|
|
116
|
+
if (!allRust) {
|
|
117
|
+
const given = { 'cargo-features': cargoFeatures.length > 0, 'cargo-no-default-features': cargoNoDefaultFeatures, 'cargo-all-features': cargoAllFeatures, 'cargo-target': cargoTarget !== null, 'cargo-manifests': cargoManifests }
|
|
118
|
+
for (const [flag, on] of Object.entries(given)) if (on) throw new Error(`--${flag} is only valid for Rust bundles`)
|
|
119
|
+
}
|
|
120
|
+
if (values.scope && !allJs) throw new Error('--scope is only valid for JS bundles')
|
|
121
|
+
if (values.scope && !['node_modules', 'full'].includes(values.scope)) {
|
|
122
|
+
throw new Error('--scope must be node_modules or full')
|
|
123
|
+
}
|
|
124
|
+
// --mainFields/--metro always emit a full-scope bundle, so they'd silently ignore a narrower --scope.
|
|
125
|
+
if (values.scope !== undefined && values.scope !== 'full' && (values.mainFields !== undefined || values.metro)) {
|
|
126
|
+
throw new Error(`--scope=${values.scope} is not supported with --mainFields or --metro (they always build a full-scope bundle)`)
|
|
127
|
+
}
|
|
128
|
+
// --conditions: extra exports/imports resolution conditions merged onto Node's defaults;
|
|
129
|
+
// they don't honour legacy `mainFields` or platform suffixes (see --mainFields).
|
|
130
|
+
if (values.conditions !== undefined && !allJs) throw new Error('--conditions is only valid for JS bundles')
|
|
131
|
+
const conditions = values.conditions === undefined
|
|
132
|
+
? []
|
|
133
|
+
: values.conditions.split(',').map((s) => s.trim()).filter(Boolean)
|
|
134
|
+
if (values.conditions !== undefined && conditions.length === 0) {
|
|
135
|
+
throw new Error('--conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
|
|
136
|
+
}
|
|
137
|
+
// --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
|
|
138
|
+
if (values.flow && !allJs) throw new Error('--flow is only valid for JS bundles')
|
|
139
|
+
const flow = Boolean(values.flow)
|
|
140
|
+
// --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
|
|
141
|
+
// extensionless) lands on its on-disk TS source (./x.ts, .mts, .cts); an existing .js always wins.
|
|
142
|
+
if (values.typescript && !allJs) throw new Error('--typescript is only valid for JS bundles')
|
|
143
|
+
const typescript = Boolean(values.typescript)
|
|
144
|
+
// --tsconfig: the config whose compilerOptions.paths aliases --typescript honours (default: the
|
|
145
|
+
// tsconfig.json beside each importing file's package.json). Meaningless without --typescript.
|
|
146
|
+
if (values.tsconfig !== undefined && !typescript) throw new Error('--tsconfig is only valid with --typescript')
|
|
147
|
+
// --mainFields: legacy package entry fields (e.g. react-native,browser,main) for the non-exports resolver.
|
|
148
|
+
if (values.mainFields !== undefined && !allJs) throw new Error('--mainFields is only valid for JS bundles')
|
|
149
|
+
const mainFields = values.mainFields === undefined
|
|
150
|
+
? undefined
|
|
151
|
+
: values.mainFields.split(',').map((s) => s.trim()).filter(Boolean)
|
|
152
|
+
if (values.mainFields !== undefined && mainFields.length === 0) {
|
|
153
|
+
throw new Error('--mainFields must list at least one field (e.g. --mainFields=react-native,browser,main)')
|
|
154
|
+
}
|
|
155
|
+
// --metro: resolve like Metro/RN (its own conditions + mainFields, platform suffixes per
|
|
156
|
+
// --platforms target). --platforms is repeatable and/or comma-separated; the values union.
|
|
157
|
+
const metro = Boolean(values.metro)
|
|
158
|
+
// --metro-resolver: resolve through the project's own metro-resolver instead of the built-in
|
|
159
|
+
// approximation. Only meaningful alongside --metro (enforced below and in classifyEntries).
|
|
160
|
+
const metroResolver = Boolean(values['metro-resolver'])
|
|
161
|
+
const platforms = [...new Set((values.platforms ?? []).flatMap((p) => p.split(',')).map((s) => s.trim()).filter(Boolean))]
|
|
162
|
+
// A platform name becomes an edge key: reject '/' (parsers reject it) and '*' (reserved placeholder).
|
|
163
|
+
for (const p of platforms) {
|
|
164
|
+
if (p === '*' || p.includes('/')) throw new Error(`invalid --platforms value '${p}' (a platform name can't contain '/' or be '*')`)
|
|
165
|
+
}
|
|
166
|
+
if ((metro || platforms.length > 0) && !allJs) throw new Error('--metro is only valid for JS bundles')
|
|
167
|
+
// --jsx: parse React Native's JSX-in-.js source in the static scanner (off by default; oxc,
|
|
168
|
+
// like tsc, auto-enables JSX for .jsx/.tsx only). Orthogonal to the resolver, so it pairs with
|
|
169
|
+
// plain/--mainFields/--metro alike -- JS-only, since no other entry language is scanned.
|
|
170
|
+
const jsx = Boolean(values.jsx)
|
|
171
|
+
if (jsx && !allJs) throw new Error('--jsx is only valid for JS bundles')
|
|
172
|
+
// --package-json: fold each bundled module's package.json into the bundle. JS-only (only JS
|
|
173
|
+
// modules carry an npm package.json; the sol/php/bash/rust bucketizers have no such manifest).
|
|
174
|
+
const packageJSON = Boolean(values['package-json'])
|
|
175
|
+
if (packageJSON && !allJs) throw new Error('--package-json is only valid for JS bundles')
|
|
176
|
+
// --resources: comma-separated extension/filename allowlist for assets reached through the graph
|
|
177
|
+
// (e.g. --resources=png,svg). They're carried as resources instead of failing "can't carry" --
|
|
178
|
+
// for graphs that aren't fully loadable in JS (Metro consumes such assets). JS-only.
|
|
179
|
+
if (values.resources !== undefined && !allJs) throw new Error('--resources is only valid for JS bundles')
|
|
180
|
+
const resources = values.resources === undefined
|
|
181
|
+
? undefined
|
|
182
|
+
: values.resources.split(',').map((s) => s.trim()).filter(Boolean)
|
|
183
|
+
if (values.resources !== undefined && resources.length === 0) {
|
|
184
|
+
throw new Error('--resources must list at least one extension or filename (e.g. --resources=png,svg)')
|
|
185
|
+
}
|
|
186
|
+
parseResourcesOption('--resources', resources) // validate early for a clean usage error (code exts / bad chars rejected)
|
|
187
|
+
if (metro) {
|
|
188
|
+
if (conditions.length > 0) throw new Error("--conditions can't be combined with --metro (it sets its own conditions)")
|
|
189
|
+
if (mainFields !== undefined) throw new Error("--mainFields can't be combined with --metro (it sets its own mainFields)")
|
|
190
|
+
if (platforms.length === 0) throw new Error('--metro requires --platforms (e.g. --platforms=ios,android)')
|
|
191
|
+
} else if (platforms.length > 0) {
|
|
192
|
+
throw new Error('--platforms is only valid with --metro')
|
|
193
|
+
}
|
|
194
|
+
if (metroResolver && !metro) throw new Error('--metro-resolver is only valid with --metro')
|
|
195
|
+
// --babel: resolve through the import aliases (babel-plugin-module-resolver) of the project's
|
|
196
|
+
// babel.config.*, which Metro runs before it resolves. Runs that config, so opt-in; --metro only.
|
|
197
|
+
const babel = Boolean(values.babel)
|
|
198
|
+
if (babel && !metro) throw new Error('--babel is only valid with --metro')
|
|
199
|
+
// --babel-aliases: the same aliases from a JSON file of the project (module-resolver's `alias` option as
|
|
200
|
+
// data), which runs nothing, so stasis.config.json's entries may set it alone. --metro only.
|
|
201
|
+
if (values['babel-aliases'] !== undefined && !metro) throw new Error('--babel-aliases is only valid with --metro')
|
|
202
|
+
if (values['babel-aliases'] !== undefined && babel) throw new Error("--babel-aliases can't be combined with --babel (both set the import aliases)")
|
|
203
|
+
// metro-resolver can't substitute .js -> .ts, so --typescript would silently not apply -- reject it.
|
|
204
|
+
if (typescript && metroResolver) throw new Error("--typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)")
|
|
205
|
+
// --define=KEY=VALUE: a global's value (JSON), repeatable; the scan leaves out the imports of the
|
|
206
|
+
// branches the values keep from running (`if (__DEV__)` under __DEV__=false). JS-only.
|
|
207
|
+
if (values.define !== undefined && !allJs) throw new Error('--define is only valid for JS bundles')
|
|
208
|
+
const define = values.define === undefined ? undefined : parseDefineFlags(null, values.define)
|
|
209
|
+
return { mappingFile: values.mapping, manifests, scope: values.scope, conditions, mainFields, metro, metroResolver, babel, babelAliases: values['babel-aliases'], platforms, jsx, flow, typescript, tsconfig: values.tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// bundleCommand's options for writing the bundle of entries in `lang` from the parsed output flags in `values`.
|
|
213
|
+
function outputOptions(values, { allJs }) {
|
|
214
|
+
if (values.lockfile && !allJs) throw new Error('--lockfile is only valid for JS bundles')
|
|
215
|
+
// --brotli-quality: valid for every entry language (no allJs gate).
|
|
216
|
+
const brotliQuality = values['brotli-quality'] === undefined ? undefined : parseBrotliQuality('--brotli-quality', values['brotli-quality'])
|
|
217
|
+
// --add merges into the existing bundle at --output, so it can't target write-only stdout.
|
|
218
|
+
const add = Boolean(values.add)
|
|
219
|
+
if (add && values.output === '-') throw new Error('--add cannot be combined with --output=-')
|
|
220
|
+
return { output: values.output, lockfile: values.lockfile, brotliQuality, add }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// An entry's options in stasis.config.json's `entries` (`what` names it) as the flags they alias, in
|
|
224
|
+
// parseArgs' shape: `true` for a boolean flag set (`false`, its default, is no flag), a string for one
|
|
225
|
+
// taking a value, which a list flag takes as an array too, and an array of it for a repeatable one
|
|
226
|
+
// (each of a REPEATED_FLAGS one's values, as given).
|
|
227
|
+
function entryFlags(what, options) {
|
|
228
|
+
if (!isPlainObject(options)) throw new Error(`${what} must be an object of stasis bundle options`)
|
|
229
|
+
const values = {}
|
|
230
|
+
for (const [flag, value] of Object.entries(options)) {
|
|
231
|
+
if (OUTPUT_FLAGS.has(flag)) throw new Error(`${what}: ${flag} is the bundle's option, not an entry's: pass --${flag}`)
|
|
232
|
+
if (!Object.hasOwn(BUNDLE_FLAGS, flag)) throw new Error(`${what}: unknown option ${JSON.stringify(flag)}`)
|
|
233
|
+
const { type, multiple } = BUNDLE_FLAGS[flag]
|
|
234
|
+
if (type === 'boolean') {
|
|
235
|
+
if (typeof value !== 'boolean') throw new Error(`${what}: ${flag} must be true or false`)
|
|
236
|
+
if (value) values[flag] = true
|
|
237
|
+
continue
|
|
238
|
+
}
|
|
239
|
+
const takesArray = LIST_FLAGS.has(flag) || REPEATED_FLAGS.has(flag)
|
|
240
|
+
const list = takesArray && Array.isArray(value) && value.every((v) => typeof v === 'string')
|
|
241
|
+
if (typeof value !== 'string' && !list) throw new Error(`${what}: ${flag} must be a string${takesArray ? ' or an array of strings' : ''}`)
|
|
242
|
+
if (REPEATED_FLAGS.has(flag)) {
|
|
243
|
+
values[flag] = [value].flat()
|
|
244
|
+
continue
|
|
245
|
+
}
|
|
246
|
+
const text = list ? value.join(',') : value
|
|
247
|
+
values[flag] = multiple ? [text] : text
|
|
248
|
+
}
|
|
249
|
+
return values
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// The `entries` of the stasis.config.json in `cwd`: each entry it names, as a path relative to cwd
|
|
253
|
+
// -> { entry: the name as written, values: its options as flags (entryFlags') }. null where there is
|
|
254
|
+
// none.
|
|
255
|
+
export function readConfigEntries(cwd = process.cwd(), host = diskHost) {
|
|
256
|
+
const text = readFileSyncMaybe(resolve(cwd), CONFIG_FILE, 'utf8', host)
|
|
257
|
+
if (text === null) return null
|
|
258
|
+
let config
|
|
259
|
+
try {
|
|
260
|
+
config = JSON.parse(text)
|
|
261
|
+
} catch (cause) {
|
|
262
|
+
throw new Error(`${CONFIG_FILE} is not valid JSON`, { cause })
|
|
263
|
+
}
|
|
264
|
+
const entries = config?.entries
|
|
265
|
+
if (entries === undefined) return null
|
|
266
|
+
if (!isPlainObject(entries)) throw new Error(`${CONFIG_FILE}: entries must be an object of each entry's stasis bundle options`)
|
|
267
|
+
const named = new Map()
|
|
268
|
+
for (const [entry, options] of Object.entries(entries)) {
|
|
269
|
+
const what = `${CONFIG_FILE}: entries ${JSON.stringify(entry)}`
|
|
270
|
+
const key = isAbsolute(entry) ? null : entryKey(cwd, entry)
|
|
271
|
+
if (key === null) throw new Error(`${what}: an entry must be a path relative to the directory of ${CONFIG_FILE}, within it`)
|
|
272
|
+
if (named.has(key)) throw new Error(`${what} names the same entry as ${JSON.stringify(named.get(key).entry)}`)
|
|
273
|
+
named.set(key, { entry, values: entryFlags(what, options) })
|
|
274
|
+
}
|
|
275
|
+
return named
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// bundleCommand's options for bundling `entries` with the parsed flags `values` in `cwd`, whose
|
|
279
|
+
// stasis.config.json's `entries` is `config` (readConfigEntries'). Where it names every entry, each is
|
|
280
|
+
// built with its options there, the ones with the same options together (a build each), and none
|
|
281
|
+
// may be given as a flag but the bundle's own (OUTPUT_FLAGS) and the consent to a CONSENT_FLAGS
|
|
282
|
+
// option, which an entry setting it needs and some entry must set. Where it names none, they are all
|
|
283
|
+
// built with the flags; it may not name only some. A usage error throws.
|
|
284
|
+
export function bundlePlan({ cwd = process.cwd(), entries, values, config = null }) {
|
|
285
|
+
const lang = entriesLanguage(entries, cwd)
|
|
286
|
+
const output = outputOptions(values, lang)
|
|
287
|
+
const keys = entries.map((entry) => entryKey(cwd, entry))
|
|
288
|
+
const configured = config === null ? [] : entries.filter((_, i) => config.has(keys[i]))
|
|
289
|
+
if (configured.length === 0) return { ...output, entries, ...buildOptions(values, lang) }
|
|
290
|
+
const unnamed = entries.find((_, i) => !config.has(keys[i]))
|
|
291
|
+
if (unnamed !== undefined) {
|
|
292
|
+
throw new Error(`${CONFIG_FILE}'s entries name ${configured[0]} but not ${unnamed}: bundle either the entries it names or others, not both`)
|
|
293
|
+
}
|
|
294
|
+
const flag = Object.keys(values).find((name) => !OUTPUT_FLAGS.has(name) && !CONSENT_FLAGS.has(name))
|
|
295
|
+
if (flag !== undefined) throw new Error(`--${flag} can't be given for ${configured[0]}, whose options ${CONFIG_FILE}'s entries set: set it there`)
|
|
296
|
+
const named = keys.map((key) => config.get(key))
|
|
297
|
+
for (const consent of CONSENT_FLAGS.keys()) {
|
|
298
|
+
const given = values[consent]
|
|
299
|
+
if (given !== undefined && !named.some(({ values: flags }) => flags[consent] === given)) {
|
|
300
|
+
throw new Error(`${flagText(consent, given)} is given, but ${CONFIG_FILE}'s entries set ${flagText(consent, given).slice(2)} for none of ${entries.join(', ')}`)
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
const builds = new Map()
|
|
304
|
+
for (const [i, entry] of entries.entries()) {
|
|
305
|
+
const { entry: name, values: flags } = named[i]
|
|
306
|
+
const unconsented = [...CONSENT_FLAGS.keys()].find((consent) => flags[consent] !== undefined && values[consent] !== flags[consent])
|
|
307
|
+
if (unconsented !== undefined) {
|
|
308
|
+
const consent = flagText(unconsented, flags[unconsented])
|
|
309
|
+
throw new Error(`${CONFIG_FILE}: entries ${JSON.stringify(name)} sets ${consent.slice(2)}, which runs ${CONSENT_FLAGS.get(unconsented)}: pass ${consent} to allow it`)
|
|
310
|
+
}
|
|
311
|
+
let options
|
|
312
|
+
try {
|
|
313
|
+
options = buildOptions(flags, entriesLanguage([entry], cwd))
|
|
314
|
+
} catch (cause) {
|
|
315
|
+
throw new Error(`${CONFIG_FILE}: entries ${JSON.stringify(name)}: ${cause.message}`, { cause })
|
|
316
|
+
}
|
|
317
|
+
const id = JSON.stringify(options)
|
|
318
|
+
if (builds.has(id)) builds.get(id).entries.push(entry)
|
|
319
|
+
else builds.set(id, { entries: [entry], ...options })
|
|
320
|
+
}
|
|
321
|
+
return { ...output, builds: [...builds.values()] }
|
|
322
|
+
}
|