@exodus/stasis 1.0.0-beta.9 → 1.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +6 -2
  2. package/bin/stasis.js +222 -334
  3. package/package.json +38 -14
  4. package/src/audit-corrections.js +11 -42
  5. package/src/audit.js +256 -212
  6. package/src/babel.js +119 -82
  7. package/src/bundle-from-lockfile.js +9 -21
  8. package/src/bundle-reader.js +24 -8
  9. package/src/bundle.js +0 -3
  10. package/src/cmd/build.js +211 -117
  11. package/src/cmd/bundle-options.js +347 -0
  12. package/src/cmd/bundle.js +1664 -1001
  13. package/src/cmd/diff.js +1 -4
  14. package/src/cmd/github-bundle.js +48 -21
  15. package/src/cmd/output.js +25 -12
  16. package/src/cmd/sbom.js +6 -9
  17. package/src/cmd/tokens.js +60 -0
  18. package/src/define.js +218 -0
  19. package/src/diff.js +73 -129
  20. package/src/esbuild.js +0 -4
  21. package/src/flow.js +27 -0
  22. package/src/installed.js +265 -0
  23. package/src/json-stream.js +4 -9
  24. package/src/loader-mock.js +3 -8
  25. package/src/loader.js +1 -5
  26. package/src/loaders/bash.js +43 -120
  27. package/src/loaders/cargo.js +301 -808
  28. package/src/loaders/foundry.js +112 -290
  29. package/src/loaders/paths.js +15 -26
  30. package/src/loaders/php.js +211 -492
  31. package/src/loaders/rust.js +518 -1461
  32. package/src/loaders/solidity-ownership.js +51 -142
  33. package/src/loaders/solidity.js +42 -188
  34. package/src/loaders/toml.js +7 -17
  35. package/src/lockfile.js +0 -3
  36. package/src/metro-assets.js +41 -0
  37. package/src/metro-resolver.js +58 -133
  38. package/src/metro-transformer.js +0 -6
  39. package/src/metro.js +0 -4
  40. package/src/mock.js +32 -80
  41. package/src/parse.js +8 -7
  42. package/src/prune.js +0 -3
  43. package/src/resolve-fields.js +152 -249
  44. package/src/resolve-node.js +29 -45
  45. package/src/resolve-typescript.js +166 -298
  46. package/src/rollup.js +0 -4
  47. package/src/run-installed.js +10 -0
  48. package/src/sbom.js +70 -97
  49. package/src/scan.js +240 -282
  50. package/src/sixel.js +310 -0
  51. package/src/table.js +95 -0
  52. package/src/validate-notes.d.ts +19 -0
  53. package/src/validate-notes.js +72 -0
  54. package/src/validate.d.ts +159 -0
  55. package/src/validate.js +1315 -0
  56. package/src/vfs-bundle/entries.js +50 -46
  57. package/src/vfs-bundle/github.js +114 -94
  58. package/src/vfs-bundle/glob.js +379 -0
  59. package/src/vfs-bundle/lazy.js +99 -0
  60. package/src/vfs-bundle/prisma.js +235 -105
  61. package/src/vfs-bundle/soldeer.js +28 -49
  62. package/src/vfs-bundle/tree.js +418 -277
  63. package/src/vfs-bundle/yarnclean.js +79 -0
  64. package/src/vfs-bundle.js +24 -55
  65. package/src/webpack.js +0 -4
  66. package/src/why.js +79 -231
  67. package/src/installed-commits.js +0 -182
@@ -1,8 +1,3 @@
1
- // PHP include-graph + Composer-autoload loader. Statically scans PHP (never runs
2
- // it) into `{ sources, resolutions, missing }`. Literal includes are strict
3
- // (unresolved -> `missing`); Composer-autoloaded class refs are best-effort
4
- // (unresolved -> silently skipped).
5
-
6
1
  import { isUtf8 } from 'node:buffer'
7
2
  import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs'
8
3
  import { readFile } from 'node:fs/promises'
@@ -11,18 +6,17 @@ import { isDeepStrictEqual } from 'node:util'
11
6
 
12
7
  import { isValidRepoField } from '@exodus/stasis-core/bundle'
13
8
  import { checkoutCommit, parseGithubRepository } from '@exodus/stasis-core/bundle-util'
14
- import { assertRealPathWithinBase, isPlainObject, relativeEscapes, toPosix } from '@exodus/stasis-core/util'
9
+ import { archiveIntegrity, assertRealPathWithinBase, fileInBucket, isPlainObject, moduleInfo, relativeEscapes, toPosix, upsert } from '@exodus/stasis-core/util'
15
10
  import { LockfileError, parseComposerLock } from '@preventive/lockfile/composer.js'
16
11
  import { isDir, isFile } from '../resolve-typescript.js'
17
- import { applyToDir } from './paths.js'
12
+ import { applyToDir, isDotRelative } from './paths.js'
18
13
  import { readUtf8OrNull } from './solidity-ownership.js'
19
14
  import { nameErrors } from './toml.js'
20
15
 
21
- // Cap concurrent reads per wave to avoid EMFILE on large directory globs.
16
+ // Reads at once: a wave can be huge (a dynamic include's directory), and opening every file at once EMFILE.
22
17
  const READ_CONCURRENCY = 64
23
18
 
