@exodus/stasis 1.0.0-beta.14 → 1.0.0-beta.15

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/src/cmd/bundle.js CHANGED
@@ -6,22 +6,23 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
6
6
  import { Bundle, isValidRepoField } from '@exodus/stasis-core/bundle'
7
7
  import { Lockfile } from '@exodus/stasis-core/lockfile'
8
8
  import { extraArtifacts } from '@exodus/stasis-core/add'
9
- import { getParser, importsTypescriptByOutputName, literalSpec, scan, scanCounts } from '../scan.js'
10
- import { parseDefine } from '../define.js'
11
- import { METRO_ASSET_EXTS, METRO_SOURCE_EXTS, createFieldResolver, isMetroAssetFile, resolveConditions } from '../resolve-fields.js'
12
- import { discoverTsconfig, isDir, loadTsconfigPaths, packageTsconfigPaths } from '../resolve-typescript.js'
9
+ import { getParser, importsTypescriptByOutputName, isResolvableExt, literalSpec, scan, scanCounts } from '../scan.js'
10
+ import { METRO_RELEASE_DEFINE, parseDefine } from '../define.js'
11
+ import { METRO_ASSET_EXTS, METRO_ASSET_RESOLUTIONS, METRO_SOURCE_EXTS, createFieldResolver, resolveConditions } from '../resolve-fields.js'
12
+ import { discoverTsconfig, isDir, loadTsconfigPaths, packageTsconfigPaths, tsconfigOutputsOf } from '../resolve-typescript.js'
13
13
  import { createMetroResolver } from '../metro-resolver.js'
14
14
  import { ASSET_REGISTRY } from '../metro-assets.js'
15
15
  import { createAliases, createBabelAliases, createBabelTypeImportsKept } from '../babel.js'
16
16
  import { AUTO_INCLUDES, RN_CORE_INCLUDE_FILES, linkedNativePackages, linkedPackages, listing, looksNative, metroAssetFiles, nativeInputs } from '@exodus/stasis-plugins/metro-native'
17
17
  import { pinInstalledCommits } from '../installed-commits.js'
18
18
  import { State } from '@exodus/stasis-core/state'
19
- import { readFileSyncMaybe, sha512integrity } from '@exodus/stasis-core/state-util'
19
+ import { deferredLockfile, readFileSyncMaybe } from '@exodus/stasis-core/state-util'
20
20
  import { checkoutCommit, detectRepo, normalizeEntries, packageLookup, packageJSONStat, packageType, parseGithubRepository, readJson, readModuleManifest, readPackageJson, readRegularFileOrNull, scopeManifestOf } from '@exodus/stasis-core/bundle-util'
21
- import { EMPTY_MODULE_PATH, assertRealPathWithinBase, classifyFormat, fileInBucket, hasNodeModulesSegment, isDotEnvFile, isPathWithin, isPlainObject, moduleFileKey, moduleInfo, nestedMap, nodeExtFormat, observeExecutable, parseExtraOption, parseInstallDevDependencies, parseLazyDependencies, parseResourcesOption, posixPathEscapes, relativeEscapes, splitNodeModulesPath, toPosix, withMetadataOf } from '@exodus/stasis-core/util'
21
+ import { EMPTY_MODULE_PATH, assertRealPathWithinBase, classifyFormat, fileInBucket, hasNodeModulesSegment, isDotEnvFile, isPathWithin, isPlainObject, moduleFileKey, moduleInfo, nestedMap, nodeExtFormat, observeExecutable, parseExtraOption, parseGeneratePrisma, parseInstallDevDependencies, parseLazyDependencies, parseResourcesOption, posixPathEscapes, relativeEscapes, splitNodeModulesPath, toPosix, withMetadataOf } from '@exodus/stasis-core/util'
22
22
  import { diskHost } from '@exodus/stasis-core/host'
23
23
  import { parseBundleBytes } from '@exodus/stasis-core/brotli'
24
24
  import { parseSoldeerLockfile } from '@preventive/lockfile/soldeer.js'
