@preventive/triage 1.0.0-alpha.6 → 1.0.0-alpha.60

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 (406) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +17 -0
  4. package/cli.js +6 -0
  5. package/client/dependency-paths.d.ts +3 -0
  6. package/client/dependency-paths.js +36 -0
  7. package/client/finding-link.js +305 -0
  8. package/client/linked-findings.d.ts +1 -0
  9. package/client/linked-findings.js +115 -0
  10. package/common/bundle-commit.d.ts +1 -0
  11. package/common/bundle-commit.js +4 -0
  12. package/common/bundle-compare-diff.d.ts +3 -0
  13. package/common/bundle-compare-diff.js +376 -0
  14. package/common/bundle-compare-inputs.d.ts +3 -0
  15. package/common/bundle-compare-inputs.js +141 -0
  16. package/common/bundle-compare-versions.js +172 -0
  17. package/common/bundle-comparison.d.ts +8 -0
  18. package/common/bundle-comparison.js +69 -0
  19. package/common/bundle-metadata.d.ts +15 -0
  20. package/common/bundle-metadata.js +226 -0
  21. package/common/bundle-pkg-of.d.ts +1 -0
  22. package/common/bundle-pkg-of.js +90 -0
  23. package/common/bundle-reasons.d.ts +2 -0
  24. package/common/bundle-reasons.js +21 -0
  25. package/common/bundle-source-links.d.ts +6 -0
  26. package/common/bundle-source-links.js +216 -0
  27. package/common/bundle-sourcemap.d.ts +10 -0
  28. package/common/bundle-sourcemap.js +100 -0
  29. package/common/bundle-sources.d.ts +7 -0
  30. package/common/bundle-sources.js +333 -0
  31. package/common/bundle-stats.js +41 -0
  32. package/common/bundle-tabs.js +1 -0
  33. package/common/code-language.js +65 -0
  34. package/common/default-scan-models.ts +35 -0
  35. package/common/dependency-reviews.d.ts +18 -0
  36. package/common/dependency-reviews.js +64 -0
  37. package/common/finding-duplicates.js +58 -0
  38. package/common/finding-filters.js +274 -0
  39. package/common/finding-id.js +47 -0
  40. package/common/finding-repo.d.ts +5 -0
  41. package/common/finding-repo.js +67 -0
  42. package/common/github-issue-labels.d.ts +1 -0
  43. package/common/github-issue-labels.js +11 -0
  44. package/common/github-pr.ts +56 -0
  45. package/common/gzip.js +59 -0
  46. package/common/line-diff.d.ts +8 -0
  47. package/common/line-diff.js +57 -0
  48. package/common/linked-workspace-groups.js +63 -0
  49. package/common/managed/agent-tasks.ts +292 -0
  50. package/common/managed/comments.ts +34 -0
  51. package/common/managed/finding-detail.d.ts +5 -0
  52. package/common/managed/finding-detail.js +75 -0
  53. package/common/managed/finding-values.d.ts +2 -0
  54. package/common/managed/finding-values.js +44 -0
  55. package/common/managed/github-agents.ts +114 -0
  56. package/common/managed/github-logins.ts +49 -0
  57. package/common/managed/lite-name.d.ts +2 -0
  58. package/common/managed/lite-name.js +20 -0
  59. package/common/managed/npm-packages.d.ts +7 -0
  60. package/common/managed/npm-packages.js +51 -0
  61. package/common/managed/permissions.ts +31 -0
  62. package/common/managed/report-content.ts +72 -0
  63. package/common/managed/report-filter.ts +120 -0
  64. package/common/managed/repository-alias.ts +65 -0
  65. package/common/managed/roles.ts +35 -0
  66. package/common/managed/routes.d.ts +2 -0
  67. package/common/managed/routes.js +363 -0
  68. package/common/managed/scan-models.ts +6 -0
  69. package/common/managed/team-app.d.ts +15 -0
  70. package/common/managed/team-app.js +100 -0
  71. package/common/managed/team-filters.js +26 -0
  72. package/common/managed/triage.ts +83 -0
  73. package/common/managed/upload-seal.ts +126 -0
  74. package/common/pretty-print.d.ts +5 -0
  75. package/common/pretty-print.js +24 -0
  76. package/common/repo-commit.d.ts +4 -0
  77. package/common/repo-commit.js +30 -0
  78. package/common/revalidation-conflicts.js +48 -0
  79. package/common/revalidation-input-groups.js +56 -0
  80. package/common/save-error-reason.ts +20 -7
  81. package/common/scan-server.ts +13 -0
  82. package/common/security-links.d.ts +5 -0
  83. package/common/security-links.js +33 -0
  84. package/common/server-info.ts +46 -0
  85. package/common/utf8.d.ts +3 -0
  86. package/common/utf8.js +45 -0
  87. package/common/workspace-app.js +71 -0
  88. package/common/workspace-groups.js +176 -0
  89. package/out/activity.js +4 -0
  90. package/out/brotli-fallback.js +3 -3
  91. package/out/chunk-2SY4PYUQ.js +4 -0
  92. package/out/chunk-2XUEZHIP.js +28 -0
  93. package/out/chunk-4EMM6UCD.js +1 -0
  94. package/out/chunk-4HI2MSAV.js +17 -0
  95. package/out/chunk-4ISO5F7Y.js +7 -0
  96. package/out/chunk-4TQKM3JC.js +42 -0
  97. package/out/chunk-4XIH7YTX.js +1 -0
  98. package/out/chunk-6VDDCFHT.js +3 -0
  99. package/out/chunk-74AEKRES.js +10 -0
  100. package/out/chunk-7BKKYVWR.js +7 -0
  101. package/out/chunk-7C7DWL7I.js +1 -0
  102. package/out/chunk-C4Z6ZBXV.js +10 -0
  103. package/out/chunk-DEVAORP2.js +1 -0
  104. package/out/chunk-E3LFSUDJ.js +9 -0
  105. package/out/chunk-EEQHVKR3.js +1 -0
  106. package/out/chunk-G3LY2FV4.js +1 -0
  107. package/out/chunk-GO7FT4OD.js +1 -0
  108. package/out/chunk-HAZKDK4M.js +4 -0
  109. package/out/chunk-HNQNDNIE.js +12 -0
  110. package/out/chunk-HOB3YPS5.js +1 -0
  111. package/out/chunk-IYPY47MC.js +1 -0
  112. package/out/chunk-IZ6MYRYB.js +3 -0
  113. package/out/chunk-J2FWBXFV.js +1 -0
  114. package/out/chunk-JCIIBLKR.js +1 -0
  115. package/out/chunk-JFL7WLRV.js +1 -0
  116. package/out/chunk-JMG5DXII.js +2 -0
  117. package/out/chunk-JOXLZXMI.js +1 -0
  118. package/out/chunk-M37X4LCF.js +14 -0
  119. package/out/chunk-M3Y6SLC4.js +1 -0
  120. package/out/chunk-NRPC74AM.js +1 -0
  121. package/out/chunk-NXATZJQ2.js +1 -0
  122. package/out/chunk-OFPDMZJF.js +244 -0
  123. package/out/chunk-OOJM4CTU.js +1 -0
  124. package/out/chunk-OQRSIBSC.js +1 -0
  125. package/out/chunk-PAD2JHZT.js +1 -0
  126. package/out/chunk-PNHBZGDD.js +1 -0
  127. package/out/chunk-PTFQKLKO.js +1 -0
  128. package/out/chunk-PWFUOLZK.js +17 -0
  129. package/out/chunk-PXK7EU4V.js +1 -0
  130. package/out/chunk-QMVOEBWC.js +13 -0
  131. package/out/chunk-QRKFPLA4.js +80 -0
  132. package/out/chunk-R3NZFXVR.js +1 -0
  133. package/out/chunk-R5O6FAW4.js +2 -0
  134. package/out/chunk-RRBIJL2B.js +1 -0
  135. package/out/chunk-SYXT3SFP.js +2 -0
  136. package/out/chunk-TOXMUOIW.js +5 -0
  137. package/out/chunk-TUII34K2.js +1 -0
  138. package/out/chunk-TZS7KERJ.js +52 -0
  139. package/out/chunk-UCP3JRE2.js +1 -0
  140. package/out/chunk-VFWMQ3LG.js +2 -0
  141. package/out/chunk-VRX2APNA.js +9 -0
  142. package/out/chunk-VZJIHHTQ.js +1 -0
  143. package/out/chunk-WCPJDAYA.js +10 -0
  144. package/out/chunk-WMFDQS2L.js +11 -0
  145. package/out/chunk-WREU7JAG.js +1 -0
  146. package/out/chunk-Y5ZHFNBD.js +2 -0
  147. package/out/chunk-YF4M5OCI.js +1 -0
  148. package/out/chunk-YGRRXC2L.js +1 -0
  149. package/out/chunk-YTO6AQZM.js +2 -0
  150. package/out/chunk-Z667U2UJ.js +1 -0
  151. package/out/chunk-ZQHLECTI.js +1 -0
  152. package/out/client-managed-import.js +4 -0
  153. package/out/client-managed.js +34 -0
  154. package/out/client-sync.js +11 -17
  155. package/out/compare.js +35 -0
  156. package/out/dialogs.js +40 -0
  157. package/out/github-issue-authorized.html +3 -0
  158. package/out/github-issue-authorized.js +1 -0
  159. package/out/graph.js +19 -4
  160. package/out/index.html +106 -8
  161. package/out/prism.js +14 -10
  162. package/out/scan.js +2 -0
  163. package/out/stasis.svg +20 -0
  164. package/out/terminal.js +366 -39
  165. package/out/view.css +1 -1
  166. package/out/view.js +19 -144
  167. package/package.json +379 -62
  168. package/risk/actions/findings.js +161 -0
  169. package/risk/actions/resolve.js +250 -0
  170. package/risk/actions/scripts/commands.js +182 -0
  171. package/risk/actions/scripts/grade.js +113 -0
  172. package/risk/actions/scripts/packages.js +123 -0
  173. package/risk/actions/scripts/shell.js +169 -0
  174. package/risk/actions/uses.js +76 -0
  175. package/risk/actions/workflow.js +110 -0
  176. package/risk/files/characters.js +196 -0
  177. package/risk/files/hosts.js +205 -0
  178. package/risk/files/readability.js +177 -0
  179. package/risk/files/runs-code.js +615 -0
  180. package/risk/files/script.js +118 -0
  181. package/risk/files/stamps.js +47 -0
  182. package/risk/index.d.ts +272 -0
  183. package/risk/index.js +11 -0
  184. package/risk/npm/assess.js +285 -0
  185. package/risk/npm/combined.js +68 -0
  186. package/risk/npm/compare.js +257 -0
  187. package/risk/npm/dependencies.js +172 -0
  188. package/risk/npm/diff.js +79 -0
  189. package/risk/npm/downloads.js +84 -0
  190. package/risk/npm/files.js +445 -0
  191. package/risk/npm/held.js +63 -0
  192. package/risk/npm/install-scripts.js +34 -0
  193. package/risk/npm/malware.js +38 -0
  194. package/risk/npm/manifest.js +65 -0
  195. package/risk/npm/new-dependency.js +60 -0
  196. package/risk/npm/old-version.js +108 -0
  197. package/risk/npm/registry.js +390 -0
  198. package/risk/npm/release.js +85 -0
  199. package/risk/npm/score.js +59 -0
  200. package/risk/npm/specs.js +124 -0
  201. package/risk/npm/tarball.js +96 -0
  202. package/server-common/database-config.ts +16 -0
  203. package/server-common/initialize.ts +18 -0
  204. package/server-common/npm-advisories.ts +101 -0
  205. package/{server → server-common}/origin.ts +5 -5
  206. package/server-common/reap.ts +48 -0
  207. package/server-common/scan-config.ts +19 -0
  208. package/server-common/standalone.ts +29 -0
  209. package/server-common/storage-crypto.ts +182 -0
  210. package/server-common/storage-log.ts +38 -0
  211. package/server-common/vercel-blob.ts +103 -0
  212. package/server-e2e/app.ts +487 -0
  213. package/{server → server-e2e}/bus-receiver.ts +2 -1
  214. package/{server → server-e2e}/cli.js +9 -4
  215. package/{server → server-e2e}/config.ts +50 -42
  216. package/{server → server-e2e}/db-neon.ts +2 -2
  217. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  218. package/{server → server-e2e}/db-stmt.ts +2 -2
  219. package/{server → server-e2e}/db.ts +7 -7
  220. package/{server → server-e2e}/http.ts +44 -13
  221. package/{server → server-e2e}/hub.ts +40 -9
  222. package/server-e2e/index.ts +17 -0
  223. package/server-e2e/lifecycle.ts +95 -0
  224. package/{server → server-e2e}/neon-driver.ts +2 -2
  225. package/{server → server-e2e}/npm-proxy.ts +12 -145
  226. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  227. package/{server → server-e2e}/objstore/blob.ts +1 -1
  228. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  229. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  230. package/{server → server-e2e}/objstore/init.ts +19 -27
  231. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  232. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  233. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  234. package/{server → server-e2e}/objstore/rest.ts +3 -3
  235. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  236. package/{server → server-e2e}/objstore/store.ts +7 -7
  237. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  238. package/{server → server-e2e}/pubsub.ts +12 -9
  239. package/{server → server-e2e}/sign.ts +4 -4
  240. package/{server → server-e2e}/sse-server.ts +60 -33
  241. package/{server → server-e2e}/static.ts +31 -21
  242. package/{server → server-e2e}/sync-handlers.ts +64 -30
  243. package/{server → server-e2e}/ws-server.ts +20 -9
  244. package/server-managed/activity.ts +258 -0
  245. package/server-managed/agent-merges.ts +109 -0
  246. package/server-managed/app-agents.ts +23 -0
  247. package/server-managed/avatar-store.ts +13 -0
  248. package/server-managed/blob-store.ts +17 -0
  249. package/server-managed/brotli.ts +10 -0
  250. package/server-managed/bundle-advisories.ts +102 -0
  251. package/server-managed/bundle-advisory-inventory.ts +77 -0
  252. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  253. package/server-managed/bundle-build-diagnostics.js +23 -0
  254. package/server-managed/bundle-build-leases.ts +41 -0
  255. package/server-managed/bundle-build-worker.js +203 -0
  256. package/server-managed/bundle-build.ts +232 -0
  257. package/server-managed/bundle-cache.ts +211 -0
  258. package/server-managed/bundle-catalog.ts +29 -0
  259. package/server-managed/bundle-commits.ts +140 -0
  260. package/server-managed/bundle-dependency-reviews.ts +74 -0
  261. package/server-managed/bundle-store.ts +24 -0
  262. package/server-managed/bundle-summary-cache.ts +130 -0
  263. package/server-managed/bundle-validation.ts +32 -0
  264. package/server-managed/bundle.ts +119 -0
  265. package/server-managed/cache-storage.ts +20 -0
  266. package/server-managed/cli.js +21 -0
  267. package/server-managed/combined.ts +47 -0
  268. package/server-managed/comments.ts +151 -0
  269. package/server-managed/commit-coauthors.ts +106 -0
  270. package/server-managed/commit-lockfiles.ts +76 -0
  271. package/server-managed/comparison.ts +52 -0
  272. package/server-managed/config.ts +164 -0
  273. package/server-managed/content-access.ts +15 -0
  274. package/server-managed/crypto.ts +25 -0
  275. package/server-managed/db-methods.ts +1958 -0
  276. package/server-managed/db-neon.ts +484 -0
  277. package/server-managed/db-schema.ts +238 -0
  278. package/server-managed/db-table-names.ts +22 -0
  279. package/server-managed/db.ts +152 -0
  280. package/server-managed/dependabot-access.ts +60 -0
  281. package/server-managed/dependabot-alerts.ts +185 -0
  282. package/server-managed/dependency-review-comments.ts +98 -0
  283. package/server-managed/dependency-reviews.ts +364 -0
  284. package/server-managed/github-accounts.ts +60 -0
  285. package/server-managed/github-actions.ts +71 -0
  286. package/server-managed/github-app.ts +376 -0
  287. package/server-managed/github-errors.ts +70 -0
  288. package/server-managed/github-graphql.ts +39 -0
  289. package/server-managed/github-issue-links.ts +244 -0
  290. package/server-managed/github-issue-oauth.ts +47 -0
  291. package/server-managed/github-issues.ts +155 -0
  292. package/server-managed/github-link-oauth.ts +69 -0
  293. package/server-managed/github-links.ts +204 -0
  294. package/server-managed/github-metadata.ts +213 -0
  295. package/server-managed/github-oauth.ts +238 -0
  296. package/server-managed/github-pulls.ts +246 -0
  297. package/server-managed/github-requests.ts +166 -0
  298. package/server-managed/github-users.ts +30 -0
  299. package/server-managed/history-windows.ts +172 -0
  300. package/server-managed/http-response.ts +76 -0
  301. package/server-managed/http.ts +5855 -0
  302. package/server-managed/import-triage.ts +51 -0
  303. package/server-managed/index.ts +204 -0
  304. package/server-managed/kept-briefly.ts +37 -0
  305. package/server-managed/kept.ts +28 -0
  306. package/server-managed/link-reports.ts +162 -0
  307. package/server-managed/listed-activity.ts +39 -0
  308. package/server-managed/locked-packages.ts +152 -0
  309. package/server-managed/lockfile-scope.ts +49 -0
  310. package/server-managed/lru.ts +30 -0
  311. package/server-managed/managed-issues.ts +92 -0
  312. package/server-managed/management-catalog.ts +45 -0
  313. package/server-managed/management.ts +99 -0
  314. package/server-managed/npm-delta-worker.js +23 -0
  315. package/server-managed/npm-delta.ts +194 -0
  316. package/server-managed/npm-insights.ts +450 -0
  317. package/server-managed/npm-kept.ts +233 -0
  318. package/server-managed/npm-loads.ts +264 -0
  319. package/server-managed/npm-manifest.ts +115 -0
  320. package/server-managed/npm-packages.ts +454 -0
  321. package/server-managed/npm-patch.ts +325 -0
  322. package/server-managed/npm-provenance.ts +123 -0
  323. package/server-managed/npm-risk.ts +285 -0
  324. package/server-managed/object-storage-disk.ts +148 -0
  325. package/server-managed/object-storage-vercel.ts +67 -0
  326. package/server-managed/object-storage.ts +75 -0
  327. package/server-managed/package-entry-points.ts +79 -0
  328. package/server-managed/pretty-print.ts +436 -0
  329. package/server-managed/public-workspace.ts +238 -0
  330. package/server-managed/pull-comment-reviews.ts +161 -0
  331. package/server-managed/pull-dependencies.ts +351 -0
  332. package/server-managed/pull-dependency-reviews.ts +334 -0
  333. package/server-managed/pull-reviews.ts +205 -0
  334. package/server-managed/queue.ts +39 -0
  335. package/server-managed/release-commits.ts +84 -0
  336. package/server-managed/rename-diff-worker.js +26 -0
  337. package/server-managed/rename-diff.ts +279 -0
  338. package/server-managed/repo-path.ts +21 -0
  339. package/server-managed/report-migration.ts +35 -0
  340. package/server-managed/report-query.ts +10 -0
  341. package/server-managed/report-response.ts +16 -0
  342. package/server-managed/report-sources.ts +185 -0
  343. package/server-managed/report-store.ts +85 -0
  344. package/server-managed/repository-actions.ts +221 -0
  345. package/server-managed/repository-agents.ts +448 -0
  346. package/server-managed/repository-aliases.ts +91 -0
  347. package/server-managed/repository-browser.ts +301 -0
  348. package/server-managed/repository-changes.ts +284 -0
  349. package/server-managed/repository-code.ts +215 -0
  350. package/server-managed/repository-dependency-reviews.ts +166 -0
  351. package/server-managed/repository-discovery.ts +82 -0
  352. package/server-managed/repository-history.ts +432 -0
  353. package/server-managed/repository-issues.ts +195 -0
  354. package/server-managed/repository-policy.ts +27 -0
  355. package/server-managed/repository-pulls.ts +212 -0
  356. package/server-managed/repository-pulse.ts +471 -0
  357. package/server-managed/repository-risk-assess.ts +105 -0
  358. package/server-managed/repository-risk-audit.ts +78 -0
  359. package/server-managed/repository-risk-read.ts +170 -0
  360. package/server-managed/repository-risk.ts +491 -0
  361. package/server-managed/repository-squashes.ts +168 -0
  362. package/server-managed/repository-stamp.ts +41 -0
  363. package/server-managed/request-timing.ts +63 -0
  364. package/server-managed/reviewed-dependencies.ts +149 -0
  365. package/server-managed/revisions.ts +35 -0
  366. package/server-managed/scan-downloads.ts +87 -0
  367. package/server-managed/session.ts +132 -0
  368. package/server-managed/slugs.ts +38 -0
  369. package/server-managed/solidity-entry-points.ts +71 -0
  370. package/server-managed/sql-postgres.ts +34 -0
  371. package/server-managed/sql.ts +89 -0
  372. package/server-managed/stasis-config.ts +55 -0
  373. package/server-managed/static.ts +28 -0
  374. package/server-managed/storage-command.ts +16 -0
  375. package/server-managed/storage-db.ts +183 -0
  376. package/server-managed/storage-encryption.ts +290 -0
  377. package/server-managed/storage-maintenance.ts +259 -0
  378. package/server-managed/storage-payload.ts +121 -0
  379. package/server-managed/storage-stores.ts +91 -0
  380. package/server-managed/storage.ts +82 -0
  381. package/server-managed/team-app-summaries.ts +54 -0
  382. package/server-managed/team-app.ts +157 -0
  383. package/server-managed/team-catalog.ts +7 -0
  384. package/server-managed/team-feed.ts +180 -0
  385. package/server-managed/team-npm-scopes.ts +106 -0
  386. package/server-managed/team-reports.ts +351 -0
  387. package/server-managed/triage-response.ts +16 -0
  388. package/server-managed/type-only-worker.js +19 -0
  389. package/server-managed/type-only.ts +105 -0
  390. package/server-managed/uploads.ts +106 -0
  391. package/server-managed/upstream-cache.ts +252 -0
  392. package/server-managed/view-as.ts +58 -0
  393. package/server-managed/workspace-shares.ts +171 -0
  394. package/server.ts +70 -0
  395. package/server/index.ts +0 -480
  396. package/server/lifecycle.ts +0 -208
  397. /package/{LICENSE → LICENSE-MIT} +0 -0
  398. /package/{server → server-e2e}/auth.ts +0 -0
  399. /package/{server → server-e2e}/config.example.json +0 -0
  400. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  401. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  402. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  403. /package/{server → server-e2e}/peer.ts +0 -0
  404. /package/{server → server-e2e}/sse-session.ts +0 -0
  405. /package/{server → server-e2e}/util.ts +0 -0
  406. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,471 @@
