@preventive/triage 1.0.0-alpha.72 → 1.0.0-alpha.74

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 (138) hide show
  1. package/common/bundle-compare-diff.d.ts +4 -1
  2. package/common/bundle-compare-diff.js +4 -3
  3. package/common/bundle-sources.d.ts +2 -0
  4. package/common/bundle-sources.js +22 -3
  5. package/common/finding-duplicates.js +5 -0
  6. package/common/finding-filters.js +45 -4
  7. package/common/line-diff.d.ts +2 -2
  8. package/common/line-diff.js +20 -8
  9. package/common/managed/finding-detail.js +1 -1
  10. package/common/managed/review-view-routes.js +23 -0
  11. package/common/managed/risk-routes.js +30 -0
  12. package/common/managed/routes.js +11 -6
  13. package/common/managed/team-app.d.ts +8 -6
  14. package/common/managed/team-app.js +15 -3
  15. package/common/stasis-files.d.ts +5 -0
  16. package/common/stasis-files.js +20 -0
  17. package/common/stasis-tgz.d.ts +6 -0
  18. package/common/stasis-tgz.js +27 -0
  19. package/common/workspace-app.js +20 -0
  20. package/out/activity.js +2 -4
  21. package/out/{chunk-2F3CYNPZ.js → chunk-2IHCVA3Y.js} +1 -1
  22. package/out/{chunk-HAZKDK4M.js → chunk-2V6Q4ZOZ.js} +1 -1
  23. package/out/{chunk-RRBIJL2B.js → chunk-4IW3VD3H.js} +1 -1
  24. package/out/chunk-4YZOXAXR.js +2 -0
  25. package/out/chunk-5YP7P5KA.js +1 -0
  26. package/out/chunk-62QT2RXR.js +6 -0
  27. package/out/chunk-6VOB5WXX.js +2 -0
  28. package/out/chunk-A4BBBHQU.js +1 -0
  29. package/out/{chunk-4ISO5F7Y.js → chunk-ADMVRLNP.js} +1 -1
  30. package/out/{chunk-HETCVNO4.js → chunk-BLPHP4U3.js} +1 -1
  31. package/out/{chunk-Y5ZHFNBD.js → chunk-BXQCCW7F.js} +1 -1
  32. package/out/chunk-C6OPCPCA.js +1 -0
  33. package/out/{chunk-JFL7WLRV.js → chunk-CU3FPB3P.js} +1 -1
  34. package/out/chunk-DQJEVHRE.js +52 -0
  35. package/out/chunk-ESJZZF2Y.js +255 -0
  36. package/out/{chunk-M37X4LCF.js → chunk-EXQQ5VQJ.js} +1 -1
  37. package/out/{chunk-NXATZJQ2.js → chunk-GSNSP3EF.js} +1 -1
  38. package/out/chunk-GV5U7OLP.js +40 -0
  39. package/out/{chunk-JOXLZXMI.js → chunk-GX5UXWT4.js} +1 -1
  40. package/out/chunk-HLMQ7QYS.js +1 -0
  41. package/out/{chunk-YF4M5OCI.js → chunk-I6UQQKAH.js} +1 -1
  42. package/out/{chunk-UCP3JRE2.js → chunk-LVW7WWV4.js} +1 -1
  43. package/out/chunk-NEFCZAIY.js +11 -0
  44. package/out/{chunk-TOXMUOIW.js → chunk-OQS2USZM.js} +1 -1
  45. package/out/chunk-PLF4LBLE.js +1 -0
  46. package/out/chunk-QBFT2DDR.js +1 -0
  47. package/out/{chunk-QMVOEBWC.js → chunk-S2ZIKK45.js} +1 -1
  48. package/out/chunk-S5HSDGTP.js +8 -0
  49. package/out/chunk-SSPDMA6D.js +1 -0
  50. package/out/{chunk-4XIH7YTX.js → chunk-UH6NZBSU.js} +1 -1
  51. package/out/{chunk-M3Y6SLC4.js → chunk-UJP4PQJA.js} +1 -1
  52. package/out/{chunk-PAD2JHZT.js → chunk-UJSJMXEG.js} +1 -1
  53. package/out/chunk-VRAJCPV5.js +3 -0
  54. package/out/chunk-VS7RV24Z.js +4 -0
  55. package/out/{chunk-E3LFSUDJ.js → chunk-VYYUMYVW.js} +1 -1
  56. package/out/chunk-W5PRH5D7.js +2 -0
  57. package/out/{chunk-VRX2APNA.js → chunk-XVKDPU4D.js} +1 -1
  58. package/out/{chunk-WKFBZYJX.js → chunk-YI4D6XVX.js} +1 -1
  59. package/out/client-managed-import.js +3 -3
  60. package/out/client-managed.js +30 -28
  61. package/out/compare.js +16 -23
  62. package/out/dialogs.js +38 -38
  63. package/out/graph.js +14 -14
  64. package/out/index.html +31 -51
  65. package/out/scan.js +2 -2
  66. package/out/terminal.js +239 -240
  67. package/out/view.css +1 -1
  68. package/out/view.js +15 -15
  69. package/package.json +21 -13
  70. package/risk/actions/resolve.js +47 -16
  71. package/risk/actions/uses.js +27 -9
  72. package/risk/actions/workflow.js +75 -2
  73. package/risk/files/hosts.js +4 -4
  74. package/risk/files/readability.js +5 -2
  75. package/risk/files/runs-code.js +12 -25
  76. package/risk/files/script.js +141 -19
  77. package/risk/index.d.ts +24 -7
  78. package/risk/index.js +1 -0
  79. package/risk/npm/assess.js +1 -1
  80. package/risk/npm/compare.js +5 -4
  81. package/risk/npm/diff.js +1 -1
  82. package/risk/npm/held.js +6 -2
  83. package/risk/npm/registry.js +5 -2
  84. package/risk/npm/tarball.js +79 -22
  85. package/server-managed/bundle-advisories.ts +12 -36
  86. package/server-managed/bundle-build-worker.js +29 -11
  87. package/server-managed/bundle-build.ts +4 -3
  88. package/server-managed/bundle-cache.ts +53 -13
  89. package/server-managed/bundle.ts +45 -13
  90. package/server-managed/comparison.ts +7 -6
  91. package/server-managed/db-methods.ts +54 -17
  92. package/server-managed/db-neon.ts +9 -2
  93. package/server-managed/db-schema.ts +12 -2
  94. package/server-managed/db.ts +4 -1
  95. package/server-managed/dependency-reviews.ts +8 -5
  96. package/server-managed/github-errors.ts +22 -0
  97. package/server-managed/github-requests.ts +4 -2
  98. package/server-managed/http.ts +238 -27
  99. package/server-managed/management.ts +10 -4
  100. package/server-managed/npm-delta.ts +1 -1
  101. package/server-managed/npm-loads.ts +2 -2
  102. package/server-managed/npm-packages.ts +34 -29
  103. package/server-managed/npm-patch-paths.ts +57 -0
  104. package/server-managed/npm-patch.ts +77 -82
  105. package/server-managed/package-entry-points.ts +54 -6
  106. package/server-managed/rename-diff-worker.js +11 -7
  107. package/server-managed/rename-diff.ts +5 -4
  108. package/server-managed/report-opening.ts +77 -0
  109. package/server-managed/report-sources.ts +2 -1
  110. package/server-managed/repository-aliases.ts +34 -0
  111. package/server-managed/repository-browser.ts +87 -32
  112. package/server-managed/repository-code.ts +14 -8
  113. package/server-managed/repository-dependency-reviews.ts +21 -0
  114. package/server-managed/repository-risk-read.ts +71 -4
  115. package/server-managed/repository-risk.ts +9 -2
  116. package/server-managed/stasis-config.ts +97 -5
  117. package/server-managed/team-reports.ts +5 -3
  118. package/server-managed/type-only-proof.js +26 -4
  119. package/server-managed/upstream-cache.ts +18 -12
  120. package/server-managed/workspace-shares.ts +4 -4
  121. package/out/chunk-27Y75UQR.js +0 -4
  122. package/out/chunk-4RS3NDOG.js +0 -1
  123. package/out/chunk-4XSH6ZLT.js +0 -1
  124. package/out/chunk-7CHIFYQW.js +0 -42
  125. package/out/chunk-CZ3U2LI4.js +0 -2
  126. package/out/chunk-ETL5ZPPR.js +0 -259
  127. package/out/chunk-L6VIWL2Y.js +0 -1
  128. package/out/chunk-OSHR3N4S.js +0 -3
  129. package/out/chunk-UD33S2MG.js +0 -52
  130. package/out/chunk-VG5RH6KN.js +0 -2
  131. package/out/chunk-WFDXHPT2.js +0 -12
  132. package/out/chunk-WMFDQS2L.js +0 -11
  133. package/out/chunk-WREU7JAG.js +0 -1
  134. /package/out/{chunk-4LZK6C6N.js → chunk-74JZTGTO.js} +0 -0
  135. /package/out/{chunk-JMG5DXII.js → chunk-7HP2VYIC.js} +0 -0
  136. /package/out/{chunk-HOB3YPS5.js → chunk-K4XJHM2T.js} +0 -0
  137. /package/out/{chunk-4EMM6UCD.js → chunk-QI66YA4F.js} +0 -0
  138. /package/out/{chunk-G3LY2FV4.js → chunk-WCDYSIKG.js} +0 -0
