@preventive/triage 1.0.0-alpha.79 → 1.0.0-alpha.80

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 (60) hide show
  1. package/common/line-diff.d.ts +4 -0
  2. package/common/line-diff.js +72 -14
  3. package/common/managed/npm-packages.d.ts +2 -0
  4. package/common/managed/npm-packages.js +12 -0
  5. package/common/pretty-json.js +3 -0
  6. package/common/pretty-kinds.js +20 -0
  7. package/common/pretty-sourcemap.js +70 -0
  8. package/common/sourcemap-listing.js +78 -0
  9. package/common/sourcemap-mappings.js +136 -0
  10. package/common/sourcemap-unlist.js +85 -0
  11. package/out/activity.js +2 -2
  12. package/out/brotli-fallback.js +2 -2
  13. package/out/chunk-2XUEZHIP.js +1 -1
  14. package/out/{chunk-PLF4LBLE.js → chunk-5AVGKFMR.js} +1 -1
  15. package/out/{chunk-WB3NRZL7.js → chunk-5CJKUV53.js} +1 -1
  16. package/out/{chunk-6VXEPL32.js → chunk-5EAVJAD2.js} +1 -1
  17. package/out/{chunk-OWIBDEJJ.js → chunk-5M2X3QPK.js} +1 -1
  18. package/out/{chunk-26W3E5JE.js → chunk-5QWPKTCE.js} +1 -1
  19. package/out/chunk-74JZTGTO.js +1 -1
  20. package/out/{chunk-MKX6JODK.js → chunk-7YO4QV5P.js} +1 -1
  21. package/out/{chunk-EMNIV37E.js → chunk-DUS5ARE2.js} +1 -1
  22. package/out/{chunk-Z54AXVCK.js → chunk-GBMAXAYK.js} +2 -2
  23. package/out/chunk-GO7FT4OD.js +1 -1
  24. package/out/{chunk-V43XH2JQ.js → chunk-JXBRWLMA.js} +1 -1
  25. package/out/chunk-LBD3M3J6.js +1 -0
  26. package/out/chunk-MV66NL3G.js +3 -0
  27. package/out/chunk-N57OWFKY.js +15 -0
  28. package/out/{chunk-IIJK4F4U.js → chunk-OWSEQOL5.js} +1 -1
  29. package/out/chunk-PLGH63UC.js +2 -0
  30. package/out/{chunk-3S4YWYOM.js → chunk-PTFYDJUP.js} +1 -1
  31. package/out/chunk-QD3IBSF4.js +1 -1
  32. package/out/{chunk-ATT2QA77.js → chunk-VZPPX6MV.js} +1 -1
  33. package/out/chunk-YKCRCNYZ.js +266 -0
  34. package/out/client-managed-import.js +1 -1
  35. package/out/client-managed.js +1 -1
  36. package/out/client-sync.js +2 -2
  37. package/out/compare.js +13 -18
  38. package/out/dialogs.js +38 -38
  39. package/out/graph.js +3 -3
  40. package/out/index.html +11 -11
  41. package/out/prism.js +1 -1
  42. package/out/scan.js +2 -2
  43. package/out/terminal.js +167 -167
  44. package/out/view.js +8 -8
  45. package/package.json +14 -9
  46. package/risk/index.d.ts +3 -0
  47. package/risk/index.js +1 -1
  48. package/risk/npm/tarball.js +4 -4
  49. package/server-managed/http.ts +36 -80
  50. package/server-managed/npm-delta-worker.js +117 -44
  51. package/server-managed/npm-delta.ts +101 -22
  52. package/server-managed/npm-kept.ts +5 -0
  53. package/server-managed/npm-patch-paths.ts +29 -0
  54. package/server-managed/npm-patch.ts +11 -3
  55. package/out/chunk-4YZOXAXR.js +0 -2
  56. package/out/chunk-NTJJIEHS.js +0 -259
  57. package/out/chunk-PQPKHAI5.js +0 -15
  58. package/out/chunk-QBIUW5EF.js +0 -2
  59. package/out/chunk-XLX6XXJF.js +0 -1
  60. /package/out/{chunk-S5HSDGTP.js → chunk-DUASGS2O.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.79",
3
+ "version": "1.0.0-alpha.80",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -298,8 +298,10 @@
298
298
  "common/github-issue-labels.d.ts",
299
299
  "common/gzip.js",
300
300
  "common/pretty-json.js",
301
+ "common/pretty-kinds.js",
301
302
  "common/pretty-print.d.ts",
302
303
  "common/pretty-print.js",
304
+ "common/pretty-sourcemap.js",
303
305
  "common/line-diff.d.ts",
304
306
  "common/line-diff.js",
305
307
  "common/linked-workspace-groups.js",
@@ -342,6 +344,9 @@
342
344
  "common/scan-server.ts",
343
345
  "common/security-links.d.ts",
344
346
  "common/security-links.js",
347
+ "common/sourcemap-listing.js",
348
+ "common/sourcemap-mappings.js",
349
+ "common/sourcemap-unlist.js",
345
350
  "common/stasis-files.d.ts",
346
351
  "common/stasis-files.js",
347
352
  "common/stasis-tgz.d.ts",
@@ -442,27 +447,27 @@
442
447
  "esbuild": "^0.28.2",
443
448
  "lit": "^3.3.3",
444
449
  "minify-html-literals": "^1.3.5",
445
- "oxlint": "^1.93.0",
450
+ "oxlint": "^1.94.0",
446
451
  "prismjs": "^1.30.0",
447
452
  "stylelint": "^18.0.0",
448
453
  "stylelint-config-recommended": "^19.0.0",
449
454
  "typescript": "^7.0.2"
450
455
  },
