@preventive/triage 1.0.0-alpha.66 → 1.0.0-alpha.68

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 (66) hide show
  1. package/common/bundle-imports.js +20 -0
  2. package/common/bundle-metadata.js +1 -1
  3. package/common/bundle-reasons.d.ts +4 -0
  4. package/common/bundle-reasons.js +38 -1
  5. package/common/bundle-sources.d.ts +1 -0
  6. package/common/bundle-sources.js +22 -0
  7. package/common/managed/npm-packages.js +3 -3
  8. package/common/managed/routes.js +37 -18
  9. package/common/managed/stasis-config.ts +7 -0
  10. package/out/activity.js +4 -4
  11. package/out/{chunk-J2FWBXFV.js → chunk-2F3CYNPZ.js} +1 -1
  12. package/out/chunk-2HGKTQ5Q.js +52 -0
  13. package/out/chunk-4RS3NDOG.js +1 -0
  14. package/out/chunk-CGRIZ5M5.js +1 -0
  15. package/out/{chunk-Z6VEV2QL.js → chunk-D37M7J4B.js} +1 -1
  16. package/out/chunk-GZ46SSTF.js +1 -0
  17. package/out/{chunk-IZ6MYRYB.js → chunk-HETCVNO4.js} +1 -1
  18. package/out/chunk-MPXVKVPF.js +3 -0
  19. package/out/{chunk-24AKGEH3.js → chunk-NB4JBTKK.js} +1 -1
  20. package/out/{chunk-OVGR4D3M.js → chunk-OAWY4T6R.js} +1 -1
  21. package/out/chunk-QPGM3DTI.js +42 -0
  22. package/out/chunk-SCN2TBP2.js +247 -0
  23. package/out/chunk-VG5RH6KN.js +2 -0
  24. package/out/chunk-WFDXHPT2.js +12 -0
  25. package/out/client-managed-import.js +2 -2
  26. package/out/client-managed.js +19 -19
  27. package/out/compare.js +12 -12
  28. package/out/dialogs.js +38 -38
  29. package/out/graph.js +8 -8
  30. package/out/index.html +9 -9
  31. package/out/scan.js +2 -2
  32. package/out/view.css +1 -1
  33. package/out/view.js +15 -15
  34. package/package.json +11 -8
  35. package/server-managed/activity.ts +21 -12
  36. package/server-managed/bundle-build-diagnostics.d.ts +1 -1
  37. package/server-managed/bundle-build-worker.js +140 -19
  38. package/server-managed/bundle-build.ts +102 -21
  39. package/server-managed/bundle-cache.ts +28 -6
  40. package/server-managed/bundle-dependency-reviews.ts +38 -22
  41. package/server-managed/commit-lockfiles.ts +2 -1
  42. package/server-managed/db-neon.ts +5 -2
  43. package/server-managed/dependency-review-comments.ts +38 -16
  44. package/server-managed/dependency-reviews.ts +17 -14
  45. package/server-managed/http.ts +178 -70
  46. package/server-managed/locked-packages.ts +34 -14
  47. package/server-managed/lockfile-scope.ts +10 -1
  48. package/server-managed/npm-kept.ts +10 -0
  49. package/server-managed/npm-patch.ts +188 -53
  50. package/server-managed/public-workspace.ts +3 -2
  51. package/server-managed/pull-dependencies.ts +58 -37
  52. package/server-managed/pull-dependency-reviews.ts +35 -22
  53. package/server-managed/report-sources.ts +6 -3
  54. package/server-managed/repository-dependency-reviews.ts +4 -2
  55. package/server-managed/repository-issues.ts +14 -11
  56. package/server-managed/stasis-dependencies.ts +170 -0
  57. package/out/chunk-65PLAG3I.js +0 -12
  58. package/out/chunk-DCBXCBLL.js +0 -52
  59. package/out/chunk-F3UI65ZI.js +0 -42
  60. package/out/chunk-FAG6E5RC.js +0 -3
  61. package/out/chunk-OBZWBTZL.js +0 -247
  62. package/out/chunk-PTFQKLKO.js +0 -1
  63. package/out/chunk-QVKFY4FA.js +0 -1
  64. package/out/chunk-SYXT3SFP.js +0 -2
  65. package/out/chunk-WL3SPQB4.js +0 -1
  66. /package/out/{chunk-WCPJDAYA.js → chunk-D6NVKGGG.js} +0 -0