@@ -17,6 +17,7 @@ import { resolve } from 'node:path'
17
17
  import { ArchiveError, type Entry, unpack } from '@preventive/archive/tar.js'
18
18
  import { isExactVersion } from '@preventive/upstream/semver.js'
19
19
  import { isNpmPackageName, isNpmPackageSpec, npmPackageScope } from '../common/managed/npm-packages.js'
20
+ import { NPM_SYMLINKS_ABOVE, npmTarLayout } from '../risk/index.js'
20
21
  import type { Role } from '../common/managed/roles.ts'
21
22
  import { npmManifest, npmVersionFields, plainObject, stringRecord } from './npm-manifest.ts'
22
23
  import { keepJson, readKeptJson, upstreamCachePath } from './upstream-cache.ts'
@@ -379,7 +380,12 @@ export function npmPublishTime(doc: Pick<NpmVersionDocument, 'name' | 'version'
379
380
  }
380
381
  }
381
382
 
382
- export interface NpmPackageFile { path: string; bytes: Uint8Array }
383
+ // A symlink's `link` is its target as stored, its bytes that target's: no text, whatever they spell.
384
+ // One with an execute bit is `executable`.
385
+ export interface NpmPackageFile { path: string; bytes: Uint8Array; link?: string; executable?: true }
386
+
387
+ // The paths of `files` that are executable, as the viewer gets them beside their rows.
388
+ export const npmExecutablePaths = (files: NpmPackageFile[]) => files.flatMap(file => file.executable ? [file.path] : [])
383
389
 
384
390
  // Paths in the order a package's files are read in (readNpmTar), and
385
391
  // Compare's: by their UTF-16 code units, as a plain sort orders them.
@@ -389,16 +395,21 @@ export const pathOrder = (a: string, b: string) => a < b ? -1 : a > b ? 1 : 0
389
395
  // it, and the entries, files and bytes it may hold, a package's unless given.
390
396
  export interface TarReading { symlinksAbove?: number; maxEntries?: number; maxFiles?: number; maxBytes?: number }
391
397
 
