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

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.
Files changed (67) hide show
  1. package/README.md +2 -1
  2. package/bin/stasis.js +99 -16
  3. package/package.json +22 -9
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +241 -190
  6. package/src/babel.js +39 -122
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +5 -9
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +82 -174
  11. package/src/cmd/bundle-options.js +113 -167
  12. package/src/cmd/bundle.js +942 -1294
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +21 -26
  15. package/src/cmd/output.js +15 -12
  16. package/src/cmd/sbom.js +3 -8
  17. package/src/cmd/tokens.js +16 -23
  18. package/src/define.js +36 -94
  19. package/src/diff.js +72 -128
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +18 -13
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +41 -93
  27. package/src/loaders/cargo.js +298 -805
  28. package/src/loaders/foundry.js +109 -285
  29. package/src/loaders/paths.js +13 -13
  30. package/src/loaders/php.js +210 -489
  31. package/src/loaders/rust.js +507 -1430
  32. package/src/loaders/solidity-ownership.js +48 -128
  33. package/src/loaders/solidity.js +39 -122
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +10 -384
  37. package/src/metro-resolver.js +58 -134
  38. package/src/metro-transformer.js +0 -5
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +4 -4
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +137 -532
  44. package/src/resolve-node.js +27 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +52 -128
  49. package/src/scan.js +142 -284
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +63 -31
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +596 -522
  56. package/src/vfs-bundle/entries.js +40 -57
  57. package/src/vfs-bundle/github.js +80 -122
  58. package/src/vfs-bundle/glob.js +4 -45
  59. package/src/vfs-bundle/lazy.js +27 -56
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +295 -318
  63. package/src/vfs-bundle/yarnclean.js +10 -31
  64. package/src/vfs-bundle.js +23 -64
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +78 -232
  67. package/src/installed-commits.js +0 -184
package/src/cmd/diff.js CHANGED
@@ -4,16 +4,13 @@ import { sha512integrity } from '@exodus/stasis-core/state-util'
4
4
  import { parseFileWithKind } from '../parse.js'
5
5
  import { diffArtifacts, formatDiffStat, hasDifferences } from '../diff.js'
6
6
 
7
- // Run `stasis diff`: read both lockfiles/bundles from disk and diff them through
8
- // the file-free diff API. Returns { diff, differences } for the caller's exit code.
7
+ // Run `stasis diff`. -> { diff, differences } for the caller's exit code
9
8
  export function diffCommand({ cwd = process.cwd(), left, right, stat, imports = false, out = process.stdout } = {}) {
10
9
  if (!left || !right) throw new Error('diff: two files (lockfile or bundle) are required')
11
10
  if (!stat) throw new Error('diff: only --stat is implemented; pass stat: true')
12
-
13
11
  const a = parseFileWithKind(resolve(cwd, left))
14
12
  const b = parseFileWithKind(resolve(cwd, right))
15
13
  const diff = diffArtifacts(a, b, { imports, hash: sha512integrity })
16
-
17
14
  out.write(formatDiffStat(diff, { left, right, leftKind: a.kind, rightKind: b.kind }))
18
15
  return { diff, differences: hasDifferences(diff) }
19
16
  }
@@ -1,25 +1,22 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { resolve } from 'node:path'
3
3
 
4
+ import { BUNDLE_FILE } from '@exodus/stasis-core/util'
4
5
  import { createClient } from '@preventive/upstream/github.js'
5
6
  import { buildGitHubBundle } from '../vfs-bundle/github.js'
6
7
  import { debugTimed } from './bundle.js'
7
- import { auditTokens, withNpmToken } from './tokens.js'
8
- import { bundledSummary, unpackedSummary, writeBundle, writeFile } from './output.js'
8
+ import { githubToken, withNpmToken } from './tokens.js'
9
+ import { bundledSummary, lockedSummary, lockfileOnlyError, unpackedSummary, writeBundle, writeFile } from './output.js'
9
10
 
10
11
  // The longest file name ext4, APFS and NTFS take: 255 bytes, or characters, ours being ASCII.
