@preventive/triage 1.0.0-alpha.76 → 1.0.0-alpha.78

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 (64) hide show
  1. package/common/code-language.js +3 -2
  2. package/common/line-diff.d.ts +2 -0
  3. package/common/line-diff.js +54 -0
  4. package/common/managed/dependency-routes.js +25 -0
  5. package/common/managed/routes.js +9 -12
  6. package/common/pretty-json.js +95 -0
  7. package/common/pretty-print.d.ts +1 -0
  8. package/common/pretty-print.js +6 -0
  9. package/common/whitespace-insensitive.js +19 -0
  10. package/out/activity.js +2 -2
  11. package/out/{chunk-OCE6KQGJ.js → chunk-26W3E5JE.js} +1 -1
  12. package/out/chunk-3S4YWYOM.js +1 -0
  13. package/out/{chunk-OQS2USZM.js → chunk-55YIWY3H.js} +1 -1
  14. package/out/{chunk-IVDE66N5.js → chunk-6VXEPL32.js} +1 -1
  15. package/out/{chunk-XVKDPU4D.js → chunk-6Y6PZ2BU.js} +1 -1
  16. package/out/{chunk-HLMQ7QYS.js → chunk-ATT2QA77.js} +1 -1
  17. package/out/{chunk-2V6Q4ZOZ.js → chunk-B64CTMVU.js} +1 -1
  18. package/out/{chunk-EXQQ5VQJ.js → chunk-BEKYZCPX.js} +1 -1
  19. package/out/{chunk-EYTPAODY.js → chunk-BGLN56X6.js} +1 -1
  20. package/out/{chunk-S2ZIKK45.js → chunk-EEJA7JBI.js} +1 -1
  21. package/out/{chunk-O6FA2R5G.js → chunk-EMNIV37E.js} +1 -1
  22. package/out/{chunk-4IW3VD3H.js → chunk-FSU2PLJL.js} +1 -1
  23. package/out/{chunk-MFAB7P3T.js → chunk-I4YPK32I.js} +1 -1
  24. package/out/{chunk-I6UQQKAH.js → chunk-LVSLM7HB.js} +1 -1
  25. package/out/{chunk-T6EXDRB7.js → chunk-MKX6JODK.js} +1 -1
  26. package/out/{chunk-24LZZYAP.js → chunk-NCJQDKPK.js} +1 -1
  27. package/out/chunk-O2NYWLX3.js +259 -0
  28. package/out/{chunk-62QT2RXR.js → chunk-OWIBDEJJ.js} +1 -1
  29. package/out/{chunk-NEFCZAIY.js → chunk-PKLVXUEI.js} +1 -1
  30. package/out/chunk-QBIUW5EF.js +2 -0
  31. package/out/{chunk-ADMVRLNP.js → chunk-QD3IBSF4.js} +1 -1
  32. package/out/{chunk-GSNSP3EF.js → chunk-RPNO56H2.js} +1 -1
  33. package/out/{chunk-QBFT2DDR.js → chunk-UR4WYMIP.js} +1 -1
  34. package/out/{chunk-UH6NZBSU.js → chunk-VHEXSGGP.js} +1 -1
  35. package/out/{chunk-RHOQDAU4.js → chunk-WB3NRZL7.js} +1 -1
  36. package/out/chunk-XLX6XXJF.js +1 -0
  37. package/out/{chunk-BXQCCW7F.js → chunk-XM4RLC4A.js} +1 -1
  38. package/out/client-managed-import.js +1 -1
  39. package/out/client-managed.js +2 -2
  40. package/out/compare.js +14 -14
  41. package/out/dialogs.js +22 -22
  42. package/out/graph.js +1 -1
  43. package/out/index.html +11 -9
  44. package/out/prism.js +1 -1
  45. package/out/scan.js +2 -2
  46. package/out/terminal.js +7 -7
  47. package/out/view.css +1 -1
  48. package/out/view.js +8 -8
  49. package/package.json +8 -2
  50. package/server-managed/dependency-review-comments.ts +35 -27
  51. package/server-managed/http.ts +13 -11
  52. package/server-managed/npm-delta-worker.js +58 -12
  53. package/server-managed/npm-delta.ts +52 -28
  54. package/server-managed/pretty-copies.ts +22 -0
  55. package/server-managed/pretty-format.d.ts +3 -0
  56. package/server-managed/pretty-format.js +13 -0
  57. package/server-managed/pretty-print.ts +34 -24
  58. package/server-managed/public-workspace.ts +1 -1
  59. package/server-managed/pull-dependency-reviews.ts +23 -12
  60. package/out/chunk-JCIIBLKR.js +0 -1
  61. package/out/chunk-UZC7POI4.js +0 -255
  62. package/out/chunk-W5PRH5D7.js +0 -2
  63. package/out/chunk-WGQ7D5DB.js +0 -1
  64. /package/out/{chunk-Z667U2UJ.js → chunk-SZWPYLPC.js} +0 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@preventive/triage",
3
- "version": "1.0.0-alpha.76",
3
+ "version": "1.0.0-alpha.78",
4
4
  "description": "Client & relay server for triaging of automated reports",