@@ -5,7 +5,7 @@ import { brotliDecompress } from 'node:zlib'
5
5
  import { promisify } from 'node:util'
6
6
  import { bundleEdges } from '@preventive/sourcemap/edges.js'
7
7
  import { BUNDLE_METADATA_VERSION, type BundleDetails, createBundleMetadata, createBundleSummary, parseBundleContents, parseBundleMetadata } from '../common/bundle-metadata.js'
8
- import { bundleReasons } from '../common/bundle-reasons.js'
8
+ import { bundleReasons, bundleScopes, scopeLabel } from '../common/bundle-reasons.js'
9
9
  import { sourcemapEdges } from '../common/bundle-sourcemap.js'
10
10
  import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
11
11
  import { decodeUtf8 } from '../common/utf8.js'
@@ -46,7 +46,19 @@ export interface BundleCacheStorage {
46
46
  }
47
47
 
48
48
  const filename = `v${BUNDLE_METADATA_VERSION}-metadata.json.br`
49
- const packagesFilename = 'v6-advisory-inventory.json'
49
+ const packagesFilename = 'v7-advisory-inventory.json'
50
+
51
+ // An entry point's inventory is rows of the bundle's own, a package's versions
52
+ // in order and then the skipped: kept as a 0 or 1 for each, since spelled out,
53
+ // as a reason's is, many entry points' would not fit the budget.
54
+ const rowKeys = ({ packages, skipped }: BundleAdvisoryInventory) => [
55
+ ...packages.flatMap(pkg => pkg.versions.map(version => JSON.stringify([pkg.ecosystem, pkg.ecosystem === 'github' ? pkg.name.toLowerCase() : pkg.name, version]))),
56
+ ...skipped.map(pkg => JSON.stringify([pkg.ecosystem, pkg.name, pkg.version, 'skipped']))]
57
+ function keptRows(all: BundleAdvisoryInventory, rows: string): BundleAdvisoryInventory {
58
+ let row = 0
59
+ const kept = () => rows[row++] === '1'
60
+ return { packages: all.packages.map(pkg => ({ ...pkg, versions: pkg.versions.filter(kept) })).filter(pkg => pkg.versions.length > 0), skipped: all.skipped.filter(kept) }
61
+ }
50
62
 
51
63
  // All scopes share one bounded derivative. Never decode full bundle metadata
52
64
  // on advisory requests, including when selecting a reason. Persist null when
@@ -77,8 +89,16 @@ function encodePackageInventory(details: BundleDetails): Buffer {
77
89
  return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
78
90
  }
79
91
  const whole = append('{"all":') && inventory(null)
80
- && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}}')
81
- return Buffer.from(whole ? parts.join('') : 'null')
92
+ && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}')
93
+ if (!whole) return Buffer.from('null')
94
+ // Entry points last: where they don't fit, they alone are left out.
95
+ const all = rowKeys(bundleAdvisoryInventory(details)), fit = parts.length, fitSize = size, scopes = bundleScopes(details)
96
+ const entries = list(',"entries":{', scopes.ids.filter(id => id.startsWith('entry:')), id => {
97
+ const kept = new Set(rowKeys(bundleAdvisoryInventory(details, scopes.files(id))))
98
+ return append(`${JSON.stringify(scopeLabel(id))}:"${all.map(key => kept.has(key) ? 1 : 0).join('')}"`)
99
+ }, '}')
100
+ if (!entries) { parts.length = fit; size = fitSize }
101
+ return Buffer.from(append('}') ? parts.join('') : 'null')
82
102
  }
83
103
 
84
104
  // What a catalog sends of a bundle before it opens. A Stasis bundle's
@@ -177,14 +197,16 @@ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, st
177
197
  const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
178
198
  return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
179
199
  },
