@preventive/triage 1.0.0-alpha.8 → 1.0.0-alpha.80

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 (442) hide show
  1. package/LICENSE-APACHE +202 -0
  2. package/README.md +16 -0
  3. package/api/reap.ts +16 -78
  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 +6 -0
  13. package/common/bundle-compare-diff.js +377 -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-imports.js +20 -0
  20. package/common/bundle-metadata.d.ts +15 -0
  21. package/common/bundle-metadata.js +226 -0
  22. package/common/bundle-pkg-of.d.ts +1 -0
  23. package/common/bundle-pkg-of.js +90 -0
  24. package/common/bundle-reasons.d.ts +6 -0
  25. package/common/bundle-reasons.js +58 -0
  26. package/common/bundle-source-links.d.ts +6 -0
  27. package/common/bundle-source-links.js +216 -0
  28. package/common/bundle-sourcemap.d.ts +10 -0
  29. package/common/bundle-sourcemap.js +100 -0
  30. package/common/bundle-sources.d.ts +10 -0
  31. package/common/bundle-sources.js +374 -0
  32. package/common/bundle-stats.js +41 -0
  33. package/common/bundle-tabs.js +1 -0
  34. package/common/code-language.js +66 -0
  35. package/common/default-scan-models.ts +36 -0
  36. package/common/dependency-reviews.d.ts +18 -0
  37. package/common/dependency-reviews.js +64 -0
  38. package/common/finding-duplicates.js +63 -0
  39. package/common/finding-filters.js +313 -0
  40. package/common/finding-id.js +47 -0
  41. package/common/finding-repo.d.ts +5 -0
  42. package/common/finding-repo.js +67 -0
  43. package/common/github-issue-labels.d.ts +1 -0
  44. package/common/github-issue-labels.js +11 -0
  45. package/common/github-pr.ts +56 -0
  46. package/common/gzip.js +59 -0
  47. package/common/line-diff.d.ts +14 -0
  48. package/common/line-diff.js +181 -0
  49. package/common/linked-workspace-groups.js +63 -0
  50. package/common/managed/agent-tasks.ts +292 -0
  51. package/common/managed/comments.ts +43 -0
  52. package/common/managed/dependency-routes.js +25 -0
  53. package/common/managed/directory-packages.ts +28 -0
  54. package/common/managed/finding-detail.d.ts +5 -0
  55. package/common/managed/finding-detail.js +75 -0
  56. package/common/managed/finding-values.d.ts +2 -0
  57. package/common/managed/finding-values.js +138 -0
  58. package/common/managed/github-agents.ts +114 -0
  59. package/common/managed/github-logins.ts +49 -0
  60. package/common/managed/lite-name.d.ts +2 -0
  61. package/common/managed/lite-name.js +20 -0
  62. package/common/managed/npm-packages.d.ts +9 -0
  63. package/common/managed/npm-packages.js +63 -0
  64. package/common/managed/permissions.ts +31 -0
  65. package/common/managed/report-content.ts +72 -0
  66. package/common/managed/report-filter.ts +120 -0
  67. package/common/managed/repository-alias.ts +65 -0
  68. package/common/managed/review-view-routes.js +23 -0
  69. package/common/managed/risk-routes.js +30 -0
  70. package/common/managed/roles.ts +41 -0
  71. package/common/managed/routes.d.ts +2 -0
  72. package/common/managed/routes.js +385 -0
  73. package/common/managed/scan-models.ts +6 -0
  74. package/common/managed/stasis-config.ts +7 -0
  75. package/common/managed/team-app.d.ts +19 -0
  76. package/common/managed/team-app.js +129 -0
  77. package/common/managed/team-filters.js +26 -0
  78. package/common/managed/triage.ts +83 -0
  79. package/common/managed/upload-seal.ts +126 -0
  80. package/common/pretty-json.js +98 -0
  81. package/common/pretty-kinds.js +20 -0
  82. package/common/pretty-print.d.ts +6 -0
  83. package/common/pretty-print.js +36 -0
  84. package/common/pretty-sourcemap.js +70 -0
  85. package/common/repo-commit.d.ts +4 -0
  86. package/common/repo-commit.js +30 -0
  87. package/common/revalidation-conflicts.js +48 -0
  88. package/common/revalidation-input-groups.js +56 -0
  89. package/common/save-error-reason.ts +20 -7
  90. package/common/scan-server.ts +13 -0
  91. package/common/security-links.d.ts +5 -0
  92. package/common/security-links.js +33 -0
  93. package/common/server-info.ts +46 -0
  94. package/common/sourcemap-listing.js +78 -0
  95. package/common/sourcemap-mappings.js +136 -0
  96. package/common/sourcemap-unlist.js +85 -0
  97. package/common/stasis-files.d.ts +5 -0
  98. package/common/stasis-files.js +20 -0
  99. package/common/stasis-tgz.d.ts +6 -0
  100. package/common/stasis-tgz.js +27 -0
  101. package/common/utf8.d.ts +3 -0
  102. package/common/utf8.js +45 -0
  103. package/common/whitespace-insensitive.js +19 -0
  104. package/common/workspace-app.js +91 -0
  105. package/common/workspace-groups.js +176 -0
  106. package/out/activity.js +2 -0
  107. package/out/brotli-fallback.js +3 -3
  108. package/out/chunk-2XUEZHIP.js +28 -0
  109. package/out/chunk-55YIWY3H.js +5 -0
  110. package/out/chunk-5AVGKFMR.js +1 -0
  111. package/out/chunk-5CJKUV53.js +1 -0
  112. package/out/chunk-5EAVJAD2.js +3 -0
  113. package/out/chunk-5M2X3QPK.js +6 -0
  114. package/out/chunk-5QWPKTCE.js +40 -0
  115. package/out/chunk-6CCSTJWB.js +1 -0
  116. package/out/chunk-6VOB5WXX.js +2 -0
  117. package/out/chunk-6Y6PZ2BU.js +9 -0
  118. package/out/chunk-74JZTGTO.js +11 -0
  119. package/out/chunk-7BKKYVWR.js +7 -0
  120. package/out/chunk-7C7DWL7I.js +1 -0
  121. package/out/chunk-7HP2VYIC.js +2 -0
  122. package/out/chunk-7YFJUT2P.js +1 -0
  123. package/out/chunk-7YO4QV5P.js +1 -0
  124. package/out/chunk-A4BBBHQU.js +1 -0
  125. package/out/chunk-B64CTMVU.js +4 -0
  126. package/out/chunk-BEKYZCPX.js +14 -0
  127. package/out/chunk-C4Z6ZBXV.js +10 -0
  128. package/out/chunk-CU3FPB3P.js +1 -0
  129. package/out/chunk-DEVAORP2.js +1 -0
  130. package/out/chunk-DUASGS2O.js +8 -0
  131. package/out/chunk-DUS5ARE2.js +53 -0
  132. package/out/chunk-EEJA7JBI.js +13 -0
  133. package/out/chunk-FSU2PLJL.js +1 -0
  134. package/out/chunk-GBMAXAYK.js +3 -0
  135. package/out/chunk-GO7FT4OD.js +1 -0
  136. package/out/chunk-GX5UXWT4.js +1 -0
  137. package/out/chunk-ITUKKCCK.js +10 -0
  138. package/out/chunk-IYPY47MC.js +1 -0
  139. package/out/chunk-JXBRWLMA.js +4 -0
  140. package/out/chunk-K4XJHM2T.js +1 -0
  141. package/out/chunk-LBD3M3J6.js +1 -0
  142. package/out/chunk-LVSLM7HB.js +1 -0
  143. package/out/chunk-LVW7WWV4.js +1 -0
  144. package/out/chunk-MV66NL3G.js +3 -0
  145. package/out/chunk-N57OWFKY.js +15 -0
  146. package/out/chunk-NRPC74AM.js +1 -0
  147. package/out/chunk-OOJM4CTU.js +1 -0
  148. package/out/chunk-OWSEQOL5.js +1 -0
  149. package/out/chunk-PKLVXUEI.js +11 -0
  150. package/out/chunk-PLGH63UC.js +2 -0
  151. package/out/chunk-PNHBZGDD.js +1 -0
  152. package/out/chunk-PTFYDJUP.js +1 -0
  153. package/out/chunk-PWFUOLZK.js +17 -0
  154. package/out/chunk-PXK7EU4V.js +1 -0
  155. package/out/chunk-QD3IBSF4.js +7 -0
  156. package/out/chunk-QI66YA4F.js +1 -0
  157. package/out/chunk-QRKFPLA4.js +80 -0
  158. package/out/chunk-R3NZFXVR.js +1 -0
  159. package/out/chunk-R5O6FAW4.js +2 -0
  160. package/out/chunk-RPNO56H2.js +1 -0
  161. package/out/chunk-SSPDMA6D.js +1 -0
  162. package/out/chunk-SZWPYLPC.js +1 -0
  163. package/out/chunk-TUII34K2.js +1 -0
  164. package/out/chunk-UJP4PQJA.js +1 -0
  165. package/out/chunk-UJSJMXEG.js +1 -0
  166. package/out/chunk-UR4WYMIP.js +1 -0
  167. package/out/chunk-VHEXSGGP.js +1 -0
  168. package/out/chunk-VYYUMYVW.js +9 -0
  169. package/out/chunk-VZPPX6MV.js +1 -0
  170. package/out/chunk-WCDYSIKG.js +1 -0
  171. package/out/chunk-XM4RLC4A.js +2 -0
  172. package/out/chunk-YKCRCNYZ.js +266 -0
  173. package/out/chunk-ZQHLECTI.js +1 -0
  174. package/out/client-managed-import.js +4 -0
  175. package/out/client-managed.js +37 -0
  176. package/out/client-sync.js +11 -17
  177. package/out/compare.js +26 -0
  178. package/out/dialogs.js +40 -0
  179. package/out/github-issue-authorized.html +3 -0
  180. package/out/github-issue-authorized.js +1 -0
  181. package/out/graph.js +19 -4
  182. package/out/index.html +104 -24
  183. package/out/prism.js +14 -10
  184. package/out/scan.js +2 -0
  185. package/out/stasis.svg +20 -0
  186. package/out/terminal.js +367 -39
  187. package/out/view.css +1 -1
  188. package/out/view.js +19 -147
  189. package/package.json +409 -64
  190. package/risk/actions/findings.js +161 -0
  191. package/risk/actions/resolve.js +287 -0
  192. package/risk/actions/scripts/commands.js +182 -0
  193. package/risk/actions/scripts/grade.js +113 -0
  194. package/risk/actions/scripts/packages.js +123 -0
  195. package/risk/actions/scripts/shell.js +169 -0
  196. package/risk/actions/uses.js +94 -0
  197. package/risk/actions/workflow.js +183 -0
  198. package/risk/files/characters.js +341 -0
  199. package/risk/files/hosts.js +206 -0
  200. package/risk/files/readability.js +185 -0
  201. package/risk/files/runs-code.js +563 -0
  202. package/risk/files/script.js +402 -0
  203. package/risk/files/source-map-link.js +43 -0
  204. package/risk/files/stamps.js +47 -0
  205. package/risk/index.d.ts +294 -0
  206. package/risk/index.js +12 -0
  207. package/risk/npm/assess.js +285 -0
  208. package/risk/npm/combined.js +68 -0
  209. package/risk/npm/compare.js +236 -0
  210. package/risk/npm/dependencies.js +172 -0
  211. package/risk/npm/diff.js +79 -0
  212. package/risk/npm/downloads.js +84 -0
  213. package/risk/npm/files.js +445 -0
  214. package/risk/npm/held.js +67 -0
  215. package/risk/npm/install-scripts.js +34 -0
  216. package/risk/npm/malware.js +38 -0
  217. package/risk/npm/manifest.js +65 -0
  218. package/risk/npm/new-dependency.js +60 -0
  219. package/risk/npm/old-version.js +108 -0
  220. package/risk/npm/registry.js +393 -0
  221. package/risk/npm/release.js +85 -0
  222. package/risk/npm/score.js +59 -0
  223. package/risk/npm/specs.js +124 -0
  224. package/risk/npm/tarball.js +169 -0
  225. package/server-common/database-config.ts +16 -0
  226. package/server-common/initialize.ts +18 -0
  227. package/server-common/npm-advisories.ts +101 -0
  228. package/{server → server-common}/origin.ts +5 -5
  229. package/server-common/reap.ts +48 -0
  230. package/server-common/scan-config.ts +19 -0
  231. package/server-common/standalone.ts +29 -0
  232. package/server-common/storage-crypto.ts +182 -0
  233. package/server-common/storage-log.ts +38 -0
  234. package/server-common/vercel-blob.ts +103 -0
  235. package/server-e2e/app.ts +487 -0
  236. package/{server → server-e2e}/bus-receiver.ts +2 -1
  237. package/{server → server-e2e}/cli.js +9 -4
  238. package/{server → server-e2e}/config.ts +50 -42
  239. package/{server → server-e2e}/db-neon.ts +2 -2
  240. package/{server → server-e2e}/db-revision-sql.ts +1 -1
  241. package/{server → server-e2e}/db-stmt.ts +2 -2
  242. package/{server → server-e2e}/db.ts +7 -7
  243. package/{server → server-e2e}/http.ts +44 -13
  244. package/{server → server-e2e}/hub.ts +40 -9
  245. package/server-e2e/index.ts +17 -0
  246. package/server-e2e/lifecycle.ts +95 -0
  247. package/{server → server-e2e}/neon-driver.ts +2 -2
  248. package/{server → server-e2e}/npm-proxy.ts +12 -145
  249. package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
  250. package/{server → server-e2e}/objstore/blob.ts +1 -1
  251. package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
  252. package/{server → server-e2e}/objstore/handlers.ts +9 -8
  253. package/{server → server-e2e}/objstore/init.ts +19 -27
  254. package/{server → server-e2e}/objstore/reaper.ts +1 -1
  255. package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
  256. package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
  257. package/{server → server-e2e}/objstore/rest.ts +3 -3
  258. package/{server → server-e2e}/objstore/store-neon.ts +6 -10
  259. package/{server → server-e2e}/objstore/store.ts +7 -7
  260. package/{server → server-e2e}/objstore/tokens.ts +2 -2
  261. package/{server → server-e2e}/pubsub.ts +12 -9
  262. package/{server → server-e2e}/sign.ts +4 -4
  263. package/{server → server-e2e}/sse-server.ts +60 -33
  264. package/{server → server-e2e}/static.ts +18 -17
  265. package/{server → server-e2e}/sync-handlers.ts +64 -30
  266. package/{server → server-e2e}/ws-server.ts +20 -9
  267. package/server-managed/activity.ts +247 -0
  268. package/server-managed/agent-merges.ts +109 -0
  269. package/server-managed/app-agents.ts +23 -0
  270. package/server-managed/avatar-store.ts +13 -0
  271. package/server-managed/blob-store.ts +26 -0
  272. package/server-managed/brotli.ts +10 -0
  273. package/server-managed/bundle-advisories.ts +79 -0
  274. package/server-managed/bundle-advisory-inventory.ts +85 -0
  275. package/server-managed/bundle-build-diagnostics.d.ts +10 -0
  276. package/server-managed/bundle-build-diagnostics.js +23 -0
  277. package/server-managed/bundle-build-leases.ts +41 -0
  278. package/server-managed/bundle-build-worker.js +380 -0
  279. package/server-managed/bundle-build.ts +326 -0
  280. package/server-managed/bundle-cache.ts +261 -0
  281. package/server-managed/bundle-catalog.ts +29 -0
  282. package/server-managed/bundle-commits.ts +133 -0
  283. package/server-managed/bundle-dependency-reviews.ts +91 -0
  284. package/server-managed/bundle-store.ts +24 -0
  285. package/server-managed/bundle-summary-cache.ts +139 -0
  286. package/server-managed/bundle-validation.ts +33 -0
  287. package/server-managed/bundle.ts +151 -0
  288. package/server-managed/cache-storage.ts +20 -0
  289. package/server-managed/cli.js +21 -0
  290. package/server-managed/combined.ts +43 -0
  291. package/server-managed/comments.ts +138 -0
  292. package/server-managed/commit-coauthors.ts +105 -0
  293. package/server-managed/commit-lockfiles.ts +78 -0
  294. package/server-managed/comparison.ts +51 -0
  295. package/server-managed/config.ts +163 -0
  296. package/server-managed/content-access.ts +15 -0
  297. package/server-managed/crypto.ts +25 -0
  298. package/server-managed/db-methods.ts +1914 -0
  299. package/server-managed/db-neon.ts +398 -0
  300. package/server-managed/db-schema.ts +263 -0
  301. package/server-managed/db-table-names.ts +22 -0
  302. package/server-managed/db.ts +149 -0
  303. package/server-managed/dependabot-access.ts +61 -0
  304. package/server-managed/dependabot-alerts.ts +180 -0
  305. package/server-managed/dependency-review-comments.ts +143 -0
  306. package/server-managed/dependency-reviews.ts +369 -0
  307. package/server-managed/github-accounts.ts +59 -0
  308. package/server-managed/github-actions.ts +71 -0
  309. package/server-managed/github-app.ts +347 -0
  310. package/server-managed/github-errors.ts +92 -0
  311. package/server-managed/github-graphql.ts +42 -0
  312. package/server-managed/github-issue-links.ts +264 -0
  313. package/server-managed/github-issue-oauth.ts +30 -0
  314. package/server-managed/github-issues.ts +157 -0
  315. package/server-managed/github-link-oauth.ts +56 -0
  316. package/server-managed/github-links.ts +204 -0
  317. package/server-managed/github-metadata.ts +213 -0
  318. package/server-managed/github-oauth.ts +264 -0
  319. package/server-managed/github-pulls.ts +257 -0
  320. package/server-managed/github-requests.ts +181 -0
  321. package/server-managed/github-users.ts +30 -0
  322. package/server-managed/github-values.ts +26 -0
  323. package/server-managed/history-windows.ts +172 -0
  324. package/server-managed/http-response.ts +76 -0
  325. package/server-managed/http.ts +6324 -0
  326. package/server-managed/import-triage.ts +51 -0
  327. package/server-managed/index.ts +204 -0
  328. package/server-managed/kept-briefly.ts +37 -0
  329. package/server-managed/kept.ts +28 -0
  330. package/server-managed/link-reports.ts +149 -0
  331. package/server-managed/listed-activity.ts +39 -0
  332. package/server-managed/locked-packages.ts +234 -0
  333. package/server-managed/lockfile-scope.ts +58 -0
  334. package/server-managed/lru.ts +30 -0
  335. package/server-managed/managed-issues.ts +92 -0
  336. package/server-managed/management-catalog.ts +45 -0
  337. package/server-managed/management.ts +116 -0
  338. package/server-managed/npm-delta-worker.js +142 -0
  339. package/server-managed/npm-delta.ts +277 -0
  340. package/server-managed/npm-insights.ts +455 -0
  341. package/server-managed/npm-kept.ts +265 -0
  342. package/server-managed/npm-loads.ts +259 -0
  343. package/server-managed/npm-manifest.ts +117 -0
  344. package/server-managed/npm-packages.ts +469 -0
  345. package/server-managed/npm-patch-paths.ts +86 -0
  346. package/server-managed/npm-patch.ts +455 -0
  347. package/server-managed/npm-provenance.ts +127 -0
  348. package/server-managed/npm-risk.ts +287 -0
  349. package/server-managed/object-storage-disk.ts +147 -0
  350. package/server-managed/object-storage-vercel.ts +71 -0
  351. package/server-managed/object-storage.ts +82 -0
  352. package/server-managed/package-entry-points.ts +127 -0
  353. package/server-managed/pretty-copies.ts +22 -0
  354. package/server-managed/pretty-format.d.ts +3 -0
  355. package/server-managed/pretty-format.js +13 -0
  356. package/server-managed/pretty-print.ts +442 -0
  357. package/server-managed/public-workspace.ts +243 -0
  358. package/server-managed/pull-comment-reviews.ts +161 -0
  359. package/server-managed/pull-dependencies.ts +370 -0
  360. package/server-managed/pull-dependency-reviews.ts +407 -0
  361. package/server-managed/pull-reviews.ts +202 -0
  362. package/server-managed/queue.ts +54 -0
  363. package/server-managed/release-commits.ts +85 -0
  364. package/server-managed/rename-diff-worker.js +30 -0
  365. package/server-managed/rename-diff.ts +237 -0
  366. package/server-managed/repo-path.ts +21 -0
  367. package/server-managed/report-migration.ts +32 -0
  368. package/server-managed/report-opening.ts +77 -0
  369. package/server-managed/report-query.ts +10 -0
  370. package/server-managed/report-response.ts +16 -0
  371. package/server-managed/report-sources.ts +185 -0
  372. package/server-managed/report-store.ts +77 -0
  373. package/server-managed/repository-actions.ts +220 -0
  374. package/server-managed/repository-agents.ts +422 -0
  375. package/server-managed/repository-aliases.ts +119 -0
  376. package/server-managed/repository-browser.ts +361 -0
  377. package/server-managed/repository-changes.ts +280 -0
  378. package/server-managed/repository-code.ts +222 -0
  379. package/server-managed/repository-dependency-reviews.ts +182 -0
  380. package/server-managed/repository-discovery.ts +83 -0
  381. package/server-managed/repository-history.ts +428 -0
  382. package/server-managed/repository-issues.ts +293 -0
  383. package/server-managed/repository-policy.ts +27 -0
  384. package/server-managed/repository-pulls.ts +207 -0
  385. package/server-managed/repository-pulse.ts +477 -0
  386. package/server-managed/repository-risk-assess.ts +108 -0
  387. package/server-managed/repository-risk-audit.ts +78 -0
  388. package/server-managed/repository-risk-caches.ts +37 -0
  389. package/server-managed/repository-risk-read.ts +260 -0
  390. package/server-managed/repository-risk-stasis.ts +61 -0
  391. package/server-managed/repository-risk-turn.ts +97 -0
  392. package/server-managed/repository-risk.ts +516 -0
  393. package/server-managed/repository-squashes.ts +160 -0
  394. package/server-managed/repository-stamp.ts +41 -0
  395. package/server-managed/request-timing.ts +63 -0
  396. package/server-managed/reviewed-dependencies.ts +170 -0
  397. package/server-managed/revisions.ts +35 -0
  398. package/server-managed/scan-downloads.ts +121 -0
  399. package/server-managed/session.ts +132 -0
  400. package/server-managed/slugs.ts +38 -0
  401. package/server-managed/solidity-entry-points.ts +71 -0
  402. package/server-managed/sql-postgres.ts +34 -0
  403. package/server-managed/sql.ts +107 -0
  404. package/server-managed/stasis-config.ts +147 -0
  405. package/server-managed/stasis-dependencies.ts +221 -0
  406. package/server-managed/static.ts +28 -0
  407. package/server-managed/storage-command.ts +16 -0
  408. package/server-managed/storage-db.ts +183 -0
  409. package/server-managed/storage-encryption.ts +288 -0
  410. package/server-managed/storage-maintenance.ts +259 -0
  411. package/server-managed/storage-payload.ts +121 -0
  412. package/server-managed/storage-stores.ts +91 -0
  413. package/server-managed/storage.ts +82 -0
  414. package/server-managed/team-app-summaries.ts +56 -0
  415. package/server-managed/team-app.ts +156 -0
  416. package/server-managed/team-catalog.ts +7 -0
  417. package/server-managed/team-feed.ts +180 -0
  418. package/server-managed/team-npm-scopes.ts +103 -0
  419. package/server-managed/team-reports.ts +368 -0
  420. package/server-managed/triage-response.ts +16 -0
  421. package/server-managed/type-only-proof.js +161 -0
  422. package/server-managed/type-only-worker.js +31 -0
  423. package/server-managed/type-only.ts +135 -0
  424. package/server-managed/uploads.ts +106 -0
  425. package/server-managed/upstream-cache.ts +256 -0
  426. package/server-managed/view-as.ts +58 -0
  427. package/server-managed/worker-turns.ts +76 -0
  428. package/server-managed/workspace-shares.ts +170 -0
  429. package/server.ts +70 -0
  430. package/strip-types-loader.js +13 -10
  431. package/server/index.ts +0 -480
  432. package/server/lifecycle.ts +0 -208
  433. /package/{LICENSE → LICENSE-MIT} +0 -0
  434. /package/{server → server-e2e}/auth.ts +0 -0
  435. /package/{server → server-e2e}/config.example.json +0 -0
  436. /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
  437. /package/{server → server-e2e}/objstore/fs.ts +0 -0
  438. /package/{server → server-e2e}/objstore/sign.ts +0 -0
  439. /package/{server → server-e2e}/peer.ts +0 -0
  440. /package/{server → server-e2e}/sse-session.ts +0 -0
  441. /package/{server → server-e2e}/util.ts +0 -0
  442. /package/{server → server-e2e}/validation.ts +0 -0