392
- // The regular files of a tar stream, by package path: npm drops the first
393
- // component (`package/`, or whatever the archive used), and a file at the top
394
- // is not extracted. The stream is read by @preventive/archive, which refuses
395
- // one malformed, a name or a symlink that would climb out of it -- a symlink
396
- // past `symlinksAbove` levels above it, none unless given -- and a name
397
- // repeated as another entry, and gives up past `maxEntries` before reading
398
- // on; a file under another top directory at the same path replaces an
399
- // earlier one, as extraction would. Directories, links and devices hold no
400
- // file content and are skipped.
401
- export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
398
+ // The regular files of a tar stream, by package path, as npm and pnpm install
399
+ // them (risk's npmTarLayout): each name as stored past its first component,
400
+ // whatever the archive used (`package/`, a release's own directory, `.`), and
401
+ // a file under no directory at its name, as pnpm installs it. The stream is
402
+ // read by @preventive/archive, which refuses one malformed, a name that would
403
+ // climb out of it, an absolute symlink or one past `symlinksAbove` levels
404
+ // above it, any unless given, and a name repeated as another entry, and
405
+ // gives up past `maxEntries` before reading on. Every file is read, whether
406
+ // or not an installer installs it, a hard link as its target's bytes, a
407
+ // symlink for where it points. Where
408
+ // the files conflict (two that differ at one path, as under two top
409
+ // directories, a file within another), it is refused as `tarball-conflict`,
410
+ // never read as one installer does. Directories and devices hold no file
411
+ // content and are skipped.
412
+ export function readNpmTar(tar: Uint8Array, { symlinksAbove = NPM_SYMLINKS_ABOVE, maxEntries = MAX_NPM_TAR_ENTRIES, maxFiles = MAX_NPM_PACKAGE_FILES,
402
413
  maxBytes = MAX_NPM_PACKAGE_BYTES }: TarReading = {}): NpmPackageFile[] {
403
414
  let entries: Entry[]
404
415
  try { entries = unpack(tar, { maxEntries, symlinksAbove }) }
@@ -406,17 +417,8 @@ export function readNpmTar(tar: Uint8Array, { symlinksAbove = 0, maxEntries = MA
406
417
  if (err instanceof ArchiveError) throw err.limited ? new NpmPackageError(413, 'package-too-large') : new NpmPackageError(422, 'bad-tarball')
407
418
  throw err
408
419
  }
409
- const files = new Map<string, Uint8Array>()
410
- let total = 0
411
- for (const { name, type, data } of entries) {
412
- const slash = name.indexOf('/')
413
- if ((type !== 'file' && type !== 'contiguous-file') || slash === -1) continue
414
- const path = name.slice(slash + 1)
415
- total += data.length - (files.get(path)?.length ?? 0)
416
- files.set(path, data)
417
- if (files.size > maxFiles || total > maxBytes) throw new NpmPackageError(413, 'package-too-large')
418
- }
419
- return [...files].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
420
+ const files = npmTarLayout(entries, { maxFiles, maxBytes }, (code) => { throw new NpmPackageError(code === 'package-too-large' ? 413 : 422, code) })
421
+ return [...files].map(([path, file]) => ({ path, ...file })).toSorted((a, b) => pathOrder(a.path, b.path))
420
422
  }
421
423
 
422
424
  const utf8 = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true })
@@ -444,15 +446,18 @@ const ROW_LENGTH = 80
444
446
 
445
447
  // The files as the viewer gets them: `[path, bytes, text]`, text null for a
446
448
  // file that is not UTF-8, which instead carries its bytes' sha256, so a
