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

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