@preventive/triage 1.0.0-alpha.43 → 1.0.0-alpha.45

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 (186) hide show
  1. package/common/bundle-compare-diff.js +2 -167
  2. package/common/bundle-compare-versions.js +172 -0
  3. package/common/bundle-comparison.d.ts +8 -0
  4. package/common/bundle-comparison.js +62 -0
  5. package/common/bundle-sources.js +20 -1
  6. package/common/default-scan-models.ts +1 -1
  7. package/common/dependency-reviews.d.ts +0 -5
  8. package/common/dependency-reviews.js +0 -17
  9. package/common/managed/agent-tasks.ts +292 -0
  10. package/common/managed/github-agents.ts +92 -0
  11. package/common/managed/github-logins.ts +49 -0
  12. package/common/managed/roles.ts +7 -0
  13. package/common/managed/routes.js +91 -10
  14. package/common/managed/team-app.d.ts +5 -2
  15. package/common/managed/team-app.js +2 -2
  16. package/common/server-info.ts +11 -0
  17. package/common/workspace-app.js +19 -3
  18. package/out/brotli-fallback.js +3 -3
  19. package/out/chunk-2XUEZHIP.js +18 -18
  20. package/out/chunk-2ZDZWLFY.js +1 -0
  21. package/out/chunk-3PS4KWD2.js +10 -0
  22. package/out/chunk-5DHL5NG3.js +2 -0
  23. package/out/chunk-6HNXNIQY.js +52 -0
  24. package/out/chunk-7C7DWL7I.js +1 -0
  25. package/out/chunk-AFLZH7WG.js +1 -0
  26. package/out/chunk-BC2UCLFJ.js +1 -0
  27. package/out/chunk-C4Z6ZBXV.js +6 -6
  28. package/out/chunk-GDPCLSOS.js +2 -0
  29. package/out/chunk-GO7FT4OD.js +1 -0
  30. package/out/chunk-HMAJDVXN.js +1 -0
  31. package/out/chunk-I2MDGSQX.js +3 -0
  32. package/out/chunk-IYPY47MC.js +1 -0
  33. package/out/chunk-IZ7POWI3.js +18 -0
  34. package/out/chunk-JCIIBLKR.js +1 -0
  35. package/out/chunk-NPW52BM2.js +17 -0
  36. package/out/chunk-NRPC74AM.js +1 -1
  37. package/out/chunk-NV7ES4EW.js +1 -0
  38. package/out/chunk-OKRLLE5I.js +17 -0
  39. package/out/chunk-OOJM4CTU.js +1 -1
  40. package/out/chunk-PNHBZGDD.js +1 -1
  41. package/out/chunk-PTGDYLNS.js +36 -0
  42. package/out/chunk-PXK7EU4V.js +1 -0
  43. package/out/chunk-Q6MVYGYV.js +3 -0
  44. package/out/chunk-QB4CBOX2.js +1 -0
  45. package/out/chunk-QRD6GIG5.js +229 -0
  46. package/out/chunk-R3NZFXVR.js +1 -0
  47. package/out/chunk-R5O6FAW4.js +1 -1
  48. package/out/chunk-SXV2T5C4.js +80 -0
  49. package/out/chunk-TUII34K2.js +1 -1
  50. package/out/chunk-VFWMQ3LG.js +2 -0
  51. package/out/chunk-VH4XMZIW.js +2 -0
  52. package/out/chunk-WFYLMF6Z.js +10 -0
  53. package/out/chunk-WI7Z5A2T.js +6 -0
  54. package/out/chunk-WQ74ZBZF.js +7 -0
  55. package/out/chunk-XVBEOGOS.js +3 -0
  56. package/out/client-managed-import.js +3 -3
  57. package/out/client-managed.js +31 -35
  58. package/out/client-sync.js +11 -11
  59. package/out/compare.js +35 -0
  60. package/out/dialogs.js +51 -0
  61. package/out/github-issue-authorized.html +1 -1
  62. package/out/github-issue-authorized.js +1 -1
  63. package/out/graph.js +17 -17
  64. package/out/index.html +31 -31
  65. package/out/prism.js +14 -14
  66. package/out/scan.js +2 -0
  67. package/out/terminal.js +294 -293
  68. package/out/view.css +1 -1
  69. package/out/view.js +16 -107
  70. package/package.json +55 -6
  71. package/risk/actions/findings.js +156 -0
  72. package/risk/actions/resolve.js +219 -0
  73. package/risk/actions/scripts/commands.js +182 -0
  74. package/risk/actions/scripts/grade.js +113 -0
  75. package/risk/actions/scripts/packages.js +123 -0
  76. package/risk/actions/scripts/shell.js +165 -0
  77. package/risk/actions/uses.js +76 -0
  78. package/risk/actions/workflow.js +110 -0
  79. package/risk/files/hosts.js +6 -6
  80. package/risk/files/readability.js +23 -17
  81. package/risk/files/runs-code.js +18 -6
  82. package/risk/files/script.js +7 -3
  83. package/risk/files/stamps.js +8 -7
  84. package/risk/index.d.ts +68 -1
  85. package/risk/index.js +6 -2
  86. package/risk/npm/assess.js +13 -8
  87. package/risk/npm/compare.js +34 -10
  88. package/risk/npm/dependencies.js +11 -0
  89. package/risk/npm/files.js +413 -2
  90. package/risk/npm/tarball.js +56 -73
  91. package/server-managed/agent-merges.ts +198 -0
  92. package/server-managed/app-agents.ts +30 -0
  93. package/server-managed/avatar-store.ts +1 -0
  94. package/server-managed/commit-coauthors.ts +83 -0
  95. package/server-managed/commit-lockfiles.ts +62 -0
  96. package/server-managed/comparison.ts +41 -0
  97. package/server-managed/db-methods.ts +29 -10
  98. package/server-managed/db-neon.ts +30 -2
  99. package/server-managed/db-schema.ts +9 -2
  100. package/server-managed/db.ts +7 -0
  101. package/server-managed/dependabot-access.ts +60 -0
  102. package/server-managed/dependabot-alerts.ts +185 -0
  103. package/server-managed/dependency-review-comments.ts +97 -0
  104. package/server-managed/dependency-reviews.ts +65 -15
  105. package/server-managed/github-accounts.ts +33 -0
  106. package/server-managed/github-actions.ts +71 -0
  107. package/server-managed/github-app.ts +23 -9
  108. package/server-managed/github-errors.ts +2 -0
  109. package/server-managed/github-link-oauth.ts +69 -0
  110. package/server-managed/github-links.ts +204 -0
  111. package/server-managed/github-oauth.ts +5 -2
  112. package/server-managed/github-users.ts +30 -0
  113. package/server-managed/http.ts +1219 -81
  114. package/server-managed/index.ts +6 -2
  115. package/server-managed/locked-packages.ts +48 -16
  116. package/server-managed/lockfile-scope.ts +49 -0
  117. package/server-managed/npm-delta-worker.js +23 -0
  118. package/server-managed/npm-delta.ts +173 -0
  119. package/server-managed/npm-insights.ts +20 -11
  120. package/server-managed/npm-kept.ts +51 -4
  121. package/server-managed/npm-loads.ts +20 -13
  122. package/server-managed/npm-packages.ts +24 -64
  123. package/server-managed/pretty-print.ts +14 -9
  124. package/server-managed/public-workspace.ts +26 -8
  125. package/server-managed/pull-comment-reviews.ts +161 -0
  126. package/server-managed/pull-dependencies.ts +280 -0
  127. package/server-managed/pull-dependency-reviews.ts +318 -0
  128. package/server-managed/pull-reviews.ts +205 -0
  129. package/server-managed/release-commits.ts +84 -0
  130. package/server-managed/repository-actions.ts +209 -0
  131. package/server-managed/repository-agents.ts +220 -0
  132. package/server-managed/repository-browser.ts +54 -13
  133. package/server-managed/repository-changes.ts +284 -0
  134. package/server-managed/repository-code.ts +52 -0
  135. package/server-managed/repository-dependency-reviews.ts +135 -0
  136. package/server-managed/repository-history.ts +445 -0
  137. package/server-managed/repository-issues.ts +181 -0
  138. package/server-managed/repository-pulse.ts +432 -0
  139. package/server-managed/repository-risk-read.ts +165 -0
  140. package/server-managed/repository-risk.ts +116 -106
  141. package/server-managed/reviewed-dependencies.ts +149 -0
  142. package/server-managed/session.ts +9 -5
  143. package/server-managed/sql.ts +1 -1
  144. package/server-managed/storage-stores.ts +5 -0
  145. package/server-managed/team-app.ts +54 -14
  146. package/server-managed/workspace-shares.ts +4 -1
  147. package/server.ts +11 -0
  148. package/out/chunk-2KBF5TZ7.js +0 -2
  149. package/out/chunk-35VE6CDH.js +0 -2
  150. package/out/chunk-3BZ7JERB.js +0 -1
  151. package/out/chunk-4F6JSF57.js +0 -3
  152. package/out/chunk-4XCDFGDP.js +0 -10
  153. package/out/chunk-7RU5EDRO.js +0 -226
  154. package/out/chunk-A7M4GV7M.js +0 -1
  155. package/out/chunk-CLPKNNC7.js +0 -51
  156. package/out/chunk-CMQA4DM6.js +0 -1
  157. package/out/chunk-CVVJAXVY.js +0 -2
  158. package/out/chunk-DIJJNTRH.js +0 -10
  159. package/out/chunk-GJ4IUCNS.js +0 -1
  160. package/out/chunk-GNXOKIGP.js +0 -80
  161. package/out/chunk-GZ4MS3TE.js +0 -13
  162. package/out/chunk-IU3CCINR.js +0 -3
  163. package/out/chunk-K3X5EJBQ.js +0 -2
  164. package/out/chunk-KEX2ATEW.js +0 -2
  165. package/out/chunk-KYCNJVB7.js +0 -1
  166. package/out/chunk-LAAB5SZT.js +0 -2
  167. package/out/chunk-NWZ4PVPN.js +0 -1
  168. package/out/chunk-OSIMGFUF.js +0 -1
  169. package/out/chunk-RFZQQXSG.js +0 -17
  170. package/out/chunk-RSHMVYNS.js +0 -1
  171. package/out/chunk-TZ5KB2Y5.js +0 -10
  172. package/out/chunk-UNTRGE26.js +0 -2
  173. package/out/chunk-UXNUAIIC.js +0 -33
  174. package/out/chunk-UYAXVRVL.js +0 -1
  175. package/out/chunk-V3ME6FI5.js +0 -2
  176. package/out/chunk-V5O7M2YT.js +0 -1
  177. package/out/chunk-VIHGO77Y.js +0 -1
  178. package/out/chunk-VQJCXGIY.js +0 -7
  179. package/out/chunk-W4J3MGLB.js +0 -1
  180. package/out/chunk-WGG7KQUH.js +0 -1
  181. package/out/chunk-WZDTZE64.js +0 -1
  182. package/out/chunk-XOCAPDCM.js +0 -1
  183. package/out/chunk-XYFXXB2G.js +0 -10
  184. package/out/chunk-YVZH5SHP.js +0 -1
  185. package/out/chunk-ZBBOBQ43.js +0 -1
  186. package/out/chunk-ZMQQCGF6.js +0 -2