5
5
  "license": "MIT OR Apache-2.0",
6
6
  "author": {
@@ -173,6 +173,9 @@
173
173
  "server-managed/npm-patch-paths.ts",
174
174
  "server-managed/npm-patch.ts",
175
175
  "server-managed/package-entry-points.ts",
176
+ "server-managed/pretty-copies.ts",
177
+ "server-managed/pretty-format.d.ts",
178
+ "server-managed/pretty-format.js",
176
179
  "server-managed/pretty-print.ts",
177
180
  "server-managed/pull-reviews.ts",
178
181
  "server-managed/rename-diff.ts",
@@ -294,6 +297,7 @@
294
297
  "common/github-issue-labels.js",
295
298
  "common/github-issue-labels.d.ts",
296
299
  "common/gzip.js",
300
+ "common/pretty-json.js",
297
301
  "common/pretty-print.d.ts",
298
302
  "common/pretty-print.js",
299
303
  "common/line-diff.d.ts",
@@ -301,6 +305,7 @@
301
305
  "common/linked-workspace-groups.js",
302
306
  "common/managed/agent-tasks.ts",
303
307
  "common/managed/comments.ts",
308
+ "common/managed/dependency-routes.js",
304
309
  "common/managed/directory-packages.ts",
305
310
  "common/managed/finding-detail.d.ts",
306
311
  "common/managed/finding-detail.js",
@@ -343,6 +348,7 @@
343
348
  "common/stasis-tgz.js",
344
349
  "common/utf8.d.ts",
345
350
  "common/utf8.js",
351
+ "common/whitespace-insensitive.js",
346
352
  "common/workspace-app.js",
347
353
  "common/workspace-groups.js",
348
354
  "risk/index.js",
@@ -446,7 +452,7 @@
446
452
  "@exodus/stasis": "1.0.0-rc.10",
447
453
  "@exodus/stasis-core": "1.0.0-rc.10",
448
454
  "@preventive/archive": "^1.4.1",
449
- "@preventive/compare": "^1.2.14",
455
+ "@preventive/compare": "^1.3.0",
450
456
  "@preventive/diff": "^1.1.1",
451
457
  "@preventive/lockfile": "^1.3.1",
452
458
  "@preventive/publishers": "^1.1.0",
@@ -11,7 +11,7 @@
11
11
  import type { DependencyReview, DependencyReviewStore } from './dependency-reviews.ts'
12
12
  import type { LockedPackage } from './locked-packages.ts'
13
13
  import type { PullDependencies } from './pull-dependencies.ts'
14
- import { askedOf, basesOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
14
+ import { ACCEPTING, askedOf, basesOf, comparedWith, latestOf, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
15
15
  import { eachOf } from './queue.ts'
16
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
17
17
  import { type DependencyReviewEntry, type ReviewedBase, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
@@ -66,25 +66,31 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
66
66
  })
67
67
  }
68
68
 
69
- // Those of `reviews` `user` published of the versions `told` adds, by their
70
- // ids, each with the versions it is of, as its lockfiles lock each: of its
71
- // version, of an integrity it is locked with and of its patch, whole,
69
+ // `user`'s review of each version `told` adds that stands for them on it, as
70
+ // its lockfiles lock each, of `reviews` of its version, of an integrity it is
71
+ // locked with and of its patch (pull-dependency-reviews.ts reviewsOf,
72
+ // stancesOf), by their ids, each with the versions it is given of: their
73
+ // latest of it alone, where it is compared with what it may be, whole,
72
74
  // compared with another package's version, or compared with a version it was
73
- // or the base the host names it (`bases`; pull-dependency-reviews.ts reviewsOf,
74
- // comparedWith, basesOf), or, `any`, with any version of its package.
75
+ // or the base the host names it (`bases`; comparedWith, basesOf), or, `any`,
76
+ // with any version of its package. Else their latest of it that is, where it
77
+ // accepts it as their latest does, which then passes it still; never one
78
+ // before a latest not accepting it, whatever that was compared with, as it
79
+ // holds them all.
75
80
  interface Own { review: PublishedReview; pkgs: LockedPackage[] }
76
- // The latest of `reviews`, some, the first of those as late, as
77
- // pull-dependency-reviews.ts stancesOf takes it.
78
- const latestOf = (reviews: PublishedReview[]) => reviews.reduce((one, other) => other.time > one.time ? other : one)
79
81
  function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean, bases: Map<string, ReviewedBase>): Map<string, Own> {
80
82
  // Theirs by the version they are of, each version probed once.
81
83
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
82
84
  const mine = new Map<string, Own>()
83
85
  if (theirs.size === 0) return mine
84
86
  for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
87
+ const of = reviewsOf(pkg, theirs)
85
88
  const against = any ? 'any' : basesOf(pkg, bases.get(askedOf(pkg)[0]) ?? null)
86
- for (const review of reviewsOf(pkg, theirs)) {
87
- if (comparedWith(review, pkg, against)) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
89
+ const compared = of.filter(review => comparedWith(review, pkg, against))
90
+ if (compared.length === 0) continue
91
+ const [latest, review] = [latestOf(of), latestOf(compared)]
92
+ if (review === latest || (ACCEPTING.has(latest.status) && ACCEPTING.has(review.status))) {
93
+ (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
88
94
  }
89
95
  }
90
96
  return mine
@@ -93,18 +99,21 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
93
99
  // The comment the host formats of `user`'s reviews of the versions pull
94
100
  // request `number` of `repository` adds (`told`), those its review's state
95
101
  // tells of, published to a team counting for it; none where it has none.
96
- // A review is left out where every version it is of, as locked, wants no
97
- // comment of it there, as copying it would but repeat what `user` posted
98
- // there: the host's `lookup` passes it already, or `user`'s own comments
99
- // there (of `commented`, the reviews its comments make) make one of it with
100
- // the same verdict, any of them, a later one of another verdict too; or
101
- // stand on it, by their latest of it (pull-dependency-reviews.ts stancesOf),
102
- // where `user`'s latest review of it does, their older ones of it then
103
- // wanting no comment either, as where the host reads one verdict of a
104
- // version of a comment. A version `lookup` fails to answer of keeps its
105
- // review. Where the host reads reviews of comments (`parseComments`), what a
106
- // review was compared with is its to weigh, so one compared with any version
107
- // is given.
102
+ // Of each version, as locked, the one review of `user`'s that stands for
103
+ // them on it is given (ownOfPull), their latest, never those it revises: a
104
+ // comment of them all would tell two verdicts, or comments, of it. A review
105
+ // is left out where every version it is given of wants no comment of it
106
+ // there, as copying it would but repeat what `user` posted there, or undo a
107
+ // later word of theirs holding it: the host's `lookup` passes it already; or
108
+ // `user`'s own comments there (of `commented`, the reviews its comments
109
+ // make) stand where it does, by their latest of it, the first of those as
110
+ // late (as pull-dependency-reviews.ts stancesOf reads them), with its
111
+ // verdict, or, later than it, not accepting what it accepts. Where their
112
+ // latest comment stands elsewhere, an older one with its verdict leaves it
113
+ // in: posted again, it stands. A version `lookup` fails to answer of keeps
114
+ // its review. Where the host reads reviews of comments (`parseComments`),
115
+ // what a review was compared with is its to weigh, so one compared with any
116
+ // version is given.
108
117
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
109
118
  told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = [],
110
119
  bases: Map<string, ReviewedBase> = new Map()): Promise<string | null> {
@@ -113,12 +122,11 @@ export async function formattedPull(reviewed: ReviewedDependencies | null, db: P
113
122
  if (mine.size === 0) return null
114
123
  const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
115
124
  const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
116
- // `user`'s own of each version, as locked.
117
- const ownOf = new Map<LockedPackage, PublishedReview[]>()
118
- for (const { review, pkgs } of mine.values()) for (const pkg of pkgs) (ownOf.get(pkg) ?? ownOf.set(pkg, []).get(pkg)!).push(review)
119
125
  const posted = (review: PublishedReview, pkg: LockedPackage) => {
120
126
  const made = reviewsOf(pkg, there)
121
- return made.some(one => one.status === review.status) || (made.length > 0 && latestOf(made).status === latestOf(ownOf.get(pkg)!).status)
127
+ if (made.length === 0) return false
128
+ const stance = latestOf(made)
129
+ return stance.status === review.status || (stance.time > review.time && !ACCEPTING.has(stance.status) && ACCEPTING.has(review.status))
122
130
  }
123
131
  const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && !posted(review, pkg))).map(([id]) => id)
124
132
  if (ids.length === 0) return null
@@ -89,7 +89,8 @@
89
89
  // GET /api/bundles/<id>/validation → its last validation the reader may see, else none; POST validates it anew: its own code
90
90
  // as GitHub has it at its commit, its dependencies as upstream's packages have them, those covering every file | 401/403/404/409/422/429/502
91
91
  // GET /api/bundles/<id>/download → authorized original upload | 401/404
92
- // GET /api/bundles/<id>/pretty?path=&hash= → one of its files pretty-printed, Brotli-encoded | 400/401/404/409/413/422/429
92
+ // GET /api/bundles/<id>/pretty?path=&hash= → one of its files pretty-printed, `{ text, blank }` (its layout blank lines),
93
+ // Brotli-encoded JSON | 400/401/404/409/413/422/429
93
94
  // GET /api/bundles/<id>/pretty?other= → the files that changed between it and another bundle, both sides' pretty-printed,
94
95
  // Brotli-encoded ndjson | 400/401/404/422/503
95
96
  // GET /api/bundles/<id>/rename-diff?path=&hash=&other=&otherPath=&otherHash= → a JavaScript file diffed with another
@@ -134,7 +135,7 @@
134
135
  // GET /api/npm/pretty?name=&version= → every one of its files that needs it pretty-printed, Brotli-encoded ndjson | 400/401/404/413/429/502/503
135
136
  // GET /api/npm/pretty?name=&version=&otherVersion= → the files that changed between it and another version, both sides'
136
137
  // pretty-printed, Brotli-encoded ndjson | 400/401/404/413/429/502/503
137
- // GET /api/npm/pretty?name=&version=&path=&hash= → one of its files pretty-printed, Brotli-encoded | 400/401/404/409/413/422/429/502/503
138
+ // GET /api/npm/pretty?name=&version=&path=&hash= → one of its files pretty-printed, as a bundle's is, Brotli-encoded JSON | 400/401/404/409/413/422/429/502/503
138
139
  // GET /api/npm/rename-diff?name=&version=&path=&hash=&otherVersion=&otherPath=&otherHash= → a JavaScript file diffed with
139
140
  // another version's, both pretty-printed, renamed names hidden, whitespace changes shown and hidden | 400/401/404/409/413/422/429/502/503/504
140
141
  // GET /api/npm/rename-diff?name=&version=&otherVersion= → every pair of their JavaScript files the viewer diffs so,
@@ -143,7 +144,7 @@
143
144
  // or with otherVersion (empty) of the version against no files, each added, as Review reads one with no base; and
144
145
  // with runs=1 those in types alone but for what runs, Brotli-encoded ndjson | 400/401/404/413/429/501/502/503
145
146
  // GET /api/npm/delta?name=&version=&otherVersion= → the lines a version adds and removes against another, or `(empty)`, and
146
- // those but for declaration files changed in types alone, where any are, and whether binary files changed
147
+ // those of each file as Compare draws it with the fewest (`best`), and whether binary files changed
147
148
  // | 400/401/404/413/422/429/502/503/504
148
149
  // GET /api/npm/risk?name=&version=&otherVersion= → what calls for a look at a version, as risk tells it, against another where given | 400/401/404/413/429/502
149
150
  // POST /api/auth/logout → same-origin + CSRF, drops the session (and any view)
@@ -280,6 +281,7 @@ import { npmProvenance } from './npm-provenance.ts'
280
281
  import { npmReadyScanDownload, npmReadyScanDownloads, npmRisk, npmRiskRemoved } from './npm-risk.ts'
281
282
  import { NpmRiskError } from '../risk/index.js'
282
283
  import { type ComparedSide, type PrettyCache, PrettyError, type PrettyRequest, compared, prettyRequest, prettyText } from './pretty-print.ts'
284
+ import { npmCopies } from './pretty-copies.ts'
283
285
  import { renameDiffOf, renameDiffRequest, renamedPairs } from './rename-diff.ts'
284
286
  import { runsAsked, typeOnlyFiles } from './type-only.ts'
285
287
  import { comparisonBody, emptySide, npmComparedSide, patchedVersionBody } from './comparison.ts'
@@ -5441,7 +5443,7 @@ const MAX_ASKED_DELTAS = 50
5441
5443
  const DELTAS_AT_ONCE = 2
5442
5444
  // A version as npmDelta takes it: its integrity, and its files, loaded as
5443
5445
  // they are asked for and released once read.
5444
- const deltaSide = (doc: NpmVersionDocument) => ({ integrity: doc.dist.integrity, files: async () => {
5446
+ const deltaSide = (doc: NpmVersionDocument, npm?: CacheStorage) => ({ integrity: doc.dist.integrity, copies: npm ? npmCopies(npm, doc) : null, files: async () => {
5445
5447
  const load = loadNpmFiles(doc)
5446
5448
  try { return await load.result } finally { load.release() }
5447
5449
  } })
@@ -5479,10 +5481,10 @@ async function handleNpmDeltas(req: IncomingMessage, res: ServerResponse, deps:
5479
5481
  isPrivate = doc.private
5480
5482
  oldPrivate = old?.private === true
5481
5483
  const patched = patch && await (patches.get(patch.hash) ?? patches.set(patch.hash, npmPatchOf(deps, cookie, patch)).get(patch.hash)!)
5482
- const side = deltaSide(doc)
5484
+ const side = deltaSide(doc, deps.npmCacheStorage)
5483
5485
  if (patched && 'error' in patched) line = { ...asOne, error: patched.error, status: patched.status }
5484
5486
  else {
5485
- const delta = await npmDelta(old ? deltaSide(old) : null,
5487
+ const delta = await npmDelta(old ? deltaSide(old, deps.npmCacheStorage) : null,
5486
5488
  patched ? { integrity: `${side.integrity} patch:${patch.hash}`, files: async () => patchedFiles(await side.files(), patched.files) } : side, kept)
5487
5489
  if (!patched && !doc.private && !old?.private) await byVersions.write(versionDeltaKey(doc.name, doc.version, old?.name ?? name, old?.version ?? '(empty)'), delta, Date.now())
5488
5490
  line = { ...asOne, ...delta }
@@ -5642,12 +5644,12 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5642
5644
  }
5643
5645
  if (path === NPM_PROVENANCE_PATH) { await reply(doc.private, { name, version: doc.version, provenance: await provenanceOf() }); return }
5644
5646
  // The lines it changes against `otherVersion`, or `(empty)`, its whole
5645
- // package's, and those but for declaration files changed in types alone
5646
- // (npm-delta.ts), as a list of versions wanting reviews tells them.
5647
+ // package's, and those of each file at its fewest (npm-delta.ts), as a
5648
+ // list of versions wanting reviews tells them.
5647
5649
  if (path === NPM_DELTA_PATH) {
5648
5650
  const old = otherSpec === '(empty)' ? null : await otherDoc()
5649
5651
  dropIdle(res)
5650
- const delta = await npmDelta(old ? deltaSide(old) : null, deltaSide(doc), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
5652
+ const delta = await npmDelta(old ? deltaSide(old, deps.npmCacheStorage) : null, deltaSide(doc, deps.npmCacheStorage), npmDeltaStore<NpmDelta>(deps.db, deps.config.debug))
5651
5653
  await reply(doc.private || old?.private === true, { name, version: doc.version, otherVersion: old?.version ?? null, ...delta })
5652
5654
  return
5653
5655
  }
@@ -5693,7 +5695,7 @@ async function handleNpm(req: IncomingMessage, res: ServerResponse, deps: Manage
5693
5695
  if (!deps.prettyCache) { sendJson(res, 503, { error: 'unavailable' }); return }
5694
5696
  const copy = await deps.prettyCache.npm(doc, file)
5695
5697
  if (!(await recheck(doc.private))) { copy.stream.destroy(); return }
5696
- await sendEncoded(req, res, copy, 'text/plain; charset=utf-8', prettySource(file))
5698
+ await sendEncoded(req, res, copy, 'application/json', prettySource(file))
5697
5699
  return
5698
5700
  }
5699
5701
  // Against another version, the pairs of its files that changed that the
@@ -6084,7 +6086,7 @@ export function createManagedRequestHandler(deps: ManagedHttpDeps): Handler {
6084
6086
  if (part !== 'pretty') { await handleBundleCache(req, res, deps, session, id, bundleCache && (rec => bundleCache.open(rec, part as BundleCachePart))); return }
6085
6087
  const file = prettyRequest(url.searchParams)
6086
6088
  if (!file) { sendJson(res, 400, { error: 'bad-file' }); return }
6087
- await handleBundleCache(req, res, deps, session, id, prettyCache && (rec => prettyCache.bundle(rec, file)), 'text/plain; charset=utf-8', prettySource(file))
6089
+ await handleBundleCache(req, res, deps, session, id, prettyCache && (rec => prettyCache.bundle(rec, file)), 'application/json', prettySource(file))
6088
6090
  return
6089
6091
  }
6090
6092
  if (path === BUNDLE_CREATE_PATH) {
@@ -1,23 +1,69 @@
1
1
  // The lines a package's files change from one side to another (npm-delta.ts),
2
2
  // as @preventive/compare's compareTrees counts them (git's --numstat), off
3
3
  // the server's event loop: of its text files, renames found as git finds
4
- // them, a side not there empty; and, apart, those of its changes it stamps
5
- // `typeOnly`, declaration files changed in types alone.
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.
6
8
  import { parentPort, workerData } from 'node:worker_threads'
7
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'
12
+ import { prettyExtension, printableSize } from '../common/pretty-print.js'
13
+ import { whitespaceInsensitive } from '../common/whitespace-insensitive.js'
14
+ import { prettyFormat } from './pretty-format.js'
15
+
16
+ const { base, copies, other, prettyUntil } = workerData
17
+ const kept = new Map(copies.map(([at, path, copy]) => [`${at}\0${path}`, copy])), made = []
18
+ const NONE = { additions: 0, deletions: 0 }
19
+ 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
+
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
27
+ 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
35
+ } catch {
36
+ return null
37
+ }
38
+ }
8
39
 
9
40
  const tree = files => files.map(([name, data]) => ({ name, data }))
10
- const changes = compareTrees(tree(workerData.base), tree(workerData.other), { paths: 'keys', lines: true, renames: true })
11
- const answer = { additions: 0, deletions: 0, typeAdditions: 0, typeDeletions: 0, typeFiles: 0 }
12
- for (const change of changes) {
41
+ const best = { ...NONE }, printing = [], total = { ...NONE }
42
+ for (const change of compareTrees(tree(base), tree(other), { paths: 'keys', lines: true, renames: true })) {
13
43
  if (change.binary) continue
14
- answer.additions += change.insertions ?? 0
15
- answer.deletions += change.deletions ?? 0
16
- if (change.typeOnly !== true) continue
17
- answer.typeAdditions += change.insertions ?? 0
18
- answer.typeDeletions += change.deletions ?? 0
19
- answer.typeFiles++
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
49
+ for (const [sum, count] of [[total, published], [best, fewest]]) {
50
+ sum.additions += count.additions
51
+ sum.deletions += count.deletions
52
+ }
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 })
55
+ }
56
+ // Smallest first, so the time left goes to the most files.
57
+ let complete = true
58
+ for (const file of printing.toSorted((a, b) => a.before.length + a.after.length - b.before.length - b.after.length)) {
59
+ 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))
64
+ best.additions += now.additions - file.fewest.additions
65
+ best.deletions += now.deletions - file.fewest.deletions
20
66
  }
21
67
  // Node worker messages have no browser target origin.
22
68
  // oxlint-disable-next-line unicorn/require-post-message-target-origin
23
- parentPort.postMessage(answer)
69
+ parentPort.postMessage({ ...total, best, complete, made })
@@ -2,33 +2,41 @@
2
2
  // its whole package's (GET /api/npm/delta), as a list of versions wanting
3
3
  // reviews tells them beside each: added and removed (`additions`,
4
4
  // `deletions`), as git's --numstat counts them, of their text files, a
5
- // renamed one diffed with what it was; and, where some of the files changed
6
- // are declaration files @preventive/compare's compareTrees proves changed in
7
- // types alone (`typeOnly`, proveTypeOnly: types and comments alone erased,
8
- // the runtime they leave as it was, an added one's empty or a single bare
9
- // `export {}`), those of the rest (`typeless`), what a reviewer may pass by
10
- // leaving those out; and whether a binary file, which they count none of,
5
+ // renamed one diffed with what it was; each file's fewest as Compare can
6
+ // draw it (`best`); and whether a binary file, which they count none of,
11
7
  // was added, removed or changed (`binary`), one moved as it was not. Worked
12
8
  // out in a worker, off the event loop, as many at once per process as
13
9
  // MAX_ACTIVE, both sides' files read together only once their turn has come,
14
10
  // those waiting past MAX_WAITING refused, each waiting a minute at most and
15
11
  // counting in a minute at most; one asked again meanwhile sharing the
16
12
  // first's; and kept by both sides' integrities, in this instance and beyond
17
- // it (`kept`), what a version holds never changing. Access is the caller's
18
- // to check.
13
+ // it (`kept`), what a version holds never changing, but for one whose copies
14
+ // weren't all printed in time (`partial`). Its pretty-printed copies are
15
+ // Compare's, read and kept as Compare keeps them (`copies`). Access is the
16
+ // caller's to check.
19
17
  import { createHash } from 'node:crypto'
18
+ import { layoutBlankList, prettyExtension } from '../common/pretty-print.js'
20
19
  import { type KeptStore, VERSION_DELTA_KEPT_MS } from './npm-kept.ts'
21
20
  import { type Lru, lru } from './lru.ts'
22
21
  import { NpmPackageError, type NpmPackageFile, npmFileText } from './npm-packages.ts'
22
+ import { PRETTY_VERSION, type PrettyCopy } from './pretty-format.js'
23
+ import type { KeptCopies } from './pretty-copies.ts'
24
+ import { eachOf } from './queue.ts'
23
25
  import { workerTurns } from './worker-turns.ts'
24
26
 
25
- export interface NpmDelta { additions: number; deletions: number; typeless: { additions: number; deletions: number } | null; binary: boolean }
27
+ export interface NpmDelta { additions: number; deletions: number; best: { additions: number; deletions: number }; binary: boolean; partial?: true }
26
28
 
27
29
  const MAX_ACTIVE = 2
28
30
  const MAX_WAITING = 64
29
31
  const DELTA_TIMEOUT_MS = 60_000
32
+ // No file is begun pretty-printing in this last part of it, as one may take seconds.
33
+ const PRETTY_MARGIN_MS = 15_000
30
34
  // The text the two sides may hold together, past which none is counted.
31
35
  const MAX_TEXT_LENGTH = 64 * 1024 * 1024
36
+ // Bumped when what a delta counts changes; its keys carry it and PRETTY_VERSION, so none counted otherwise is read.
37
+ const DELTA_VERSION = 1
38
+ const COUNTING = `v${DELTA_VERSION}.${PRETTY_VERSION}`
39
+ const COPIES_AT_ONCE = 8
32
40
 
33
41
  const deltas: Lru<NpmDelta> = lru(20_000)
34
42
  const working = new Map<string, Promise<NpmDelta>>()
@@ -37,22 +45,25 @@ const workers = workerTurns({ what: 'package delta', active: MAX_ACTIVE, waiting
37
45
 
38
46
  const lines = (told: unknown): told is { additions: number; deletions: number } => typeof told === 'object' && told !== null
39
47
  && Number.isSafeInteger((told as { additions?: unknown }).additions) && Number.isSafeInteger((told as { deletions?: unknown }).deletions)
40
- // A delta as kept, none where it isn't one, or was kept before it told of
41
- // binary files.
48
+ // A delta as kept, none where it isn't one, or is partial.
42
49
  function deltaOf(told: unknown): NpmDelta | null {
43
50
  if (!lines(told)) return null
44
- const { typeless, binary } = told as { typeless?: unknown; binary?: unknown }
45
- return (typeless === null || lines(typeless)) && typeof binary === 'boolean' ? { additions: told.additions, deletions: told.deletions, typeless, binary } : null
51
+ const { best, binary, partial } = told as { best?: unknown; binary?: unknown; partial?: unknown }
52
+ return lines(best) && typeof binary === 'boolean' && partial === undefined
53
+ ? { additions: told.additions, deletions: told.deletions, best: { additions: best.additions, deletions: best.deletions }, binary } : null
46
54
  }
47
55
 
48
- type Counted = { additions: number; deletions: number; typeAdditions: number; typeDeletions: number; typeFiles: number }
49
- const isCounted = (told: unknown): told is Counted => typeof told === 'object' && told !== null
50
- && ['additions', 'deletions', 'typeAdditions', 'typeDeletions', 'typeFiles'].every(key => Number.isSafeInteger((told as Record<string, unknown>)[key]))
56
+ // A copy by side (0 the base, 1 the other) and path, as the worker reads and makes them.
57
+ type SideCopy = [number, string, PrettyCopy]
58
+ type Counted = Omit<NpmDelta, 'binary' | 'partial'> & { complete: boolean; made: SideCopy[] }
59
+ const isCounted = (told: unknown): told is Counted => lines(told) && lines((told as { best?: unknown }).best)
60
+ && typeof (told as { complete?: unknown }).complete === 'boolean' && Array.isArray((told as { made?: unknown }).made)
61
+ const isCopy = (copy: unknown): copy is PrettyCopy => typeof (copy as { text?: unknown } | null)?.text === 'string' && layoutBlankList((copy as { blank?: unknown }).blank) !== null
51
62
 
52
- // What the worker counts of `base` against `other`, each its text files' paths and texts.
53
- function counted(base: [string, string][], other: [string, string][], deadline: number): Promise<Counted> {
63
+ // What the worker counts of `base` against `other`, each its text files' paths and texts, given the copies kept.
64
+ function counted(base: [string, string][], other: [string, string][], copies: SideCopy[], deadline: number): Promise<Counted> {
54
65
  return workers.run(new URL('./npm-delta-worker.js', import.meta.url), {
55
- workerData: { base, other }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
66
+ workerData: { base, other, copies, prettyUntil: deadline - PRETTY_MARGIN_MS }, execArgv: ['--disable-warning=ExperimentalWarning'], resourceLimits: { maxOldGenerationSizeMb: 1536 },
56
67
  }, told => (isCounted(told) ? told : null), deadline)
57
68
  }
58
69
 
@@ -100,15 +111,15 @@ function binaryChanged(olds: NpmPackageFile[], news: NpmPackageFile[]): boolean
100
111
  })
101
112
  }
102
113
 
103
- type Side = { integrity: string; files: () => Promise<NpmPackageFile[]> }
114
+ type Side = { integrity: string; files: () => Promise<NpmPackageFile[]>; copies?: KeptCopies | null }
104
115
  // A delta's key: the integrities of the version it is against, or none, and
105
116
  // of the version.
106
- export const deltaKey = (base: string | null, other: string) => `${base ?? '(empty)'}\0${other}`
117
+ export const deltaKey = (base: string | null, other: string) => `${COUNTING}\0${base ?? '(empty)'}\0${other}`
107
118
  // The same of two public versions by their names and versions (`(empty)`
108
119
  // for none), as npm never gives one other files: its key in
109
120
  // npmVersionDeltaStore.
110
121
  export const versionDeltaKey = (name: string, version: string, otherName: string, otherVersion: string) =>
111
- `${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
122
+ `${COUNTING}\0${name}@${version}\0${otherVersion === '(empty)' ? '(empty)' : `${otherName}@${otherVersion}`}`
112
123
  // Those of `keys` (versionDeltaKey) kept, by key, as of `now`: one kept past
113
124
  // VERSION_DELTA_KEPT_MS not, though no write has pruned it yet.
114
125
  export async function keptVersionDeltas(keys: string[], kept: KeptStore<NpmDelta>, now = Date.now()): Promise<Map<string, NpmDelta>> {
@@ -152,11 +163,21 @@ export async function keptNpmDeltas(sides: [string | null, string][], kept: Kept
152
163
  return found
153
164
  }
154
165
 
155
- // As kept, else its turn awaited, then both sides' files read, counted and kept.
166
+ // Those kept of the printable files both sides have, changed, by side and path.
167
+ async function keptCopies(sides: (Side | null)[], files: Map<string, Uint8Array>[]): Promise<SideCopy[]> {
168
+ const changed = [...files[1]!].filter(([path, bytes]) => prettyExtension(path) !== null && files[0]!.has(path) && !same(files[0]!.get(path)!, bytes))
169
+ const asked = changed.flatMap(([path]) => [0, 1].map(at => [at, path] as const)).filter(([at]) => sides[at]?.copies)
170
+ const found = await eachOf(asked, COPIES_AT_ONCE, async ([at, path]) => [at, path, await sides[at]!.copies!.kept(path, files[at]!.get(path)!).catch(() => null)] as const)
171
+ return found.filter((copy): copy is SideCopy => copy[2] !== null)
172
+ }
173
+
174
+ // As kept, else its turn awaited, then both sides' files read, counted and
175
+ // kept, the copies it printed kept for Compare.
156
176
  async function worked(key: string, base: Side | null, other: Side, kept: KeptStore<NpmDelta> | null): Promise<NpmDelta> {
157
177
  const known = deltaOf((await kept?.read(key))?.value)
158
178
  if (known) { deltas.set(key, known); return known }
159
- const delta = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async (): Promise<NpmDelta> => {
179
+ const sides = [base, other]
180
+ const [delta, made, files] = await workers.inTurn(Date.now() + DELTA_TIMEOUT_MS, async () => {
160
181
  // Its turn held till both sides are read, or have failed.
161
182
  const [baseRead, otherRead] = await Promise.allSettled([base ? base.files() : Promise.resolve(null), other.files()])
162
183
  if (baseRead.status === 'rejected') throw baseRead.reason
@@ -164,11 +185,14 @@ async function worked(key: string, base: Side | null, other: Side, kept: KeptSto
164
185
  const [olds, news] = [texts(baseRead.value), texts(otherRead.value)]
165
186
  if (olds.length + news.length > MAX_TEXT_LENGTH) throw new NpmPackageError(413, 'package-too-large')
166
187
  const binary = binaryChanged(olds.binaries, news.binaries)
167
- const told = await counted(olds.read, news.read, Date.now() + DELTA_TIMEOUT_MS)
168
- return { additions: told.additions, deletions: told.deletions,
169
- typeless: told.typeFiles > 0 ? { additions: told.additions - told.typeAdditions, deletions: told.deletions - told.typeDeletions } : null, binary }
188
+ const byPath = [baseRead.value ?? [], otherRead.value].map(side => new Map(side.filter(file => file.link === undefined).map(file => [file.path, file.bytes])))
189
+ const told = await counted(olds.read, news.read, await keptCopies(sides, byPath), Date.now() + DELTA_TIMEOUT_MS)
190
+ const counts: NpmDelta = { additions: told.additions, deletions: told.deletions, best: told.best, binary, ...told.complete ? {} : { partial: true as const } }
191
+ return [counts, told.made, byPath] as const
170
192
  })
171
193
  deltas.set(key, delta)
172
- await kept?.write(key, delta, Date.now())
194
+ if (!delta.partial) await kept?.write(key, delta, Date.now())
195
+ await eachOf(made.filter(([at, path, copy]) => sides[at]?.copies && files[at]?.has(path) && isCopy(copy)), COPIES_AT_ONCE,
196
+ ([at, path, copy]) => sides[at]!.copies!.keep(path, files[at]!.get(path)!, copy))
173
197
  return delta
174
198
  }
@@ -0,0 +1,22 @@
1
+ // A public version's pretty-printed copies as Compare keeps them (pretty-print.ts), by its files'
2
+ // paths and bytes, for a delta to read and keep (npm-delta.ts); none for a private version.
3
+ import { prettyExtension } from '../common/pretty-print.js'
4
+ import { encodeBrotli } from './brotli.ts'
5
+ import type { CacheStorage } from './cache-storage.ts'
6
+ import type { NpmVersionDocument } from './npm-packages.ts'
7
+ import type { PrettyCopy } from './pretty-format.js'
8
+ import { keep, kept, npmFileHash, prettyCopy, prettyFile } from './pretty-print.ts'
9
+
10
+ export interface KeptCopies { kept(path: string, bytes: Uint8Array): Promise<PrettyCopy | null>; keep(path: string, bytes: Uint8Array, copy: PrettyCopy): Promise<void> }
11
+
12
+ export function npmCopies(npm: CacheStorage, doc: NpmVersionDocument): KeptCopies | null {
13
+ if (doc.private) return null
14
+ const file = async (path: string, bytes: Uint8Array) => prettyFile({ path, hash: await npmFileHash(bytes), extension: prettyExtension(path) ?? '' })
15
+ return {
16
+ async kept(path, bytes) {
17
+ const copy = await kept(async () => npm.open(await file(path, bytes)))
18
+ return copy && prettyCopy(copy)
19
+ },
20
+ keep: (path, bytes, copy) => keep(async () => npm.put(await file(path, bytes), await encodeBrotli(Buffer.from(JSON.stringify(copy))))),
21
+ }
22
+ }
@@ -0,0 +1,3 @@
1
+ export const PRETTY_VERSION: number
2
+ export interface PrettyCopy { text: string; blank: number[] }
3
+ export function prettyFormat(text: string, extension: string): Promise<PrettyCopy | { error: 'unsupported' | 'unformattable' | 'pretty-mismatch' }>
@@ -0,0 +1,13 @@
1
+ // A file pretty-printed as Compare draws it, with its copy's layout blank lines: the server's
2
+ // copies (pretty-print.ts) and a delta's (npm-delta-worker.js) alike.
3
+ import { format, layoutBlankLines } from '@preventive/compare/pretty.js'
4
+
5
+ // Part of every kept copy's name; bumped when what the formatter writes for
6
+ // the same file changes, or what its check lets through, so copies written
7
+ // before are no longer read.
8
+ export const PRETTY_VERSION = 6
9
+
10
+ export async function prettyFormat(text, extension) {
11
+ const result = await format(text, extension)
12
+ return 'error' in result ? result : { text: result.code, blank: await layoutBlankLines(result.code, extension) }
13
+ }