11
12
  const NAME_MAX = 255
12
- // Each character outside the portable filename set [A-Za-z0-9._-] made `_`.
13
13
  const portable = (s) => s.replaceAll(/[^\w.-]/gu, '_')
14
14
 
15
- // The default output of `stasis github-bundle`: `owner-name.<commit's first 7>.stasis.code.br` of
16
- // the repo, or `owner-name.<directory, its / made ->.<commit's first 7>.stasis.code.br` of a
17
- // directory in it, portable. A directory too deep for that to fit in NAME_MAX keeps what fits of
18
- // its start, and `_` and the first 8 of its sha256 after it; a valid `github` (at most 140
19
- // characters) leaves at least 91 for it.
15
+ // `owner-name[.<directory, its / made ->].<commit's first 7>.stasis.code.br`. A directory too long for NAME_MAX
16
+ // keeps what fits of its start, then `_` and its sha256's first 8 (a valid `github` leaves it 91 at least).
20
17
  export function githubBundleFile({ github, directory, commit }) {
21
18
  const repo = portable(github.replace('/', '-'))
22
- const tail = `.${portable(commit.slice(0, 7))}.stasis.code.br`
19
+ const tail = `.${portable(commit.slice(0, 7))}.${BUNDLE_FILE}`
23
20
  if (!directory) return `${repo}${tail}`
24
21
  const room = NAME_MAX - `${repo}.${tail}`.length
25
22
  let dir = portable(directory.replaceAll('/', '-'))
@@ -27,22 +24,20 @@ export function githubBundleFile({ github, directory, commit }) {
27
24
  return `${repo}.${dir}${tail}`
28
25
  }
29
26
 
30
- // Run `stasis github-bundle`: the bundle of a GitHub repo at a commit, or the one a tag names (the
31
- // default branch's head without either), as buildGitHubBundle builds it from `options`, written
32
- // brotli-compressed to `output` (githubBundleFile's name for it by default, of the directory
33
- // bundled, the one a `path` gives too; `-` for stdout), and a JS bundle's lockfile to `lockfile`
34
- // where given; then it says how many packages it unpacked, and what it bundled.
35
- // The tree is fetched with GITHUB_TOKEN from `env` where it is set, else with auditTokens(home)'s
36
- // `token` (tokens.js); nothing else of `env` is read. Where process.env gives the npm client no
37
- // token, it is given auditTokens(home)'s `npmToken`, else the one `<home>/.npmrc` gives npm's
38
- // registry, while the bundle is built (tokens.js's withNpmToken).
39
- export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, home, output, lockfile, brotliQuality, client, ...options } = {}) {
40
- const audit = auditTokens(home)
41
- const built = await withNpmToken({ home, audit }, () => buildGitHubBundle({ ...options, lockfile, client: client ?? createClient({ token: env.GITHUB_TOKEN || audit.token || null }) }))
42
- const { directory } = built
43
- const dest = await debugTimed('Wrote the bundle', () => writeBundle(cwd, output ?? githubBundleFile({ github: options.github, directory, commit: built.bundle.repo.commit }), built.bundle.serialize(), brotliQuality))
44
- if (lockfile !== undefined) writeFile(resolve(cwd, lockfile), built.lockfile.serialize())
45
- const from = `${options.github}@${built.bundle.repo.commit}${directory ? `/${directory}` : ''}`
27
+ // Run `stasis github-bundle`. Of `env`, only GITHUB_TOKEN and EXODUS_STASIS_LOCK are read.
28
+ export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, home, output, lockfile, lockfileOnly = false, brotliQuality, client, ...options } = {}) {
29
+ const lockfileOnlyRefused = lockfileOnly ? lockfileOnlyError({ lockfile, output, brotliQuality }) : null
30
+ if (lockfileOnlyRefused !== null) throw new Error(`githubBundleCommand: ${lockfileOnlyRefused}`)
31
+ const built = await withNpmToken(home, () => buildGitHubBundle({ ...options, lockfile, lock: env.EXODUS_STASIS_LOCK || undefined, client: client ?? createClient({ token: githubToken({ env, home }) }) }))
32
+ const { directory, bundle } = built
33
+ // Built before anything is written, as `stasis bundle` builds it.
34
+ const lockData = lockfile === undefined ? undefined : built.lockfile.serialize()
35
+ let dest
36
+ // Serialized under --lockfile-only too: never write a lockfile of a bundle that couldn't be written.
37
+ if (lockfileOnly) bundle.serialize()
38
+ else dest = await debugTimed('Wrote the bundle', () => writeBundle(cwd, output ?? githubBundleFile({ github: options.github, directory, commit: bundle.repo.commit }), bundle.serialize(), brotliQuality))
39
+ if (lockData !== undefined) writeFile(resolve(cwd, lockfile), lockData)
40
+ const from = `${options.github}@${bundle.repo.commit}${directory ? `/${directory}` : ''}`
46
41
  console.warn(unpackedSummary(built.stats))
47
- console.warn(bundledSummary(built.bundle.sources.size, built.bundle.modules, from, dest))
42
+ console.warn((lockfileOnly ? lockedSummary : bundledSummary)(bundle.sources.size, bundle.modules, from, lockfileOnly ? lockfile : dest))
48
43
  }