@@ -0,0 +1,52 @@
1
+ // Reading a directory of a repository at a commit for the managed code viewer
2
+ // (GET /api/admin/repositories/code): its tree's tarball as GitHub archives
3
+ // it, verified against the tree's id and kept in upstream's disk cache as
4
+ // bundle builds keep theirs (getRepoTreeTarball), and its files as the npm
5
+ // viewer reads a package's (npm-packages.ts npmFileRows). Readers asking for
6
+ // the same directory meanwhile share its body, a load among the npm viewer's
7
+ // active ones (npm-loads.ts sharedLoad).
8
+ import { Buffer } from 'node:buffer'
9
+ import { encodeBrotli } from './brotli.ts'
10
+ import { MAX_NPM_PACKAGE_BYTES, MAX_NPM_PACKAGE_FILES, NpmPackageError, npmFileRows } from './npm-packages.ts'
11
+ import { type NpmLoad, readTarballFiles, sharedLoad } from './npm-loads.ts'
12
+
13
+ // As much as a package may hold: the viewer holds every file in memory.
14
+ export const MAX_REPOSITORY_CODE_FILES = MAX_NPM_PACKAGE_FILES
15
+ export const MAX_REPOSITORY_CODE_BYTES = MAX_NPM_PACKAGE_BYTES
16
+
17
+ // Whether a directory's files fit, by GitHub's listing of its tree and every
18
+ // tree under it (repository-browser.ts repositoryTreeFiles): asked before
19
+ // its tarball is, which may run to hundreds of MiB. One GitHub cut short
20
+ // (null) has too many.
21
+ export function repositoryCodeFits(files: { files: number; bytes: number } | null): boolean {
22
+ return files !== null && files.files <= MAX_REPOSITORY_CODE_FILES && files.bytes <= MAX_REPOSITORY_CODE_BYTES
23
+ }
24
+
25
+ // The directory read: the repository by its id and name, the commit, the
26
+ // directory (`''` for the root) and its tree's id.
27
+ export interface RepositoryCodeInput { repoId: number; repo: string; commit: string; path: string; tree: string }
28
+
29
+ // A package's refusals, as a directory's: past the bounds, or an archive
30
+ // @preventive/archive refuses, as it does one holding a symlink that climbs
31
+ // past the repository's root, or an absolute one.
32
+ const DIRECTORY_ERRORS: Record<string, [number, string]> = { 'package-too-large': [413, 'directory-too-large'], 'bad-tarball': [422, 'directory-unreadable'] }
33
+ const directoryError = (err: unknown) => {
34
+ const as = err instanceof NpmPackageError ? DIRECTORY_ERRORS[err.message] : undefined
35
+ return as ? new NpmPackageError(...as) : err
36
+ }
37
+
38
+ // The directory as the viewer reads it, as brotli-encoded JSON: `{ repoId,
39
+ // repo, commit, path, tree, files }`, its files as npmFileRows gives them,
40
+ // by their paths in the directory, from `tarball`, the tree's.
41
+ export function loadRepositoryCodeBody(input: RepositoryCodeInput, tarball: () => Promise<Uint8Array>): NpmLoad<Buffer> {
42
+ const { repoId, repo, commit, path, tree } = input
43
+ return sharedLoad(`repository ${repoId} ${repo} ${commit} ${path} ${tree}`, async () => {
44
+ let files
45
+ // A symlink may reach the repository's root, as a monorepo package's
46
+ // LICENSE links the root's, and no further: the directory's depth, less
47
+ // the level the archive's root already stands above its top directory.
48
+ try { files = npmFileRows(await readTarballFiles(await tarball(), { symlinksAbove: path.split('/').length - 1 })) }
49
+ catch (err) { throw directoryError(err) }
50
+ return encodeBrotli(Buffer.from(JSON.stringify({ repoId, repo, commit, path, tree, files })))
51
+ }, 'repository-busy')
52
+ }
@@ -0,0 +1,135 @@
1
+ // A connected repository's dependency review, as an admin sets it, and the
2
+ // reviews that pass its pull requests' dependencies (pull-dependency-reviews.ts).
3
+ // Enabled, each package version its open pull requests' lockfiles lock needs
4
+ // as many published reviews as `required`; those its lockfiles locked at
5
+ // `since`, a commit (null for none), none; of the lockfiles it holds to
6
+ // (`lockfiles`, lockfile-scope.ts), every one by default. It is in effect only where a team
7
+ // that reviews dependencies has the repository, which is where reviews that
8
+ // count are published, and not revoked: each reviewer's latest of a version
9
+ // tells where they stand on it, a reject holding it unreviewed whatever
10
+ // others passed it till they accept it again; and a reviewer standing on
11
+ // accepting it passes it by a review of theirs that is full (every file
12
+ // checked; a partial review counts for nothing yet) and accepting (Accept,
13
+ // or Accept with nits).
14
+ import type { ManagedSql } from './sql.ts'
15
+ import { type LockfileScope, scopeText, storedScope } from './lockfile-scope.ts'
16
+ import { reviewsIn } from './dependency-reviews.ts'
17
+ import { type ReviewVerdict, summarizeReview } from '../common/dependency-reviews.js'
18
+
19
+ export const REPOSITORY_DEPENDENCY_REVIEW_COLUMNS = [['dependency_review', 'INTEGER NOT NULL DEFAULT 0'],
20
+ ['dependency_reviews_required', 'INTEGER NOT NULL DEFAULT 1'], ['dependency_review_since', 'TEXT'], ['dependency_review_lockfiles', 'TEXT']] as const
21
+ export const MAX_REQUIRED_REVIEWS = 10
22
+ export const SINCE_COMMIT = /^[a-f\d]{40}$/u
23
+
24
+ export interface RepoDependencyReview { enabled: boolean; required: number; since: string | null; lockfiles: LockfileScope }
25
+ // A review published of the version it is of: its package, version and
26
+ // npm's integrity of it, the patch it is of (none here, the app reviewing no
27
+ // patch yet), the version it was compared with (none for a whole package's),
28
+ // who wrote it (`reviewer`, their id, else their login then), its verdict,
29
+ // whether it checked every file (`full`), and when it was published.
30
+ // One made in a pull request's comments (`comment`) counts for it alone;
31
+ // one published here has its `id`.
32
+ export interface PublishedReview {
33
+ id?: string; package: string; version: string; integrity: string; patchHash?: string; basePackage: string | null; baseVersion: string | null
34
+ reviewer: string; status: ReviewVerdict; full: boolean; time: number; comment?: true
35
+ }
36
+ // A repository's review in effect for a reader: its settings, whether they
37
+ // publish reviews to one of the teams that count (`canReview`), and the
38
+ // published reviews of the packages asked.
39
+ export interface RepoReviewState extends Omit<RepoDependencyReview, 'enabled'> { canReview: boolean; reviews: PublishedReview[] }
40
+
41
+ export interface RepositoryDependencyReviewStore {
42
+ listRepoDependencyReviews(): Promise<Map<number, RepoDependencyReview>>
43
+ // The teams whose published reviews count for each repository (COUNTING_TEAM),
44
+ // by name.
45
+ listRepoReviewTeams(): Promise<Map<number, { id: string; name: string }[]>>
46
+ // Sets a repository's review, its commit and lockfiles too but where
47
+ // `since` or `lockfiles` is undefined, which keeps it; the setting then, or
48
+ // null for no repository.
49
+ setRepoDependencyReview(repoId: number, setting: Omit<RepoDependencyReview, 'since' | 'lockfiles'> & { since?: string | null; lockfiles?: LockfileScope }): Promise<RepoDependencyReview | null>
50
+ repoDependencyReviewState(repoId: number, user: string, packages: string[]): Promise<RepoReviewState | null>
51
+ // Which of `users` publish reviews to a team counting for repository
52
+ // `repoId`, whose reviews its pull requests' comments make count.
53
+ listRepoReviewers(repoId: number, users: string[]): Promise<Set<string>>
54
+ }
55
+
56
+ type SettingRow = { repoId: number; enabled: number; required: number; since: string | null; lockfiles: string | null }
57
+ const setting = (row: SettingRow): RepoDependencyReview => ({ enabled: row.enabled === 1, required: row.required, since: row.since, lockfiles: storedScope(row.lockfiles) })
58
+ // Teams whose published reviews count for repository `?`: that review
59
+ // dependencies and have it, not hidden.
60
+ const COUNTING_TEAM = `t.hidden = 0 AND t.dependency_review = 1 AND EXISTS (
61
+ SELECT 1 FROM managed_team_repo tr WHERE tr.team_id = t.id AND tr.repo_id = ?)`
62
+ const PACKAGES_AT_ONCE = 500
63
+
64
+ // The published and unrevoked reviews of `packages` in teams counting for
65
+ // repository `repoId`, each with whether it is full, a few hundred packages
66
+ // a query.
67
+ async function publishedReviews(db: ManagedSql, repoId: number, packages: string[]): Promise<PublishedReview[]> {
68
+ const found: PublishedReview[] = []
69
+ for (let at = 0; at < packages.length; at += PACKAGES_AT_ONCE) {
70
+ const names = packages.slice(at, at + PACKAGES_AT_ONCE)
71
+ const rows = await db.prepare(`SELECT r.id, r.user_id AS userId, r.user_login AS userLogin, r.package, r.version, r.integrity,
72
+ NULLIF(r.base_package, '') AS basePackage, NULLIF(r.base_version, '') AS baseVersion, r.files, r.status, r.published_at AS publishedAt
73
+ FROM managed_dependency_review r
74
+ WHERE r.ecosystem = 'npm' AND r.published_at IS NOT NULL AND r.revoked_at IS NULL AND r.status IS NOT NULL
75
+ AND r.package IN (${names.map(() => '?').join(',')})
76
+ AND EXISTS (SELECT 1 FROM managed_dependency_review_team rt JOIN managed_team t ON t.id = rt.team_id
77
+ WHERE rt.review_id = r.id AND ${COUNTING_TEAM})`).all(...names, repoId) as
78
+ { id: string; userId: string | null; userLogin: string; package: string; version: string; integrity: string
79
+ basePackage: string | null; baseVersion: string | null; files: string | null; status: ReviewVerdict; publishedAt: number }[]
80
+ if (rows.length === 0) continue
81
+ const entries = await db.prepare(`SELECT review_id AS reviewId, file, status FROM managed_dependency_file_review
82
+ WHERE review_id IN (${rows.map(() => '?').join(',')})`).all(...rows.map(row => row.id)) as { reviewId: string; file: string; status: ReviewVerdict | null }[]
83
+ for (const row of rows) {
84
+ const snapshot = row.files === null ? null : JSON.parse(row.files) as string[] | { paths: string[]; nonTextFiles: string[] }
85
+ // A snapshot of paths alone, before non-text files were told, can't be full.
86
+ const files = Array.isArray(snapshot) ? snapshot : snapshot?.paths ?? null
87
+ const nonText = Array.isArray(snapshot) ? null : snapshot?.nonTextFiles ?? []
88
+ const full = summarizeReview(entries.filter(entry => entry.reviewId === row.id), files, nonText).coverage === 'full'
89
+ found.push({ id: row.id, package: row.package, version: row.version, integrity: row.integrity, basePackage: row.basePackage, baseVersion: row.baseVersion,
90
+ reviewer: row.userId ?? `login:${row.userLogin.toLowerCase()}`, status: row.status, full, time: Number(row.publishedAt) })
91
+ }
92
+ }
93
+ return found
94
+ }
95
+
96
+ export function repositoryDependencyReviewMethods(db: ManagedSql): RepositoryDependencyReviewStore {
97
+ const columns = `repo_id AS repoId, dependency_review AS enabled, dependency_reviews_required AS required, dependency_review_since AS since,
98
+ dependency_review_lockfiles AS lockfiles`
99
+ return {
100
+ async listRepoDependencyReviews() {
101
+ const rows = await db.prepare(`SELECT ${columns} FROM managed_selected_repo`).all() as SettingRow[]
102
+ return new Map(rows.map(row => [row.repoId, setting(row)]))
103
+ },
104
+ async listRepoReviewTeams() {
105
+ const rows = await db.prepare(`SELECT DISTINCT tr.repo_id AS repoId, t.id AS id, t.name AS name FROM managed_team_repo tr
106
+ JOIN managed_team t ON t.id = tr.team_id WHERE t.hidden = 0 AND t.dependency_review = 1 ORDER BY t.name, t.id`).all() as { repoId: number; id: string; name: string }[]
107
+ const teams = new Map<number, { id: string; name: string }[]>()
108
+ for (const { repoId, id, name } of rows) teams.set(repoId, [...teams.get(repoId) ?? [], { id, name }])
109
+ return teams
110
+ },
111
+ async setRepoDependencyReview(repoId, { enabled, required, since, lockfiles }) {
112
+ const set: [string, unknown][] = [['dependency_review', enabled ? 1 : 0], ['dependency_reviews_required', required],
113
+ ...since === undefined ? [] : [['dependency_review_since', since] as [string, unknown]],
114
+ ...lockfiles === undefined ? [] : [['dependency_review_lockfiles', scopeText(lockfiles)] as [string, unknown]]]
115
+ const { changes } = await db.prepare(`UPDATE managed_selected_repo SET ${set.map(([column]) => `${column} = ?`).join(', ')} WHERE repo_id = ?`)
116
+ .run(...set.map(([, value]) => value), repoId)
117
+ if (Number(changes) === 0) return null
118
+ return setting(await db.prepare(`SELECT ${columns} FROM managed_selected_repo WHERE repo_id = ?`).get(repoId) as SettingRow)
119
+ },
120
+ async listRepoReviewers(repoId, users) {
121
+ if (users.length === 0) return new Set()
122
+ const rows = await db.prepare(`SELECT DISTINCT u.id FROM managed_user u JOIN managed_team t ON t.hidden = 0
123
+ WHERE u.id IN (${users.map(() => '?').join(',')}) AND ${reviewsIn(true)} AND ${COUNTING_TEAM}`).all(...users, repoId) as { id: string }[]
124
+ return new Set(rows.map(row => row.id))
125
+ },
126
+ async repoDependencyReviewState(repoId, user, packages) {
127
+ const row = await db.prepare(`SELECT ${columns} FROM managed_selected_repo WHERE repo_id = ?`).get(repoId) as SettingRow | undefined
128
+ if (!row || row.enabled !== 1) return null
129
+ if (!await db.prepare(`SELECT 1 FROM managed_team t WHERE ${COUNTING_TEAM}`).get(repoId)) return null
130
+ const canReview = await db.prepare(`SELECT 1 FROM managed_team t JOIN managed_user u ON u.id = ?
131
+ WHERE ${reviewsIn(true)} AND ${COUNTING_TEAM}`).get(user, repoId) != null
132
+ return { required: row.required, since: row.since, lockfiles: storedScope(row.lockfiles), canReview, reviews: await publishedReviews(db, repoId, [...new Set(packages)]) }
133
+ },
134
+ }
135
+ }
@@ -0,0 +1,445 @@
1
+ // The commit history the code viewer's History tab draws
2
+ // (GET /api/admin/repositories/history), as `git log --oneline --decorate
3
+ // --graph` shows it: each commit's id, parents, subject, author and time, and
4
+ // the branches and tags pointing at commits. From a revision, a page at a
5
+ // time, of the whole repository or of the commits touching a directory, as
6
+ // GitHub's REST API lists them, for any reader; or, as `--all`, across the
7
+ // repository's most recently committed to branches at once, then on from where
8
+ // those stop, in GraphQL queries, which need a token. A whole repository's is
9
+ // read a page from a commit at a time, each page kept by the commit it starts
10
+ // at (historyFrom): a commit's history never changes, and where a commit read
11
+ // starts a page kept, that page glues on, and those after it.
12
+ import { type Coauthor, MAX_COAUTHORS, type Maker, coauthorsOf } from './commit-coauthors.ts'
13
+ import { GithubApiError, githubJson } from './github-app.ts'
14
+ import { type GraphActor, accountOf, commitAccount } from './github-accounts.ts'
15
+
16
+ export { ACTOR, type GraphAccount, type GraphActor, type NamedAccount, accountOf, actorOf, commitAccount } from './github-accounts.ts'
17
+
18
+ export const HISTORY_PAGE = 100
19
+ // The deepest page read, as far as Older commits goes.
20
+ export const MAX_HISTORY_PAGE = 100
21
+ // `--all`: the branches most recently committed to, of as many as fifty
22
+ // pages of them list, the latest commits of each (as many as a GraphQL connection
23
+ // gives), and the latest tags.
24
+ export const ALL_BRANCHES = 25
25
+ const MAX_HEAD_PAGES = 50
26
+ const ALL_DEPTH = 100
27
+ const ALL_TAGS = 100
28
+ const REF_TIPS = 100
29
+ const MAX_PARENTS = 8
30
+ const MAX_SUBJECT = 1000
31
+ const MAX_NAME = 256
32
+ const SHA = /^[a-f\d]{40}$/u
33
+
34
+ // A commit, its author by name and by their account's login and numeric id
35
+ // (`authorId`, absent from pages kept before it was read), its co-authors
36
+ // (coauthorsOf, absent from pages kept before they were read), with the lines
37
+ // it adds and removes and when it was authored in its author's own time zone
38
+ // (`authorZone`, minutes east of UTC), where GitHub's GraphQL API tells them
39
+ // (null where its REST API lists it).
40
+ export interface HistoryCommit { sha: string; parents: string[]; subject: string; authorName: string | null; authorLogin: string | null; authorId?: number | null
41
+ coauthors?: Coauthor[]; committedAt: number | null; additions?: number | null; deletions?: number | null; authoredAt?: number | null; authorZone?: number | null }
42
+ export interface HistoryRef { name: string; sha: string }
43
+
44
+ const textOf = (value: unknown, max: number) => typeof value === 'string' && value.trim() ? value.trim().slice(0, max) : null
45
+ const timeOf = (value: unknown) => {
46
+ const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
47
+ return Number.isSafeInteger(at) ? at : null
48
+ }
49
+
50
+ const lineCount = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : null
51
+ // The minutes east of UTC an ISO 8601 time is given in: `Z` none.
52
+ const zoneOf = (value: unknown) => {
53
+ const zone = typeof value === 'string' ? /(?:Z|([+-])(\d{2}):?(\d{2}))$/u.exec(value) : null
54
+ return zone ? zone[1] ? (zone[1] === '-' ? -1 : 1) * (Number(zone[2]) * 60 + Number(zone[3])) : 0 : null
55
+ }
56
+
57
+ // A commit as the Commits tab reads it, its subject the message's first
58
+ // line, as `--oneline` shows, its author by name and account, and its
59
+ // co-authors (coauthorsOf, `listed` as GitHub's GraphQL API lists them); null
60
+ // for one GitHub names no commit id for. With `stats`, the GraphQL API's, its
61
+ // lines and its author's time.
62
+ function historyCommit(sha: unknown, parents: unknown[], message: unknown, author: Maker, committedAt: unknown,
63
+ stats: { additions?: unknown; deletions?: unknown; authoredAt?: unknown } | null = null, listed: Maker[] | null = null): HistoryCommit | null {
64
+ if (typeof sha !== 'string' || !SHA.test(sha)) return null
65
+ const lines = stats ? { additions: lineCount(stats.additions), deletions: lineCount(stats.deletions), authoredAt: timeOf(stats.authoredAt),
66
+ authorZone: zoneOf(stats.authoredAt) } : { additions: null, deletions: null, authoredAt: null, authorZone: null }
67
+ return {
68
+ sha,
69
+ parents: parents.filter((parent): parent is string => typeof parent === 'string' && SHA.test(parent)).slice(0, MAX_PARENTS),
70
+ subject: typeof message === 'string' ? message.replaceAll('\r\n', '\n').split('\n', 1)[0]!.trim().slice(0, MAX_SUBJECT) : '',
71
+ authorName: textOf(author.name, MAX_NAME),
72
+ authorLogin: author.account.login,
73
+ authorId: author.account.id,
74
+ coauthors: coauthorsOf(message, author, listed),
75
+ committedAt: timeOf(committedAt),
76
+ ...lines,
77
+ }
78
+ }
79
+
80
+ type RestCommit = { sha?: unknown; parents?: { sha?: unknown }[]; author?: { login?: unknown; id?: unknown } | null
81
+ commit?: { message?: unknown; author?: { name?: unknown; email?: unknown } | null; committer?: { date?: unknown } | null } }
82
+ const restCommit = (item: RestCommit) => historyCommit(item?.sha, Array.isArray(item?.parents) ? item.parents.map(parent => parent?.sha) : [],
83
+ item?.commit?.message, { name: item?.commit?.author?.name, email: item?.commit?.author?.email, account: accountOf(item?.author) }, item?.commit?.committer?.date)
84
+
85
+ const repoApi = (fullName: string) => `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
86
+
87
+ // A page of the commits `commit` reaches, newest first as GitHub lists them,
88
+ // those touching `path` alone where it names a directory; `more` where a
89
+ // full page leaves some for the next, one that may be read.
90
+ export async function repositoryHistory(fullName: string, token: string | null, commit: string, path: string, page: number, fetchImpl: typeof fetch = globalThis.fetch) {
91
+ const params = new URLSearchParams({ sha: commit, per_page: String(HISTORY_PAGE), page: String(page), ...path ? { path } : {} })
92
+ const data = await githubJson(`${repoApi(fullName)}/commits?${params}`, token, fetchImpl)
93
+ if (!Array.isArray(data)) throw new GithubApiError(502, 'github-malformed')
94
+ return { commits: data.flatMap(item => restCommit(item as RestCommit) ?? []), more: data.length >= HISTORY_PAGE && page < MAX_HISTORY_PAGE }
95
+ }
96
+
97
+ // The commits the repository's branches and tags point at, as GitHub's
98
+ // first page of each lists them, to name commits by.
99
+ export async function repositoryRefTips(fullName: string, token: string | null, fetchImpl: typeof fetch = globalThis.fetch) {
100
+ const tips = (list: unknown): HistoryRef[] => Array.isArray(list) ? list.flatMap((item: { name?: unknown; commit?: { sha?: unknown } }) =>
101
+ typeof item?.name === 'string' && item.name && typeof item.commit?.sha === 'string' && SHA.test(item.commit.sha)
102
+ ? [{ name: item.name.slice(0, MAX_NAME), sha: item.commit.sha }] : []) : []
103
+ const [branches, tags] = await Promise.all(['branches', 'tags'].map(kind => githubJson(`${repoApi(fullName)}/${kind}?per_page=${REF_TIPS}`, token, fetchImpl)))
104
+ return { branches: tips(branches), tags: tips(tags) }
105
+ }
106
+
107
+ export type GraphqlError = { type?: unknown; path?: unknown; message?: unknown }
108
+
109
+ const NAMED_ERRORS = new Set(['RATE_LIMITED', 'NOT_FOUND', 'FORBIDDEN'])
110
+ // GitHub's own words for a query it stopped past its time (ten seconds):
111
+ // "Something went wrong while executing your query. This may be the result
112
+ // of a timeout, …", with no type.
113
+ const TIMED_OUT = /\btimeout\b/iu
114
+
115
+ // One GraphQL query with `token`, answered with its `data`: one GitHub answers
116
+ // with errors, but for those the caller reads past (`tolerated`, the fields
117
+ // they name then null), is rate limited, names what isn't there, is refused,
118
+ // as one a GitHub App lacks the permission for is, or a token the scope for
119
+ // (`INSUFFICIENT_SCOPES`, a sign-in's having none), took GitHub too long, or
120
+ // else is malformed, as one GitHub rejects unread is (a field or type its API
121
+ // doesn't know). GitHub's words for errors of none of those first three types
122
+ // are logged, those read past too.
123
+ export async function githubGraphql(query: string, variables: Record<string, unknown>, token: string, fetchImpl: typeof fetch,
124
+ tolerated: (error: GraphqlError) => boolean = () => false) {
125
+ const body = await githubJson('https://api.github.com/graphql', token, fetchImpl, 'POST', { query, variables }) as { data?: unknown; errors?: GraphqlError[] } | null
126
+ const all = Array.isArray(body?.errors) ? body.errors : []
127
+ const unnamed = all.filter(error => !NAMED_ERRORS.has(String(error?.type)))
128
+ if (unnamed.length > 0) {
129
+ console.warn('managed: GitHub answered a query with errors:', JSON.stringify(unnamed.slice(0, 3)
130
+ .map(error => ({ type: error?.type, message: String(error?.message).slice(0, 300), path: error?.path }))))
131
+ }
132
+ const errors = all.filter(error => !tolerated(error))
133
+ if (errors.length > 0) {
134
+ if (errors.some(error => error?.type === 'RATE_LIMITED')) throw new GithubApiError(429, 'github-rate-limited', 60)
135
+ if (errors.some(error => error?.type === 'NOT_FOUND')) throw new GithubApiError(404, 'github-not-found')
136
+ if (errors.some(error => error?.type === 'FORBIDDEN' || error?.type === 'INSUFFICIENT_SCOPES')) throw new GithubApiError(502, 'github-status-403')
137
+ if (errors.some(error => typeof error?.message === 'string' && TIMED_OUT.test(error.message))) throw new GithubApiError(502, 'github-timeout')
138
+ throw new GithubApiError(502, 'github-malformed')
139
+ }
140
+ return body?.data
141
+ }
142
+
143
+ // A tag's target, an annotated tag's own target in turn, through as many as
144
+ // MAX_TAG_DEPTH annotated tags, each object's type naming what it is.
145
+ const MAX_TAG_DEPTH = 4
146
+ const tagTarget = (tags: number): string => `target { __typename oid${tags > 0 ? ` ... on Tag { ${tagTarget(tags - 1)} }` : ''} }`
147
+
148
+ // The branches' tips, a page at a time, each with its commit's date (GitHub
149
+ // orders heads by name alone), and, on the first page, the default branch's
150
+ // tip, wherever its name sorts, and the latest tags.
151
+ const HEADS_QUERY = `query($owner: String!, $name: String!, $after: String, $tags: Int!, $first: Boolean!) {
152
+ repository(owner: $owner, name: $name) {
153
+ defaultBranchRef { name target { oid ... on Commit { committedDate } } }
154
+ branches: refs(refPrefix: "refs/heads/", first: 100, after: $after) {
155
+ pageInfo { hasNextPage endCursor }
156
+ nodes { name target { oid ... on Commit { committedDate } } }
157
+ }
158
+ tags: refs(refPrefix: "refs/tags/", first: $tags, orderBy: { field: TAG_COMMIT_DATE, direction: DESC }) @include(if: $first) {
159
+ nodes { name ${tagTarget(MAX_TAG_DEPTH)} }
160
+ }
161
+ }
162
+ }`
163
+
164
+ // As many commits as gluing kept pages on goes to, in as many rounds of
165
+ // looking them up, each looking up as many commits as tops.
166
+ export const HISTORY_GLUED = 2000
167
+ const MAX_GLUE_ROUNDS = 20
168
+ const GLUE_LOOKUP = 50
169
+
170
+ // The pages of a repository's history kept, each by the commit it starts at
171
+ // (its top): the first page of the history from that commit, which never
172
+ // changes.
173
+ export interface HistoryPages {
174
+ read(tops: string[]): Promise<Map<string, HistoryCommit[]>>
175
+ write(top: string, commits: HistoryCommit[]): Promise<void>
176
+ }
177
+
178
+ // What a commit is read by in GraphQL.
179
+ const COMMIT_FRAGMENT = `fragment historyCommit on Commit { oid message committedDate additions deletions author { name email date user { login databaseId } }
180
+ authors(first: ${MAX_COAUTHORS + 1}) { nodes { name email user { login databaseId } } } parents(first: ${MAX_PARENTS}) { nodes { oid } } }`
181
+ // A query's variables `$<prefix><n>` of `type`, as many as `count`.
182
+ const variablesOf = (prefix: string, count: number, type: string) => Array.from({ length: count }, (_, at) => `$${prefix}${at}: ${type}`).join(', ')
183
+
184
+ // The latest commits of each tip, by its id, `b<n>` the `n`th's.
185
+ const historiesQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('o', count, 'GitObjectID!')}) {
186
+ repository(owner: $owner, name: $name) {
187
+ ${Array.from({ length: count }, (_, at) => `b${at}: object(oid: $o${at}) { ... on Commit { history(first: ${ALL_DEPTH}) { pageInfo { hasNextPage } nodes { ...historyCommit } } } }`).join('\n ')}
188
+ }
189
+ }
190
+ ${COMMIT_FRAGMENT}`
191
+
192
+ type GraphCommit = { oid?: unknown; message?: unknown; committedDate?: unknown; additions?: unknown; deletions?: unknown
193
+ author?: ({ name?: unknown; date?: unknown } & GraphActor) | null; authors?: { nodes?: (({ name?: unknown } & GraphActor) | null)[] } | null
194
+ parents?: { nodes?: { oid?: unknown }[] } }
195
+ type GraphTarget = { __typename?: unknown; oid?: unknown; committedDate?: unknown; target?: GraphTarget | null }
196
+ type GraphRef = { name?: unknown; target?: GraphTarget | null }
197
+ type HeadsPage = { repository?: { defaultBranchRef?: GraphRef | null
198
+ branches?: { pageInfo?: { hasNextPage?: unknown; endCursor?: unknown }; nodes?: GraphRef[] }; tags?: { nodes?: GraphRef[] } } | null }
199
+ type Histories = { repository?: Record<string, { history?: { pageInfo?: { hasNextPage?: unknown }; nodes?: GraphCommit[] } } | null> | null }
200
+
201
+ // The repository's branches, as many as MAX_HEAD_PAGES of them list, each
202
+ // with its tip's time, its default branch and latest tags (an annotated tag
203
+ // by the commit it tags), and whether any branch is left out.
204
+ async function repositoryHeads(owner: string, name: string, token: string, fetchImpl: typeof fetch) {
205
+ const heads: (HistoryRef & { at: number | null })[] = []
206
+ let first: HeadsPage['repository'] = null
207
+ let after: string | null = null
208
+ for (let page = 0; page < MAX_HEAD_PAGES; page++) {
209
+ const data = await githubGraphql(HEADS_QUERY, { owner, name, after, tags: ALL_TAGS, first: page === 0 }, token, fetchImpl) as HeadsPage
210
+ const repository = data?.repository
211
+ if (!repository) throw new GithubApiError(404, 'github-not-found')
212
+ first ??= repository
213
+ for (const ref of repository.branches?.nodes ?? []) {
214
+ const sha = ref?.target?.oid
215
+ if (typeof ref?.name === 'string' && ref.name && typeof sha === 'string' && SHA.test(sha)) heads.push({ name: ref.name.slice(0, MAX_NAME), sha, at: timeOf(ref.target?.committedDate) })
216
+ }
217
+ const next = repository.branches?.pageInfo
218
+ if (next?.hasNextPage !== true || typeof next.endCursor !== 'string') return { heads, repository: first, cut: false }
219
+ after = next.endCursor
220
+ }
221
+ return { heads, repository: first, cut: true }
222
+ }
223
+
224
+ // The first page of the history from each of `tops`, by its top: with a
225
+ // token, in one GraphQL query; without, a REST list each.
226
+ async function readPages(fullName: string, token: string | null, tops: string[], fetchImpl: typeof fetch) {
227
+ if (!token) {
228
+ return new Map(await Promise.all(tops.map(async top => [top, (await repositoryHistory(fullName, null, top, '', 1, fetchImpl)).commits] as const)))
229
+ }
230
+ const [owner, name] = fullName.split('/') as [string, string]
231
+ const data = await githubGraphql(historiesQuery(tops.length), { owner, name, ...Object.fromEntries(tops.map((sha, at) => [`o${at}`, sha])) }, token, fetchImpl) as Histories
232
+ return new Map(tops.map((top, at) => [top, (data?.repository?.[`b${at}`]?.history?.nodes ?? []).flatMap(node => graphCommit(node) ?? [])]))
233
+ }
234
+
235
+ // Its authors past the first, the git author, GitHub lists from its
236
+ // `Co-authored-by:` trailers.
237
+ const graphCommit = (node: GraphCommit | null | undefined) => historyCommit(node?.oid, (node?.parents?.nodes ?? []).map(parent => parent?.oid),
238
+ node?.message, { name: node?.author?.name, email: node?.author?.email, account: commitAccount(node?.author) }, node?.committedDate,
239
+ { additions: node?.additions, deletions: node?.deletions, authoredAt: node?.author?.date },
240
+ Array.isArray(node?.authors?.nodes) ? node.authors.nodes.slice(1).map(actor => ({ name: actor?.name, email: actor?.email, account: commitAccount(actor) })) : null)
241
+
242
+ // The history from each of `starts`, a page of each, kept (`pages`), or read
243
+ // and then kept by its top; glued on to it, the pages kept that start at a
244
+ // parent of a commit listed not listed, or at a commit listed, the oldest
245
+ // first (where each goes on furthest), GLUE_LOOKUP looked up at a time, and
246
+ // those that start where those go on, till HISTORY_GLUED are listed. The
247
+ // pages from `starts` are listed whole, however many that is (all branches'
248
+ // first, as many as ALL_BRANCHES of them): the cap is gluing's. Each commit
249
+ // once, whether any goes on past those listed (`more`), and how many pages
250
+ // were read of GitHub (`read`).
251
+ export async function historyFrom(fullName: string, token: string | null, starts: string[], pages: HistoryPages, fetchImpl: typeof fetch = globalThis.fetch) {
252
+ const kept = await pages.read(starts)
253
+ const unread = starts.filter(top => !kept.has(top))
254
+ const read = unread.length > 0 ? await readPages(fullName, token, unread, fetchImpl) : new Map<string, HistoryCommit[]>()
255
+ // Kept only as GitHub listed it from its top: none for a commit it named nothing of.
256
+ await Promise.all([...read].flatMap(([top, commits]) => commits[0]?.sha === top ? [pages.write(top, commits)] : []))
257
+ const listed = new Map<string, HistoryCommit>()
258
+ const add = (commits: HistoryCommit[]) => { for (const commit of commits) if (!listed.has(commit.sha)) listed.set(commit.sha, commit) }
259
+ for (const top of starts) add(kept.get(top) ?? read.get(top) ?? [])
260
+ const looked = new Set(starts)
261
+ for (let round = 0; round < MAX_GLUE_ROUNDS && listed.size < HISTORY_GLUED; round++) {
262
+ const parents = [...listed.values()].flatMap(commit => commit.parents.filter(parent => !listed.has(parent)))
263
+ const tops = [...new Set([...parents, ...[...listed.keys()].toReversed()])].filter(sha => !looked.has(sha)).slice(0, GLUE_LOOKUP)
264
+ if (tops.length === 0) break
265
+ for (const sha of tops) looked.add(sha)
266
+ const glued = await pages.read(tops)
267
+ for (const commit of [...glued.values()].flat()) {
268
+ if (listed.size >= HISTORY_GLUED) break
269
+ if (!listed.has(commit.sha)) listed.set(commit.sha, commit)
270
+ }
271
+ }
272
+ const commits = [...listed.values()]
273
+ return { commits, more: commits.some(commit => commit.parents.some(parent => !listed.has(parent))), read: unread.length }
274
+ }
275
+
276
+ export type AllHeads = { heads: (HistoryRef & { at: number | null })[]; defaultBranch: string | null; tags: HistoryRef[]; cut: boolean }
277
+
278
+ // `--all`'s branches: the repository's, as many as MAX_HEAD_PAGES of them
279
+ // list, each with its tip's time, its default branch among them wherever its
280
+ // name sorts; its latest tags, each by the commit it tags; and whether
281
+ // branches past those listed are left out (`cut`).
282
+ export async function repositoryAllHeads(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<AllHeads> {
283
+ const [owner, name] = fullName.split('/') as [string, string]
284
+ const { heads, repository, cut } = await repositoryHeads(owner, name, token, fetchImpl)
285
+ const defaultBranch = textOf(repository?.defaultBranchRef?.name, MAX_NAME)
286
+ // The default branch, where its name sorts past the heads read.
287
+ const defaultTip = repository?.defaultBranchRef?.target?.oid
288
+ if (defaultBranch && typeof defaultTip === 'string' && SHA.test(defaultTip) && !heads.some(head => head.name === defaultBranch)) {
289
+ heads.push({ name: defaultBranch, sha: defaultTip, at: timeOf(repository?.defaultBranchRef?.target?.committedDate) })
290
+ }
291
+ // A tag by the commit it tags, through the annotated tags between; one
292
+ // ending at no commit names none.
293
+ const tags = (repository?.tags?.nodes ?? []).flatMap(ref => {
294
+ let target = ref?.target
295
+ while (target?.__typename === 'Tag') target = target.target
296
+ const sha = target?.__typename === 'Commit' ? target.oid : null
297
+ return typeof ref?.name === 'string' && typeof sha === 'string' && SHA.test(sha) ? [{ name: ref.name.slice(0, MAX_NAME), sha }] : []
298
+ })
299
+ return { heads, defaultBranch, tags, cut }
300
+ }
301
+
302
+ // `--all`: the latest commits of the most recently committed to of `heads`
303
+ // (repositoryAllHeads), the default branch's among them, each commit once
304
+ // (historyFrom); the branches naming them and the latest tags; the branches
305
+ // not read, newest first, whose tips none of those is (`unread`), where
306
+ // reading on goes; whether branches past those listed are left out, never to
307
+ // be read (`cut`); and whether any is left out (`more`).
308
+ export async function repositoryAllHistory(fullName: string, token: string, { heads, defaultBranch, tags, cut }: AllHeads, pages: HistoryPages,
309
+ fetchImpl: typeof fetch = globalThis.fetch) {
310
+ const newest = heads.toSorted((a, b) => Number(b.name === defaultBranch) - Number(a.name === defaultBranch) || (b.at ?? 0) - (a.at ?? 0))
311
+ const shown = newest.slice(0, ALL_BRANCHES)
312
+ const read = await historyFrom(fullName, token, [...new Set(shown.map(head => head.sha))], pages, fetchImpl)
313
+ const listed = new Set(read.commits.map(commit => commit.sha))
314
+ const more = cut || heads.length > shown.length || read.more
315
+ // Every branch naming a commit listed, those not read among them.
316
+ const branches = heads.flatMap(({ name: branch, sha }) => listed.has(sha) ? [{ name: branch, sha }] : [])
317
+ const unread = newest.slice(ALL_BRANCHES).filter(head => !listed.has(head.sha))
318
+ return { commits: read.commits, branches, tags, defaultBranch, unread, cut, more }
319
+ }
320
+
321
+ // A pull request squashed into a commit of the default branch's history
322
+ // (`merge`): its number, the commit its head was at when merged (`head`,
323
+ // GitHub's own of it, which a branch reused or pushed over since never
324
+ // moves), and its own commits, the latest MAX_SQUASHED of them, `more`
325
+ // where it had more. Drawn as the merge it was, its commits on a lane of
326
+ // their own (repository-history.js).
327
+ export interface SquashedPull { merge: string; number: number; head: string; commits: HistoryCommit[]; more: boolean }
328
+ // The pull requests squashed into commits, kept by each commit (a merged pull
329
+ // request's commits never change); null for a commit none was.
330
+ export interface Squashes {
331
+ read(shas: string[]): Promise<Map<string, SquashedPull | null>>
332
+ write(sha: string, pull: SquashedPull | null): Promise<void>
333
+ }
334
+
335
+ const MAX_SQUASHED = 100
336
+ // Looked up of an answer's commits not yet kept, at most, the newest first;
337
+ // in queries of as many commits, or pull requests, as many at once.
338
+ export const MAX_SQUASH_LOOKUPS = 500
339
+ const SQUASH_COMMITS = 100
340
+ const SQUASH_PULLS = 20
341
+ const SQUASH_PARALLEL = 4
342
+
343
+ // The merged pull request that brought each commit in, `c<n>` the `n`th's.
344
+ const mergedPullsQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('o', count, 'GitObjectID!')}) {
345
+ repository(owner: $owner, name: $name) {
346
+ ${Array.from({ length: count }, (_, at) => `c${at}: object(oid: $o${at}) { ... on Commit { associatedPullRequests(first: 1) { nodes { number mergeCommit { oid } } } } }`).join('\n ')}
347
+ }
348
+ }`
349
+ // Each pull request's head when merged and its latest commits, `p<n>` the `n`th's.
350
+ const squashedQuery = (count: number) => `query($owner: String!, $name: String!, ${variablesOf('n', count, 'Int!')}) {
351
+ repository(owner: $owner, name: $name) {
352
+ ${Array.from({ length: count }, (_, at) => `p${at}: pullRequest(number: $n${at}) { headRefOid commits(last: ${MAX_SQUASHED}) { totalCount nodes { commit { ...historyCommit } } } }`).join('\n ')}
353
+ }
354
+ }
355
+ ${COMMIT_FRAGMENT}`
356
+
357
+ type MergedPulls = { repository?: Record<string, { associatedPullRequests?: { nodes?: ({ number?: unknown; mergeCommit?: { oid?: unknown } | null } | null)[] } } | null> | null }
358
+ type SquashedPage = { repository?: Record<string, { headRefOid?: unknown; commits?: { totalCount?: unknown; nodes?: ({ commit?: GraphCommit | null } | null)[] } } | null> | null }
359
+
360
+ const chunked = <T>(items: T[], size: number) => Array.from({ length: Math.ceil(items.length / size) }, (_, at) => items.slice(at * size, (at + 1) * size))
361
+ // `run` for each of `items`, as many at once as `parallel`.
362
+ async function eachOf<T>(items: T[], parallel: number, run: (item: T) => Promise<void>) {
363
+ let next = 0
364
+ await Promise.all(Array.from({ length: Math.min(parallel, items.length) }, async () => { while (next < items.length) await run(items[next++]!) }))
365
+ }
366
+ // A pull request or commit GitHub has none of, as one deleted: its field null.
367
+ const notFound = (error: GraphqlError) => error?.type === 'NOT_FOUND'
368
+
369
+ // The pull requests squashed into `commits`, a merged pull request's merge
370
+ // commit of one parent, not one rebased (its commits copied onto the branch,
371
+ // told by their subjects), kept by each commit (`squashes`), those not yet
372
+ // kept looked up with GraphQL, as many as MAX_SQUASH_LOOKUPS an answer.
373
+ export async function squashedPulls(fullName: string, token: string, commits: HistoryCommit[], squashes: Squashes,
374
+ fetchImpl: typeof fetch = globalThis.fetch): Promise<SquashedPull[]> {
375
+ const [owner, name] = fullName.split('/') as [string, string]
376
+ const single = commits.filter(commit => commit.parents.length === 1)
377
+ const listed = new Map(commits.map(commit => [commit.sha, commit]))
378
+ const kept = await squashes.read(single.map(commit => commit.sha))
379
+ const unknown = single.filter(commit => !kept.has(commit.sha)).slice(0, MAX_SQUASH_LOOKUPS)
380
+ const merged: { commit: HistoryCommit; number: number }[] = []
381
+ const found = new Map<string, SquashedPull | null>()
382
+ await eachOf(chunked(unknown, SQUASH_COMMITS), SQUASH_PARALLEL, async batch => {
383
+ const data = await githubGraphql(mergedPullsQuery(batch.length), { owner, name, ...Object.fromEntries(batch.map((commit, at) => [`o${at}`, commit.sha])) },
384
+ token, fetchImpl, notFound) as MergedPulls
385
+ for (const [at, commit] of batch.entries()) {
386
+ const node = data?.repository?.[`c${at}`]
387
+ if (!node) continue
388
+ const pull = node.associatedPullRequests?.nodes?.[0]
389
+ const number = pull?.mergeCommit?.oid === commit.sha && Number.isSafeInteger(pull.number) && (pull.number as number) > 0 ? pull.number as number : null
390
+ if (number === null) { found.set(commit.sha, null); await squashes.write(commit.sha, null) }
391
+ else merged.push({ commit, number })
392
+ }
393
+ })
394
+ await eachOf(chunked(merged, SQUASH_PULLS), SQUASH_PARALLEL, async batch => {
395
+ const data = await githubGraphql(squashedQuery(batch.length), { owner, name, ...Object.fromEntries(batch.map(({ number }, at) => [`n${at}`, number])) },
396
+ token, fetchImpl, notFound) as SquashedPage
397
+ for (const [at, { commit, number }] of batch.entries()) {
398
+ const node = data?.repository?.[`p${at}`]
399
+ if (!node) continue
400
+ const own = (node.commits?.nodes ?? []).flatMap(item => graphCommit(item?.commit) ?? [])
401
+ const head = typeof node.headRefOid === 'string' && SHA.test(node.headRefOid) ? node.headRefOid : own.at(-1)?.sha
402
+ // Fast-forwarded, its last commit the merge's own; or rebased, its
403
+ // commits, more than one, copied onto the branch: the merge and those
404
+ // below it on their first parents, by their subjects, its commits'
405
+ // (one squashed is told by its commit's title too, by default, and
406
+ // drawn as it was either way).
407
+ const below = [commit]
408
+ for (let next = listed.get(commit.parents[0] ?? ''); next && below.length < own.length; next = listed.get(next.parents[0] ?? '')) below.push(next)
409
+ const copies = own.toReversed().slice(0, below.length).every((item, step) => below[step]!.subject === item.subject)
410
+ // Its commits' copies as far as those listed go, but not all of them
411
+ // listed: told, and kept, once they are.
412
+ if (own.length > 1 && copies && below.length < own.length) continue
413
+ const rebased = own.length > 1 && copies
414
+ const squashed = head !== undefined && head !== commit.sha && own.length > 0 && !own.some(item => item.sha === commit.sha) && !rebased
415
+ const pull = squashed ? { merge: commit.sha, number, head, commits: own, more: Number(node.commits?.totalCount) > own.length } : null
416
+ found.set(commit.sha, pull)
417
+ await squashes.write(commit.sha, pull)
418
+ }
419
+ })
420
+ return single.flatMap(commit => kept.get(commit.sha) ?? found.get(commit.sha) ?? [])
421
+ }
422
+
423
+ // The open pull requests most recently updated, each by the commit its head
424
+ // is at, to name commits by.
425
+ const OPEN_PULLS = 100
426
+ const OPEN_PULLS_QUERY = `query($owner: String!, $name: String!) {
427
+ repository(owner: $owner, name: $name) {
428
+ pullRequests(states: OPEN, first: ${OPEN_PULLS}, orderBy: { field: UPDATED_AT, direction: DESC }) { nodes { number headRefOid } }
429
+ }
430
+ }`
431
+ export async function openPullHeads(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch) {
432
+ const [owner, name] = fullName.split('/') as [string, string]
433
+ const data = await githubGraphql(OPEN_PULLS_QUERY, { owner, name }, token, fetchImpl) as
434
+ { repository?: { pullRequests?: { nodes?: ({ number?: unknown; headRefOid?: unknown } | null)[] } } | null }
435
+ return { pulls: (data?.repository?.pullRequests?.nodes ?? []).flatMap(node => Number.isSafeInteger(node?.number) && (node!.number as number) > 0
436
+ && typeof node!.headRefOid === 'string' && SHA.test(node!.headRefOid) ? [{ number: node!.number as number, sha: node!.headRefOid }] : []) }
437
+ }
438
+
439
+ // Where `--all` reads on from, as a request names them (`from`): as many
440
+ // commit ids, each once, as branches are read at first; null for none, or
441
+ // for one that isn't a commit id.
442
+ export function historyStarts(from: string): string[] | null {
443
+ const starts = [...new Set(from.split(','))]
444
+ return starts.length <= ALL_BRANCHES && starts.every(sha => SHA.test(sha)) ? starts : null
445
+ }