@exodus/stasis 1.0.0-beta.11 → 1.0.0-beta.13
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/stasis.js +27 -196
- package/package.json +7 -8
- package/src/audit.js +4 -4
- package/src/babel.js +122 -9
- package/src/cmd/bundle-options.js +398 -0
- package/src/cmd/bundle.js +487 -179
- package/src/define.js +276 -0
- package/src/metro-resolver.js +6 -7
- package/src/metro-transformer.js +3 -4
- package/src/resolve-fields.js +271 -5
- package/src/scan.js +28 -23
- package/src/vfs-bundle/entries.js +20 -2
- package/src/vfs-bundle/github.js +7 -5
- package/src/vfs-bundle/tree.js +4 -4
- package/src/vfs-bundle.js +11 -10
package/src/define.js
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
import { isPlainObject } from '@exodus/stasis-core/util'
|
|
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.
|
|
11
|
+
|
|
12
|
+
// A defined name: an identifier, or a dotted path of them (`process.env.NODE_ENV`).
|
|
13
|
+
const NAME = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*$/u
|
|
14
|
+
|
|
15
|
+
// A usage error, prefixed with `name` where there is one.
|
|
16
|
+
const usageError = (name, message, ErrorType = Error) => new ErrorType(name ? `${name}: ${message}` : message)
|
|
17
|
+
|
|
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
|
+
export function parseDefine(name, define) {
|
|
21
|
+
if (define === undefined) return new Map()
|
|
22
|
+
if (!isPlainObject(define)) throw usageError(name, "define must be an object of each name's value", TypeError)
|
|
23
|
+
for (const [key, value] of Object.entries(define)) {
|
|
24
|
+
if (!NAME.test(key)) throw usageError(name, `--define names an identifier or a dotted path of them (e.g. __DEV__, process.env.NODE_ENV), not ${JSON.stringify(key)}`)
|
|
25
|
+
if (!(value === null || ['string', 'boolean'].includes(typeof value) || Number.isFinite(value))) {
|
|
26
|
+
throw usageError(name, `--define's value for ${key} must be a string, number, boolean or null, not ${typeof value === 'object' ? JSON.stringify(value) : String(value)}`)
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return new Map(Object.entries(define))
|
|
30
|
+
}
|
|
31
|
+
|
|
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"`.
|
|
35
|
+
export function parseDefineFlags(name, texts) {
|
|
36
|
+
if (texts.length === 0) throw usageError(name, '--define must give at least one KEY=VALUE (e.g. --define=__DEV__=false)')
|
|
37
|
+
const define = {}
|
|
38
|
+
for (const text of texts) {
|
|
39
|
+
const eq = text.indexOf('=')
|
|
40
|
+
if (eq <= 0) throw usageError(name, `--define must be KEY=VALUE (e.g. --define=__DEV__=false), not ${JSON.stringify(text)}`)
|
|
41
|
+
const key = text.slice(0, eq)
|
|
42
|
+
if (Object.hasOwn(define, key)) throw usageError(name, `--define gives ${key} a value twice`)
|
|
43
|
+
try {
|
|
44
|
+
define[key] = JSON.parse(text.slice(eq + 1))
|
|
45
|
+
} catch {
|
|
46
|
+
throw usageError(name, `--define's value for ${key} must be JSON: a string, quoted (--define=${key}='"production"'), a number, true, false or null, not ${JSON.stringify(text.slice(eq + 1))}`)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
parseDefine(name, define)
|
|
50
|
+
return define
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
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.
|
|
56
|
+
const WRAPPERS = new Set(['ParenthesizedExpression', 'TSAsExpression', 'TSSatisfiesExpression', 'TSNonNullExpression', 'TSTypeAssertion'])
|
|
57
|
+
const EQUALITY = new Set(['===', '!==', '==', '!='])
|
|
58
|
+
const SKIP_KEYS = new Set(['type', 'loc', 'range', 'start', 'end', 'typeAnnotation', 'returnType', 'typeParameters', 'typeArguments'])
|
|
59
|
+
|
|
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`.
|
|
62
|
+
function dottedPath(node) {
|
|
63
|
+
const parts = []
|
|
64
|
+
for (;;) {
|
|
65
|
+
if (WRAPPERS.has(node.type)) node = node.expression
|
|
66
|
+
else if (node.type === 'MemberExpression' && !node.computed && !node.optional) {
|
|
67
|
+
parts.unshift(node.property.name)
|
|
68
|
+
node = node.object
|
|
69
|
+
} else break
|
|
70
|
+
}
|
|
71
|
+
if (node.type !== 'Identifier') return null
|
|
72
|
+
parts.unshift(node.name)
|
|
73
|
+
return parts.join('.')
|
|
74
|
+
}
|
|
75
|
+
|
|
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.
|
|
78
|
+
function writtenPath(node) {
|
|
79
|
+
const parts = []
|
|
80
|
+
while (WRAPPERS.has(node.type) || node.type === 'MemberExpression') {
|
|
81
|
+
if (node.type === 'MemberExpression') {
|
|
82
|
+
const property = node.computed
|
|
83
|
+
? (node.property.type === 'Literal' && typeof node.property.value === 'string' ? node.property.value : null)
|
|
84
|
+
: node.property.name
|
|
85
|
+
// A computed part cuts the path there: what lies past it, it can't name.
|
|
86
|
+
if (property === null) parts.length = 0
|
|
87
|
+
else parts.unshift(property)
|
|
88
|
+
node = node.object
|
|
89
|
+
} else {
|
|
90
|
+
node = node.expression
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (node.type !== 'Identifier') return null
|
|
94
|
+
parts.unshift(node.name)
|
|
95
|
+
return parts.join('.')
|
|
96
|
+
}
|
|
97
|
+
|
|
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.
|
|
100
|
+
// What is only declared for the type checker (`declare const __DEV__: boolean`) binds nothing.
|
|
101
|
+
function ownPaths(program) {
|
|
102
|
+
const paths = new Set()
|
|
103
|
+
const target = (node) => {
|
|
104
|
+
if (!node) return
|
|
105
|
+
if (node.type === 'Identifier') paths.add(node.name)
|
|
106
|
+
else if (node.type === 'ObjectPattern') for (const p of node.properties) target(p.type === 'RestElement' ? p.argument : p.value)
|
|
107
|
+
else if (node.type === 'ArrayPattern') for (const e of node.elements) target(e)
|
|
108
|
+
else if (node.type === 'AssignmentPattern') target(node.left)
|
|
109
|
+
else if (node.type === 'RestElement') target(node.argument)
|
|
110
|
+
else if (node.type === 'TSParameterProperty') target(node.parameter)
|
|
111
|
+
else if (node.type === 'MemberExpression' || WRAPPERS.has(node.type)) {
|
|
112
|
+
const path = writtenPath(node)
|
|
113
|
+
if (path !== null) paths.add(path)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const visit = (node) => {
|
|
117
|
+
if (!node || typeof node !== 'object') return
|
|
118
|
+
if (Array.isArray(node)) {
|
|
119
|
+
for (const c of node) visit(c)
|
|
120
|
+
return
|
|
121
|
+
}
|
|
122
|
+
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
|
+
}
|
|
163
|
+
for (const key of Object.keys(node)) if (!SKIP_KEYS.has(key)) visit(node[key])
|
|
164
|
+
}
|
|
165
|
+
visit(program)
|
|
166
|
+
return paths
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Whether `own` (ownPaths') holds `key` or a path above it.
|
|
170
|
+
function owned(own, key) {
|
|
171
|
+
for (let i = key.length; i > 0; i = key.lastIndexOf('.', i - 1)) {
|
|
172
|
+
if (own.has(key.slice(0, i))) return true
|
|
173
|
+
}
|
|
174
|
+
return false
|
|
175
|
+
}
|
|
176
|
+
|
|
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.
|
|
181
|
+
export function branchFolder(defines, program) {
|
|
182
|
+
if (defines.size === 0) return null
|
|
183
|
+
const own = ownPaths(program)
|
|
184
|
+
const values = new Map([...defines].filter(([key]) => !owned(own, key)))
|
|
185
|
+
if (values.size === 0) return null
|
|
186
|
+
|
|
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.
|
|
199
|
+
const evaluate = (node) => {
|
|
200
|
+
if (WRAPPERS.has(node.type)) return fold(node.expression)
|
|
201
|
+
switch (node.type) {
|
|
202
|
+
case 'Literal':
|
|
203
|
+
return node.regex === undefined && node.bigint === undefined ? node.value : UNKNOWN
|
|
204
|
+
case 'TemplateLiteral':
|
|
205
|
+
return node.expressions.length === 0 && typeof node.quasis[0].value.cooked === 'string' ? node.quasis[0].value.cooked : UNKNOWN
|
|
206
|
+
case 'Identifier':
|
|
207
|
+
case 'MemberExpression': {
|
|
208
|
+
const path = dottedPath(node)
|
|
209
|
+
return path !== null && values.has(path) ? values.get(path) : UNKNOWN
|
|
210
|
+
}
|
|
211
|
+
case 'UnaryExpression': {
|
|
212
|
+
// Metro folds a `void` of a literal alone (`void 0`).
|
|
213
|
+
if (node.operator === 'void') return node.argument.type === 'Literal' ? undefined : UNKNOWN
|
|
214
|
+
if (node.operator !== '!') return UNKNOWN // `typeof`: see BinaryExpression
|
|
215
|
+
const value = fold(node.argument)
|
|
216
|
+
return value === UNKNOWN ? UNKNOWN : !value
|
|
217
|
+
}
|
|
218
|
+
case 'BinaryExpression': {
|
|
219
|
+
if (!EQUALITY.has(node.operator)) return UNKNOWN
|
|
220
|
+
const left = operand(node.left, node.right)
|
|
221
|
+
const right = left === UNKNOWN ? UNKNOWN : operand(node.right, node.left)
|
|
222
|
+
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
|
+
}
|
|
231
|
+
}
|
|
232
|
+
case 'LogicalExpression': {
|
|
233
|
+
const left = node.operator === '??' ? UNKNOWN : fold(node.left)
|
|
234
|
+
if (left === UNKNOWN) return UNKNOWN
|
|
235
|
+
return rightRuns(node.operator, left) ? fold(node.right) : left
|
|
236
|
+
}
|
|
237
|
+
case 'ConditionalExpression': {
|
|
238
|
+
const test = fold(node.test)
|
|
239
|
+
if (test === UNKNOWN) return UNKNOWN
|
|
240
|
+
return fold(test ? node.consequent : node.alternate)
|
|
241
|
+
}
|
|
242
|
+
default:
|
|
243
|
+
return UNKNOWN
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
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).
|
|
249
|
+
const operand = (node, other) => {
|
|
250
|
+
while (WRAPPERS.has(node.type)) node = node.expression
|
|
251
|
+
if (node.type !== 'UnaryExpression' || node.operator !== 'typeof') return fold(node)
|
|
252
|
+
while (WRAPPERS.has(other.type)) other = other.expression
|
|
253
|
+
if (other.type !== 'Literal' || typeof other.value !== 'string' || ['symbol', 'object'].includes(other.value)) return UNKNOWN
|
|
254
|
+
const value = fold(node.argument)
|
|
255
|
+
return value === UNKNOWN ? UNKNOWN : typeof value
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return (node) => {
|
|
259
|
+
if (node.type === 'IfStatement' || node.type === 'ConditionalExpression') {
|
|
260
|
+
const test = fold(node.test)
|
|
261
|
+
if (test === UNKNOWN) return undefined
|
|
262
|
+
return [node.test, test ? node.consequent : node.alternate]
|
|
263
|
+
}
|
|
264
|
+
// `??` never folds: Babel's nullish-coalescing transform makes it an assignment, which Metro
|
|
265
|
+
// doesn't fold.
|
|
266
|
+
if (node.type === 'LogicalExpression' && node.operator !== '??') {
|
|
267
|
+
const left = fold(node.left)
|
|
268
|
+
if (left === UNKNOWN || rightRuns(node.operator, left)) return undefined
|
|
269
|
+
return [node.left]
|
|
270
|
+
}
|
|
271
|
+
return undefined
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Whether the right of `left <operator> right` (`&&` or `||`) runs, `left` its left's value.
|
|
276
|
+
const rightRuns = (operator, left) => (operator === '&&' ? Boolean(left) : !left)
|
package/src/metro-resolver.js
CHANGED
|
@@ -5,6 +5,7 @@ import { pathToFileURL } from 'node:url'
|
|
|
5
5
|
import { diskHost } from '@exodus/stasis-core/host'
|
|
6
6
|
import { isTypeDeclaration } from '@exodus/stasis-core/util'
|
|
7
7
|
import { readJson } from './resolve-typescript.js'
|
|
8
|
+
import { METRO_ASSET_EXTS, lowestPath, metroAssetCandidates } from './resolve-fields.js'
|
|
8
9
|
|
|
9
10
|
// Adapter that drives the PROJECT's own `metro-resolver` from stasis's static scanner, so
|
|
10
11
|
// `stasis bundle --metro --metro-resolver` resolves modules EXACTLY the way that project's
|
|
@@ -89,7 +90,8 @@ export function createMetroResolver({
|
|
|
89
90
|
// A React Native app has no Node builtins by default; Metro only prefers native suffixes off web.
|
|
90
91
|
const base = {
|
|
91
92
|
allowHaste: false,
|
|
92
|
-
|
|
93
|
+
// Metro's default asset extensions, resolved as Metro's DependencyGraph resolves them.
|
|
94
|
+
assetExts: METRO_ASSET_EXTS,
|
|
93
95
|
customResolverOptions: {},
|
|
94
96
|
disableHierarchicalLookup: false,
|
|
95
97
|
doesFileExist: (p) => resolvableType(p) === 'f',
|
|
@@ -110,10 +112,7 @@ export function createMetroResolver({
|
|
|
110
112
|
mainFields,
|
|
111
113
|
nodeModulesPaths: [],
|
|
112
114
|
preferNativePlatform: platform !== 'web',
|
|
113
|
-
resolveAsset: (dirPath, assetName, ext) =>
|
|
114
|
-
const f = join(dirPath, `${assetName}${ext}`)
|
|
115
|
-
return pathType(f) === 'f' ? [f] : null
|
|
116
|
-
},
|
|
115
|
+
resolveAsset: (dirPath, assetName, ext) => metroAssetCandidates(dirPath, assetName, ext),
|
|
117
116
|
resolveHasteModule: () => null,
|
|
118
117
|
resolveHastePackage: () => null,
|
|
119
118
|
// Inert placeholder: `resolve` redirects via its own bundled helper, never this (see header).
|
|
@@ -143,8 +142,8 @@ export function createMetroResolver({
|
|
|
143
142
|
if (!res) return null
|
|
144
143
|
if (res.type === 'empty') return { empty: true }
|
|
145
144
|
if (res.type === 'sourceFile') return { url: pathToFileURL(res.filePath).toString() }
|
|
146
|
-
//
|
|
147
|
-
if (res.type === 'assetFiles' && res.filePaths?.length) return { url: pathToFileURL(res.filePaths
|
|
145
|
+
// An asset's files are it and its scale variants: Metro's graph takes the lowest path for the module.
|
|
146
|
+
if (res.type === 'assetFiles' && res.filePaths?.length) return { url: pathToFileURL(lowestPath(res.filePaths)).toString() }
|
|
148
147
|
return null
|
|
149
148
|
}
|
|
150
149
|
}
|
package/src/metro-transformer.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
// Public-export adapter: backs `@exodus/stasis/metro-transformer`. The transformer
|
|
2
2
|
// lives in @exodus/stasis-plugins (which depends on @exodus/stasis-core for State; it
|
|
3
|
-
// drives load-mode getFile directly).
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
// without cross-worker state sync.
|
|
3
|
+
// drives load-mode getFile directly). withStasis() wires it as Metro's `transformerPath`;
|
|
4
|
+
// wire it yourself only alongside a hand-wired serializer. See the source for the load
|
|
5
|
+
// asymmetry that lets this run per-worker without cross-worker state sync.
|
|
7
6
|
export * from '@exodus/stasis-plugins/metro-transformer'
|
package/src/resolve-fields.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { isBuiltin } from 'node:module'
|
|
2
|
-
import { dirname, isAbsolute, join, relative, resolve as resolvePath } from 'node:path'
|
|
2
|
+
import { basename, dirname, extname, isAbsolute, join, normalize, relative, resolve as resolvePath } from 'node:path'
|
|
3
3
|
import { pathToFileURL } from 'node:url'
|
|
4
4
|
|
|
5
5
|
import { isTypeDeclaration, stripTypeDeclaration, toPosix } from '@exodus/stasis-core/util'
|
|
@@ -20,7 +20,9 @@ import { createNodeResolver } from './resolve-node.js'
|
|
|
20
20
|
// redirect maps) and platform suffixes (`.ios`/`.android`/`.native`), reproducing Metro/React-Native
|
|
21
21
|
// resolution that Node's own resolver (used by scan.js) can't. `exports`-bearing packages are
|
|
22
22
|
// delegated to Node's algorithm, under a bundler's conditions rather than Node's (see
|
|
23
|
-
// resolveConditions)
|
|
23
|
+
// resolveConditions); under `metro`, metro-resolver's own steps around them (viaMetro) and its own
|
|
24
|
+
// reading of `exports` and `imports` maps (metroMapTarget).
|
|
25
|
+
// No user code is executed (only package.json is stat/read).
|
|
24
26
|
//
|
|
25
27
|
// Returns, for each specifier:
|
|
26
28
|
// { url } resolved to a file, by its real path (file: URL string; see fileResolution)
|
|
@@ -139,6 +141,174 @@ function matchRedirect(map, relPath) {
|
|
|
139
141
|
return undefined
|
|
140
142
|
}
|
|
141
143
|
|
|
144
|
+
// The package.json closest to `path` as Metro finds a module's package (getPackageForModule, through
|
|
145
|
+
// metro-file-map's hierarchicalLookup): at the path itself where it is a directory, else above it,
|
|
146
|
+
// none past a `node_modules` segment. A nested package.json (`dist/esm/package.json`, or a subpath
|
|
147
|
+
// directory's own) is one. -> { pkgDir, pkg } or null
|
|
148
|
+
function metroPackageScope(path, host) {
|
|
149
|
+
for (let dir = isDir(path, host) ? path : dirname(path); basename(dir) !== 'node_modules'; dir = dirname(dir)) {
|
|
150
|
+
const pkgPath = join(dir, 'package.json')
|
|
151
|
+
if (isFile(pkgPath, host)) {
|
|
152
|
+
const pkg = readJson(pkgPath, host)
|
|
153
|
+
if (pkg) return { pkgDir: dir, pkg }
|
|
154
|
+
}
|
|
155
|
+
if (dirname(dir) === dir) break
|
|
156
|
+
}
|
|
157
|
+
return null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Metro's redirectModulePath for an absolute `path`: the browser/react-native map of the package
|
|
161
|
+
// closest to it (metroPackageScope), matched by the path's package-relative spelling. A string is
|
|
162
|
+
// taken as package-relative, as Metro takes it, even where it names another package.
|
|
163
|
+
// -> the path, redirected where the map says so, or false (an empty module)
|
|
164
|
+
function metroRedirect(path, opts) {
|
|
165
|
+
const scope = metroPackageScope(path, opts.host)
|
|
166
|
+
if (!scope) return path
|
|
167
|
+
const rel = path === scope.pkgDir ? '' : toPosix(relative(scope.pkgDir, path))
|
|
168
|
+
const r = matchRedirect(mergeRedirectMap(scope.pkg, opts.mainFields), `./${rel}`)
|
|
169
|
+
if (r === false) return false
|
|
170
|
+
if (typeof r === 'string') return isAbsolute(r) ? normalize(r) : join(scope.pkgDir, r)
|
|
171
|
+
return path
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// A bare specifier's package name, first segment and `exports` subpath ('.' or './x'), as Metro
|
|
175
|
+
// parses one (parseBareSpecifier).
|
|
176
|
+
function parseBare(spec) {
|
|
177
|
+
const parts = spec.split('/')
|
|
178
|
+
const n = spec.startsWith('@') && parts.length > 1 ? 2 : 1
|
|
179
|
+
return { name: parts.slice(0, n).join('/'), firstPart: parts[0], subpath: parts.length > n ? `./${parts.slice(n).join('/')}` : '.' }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Metro's default assetExts and assetResolutions (metro-config's defaults).
|
|
183
|
+
export const METRO_ASSET_EXTS = new Set(['bmp', 'gif', 'jpg', 'jpeg', 'png', 'psd', 'svg', 'webp', 'xml', 'm4v', 'mov', 'mp4', 'mpeg', 'mpg', 'webm', 'aac', 'aiff', 'caf', 'm4a', 'mp3', 'wav', 'html', 'pdf', 'yaml', 'yml', 'otf', 'ttf', 'zip'])
|
|
184
|
+
const METRO_ASSET_RESOLUTIONS = ['1', '1.5', '2', '3', '4']
|
|
185
|
+
|
|
186
|
+
// Metro's isAssetFile: any of the file name's dot-suffixes (`png`, or `tar.gz` and `gz`) an asset extension.
|
|
187
|
+
function isMetroAssetFile(path) {
|
|
188
|
+
const name = basename(path)
|
|
189
|
+
for (let i = name.length - 1; i >= 0; i--) {
|
|
190
|
+
if (name[i] === '.' && METRO_ASSET_EXTS.has(name.slice(i + 1))) return true
|
|
191
|
+
}
|
|
192
|
+
return false
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// Metro's own resolveAsset (metro's DependencyGraph): `assetName` with `ext` in `dirPath`, and its
|
|
196
|
+
// scale variants (`a@1x.png` ... `a@4x.png`), those that exist, by real path. -> the paths, or null
|
|
197
|
+
export function metroAssetCandidates(dirPath, assetName, ext, host = diskHost) {
|
|
198
|
+
const base = join(dirPath, assetName)
|
|
199
|
+
const files = [`${base}${ext}`, ...METRO_ASSET_RESOLUTIONS.map((r) => `${base}@${r}x${ext}`)]
|
|
200
|
+
.filter((p) => isFile(p, host))
|
|
201
|
+
.map((p) => host.realpath(p))
|
|
202
|
+
return files.length > 0 ? files : null
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// The file Metro takes for an asset of several (getArrayLowestItem): the lowest path.
|
|
206
|
+
export const lowestPath = (paths) => paths.reduce((lowest, p) => (p < lowest ? p : lowest))
|
|
207
|
+
|
|
208
|
+
// Metro's asset resolution of `path` (resolveFile's, through metro-resolver's resolveAsset): the
|
|
209
|
+
// lowest of it and its scale variants, so `./a.png` lands on `a@3x.png` where only that exists;
|
|
210
|
+
// nothing for a path naming a scale variant itself (`./a@2x.png`), which Metro refuses.
|
|
211
|
+
function metroAsset(path, host) {
|
|
212
|
+
const ext = extname(path)
|
|
213
|
+
const name = basename(path, ext)
|
|
214
|
+
if (/@\d+(?:\.\d+)?x$/u.test(name)) return null
|
|
215
|
+
const files = metroAssetCandidates(dirname(path), name, ext, host)
|
|
216
|
+
return files === null ? null : lowestPath(files)
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// --metro: metro-resolver's own reading of an `exports` or `imports` map (PackageExportsResolve,
|
|
220
|
+
// PackageImportsResolve and their utils), which Node's differs from. Each entry reduces by the
|
|
221
|
+
// conditions (reduceConditionalExport): an object to the first of its keys `conds` holds, again
|
|
222
|
+
// until a string or null, so a fallback array, whose indices no condition names, to null. The whole
|
|
223
|
+
// map is refused where an entry reduces to a value not starting `./` (reduceExportsLikeMap), as
|
|
224
|
+
// Metro refuses it: a bare or `../` target anywhere fails every specifier the map serves. A
|
|
225
|
+
// specifier takes its own entry, else (where that reduces to null as well) the pattern whose base
|
|
226
|
+
// before its `*` is longest, then the longest (matchSubpathFromExportsLike). Each miss -- the map
|
|
227
|
+
// refused, the specifier unmatched, its target null or naming no file -- is Metro's cue to fall
|
|
228
|
+
// back to file-based resolution, which the callers take.
|
|
229
|
+
|
|
230
|
+
// Metro failing a resolution outright, where a miss falls back: on a map value it can't reduce (a
|
|
231
|
+
// number or boolean, where its reduceConditionalExport throws), or a `#` specifier from a package
|
|
232
|
+
// with no `imports` (resolve.js throws before its fallback).
|
|
233
|
+
class MetroFailure extends Error {}
|
|
234
|
+
|
|
235
|
+
// reduceConditionalExport: the string or null `value` reduces to under `conds`, or 'no-match'.
|
|
236
|
+
function metroReduceConditional(value, conds) {
|
|
237
|
+
let reduced = value
|
|
238
|
+
while (reduced != null && typeof reduced !== 'string') {
|
|
239
|
+
if (typeof reduced !== 'object') throw new MetroFailure(`Can't reduce ${JSON.stringify(reduced)} by conditions`)
|
|
240
|
+
let match = 'default' in reduced ? 'no-match' : null
|
|
241
|
+
for (const name in reduced) {
|
|
242
|
+
if (conds.has(name)) {
|
|
243
|
+
match = reduced[name]
|
|
244
|
+
break
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
reduced = match
|
|
248
|
+
}
|
|
249
|
+
return reduced
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// matchSubpathPattern: what `pattern`'s `*` stands for in `subpath`, else null.
|
|
253
|
+
function metroPatternMatch(pattern, subpath) {
|
|
254
|
+
const [base, trailer] = pattern.split('*')
|
|
255
|
+
if (subpath.startsWith(base) && (trailer.length === 0 || (subpath.endsWith(trailer) && subpath.length >= pattern.length))) {
|
|
256
|
+
return subpath.slice(base.length, subpath.length - trailer.length)
|
|
257
|
+
}
|
|
258
|
+
return null
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// The target `subpath` takes in `map` (a Map of a package map's entries) under `conds`, each `*` its
|
|
262
|
+
// match, as Metro maps it; null where it takes none. An `exports` target holding an empty, `.`,
|
|
263
|
+
// `..` or `node_modules` segment is refused besides (findInvalidPathSegment).
|
|
264
|
+
function metroMapTarget(map, subpath, conds, { exports = false } = {}) {
|
|
265
|
+
// isSubpathDefinedInExportsLike: listed, as itself or by a one-`*` pattern, before conditions apply.
|
|
266
|
+
if (!map.has(subpath) && ![...map.keys()].some((key) => key.split('*').length === 2 && metroPatternMatch(key, subpath) !== null)) return null
|
|
267
|
+
const reduced = new Map()
|
|
268
|
+
for (const [key, value] of map) {
|
|
269
|
+
const target = metroReduceConditional(value, conds)
|
|
270
|
+
if (target !== 'no-match') reduced.set(key, target)
|
|
271
|
+
}
|
|
272
|
+
if ([...reduced.values()].some((target) => target != null && !target.startsWith('./'))) return null
|
|
273
|
+
let target = reduced.get(subpath)
|
|
274
|
+
let match = null
|
|
275
|
+
if (target == null) {
|
|
276
|
+
const patterns = [...reduced.keys()].filter((key) => key.includes('*')).toSorted((a, b) => b.indexOf('*') - a.indexOf('*') || b.length - a.length)
|
|
277
|
+
for (const key of patterns) {
|
|
278
|
+
match = metroPatternMatch(key, subpath)
|
|
279
|
+
if (match !== null) {
|
|
280
|
+
target = reduced.get(key)
|
|
281
|
+
break
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (target == null) return null
|
|
286
|
+
if (exports && target.slice(2).split(/[\\/]/u).some((segment) => ['', '.', '..', 'node_modules'].includes(segment))) return null
|
|
287
|
+
// The match as a replacement pattern, as Metro's replaceAll takes it: a `$&` in it is the `*`.
|
|
288
|
+
return match === null ? target : target.replaceAll('*', match)
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// normalizeExportsField: an `exports` field as Metro's Map of subpaths, null where it refuses it --
|
|
292
|
+
// an array to its first `./` string (or first value), each subpath's legacy array to its first item.
|
|
293
|
+
function metroExportsMap(exportsField) {
|
|
294
|
+
if (typeof exportsField === 'string') return new Map([['.', exportsField]])
|
|
295
|
+
let root = exportsField
|
|
296
|
+
if (Array.isArray(exportsField)) root = exportsField.every((value) => typeof value === 'string') ? exportsField.find((value) => value.startsWith('./')) : exportsField[0]
|
|
297
|
+
if (root == null || Array.isArray(root)) return null
|
|
298
|
+
if (typeof root === 'string') return new Map([['.', root]])
|
|
299
|
+
const flat = {}
|
|
300
|
+
for (const [key, value] of Object.entries(root)) {
|
|
301
|
+
if (Array.isArray(value) && (value.length === 0 || Array.isArray(value[0]))) return null
|
|
302
|
+
flat[key] = Array.isArray(value) ? value[0] : value
|
|
303
|
+
}
|
|
304
|
+
const keys = Object.keys(root)
|
|
305
|
+
if (keys.every((key) => key.startsWith('.') || key.startsWith('#'))) return new Map(Object.entries(flat))
|
|
306
|
+
return keys.some((key) => key.startsWith('.')) ? null : new Map([['.', flat]])
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Metro's relative specifier (isRelativeImport): `.`, `..`, or one starting `./` or `../`.
|
|
310
|
+
const METRO_RELATIVE = /^\.\.?(?:\/|$)/u
|
|
311
|
+
|
|
142
312
|
// Probe `base` for a source file in platform order: bare name first, then per ext
|
|
143
313
|
// `base.<platform>.<ext>`, `base.native.<ext>` (native only), `base.<ext>`. `platform: null`
|
|
144
314
|
// disables suffixes. Under metro, every SUFFIXED candidate first passes through the candidate's
|
|
@@ -152,6 +322,8 @@ function resolveSourceFile(base, opts) {
|
|
|
152
322
|
// `dist/index.js` beside it rather than bundling the declaration -- or failing the package
|
|
153
323
|
// outright by falling back to a different index. The probe below still refuses a literal hit.
|
|
154
324
|
base = stripTypeDeclaration(base)
|
|
325
|
+
// Metro resolves an asset by its own rule, scale variants and all, not as a source file.
|
|
326
|
+
if (opts.metro && isMetroAssetFile(base)) return metroAsset(base, opts.host)
|
|
155
327
|
// Candidates share base's directory, hence its package scope; resolve it lazily, once.
|
|
156
328
|
let scope
|
|
157
329
|
const redirectCandidate = (p) => {
|
|
@@ -231,9 +403,11 @@ function resolveFileOrDir(base, opts) {
|
|
|
231
403
|
if (r.empty) return { empty: true }
|
|
232
404
|
// Node's LOAD_AS_DIRECTORY resolves `main` as a file, else as a directory index
|
|
233
405
|
// (`main: "./lib/"` -> lib/index.js); a broken `main` falls back to the package index below.
|
|
406
|
+
// Metro's resolvePackageEntryPoint has no such fallback: it throws (InvalidPackageError).
|
|
234
407
|
const entryBase = join(base, r.entry)
|
|
235
408
|
const inner = asResolution(resolveSourceFile(entryBase, opts) ?? resolveSourceFile(join(entryBase, 'index'), opts))
|
|
236
409
|
if (inner) return inner
|
|
410
|
+
if (opts.metro) return null
|
|
237
411
|
}
|
|
238
412
|
const index = asResolution(resolveSourceFile(join(base, 'index'), opts))
|
|
239
413
|
if (index) return index
|
|
@@ -270,6 +444,88 @@ export function createFieldResolver({
|
|
|
270
444
|
// Node answers a builtin name with the builtin itself, so an `exports`-bearing package named like
|
|
271
445
|
// one (see the header) resolves through this instead, with builtins off; built on first use.
|
|
272
446
|
let packageResolver
|
|
447
|
+
const nodeResolver = () => (packageResolver ??= createNodeResolver(host))
|
|
448
|
+
// --metro: the file a package-map target (`exports`, `imports`; a path from `pkgDir`) names, as
|
|
449
|
+
// Metro takes it (PackageExportsResolve, PackageImportsResolve): an asset as an asset, its scale
|
|
450
|
+
// variants included, so `"./logo": "./logo.png"` reaches `logo@3x.png` where only that exists,
|
|
451
|
+
// else that file itself, no probing; null where it names none.
|
|
452
|
+
const metroTargetFile = (pkgDir, target) => {
|
|
453
|
+
const path = join(pkgDir, target)
|
|
454
|
+
const asset = isMetroAssetFile(path) ? metroAsset(path, host) : null
|
|
455
|
+
if (asset !== null) return fileResolution(asset, host)
|
|
456
|
+
return isFile(path, host) && !isTypeDeclaration(path) ? fileResolution(path, host) : null
|
|
457
|
+
}
|
|
458
|
+
// --metro: the file a `#` specifier names through the `imports` of the package closest to the
|
|
459
|
+
// importer, as Metro maps it (resolvePackageTargetFromImports), which refuses a map with no keys
|
|
460
|
+
// or with one not starting `#`; null where it names none. With no such package or no `imports`
|
|
461
|
+
// in it, Metro fails the specifier, with no file-based fallback.
|
|
462
|
+
const viaMetroImports = (parentFile, specifier, conds) => {
|
|
463
|
+
const scope = metroPackageScope(parentFile, host)
|
|
464
|
+
const imports = scope?.pkg.imports
|
|
465
|
+
if (imports == null) throw new MetroFailure(`No "imports" for ${specifier} from ${parentFile}`)
|
|
466
|
+
const keys = Object.keys(imports)
|
|
467
|
+
if (keys.length === 0 || !keys.every((key) => key.startsWith('#'))) return null
|
|
468
|
+
const target = metroMapTarget(new Map(Object.entries(imports)), specifier, conds)
|
|
469
|
+
return target === null ? null : metroTargetFile(scope.pkgDir, target)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// --metro: metro-resolver's own steps (its resolve.js), so the two resolve alike where they can.
|
|
473
|
+
// A path takes the redirect of the package closest to it, then resolves as a file or directory
|
|
474
|
+
// (resolveModulePath). A bare specifier takes the importer's redirect, then the importer's own
|
|
475
|
+
// `exports` where it names its own package, then, in each node_modules up from the importer, the
|
|
476
|
+
// package there (resolveModuleFromTargetPath): the redirect of the package closest to the
|
|
477
|
+
// candidate path -- a nested package.json counts -- then the `exports` of the one closest to where
|
|
478
|
+
// that lands, else that path as a file or directory. Metro falls back so from any `exports` miss,
|
|
479
|
+
// which keeps `main` and the browser map in play where `exports` serves no condition it asserts.
|
|
480
|
+
const viaMetro = (parentFile, specifier, conds, fileOpts) => {
|
|
481
|
+
const viaPath = (abs) => {
|
|
482
|
+
const target = metroRedirect(abs, opts)
|
|
483
|
+
return target === false ? { empty: true } : resolveFileOrDir(target, fileOpts)
|
|
484
|
+
}
|
|
485
|
+
// The file `subpath` names through the package at `pkgDir`'s `exports` field, as Metro maps it.
|
|
486
|
+
const viaExports = (pkgDir, exportsField, subpath) => {
|
|
487
|
+
const map = metroExportsMap(exportsField)
|
|
488
|
+
const target = map === null ? null : metroMapTarget(map, subpath, conds, { exports: true })
|
|
489
|
+
return target === null ? null : metroTargetFile(pkgDir, target)
|
|
490
|
+
}
|
|
491
|
+
const viaPackage = (spec) => {
|
|
492
|
+
const { name, firstPart, subpath } = parseBare(spec)
|
|
493
|
+
const own = nearestPackage(parentFile, host)
|
|
494
|
+
if (own?.pkg.exports != null && own.pkg.name === name) {
|
|
495
|
+
const hit = viaExports(own.pkgDir, own.pkg.exports, subpath)
|
|
496
|
+
if (hit) return hit
|
|
497
|
+
}
|
|
498
|
+
for (let dir = dirname(parentFile); ; dir = dirname(dir)) {
|
|
499
|
+
const nm = join(dir, 'node_modules')
|
|
500
|
+
// The shallowest directory the package can be in must exist (resolveFromNodeModulesPath).
|
|
501
|
+
if (isDir(subpath !== '.' || name !== firstPart ? join(nm, firstPart) : nm, host)) {
|
|
502
|
+
const target = metroRedirect(join(nm, spec), opts)
|
|
503
|
+
if (target === false) return { empty: true }
|
|
504
|
+
const scope = metroPackageScope(target, host)
|
|
505
|
+
const hit = (scope?.pkg.exports != null && viaExports(scope.pkgDir, scope.pkg.exports, target === scope.pkgDir ? '.' : `./${toPosix(relative(scope.pkgDir, target))}`)) || viaPath(target)
|
|
506
|
+
if (hit) return hit
|
|
507
|
+
// A package there whose entry resolves to nothing ends the lookup: Metro throws on it
|
|
508
|
+
// (InvalidPackageError). Anything else that misses gives way to the next node_modules up.
|
|
509
|
+
if (isFile(join(target, 'package.json'), host)) return null
|
|
510
|
+
}
|
|
511
|
+
if (dirname(dir) === dir) return null
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
if (METRO_RELATIVE.test(specifier) || isAbsolute(specifier)) {
|
|
515
|
+
return viaPath(isAbsolute(specifier) ? specifier : resolvePath(dirname(parentFile), specifier))
|
|
516
|
+
}
|
|
517
|
+
let spec = specifier
|
|
518
|
+
const imp = nearestPackage(parentFile, host)
|
|
519
|
+
const r = imp ? matchRedirect(mergeRedirectMap(imp.pkg, mainFields), spec) : undefined
|
|
520
|
+
if (r === false) return { empty: true }
|
|
521
|
+
if (typeof r === 'string') {
|
|
522
|
+
if (METRO_RELATIVE.test(r) || isAbsolute(r)) return viaPath(isAbsolute(r) ? r : resolvePath(imp.pkgDir, r))
|
|
523
|
+
spec = r
|
|
524
|
+
}
|
|
525
|
+
// A builtin the importer's map did not remap: as for the field resolver (see the header).
|
|
526
|
+
if (isBuiltin(spec)) return spec.startsWith('node:') ? { builtin: true } : (viaPackage(spec) ?? { builtin: true })
|
|
527
|
+
return viaPackage(spec)
|
|
528
|
+
}
|
|
273
529
|
// `callConditions` (from scan) is the parent's format-driven condition set, so `exports`
|
|
274
530
|
// delegation matches Node resolving from THAT file; falls back to configured `conditions`.
|
|
275
531
|
const resolve = function resolve(parentFile, specifier, callConditions) {
|
|
@@ -278,8 +534,7 @@ export function createFieldResolver({
|
|
|
278
534
|
const viaNode = (spec) => {
|
|
279
535
|
try {
|
|
280
536
|
if (!isBuiltin(spec)) return fileResolution(host.resolve(parentFile, spec, conds), host)
|
|
281
|
-
|
|
282
|
-
return fileResolution(packageResolver.resolve(parentFile, spec, conds, { builtins: false }), host)
|
|
537
|
+
return fileResolution(nodeResolver().resolve(parentFile, spec, conds, { builtins: false }), host)
|
|
283
538
|
} catch {
|
|
284
539
|
return null
|
|
285
540
|
}
|
|
@@ -299,7 +554,16 @@ export function createFieldResolver({
|
|
|
299
554
|
const target = typeof r === 'string' ? r : sub
|
|
300
555
|
return resolveFileOrDir(join(loc.pkgDir, target), fileOpts)
|
|
301
556
|
}
|
|
302
|
-
// `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them
|
|
557
|
+
// `#name` subpath imports use the `imports` field + conditions; Node's algorithm handles them,
|
|
558
|
+
// Metro's own under --metro, which falls back to file-based resolution where `imports` misses.
|
|
559
|
+
if (metro) {
|
|
560
|
+
try {
|
|
561
|
+
return (specifier.startsWith('#') && viaMetroImports(parentFile, specifier, conds)) || viaMetro(parentFile, specifier, conds, fileOpts)
|
|
562
|
+
} catch (error) {
|
|
563
|
+
if (error instanceof MetroFailure) return null
|
|
564
|
+
throw error
|
|
565
|
+
}
|
|
566
|
+
}
|
|
303
567
|
if (specifier.startsWith('#')) return viaNode(specifier)
|
|
304
568
|
|
|
305
569
|
let spec = specifier
|
|
@@ -346,6 +610,8 @@ export function createFieldResolver({
|
|
|
346
610
|
return function resolveWithTypescriptFallback(parentFile, specifier, callConditions) {
|
|
347
611
|
const resolved = resolve(parentFile, specifier, callConditions)
|
|
348
612
|
if (resolved) return resolved
|
|
613
|
+
// Under --metro an asset is Metro's asset rule's to resolve (resolveSourceFile), as tsc never does.
|
|
614
|
+
if (metro && isMetroAssetFile(specifier)) return null
|
|
349
615
|
const hit = resolveTypescriptFallback(parentFile, specifier, {
|
|
350
616
|
conditions: new Set(callConditions ?? conditions),
|
|
351
617
|
paths: typescriptPaths,
|