24
- // End index (exclusive) of the heredoc/nowdoc opener at `start`, or `start` if
25
- // not a valid opener. Consumes to EOF when unterminated.
19
+ // The end of the heredoc/nowdoc opening at `start`, or `start` where none does; an unterminated one runs to the end.
26
20
  function heredocEnd(code, start) {
27
21
  const n = code.length
28
22
  let j = start + 3
@@ -32,120 +26,91 @@ function heredocEnd(code, start) {
32
26
  while (j < n && /\w/u.test(code[j])) label += code[j++]
33
27
  if (label === '') return start
34
28
  if (quote && code[j] === quote) j++
35
- let p = code.indexOf('\n', j)
36
- if (p === -1) return n
37
- p += 1
38
- while (p <= n) {
39
- let q = p
29
+ for (let nl = code.indexOf('\n', j); nl !== -1; nl = code.indexOf('\n', nl + 1)) {
30
+ let q = nl + 1
40
31
  while (q < n && (code[q] === ' ' || code[q] === '\t')) q++
41
- if (code.startsWith(label, q)) {
42
- const after = code[q + label.length]
43
- if (after === undefined || !/\w/u.test(after)) {
44
- const nl = code.indexOf('\n', q)
45
- return nl === -1 ? n : nl
46
- }
32
+ if (code.startsWith(label, q) && !/\w/u.test(code[q + label.length] ?? '')) {
33
+ const end = code.indexOf('\n', q)
34
+ return end === -1 ? n : end
47
35
  }
48
- const nl = code.indexOf('\n', p)
49
- if (nl === -1) return n
50
- p = nl + 1
51
36
  }
52
37
  return n
53
38
  }
54
39
 
55
- // Blank everything that isn't executable PHP (comments, heredocs/nowdocs, and
56
- // unless `keepStrings` string literals) to spaces, preserving newlines so byte
57
- // offsets stay aligned with the input. `#[` (a PHP 8 attribute) is left intact.
40
+ // Comments, heredocs/nowdocs and (unless `keepStrings`) string literals blanked, newlines kept so offsets stay
41
+ // the input's. `#[` (a PHP 8 attribute) is code.
58
42
  function maskNonCode(code, keepStrings) {
59
43
  const n = code.length
60
- const blank = (s) => s.replace(/[^\n]/gu, ' ')
61
44
  let out = ''
62
45
  let i = 0
63
46
  while (i < n) {
64
47
  const c = code[i]
48
+ let end = i + 1
49
+ let masked = true
65
50
  if ((c === '/' && code[i + 1] === '/') || (c === '#' && code[i + 1] !== '[')) {
66
- let end = code.indexOf('\n', i)
51
+ end = code.indexOf('\n', i)
67
52
  if (end === -1) end = n
68
- out += blank(code.slice(i, end))
69
- i = end
70
53
  } else if (c === '/' && code[i + 1] === '*') {
71
54
  const close = code.indexOf('*/', i + 2)
72
- const end = close === -1 ? n : close + 2
73
- out += blank(code.slice(i, end))
74
- i = end
55
+ end = close === -1 ? n : close + 2
75
56
  } else if (c === '<' && code[i + 1] === '<' && code[i + 2] === '<') {
76
- const end = heredocEnd(code, i)
77
- if (end === i) { out += c; i++ } else { out += blank(code.slice(i, end)); i = end }
57
+ end = Math.max(heredocEnd(code, i), i + 1)
58
+ masked = end > i + 1
78
59
  } else if (c === "'" || c === '"') {
79
- let j = i + 1
80
- while (j < n) {
81
- if (code[j] === '\\') { j += 2; continue }
82
- if (code[j] === c) { j++; break }
83
- j++
60
+ while (end < n) {
61
+ if (code[end] === '\\') { end += 2; continue }
62
+ if (code[end++] === c) break
84
63
  }
85
- out += keepStrings ? code.slice(i, j) : blank(code.slice(i, j))
86
- i = j
87
- } else {
88
- out += c
89
- i++
90
- }
64
+ masked = !keepStrings
65
+ } else masked = false
66
+ out += masked ? code.slice(i, end).replace(/[^\n]/gu, ' ') : code.slice(i, end)
67
+ i = end
91
68
  }
92
69
  return out
93
70
  }
94
71
 
95
- // Blank comments/heredocs, keep string literals (include paths live in strings).
96
- function maskCommentsAndHeredocs(content) {
97
- return maskNonCode(content, true)
72
+ // String literals kept, as include paths live in them.
73
+ function maskedPhp(content) {
74
+ const code = maskNonCode(content, true)
75
+ return { code, strings: stringLiterals(code) }
98
76
  }
99
77
 
100
- // Scan string literals -> { start, end, value, quote } with PHP single-quote
101
- // unescaping (only `\\` and the closing quote are escapes; other backslashes
102
- // literal -- good enough for path values).
78
+ // Only `\\` and the closing quote unescaped, as PHP's single quotes do: good enough for path values.
103
79
  function stringLiterals(code) {
104
80
  const out = []
105
81
  let i = 0
106
82
  while (i < code.length) {
107
83
  const q = code[i]
108
- if (q === "'" || q === '"') {
109
- let j = i + 1
110
- let value = ''
111
- while (j < code.length) {
112
- const c = code[j]
113
- if (c === '\\') {
114
- const next = code[j + 1]
115
- value += next === '\\' || next === q ? next : c + (next ?? '')
116
- j += next === undefined ? 1 : 2
117
- continue
118
- }
119
- if (c === q) { j++; break }
120
- value += c
121
- j++
84
+ if (q !== "'" && q !== '"') { i++; continue }
85
+ let j = i + 1
86
+ let value = ''
87
+ while (j < code.length) {
88
+ const c = code[j]
89
+ if (c === '\\') {
90
+ const next = code[j + 1]
91
+ value += next === '\\' || next === q ? next : c + (next ?? '')
92
+ j += next === undefined ? 1 : 2
93
+ continue
122
94
  }
123
- out.push({ start: i, end: j, value, quote: q })
124
- i = j
125
- } else {
126
- i++
95
+ if (c === q) { j++; break }
96
+ value += c
97
+ j++
127
98
  }
99
+ out.push({ start: i, end: j, value, quote: q })
100
+ i = j
128
101
  }
129
102
  return out
130
103
  }
131
104
 
132
- // Whether `pos` is inside one of `strings` (stringLiterals), and the literal starting at `pos`.
133
105
  const inString = (strings, pos) => strings.some(({ start, end }) => pos > start && pos < end)
134
106
  const stringAt = (strings, pos) => strings.find(({ start }) => start === pos)
135
107
 
136
- // Include keyword. The lookbehind rejects method/scope-resolution calls
137
- // (`$x->require`, `Foo::include`); the trailing `\b` stops matching inside
138
- // `requireConfig`. String-literal matches are filtered out by the caller.
108
+ // The lookbehind rejects `$x->require` and `Foo::include`, the `\b` `requireConfig`.
139
109
  const PHP_INCLUDE_KEYWORD_RE = /(?<![\w$>:])(?:require_once|require|include_once|include)\b/gidu
140
-
141
- // Directory anchor (sticky): `__DIR__`/`dirname(__FILE__)` (file's own dir) or
142
- // `dirname(__DIR__[, N])` (N parent levels up).
143
110
  const PHP_DIR_ANCHOR_RE = /__DIR__\b|dirname\s*\(\s*(__FILE__|__DIR__)\s*(?:,\s*(\d+)\s*)?\)/y
144
- // Anchor starts, for scanning path literals anywhere (not just after `require`).
145
111
  const PHP_DIR_ANCHOR_FIND_RE = /(?<![\w$>])(?:__DIR__\b|dirname\s*\(\s*(?:__FILE__|__DIR__))/gu
146
112
 
147
- // Laravel path helpers resolving a string arg relative to the project root (or a
148
- // fixed subdirectory); they name real PHP files the framework require()s.
113
+ // Laravel's helpers taking a path from the project root (or a directory of it): they name PHP files it require()s.
149
114
  const PHP_PATH_HELPERS = new Map([
150
115
  ['base_path', ''],
151
116
  ['app_path', 'app'],
@@ -156,11 +121,9 @@ const PHP_PATH_HELPERS = new Map([
156
121
  ['resource_path', 'resources'],
157
122
  ['storage_path', 'storage'],
158
123
  ])
159
- const PHP_PATH_HELPER_FIND_RE =
160
- /(?<![\w$>:])(base_path|app_path|config_path|database_path|lang_path|public_path|resource_path|storage_path)\s*\(/giu
124
+ const PHP_PATH_HELPER_FIND_RE = new RegExp(String.raw`(?<![\w$>:])(${[...PHP_PATH_HELPERS.keys()].join('|')})\s*\(`, 'giu')
161
125
 
162
- // Interpolation markers inside a double-quoted string (`$var`, `${...}`,
163
- // `{$...}`). Single-quoted strings never interpolate, so a `$` there is literal.
126
+ // A double-quoted string's interpolation; a single-quoted one's `$` is literal.
164
127
  const PHP_INTERPOLATION_RE = /\$[A-Za-z_{]|\{\$/u
165
128
 
166
129
  function skipWs(code, pos) {
@@ -168,32 +131,20 @@ function skipWs(code, pos) {
168
131
  return pos
169
132
  }
170
133
 
171
- // If a directory anchor starts at `pos`, return { end, up } (up = parent levels
172
- // above the file's dir; 0 for `__DIR__`/`dirname(__FILE__)`); else null.
173
134
  function matchDirAnchor(code, pos) {
174
135
  PHP_DIR_ANCHOR_RE.lastIndex = pos
175
136
  const m = PHP_DIR_ANCHOR_RE.exec(code)
176
137
  if (!m) return null
177
- const up = m[1] === '__DIR__' ? (m[2] ? Number(m[2]) : 1) : 0
178
- return { end: PHP_DIR_ANCHOR_RE.lastIndex, up }
138
+ return { end: PHP_DIR_ANCHOR_RE.lastIndex, up: m[1] === '__DIR__' ? (m[2] ? Number(m[2]) : 1) : 0 }
179
139
  }
180
140
 
181
- // A `./`/`../` specifier, as PHP tells one (a `.`-led NAME like `..cache/a.php` is a bare one).
182
- const isDotRelative = (spec) => spec === '.' || spec === '..' || spec.startsWith('./') || spec.startsWith('../')
183
-
184
- // Normalise an include path to a specifier. Dir-relative paths get a `./` prefix
185
- // with the leading separator stripped; empty means the file's own dir (`.`).
186
141
  function normalizeIncludePath(raw, dirRelative) {
187
142
  if (!dirRelative) return raw
188
143
  const rel = raw.replace(/^\/+/u, '')
189
- if (rel === '') return '.'
190
- return isDotRelative(rel) ? rel : `./${rel}`
144
+ return rel === '' ? '.' : isDotRelative(rel) ? rel : `./${rel}`
191
145
  }
192
146
 
193
- // Parse an include/path argument at `start`: an optional directory anchor then a
194
- // concatenation chain of string literals (static literals fold together). Goes
195
- // `dynamic` at the first variable/function/constant/interpolation; `prefix` is
196
- // the static path up to there. Returns null with neither anchor nor static string.
147
+ // Null with neither a directory anchor nor a literal; `dynamic` from the first variable, call or interpolation.
197
148
  function parseArgPath(code, start, strings) {
198
149
  let i = start
199
150
  let dirRelative = false
@@ -206,32 +157,22 @@ function parseArgPath(code, start, strings) {
206
157
  if (code[i] !== '.') return null
207
158
  i = skipWs(code, i + 1)
208
159
  }
209
-
160
+ if (!dirRelative && !stringAt(strings, i)) return null
210
161
  let prefix = '/..'.repeat(up)
211
- let dynamic = false
212
- let sawStatic = false
213
162
  for (;;) {
214
163
  const lit = stringAt(strings, i)
215
- if (!lit) { dynamic = true; break }
164
+ if (!lit) return { dirRelative, up, prefix, dynamic: true }
216
165
  const interp = lit.quote === '"' ? lit.value.search(PHP_INTERPOLATION_RE) : -1
217
- if (interp >= 0) { prefix += lit.value.slice(0, interp); sawStatic = true; dynamic = true; break }
166
+ if (interp >= 0) return { dirRelative, up, prefix: prefix + lit.value.slice(0, interp), dynamic: true }
218
167
  prefix += lit.value
219
- sawStatic = true
220
168
  i = skipWs(code, lit.end)
221
- if (code[i] === '.') { i = skipWs(code, i + 1); continue }
222
- break
169
+ if (code[i] !== '.') return { dirRelative, up, prefix, dynamic: false }
170
+ i = skipWs(code, i + 1)
223
171
  }
224
- if (!dirRelative && !sawStatic) return null
225
- return { dirRelative, up, prefix, dynamic, sawStatic }
226
172
  }
227
173
 
228
- // Scan `require`/`include` statements, classifying each as a concrete `file` or
229
- // -- when the path is dynamic but has a static directory prefix -- a `dir` whose
230
- // `.php` files are all bundled (any could be the runtime target).
231
- function scanIncludes(content) {
232
- const code = maskCommentsAndHeredocs(content)
233
- const strings = stringLiterals(code)
234
-
174
+ // A dynamic include's static directory prefix (`dir`): any `.php` file in it may be its target at runtime.
175
+ function scanIncludes({ code, strings }) {
235
176
  const out = []
236
177
  for (const m of code.matchAll(PHP_INCLUDE_KEYWORD_RE)) {
237
178
  if (inString(strings, m.index)) continue
@@ -239,39 +180,27 @@ function scanIncludes(content) {
239
180
  if (code[i] === '(') i = skipWs(code, i + 1)
240
181
  const arg = parseArgPath(code, i, strings)
241
182
  if (!arg) continue
242
- const { dirRelative, up, prefix, dynamic, sawStatic } = arg
243
-
244
- if (!dynamic) {
245
- if (sawStatic) out.push({ kind: 'file', spec: normalizeIncludePath(prefix, dirRelative) })
246
- continue
183
+ const { dirRelative, up, prefix, dynamic } = arg
184
+ if (!dynamic) out.push({ kind: 'file', spec: normalizeIncludePath(prefix, dirRelative) })
185
+ else if (dirRelative || prefix.includes('/')) {
186
+ let dir = prefix.includes('/') ? prefix.slice(0, prefix.lastIndexOf('/')) : ''
187
+ if (dir === '' && up > 0) dir = '/..'.repeat(up)
188
+ out.push({ kind: 'dir', spec: normalizeIncludePath(dir, dirRelative) })
247
189
  }
248
- // Dynamic path: fall back to the static dir prefix; a bare path with no separator has none.
249
- if (!dirRelative && !prefix.includes('/')) continue
250
- const lastSlash = prefix.lastIndexOf('/')
251
- let dir = lastSlash >= 0 ? prefix.slice(0, lastSlash) : ''
252
- if (dir === '' && up > 0) dir = '/..'.repeat(up)
253
- out.push({ kind: 'dir', spec: normalizeIncludePath(dir, dirRelative) })
254
190
  }
255
191
  return out
256
192
  }
257
193
 
258
- // Dir-anchored static `.php` path literals anywhere in the file (not just after
259
- // `require`) -- frameworks pass these to code that require()s them internally.
260
- // Best-effort: bundled only if they resolve to an existing file.
261
- function scanPathLiterals(content) {
262
- const code = maskCommentsAndHeredocs(content)
263
- const strings = stringLiterals(code)
264
-
194
+ // `.php` path literals outside a `require`, which frameworks require() themselves.
195
+ function scanPathLiterals({ code, strings }) {
265
196
  const out = []
266
- // Dir-anchored literals: `__DIR__ . '/x.php'` (resolve against the file).
267
197
  for (const m of code.matchAll(PHP_DIR_ANCHOR_FIND_RE)) {
268
198
  if (inString(strings, m.index)) continue
269
199
  const arg = parseArgPath(code, m.index, strings)
270
- if (!arg || arg.dynamic || !arg.sawStatic || !arg.dirRelative) continue
200
+ if (!arg || arg.dynamic || !arg.dirRelative) continue
271
201
  const spec = normalizeIncludePath(arg.prefix, true)
272
202
  if (spec.endsWith('.php')) out.push({ spec, anchor: 'file' })
273
203
  }
274
- // Laravel path helpers: `base_path('routes/web.php')` (resolve against project root).
275
204
  for (const m of code.matchAll(PHP_PATH_HELPER_FIND_RE)) {
276
205
  if (inString(strings, m.index)) continue
277
206
  const lit = stringAt(strings, skipWs(code, m.index + m[0].length))
@@ -286,64 +215,44 @@ function scanPathLiterals(content) {
286
215
 
287
216
  const includeSpecs = (includes, kind) => includes.filter((e) => e.kind === kind).map((e) => e.spec)
288
217
 
289
- // Statically-resolvable include specifiers (concrete files). See scanIncludes.
290
- export function extractPhpImports(content) {
291
- return includeSpecs(scanIncludes(content), 'file')
292
- }
293
-
294
- // Directory specifiers for dynamic includes; every `.php` file directly inside is
295
- // a candidate target.
296
- export function extractPhpImportDirs(content) {
297
- return includeSpecs(scanIncludes(content), 'dir')
298
- }
299
-
300
- // `.php` path literals used outside a `require` -- dir-anchored (`anchor: 'file'`)
301
- // or via a Laravel path helper (`anchor: 'root'`). De-duplicated; best-effort.
302
- export function extractPhpPathRefs(content) {
303
- const seen = new Set()
304
- return scanPathLiterals(content).filter(({ spec, anchor }) => {
305
- const key = `${anchor}:${spec}`
306
- if (seen.has(key)) return false
307
- seen.add(key)
308
- return true
309
- })
310
- }
218
+ export const extractPhpImports = (content) => includeSpecs(scanIncludes(maskedPhp(content)), 'file')
219
+ export const extractPhpImportDirs = (content) => includeSpecs(scanIncludes(maskedPhp(content)), 'dir')
220
+ const pathRefs = (masked) => [...new Map(scanPathLiterals(masked).map((ref) => [`${ref.anchor}:${ref.spec}`, ref])).values()]
221
+ export const extractPhpPathRefs = (content) => pathRefs(maskedPhp(content))
311
222
 
312
223
  const isFileOnDisk = (baseDir, rel) => isFile(join(baseDir, rel))
313
- const isDirOnDisk = (baseDir, rel) => isDir(join(baseDir, rel))
314
224
 
315
- // Throws on a path holding `\`: no separator to PHP off Windows but part of a name, and stasis
316
- // refuses such a name rather than resolve it, or take it for another path. `from`: the includer.
225
+ // A `\` is no separator to PHP off Windows but part of a name: stasis refuses such a name rather than resolve
226
+ // it, or take it for another path.
317
227
  function refuseBackslash(path, from) {
318
228
  if (path.includes('\\')) throw new Error(`[loader.php] path holds a '\\', which stasis refuses: ${path}${from ? ` (from ${from})` : ''}`)
319
229
  }
320
230
 
321
- // `abs` as a baseDir-relative POSIX path ('' for baseDir itself), or null when it escapes the root.
322
231
  function projectRel(baseDir, abs) {
323
232
  const rel = toPosix(relative(baseDir, abs))
324
233
  return relativeEscapes(rel) ? null : rel
325
234
  }
326
235
 
327
- // Resolve a directory specifier to an existing baseDir-relative dir, or null.
328
- // `./`/`../` resolve against the including file; a bare spec tries file- then
329
- // project-relative.
330
- export function resolvePhpDir(spec, fromFile, baseDir) {
236
+ // `./`/`../` resolve against the including file (null escaping the root; existence unchecked); a bare one next
237
+ // to the includer, then from the project root, the first that is `present`. Absolute ones are refused.
238
+ function resolvePhpSpec(spec, fromFile, baseDir, present) {
331
239
  refuseBackslash(spec, fromFile)
332
- if (isDotRelative(spec)) {
333
- const rel = applyToDir(fromFile, spec.split('/'))
334
- return rel !== null && isDirOnDisk(baseDir, rel) ? rel : null
335
- }
336
- if (baseDir && !isAbsolute(spec)) {
337
- const fileRel = applyToDir(fromFile, spec.split('/'))
338
- if (fileRel && isDirOnDisk(baseDir, fileRel)) return fileRel
339
- const projRel = projectRel(baseDir, resolve(baseDir, spec))
340
- if (projRel && isDirOnDisk(baseDir, projRel)) return projRel
341
- }
342
- return null
240
+ if (isDotRelative(spec)) return applyToDir(fromFile, spec.split('/'))
241
+ if (!baseDir || isAbsolute(spec)) return null
242
+ const fileRel = applyToDir(fromFile, spec.split('/'))
243
+ if (fileRel && present(fileRel)) return fileRel
244
+ const projRel = projectRel(baseDir, resolve(baseDir, spec))
245
+ return projRel && present(projRel) ? projRel : null
246
+ }
247
+
248
+ // A bare specifier resolvePhpSpec found present already.
249
+ export function resolvePhpDir(spec, fromFile, baseDir) {
250
+ const present = (rel) => isDir(join(baseDir, rel))
251
+ const rel = resolvePhpSpec(spec, fromFile, baseDir, present)
252
+ return rel !== null && (!isDotRelative(spec) || present(rel)) ? rel : null
343
253
  }
344
254
 
345
- // The `.php` files directly in `dir` (baseDir-relative). Non-recursive: recursing
346
- // could pull in an unbounded subtree.
255
+ // Not recursive, which could pull in an unbounded subtree.
347
256
  function listPhpFiles(baseDir, dir) {
348
257
  try {
349
258
  return readdirSync(join(baseDir, dir), { withFileTypes: true })
@@ -354,41 +263,17 @@ function listPhpFiles(baseDir, dir) {
354
263
  }
355
264
  }
356
265
 
357
- // Resolve a PHP include specifier to a baseDir-relative POSIX path. `./`/`../`
358
- // resolve against the including file (escaping the root -> null); a bare specifier
359
- // tries a file next to the includer, then project-root-relative. Absolute
360
- // specifiers are rejected. Returns null when nothing resolves. One holding `\` throws
361
- // (see refuseBackslash).
362
- export function resolvePhpImport(specifier, fromFile, { baseDir } = {}) {
363
- refuseBackslash(specifier, fromFile)
364
- if (isDotRelative(specifier)) {
365
- return applyToDir(fromFile, specifier.split('/'))
366
- }
367
-
368
- if (baseDir && !isAbsolute(specifier)) {
369
- const fileRel = applyToDir(fromFile, specifier.split('/'))
370
- if (fileRel && isFileOnDisk(baseDir, fileRel)) return fileRel
371
-
372
- const projRel = projectRel(baseDir, resolve(baseDir, specifier))
373
- if (projRel && isFileOnDisk(baseDir, projRel)) return projRel
374
- }
375
-
376
- return null
377
- }
266
+ export const resolvePhpImport = (specifier, fromFile, { baseDir } = {}) =>
267
+ resolvePhpSpec(specifier, fromFile, baseDir, (rel) => isFileOnDisk(baseDir, rel))
378
268
 
379
- // Normalise a project-root-relative autoload path to POSIX baseDir-relative, or
380
- // null when it escapes root. Re-derives via resolve() so interior `..` escapes
381
- // (`src/foo/../../../secret.php`) are caught -- a leading-`..`/absolute check
382
- // alone would let files outside the project into the bundle. One holding `\`
383
- // throws (see refuseBackslash).
269
+ // Re-derived via resolve() so an interior `..` escaping the root (`src/foo/../../../secret.php`) is caught,
270
+ // which a leading-`..`/absolute check alone would let in.
384
271
  function normalizeProjectRel(baseDir, p) {
385
272
  refuseBackslash(p)
386
273
  return projectRel(baseDir, resolve(baseDir, p))
387
274
  }
388
275
 
389
- // Evaluate a generated-autoload path expr (`$baseDir . '/src'`, a bare quoted
390
- // string) given the `$baseDir`/`$vendorDir` values. Returns null on anything
391
- // unrecognised (function call, unknown variable) rather than guessing.
276
+ // A generated autoload path (`$baseDir . '/src'`, a quoted string); null for anything else rather than a guess.
392
277
  function evalPathExpr(expr, vars) {
393
278
  const s = expr.trim().replace(/,+$/u, '').trim()
394
279
  let out = ''
@@ -396,8 +281,7 @@ function evalPathExpr(expr, vars) {
396
281
  const re = /\$(\w+)|'((?:\\.|[^'\\])*)'|"((?:\\.|[^"\\])*)"|\.|\s+/gy
397
282
  let m
398
283
  while ((m = re.exec(s)) !== null) {
399
- // A sticky regex resets lastIndex to 0 when exec() returns null, so track how
400
- // far we parsed instead of reading lastIndex after the loop.
284
+ // A sticky regex resets lastIndex to 0 when exec() returns null: how far it parsed is kept here.
401
285
  consumed = re.lastIndex
402
286
  if (m[1] !== undefined) {
403
287
  if (vars[m[1]] === undefined) return null
@@ -412,9 +296,7 @@ function evalPathExpr(expr, vars) {
412
296
  return out
413
297
  }
414
298
 
415
- // Parse a Composer generated `autoload_*.php` map (one entry per line). `multi`
416
- // true -> psr-4/psr-0 (key -> dirs[]); false -> classmap/files (key -> file).
417
- // PHP single-quote escapes in keys are unfolded.
299
+ // A Composer `autoload_*.php` map, one entry a line: `multi`, psr-4/psr-0's (key -> dirs); else a file each.
418
300
  function parseGeneratedMap(content, vars, multi) {
419
301
  const out = new Map()
420
302
  for (const line of content.split('\n')) {
@@ -423,13 +305,7 @@ function parseGeneratedMap(content, vars, multi) {
423
305
  const key = m[1].replace(/\\(['\\])/gu, '$1')
424
306
  if (multi) {
425
307
  const am = m[2].match(/^array\s*\(([\s\S]*)\)$/u)
426
- if (!am) continue
427
- const dirs = []
428
- for (const piece of am[1].split(',')) {
429
- const abs = evalPathExpr(piece, vars)
430
- if (abs) dirs.push(abs)
431
- }
432
- out.set(key, dirs)
308
+ if (am) out.set(key, am[1].split(',').map((piece) => evalPathExpr(piece, vars)).filter(Boolean))
433
309
  } else {
434
310
  const abs = evalPathExpr(m[2], vars)
435
311
  if (abs) out.set(key, abs)
@@ -446,51 +322,40 @@ function readJsonIfExists(file) {
446
322
  }
447
323
  }
448
324
 
449
- // The root composer.json (null when absent or unparsable) and its baseDir-relative vendor dir.
450
325
  function readComposerJson(baseDir) {
451
326
  const composerJson = readJsonIfExists(join(baseDir, 'composer.json'))
452
327
  const vendorDir = normalizeProjectRel(baseDir, composerJson?.config?.['vendor-dir'] ?? 'vendor') ?? 'vendor'
453
328
  return { composerJson, vendorDir }
454
329
  }
455
330
 
456
- // The packages `vendor/composer/installed.json` lists, in the Composer 2 ({ packages }) or
457
- // Composer 1 (flat array) shape.
331
+ // Composer 2's `{ packages }`, or Composer 1's flat array.
458
332
  function readInstalledPackages(baseDir, vendorDir) {
459
333
  const json = readJsonIfExists(join(baseDir, vendorDir, 'composer', 'installed.json'))
460
334
  return Array.isArray(json) ? json : (json?.packages ?? [])
461
335
  }
462
336
 
463
- // JSON `text` with each integer as PHP holds it: one past ±(2^53 − 1) a BigInt, as
464
- // @preventive/lockfile reads one, so two values compare equal only where PHP's do.
337
+ // An integer past ±(2^53 − 1) a BigInt, as @preventive/lockfile reads one, so two values compare equal only
338
+ // where PHP's do.
465
339
  const parseJsonExact = (text) => JSON.parse(text, (key, value, { source }) =>
466
340
  (typeof value === 'number' && !Number.isSafeInteger(value) && /^-?\d+$/u.test(source) ? BigInt(source) : value))
467
341
 
468
- // Where installed.json says Composer installed package `p`, baseDir-relative: its install-path,
469
- // from vendor/composer (null for none, as of a metapackage), or <vendor-dir>/<name> where it gives
470
- // none (Composer 1's); null outside baseDir.
342
+ // installed.json's install-path is from vendor/composer, null for a metapackage; Composer 1's gives none.
471
343
  function installedDir(baseDir, vendorDir, p) {
472
344
  const path = p['install-path']
473
345
  if (path === undefined) return projectRel(baseDir, resolve(baseDir, vendorDir, p.name))
474
346
  return typeof path === 'string' ? projectRel(baseDir, resolve(baseDir, vendorDir, 'composer', path)) : null
475
347
  }
476
348
 
477
- // Where Composer's library installer puts a package of the lockfile, baseDir-relative
478
- // (LibraryInstaller::getInstallPath): <vendor-dir>/<name>, under its target-dir where it has one; a
479
- // metapackage nowhere (null). One of a type an installer plugin takes (composer/installers') goes
480
- // elsewhere, where its own composer.json's name finds it.
481
- function lockedDir(baseDir, vendorDir, p) {
482
- return p.type === 'metapackage' ? null : projectRel(baseDir, resolve(baseDir, vendorDir, p.name, p.targetDir ?? ''))
483
- }
349
+ // As LibraryInstaller::getInstallPath puts a package; one an installer plugin takes goes elsewhere, where its
350
+ // own composer.json's name finds it.
351
+ const lockedDir = (baseDir, vendorDir, p) =>
352
+ (p.type === 'metapackage' ? null : projectRel(baseDir, resolve(baseDir, vendorDir, p.name, p.targetDir ?? '')))
484
353
 
485
- // What Composer adds to a package of the lockfile as it installs it, in installed.json.
354
+ // What Composer adds to a locked package in installed.json as it installs it.
486
355
  const INSTALL_FIELDS = new Set(['version_normalized', 'installation-source', 'install-path'])
487
356
 
488
- // That vendor/composer/installed.json (`installedText`, at `installedFile`) is the install of
489
- // composer.lock (`lockText`, read by @preventive/lockfile already): as Composer 2 writes it,
490
- // `{ packages, dev, dev-package-names }`; each package of the lockfile's `packages`, and of its
491
- // `packages-dev` where it was installed with dev, there once and exactly as locked but for
492
- // INSTALL_FIELDS, and nothing else; and the names of those of `packages-dev`, in lowercase and
493
- // sorted, as dev-package-names. Throws where not. Returns the installed.json.
357
+ // Throws unless installed.json is, as Composer 2 writes it, the install of composer.lock: each locked package
358
+ // (packages-dev too, installed with dev) there once, as locked but for INSTALL_FIELDS, and nothing else.
494
359
  function assertInstalledAsLocked(lockText, installedText, { installedFile, vendorDir }) {
495
360
  const differ = (detail) => new Error(`${installedFile} is not the install of composer.lock: ${detail}${vendorDir ? `; remove ${vendorDir} and run \`composer install\`` : ''}`)
496
361
  let installed
@@ -522,8 +387,7 @@ function assertInstalledAsLocked(lockText, installedText, { installedFile, vendo
522
387
  const spec = Object.fromEntries(Object.entries(entry).filter(([key]) => !INSTALL_FIELDS.has(key)))
523
388
  const key = [...new Set([...Object.keys(spec), ...Object.keys(want.spec)])].find((k) => !isDeepStrictEqual(spec[k], want.spec[k]))
524
389
  if (key === 'version' && typeof spec.version === 'string') throw differ(`${name} is installed at ${JSON.stringify(spec.version)}, and locked at ${want.spec.version}`)
525
- // `composer install` takes a package installed at the version and reference locked as it is,
526
- // whatever else of it the lockfile changes.
390
+ // `composer install` takes a package at the version and reference locked as it is, whatever else changed.
527
391
  if (key !== undefined) throw differ(`${name}'s ${JSON.stringify(key)} is not as locked`)
528
392
  }
529
393
  for (const [name, { dev }] of locked) {
@@ -534,40 +398,32 @@ function assertInstalledAsLocked(lockText, installedText, { installedFile, vendo
534
398
  return installed
535
399
  }
536
400
 
537
- // The GitHub repository a Composer package `p` (composer.lock's, or installed.json's) is cloned
538
- // from, at the commit it is installed at: its git `source` on GitHub, at its `reference` where that
539
- // is a full commit and what is installed at `at` (its directory, or null for none) is at it.
540
- // Installed from its source -- as installed.json's `installation-source`, `from`, says, or as it
541
- // must be with no dist, or as a git checkout there shows -- it is a clone Composer checked out at
542
- // the reference, which may have been moved since: so only where that checkout's HEAD is it. Else
543
- // from its dist, which Composer installs by default: only one at the same reference, as one with
544
- // none, or another, is an archive no commit is known of. Packagist takes a package from the root
545
- // of its repository, so `directory` is ''. Undefined otherwise.
546
- function composerRepo({ source, dist }, from, at) {
401
+ // Its git `source`'s `reference`, where a clone's checkout HEAD (installed from source) or its dist's reference
402
+ // is that commit; `directory` '', as Packagist takes a package from its repository's root.
403
+ function composerRepo({ source, dist }, fromSource, at) {
547
404
  if (source?.type !== 'git') return undefined
548
- const fromSource = from === 'source' || dist == null || (at !== null && existsSync(join(at, '.git')))
549
405
  if (fromSource ? at === null || checkoutCommit(at) !== source.reference : dist.reference !== source.reference) return undefined
550
406
  const github = parseGithubRepository(source.url)
551
407
  return github !== null && isValidRepoField('commit', source.reference) ? { github, directory: '', commit: source.reference } : undefined
552
408
  }
553
409
 
554
- // The Composer packages of the project at `baseDir`, `[{ name, version, dir, extra, repo }]`, `dir` where
555
- // the package is installed, baseDir-relative (null for nowhere in baseDir, as a metapackage). Of
556
- // its composer.lock where there is one, read by @preventive/lockfile beside composer.json as
557
- // `composer install` reads them -- one it refuses stops the build -- each package where Composer
558
- // installs it (lockedDir), so no install is needed; else of vendor/composer/installed.json, as
559
- // it is. Where both are, installed.json must be the lockfile's install (assertInstalledAsLocked):
560
- // its packages, each where installed.json says. `repo` is composerRepo's.
410
+ // As installed.json's `installation-source` says, as it must with no dist, or as a git checkout at `at` shows.
411
+ const installedFromSource = ({ dist }, from, at) => from === 'source' || dist == null || (at !== null && existsSync(join(at, '.git')))
412
+
413
+ function composerInstall(p, from, at) {
414
+ const fromSource = installedFromSource(p, from, at)
415
+ return { repo: composerRepo(p, fromSource, at), integrity: fromSource ? undefined : archiveIntegrity('composer', p.dist.shasum) }
416
+ }
417
+
418
+ // Of composer.lock, each where Composer installs it, or where installed.json, which must be its install, says.
561
419
  export function loadComposerPackages(baseDir) {
562
420
  const { vendorDir } = readComposerJson(baseDir)
421
+ const packageAt = (p, dir, from) => ({ name: p.name, version: p.version, dir, extra: p.extra, ...composerInstall(p, from, dir == null ? null : join(baseDir, dir)) })
563
422
  const lockText = readUtf8OrNull(join(baseDir, 'composer.lock'), 'composer.lock')
564
423
  if (lockText === null) {
565
424
  return readInstalledPackages(baseDir, vendorDir)
566
425
  .filter((p) => p?.name && p.version)
567
- .map((p) => {
568
- const dir = installedDir(baseDir, vendorDir, p)
569
- return { name: p.name, version: p.version, dir, extra: p.extra, repo: composerRepo(p, p['installation-source'], dir == null ? null : join(baseDir, dir)) }
570
- })
426
+ .map((p) => packageAt(p, installedDir(baseDir, vendorDir, p), p['installation-source']))
571
427
  }
572
428
 
573
429
  const composerJson = readUtf8OrNull(join(baseDir, 'composer.json'), 'composer.json')
@@ -579,16 +435,10 @@ export function loadComposerPackages(baseDir) {
579
435
  const from = new Map(installed?.packages.map((p) => [p.name, p['installation-source']]))
580
436
  return Object.values(lock.packages)
581
437
  .filter((p) => dirs === null || dirs.has(p.name))
582
- .map((p) => {
583
- const dir = dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name)
584
- return { name: p.name, version: p.version, dir, extra: p.extra, repo: composerRepo(p, from.get(p.name), dir == null ? null : join(baseDir, dir)) }
585
- })
438
+ .map((p) => packageAt(p, dirs === null ? lockedDir(baseDir, vendorDir, p) : dirs.get(p.name), from.get(p.name)))
586
439
  }
587
440
 
588
- // Build the autoload config for `baseDir`, merging the root composer.json
589
- // `autoload`(+dev) with the generated `vendor/composer/autoload_*` maps. All
590
- // paths normalised to POSIX baseDir-relative (escapers dropped). Returns
591
- // `{ psr4, psr0, classmap, files }`, or null when no Composer config is found.
441
+ // Null where there is no Composer config.
592
442
  export function loadComposerAutoload(baseDir) {
593
443
  const { composerJson, vendorDir } = readComposerJson(baseDir)
594
444
 
@@ -599,17 +449,10 @@ export function loadComposerAutoload(baseDir) {
599
449
  let found = false
600
450
 
601
451
  const mergeDirs = (map, prefix, dirs) => map.set(prefix, [...new Set([...(map.get(prefix) ?? []), ...dirs])])
602
- const addPrefixDirs = (map, prefix, paths) => {
603
- const list = Array.isArray(paths) ? paths : [paths]
604
- const dirs = []
605
- for (const p of list) {
606
- const rel = normalizeProjectRel(baseDir, String(p))
607
- if (rel !== null) dirs.push(rel)
608
- }
609
- mergeDirs(map, prefix, dirs)
610
- }
452
+ const addPrefixDirs = (map, prefix, paths) =>
453
+ mergeDirs(map, prefix, [paths].flat().map((p) => normalizeProjectRel(baseDir, String(p))).filter((rel) => rel !== null))
611
454
 
612
- // Root composer.json autoload (+ dev). PSR-4 keys keep their trailing '\'.
455
+ // PSR-4 keys keep their trailing '\'.
613
456
  for (const block of [composerJson?.autoload, composerJson?.['autoload-dev']]) {
614
457
  if (!block || typeof block !== 'object') continue
615
458
  found = true
@@ -621,11 +464,9 @@ export function loadComposerAutoload(baseDir) {
621
464
  }
622
465
  }
623
466
 
624
- // Generated maps. `$vendorDir` = <baseDir>/<vendorDir>, `$baseDir` = <baseDir>.
625
467
  const composerGenDir = join(baseDir, vendorDir, 'composer')
626
468
  const vars = { baseDir: resolve(baseDir), vendorDir: resolve(baseDir, vendorDir) }
627
469
  const toRel = (abs) => projectRel(baseDir, abs) || null
628
- // A generated map's entries; none when the file is absent.
629
470
  const generated = (name, multi) => {
630
471
  const file = join(composerGenDir, name)
631
472
  if (!existsSync(file)) return new Map()
@@ -650,105 +491,63 @@ export function loadComposerAutoload(baseDir) {
650
491
  return { psr4, psr0, classmap, files: [...files] }
651
492
  }
652
493
 
653
- // Resolve a FQCN to a baseDir-relative file via the autoload config, mirroring
654
- // Composer's lookup order: classmap, then longest PSR-4 prefix, then PSR-0. Only
655
- // returns a path that exists on disk (an absent prefix match isn't bundled as a hole).
494
+ // As Composer looks a class up: its classmap, then each matching PSR-4 prefix longest first (falling back from
495
+ // one whose file is absent, to the `""` prefix), then PSR-0's. Only a file on disk, as an absent one is no hole.
656
496
  export function resolveClassFile(fqcn, autoload, baseDir) {
657
497
  if (!autoload || !fqcn) return null
658
498
  const name = fqcn.replace(/^\\+/u, '')
659
499
  if (!name) return null
660
-
661
- const exact = autoload.classmap.get(name)
662
- if (exact && isFileOnDisk(baseDir, exact)) return exact
663
-
664
- // PSR-4: try every matching prefix longest-first (Composer falls back from a
665
- // longer prefix whose file is absent to a shorter one, incl. the `""` prefix).
666
- for (const [prefix, dirs] of matchingPrefixes(autoload.psr4, name)) {
667
- const sub = name.slice(prefix.length).replace(/\\/gu, '/')
668
- for (const dir of dirs) {
669
- const file = dir ? `${dir}/${sub}.php` : `${sub}.php`
670
- if (isFileOnDisk(baseDir, file)) return file
671
- }
672
- }
673
-
674
- // PSR-0: namespace separators AND underscores in the class name map to
675
- // directory separators; the namespace prefix is kept under the mapped dir.
676
- for (const [, dirs] of matchingPrefixes(autoload.psr0, name)) {
677
- const lastNs = name.lastIndexOf('\\')
678
- const nsPart = lastNs === -1 ? '' : name.slice(0, lastNs).replace(/\\/gu, '/')
679
- const clsPart = (lastNs === -1 ? name : name.slice(lastNs + 1)).replace(/_/gu, '/')
680
- const sub = `${nsPart ? `${nsPart}/` : ''}${clsPart}.php`
681
- for (const dir of dirs) {
682
- const file = dir ? `${dir}/${sub}` : sub
683
- if (isFileOnDisk(baseDir, file)) return file
684
- }
685
- }
686
-
687
- return null
688
- }
689
-
690
- // [prefix, dirs] entries whose prefix is a prefix of `name`, longest first --
691
- // prefer the most specific mapping, fall back to shorter (and the `""` fallback).
692
- function matchingPrefixes(map, name) {
693
- return [...map].filter(([prefix]) => name.startsWith(prefix)).toSorted((a, b) => b[0].length - a[0].length)
694
- }
695
-
696
- // The versions and repos of the Composer `packages` (loadComposerPackages: the authoritative source;
697
- // a package's own composer.json usually omits `version`), by where each is installed and by name.
500
+ const within = (dir, sub) => (dir ? `${dir}/${sub}` : sub)
501
+ // PSR-0 maps the class name's underscores to directories too, its namespace kept under the prefix's.
502
+ const ns = name.lastIndexOf('\\') + 1
503
+ const psr0 = `${name.slice(0, ns).replace(/\\/gu, '/')}${name.slice(ns).replace(/_/gu, '/')}.php`
504
+ const psr4 = (prefix) => `${name.slice(prefix.length).replace(/\\/gu, '/')}.php`
505
+ const candidates = [
506
+ ...[autoload.classmap.get(name)].filter(Boolean),
507
+ ...matchingPrefixes(autoload.psr4, name).flatMap(([prefix, dirs]) => dirs.map((dir) => within(dir, psr4(prefix)))),
508
+ ...matchingPrefixes(autoload.psr0, name).flatMap(([, dirs]) => dirs.map((dir) => within(dir, psr0))),
509
+ ]
510
+ return candidates.find((file) => isFileOnDisk(baseDir, file)) ?? null
511
+ }
512
+
513
+ const matchingPrefixes = (map, name) => [...map].filter(([prefix]) => name.startsWith(prefix)).toSorted((a, b) => b[0].length - a[0].length)
514
+
515
+ // From loadComposerPackages, as a package's own composer.json usually omits its `version`.
698
516
  function packageVersions(packages) {
699
517
  const byDir = new Map()
700
518
  const byName = new Map()
701
- for (const { name, version, dir, repo } of packages) {
702
- byName.set(name, { version, repo })
703
- if (dir) byDir.set(dir, { version, repo })
519
+ for (const { name, version, dir, repo, integrity } of packages) {
520
+ const known = { version, repo, integrity }
521
+ byName.set(name, known)
522
+ if (dir) byDir.set(dir, known)
704
523
  }
705
524
  return { byDir, byName }
706
525
  }
707
526
 
708
- // Walk up from a bundled file to the nearest named composer.json, returning
709
- // { pkgDir, name, version, repo } (pkgDir "." for the root; version and repo from composer.lock or
710
- // installed.json by dir/name, else composer.json `version`, else `fallbackVersion`). Null if none.
711
527
  function findComposerPackage(baseDir, fileRelPath, installed, fallbackVersion) {
712
- let dir = dirname(fileRelPath)
713
- for (;;) {
528
+ for (let dir = dirname(fileRelPath); ; dir = dirname(dir)) {
714
529
  const cj = readJsonIfExists(join(baseDir, dir, 'composer.json'))
715
530
  if (cj?.name) {
716
531
  const known = installed.byDir.get(dir) ?? installed.byName.get(cj.name)
717
- return { pkgDir: dir, name: cj.name, version: known?.version ?? cj.version ?? fallbackVersion, repo: known?.repo }
532
+ return { pkgDir: dir, name: cj.name, version: known?.version ?? cj.version ?? fallbackVersion, repo: known?.repo, integrity: known?.integrity }
718
533
  }
719
- if (dir === '.' || dir === '/' || dir === '') return null
720
- const parent = dirname(dir)
721
- if (parent === dir) return null
722
- dir = parent
534
+ if (dirname(dir) === dir) return null
723
535
  }
724
536
  }
725
537
 
726
- // Group bundled PHP sources into per-package buckets keyed by the nearest
727
- // composer.json's directory (vendor deps get their own; workspace files and
728
- // orphans -> the root "." bucket with the placeholder identity). Returns a
729
- // Map<dir, { name, version, ecosystem?, repo?, files }>, a dependency's `repo` where composerRepo
730
- // gives one. `packages`: loadComposerPackages(baseDir).
538
+ // By the nearest composer.json's directory; workspace files and orphans in the root "." bucket, the placeholder's.
731
539
  export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVersion, packages = loadComposerPackages(baseDir)) {
732
540
  const installed = packageVersions(packages)
733
-
734
541
  const modules = new Map()
735
- const ensureBucket = (dir, name, version, ecosystem, repo) => {
736
- if (!modules.has(dir)) {
737
- modules.set(dir, ecosystem === undefined
738
- ? { name, version, files: Object.create(null) }
739
- : { name, version, ecosystem, ...(repo === undefined ? {} : { repo }), files: Object.create(null) })
740
- }
741
- return modules.get(dir)
742
- }
542
+ const ensureBucket = (dir, name, version, ecosystem, { repo, integrity } = {}) =>
543
+ upsert(modules, dir, () => moduleInfo({ name, version, ecosystem, ...(ecosystem !== undefined && { integrity, repo }), files: Object.create(null) }))
743
544
 
744
545
  for (const [path, content] of sources) {
745
546
  const pkg = findComposerPackage(baseDir, path, installed, fallbackVersion)
746
547
  if (pkg) {
747
- const rel = pkg.pkgDir === '.' ? path : path.slice(pkg.pkgDir.length + 1)
748
- // Below the root package = an installed Composer dependency, tagged
749
- // `composer`; the root "." bucket is workspace code and stays ecosystem-less.
548
+ // The root package is workspace code; one below it an installed dependency.
750
549
  const ecosystem = pkg.pkgDir === '.' ? undefined : 'composer'
751
- ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem, pkg.repo).files[rel] = content
550
+ ensureBucket(pkg.pkgDir, pkg.name, pkg.version, ecosystem, pkg).files[fileInBucket(pkg.pkgDir, path)] = content
752
551
  } else {
753
552
  ensureBucket('.', fallbackName, fallbackVersion).files[path] = content
754
553
  }
@@ -756,11 +555,8 @@ export function bucketizePhpSources(baseDir, sources, fallbackName, fallbackVers
756
555
  return modules
757
556
  }
758
557
 
759
- // Laravel auto-registers service providers nothing references statically. Returns
760
- // discoverable provider files (from composer.json + the Composer `packages`'
761
- // `extra.laravel.providers`, autoload-resolved) plus bootstrap/providers.php as
762
- // extra collection roots. Best-effort: unresolvable classes skipped.
763
- // `packages`: loadComposerPackages(baseDir).
558
+ // Laravel registers service providers nothing references statically: composer.json's and the `packages`'
559
+ // `extra.laravel.providers`, and bootstrap/providers.php, are roots of their own.
764
560
  export function loadLaravelProviderFiles(baseDir, autoload, packages = loadComposerPackages(baseDir)) {
765
561
  const files = new Set()
766
562
  if (existsSync(join(baseDir, 'bootstrap', 'providers.php'))) files.add('bootstrap/providers.php')
@@ -778,9 +574,7 @@ export function loadLaravelProviderFiles(baseDir, autoload, packages = loadCompo
778
574
  return [...files]
779
575
  }
780
576
 
781
- // Names excluded from class-reference scanning: pseudo-types, scalar/special
782
- // types, and keywords that can sit before `$var`/`::` or after `new` and would
783
- // otherwise be mistaken for a class reference (`return $x`, `new class`, …).
577
+ // Names that can sit where a class reference does (`return $x`, `new class`, …) and are none.
784
578
  const RESERVED = new Set([
785
579
  'self', 'static', 'parent', 'this',
786
580
  'int', 'integer', 'float', 'double', 'string', 'bool', 'boolean', 'void',
@@ -791,15 +585,7 @@ const RESERVED = new Set([
791
585
  'endif', 'endswitch', 'endwhile', 'endfor',
792
586
  ])
793
587
 
794
- // Blank heredocs, comments AND string literals (unlike maskCommentsAndHeredocs,
795
- // which keeps strings) so class-reference scans don't trip over text inside them.
796
- function stripPhp(content) {
797
- return maskNonCode(content, false)
798
- }
799
-
800
- // Add the FQCN for a class reference `raw` given namespace `ns` and the `use`-alias
801
- // map, mirroring PHP name resolution: leading `\` = fully-qualified; a first
802
- // segment matching an alias expands through it; else relative to `ns`.
588
+ // As PHP resolves a name: a leading `\` fully qualified, a first segment an alias expands, else relative to `ns`.
803
589
  function addRef(set, raw, ns, aliasMap) {
804
590
  const n = raw.trim().replace(/^\?/u, '') // drop a nullable-type marker (`?Foo`)
805
591
  if (!n || !/^\\?[A-Za-z_][\w\\]*$/u.test(n)) return
@@ -807,21 +593,12 @@ function addRef(set, raw, ns, aliasMap) {
807
593
  set.add(n.replace(/^\\+/u, ''))
808
594
  return
809
595
  }
810
- const first = n.split('\\')[0]
811
- if (!n.includes('\\')) {
812
- if (RESERVED.has(n.toLowerCase())) return
813
- if (aliasMap.has(n)) set.add(aliasMap.get(n))
814
- else set.add(ns ? `${ns}\\${n}` : n)
815
- } else if (aliasMap.has(first)) {
816
- set.add(`${aliasMap.get(first)}\\${n.slice(first.length + 1)}`)
817
- } else {
818
- set.add(ns ? `${ns}\\${n}` : n)
819
- }
596
+ const [first, ...rest] = n.split('\\')
597
+ if (rest.length === 0 && RESERVED.has(n.toLowerCase())) return
598
+ if (aliasMap.has(first)) set.add([aliasMap.get(first), ...rest].join('\\'))
599
+ else set.add(ns ? `${ns}\\${n}` : n)
820
600
  }
821
601
 
822
- // Parse a `use` body (between `use` and `;`) into entries, handling comma lists
823
- // and group syntax (`Pre\{A, B as C}`). Returns `[{ name, short }]` (short = the
824
- // alias or last segment).
825
602
  function parseUseBody(body) {
826
603
  const grouped = body.match(/^([\w\\]+\\)\{([\s\S]*)\}$/u)
827
604
  const entries = grouped
@@ -837,49 +614,38 @@ function parseUseBody(body) {
837
614
  return out
838
615
  }
839
616
 
840
- // Position of the first class/interface/trait/enum declaration -- the end of the
841
- // import region (a `use` before it is an alias import; after it, an in-body trait
842
- // use that loads the trait). `::class`/member accesses excluded via the
843
- // lookbehind. Infinity when there's no class-like declaration.
844
- function firstDeclPos(stripped) {
845
- const m = stripped.match(/(?<![:\w$\\>])\b(?:class|interface|trait|enum)\b/iu)
846
- return m ? m.index : Infinity
847
- }
617
+ // The first class-like declaration ends the import region: a `use` before it is an alias import; after it, an
618
+ // in-body trait use, which loads the trait.
619
+ const firstDeclPos = (stripped) => stripped.match(/(?<![:\w$\\>])\b(?:class|interface|trait|enum)\b/iu)?.index ?? Infinity
848
620
 
849
- // Collect the FQCNs a PHP file actually depends on. A `use` import only aliases
850
- // and loads nothing, so it is NOT a dependency; only real reference sites pull a
851
- // file in (new/extends/implements/instanceof/catch/`Foo::bar`/attributes/type
852
- // hints/FQNs, plus in-body `use Trait;`).
621
+ // A `use` import only aliases and loads nothing, so is no dependency: only where a class is referenced is.
853
622
  export function phpClassDependencies(content) {
854
- const stripped = stripPhp(content)
623
+ // Strings blanked too, so class-reference scans don't trip over text in them.
624
+ const stripped = maskNonCode(content, false)
855
625
  const nsMatch = stripped.match(/\bnamespace\s+([\w\\]+)/u)
856
626
  const ns = nsMatch ? nsMatch[1].replace(/^\\+|\\+$/gu, '') : ''
857
627
  const set = new Set()
628
+ const aliasMap = new Map()
629
+ const add = (raw) => addRef(set, raw, ns, aliasMap)
630
+ const addAll = (re, separator) => {
631
+ for (const m of stripped.matchAll(re)) for (const nm of separator ? m[1].split(separator) : [m[1]]) add(nm)
632
+ }
858
633
 
859
- // `use` before the first declaration builds the alias map; a `use` after it is
860
- // an in-body trait use, counted as a reference.
861
634
  const declAt = firstDeclPos(stripped)
862
- const aliasMap = new Map()
863
- const traitRefs = []
864
635
  for (const m of stripped.matchAll(/\buse\s+(?!\()(function\s+|const\s+)?([\s\S]*?);/giu)) {
865
636
  if (m[1]) continue
866
637
  const entries = parseUseBody(m[2].trim())
867
638
  if (m.index < declAt) {
868
639
  for (const e of entries) aliasMap.set(e.short, e.name.replace(/^\\+/u, ''))
869
640
  } else {
870
- for (const e of entries) traitRefs.push(e.name)
641
+ for (const e of entries) add(e.name)
871
642
  }
872
643
  }
873
644
 
874
- const add = (raw) => addRef(set, raw, ns, aliasMap)
875
- for (const raw of traitRefs) add(raw)
876
-
877
- for (const m of stripped.matchAll(/(?<![\w$\\])new\s+(\\?[\w\\]+)/giu)) add(m[1])
878
- for (const m of stripped.matchAll(/(?<![\w$\\])instanceof\s+(\\?[\w\\]+)/giu)) add(m[1])
879
- for (const m of stripped.matchAll(/(?<![\w$\\])(\\?[\w\\]+)\s*::/giu)) add(m[1])
880
- for (const m of stripped.matchAll(/#\[\s*(\\?[\w\\]+)/giu)) add(m[1])
881
-
882
- // class/interface/trait/enum headers: pull names out of extends/implements.
645
+ addAll(/(?<![\w$\\])new\s+(\\?[\w\\]+)/giu)
646
+ addAll(/(?<![\w$\\])instanceof\s+(\\?[\w\\]+)/giu)
647
+ addAll(/(?<![\w$\\])(\\?[\w\\]+)\s*::/giu)
648
+ addAll(/#\[\s*(\\?[\w\\]+)/giu)
883
649
  for (const m of stripped.matchAll(/\b(?:class|interface|trait|enum)\b[^{;]*?\{/giu)) {
884
650
  const header = m[0]
885
651
  const ext = header.match(/\bextends\s+([\w\\\s,?]+?)(?:\bimplements\b|\{)/iu)
@@ -887,31 +653,16 @@ export function phpClassDependencies(content) {
887
653
  const impl = header.match(/\bimplements\s+([\w\\\s,?]+?)\{/iu)
888
654
  if (impl) for (const nm of impl[1].split(',')) add(nm)
889
655
  }
890
-
891
- // catch (A | B $e), or PHP 8's catch (A | B) with no variable: capture the type
892
- // list up to `$var` or `)`. One quantifier with nothing after it keeps matching
893
- // linear on adversarial input.
894
- for (const m of stripped.matchAll(/\bcatch\s*\(([^)$]*)/giu)) {
895
- for (const nm of m[1].split('|')) add(nm)
896
- }
897
-
898
- // parameter/property type hints: `Type $var`, incl. `?Type`, variadic, by-ref,
899
- // and union/intersection `A|B`/`A&B` (each member counts). Only one whitespace
900
- // quantifier is unbounded (inner `\s*` gated behind `[&.]`) to avoid
901
- // catastrophic backtracking against adversarial input.
902
- for (const m of stripped.matchAll(/(?<![\w$\\])([?\w\\|&]+)\s+(?:[&.]+\s*)?\$\w+/giu)) {
903
- for (const nm of m[1].split(/[|&]/u)) add(nm)
904
- }
905
- // return types: `): Type`, incl. nullable and union/intersection `): A|B`.
906
- for (const m of stripped.matchAll(/\)\s*:\s*([?\w\\|&]+)/giu)) {
907
- for (const nm of m[1].split(/[|&]/u)) add(nm)
908
- }
909
-
656
+ // `catch (A | B $e)`, or PHP 8's with no variable: one quantifier with nothing after it keeps matching linear
657
+ // on adversarial input.
658
+ addAll(/\bcatch\s*\(([^)$]*)/giu, '|')
659
+ // Type hints, `?Type`, variadic, by-ref and `A|B`/`A&B` too, then return types: only one whitespace quantifier
660
+ // is unbounded (the inner `\s*` behind `[&.]`), against catastrophic backtracking.
661
+ addAll(/(?<![\w$\\])([?\w\\|&]+)\s+(?:[&.]+\s*)?\$\w+/giu, /[|&]/u)
662
+ addAll(/\)\s*:\s*([?\w\\|&]+)/giu, /[|&]/u)
910
663
  return set
911
664
  }
912
665
 
913
- // Resolve each autoloaded class a file references to a baseDir-relative file that
914
- // exists and is in `sources`. Best-effort: unresolvable refs skipped.
915
666
  function autoloadEdges(content, autoload, baseDir, sources) {
916
667
  const edges = new Map()
917
668
  if (!autoload) return edges
@@ -922,37 +673,28 @@ function autoloadEdges(content, autoload, baseDir, sources) {
922
673
  return edges
923
674
  }
924
675
 
925
- // Build `{ sources, resolutions, missing }` from already-loaded PHP sources.
926
- // Explicit includes are strict (unresolvable -> `missing`); Composer-autoloaded
927
- // class refs (when `autoload` is given) are best-effort and never added to
928
- // `missing`. Fallback: a specifier matching a stored key verbatim is accepted.
676
+ // Explicit includes are strict (unresolvable -> `missing`); Composer-autoloaded class refs (with `autoload`)
677
+ // best-effort, never `missing`.
929
678
  export function buildPhpTree(sources, { baseDir, autoload = null } = {}) {
930
679
  const resolutions = new Map()
931
680
  const missing = []
932
681
  for (const [path, content] of sources) {
933
682
  const specMap = new Map()
934
683
  for (const spec of extractPhpImports(content)) {
935
- let resolved = resolvePhpImport(spec, path, { baseDir })
936
- if (resolved && !sources.has(resolved)) resolved = null
937
- if (!resolved && sources.has(spec)) resolved = spec
938
- if (resolved) {
939
- specMap.set(spec, resolved)
940
- } else {
684
+ // A specifier naming a stored key verbatim is taken where it resolves to none.
685
+ const resolved = [resolvePhpImport(spec, path, { baseDir }), spec].find((p) => p && sources.has(p))
686
+ if (resolved) specMap.set(spec, resolved)
687
+ else {
941
688
  console.warn(`[loader.php] Missing import: ${spec} from ${path}`)
942
689
  missing.push({ spec, from: path })
943
690
  }
944
691
  }
945
- for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) {
946
- specMap.set(fqcn, file)
947
- }
692
+ for (const [fqcn, file] of autoloadEdges(content, autoload, baseDir, sources)) specMap.set(fqcn, file)
948
693
  resolutions.set(path, specMap)
949
694
  }
950
695
  return { sources, resolutions, missing }
951
696
  }
952
697
 
953
- // Walk the filesystem from `entries` (plus Composer `files` autoload entries),
954
- // following resolved includes and autoloaded class refs, reading each file once.
955
- // Same-wave files are read in parallel; the next wave depends on the previous.
956
698
  export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = null } = {}) {
957
699
  const sources = new Map()
958
700
  const realBase = realpathSync(baseDir)
@@ -965,9 +707,7 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
965
707
  if (!isUtf8(bytes)) throw new Error(`PHP source is not valid UTF-8: ${relPath}`)
966
708
  return [relPath, bytes.toString('utf8')]
967
709
  } catch (err) {
968
- // ENOENT (no file) / EISDIR (specifier resolved to a directory): not a
969
- // loadable file -- warn and skip rather than crash (buildPhpTree surfaces
970
- // the unresolved edge for real includes).
710
+ // No file, or a specifier resolved to a directory: buildPhpTree tells a real include's edge unresolved.
971
711
  if (err.code === 'ENOENT' || err.code === 'EISDIR') {
972
712
  console.warn(`[loader.php] Missing import: ${relPath}`)
973
713
  return null
@@ -976,56 +716,35 @@ export async function collectPhpFilesFromDisk(baseDir, entries, { autoload = nul
976
716
  }
977
717
  }
978
718
 
979
- const processWave = async (wave) => {
719
+ // Composer `files` autoload entries load unconditionally, so they're roots too.
720
+ for (let wave = [...entries, ...(autoload?.files ?? [])]; wave.length > 0;) {
980
721
  const toLoad = [...new Set(wave)].filter((p) => !sources.has(p))
981
- if (toLoad.length === 0) return
982
- // Bounded batches: a wave can be huge (a dynamic include's directory glob),
983
- // and an unbounded Promise.all would open every file at once and crash EMFILE.
984
722
  const reads = []
985
723
  for (let k = 0; k < toLoad.length; k += READ_CONCURRENCY) {
986
724
  // eslint-disable-next-line no-await-in-loop -- batches are intentionally sequential to cap open files
987
725
  reads.push(...(await Promise.all(toLoad.slice(k, k + READ_CONCURRENCY).map(readOne))))
988
726
  }
989
727
  const next = []
990
- for (const entry of reads) {
991
- if (!entry) continue
992
- const [relPath, content] = entry
728
+ for (const [relPath, content] of reads.filter(Boolean)) {
993
729
  sources.set(relPath, content)
994
- const includes = scanIncludes(content)
730
+ const masked = maskedPhp(content)
731
+ const includes = scanIncludes(masked)
995
732
  for (const spec of includeSpecs(includes, 'file')) {
996
733
  const resolved = resolvePhpImport(spec, relPath, { baseDir })
997
- if (resolved) {
998
- if (!sources.has(resolved)) next.push(resolved)
999
- } else {
1000
- console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
1001
- }
734
+ if (resolved) next.push(resolved)
735
+ else console.warn(`[loader.php] Missing import: ${spec} from ${relPath}`)
1002
736
  }
1003
- // Dynamic includes with a static dir prefix: the exact file is known only
1004
- // at runtime, so bundle every `.php` file in that directory as a candidate.
1005
737
  for (const dirSpec of includeSpecs(includes, 'dir')) {
1006
738
  const dir = resolvePhpDir(dirSpec, relPath, baseDir)
1007
- if (!dir) continue
1008
- for (const file of listPhpFiles(baseDir, dir)) {
1009
- if (!sources.has(file)) next.push(file)
1010
- }
739
+ if (dir) for (const file of listPhpFiles(baseDir, dir)) next.push(file)
1011
740
  }
1012
- // `.php` path literals outside a require (route/config files passed to a
1013
- // framework). Best-effort: bundle only if they resolve to an existing file.
1014
- for (const { spec, anchor } of extractPhpPathRefs(content)) {
1015
- const resolved = anchor === 'root'
1016
- ? normalizeProjectRel(baseDir, spec)
1017
- : resolvePhpImport(spec, relPath, { baseDir })
1018
- if (resolved && isFileOnDisk(baseDir, resolved) && !sources.has(resolved)) next.push(resolved)
1019
- }
1020
- // Autoloaded class references (best-effort): enqueue whatever resolves.
1021
- for (const [, file] of autoloadEdges(content, autoload, baseDir, null)) {
1022
- if (!sources.has(file)) next.push(file)
741
+ for (const { spec, anchor } of pathRefs(masked)) {
742
+ const resolved = anchor === 'root' ? normalizeProjectRel(baseDir, spec) : resolvePhpImport(spec, relPath, { baseDir })
743
+ if (resolved && isFileOnDisk(baseDir, resolved)) next.push(resolved)
1023
744
  }
745
+ for (const file of autoloadEdges(content, autoload, baseDir, null).values()) next.push(file)
1024
746
  }
1025
- await processWave(next)
747
+ wave = next
1026
748
  }
1027
-
1028
- // Composer `files` autoload entries load unconditionally, so they're graph roots too.
1029
- await processWave([...entries, ...(autoload?.files ?? [])])
1030
749
  return sources
1031
750
  }