@exodus/stasis-core 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/src/util.js CHANGED
@@ -1,44 +1,44 @@
1
1
  import { isUtf8 } from 'node:buffer'
2
- import { basename, isAbsolute, join, normalize, posix, 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, isLockfileName } 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])
20
- // The format the name of the file `path` alone gives it, as Node loads it: .json, .mjs, .cjs, .mts and
21
- // .cts are each one format whatever the file holds or its package declares. -> undefined for any other
22
- export const nodeExtFormat = (path) => NODE_EXT_FORMATS.get(pathExt(path))
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))
23
28
 
24
- export function pathExt(filePath) {
25
- const m = /\.([^./\\]+)$/.exec(filePath)
26
- return m ? m[1].toLowerCase() : ''
27
- }
29
+ export const pathExt = (filePath) => /\.([^./\\]+)$/.exec(filePath)?.[1].toLowerCase() ?? ''
28
30
 
29
- // A native path as the '/'-joined form every artifact key uses. Off Windows `\` is no separator but
30
- // 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.
31
32
  export function toPosix(path) {
32
33
  if (sep === '\\') return path.replaceAll('\\', '/')
33
34
  if (path.includes('\\')) throw new Error(`stasis: a path holding '\\' is not supported: ${path}`)
34
35
  return path
35
36
  }
36
37
 
37
- // Whether a path.relative() result climbs out of its base: absolute, or beginning with a `..`
38
- // SEGMENT -- a bare startsWith('..') would also reject a legitimate `..cache` name.
38
+ // A `..` SEGMENT: a bare startsWith('..') would also reject a legitimate `..cache` name.
39
39
  export const relativeEscapes = (rel) => rel === '..' || rel.startsWith('../') || rel.startsWith(`..${sep}`) || isAbsolute(rel)
40
40
 
41
- // 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.
42
42
  export const isPathWithin = (base, path) => !relativeEscapes(relative(base, path))
43
43
 
44
44
  // Both rules are needed: pathExt('.env.local') is 'local', and the extension rule alone misses `.env.*`.
@@ -47,18 +47,13 @@ export function isDotEnvFile(name) {
47
47
  return base === '.env' || base.startsWith('.env.') || pathExt(base) === 'env'
48
48
  }
49
49
 