180
- async advisoryInventory(record: ManagedBundle, reason = ''): Promise<BundleAdvisoryInventory | null | undefined> {
200
+ // The whole bundle's, one `reason`'s, or one `entry` point's instead: undefined for one it has none of.
201
+ async advisoryInventory(record: ManagedBundle, reason = '', entry = ''): Promise<BundleAdvisoryInventory | null | undefined> {
181
202
  if (record.kind !== 'stasis') return { packages: [], skipped: [] }
182
203
  const cached = await openCached(record, packagesFilename)
183
204
  if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
184
205
  const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
185
206
  if (!bytes) return null
186
207
  const inventory = JSON.parse(decodeUtf8(bytes))
187
- if (inventory === null) return null
208
+ if (inventory === null || (entry && !inventory.entries)) return null
209
+ if (entry) return Object.hasOwn(inventory.entries, entry) ? keptRows(inventory.all, inventory.entries[entry]) : undefined
188
210
  return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
189
211
  },
190
212
  async delete(id: string) {
@@ -19,13 +19,15 @@
19
19
  import { type CommitLockfiles, lockedIn } from './commit-lockfiles.ts'
20
20
  import type { LockedPackage } from './locked-packages.ts'
21
21
  import { MAX_LOCKED, type PullDependencies, lockedWith, lockfileFormat } from './pull-dependencies.ts'
22
- import { MAX_UNREVIEWED } from './pull-dependency-reviews.ts'
22
+ import { MAX_UNREVIEWED, hashesOf } from './pull-dependency-reviews.ts'
23
23
 
24
- // A version a bundle holds: its package's name and its version.
25
- export interface BundledVersion { name: string; version: string }
24
+ // A version a bundle holds: its package's name and its version; and, as a
25
+ // Stasis lockfile tells one (stasis-dependencies.ts), how it was installed:
26
+ // its tarball's integrity, and pnpm's hash of the patch applied to it.
27
+ export interface BundledVersion { name: string; version: string; integrity?: string; patch?: string }
26
28
 
27
- // The directory a lockfile at `path` is in, '' for the repository's root.
28
- const directoryOf = (path: string) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
29
+ // The directory a file at `path` is in, '' for the repository's root.
30
+ export const directoryOf = (path: string) => path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : ''
29
31
  // A bundle's directory as one is compared: without the slashes either end.
30
32
  const bundleDirectory = (directory: string) => directory.replaceAll(/^\/+|\/+$/gu, '')
31
33
  const depth = (dir: string) => dir === '' ? 0 : dir.split('/').length
@@ -37,32 +39,46 @@ export function installsBundle(path: string, directory: string): boolean {
37
39
  return dir === '' || at === dir || at.startsWith(`${dir}/`)
38
40
  }
39
41
 
40
- // The versions `bundled` as `read`'s lockfiles (those installing the bundle,
41
- // read at `commit`) lock them, as one directory of a pull request's
42
- // lockfiles (pull-dependencies.ts) whose versions it adds none of, each as
43
- // the nearest of their directories locking it locks it, those past
44
- // MAX_LOCKED counted (`moreLocked`), and each lockfile left unread a
45
- // directory of its own failing the review; with those none lock
46
- // (`unlocked`, as many as MAX_UNREVIEWED, how many more `moreUnlocked`) and
47
- // how many versions it bundles (`versions`), each once.
48
- export function bundleDependencies(bundled: BundledVersion[], read: CommitLockfiles, commit: string) {
49
- const versions = [...new Map(bundled.map(one => [`${one.name}@${one.version}`, one])).values()]
42
+ // Whether `pkg` is locked as `one` was installed, where it tells how: with
43
+ // its tarball's integrity among its own, and its patch, or none.
44
+ const lockedAsInstalled = (one: BundledVersion, pkg: LockedPackage) => one.integrity !== undefined
45
+ && hashesOf(pkg).includes(one.integrity) && (pkg.patchHash ?? '') === (one.patch ?? '')
46
+
47
+ // The versions `bundled` as `read`'s lockfiles lock them (`locked`), each as
48
+ // the nearest of their directories locking it locks it; one told with how it
49
+ // was installed, as the nearest locking it so does, where one does. With
50
+ // those none lock (`unlocked`), how many versions there are (`versions`),
51
+ // and the lockfiles' paths, the nearest first.
52
+ export function lockedVersions(bundled: BundledVersion[], read: CommitLockfiles) {
50
53
  const byDirectory = Map.groupBy(read.lockfiles.map(({ path }) => path), directoryOf)
51
54
  // Each directory's versions by their name and version, the nearest first.
52
55
  const nearest = [...byDirectory].toSorted(([a], [b]) => depth(b) - depth(a)).map(([dir, paths]) =>
53
56
  ({ paths, locked: Map.groupBy(lockedIn(read, path => directoryOf(path) === dir).packages, pkg => `${pkg.name}@${pkg.version ?? ''}`) }))
54
57
  const found = new Map<string, LockedPackage>()
55
- const unlocked: BundledVersion[] = []
56
- for (const one of versions) {
58
+ const unlocked = new Map<string, BundledVersion>()
59
+ for (const one of bundled) {
57
60
  const key = `${one.name}@${one.version}`
58
- const variants = nearest.find(({ locked }) => locked.has(key))?.locked.get(key)
59
- if (!variants) { unlocked.push(one); continue }
61
+ const locking = nearest.flatMap(({ locked }) => locked.has(key) ? [locked.get(key)!] : [])
62
+ const variants = locking.map(locks => locks.filter(pkg => lockedAsInstalled(one, pkg))).find(locks => locks.length > 0) ?? locking[0]
63
+ if (!variants) { unlocked.set(key, { name: one.name, version: one.version }); continue }
60
64
  for (const pkg of variants) if (!found.has(lockedWith(pkg))) found.set(lockedWith(pkg), pkg)
61
65
  }
62
- const locked = [...found.values()]
66
+ return { locked: [...found.values()], unlocked: [...unlocked.values()], versions: new Set(bundled.map(one => `${one.name}@${one.version}`)).size,
67
+ paths: nearest.flatMap(({ paths }) => paths) }
68
+ }
69
+
70
+ // The versions `bundled` as `read`'s lockfiles (those installing the bundle,
71
+ // read at `commit`) lock them (lockedVersions), as one directory of a pull
72
+ // request's lockfiles (pull-dependencies.ts) whose versions it adds none of,
73
+ // those past MAX_LOCKED counted (`moreLocked`), and each lockfile left
74
+ // unread a directory of its own failing the review; with those none lock
75
+ // (`unlocked`, as many as MAX_UNREVIEWED, how many more `moreUnlocked`) and
76
+ // how many versions it bundles (`versions`), each once.
77
+ export function bundleDependencies(bundled: BundledVersion[], read: CommitLockfiles, commit: string) {
78
+ const { locked, unlocked, versions, paths } = lockedVersions(bundled, read)
63
79
  const told: PullDependencies = { base: commit, head: commit, cut: false, lockfiles: [
64
- { paths: nearest.flatMap(({ paths }) => paths), added: [], more: 0, locked: locked.slice(0, MAX_LOCKED), moreLocked: Math.max(0, locked.length - MAX_LOCKED) },
80
+ { paths, added: [], more: 0, locked: locked.slice(0, MAX_LOCKED), moreLocked: Math.max(0, locked.length - MAX_LOCKED) },
65
81
  ...read.unread.map(path => ({ paths: [path], error: lockfileFormat(path) === 'bun' ? 'lockfile-unsupported' : 'lockfile-unreadable' })),
66
82
  ] }
67
- return { told, versions: versions.length, unlocked: unlocked.slice(0, MAX_UNREVIEWED), moreUnlocked: Math.max(0, unlocked.length - MAX_UNREVIEWED) }
83
+ return { told, versions, unlocked: unlocked.slice(0, MAX_UNREVIEWED), moreUnlocked: Math.max(0, unlocked.length - MAX_UNREVIEWED) }
68
84
  }
@@ -59,7 +59,8 @@ export async function lockedAt(fullName: string, token: string, sha: string, kep
59
59
 
60
60
  // The versions those of `read`'s lockfiles `held` holds to lock, each once,
61
61
  // each patch's file from the repository's root (patchedIn), the first of
62
- // them that names one there, and their paths.
62
+ // them that names one there, with the directory of the first lockfile that
63
+ // locks it so, and their paths.
63
64
  export function lockedIn(read: CommitLockfiles, held: (path: string) => boolean = () => true) {
64
65
  const packages = new Map<string, LockedPackage>()
65
66
  const paths: string[] = []
@@ -40,7 +40,7 @@ const LOCK = 'SELECT pg_advisory_xact_lock(1937006964, 1835101793)'
40
40
  // Whether every version up to the latest is recorded, in one round trip at
41
41
  // a cold start: a database with no versions table yet (undefined_table) has
42
42
  // none. Outside a transaction, so the failed read aborts nothing.
43
- const SCHEMA_VERSIONS = 35
43
+ const SCHEMA_VERSIONS = 36
44
44
  async function currentSchema(db: PgConnection): Promise<boolean> {
45
45
  try {
46
46
  const { rows } = await db.query(`SELECT count(*) AS n FROM managed_schema_version WHERE version BETWEEN 1 AND ${SCHEMA_VERSIONS}`)
@@ -136,6 +136,9 @@ async function migrateFrom12(db: PgConnection): Promise<void> {
136
136
  // The issue a saved one was closed as a duplicate of, none known of those
137
137
  // checked before.
138
138
  await migration(db, 35, 'ALTER TABLE managed_finding_issue ADD COLUMN IF NOT EXISTS duplicate_of_url TEXT')
139
+ // The patch a dependency review's base is of, none of those written
140
+ // before; each author's one draft of a comparison held to it too.
141
+ await migration(db, 36, `ALTER TABLE managed_dependency_review ${addColumns(DEPENDENCY_REVIEW_COLUMNS)}`, DEPENDENCY_REVIEW_INDEXES)
139
142
  }
140
143
 
141
144
  async function initialize(db: PgConnection): Promise<void> {
@@ -292,7 +295,7 @@ export async function openPostgresManagedDb(leased: PgConnect, options: ManagedD
292
295
  for (const row of result.rows) {
293
296
  if (row[field.name] == null) continue
294
297
  const value = Number(row[field.name])
295
- if (!Number.isSafeInteger(value)) throw new Error('Managed integer exceeds safe range')
298
+ if (!Number.isSafeInteger(value)) throw new RangeError('Managed integer exceeds safe range')
296
299
  row[field.name] = value
297
300
  }
298
301
  }
@@ -2,16 +2,19 @@
2
2
  // button to give (reviewed-dependencies.ts `formatDependencyReviews`): of each
3
3
  // of one's reviews, as their lists and the review page show them
4
4
  // (`withFormatted`), and of those of the versions an open pull request adds
5
- // (`formattedPull`). It is given one's own published reviews alone, never
5
+ // (`formattedPull`), but the versions the host's `lookup` passes already,
6
+ // which want no review there, and those one's own comments there review
7
+ // alike already. It is given one's own published reviews alone, never
6
8
  // another's, a draft or a revoked one, however it is asked (`formatOwn`, the
7
9
  // only caller of the hook); and is told of none where it answers nothing, or
8
10
  // fails, which is logged.
9
11
  import type { DependencyReview, DependencyReviewStore } from './dependency-reviews.ts'
12
+ import type { LockedPackage } from './locked-packages.ts'
10
13
  import type { PullDependencies } from './pull-dependencies.ts'
11
- import { comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
14
+ import { askedOf, comparedWith, reviewsByVersion, reviewsOf } from './pull-dependency-reviews.ts'
12
15
  import { eachOf } from './queue.ts'
13
16
  import type { PublishedReview, RepoReviewState } from './repository-dependency-reviews.ts'
14
- import type { DependencyReviewEntry, ReviewedDependencies } from './reviewed-dependencies.ts'
17
+ import { type DependencyReviewEntry, type ReviewedDependencies, askReviewed } from './reviewed-dependencies.ts'
15
18
 
16
19
  const FORMAT_AT_ONCE = 8
17
20
  // The longest comment told, past which none is.
@@ -21,11 +24,11 @@ const MAX_FORMATTED = 1_000_000
21
24
  const REVIEWS_AT_ONCE = 200
22
25
 
23
26
  // `review` as the hook is given it: each version with the integrity and
24
- // shasum the review keeps of the tarball it read, and the version it is of
25
- // with the patch it is of, where it is a patched one's.
27
+ // shasum the review keeps of the tarball it read, and the patch it is of,
28
+ // where it is a patched one's.
26
29
  function entryOf(review: DependencyReview): DependencyReviewEntry {
27
30
  return { ecosystem: 'npm', old: review.basePackage === null ? null : { name: review.basePackage, version: review.baseVersion ?? '', integrity: review.baseIntegrity ?? '',
28
- ...review.baseShasum ? { shasum: review.baseShasum } : {} },
31
+ ...review.baseShasum ? { shasum: review.baseShasum } : {}, ...review.basePatchHash ? { patchHash: review.basePatchHash } : {} },
29
32
  new: { name: review.package, version: review.version, integrity: review.integrity, ...review.shasum ? { shasum: review.shasum } : {},
30
33
  ...review.patchHash ? { patchHash: review.patchHash } : {} },
31
34
  status: review.status!, coverage: review.coverage === 'full' ? 'full' : 'partial', comment: review.comment,
@@ -63,17 +66,22 @@ export function withFormatted<T extends DependencyReview>(reviewed: ReviewedDepe
63
66
  })
64
67
  }
65
68
 
66
- // The ids of those of `reviews` `user` published of the versions `told`
67
- // adds, as its lockfiles lock each: of its version, of an integrity it is
68
- // locked with and of its patch, whole or compared with a version it was
69
- // (pull-dependency-reviews.ts reviewsOf, comparedWith).
70
- function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string): Set<string> {
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,
72
+ // compared with another package's version, or compared with a version it was
73
+ // (pull-dependency-reviews.ts reviewsOf, comparedWith), or, `any`, with any
74
+ // version of its package.
75
+ interface Own { review: PublishedReview; pkgs: LockedPackage[] }
76
+ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: string, any: boolean): Map<string, Own> {
71
77
  // Theirs by the version they are of, each version probed once.
72
78
  const theirs = reviewsByVersion(reviews.filter(review => review.id !== undefined && review.reviewer === user))
73
- const mine = new Set<string>()
79
+ const mine = new Map<string, Own>()
74
80
  if (theirs.size === 0) return mine
75
81
  for (const pkg of told.lockfiles.flatMap(dir => 'added' in dir ? dir.added : [])) {
76
- for (const review of reviewsOf(pkg, theirs)) if (comparedWith(review, pkg, pkg.was ?? [])) mine.add(review.id!)
82
+ for (const review of reviewsOf(pkg, theirs)) {
83
+ if (comparedWith(review, pkg, any ? 'any' : pkg.was ?? [])) (mine.get(review.id!) ?? mine.set(review.id!, { review, pkgs: [] }).get(review.id!)!).pkgs.push(pkg)
84
+ }
77
85
  }
78
86
  return mine
79
87
  }
@@ -81,12 +89,26 @@ function ownOfPull(told: PullDependencies, reviews: PublishedReview[], user: str
81
89
  // The comment the host formats of `user`'s reviews of the versions pull
82
90
  // request `number` of `repository` adds (`told`), those its review's state
83
91
  // tells of, published to a team counting for it; none where it has none.
92
+ // A review is left out where every version it is of, as locked, wants no
93
+ // comment of it there: the host's `lookup` passes it already, or `user`'s
94
+ // own comments there (of `commented`, the reviews its comments make) review
95
+ // it with the same verdict, as copying it would but repeat them: by their
96
+ // latest of it, which tells where they stand there (pull-dependency-
97
+ // reviews.ts stancesOf), an older one of that verdict not counting. A
98
+ // version `lookup` fails to answer of keeps its review. Where the host reads
99
+ // reviews of comments (`parseComments`), what a review was compared with is
100
+ // its to weigh, so one compared with any version is given.
84
101
  export async function formattedPull(reviewed: ReviewedDependencies | null, db: Pick<DependencyReviewStore, 'listOwnDependencyReviewsById'>, user: string,
85
- told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }): Promise<string | null> {
102
+ told: PullDependencies, state: RepoReviewState | null, pullRequest: { repository: string; number: number }, commented: PublishedReview[] = []): Promise<string | null> {
86
103
  if (!reviewed?.formatDependencyReviews || !state) return null
87
- const mine = ownOfPull(told, state.reviews, user)
104
+ const mine = ownOfPull(told, state.reviews, user, reviewed.parseComments !== undefined)
88
105
  if (mine.size === 0) return null
89
- const ids = [...mine], reviews: DependencyReview[] = []
106
+ const { passed } = await askReviewed(reviewed.lookup, new Map([...mine.values()].flatMap(({ pkgs }) => pkgs.map(askedOf))))
107
+ const there = reviewsByVersion(commented.filter(review => review.reviewer === user))
108
+ const stands = (pkg: LockedPackage) => reviewsOf(pkg, there).reduce<PublishedReview | null>((one, other) => one && one.time >= other.time ? one : other, null)?.status
109
+ const ids = [...mine].filter(([, { review, pkgs }]) => pkgs.some(pkg => !passed.has(askedOf(pkg)[0]) && stands(pkg) !== review.status)).map(([id]) => id)
110
+ if (ids.length === 0) return null
111
+ const reviews: DependencyReview[] = []
90
112
  for (let at = 0; at < ids.length; at += REVIEWS_AT_ONCE) reviews.push(...await db.listOwnDependencyReviewsById(user, ids.slice(at, at + REVIEWS_AT_ONCE)))
91
113
  return formatOwn(reviewed, user, reviews, pullRequest)
92
114
  }
@@ -6,10 +6,11 @@ import { REVIEW_VERDICTS, type ReviewSummary, type ReviewVerdict, allowedReviewV
6
6
 
7
7
  // A review is of a version, as npm's registry has it, by its integrity; of
8
8
  // it as pnpm patches it (`patchHash`, the patch's hash as a lockfile names
9
- // it), where it is patched; and compared with a version (its base), or none.
9
+ // it), where it is patched; and compared with a version (its base), or none,
10
+ // that as a patch changes it too (`basePatchHash`), where named so.
10
11
  export interface ReviewContext {
11
12
  ecosystem: 'npm'; package: string; version: string; integrity: string; patchHash: string | null
12
- basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null
13
+ basePackage: string | null; baseVersion: string | null; baseIntegrity: string | null; basePatchHash: string | null
13
14
  }
14
15
  // The shasums (sha1s, in hex) of the tarballs a review reads, its version's
15
16
  // and its base's, where npm tells them: each held, with its integrity, to the
@@ -67,7 +68,8 @@ CREATE TABLE IF NOT EXISTS managed_dependency_review (
67
68
  base_package TEXT NOT NULL, base_version TEXT NOT NULL, base_integrity TEXT NOT NULL,
68
69
  time INTEGER NOT NULL, revision INTEGER NOT NULL, published_at INTEGER, revoked_at INTEGER, files TEXT,
69
70
  status TEXT CHECK (status IN ('accept', 'accept-with-nits', 'request-changes', 'reject')), comment TEXT NOT NULL DEFAULT '',
70
- shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT
71
+ shasum TEXT NOT NULL DEFAULT '', base_shasum TEXT NOT NULL DEFAULT '', patch_hash TEXT NOT NULL DEFAULT '', patch_source TEXT,
72
+ base_patch_hash TEXT NOT NULL DEFAULT ''
71
73
  ) STRICT;
72
74
  CREATE INDEX IF NOT EXISTS managed_dependency_review_context_idx
73
75
  ON managed_dependency_review(ecosystem, package, version, integrity, base_package, base_version, base_integrity, time);
@@ -87,22 +89,23 @@ CREATE INDEX IF NOT EXISTS managed_dependency_review_team_idx ON managed_depende
87
89
  `
88
90
  // The columns added since the table was, for a database that has it already.
89
91
  export const DEPENDENCY_REVIEW_COLUMNS = [['shasum', "TEXT NOT NULL DEFAULT ''"], ['base_shasum', "TEXT NOT NULL DEFAULT ''"],
90
- ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT']] as const
91
- // Each author's one draft of a comparison, its patch's too, made once those
92
- // columns are: the index held to it before patches were reviewed gone.
92
+ ['patch_hash', "TEXT NOT NULL DEFAULT ''"], ['patch_source', 'TEXT'], ['base_patch_hash', "TEXT NOT NULL DEFAULT ''"]] as const
93
+ // Each author's one draft of a comparison, its patches' too, made once those
94
+ // columns are: those held to it before patches, then its base's, were reviewed gone.
93
95
  export const DEPENDENCY_REVIEW_INDEXES = `
94
96
  DROP INDEX IF EXISTS managed_dependency_review_unpublished_idx;
95
- CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_draft_idx
96
- ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity)
97
+ DROP INDEX IF EXISTS managed_dependency_review_draft_idx;
98
+ CREATE UNIQUE INDEX IF NOT EXISTS managed_dependency_review_drafts_idx
99
+ ON managed_dependency_review(user_id, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash)
97
100
  WHERE published_at IS NULL;`
98
- const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '']
101
+ const values = (c: ReviewContext) => [c.ecosystem, c.package, c.version, c.integrity, c.patchHash ?? '', c.basePackage ?? '', c.baseVersion ?? '', c.baseIntegrity ?? '', c.basePatchHash ?? '']
99
102
  const targetWhere = 'ecosystem = ? AND package = ? AND version = ? AND integrity = ? AND patch_hash = ?'
100
- const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ?`
103
+ const contextWhere = `${targetWhere} AND base_package = ? AND base_version = ? AND base_integrity = ? AND base_patch_hash = ?`
101
104
  // Its author by the login they reviewed as, and by the name the app's user
102
105
  // has now (null once they are none, or have none), as the lists show them.
103
106
  const columns = `id, user_id AS user, user_login AS userLogin, (SELECT n.name FROM managed_user n WHERE n.id = user_id) AS userName, ecosystem, package, version, integrity,
104
107
  NULLIF(patch_hash, '') AS patchHash, NULLIF(base_package, '') AS basePackage, NULLIF(base_version, '') AS baseVersion, NULLIF(base_integrity, '') AS baseIntegrity,
105
- NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
108
+ NULLIF(base_patch_hash, '') AS basePatchHash, NULLIF(shasum, '') AS shasum, NULLIF(base_shasum, '') AS baseShasum, patch_source AS patchSource,
106
109
  time, revision, published_at AS publishedAt, revoked_at AS revokedAt, files, status, comment`
107
110
  const conflict = () => { throw new ManagedMutationError(409, 'review-conflict') }
108
111
  // What a review keeps of the bytes it read: its tarballs' shasums, and where
@@ -225,7 +228,7 @@ async function listContext(db: ManagedSql, context: ReviewContext, user: string,
225
228
  AND (user_id = ? OR (published_at IS NOT NULL AND EXISTS (
226
229
  SELECT 1 FROM managed_dependency_review_team rt JOIN managed_team t ON t.id = rt.team_id JOIN managed_user u ON u.id = ?
227
230
  WHERE rt.review_id = r.id AND ${reviewsIn(false)})))
228
- ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 8), user, user)
231
+ ORDER BY time, id`).all(...values(context).slice(0, allBases ? 5 : 9), user, user)
229
232
  return expandReviews(db, rows, user)
230
233
  }
231
234
 
@@ -329,8 +332,8 @@ export function dependencyReviewMethods(db: ManagedSql): DependencyReviewStore {
329
332
  if (await unpublished()) return conflict()
330
333
  const next = randomUUID()
331
334
  await db.prepare(`INSERT INTO managed_dependency_review
332
- (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, shasum, base_shasum, patch_source, time, revision)
333
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
335
+ (id, user_id, user_login, ecosystem, package, version, integrity, patch_hash, base_package, base_version, base_integrity, base_patch_hash, shasum, base_shasum, patch_source, time, revision)
336
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1)`).run(next, user.id, user.login, ...values(context), ...shasums(tarballs), now)
334
337
  return next
335
338
  }
336
339
  if (change.action === 'start') {