25
+ import { isAssetFile } from '@preventive/rn/metro-assets.js'
25
26
  import {
26
27
  SOLIDITY_PACKAGE_MANIFESTS,
27
28
  SOLIDITY_ROOT_MANIFESTS,
@@ -43,6 +44,7 @@ import {
43
44
  loadLaravelProviderFiles,
44
45
  } from '../loaders/php.js'
45
46
  import { DEFAULT_BUNDLE_FILE, bundledSummary, packagesLabel, unpackedSummary, writeBundle, writeFile } from './output.js'
47
+ import { withNpmToken } from './tokens.js'
46
48
 
47
49
  const JS_EXTS = new Set(['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '.jsx', '.tsx'])
48
50
  const BASH_EXTS = new Set(['.sh', '.bash'])
@@ -794,11 +796,14 @@ const cleanConditions = (conditions) => conditions.map((c) => (typeof c === 'str
794
796
 
795
797
  // --typescript honours tsconfig `paths` aliases: an explicit --tsconfig's for every file (it must
796
798
  // exist), else those of the tsconfig.json beside each importing file's package.json
797
- // (packageTsconfigPaths, the project read as the State reads it, to `env`'s PROJECT_CWD; null
798
- // matcher = no aliases). Without --typescript they only hint a miss (Scan#typescriptCandidate), so a
799
- // config that doesn't load is none.
799
+ // (packageTsconfigPaths, the project read as the State reads it, to `env`'s PROJECT_CWD). Either way
800
+ // it carries the packages' layouts (`outputs`). Without --typescript they only hint a miss
801
+ // (Scan#typescriptCandidate), so a config that doesn't load is none.
800
802
  function typescriptPathsFor(typescript, baseDir, tsconfig, host, env) {
801
- if (typescript && tsconfig !== undefined) return loadTsconfigPaths(discoverTsconfig(baseDir, tsconfig, host), host)
803
+ if (typescript && tsconfig !== undefined) {
804
+ const matcher = loadTsconfigPaths(discoverTsconfig(baseDir, tsconfig, host), host)
805
+ return { matchPaths: (spec) => matcher?.matchPaths(spec) ?? [], outputs: tsconfigOutputsOf({ host }) }
806
+ }
802
807
  return packageTsconfigPaths(baseDir, { host, lenient: !typescript, projectCwd: env.PROJECT_CWD })
803
808
  }
804
809
 
@@ -931,8 +936,8 @@ function innermostRootOf(baseDir, files, root, host) {
931
936
  // Extensions probed when a resolved target names none, in Metro's default sourceExts order.
932
937
  // Limited to what a source bundle can carry (scan's RESOLVABLE_EXTS) so the resolver never
933
938
  // resolves a file the bundle would reject; an extensionless `import './Foo'` can land on
934
- // Foo.jsx/Foo.tsx, as it does under Metro. Like Metro's default, this doesn't track a project's
935
- // own sourceExts.
939
+ // Foo.jsx/Foo.tsx, as it does under Metro. A project's own sourceExts are taken from its
940
+ // rn.config.json alone (metroLists), never off its Metro config, which is code.
936
941
  const SOURCE_EXTS = METRO_SOURCE_EXTS
937
942
  // React Native preset mainFields for `--metro` (which also sets the RN conditions + platform suffixes).
938
943
  const METRO_MAIN_FIELDS = ['react-native', 'browser', 'main']
@@ -941,6 +946,8 @@ const METRO_MAIN_FIELDS = ['react-native', 'browser', 'main']
941
946
  // imports reaches them: Metro's and the React Native CLI's, and with --babel(-aliases) Babel's.
942
947
  const METRO_CONFIG_FILE = 'metro.config.js'
943
948
  const METRO_CONFIG_FILES = [METRO_CONFIG_FILE, 'react-native.config.js']
949
+ // @preventive/rn's config of a React Native app's build (rn-bundle's and rn-serve's), in its root.
950
+ const RN_CONFIG_FILE = 'rn.config.json'
944
951
  const BABEL_CONFIG_FILE = 'babel.config.js'
945
952
  // What else a React Native app's build runs in Node, which neither the app nor the configs import:
946
953
  // the CLI that runs Metro and Metro itself, and what they load by a name or path given as a string.
@@ -986,19 +993,21 @@ const BUNDLER_CONDITIONS = ['module']
986
993
  // it adds to the bundler base (`import`/`require` + `default`, never Node's `node`; see
987
994
  // resolveConditions): --metro asserts the RN conditions (+ browser on web), Metro's own set;
988
995
  // --mainFields asserts esbuild's and webpack's `module` (BUNDLER_CONDITIONS) and the user's --conditions.
989
- // Under --metro, `assetExts` are the extensions Metro takes as assets (its defaults where not given).
990
- export function fieldResolverFor(platform, { mainFields, metro = false, assetExts, conditions = [], typescript = false, typescriptPaths = null, host = diskHost, kept }) {
996
+ // Under --metro, `assetExts`, `sourceExts` and `assetResolutions` are Metro's resolver lists (its
997
+ // defaults where not given; metroLists).
998
+ export function fieldResolverFor(platform, { mainFields, metro = false, assetExts, sourceExts = SOURCE_EXTS, assetResolutions, conditions = [], typescript = false, typescriptPaths = null, host = diskHost, kept }) {
991
999
  const extras = metro ? ['react-native', ...(platform === 'web' ? ['browser'] : [])] : [...new Set([...BUNDLER_CONDITIONS, ...conditions])]
992
1000
  const fields = metro ? METRO_MAIN_FIELDS : mainFields
993
1001
  const resolver = createFieldResolver({
994
1002
  mainFields: fields,
995
1003
  platform,
996
1004
  preferNative: platform !== null && platform !== 'web',
997
- sourceExts: SOURCE_EXTS,
1005
+ sourceExts,
998
1006
  conditions: resolveConditions('commonjs', extras),
999
1007
  // Opt into Metro's package-entry browser-field quirks only on the --metro path.
1000
1008
  metro,
1001
1009
  assetExts,
1010
+ assetResolutions,
1002
1011
  // --typescript: tsc's mapping, inside the field resolver (the scanner's own fallback
1003
1012
  // only backs the built-in resolver). Unreachable under --metro-resolver
1004
1013
  // (classifyEntries rejects the combination -- metro-resolver can't substitute).
@@ -1029,6 +1038,8 @@ export const installsDevDependencies = (name, cwd, host) => parseInstallDevDepen
1029
1038
  // Whether the tree laid out from the lockfile for the project `host` holds at `cwd` may be lazy: the
1030
1039
  // `lazyDependencies` of the stasis.config.json there, true without one.
1031
1040
  const lazesDependencies = (name, cwd, host) => parseLazyDependencies(CONFIG_FILE, readConfigFile(name, cwd, host)?.lazyDependencies)
1041
+ // `generatePrisma` of the stasis.config.json there, true without one.
1042
+ const generatesPrisma = (name, cwd, host) => parseGeneratePrisma(CONFIG_FILE, readConfigFile(name, cwd, host)?.generatePrisma)
1032
1043
 
1033
1044
  // --babel-aliases: the alias map of the JSON file `file` (a path from `baseDir`, in the project, read through
1034
1045
  // `host`), babel-plugin-module-resolver's `alias` option as data: each alias to the string it maps to.
@@ -1321,12 +1332,13 @@ function babelNamedModules(file, host, { anyString = false } = {}) {
1321
1332
  }
1322
1333
 
1323
1334
  // The extensions Metro takes as assets (`resolver.assetExts`), as the project's Metro config gives them:
1324
- // Metro's defaults, and each string its metro.config.js lists among them, read off its source, never
1325
- // run (readLists: `assetExts: [...defaultConfig.resolver.assetExts, 'riv']`,
1326
- // `config.resolver.assetExts.push('riv')`). One it filters out is still taken as one.
1327
- function metroAssetExts(baseDir, host) {
1335
+ // Metro's defaults, and each string its Metro config (`file`, from `baseDir`; metro.config.js where not
1336
+ // given) lists among them, read off its source, never run (readLists: `assetExts:
1337
+ // [...defaultConfig.resolver.assetExts, 'riv']`, `config.resolver.assetExts.push('riv')`). One it filters
1338
+ // out is still taken as one. Metro's defaults alone where there's no such file.
1339
+ function metroAssetExts(baseDir, host, file = METRO_CONFIG_FILE) {
1328
1340
  const exts = new Set(METRO_ASSET_EXTS)
1329
- const config = join(baseDir, METRO_CONFIG_FILE)
1341
+ const config = resolve(baseDir, file)
1330
1342
  if (!host.stat(config)?.isFile()) return exts
1331
1343
  readLists(parseModule(config, host), METRO_ASSET_LISTS, (_, node) => {
1332
1344
  const ext = literalSpec(node)
@@ -1335,6 +1347,82 @@ function metroAssetExts(baseDir, host) {
1335
1347
  return exts
1336
1348
  }
1337
1349
 
1350
+ // An extension as Metro lists one (`riv`: no dot before it, of no directory), and a scale as its
1351
+ // assetResolutions has one (`"0.75"`, or 0.75), as rn.config.json takes them.
1352
+ const isMetroExt = (value) => typeof value === 'string' && /^[^./\\][^/\\]*$/u.test(value)
1353
+ const isMetroScale = (value) => (typeof value === 'number' && Number.isFinite(value) && value > 0) || (typeof value === 'string' && /^\d+(?:\.\d+)?$/u.test(value) && Number(value) > 0)
1354
+ // rn.config.json's options that bear on Metro's resolver lists, as rn-bundle takes them: whether the
1355
+ // project's Metro config is loaded (or which file), and what it adds to each list.
1356
+ const RN_CONFIG_OPTIONS = {
1357
+ metroConfig: [(value) => typeof value === 'boolean' || (typeof value === 'string' && value !== ''), 'true, false or the path of a Metro config'],
1358
+ assetExts: [(value) => Array.isArray(value) && value.every(isMetroExt), 'a list of extensions, each without its dot ("riv")'],
1359
+ sourceExts: [(value) => Array.isArray(value) && value.every(isMetroExt), 'a list of extensions, each without its dot ("mjs")'],
1360
+ assetResolutions: [(value) => Array.isArray(value) && value.every(isMetroScale), 'a list of scales ("0.75", or 0.75)'],
1361
+ }
1362
+
1363
+ // The options of the project's rn.config.json that bear on Metro's resolver lists (RN_CONFIG_OPTIONS),
1364
+ // those it has; its others are rn-bundle's own. -> them, or null where there's no rn.config.json;
1365
+ // throws where it isn't one rn-bundle takes for them: not JSON, not an object, or one of them of
1366
+ // another kind.
1367
+ function readRnConfig(baseDir, host) {
1368
+ const text = readFileSyncMaybe(baseDir, RN_CONFIG_FILE, 'utf8', host)
1369
+ if (text === null) return null
1370
+ let config
1371
+ try {
1372
+ config = JSON.parse(text)
1373
+ } catch (cause) {
1374
+ throw new Error(`${RN_CONFIG_FILE} is not valid JSON`, { cause })
1375
+ }
1376
+ if (!isPlainObject(config)) throw new Error(`${RN_CONFIG_FILE} is not an object of options`)
1377
+ const options = {}
1378
+ for (const [key, [valid, what]] of Object.entries(RN_CONFIG_OPTIONS)) {
1379
+ if (config[key] === undefined) continue
1380
+ if (!valid(config[key])) throw new Error(`${RN_CONFIG_FILE}: ${key} is ${what}, not ${JSON.stringify(config[key])}`)
1381
+ options[key] = config[key]
1382
+ }
1383
+ return options
1384
+ }
1385
+
1386
+ // `base`, and what of `more` it has none of, after it, each once, as strings.
1387
+ const addedTo = (base, more = []) => [...base, ...more.map(String).filter((each, i, all) => !base.includes(each) && all.indexOf(each) === i)]
1388
+
1389
+ // --metro: Metro's resolver lists, as the project gives them, as rn-bundle takes them from its
1390
+ // rn.config.json (readRnConfig) and its Metro config, read off its source, never run:
1391
+ // - assetExts: Metro's defaults and those rn.config.json adds, where it has assetExts; Metro's defaults
1392
+ // alone where it has metroConfig false (no Metro config is loaded); else those the Metro config
1393
+ // (rn.config.json's metroConfig, where it names one; else metro.config.js) adds (metroAssetExts);
1394
+ // - sourceExts and assetResolutions: Metro's defaults and what rn.config.json adds, after them. Of the
1395
+ // sourceExts, those a bundle can carry a file of (scan's isResolvableExt).
1396
+ // An rn.config.json that isn't one rn-bundle takes for them, or adds an extension to one of assetExts
1397
+ // and sourceExts that the other has (Metro takes a file of it for an asset; rn.config.json removes none),
1398
+ // is warned of, and read as none. `configs` are the files the lists come of besides metro.config.js
1399
+ // (carried as it is): rn.config.json, where there is one, and the Metro config its metroConfig names.
1400
+ // -> { assetExts (a Set), sourceExts, assetResolutions, configs (absolute paths) }
1401
+ function metroLists(baseDir, host) {
1402
+ const rnFile = join(baseDir, RN_CONFIG_FILE)
1403
+ const configs = host.stat(rnFile)?.isFile() ? [rnFile] : []
1404
+ let rn = null
1405
+ try {
1406
+ rn = readRnConfig(baseDir, host)
1407
+ } catch (error) {
1408
+ console.warn(`[stasis] ${error.message}; reading ${METRO_CONFIG_FILE} as without it`)
1409
+ }
1410
+ const withoutRn = () => ({ assetExts: metroAssetExts(baseDir, host), sourceExts: SOURCE_EXTS, assetResolutions: METRO_ASSET_RESOLUTIONS, configs })
1411
+ if (rn === null) return withoutRn()
1412
+ let assetExts
1413
+ if (rn.assetExts !== undefined) assetExts = new Set(addedTo([...METRO_ASSET_EXTS], rn.assetExts))
1414
+ else if (rn.metroConfig === false) assetExts = new Set(METRO_ASSET_EXTS)
1415
+ else assetExts = metroAssetExts(baseDir, host, typeof rn.metroConfig === 'string' ? rn.metroConfig : METRO_CONFIG_FILE)
1416
+ const sourceExts = addedTo([...SOURCE_EXTS], rn.sourceExts)
1417
+ const both = [...(rn.sourceExts ?? []).filter((ext) => assetExts.has(ext)), ...(rn.assetExts ?? []).filter((ext) => sourceExts.includes(ext))][0]
1418
+ if (both !== undefined) {
1419
+ console.warn(`[stasis] ${RN_CONFIG_FILE}: ${both} is in both assetExts and sourceExts, which Metro takes a file of as an asset; reading ${METRO_CONFIG_FILE} as without it`)
1420
+ return withoutRn()
1421
+ }
1422
+ const named = rn.assetExts === undefined && typeof rn.metroConfig === 'string' ? [resolve(baseDir, rn.metroConfig)] : []
1423
+ return { assetExts, sourceExts: sourceExts.filter((ext) => isResolvableExt(`.${ext}`)), assetResolutions: addedTo([...METRO_ASSET_RESOLUTIONS], rn.assetResolutions), configs: [...configs, ...named] }
1424
+ }
1425
+
1338
1426
  // How deep a Babel config's lists nest, as read: arrays of arrays `.flat()` flattens.
1339
1427
  const MAX_LIST_DEPTH = 8
1340
1428
  // The levels `.flat(arg)` flattens: 1 by default, else the number written (Infinity as deep as read).
@@ -1430,7 +1518,7 @@ function metroInsertedFiles(files, { assets, baseDir, babelled, dynamicImports,
1430
1518
  // Build a JS/TS Bundle + companion Lockfile via the legacy-field resolver (`--mainFields`/
1431
1519
  // `--metro`). Scanned once per platform; each edge is recorded flat when the platforms that
1432
1520
  // have it agree, or as a `{ platform: target }` map where they diverge. `scope` and `resources`
1433
- // are fieldBuildOptions'. Returns { bundle, lockfile }.
1521
+ // are fieldBuildOptions'. Returns { bundle, lockfile: () => Lockfile }, the lockfile built when called.
1434
1522
  async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, entries, mainFields, platforms, conditions = [], metro, metroResolver, babel, babelAliases: aliasesFile, jsx = false, flow = false, typescript = false, tsconfig, scope, resources, define, packageJSON = false, host = diskHost, memo }) {
1435
1523
  const baseDir = resolve(cwd)
1436
1524
  const absEntries = entries.map((e) => resolve(baseDir, e))
@@ -1496,15 +1584,16 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1496
1584
  const babelled = babel || fileAliases !== null
1497
1585
  // The edges each platform's scan left out above the root (withinRoot's leftOut), across platforms.
1498
1586
  const leftOutEdges = []
1499
- // --metro: the extensions Metro takes as assets, its defaults and those the project's Metro config
1500
- // adds (metroAssetExts: `assetExts: [...defaultConfig.resolver.assetExts, 'riv']`), which it resolves
1501
- // by its asset rule, scale variants and all.
1502
- const assetExts = metro ? metroAssetExts(baseDir, host) : METRO_ASSET_EXTS
1587
+ // --metro: Metro's resolver lists, as the project's rn.config.json gives them, else its Metro config
1588
+ // (metroLists): the extensions Metro takes as assets, which it resolves by its asset rule, scale
1589
+ // variants and all (`assetExts: [...defaultConfig.resolver.assetExts, 'riv']`), those it probes, and
1590
+ // the scales of an asset's files.
1591
+ const { assetExts, sourceExts, assetResolutions, configs: listConfigs } = metro ? metroLists(baseDir, host) : { assetExts: METRO_ASSET_EXTS, sourceExts: SOURCE_EXTS, assetResolutions: METRO_ASSET_RESOLUTIONS, configs: [] }
1503
1592
  // The resources the app imports that are no asset of Metro's are no module of Metro's, which can't
1504
1593
  // resolve one: one reaches the build only as a transform's input, read and inlined by a Babel plugin
1505
1594
  // (`require('./messages.po')`, @exodus/i18n's plugin-inline-po), as the Metro plugin records it
1506
1595
  // (`metro`, no edge): no edge to one, and no asset registry for one.
1507
- const isTransformInput = (abs, info) => metro && info?.resource === true && !isMetroAssetFile(abs, assetExts)
1596
+ const isTransformInput = (abs, info) => metro && info?.resource === true && !isAssetFile(abs, assetExts)
1508
1597
  // A round of a lazy tree that asked for a package already is void (vfs-bundle/lazy.js): it reads
1509
1598
  // on, for all else it asks for, but reports and refuses nothing, which the round that asks for
1510
1599
  // none does, and stops before it reads the files in.
@@ -1521,18 +1610,18 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1521
1610
  for (const platform of platforms) {
1522
1611
  // What each resolves, kept across a lazy tree's rounds where it read nothing not unpacked yet.
1523
1612
  const keptFor = (label) => (memo ? nestedMap(memo, `${label} ${platform ?? '*'}`) : undefined)
1524
- const field = fieldResolverFor(platform, { mainFields, metro, assetExts, conditions: scanConditions, typescript, typescriptPaths, host, kept: keptFor('resolutions') })
1613
+ const field = fieldResolverFor(platform, { mainFields, metro, assetExts, sourceExts, assetResolutions, conditions: scanConditions, typescript, typescriptPaths, host, kept: keptFor('resolutions') })
1525
1614
  const { extras } = field
1526
1615
  // --metro --metro-resolver delegates to the project's own metro-resolver for byte-for-byte Metro
1527
1616
  // fidelity; otherwise the built-in field/suffix resolver reproduces it. metro-resolver derives
1528
1617
  // default/require|import/platform conditions itself, so it takes only the extra `react-native`
1529
1618
  // condition (browser comes from its per-platform map, keyed on `web`).
1530
1619
  const resolver = metroResolver
1531
- ? createMetroResolver({ projectDir: baseDir, platform, sourceExts: SOURCE_EXTS, mainFields, conditionNames: ['react-native'], assetExts, host })
1620
+ ? createMetroResolver({ projectDir: baseDir, platform, sourceExts, mainFields, conditionNames: ['react-native'], assetExts, assetResolutions, host })
1532
1621
  : field.resolver
1533
1622
  // Without --typescript, the field resolver --typescript would build names the file a miss would
1534
1623
  // land on: a hint in the unresolved report, never an edge (see Scan#typescriptCandidate).
1535
- const typescriptResolve = typescript || metroResolver ? null : fieldResolverFor(platform, { mainFields, metro, assetExts, conditions: scanConditions, typescript: true, typescriptPaths, host, kept: keptFor('typescript resolutions') }).resolver
1624
+ const typescriptResolve = typescript || metroResolver ? null : fieldResolverFor(platform, { mainFields, metro, assetExts, sourceExts, assetResolutions, conditions: scanConditions, typescript: true, typescriptPaths, host, kept: keptFor('typescript resolutions') }).resolver
1536
1625
  // --babel: a specifier the project's babel-plugin-module-resolver rewrites resolves as rewritten,
1537
1626
  // as Metro resolves it after Babel; its edge stays keyed by the specifier the source holds.
1538
1627
  const aliases = babel ? createBabelAliases({ projectDir: baseDir, platform }) : fileAliases
@@ -1618,7 +1707,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1618
1707
  const configOnly = new Set()
1619
1708
  const configsAt = performance.now()
1620
1709
  if (metro) {
1621
- const configs = [...METRO_CONFIG_FILES, ...(babelled ? [BABEL_CONFIG_FILE] : [])].map((rel) => join(baseDir, rel)).filter((abs) => host.stat(abs)?.isFile())
1710
+ // And the files Metro's resolver lists came of (metroLists): rn.config.json, and the Metro config
1711
+ // its metroConfig names, where in the project.
1712
+ const configs = [...new Set([...[...METRO_CONFIG_FILES, ...(babelled ? [BABEL_CONFIG_FILE] : [])].map((rel) => join(baseDir, rel)), ...listConfigs.filter((abs) => relWithin(abs) !== null)])].filter((abs) => host.stat(abs)?.isFile())
1622
1713
  // A METRO_TOOLCHAIN entry's file. -> absolute path, or undefined
1623
1714
  const toolchainFile = ({ name, file, via }) => {
1624
1715
  for (let i = 0; i <= via.length; i++) {
@@ -1757,23 +1848,22 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1757
1848
  if (voided()) throw new Error('buildResolvedJsBundle: this round reads a package not unpacked yet')
1758
1849
  const carryingAt = performance.now()
1759
1850
 
1760
- // Read each reached file once: bytes for the bundle, integrity for the lockfile. Source is
1761
- // stored as UTF-8 text, so non-UTF-8 bytes would diverge from the hashed bytes -- reject them.
1851
+ // Read each reached file once, into the bundle as the bytes read, encoded without loss: the
1852
+ // lockfile hashes them from there, once it is wanted (deferredLockfile). Source is
1853
+ // stored as UTF-8 text, which non-UTF-8 bytes would not survive -- reject them.
1762
1854
  const sources = new Map()
1763
- const integrities = new Map()
1764
- // Carry `rel`: `content` in the bundle as `format`, the integrity of its bytes `buf` in the lockfile.
1765
- const put = (rel, content, format, buf) => {
1855
+ // Carry `rel`: `content` in the bundle as `format`.
1856
+ const put = (rel, content, format) => {
1766
1857
  sources.set(rel, content)
1767
1858
  formatsByRel.set(rel, format)
1768
- integrities.set(rel, sha512integrity(buf))
1769
1859
  }
1770
1860
  // A resource carries bytes, not source: UTF-8 verbatim or base64 when binary, tagged with the
1771
1861
  // byte-derived format (here and in the --metro native capture below).
1772
- const putResource = (rel, buf) => (isUtf8(buf) ? put(rel, buf.toString('utf8'), 'resource', buf) : put(rel, buf.toString('base64'), 'resource:base64', buf))
1862
+ const putResource = (rel, buf) => (isUtf8(buf) ? put(rel, buf.toString('utf8'), 'resource') : put(rel, buf.toString('base64'), 'resource:base64'))
1773
1863
  // Code carries its source, UTF-8 (`what` it is, refused where it isn't).
1774
1864
  const putCode = (rel, buf, format, what = 'JS bundle source') => {
1775
1865
  if (!isUtf8(buf)) throw new Error(`${what} is not valid UTF-8: ${rel}`)
1776
- put(rel, buf.toString('utf8'), format, buf)
1866
+ put(rel, buf.toString('utf8'), format)
1777
1867
  }
1778
1868
  const realBase = host.realpath(baseDir)
1779
1869
  // Metro's empty module is carried as the file it is, a code file of Metro's (no format).
@@ -1795,7 +1885,7 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1795
1885
  if (formatsByRel.has(EMPTY_MODULE_PATH)) {
1796
1886
  throw new Error(`Bundle needs the reserved empty-module path ${EMPTY_MODULE_PATH}, but the project has a real file there`)
1797
1887
  }
1798
- put(EMPTY_MODULE_PATH, '', metro ? undefined : 'commonjs', Buffer.alloc(0))
1888
+ put(EMPTY_MODULE_PATH, '', metro ? undefined : 'commonjs')
1799
1889
  }
1800
1890
 
1801
1891
  // The package a bundled file is in (findPackageMetadata: its pkgDir and identity, null where no
@@ -1930,7 +2020,7 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1930
2020
  if (sources.has(rel)) continue
1931
2021
  const buf = readModuleManifest({ baseDir, realBase, rel, host })
1932
2022
  if (!buf) continue
1933
- put(rel, buf.toString('utf8'), 'json', buf)
2023
+ put(rel, buf.toString('utf8'), 'json')
1934
2024
  // Attributed as the files it serves are, as State#includePackageJson attributes one.
1935
2025
  if (of.some((file) => configReached.has(file))) configReached.add(rel)
1936
2026
  if (of.every((file) => configOnly.has(file))) configOnly.add(rel)
@@ -1977,9 +2067,9 @@ async function buildResolvedJsBundle({ cwd = process.cwd(), env = process.env, e
1977
2067
  // What the configs reach is the bundler's, not the app's: `bundle`, as a Node build's files are.
1978
2068
  const bundle = configReached.size === 0 ? assembled : assembled.withReason('bundle', [...configReached])
1979
2069
 
1980
- // The companion lockfile mirrors the bundle, swapping file content for its integrity.
2070
+ // The companion lockfile mirrors the bundle, swapping file content for its integrity, once it is wanted.
1981
2071
  stageTimes.carrying += performance.now() - carryingAt
1982
- return { bundle, lockfile: Lockfile.fromBundle(bundle, (file) => integrities.get(file)) }
2072
+ return { bundle, lockfile: deferredLockfile(bundle) }
1983
2073
  }
1984
2074
 
1985
2075
  // Classify entries into their single shared language and check option applicability; `name` prefixes
@@ -2114,12 +2204,15 @@ function classifyEntries(name, { cwd = process.cwd(), entries, mappingFile, mani
2114
2204
  // `metro`, whose per-platform edges and synthetic empty module a State can't hold, else through a
2115
2205
  // State, which detects the bundle's repo itself. `root` is the directory the bundle's paths are
2116
2206
  // relative to: cwd for the resolver's, the State's root for the State's. `extra` and `outputsAt` are
2117
- // buildJsBundle's, for the State's alone (see withExtra).
2207
+ // buildJsBundle's, for the State's alone (see withExtra). `metro` turns on `jsx` and `flow`, as
2208
+ // Metro's Babel parses JSX and Flow in every file, and defines what Metro's release build does
2209
+ // (METRO_RELEASE_DEFINE), each name `define` gives a value taking that one instead.
2118
2210
  // -> { bundle, lockfile: () => Lockfile, stateBuilt, root }
2119
2211
  async function buildJs({ mainFields, platforms, metro, metroResolver, babel, babelAliases, innermostRoot, extra, outputsAt, ...options }) {
2212
+ if (metro) options = { ...options, jsx: true, flow: true, define: { ...METRO_RELEASE_DEFINE, ...options.define } }
2120
2213
  if (metro || mainFields !== undefined) {
2121
2214
  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 })
2122
- return { bundle: built.bundle, lockfile: () => built.lockfile, stateBuilt: false, root: resolve(options.cwd) }
2215
+ return { bundle: built.bundle, lockfile: built.lockfile, stateBuilt: false, root: resolve(options.cwd) }
2123
2216
  }
2124
2217
  const state = await buildJsBundle({ ...options, innermostRoot, extra, outputsAt })
2125
2218
  const bundle = state.sourceBundle
@@ -2153,8 +2246,9 @@ function withExtra(built, cwd, { outputs = [], resources, host = diskHost, name
2153
2246
  // stamps it), `extra`, or both, for one `extra` names that the build carries itself.
2154
2247
  const merged = added.bundle === null ? built.bundle : built.bundle.merge(added.bundle)
2155
2248
  const bundle = added.carried.length === 0 ? merged : merged.withReason('extra', added.carried)
2249
+ // The lockfile of what was added is built when read, as the build's is: not here.
2156
2250
  const { lockfile } = built
2157
- return { ...built, bundle, ...(lockfile && added.lockfile && { lockfile: () => lockfile().merge(added.lockfile) }) }
2251
+ return { ...built, bundle, ...(lockfile && added.bundle !== null && { lockfile: () => lockfile().merge(added.lockfile) }) }
2158
2252
  }
2159
2253
 
2160
2254
  // The bundle of `kind` (classifyEntries') built from buildBundle's options, from disk, with the files
@@ -2195,9 +2289,9 @@ export function checkVfsOptions(name, options) {
2195
2289
  if (options.metroResolver) throw new Error(`${name}: metroResolver is not supported`)
2196
2290
  // The project's Babel config is code, run from the disk.
2197
2291
  if (options.babel) throw new Error(`${name}: babel is not supported`)
2198
- const { generate = [] } = options
2199
- if (!Array.isArray(generate) || generate.some((step) => step !== 'prisma')) throw new TypeError(`${name}: generate must be an array of 'prisma'`)
2200
- if (generate.length > 0 && kind !== 'js') throw new Error(`${name}: --generate is only valid for JS bundles`)
2292
+ const { generate } = options
2293
+ if (generate !== undefined && (!Array.isArray(generate) || generate.some((step) => step !== 'prisma'))) throw new TypeError(`${name}: generate must be an array of 'prisma'`)
2294
+ if (generate?.length > 0 && kind !== 'js') throw new Error(`${name}: --generate is only valid for JS bundles`)
2201
2295
  return kind
2202
2296
  }
2203
2297
 
@@ -2218,7 +2312,9 @@ export function checkVfsOptions(name, options) {
2218
2312
  // `cpu` and `libc` are loadNodeModules'. Without a `packageManager`, it is the one whose lockfile
2219
2313
  // installs cwd, where only one's does. `innermostRoot` is buildJsBundle's, for a JS bundle built
2220
2314
  // through a State. `generate: ['prisma']` writes each project's Prisma Client into the laid-out
2221
- // tree before the scan, leaving `vfs` as it is (vfs-bundle/prisma.js). `client`, a
2315
+ // tree before the scan, leaving `vfs` as it is (vfs-bundle/prisma.js); without `generate`, those of
2316
+ // the projects the entries reach, silently, unless the stasis.config.json in cwd sets
2317
+ // `generatePrisma` false; `generate: []`, none. `client`, a
2222
2318
  // @preventive/upstream/github.js client, is what a Soldeer git dependency is fetched through; without
2223
2319
  // one, a soldeer.lock holding one is refused, naming deptree's `github`, before anything is fetched.
2224
2320
  // `cache` is where npm packages' tarballs and version documents are kept (checkCache). Each
@@ -2233,7 +2329,7 @@ export function checkVfsOptions(name, options) {
2233
2329
  // true; `lazy: false` installs every package, and `lazy: true` is refused where the tree cannot be
2234
2330
  // lazy, or `lazyDependencies` is false. `stats` are deptree's, and `stats.unpacked` the packages
2235
2331
  // unpacked: each one installed, or those a lazy tree unpacked.
2236
- // -> { bundle: Bundle, lockfile: Lockfile (of a JS bundle), stats, packageManager, root }
2332
+ // -> { bundle: Bundle, lockfile: Lockfile (of a JS bundle, built when first read), stats, packageManager, root }
2237
2333
  export async function buildVfsBundle(options = {}) {
2238
2334
  const { checkVfs, vfsHost } = await import('../vfs-bundle/tree.js')
2239
2335
  checkVfs('buildVfsBundle', options.vfs)
@@ -2248,7 +2344,7 @@ export async function buildVfsBundle(options = {}) {
2248
2344
  // configuredBuilds makes, and whether their union's `extra` is the bundle's, as bundleCommand adds
2249
2345
  // it; `env`, what the builds read their settings from (none by default); `outputsAt(root)`, the
2250
2346
  // absolute paths written, which `extra` never takes; and `refuseInstalled`, layOutTree's.
2251
- async function buildFromLockfile(name, project, { vfs, packageManager, cwd = '/', packageManagerVersion, os, cpu, libc, repo, innermostRoot = false, generate = [], client, cache, lazy, ...options } = {}, { env = {}, plan, outputsAt = () => [], refuseInstalled = false } = {}) {
2347
+ async function buildFromLockfile(name, project, { vfs, packageManager, cwd = '/', packageManagerVersion, os, cpu, libc, repo, innermostRoot = false, generate, client, cache, lazy, ...options } = {}, { env = {}, plan, outputsAt = () => [], refuseInstalled = false } = {}) {
2252
2348
  const { checkCache, checkKind, checkLazy, checkTarget, lazyTaken, loadTree, packageManagerFor, packageManagerOf, pinCommits, treeHost, vfsHost } = await import('../vfs-bundle/tree.js')
2253
2349
  const { configuredBuilds } = await import('./bundle-options.js')
2254
2350
  const { checkGlob } = await import('../vfs-bundle/glob.js')
@@ -2278,6 +2374,12 @@ async function buildFromLockfile(name, project, { vfs, packageManager, cwd = '/'
2278
2374
  const lazyDependencies = lazesDependencies(name, cwd, project)
2279
2375
  if (lazy && !lazyDependencies) throw new Error(`${name}: lazy is given, and ${CONFIG_FILE}'s lazyDependencies is false`)
2280
2376
  lazy ??= lazyDependencies && lazyTaken(project, packageManager, cwd)
2377
+ // Each project's Prisma Client: asked for (`generate: ['prisma']`), every project's, strictly; else, of a JS
2378
+ // build of a Vfs, detected where stasis.config.json's `generatePrisma` leaves it: the projects the entries
2379
+ // are in and their workspace dependencies, silently. `generate: []`, or `generatePrisma` false: none.
2380
+ const generatePrisma = generatesPrisma(name, cwd, project)
2381
+ if (generate?.length > 0 && !generatePrisma) throw new Error(`${name}: generate is given, and ${CONFIG_FILE}'s generatePrisma is false`)
2382
+ const prismaGeneration = generate?.includes('prisma') ? 'asked' : generate === undefined && generatePrisma && vfs !== undefined && pm.kind === 'js' ? 'detected' : null
2281
2383
  for (const build of builds) checkKind(name, checkVfsOptions(name, { ...build, lockfile: options.lockfile, generate, cwd, host: project }), [packageManager])
2282
2384
  // Checked before anything is fetched: an entry out of what the tree installs is in the project
2283
2385
  // already. (A Solidity entry that is no .sol file is a directory, skipped where it is missing.)
@@ -2292,11 +2394,29 @@ async function buildFromLockfile(name, project, { vfs, packageManager, cwd = '/'
2292
2394
  // any build, for a lazy tree in rounds of their own (they read the tree's `prisma`), so that each
2293
2395
  // of the build's rounds reads the same project, as what its scans keep across them takes it to.
2294
2396
  let outside = project
2295
- if (generate.includes('prisma')) {
2296
- const { generatePrismaClients, withPrismaClients } = await import('../vfs-bundle/prisma.js')
2297
- const generating = (reads) => generatePrismaClients({ host: treeHost(tree, project, reads), root: tree.root, projects: tree.projects })
2298
- const outputs = await debugTimed('Generated the Prisma Clients', () => (tree.unpack === undefined ? generating() : inRounds(generating, tree.unpack)))
2299
- if (outputs.length > 0) outside = vfsHost(withPrismaClients(vfs, outputs))
2397
+ if (prismaGeneration !== null) {
2398
+ const prisma = await import('../vfs-bundle/prisma.js')
2399
+ // The projects with a schema (looked for before any `prisma` is read, which a lazy tree fetches once read):
2400
+ // all of them, asked for; else those the entries reach. Nothing done, nor said, where none has one.
2401
+ const withSchema = prisma.schemaProjects(project, tree.root, tree.projects)
2402
+ const strict = prismaGeneration === 'asked'
2403
+ // Reached by the entries alone (cwd's own project, the root's say, only where an entry is in it), each by its
2404
+ // real path, as the scan reaches it, where the project holds it: an installed one is the tree's, no project's.
2405
+ const entryPath = (entry) => {
2406
+ const path = posix.resolve(cwd, entry)
2407
+ try {
2408
+ return project.realpath(path)
2409
+ } catch {
2410
+ return path
2411
+ }
2412
+ }
2413
+ const reached = () => prisma.reachedProjects(project, tree.root, tree.projects, builds.flatMap((build) => build.entries.map(entryPath)))
2414
+ const projects = strict || withSchema.size === 0 ? withSchema : withSchema.intersection(reached())
2415
+ if (projects.size > 0) {
2416
+ const generating = (reads) => prisma.generatePrismaClients({ host: treeHost(tree, project, reads), root: tree.root, projects, strict })
2417
+ const outputs = await debugTimed('Generated the Prisma Clients', () => (tree.unpack === undefined ? generating() : inRounds(generating, tree.unpack)))
2418
+ if (outputs.length > 0) outside = vfsHost(prisma.withPrismaClients(vfs, outputs))
2419
+ }
2300
2420
  }
2301
2421
  // What follows reads the tree through a host of `outside`: once, or for a lazy tree, in rounds,
2302
2422
  // each reading into its `reads`, each build keeping what its scans read across them in a memo of
@@ -2340,7 +2460,10 @@ async function buildFromLockfile(name, project, { vfs, packageManager, cwd = '/'
2340
2460
  if (repo !== undefined) bundle.repo = repo
2341
2461
  pinCommits(bundle, root, tree)
2342
2462
  const unpacked = tree.lazy?.unpacked.size ?? tree.stats.installed ?? tree.stats.dependencies
2343
- return { bundle, lockfile: lockfile?.(), stats: { ...tree.stats, unpacked }, packageManager, root }
2463
+ // The lockfile is built when first read, the same one after: `stasis github-bundle` and `stasis
2464
+ // bundle --deptree` read it for --lockfile alone.
2465
+ let lock
2466
+ return { bundle, get lockfile() { return (lock ??= lockfile?.()) }, stats: { ...tree.stats, unpacked }, packageManager, root }
2344
2467
  }
2345
2468
 
2346
2469
  // EXODUS_STASIS_DEBUG=1 or true.
@@ -2432,75 +2555,22 @@ export async function buildBundle({ cwd = process.cwd(), env = process.env, entr
2432
2555
  // installed already (layOutTree's `refuseInstalled`), before anything is fetched. The tarballs are fetched (or read
2433
2556
  // from a cache that holds them, held to the lockfile all the same) and nothing is cached: nothing
2434
2557
  // is written but the bundle and the lockfile. A Soldeer git dependency is fetched from GitHub with
2435
- // `env`'s GITHUB_TOKEN where it is set. Where process.env gives the npm client no token, it is given
2436
- // `<home>/.audit/config.json`'s `npmToken` (the user's home by default), else the one `<home>/.npmrc`
2437
- // gives npm's registry, while the tree is laid out and the bundle built (tokens.js's withNpmToken).
2438
- export async function bundleCommand({ cwd = process.cwd(), env = process.env, home, 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, deptree = false } = {}) {
2439
- 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 }
2440
- if (builds !== undefined) {
2441
- if (!Array.isArray(builds) || builds.length === 0) throw new TypeError('bundleCommand: builds must be a non-empty array')
2442
- const given = Object.entries(options).find(([key, value]) => !['cwd', 'env'].includes(key) && value !== undefined && value !== false && value !== null && !(Array.isArray(value) && value.length === 0))
2443
- if (given) throw new TypeError(`bundleCommand: ${given[0]} can't be combined with builds (each build sets its own)`)
2444
- }
2445
- // Each build's options, the defaults above where it leaves one out.
2446
- const plans = (builds ?? [{}]).map((build) => ({ ...options, ...build, cwd, env }))
2447
- const kinds = plans.map((plan) => classifyEntries('bundleCommand', { ...plan, lockfile }))
2448
-
2558
+ // `env`'s GITHUB_TOKEN where it is set; npm is asked with withNpmToken's token (tokens.js).
2559
+ export async function bundleCommand({ cwd = process.cwd(), output, lockfile, brotliQuality, add = false, ...options } = {}) {
2449
2560
  // --add has nothing to merge into on stdout (write-only).
2450
2561
  if (add && output === '-') {
2451
2562
  throw new Error('bundleCommand: --add cannot be combined with --output=- (nothing to merge into on stdout)')
2452
2563
  }
2453
-
2454
- // The files this build writes, never taken into `extra`, given the root its paths are relative to:
2455
- // the bundle (by default at that root, see `target` below) and the lockfile.
2456
- const outputsAt = (root) => [output ?? join(root, DEFAULT_BUNDLE_FILE), lockfile].filter((file) => file !== undefined && file !== '-').map((file) => resolve(cwd, file))
2457
- // With `builds` (stasis.config.json's entries, however many builds they make), `extra` is the
2458
- // bundle's, not any build's: added to their union below.
2459
- const bundleExtra = builds !== undefined
2460
- let union, root
2461
- if (deptree) {
2462
- // The disk read through the tree, nothing cached (`cache: false`, and no setCacheDir here).
2463
- const [{ createClient }, { detectPackageManager }, { withNpmToken }] = await Promise.all([import('@preventive/upstream/github.js'), import('../vfs-bundle/tree.js'), import('./tokens.js')])
2464
- const built = await withNpmToken({ home }, () => buildFromLockfile('bundleCommand', diskHost, {
2465
- cwd: resolve(cwd),
2466
- packageManager: detectPackageManager('bundleCommand', diskHost, resolve(cwd), { why: '--deptree lays out the dependencies from a lockfile' }),
2467
- lockfile,
2468
- cache: false,
2469
- lazy: false,
2470
- client: createClient({ token: env.GITHUB_TOKEN || null }),
2471
- }, { env, plan: { builds: plans, bundleExtra }, outputsAt, refuseInstalled: true }))
2472
- console.warn(unpackedSummary(built.stats))
2473
- root = built.root
2474
- union = { bundle: built.bundle, lockfile: () => built.lockfile }
2475
- } else {
2476
- const builts = []
2477
- for (const [i, plan] of plans.entries()) {
2478
- // eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
2479
- builts.push(await buildOfKind(kinds[i], { ...plan, outputsAt, extra: !bundleExtra }))
2480
- }
2481
- // The directory the bundle's paths are relative to: a State-built JS bundle's root, which is the
2482
- // project's at or above cwd (a workspace package's is the workspace root's), else cwd.
2483
- const roots = builts.map((built) => built.root ?? resolve(cwd))
2484
- root = roots[0]
2485
- // State-built bundles keep the State root's repo (no cwd fallback: their paths are relative to that root).
2486
- for (const built of builts) if (!built.stateBuilt) built.bundle.repo ??= detectRepo(cwd)
2487
- union = unionOfBuilds('bundleCommand', plans, builts, roots)
2488
- if (bundleExtra) {
2489
- // Once, whatever the builds' order: to their union, whose own record of a file stands, by the
2490
- // allowlist of the stasis.config.json at the root, not any one entry's `resources`.
2491
- const withExtras = withExtra(union, root, { outputs: outputsAt(root) })
2492
- if (withExtras !== union) pinInstalledCommits(withExtras.bundle, root)
2493
- union = withExtras
2494
- }
2495
- }
2564
+ const built = await buildOfCommand({ ...options, cwd, output, lockfile })
2565
+ const { root } = built
2496
2566
  // By default the bundle goes there, where `stasis run --bundle=load` discovers it. In cwd below
2497
2567
  // the root it would load as rooted at cwd, and root the next `stasis bundle` there too, out of the
2498
2568
  // files above it.
2499
2569
  const target = output ?? relative(resolve(cwd), join(root, DEFAULT_BUNDLE_FILE))
2500
2570
 
2501
- let { bundle } = union
2571
+ let { bundle } = built
2502
2572
  // Only a JS bundle has a lockfile (classifyEntries refuses one for the others).
2503
- let lockData = lockfile ? union.lockfile().serialize() : undefined
2573
+ let lockData = lockfile ? built.lockfile().serialize() : undefined
2504
2574
 
2505
2575
  // --add: union the fresh build into the existing on-disk bundle; a conflicting file throws. Skipped when nothing is on disk.
2506
2576
  const outAbs = target === '-' ? undefined : resolve(cwd, target)
@@ -2549,3 +2619,72 @@ export async function bundleCommand({ cwd = process.cwd(), env = process.env, ho
2549
2619
  console.warn(bundledSummary(files.length, modules, fromDir, dest))
2550
2620
  }
2551
2621
  }
2622
+
2623
+ // The bundle bundleCommand writes of its options (but `brotliQuality` and `add`, which say how it is
2624
+ // written), built as it builds it, warnings and all, and not written: as `stasis audit` would read it
2625
+ // back from the file, a Bundle parsed from what bundleCommand would compress (no lockfile is
2626
+ // written either). Its errors are bundleCommand's.
2627
+ export async function buildCommandBundle(options = {}) {
2628
+ const { bundle } = await buildOfCommand(options)
2629
+ return Bundle.parse(bundle.serialize())
2630
+ }
2631
+
2632
+ // bundleCommand's bundle, and its lockfile (`lockfile()`, a JS bundle's), built as it builds them from
2633
+ // its options (but `brotliQuality` and `add`, which say how they are written) and not written, with
2634
+ // the root their paths are relative to. `output` and `lockfile` are where it would write them, which
2635
+ // `extra` never takes in. -> { bundle, lockfile: () => Lockfile, root }
2636
+ async function buildOfCommand({ cwd = process.cwd(), env = process.env, home, 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, builds, deptree = false } = {}) {
2637
+ 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 }
2638
+ if (builds !== undefined) {
2639
+ if (!Array.isArray(builds) || builds.length === 0) throw new TypeError('bundleCommand: builds must be a non-empty array')
2640
+ const given = Object.entries(options).find(([key, value]) => !['cwd', 'env'].includes(key) && value !== undefined && value !== false && value !== null && !(Array.isArray(value) && value.length === 0))
2641
+ if (given) throw new TypeError(`bundleCommand: ${given[0]} can't be combined with builds (each build sets its own)`)
2642
+ }
2643
+ // Each build's options, the defaults above where it leaves one out.
2644
+ const plans = (builds ?? [{}]).map((build) => ({ ...options, ...build, cwd, env }))
2645
+ const kinds = plans.map((plan) => classifyEntries('bundleCommand', { ...plan, lockfile }))
2646
+
2647
+ // The files this build writes, never taken into `extra`, given the root its paths are relative to:
2648
+ // the bundle (by default at that root, see bundleCommand's `target`) and the lockfile.
2649
+ const outputsAt = (root) => [output ?? join(root, DEFAULT_BUNDLE_FILE), lockfile].filter((file) => file !== undefined && file !== '-').map((file) => resolve(cwd, file))
2650
+ // With `builds` (stasis.config.json's entries, however many builds they make), `extra` is the
2651
+ // bundle's, not any build's: added to their union below.
2652
+ const bundleExtra = builds !== undefined
2653
+ let union, root
2654
+ if (deptree) {
2655
+ // The disk read through the tree, nothing cached (`cache: false`, and no setCacheDir here).
2656
+ const [{ createClient }, { detectPackageManager }] = await Promise.all([import('@preventive/upstream/github.js'), import('../vfs-bundle/tree.js')])
2657
+ const built = await withNpmToken(home, () => buildFromLockfile('bundleCommand', diskHost, {
2658
+ cwd: resolve(cwd),
2659
+ packageManager: detectPackageManager('bundleCommand', diskHost, resolve(cwd), { why: '--deptree lays out the dependencies from a lockfile' }),
2660
+ lockfile,
2661
+ cache: false,
2662
+ lazy: false,
2663
+ client: createClient({ token: env.GITHUB_TOKEN || null }),
2664
+ }, { env, plan: { builds: plans, bundleExtra }, outputsAt, refuseInstalled: true }))
2665
+ console.warn(unpackedSummary(built.stats))
2666
+ root = built.root
2667
+ union = { bundle: built.bundle, lockfile: () => built.lockfile }
2668
+ } else {
2669
+ const builts = []
2670
+ for (const [i, plan] of plans.entries()) {
2671
+ // eslint-disable-next-line no-await-in-loop -- one build at a time, in the order its warnings read
2672
+ builts.push(await buildOfKind(kinds[i], { ...plan, outputsAt, extra: !bundleExtra }))
2673
+ }
2674
+ // The directory the bundle's paths are relative to: a State-built JS bundle's root, which is the
2675
+ // project's at or above cwd (a workspace package's is the workspace root's), else cwd.
2676
+ const roots = builts.map((built) => built.root ?? resolve(cwd))
2677
+ root = roots[0]
2678
+ // State-built bundles keep the State root's repo (no cwd fallback: their paths are relative to that root).
2679
+ for (const built of builts) if (!built.stateBuilt) built.bundle.repo ??= detectRepo(cwd)
2680
+ union = unionOfBuilds('bundleCommand', plans, builts, roots)
2681
+ if (bundleExtra) {
2682
+ // Once, whatever the builds' order: to their union, whose own record of a file stands, by the
2683
+ // allowlist of the stasis.config.json at the root, not any one entry's `resources`.
2684
+ const withExtras = withExtra(union, root, { outputs: outputsAt(root) })
2685
+ if (withExtras !== union) pinInstalledCommits(withExtras.bundle, root)
2686
+ union = withExtras
2687
+ }
2688
+ }
2689
+ return { ...union, root }
2690
+ }