451
456
  "dependencies": {
452
- "@exodus/stasis": "1.0.0-rc.10",
453
- "@exodus/stasis-core": "1.0.0-rc.10",
454
- "@preventive/archive": "^1.4.1",
455
- "@preventive/compare": "^1.3.0",
457
+ "@exodus/stasis": "1.0.0-rc.11",
458
+ "@exodus/stasis-core": "1.0.0-rc.11",
459
+ "@preventive/archive": "^1.5.0",
460
+ "@preventive/compare": "^1.4.0",
456
461
  "@preventive/diff": "^1.1.1",
457
462
  "@preventive/lockfile": "^1.3.1",
458
463
  "@preventive/publishers": "^1.1.0",
459
464
  "@preventive/report": "^1.0.1",
460
465
  "@preventive/sourcemap": "1.0.0-alpha.1",
461
- "@preventive/upstream": "^1.10.0",
466
+ "@preventive/upstream": "^1.12.0",
462
467
  "css-tree": "^3.2.1",
463
- "oxc-minify": "^0.158.0",
468
+ "oxc-minify": "^0.159.0",
464
469
  "oxc-parser": "^0.152.0",
465
- "oxfmt": "^0.78.0",
470
+ "oxfmt": "^0.79.0",
466
471
  "semver": "^7.8.6",
467
472
  "ws": "^8.23.0"
468
473
  },
