@exodus/stasis-core 1.0.0-beta.9 → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/util.js CHANGED
@@ -1,41 +1,44 @@
1
1
  import { isUtf8 } from 'node:buffer'
2
- import { basename, isAbsolute, join, relative, sep } from 'node:path'
2
+ import { basename, extname, isAbsolute, join, normalize, posix, relative, sep } from 'node:path'
3
3
  import { parseArgs } from 'node:util'
4
4
 
5
- import { NODE_FORMATS } from './artifact-util.js'
5
+ import { ARCHIVE_ALGORITHM, CONFIG_FILE, NODE_FORMATS, isLockfileName } from './artifact-util.js'
6
6
  import { diskHost } from './host.js'
7
7
 
8
- // The Node-side half of the util split: byte/name classification for the capture walks, fs/execute-bit
9
- // observation and CLI parsing. The pure artifact data model lives in artifact-util.js, re-exported
10
- // here so `@exodus/stasis-core/util` keeps serving the full set.
11
8
  export * from './artifact-util.js'
12
9
 
10
+ export const hexIntegrity = (algorithm, hex) => (typeof hex === 'string' && /^(?:[\da-f]{2})+$/u.test(hex) ? `${algorithm}-${Buffer.from(hex, 'hex').toString('base64')}` : undefined)
11
+ export const integrityHex = (integrity) => Buffer.from(integrity.slice(integrity.indexOf('-') + 1), 'base64').toString('hex')
12
+ export const archiveIntegrity = (ecosystem, hex) => hexIntegrity(ARCHIVE_ALGORITHM[ecosystem], hex)
13
+
14
+ // Where another package (stasis's run-installed.js) registers the reader of how packages were installed.
15
+ export const INSTALLED = Symbol.for('@exodus/stasis-core/installed')
16
+ export const installedAccounts = (modules, root) => (modules.size > 0 && globalThis[INSTALLED]?.(modules, root)) || new Map()
17
+
13
18
  // JS_UNRESOLVED_EXTS (.js/.ts type/syntax-dependent, .jsx/.tsx transformed) classify as null, not a format.
14
19
  const NODE_EXT_FORMATS = new Map([
15
20
  ['mjs', 'module'], ['cjs', 'commonjs'], ['json', 'json'],
16
21
  ['mts', 'module-typescript'], ['cts', 'commonjs-typescript'],
17
22
  ])
18
23
  const JS_UNRESOLVED_EXTS = new Set(['js', 'ts', 'jsx', 'tsx'])
24
+ export const JS_EXTENSIONS = new Set(['.js', '.cjs', '.mjs', '.ts', '.cts', '.mts', '.jsx', '.tsx'])
19
25
  export const CODE_EXTENSIONS = new Set([...NODE_EXT_FORMATS.keys(), ...JS_UNRESOLVED_EXTS])
26
+ // As Node spells them, by extname: `Foo.MJS` and a `.mjs` dotfile are none (require loads them as commonjs).
27
+ export const nodeExtFormat = (path) => NODE_EXT_FORMATS.get(extname(path).slice(1))
20
28
 
21
- export function pathExt(filePath) {
22
- const m = /\.([^./\\]+)$/.exec(filePath)
23
- return m ? m[1].toLowerCase() : ''
24
- }
29
+ export const pathExt = (filePath) => /\.([^./\\]+)$/.exec(filePath)?.[1].toLowerCase() ?? ''
25
30
 
26
- // A native path as the '/'-joined form every artifact key uses. Off Windows `\` is no separator but
27
- // part of a name, and a name holding one is refused rather than taken for another path.
31
+ // Off Windows `\` is no separator but part of a name, and a name holding one is refused rather than taken for another path.
28
32
  export function toPosix(path) {
29
33
  if (sep === '\\') return path.replaceAll('\\', '/')
30
34
  if (path.includes('\\')) throw new Error(`stasis: a path holding '\\' is not supported: ${path}`)
31
35
  return path
32
36
  }
33
37
 
34
- // Whether a path.relative() result climbs out of its base: absolute, or beginning with a `..`
35
- // SEGMENT -- a bare startsWith('..') would also reject a legitimate `..cache` name.
38
+ // A `..` SEGMENT: a bare startsWith('..') would also reject a legitimate `..cache` name.
36
39
  export const relativeEscapes = (rel) => rel === '..' || rel.startsWith('../') || rel.startsWith(`..${sep}`) || isAbsolute(rel)
