@exodus/stasis 1.0.0-beta.11 → 1.0.0-beta.13
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 +7 -8
- package/src/audit.js +4 -4
- package/src/babel.js +122 -9
- package/src/cmd/bundle-options.js +398 -0
- package/src/cmd/bundle.js +487 -179
- 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 +28 -23
- package/src/vfs-bundle/entries.js +20 -2
- package/src/vfs-bundle/github.js +7 -5
- package/src/vfs-bundle/tree.js +4 -4
- package/src/vfs-bundle.js +11 -10
package/src/cmd/bundle.js
CHANGED
|
@@ -6,15 +6,19 @@ import { brotliDecompressSync } from 'node:zlib'
|
|
|
6
6
|
|
|
7
7
|
import { Bundle, isValidRepoField } from '@exodus/stasis-core/bundle'
|
|
8
8
|
import { Lockfile } from '@exodus/stasis-core/lockfile'
|
|
9
|
-
import {
|
|
9
|
+
import { extraArtifacts } from '@exodus/stasis-core/add'
|
|
10
|
+
import { Scan, importsTypescriptByOutputName, scan } from '../scan.js'
|
|
11
|
+
import { parseDefine } from '../define.js'
|
|
10
12
|
import { createFieldResolver, resolveConditions } from '../resolve-fields.js'
|
|
11
13
|
import { discoverTsconfig, isDir, loadTsconfigPaths, packageTsconfigPaths } from '../resolve-typescript.js'
|
|
12
14
|
import { createMetroResolver } from '../metro-resolver.js'
|
|
15
|
+
import { createAliases, createBabelAliases } from '../babel.js'
|
|
16
|
+
import { linkedNativePackages, looksNative, nativeInputs } from '@exodus/stasis-plugins/metro-native'
|
|
13
17
|
import { pinInstalledCommits } from '../installed-commits.js'
|
|
14
18
|
import { State } from '@exodus/stasis-core/state'
|
|
15
|
-
import { sha512integrity } from '@exodus/stasis-core/state-util'
|
|
16
|
-
import { checkoutCommit, detectRepo, findPackageMetadata, normalizeEntries, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull } from '@exodus/stasis-core/bundle-util'
|
|
17
|
-
import { EMPTY_MODULE_PATH, RN_CORE_INCLUDE_FILES, assertRealPathWithinBase,
|
|
19
|
+
import { readFileSyncMaybe, sha512integrity } from '@exodus/stasis-core/state-util'
|
|
20
|
+
import { checkoutCommit, detectRepo, findPackageMetadata, normalizeEntries, packageJSONStat, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull, scopeManifestOf } from '@exodus/stasis-core/bundle-util'
|
|
21
|
+
import { EMPTY_MODULE_PATH, RN_CORE_INCLUDE_FILES, assertRealPathWithinBase, hasNodeModulesSegment, isDotEnvFile, isExecutableFile, isPathWithin, isPlainObject, moduleFileKey, moduleInfo, parseExtraOption, parseResourcesOption, posixPathEscapes, relativeEscapes, splitNodeModulesPath, toPosix, withMetadataOf } from '@exodus/stasis-core/util'
|
|
18
22
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
19
23
|
import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
|
|
20
24
|
import {
|
|
@@ -264,10 +268,11 @@ function assertSelfContained(lang, noun, entries, sources, missing) {
|
|
|
264
268
|
// (packageLookup by default, which walks past a malformed one). `classifyDep(path)` optionally
|
|
265
269
|
// places a file directly (non-node_modules ecosystems like Soldeer/github); null defers. `format` tags
|
|
266
270
|
// every file; `formats` (Map<path,format>) overrides it per file. `resolutions` values are
|
|
267
|
-
// a flat target string or a Map<platform,target>; both round-trip untouched.
|
|
271
|
+
// a flat target string or a Map<platform,target>; both round-trip untouched. `consumer` is
|
|
272
|
+
// codeBundle's.
|
|
268
273
|
function assembleCodeBundle({
|
|
269
274
|
baseDir, entries, sources, resolutions, workspaceName, workspaceVersion, format, formats, conditionKey, classifyDep, host,
|
|
270
|
-
packageOf = packageLookup(baseDir, { host }),
|
|
275
|
+
packageOf = packageLookup(baseDir, { host }), consumer,
|
|
271
276
|
}) {
|
|
272
277
|
const modules = new Map()
|
|
273
278
|
// `identity`'s name, version, ecosystem, repo and vendored (moduleInfo takes those alone); a later
|
|
@@ -297,14 +302,19 @@ function assembleCodeBundle({
|
|
|
297
302
|
}
|
|
298
303
|
}
|
|
299
304
|
|
|
300
|
-
return codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host })
|
|
305
|
+
return codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host, consumer })
|
|
301
306
|
}
|
|
302
307
|
|
|
303
308
|
// A full-scope code Bundle of `sources`, bucketed as `modules`: `format` tags every file, `formats`
|
|
304
|
-
// (Map<path,format>) overrides it per file, and the `resolutions` edges
|
|
305
|
-
|
|
309
|
+
// (Map<path,format>) overrides it per file (a file neither tags has none), and the `resolutions` edges
|
|
310
|
+
// are keyed under `conditionKey`. Every file is attributed to `consumer` in the `reason` map: `bundle`,
|
|
311
|
+
// or `bundle:metro` for --metro.
|
|
312
|
+
function codeBundle({ baseDir, entries, sources, modules, resolutions, format, formats, conditionKey, host, consumer = 'bundle' }) {
|
|
306
313
|
const formatsMap = new Map()
|
|
307
|
-
for (const path of sources.keys())
|
|
314
|
+
for (const path of sources.keys()) {
|
|
315
|
+
const fileFormat = formats?.get(path) ?? format
|
|
316
|
+
if (fileFormat !== undefined) formatsMap.set(path, fileFormat)
|
|
317
|
+
}
|
|
308
318
|
|
|
309
319
|
const importsForKey = new Map()
|
|
310
320
|
for (const [parent, specMap] of resolutions) importsForKey.set(parent, specMap)
|
|
@@ -314,7 +324,7 @@ function codeBundle({ baseDir, entries, sources, modules, resolutions, format, f
|
|
|
314
324
|
// executable). Shell bundles lean on this most: `stasis extract` puts the +x back on the scripts.
|
|
315
325
|
const executable = executableSources(baseDir, sources, host)
|
|
316
326
|
|
|
317
|
-
// Attribute files to the
|
|
327
|
+
// Attribute files to the static build's consumer (static builders skip State's per-file tagging).
|
|
318
328
|
return new Bundle({
|
|
319
329
|
config: { scope: 'full' },
|
|
320
330
|
entries: new Set(entries),
|
|
@@ -322,7 +332,7 @@ function codeBundle({ baseDir, entries, sources, modules, resolutions, format, f
|
|
|
322
332
|
formats: formatsMap,
|
|
323
333
|
imports,
|
|
324
334
|
executable,
|
|
325
|
-
}).withReason(
|
|
335
|
+
}).withReason(consumer)
|
|
326
336
|
}
|
|
327
337
|
|
|
328
338
|
// Files never carried, whatever reads them: `.env` files, and Hardhat's config, which is code
|
|
@@ -666,25 +676,89 @@ function describeUnresolved(u, show) {
|
|
|
666
676
|
return `${u.kind} ${u.spec ?? '<dynamic>'} from ${show(u.parentURL)} (${u.reason}${typescript})`
|
|
667
677
|
}
|
|
668
678
|
|
|
669
|
-
//
|
|
670
|
-
//
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
const staticKinds = new Set(['import', 'export-from'])
|
|
677
|
-
const staticReachable = new Set(scanner.entries)
|
|
679
|
+
// Static ESM import/export-from edges load eagerly before user code, so a failure there is
|
|
680
|
+
// uncatchable; one below a require()/dynamic-import() boundary is catchable.
|
|
681
|
+
const STATIC_KINDS = new Set(['import', 'export-from'])
|
|
682
|
+
|
|
683
|
+
// The files the entries link eagerly, through static edges alone.
|
|
684
|
+
function eagerlyLinked(scanner) {
|
|
685
|
+
const linked = new Set(scanner.entries)
|
|
678
686
|
const walk = [...scanner.entries]
|
|
679
687
|
while (walk.length > 0) {
|
|
680
688
|
for (const e of scanner.files.get(walk.shift())?.edges ?? []) {
|
|
681
|
-
if (
|
|
682
|
-
|
|
689
|
+
if (STATIC_KINDS.has(e.kind) && e.child && !linked.has(e.child)) {
|
|
690
|
+
linked.add(e.child)
|
|
683
691
|
walk.push(e.child)
|
|
684
692
|
}
|
|
685
693
|
}
|
|
686
694
|
}
|
|
687
|
-
|
|
695
|
+
return linked
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// The scan within the project root (`within(url)`), since a bundle can't carry a file outside it.
|
|
699
|
+
// One the entries link eagerly is returned in `outside`, for the caller to refuse. One reached
|
|
700
|
+
// only past a require()/import() boundary is left out, with whatever only it reaches, and its edges
|
|
701
|
+
// are returned in `leftOut`, misses that load can catch as it does an unresolved one: an optional
|
|
702
|
+
// peer dependency's lazy require() reaching a copy hoisted above a root that a stasis file pins, say.
|
|
703
|
+
function withinRoot(scanner, within) {
|
|
704
|
+
const outside = [...eagerlyLinked(scanner)].filter((url) => scanner.files.has(url) && !within(url))
|
|
705
|
+
if (outside.length > 0) return { scanner, outside, leftOut: [] }
|
|
706
|
+
const kept = new Set([...scanner.entries].filter((url) => scanner.files.has(url)))
|
|
707
|
+
const walk = [...kept]
|
|
708
|
+
while (walk.length > 0) {
|
|
709
|
+
for (const e of scanner.files.get(walk.shift())?.edges ?? []) {
|
|
710
|
+
if (e.child && scanner.files.has(e.child) && !kept.has(e.child) && within(e.child)) {
|
|
711
|
+
kept.add(e.child)
|
|
712
|
+
walk.push(e.child)
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (kept.size === scanner.files.size) return { scanner, outside, leftOut: [] }
|
|
717
|
+
const leftOut = []
|
|
718
|
+
const files = new Map()
|
|
719
|
+
for (const url of kept) {
|
|
720
|
+
const info = scanner.files.get(url)
|
|
721
|
+
const edges = info.edges.map((e) => {
|
|
722
|
+
if (!e.child || within(e.child)) return e
|
|
723
|
+
const { child, ...rest } = e
|
|
724
|
+
leftOut.push({ parentURL: url, kind: e.kind, spec: e.spec, outsideURL: child })
|
|
725
|
+
return { ...rest, error: 'outside the project root' }
|
|
726
|
+
})
|
|
727
|
+
files.set(url, { ...info, edges })
|
|
728
|
+
}
|
|
729
|
+
const imports = new Map()
|
|
730
|
+
for (const [key, byParent] of scanner.imports) {
|
|
731
|
+
const parents = new Map()
|
|
732
|
+
for (const [parentURL, specMap] of byParent) {
|
|
733
|
+
if (!files.has(parentURL)) continue
|
|
734
|
+
const specs = new Map([...specMap].filter(([, childURL]) => within(childURL)))
|
|
735
|
+
if (specs.size > 0) parents.set(parentURL, specs)
|
|
736
|
+
}
|
|
737
|
+
if (parents.size > 0) imports.set(key, parents)
|
|
738
|
+
}
|
|
739
|
+
const unresolved = scanner.unresolved.filter((u) => files.has(u.parentURL))
|
|
740
|
+
const parseErrors = scanner.parseErrors.filter((p) => files.has(p.url))
|
|
741
|
+
return { scanner: { entries: scanner.entries, files, imports, unresolved, parseErrors }, outside, leftOut }
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// Refuse an edge one --metro platform resolves within the root and another leaves out (see
|
|
745
|
+
// withinRoot): collapsed to the one target, it would serve that platform the other's file.
|
|
746
|
+
function refuseSplit(split, baseDir) {
|
|
747
|
+
for (const { parentURL, spec, outsideURL } of split) {
|
|
748
|
+
throw new Error(
|
|
749
|
+
`${spec} from ${displayPath(parentURL, baseDir)} resolves within the project root in one context and outside it, ` +
|
|
750
|
+
`at ${relative(baseDir, fileURLToPath(outsideURL))}, in another: a bundle can't leave out the one without serving the other in its place`
|
|
751
|
+
)
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// Classify scanner unresolved edges + parse errors into fatal (broken/divergent at load)
|
|
756
|
+
// vs tolerated (a catchable runtime miss). Shared so the plain and --mainFields JS paths
|
|
757
|
+
// gate identically. `baseDir` relativizes the paths in the emitted messages (see displayPath).
|
|
758
|
+
function analyzeScanner(scanner, { baseDir }) {
|
|
759
|
+
const show = (url) => displayPath(url, baseDir)
|
|
760
|
+
const staticReachable = eagerlyLinked(scanner)
|
|
761
|
+
const fatalUnresolved = (u) => STATIC_KINDS.has(u.kind) && staticReachable.has(u.parentURL)
|
|
688
762
|
const fatal = scanner.unresolved
|
|
689
763
|
.filter((u) => fatalUnresolved(u))
|
|
690
764
|
.map((u) => `unresolved ${describeUnresolved(u, show)}`)
|
|
@@ -711,7 +785,7 @@ function analyzeScanner(scanner, { baseDir }) {
|
|
|
711
785
|
|
|
712
786
|
// Throw on fatal scan issues; warn on tolerated ones. `label` tags the scan pass; `baseDir`
|
|
713
787
|
// relativizes the paths in the warnings (see displayPath), matching analyzeScanner's messages.
|
|
714
|
-
function reportScanIssues({ fatal, tolerated, toleratedParse }, { label = '', baseDir }) {
|
|
788
|
+
function reportScanIssues({ fatal, tolerated, toleratedParse, leftOut = [] }, { label = '', baseDir, root = '' }) {
|
|
715
789
|
const where = label ? ` (${label})` : ''
|
|
716
790
|
const show = (url) => displayPath(url, baseDir)
|
|
717
791
|
// The first 10 of `items` as indented lines (`line` renders one), then how many more there are.
|
|
@@ -730,6 +804,11 @@ function reportScanIssues({ fatal, tolerated, toleratedParse }, { label = '', ba
|
|
|
730
804
|
const summary = listed(toleratedParse, (p) => `${show(p.url)}: ${p.message}`)
|
|
731
805
|
console.warn(`[stasis] Bundle has ${toleratedParse.length} file(s) with parse errors${where}; their recorded imports may be incomplete:\n${summary}`)
|
|
732
806
|
}
|
|
807
|
+
if (leftOut.length > 0) {
|
|
808
|
+
// The file outside the root by its path from the cwd, as the refusal of one linked eagerly names it.
|
|
809
|
+
const summary = listed(leftOut, (u) => `${u.kind} ${u.spec} from ${show(u.parentURL)} (at ${relative(baseDir, fileURLToPath(u.outsideURL))})`)
|
|
810
|
+
console.warn(`[stasis] Bundle leaves out ${leftOut.length} import(s) of files outside the project root${root}${where}; they will fall through at load time:\n${summary}`)
|
|
811
|
+
}
|
|
733
812
|
}
|
|
734
813
|
|
|
735
814
|
// Normalize conditions (trim, drop empties) so a sloppy programmatic caller can't push a bogus
|
|
@@ -754,11 +833,16 @@ function typescriptPathsFor(typescript, baseDir, tsconfig, host, env) {
|
|
|
754
833
|
// resolution to its on-disk TS source (tsc's rules; see resolve-typescript.js), honouring the
|
|
755
834
|
// `paths` aliases of `tsconfig` (an explicit config path, default each package's tsconfig.json); it
|
|
756
835
|
// is taken as given where the entries import TS sources by output name (importsTypescriptByOutputName).
|
|
836
|
+
// `define` gives globals their values, a branch they keep from running reaching nothing (define.js).
|
|
757
837
|
// Files are read through `host` (@exodus/stasis-core/host), the disk by default; EXODUS_STASIS_*
|
|
758
838
|
// settings from `env`. With `innermostRoot`, the State is rooted at the innermost package at or
|
|
759
839
|
// above cwd that holds every file the scan reaches (innermostRootOf), rather than at the project's
|
|
760
|
-
// root above it, where that holds no stasis file of its own.
|
|
761
|
-
|
|
840
|
+
// root above it, where that holds no stasis file of its own. With `extra`, the files its
|
|
841
|
+
// stasis.config.json's `extra` names are added as `stasis run` adds them (State#includeExtra), never
|
|
842
|
+
// one of `outputsAt(root)` (the absolute paths the build writes, given the root its paths are
|
|
843
|
+
// relative to), resources by `resources` where given, else by the config's; from disk alone, as
|
|
844
|
+
// Node's glob reads it.
|
|
845
|
+
export async function buildJsBundle({ cwd = process.cwd(), env = process.env, entries, scope, conditions = [], jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, host = diskHost, innermostRoot = false, extra = false, outputsAt = () => [] } = {}) {
|
|
762
846
|
if (!Array.isArray(entries) || entries.length === 0) {
|
|
763
847
|
throw new Error('buildJsBundle: at least one entry .js/.cjs/.mjs/.ts/.cts/.mts/.jsx/.tsx file is required')
|
|
764
848
|
}
|
|
@@ -776,10 +860,7 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
|
|
|
776
860
|
typescript ||= importsTypescriptByOutputName(absEntries, host)
|
|
777
861
|
const typescriptPaths = typescriptPathsFor(typescript, baseDir, tsconfig, host, env)
|
|
778
862
|
|
|
779
|
-
const
|
|
780
|
-
|
|
781
|
-
// Fail closed where the bundle is guaranteed broken at load; warn on catchable misses (see analyzeScanner).
|
|
782
|
-
reportScanIssues(analyzeScanner(scanner, { baseDir }), { baseDir })
|
|
863
|
+
const scanned = scan(absEntries, { conditions: scanConditions, jsx, flow, typescript, typescriptPaths, resources: resourceSet, define, host })
|
|
783
864
|
|
|
784
865
|
// Materialise via a non-preload State: addFile bucketizes + records sources/formats,
|
|
785
866
|
// addImport replays the edge map; serialize emits the runtime loader's v1 layout.
|
|
@@ -790,33 +871,41 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
|
|
|
790
871
|
let state = new State(baseDir, { ...stateOptions, env })
|
|
791
872
|
// A root holding a stasis file is the project's own choice, whose config the build takes.
|
|
792
873
|
if (innermostRoot && !STASIS_ROOT_FILES.some((file) => host.stat(join(state.root, file)) !== null)) {
|
|
793
|
-
const root = innermostRootOf(baseDir, [...
|
|
874
|
+
const root = innermostRootOf(baseDir, [...scanned.files.keys()].map((url) => host.realpath(fileURLToPath(url))), state.root, host)
|
|
794
875
|
// The State's walk up from cwd stops at PROJECT_CWD, as it does where yarn sets it.
|
|
795
876
|
if (root !== state.root) state = new State(baseDir, { ...stateOptions, env: { ...env, PROJECT_CWD: root } })
|
|
796
877
|
}
|
|
797
|
-
//
|
|
798
|
-
//
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
878
|
+
// Only what lies within the root is carried (see withinRoot). One the entries link eagerly is
|
|
879
|
+
// refused, named here rather than as the State's bare assertion: a stasis file in a directory below
|
|
880
|
+
// the project's root (a stray stasis.code.br there, say) roots the State at it, out of the files above.
|
|
881
|
+
const { scanner, outside, leftOut } = withinRoot(scanned, (url) => !relativeEscapes(relative(state.root, fileURLToPath(url))))
|
|
882
|
+
const markers = STASIS_ROOT_FILES.filter((name) => host.stat(join(state.root, name)) !== null)
|
|
883
|
+
const rootedBy = markers.length === 0 ? '' : ` (rooted there by its ${markers.join(' and ')}, which can be removed if stale)`
|
|
884
|
+
const root = ` at ${relative(baseDir, state.root) || '.'}${rootedBy}`
|
|
885
|
+
for (const url of outside) {
|
|
886
|
+
throw new Error(`buildJsBundle: ${relative(baseDir, fileURLToPath(url))} is outside the project root${root}`)
|
|
805
887
|
}
|
|
888
|
+
// Fail closed where the bundle is guaranteed broken at load; warn on catchable misses (see analyzeScanner).
|
|
889
|
+
reportScanIssues({ ...analyzeScanner(scanner, { baseDir }), leftOut }, { baseDir, root })
|
|
806
890
|
for (const [url, info] of scanner.files) {
|
|
807
891
|
// A resource carries bytes only: addFile derives resource vs resource:base64 from the content
|
|
808
892
|
// and stores it under `resources` (a resource can't be an entry, so no isEntry).
|
|
893
|
+
// Recorded as the `bundle` consumer's, which `extra` files are not.
|
|
809
894
|
if (info.resource) {
|
|
810
|
-
state.addFile(url, { resource: true })
|
|
895
|
+
state.addFile(url, { resource: true, reason: 'bundle' })
|
|
811
896
|
continue
|
|
812
897
|
}
|
|
813
898
|
const isEntry = scanner.entries.has(url)
|
|
814
|
-
state.addFile(url, { format: info.format, isEntry })
|
|
899
|
+
state.addFile(url, { format: info.format, isEntry, reason: 'bundle' })
|
|
815
900
|
}
|
|
816
901
|
// Edges where every context agrees keep the wildcard '*' key (getImport's fallback when a
|
|
817
902
|
// condition lookup misses). Where the require()- and import()-context resolutions of one
|
|
818
903
|
// (parent, specifier) DIVERGE, each target keeps its real condition key -- one '*' entry
|
|
819
904
|
// would serve one context the other's file; an unmatched set fails closed via resolveBundled.
|
|
905
|
+
// So does one that a context resolves and another misses or leaves out (an `exports` map with
|
|
906
|
+
// a `require` branch alone, say): getImport serves no context the other's key where conditions
|
|
907
|
+
// decide the resolution, so the miss stays one, as under Node.
|
|
908
|
+
const missed = new Set([...scanner.unresolved, ...leftOut].filter((u) => u.spec !== undefined).map((u) => `${u.parentURL}\0${u.spec}`))
|
|
820
909
|
const byParent = new Map()
|
|
821
910
|
for (const [key, parents] of scanner.imports) {
|
|
822
911
|
for (const [parentURL, specs] of parents) {
|
|
@@ -831,7 +920,7 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
|
|
|
831
920
|
for (const [parentURL, bySpec] of byParent) {
|
|
832
921
|
for (const [spec, byKey] of bySpec) {
|
|
833
922
|
const targets = new Set(byKey.values())
|
|
834
|
-
if (targets.size === 1) {
|
|
923
|
+
if (targets.size === 1 && !missed.has(`${parentURL}\0${spec}`)) {
|
|
835
924
|
state.addImport(parentURL, spec, [...targets][0], { conditions: '*' })
|
|
836
925
|
} else {
|
|
837
926
|
for (const [key, childURL] of byKey) {
|
|
@@ -840,9 +929,12 @@ export async function buildJsBundle({ cwd = process.cwd(), env = process.env, en
|
|
|
840
929
|
}
|
|
841
930
|
}
|
|
842
931
|
}
|
|
843
|
-
//
|
|
844
|
-
|
|
845
|
-
|
|
932
|
+
// Its own targets are none of the State's: it writes nothing.
|
|
933
|
+
if (extra) state.includeExtra({ outputs: outputsAt(state.root), resources: resources === undefined ? undefined : resourceSet })
|
|
934
|
+
// --package-json, or the `packageJSON` of the stasis.config.json the State took, as `stasis run` takes
|
|
935
|
+
// it: fold each bundled module's package.json into the State's buckets (idempotent -- no-ops any
|
|
936
|
+
// manifest the scan already reached). State's bundle=replace makes writeBundle true, so addFile accepts them.
|
|
937
|
+
if (packageJSON || state.config.packageJSON) state.includePackageJson()
|
|
846
938
|
return state
|
|
847
939
|
}
|
|
848
940
|
|
|
@@ -868,53 +960,17 @@ function innermostRootOf(baseDir, files, root, host) {
|
|
|
868
960
|
const SOURCE_EXTS = ['js', 'jsx', 'json', 'ts', 'tsx']
|
|
869
961
|
// React Native preset mainFields for `--metro` (which also sets the RN conditions + platform suffixes).
|
|
870
962
|
const METRO_MAIN_FIELDS = ['react-native', 'browser', 'main']
|
|
963
|
+
|
|
964
|
+
// The config files a React Native app's build loads from its project root, though nothing the app
|
|
965
|
+
// imports reaches them: Metro's and the React Native CLI's, and with --babel(-aliases) Babel's.
|
|
966
|
+
const METRO_CONFIG_FILES = ['metro.config.js', 'react-native.config.js']
|
|
967
|
+
const BABEL_CONFIG_FILE = 'babel.config.js'
|
|
871
968
|
// What esbuild and webpack 5 both assert on every platform besides `import`/`require` and
|
|
872
969
|
// `default`, and so `--mainFields` too: `module`, the bundler-only condition a package's ESM build
|
|
873
970
|
// sits under, from an import and a require alike. (esbuild drops it when given conditions of its
|
|
874
971
|
// own; webpack keeps it, as `--conditions` adds to it here.) Node and Metro never assert it.
|
|
875
972
|
const BUNDLER_CONDITIONS = ['module']
|
|
876
973
|
|
|
877
|
-
// Recursively collect the files under `dirAbs` whose name `keep` takes, skipping build output,
|
|
878
|
-
// symlinks (cycle/escape hazard) and, directly in `dirAbs`, the dirs `skipAtRoot` names. Absolute
|
|
879
|
-
// paths into `out`.
|
|
880
|
-
function walkNative(dirAbs, out, host, keep, skipAtRoot) {
|
|
881
|
-
let entries
|
|
882
|
-
try {
|
|
883
|
-
entries = host.readdir(dirAbs)
|
|
884
|
-
} catch {
|
|
885
|
-
return // absent -- nothing for this platform
|
|
886
|
-
}
|
|
887
|
-
for (const ent of entries) {
|
|
888
|
-
if (ent.isSymbolicLink()) continue
|
|
889
|
-
const full = join(dirAbs, ent.name)
|
|
890
|
-
if (ent.isDirectory()) {
|
|
891
|
-
if (!isSkippedNativeWalkDir(ent.name) && !skipAtRoot?.(ent.name)) walkNative(full, out, host, keep)
|
|
892
|
-
} else if (ent.isFile() && keep(ent.name)) {
|
|
893
|
-
out.push(full)
|
|
894
|
-
}
|
|
895
|
-
}
|
|
896
|
-
}
|
|
897
|
-
|
|
898
|
-
// The files of a native ios/android dir: all but build artifacts.
|
|
899
|
-
const isNativeSource = (name) => !isNativeArtifact(name)
|
|
900
|
-
|
|
901
|
-
// Native source files a bundled RN dep contributes to the app's native build (podspecs +
|
|
902
|
-
// ios/android sources). Manifests are kept only when the package is actually native (podspec
|
|
903
|
-
// or ios/android dir), else a JS-only dep's package.json would be pulled in. Deduped absolute paths.
|
|
904
|
-
function nativeModuleFiles(pkgAbs, host) {
|
|
905
|
-
// Podspec-load manifests: RN's own podspecs live in scattered subdirs a root-only scan would miss,
|
|
906
|
-
// so recurse fully.
|
|
907
|
-
const manifests = []
|
|
908
|
-
walkNative(pkgAbs, manifests, host, isNativeManifest, isExcludedNativeDir)
|
|
909
|
-
const hasIos = host.stat(join(pkgAbs, 'ios')) !== null
|
|
910
|
-
const hasAndroid = host.stat(join(pkgAbs, 'android')) !== null
|
|
911
|
-
if (!hasIos && !hasAndroid && !manifests.some((f) => isPodspec(f))) return []
|
|
912
|
-
const out = [...manifests]
|
|
913
|
-
if (hasIos) walkNative(join(pkgAbs, 'ios'), out, host, isNativeSource)
|
|
914
|
-
if (hasAndroid) walkNative(join(pkgAbs, 'android'), out, host, isNativeSource)
|
|
915
|
-
return [...new Set(out)]
|
|
916
|
-
}
|
|
917
|
-
|
|
918
974
|
// The built-in field/suffix resolver (resolve-fields.js) the legacy-field build resolves with on
|
|
919
975
|
// `platform` (null for --mainFields), its `mainFields` (Metro's under --metro), and the conditions
|
|
920
976
|
// it adds to the bundler base (`import`/`require` + `default`, never Node's `node`; see
|
|
@@ -941,10 +997,93 @@ export function fieldResolverFor(platform, { mainFields, metro = false, conditio
|
|
|
941
997
|
return { extras, mainFields: fields, resolver }
|
|
942
998
|
}
|
|
943
999
|
|
|
1000
|
+
const CONFIG_FILE = 'stasis.config.json'
|
|
1001
|
+
|
|
1002
|
+
// The stasis.config.json in `cwd`, parsed; null where there is none.
|
|
1003
|
+
function readConfigFile(name, cwd, host = diskHost) {
|
|
1004
|
+
const text = readFileSyncMaybe(resolve(cwd), CONFIG_FILE, 'utf8', host)
|
|
1005
|
+
try {
|
|
1006
|
+
return text === null ? null : JSON.parse(text)
|
|
1007
|
+
} catch (cause) {
|
|
1008
|
+
throw new Error(`${name}: ${CONFIG_FILE} is not valid JSON`, { cause })
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
|
|
1012
|
+
// --babel-aliases: the alias map of the JSON file `file` (a path from `baseDir`, in the project, read through
|
|
1013
|
+
// `host`), babel-plugin-module-resolver's `alias` option as data: each alias to the string it maps to.
|
|
1014
|
+
function readAliasesFile(baseDir, file, host = diskHost) {
|
|
1015
|
+
const rel = relative(baseDir, resolve(baseDir, file))
|
|
1016
|
+
if (relativeEscapes(rel)) throw new Error(`stasis bundle: --babel-aliases must name a file in the project: ${file}`)
|
|
1017
|
+
const text = readFileSyncMaybe(baseDir, toPosix(rel), 'utf8', host)
|
|
1018
|
+
if (text === null) throw new Error(`stasis bundle: --babel-aliases file not found: ${file}`)
|
|
1019
|
+
// A link to a file out of the project is refused too.
|
|
1020
|
+
assertRealPathWithinBase(host.realpath(baseDir), baseDir, toPosix(rel), host)
|
|
1021
|
+
let alias
|
|
1022
|
+
try {
|
|
1023
|
+
alias = JSON.parse(text)
|
|
1024
|
+
} catch (cause) {
|
|
1025
|
+
throw new Error(`stasis bundle: --babel-aliases file ${file} is not valid JSON`, { cause })
|
|
1026
|
+
}
|
|
1027
|
+
if (!isPlainObject(alias) || !Object.values(alias).every((value) => typeof value === 'string')) {
|
|
1028
|
+
throw new Error(`stasis bundle: --babel-aliases file ${file} must be an object mapping each alias to a string`)
|
|
1029
|
+
}
|
|
1030
|
+
for (const key of Object.keys(alias)) {
|
|
1031
|
+
if (!key.startsWith('^') && !key.endsWith('$')) continue
|
|
1032
|
+
try {
|
|
1033
|
+
RegExp(key) // compiled to check it, as createAliases compiles it
|
|
1034
|
+
} catch (cause) {
|
|
1035
|
+
throw new Error(`stasis bundle: --babel-aliases file ${file}: ${JSON.stringify(key)} is not a valid regular expression`, { cause })
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
return alias
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
// The `scope`, `resources` and `packageJSON` of a --mainFields/--metro build: as given (an empty
|
|
1042
|
+
// `resources` too, for no allowlist; `packageJSON` true), else as the stasis.config.json in `cwd`
|
|
1043
|
+
// sets them (the directory these bundles' paths are relative to, and where one is written by
|
|
1044
|
+
// default). The field resolver builds a full-scope bundle alone, so a narrower scope, from either,
|
|
1045
|
+
// is refused rather than silently ignored.
|
|
1046
|
+
// -> { resources: Set<string> (parseResourcesOption's), packageJSON: boolean }
|
|
1047
|
+
function fieldBuildOptions(name, { cwd = process.cwd(), scope, resources, packageJSON = false, host = diskHost }) {
|
|
1048
|
+
const resourcesGiven = resources !== undefined
|
|
1049
|
+
const config = scope === undefined || !resourcesGiven || !packageJSON ? readConfigFile(name, cwd, host) : null
|
|
1050
|
+
if (scope !== undefined && scope !== 'full') {
|
|
1051
|
+
throw new Error(`${name}: --scope=${scope} is not supported with --mainFields or --metro (they always build a full-scope bundle)`)
|
|
1052
|
+
}
|
|
1053
|
+
if (scope === undefined && config?.scope !== undefined && config.scope !== 'full') {
|
|
1054
|
+
throw new Error(`${name}: ${CONFIG_FILE} sets scope ${JSON.stringify(config.scope)}, which --mainFields and --metro don't support (they always build a full-scope bundle); pass --scope=full to override it`)
|
|
1055
|
+
}
|
|
1056
|
+
if (config?.packageJSON !== undefined && typeof config.packageJSON !== 'boolean') {
|
|
1057
|
+
throw new Error(`${name}: ${CONFIG_FILE} sets packageJSON ${JSON.stringify(config.packageJSON)}, which must be true or false`)
|
|
1058
|
+
}
|
|
1059
|
+
return {
|
|
1060
|
+
resources: resourcesGiven ? parseResourcesOption(name, resources) : parseResourcesOption(CONFIG_FILE, config?.resources),
|
|
1061
|
+
packageJSON: packageJSON || config?.packageJSON === true,
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
// Metro's own empty module, which it resolves a disabled import to (its default
|
|
1066
|
+
// resolver.emptyModulePath), where the project installs metro-runtime at its root.
|
|
1067
|
+
const METRO_EMPTY_MODULE = 'node_modules/metro-runtime/src/modules/empty-module.js'
|
|
1068
|
+
// An empty module's source, trimmed: nothing, or a lone "use strict" directive.
|
|
1069
|
+
const EMPTY_MODULE_SOURCE = /^(?:(["'])use strict\1;?)?$/u
|
|
1070
|
+
|
|
1071
|
+
// The real path of METRO_EMPTY_MODULE under `baseDir`, where it is a file in the project that is in
|
|
1072
|
+
// fact empty (EMPTY_MODULE_SOURCE), else null.
|
|
1073
|
+
function metroEmptyModule(baseDir, host) {
|
|
1074
|
+
const abs = join(baseDir, METRO_EMPTY_MODULE)
|
|
1075
|
+
if (!host.stat(abs)?.isFile()) return null
|
|
1076
|
+
const real = host.realpath(abs)
|
|
1077
|
+
if (!isPathWithin(host.realpath(baseDir), real)) return null
|
|
1078
|
+
const buf = host.readFile(real)
|
|
1079
|
+
return isUtf8(buf) && EMPTY_MODULE_SOURCE.test(buf.toString('utf8').trim()) ? real : null
|
|
1080
|
+
}
|
|
1081
|
+
|
|
944
1082
|
// Build a JS/TS Bundle + companion Lockfile via the legacy-field resolver (`--mainFields`/
|
|
945
1083
|
// `--metro`). Scanned once per platform; each edge is recorded flat when the platforms that
|
|
946
|
-
// have it agree, or as a `{ platform: target }` map where they diverge.
|
|
947
|
-
|
|
1084
|
+
// have it agree, or as a `{ platform: target }` map where they diverge. `scope` and `resources`
|
|
1085
|
+
// are fieldBuildOptions'. Returns { bundle, lockfile }.
|
|
1086
|
+
async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, entries, mainFields, platforms, conditions = [], metro = false, metroResolver = false, babel = false, babelAliases: aliasesFile, jsx = false, flow = false, typescript = false, tsconfig, scope, resources, define, packageJSON = false, host = diskHost }) {
|
|
948
1087
|
const baseDir = resolve(cwd)
|
|
949
1088
|
const absEntries = entries.map((e) => resolve(baseDir, e))
|
|
950
1089
|
const normalized = normalizeEntries(entries, cwd)
|
|
@@ -954,15 +1093,17 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
954
1093
|
// is the root; a file below neither is outside it. (Realpathed only when needed, so a missing cwd
|
|
955
1094
|
// is still the scan's missing entry.)
|
|
956
1095
|
let realRoot
|
|
957
|
-
const
|
|
1096
|
+
const relWithin = (abs) => {
|
|
958
1097
|
let rel = toPosix(relative(baseDir, abs))
|
|
959
1098
|
if (relativeEscapes(rel)) {
|
|
960
1099
|
realRoot ??= host.realpath(baseDir)
|
|
961
1100
|
rel = toPosix(relative(realRoot, abs))
|
|
962
1101
|
}
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1102
|
+
return relativeEscapes(rel) ? null : rel
|
|
1103
|
+
}
|
|
1104
|
+
const toRel = (abs) => {
|
|
1105
|
+
const rel = relWithin(abs)
|
|
1106
|
+
if (rel === null) throw new Error(`Bundle would reach a file outside the project root: ${abs}`)
|
|
966
1107
|
return rel
|
|
967
1108
|
}
|
|
968
1109
|
|
|
@@ -973,8 +1114,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
973
1114
|
if (!metroResolver) typescript ||= importsTypescriptByOutputName(absEntries, host)
|
|
974
1115
|
// --typescript's tsconfig `paths` matcher, shared by every per-platform resolver below.
|
|
975
1116
|
const typescriptPaths = typescriptPathsFor(typescript, baseDir, tsconfig, host, env)
|
|
976
|
-
// --resources: extensions/filenames carried as opaque assets instead of
|
|
977
|
-
|
|
1117
|
+
// --resources (else the config's): extensions/filenames carried as opaque assets instead of
|
|
1118
|
+
// failing "can't carry". --package-json, else the config's `packageJSON`: see withManifests below.
|
|
1119
|
+
const { resources: resourceSet, packageJSON: withManifests } = fieldBuildOptions('buildResolvedJsBundle', { cwd, scope, resources, packageJSON, host })
|
|
978
1120
|
|
|
979
1121
|
const formatsByRel = new Map()
|
|
980
1122
|
// Reached files the scanner tagged as resources (rel keys); read as bytes below, not UTF-8 source.
|
|
@@ -983,7 +1125,15 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
983
1125
|
const edges = new Map()
|
|
984
1126
|
const reached = new Set() // absolute paths reached on any platform
|
|
985
1127
|
let usesEmpty = false
|
|
986
|
-
|
|
1128
|
+
// What a disabled import resolves to: under --metro Metro's own empty module where the project
|
|
1129
|
+
// has it (metroEmptyModule), as Metro resolves it; else the reserved synthetic one.
|
|
1130
|
+
const metroEmpty = metro ? metroEmptyModule(baseDir, host) : null
|
|
1131
|
+
const emptyTarget = metroEmpty === null ? EMPTY_MODULE_PATH : toRel(metroEmpty)
|
|
1132
|
+
|
|
1133
|
+
// --babel-aliases: the same aliasing as --babel's, from a JSON file of the project, for every platform alike.
|
|
1134
|
+
const fileAliases = aliasesFile === undefined ? null : createAliases(readAliasesFile(baseDir, aliasesFile, host), baseDir)
|
|
1135
|
+
// The edges each platform's scan left out above the root (withinRoot's leftOut), across platforms.
|
|
1136
|
+
const leftOutEdges = []
|
|
987
1137
|
for (const platform of platforms) {
|
|
988
1138
|
const field = fieldResolverFor(platform, { mainFields, metro, conditions: scanConditions, typescript, typescriptPaths, host })
|
|
989
1139
|
const { extras } = field
|
|
@@ -997,8 +1147,16 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
997
1147
|
// Without --typescript, the field resolver --typescript would build names the file a miss would
|
|
998
1148
|
// land on: a hint in the unresolved report, never an edge (see Scan#typescriptCandidate).
|
|
999
1149
|
const typescriptResolve = typescript || metroResolver ? null : fieldResolverFor(platform, { mainFields, metro, conditions: scanConditions, typescript: true, typescriptPaths, host }).resolver
|
|
1000
|
-
|
|
1001
|
-
|
|
1150
|
+
// --babel: a specifier the project's babel-plugin-module-resolver rewrites resolves as rewritten,
|
|
1151
|
+
// as Metro resolves it after Babel; its edge stays keyed by the specifier the source holds.
|
|
1152
|
+
const aliases = babel ? createBabelAliases({ projectDir: baseDir, platform }) : fileAliases
|
|
1153
|
+
const aliased = (resolveFn) => (aliases && resolveFn ? (file, spec, conds) => resolveFn(file, aliases(file, spec) ?? spec, conds) : resolveFn)
|
|
1154
|
+
const scanned = scan(absEntries, { conditions: extras, resolve: aliased(resolver), typescriptResolve: aliased(typescriptResolve), jsx, flow, resources: resourceSet, define, host })
|
|
1155
|
+
// Only what lies within the root is carried; one the entries link eagerly is refused (see withinRoot).
|
|
1156
|
+
const { scanner, outside, leftOut } = withinRoot(scanned, (url) => relWithin(fileURLToPath(url)) !== null)
|
|
1157
|
+
for (const url of outside) toRel(fileURLToPath(url))
|
|
1158
|
+
reportScanIssues({ ...analyzeScanner(scanner, { baseDir }), leftOut }, { baseDir, label: platform ?? 'mainFields', root: ' at .' })
|
|
1159
|
+
leftOutEdges.push(...leftOut)
|
|
1002
1160
|
|
|
1003
1161
|
const platformKey = platform ?? '*' // '*' is a private placeholder for the single mainFields pass; it never unflattens
|
|
1004
1162
|
for (const [url, info] of scanner.files) {
|
|
@@ -1006,11 +1164,13 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1006
1164
|
const rel = toRel(abs)
|
|
1007
1165
|
reached.add(abs)
|
|
1008
1166
|
if (info.resource) resourceRels.add(rel)
|
|
1009
|
-
|
|
1167
|
+
// Under --metro a code file has no format, as the Metro plugin records it: Metro transforms
|
|
1168
|
+
// it from source, and Node's module/commonjs isn't what it runs.
|
|
1169
|
+
formatsByRel.set(rel, metro && !info.resource ? undefined : info.format)
|
|
1010
1170
|
for (const e of info.edges) {
|
|
1011
1171
|
if (e.builtin || e.dynamic) continue
|
|
1012
1172
|
let target
|
|
1013
|
-
if (e.empty) { usesEmpty = true; target =
|
|
1173
|
+
if (e.empty) { usesEmpty = true; target = emptyTarget }
|
|
1014
1174
|
else if (e.child) target = toRel(fileURLToPath(e.child))
|
|
1015
1175
|
else continue // unresolved (already warned/thrown by reportScanIssues)
|
|
1016
1176
|
if (!edges.has(rel)) edges.set(rel, new Map())
|
|
@@ -1021,6 +1181,10 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1021
1181
|
}
|
|
1022
1182
|
}
|
|
1023
1183
|
|
|
1184
|
+
// One platform leaving out an edge another resolves within the root is a split too: collapsed
|
|
1185
|
+
// below, the edge would serve that platform the other's file in its place.
|
|
1186
|
+
refuseSplit(leftOutEdges.filter((e) => edges.get(toRel(fileURLToPath(e.parentURL)))?.has(e.spec)), baseDir)
|
|
1187
|
+
|
|
1024
1188
|
// Read each reached file once: bytes for the bundle, integrity for the lockfile. Source is
|
|
1025
1189
|
// stored as UTF-8 text, so non-UTF-8 bytes would diverge from the hashed bytes -- reject them.
|
|
1026
1190
|
const sources = new Map()
|
|
@@ -1035,6 +1199,8 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1035
1199
|
// byte-derived format (here and in the --metro native capture below).
|
|
1036
1200
|
const putResource = (rel, buf) => (isUtf8(buf) ? put(rel, buf.toString('utf8'), 'resource', buf) : put(rel, buf.toString('base64'), 'resource:base64', buf))
|
|
1037
1201
|
const realBase = host.realpath(baseDir)
|
|
1202
|
+
// Metro's empty module is carried as the file it is, a code file of Metro's (no format).
|
|
1203
|
+
if (usesEmpty && metroEmpty !== null) reached.add(metroEmpty)
|
|
1038
1204
|
for (const abs of reached) {
|
|
1039
1205
|
const rel = toRel(abs)
|
|
1040
1206
|
// Security: a resolved file arrives by its real path, which toRel already holds to the root,
|
|
@@ -1051,21 +1217,21 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1051
1217
|
put(rel, buf.toString('utf8'), formatsByRel.get(rel), buf)
|
|
1052
1218
|
}
|
|
1053
1219
|
}
|
|
1054
|
-
if (usesEmpty) {
|
|
1220
|
+
if (usesEmpty && metroEmpty === null) {
|
|
1055
1221
|
// Refuse to shadow a real reached file sitting at the reserved empty-module path.
|
|
1056
1222
|
if (formatsByRel.has(EMPTY_MODULE_PATH)) {
|
|
1057
1223
|
throw new Error(`Bundle needs the reserved empty-module path ${EMPTY_MODULE_PATH}, but the project has a real file there`)
|
|
1058
1224
|
}
|
|
1059
|
-
put(EMPTY_MODULE_PATH, '', 'commonjs', Buffer.alloc(0))
|
|
1225
|
+
put(EMPTY_MODULE_PATH, '', metro ? undefined : 'commonjs', Buffer.alloc(0))
|
|
1060
1226
|
}
|
|
1061
1227
|
|
|
1062
1228
|
// The package a bundled file is in (findPackageMetadata: its pkgDir and identity, null where no
|
|
1063
1229
|
// manifest names one), memoized per directory so a package's many files don't each re-walk to it.
|
|
1064
1230
|
const packageOf = packageLookup(baseDir, { host })
|
|
1065
1231
|
|
|
1066
|
-
// --metro also carries
|
|
1067
|
-
//
|
|
1068
|
-
//
|
|
1232
|
+
// --metro also carries the native build inputs of each native package the app links, as the Metro
|
|
1233
|
+
// plugin does: the bundled packages installed or linked into node_modules, and those React Native
|
|
1234
|
+
// links unimported. Native source is stored as code under a language tag; other assets as
|
|
1069
1235
|
// 'resource'/'resource:base64'.
|
|
1070
1236
|
if (metro) {
|
|
1071
1237
|
const pkgDirs = new Map() // package dir -> its package's name
|
|
@@ -1136,30 +1302,40 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1136
1302
|
}
|
|
1137
1303
|
}
|
|
1138
1304
|
}
|
|
1305
|
+
// And the app's packages React Native links whether JS imports them or not (`react-native config`'s
|
|
1306
|
+
// list, read as data), by their real path, but one above the root, which the plugin passes over too.
|
|
1307
|
+
for (const dir of linkedNativePackages(baseDir, host)) {
|
|
1308
|
+
let rel
|
|
1309
|
+
try {
|
|
1310
|
+
rel = toRel(host.realpath(dir))
|
|
1311
|
+
} catch {
|
|
1312
|
+
continue
|
|
1313
|
+
}
|
|
1314
|
+
if (!pkgDirs.has(rel)) pkgDirs.set(rel, readPackageJson(baseDir, `${rel}/package.json`, { host })?.name)
|
|
1315
|
+
}
|
|
1316
|
+
// Each one's native build inputs, walked whole (nativeInputs, shared with the plugin), read only
|
|
1317
|
+
// once its real path is held to the root.
|
|
1318
|
+
const nativeFs = {
|
|
1319
|
+
readdir: (abs) => host.readdir(abs),
|
|
1320
|
+
stat: (abs) => host.stat(abs),
|
|
1321
|
+
readFile(abs) {
|
|
1322
|
+
assertRealPathWithinBase(realBase, baseDir, toRel(abs), host)
|
|
1323
|
+
return host.readFile(abs)
|
|
1324
|
+
},
|
|
1325
|
+
}
|
|
1139
1326
|
for (const [pkgDir, name] of [...pkgDirs].toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
|
1140
1327
|
const pkgAbs = join(baseDir, pkgDir)
|
|
1141
1328
|
// react-native core isn't a Pod (config reports it via reactNativePath, not `dependencies`),
|
|
1142
|
-
//
|
|
1143
|
-
// way a native dep's ios/android surface is walked; every other dep gets its ios/android + podspecs.
|
|
1329
|
+
// but its native source (React/, ReactCommon/, ReactAndroid/, ...) is walked all the same.
|
|
1144
1330
|
const isRnCore = name === 'react-native'
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
const rel = toRel(abs)
|
|
1149
|
-
if (sources.has(rel)) continue
|
|
1150
|
-
assertRealPathWithinBase(realBase, baseDir, rel, host)
|
|
1151
|
-
// classifyNativeCapture (shared with the StasisMetro plugin) returns action skip/code/resource with a format tag.
|
|
1152
|
-
const byName = classifyNativeCapture(rel)
|
|
1153
|
-
if (byName.action === 'skip') continue
|
|
1154
|
-
const buf = host.readFile(abs)
|
|
1155
|
-
// Byte-level rules (prebuilt binaries, binary plists) -- see refineNativeCapture.
|
|
1156
|
-
const { action, format } = refineNativeCapture(byName, rel, buf, resourceSet)
|
|
1157
|
-
if (action === 'skip') continue
|
|
1331
|
+
if (!isRnCore && !looksNative(pkgAbs, nativeFs)) continue
|
|
1332
|
+
for (const { file, source, action, format } of nativeInputs(pkgAbs, nativeFs, { resources: resourceSet, skip: (abs) => sources.has(toRel(abs)) })) {
|
|
1333
|
+
const rel = toRel(file)
|
|
1158
1334
|
if (action === 'code') {
|
|
1159
|
-
if (!isUtf8(
|
|
1160
|
-
put(rel,
|
|
1335
|
+
if (!isUtf8(source)) throw new Error(`native source is not valid UTF-8: ${rel}`)
|
|
1336
|
+
put(rel, source.toString('utf8'), format, source)
|
|
1161
1337
|
} else {
|
|
1162
|
-
putResource(rel,
|
|
1338
|
+
putResource(rel, source)
|
|
1163
1339
|
}
|
|
1164
1340
|
}
|
|
1165
1341
|
// RN core's `.js` build scripts the classify loop skips (Metro-owned by extension, but never in
|
|
@@ -1177,23 +1353,44 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1177
1353
|
}
|
|
1178
1354
|
}
|
|
1179
1355
|
}
|
|
1356
|
+
|
|
1357
|
+
// And the project's configs the Metro plugin's run loads, which nothing the app imports reaches:
|
|
1358
|
+
// Metro's and the React Native CLI's, and with --babel or --babel-aliases the Babel config Metro's
|
|
1359
|
+
// transformer runs. Each file itself, in the format Node loads it in (its package's `type`, else
|
|
1360
|
+
// the one Node detects from its syntax, as Scan#parseFile has it), not what it imports.
|
|
1361
|
+
const configs = [...METRO_CONFIG_FILES, ...(babel || aliasesFile !== undefined ? [BABEL_CONFIG_FILE] : [])]
|
|
1362
|
+
const configScan = new Scan({ host })
|
|
1363
|
+
for (const rel of configs) {
|
|
1364
|
+
const abs = join(baseDir, rel)
|
|
1365
|
+
if (sources.has(rel) || !host.stat(abs)?.isFile()) continue
|
|
1366
|
+
assertRealPathWithinBase(realBase, baseDir, rel, host)
|
|
1367
|
+
const buf = host.readFile(abs)
|
|
1368
|
+
if (!isUtf8(buf)) throw new Error(`config is not valid UTF-8: ${rel}`)
|
|
1369
|
+
const parsed = configScan.parseFile(abs)
|
|
1370
|
+
put(rel, buf.toString('utf8'), parsed.format ?? parsed.declared ?? 'commonjs', buf)
|
|
1371
|
+
}
|
|
1180
1372
|
}
|
|
1181
1373
|
|
|
1182
|
-
// --package-json: fold each bundled module's package.json into
|
|
1183
|
-
// the companion lockfile) even when the scan never reached it
|
|
1184
|
-
//
|
|
1185
|
-
//
|
|
1186
|
-
//
|
|
1187
|
-
|
|
1188
|
-
|
|
1374
|
+
// --package-json (or the config's packageJSON): fold each bundled module's package.json into
|
|
1375
|
+
// `sources` (and its integrity into the companion lockfile) even when the scan never reached it,
|
|
1376
|
+
// and the nearer one a reached file of it has (scopeManifestOf: a `{"type":"module"}` marker such
|
|
1377
|
+
// as `esm/package.json`), which Metro's resolver reads for the file, as the State path does.
|
|
1378
|
+
// Buckets are the ones assembleCodeBundle derives, from the same `packageOf` (its pkgDir, else the
|
|
1379
|
+
// '.' workspace bucket). readModuleManifest applies the read/validate rules shared with the State
|
|
1380
|
+
// path (containment, UTF-8-aborts); no identity check here -- these buckets are all fresh from disk.
|
|
1381
|
+
if (withManifests) {
|
|
1382
|
+
const found = new Map()
|
|
1383
|
+
const exists = (rel) => found.get(rel) ?? found.set(rel, packageJSONStat(host, join(baseDir, rel))?.isFile() ?? false).get(rel)
|
|
1384
|
+
const manifests = new Set()
|
|
1189
1385
|
for (const abs of reached) {
|
|
1190
1386
|
const rel = toRel(abs)
|
|
1191
|
-
const
|
|
1192
|
-
if (
|
|
1193
|
-
|
|
1387
|
+
const pkgDir = packageOf(rel)?.pkgDir ?? (splitNodeModulesPath(rel) ? undefined : '.')
|
|
1388
|
+
if (pkgDir === undefined) continue
|
|
1389
|
+
manifests.add(moduleFileKey(pkgDir, 'package.json'))
|
|
1390
|
+
const nearest = scopeManifestOf(rel, pkgDir, exists)
|
|
1391
|
+
if (nearest !== undefined) manifests.add(nearest)
|
|
1194
1392
|
}
|
|
1195
|
-
for (const
|
|
1196
|
-
const rel = moduleFileKey(pkgDir, 'package.json')
|
|
1393
|
+
for (const rel of manifests) {
|
|
1197
1394
|
if (sources.has(rel)) continue
|
|
1198
1395
|
const buf = readModuleManifest({ baseDir, realBase, rel, host })
|
|
1199
1396
|
if (!buf) continue
|
|
@@ -1228,6 +1425,7 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1228
1425
|
conditionKey: '*',
|
|
1229
1426
|
host,
|
|
1230
1427
|
packageOf,
|
|
1428
|
+
consumer: metro ? 'bundle:metro' : 'bundle',
|
|
1231
1429
|
})
|
|
1232
1430
|
|
|
1233
1431
|
// The companion lockfile mirrors the bundle, swapping file content for its integrity.
|
|
@@ -1252,7 +1450,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
|
|
|
1252
1450
|
|
|
1253
1451
|
// Classify entries into their single shared language and check option applicability; `name` prefixes
|
|
1254
1452
|
// errors. A directory entry (resolved against `cwd`, on `host`) stands for the .sol files under it: Solidity only.
|
|
1255
|
-
|
|
1453
|
+
// `partial`: the options may yet be completed by a stasis.config.json entry's (configuredBuilds), so
|
|
1454
|
+
// what one needs of another one there could set (`--platforms` of `--metro`) is left to the build.
|
|
1455
|
+
function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, manifests, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, host = diskHost, fetched, partial = false }) {
|
|
1256
1456
|
if (!Array.isArray(entries) || entries.length === 0) {
|
|
1257
1457
|
throw new Error(`${name}: at least one entry file is required`)
|
|
1258
1458
|
}
|
|
@@ -1299,7 +1499,7 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
|
|
|
1299
1499
|
throw new Error(`${name}: --typescript is only valid for JS bundles`)
|
|
1300
1500
|
}
|
|
1301
1501
|
// --tsconfig names the config whose `paths` aliases --typescript honours; meaningless without it.
|
|
1302
|
-
if (tsconfig !== undefined && !typescript) {
|
|
1502
|
+
if (tsconfig !== undefined && !typescript && !partial) {
|
|
1303
1503
|
throw new Error(`${name}: --tsconfig is only valid with --typescript`)
|
|
1304
1504
|
}
|
|
1305
1505
|
// --resources carries allowlisted assets reached through the JS import graph; JS-only. The list
|
|
@@ -1318,6 +1518,10 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
|
|
|
1318
1518
|
if (jsx && kind !== 'js') {
|
|
1319
1519
|
throw new Error(`${name}: --jsx is only valid for JS bundles`)
|
|
1320
1520
|
}
|
|
1521
|
+
// --define folds the globals it gives in the JS scan's branch tests; no other language is scanned for them.
|
|
1522
|
+
if (parseDefine(name, define).size > 0 && kind !== 'js') {
|
|
1523
|
+
throw new Error(`${name}: --define is only valid for JS bundles`)
|
|
1524
|
+
}
|
|
1321
1525
|
// --package-json folds each bundled module's npm package.json in; JS-only (the sol/php/bash/rust
|
|
1322
1526
|
// bucketizers group by their own ecosystems' manifests, not an npm package.json).
|
|
1323
1527
|
if (packageJSON && kind !== 'js') {
|
|
@@ -1335,58 +1539,101 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
|
|
|
1335
1539
|
if (mainFields !== undefined) {
|
|
1336
1540
|
throw new Error(`${name}: --mainFields can't be combined with --metro (it sets its own mainFields)`)
|
|
1337
1541
|
}
|
|
1338
|
-
if (!Array.isArray(platforms) || platforms.length === 0) {
|
|
1542
|
+
if ((!Array.isArray(platforms) || platforms.length === 0) && !partial) {
|
|
1339
1543
|
throw new Error(`${name}: --metro requires --platforms (e.g. --platforms=ios,android)`)
|
|
1340
1544
|
}
|
|
1341
1545
|
// A platform name becomes an edge key: reject '/' (Bundle/Lockfile parse refuse it) and
|
|
1342
1546
|
// the reserved '*' placeholder, so the writer never emits a map the readers reject.
|
|
1343
|
-
for (const p of platforms) {
|
|
1547
|
+
for (const p of Array.isArray(platforms) ? platforms : []) {
|
|
1344
1548
|
if (typeof p !== 'string' || p.length === 0 || p === '*' || p.includes('/')) {
|
|
1345
1549
|
throw new Error(`${name}: invalid platform '${p}' (a platform name can't be empty, contain '/', or be '*')`)
|
|
1346
1550
|
}
|
|
1347
1551
|
}
|
|
1348
|
-
} else if (Array.isArray(platforms) && platforms.length > 0) {
|
|
1552
|
+
} else if (Array.isArray(platforms) && platforms.length > 0 && !partial) {
|
|
1349
1553
|
throw new Error(`${name}: --platforms is only valid with --metro`)
|
|
1350
1554
|
}
|
|
1351
1555
|
// --metro-resolver swaps in the project's real metro-resolver; it only means something under --metro.
|
|
1352
1556
|
if (metroResolver && !metro) {
|
|
1353
1557
|
throw new Error(`${name}: --metro-resolver is only valid with --metro`)
|
|
1354
1558
|
}
|
|
1559
|
+
// --babel takes the import aliases of the project's Babel config, which Metro runs; not otherwise.
|
|
1560
|
+
if (babel && !metro) {
|
|
1561
|
+
throw new Error(`${name}: --babel is only valid with --metro`)
|
|
1562
|
+
}
|
|
1563
|
+
// --babel-aliases takes the same aliases from a JSON file instead, so the two don't combine.
|
|
1564
|
+
if (babelAliases !== undefined) {
|
|
1565
|
+
if (typeof babelAliases !== 'string' || babelAliases === '') throw new TypeError(`${name}: babelAliases must be a path to a JSON file`)
|
|
1566
|
+
if (!metro && !partial) throw new Error(`${name}: --babel-aliases is only valid with --metro`)
|
|
1567
|
+
if (babel) throw new Error(`${name}: --babel-aliases can't be combined with --babel (both set the import aliases)`)
|
|
1568
|
+
}
|
|
1355
1569
|
// metro-resolver has no TS extension substitution, so --typescript would silently not apply -- reject it.
|
|
1356
1570
|
if (typescript && metroResolver) {
|
|
1357
1571
|
throw new Error(`${name}: --typescript is not supported with --metro-resolver (the project's metro-resolver doesn't substitute .js -> .ts)`)
|
|
1358
1572
|
}
|
|
1359
|
-
// The field resolver always emits full-scope
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
}
|
|
1573
|
+
// The field resolver always emits full-scope: a narrower --scope, or one from stasis.config.json,
|
|
1574
|
+
// would be silently ignored -- reject it here, before anything is built (or fetched).
|
|
1575
|
+
if (mainFields !== undefined || metro) fieldBuildOptions(name, { cwd, scope, resources, host })
|
|
1363
1576
|
return kind
|
|
1364
1577
|
}
|
|
1365
1578
|
|
|
1366
1579
|
// A JS bundle as `stasis bundle` builds it: by the legacy-field resolver with `mainFields` or
|
|
1367
1580
|
// `metro`, whose per-platform edges and synthetic empty module a State can't hold, else through a
|
|
1368
1581
|
// State, which detects the bundle's repo itself. `root` is the directory the bundle's paths are
|
|
1369
|
-
// relative to: cwd for the resolver's, the State's root for the State's.
|
|
1582
|
+
// relative to: cwd for the resolver's, the State's root for the State's. `extra` and `outputsAt` are
|
|
1583
|
+
// buildJsBundle's, for the State's alone (see withExtra).
|
|
1370
1584
|
// -> { bundle, lockfile: () => Lockfile, stateBuilt, root }
|
|
1371
|
-
async function buildJs({ mainFields, platforms, metro, metroResolver, innermostRoot, ...options }) {
|
|
1585
|
+
async function buildJs({ mainFields, platforms, metro, metroResolver, babel, babelAliases, innermostRoot, extra, outputsAt, ...options }) {
|
|
1372
1586
|
if (metro || mainFields !== undefined) {
|
|
1373
|
-
const built = await buildResolvedJsBundle({ ...options, mainFields: metro ? METRO_MAIN_FIELDS : mainFields, platforms: metro ? platforms : [null], metro: Boolean(metro), metroResolver: Boolean(metroResolver) })
|
|
1587
|
+
const built = await buildResolvedJsBundle({ ...options, mainFields: metro ? METRO_MAIN_FIELDS : mainFields, platforms: metro ? platforms : [null], metro: Boolean(metro), metroResolver: Boolean(metroResolver), babel: Boolean(babel), babelAliases })
|
|
1374
1588
|
return { bundle: built.bundle, lockfile: () => built.lockfile, stateBuilt: false, root: resolve(options.cwd) }
|
|
1375
1589
|
}
|
|
1376
|
-
const state = await buildJsBundle({ ...options, innermostRoot })
|
|
1377
|
-
|
|
1378
|
-
|
|
1590
|
+
const state = await buildJsBundle({ ...options, innermostRoot, extra, outputsAt })
|
|
1591
|
+
const bundle = state.sourceBundle
|
|
1592
|
+
// Stamp the `bundle` consumer (the static build carries none), unless `extra` added files: then
|
|
1593
|
+
// the State attributes each file, to `bundle` or `extra`.
|
|
1594
|
+
return { bundle: bundle.reason === undefined ? bundle.withReason('bundle') : bundle, lockfile: () => state.lockfile, stateBuilt: true, root: state.root }
|
|
1379
1595
|
}
|
|
1380
1596
|
|
|
1381
|
-
//
|
|
1382
|
-
//
|
|
1597
|
+
// `built` (buildOfKind's, built in `cwd` without a State, or the union of bundleCommand's `builds` rooted there) with the files the stasis.config.json
|
|
1598
|
+
// there names in `extra`, as `stasis add` adds them (extraArtifacts), into its bundle and its
|
|
1599
|
+
// lockfile; never one of `outputs` (the absolute paths the build writes), and resources by the
|
|
1600
|
+
// build's `resources` where given, else by the config's. A State-built bundle takes them in its
|
|
1601
|
+
// State instead, as `stasis run` does (State#includeExtra).
|
|
1602
|
+
function withExtra(built, cwd, outputs, resources) {
|
|
1603
|
+
const config = readConfigFile('bundle', cwd)
|
|
1604
|
+
const patterns = parseExtraOption(CONFIG_FILE, config?.extra)
|
|
1605
|
+
if (patterns.length === 0) return built
|
|
1606
|
+
// The union of `builds` (see bundleCommand) may be State-built in node_modules scope, which the
|
|
1607
|
+
// full-scope files `extra` adds can't join.
|
|
1608
|
+
if (built.bundle.config.scope !== 'full') throw new Error(`bundle: ${CONFIG_FILE}'s extra can't be added to a ${built.bundle.config.scope}-scope bundle of its entries`)
|
|
1609
|
+
const baseDir = resolve(cwd)
|
|
1610
|
+
const written = new Set(outputs.map((file) => toPosix(relative(baseDir, file))))
|
|
1611
|
+
const allowlist = resources === undefined ? parseResourcesOption(CONFIG_FILE, config.resources) : parseResourcesOption('--resources', resources)
|
|
1612
|
+
const added = extraArtifacts({ baseDir, patterns, resources: allowlist, bundle: built.bundle, outputs: written })
|
|
1613
|
+
if (added.bundle === null && added.carried.length === 0) return built
|
|
1614
|
+
// Each file attributed: to the build's own consumer (`bundle`, or `bundle:metro`, as codeBundle
|
|
1615
|
+
// stamps it), `extra`, or both, for one `extra` names that the build carries itself.
|
|
1616
|
+
const merged = added.bundle === null ? built.bundle : built.bundle.merge(added.bundle)
|
|
1617
|
+
const bundle = added.carried.length === 0 ? merged : merged.withReason('extra', added.carried)
|
|
1618
|
+
const { lockfile } = built
|
|
1619
|
+
return { ...built, bundle, ...(lockfile && added.lockfile && { lockfile: () => lockfile().merge(added.lockfile) }) }
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
// The bundle of `kind` (classifyEntries') built from buildBundle's options, from disk, with the files
|
|
1623
|
+
// stasis.config.json's `extra` names: a JS bundle's git dependencies at the commits their package
|
|
1624
|
+
// managers' records name (pinInstalledCommits). `outputsAt(root)` are the absolute paths the build
|
|
1625
|
+
// writes, given the root its paths are relative to.
|
|
1383
1626
|
// -> { bundle, lockfile: () => Lockfile, stateBuilt } (the last two of a JS bundle alone)
|
|
1384
|
-
async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, jsx, flow, typescript, tsconfig, resources, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }) {
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
if (kind === '
|
|
1389
|
-
|
|
1627
|
+
async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests, outputsAt = () => [], extra = true }) {
|
|
1628
|
+
const outputs = outputsAt(resolve(cwd))
|
|
1629
|
+
// Without `extra`, built as if the config named none (one of several builds of a bundle, see bundleCommand).
|
|
1630
|
+
const withExtraOf = (built, buildResources) => (extra ? withExtra(built, cwd, outputs, buildResources) : built)
|
|
1631
|
+
if (kind === 'sol') return withExtraOf({ bundle: await buildSolidityBundle({ cwd, env, entries, mappingFile, manifests }) })
|
|
1632
|
+
if (kind === 'php') return withExtraOf({ bundle: await buildPhpBundle({ cwd, entries }) })
|
|
1633
|
+
if (kind === 'bash') return withExtraOf({ bundle: await buildBashBundle({ cwd, entries }) })
|
|
1634
|
+
if (kind === 'rust') return withExtraOf({ bundle: await buildRustBundle({ cwd, entries, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }) })
|
|
1635
|
+
let built = await buildJs({ cwd, env, entries, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, extra, outputsAt })
|
|
1636
|
+
if (!built.stateBuilt) built = withExtraOf(built, resources)
|
|
1390
1637
|
pinInstalledCommits(built.bundle, built.root)
|
|
1391
1638
|
return built
|
|
1392
1639
|
}
|
|
@@ -1398,6 +1645,8 @@ async function buildOfKind(kind, { cwd, env, entries, mappingFile, manifests, sc
|
|
|
1398
1645
|
export function checkVfsOptions(name, options) {
|
|
1399
1646
|
const kind = classifyEntries(name, options)
|
|
1400
1647
|
if (options.metroResolver) throw new Error(`${name}: metroResolver is not supported`)
|
|
1648
|
+
// The project's Babel config is code, run from the disk.
|
|
1649
|
+
if (options.babel) throw new Error(`${name}: babel is not supported`)
|
|
1401
1650
|
const { generate = [] } = options
|
|
1402
1651
|
if (!Array.isArray(generate) || generate.some((step) => step !== 'prisma')) throw new TypeError(`${name}: generate must be an array of 'prisma'`)
|
|
1403
1652
|
if (generate.length > 0 && kind !== 'js') throw new Error(`${name}: --generate is only valid for JS bundles`)
|
|
@@ -1409,7 +1658,11 @@ export function checkVfsOptions(name, options) {
|
|
|
1409
1658
|
// would install, or its Solidity options, through the dependencies folder 'soldeer' would install; with
|
|
1410
1659
|
// nothing read from disk but tarballs and zips, nor from the environment: a Solidity bundle is
|
|
1411
1660
|
// built with foundry.toml's default profile, whatever FOUNDRY_PROFILE or remappings one sets, and no
|
|
1412
|
-
// EXODUS_STASIS_* setting is read.
|
|
1661
|
+
// EXODUS_STASIS_* setting is read. The entries the stasis.config.json in cwd names in its `entries`
|
|
1662
|
+
// (every one, where none are given) are built with their options there, as `stasis bundle` builds
|
|
1663
|
+
// them, but none that runs a program; an option given has to agree with theirs, one left out is
|
|
1664
|
+
// theirs (configuredBuilds).
|
|
1665
|
+
// `repo`, the informational `{ github, directory, commit }`,
|
|
1413
1666
|
// is the Bundle's, over what is detected in the Vfs as `stasis bundle` detects it on disk. `os`,
|
|
1414
1667
|
// `cpu` and `libc` are loadNodeModules'. Without a `packageManager`, it is the one whose lockfile
|
|
1415
1668
|
// installs cwd, where only one's does. `innermostRoot` is buildJsBundle's, for a JS bundle built
|
|
@@ -1424,6 +1677,7 @@ export function checkVfsOptions(name, options) {
|
|
|
1424
1677
|
// -> { bundle: Bundle, lockfile: Lockfile (of a JS bundle), stats, packageManager, root }
|
|
1425
1678
|
export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageManagerVersion, os, cpu, libc, repo, innermostRoot = false, generate = [], client, cache, ...options } = {}) {
|
|
1426
1679
|
const { checkCache, checkKind, checkTarget, checkVfs, loadTree, packageManagerFor, packageManagerOf, pinCommits, treeHost, vfsHost } = await import('../vfs-bundle/tree.js')
|
|
1680
|
+
const { configuredBuilds } = await import('./bundle-options.js')
|
|
1427
1681
|
checkVfs('buildVfsBundle', vfs)
|
|
1428
1682
|
checkTarget('buildVfsBundle', { os, cpu, libc })
|
|
1429
1683
|
checkCache('buildVfsBundle', cache)
|
|
@@ -1434,10 +1688,15 @@ export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageMa
|
|
|
1434
1688
|
cwd = project.realpath(posix.resolve('/', cwd))
|
|
1435
1689
|
packageManager = packageManagerFor('buildVfsBundle', project, cwd, { packageManager, packageManagerVersion, os })
|
|
1436
1690
|
const pm = packageManagerOf('buildVfsBundle', packageManager)
|
|
1437
|
-
|
|
1691
|
+
// The entries stasis.config.json's `entries` names, every one where none are given, each built
|
|
1692
|
+
// with its options there, which the options given agree with (configuredBuilds); else built with
|
|
1693
|
+
// the options given. Each build is checked with the options it is built with.
|
|
1694
|
+
const builds = configuredBuilds('buildVfsBundle', { cwd, host: project, entries: options.entries, options })?.builds ?? [options]
|
|
1695
|
+
if (builds.length === 0) throw new Error(`buildVfsBundle: no entries given, and ${CONFIG_FILE}'s entries name none`)
|
|
1696
|
+
for (const build of builds) checkKind('buildVfsBundle', checkVfsOptions('buildVfsBundle', { ...build, lockfile: options.lockfile, generate, cwd, host: project }), [packageManager])
|
|
1438
1697
|
// Checked before anything is fetched: an entry out of what the tree installs is in the project
|
|
1439
1698
|
// already. (A Solidity entry that is no .sol file is a directory, skipped where it is missing.)
|
|
1440
|
-
for (const entry of
|
|
1699
|
+
for (const entry of builds.flatMap((build) => build.entries)) {
|
|
1441
1700
|
const abs = posix.resolve(cwd, entry)
|
|
1442
1701
|
if (pm.kind === 'sol' && !abs.endsWith('.sol')) continue
|
|
1443
1702
|
if (!posix.relative(cwd, abs).split('/').includes(pm.installs) && project.stat(abs) === null) throw new Error(`entry not found: ${abs}`)
|
|
@@ -1449,20 +1708,35 @@ export async function buildVfsBundle({ vfs, packageManager, cwd = '/', packageMa
|
|
|
1449
1708
|
const outputs = await generatePrismaClients({ host, root: tree.root, projects: tree.projects })
|
|
1450
1709
|
if (outputs.length > 0) host = treeHost(tree, vfsHost(withPrismaClients(vfs, outputs)))
|
|
1451
1710
|
}
|
|
1452
|
-
const args = {
|
|
1453
|
-
const
|
|
1711
|
+
const args = { cwd, host, env: {} }
|
|
1712
|
+
const builts = []
|
|
1713
|
+
for (const build of builds) {
|
|
1714
|
+
// eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
|
|
1715
|
+
const built = pm.kind === 'sol' ? { bundle: await buildSolidityBundle({ ...build, ...args }), root: cwd } : await buildJs({ ...build, ...args, innermostRoot })
|
|
1716
|
+
// Rooted at cwd, where `stasis bundle` detects its repo.
|
|
1717
|
+
if (repo === undefined && !built.stateBuilt) built.bundle.repo ??= detectRepo(cwd, host)
|
|
1718
|
+
builts.push(built)
|
|
1719
|
+
}
|
|
1720
|
+
// Merged as bundleCommand merges its builds: rooted where every one of them is.
|
|
1721
|
+
const { root } = builts[0]
|
|
1722
|
+
const other = builts.findIndex((built) => built.root !== root)
|
|
1723
|
+
if (other !== -1) {
|
|
1724
|
+
throw new Error(`buildVfsBundle: ${builds[0].entries[0]} and ${builds[other].entries[0]} can't be bundled together: their bundles' paths are relative to different roots (${root} and ${builts[other].root})`)
|
|
1725
|
+
}
|
|
1726
|
+
const { bundle, lockfile } = builts.reduce((a, b) => ({ bundle: a.bundle.merge(b.bundle), lockfile: a.lockfile && (() => a.lockfile().merge(b.lockfile())) }))
|
|
1454
1727
|
if (repo !== undefined) bundle.repo = repo
|
|
1455
|
-
// Rooted at cwd, where `stasis bundle` detects its repo.
|
|
1456
|
-
else if (!stateBuilt) bundle.repo ??= detectRepo(cwd, host)
|
|
1457
1728
|
pinCommits(bundle, root, tree)
|
|
1458
1729
|
return { bundle, lockfile: lockfile?.(), stats: tree.stats, packageManager, root }
|
|
1459
1730
|
}
|
|
1460
1731
|
|
|
1461
1732
|
// Programmatic equivalent of `stasis bundle`: build and return an in-memory Bundle without
|
|
1462
|
-
// writing to disk. Files are attributed to the `bundle` consumer
|
|
1463
|
-
// (--mapping|--manifests/.sol, --scope|--conditions|--mainFields|--metro|--jsx
|
|
1464
|
-
|
|
1465
|
-
|
|
1733
|
+
// writing to disk. Files are attributed to the `bundle` consumer (`bundle:metro` with `metro`).
|
|
1734
|
+
// Option applicability (--mapping|--manifests/.sol, --scope|--conditions|--mainFields|--metro|--jsx|
|
|
1735
|
+
// --flow|--typescript|--define/JS) is enforced by classifyEntries. `define` gives globals their
|
|
1736
|
+
// values (`{ __DEV__: false, 'process.env.NODE_ENV': 'production' }`), whose dead branches' imports
|
|
1737
|
+
// are left out (see define.js).
|
|
1738
|
+
export async function buildBundle({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, scope, conditions, mainFields, platforms, metro, metroResolver, babel = false, babelAliases, jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false } = {}) {
|
|
1739
|
+
const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
|
|
1466
1740
|
return (await buildOfKind(classifyEntries('buildBundle', options), options)).bundle
|
|
1467
1741
|
}
|
|
1468
1742
|
|
|
@@ -1472,30 +1746,64 @@ export async function buildBundle({ cwd = process.cwd(), env = process.env, entr
|
|
|
1472
1746
|
// with `--conditions` it attests the conditions-selected graph, so a plain
|
|
1473
1747
|
// `stasis run --lock=frozen` (which doesn't replay them) fails closed -- pair it with
|
|
1474
1748
|
// `--bundle=load` or replay the conditions. `add` unions the fresh build into the bundle
|
|
1475
|
-
// already on disk (strict; a conflicting file throws) and can't target stdout.
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1749
|
+
// already on disk (strict; a conflicting file throws) and can't target stdout. `builds`, in place
|
|
1750
|
+
// of `entries` and the options building them, is several builds' (each `{ entries, ...options }`,
|
|
1751
|
+
// as stasis.config.json's `bundle` gives an entry its own, see bundle-options.js), whose bundles
|
|
1752
|
+
// (and lockfiles) are one's: their strict union, rooted where every one of them is.
|
|
1753
|
+
export async function bundleCommand({ cwd = process.cwd(), env = process.env, entries, mappingFile, manifests = false, output, scope, lockfile, conditions, mainFields, platforms, metro, metroResolver, babel = false, babelAliases, jsx = false, flow = false, typescript = false, tsconfig, resources, define, packageJSON = false, cargo = false, cargoFeatures = [], cargoNoDefaultFeatures = false, cargoAllFeatures = false, cargoTarget = null, cargoManifests = false, brotliQuality, add = false, builds } = {}) {
|
|
1754
|
+
const options = { cwd, env, entries, mappingFile, manifests, scope, conditions, mainFields, platforms, metro, metroResolver, babel, babelAliases, jsx, flow, typescript, tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
|
|
1755
|
+
if (builds !== undefined) {
|
|
1756
|
+
if (!Array.isArray(builds) || builds.length === 0) throw new TypeError('bundleCommand: builds must be a non-empty array')
|
|
1757
|
+
const given = Object.entries(options).find(([key, value]) => !['cwd', 'env'].includes(key) && value !== undefined && value !== false && value !== null && !(Array.isArray(value) && value.length === 0))
|
|
1758
|
+
if (given) throw new TypeError(`bundleCommand: ${given[0]} can't be combined with builds (each build sets its own)`)
|
|
1759
|
+
}
|
|
1760
|
+
// Each build's options, the defaults above where it leaves one out.
|
|
1761
|
+
const defaults = { manifests, babel, jsx, flow, typescript, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
|
|
1762
|
+
const plans = (builds ?? [{}]).map((build) => ({ ...options, ...defaults, ...build, cwd, env }))
|
|
1763
|
+
const kinds = plans.map((plan) => classifyEntries('bundleCommand', { ...plan, lockfile }))
|
|
1479
1764
|
|
|
1480
1765
|
// --add has nothing to merge into on stdout (write-only).
|
|
1481
1766
|
if (add && output === '-') {
|
|
1482
1767
|
throw new Error('bundleCommand: --add cannot be combined with --output=- (nothing to merge into on stdout)')
|
|
1483
1768
|
}
|
|
1484
1769
|
|
|
1485
|
-
|
|
1486
|
-
|
|
1770
|
+
// The files this build writes, never taken into `extra`, given the root its paths are relative to:
|
|
1771
|
+
// the bundle (by default at that root, see `target` below) and the lockfile.
|
|
1772
|
+
const outputsAt = (root) => [output ?? join(root, DEFAULT_BUNDLE_FILE), lockfile].filter((file) => file !== undefined && file !== '-').map((file) => resolve(cwd, file))
|
|
1773
|
+
// With `builds` (stasis.config.json's entries, however many builds they make), `extra` is the
|
|
1774
|
+
// bundle's, not any build's: added to their union below.
|
|
1775
|
+
const bundleExtra = builds !== undefined
|
|
1776
|
+
const builts = []
|
|
1777
|
+
for (const [i, plan] of plans.entries()) {
|
|
1778
|
+
// eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
|
|
1779
|
+
builts.push(await buildOfKind(kinds[i], { ...plan, outputsAt, extra: !bundleExtra }))
|
|
1780
|
+
}
|
|
1487
1781
|
// The directory the bundle's paths are relative to: a State-built JS bundle's root, which is the
|
|
1488
1782
|
// project's at or above cwd (a workspace package's is the workspace root's), else cwd.
|
|
1489
|
-
const
|
|
1783
|
+
const roots = builts.map((built) => built.root ?? resolve(cwd))
|
|
1784
|
+
const root = roots[0]
|
|
1785
|
+
const other = roots.findIndex((r) => r !== root)
|
|
1786
|
+
if (other !== -1) {
|
|
1787
|
+
throw new Error(`bundleCommand: ${plans[0].entries[0]} and ${plans[other].entries[0]} can't be bundled together: their bundles' paths are relative to different roots (${root} and ${roots[other]})`)
|
|
1788
|
+
}
|
|
1490
1789
|
// By default the bundle goes there, where `stasis run --bundle=load` discovers it. In cwd below
|
|
1491
1790
|
// the root it would load as rooted at cwd, and root the next `stasis bundle` there too, out of the
|
|
1492
1791
|
// files above it.
|
|
1493
1792
|
const target = output ?? relative(resolve(cwd), join(root, DEFAULT_BUNDLE_FILE))
|
|
1494
|
-
// Only a JS bundle has a lockfile (classifyEntries refuses one for the others).
|
|
1495
|
-
let lockData = lockfile ? built.lockfile().serialize() : undefined
|
|
1496
1793
|
|
|
1497
1794
|
// State-built bundles keep the State root's repo (no cwd fallback: their paths are relative to that root).
|
|
1498
|
-
if (!built.stateBuilt) bundle.repo ??= detectRepo(cwd)
|
|
1795
|
+
for (const built of builts) if (!built.stateBuilt) built.bundle.repo ??= detectRepo(cwd)
|
|
1796
|
+
let union = builts.reduce((a, b) => ({ bundle: a.bundle.merge(b.bundle), lockfile: a.lockfile && (() => a.lockfile().merge(b.lockfile())) }))
|
|
1797
|
+
if (bundleExtra) {
|
|
1798
|
+
// Once, whatever the builds' order: to their union, whose own record of a file stands, by the
|
|
1799
|
+
// allowlist of the stasis.config.json at the root, not any one entry's `resources`.
|
|
1800
|
+
const withExtras = withExtra(union, root, outputsAt(root))
|
|
1801
|
+
if (withExtras !== union) pinInstalledCommits(withExtras.bundle, root)
|
|
1802
|
+
union = withExtras
|
|
1803
|
+
}
|
|
1804
|
+
let { bundle } = union
|
|
1805
|
+
// Only a JS bundle has a lockfile (classifyEntries refuses one for the others).
|
|
1806
|
+
let lockData = lockfile ? union.lockfile().serialize() : undefined
|
|
1499
1807
|
|
|
1500
1808
|
// --add: union the fresh build into the existing on-disk bundle; a conflicting file throws. Skipped when nothing is on disk.
|
|
1501
1809
|
const outAbs = target === '-' ? undefined : resolve(cwd, target)
|