@exodus/stasis 1.0.0-beta.15 → 1.0.0-beta.17
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/README.md +1 -1
- package/bin/stasis.js +26 -11
- package/package.json +10 -9
- package/src/audit-corrections.js +11 -42
- package/src/audit.js +113 -233
- package/src/babel.js +39 -122
- package/src/bundle-from-lockfile.js +9 -21
- package/src/bundle-reader.js +5 -9
- package/src/bundle.js +0 -3
- package/src/cmd/build.js +50 -166
- package/src/cmd/bundle-options.js +110 -167
- package/src/cmd/bundle.js +861 -1344
- package/src/cmd/diff.js +1 -4
- package/src/cmd/github-bundle.js +46 -27
- package/src/cmd/output.js +17 -12
- package/src/cmd/sbom.js +3 -8
- package/src/cmd/tokens.js +10 -23
- package/src/define.js +34 -97
- package/src/diff.js +72 -128
- package/src/esbuild.js +0 -4
- package/src/flow.js +10 -25
- package/src/installed.js +265 -0
- package/src/json-stream.js +4 -9
- package/src/loader-mock.js +3 -8
- package/src/loader.js +1 -5
- package/src/loaders/bash.js +41 -93
- package/src/loaders/cargo.js +298 -805
- package/src/loaders/foundry.js +109 -285
- package/src/loaders/paths.js +13 -13
- package/src/loaders/php.js +210 -489
- package/src/loaders/rust.js +507 -1430
- package/src/loaders/solidity-ownership.js +48 -128
- package/src/loaders/solidity.js +39 -122
- package/src/loaders/toml.js +7 -17
- package/src/lockfile.js +0 -3
- package/src/metro-assets.js +9 -33
- package/src/metro-resolver.js +20 -47
- package/src/metro-transformer.js +0 -5
- package/src/metro.js +0 -4
- package/src/mock.js +32 -80
- package/src/parse.js +2 -5
- package/src/prune.js +0 -3
- package/src/resolve-fields.js +90 -220
- package/src/resolve-node.js +27 -45
- package/src/resolve-typescript.js +109 -313
- package/src/rollup.js +0 -4
- package/src/run-installed.js +10 -0
- package/src/sbom.js +52 -128
- package/src/scan.js +136 -283
- package/src/sixel.js +18 -41
- package/src/table.js +14 -35
- package/src/validate-notes.d.ts +3 -2
- package/src/validate-notes.js +25 -19
- package/src/validate.d.ts +38 -11
- package/src/validate.js +478 -512
- package/src/vfs-bundle/entries.js +40 -57
- package/src/vfs-bundle/github.js +88 -121
- package/src/vfs-bundle/glob.js +4 -45
- package/src/vfs-bundle/lazy.js +27 -56
- package/src/vfs-bundle/prisma.js +167 -110
- package/src/vfs-bundle/soldeer.js +28 -49
- package/src/vfs-bundle/tree.js +295 -318
- package/src/vfs-bundle/yarnclean.js +10 -31
- package/src/vfs-bundle.js +23 -64
- package/src/webpack.js +0 -4
- package/src/why.js +75 -231
- 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
|
|
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
|
}
|
package/src/cmd/github-bundle.js
CHANGED
|
@@ -1,25 +1,24 @@
|
|
|
1
1
|
import { createHash } from 'node:crypto'
|
|
2
|
-
import {
|
|
2
|
+
import { existsSync } from 'node:fs'
|
|
3
|
+
import { relative, resolve } from 'node:path'
|
|
3
4
|
|
|
5
|
+
import { BUNDLE_FILE, LOCK_FILE } from '@exodus/stasis-core/util'
|
|
4
6
|
import { createClient } from '@preventive/upstream/github.js'
|
|
5
7
|
import { buildGitHubBundle } from '../vfs-bundle/github.js'
|
|
6
|
-
import { debugTimed } from './bundle.js'
|
|
8
|
+
import { debugTimed, heldToLockfile } from './bundle.js'
|
|
7
9
|
import { githubToken, withNpmToken } from './tokens.js'
|
|
8
|
-
import { bundledSummary, unpackedSummary, writeBundle, writeFile } from './output.js'
|
|
10
|
+
import { bundledSummary, heldSummary, lockedSummary, lockfileOnlyError, unpackedSummary, writeBundle, writeFile } from './output.js'
|
|
9
11
|
|
|
10
12
|
// The longest file name ext4, APFS and NTFS take: 255 bytes, or characters, ours being ASCII.
|
|
11
13
|
const NAME_MAX = 255
|
|
12
|
-
// Each character outside the portable filename set [A-Za-z0-9._-] made `_`.
|
|
13
14
|
const portable = (s) => s.replaceAll(/[^\w.-]/gu, '_')
|
|
14
15
|
|
|
15
|
-
//
|
|
16
|
-
//
|
|
17
|
-
//
|
|
18
|
-
|
|
19
|
-
// characters) leaves at least 91 for it.
|
|
20
|
-
export function githubBundleFile({ github, directory, commit }) {
|
|
16
|
+
// `owner-name[.<directory, its / made ->].<commit's first 7>.stasis.code.br`, or `.stasis.lock.json` for
|
|
17
|
+
// `suffix` LOCK_FILE. A directory too long for NAME_MAX keeps what fits of its start, then `_` and its sha256's
|
|
18
|
+
// first 8 (a valid `github` leaves it 91 at least, 89 of a lockfile).
|
|
19
|
+
export function githubBundleFile({ github, directory, commit }, suffix = BUNDLE_FILE) {
|
|
21
20
|
const repo = portable(github.replace('/', '-'))
|
|
22
|
-
const tail = `.${portable(commit.slice(0, 7))}
|
|
21
|
+
const tail = `.${portable(commit.slice(0, 7))}.${suffix}`
|
|
23
22
|
if (!directory) return `${repo}${tail}`
|
|
24
23
|
const room = NAME_MAX - `${repo}.${tail}`.length
|
|
25
24
|
let dir = portable(directory.replaceAll('/', '-'))
|
|
@@ -27,21 +26,41 @@ export function githubBundleFile({ github, directory, commit }) {
|
|
|
27
26
|
return `${repo}.${dir}${tail}`
|
|
28
27
|
}
|
|
29
28
|
|
|
30
|
-
// Run `stasis github-bundle
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
//
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
const
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const
|
|
29
|
+
// Run `stasis github-bundle`. Of `env`, only GITHUB_TOKEN and EXODUS_STASIS_LOCK are read.
|
|
30
|
+
// The local lockfile is `lockfile`, else the one named as the bundle would be, `.stasis.lock.json` for
|
|
31
|
+
// `.stasis.code.br`. One there holds the build, by EXODUS_STASIS_LOCK's mode, frozen without it: it must attest the
|
|
32
|
+
// build, and the repo it records the build's, and is left as it is. One not there is written, where `lockfile` or
|
|
33
|
+
// `lockfileOnly` asks for it, recording the repo as the bundle does.
|
|
34
|
+
export async function githubBundleCommand({ cwd = process.cwd(), env = process.env, home, output, lockfile, lockfileOnly = false, brotliQuality, client, ...options } = {}) {
|
|
35
|
+
const lockfileOnlyRefused = lockfileOnly ? lockfileOnlyError({ lockfile, output, brotliQuality, named: true }) : null
|
|
36
|
+
if (lockfileOnlyRefused !== null) throw new Error(`githubBundleCommand: ${lockfileOnlyRefused}`)
|
|
37
|
+
const locks = lockfile !== undefined || lockfileOnly
|
|
38
|
+
// The local lockfile's mode is the environment's alone: a repo's `lock: frozen` pins its own stasis.lock.json.
|
|
39
|
+
const mode = env.EXODUS_STASIS_LOCK || 'frozen'
|
|
40
|
+
if (locks && (mode === 'ignore' || mode === 'none')) throw new Error(`githubBundleCommand: ${lockfile === undefined ? '--lockfile-only' : '--lockfile'}: lock = ${mode} writes no lockfile`)
|
|
41
|
+
// buildGitHubBundle reads only whether a lockfile is asked for, refusing one but of a JS bundle; it writes none.
|
|
42
|
+
const built = await withNpmToken(home, () => buildGitHubBundle({ ...options, lockfile: locks ? lockfile ?? LOCK_FILE : undefined, lock: env.EXODUS_STASIS_LOCK || undefined, client: client ?? createClient({ token: githubToken({ env, home }) }) }))
|
|
43
|
+
const { directory, bundle } = built
|
|
44
|
+
const named = (suffix) => githubBundleFile({ github: options.github, directory, commit: bundle.repo.commit }, suffix)
|
|
45
|
+
const lockTarget = lockfile ?? named(LOCK_FILE)
|
|
46
|
+
const lockAbs = resolve(cwd, lockTarget)
|
|
47
|
+
const label = relative(resolve(cwd), lockAbs)
|
|
48
|
+
// Before anything is written: the build, and the lockfile it writes, take what the one there alone attests. Of
|
|
49
|
+
// a build of none (a Solidity one), it holds nothing.
|
|
50
|
+
const present = existsSync(lockAbs)
|
|
51
|
+
const held = present && heldToLockfile(() => built.lockfile, lockAbs, label, mode, { bundle, accounts: built.accounts, repo: bundle.repo }) !== undefined
|
|
52
|
+
const writes = locks && !(present && mode === 'frozen')
|
|
53
|
+
// Built before anything is written, as `stasis bundle` builds it.
|
|
54
|
+
const lockData = writes ? built.lockfile.serialize() : undefined
|
|
55
|
+
let dest
|
|
56
|
+
// Serialized under --lockfile-only too: never write a lockfile of a bundle that couldn't be written.
|
|
57
|
+
if (lockfileOnly) bundle.serialize()
|
|
58
|
+
else dest = await debugTimed('Wrote the bundle', () => writeBundle(cwd, output ?? named(BUNDLE_FILE), bundle.serialize(), brotliQuality))
|
|
59
|
+
if (lockData !== undefined) writeFile(lockAbs, lockData)
|
|
60
|
+
const from = `${options.github}@${bundle.repo.commit}${directory ? `/${directory}` : ''}`
|
|
61
|
+
const summarized = (summary, to) => summary(bundle.sources.size, bundle.modules, from, to)
|
|
45
62
|
console.warn(unpackedSummary(built.stats))
|
|
46
|
-
console.warn(
|
|
63
|
+
if (held) console.warn(summarized(heldSummary, label))
|
|
64
|
+
if (!lockfileOnly) console.warn(summarized(bundledSummary, dest))
|
|
65
|
+
else if (writes) console.warn(summarized(lockedSummary, lockTarget))
|
|
47
66
|
}
|
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
|
-
//
|
|
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,31 @@ 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)`:
|
|
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
|
-
|
|
43
|
-
export const bundledSummary = (
|
|
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
|
+
export const heldSummary = summary('Held')
|
|
38
|
+
|
|
39
|
+
// Why --lockfile-only can't be taken with these output options, or null where it can; `brotliQuality`
|
|
40
|
+
// counts as given, parsed or not. `named`: a lockfile left out is named by the command, so only an empty one is refused.
|
|
41
|
+
export function lockfileOnlyError({ lockfile, output, add = false, brotliQuality, named = false }) {
|
|
42
|
+
if (named && lockfile === '') return "--lockfile can't be empty: give a path, or leave it out for the default name"
|
|
43
|
+
if (!lockfile && !named) return '--lockfile-only requires --lockfile=path'
|
|
44
|
+
if (output !== undefined) return "--lockfile-only can't be combined with --output (no bundle is written)"
|
|
45
|
+
if (add) return "--lockfile-only can't be combined with --add (no bundle is merged into)"
|
|
46
|
+
if (brotliQuality !== undefined) return "--lockfile-only can't be combined with --brotli-quality (no bundle is compressed)"
|
|
47
|
+
return null
|
|
48
|
+
}
|
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
|
-
|
|
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
|
|
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,39 +5,29 @@ import { join } from 'node:path'
|
|
|
5
5
|
|
|
6
6
|
import { readJson } from '@exodus/stasis-core/bundle-util'
|
|
7
7
|
|
|
8
|
-
//
|
|
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
|
-
//
|
|
16
|
-
//
|
|
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
|
-
//
|
|
20
|
-
//
|
|
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
|
-
// The GitHub token: `env`'s GITHUB_TOKEN where it is set, else, as a fallback, auditTokens(home)'s,
|
|
28
|
-
// only read then. -> it, or null where there is none
|
|
29
22
|
export function githubToken({ env = process.env, home } = {}) {
|
|
30
23
|
return env.GITHUB_TOKEN || auditTokens(home).token || null
|
|
31
24
|
}
|
|
32
25
|
|
|
33
|
-
//
|
|
34
|
-
// registry's, no variable for npm to expand, and nothing else on the line.
|
|
26
|
+
// npm's registry's token exactly as npm writes it: no other registry's, no variable to expand.
|
|
35
27
|
const NPMRC_LINE = /^\/\/registry\.npmjs\.org\/:_authToken=(npm_[\dA-Za-z]+)\r?$/u
|
|
36
28
|
|
|
37
|
-
//
|
|
38
|
-
//
|
|
39
|
-
// token, or one in any other form, is none. The file is npm's, read for compatibility: one that is
|
|
40
|
-
// 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.
|
|
41
31
|
export function npmrcToken(home) {
|
|
42
32
|
const file = join(home ?? homedir(), '.npmrc')
|
|
43
33
|
let bytes
|
|
@@ -52,11 +42,8 @@ export function npmrcToken(home) {
|
|
|
52
42
|
return token
|
|
53
43
|
}
|
|
54
44
|
|
|
55
|
-
//
|
|
56
|
-
//
|
|
57
|
-
// npmrcToken(home)'s, each file only read then. That token is STASIS_NPM_TOKEN in process.env while
|
|
58
|
-
// `fn` runs, for the client to read, and process.env is as it was after, unless something else set
|
|
59
|
-
// STASIS_NPM_TOKEN meanwhile. -> what `fn` gives
|
|
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.
|
|
60
47
|
export async function withNpmToken(home, fn) {
|
|
61
48
|
const token = NPM_TOKEN_VARS.some((name) => process.env[name]) ? undefined : (auditTokens(home).npmToken ?? npmrcToken(home))
|
|
62
49
|
if (token === undefined) return fn()
|
package/src/define.js
CHANGED
|
@@ -1,27 +1,15 @@
|
|
|
1
|
-
import { isPlainObject } from '@exodus/stasis-core/util'
|
|
1
|
+
import { isPlainObject, memoized } from '@exodus/stasis-core/util'
|
|
2
2
|
|
|
3
|
-
// --define:
|
|
4
|
-
//
|
|
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.
|
|
11
5
|
|
|
12
|
-
//
|
|
13
|
-
// prelude gives the globals: what `stasis bundle --metro` and `stasis build --metro` define by
|
|
14
|
-
// default, for each name no define given (a flag or the entry's `define`) gives a value of its own.
|
|
6
|
+
// What Metro's release build (`dev: false`) inlines and its prelude gives the globals: --metro's default defines.
|
|
15
7
|
export const METRO_RELEASE_DEFINE = Object.freeze({ __DEV__: false, 'process.env.NODE_ENV': 'production' })
|
|
16
8
|
|
|
17
|
-
// A defined name: an identifier, or a dotted path of them (`process.env.NODE_ENV`).
|
|
18
9
|
const NAME = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u
|
|
19
10
|
|
|
20
|
-
// A usage error, prefixed with `name` where there is one.
|
|
21
11
|
const usageError = (name, message, ErrorType = Error) => new ErrorType(name ? `${name}: ${message}` : message)
|
|
22
12
|
|
|
23
|
-
// `define` (each name -> its value: a string, number, boolean or null) checked, `name` (if any)
|
|
24
|
-
// prefixing errors. -> Map, empty where it is undefined.
|
|
25
13
|
export function parseDefine(name, define) {
|
|
26
14
|
if (define === undefined) return new Map()
|
|
27
15
|
if (!isPlainObject(define)) throw usageError(name, "define must be an object of each name's value", TypeError)
|
|
@@ -34,9 +22,7 @@ export function parseDefine(name, define) {
|
|
|
34
22
|
return new Map(Object.entries(define))
|
|
35
23
|
}
|
|
36
24
|
|
|
37
|
-
// `--define=KEY=VALUE` texts
|
|
38
|
-
// errors. VALUE is JSON, as esbuild's --define takes it: `__DEV__=false`,
|
|
39
|
-
// `process.env.NODE_ENV="production"`.
|
|
25
|
+
// `--define=KEY=VALUE` texts -> parseDefine's object. VALUE is JSON, as esbuild's --define takes it.
|
|
40
26
|
export function parseDefineFlags(name, texts) {
|
|
41
27
|
if (texts.length === 0) throw usageError(name, '--define must give at least one KEY=VALUE (e.g. --define=__DEV__=false)')
|
|
42
28
|
const define = {}
|
|
@@ -56,14 +42,21 @@ export function parseDefineFlags(name, texts) {
|
|
|
56
42
|
}
|
|
57
43
|
|
|
58
44
|
const UNKNOWN = Symbol('unknown')
|
|
59
|
-
//
|
|
60
|
-
// 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).
|
|
61
46
|
const WRAPPERS = new Set(['ParenthesizedExpression', 'TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'])
|
|
62
47
|
const EQUALITY = new Set(['===', '!==', '==', '!='])
|
|
63
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'])
|
|
64
58
|
|
|
65
|
-
//
|
|
66
|
-
// 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`.
|
|
67
60
|
function dottedPath(node) {
|
|
68
61
|
const parts = []
|
|
69
62
|
for (;;) {
|
|
@@ -78,8 +71,7 @@ function dottedPath(node) {
|
|
|
78
71
|
return parts.join('.')
|
|
79
72
|
}
|
|
80
73
|
|
|
81
|
-
//
|
|
82
|
-
// 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`).
|
|
83
75
|
function writtenPath(node) {
|
|
84
76
|
const parts = []
|
|
85
77
|
while (WRAPPERS.has(node.type) || node.type === 'MemberExpression') {
|
|
@@ -100,8 +92,7 @@ function writtenPath(node) {
|
|
|
100
92
|
return parts.join('.')
|
|
101
93
|
}
|
|
102
94
|
|
|
103
|
-
//
|
|
104
|
-
// `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.
|
|
105
96
|
// What is only declared for the type checker (`declare const __DEV__: boolean`) binds nothing.
|
|
106
97
|
function ownPaths(program) {
|
|
107
98
|
const paths = new Set()
|
|
@@ -125,53 +116,16 @@ function ownPaths(program) {
|
|
|
125
116
|
return
|
|
126
117
|
}
|
|
127
118
|
if (typeof node.type !== 'string' || node.declare === true) return
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
case 'FunctionDeclaration':
|
|
133
|
-
case 'FunctionExpression':
|
|
134
|
-
case 'ArrowFunctionExpression':
|
|
135
|
-
target(node.id)
|
|
136
|
-
for (const p of node.params) target(p)
|
|
137
|
-
break
|
|
138
|
-
case 'ClassDeclaration':
|
|
139
|
-
case 'ClassExpression':
|
|
140
|
-
case 'TSImportEqualsDeclaration':
|
|
141
|
-
case 'TSEnumDeclaration':
|
|
142
|
-
case 'TSModuleDeclaration':
|
|
143
|
-
target(node.id)
|
|
144
|
-
break
|
|
145
|
-
case 'CatchClause':
|
|
146
|
-
target(node.param)
|
|
147
|
-
break
|
|
148
|
-
case 'ImportSpecifier':
|
|
149
|
-
case 'ImportDefaultSpecifier':
|
|
150
|
-
case 'ImportNamespaceSpecifier':
|
|
151
|
-
target(node.local)
|
|
152
|
-
break
|
|
153
|
-
case 'AssignmentExpression':
|
|
154
|
-
target(node.left)
|
|
155
|
-
break
|
|
156
|
-
case 'UpdateExpression':
|
|
157
|
-
target(node.argument)
|
|
158
|
-
break
|
|
159
|
-
case 'UnaryExpression':
|
|
160
|
-
if (node.operator === 'delete') target(node.argument)
|
|
161
|
-
break
|
|
162
|
-
case 'ForInStatement':
|
|
163
|
-
case 'ForOfStatement':
|
|
164
|
-
if (node.left.type !== 'VariableDeclaration') target(node.left)
|
|
165
|
-
break
|
|
166
|
-
default:
|
|
167
|
-
}
|
|
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)
|
|
168
123
|
for (const key of Object.keys(node)) if (!SKIP_KEYS.has(key)) visit(node[key])
|
|
169
124
|
}
|
|
170
125
|
visit(program)
|
|
171
126
|
return paths
|
|
172
127
|
}
|
|
173
128
|
|
|
174
|
-
// Whether `own` (ownPaths') holds `key` or a path above it.
|
|
175
129
|
function owned(own, key) {
|
|
176
130
|
for (let i = key.length; i > 0; i = key.lastIndexOf('.', i - 1)) {
|
|
177
131
|
if (own.has(key.slice(0, i))) return true
|
|
@@ -179,28 +133,18 @@ function owned(own, key) {
|
|
|
179
133
|
return false
|
|
180
134
|
}
|
|
181
135
|
|
|
182
|
-
//
|
|
183
|
-
//
|
|
184
|
-
// undefined. null where no define applies to the file: none given, or every one bound or written by
|
|
185
|
-
// 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).
|
|
186
138
|
export function branchFolder(defines, program) {
|
|
187
139
|
if (defines.size === 0) return null
|
|
188
140
|
const own = ownPaths(program)
|
|
189
141
|
const values = new Map([...defines].filter(([key]) => !owned(own, key)))
|
|
190
142
|
if (values.size === 0) return null
|
|
191
143
|
|
|
192
|
-
const
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (cache.has(node)) return cache.get(node)
|
|
197
|
-
const value = evaluate(node)
|
|
198
|
-
cache.set(node, value)
|
|
199
|
-
return value
|
|
200
|
-
}
|
|
201
|
-
// What Metro's constant folding evaluates, once it has inlined the defines (Babel's
|
|
202
|
-
// path.evaluate()), and less: a value it can't be sure Metro folds is UNKNOWN, as the bundle may
|
|
203
|
-
// 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.
|
|
204
148
|
const evaluate = (node) => {
|
|
205
149
|
if (WRAPPERS.has(node.type)) return fold(node.expression)
|
|
206
150
|
switch (node.type) {
|
|
@@ -225,14 +169,9 @@ export function branchFolder(defines, program) {
|
|
|
225
169
|
const left = operand(node.left, node.right)
|
|
226
170
|
const right = left === UNKNOWN ? UNKNOWN : operand(node.right, node.left)
|
|
227
171
|
if (right === UNKNOWN) return UNKNOWN
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
// eslint-disable-next-line eqeqeq -- the source's own loose comparison, of primitives
|
|
232
|
-
case '==': return left == right
|
|
233
|
-
// eslint-disable-next-line eqeqeq
|
|
234
|
-
default: return left != right
|
|
235
|
-
}
|
|
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
|
|
236
175
|
}
|
|
237
176
|
case 'LogicalExpression': {
|
|
238
177
|
const left = node.operator === '??' ? UNKNOWN : fold(node.left)
|
|
@@ -249,8 +188,8 @@ export function branchFolder(defines, program) {
|
|
|
249
188
|
}
|
|
250
189
|
}
|
|
251
190
|
|
|
252
|
-
//
|
|
253
|
-
//
|
|
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).
|
|
254
193
|
const operand = (node, other) => {
|
|
255
194
|
while (WRAPPERS.has(node.type)) node = node.expression
|
|
256
195
|
if (node.type !== 'UnaryExpression' || node.operator !== 'typeof') return fold(node)
|
|
@@ -266,8 +205,7 @@ export function branchFolder(defines, program) {
|
|
|
266
205
|
if (test === UNKNOWN) return undefined
|
|
267
206
|
return [node.test, test ? node.consequent : node.alternate]
|
|
268
207
|
}
|
|
269
|
-
// `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro
|
|
270
|
-
// doesn't fold.
|
|
208
|
+
// `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro doesn't fold.
|
|
271
209
|
if (node.type === 'LogicalExpression' && node.operator !== '??') {
|
|
272
210
|
const left = fold(node.left)
|
|
273
211
|
if (left === UNKNOWN || rightRuns(node.operator, left)) return undefined
|
|
@@ -277,5 +215,4 @@ export function branchFolder(defines, program) {
|
|
|
277
215
|
}
|
|
278
216
|
}
|
|
279
217
|
|
|
280
|
-
// Whether the right of `left <operator> right` (`&&` or `||`) runs, `left` its left's value.
|
|
281
218
|
const rightRuns = (operator, left) => (operator === '&&' ? Boolean(left) : !left)
|