1
+ // What the code viewer's Pulse tab shows of a repository
2
+ // (GET /api/admin/repositories/pulse): how its default branch moves, week by
3
+ // week over the last year: its commits each day, the lines they add and
4
+ // remove, those an agent made or co-authored, who made them and when in the
5
+ // week, counted from its commits as the Commits tab reads and keeps them
6
+ // (repository-history.ts historyFrom), so that only those not kept yet are
7
+ // read of GitHub, a few queries an answer, the client asking again for the
8
+ // rest; a year past YEAR_COMMITS is counted by GitHub's statistics instead,
9
+ // which GitHub computes when first asked and again once the default branch
10
+ // moves, answering 202 till they are (told pending, StatsPending, for the
11
+ // client to ask again). And, since
12
+ // the start of the week `weeks` weeks back, and over the same days of the
13
+ // week `weeks` weeks earlier, the pull requests merged and opened and the
14
+ // issues closed and opened, how many and the latest of each.
15
+ import { agentOperated, githubAgent } from '../common/managed/github-agents.ts'
16
+ import { GithubApiError, githubJson } from './github-app.ts'
17
+ import { shareGithubRead } from './github-requests.ts'
18
+ import { coauthorsOf } from './commit-coauthors.ts'
19
+ import { windowsOn } from './history-windows.ts'
20
+ import { ACTOR, type GraphAccount, type HistoryCommit, type HistoryPages, accountOf, actorOf, githubGraphql, historyFrom } from './repository-history.ts'
21
+
22
+ export const PULSE_WEEKS = [1, 4, 13, 52]
23
+ // What a year counted from its commits holds, its version: kept years of
24
+ // another are counted again.
25
+ export const PULSE_YEAR_VERSION = 12
26
+ const WEEK_MS = 7 * 24 * 60 * 60_000
27
+ const DAY_MS = 24 * 60 * 60_000
28
+ const MAX_CONTRIBUTORS = 100
29
+ const DIRECT_LISTED = 500
30
+ export const LISTED = 10
31
+ // Merged pull requests and closed issues are searched by when each was last
32
+ // updated, GitHub sorting by no merge or close: as many as this are read, and
33
+ // the latest merged or closed of them listed.
34
+ const SEARCHED = 50
35
+ // A year of more commits than this is counted by GitHub's statistics: read a
36
+ // page at a time, it would take a hundred queries. Of those not kept, as
37
+ // many queries are made an answer as YEAR_QUERIES, each reading on from as
38
+ // many commits as YEAR_STARTS.
39
+ export const YEAR_COMMITS = 10_000
40
+ const YEAR_QUERIES = 5
41
+ const YEAR_STARTS = 10
42
+ // Commits are read on from as far as this before the year, a commit's clock
43
+ // not always later than its parents': one dated before the year may have a
44
+ // parent dated in it.
45
+ const YEAR_SKEW_MS = 30 * DAY_MS
46
+ const MAX_TITLE = 1000
47
+ const SHA = /^[a-f\d]{40}$/u
48
+
49
+ // GitHub still computing a statistic.
50
+ export class StatsPending extends Error {
51
+ constructor() { super('github-stats-pending') }
52
+ }
53
+
54
+ // A week: its commits each day (Sunday first) and in all, the lines they
55
+ // added and removed, and, counted from its commits, each day's lines
56
+ // (`dayLines`, `[added, removed]`), the commits that release the repository
57
+ // each day (`releaseDays`, release-commits.ts) and, of the rest, those an
58
+ // agent made or co-authored (`agentDays`), and those pushed to the branch
59
+ // directly (`directDays`, agent-merges.ts directCommits), which GitHub's
60
+ // statistics don't count.
61
+ export interface PulseWeek { week: number; days: number[]; commits: number; additions: number | null; deletions: number | null; dayLines?: [number, number][]
62
+ agentDays?: number[]; releaseDays?: number[]; directDays?: number[] }
63
+ // A contributor, by their login and their account's numeric id (`id`, where
64
+ // GitHub named it), else by the name their commits carry, and their weeks,
65
+ // each `[week, commits, additions, deletions]`, those with any; counted from
66
+ // their commits, their days too, each `[day, commits, additions, deletions,
67
+ // agents, releases, direct]`, `releases` those that release the repository,
68
+ // `agents`, of the rest, those an agent took part in (withAgent), and
69
+ // `direct` those pushed to the branch directly.
70
+ export interface PulseContributor { login: string | null; id?: number | null; name: string | null; weeks: [number, number, number, number][]
71
+ days?: [number, number, number, number, number, number, number][] }
72
+ // A commit pushed to the branch directly, as Pulse lists it: its id, when it
73
+ // was committed, its subject, its author, by account, else name, and what it
74
+ // is: a release, else one an agent took part in, else one without.
75
+ export interface PulseCommit { sha: string; at: number; subject: string; login: string | null; id: number | null; name: string | null
76
+ kind: 'agent' | 'without' | 'release' }
77
+ // Commits by day of the week and hour (`punch[day][hour]`, Sunday first), in
78
+ // each commit's own time zone, and, counted from its commits, each period's
79
+ // (`punches`, by its weeks); `lines` false where GitHub counts none, null
80
+ // while it is counting them; counted from its commits, the latest pushed to
81
+ // the branch directly (`directCommits`, as many as DIRECT_LISTED); and,
82
+ // counted from its commits read no further back than a period needed, when
83
+ // from it is counted whole (`from`), absent for the year whole.
84
+ export interface PulseStats { weeks: PulseWeek[]; contributors: PulseContributor[]; punch: number[][]; punches?: Record<number, number[][]>; lines: boolean | null
85
+ directCommits?: PulseCommit[]; from?: number }
86
+ // The lines added and removed a week, and each contributor's, as GitHub's
87
+ // statistics count them, `lines` false where it counts none.
88
+ export interface PulseLines { weeks: [number, number, number][]; contributors: { login: string; weeks: [number, number, number][] }[]; lines: boolean }
89
+ // The days (`from`, `to`, both days, UTC; `to` none, on) and the authors (GitHub
90
+ // logins, any of them) a period's pull requests and issues are narrowed to.
91
+ export interface PulseNarrowing { from: number; to: number | null; authors: string[] }
92
+ // The year's commits read so far: all of them, or as far back as asked
93
+ // (`commits`, `from`), else how many (`read`), and whether past
94
+ // YEAR_COMMITS (`tooMany`).
95
+ export type YearCommits = { complete: true; commits: HistoryCommit[]; passed: HistoryCommit[]; from: number | null } | { complete: false; read: number; tooMany: boolean }
96
+
97
+ const count = (value: unknown) => Number.isSafeInteger(value) && (value as number) >= 0 ? value as number : 0
98
+ const timeOf = (value: unknown) => {
99
+ const at = typeof value === 'string' ? Date.parse(value) : Number.NaN
100
+ return Number.isSafeInteger(at) ? at : null
101
+ }
102
+ const repoApi = (fullName: string) => `https://api.github.com/repos/${fullName.split('/').map(encodeURIComponent).join('/')}`
103
+ const emptyPunch = () => Array.from({ length: 7 }, () => Array.from({ length: 24 }, () => 0))
104
+
105
+ // One statistic: its rows once GitHub has computed it, 'pending' while it
106
+ // computes them (202), none for a repository with no commits (204, no body),
107
+ // 'too-large' where it counts none (lines past 10,000 commits, 422).
108
+ function statistic(fullName: string, token: string | null, kind: string, fetchImpl: typeof fetch) {
109
+ // Stats and lines both need contributors. Share by the original transport;
110
+ // the per-call status wrapper below would otherwise give each its own read.
111
+ return shareGithubRead(fetchImpl, JSON.stringify(['statistic', fullName, token, kind]), () => readStatistic(fullName, token, kind, fetchImpl))
112
+ }
113
+
114
+ async function readStatistic(fullName: string, token: string | null, kind: string, fetchImpl: typeof fetch): Promise<unknown[] | 'pending' | 'too-large'> {
115
+ let status = 0
116
+ const answered: typeof fetch = async (input, init) => {
117
+ const res = await fetchImpl(input, init)
118
+ status = res.status
119
+ return res
120
+ }
121
+ try {
122
+ const data = await githubJson(`${repoApi(fullName)}/stats/${kind}`, token, answered)
123
+ if (status === 202) return 'pending'
124
+ if (!Array.isArray(data)) throw new GithubApiError(502, 'github-malformed')
125
+ return data
126
+ } catch (err) {
127
+ if (status === 202) return 'pending'
128
+ if (status === 204) return []
129
+ if (err instanceof GithubApiError && err.message === 'github-status-422') return 'too-large'
130
+ throw err
131
+ }
132
+ }
133
+
134
+ // `kinds` of GitHub's statistics, each asked once, together; any still
135
+ // computed, StatsPending.
136
+ async function statistics(fullName: string, token: string | null, kinds: string[], fetchImpl: typeof fetch) {
137
+ const read = await Promise.all(kinds.map(kind => statistic(fullName, token, kind, fetchImpl)))
138
+ if (read.includes('pending')) throw new StatsPending()
139
+ return read.map(rows => rows === 'too-large' ? null : rows as unknown[])
140
+ }
141
+
142
+ type ActivityRow = { week?: unknown; days?: unknown; total?: unknown }
143
+ type ContributorRow = { author?: { login?: unknown; id?: unknown } | null; weeks?: { w?: unknown; a?: unknown; d?: unknown; c?: unknown }[] }
144
+
145
+ // The default branch's commits over the last year as GitHub's statistics
146
+ // count them, for a year past YEAR_COMMITS: a week a row, the oldest first,
147
+ // its commits each day (Sunday first) and in all; its contributors (as many
148
+ // as MAX_CONTRIBUTORS, the most commits that year first) and their weeks;
149
+ // and its commits by day of the week and hour, in each commit's own time
150
+ // zone. Lines are GitHub's to count apart (repositoryLines).
151
+ export async function repositoryStats(fullName: string, token: string | null, fetchImpl: typeof fetch = globalThis.fetch): Promise<PulseStats> {
152
+ const [activityRows = null, contributorRows = null, punchRows = null] = await statistics(fullName, token, ['commit_activity', 'contributors', 'punch_card'], fetchImpl)
153
+ const weeks = ((activityRows ?? []) as ActivityRow[]).flatMap(row => {
154
+ if (!Number.isSafeInteger(row?.week)) return []
155
+ const days = Array.from({ length: 7 }, (_, day) => count(Array.isArray(row.days) ? row.days[day] : 0))
156
+ return [{ week: (row.week as number) * 1000, days, commits: count(row.total), additions: null, deletions: null }]
157
+ }).toSorted((a, b) => a.week - b.week)
158
+ const first = weeks[0]?.week ?? Number.POSITIVE_INFINITY
159
+ const contributors = ((contributorRows ?? []) as ContributorRow[]).flatMap(row => {
160
+ const { login, id } = accountOf(row?.author)
161
+ const theirs = (row?.weeks ?? []).flatMap(item => {
162
+ const week = count(item?.w) * 1000
163
+ return week >= first && count(item?.c) > 0 ? [[week, count(item?.c), 0, 0] as [number, number, number, number]] : []
164
+ })
165
+ return login && theirs.length > 0 ? [{ login, id, name: null, weeks: theirs, commits: theirs.reduce((sum, item) => sum + item[1], 0) }] : []
166
+ }).toSorted((a, b) => b.commits - a.commits).slice(0, MAX_CONTRIBUTORS).map(({ login, id, name, weeks: theirs }) => ({ login, id, name, weeks: theirs }))
167
+ const punch = emptyPunch()
168
+ for (const row of (punchRows ?? []) as unknown[][]) {
169
+ if (Array.isArray(row) && Number.isSafeInteger(row[0]) && Number.isSafeInteger(row[1]) && punch[row[0] as number]?.[row[1] as number] !== undefined) {
170
+ punch[row[0] as number]![row[1] as number] = count(row[2])
171
+ }
172
+ }
173
+ return { weeks, contributors, punch, lines: null }
174
+ }
175
+
176
+ // The lines added and removed each week since `since`, and each
177
+ // contributor's, as GitHub's statistics count them; none, `lines` false,
178
+ // where it counts none (past 10,000 commits, where it counts each
179
+ // contributor's as none too).
180
+ export async function repositoryLines(fullName: string, token: string | null, since: number, fetchImpl: typeof fetch = globalThis.fetch): Promise<PulseLines> {
181
+ const [frequency = null, contributorRows = null] = await statistics(fullName, token, ['code_frequency', 'contributors'], fetchImpl)
182
+ if (frequency === null) return { weeks: [], contributors: [], lines: false }
183
+ const weeks = frequency.flatMap(row => Array.isArray(row) && Number.isSafeInteger(row[0]) && (row[0] as number) * 1000 >= since
184
+ ? [[(row[0] as number) * 1000, count(row[1]), count(Math.abs(Number(row[2])))] as [number, number, number]] : [])
185
+ const contributors = ((contributorRows ?? []) as ContributorRow[]).flatMap(row => {
186
+ const { login } = accountOf(row?.author)
187
+ const theirs = (row?.weeks ?? []).flatMap(item => count(item?.w) * 1000 >= since && count(item?.a) + count(item?.d) > 0
188
+ ? [[count(item?.w) * 1000, count(item?.a), count(item?.d)] as [number, number, number]] : [])
189
+ return login && theirs.length > 0 ? [{ login, weeks: theirs }] : []
190
+ })
191
+ return { weeks, contributors, lines: true }
192
+ }
193
+
194
+ // The default branch's head, null for a repository with none.
195
+ export async function defaultHead(fullName: string, token: string, fetchImpl: typeof fetch = globalThis.fetch): Promise<string | null> {
196
+ const [owner, name] = fullName.split('/') as [string, string]
197
+ const data = await githubGraphql('query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { defaultBranchRef { target { oid } } } }',
198
+ { owner, name }, token, fetchImpl) as { repository?: { defaultBranchRef?: { target?: { oid?: unknown } | null } | null } | null } | null
199
+ if (!data?.repository) throw new GithubApiError(404, 'github-not-found')
200
+ const oid = data.repository.defaultBranchRef?.target?.oid
201
+ return typeof oid === 'string' && SHA.test(oid) ? oid : null
202
+ }
203
+
204
+ // The commits from `head` made since `since`, as the Commits tab reads and
205
+ // keeps them (`pages`, historyFrom): on from the parents of those since (or
206
+ // as much as YEAR_SKEW_MS before), not yet listed, YEAR_STARTS at a time,
207
+ // till none is left; the pages kept read
208
+ // of the store, those not of GitHub, as many queries of them as
209
+ // YEAR_QUERIES, the rest left for the next to ask (`complete` false, how
210
+ // many are `read`); more than YEAR_COMMITS, too many (`tooMany`). Read
211
+ // whole, those it was read on past besides (`passed`): undated, or dated
212
+ // before it, a clock behind, the branch's commits since beneath them. Read
213
+ // no further than `need` asks, those since it read whole (`complete`, `from`
214
+ // the newest of those read whose parents are not, every commit after it
215
+ // read; null, the year read whole). How many are read so far `told` as they
216
+ // are.
217
+ export async function yearCommits(fullName: string, token: string, head: string, since: number, pages: HistoryPages,
218
+ fetchImpl: typeof fetch = globalThis.fetch, need = since, told: (read: number) => void = () => {}): Promise<YearCommits> {
219
+ const found = new Map<string, HistoryCommit>()
220
+ const tried = new Set<string>()
221
+ const within = (commit: HistoryCommit) => commit.committedAt === null || commit.committedAt >= since - YEAR_SKEW_MS
222
+ const dated = (commit: HistoryCommit) => commit.committedAt !== null && commit.committedAt >= since
223
+ const read = () => [...found.values()].filter(dated).length
224
+ const passed = () => [...found.values()].filter(commit => !dated(commit) && within(commit))
225
+ let queries = 0
226
+ let windowed = false
227
+ let starts = [head]
228
+ while (starts.length > 0) {
229
+ // Those not read yet, the head before any, else the parents of those
230
+ // read, no later than the newest of them (but for a clock behind): read
231
+ // whole after it.
232
+ const unread = new Set(starts)
233
+ const from = found.size === 0 ? Number.POSITIVE_INFINITY : Math.max(Number.NEGATIVE_INFINITY, ...[...found.values()]
234
+ .filter(commit => commit.parents.some(sha => unread.has(sha))).map(commit => commit.committedAt ?? Number.POSITIVE_INFINITY))
235
+ if (need > since && from < need) return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from }
236
+ if (queries >= YEAR_QUERIES) return { complete: false, read: read(), tooMany: false }
237
+ // The pages kept read first; once past them, the rest read at once by
238
+ // when its commits were made (history-windows.ts windowsOn), as far back
239
+ // as it needs, the year's as far as its commits are followed.
240
+ const next: Awaited<ReturnType<typeof windowsOn>> | null = windowed || found.size === 0 ? null
241
+ : await windowsOn(fullName, token, head, starts, found, need > since ? need : since - YEAR_SKEW_MS, from, pages, fetchImpl, queries)
242
+ windowed ||= next?.windowed === true
243
+ queries += next?.queries ?? 0
244
+ const batch = (next?.batch ?? starts).slice(0, YEAR_STARTS)
245
+ for (const sha of batch) tried.add(sha)
246
+ const got = batch.length > 0 ? await historyFrom(fullName, token, batch, pages, fetchImpl) : { commits: [], read: 0 }
247
+ if (got.read > 0) queries++
248
+ for (const commit of got.commits) if (!found.has(commit.sha)) found.set(commit.sha, commit)
249
+ told(read())
250
+ if (read() > YEAR_COMMITS) return { complete: false, read: read(), tooMany: true }
251
+ starts = [...new Set([...found.values()].filter(within).flatMap(commit => commit.parents))].filter(sha => !found.has(sha) && !tried.has(sha))
252
+ }
253
+ return { complete: true, commits: [...found.values()].filter(dated), passed: passed(), from: null }
254
+ }
255
+
256
+ // Whether an author is a GitHub App's bot: by its login (`<app>[bot]`, as a
257
+ // commit's no-reply address names it, github-accounts.ts commitAccount),
258
+ // else, for one GitHub names no account for, by the name it commits as.
259
+ const bot = (login: string | null | undefined, name: string | null | undefined) => /\[bot\]$/iu.test(login ?? name ?? '')
260
+
261
+ // Whether an agent made `commit` or co-authored it: its author one of
262
+ // GitHub's agents (common/managed/github-agents.ts githubAgent), or any of
263
+ // its co-authors an agent (commit-coauthors.ts coauthorsOf), as Commits
264
+ // marks them, or any bot, whichever GitHub App's; or one an agent's pull request brought (`merges`,
265
+ // agent-merges.ts agentCommits); or one an account agents work as pushed to
266
+ // the branch directly (`direct`, github-agents.ts agentOperated).
267
+ const withAgent = (commit: HistoryCommit, merges: ReadonlySet<string>, direct: ReadonlySet<string>) => merges.has(commit.sha)
268
+ || (direct.has(commit.sha) && agentOperated(commit.authorLogin, commit.authorId ?? null))
269
+ || githubAgent(commit.authorLogin, commit.authorId ?? null, commit.authorName) !== null || bot(commit.authorLogin, commit.authorName)
270
+ || coauthorsOf(commit).some(coauthor => Boolean(coauthor.agent) || bot(coauthor.login, coauthor.name))
271
+
272
+ // The year from `first` (pulseSince(52, …)) of `commits`, as GitHub's
273
+ // statistics count them, merges left out: a week a row, its commits each day
274
+ // (UTC) and in all and the lines they added and removed, in all and each day,
275
+ // those that release the repository (`releases`, release-commits.ts) and,
276
+ // of the rest, those an agent made or co-authored, merged from an agent's
277
+ // pull request (`merges`) or pushed directly as an account agents work as
278
+ // (`direct`, withAgent), each day;
279
+ // its contributors,
280
+ // by account (its id, by the login it committed as first listed, the newest,
281
+ // whatever it was renamed from; a login's commits read before ids were, the
282
+ // one account's that committed as it, where only one did), else login, each
283
+ // matched as GitHub matches logins, regardless of case, else name (as many
284
+ // as MAX_CONTRIBUTORS, the most commits first),
285
+ // and their weeks and days, each day's releases and commits with agents too;
286
+ // and its commits by day of the week and hour, in each author's own time
287
+ // zone (else UTC, where GitHub told none), the year's and each period's
288
+ // (PULSE_WEEKS, its last weeks).
289
+ export function commitStats(commits: HistoryCommit[], first: number, merges: ReadonlySet<string> = new Set(), releases: ReadonlySet<string> = new Set(),
290
+ direct: ReadonlySet<string> = new Set()): PulseStats {
291
+ const weeks = Array.from({ length: 52 }, (_, at) => ({ week: first + at * WEEK_MS, days: Array.from({ length: 7 }, () => 0), commits: 0, additions: 0, deletions: 0,
292
+ dayLines: Array.from({ length: 7 }, () => [0, 0] as [number, number]), agentDays: Array.from({ length: 7 }, () => 0), releaseDays: Array.from({ length: 7 }, () => 0),
293
+ directDays: Array.from({ length: 7 }, () => 0) }))
294
+ type Counts = Map<number, number[]>
295
+ const people = new Map<string, { login: string | null; logins: Set<string>; id: number | null; name: string | null; weeks: Counts; days: Counts; commits: number }>()
296
+ const punches = Object.fromEntries(PULSE_WEEKS.map(span => [span, emptyPunch()]))
297
+ // Each commit's author, by the key their commits are counted by, and of a
298
+ // login an account took on, that account (`merged`).
299
+ const keys = new Map<string, string>()
300
+ const merged = new Map<string, { login: string | null; id: number | null; name: string | null }>()
301
+ const add = (counts: Counts, at: number, made: number[]) => counts.set(at, made.map((value, index) => (counts.get(at)?.[index] ?? 0) + value))
302
+ for (const commit of commits) {
303
+ if (commit.parents.length > 1 || commit.committedAt === null || commit.committedAt < first) continue
304
+ const at = Math.floor((commit.committedAt - first) / WEEK_MS)
305
+ const week = weeks[at]
306
+ if (!week) continue
307
+ const [additions, deletions] = [commit.additions ?? 0, commit.deletions ?? 0]
308
+ const weekday = new Date(commit.committedAt).getUTCDay()
309
+ week.days[weekday]!++
310
+ week.dayLines[weekday]![0] += additions
311
+ week.dayLines[weekday]![1] += deletions
312
+ week.commits++
313
+ week.additions += additions
314
+ week.deletions += deletions
315
+ const release = releases.has(commit.sha)
316
+ const agent = !release && withAgent(commit, merges, direct)
317
+ if (release) week.releaseDays[weekday]!++
318
+ if (direct.has(commit.sha)) week.directDays[weekday]!++
319
+ if (agent) week.agentDays[weekday]!++
320
+ const local = new Date(commit.authoredAt != null && commit.authorZone != null ? commit.authoredAt + commit.authorZone * 60_000 : commit.committedAt)
321
+ for (const span of PULSE_WEEKS) if (at >= 52 - span) punches[span]![local.getUTCDay()]![local.getUTCHours()]!++
322
+ const key = commit.authorLogin && commit.authorId != null ? `#${commit.authorId}` : commit.authorLogin ? `@${commit.authorLogin.toLowerCase()}`
323
+ : commit.authorName ? `=${commit.authorName}` : null
324
+ if (!key) continue
325
+ keys.set(commit.sha, key)
326
+ const person = people.get(key) ?? { login: commit.authorLogin, logins: new Set<string>(), id: commit.authorId ?? null, name: commit.authorName,
327
+ weeks: new Map(), days: new Map(), commits: 0 }
328
+ if (commit.authorLogin) person.logins.add(commit.authorLogin.toLowerCase())
329
+ add(person.weeks, week.week, [1, additions, deletions])
330
+ add(person.days, Math.floor(commit.committedAt / DAY_MS) * DAY_MS, [1, additions, deletions, agent ? 1 : 0, release ? 1 : 0, direct.has(commit.sha) ? 1 : 0])
331
+ person.commits++
332
+ people.set(key, person)
333
+ }
334
+ // A login one account committed as, those of its commits read before ids
335
+ // were that account's; one more did, theirs apart, no one's.
336
+ const accounts = Map.groupBy([...people.values()].filter(person => person.id !== null).flatMap(person => [...person.logins].map(login => ({ login, person }))),
337
+ ({ login }) => login)
338
+ for (const [key, person] of people) {
339
+ const [owner, ...others] = person.login !== null && person.id === null ? accounts.get(person.login.toLowerCase()) ?? [] : []
340
+ if (!owner || others.length > 0) continue
341
+ const account = owner.person
342
+ for (const [week, counts] of person.weeks) add(account.weeks, week, counts)
343
+ for (const [day, counts] of person.days) add(account.days, day, counts)
344
+ account.commits += person.commits
345
+ people.delete(key)
346
+ merged.set(key, account)
347
+ }
348
+ const rows = (counts: Counts) => [...counts].toSorted(([a], [b]) => a - b).map(([at, made]) => [at, ...made])
349
+ const contributors = [...people.values()].toSorted((a, b) => b.commits - a.commits).slice(0, MAX_CONTRIBUTORS).map(({ login, id, name, weeks: theirs, days }) => ({
350
+ login, id, name, weeks: rows(theirs) as [number, number, number, number][], days: rows(days) as [number, number, number, number, number, number, number][] }))
351
+ // Each pushed directly by the contributor its author's commits are counted
352
+ // as, whatever account it named.
353
+ const directCommits = commits.filter(commit => direct.has(commit.sha) && commit.committedAt !== null && commit.committedAt >= first)
354
+ .toSorted((a, b) => b.committedAt! - a.committedAt!).slice(0, DIRECT_LISTED).map((commit): PulseCommit => {
355
+ const { sha, committedAt, subject, authorLogin, authorId, authorName } = commit
356
+ const author = people.get(keys.get(sha) ?? '') ?? merged.get(keys.get(sha) ?? '') ?? { login: authorLogin, id: authorId ?? null, name: authorName }
357
+ const kind = releases.has(sha) ? 'release' : withAgent(commit, merges, direct) ? 'agent' : 'without'
358
+ return { sha, at: committedAt!, subject, login: author.login, id: author.id, name: author.name, kind }
359
+ })
360
+ return { weeks, contributors, punch: punches[52]!, punches, lines: true, directCommits }
361
+ }
362
+
363
+ // The year's statistics as a period of `weeks` weeks shows them: when its
364
+ // commits are made, the period's where they were counted from its commits
365
+ // (`periodPunch`), else the year's or more, as GitHub's statistics count it;
366
+ // the commits pushed to the branch directly, the period's alone.
367
+ export function periodStats(stats: PulseStats, weeks: number) {
368
+ const { punches, directCommits, ...rest } = stats
369
+ const punch = punches?.[weeks]
370
+ const since = stats.weeks.at(-weeks)?.week ?? Number.NEGATIVE_INFINITY
371
+ return { ...rest, punch: punch ?? rest.punch, periodPunch: Boolean(punch), ...directCommits ? { directCommits: directCommits.filter(commit => commit.at >= since) } : {} }
372
+ }
373
+
374
+ // GitHub's statistics of a year past YEAR_COMMITS (repositoryStats) with
375
+ // its `lines` added in, each week's and each contributor's, by login; null
376
+ // while GitHub is counting them, `lines` null.
377
+ export function withLines(stats: PulseStats, lines: PulseLines | null): PulseStats {
378
+ if (!lines) return { ...stats, lines: null }
379
+ if (!lines.lines) return { ...stats, lines: false }
380
+ const weekly = new Map(lines.weeks.map(([week, additions, deletions]) => [week, [additions, deletions]]))
381
+ const theirs = new Map(lines.contributors.map(person => [person.login, new Map(person.weeks.map(([week, additions, deletions]) => [week, [additions, deletions]]))]))
382
+ return {
383
+ ...stats,
384
+ weeks: stats.weeks.map(week => ({ ...week, additions: weekly.get(week.week)?.[0] ?? 0, deletions: weekly.get(week.week)?.[1] ?? 0 })),
385
+ contributors: stats.contributors.map(person => ({ ...person, weeks: person.weeks.map(([week, made]) => {
386
+ const added = person.login ? theirs.get(person.login)?.get(week) : undefined
387
+ return [week, made, added?.[0] ?? 0, added?.[1] ?? 0] as [number, number, number, number]
388
+ }) })),
389
+ lines: true,
390
+ }
391
+ }
392
+
393
+ // Where a period of `weeks` weeks starts, as GitHub's statistics count weeks:
394
+ // the Sunday (UTC) that many weeks back, this week the last of them.
395
+ export function pulseSince(weeks: number, now: number) {
396
+ const today = Math.floor(now / DAY_MS) * DAY_MS
397
+ const sunday = today - new Date(today).getUTCDay() * DAY_MS
398
+ return sunday - (weeks - 1) * WEEK_MS
399
+ }
400
+
401
+ const SEARCH = (name: string, fragment: string, first = 0) => `${name}: search(type: ISSUE, query: $${name}, first: ${Math.max(first, 1)}) {
402
+ issueCount${first > 0 ? ` nodes { ...${fragment} }` : ''}
403
+ }`
404
+ const ACTIVITY_QUERY = `query($merged: String!, $mergedBefore: String!, $opened: String!, $openedBefore: String!,
405
+ $closed: String!, $closedBefore: String!, $created: String!, $createdBefore: String!) {
406
+ ${SEARCH('merged', 'pull', SEARCHED)}
407
+ ${SEARCH('mergedBefore', 'pull')}
408
+ ${SEARCH('opened', 'pull', LISTED)}
409
+ ${SEARCH('openedBefore', 'pull')}
410
+ ${SEARCH('closed', 'issue', SEARCHED)}
411
+ ${SEARCH('closedBefore', 'issue')}
412
+ ${SEARCH('created', 'issue', LISTED)}
413
+ ${SEARCH('createdBefore', 'issue')}
414
+ }
415
+ fragment pull on PullRequest { number title pullState: state isDraft createdAt mergedAt author { ${ACTOR} } }
416
+ fragment issue on Issue { number title issueState: state stateReason createdAt closedAt author { ${ACTOR} } }`
417
+
418
+ type SearchNode = { number?: unknown; title?: unknown; pullState?: unknown; issueState?: unknown; isDraft?: unknown; stateReason?: unknown
419
+ createdAt?: unknown; mergedAt?: unknown; closedAt?: unknown; author?: GraphAccount } | null
420
+ type Search = { issueCount?: unknown; nodes?: SearchNode[] } | null | undefined
421
+ const REASONS: Record<string, string> = { COMPLETED: 'completed', NOT_PLANNED: 'not-planned', DUPLICATE: 'duplicate' }
422
+
423
+ // An issue or pull request a search lists, as the popup's preview of it
424
+ // takes one, `at` when it was merged, opened or closed.
425
+ function listed(node: SearchNode, at: unknown) {
426
+ if (!node || !Number.isSafeInteger(node.number) || (node.number as number) <= 0) return null
427
+ const title = typeof node.title === 'string' ? node.title.trim().slice(0, MAX_TITLE) : ''
428
+ const author = actorOf(node.author)
429
+ const common = { number: node.number as number, title, author: author.login, authorId: author.id, at: timeOf(at), createdAt: timeOf(node.createdAt) }
430
+ return node.pullState === undefined
431
+ ? { ...common, kind: 'issues', state: node.issueState === 'OPEN' ? 'open' : 'closed', reason: REASONS[String(node.stateReason)] ?? null }
432
+ : { ...common, kind: 'pulls', state: node.pullState === 'MERGED' ? 'merged' : node.pullState === 'OPEN' ? 'open' : 'closed', draft: node.isDraft === true }
433
+ }
434
+
435
+ // The pull requests merged and opened and the issues closed and opened since
436
+ // the start of the week `weeks` weeks back (`since`), and over the same days
437
+ // of the week `weeks` weeks earlier (`previous`, its count: a week's Sunday to
438
+ // Thursday beside the week before's, not the days just before, whose days of
439
+ // the week differ), the latest of each listed, as many as LISTED: those
440
+ // opened as GitHub sorts them, those merged or closed the latest of the
441
+ // SEARCHED most recently updated, which are the latest of all where the
442
+ // period holds no more, or the last listed was merged or closed after the
443
+ // SEARCHED-th was last updated. A search counts by the day (UTC). Narrowed
444
+ // (`narrowing`), those of its days from `from` to `to` (both days, UTC;
445
+ // none, on), and those its `authors` (GitHub logins) opened, any of them.
446
+ export async function repositoryActivity(fullName: string, token: string, weeks: number, now: number = Date.now(), fetchImpl: typeof fetch = globalThis.fetch,
447
+ narrowing: PulseNarrowing | null = null) {
448
+ const since = pulseSince(weeks, now)
449
+ const back = weeks * WEEK_MS
450
+ const day = (at: number) => new Date(at).toISOString().slice(0, 10)
451
+ const current = narrowing?.to == null ? `>=${day(narrowing?.from ?? since)}` : `${day(narrowing.from)}..${day(narrowing.to)}`
452
+ const previous = `${day(since - back)}..${day(now - back)}`
453
+ const repo = `repo:${fullName}`
454
+ // An app's login (`name[bot]`) is searched for as GitHub names its app.
455
+ const by = (narrowing?.authors ?? []).map(login => ` author:${login.endsWith('[bot]') ? `app/${login.slice(0, -5)}` : login}`).join('')
456
+ const asked = (what: string, range: string, sort: string) => `${repo} ${what}${range}${by} sort:${sort}`
457
+ const kinds = {
458
+ merged: ['is:pr is:merged merged:', 'updated-desc'], opened: ['is:pr created:', 'created-desc'],
459
+ closed: ['is:issue is:closed closed:', 'updated-desc'], created: ['is:issue created:', 'created-desc'],
460
+ } as const
461
+ const variables = Object.fromEntries(Object.entries(kinds).flatMap(([name, [what, sort]]) => [[name, asked(what, current, sort)],
462
+ [`${name}Before`, asked(what, previous, sort)]]))
463
+ const data = await githubGraphql(ACTIVITY_QUERY, variables, token, fetchImpl) as Record<string, Search> | null
464
+ const at = { merged: 'mergedAt', opened: 'createdAt', closed: 'closedAt', created: 'createdAt' } as const
465
+ const told = Object.fromEntries((Object.keys(kinds) as (keyof typeof kinds)[]).map(name => [name, {
466
+ count: count(data?.[name]?.issueCount),
467
+ previous: count(data?.[`${name}Before`]?.issueCount),
468
+ items: (data?.[name]?.nodes ?? []).flatMap(node => listed(node, node?.[at[name]]) ?? []).toSorted((a, b) => (b.at ?? 0) - (a.at ?? 0)).slice(0, LISTED),
469
+ }]))
470
+ return { since, previousSince: since - back, ...told }
471
+ }
@@ -0,0 +1,105 @@
1
+ // A package's risk line, as a repository risk scan tells it
2
+ // (repository-risk.ts): its version's document read and assessed, as risk
3
+ // tells one npm removed where npm has none; and how a failure is told.
4
+ import { setTimeout as delay } from 'node:timers/promises'
5
+ import { NpmRiskError, SEVERITIES, type Severity } from '../risk/index.js'
6
+ import { GithubApiError } from './github-errors.ts'
7
+ import { NpmPackageError, type NpmVersionDocument } from './npm-packages.ts'
8
+ import type { RepositoryRiskLine } from './repository-risk.ts'
9
+
10
+ // An assessment refused as busy (`npm-busy`, by npm-risk.ts or the npm reads
11
+ // beneath it), or that npm asked to ask later (risk's `upstream-busy`, as its
12
+ // downloads API answers past a burst of requests), is asked again after a
13
+ // wait, up to this many times.
14
+ export const BUSY_RETRIES = 20
15
+ export const BUSY_WAIT_MS = 1000
16
+
17
+ // How long a package's risk line, or a lockfile's advisories, is told as it
18
+ // is: after it, a risk line is told stale and assessed again, as risk tells
19
+ // again what of a package changes in time, and advisories asked again, as npm
20
+ // publishes them (repository-risk.ts).
21
+ export const RISK_KEPT_MS = 60 * 60_000
22
+
23
+ // The most severe of `findings`, or null for none.
24
+ export function highestSeverity(findings: readonly { severity: Severity }[]): Severity | null {
25
+ return SEVERITIES.find(severity => findings.some(finding => finding.severity === severity)) ?? null
26
+ }
27
+
28
+ // Why a step failed, as a line says it: an error's code, and for a lockfile
29
+ // refused, what of it its reader refused.
30
+ export type RiskFailure = { error: string; detail?: string }
31
+ type RiskLine = Extract<RepositoryRiskLine, { type: 'risk' }>
32
+
33
+ // What an error is known by: a GitHub or npm failure's code, or `failed`;
34
+ // GitHub not reached with what failed (githubUnreachable), while `doing` what
35
+ // of a repository, and risk's with what it asked of npm and how that failed,
36
+ // where they say.
37
+ export function failureOf(error: unknown, doing?: string): RiskFailure {
38
+ if (error instanceof GithubApiError && error.detail) return { error: error.message, detail: doing ? `${doing}: ${error.detail}` : error.detail }
39
+ if (error instanceof GithubApiError || error instanceof NpmPackageError) return { error: error.message }
40
+ if (!(error instanceof NpmRiskError)) return { error: 'failed' }
41
+ return error.message === error.code ? { error: error.code } : { error: error.code, detail: error.message }
42
+ }
43
+
44
+ export const isBusy = (error: unknown) => (error instanceof NpmPackageError && error.status === 429) || (error instanceof NpmRiskError && error.code === 'upstream-busy')
45
+
46
+ // A package to assess: npm's of its name and version, or, with an
47
+ // `integrity`, a mirror's held to it.
48
+ export interface AssessedPackage { name: string; version: string; integrity?: string }
49
+
50
+ export type Assessment = { published: string | null; findings: { id: string; severity: Severity; takenDown?: unknown }[]; score: { score: number } }
51
+
52
+ // What of a scan's source assessing a package asks (RepositoryRiskSource).
53
+ export interface AssessingSource {
54
+ version(name: string, version: string, signal: AbortSignal): Promise<NpmVersionDocument>
55
+ assess(doc: NpmVersionDocument, teamScoped: boolean, signal: AbortSignal): Promise<Assessment>
56
+ removed(name: string, version: string, teamScoped: boolean, signal: AbortSignal): Promise<Assessment>
57
+ }
58
+
59
+ // A package's risk line, its version's document kept and the assessment asked
60
+ // again after a wait while the server is busy; null once the scan stops. A
61
+ // version npm has no document of is told as risk tells one npm removed
62
+ // (removedOf), its malware keeping whether its package was taken down.
63
+ export async function assessPackage(source: AssessingSource, signal: AbortSignal, pkg: AssessedPackage, teamScoped: boolean): Promise<RiskLine | null> {
64
+ const at = { type: 'risk', ...pkg } as const
65
+ let doc: NpmVersionDocument | NpmPackageError | undefined
66
+ for (let attempt = 0; ; attempt++) {
67
+ try {
68
+ const read = doc ??= await documentOf(source, pkg, signal)
69
+ if (!(read instanceof NpmPackageError) && pkg.integrity !== undefined && !pkg.integrity.split(/\s+/u).includes(read.dist.integrity)) return { ...at, error: 'integrity-mismatch' }
70
+ const { published, findings, score } = read instanceof NpmPackageError ? await removedOf(source, pkg, teamScoped, signal, read) : await assessedOf(source, pkg, teamScoped, signal, read)
71
+ const told = findings.map(({ id, severity, takenDown }) => ({ id, severity, ...takenDown === true ? { takenDown: true as const } : {} }))
72
+ return { ...at, published, severity: highestSeverity(told), score: score.score, findings: told }
73
+ } catch (error) {
74
+ if (signal.aborted) return null
75
+ if (!isBusy(error) || attempt >= BUSY_RETRIES) return { ...at, ...failureOf(error) }
76
+ try { await delay(BUSY_WAIT_MS * Math.min(attempt + 1, 5), undefined, { signal }) } catch { return null }
77
+ }
78
+ }
79
+ }
80
+
81
+ // npm's document of a version, or its answer that it has none (a 404).
82
+ async function documentOf(source: AssessingSource, pkg: AssessedPackage, signal: AbortSignal): Promise<NpmVersionDocument | NpmPackageError> {
83
+ try { return await source.version(pkg.name, pkg.version, signal) } catch (error) {
84
+ if (error instanceof NpmPackageError && error.status === 404) return error
85
+ throw error
86
+ }
87
+ }
88
+
89
+ // A version's assessment; where risk finds npm no longer has it, as a document
90
+ // read from where versions' are kept doesn't tell, as one npm removed.
91
+ async function assessedOf(source: AssessingSource, pkg: AssessedPackage, teamScoped: boolean, signal: AbortSignal, doc: NpmVersionDocument): Promise<Assessment> {
92
+ try { return await source.assess(doc, teamScoped, signal) } catch (error) {
93
+ if (!(error instanceof NpmRiskError && error.code === 'version-not-found')) throw error
94
+ return removedOf(source, pkg, teamScoped, signal, new NpmPackageError(404, 'package-not-found'))
95
+ }
96
+ }
97
+
98
+ // A version npm has no document of, as risk tells one npm removed, as it
99
+ // removes every one it finds malware in (`removed`): `gone`, npm's answer of
100
+ // none, thrown where nothing tells of it.
101
+ async function removedOf(source: AssessingSource, pkg: AssessedPackage, teamScoped: boolean, signal: AbortSignal, gone: NpmPackageError): Promise<Assessment> {
102
+ try { return await source.removed(pkg.name, pkg.version, teamScoped, signal) } catch (error) {
103
+ throw error instanceof NpmRiskError && (error.code === 'version-not-found' || error.code === 'package-not-found') ? gone : error
104
+ }
105
+ }