@@ -0,0 +1,326 @@
1
+ import { Buffer } from 'node:buffer'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { tmpdir, totalmem } from 'node:os'
4
+ import { join, posix } from 'node:path'
5
+ import { Worker } from 'node:worker_threads'
6
+ import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
7
+ import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
8
+ import type { BundleBuildConditions } from './db-methods.ts'
9
+
10
+ export class BundleBuildError extends Error {
11
+ status: number
12
+ code: string
13
+ constructor(status: number, code: string) { super(code); this.status = status; this.code = code }
14
+ }
15
+
16
+ interface BundleBuildInput {
17
+ repoId: number
18
+ commit: string
19
+ entries: string[]
20
+ directory: string
21
+ options: { conditions?: string[]; mainFields?: string[]; metro?: boolean; platforms?: string[]; jsx?: boolean; packageManager?: 'soldeer' }
22
+ // What the stored bundle records; null for Solidity, which takes no
23
+ // conditions, and for entries given none, which stasis.config.json must
24
+ // then list (the build checks: bundle-build-worker.js).
25
+ conditions: BundleBuildConditions | null
26
+ // The branch the commit was picked by, where it was: Stasis asks it first
27
+ // when it holds the commit to the repo's own history, which GitHub's compare
28
+ // tells of it, so nothing is taken on trust (one the commit isn't of is
29
+ // looked past). Without it, Stasis lists the repo's tags and branches and
30
+ // compares up to 100 of those.
31
+ branch?: string
32
+ }
33
+
34
+ // A name git takes for a branch (git check-ref-format --branch), at most
35
+ // GitHub's length for one.
36
+ export function branchName(value: unknown): value is string {
37
+ return typeof value === 'string' && value.length > 0 && value.length <= 255
38
+ && !/[\p{Cc}\s~^:?*[\\]|\.\.|@\{|\/\/|^-|^\/|\/$|\.$|^@$|(?:^|\/)\.|\.lock(?:\/|$)/u.test(value)
39
+ }
40
+
41
+ function path(value: unknown): value is string {
42
+ return typeof value === 'string' && value.length > 0 && value.length <= 1024 && !/[\\\p{Cc}]/u.test(value)
43
+ && value.split('/').every(part => part !== '' && part !== '.' && part !== '..')
44
+ }
45
+
46
+ const isScript = (entry: string) => /\.[cm]?[tj]sx?$/iu.test(entry)
47
+
48
+ // Whether a build takes `value` as an entry point, with others in its language.
49
+ export function buildableEntry(value: unknown): value is string {
50
+ return path(value) && (isScript(value) || value.endsWith('.sol'))
51
+ }
52
+
53
+ export function parseBundleBuild(value: unknown): BundleBuildInput {
54
+ const fail = (code = 'bad-request'): never => { throw new BundleBuildError(400, code) }
55
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) return fail()
56
+ const { repoId, commit, entries, conditions, branch } = value as Record<string, unknown>
57
+ if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0
58
+ || typeof commit !== 'string' || !/^[a-f\d]{40}$/u.test(commit)
59
+ || !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)
60
+ || (branch != null && !branchName(branch))) return fail()
61
+ const selected = [...new Set(entries as string[])]
62
+ const scripts = selected.every(isScript)
63
+ if (!scripts && !selected.every(entry => entry.endsWith('.sol'))) return fail('unsupported-entries')
64
+ const parts = posix.dirname(selected[0]!).split('/').filter(part => part !== '.')
65
+ for (const entry of selected) {
66
+ const parent = posix.dirname(entry).split('/')
67
+ while (parts.some((part, i) => parent[i] !== part)) parts.pop()
68
+ }
69
+ // Stasis builds Solidity with Soldeer alone. Named, a JS lockfile beside or
70
+ // above the project no longer leaves it unable to tell which one installs it.
71
+ const options: BundleBuildInput['options'] = scripts ? {} : { packageManager: 'soldeer' }
72
+ let recorded: BundleBuildConditions | null = null
73
+ if (scripts && conditions != null) {
74
+ if (typeof conditions !== 'object' || Array.isArray(conditions)) return fail('bad-conditions')
75
+ const { preset, conditions: names, platforms } = conditions as Record<string, unknown>
76
+ if (typeof preset !== 'string' || !['node', 'browser', 'metro'].includes(preset) || !Array.isArray(names) || names.length > 16
77
+ || !names.every(name => typeof name === 'string' && name.length > 0 && name.length <= 64
78
+ && !/^\.|^\d+$|[\s,/\\\p{Cc}]/u.test(name) && !['default', 'import', 'require'].includes(name))) return fail('bad-conditions')
79
+ if (preset === 'metro') {
80
+ if (names.length !== 1 || names[0] !== 'react-native') return fail('metro-conditions')
81
+ if (!Array.isArray(platforms) || platforms.length === 0 || platforms.length > 2
82
+ || !platforms.every(platform => ['ios', 'android'].includes(platform))) return fail('bad-conditions')
83
+ // React Native's convention puts JSX in .js files, which Stasis parses as
84
+ // JSX only on request. TypeScript is left to Stasis to detect.
85
+ Object.assign(options, { metro: true, platforms: [...new Set(platforms)], jsx: true })
86
+ } else {
87
+ options.conditions = [...new Set(names)]
88
+ if (preset === 'browser') options.mainFields = ['browser', 'module', 'main']
89
+ }
90
+ recorded = { preset: preset as BundleBuildConditions['preset'], conditions: [...new Set(names as string[])],
91
+ platforms: options.platforms ?? [] }
92
+ }
93
+ return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded, ...(branchName(branch) && { branch }) }
94
+ }
95
+
96
+ // A package name as a filename base: `@scope/name` as `scope-name`, or as
97
+ // `name` alone where it is `scope` or already starts with `scope-`. Null for
98
+ // a name npm could not publish by its length or leading dot.
99
+ function packageBase(name: string): string | null {
100
+ const match = name.length <= 214 ? /^(?:@([^/.][^/]*)\/)?([^/.][^/]*)$/u.exec(name) : null
101
+ if (!match) return null
102
+ const base = match[2]!, scope = match[1]
103
+ return scope === undefined || base === scope || base.startsWith(`${scope}-`) ? base : `${scope}-${base}`
104
+ }
105
+
106
+ // Same portable name and 255-character limit as Stasis's githubBundleFile
107
+ // (src/cmd/github-bundle.js), which is not a public package export, except
108
+ // that a usable `packageName` replaces both the repo and the directory; a
109
+ // .stasis.tgz's (`format` tgz) ends in `.stasis.tgz`, as Stasis's does.
110
+ export function githubBundleFilename(github: string, directory: string, commit: string, packageName: string | null = null, format: 'br' | 'tgz' = 'br'): string {
111
+ const portable = (value: string) => value.replaceAll(/[^\w.-]/gu, '_')
112
+ const tail = `.${portable(commit.slice(0, 7))}.${format === 'tgz' ? 'stasis.tgz' : 'stasis.code.br'}`
113
+ const named = packageName === null ? null : packageBase(packageName)
114
+ if (named !== null) return `${portable(named)}${tail}`
115
+ const repo = portable(github.replace('/', '-'))
116
+ if (!directory) return `${repo}${tail}`
117
+ const room = 255 - `${repo}.${tail}`.length
118
+ let dir = portable(directory.replaceAll('/', '-'))
119
+ if (dir.length > room) dir = `${dir.slice(0, room - 9)}_${createHash('sha256').update(directory).digest('hex').slice(0, 8)}`
120
+ return `${repo}.${dir}${tail}`
121
+ }
122
+
123
+ interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
124
+ interface BuildRequest {
125
+ input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
126
+ // Upstream's disk cache for what a build fetches (setCacheDir), or null for
127
+ // none, as on Vercel. Resolved here: the worker's env holds NPM_TOKEN and
128
+ // VERCEL_ENV alone.
129
+ cacheDir: string | null
130
+ }
131
+ // A version a Stasis lockfile holds, as the worker tells it in place of a
132
+ // bundle (bundle-build-worker.js buildStasisLockfile); and what it is asked
133
+ // to build one of, with the `branch` the commit is of, where its asker knows
134
+ // it, as a bundle's is (BundleBuildInput).
135
+ export interface StasisDependency { name: string; version: string; integrity?: string; patch?: string }
136
+ export interface LockfileInput { repoId: number; commit: string; config: string; branch?: string }
137
+ interface LockfileRequest { input: LockfileInput; github: string; token: string | null; cacheDir: string | null }
138
+ // An extra per-process ceiling, one build at a time, its worker given the heap
139
+ // buildHeapLimitMib sizes; admission must also hold the shared DB lease.
140
+ const active = new Set<string>()
141
+ const MAX_ACTIVE_BUILDS = 1
142
+ // The build running behind no request (buildRepositoryLockfile), which one
143
+ // asked for takes the slot and the lease of: told to yield
144
+ // (`build-yielded`), and gone once its lease is released.
145
+ let behind: { yield: () => void; gone: Promise<void> } | null = null
146
+ // Who builds behind no request, as `active` and the shared lease name it.
147
+ const LOCKFILE_BUILDER = 'dependency-review'
148
+ // Where builds keep what they download of npm for those after them in this
149
+ // instance, where no cache directory is set, as on Vercel
150
+ // (bundle-build-worker.js instanceCache).
151
+ const INSTANCE_DIR = join(tmpdir(), 'triage-stasis-cache')
152
+ async function yielded(): Promise<void> {
153
+ const running = behind
154
+ if (!running) return
155
+ running.yield()
156
+ await running.gone
157
+ }
158
+
159
+ // What a build's worker may take of the JS heap, in MiB: the memory the
160
+ // process may use, its container's limit else the machine's, less
161
+ // RESERVED_MIB, at least the 512 MiB a build always had. A large project's
162
+ // tree, as a React Native app's, laid out and scanned in memory, takes more
163
+ // than 2 GiB, as `stasis github-bundle` takes what Node's default heap gives
164
+ // it. What is reserved is the server's, and the worker's own beyond its heap:
165
+ // the bytes of the files it lays out, its bundle's JSON (512 MiB at most, the
166
+ // worker's MAX_SERIALIZED_BYTES) and that compressed. Past it, Node
167
+ // terminates the worker (build-memory), not the process.
168
+ const RESERVED_MIB = 512
169
+ const MIN_BUILD_HEAP_MIB = 512
170
+ const processMemory = () => Math.min(process.constrainedMemory() || Infinity, totalmem())
171
+ export function buildHeapLimitMib(memory = processMemory()): number {
172
+ return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
173
+ }
174
+
175
+ // `work` under one of the deployment's leases, `userId`'s one at a time. One
176
+ // asked for first has this instance's build behind no request yield, and
177
+ // waits for its lease to be released, lest that hold a lease against it.
178
+ export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
179
+ work: (signal: AbortSignal) => Promise<T>): Promise<T> {
180
+ signal.throwIfAborted()
181
+ const owner = randomUUID(), started = performance.now(), timeout = new AbortController()
182
+ const expired = () => timeout.abort(new BundleBuildError(504, 'build-timeout'))
183
+ const timer = setTimeout(expired, BUNDLE_BUILD_TIMEOUT_MS)
184
+ const combined = AbortSignal.any([signal, timeout.signal])
185
+ let claimed = false
186
+ try {
187
+ if (userId !== LOCKFILE_BUILDER && behind) await yielded()
188
+ claimed = await db.claimBundleBuildLease(userId, owner)
189
+ if (!claimed) throw new BundleBuildError(429, 'build-busy')
190
+ // Account for a slow/lost claim response or a suspended invocation before
191
+ // starting work. The three-minute budget starts before lease acquisition.
192
+ if (performance.now() - started >= BUNDLE_BUILD_TIMEOUT_MS) expired()
193
+ combined.throwIfAborted()
194
+ return await work(combined)
195
+ } catch (error) {
196
+ if (timeout.signal.aborted && !signal.aborted) throw timeout.signal.reason
197
+ throw error
198
+ } finally {
199
+ clearTimeout(timer)
200
+ // buildRepositoryBundle waits for worker termination before settling.
201
+ // Unknown claim/release outcomes expire safely without starting more work.
202
+ if (claimed) await db.releaseBundleBuildLease(owner)
203
+ }
204
+ }
205
+
206
+ // Parsing repositories and compressing bundles stays off the HTTP event loop.
207
+ // Cap concurrent builds, terminate disconnected/timed-out work, and share no
208
+ // credentials or mutable Stasis state between requests.
209
+ export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
210
+ const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
211
+ const asked = { ...request, instanceDir: INSTANCE_DIR }
212
+ return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, asked, context, signal, message => {
213
+ // A view of the bytes the worker handed over, not a copy of them.
214
+ const { bytes } = message
215
+ return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
216
+ })
217
+ }
218
+
219
+ // A Stasis lockfile's dependencies in place of a bundle, for a repository's
220
+ // dependency review (stasis-dependencies.ts), built behind no request, under
221
+ // the deployment's lease as its one builder of them: in the same one slot,
222
+ // which it gives up to a build asked for, with its lease (`build-yielded`),
223
+ // and is refused while another holds (`build-busy`), to be built later.
224
+ export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisDependency[]> {
225
+ if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
226
+ const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
227
+ const asked = { ...request, instanceDir: INSTANCE_DIR, lockfileOnly: true }
228
+ const yielding = new AbortController()
229
+ let gone = () => {}
230
+ behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
231
+ try {
232
+ return await withBundleBuildLease(db, LOCKFILE_BUILDER, AbortSignal.any([signal, yielding.signal]), leased => runBuild<{ dependencies: StasisDependency[] }, StasisDependency[]>(
233
+ LOCKFILE_BUILDER, asked, context, leased, ({ dependencies }) => ({ value: dependencies, logged: { dependencies: dependencies.length } }), true))
234
+ } finally {
235
+ behind = null
236
+ gone()
237
+ }
238
+ }
239
+
240
+ // What a build's worker told last, by its type: its progress, memory or a
241
+ // note, its failure, else what it built.
242
+ type WorkerMessage<M> = M & { type?: string; stage?: BundleBuildStage; error?: string; status?: number; diagnostic?: BundleBuildDiagnostic
243
+ memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }
244
+
245
+ // `request` built in a worker of its own, `owner`'s one build at a time, what
246
+ // it built told by `built` of its last message, with what its log keeps of
247
+ // it; `background`, behind no request.
248
+ async function runBuild<M, T>(owner: string, request: { token: string | null }, about: Record<string, unknown>, signal: AbortSignal,
249
+ built: (message: M) => { value: T; logged: Record<string, unknown> }, background = false): Promise<T> {
250
+ const { token } = request
251
+ // One asked for takes the slot of one running behind no request, where its lease didn't already.
252
+ if (!background && behind) await yielded()
253
+ if (active.has(owner) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
254
+ signal.throwIfAborted()
255
+ active.add(owner)
256
+ let worker: Worker | undefined
257
+ let workerUrl: URL | undefined
258
+ let stage: BundleBuildStage = 'worker-start'
259
+ const buildId = randomUUID(), started = performance.now()
260
+ const heapLimitMib = buildHeapLimitMib()
261
+ // How this Node was built, as it decides what a heap holds the same objects in.
262
+ const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
263
+ const context = { buildId, ...about, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
264
+ memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
265
+ const log = (event: string, details: Record<string, unknown> = {}) => {
266
+ const write = event === 'failed' ? console.error : console.info
267
+ write('managed-bundle-build:', JSON.stringify({ ...context, workerUrl: workerUrl?.href, event, stage, elapsedMs: Math.round(performance.now() - started), ...details }))
268
+ }
269
+ try {
270
+ workerUrl = new URL('./bundle-build-worker.js', import.meta.url)
271
+ log('started')
272
+ // Upstream reads NPM_TOKEN from the env for scoped packages, which npm
273
+ // answers with 404 when private and asked without it. Stasis reads
274
+ // VERCEL_ENV, set or not as here, to parse without oxc-parser's raw
275
+ // transfer on Vercel, whose functions can't reserve its 6 GiB buffer.
276
+ // Nothing else passes.
277
+ const npmToken = process.env['NPM_TOKEN'], vercelEnv = process.env['VERCEL_ENV']
278
+ const env = { ...(npmToken ? { NPM_TOKEN: npmToken } : {}), ...(vercelEnv === undefined ? {} : { VERCEL_ENV: vercelEnv }) }
279
+ worker = new Worker(workerUrl, {
280
+ workerData: { ...request, type: 'managed-bundle-build' }, env, execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
281
+ })
282
+ const running = worker
283
+ return await new Promise((resolve, reject) => {
284
+ let settled = false
285
+ const cleanup = () => { clearTimeout(timer); signal.removeEventListener('abort', abort) }
286
+ const fail = (status: number, code: string, details: Record<string, unknown> = {}) => {
287
+ if (settled) return
288
+ settled = true
289
+ cleanup()
290
+ log(code === 'build-cancelled' || code === 'build-yielded' ? 'cancelled' : 'failed', { code, ...details })
291
+ reject(new BundleBuildError(status, code))
292
+ }
293
+ const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
294
+ const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
295
+ signal.addEventListener('abort', abort, { once: true })
296
+ // The worker's memory and notes are the log's alone: the response tells
297
+ // what it built, or the error's code, and nothing of them.
298
+ running.on('message', (message: WorkerMessage<M>) => {
299
+ if (settled) return
300
+ if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
301
+ if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
302
+ if (message.type === 'note' && typeof message.event === 'string') { log(message.event, message.details ?? {}); return }
303
+ if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
304
+ settled = true
305
+ cleanup()
306
+ const { value, logged } = built(message)
307
+ log('completed', logged)
308
+ resolve(value)
309
+ })
310
+ // Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
311
+ running.once('error', error => {
312
+ const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
313
+ fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, token) })
314
+ })
315
+ running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
316
+ if (signal.aborted) abort()
317
+ })
318
+ } catch (error) {
319
+ if (!(error instanceof BundleBuildError)) {
320
+ log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, token) })
321
+ }
322
+ throw error
323
+ } finally {
324
+ try { await worker?.terminate() } finally { active.delete(owner) }
325
+ }
326
+ }
@@ -0,0 +1,261 @@
1
+ // Metadata is cached as Brotli. Contents use the stored Brotli bytes directly:
2
+ // unchanged Stasis uploads or sourcemaps compressed once at upload. A
3
+ // .stasis.tgz's are its bundle's JSON, made from it once and cached as Brotli.
4
+ import { Buffer } from 'node:buffer'
5
+ import { brotliDecompress } from 'node:zlib'
6
+ import { promisify } from 'node:util'
7
+ import { bundleEdges } from '@preventive/sourcemap/edges.js'
8
+ import { BUNDLE_METADATA_VERSION, type BundleDetails, createBundleMetadata, createBundleSummary, parseBundleContents, parseBundleMetadata } from '../common/bundle-metadata.js'
9
+ import { bundleReasons, bundleScopes, scopeLabel } from '../common/bundle-reasons.js'
10
+ import { sourcemapEdges } from '../common/bundle-sourcemap.js'
11
+ import { type BundleAdvisoryInventory, bundleAdvisoryInventory } from './bundle-advisory-inventory.ts'
12
+ import { decodeUtf8 } from '../common/utf8.js'
13
+ import { isStasisTgzName } from '../common/stasis-files.js'
14
+ import { readStasisTgz } from '../common/stasis-tgz.js'
15
+ import { type OpenedBlob, readBytes } from './blob-store.ts'
16
+ import type { BundleStore } from './bundle-store.ts'
17
+ import { encodeBrotli } from './brotli.ts'
18
+ import type { ManagedBundle, ManagedDb } from './db.ts'
19
+ import { CacheMissError } from './cache-storage.ts'
20
+ import { SUMMARY_FILENAME, createBundleSummaryCache, readCachedBytes } from './bundle-summary-cache.ts'
21
+
22
+ const decompress = promisify(brotliDecompress)
23
+ const MAX_DECODED_BYTES = 512 * 1024 * 1024
24
+ export const MAX_PACKAGE_INVENTORY_BYTES = 1024 * 1024
25
+ export type BundleCachePart = 'metadata' | 'contents'
26
+ export type BundleCacheRecord = Pick<ManagedBundle, 'id' | 'integrity' | 'filename' | 'kind' | 'byteSize'>
27
+ export interface BundleSummary { files: number; codeFiles: number; lines: number; commit?: string; stasisVersion?: number; versionedPackages?: number }
28
+
29
+ export async function readBundleDetails(record: BundleCacheRecord, store: BundleStore) {
30
+ return (await readSizedBundleDetails(record, store))?.details ?? null
31
+ }
32
+
33
+ // As readBundleDetails, with the bytes the bundle decoded to: about what
34
+ // holding its details takes. A Stasis bundle's name tells a .stasis.tgz's.
35
+ export async function readSizedBundleDetails(record: BundleCacheRecord, store: BundleStore) {
36
+ const bytes = await store.get(record.id, record.kind)
37
+ if (!bytes) return null
38
+ if (record.kind === 'stasis' && isStasisTgzName(record.filename)) {
39
+ const { bundle, size } = await readStasisTgz(bytes, { limit: MAX_DECODED_BYTES })
40
+ return { details: { integrity: record.integrity, kind: record.kind, size: record.byteSize, bundle } as BundleDetails, decodedBytes: size, tgz: true }
41
+ }
42
+ const decoded = record.kind === 'stasis' || record.kind === 'sourcemap' ? await decompress(bytes, { maxOutputLength: MAX_DECODED_BYTES }) : bytes
43
+ if (decoded.length > MAX_DECODED_BYTES) throw new Error('Decoded bundle too large')
44
+ return { details: parseBundleContents(decodeUtf8(decoded), { integrity: record.integrity, kind: record.kind, size: record.byteSize }), decodedBytes: decoded.length, tgz: false }
45
+ }
46
+
47
+ export interface BundleCacheStorage {
48
+ exists(id: string, file: string): Promise<boolean>
49
+ put(id: string, file: string, bytes: Buffer): Promise<void>
50
+ open(id: string, file: string): Promise<OpenedBlob>
51
+ // Remove all cached versions for this bundle, including legacy derivatives.
52
+ delete(id: string): Promise<void>
53
+ }
54
+
55
+ const filename = `v${BUNDLE_METADATA_VERSION}-metadata.json.br`
56
+ // A .stasis.tgz's bundle as a stasis.code.br holds it: its JSON, as Brotli.
57
+ const contentsFilename = 'v1-contents.json.br'
58
+ const packagesFilename = 'v8-advisory-inventory.json'
59
+
60
+ // An entry point's inventory is rows of the bundle's own, a package's versions
61
+ // in order and then the skipped: kept as a 0 or 1 for each, since spelled out,
62
+ // as a reason's is, many entry points' would not fit the budget.
63
+ const rowKeys = ({ packages, skipped }: BundleAdvisoryInventory) => [
64
+ ...packages.flatMap(pkg => pkg.versions.map(version => JSON.stringify([pkg.ecosystem, pkg.ecosystem === 'github' ? pkg.name.toLowerCase() : pkg.name, version]))),
65
+ ...skipped.map(pkg => JSON.stringify([pkg.ecosystem, pkg.name, pkg.version, 'skipped']))]
66
+ function keptRows(all: BundleAdvisoryInventory, rows: string): BundleAdvisoryInventory {
67
+ let row = 0
68
+ const kept = () => rows[row++] === '1'
69
+ return { packages: all.packages.map(pkg => ({ ...pkg, versions: pkg.versions.filter(kept) })).filter(pkg => pkg.versions.length > 0), skipped: all.skipped.filter(kept) }
70
+ }
71
+
72
+ // All scopes share one bounded derivative. Never decode full bundle metadata
73
+ // on advisory requests, including when selecting a reason. Persist null when
74
+ // the combined inventory exceeds the budget, without disabling metadata.
75
+ function encodePackageInventory(details: BundleDetails): Buffer {
76
+ const parts: string[] = []
77
+ let size = 0
78
+ function append(part: string) {
79
+ size += Buffer.byteLength(part)
80
+ if (size > MAX_PACKAGE_INVENTORY_BYTES) return false
81
+ parts.push(part)
82
+ return true
83
+ }
84
+ // `items` as `write` writes each, a comma apart, between `open` and
85
+ // `close`: false once past the budget, as `append` is.
86
+ function list<T>(open: string, items: Iterable<T>, write: (item: T) => boolean, close: string) {
87
+ if (!append(open)) return false
88
+ let first = true
89
+ for (const item of items) {
90
+ if (!append(first ? '' : ',') || !write(item)) return false
91
+ first = false
92
+ }
93
+ return append(close)
94
+ }
95
+ const rows = (items: unknown[]) => list('[', items, row => append(JSON.stringify(row)), ']')
96
+ function inventory(paths: Set<string> | null) {
97
+ const { packages, skipped } = bundleAdvisoryInventory(details, paths)
98
+ return append('{"packages":') && rows(packages) && append(',"skipped":') && rows(skipped) && append('}')
99
+ }
100
+ const whole = append('{"all":') && inventory(null)
101
+ && list(',"reasons":{', bundleReasons(details), ([reason, paths]) => append(`${JSON.stringify(reason)}:`) && inventory(paths), '}')
102
+ if (!whole) return Buffer.from('null')
103
+ // Entry points last: where they don't fit, they alone are left out.
104
+ const all = rowKeys(bundleAdvisoryInventory(details)), fit = parts.length, fitSize = size, scopes = bundleScopes(details)
105
+ const entries = list(',"entries":{', scopes.ids.filter(id => id.startsWith('entry:')), id => {
106
+ const kept = new Set(rowKeys(bundleAdvisoryInventory(details, scopes.files(id))))
107
+ return append(`${JSON.stringify(scopeLabel(id))}:"${all.map(key => kept.has(key) ? 1 : 0).join('')}"`)
108
+ }, '}')
109
+ if (!entries) { parts.length = fit; size = fitSize }
110
+ return Buffer.from(append('}') ? parts.join('') : 'null')
111
+ }
112
+
113
+ // What a catalog sends of a bundle before it opens. A Stasis bundle's
114
+ // `versionedPackages` counts the name@version pairs its unscoped advisory
115
+ // audit covers, audited or skipped: with none, Advisories has nothing to show.
116
+ export function bundleSummary(details: BundleDetails, metadata?: Parameters<typeof createBundleSummary>[1]): BundleSummary {
117
+ const summary = createBundleSummary(details, metadata)
118
+ if (details.kind !== 'stasis') return summary
119
+ const { packages, skipped } = bundleAdvisoryInventory(details)
120
+ return { ...summary, versionedPackages: packages.reduce((count, pkg) => count + pkg.versions.length, 0) + skipped.length }
121
+ }
122
+
123
+ // A sourcemap's edges, read with the parser (edges.js) that the client goes
124
+ // without: every map's, where the client reads Metro's alone. Without it,
125
+ // the metadata keeps what the client would read. A map with no
126
+ // sourcesContent has no source to read them from.
127
+ function readSourcemapEdges(details: BundleDetails) {
128
+ if (details.kind !== 'sourcemap' || !details.map?.files.some(file => file.content !== null)) return
129
+ try { details.edges = sourcemapEdges(details.map, bundleEdges) }
130
+ catch (err) { console.warn('managed: sourcemap edges failed:', err) }
131
+ }
132
+
133
+ // As readBundleDetails, thrown where the bundle's bytes are gone.
134
+ async function storedDetails(record: BundleCacheRecord, store: BundleStore) {
135
+ const read = await readSizedBundleDetails(record, store)
136
+ if (!read) throw new Error('Bundle bytes unavailable')
137
+ return read
138
+ }
139
+
140
+ // A .stasis.tgz's contents (contentsFilename), of its bundle as read.
141
+ const encodeContents = (details: BundleDetails) => encodeBrotli((details.bundle as { serializedBytes(): Uint8Array }).serializedBytes())
142
+
143
+ // What a build wrote is removed where another instance deleted the row
144
+ // meanwhile, so its cleanup cannot be undone by us.
145
+ async function reconcile(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb) {
146
+ if (await db.getBundle(record.id)) return
147
+ await storage.delete(record.id)
148
+ throw new Error('Bundle deleted')
149
+ }
150
+
151
+ async function build(record: BundleCacheRecord, storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
152
+ const { details, tgz } = await storedDetails(record, store)
153
+ readSourcemapEdges(details)
154
+ const metadata = { ...await createBundleMetadata(details), id: record.id, filename: record.filename }
155
+ const body = await encodeBrotli(Buffer.from(JSON.stringify(metadata)))
156
+ if (!(await db.getBundle(record.id))) throw new Error('Bundle deleted')
157
+ const summary = bundleSummary(details, metadata)
158
+ // Written together, each settled before the row is looked at again: one
159
+ // failing leaves the others, which a later open builds over.
160
+ const written = await Promise.allSettled([
161
+ storage.put(record.id, filename, body),
162
+ ...record.kind === 'stasis' ? [storage.put(record.id, packagesFilename, encodePackageInventory(details))] : [],
163
+ ...tgz ? [encodeContents(details).then(contents => storage.put(record.id, contentsFilename, contents))] : [],
164
+ storage.put(record.id, SUMMARY_FILENAME, Buffer.from(JSON.stringify(summary))),
165
+ ])
166
+ // A different instance may have deleted the row while these writes ran.
167
+ // Reconcile after publishing so its cleanup cannot be undone by us.
168
+ await reconcile(record, storage, db)
169
+ const failed = written.find(result => result.status === 'rejected')
170
+ if (failed) throw failed.reason
171
+ return summary
172
+ }
173
+
174
+ export function createBundleCache(storage: BundleCacheStorage, db: ManagedDb, store: BundleStore) {
175
+ const pending = new Map<string, Promise<void>>()
176
+ // The database deduplicates by integrity, so each hash has one persistent
177
+ // bundle/cache directory, shared across teams and repeated uploads.
178
+ const summaries = createBundleSummaryCache(storage, async record => bundleSummary((await storedDetails(record, store)).details), id => db.getBundle(id))
179
+ let queue = Promise.resolve()
180
+ async function ensure(record: BundleCacheRecord): Promise<void> {
181
+ const existing = pending.get(record.id)
182
+ if (existing) return existing
183
+ const job = (async () => {
184
+ if (await storage.exists(record.id, filename) && (record.kind !== 'stasis' || await storage.exists(record.id, packagesFilename))) return
185
+ const work = queue.then(async () => summaries.remember(record, await build(record, storage, db, store)))
186
+ queue = work.catch(() => {})
187
+ await work
188
+ })()
189
+ pending.set(record.id, job)
190
+ try { await job } finally { if (pending.get(record.id) === job) pending.delete(record.id) }
191
+ }
192
+ // A .stasis.tgz's contents as cached, else made from it, as a build of
193
+ // the rest makes them beside its metadata, each made once at a time.
194
+ async function openContents(record: BundleCacheRecord) {
195
+ try { return await storage.open(record.id, contentsFilename) }
196
+ catch (error) { if (!(error instanceof CacheMissError)) throw error }
197
+ const key = `${record.id}\0contents`
198
+ let job = pending.get(key)
199
+ if (!job) {
200
+ job = (async () => {
201
+ const body = await encodeContents((await storedDetails(record, store)).details)
202
+ if (!(await db.getBundle(record.id))) throw new Error('Bundle deleted')
203
+ await storage.put(record.id, contentsFilename, body)
204
+ await reconcile(record, storage, db)
205
+ })()
206
+ pending.set(key, job)
207
+ job.finally(() => { if (pending.get(key) === job) pending.delete(key) }).catch(() => {})
208
+ }
209
+ await job
210
+ return storage.open(record.id, contentsFilename)
211
+ }
212
+ async function openCached(record: BundleCacheRecord, file: string) {
213
+ try { return await storage.open(record.id, file) }
214
+ catch (error) { if (!(error instanceof CacheMissError)) throw error }
215
+ await ensure(record)
216
+ return storage.open(record.id, file)
217
+ }
218
+ return {
219
+ prebuild: ensure,
220
+ summary: summaries.summary,
221
+ summaryStatus: summaries.summaryStatus,
222
+ backfillSummaries: summaries.backfill,
223
+ async open(record: ManagedBundle, part: BundleCachePart) {
224
+ if (part === 'contents') {
225
+ if (record.kind !== 'stasis' && record.kind !== 'sourcemap') throw new Error('Unsupported bundle')
226
+ // A .stasis.tgz's: its bundle's JSON in its place.
227
+ if (record.kind === 'stasis' && isStasisTgzName(record.filename)) return openContents(record)
228
+ const stored = await store.open(record.id, record.kind)
229
+ if (!stored) throw new Error('Bundle bytes unavailable')
230
+ return stored
231
+ }
232
+ return openCached(record, filename)
233
+ },
234
+ // A sourcemap's edges as its metadata keeps them, read with the parser
235
+ // once, for a derivative that reads the bundle itself (report previews).
236
+ async sourcemapEdges(record: ManagedBundle): Promise<BundleDetails['edges']> {
237
+ const decoded = await decompress(await readBytes(await openCached(record, filename)), { maxOutputLength: MAX_DECODED_BYTES })
238
+ return parseBundleMetadata(JSON.parse(decodeUtf8(decoded)), record.integrity).edges
239
+ },
240
+ // The whole bundle's, one `reason`'s, or one `entry` point's instead: undefined for one it has none of.
241
+ async advisoryInventory(record: ManagedBundle, reason = '', entry = ''): Promise<BundleAdvisoryInventory | null | undefined> {
242
+ if (record.kind !== 'stasis') return { packages: [], skipped: [] }
243
+ const cached = await openCached(record, packagesFilename)
244
+ if (cached.size != null && cached.size > MAX_PACKAGE_INVENTORY_BYTES) { cached.stream.destroy(); return null }
245
+ const bytes = await readCachedBytes(cached, MAX_PACKAGE_INVENTORY_BYTES)
246
+ if (!bytes) return null
247
+ const inventory = JSON.parse(decodeUtf8(bytes))
248
+ if (inventory === null || (entry && !inventory.entries)) return null
249
+ if (entry) return Object.hasOwn(inventory.entries, entry) ? keptRows(inventory.all, inventory.entries[entry]) : undefined
250
+ return reason ? (Object.hasOwn(inventory.reasons, reason) ? inventory.reasons[reason] : undefined) : inventory.all
251
+ },
252
+ async delete(id: string) {
253
+ // Call after deleting the row. Waiting prevents an in-flight builder
254
+ // from recreating its files after deletion has completed.
255
+ await Promise.all([id, `${id}\0contents`].map(key => pending.get(key)?.catch(() => {})))
256
+ await summaries.forget(id)
257
+ await storage.delete(id)
258
+ },
259
+ }
260
+ }
261
+ export type BundleCache = ReturnType<typeof createBundleCache>
@@ -0,0 +1,29 @@
1
+ import type { BundleCache, BundleSummary } from './bundle-cache.ts'
2
+ import type { AdminBundle, UserTeamBundle } from './db.ts'
3
+ import { eachOf } from './queue.ts'
4
+
5
+ const SUMMARY_READ_CONCURRENCY = 8
6
+ type ListedBundle = AdminBundle | UserTeamBundle
7
+
8
+ // The bundles, one of each content hash.
9
+ const byIntegrity = (bundles: readonly ListedBundle[]) => [...new Map(bundles.map(bundle => [bundle.integrity, bundle])).values()]
10
+
11
+ // Read only existing summaries: cold/malformed bundles must never trigger
12
+ // parsing or wait for metadata builds before the catalog response is sent.
13
+ export async function bundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
14
+ const summaries = new Map<string, { summary: BundleSummary | null; summaryRetryAt: number | null }>()
15
+ if (cache) {
16
+ // Cold reads may each access remote storage. Bound those requests as well
17
+ // as the subsequent backfill, without dropping entries from large catalogs.
18
+ await eachOf(byIntegrity(bundles), SUMMARY_READ_CONCURRENCY, async bundle => {
19
+ summaries.set(bundle.integrity, await cache.summaryStatus(bundle).catch(() => ({ summary: null, summaryRetryAt: null })))
20
+ })
21
+ }
22
+ return summaries
23
+ }
24
+
25
+ // Called after sending the response. Each cache permits one small batch at a
26
+ // time, deduplicated by content hash, and skips persisted retry-backoff markers.
27
+ export async function backfillBundleSummaries(bundles: readonly ListedBundle[], cache?: BundleCache) {
28
+ await cache?.backfillSummaries(byIntegrity(bundles))
29
+ }