package/src/cmd/output.js CHANGED
@@ -3,16 +3,12 @@ import { dirname, resolve } from 'node:path'
3
3
 
4
4
  import { compressBundleText } from '@exodus/stasis-core/brotli'
5
5
 
6
- // Default bundle output: stasis.code.br, the same name `stasis run --bundle=load` discovers, so the two round-trip with no flags.
7
- export const DEFAULT_BUNDLE_FILE = 'stasis.code.br'
8
-
9
- // Write `data` to the absolute path `abs`, creating its directory.
10
6
  export function writeFile(abs, data) {
11
7
  mkdirSync(dirname(abs), { recursive: true })
12
8
  writeFileSync(abs, data)
13
9
  }
14
10
 
15
- // Write `data` to `target` (resolved against `cwd`), or to stdout for `-`. -> where it went, for the summary
11
+ // `target` from `cwd`, or `-` for stdout. -> where it went, for the summary
16
12
  export function writeOutput(cwd, target, data) {
17
13
  if (target === '-') {
18
14
  process.stdout.write(data)
@@ -22,22 +18,29 @@ export function writeOutput(cwd, target, data) {
22
18
  return target
23
19
  }
24
20
 
25
- // Write a bundle's `serialized` text brotli-compressed (at `brotliQuality`) as writeOutput does. -> where it went
26
21
  export const writeBundle = (cwd, target, serialized, brotliQuality) => writeOutput(cwd, target, compressBundleText(serialized, brotliQuality))
27
22
 
28
- // `N package(s)`: every non-empty bucket of a bundle's `modules` (the "." workspace bucket counts as one).
23
+ // `N package(s)`: the non-empty buckets of `modules`, the "." workspace bucket one of them.
29
24
  export function packagesLabel(modules) {
30
25
  const packages = [...modules.values()].filter((m) => Object.keys(m.files).length > 0).length
31
26
  return `${packages} package${packages === 1 ? '' : 's'}`
32
27
  }
33
28
 
34
- // The summary of what a tree buildVfsBundle built from unpacked, by its `stats`: how many of the
35
- // packages installed (a Soldeer tree's dependencies), the files and their size, and the tarballs
36
- // fetched, where deptree counts them.
37
29
  export function unpackedSummary({ unpacked, installed, dependencies, files, bytes, tarballs }) {
38
30
  const fetched = typeof tarballs === 'number' ? `, ${tarballs} tarball${tarballs === 1 ? '' : 's'} fetched` : ''
39
31
  return `[stasis] Unpacked ${unpacked} of ${installed ?? dependencies} packages: ${files} files, ${(bytes / 2 ** 20).toFixed(1)} MiB${fetched}`
40
32
  }
41
33
 
42
- // The summary of a bundle of `count` files in `modules` written from `from` to `dest`.
43
- export const bundledSummary = (count, modules, from, dest) => `[stasis] Bundled ${count} files in ${packagesLabel(modules)} from ${from} to ${dest}`
34
+ const summary = (verb) => (count, modules, from, dest) => `[stasis] ${verb} ${count} files in ${packagesLabel(modules)} from ${from} to ${dest}`
35
+ export const bundledSummary = summary('Bundled')
36
+ export const lockedSummary = summary('Locked')
37
+
38
+ // Why --lockfile-only can't be taken with these output options, or null where it can; `brotliQuality`
39
+ // counts as given, parsed or not.
40
+ export function lockfileOnlyError({ lockfile, output, add = false, brotliQuality }) {
41
+ if (!lockfile) return '--lockfile-only requires --lockfile=path'
42
+ if (output !== undefined) return "--lockfile-only can't be combined with --output (no bundle is written)"
43
+ if (add) return "--lockfile-only can't be combined with --add (no bundle is merged into)"
44
+ if (brotliQuality !== undefined) return "--lockfile-only can't be combined with --brotli-quality (no bundle is compressed)"
45
+ return null
46
+ }
package/src/cmd/sbom.js CHANGED
@@ -6,15 +6,10 @@ import { writeOutput } from './output.js'
6
6
 
7
7
  // The one-line summary goes to stderr so it never corrupts an SBOM streamed to stdout.
8
8
  export function sbomCommand({ cwd = process.cwd(), files, format, output, now, uuid } = {}) {
9
- if (!Array.isArray(files) || files.length === 0) {
10
- throw new Error('sbom: at least one lockfile or bundle is required')
11
- }
12
- const artifacts = files.map((f) => parseFile(resolve(cwd, f)))
13
- const components = collectComponents(artifacts)
9
+ if (!Array.isArray(files) || files.length === 0) throw new Error('sbom: at least one lockfile or bundle is required')
10
+ const components = collectComponents(files.map((f) => parseFile(resolve(cwd, f))))
14
11
  const doc = generateSbom(format, components, { now, uuid })
15
- const text = JSON.stringify(doc, undefined, 2) + '\n'
16
-
17
- const dest = writeOutput(cwd, output ?? '-', text)
12
+ const dest = writeOutput(cwd, output ?? '-', JSON.stringify(doc, undefined, 2) + '\n')
18
13
  const n = components.length
19
14
  const vendored = components.reduce((sum, c) => sum + (c.vendored?.length ?? 0), 0)
20
15
  const inThem = vendored === 0 ? '' : ` (and ${vendored} vendored in them)`
package/src/cmd/tokens.js CHANGED
@@ -5,33 +5,29 @@ import { join } from 'node:path'
5
5
 
6
6
  import { readJson } from '@exodus/stasis-core/bundle-util'
7
7
 
8
- // Tokens for fetching, from the environment, and where it has none, as a fallback, from other tools'
9
- // files in the user's home, read for compatibility.
10
-
11
- // The variables @preventive/upstream's npm client takes its token from, the first set and not
12
- // empty, read from process.env on each request.
8
+ // What @preventive/upstream's npm client takes its token from: the first set, read on each request.
13
9
  export const NPM_TOKEN_VARS = ['PREVENTIVE_MEASURES_NPM_TOKEN', 'STASIS_NPM_TOKEN', 'NPM_TOKEN']
14
10
 
15
- // A token as @preventive/upstream takes one, printable ASCII and no space, around which whitespace
16
- // is dropped; anything else is none, so that it never reaches an error message.
11
+ // Printable ASCII and no space, as @preventive/upstream takes one; anything else is none, so that it
12
+ // never reaches an error message.
17
13
  const asToken = (value) => (typeof value === 'string' && /^[!-~]+$/u.test(value.trim()) ? value.trim() : undefined)
18
14
 
19
- // The GitHub `token` and `npmToken` of `<home>/.audit/config.json` (the user's home by default),
20
- // each where the file has it as a token. The file is another tool's, read for compatibility: one
21
- // that is missing, unreadable, not JSON or of another shape gives neither, and nothing is said.
15
+ // `<home>/.audit/config.json`'s tokens. Another tool's file, read for compatibility: one missing,
16
+ // unreadable or of another shape gives none, silently.
22
17
  export function auditTokens(home) {
23
18
  const config = readJson(join(home ?? homedir(), '.audit', 'config.json'))
24
19
  return config === null ? {} : { token: asToken(config.token), npmToken: asToken(config.npmToken) }
25
20
  }
26
21
 
27
- // A line of an .npmrc giving npm's own registry an npm token, exactly as npm writes it: no other
28
- // registry's, no variable for npm to expand, and nothing else on the line.
22
+ export function githubToken({ env = process.env, home } = {}) {
23
+ return env.GITHUB_TOKEN || auditTokens(home).token || null
24
+ }
25
+
26
+ // npm's registry's token exactly as npm writes it: no other registry's, no variable to expand.
29
27
  const NPMRC_LINE = /^\/\/registry\.npmjs\.org\/:_authToken=(npm_[\dA-Za-z]+)\r?$/u
30
28
 
31
- // The npm token `<home>/.npmrc` (the user's home by default) gives npm's registry: that of the last
32
- // line of it that is NPMRC_LINE, as npm takes the last of a setting given twice. Another registry's
33
- // token, or one in any other form, is none. The file is npm's, read for compatibility: one that is
34
- // missing or unreadable gives none, and nothing is said; one that is not valid UTF-8 is refused.
29
+ // `<home>/.npmrc`'s last NPMRC_LINE, as npm takes the last of a setting given twice. A missing or
30
+ // unreadable file gives none, silently; one that is not UTF-8 is refused.
35
31
  export function npmrcToken(home) {
36
32
  const file = join(home ?? homedir(), '.npmrc')
37
33
  let bytes
@@ -46,13 +42,10 @@ export function npmrcToken(home) {
46
42
  return token
47
43
  }
48
44
 
49
- // Run `fn`, with a token for the npm client where process.env gives it none (none of
50
- // NPM_TOKEN_VARS set and not empty), as a fallback: auditTokens(home)'s `npmToken` (`audit`, where
51
- // it is read already), else npmrcToken(home)'s, each file only read then. That token is
52
- // STASIS_NPM_TOKEN in process.env while `fn` runs, for the client to read, and process.env is as it
53
- // was after, unless something else set STASIS_NPM_TOKEN meanwhile. -> what `fn` gives
54
- export async function withNpmToken({ home, audit } = {}, fn) {
55
- const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : ((audit ?? auditTokens(home)).npmToken ?? npmrcToken(home))
45
+ // `fn()` with STASIS_NPM_TOKEN auditTokens' or npmrcToken's where no NPM_TOKEN_VARS is set (each file only
46
+ // read then), restored after unless something else set it meanwhile.
47
+ export async function withNpmToken(home, fn) {
48
+ const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : (auditTokens(home).npmToken ?? npmrcToken(home))
56
49
  if (token === undefined) return fn()
57
50
  const before = process.env.STASIS_NPM_TOKEN
58
51
  process.env.STASIS_NPM_TOKEN = token
package/src/define.js CHANGED
@@ -1,22 +1,15 @@
1
- import { isPlainObject } from '@exodus/stasis-core/util'
1
+ import { isPlainObject, memoized } from '@exodus/stasis-core/util'
2
2
 
3
- // --define: the values a build gives globals (`__DEV__`, `process.env.NODE_ENV`), which the static
4
- // scan takes as constants, to leave out the imports of code they keep from running: under
5
- // `__DEV__=false`, `if (__DEV__) require('./dev')` reaches nothing. Only a branch whose test folds
6
- // to a constant is left out -- `if`/`else`, `?:` and the right of `&&` and `||` -- as Metro's
7
- // release build drops it (its inline and constant-folding transforms, run before it collects a
8
- // file's dependencies); a test that doesn't fold walks both sides, as without a define. It folds
9
- // no test Metro wouldn't, after React Native's Babel transforms, so a --metro bundle never lacks a
10
- // file Metro's graph holds.
3
+ // --define: globals' values (`__DEV__`, `process.env.NODE_ENV`) the scan takes as constants, leaving out the imports in
4
+ // branches they keep from running. No test folds that Metro wouldn't fold, so a --metro bundle lacks no file Metro holds.
5
+
6
+ // What Metro's release build (`dev: false`) inlines and its prelude gives the globals: --metro's default defines.
7
+ export const METRO_RELEASE_DEFINE = Object.freeze({ __DEV__: false, 'process.env.NODE_ENV': 'production' })
11
8
 
12
- // A defined name: an identifier, or a dotted path of them (`process.env.NODE_ENV`).
13
9
  const NAME = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u
14
10
 
15
- // A usage error, prefixed with `name` where there is one.
16
11
  const usageError = (name, message, ErrorType = Error) => new ErrorType(name ? `${name}: ${message}` : message)
17
12
 
18
- // `define` (each name -> its value: a string, number, boolean or null) checked, `name` (if any)
19
- // prefixing errors. -> Map, empty where it is undefined.
20
13
  export function parseDefine(name, define) {
21
14
  if (define === undefined) return new Map()
22
15
  if (!isPlainObject(define)) throw usageError(name, "define must be an object of each name's value", TypeError)
@@ -29,9 +22,7 @@ export function parseDefine(name, define) {
29
22
  return new Map(Object.entries(define))
30
23
  }
31
24
 
32
- // `--define=KEY=VALUE` texts (`texts`, as given) -> parseDefine's object, `name` (if any) prefixing
33
- // errors. VALUE is JSON, as esbuild's --define takes it: `__DEV__=false`,
34
- // `process.env.NODE_ENV="production"`.
25
+ // `--define=KEY=VALUE` texts -> parseDefine's object. VALUE is JSON, as esbuild's --define takes it.
35
26
  export function parseDefineFlags(name, texts) {
36
27
  if (texts.length === 0) throw usageError(name, '--define must give at least one KEY=VALUE (e.g. --define=__DEV__=false)')
37
28
  const define = {}
@@ -51,14 +42,21 @@ export function parseDefineFlags(name, texts) {
51
42
  }
52
43
 
53
44
  const UNKNOWN = Symbol('unknown')
54
- // The wrappers that are gone by the time Metro folds (Babel keeps no parentheses, and TypeScript's
55
- // are stripped first), so leave the value as it is.
45
+ // Gone by the time Metro folds (Babel keeps no parentheses, and TypeScript's are stripped first).
56
46
  const WRAPPERS = new Set(['ParenthesizedExpression', 'TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'])
57
47
  const EQUALITY = new Set(['===', '!==', '==', '!='])
58
48
  const SKIP_KEYS = new Set(['type', 'loc', 'range', 'start', 'end', 'typeAnnotation', 'returnType', 'typeParameters', 'typeArguments'])
49
+ // The child a node of each type binds or writes; functions, `delete` and for-in/of are ownPaths' own.
50
+ const BINDS = {
51
+ __proto__: null,
52
+ VariableDeclarator: 'id', ClassDeclaration: 'id', ClassExpression: 'id',
53
+ TSImportEqualsDeclaration: 'id', TSEnumDeclaration: 'id', TSModuleDeclaration: 'id',
54
+ ImportSpecifier: 'local', ImportDefaultSpecifier: 'local', ImportNamespaceSpecifier: 'local',
55
+ CatchClause: 'param', AssignmentExpression: 'left', UpdateExpression: 'argument',
56
+ }
57
+ const FUNCTIONS = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression'])
59
58
 
60
- // The dotted path `node` names (`process.env.NODE_ENV`), or null: plain property accesses alone, as
61
- // Metro inlines them, not `process.env['NODE_ENV']` or `process.env?.NODE_ENV`.
59
+ // Plain property accesses alone, as Metro inlines them: not `process.env['NODE_ENV']` or `process.env?.NODE_ENV`.
62
60
  function dottedPath(node) {
63
61
  const parts = []
64
62
  for (;;) {
@@ -73,8 +71,7 @@ function dottedPath(node) {
73
71
  return parts.join('.')
74
72
  }
75
73
 
76
- // The path a write to `node` (an assignment target) reaches, as far as it is static from its root
77
- // identifier (`process.env[name]` writes `process.env`), or null where it has no root identifier.
74
+ // As far as it is static from its root identifier (`process.env[name]` writes `process.env`).
78
75
  function writtenPath(node) {
79
76
  const parts = []
80
77
  while (WRAPPERS.has(node.type) || node.type === 'MemberExpression') {
@@ -95,8 +92,7 @@ function writtenPath(node) {
95
92
  return parts.join('.')
96
93
  }
97
94
 
98
- // The paths `program` binds or writes itself, each as far as it is static: a declaration of
99
- // `process` or an assignment to `process.env.NODE_ENV` makes it the file's own, not the define's.
95
+ // A declaration of `process` or an assignment to `process.env.NODE_ENV` makes it the file's own, not the define's.
100
96
  // What is only declared for the type checker (`declare const __DEV__: boolean`) binds nothing.
101
97
  function ownPaths(program) {
102
98
  const paths = new Set()
@@ -120,53 +116,16 @@ function ownPaths(program) {
120
116
  return
121
117
  }
122
118
  if (typeof node.type !== 'string' || node.declare === true) return
123
- switch (node.type) {
124
- case 'VariableDeclarator':
125
- target(node.id)
126
- break
127
- case 'FunctionDeclaration':
128
- case 'FunctionExpression':
129
- case 'ArrowFunctionExpression':
130
- target(node.id)
131
- for (const p of node.params) target(p)
132
- break
133
- case 'ClassDeclaration':
134
- case 'ClassExpression':
135
- case 'TSImportEqualsDeclaration':
136
- case 'TSEnumDeclaration':
137
- case 'TSModuleDeclaration':
138
- target(node.id)
139
- break
140
- case 'CatchClause':
141
- target(node.param)
142
- break
143
- case 'ImportSpecifier':
144
- case 'ImportDefaultSpecifier':
145
- case 'ImportNamespaceSpecifier':
146
- target(node.local)
147
- break
148
- case 'AssignmentExpression':
149
- target(node.left)
150
- break
151
- case 'UpdateExpression':
152
- target(node.argument)
153
- break
154
- case 'UnaryExpression':
155
- if (node.operator === 'delete') target(node.argument)
156
- break
157
- case 'ForInStatement':
158
- case 'ForOfStatement':
159
- if (node.left.type !== 'VariableDeclaration') target(node.left)
160
- break
161
- default:
162
- }
119
+ if (node.type in BINDS) target(node[BINDS[node.type]])
120
+ else if (FUNCTIONS.has(node.type)) for (const p of [node.id, ...node.params]) target(p)
121
+ else if (node.type === 'UnaryExpression' && node.operator === 'delete') target(node.argument)
122
+ else if ((node.type === 'ForInStatement' || node.type === 'ForOfStatement') && node.left.type !== 'VariableDeclaration') target(node.left)
163
123
  for (const key of Object.keys(node)) if (!SKIP_KEYS.has(key)) visit(node[key])
164
124
  }
165
125
  visit(program)
166
126
  return paths
167
127
  }
168
128
 
169
- // Whether `own` (ownPaths') holds `key` or a path above it.
170
129
  function owned(own, key) {
171
130
  for (let i = key.length; i > 0; i = key.lastIndexOf('.', i - 1)) {
172
131
  if (own.has(key.slice(0, i))) return true
@@ -174,28 +133,18 @@ function owned(own, key) {
174
133
  return false
175
134
  }
176
135
 
177
- // The branch folder of `program` under `defines` (parseDefine's): for a node, the children the scan
178
- // is to walk where it is a branch whose test folds (the test itself, and the side that runs), else
179
- // undefined. null where no define applies to the file: none given, or every one bound or written by
180
- // the file itself.
136
+ // For a branch whose test folds, the children to walk: the test and the side that runs. null where no define applies
137
+ // to the file (each one given is the file's own).
181
138
  export function branchFolder(defines, program) {
182
139
  if (defines.size === 0) return null
183
140
  const own = ownPaths(program)
184
141
  const values = new Map([...defines].filter(([key]) => !owned(own, key)))
185
142
  if (values.size === 0) return null
186
143
 
187
- const cache = new WeakMap()
188
- // The value `node` folds to, or UNKNOWN.
189
- const fold = (node) => {
190
- if (!node) return UNKNOWN
191
- if (cache.has(node)) return cache.get(node)
192
- const value = evaluate(node)
193
- cache.set(node, value)
194
- return value
195
- }
196
- // What Metro's constant folding evaluates, once it has inlined the defines (Babel's
197
- // path.evaluate()), and less: a value it can't be sure Metro folds is UNKNOWN, as the bundle may
198
- // never leave out a file Metro's graph holds.
144
+ const folded = memoized((node) => evaluate(node))
145
+ const fold = (node) => (node ? folded(node) : UNKNOWN)
146
+ // What Metro's constant folding evaluates once it has inlined the defines (Babel's path.evaluate()), and less: a
147
+ // value it can't be sure Metro folds is UNKNOWN, as the bundle may never leave out a file Metro's graph holds.
199
148
  const evaluate = (node) => {
200
149
  if (WRAPPERS.has(node.type)) return fold(node.expression)
201
150
  switch (node.type) {
@@ -220,14 +169,9 @@ export function branchFolder(defines, program) {
220
169
  const left = operand(node.left, node.right)
221
170
  const right = left === UNKNOWN ? UNKNOWN : operand(node.right, node.left)
222
171
  if (right === UNKNOWN) return UNKNOWN
223
- switch (node.operator) {
224
- case '===': return left === right
225
- case '!==': return left !== right
226
- // eslint-disable-next-line eqeqeq -- the source's own loose comparison, of primitives
227
- case '==': return left == right
228
- // eslint-disable-next-line eqeqeq
229
- default: return left != right
230
- }
172
+ // eslint-disable-next-line eqeqeq -- the source's own loose comparison, of primitives
173
+ const equal = node.operator.length === 3 ? left === right : left == right
174
+ return node.operator.startsWith('=') ? equal : !equal
231
175
  }
232
176
  case 'LogicalExpression': {
233
177
  const left = node.operator === '??' ? UNKNOWN : fold(node.left)
@@ -244,8 +188,8 @@ export function branchFolder(defines, program) {
244
188
  }
245
189
  }
246
190
 
247
- // The value of `node`, compared with `other`: a `typeof` only beside a string other than 'symbol'
248
- // and 'object', the one Babel's typeof-symbol transform leaves as it is (it makes any other a call).
191
+ // A `typeof` only beside a string other than 'symbol' and 'object', the one Babel's typeof-symbol transform leaves
192
+ // as it is (it makes any other a call).
249
193
  const operand = (node, other) => {
250
194
  while (WRAPPERS.has(node.type)) node = node.expression
251
195
  if (node.type !== 'UnaryExpression' || node.operator !== 'typeof') return fold(node)
@@ -261,8 +205,7 @@ export function branchFolder(defines, program) {
261
205
  if (test === UNKNOWN) return undefined
262
206
  return [node.test, test ? node.consequent : node.alternate]
263
207
  }
264
- // `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro
265
- // doesn't fold.
208
+ // `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro doesn't fold.
266
209
  if (node.type === 'LogicalExpression' && node.operator !== '??') {
267
210
  const left = fold(node.left)
268
211
  if (left === UNKNOWN || rightRuns(node.operator, left)) return undefined
@@ -272,5 +215,4 @@ export function branchFolder(defines, program) {
272
215
  }
273
216
  }
274
217
 
275
- // Whether the right of `left <operator> right` (`&&` or `||`) runs, `left` its left's value.
276
218
  const rightRuns = (operator, left) => (operator === '&&' ? Boolean(left) : !left)