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

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.
@@ -1,15 +1,14 @@
1
1
  import { isAbsolute, relative, resolve } from 'node:path'
2
2
 
3
3
  import { diskHost } from '@exodus/stasis-core/host'
4
- import { readFileSyncMaybe } from '@exodus/stasis-core/state-util'
5
4
  import { isPlainObject, parseBrotliQuality, parseResourcesOption, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
6
5
  import { parseFeatureList } from '../loaders/cargo.js'
7
6
  import { parseDefineFlags } from '../define.js'
8
- import { directoryEntryError, isSolidityEntry } from './bundle.js'
7
+ import { directoryEntryError, isSolidityEntry, readConfigFile } from './bundle.js'
9
8
 
10
9
  const CONFIG_FILE = 'stasis.config.json'
11
10
 
12
- // `stasis bundle`'s flags, as parseArgs takes them, and those taking their value as the next argument.
11
+ // `stasis bundle`'s flags, as parseArgs takes them.
13
12
  export const BUNDLE_FLAGS = {
14
13
  mapping: { type: 'string' },
15
14
  manifests: { type: 'boolean' },
@@ -38,12 +37,13 @@ export const BUNDLE_FLAGS = {
38
37
  'cargo-manifests': { type: 'boolean' },
39
38
  'brotli-quality': { type: 'string' },
40
39
  add: { type: 'boolean' },
40
+ deptree: { type: 'boolean' },
41
41
  }
42
- export const BUNDLE_VALUE_FLAGS = ['--mapping', '--output', '--scope', '--lockfile', '--conditions', '--mainFields', '--babel-aliases', '--platforms', '--resources', '--tsconfig', '--define', '--cargo-features', '--cargo-target', '--brotli-quality', '-o']
43
42
 
44
- // The flags saying where and how the bundle is written. Every other one says how its entries are
45
- // built, which stasis.config.json's `entries` sets per entry instead.
46
- const OUTPUT_FLAGS = new Set(['output', 'lockfile', 'brotli-quality', 'add'])
43
+ // The flags of the bundle as a whole: where and how it is written, and where its dependencies are
44
+ // read from. Every other one says how its entries are built, which stasis.config.json's `entries`
45
+ // sets per entry instead.
46
+ const OUTPUT_FLAGS = new Set(['output', 'lockfile', 'brotli-quality', 'add', 'deptree'])
47
47
  // The entry flags taking a list (comma-separated, or repeated), which an entry's options may give as an array.
48
48
  const LIST_FLAGS = new Set(['conditions', 'mainFields', 'platforms', 'resources', 'cargo-features'])
49
49
  // The entry flags given once per value, which a comma doesn't separate (a define's JSON value may
@@ -55,7 +55,6 @@ const REPEATED_FLAGS = new Set(['define'])
55
55
  const CONSENT_FLAGS = new Map([
56
56
  ['babel', "the project's Babel config"],
57
57
  ['metro-resolver', "the project's metro-resolver"],
58
- ['flow', "the flow-remove-types the project installs (stasis's peer)"],
59
58
  ['cargo', "cargo, and what the project's .cargo/config.toml names"],
60
59
  ['cargo-target', 'rustc'],
61
60
  ])
@@ -68,12 +67,13 @@ function entryKey(cwd, entry) {
68
67
  return relativeEscapes(rel) ? null : toPosix(rel) || '.'
69
68
  }
70
69
 
71
- // The language `entries` share, one bundle being built from one: which of them they all are in.
72
- function entriesLanguage(entries, cwd) {
73
- const dirError = directoryEntryError(entries, cwd)
70
+ // The language `entries` share, one bundle being built from one: which of them they all are in, as
71
+ // the project in `cwd`, read through `host`, holds them.
72
+ function entriesLanguage(entries, cwd, host = diskHost) {
73
+ const dirError = directoryEntryError(entries, cwd, host)
74
74
  if (dirError !== null) throw new Error(dirError)
75
75
  const lang = {
76
- allSol: entries.every((f) => isSolidityEntry(f, cwd)),
76
+ allSol: entries.every((f) => isSolidityEntry(f, cwd, host)),
77
77
  allPhp: entries.every((f) => f.endsWith('.php')),
78
78
  allJs: entries.every((f) => /\.(?:js|cjs|mjs|ts|cts|mts|jsx|tsx)$/u.test(f)),
79
79
  allBash: entries.every((f) => /\.(?:sh|bash)$/u.test(f)),
@@ -134,7 +134,7 @@ function buildOptions(values, { allSol, allJs, allRust }) {
134
134
  if (values.conditions !== undefined && conditions.length === 0) {
135
135
  throw new Error('--conditions must list at least one condition name (e.g. --conditions=react-native,browser)')
136
136
  }
137
- // --flow: strip Flow type syntax (via the optional flow-remove-types dep) before parsing; JS-only.
137
+ // --flow: strip Flow type syntax (via stasis's own flow-remove-types) before parsing; JS-only.
138
138
  if (values.flow && !allJs) throw new Error('--flow is only valid for JS bundles')
139
139
  const flow = Boolean(values.flow)
140
140
  // --typescript: resolve like tsc -- a specifier naming a missing JS output (./x.js, .mjs, .cjs,
@@ -209,15 +209,26 @@ function buildOptions(values, { allSol, allJs, allRust }) {
209
209
  return { mappingFile: values.mapping, manifests, scope: values.scope, conditions, mainFields, metro, metroResolver, babel, babelAliases: values['babel-aliases'], platforms, jsx, flow, typescript, tsconfig: values.tsconfig, resources, define, packageJSON, cargo, cargoFeatures, cargoNoDefaultFeatures, cargoAllFeatures, cargoTarget, cargoManifests }
210
210
  }
211
211
 
212
+ // The CONSENT_FLAGS that run a program of the project's from disk, which needs what it installs on
213
+ // disk: none that --deptree lays out in memory.
214
+ const DISK_RUN_FLAGS = ['babel', 'metro-resolver']
215
+
212
216
  // bundleCommand's options for writing the bundle of entries in `lang` from the parsed output flags in `values`.
213
- function outputOptions(values, { allJs }) {
217
+ function outputOptions(values, { allJs, allSol }) {
214
218
  if (values.lockfile && !allJs) throw new Error('--lockfile is only valid for JS bundles')
219
+ // --deptree: the dependencies laid out in memory from the lockfile (pnpm, yarn 1, npm or Soldeer's),
220
+ // never read from disk, which holds none.
221
+ const deptree = Boolean(values.deptree)
222
+ if (deptree && !allJs && !allSol) throw new Error('--deptree is only valid for JS and .sol bundles')
223
+ for (const flag of deptree ? DISK_RUN_FLAGS : []) {
224
+ if (values[flag]) throw new Error(`--${flag} can't be combined with --deptree (it runs ${CONSENT_FLAGS.get(flag)} from disk, where --deptree installs nothing)`)
225
+ }
215
226
  // --brotli-quality: valid for every entry language (no allJs gate).
216
227
  const brotliQuality = values['brotli-quality'] === undefined ? undefined : parseBrotliQuality('--brotli-quality', values['brotli-quality'])
217
228
  // --add merges into the existing bundle at --output, so it can't target write-only stdout.
218
229
  const add = Boolean(values.add)
219
230
  if (add && values.output === '-') throw new Error('--add cannot be combined with --output=-')
220
- return { output: values.output, lockfile: values.lockfile, brotliQuality, add }
231
+ return { output: values.output, lockfile: values.lockfile, brotliQuality, add, deptree }
221
232
  }
222
233
 
223
234
  // An entry's options in stasis.config.json's `entries` (`what` names it) as the flags they alias, in
@@ -253,15 +264,7 @@ function entryFlags(what, options) {
253
264
  // -> { entry: the name as written, values: its options as flags (entryFlags') }. null where there is
254
265
  // none.
255
266
  export function readConfigEntries(cwd = process.cwd(), host = diskHost) {
256
- const text = readFileSyncMaybe(resolve(cwd), CONFIG_FILE, 'utf8', host)
257
- if (text === null) return null
258
- let config
259
- try {
260
- config = JSON.parse(text)
261
- } catch (cause) {
262
- throw new Error(`${CONFIG_FILE} is not valid JSON`, { cause })
263
- }
264
- const entries = config?.entries
267
+ const entries = readConfigFile(undefined, cwd, host)?.entries
265
268
  if (entries === undefined) return null
266
269
  if (!isPlainObject(entries)) throw new Error(`${CONFIG_FILE}: entries must be an object of each entry's stasis bundle options`)
267
270
  const named = new Map()
@@ -320,3 +323,79 @@ export function bundlePlan({ cwd = process.cwd(), entries, values, config = null
320
323
  }
321
324
  return { ...output, builds: [...builds.values()] }
322
325
  }
326
+
327
+ // buildOptions' options, each by the flag it is given as; and those whose values are a set, in
328
+ // whatever order given (each value of `resources` as parseResourcesOption takes it).
329
+ const OPTION_FLAGS = {
330
+ mappingFile: 'mapping', manifests: 'manifests', scope: 'scope', conditions: 'conditions', mainFields: 'mainFields', metro: 'metro', metroResolver: 'metro-resolver', babel: 'babel', babelAliases: 'babel-aliases', platforms: 'platforms', jsx: 'jsx', flow: 'flow', typescript: 'typescript', tsconfig: 'tsconfig', resources: 'resources', define: 'define', packageJSON: 'package-json', cargo: 'cargo', cargoFeatures: 'cargo-features', cargoNoDefaultFeatures: 'cargo-no-default-features', cargoAllFeatures: 'cargo-all-features', cargoTarget: 'cargo-target', cargoManifests: 'cargo-manifests',
331
+ }
332
+ const SET_OPTIONS = new Set(['conditions', 'platforms', 'resources', 'cargoFeatures'])
333
+ // buildOptions' options where no flag is given.
334
+ const DEFAULT_OPTIONS = buildOptions({}, {})
335
+ // An option's value as compared: a set's sorted, defines by name, none (null) for no value or no define.
336
+ const comparable = (key, value) => {
337
+ if (value === undefined || value === null || (key === 'define' && isPlainObject(value) && Object.keys(value).length === 0)) return 'null'
338
+ if (key === 'resources' && Array.isArray(value)) value = value.map((v) => (typeof v === 'string' ? v.toLowerCase().replace(/^\./u, '') : v))
339
+ if (SET_OPTIONS.has(key) && Array.isArray(value)) return JSON.stringify([...new Set(value)].toSorted())
340
+ if (key === 'define' && isPlainObject(value)) return JSON.stringify(Object.entries(value).toSorted(([a], [b]) => (a < b ? -1 : 1)))
341
+ return JSON.stringify(value)
342
+ }
343
+ // An option as its flags give it: `--jsx`, `--platforms=ios,android`, `--define=__DEV__=false`.
344
+ const optionText = (key, value) => (key === 'define'
345
+ ? Object.entries(value).map(([name, v]) => `--define=${name}=${JSON.stringify(v)}`).join(' ')
346
+ : flagText(OPTION_FLAGS[key], Array.isArray(value) ? value.join(',') : value))
347
+
348
+ // The builds of `entries` that the stasis.config.json in `cwd` (read through `host`) names in its
349
+ // `entries`, for `name`'s bundle, built from a project it runs nothing of
350
+ // (@exodus/stasis/vfs-bundle's): every entry it names where none are given (none, of an empty
351
+ // `entries`: nothing else stands in for them), as paths from `cwd`.
352
+ // -> { entries, builds }, each build `{ entries, ...options }` with the options there (buildOptions'),
353
+ // the entries with the same ones together; null where it names none of those given, or has no
354
+ // `entries`: they are built with `options` alone. It may not name only some. Each of `options`
355
+ // (buildOptions' shape) given other than at its default has to be the one each entry's options
356
+ // set, else it is refused, neither taken over them nor left aside; one left out is theirs. One that
357
+ // runs a program (CONSENT_FLAGS'), set by an entry or given, is refused: nothing of the project
358
+ // runs, so no option allows it. A usage error throws.
359
+ export function configuredBuilds(name, { cwd, host = diskHost, entries, options = {} }) {
360
+ const prefixed = (fn, what = `${name}: `) => {
361
+ try {
362
+ return fn()
363
+ } catch (cause) {
364
+ throw new Error(`${what}${cause.message}`, { cause })
365
+ }
366
+ }
367
+ const config = prefixed(() => readConfigEntries(cwd, host))
368
+ if (config === null || (entries !== undefined && !Array.isArray(entries))) return null
369
+ if (entries === undefined) {
370
+ entries = [...config.keys()]
371
+ if (entries.length === 0) return { entries, builds: [] }
372
+ }
373
+ const keys = entries.map((entry) => entryKey(cwd, entry))
374
+ const configured = entries.filter((_, i) => config.has(keys[i]))
375
+ if (configured.length === 0) return null
376
+ const unnamed = entries.find((_, i) => !config.has(keys[i]))
377
+ if (unnamed !== undefined) {
378
+ throw new Error(`${name}: ${CONFIG_FILE}'s entries name ${configured[0]} but not ${unnamed}: bundle either the entries it names or others, not both`)
379
+ }
380
+ const given = Object.keys(OPTION_FLAGS).filter((key) => options[key] !== undefined && comparable(key, options[key]) !== comparable(key, DEFAULT_OPTIONS[key]))
381
+ const builds = new Map()
382
+ for (const [i, entry] of entries.entries()) {
383
+ const { entry: written, values } = config.get(keys[i])
384
+ const what = `${name}: ${CONFIG_FILE}: entries ${JSON.stringify(written)}`
385
+ const running = [...CONSENT_FLAGS.keys()].find((flag) => values[flag] !== undefined)
386
+ if (running !== undefined) throw new Error(`${what} sets ${running}, which runs ${CONSENT_FLAGS.get(running)}, and nothing of the project runs here`)
387
+ const built = prefixed(() => buildOptions(values, entriesLanguage([entry], cwd, host)), `${what}: `)
388
+ for (const key of given) {
389
+ if (CONSENT_FLAGS.has(OPTION_FLAGS[key])) continue
390
+ if (comparable(key, options[key]) === comparable(key, built[key])) continue
391
+ const set = comparable(key, built[key]) === comparable(key, DEFAULT_OPTIONS[key]) ? `without --${OPTION_FLAGS[key]}` : `with ${optionText(key, built[key])}`
392
+ throw new Error(`${name}: ${optionText(key, options[key])} is given, but ${CONFIG_FILE}'s entries build ${JSON.stringify(written)} ${set}: an entry it names is built with its options there`)
393
+ }
394
+ const id = JSON.stringify(built)
395
+ if (builds.has(id)) builds.get(id).entries.push(entry)
396
+ else builds.set(id, { entries: [entry], ...built })
397
+ }
398
+ const running = given.find((key) => CONSENT_FLAGS.has(OPTION_FLAGS[key]))
399
+ if (running !== undefined) throw new Error(`${name}: ${optionText(running, options[running])} is given, which runs ${CONSENT_FLAGS.get(OPTION_FLAGS[running])}, and nothing of the project runs here`)
400
+ return { entries, builds: [...builds.values()] }
401
+ }