447
- // comparison of two versions tells a changed one from an unchanged one. They
448
- // may take `maxLength` characters of JSON, a package's unless given.
449
- export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string])[] {
449
+ // comparison of two versions tells a changed one from an unchanged one; a
450
+ // symlink so too, its target last. They may take `maxLength` characters of
451
+ // JSON, a package's unless given.
452
+ export function npmFileRows(files: NpmPackageFile[], maxLength = MAX_NPM_JSON_LENGTH): ([string, number, string] | [string, number, null, string, string?])[] {
450
453
  let length = 0
451
- return files.map(({ path, bytes }) => {
452
- const text = npmFileText(bytes)
453
- length += ROW_LENGTH + jsonLength(path) + (text === null ? 0 : jsonLength(text))
454
+ return files.map(({ path, bytes, link }) => {
455
+ const text = link === undefined ? npmFileText(bytes) : null
456
+ length += ROW_LENGTH + jsonLength(path) + jsonLength(text ?? link ?? '')
454
457
  if (length > maxLength) throw new NpmPackageError(413, 'package-too-large')
455
- return text === null ? [path, bytes.byteLength, null, `sha256-${createHash('sha256').update(bytes).digest('base64')}`] : [path, bytes.byteLength, text]
458
+ const digest = () => `sha256-${createHash('sha256').update(bytes).digest('base64')}`
459
+ if (text !== null) return [path, bytes.byteLength, text]
460
+ return link === undefined ? [path, bytes.byteLength, null, digest()] : [path, bytes.byteLength, null, digest(), link]
456
461
  })
457
462
  }
458
463
 
@@ -0,0 +1,57 @@
1
+ // Paths as git writes them in a diff's headers (npm-patch.ts parsePatch):
2
+ // quoted as C writes a string where they need it, prefixed `a/` and `b/`.
3
+ import { Buffer } from 'node:buffer'
4
+ import { NpmPackageError } from './npm-packages.ts'
5
+
6
+ const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
7
+
8
+ // A path as git writes it, unquoted where quoted (as C writes a string, its
9
+ // bytes past ASCII in octal); null where it is quoted otherwise.
10
+ const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
11
+ export function unquoted(path: string): string | null {
12
+ if (!path.startsWith('"')) return path
13
+ const bytes: number[] = []
14
+ for (let at = 1; at < path.length; at++) {
15
+ const char = path[at]!
16
+ if (char === '"') return at === path.length - 1 ? new TextDecoder().decode(Uint8Array.from(bytes)) : null
17
+ if (char !== '\\') { bytes.push(...Buffer.from(char)); continue }
18
+ const next = path[++at] ?? ''
19
+ const octal = /^[0-3][0-7]{2}/u.exec(path.slice(at))?.[0]
20
+ if (octal) { bytes.push(Number.parseInt(octal, 8)); at += 2 }
21
+ else if (next in ESCAPES) bytes.push(ESCAPES[next]!)
22
+ else return null
23
+ }
24
+ return null
25
+ }
26
+
27
+ // A side's path in the package, as a `---` or `+++` line names it after its
28
+ // prefix (`a/` or `b/`), git's tab after one with a space in it left out;
29
+ // null for none (`/dev/null`).
30
+ export function sidePath(named: string, prefix: string): string | null {
31
+ const path = unquoted(named.endsWith('\t') ? named.slice(0, -1) : named)
32
+ if (path === '/dev/null') return null
33
+ if (path === null || !path.startsWith(prefix)) throw unreadable()
34
+ return path.slice(prefix.length)
35
+ }
36
+
37
+ // The paths a `diff --git` line names, where they are the same, as git
38
+ // writes them for a file neither renamed nor copied: `a/<path> b/<path>`.
39
+ export function gitPath(named: string): string | null {
40
+ if (named.startsWith('"')) {
41
+ const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/u.exec(named)
42
+ const [a, b] = quoted ? [unquoted(quoted[1]!), unquoted(quoted[2]!)] : []
43
+ return a?.startsWith('a/') && b?.startsWith('b/') && a.slice(2) === b.slice(2) ? a.slice(2) : null
44
+ }
45
+ const length = (named.length - 5) / 2
46
+ const path = named.slice(2, 2 + length)
47
+ return Number.isInteger(length) && named.startsWith('a/') && named.slice(2 + length) === ` b/${path}` ? path : null
48
+ }
49
+
50
+ // Whether a `diff --git` line's paths (`rest`, past `diff --git `) are
51
+ // `before` and `after`, as git writes them, either quoted or not.
52
+ export function namesBoth(rest: string, before: string, after: string): boolean {
53
+ const first = rest.startsWith('"') ? /^"(?:[^"\\]|\\.)*"/u.exec(rest)?.[0] : `a/${before}`
54
+ if (first === undefined || !rest.startsWith(`${first} `)) return false
55
+ const second = rest.slice(first.length + 1)
56
+ return unquoted(first) === `a/${before}` && unquoted(second) === `b/${after}`
57
+ }
@@ -6,14 +6,18 @@
6
6
  // to the hash the lockfile names it by, as pnpm 10 and later hash it
7
7
  // (hashOfPatch; one pnpm 9 names by an md5 isn't read), by which it is kept
8
8
  // for good, read of GitHub once; and applied to the version's files as pnpm applies
9
- // it as it installs it (patch-package's applyPatch, which pnpm 10 and 11
10
- // bundle): each file it deletes, creates, renames or changes, a change's
11
- // hunks each found in the file as it was, where its header says, else as
12
- // many as FUZZ lines either side, its lines the same but for the space they
13
- // end in, and those it keeps kept as the file has them. A patch of a file's
14
- // bytes (git's binary patch), or of a file outside the package, isn't read,
15
- // and one that doesn't apply fails as a whole; what a patch changes of a
16
- // file's mode is left out, as the files it reads have none.
9
+ // it as it installs it (patch-package's applyPatch, which pnpm 10 bundles):
10
+ // each file it deletes, creates, renames or changes, a change's hunks each
11
+ // found in the file as it was, where its header says, else as many as FUZZ
12
+ // lines either side, its lines the same but for the space they end in, and
13
+ // those it keeps kept as the file has them. pnpm 10, 11 and 12 each read a
14
+ // patch their own way, so one is read only where none installs other than
15
+ // it shows (parsePatch): a line outside what git writes, paths that
16
+ // disagree, a rename that also creates or deletes, or a hunk whose missing
17
+ // final newline the file doesn't bear out, isn't read. A file it makes
18
+ // executable, or no longer, is so, as every pnpm makes it. Nor is a patch of
19
+ // a file's bytes (git's binary patch) or of a mode but 644 and 755, or of a
20
+ // file outside the package, read; and one that doesn't apply fails as a whole.
17
21
  import { Buffer } from 'node:buffer'
18
22
  import { createHash } from 'node:crypto'
19
23
  import { YamlError, parseYaml } from '@preventive/lockfile/yaml.js'
@@ -27,6 +31,7 @@ import { type Lru, lru } from './lru.ts'
27
31
  import type { KeptStore } from './npm-kept.ts'
28
32
  import { plainObject } from './npm-manifest.ts'
29
33
  import { NpmPackageError, type NpmPackageFile, npmFileText, pathOrder } from './npm-packages.ts'
34
+ import { gitPath, namesBoth, sidePath, unquoted } from './npm-patch-paths.ts'
30
35
  import { type GithubAsked, type PullDependencies, lockfileFormat, repositoryFile } from './pull-dependencies.ts'
31
36
  import { eachOf } from './queue.ts'
32
37
 
@@ -77,55 +82,14 @@ const patchFileAt = (fullName: string, token: string, path: string, commit: stri
77
82
  // first's index, as it reads `-0`, the first line), how many it finds
78
83
  // (`length`), and its lines, each without its LF, in runs of a kind
79
84
  // (`parts`): those it keeps, removes or adds, the last of a side told where
80
- // the file has no LF after it (`unended`).
85
+ // the file has no LF after it (`unended`); and whether it makes the file
86
+ // executable, or no longer (`executable`), where it says.
81
87
  export interface HunkPart { kind: 'context' | 'deletion' | 'insertion'; lines: string[]; unended?: true }
82
88
  export interface PatchHunk { at: number; length: number; parts: HunkPart[] }
83
- export interface PatchedFile { path: string; from?: string; deleted?: true; created?: true; hunks: PatchHunk[] }
89
+ export interface PatchedFile { path: string; from?: string; deleted?: true; created?: true; executable?: boolean; hunks: PatchHunk[] }
84
90
 
85
91
  const unreadable = () => new NpmPackageError(422, 'patch-unreadable')
86
92
 
87
- // A path as git writes it, unquoted where quoted (as C writes a string, its
88
- // bytes past ASCII in octal); null where it is quoted otherwise.
89
- const ESCAPES: Record<string, number> = { a: 7, b: 8, t: 9, n: 10, v: 11, f: 12, r: 13, '"': 34, '\\': 92 }
90
- function unquoted(path: string): string | null {
91
- if (!path.startsWith('"')) return path
92
- const bytes: number[] = []
93
- for (let at = 1; at < path.length; at++) {
94
- const char = path[at]!
95
- if (char === '"') return at === path.length - 1 ? new TextDecoder().decode(Uint8Array.from(bytes)) : null
96
- if (char !== '\\') { bytes.push(...Buffer.from(char)); continue }
97
- const next = path[++at] ?? ''
98
- const octal = /^[0-3][0-7]{2}/u.exec(path.slice(at))?.[0]
99
- if (octal) { bytes.push(Number.parseInt(octal, 8)); at += 2 }
100
- else if (next in ESCAPES) bytes.push(ESCAPES[next]!)
101
- else return null
102
- }
103
- return null
104
- }
105
-
106
- // A side's path in the package, as a `---` or `+++` line names it after its
107
- // prefix (`a/` or `b/`), git's tab after one with a space in it left out;
108
- // null for none (`/dev/null`).
109
- function sidePath(named: string, prefix: string): string | null {
110
- const path = unquoted(named.endsWith('\t') ? named.slice(0, -1) : named)
111
- if (path === '/dev/null') return null
112
- if (path === null || !path.startsWith(prefix)) throw unreadable()
113
- return path.slice(prefix.length)
114
- }
115
-
116
- // The paths a `diff --git` line names, where they are the same, as git
117
- // writes them for a file neither renamed nor copied: `a/<path> b/<path>`.
118
- function gitPath(named: string): string | null {
119
- if (named.startsWith('"')) {
120
- const quoted = /^("(?:[^"\\]|\\.)*") ("(?:[^"\\]|\\.)*")$/u.exec(named)
121
- const [a, b] = quoted ? [unquoted(quoted[1]!), unquoted(quoted[2]!)] : []
122
- return a?.startsWith('a/') && b?.startsWith('b/') && a.slice(2) === b.slice(2) ? a.slice(2) : null
123
- }
124
- const length = (named.length - 5) / 2
125
- const path = named.slice(2, 2 + length)
126
- return Number.isInteger(length) && named.startsWith('a/') && named.slice(2 + length) === ` b/${path}` ? path : null
127
- }
128
-
129
93
  // The hunk whose `@@` line is at `at` of `lines`, those before `end` read,
130
94
  // and the line after it, as patch-package reads it: a line of its own
131
95
  // kind, else of those it keeps where it is empty, or a CR alone.
@@ -156,11 +120,16 @@ function readHunk(lines: string[], at: number, end: number): { hunk: PatchHunk;
156
120
  }
157
121
 
158
122
  // A patch's files as git's diff writes them, as pnpm writes a patch: a file's
159
- // `diff --git` line, its headers, the paths its sides have, and its hunks;
160
- // what comes before the first file, or between one file and the next, left
161
- // out. One whose own lines end in CRLFs, as an editor or git's autocrlf
162
- // leaves one, is read as patch-package reads it: its headers but their CRs,
163
- // its hunks' lines with them. Throws for one it can't read, or of bytes.
123
+ // `diff --git` line, its headers, the paths its sides have, and its hunks.
124
+ // One whose own lines end in CRLFs, as an editor or git's autocrlf leaves
125
+ // one, is read as patch-package reads it: its headers but their CRs, its
126
+ // hunks' lines with them. pnpm 10 and 11 also read hunks where git puts none
127
+ // (with no `diff --git` line, past a blank or `index` line, after another
128
+ // file's hunks) and pnpm 12 doesn't, so a line git doesn't write is refused,
129
+ // but blank lines at the end. So are a `diff --git` line naming other paths
130
+ // than its sides (pnpm 10 and 11 take one, pnpm 12 the other), a rename that
131
+ // also creates or deletes, and a `new mode` line without its `old mode`
132
+ // (pnpm 12 alone reads one). Throws for one it can't read, or of bytes.
164
133
  export function parsePatch(patch: string): PatchedFile[] {
165
134
  const lines = patch.split('\n')
166
135
  // The lines read: those but the empty one past the patch's last ending.
@@ -170,37 +139,47 @@ export function parsePatch(patch: string): PatchedFile[] {
170
139
  const files: PatchedFile[] = []
171
140
  for (let at = 0; at < lines.length;) {
172
141
  const head = headerAt(at++)
173
- if (!head.startsWith('diff --git ')) continue
174
- let created = false, deleted = false, from: string | null = null, to: string | null = null
142
+ if (head === '' && lines.slice(at, end).every((_, i) => headerAt(at + i) === '')) break
143
+ if (!head.startsWith('diff --git ')) throw unreadable()
144
+ let created = false, deleted = false, executable: boolean | undefined, from: string | null = null, to: string | null = null
175
145
  let sides: [string | null, string | null] | null = null
176
- for (; at < lines.length && !/^(?:diff --git |@@ |--- )/u.test(lines[at]!); at++) {
146
+ const seen = new Set<string>()
147
+ for (; at < end && !/^(?:diff --git |@@ |--- )/u.test(lines[at]!); at++) {
177
148
  const header = headerAt(at)
178
149
  if (header === 'GIT binary patch' || header.startsWith('Binary files ')) throw new NpmPackageError(422, 'patch-unsupported')
179
- if (header.startsWith('copy from ') || header.startsWith('copy to ')) throw new NpmPackageError(422, 'patch-unsupported')
180
- if (header.startsWith('deleted file mode ')) deleted = true
181
- else if (header.startsWith('new file mode ')) created = true
182
- else if (header.startsWith('rename from ')) from = unquoted(header.slice('rename from '.length))
183
- else if (header.startsWith('rename to ')) to = unquoted(header.slice('rename to '.length))
150
+ const kind = /^(?:index|similarity index|dissimilarity index|deleted file mode|new file mode|rename from|rename to|old mode|new mode|copy from|copy to) /u.exec(header)?.[0]
151
+ if (kind === undefined || seen.has(kind)) throw unreadable()
152
+ seen.add(kind)
153
+ // A mode it names: `100644`, or `100755` (executable).
154
+ const mode = kind.endsWith('mode ') ? header.slice(kind.length) : undefined
155
+ if (kind.startsWith('copy ') || (mode !== undefined && mode !== '100644' && mode !== '100755')) throw new NpmPackageError(422, 'patch-unsupported')
156
+ if (kind === 'deleted file mode ') deleted = true
157
+ else if (kind === 'new file mode ') { created = true; executable = mode === '100755' }
158
+ else if (kind === 'new mode ') executable = mode === '100755'
159
+ else if (kind === 'rename from ') from = unquoted(header.slice(kind.length))
160
+ else if (kind === 'rename to ') to = unquoted(header.slice(kind.length))
184
161
  }
185
162
  if (lines[at]?.startsWith('--- ')) {
186
163
  if (!lines[at + 1]?.startsWith('+++ ')) throw unreadable()
187
164
  sides = [sidePath(headerAt(at).slice(4), 'a/'), sidePath(headerAt(at + 1).slice(4), 'b/')]
188
165
  at += 2
189
166
  }
190
- const named = gitPath(head.slice('diff --git '.length))
191
- const after = to ?? (sides ? sides[1] : named), before = from ?? (sides ? sides[0] : named)
192
- if ((from === null) !== (to === null) || (deleted && created)) throw unreadable()
193
- const path = deleted ? before : after
194
- if (path == null || (!created && before == null) || (!deleted && after == null) || ![before, after].every(side => side == null || isPatchPath(side))
195
- || (from === null && !deleted && !created && before !== after)) throw unreadable()
167
+ if ((from === null) !== (to === null) || (deleted && created) || (from !== null && (deleted || created)) || seen.has('old mode ') !== seen.has('new mode ')) throw unreadable()
168
+ const rest = head.slice('diff --git '.length)
169
+ const path = sides ? (created ? sides[1] : sides[0]) : gitPath(rest)
170
+ const after = to ?? path, before = from ?? path
171
+ if (before == null || after == null || ![before, after].every(isPatchPath) || !namesBoth(rest, before, after)
172
+ || (sides && (sides[0] !== (created ? null : before) || sides[1] !== (deleted ? null : after)))) throw unreadable()
196
173
  const hunks: PatchHunk[] = []
197
174
  while (lines[at]?.startsWith('@@ ')) {
198
175
  const { hunk, next } = readHunk(lines, at, end)
199
176
  hunks.push(hunk)
200
177
  at = next
201
178
  }
202
- files.push({ path, ...from !== null && to !== null ? { from: before! } : {}, ...deleted ? { deleted: true as const } : {},
203
- ...created ? { created: true as const } : {}, hunks: deleted ? [] : hunks })
179
+ // A file created is its one hunk's lines, as git writes it, which pnpm 10 alone writes of a hunk otherwise.
180
+ if (created && (hunks.length > 1 || hunks.some(hunk => hunk.parts.some(part => part.kind !== 'insertion')))) throw unreadable()
181
+ files.push({ path: deleted ? before : after, ...from === null ? {} : { from: before }, ...deleted ? { deleted: true as const } : {},
182
+ ...created ? { created: true as const } : {}, ...executable === undefined || deleted ? {} : { executable }, hunks: deleted ? [] : hunks })
204
183
  }
205
184
  return files
206
185
  }
@@ -233,6 +212,18 @@ function changesAt(hunk: PatchHunk, lines: string[], at: number): LineChange[] |
233
212
  return changes
234
213
  }
235
214
 
215
+ // Whether `hunk`, found at `at` of `lines`, may say a side ends with no LF
216
+ // (`unended`): pnpm versions apply that mark alike only where the hunk ends
217
+ // where the file does, and the file agrees: no LF at its end for the old
218
+ // side's mark; one, or the old side's mark, for the new side's.
219
+ function endsAgree(hunk: PatchHunk, lines: string[], at: number): boolean {
220
+ const unended = lines.at(-1) !== ''
221
+ const ending = at + hunk.length === lines.length - (unended ? 0 : 1)
222
+ const pushes = hunk.parts.some(part => part.kind === 'deletion' && part.unended)
223
+ const pops = hunk.parts.some(part => part.kind === 'insertion' && part.unended)
224
+ return (!pushes || (ending && unended)) && (!pops || (ending && (pushes || !unended)))
225
+ }
226
+
236
227
  // `text` with `hunks` applied as patch-package applies them (applyPatch):
237
228
  // each one's lines found in the text as it was, where its header says, else
238
229
  // as near as FUZZ lines either side, the nearer first, and the earlier of
@@ -243,6 +234,8 @@ function applied(text: string, hunks: PatchHunk[]): string {
243
234
  const changes = hunks.flatMap(hunk => {
244
235
  for (let offset = 0; Math.abs(offset) <= FUZZ; offset = offset < 0 ? -offset : -offset - 1) {
245
236
  const found = changesAt(hunk, lines, hunk.at + offset)
237
+ // Where pnpm finds it, whatever its marks say, lest another place be shown changed than it changes.
238
+ if (found && !endsAgree(hunk, lines, hunk.at + offset)) throw doesNotApply()
246
239
  if (found) return found
247
240
  }
248
241
  throw doesNotApply()
@@ -262,23 +255,25 @@ function applied(text: string, hunks: PatchHunk[]): string {
262
255
  // A version's `files` with `patch` applied, in the order of their paths, as
263
256
  // its tarball's are read; a file it changes the text of must be text. One it
264
257
  // creates holds its first hunk's first lines, in place of any there, as
265
- // patch-package writes it.
258
+ // patch-package writes it. A file keeps its mode but where the patch says
259
+ // otherwise. A symlink, which pnpm never installs, is none to patch.
266
260
  export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): NpmPackageFile[] {
267
- const byPath = new Map(files.map(file => [file.path, file.bytes]))
261
+ const byPath = new Map(files.map(file => [file.path, file]))
268
262
  const encoder = new TextEncoder()
269
263
  for (const file of patch) {
270
264
  if (file.created) {
271
265
  const first = file.hunks[0]?.parts[0]
272
- byPath.set(file.path, encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''))
266
+ byPath.set(file.path, { path: file.path, bytes: encoder.encode(first ? `${first.lines.join('\n')}${first.unended ? '' : '\n'}` : ''),
267
+ ...file.executable ? { executable: true as const } : {} })
273
268
  continue
274
269
  }
275
270
  const source = file.from ?? file.path
276
- const bytes = byPath.get(source)
277
- if (!bytes) throw doesNotApply()
271
+ const was = byPath.get(source)
272
+ if (!was || was.link !== undefined) throw doesNotApply()
278
273
  if (file.deleted) { byPath.delete(source); continue }
279
- let next = bytes
274
+ let next = was.bytes
280
275
  if (file.hunks.length > 0) {
281
- const text = npmFileText(bytes)
276
+ const text = npmFileText(was.bytes)
282
277
  if (text === null) throw doesNotApply()
283
278
  next = encoder.encode(applied(text, file.hunks))
284
279
  }
@@ -286,9 +281,9 @@ export function patchedFiles(files: NpmPackageFile[], patch: PatchedFile[]): Npm
286
281
  if (byPath.has(file.path)) throw doesNotApply()
287
282
  byPath.delete(source)
288
283
  }
289
- byPath.set(file.path, next)
284
+ byPath.set(file.path, { path: file.path, bytes: next, ...(file.executable ?? was.executable) ? { executable: true as const } : {} })
290
285
  }
291
- return [...byPath].map(([path, bytes]) => ({ path, bytes })).toSorted((a, b) => pathOrder(a.path, b.path))
286
+ return [...byPath.values()].toSorted((a, b) => pathOrder(a.path, b.path))
292
287
  }
293
288
 
294
289
  // About the bytes a patch read takes: the characters of its paths and of the
@@ -1,10 +1,13 @@
1
1
  import { Buffer } from 'node:buffer'
2
2
  import { buildableEntry } from './bundle-build.ts'
3
3
  import { normalizeTeamPath } from './repo-path.ts'
4
- import { MAX_STASIS_CONFIG_BYTES, parseStasisConfig } from './stasis-config.ts'
4
+ import { type ConfigListing, MAX_STASIS_CONFIG_BYTES, configEntries, parseStasisConfig } from './stasis-config.ts'
5
5
 
6
6
  export const MAX_PACKAGE_BYTES = 256 * 1024
7
7
  const MAX_ENTRY_POINTS = 100
8
+ // The directories a stasis.config.json's patterns are matched in, at most,
9
+ // its own among them: past these, a pattern matches none of what is below.
10
+ const MAX_PATTERN_LISTINGS = 20
8
11
 
9
12
  // Declared paths, not a Node resolver: never guess defaults, expand export
10
13
  // patterns, or execute package code. Keep every suggestion in its package.
@@ -35,11 +38,54 @@ export function packageEntryPoints(manifest: unknown, directory: string): string
35
38
  return [...paths]
36
39
  }
37
40
 
41
+ type ListingEntry = { name?: unknown; path?: unknown; type?: unknown; sha?: unknown; submodule_git_url?: unknown }
42
+ type ListedName = { name: string; directory: boolean; sha: string | null }
43
+
44
+ const listingEntries = (listing: unknown): ListingEntry[] =>
45
+ Array.isArray(listing) ? listing.filter((entry): entry is ListingEntry => !!entry && typeof entry === 'object') : []
46
+ const listedName = (name: unknown, directory: boolean, sha: unknown): ListedName[] =>
47
+ typeof name !== 'string' || !name || name.includes('/') || name === '.' || name === '..' ? []
48
+ : [{ name, directory, sha: typeof sha === 'string' && /^[a-f\d]{40}$/iu.test(sha) ? sha : null }]
49
+
50
+ // The names of `directory` as its contents list them: each a directory's,
51
+ // with its tree, or a file's (a symlink's too). A submodule's are none.
52
+ const contentsNames = (listing: unknown, directory: string) => listingEntries(listing).flatMap(entry =>
53
+ entry.path !== (directory ? `${directory}/${String(entry.name)}` : entry.name) || entry.submodule_git_url ? []
54
+ : entry.type === 'dir' || ['file', 'symlink'].includes(entry.type as string) ? listedName(entry.name, entry.type === 'dir', entry.sha) : [])
55
+
56
+ // The names a tree lists, as contentsNames gives them.
57
+ const treeNames = (tree: unknown) => listingEntries(tree).flatMap(entry =>
58
+ entry.type === 'tree' || entry.type === 'blob' ? listedName(entry.path, entry.type === 'tree', entry.sha) : [])
59
+
60
+ // The directories under a stasis.config.json's, as its patterns are matched
61
+ // in them: its own as `listing`, its contents, names it, each below as the
62
+ // tree its parent's names, read once, at most MAX_PATTERN_LISTINGS of them.
63
+ // One past those, or whose tree can't be read, lists none.
64
+ function patternListings(directory: string, listing: unknown, read: (suffix: string) => Promise<unknown>): (path: string) => Promise<ConfigListing | null> {
65
+ const listed = new Map<string, Promise<ListedName[] | null>>([['', Promise.resolve(contentsNames(listing, directory))]])
66
+ const list = (path: string): Promise<ListedName[] | null> => {
67
+ const known = listed.get(path)
68
+ if (known) return known
69
+ const parent = path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
70
+ const name = path.slice(parent ? parent.length + 1 : 0)
71
+ const reading = listed.size >= MAX_PATTERN_LISTINGS ? Promise.resolve(null) : list(parent).then(async names => {
72
+ const tree = names?.find(entry => entry.name === name && entry.directory)?.sha
73
+ return tree ? treeNames((await read(`/git/trees/${tree}`) as { tree?: unknown } | null)?.tree) : null
74
+ }).catch(() => null)
75
+ listed.set(path, reading)
76
+ return reading
77
+ }
78
+ return list
79
+ }
80
+
38
81
  // The entries a stasis.config.json in `directory` lists, as repository paths:
39
- // the ones a server build takes, which it builds with their options there.
40
- export function configEntryPoints(text: string, directory: string): string[] {
82
+ // the ones a server build takes, which it builds with their options there. A
83
+ // pattern's are the files it matches, as `list` lists the directories below
84
+ // the file's ('' for its own).
85
+ export async function configEntryPoints(text: string, directory: string, list: (path: string) => Promise<ConfigListing | null> = () => Promise.resolve(null)): Promise<string[]> {
86
+ const config = parseStasisConfig(text, directory)
41
87
  const paths: string[] = []
42
- for (const key of parseStasisConfig(text, directory) ?? []) {
88
+ for (const key of config ? await configEntries(config, list) : []) {
43
89
  const path = directory ? `${directory}/${key}` : key
44
90
  if (buildableEntry(path) && paths.length < MAX_ENTRY_POINTS) paths.push(path)
45
91
  }
@@ -69,10 +115,12 @@ export async function readPackageEntryPoints(sha: string, directory: string, rea
69
115
 
70
116
  // A stasis.config.json whose entries Stasis can't tell lists none here;
71
117
  // building them reports why (config-invalid), as it does options Stasis refuses.
72
- export async function readConfigEntryPoints(sha: string, directory: string, read: (suffix: string) => Promise<unknown>): Promise<string[]> {
118
+ // Its patterns are matched in `listing`, the contents of its directory, and
119
+ // the trees below it.
120
+ export async function readConfigEntryPoints(sha: string, directory: string, read: (suffix: string) => Promise<unknown>, listing: unknown = []): Promise<string[]> {
73
121
  try {
74
122
  const text = await readBlobText(sha, read, MAX_STASIS_CONFIG_BYTES)
75
- return text === null ? [] : configEntryPoints(text, directory)
123
+ return text === null ? [] : await configEntryPoints(text, directory, patternListings(directory, listing, read))
76
124
  } catch {
77
125
  return []
78
126
  }
@@ -2,16 +2,19 @@
2
2
  // server's event loop by @preventive/compare's renamedDiffs: the old side given
3
3
  // the new side's names, not formatted again (each line where the old side's was),
4
4
  // diffed with whitespace changes shown and hidden, and the blocks checked to
5
- // take it to the new side. `{ before, blocks, reason, reads, marks,
5
+ // take it to the new side. `{ before, blocks, reason, reads, assumed, marks,
6
6
  // ignoringWhitespace }`: the old side as diffed, the change blocks, why the
7
7
  // old side is as it was where its names could not be given safely, the
8
8
  // properties through which either side reads names (a view marks renamed
9
9
  // lines rather than hiding them where any are read, as a rename may then
10
- // change what the code does), and the blocks of the diff of the files as they
11
- // are that differ in renamed names alone; `ignoringWhitespace` the blocks and
12
- // those marked with whitespace changes hidden, as diff -b hides them. Blocks
13
- // that would not take the old side to the new are thrown, and so answer
14
- // nothing.
10
+ // change what the code does), what a name renamed at a script's top level
11
+ // was taken as its own for (`module`, the other side being one; `minified`,
12
+ // a minifier having renamed them all), which it is not where the script runs
13
+ // as a classic one, its top level's names globals, and the blocks of the diff
14
+ // of the files as they are that differ in renamed names alone;
15
+ // `ignoringWhitespace` the blocks and those marked with whitespace changes
16
+ // hidden, as diff -b hides them. Blocks that would not take the old side to
17
+ // the new are thrown, and so answer nothing.
15
18
  import { parentPort, workerData } from 'node:worker_threads'
16
19
  import { renamedDiffs } from '@preventive/compare/names.js'
17
20
 
@@ -20,7 +23,8 @@ const diff = await renamedDiffs(before, after, { extension, otherExtension, whit
20
23
  // A check that should never fail did, or a step gave way: told, the file shown with its names.
21
24
  for (const warning of diff.warnings) console.warn(`managed: rename diff: ${warning}`)
22
25
  const [shown, hidden] = diff.diffs
23
- const answer = { before: diff.before, blocks: shown.blocks, reason: diff.reason, reads: diff.reads, marks: shown.marks, ignoringWhitespace: { blocks: hidden.blocks, marks: hidden.marks } }
26
+ const answer = { before: diff.before, blocks: shown.blocks, reason: diff.reason, reads: diff.reads, assumed: diff.assumed, marks: shown.marks,
27
+ ignoringWhitespace: { blocks: hidden.blocks, marks: hidden.marks } }
24
28
  // Node worker messages have no browser target origin.
25
29
  // oxlint-disable-next-line unicorn/require-post-message-target-origin
26
30
  parentPort.postMessage(answer)
@@ -4,7 +4,7 @@
4
4
  // has them (pretty-print.ts), then diffed by @preventive/compare's
5
5
  // renamedDiffs in a worker, off the event loop and two at a time per process,
6
6
  // with whitespace changes shown and hidden both. Answered as Brotli-encoded
7
- // JSON, `{ before, blocks, reason, reads, marks, ignoringWhitespace }`
7
+ // JSON, `{ before, blocks, reason, reads, assumed, marks, ignoringWhitespace }`
8
8
  // (rename-diff-worker.js), the two files' hashes, `hash` and `otherHash`, and
9
9
  // those of the two copies diffed, `prettyHash` and `otherPrettyHash`, which
10
10
  // the viewer checks are those it asked about and draws: one file's asked for
@@ -49,7 +49,7 @@ const KEPT_DIFFS = 32
49
49
  // `blocks` and `marks` with whitespace changes shown, `ignoringWhitespace`'s
50
50
  // hidden as diff -b hides them.
51
51
  export interface RenameDiff {
52
- before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; marks: ChangeBlock[]
52
+ before: string; blocks: ChangeBlock[]; reason: string | null; reads: string[]; assumed: string[]; marks: ChangeBlock[]
53
53
  ignoringWhitespace: { blocks: ChangeBlock[]; marks: ChangeBlock[] }
54
54
  }
55
55
 
@@ -77,8 +77,9 @@ const pending = new Map<string, Promise<Buffer>>()
77
77
  // changes shown and hidden: checked again here, apart from the worker, as an
78
78
  // answer that is not would hide a change.
79
79
  function answers(diff: unknown, original: string, after: string): diff is RenameDiff {
80
- const { before, blocks, reason, reads, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
- return typeof before === 'string' && (reason === null || typeof reason === 'string') && Array.isArray(reads) && reads.every(read => typeof read === 'string')
80
+ const { before, blocks, reason, reads, assumed, marks, ignoringWhitespace } = (diff ?? {}) as Partial<RenameDiff>
81
+ const strings = (list: unknown) => Array.isArray(list) && list.every(item => typeof item === 'string')
82
+ return typeof before === 'string' && (reason === null || typeof reason === 'string') && strings(reads) && strings(assumed)
82
83
  && blocksHold(before, after, blocks, false) && marksFit(original, after, marks)
83
84
  && blocksHold(before, after, ignoringWhitespace?.blocks, true) && marksFit(original, after, ignoringWhitespace?.marks)
84
85
  }