50
- // Entries are a bare extension (`png`) or extensionless filename (`LICENSE`); a dotted entry
51
- // (`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.
52
51
  export function parseResourcesOption(label, resources) {
53
52
  if (resources === undefined) return new Set()
54
- if (!Array.isArray(resources)) {
55
- throw new TypeError(`${label}: resources must be an array of extension/filename strings`)
56
- }
53
+ if (!Array.isArray(resources)) throw new TypeError(`${label}: resources must be an array of extension/filename strings`)
57
54
  const out = new Set()
58
55
  for (const entry of resources) {
59
- if (typeof entry !== 'string') {
60
- throw new TypeError(`${label}: resources entry must be a string, got ${typeof entry}`)
61
- }
56
+ if (typeof entry !== 'string') throw new TypeError(`${label}: resources entry must be a string, got ${typeof entry}`)
62
57
  const clean = entry.toLowerCase().replace(/^\./, '')
63
58
  if (!/^[a-z0-9][a-z0-9_-]*$/.test(clean)) {
64
59
  throw new Error(`${label}: resources entry '${entry}' is not a valid extension or filename (use e.g. 'png' or 'LICENSE')`)
@@ -71,98 +66,97 @@ export function parseResourcesOption(label, resources) {
71
66
  return out
72
67
  }
73
68
 
74
- const CONFIG_FILE_NAME = 'stasis.config.json'
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)
75
83
 
76
- // stasis.config.json's `extra`: paths, directories and glob patterns relative to the project root,
77
- // taken as `stasis add` takes its arguments, and `!`-prefixed ones excluding what they match
78
- // (expandExtra). Each must stay within the root. A config that sets it names itself too, unless
79
- // an entry names it already or `!stasis.config.json` leaves it out (another exclusion matching it
80
- // still does, at expansion): the files it adds travel with the config that adds them.
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).
81
87
  export function parseExtraOption(label, extra) {
82
88
  if (extra === undefined) return []
83
- if (!Array.isArray(extra)) {
84
- throw new TypeError(`${label}: extra must be an array of paths or glob patterns`)
85
- }
89
+ if (!Array.isArray(extra)) throw new TypeError(`${label}: extra must be an array of paths or glob patterns`)
86
90
  for (const entry of extra) {
87
91
  if (typeof entry !== 'string' || entry === '') {
88
92
  throw new TypeError(`${label}: extra entry must be a non-empty string, got ${JSON.stringify(entry)}`)
89
93
  }
90
94
  if (entry === '!') throw new Error(`${label}: extra entry '!' needs a pattern to exclude (e.g. '!ios/Pods')`)
91
- if (relativeEscapes(normalize(entry.startsWith('!') ? entry.slice(1) : entry))) {
95
+ if (relativeEscapes(normalize(unnegated(entry)))) {
92
96
  throw new Error(`${label}: extra entry '${entry}' must be a path or pattern within the project root`)
93
97
  }
94
98
  }
95
- // Compared as expandExtra matches: no `./`, no trailing `/`.
96
- const names = (entry) => posix.normalize(entry.startsWith('!') ? entry.slice(1) : entry).replace(/\/+$/u, '') === CONFIG_FILE_NAME
97
- return extra.some(names) ? [...extra] : [...extra, CONFIG_FILE_NAME]
98
- }
99
-
100
- // A stasis.config.json key that is true or false, true where it is left out.
101
- const configFlag = (key) => (label, value) => {
102
- if (value === undefined) return true
103
- if (typeof value !== 'boolean') throw new TypeError(`${label}: ${key} must be true or false, got ${JSON.stringify(value)}`)
104
- return value
99
+ return extra.some((entry) => extraPattern(entry) === CONFIG_FILE) ? [...extra] : [...extra, CONFIG_FILE]
105
100
  }
106
101
 
107
- // stasis.config.json's `installDevDependencies`: whether the trees laid out from the lockfile (`stasis
108
- // github-bundle`, @exodus/stasis/vfs-bundle) install devDependencies, as a plain install does (true,
109
- // the default), or leave out what devDependencies alone reach, as `pnpm install --prod`, `npm ci
110
- // --omit=dev` and `yarn install --production` do (false).
111
- export const parseInstallDevDependencies = configFlag('installDevDependencies')
102
+ export const extraPattern = (entry) => posix.normalize(unnegated(entry)).replace(/\/+$/u, '')
112
103
 
113
- // stasis.config.json's `lazyDependencies`: whether the trees `stasis github-bundle` and
114
- // @exodus/stasis/vfs-bundle's builds lay out from the lockfile are lazy where the package manager
115
- // lays one out from the lockfile alone (pnpm, npm), each package fetched once the build reads it
116
- // (true, the default), or have every package fetched before the build (false).
117
- export const parseLazyDependencies = configFlag('lazyDependencies')
118
-
119
- // stasis.config.json's `generatePrisma`: whether `stasis github-bundle` and @exodus/stasis/vfs-bundle's
120
- // builds, given no `generate`, write the Prisma Client of each project the entries reach whose schema
121
- // asks for one, as `prisma generate` would (true, the default), or none (false).
122
- export const parseGeneratePrisma = configFlag('generatePrisma')
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
+ }
123
126
 
124
127
  export const isBrotliQuality = (n) => Number.isInteger(n) && n >= 0 && n <= 11
125
128
 
126
129
  // `${n}` must round-trip to the input, so non-canonical forms ('5.0', '05', ' 5 ') throw.
127
130
  export function parseBrotliQuality(name, value) {
128
131
  const n = Number(value)
129
- if (`${n}` !== value || !isBrotliQuality(n)) {
130
- throw new RangeError(`${name} must be an integer 0..11 (got '${value}')`)
131
- }
132
+ if (`${n}` !== value || !isBrotliQuality(n)) throw new RangeError(`${name} must be an integer 0..11 (got '${value}')`)
132
133
  return n
133
134
  }
134
135
 
135
- // The `valueFlags` (parseLeadingOptions') of parseArgs `options`: each string option's flag and its short alias.
136
136
  export const valueFlagsOf = (options) => Object.entries(options).filter(([, { type }]) => type === 'string')
137
137
  .flatMap(([name, { short }]) => (short === undefined ? [`--${name}`] : [`--${name}`, `-${short}`]))
138
138
 
139
- // Shifts the leading option tokens off `argv`, stopping at the first positional so `run`'s forwarded
140
- // child argv survives. `valueFlags` lists options whose separate-token value (`-o dir`) isn't the positional.
139
+ // Stops at the first positional, so `run`'s forwarded child argv survives.
141
140
  export function parseLeadingOptions(argv, options, { valueFlags = [], onError } = {}) {
142
141
  const takesValue = new Set(valueFlags)
143
142
  const flags = []
144
- while (argv.length > 0 && (argv[0].startsWith('-') || takesValue.has(flags.at(-1)))) {
145
- flags.push(argv.shift())
146
- }
143
+ while (argv.length > 0 && (argv[0].startsWith('-') || takesValue.has(flags.at(-1)))) flags.push(argv.shift())
147
144
  try {
148
145
  return parseArgs({ args: flags, options }).values
149
146
  } catch (cause) {
150
147
  onError(`Error: ${cause.message}`) // usage(), which exits
151
- return undefined
152
148
  }
153
149
  }
154
150
 
155
- // The JS-graph bundlers' policy view over classifyFormat: only JS-family code (null or a NODE_FORMAT)
156
- // counts as 'code'; native/source formats don't. Otherwise 'resource' if allowlisted, else 'unknown'.
157
151
  export function classifyExtension(filePath, resources) {
158
152
  const format = classifyFormat(filePath)
159
153
  if (format === null || NODE_FORMATS.has(format)) return 'code'
160
- if (resources.has(pathExt(filePath) || basename(filePath).toLowerCase())) return 'resource'
161
- return 'unknown'
154
+ return inResources(filePath, resources) ? 'resource' : 'unknown'
162
155
  }
163
156
 
164
- // Compiled/prebuilt artifacts, non-deterministic across installs, so the native capture skips them
165
- // 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`).
166
160
  const NATIVE_ARTIFACT_EXTS = new Set([
167
161
  'a', 'so', 'o', 'obj', 'dylib', 'lib', 'dll', 'exe', 'pdb',
168
162
  'aar', 'jar', 'class', 'dex',
@@ -171,22 +165,18 @@ const NATIVE_ARTIFACT_EXTS = new Set([
171
165
  'xcodeproj', 'xcworkspace',
172
166
  'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z',
173
167
  ])
174
- export function isNativeArtifact(name) {
175
- return NATIVE_ARTIFACT_EXTS.has(pathExt(name))
176
- }
168
+ export const isNativeArtifact = (name) => NATIVE_ARTIFACT_EXTS.has(pathExt(name))
177
169
 
178
- // A binary plist is a real build input, but its bytes can't ride the text-only 'xml' format
179
- // classifyFormat gives a `.plist`. Callers treat it as NOT code, so it needs `.plist` in `resources`.
180
- export function isBinaryPlist(name, content) {
181
- return pathExt(name) === 'plist' && Buffer.isBuffer(content) && !isUtf8(content)
182
- }
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)
183
172
 
184
- // Non-JS code formats by extension. Every value must be in KNOWN_FORMATS.
173
+ // Every value must be in KNOWN_FORMATS.
185
174
  const CODE_EXT_FORMATS = new Map([
186
175
  ['sol', 'solidity'],
187
176
  ['php', 'php'],
188
177
  ['sh', 'shell'], ['bash', 'shell'],
189
178
  ['rs', 'rust'],
179
+ ['teal', 'teal'],
190
180
  ['patch', 'patch'],
191
181
  ['java', 'java'],
192
182
  ['kt', 'kotlin'], ['kts', 'kotlin'],
@@ -209,8 +199,7 @@ const CODE_EXT_FORMATS = new Map([
209
199
  ['pbxproj', 'pbxproj'],
210
200
  ])
211
201
 
212
- // Code formats by exact (lowercased) basename, for names whose extension is too generic to key
213
- // (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).
214
203
  const CODE_NAME_FORMATS = new Map([
215
204
  ['podfile', 'podfile'],
216
205
  ['podfile.lock', 'podfile-lock'],
@@ -222,15 +211,9 @@ const CODE_NAME_FORMATS = new Map([
222
211
  ])
223
212
 
224
213
  const SHELL_SHEBANG = /^#![^\n]*\b(?:bash|sh)\b/u
225
- function isShellShebang(content) {
226
- if (!Buffer.isBuffer(content) || !isUtf8(content)) return false
227
- const head = content.subarray(0, 256).toString('utf8')
228
- const nl = head.indexOf('\n')
229
- return SHELL_SHEBANG.test(nl === -1 ? head : head.slice(0, nl))
230
- }
214
+ const isShellShebang = (content) => Buffer.isBuffer(content) && isUtf8(content) && SHELL_SHEBANG.test(content.subarray(0, 256).toString('utf8'))
231
215
 
232
- // Files a native package ships that are NOT build inputs (docs/legal, editor/lint/CI config, logs,
233
- // 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.
234
217
  const NATIVE_EXCLUDE_EXTS = new Set(['md', 'log', 'map', 'flow', 'swiftdoc'])
235
218
  const NATIVE_EXCLUDE_NAMES = new Set([
236
219
  'license', 'licence', 'third-party-licenses',
@@ -247,42 +230,21 @@ export function isExcludedNativeFile(name, { win32 = process.platform === 'win32
247
230
  return NATIVE_EXCLUDE_EXTS.has(ext) || (!win32 && ext === 'bat')
248
231
  }
249
232
 
250
- // An Apple prebuilt-slice dir (`ios-arm64`, `tvos-arm64_x86_64-simulator`): compiled output, not source,
251
- // 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.
252
234
  const APPLE_ARCH = String.raw`(?:arm64e|arm64_32|arm64|armv7k|armv7s|armv7|x86_64|i386)`
253
- const APPLE_SLICE_DIR = new RegExp(
254
- String.raw`^[a-z0-9]+-${APPLE_ARCH}(?:_${APPLE_ARCH})*(?:-(?:simulator|maccatalyst))?$`,
255
- 'u'
256
- )
257
- export function isAppleSliceDir(name) {
258
- return APPLE_SLICE_DIR.test(name)
259
- }
260
-
261
- // Types only, never a runtime module: the resolvers must refuse to land on one and fall through to the
262
- // real `.js`. Keyed by compound suffix -- pathExt only sees the trailing `ts`.
263
- const TYPE_DECLARATION_SUFFIXES = ['.d.ts', '.d.mts', '.d.cts']
264
- export function isTypeDeclaration(name) {
265
- const base = basename(name).toLowerCase()
266
- return TYPE_DECLARATION_SUFFIXES.some((suffix) => base.endsWith(suffix))
267
- }
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)
268
237
 
269
- export function stripTypeDeclaration(name) {
270
- const lower = name.toLowerCase()
271
- const suffix = TYPE_DECLARATION_SUFFIXES.find((s) => lower.endsWith(s))
272
- return suffix === undefined ? name : name.slice(0, -suffix.length)
273
- }
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())
274
240
 
275
- // stasis's own outputs (`stasis.lock.json`, a `*stasis*.br`): absent on a first run but present on a
276
- // later one, so a listing (`--fs` readdir) or a sweep (`add .`) that records one diverges between runs
277
- // 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.
278
242
  export function isStasisArtifactName(name) {
279
243
  const base = basename(name).toLowerCase()
280
244
  return isLockfileName(base) || (base.includes('stasis') && base.endsWith('.br'))
281
245
  }
282
246
 
283
- // Dirs no walk descends into: VCS/CI/IDE metadata, sample apps, test scaffolding -- none of it is the
284
- // code being shipped -- plus the Apple prebuilt slice dirs. `name` is a BARE dir name (a dirent name
285
- // 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.
286
248
  const AUTO_EXCLUDED_DIRS = new Set([
287
249
  '.git', '.github', '.settings', // VCS / CI / IDE metadata
288
250
  'example', 'examples', // sample apps -- they import the package, they aren't it
@@ -293,17 +255,11 @@ export function isAutoExcludedDir(name) {
293
255
  return AUTO_EXCLUDED_DIRS.has(base) || isAppleSliceDir(base)
294
256
  }
295
257
 
296
- // Files a sweep drops: type declarations (types only, erased at runtime), the `.env` family (secrets),
297
- // stasis's own outputs (they'd attest themselves), and everything the native capture excludes as
298
- // non-build-input noise (docs/legal, editor/lint/CI config, `*.map`/`*.js.flow` sidecars, logs).
299
- // A path can only reach this via a glob -- an EXPLICITLY named one is added as asked (`add .env` still
300
- // captures), which is also the only way to attest a file this set covers.
301
- export function isAutoExcludedFile(name) {
302
- return isTypeDeclaration(name) || isDotEnvFile(name) || isStasisArtifactName(name) || isExcludedNativeFile(name)
303
- }
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)
304
262
 
305
- // The format a file's name alone gives it, whatever its extension (pathExt) would: a `*.podspec.json`
306
- // is `json`, a `*.cmake.in` `cmake`. -> it, or undefined
307
263
  export function nameFormat(name) {
308
264
  const base = basename(name).toLowerCase()
309
265
  if (base === 'package.json' || base.endsWith('.podspec.json')) return 'json'
@@ -311,17 +267,14 @@ export function nameFormat(name) {
311
267
  return CODE_NAME_FORMATS.get(base)
312
268
  }
313
269
 
314
- // The single name->format classifier every capture path is a policy view of. Returns a concrete format
315
- // when the name determines one; null for a JS-family file (.js/.ts/.jsx/.tsx); undefined if unrecognized.
270
+ // A format, null for a JS-family file, undefined if unrecognized.
316
271
  export function classifyFormat(name, { content } = {}) {
317
272
  const byName = nameFormat(name)
318
273
  if (byName !== undefined) return byName
319
274
  const ext = pathExt(name)
320
- if (JS_UNRESOLVED_EXTS.has(ext)) return null
321
- const byExt = NODE_EXT_FORMATS.get(ext) ?? CODE_EXT_FORMATS.get(ext)
322
- if (byExt !== undefined) return byExt
323
- if (ext === '' && isShellShebang(content)) return 'shell'
324
- return undefined
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)
325
278
  }
326
279
 
327
280
  export const extSetsEqual = (a, b) => a.size === b.size && a.isSubsetOf(b)
@@ -330,22 +283,17 @@ export const EXECUTE_BITS = 0o111
330
283
 
331
284
  export const isExecutableMode = (stats) => stats.isFile() && (stats.mode & EXECUTE_BITS) !== 0
332
285
 
333
- // Tri-state: `undefined` means the mode could NOT be observed (gone mid-run, EACCES, ELOOP, a synthetic
334
- // 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".
335
287
  export function observeExecutable(abs, host = diskHost) {
336
288
  const stats = host.stat(abs)
337
289
  return stats === null ? undefined : isExecutableMode(stats)
338
290
  }
339
291
 
340
- // Windows reports no POSIX execute bits, so a capture there records none and must NOT read "no bit" as
341
- // "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.
342
293
  export const canObserveExecuteBits = ({ win32 = process.platform === 'win32' } = {}) => !win32
343
294
 
344
- // Throws on a symlink escaping the bundle root: a crafted `link.sh -> /etc/passwd` must not pull an
345
- // 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.
346
296
  export function assertRealPathWithinBase(realBase, baseDir, relPath, host = diskHost) {
347
297
  const real = host.realpath(join(baseDir, relPath))
348
- if (!isPathWithin(realBase, real)) {
349
- throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
350
- }
298
+ if (!isPathWithin(realBase, real)) throw new Error(`Refusing to follow symlink escaping bundle root: ${relPath} -> ${real}`)
351
299
  }