package/risk/index.d.ts CHANGED
@@ -190,6 +190,9 @@ export function npmFileRisk(path: string, text: string | null, bytes?: number, s
190
190
  // How many levels up a package's symlinks may point: any (npm/tarball.js).
191
191
  export const NPM_SYMLINKS_ABOVE: number
192
192
 
193
+ // The folds macOS or Windows may take two paths as one under (npm/tarball.js).
194
+ export const NPM_PATH_FOLDS: readonly ((path: string) => string)[]
195
+
193
196
  // Every file a tar archive's entries hold, by package path, as npm and pnpm
194
197
  // lay them out (npm/tarball.js): each entry's name as stored past its first
195
198
  // component, whatever that is, and a file under no directory at its name, as
package/risk/index.js CHANGED
@@ -5,7 +5,7 @@ export { assessNpm } from './npm/assess.js'
5
5
  export { npmMalwareAdvisory } from './npm/malware.js'
6
6
  export { DEFAULT_MINIMUM_RELEASE_AGE } from './npm/release.js'
7
7
  export { NpmRiskError, npmReadyDownload, npmReadyDownloads } from './npm/registry.js'
8
- export { NPM_SYMLINKS_ABOVE, npmTarLayout } from './npm/tarball.js'
8
+ export { NPM_PATH_FOLDS, NPM_SYMLINKS_ABOVE, npmTarLayout } from './npm/tarball.js'
9
9
  export { SEVERITIES, npmFileRisk } from './files/stamps.js'
10
10
  export { ownFilesOf, scanWorkflow } from './actions/findings.js'
11
11
  export { dockerfileFindings, keptSource, resolveAction } from './actions/resolve.js'
@@ -42,7 +42,7 @@ const encoder = new TextEncoder()
42
42
  // either case and macOS normalized too, are one under some fold: NFC, lower,
43
43
  // upper, or lower then upper case, as JavaScript has no full case folding
44
44
  // (`ß` upper is `SS`, and `ẞ` lower is `ß`), then NFC again.
45
- const FOLDS = [path => path.normalize().toLowerCase().normalize(), path => path.normalize().toUpperCase().normalize(),
45
+ export const NPM_PATH_FOLDS = [path => path.normalize().toLowerCase().normalize(), path => path.normalize().toUpperCase().normalize(),
46
46
  path => path.normalize().toLowerCase().toUpperCase().normalize()]
47
47
 
48
48
  // Lays `file` at `path` in `tree`, each name a file or a directory's Map, so
@@ -76,13 +76,13 @@ function laidAt(tree, path, file, refuse) {
76
76
  // under `package/` there); and a file where another lies within it, as in a
77
77
  // directory (npm keeps the file, pnpm the directory). Unless `foldPaths` is
78
78
  // false, as for a repository's directory, so too where paths are one on macOS
79
- // or Windows (FOLDS), as `a.js` and `A.js` are; the same file at both is read
79
+ // or Windows (NPM_PATH_FOLDS), as `a.js` and `A.js` are; the same file at both is read
80
80
  // at both. Directories and devices hold no bytes of their own.
81
81
  // Past `maxFiles` files or `maxBytes` bytes, `package-too-large`.
82
82
  // `refuse(code)` throws.
83
83
  export function npmTarLayout(entries, { maxFiles, maxBytes, foldPaths = true }, refuse) {
84
84
  const files = new Map()
85
- // The paths laid out as a tree (laidAt), and again as folded (FOLDS).
85
+ // The paths laid out as a tree (laidAt), and again as folded (NPM_PATH_FOLDS).
86
86
  const root = new Map()
87
87
  const folded = new Map()
88
88
  // Each file by its name in the archive, which a hard link names.
@@ -95,7 +95,7 @@ export function npmTarLayout(entries, { maxFiles, maxBytes, foldPaths = true },
95
95
  named.set(name, file)
96
96
  const path = npmTarPath(storedName) || name
97
97
  if (laidAt(root, path, file, refuse) !== undefined) continue
98
- if (foldPaths) for (const fold of FOLDS) laidAt(folded, fold(path), file, refuse)
98
+ if (foldPaths) for (const fold of NPM_PATH_FOLDS) laidAt(folded, fold(path), file, refuse)
99
99
  files.set(path, file)
100
100
  total += file.bytes.length
101
101
  if (files.size > maxFiles || total > maxBytes) refuse('package-too-large')
@@ -157,10 +157,11 @@ import { pipeline } from 'node:stream/promises'
157
157
  import { setTimeout as delay } from 'node:timers/promises'
158
158
  import { type KeptStore, REPOSITORY_READ_KEPT_MS, authoredCommitStore, branchTipStore, bundleValidationStore, codeHeadStore, codeTreeStore, commitPullStore, githubTagStore, historyChangeStore, historyPageStore, historySquashStore, historyTreeStore,
159
159
  issueListStore, lockfileReadStore,
160
- npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, pullDependencyStore, pullListStore, repositoryReadStore, reviewBaselineStore, riskLineStore,
160
+ npmDeltaStore, npmPublishTimeStore, npmVersionDeltaStore, npmVersionStore, ownKeptPrunes, patchStore, privateVersionDeltaStore, pullDependencyStore, pullListStore, repositoryReadStore,
161
+ reviewBaselineStore, riskLineStore,
161
162
  scanReadStore, stasisDependencyStore, teamDependencyStore } from './npm-kept.ts'
162
163
  import { plainObject } from './npm-manifest.ts'
163
- import { type NpmDelta, deltaKey, keptNpmDeltas, keptVersionDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
164
+ import { type NpmDelta, countedDeltas, npmDelta, versionDeltaKey } from './npm-delta.ts'
164
165
  import { ADVISORIES_TIMEOUT_MS, fetchBundleAdvisories } from './bundle-advisories.ts'
165
166
  import { auditCache, auditedKeys, lastListing } from './upstream-cache.ts'
166
167
  import type { BundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
@@ -215,7 +216,6 @@ import { type Lru, lru } from './lru.ts'
215
216
  import { CALLBACK_PATH, LOGIN_PATH, OAuthError, buildLoginRedirect, cacheAvatar, ensureUserAccessToken, handleCallback } from './github-oauth.ts'
216
217
  import { clearCookie, endSession, handOverSession, readSession, runRequestPresence, sessionIds } from './session.ts'
217
218
  import { runTimed } from './request-timing.ts'
218
- import { isExactVersion } from '@preventive/upstream/semver.js'
219
219
  import { VIEW_AS_PATH, VIEW_ONLY_ERROR, clearViewCookie, endViewSession, runViewing, startViewSession, viewToken } from './view-as.ts'
220
220
  import type { ActivityContext, ActivityInput } from './activity.ts'
221
221
  import { acceptsReportMetadata } from './report-response.ts'
@@ -240,7 +240,7 @@ import { canDeleteComment, parseCommentBody } from '../common/managed/comments.t
240
240
  import { ManagedMutationError, reportReferenceSnapshot } from './management.ts'
241
241
  import { confirmedDefaultOffered, readConfirmedOffered, withConfirmedOffered } from './report-opening.ts'
242
242
  import { BundleBuildError, buildRepositoryBundle, buildRepositoryLockfile, parseBundleBuild, withBundleBuildLease } from './bundle-build.ts'
243
- import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, VERSION_KEPT_MS, canReadPrivateNpm, npmExecutablePaths, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
243
+ import { NpmPackageError, type NpmReader, type NpmVersionDocument, type NpmVersionStore, canReadPrivateNpm, npmExecutablePaths, npmFileRows, npmPublishTime, npmScopesCount, npmTarballFilename, readNpmVersion, readNpmVersions, readTogether } from './npm-packages.ts'
244
244
  import { loadNpmFiles, loadNpmPackageBody, loadNpmTarball } from './npm-loads.ts'
245
245
  import { type ReadPatch, type RequestedPatch, foundPatch, keptPatch, patchedFiles, readPatch, requestedPatch, withPatchFiles } from './npm-patch.ts'
246
246
  import { type RepositoryCodeKept, loadRepositoryCodeBody, repositoryCodeFits, repositoryCodeKept } from './repository-code.ts'
@@ -2907,7 +2907,7 @@ async function handleRepositoryLockfiles(res: ServerResponse, deps: ManagedHttpD
2907
2907
  // till then, with why the rest weren't (`pulls.error`; teamOpenPulls); each
2908
2908
  // line of
2909
2909
  // dependencies with the lines their versions wanting reviews change, where
2910
- // they are counted already (`deltas`, npm-delta.ts keptNpmDeltas), told
2910
+ // they are counted already (`deltas`, npm-delta.ts countedDeltas), told
2911
2911
  // before the rows asking for them are drawn. Last, `{ done: true
2912
2912
  // }`, or, its time up, `{ done: false, unread }`, the repositories left for
2913
2913
  // the reader to ask for again. The team's repositories, the reader's grants
@@ -3033,30 +3033,33 @@ async function handleTeamReviewChanges(req: IncomingMessage, res: ServerResponse
3033
3033
  }
3034
3034
 
3035
3035
  // What a team's Dependencies keeps of a repository it told whole to a
3036
- // reader (teamDependencyStore): its default branch's line, its pull
3036
+ // reader (teamDependencyStore): its default branch's line and its pull
3037
3037
  // requests' dependencies told (those GitHub failed left out, as still to be
3038
- // told), and the lines their versions change, each once. By the reader and
3039
- // their role, the repository, its review's setting, so that one set anew
3040
- // tells none kept before, and what was asked (`every`).
3041
- type KeptTeamRepository = { branch: object; pulls: object; dependencies: object[]; deltas: unknown[] }
3038
+ // told); not the lines their versions change, as those counted since are
3039
+ // told when it is (keptTeamLines). By the reader and their role, the
3040
+ // repository, its review's setting, so that one set anew tells none kept
3041
+ // before, and what was asked (`every`).
3042
+ type KeptTeamRepository = { branch: object; pulls: object; dependencies: object[] }
3042
3043
  const TEAM_KEPT_VERSION = 1
3043
3044
  const teamKeptKey = (user: StoredUser, repoId: number, setting: RepoDependencyReview, every: TeamEvery) =>
3044
3045
  JSON.stringify([TEAM_KEPT_VERSION, user.id, user.role, repoId, setting, every.branch, every.draft])
3045
3046
  const keptTeamStore = (deps: ManagedHttpDeps) => teamDependencyStore<KeptTeamRepository>(deps.db, deps.config.debug)
3046
3047
 
3047
3048
  // The lines kept of those of `reading` its reader was told whole before,
3048
- // one a repository, in one read of the database: `kept` when its read began.
3049
+ // one a repository, in one read of the database: `kept` when its read began;
3050
+ // each with the lines its versions change counted by now (withDeltas), those
3051
+ // its rows asked for since it was kept among them.
3049
3052
  async function keptTeamLines(deps: ManagedHttpDeps, reading: { access: WholeAccess; setting: RepoDependencyReview }[], every: TeamEvery): Promise<TeamDependencyLine[]> {
3050
3053
  if (reading.length === 0) return []
3051
3054
  const keys = reading.map(({ access, setting }) => teamKeptKey(access.user, access.repo.repoId, setting, every))
3052
3055
  const hits = await keptTeamStore(deps).readMany(keys)
3053
- return reading.flatMap(({ access }, at) => {
3056
+ return Promise.all(reading.flatMap(({ access }, at) => {
3054
3057
  const hit = hits.get(keys[at]!)
3055
3058
  const value = hit?.value as Partial<KeptTeamRepository> | undefined
3056
3059
  if (!hit || !plainObject(value?.branch) || !plainObject(value.pulls) || !Array.isArray(value.dependencies)) return []
3057
- return [{ repoId: access.repo.repoId, kept: hit.at, branch: value.branch, pulls: value.pulls, dependencies: value.dependencies,
3058
- ...Array.isArray(value.deltas) && value.deltas.length > 0 ? { deltas: value.deltas } : {} }]
3059
- })
3060
+ const { branch, pulls, dependencies } = value
3061
+ return [withDeltas(deps, [branch, ...dependencies]).then(deltas => ({ repoId: access.repo.repoId, kept: hit.at, branch, pulls, dependencies, ...deltas }))]
3062
+ }))
3060
3063
  }
3061
3064
 
3062
3065
  // The repository a read told `told` of, kept as told whole (KeptTeamRepository),
@@ -3067,11 +3070,7 @@ async function keepTeamRepository(deps: ManagedHttpDeps, key: string, told: Team
3067
3070
  const head = told.find(line => line['branch'] !== undefined || line['error'] !== undefined)
3068
3071
  if (!head?.['branch'] || !plainObject(head['pulls'])) { await store.remove(key); return }
3069
3072
  const dependencies = told.flatMap(line => Array.isArray(line['dependencies']) ? line['dependencies'] as { error?: unknown }[] : []).filter(answer => answer.error === undefined)
3070
- const deltas = new Map<string, unknown>()
3071
- for (const line of told) {
3072
- for (const delta of Array.isArray(line['deltas']) ? line['deltas'] as unknown[][] : []) deltas.set(JSON.stringify(delta.slice(0, 3)), delta)
3073
- }
3074
- await store.write(key, { branch: head['branch'] as object, pulls: head['pulls'], dependencies, deltas: [...deltas.values()] }, began)
3073
+ await store.write(key, { branch: head['branch'] as object, pulls: head['pulls'], dependencies }, began)
3075
3074
  }
3076
3075
 
3077
3076
  // A repository's lines of its team's Dependencies, as handleTeamDependencies
@@ -3207,60 +3206,9 @@ async function keptPullCommits(deps: ManagedHttpDeps, repoId: number, numbers: n
3207
3206
  return commits
3208
3207
  }
3209
3208
 
3210
- // The lines the versions wanting reviews of `answers` change, as their rows
3211
- // show them (npm-delta.js reviewBase), a patched one's none, where they are
3212
- // counted already: of public versions alone, kept by their names
3213
- // (npmVersionDeltaStore), else, those npm answered for in a day
3214
- // (npmVersionStore), by their integrities, as npmDelta keys them, then kept
3215
- // by their names too. `[name, version, base, delta]` each, none counted here,
3216
- // nor npm asked.
3217
- async function teamDeltas(deps: ManagedHttpDeps, answers: object[]) {
3218
- const asked = new Map<string, [string, string, string]>()
3219
- for (const answer of answers as { lockfiles?: { added?: unknown; unreviewed?: unknown }[]; review?: { required?: number; reviewedBases?: true } }[]) {
3220
- const required = answer.review?.required
3221
- if (!Number.isSafeInteger(required)) continue
3222
- for (const pkg of (answer.lockfiles ?? []).flatMap(dir => [...Array.isArray(dir.added) ? dir.added : [], ...Array.isArray(dir.unreviewed) ? dir.unreviewed : []]) as
3223
- { name?: unknown; version?: unknown; source?: unknown; was?: unknown; base?: { name?: unknown; version?: unknown }; reviews?: unknown; rejected?: unknown; baseline?: unknown
3224
- reviewed?: unknown; unsupported?: unknown; patch?: unknown }[]) {
3225
- if (pkg.source !== 'registry' || pkg.patch || typeof pkg.name !== 'string' || typeof pkg.version !== 'string' || !isExactVersion(pkg.version)) continue
3226
- if (pkg.unsupported || pkg.baseline || pkg.reviewed || typeof pkg.reviews !== 'number' || (pkg.reviews >= required! && !pkg.rejected)) continue
3227
- // Against the base the host names, where it names them; one of another package's not counted.
3228
- if (answer.review?.reviewedBases && pkg.base && pkg.base.name !== pkg.name) continue
3229
- const was = answer.review?.reviewedBases ? pkg.base?.version as string | undefined
3230
- : Array.isArray(pkg.was) ? pkg.was.find(prior => typeof prior === 'string' && prior !== pkg.version) as string | undefined : undefined
3231
- asked.set(`${pkg.name}\0${pkg.version}\0${was ?? '(empty)'}`, [pkg.name, pkg.version, was ?? '(empty)'])
3232
- }
3233
- }
3234
- if (asked.size === 0) return []
3235
- const byVersions = npmVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug)
3236
- const named = await keptVersionDeltas([...asked.values()].map(([name, version, base]) => versionDeltaKey(name, version, name, base)), byVersions)
3237
- const told = [...asked.values()].flatMap(([name, version, base]) => {
3238
- const delta = named.get(versionDeltaKey(name, version, name, base))
3239
- return delta ? [[name, version, base, delta] as const] : []
3240
- })
3241
- for (const [key, [name, version, base]] of [...asked]) if (named.has(versionDeltaKey(name, version, name, base))) asked.delete(key)
3242
- if (asked.size === 0) return told
3243
- const versions = [...asked.values()].flatMap(([name, version, base]) => [{ name, version }, ...base === '(empty)' || !isExactVersion(base) ? [] : [{ name, version: base }]])
3244
- const kept = await npmVersionStore(deps.db, deps.config.debug).readMany!(versions)
3245
- const integrity = (name: string, version: string) => {
3246
- const hit = kept.get(`${name}@${version}`)
3247
- const dist = hit && Date.now() - hit.at < VERSION_KEPT_MS ? hit.json['dist'] : null
3248
- return plainObject(dist) && typeof dist['integrity'] === 'string' ? dist['integrity'] : null
3249
- }
3250
- const sides = [...asked.values()].flatMap(([name, version, base]) => {
3251
- const against = base === '(empty)' ? null : integrity(name, base), other = integrity(name, version)
3252
- return other && (base === '(empty)' || against) ? [{ name, version, base, key: [against, other] as [string | null, string] }] : []
3253
- })
3254
- if (sides.length === 0) return told
3255
- const counted = await keptNpmDeltas(sides.map(({ key }) => key), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
3256
- const byIntegrity = sides.flatMap(({ name, version, base, key: [against, other] }) => {
3257
- const delta = counted.get(deltaKey(against, other))
3258
- return delta ? [[name, version, base, delta] as const] : []
3259
- })
3260
- // Kept by their names too, as those npm told of are public, for a later read past the day.
3261
- await Promise.all(byIntegrity.map(([name, version, base, delta]) => byVersions.write(versionDeltaKey(name, version, name, base), delta, Date.now())))
3262
- return [...told, ...byIntegrity]
3263
- }
3209
+ // The lines the versions wanting reviews of `answers` change, where they are
3210
+ // counted already (npm-delta.ts countedDeltas), none counted here, nor npm asked.
3211
+ const teamDeltas = (deps: ManagedHttpDeps, answers: object[]) => countedDeltas(deps.db, answers, deps.config.debug)
3264
3212
 
3265
3213
  // The app's users `accounts` are, by their logins in lower case, of those
3266
3214
  // who publish reviews to a team counting for repository `repoId`.
@@ -4050,6 +3998,8 @@ async function tellOfBundle(res: ServerResponse, deps: ManagedHttpDeps, session:
4050
3998
  // one whose repository reviews none, and for a reader who may read only some
4051
3999
  // of it, as a team's Dependencies tab leaves such a one out; the bundle's
4052
4000
  // access checked again before it is told, and its repository not moved.
4001
+ // With the lines its versions wanting reviews change, where they are counted
4002
+ // already (`deltas`, teamDeltas).
4053
4003
  async function handleBundleDependencyReview(res: ServerResponse, deps: ManagedHttpDeps, cookie: string | undefined, session: ManagedSession, id: string) {
4054
4004
  const record = await readableBundle(res, deps, session, id)
4055
4005
  if (!record) return
@@ -4079,7 +4029,8 @@ async function handleBundleDependencyReview(res: ServerResponse, deps: ManagedHt
4079
4029
  const read = await readWholeRepositoryOf(deps, access, (fullName, token, user) => bundleDependencyAnswer(deps, fullName, token, user, repoId, setting,
4080
4030
  { commit: commit!, directory: record.repoDirectory, bundled }), () => wholeRepositoryAccess(deps, cookie, repoId))
4081
4031
  if ('error' in read) { sendRefusal(res, read); return }
4082
- await tellOfBundle(res, deps, session, id, record, await withAppUsers(deps.db, read.value))
4032
+ // With the lines its versions wanting reviews change, those counted already, as a team's Dependencies tells them.
4033
+ await tellOfBundle(res, deps, session, id, record, await withAppUsers(deps.db, { ...read.value, ...await withDeltas(deps, [read.value]) }))
4083
4034
  }
4084
4035
 
4085
4036
  // A bundle's answer, as GET /api/bundles/:id/dependency-review gives it, and
@@ -5498,8 +5449,9 @@ async function handleNpmReviews(req: IncomingMessage, res: ServerResponse, deps:
5498
5449
  // DELTAS_AT_ONCE at a time. Each read as GET delta reads it, with the
5499
5450
  // reader's access to each package, which is checked again once it is
5500
5451
  // counted: a private one's told only to a reader who may still read it,
5501
- // none told to one whose session is gone. Each of two public versions,
5502
- // unpatched, kept by their names too (npmVersionDeltaStore), for a team's
5452
+ // none told to one whose session is gone. Each kept by its versions' names
5453
+ // too, a patched one's with its patch's hash (npmVersionDeltaStore, and
5454
+ // privateVersionDeltaStore where either is private), for a team's
5503
5455
  // Dependencies to tell it without asking npm of them (teamDeltas).
5504
5456
  const MAX_ASKED_DELTAS = 50
5505
5457
  const DELTAS_AT_ONCE = 2
@@ -5528,7 +5480,7 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
5528
5480
  res.once('close', () => { if (!res.writableEnded) controller.abort() })
5529
5481
  dropIdle(res)
5530
5482
  const kept = npmDeltaStore<NpmDelta>(deps.db, deps.config.debug), keptVersions = npmVersionStore(deps.db, deps.config.debug)
5531
- const byVersions = npmVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug)
5483
+ const byVersions = npmVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug), privately = privateVersionDeltaStore<NpmDelta>(deps.db, deps.config.debug)
5532
5484
  const out = openLines(res)
5533
5485
  let stopped = false
5534
5486
  await eachOf(versions, DELTAS_AT_ONCE, async ([name, version, otherVersion, patch, otherName]) => {
@@ -5547,8 +5499,12 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
5547
5499
  if (patched && 'error' in patched) line = { ...asOne, error: patched.error, status: patched.status }
5548
5500
  else {
5549
5501
  const delta = await npmDelta(old ? deltaSide(old, deps.npmCacheStorage) : null,
5550
- patched ? { integrity: `${side.integrity} patch:${patch.hash}`, files: async () => patchedFiles(await side.files(), patched.files) } : side, kept)
5551
- if (!patched && !doc.private && !old?.private) await byVersions.write(versionDeltaKey(doc.name, doc.version, old?.name ?? name, old?.version ?? '(empty)'), delta, Date.now())
5502
+ patched ? { integrity: `${side.integrity} patch:${patch.hash}`, files: async () => patchedFiles(await side.files(), patched.files) } : side, kept,
5503
+ !patched && otherName === name)
5504
+ if (!delta.partial) {
5505
+ await (doc.private || old?.private ? privately : byVersions).write(versionDeltaKey(doc.name, doc.version, old?.name ?? name, old?.version ?? '(empty)',
5506
+ patch && patched ? patch.hash : null), delta, Date.now())
5507
+ }
5552
5508
  line = { ...asOne, ...delta }
5553
5509
  }
5554
5510
  } catch (err) {
@@ -1,69 +1,142 @@
1
- // The lines a package's files change from one side to another (npm-delta.ts),
2
- // as @preventive/compare's compareTrees counts them (git's --numstat), off
3
- // the server's event loop: of its text files, renames found as git finds
4
- // them, a side not there empty; and each file's fewest (`best`), as Compare
5
- // can draw it: as published, without type-only and whitespace changes, or
6
- // pretty-printed too: by Compare's copies where kept (`copies`), else made and
7
- // told (`made`), as `complete` where none was left for want of time.
1
+ // The lines a package's files change (npm-delta.ts), off the event loop, paired as Compare pairs them (rename-diff.ts
2
+ // comparedFiles); and each file's fewest (`best`): the least of the diffs Compare draws of it (drawn), one per setting of
3
+ // its toggles the comparison has (`proves` types, `prints` code), those needing proofs or copies smallest first.
8
4
  import { parentPort, workerData } from 'node:worker_threads'
9
- import { compareTrees } from '@preventive/compare'
10
- import { changeBlocks, indentHiddenBlocks, withSharedBlankLines } from '../common/line-diff.js'
11
- import { jsonPrinted, prettyJsonText } from '../common/pretty-json.js'
5
+ import { treeLayout } from '@preventive/compare'
6
+ import { renamedDiff } from '@preventive/compare/names.js'
7
+ import { hidesMixedWhitespace } from '@preventive/compare/view.js'
8
+ import { computeBundleDiff } from '../common/bundle-compare-diff.js'
9
+ import { bundlePkgOf } from '../common/bundle-pkg-of.js'
10
+ import { blocksHold, changeBlocks, diffSize, isLargeDiff, markedCounts, textLines, typeFolds, withSharedBlankLines } from '../common/line-diff.js'
11
+ import { viewerKind, viewerPrintable } from '../common/pretty-kinds.js'
12
12
  import { prettyExtension, printableSize } from '../common/pretty-print.js'
13
13
  import { whitespaceInsensitive } from '../common/whitespace-insensitive.js'
14
+ import { npmFileReadability } from '../risk/files/readability.js'
14
15
  import { prettyFormat } from './pretty-format.js'
16
+ import { typeOnlyRuns, typeOnlyStamped } from './type-only-proof.js'
15
17
 
16
- const { base, copies, other, prettyUntil } = workerData
18
+ const { base, copies, other, prettyUntil, prints, proves } = workerData
17
19
  const kept = new Map(copies.map(([at, path, copy]) => [`${at}\0${path}`, copy])), made = []
18
20
  const NONE = { additions: 0, deletions: 0 }
19
21
  const least = (a, b) => (b.additions < a.additions || (b.additions === a.additions && b.deletions < a.deletions) ? b : a)
20
- const counted = (before, after, insensitive) => (insensitive ? indentHiddenBlocks(before, after) : changeBlocks(before, after))
21
- .reduce((sum, { a0, a1, b0, b1 }) => ({ additions: sum.additions + b1 - b0, deletions: sum.deletions + a1 - a0 }), NONE)
22
+ // Node worker messages have no browser target origin.
23
+ // oxlint-disable-next-line unicorn/require-post-message-target-origin
24
+ const tell = told => parentPort.postMessage(told)
25
+ const TYPESCRIPT = new Set(['ts', 'mts', 'cts'])
26
+ const RENAMABLE = /\.[cm]?js$/iu
27
+ const minified = (path, text) => text !== '' && npmFileReadability(path, text).category === 'minified'
28
+ const once = (file, key, make) => {
29
+ if (!file.memo.has(key)) file.memo.set(key, make())
30
+ return file.memo.get(key)
31
+ }
32
+
33
+ // As _fileState's diffed: indentation set aside where `ws`, but not where that hides blanks of more than one kind
34
+ // changing; the server's `blocks` where given, those of `marks` counted apart.
35
+ function diffed(file, key, before, after, ws, { blocks = null, marks = null } = {}) {
36
+ return once(file, `${key}\0${ws}`, () => {
37
+ let found = ws || !blocks ? changeBlocks(before, after, ws && 'leading') : blocks
38
+ if (ws && hidesMixedWhitespace(before, after, found)) found = blocks ?? changeBlocks(before, after)
39
+ return { blocks: found, ...markedCounts(found, marks) }
40
+ })
41
+ }
22
42
 
23
- // A side's file (`at` 0 the base, 1 the other) as Compare's pretty-print toggle prints it, or null.
24
- async function printed(at, path, text) {
25
- const copy = kept.get(`${at}\0${path}`)
26
- if (copy) return copy
43
+ // A side's file as Compare's toggle prints it in `layout`: as the viewer prints its kind (pretty-kinds.js), else
44
+ // as the server copies code where the comparison has copies; null where it can't be.
45
+ async function copyOf(at, path, text, layout) {
46
+ if (text === '') return { text, blank: [] }
47
+ const kind = viewerKind(path)
27
48
  try {
28
- if (!printableSize(text)) return null
29
- const extension = prettyExtension(path), json = jsonPrinted(path) ? prettyJsonText(text, { width: 0 }) : null
30
- if (json !== null) return { text: json, blank: [] }
31
- const result = extension && await prettyFormat(text, extension)
32
- if (!result || 'error' in result) return null
33
- made.push([at, path, result])
34
- return result
49
+ if (kind) return viewerPrintable(kind, text) ? { text: kind.copy(text, layout), blank: [] } : null
50
+ if (!prints || prettyExtension(path) === null || !printableSize(text)) return null
51
+ const known = kept.get(`${at}\0${path}`)
52
+ const copy = known ?? await prettyFormat(text, prettyExtension(path))
53
+ if ('error' in copy) return null
54
+ if (!known) made.push([at, path, copy])
55
+ return copy
35
56
  } catch {
36
57
  return null
37
58
  }
38
59
  }
39
60
 
40
- const tree = files => files.map(([name, data]) => ({ name, data }))
41
- const best = { ...NONE }, printing = [], total = { ...NONE }
42
- for (const change of compareTrees(tree(base), tree(other), { paths: 'keys', lines: true, renames: true })) {
43
- if (change.binary) continue
44
- const published = { additions: change.insertions ?? 0, deletions: change.deletions ?? 0 }
45
- const after = change.new?.data ?? '', before = change.old?.data ?? ''
46
- const insensitive = before !== '' && after !== '' && whitespaceInsensitive(change.old.path, before) && whitespaceInsensitive(change.new.path, after)
47
- // Additions less deletions is the same for any diff, so one with none of either is at its least.
48
- const fewest = change.typeOnly ? NONE : insensitive && published.additions && published.deletions ? least(published, counted(before, after, true)) : published
61
+ // As _printing: a file's sides printed and drawn (_drawn), where Compare's toggle applies to it (a kind the viewer
62
+ // prints always, else either side minified, or its copies' diff smaller as drawn: _smaller); null where it doesn't.
63
+ async function printingOf(file, layout, ws) {
64
+ const sides = [[0, file.basePath, file.before], [1, file.path, file.after]]
65
+ const kinds = sides.filter(([, , text]) => text !== '').map(([, path]) => viewerKind(path))
66
+ const viewed = kinds.every(kind => kind && kind === kinds[0])
67
+ const unreadable = !viewed && sides.some(([, path, text]) => minified(path, text))
68
+ if (!viewed && !unreadable && (file.before === '' || file.after === '')) return null
69
+ const copy = ([at, path, text]) => once(file, `copy\0${layout}\0${at}`, () => copyOf(at, path, text, layout))
70
+ const a = await copy(sides[0]), b = a && await copy(sides[1])
71
+ if (!a || !b) return null
72
+ const shown = file.generated ? { before: a.text, after: b.text } : withSharedBlankLines(a.text, b.text, a.blank, b.blank)
73
+ if (viewed || unreadable) return { ...shown, kind: viewed && kinds[0], copies: [a.text, b.text] }
74
+ if (isLargeDiff(file.before, file.after) || isLargeDiff(shown.before, shown.after)) return null
75
+ const mode = ws && 'leading', now = diffSize(shown.before, shown.after, mode), was = diffSize(file.before, file.after, mode)
76
+ return now.lines < was.lines || (now.lines === was.lines && now.marks < was.marks) ? shown : null
77
+ }
78
+
79
+ // The diff Compare draws of a file with its toggles so (_fileState): whitespace hidden (`ws`), type-only changes
80
+ // (`types`), renamed names (`renames`), printed in `layout` or not (null); null where it draws none.
81
+ async function drawn(file, { ws, types, layout, renames }) {
82
+ const proof = types ? (file.stamped || once(file, 'runs', () => typeOnlyRuns(file.from, file.to))) : null
83
+ if (proof === true) return NONE
84
+ const folds = proof && once(file, 'folds', () => typeFolds(file.before, file.after, proof))
85
+ if (folds) return diffed(file, 'folds', folds.before, folds.after, ws)
86
+ const printing = layout && await once(file, `printing\0${layout}\0${ws}`, () => printingOf(file, layout, ws))
87
+ if (!printing) return diffed(file, 'texts', file.before, file.after, ws)
88
+ if (file.generated) {
89
+ const diff = await once(file, `renamed\0${layout}`, () => renamedDiff(printing.before, printing.after,
90
+ { extension: prettyExtension(file.basePath), otherExtension: prettyExtension(file.path) }).catch(() => null))
91
+ if (renames) return diff && blocksHold(diff.before, printing.after, diff.blocks) ? diffed(file, `hidden\0${layout}`, diff.before, printing.after, ws, { blocks: diff.blocks }) : null
92
+ if (diff) return diffed(file, `marked\0${layout}`, printing.before, printing.after, ws, { marks: diff.marks })
93
+ }
94
+ const found = diffed(file, `printed\0${layout}`, printing.before, printing.after, ws)
95
+ // Drawn as published where its kind refuses the diff of its copies (comparedListingRefusal).
96
+ const refused = printing.kind?.refusal?.({ a: textLines(printing.before), b: textLines(printing.after), blocks: found.blocks }, [file.before, file.after], printing.copies)
97
+ return refused == null ? found : diffed(file, 'texts', file.before, file.after, ws)
98
+ }
99
+
100
+ // Each setting of Compare's toggles that may draw a file otherwise.
101
+ const SETTINGS = [false, true].flatMap(ws => [false, true].flatMap(types => [null, 'indented', 'folded'].flatMap(layout => [false, true].map(renames => ({ ws, types, layout, renames })))))
102
+ const settingsOf = file => SETTINGS.filter(({ ws, types, layout, renames }) => (!ws || file.insensitive) && (!types || file.ts)
103
+ && (layout !== 'folded' || file.layouts) && (!renames || (layout && file.generated)))
104
+
105
+ const [olds, news] = [new Map(base), new Map(other)]
106
+ const { files } = computeBundleDiff(olds, news, path => bundlePkgOf(path), treeLayout(olds.keys(), news.keys()))
107
+ const best = { ...NONE }, later = [], total = { ...NONE }
108
+ for (const { path, basePath = path, side } of [...files.changed, ...files.onlyBase.map(row => ({ ...row, side: 0 })), ...files.onlyOther.map(row => ({ ...row, side: 1 }))]) {
109
+ const after = side === 0 ? '' : news.get(path), before = side === 1 ? '' : olds.get(basePath)
110
+ if (typeof before !== 'string' || typeof after !== 'string' || before === after) continue
111
+ const from = side === 1 ? null : { path: basePath, text: before }, to = side === 0 ? null : { path, text: after }
112
+ const ts = proves && [from, to].every(file => !file || TYPESCRIPT.has(prettyExtension(file.path)))
113
+ const file = { path, basePath, before, after, from, to, ts, stamped: ts && typeOnlyStamped(from, to), memo: new Map(),
114
+ insensitive: whitespaceInsensitive(path, after) && whitespaceInsensitive(basePath, before), layouts: [path, basePath].some(name => viewerKind(name)?.layouts),
115
+ generated: prints && RENAMABLE.test(path) && RENAMABLE.test(basePath) && minified(basePath, before) && minified(path, after) }
116
+ const published = diffed(file, 'texts', before, after, false)
117
+ // Additions less deletions is the same for any diff of two texts, so hiding whitespace can't lower one adding or removing none.
118
+ const fewest = file.stamped ? NONE : file.insensitive && published.additions && published.deletions ? least(published, diffed(file, 'texts', before, after, true)) : published
49
119
  for (const [sum, count] of [[total, published], [best, fewest]]) {
50
120
  sum.additions += count.additions
51
121
  sum.deletions += count.deletions
52
122
  }
53
- // Compare prints a file one side alone has only where that lengthens it.
54
- if (fewest.additions + fewest.deletions > 0 && before !== '' && after !== '') printing.push({ from: change.old.path, to: change.new.path, before, after, insensitive, fewest })
123
+ const printable = [basePath, path].some(name => viewerKind(name) || (prints && prettyExtension(name) !== null))
124
+ if (fewest !== NONE && (ts || printable)) later.push({ ...file, fewest, size: before.length + after.length })
55
125
  }
56
- // Smallest first, so the time left goes to the most files.
126
+ const count = complete => ({ ...total, best, complete })
127
+ tell({ sofar: count(false) })
128
+
57
129
  let complete = true
58
- for (const file of printing.toSorted((a, b) => a.before.length + a.after.length - b.before.length - b.after.length)) {
130
+ for (const file of later.toSorted((a, b) => a.size - b.size)) {
59
131
  if (Date.now() >= prettyUntil) { complete = false; break }
60
- const [a, b] = [await printed(0, file.from, file.before), await printed(1, file.to, file.after)]
61
- if (a === null || b === null) continue
62
- const { before, after } = withSharedBlankLines(a.text, b.text, a.blank, b.blank)
63
- const now = least(file.fewest, counted(before, after, file.insensitive))
132
+ let now = file.fewest
133
+ for (const setting of settingsOf(file)) {
134
+ const counts = await drawn(file, setting)
135
+ if (counts) now = least(now, counts)
136
+ }
137
+ if (now === file.fewest) continue
64
138
  best.additions += now.additions - file.fewest.additions
65
139
  best.deletions += now.deletions - file.fewest.deletions
140
+ tell({ sofar: count(false) })
66
141
  }
67
- // Node worker messages have no browser target origin.
68
- // oxlint-disable-next-line unicorn/require-post-message-target-origin
69
- parentPort.postMessage({ ...total, best, complete, made })
142
+ tell({ ...count(complete), made })