37
40
 
38
- // True when `path` is `base` or lies beneath it. Lexical: resolve real paths first where symlinks matter.
41
+ // Lexical: resolve real paths first where symlinks matter.
39
42
  export const isPathWithin = (base, path) => !relativeEscapes(relative(base, path))
40
43
 
41
44
  // Both rules are needed: pathExt('.env.local') is 'local', and the extension rule alone misses `.env.*`.
@@ -44,18 +47,13 @@ export function isDotEnvFile(name) {
44
47
  return base === '.env' || base.startsWith('.env.') || pathExt(base) === 'env'
45
48
  }
46
49
 
47
- // Entries are a bare extension (`png`) or extensionless filename (`LICENSE`); a dotted entry
48
- // (`data.bin`) is rejected because a file with an extension is keyed by it and would never match.
50
+ // A dotted entry (`data.bin`) is rejected: a file with an extension is keyed by it and would never match.
49
51
  export function parseResourcesOption(label, resources) {
50
52
  if (resources === undefined) return new Set()
51
- if (!Array.isArray(resources)) {
52
- throw new TypeError(`${label}: resources must be an array of extension/filename strings`)
53
- }
53
+ if (!Array.isArray(resources)) throw new TypeError(`${label}: resources must be an array of extension/filename strings`)
54
54
  const out = new Set()
55
55
  for (const entry of resources) {
56
- if (typeof entry !== 'string') {
57
- throw new TypeError(`${label}: resources entry must be a string, got ${typeof entry}`)
58
- }
56
+ if (typeof entry !== 'string') throw new TypeError(`${label}: resources entry must be a string, got ${typeof entry}`)
59
57
  const clean = entry.toLowerCase().replace(/^\./, '')
60
58
  if (!/^[a-z0-9][a-z0-9_-]*$/.test(clean)) {
61
59
  throw new Error(`${label}: resources entry '${entry}' is not a valid extension or filename (use e.g. 'png' or 'LICENSE')`)
@@ -68,44 +66,97 @@ export function parseResourcesOption(label, resources) {
68
66
  return out
69
67
  }
70
68
 
69
+ // `lock`'s in the order extract's error lists them.
70
+ export const LOCK_MODES = new Set(['frozen', 'add', 'replace', 'ignore', 'none'])
71
+ export const BUNDLE_MODES = new Set(['none', 'ignore', 'add', 'replace', 'load', 'frozen'])
72
+
73
+ export function memoized(fn, keyOf = (arg) => arg) {
74
+ const cache = new Map()
75
+ return (arg) => {
76
+ const key = keyOf(arg)
77
+ if (!cache.has(key)) cache.set(key, fn(arg))
78
+ return cache.get(key)
79
+ }
80
+ }
81
+
82
+ export const withoutBom = (text) => (text.charCodeAt(0) === 0xFE_FF ? text.slice(1) : text)
83
+
84
+ const unnegated = (entry) => (entry.startsWith('!') ? entry.slice(1) : entry)
85
+
86
+ // The config adds itself, so its files travel with it, unless an entry names it (`!stasis.config.json` too).
87
+ export function parseExtraOption(label, extra) {
88
+ if (extra === undefined) return []
89
+ if (!Array.isArray(extra)) throw new TypeError(`${label}: extra must be an array of paths or glob patterns`)
90
+ for (const entry of extra) {
91
+ if (typeof entry !== 'string' || entry === '') {
92
+ throw new TypeError(`${label}: extra entry must be a non-empty string, got ${JSON.stringify(entry)}`)
93
+ }
94
+ if (entry === '!') throw new Error(`${label}: extra entry '!' needs a pattern to exclude (e.g. '!ios/Pods')`)
95
+ if (relativeEscapes(normalize(unnegated(entry)))) {
96
+ throw new Error(`${label}: extra entry '${entry}' must be a path or pattern within the project root`)
97
+ }
98
+ }
99
+ return extra.some((entry) => extraPattern(entry) === CONFIG_FILE) ? [...extra] : [...extra, CONFIG_FILE]
100
+ }
101
+
102
+ export const extraPattern = (entry) => posix.normalize(unnegated(entry)).replace(/\/+$/u, '')
103
+
104
+ // Paths from the config's dir, which `../` may climb out of to a workspace root's.
105
+ export function parseLockfilesOption(label, lockfiles) {
106
+ if (lockfiles === undefined) return undefined
107
+ if (!Array.isArray(lockfiles) || lockfiles.length === 0) throw new TypeError(`${label}: lockfiles must be a non-empty array of paths`)
108
+ const out = []
109
+ for (const entry of lockfiles) {
110
+ if (typeof entry !== 'string' || entry === '') {
111
+ throw new TypeError(`${label}: lockfiles entry must be a non-empty string, got ${JSON.stringify(entry)}`)
112
+ }
113
+ // As every artifact path: `/`-separated, a `\` being no separator but part of a name.
114
+ if (entry.includes('\\') || posix.isAbsolute(entry)) {
115
+ throw new Error(`${label}: lockfiles entry '${entry}' must be a POSIX path relative to the directory holding ${CONFIG_FILE}`)
116
+ }
117
+ const path = posix.normalize(entry)
118
+ if (path.endsWith('/') || path === '.' || path === '..' || path.endsWith('/..')) {
119
+ throw new Error(`${label}: lockfiles entry '${entry}' must name a file`)
120
+ }
121
+ if (out.includes(path)) throw new Error(`${label}: lockfiles names ${path} twice`)
122
+ out.push(path)
123
+ }
124
+ return out
125
+ }
126
+
71
127
  export const isBrotliQuality = (n) => Number.isInteger(n) && n >= 0 && n <= 11
72
128
 
73
129
  // `${n}` must round-trip to the input, so non-canonical forms ('5.0', '05', ' 5 ') throw.
74
130
  export function parseBrotliQuality(name, value) {
75
131
  const n = Number(value)
76
- if (`${n}` !== value || !isBrotliQuality(n)) {
77
- throw new RangeError(`${name} must be an integer 0..11 (got '${value}')`)
78
- }
132
+ if (`${n}` !== value || !isBrotliQuality(n)) throw new RangeError(`${name} must be an integer 0..11 (got '${value}')`)
79
133
  return n
80
134
  }
81
135
 
82
- // Shifts the leading option tokens off `argv`, stopping at the first positional so `run`'s forwarded
83
- // child argv survives. `valueFlags` lists options whose separate-token value (`-o dir`) isn't the positional.
136
+ export const valueFlagsOf = (options) => Object.entries(options).filter(([, { type }]) => type === 'string')
137
+ .flatMap(([name, { short }]) => (short === undefined ? [`--${name}`] : [`--${name}`, `-${short}`]))
138
+
139
+ // Stops at the first positional, so `run`'s forwarded child argv survives.
84
140
  export function parseLeadingOptions(argv, options, { valueFlags = [], onError } = {}) {
85
141
  const takesValue = new Set(valueFlags)
86
142
  const flags = []
87
- while (argv.length > 0 && (argv[0].startsWith('-') || takesValue.has(flags.at(-1)))) {
88
- flags.push(argv.shift())
89
- }
143
+ while (argv.length > 0 && (argv[0].startsWith('-') || takesValue.has(flags.at(-1)))) flags.push(argv.shift())
90
144
  try {
91
145
  return parseArgs({ args: flags, options }).values
92
146
  } catch (cause) {
93
147
  onError(`Error: ${cause.message}`) // usage(), which exits
94
- return undefined
95
148
  }
96
149
  }
97
150
 
98
- // The JS-graph bundlers' policy view over classifyFormat: only JS-family code (null or a NODE_FORMAT)
99
- // counts as 'code'; native/source formats don't. Otherwise 'resource' if allowlisted, else 'unknown'.
100
151
  export function classifyExtension(filePath, resources) {
101
152
  const format = classifyFormat(filePath)
102
153
  if (format === null || NODE_FORMATS.has(format)) return 'code'
103
- if (resources.has(pathExt(filePath) || basename(filePath).toLowerCase())) return 'resource'
104
- return 'unknown'
154
+ return inResources(filePath, resources) ? 'resource' : 'unknown'
105
155
  }
106
156
 
107
- // Compiled/prebuilt artifacts, non-deterministic across installs, so the native capture skips them
108
- // entirely. Matched on a file OR directory name (an Apple `*.framework`/`*.xcodeproj` bundle dir).
157
+ export const inResources = (path, resources) => resources.has(pathExt(path) || basename(path).toLowerCase())
158
+
159
+ // Non-deterministic across installs, so the native capture skips them; also matched on a dir (`*.framework`).
109
160
  const NATIVE_ARTIFACT_EXTS = new Set([
110
161
  'a', 'so', 'o', 'obj', 'dylib', 'lib', 'dll', 'exe', 'pdb',
111
162
  'aar', 'jar', 'class', 'dex',
@@ -114,32 +165,18 @@ const NATIVE_ARTIFACT_EXTS = new Set([
114
165
  'xcodeproj', 'xcworkspace',
115
166
  'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z',
116
167
  ])
117
- export function isNativeArtifact(name) {
118
- return NATIVE_ARTIFACT_EXTS.has(pathExt(name))
119
- }
168
+ export const isNativeArtifact = (name) => NATIVE_ARTIFACT_EXTS.has(pathExt(name))
120
169
 
121
- // An extensionless non-UTF-8 file is a compiled tool (Hermes' `hermesc`), never source -- skipped.
122
- function isExtensionlessBinary(name, content) {
123
- return pathExt(name) === '' && Buffer.isBuffer(content) && !isUtf8(content)
124
- }
170
+ // Its bytes can't ride the text-only 'xml' format a `.plist` gets, so it needs `.plist` in `resources`.
171
+ export const isBinaryPlist = (name, content) => pathExt(name) === 'plist' && Buffer.isBuffer(content) && !isUtf8(content)
125
172
 
126
- // A binary plist is a real build input, but its bytes can't ride the text-only 'xml' format
127
- // classifyFormat gives a `.plist`. Callers treat it as NOT code, so it needs `.plist` in `resources`.
128
- export function isBinaryPlist(name, content) {
129
- return pathExt(name) === 'plist' && Buffer.isBuffer(content) && !isUtf8(content)
130
- }
131
-
132
- // Discovered by name: RN scatters podspecs in subdirs `react-native config` misses.
133
- export function isPodspec(name) {
134
- return name.endsWith('.podspec') || name.endsWith('.podspec.json')
135
- }
136
-
137
- // Non-JS code formats by extension. Every value must be in KNOWN_FORMATS.
173
+ // Every value must be in KNOWN_FORMATS.
138
174
  const CODE_EXT_FORMATS = new Map([
139
175
  ['sol', 'solidity'],
140
176
  ['php', 'php'],
141
177
  ['sh', 'shell'], ['bash', 'shell'],
142
178
  ['rs', 'rust'],
179
+ ['teal', 'teal'],
143
180
  ['patch', 'patch'],
144
181
  ['java', 'java'],
145
182
  ['kt', 'kotlin'], ['kts', 'kotlin'],
@@ -162,8 +199,7 @@ const CODE_EXT_FORMATS = new Map([
162
199
  ['pbxproj', 'pbxproj'],
163
200
  ])
164
201
 
165
- // Code formats by exact (lowercased) basename, for names whose extension is too generic to key
166
- // (Podfile.lock's `.lock`, CMakeLists.txt's `.txt`).
202
+ // By exact (lowercased) basename, where the extension is too generic to key (Podfile.lock, CMakeLists.txt).
167
203
  const CODE_NAME_FORMATS = new Map([
168
204
  ['podfile', 'podfile'],
169
205
  ['podfile.lock', 'podfile-lock'],
@@ -175,15 +211,9 @@ const CODE_NAME_FORMATS = new Map([
175
211
  ])
176
212
 
177
213
  const SHELL_SHEBANG = /^#![^\n]*\b(?:bash|sh)\b/u
178
- function isShellShebang(content) {
179
- if (!Buffer.isBuffer(content) || !isUtf8(content)) return false
180
- const head = content.subarray(0, 256).toString('utf8')
181
- const nl = head.indexOf('\n')
182
- return SHELL_SHEBANG.test(nl === -1 ? head : head.slice(0, nl))
183
- }
214
+ const isShellShebang = (content) => Buffer.isBuffer(content) && isUtf8(content) && SHELL_SHEBANG.test(content.subarray(0, 256).toString('utf8'))
184
215
 
185
- // Files a native package ships that are NOT build inputs (docs/legal, editor/lint/CI config, logs,
186
- // sidecars), excluded from the Metro native capture. `flow` covers the `*.js.flow` sidecars.
216
+ // Not build inputs, so the Metro native capture skips them. `flow` covers the `*.js.flow` sidecars.
187
217
  const NATIVE_EXCLUDE_EXTS = new Set(['md', 'log', 'map', 'flow', 'swiftdoc'])
188
218
  const NATIVE_EXCLUDE_NAMES = new Set([
189
219
  'license', 'licence', 'third-party-licenses',
@@ -200,46 +230,21 @@ export function isExcludedNativeFile(name, { win32 = process.platform === 'win32
200
230
  return NATIVE_EXCLUDE_EXTS.has(ext) || (!win32 && ext === 'bat')
201
231
  }
202
232
 
203
- export function isExcludedNativeDir(name, { win32 = process.platform === 'win32' } = {}) {
204
- return !win32 && name === 'windows'
205
- }
206
-
207
- // An Apple prebuilt-slice dir (`ios-arm64`, `tvos-arm64_x86_64-simulator`): compiled output, not source,
208
- // at ANY depth. The PLATFORM segment is deliberately loose -- the required ARCH segment is the precision.
233
+ // Compiled output (`ios-arm64`) at ANY depth. The PLATFORM segment is deliberately loose: the ARCH is the precision.
209
234
  const APPLE_ARCH = String.raw`(?:arm64e|arm64_32|arm64|armv7k|armv7s|armv7|x86_64|i386)`
210
- const APPLE_SLICE_DIR = new RegExp(
211
- String.raw`^[a-z0-9]+-${APPLE_ARCH}(?:_${APPLE_ARCH})*(?:-(?:simulator|maccatalyst))?$`,
212
- 'u'
213
- )
214
- export function isAppleSliceDir(name) {
215
- return APPLE_SLICE_DIR.test(name)
216
- }
235
+ const APPLE_SLICE_DIR = new RegExp(String.raw`^[a-z0-9]+-${APPLE_ARCH}(?:_${APPLE_ARCH})*(?:-(?:simulator|maccatalyst))?$`, 'u')
236
+ export const isAppleSliceDir = (name) => APPLE_SLICE_DIR.test(name)
217
237
 
218
- // Types only, never a runtime module: the resolvers must refuse to land on one and fall through to the
219
- // real `.js`. Keyed by compound suffix -- pathExt only sees the trailing `ts`.
220
- const TYPE_DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts']
221
- export function isTypeDeclaration(name) {
222
- const base = basename(name).toLowerCase()
223
- return TYPE_DECLARATION_SUFFIXES.some((suffix) => base.endsWith(suffix))
224
- }
225
-
226
- export function stripTypeDeclaration(name) {
227
- const lower = name.toLowerCase()
228
- const suffix = TYPE_DECLARATION_SUFFIXES.find((s) => lower.endsWith(s))
229
- return suffix === undefined ? name : name.slice(0, -suffix.length)
230
- }
238
+ // Never a runtime module: the resolvers must refuse to land on one and fall through to the real `.js`.
239
+ export const isTypeDeclaration = (name) => /\.d\.[cm]?ts$/u.test(basename(name).toLowerCase())
231
240
 
232
- // stasis's own outputs (`stasis.lock.json`, a `*stasis*.br`): absent on a first run but present on a
233
- // later one, so a listing (`--fs` readdir) or a sweep (`add .`) that records one diverges between runs
234
- // and the later capture conflicts.
241
+ // Absent on a first run but present on a later one, so a capture recording one conflicts on the next run.
235
242
  export function isStasisArtifactName(name) {
236
243
  const base = basename(name).toLowerCase()
237
- return base === 'stasis.lock.json' || (base.includes('stasis') && base.endsWith('.br'))
244
+ return isLockfileName(base) || (base.includes('stasis') && base.endsWith('.br'))
238
245
  }
239
246
 
240
- // Dirs no walk descends into: VCS/CI/IDE metadata, sample apps, test scaffolding -- none of it is the
241
- // code being shipped -- plus the Apple prebuilt slice dirs. `name` is a BARE dir name (a dirent name
242
- // or path segment), matched at any depth, so every walk agrees on what "not source" means.
247
+ // `name` is a BARE dir name, matched at any depth, so every walk agrees on what "not source" means.
243
248
  const AUTO_EXCLUDED_DIRS = new Set([
244
249
  '.git', '.github', '.settings', // VCS / CI / IDE metadata
245
250
  'example', 'examples', // sample apps -- they import the package, they aren't it
@@ -250,99 +255,45 @@ export function isAutoExcludedDir(name) {
250
255
  return AUTO_EXCLUDED_DIRS.has(base) || isAppleSliceDir(base)
251
256
  }
252
257
 
253
- // Dirs the NATIVE walks (Metro plugin + the static --metro bundler) skip, on top of the shared set:
254
- // nested packages (attested separately) and regenerated build output -- none is a build input.
255
- const NATIVE_BUILD_OUTPUT_DIRS = new Set(['node_modules', 'build', '.gradle', '.cxx', 'Pods', 'DerivedData'])
256
- export function isSkippedNativeWalkDir(name) {
257
- return NATIVE_BUILD_OUTPUT_DIRS.has(name) || isAutoExcludedDir(name) || isNativeArtifact(name)
258
- }
259
-
260
- // Files a sweep drops: type declarations (types only, erased at runtime), the `.env` family (secrets),
261
- // stasis's own outputs (they'd attest themselves), and everything the native capture excludes as
262
- // non-build-input noise (docs/legal, editor/lint/CI config, `*.map`/`*.js.flow` sidecars, logs).
263
- // A path can only reach this via a glob -- an EXPLICITLY named one is added as asked (`add .env` still
264
- // captures), which is also the only way to attest a file this set covers.
265
- export function isAutoExcludedFile(name) {
266
- return isTypeDeclaration(name) || isDotEnvFile(name) || isStasisArtifactName(name) || isExcludedNativeFile(name)
267
- }
258
+ // Type declarations are erased at runtime, the `.env` family holds secrets, stasis's outputs would attest
259
+ // themselves. Only a glob reaches this: a path NAMED is added as asked, the only way to attest one of these.
260
+ export const isAutoExcludedFile = (name) =>
261
+ isTypeDeclaration(name) || isDotEnvFile(name) || isStasisArtifactName(name) || isExcludedNativeFile(name)
268
262
 
269
- // The single name->format classifier every capture path is a policy view of. Returns a concrete format
270
- // when the name determines one; null for a JS-family file (.js/.ts/.jsx/.tsx); undefined if unrecognized.
271
- export function classifyFormat(name, { content } = {}) {
263
+ export function nameFormat(name) {
272
264
  const base = basename(name).toLowerCase()
273
- // Before the extension rules, so a `*.podspec.json` isn't shadowed.
274
265
  if (base === 'package.json' || base.endsWith('.podspec.json')) return 'json'
275
- // Compound suffix: pathExt only sees the trailing `in`.
276
266
  if (base.endsWith('.cmake.in')) return 'cmake'
277
- const byName = CODE_NAME_FORMATS.get(base)
278
- if (byName !== undefined) return byName
279
- const ext = pathExt(name)
280
- if (JS_UNRESOLVED_EXTS.has(ext)) return null
281
- const byExt = NODE_EXT_FORMATS.get(ext) ?? CODE_EXT_FORMATS.get(ext)
282
- if (byExt !== undefined) return byExt
283
- if (ext === '' && isShellShebang(content)) return 'shell'
284
- return undefined
285
- }
286
-
287
- // The Metro native capture's policy view. Returns { action, format }: 'code' (a native build input),
288
- // 'skip' (excluded noise, or a JS-family file matched BY EXTENSION -- Metro owns those), else 'resource'.
289
- export function classifyNativeCapture(name, { win32 = process.platform === 'win32', content } = {}) {
290
- // `.env` files carry secrets: an automated capture must never sweep them in.
291
- if (isExcludedNativeFile(name, { win32 }) || isDotEnvFile(name)) return { action: 'skip' }
292
- const base = basename(name).toLowerCase()
293
- // Name-matched code is always a native build input, even when its tag is a Node format the JS
294
- // graph would otherwise own.
295
- if (base === 'package.json' || base.endsWith('.podspec.json')) return { action: 'code', format: 'json' }
296
- const byName = CODE_NAME_FORMATS.get(base)
297
- if (byName !== undefined) return { action: 'code', format: byName }
298
- if (CODE_EXTENSIONS.has(pathExt(name))) return { action: 'skip' }
299
- const format = classifyFormat(name, { content })
300
- return format === undefined ? { action: 'resource' } : { action: 'code', format }
301
- }
302
-
303
- // The byte-level half of the native classification, refining what classifyNativeCapture derived from the
304
- // NAME. Both rules only ever demote. A 'resource' carries no format: storage derives base64 from bytes.
305
- export function refineNativeCapture(classified, name, content, resources = new Set()) {
306
- if (isExtensionlessBinary(name, content)) return { action: 'skip' }
307
- if (isBinaryPlist(name, content)) return { action: resources.has('plist') ? 'resource' : 'skip' }
308
- return classified
267
+ return CODE_NAME_FORMATS.get(base)
309
268
  }
310
269
 
311
- // Files `pod install` reads while loading podspecs (Ruby helpers, package.json) -- NOT the native
312
- // source those podspecs compile.
313
- export function isNativeManifest(name) {
314
- return isPodspec(name) || pathExt(name) === 'rb' || name === 'package.json'
270
+ // A format, null for a JS-family file, undefined if unrecognized.
271
+ export function classifyFormat(name, { content } = {}) {
272
+ const byName = nameFormat(name)
273
+ if (byName !== undefined) return byName
274
+ const ext = pathExt(name)
275
+ // A Node extension gives its format only as Node spells it (nodeExtFormat), else the loader decides.
276
+ if (CODE_EXTENSIONS.has(ext)) return nodeExtFormat(name) ?? null
277
+ return CODE_EXT_FORMATS.get(ext) ?? (ext === '' && isShellShebang(content) ? 'shell' : undefined)
315
278
  }
316
279
 
317
- // RN core build scripts the native walk would defer to Metro as `.js`, but Metro never sees them (RN's
318
- // podspecs invoke them at pod-install). Project-relative, so react-native's `exports` can't hide them.
319
- export const RN_CORE_INCLUDE_FILES = ['sdks/hermes-engine/utils/replace_hermes_version.js']
320
-
321
- export const extSetsEqual = (a, b) => a.size === b.size && [...a].every((ext) => b.has(ext))
280
+ export const extSetsEqual = (a, b) => a.size === b.size && a.isSubsetOf(b)
322
281
 
323
282
  export const EXECUTE_BITS = 0o111
324
283
 
325
284
  export const isExecutableMode = (stats) => stats.isFile() && (stats.mode & EXECUTE_BITS) !== 0
326
285
 
327
- // Tri-state: `undefined` means the mode could NOT be observed (gone mid-run, EACCES, ELOOP, a synthetic
328
- // bundle entry). Callers must not read that as "not executable" -- failing to look is not evidence.
286
+ // `undefined`: the mode could NOT be observed (gone, EACCES, ELOOP, synthetic), no evidence of "not executable".
329
287
  export function observeExecutable(abs, host = diskHost) {
330
288
  const stats = host.stat(abs)
331
289
  return stats === null ? undefined : isExecutableMode(stats)
332
290
  }
333
291
 
334
- // Boolean view for callers with nothing to refute (recording a fresh set from scratch).
335
- export const isExecutableFile = (abs, host) => observeExecutable(abs, host) === true
336
-
337
- // Windows reports no POSIX execute bits, so a capture there records none and must NOT read "no bit" as
338
- // "the bit was removed" and strip what a POSIX capture attested.
292
+ // Windows reports no POSIX execute bits: "no bit" there is no evidence a POSIX capture's bit was removed.
339
293
  export const canObserveExecuteBits = ({ win32 = process.platform === 'win32' } = {}) => !win32
340
294
 
341
- // Throws on a symlink escaping the bundle root: a crafted `link.sh -> /etc/passwd` must not pull an
342
- // external file into an attestable bundle. realpath surfaces ENOENT, which loaders treat as "missing".
295
+ // A crafted `link.sh -> /etc/passwd` must not pull an external file into an attestable bundle.
343
296
  export function assertRealPathWithinBase(realBase, baseDir, relPath, host = diskHost) {
344
297
  const real = host.realpath(join(baseDir, relPath))
345
- if (!isPathWithin(realBase, real)) {
346
- throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
347
- }
298
+ if (!isPathWithin(realBase, real)) throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
348
299
  }