@preventive/triage 1.0.0-alpha.9 → 1.0.0-alpha.90
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.
- package/LICENSE-APACHE +202 -0
- package/README.md +16 -0
- package/api/reap.ts +16 -78
- package/cli.js +6 -0
- package/client/dependency-paths.d.ts +3 -0
- package/client/dependency-paths.js +36 -0
- package/client/finding-link.js +305 -0
- package/client/linked-findings.d.ts +1 -0
- package/client/linked-findings.js +115 -0
- package/common/bundle-commit.d.ts +1 -0
- package/common/bundle-commit.js +4 -0
- package/common/bundle-compare-diff.d.ts +6 -0
- package/common/bundle-compare-diff.js +378 -0
- package/common/bundle-compare-inputs.d.ts +3 -0
- package/common/bundle-compare-inputs.js +141 -0
- package/common/bundle-compare-versions.js +172 -0
- package/common/bundle-comparison.d.ts +8 -0
- package/common/bundle-comparison.js +69 -0
- package/common/bundle-imports.js +20 -0
- package/common/bundle-metadata.d.ts +15 -0
- package/common/bundle-metadata.js +226 -0
- package/common/bundle-pkg-of.d.ts +1 -0
- package/common/bundle-pkg-of.js +90 -0
- package/common/bundle-reasons.d.ts +6 -0
- package/common/bundle-reasons.js +58 -0
- package/common/bundle-source-links.d.ts +6 -0
- package/common/bundle-source-links.js +216 -0
- package/common/bundle-sourcemap.d.ts +10 -0
- package/common/bundle-sourcemap.js +100 -0
- package/common/bundle-sources.d.ts +10 -0
- package/common/bundle-sources.js +374 -0
- package/common/bundle-stats.js +41 -0
- package/common/bundle-tabs.js +1 -0
- package/common/code-language.js +80 -0
- package/common/default-scan-models.ts +37 -0
- package/common/dependency-reviews.d.ts +19 -0
- package/common/dependency-reviews.js +67 -0
- package/common/finding-duplicates.js +63 -0
- package/common/finding-filters.js +313 -0
- package/common/finding-id.js +47 -0
- package/common/finding-repo.d.ts +5 -0
- package/common/finding-repo.js +67 -0
- package/common/github-issue-labels.d.ts +3 -0
- package/common/github-issue-labels.js +42 -0
- package/common/github-pr.ts +56 -0
- package/common/gzip.js +59 -0
- package/common/line-diff.d.ts +15 -0
- package/common/line-diff.js +188 -0
- package/common/linked-workspace-groups.js +63 -0
- package/common/managed/agent-tasks.ts +292 -0
- package/common/managed/comments.ts +43 -0
- package/common/managed/dependency-routes.js +25 -0
- package/common/managed/directory-packages.ts +28 -0
- package/common/managed/finding-detail.d.ts +5 -0
- package/common/managed/finding-detail.js +75 -0
- package/common/managed/finding-values.d.ts +2 -0
- package/common/managed/finding-values.js +138 -0
- package/common/managed/github-agents.ts +114 -0
- package/common/managed/github-logins.ts +49 -0
- package/common/managed/lite-name.d.ts +2 -0
- package/common/managed/lite-name.js +20 -0
- package/common/managed/npm-packages.d.ts +9 -0
- package/common/managed/npm-packages.js +63 -0
- package/common/managed/permissions.ts +31 -0
- package/common/managed/report-content.ts +72 -0
- package/common/managed/report-filter.ts +120 -0
- package/common/managed/repository-alias.ts +65 -0
- package/common/managed/review-view-routes.js +23 -0
- package/common/managed/risk-routes.js +30 -0
- package/common/managed/roles.ts +48 -0
- package/common/managed/routes.d.ts +2 -0
- package/common/managed/routes.js +386 -0
- package/common/managed/scan-models.ts +6 -0
- package/common/managed/stasis-config.ts +7 -0
- package/common/managed/team-app.d.ts +19 -0
- package/common/managed/team-app.js +129 -0
- package/common/managed/team-filters.js +26 -0
- package/common/managed/triage.ts +83 -0
- package/common/managed/upload-seal.ts +126 -0
- package/common/npm-token.d.ts +2 -0
- package/common/npm-token.js +14 -0
- package/common/pretty-json.js +123 -0
- package/common/pretty-kinds.js +20 -0
- package/common/pretty-print.d.ts +7 -0
- package/common/pretty-print.js +41 -0
- package/common/pretty-sourcemap.js +70 -0
- package/common/repo-commit.d.ts +4 -0
- package/common/repo-commit.js +30 -0
- package/common/revalidation-conflicts.js +48 -0
- package/common/revalidation-input-groups.js +56 -0
- package/common/scan-server.ts +13 -0
- package/common/security-links.d.ts +5 -0
- package/common/security-links.js +33 -0
- package/common/server-info.ts +46 -0
- package/common/sourcemap-listing.js +78 -0
- package/common/sourcemap-mappings.js +136 -0
- package/common/sourcemap-unlist.js +85 -0
- package/common/stasis-files.d.ts +5 -0
- package/common/stasis-files.js +20 -0
- package/common/stasis-tgz.d.ts +6 -0
- package/common/stasis-tgz.js +27 -0
- package/common/utf8.d.ts +3 -0
- package/common/utf8.js +45 -0
- package/common/whitespace-insensitive.js +19 -0
- package/common/workspace-app.js +91 -0
- package/common/workspace-groups.js +176 -0
- package/out/activity.js +2 -0
- package/out/brotli-fallback.js +3 -3
- package/out/chunk-2XUEZHIP.js +28 -0
- package/out/chunk-3DOSBILK.js +4 -0
- package/out/chunk-55YIWY3H.js +5 -0
- package/out/chunk-5AVGKFMR.js +1 -0
- package/out/chunk-5PWEAEA5.js +1 -0
- package/out/chunk-6VOB5WXX.js +2 -0
- package/out/chunk-6Y6PZ2BU.js +9 -0
- package/out/chunk-74JZTGTO.js +11 -0
- package/out/chunk-7BKKYVWR.js +7 -0
- package/out/chunk-7C7DWL7I.js +1 -0
- package/out/chunk-7HP2VYIC.js +2 -0
- package/out/chunk-7YFJUT2P.js +1 -0
- package/out/chunk-A4BBBHQU.js +1 -0
- package/out/chunk-B64CTMVU.js +4 -0
- package/out/chunk-BEKYZCPX.js +14 -0
- package/out/chunk-BZJU5EEV.js +1 -0
- package/out/chunk-C4Z6ZBXV.js +10 -0
- package/out/chunk-CJVMNJDZ.js +3 -0
- package/out/chunk-CU3FPB3P.js +1 -0
- package/out/chunk-DEVAORP2.js +1 -0
- package/out/chunk-DUASGS2O.js +8 -0
- package/out/chunk-EEJA7JBI.js +13 -0
- package/out/chunk-ESXA7KID.js +1 -0
- package/out/chunk-FSU2PLJL.js +1 -0
- package/out/chunk-GO7FT4OD.js +1 -0
- package/out/chunk-GX5UXWT4.js +1 -0
- package/out/chunk-HGWFRZNC.js +267 -0
- package/out/chunk-IYPY47MC.js +1 -0
- package/out/chunk-JZAROLQT.js +40 -0
- package/out/chunk-K4XJHM2T.js +1 -0
- package/out/chunk-KP2XM324.js +6 -0
- package/out/chunk-LRWB6QVO.js +1 -0
- package/out/chunk-LVSLM7HB.js +1 -0
- package/out/chunk-LVW7WWV4.js +1 -0
- package/out/chunk-N57OWFKY.js +15 -0
- package/out/chunk-NRPC74AM.js +1 -0
- package/out/chunk-OOJM4CTU.js +1 -0
- package/out/chunk-PKLVXUEI.js +11 -0
- package/out/chunk-PLGH63UC.js +2 -0
- package/out/chunk-PNHBZGDD.js +1 -0
- package/out/chunk-PWFUOLZK.js +17 -0
- package/out/chunk-PXK7EU4V.js +1 -0
- package/out/chunk-QD3IBSF4.js +7 -0
- package/out/chunk-QI66YA4F.js +1 -0
- package/out/chunk-QRKFPLA4.js +80 -0
- package/out/chunk-R3NZFXVR.js +1 -0
- package/out/chunk-R5O6FAW4.js +2 -0
- package/out/chunk-RAM3GDAD.js +1 -0
- package/out/chunk-RPNO56H2.js +1 -0
- package/out/chunk-SMNFBOLO.js +10 -0
- package/out/chunk-SSPDMA6D.js +1 -0
- package/out/chunk-SZTCJVZJ.js +55 -0
- package/out/chunk-SZWPYLPC.js +1 -0
- package/out/chunk-TKPNRQNN.js +3 -0
- package/out/chunk-TUII34K2.js +1 -0
- package/out/chunk-UJP4PQJA.js +1 -0
- package/out/chunk-UJSJMXEG.js +1 -0
- package/out/chunk-UR4WYMIP.js +1 -0
- package/out/chunk-UTYWTUTC.js +1 -0
- package/out/chunk-VHEXSGGP.js +1 -0
- package/out/chunk-VYYUMYVW.js +9 -0
- package/out/chunk-WBK5ZN4K.js +3 -0
- package/out/chunk-WCDYSIKG.js +1 -0
- package/out/chunk-XM4RLC4A.js +2 -0
- package/out/chunk-XRAAYXPR.js +1 -0
- package/out/chunk-ZQHLECTI.js +1 -0
- package/out/client-managed-import.js +4 -0
- package/out/client-managed.js +35 -0
- package/out/client-sync.js +11 -17
- package/out/compare.js +26 -0
- package/out/dialogs.js +40 -0
- package/out/github-issue-authorized.html +3 -0
- package/out/github-issue-authorized.js +1 -0
- package/out/graph.js +19 -5
- package/out/index.html +105 -25
- package/out/prism.js +14 -10
- package/out/scan.js +2 -0
- package/out/stasis.svg +20 -0
- package/out/terminal.js +367 -39
- package/out/view.css +1 -1
- package/out/view.js +19 -148
- package/package.json +416 -64
- package/risk/actions/findings.js +161 -0
- package/risk/actions/resolve.js +287 -0
- package/risk/actions/scripts/commands.js +182 -0
- package/risk/actions/scripts/grade.js +113 -0
- package/risk/actions/scripts/packages.js +123 -0
- package/risk/actions/scripts/shell.js +169 -0
- package/risk/actions/uses.js +94 -0
- package/risk/actions/workflow.js +183 -0
- package/risk/files/characters.js +354 -0
- package/risk/files/hosts.js +206 -0
- package/risk/files/readability.js +185 -0
- package/risk/files/runs-code.js +568 -0
- package/risk/files/script.js +420 -0
- package/risk/files/source-map-link.js +43 -0
- package/risk/files/stamps.js +47 -0
- package/risk/index.d.ts +309 -0
- package/risk/index.js +12 -0
- package/risk/npm/assess.js +303 -0
- package/risk/npm/combined.js +68 -0
- package/risk/npm/compare.js +236 -0
- package/risk/npm/dependencies.js +172 -0
- package/risk/npm/diff.js +79 -0
- package/risk/npm/downloads.js +84 -0
- package/risk/npm/files.js +445 -0
- package/risk/npm/held.js +67 -0
- package/risk/npm/install-scripts.js +34 -0
- package/risk/npm/malware.js +38 -0
- package/risk/npm/manifest.js +65 -0
- package/risk/npm/new-dependency.js +60 -0
- package/risk/npm/old-version.js +108 -0
- package/risk/npm/registry.js +401 -0
- package/risk/npm/release.js +85 -0
- package/risk/npm/score.js +59 -0
- package/risk/npm/specs.js +124 -0
- package/risk/npm/tarball.js +169 -0
- package/server-common/database-config.ts +16 -0
- package/server-common/initialize.ts +18 -0
- package/server-common/npm-advisories.ts +101 -0
- package/{server → server-common}/origin.ts +5 -5
- package/server-common/reap.ts +48 -0
- package/server-common/scan-config.ts +19 -0
- package/server-common/standalone.ts +29 -0
- package/server-common/storage-crypto.ts +182 -0
- package/server-common/storage-log.ts +38 -0
- package/server-common/vercel-blob.ts +103 -0
- package/server-e2e/app.ts +487 -0
- package/{server → server-e2e}/bus-receiver.ts +2 -1
- package/{server → server-e2e}/cli.js +9 -4
- package/{server → server-e2e}/config.ts +52 -42
- package/{server → server-e2e}/db-neon.ts +2 -2
- package/{server → server-e2e}/db-revision-sql.ts +1 -1
- package/{server → server-e2e}/db-stmt.ts +2 -2
- package/{server → server-e2e}/db.ts +7 -7
- package/{server → server-e2e}/http.ts +44 -13
- package/{server → server-e2e}/hub.ts +40 -9
- package/server-e2e/index.ts +17 -0
- package/server-e2e/lifecycle.ts +95 -0
- package/{server → server-e2e}/neon-driver.ts +2 -2
- package/{server → server-e2e}/npm-proxy.ts +12 -145
- package/{server → server-e2e}/objstore/blob-vercel.ts +10 -114
- package/{server → server-e2e}/objstore/blob.ts +1 -1
- package/{server → server-e2e}/objstore/fetch-mint-guard.ts +2 -2
- package/{server → server-e2e}/objstore/handlers.ts +9 -8
- package/{server → server-e2e}/objstore/init.ts +19 -27
- package/{server → server-e2e}/objstore/reaper.ts +1 -1
- package/{server → server-e2e}/objstore/rest-deny.ts +1 -1
- package/{server → server-e2e}/objstore/rest-mint.ts +3 -3
- package/{server → server-e2e}/objstore/rest.ts +3 -3
- package/{server → server-e2e}/objstore/store-neon.ts +6 -10
- package/{server → server-e2e}/objstore/store.ts +7 -7
- package/{server → server-e2e}/objstore/tokens.ts +2 -2
- package/{server → server-e2e}/pubsub.ts +12 -9
- package/{server → server-e2e}/sign.ts +4 -4
- package/{server → server-e2e}/sse-server.ts +3 -3
- package/{server → server-e2e}/static.ts +18 -17
- package/{server → server-e2e}/sync-handlers.ts +56 -30
- package/{server → server-e2e}/ws-server.ts +20 -9
- package/server-managed/activity.ts +269 -0
- package/server-managed/agent-merges.ts +109 -0
- package/server-managed/app-agents.ts +23 -0
- package/server-managed/avatar-store.ts +21 -0
- package/server-managed/blob-store.ts +26 -0
- package/server-managed/brotli.ts +10 -0
- package/server-managed/bundle-advisories.ts +176 -0
- package/server-managed/bundle-advisory-inventory.ts +85 -0
- package/server-managed/bundle-build-diagnostics.d.ts +10 -0
- package/server-managed/bundle-build-diagnostics.js +23 -0
- package/server-managed/bundle-build-leases.ts +41 -0
- package/server-managed/bundle-build-worker.js +387 -0
- package/server-managed/bundle-build.ts +328 -0
- package/server-managed/bundle-cache.ts +261 -0
- package/server-managed/bundle-catalog.ts +29 -0
- package/server-managed/bundle-commits.ts +133 -0
- package/server-managed/bundle-dependency-reviews.ts +91 -0
- package/server-managed/bundle-store.ts +24 -0
- package/server-managed/bundle-summary-cache.ts +139 -0
- package/server-managed/bundle-validation.ts +33 -0
- package/server-managed/bundle.ts +151 -0
- package/server-managed/cache-storage.ts +20 -0
- package/server-managed/cli.js +21 -0
- package/server-managed/combined.ts +43 -0
- package/server-managed/comments.ts +138 -0
- package/server-managed/commit-coauthors.ts +105 -0
- package/server-managed/commit-lockfiles.ts +78 -0
- package/server-managed/comparison.ts +51 -0
- package/server-managed/config.ts +163 -0
- package/server-managed/content-access.ts +15 -0
- package/server-managed/crypto.ts +25 -0
- package/server-managed/db-methods.ts +1950 -0
- package/server-managed/db-neon.ts +401 -0
- package/server-managed/db-schema.ts +271 -0
- package/server-managed/db-table-names.ts +22 -0
- package/server-managed/db.ts +150 -0
- package/server-managed/dependabot-access.ts +85 -0
- package/server-managed/dependabot-alerts.ts +197 -0
- package/server-managed/dependency-review-comments.ts +158 -0
- package/server-managed/dependency-reviews.ts +369 -0
- package/server-managed/github-accounts.ts +59 -0
- package/server-managed/github-actions.ts +71 -0
- package/server-managed/github-app.ts +347 -0
- package/server-managed/github-errors.ts +92 -0
- package/server-managed/github-graphql.ts +42 -0
- package/server-managed/github-issue-links.ts +264 -0
- package/server-managed/github-issue-oauth.ts +30 -0
- package/server-managed/github-issues.ts +169 -0
- package/server-managed/github-link-oauth.ts +56 -0
- package/server-managed/github-links.ts +204 -0
- package/server-managed/github-metadata.ts +218 -0
- package/server-managed/github-oauth.ts +264 -0
- package/server-managed/github-pulls.ts +290 -0
- package/server-managed/github-requests.ts +181 -0
- package/server-managed/github-users.ts +53 -0
- package/server-managed/github-values.ts +26 -0
- package/server-managed/history-windows.ts +172 -0
- package/server-managed/http-response.ts +76 -0
- package/server-managed/http.ts +6722 -0
- package/server-managed/import-triage.ts +51 -0
- package/server-managed/index.ts +204 -0
- package/server-managed/kept-briefly.ts +37 -0
- package/server-managed/kept.ts +28 -0
- package/server-managed/known-listings.ts +112 -0
- package/server-managed/link-reports.ts +149 -0
- package/server-managed/listed-activity.ts +39 -0
- package/server-managed/locked-packages.ts +234 -0
- package/server-managed/lockfile-scope.ts +58 -0
- package/server-managed/lru.ts +30 -0
- package/server-managed/managed-issues.ts +92 -0
- package/server-managed/management-catalog.ts +45 -0
- package/server-managed/management.ts +116 -0
- package/server-managed/npm-delta-worker.js +203 -0
- package/server-managed/npm-delta.ts +277 -0
- package/server-managed/npm-insights.ts +455 -0
- package/server-managed/npm-kept.ts +274 -0
- package/server-managed/npm-loads.ts +259 -0
- package/server-managed/npm-manifest.ts +117 -0
- package/server-managed/npm-packages.ts +477 -0
- package/server-managed/npm-patch-paths.ts +86 -0
- package/server-managed/npm-patch.ts +457 -0
- package/server-managed/npm-provenance.ts +127 -0
- package/server-managed/npm-risk.ts +310 -0
- package/server-managed/object-storage-disk.ts +147 -0
- package/server-managed/object-storage-vercel.ts +71 -0
- package/server-managed/object-storage.ts +82 -0
- package/server-managed/package-entry-points.ts +127 -0
- package/server-managed/pretty-copies.ts +22 -0
- package/server-managed/pretty-format.d.ts +4 -0
- package/server-managed/pretty-format.js +27 -0
- package/server-managed/pretty-print.ts +444 -0
- package/server-managed/public-workspace.ts +242 -0
- package/server-managed/pull-comment-reviews.ts +161 -0
- package/server-managed/pull-dependencies.ts +370 -0
- package/server-managed/pull-dependency-reviews.ts +458 -0
- package/server-managed/pull-reviews.ts +202 -0
- package/server-managed/pulse-walk.ts +164 -0
- package/server-managed/queue.ts +54 -0
- package/server-managed/release-commits.ts +85 -0
- package/server-managed/rename-diff-worker.js +30 -0
- package/server-managed/rename-diff.ts +237 -0
- package/server-managed/repo-path.ts +21 -0
- package/server-managed/report-migration.ts +32 -0
- package/server-managed/report-opening.ts +77 -0
- package/server-managed/report-query.ts +10 -0
- package/server-managed/report-response.ts +16 -0
- package/server-managed/report-sources.ts +185 -0
- package/server-managed/report-store.ts +77 -0
- package/server-managed/repository-actions.ts +220 -0
- package/server-managed/repository-agents.ts +422 -0
- package/server-managed/repository-aliases.ts +119 -0
- package/server-managed/repository-browser.ts +362 -0
- package/server-managed/repository-changes.ts +280 -0
- package/server-managed/repository-code.ts +222 -0
- package/server-managed/repository-dependency-reviews.ts +220 -0
- package/server-managed/repository-discovery.ts +83 -0
- package/server-managed/repository-history.ts +444 -0
- package/server-managed/repository-issues.ts +293 -0
- package/server-managed/repository-policy.ts +27 -0
- package/server-managed/repository-pulls.ts +207 -0
- package/server-managed/repository-pulse.ts +409 -0
- package/server-managed/repository-risk-assess.ts +179 -0
- package/server-managed/repository-risk-audit.ts +145 -0
- package/server-managed/repository-risk-caches.ts +56 -0
- package/server-managed/repository-risk-kept.ts +86 -0
- package/server-managed/repository-risk-read.ts +296 -0
- package/server-managed/repository-risk-stasis.ts +61 -0
- package/server-managed/repository-risk-turn.ts +97 -0
- package/server-managed/repository-risk.ts +528 -0
- package/server-managed/repository-squashes.ts +160 -0
- package/server-managed/repository-stamp.ts +41 -0
- package/server-managed/request-timing.ts +63 -0
- package/server-managed/reviewed-dependencies.ts +170 -0
- package/server-managed/revisions.ts +35 -0
- package/server-managed/scan-downloads.ts +121 -0
- package/server-managed/session.ts +132 -0
- package/server-managed/slugs.ts +38 -0
- package/server-managed/solidity-entry-points.ts +71 -0
- package/server-managed/sql-postgres.ts +34 -0
- package/server-managed/sql.ts +107 -0
- package/server-managed/stasis-config.ts +147 -0
- package/server-managed/stasis-dependencies.ts +280 -0
- package/server-managed/static.ts +28 -0
- package/server-managed/storage-command.ts +16 -0
- package/server-managed/storage-db.ts +183 -0
- package/server-managed/storage-encryption.ts +288 -0
- package/server-managed/storage-maintenance.ts +259 -0
- package/server-managed/storage-payload.ts +121 -0
- package/server-managed/storage-stores.ts +91 -0
- package/server-managed/storage.ts +82 -0
- package/server-managed/team-app-summaries.ts +57 -0
- package/server-managed/team-app.ts +162 -0
- package/server-managed/team-catalog.ts +7 -0
- package/server-managed/team-feed.ts +180 -0
- package/server-managed/team-icons.ts +50 -0
- package/server-managed/team-npm-scopes.ts +103 -0
- package/server-managed/team-progress.ts +77 -0
- package/server-managed/team-reports.ts +369 -0
- package/server-managed/triage-response.ts +16 -0
- package/server-managed/type-only-proof.js +181 -0
- package/server-managed/type-only-worker.js +31 -0
- package/server-managed/type-only.ts +135 -0
- package/server-managed/uploads.ts +106 -0
- package/server-managed/upstream-cache.ts +275 -0
- package/server-managed/view-as.ts +58 -0
- package/server-managed/worker-turns.ts +76 -0
- package/server-managed/workspace-shares.ts +170 -0
- package/server.ts +70 -0
- package/strip-types-loader.js +13 -10
- package/server/index.ts +0 -480
- package/server/lifecycle.ts +0 -208
- /package/{LICENSE → LICENSE-MIT} +0 -0
- /package/{server → server-e2e}/auth.ts +0 -0
- /package/{server → server-e2e}/config.example.json +0 -0
- /package/{server → server-e2e}/objstore/blob-fs.ts +0 -0
- /package/{server → server-e2e}/objstore/fs.ts +0 -0
- /package/{server → server-e2e}/objstore/sign.ts +0 -0
- /package/{server → server-e2e}/peer.ts +0 -0
- /package/{server → server-e2e}/sse-session.ts +0 -0
- /package/{server → server-e2e}/util.ts +0 -0
- /package/{server → server-e2e}/validation.ts +0 -0
|
@@ -0,0 +1,328 @@
|
|
|
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 { isNpmTokenName } from '../common/npm-token.js'
|
|
7
|
+
import { BUNDLE_BUILD_TIMEOUT_MS, type BundleBuildLeaseStore } from './bundle-build-leases.ts'
|
|
8
|
+
import { type BundleBuildDiagnostic, type BundleBuildStage, bundleBuildDiagnostic } from './bundle-build-diagnostics.js'
|
|
9
|
+
import type { BundleBuildConditions } from './db-methods.ts'
|
|
10
|
+
|
|
11
|
+
export class BundleBuildError extends Error {
|
|
12
|
+
status: number
|
|
13
|
+
code: string
|
|
14
|
+
constructor(status: number, code: string) { super(code); this.status = status; this.code = code }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
interface BundleBuildInput {
|
|
18
|
+
repoId: number
|
|
19
|
+
commit: string
|
|
20
|
+
entries: string[]
|
|
21
|
+
directory: string
|
|
22
|
+
options: { conditions?: string[]; mainFields?: string[]; metro?: boolean; platforms?: string[]; jsx?: boolean; packageManager?: 'soldeer' }
|
|
23
|
+
// What the stored bundle records; null for Solidity, which takes no
|
|
24
|
+
// conditions, and for entries given none, which stasis.config.json must
|
|
25
|
+
// then list (the build checks: bundle-build-worker.js).
|
|
26
|
+
conditions: BundleBuildConditions | null
|
|
27
|
+
// The branch the commit was picked by, where it was: Stasis asks it first
|
|
28
|
+
// when it holds the commit to the repo's own history, which GitHub's compare
|
|
29
|
+
// tells of it, so nothing is taken on trust (one the commit isn't of is
|
|
30
|
+
// looked past). Without it, Stasis lists the repo's tags and branches and
|
|
31
|
+
// compares up to 100 of those.
|
|
32
|
+
branch?: string
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// A name git takes for a branch (git check-ref-format --branch), at most
|
|
36
|
+
// GitHub's length for one.
|
|
37
|
+
export function branchName(value: unknown): value is string {
|
|
38
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 255
|
|
39
|
+
&& !/[\p{Cc}\s~^:?*[\\]|\.\.|@\{|\/\/|^-|^\/|\/$|\.$|^@$|(?:^|\/)\.|\.lock(?:\/|$)/u.test(value)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function path(value: unknown): value is string {
|
|
43
|
+
return typeof value === 'string' && value.length > 0 && value.length <= 1024 && !/[\\\p{Cc}]/u.test(value)
|
|
44
|
+
&& value.split('/').every(part => part !== '' && part !== '.' && part !== '..')
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const isScript = (entry: string) => /\.[cm]?[tj]sx?$/iu.test(entry)
|
|
48
|
+
|
|
49
|
+
// Whether a build takes `value` as an entry point, with others in its language.
|
|
50
|
+
export function buildableEntry(value: unknown): value is string {
|
|
51
|
+
return path(value) && (isScript(value) || value.endsWith('.sol'))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function parseBundleBuild(value: unknown): BundleBuildInput {
|
|
55
|
+
const fail = (code = 'bad-request'): never => { throw new BundleBuildError(400, code) }
|
|
56
|
+
if (value == null || typeof value !== 'object' || Array.isArray(value)) return fail()
|
|
57
|
+
const { repoId, commit, entries, conditions, branch } = value as Record<string, unknown>
|
|
58
|
+
if (typeof repoId !== 'number' || !Number.isSafeInteger(repoId) || repoId <= 0
|
|
59
|
+
|| typeof commit !== 'string' || !/^[a-f\d]{40}$/u.test(commit)
|
|
60
|
+
|| !Array.isArray(entries) || entries.length === 0 || entries.length > 100 || !entries.every(path)
|
|
61
|
+
|| (branch != null && !branchName(branch))) return fail()
|
|
62
|
+
const selected = [...new Set(entries as string[])]
|
|
63
|
+
const scripts = selected.every(isScript)
|
|
64
|
+
if (!scripts && !selected.every(entry => entry.endsWith('.sol'))) return fail('unsupported-entries')
|
|
65
|
+
const parts = posix.dirname(selected[0]!).split('/').filter(part => part !== '.')
|
|
66
|
+
for (const entry of selected) {
|
|
67
|
+
const parent = posix.dirname(entry).split('/')
|
|
68
|
+
while (parts.some((part, i) => parent[i] !== part)) parts.pop()
|
|
69
|
+
}
|
|
70
|
+
// Stasis builds Solidity with Soldeer alone. Named, a JS lockfile beside or
|
|
71
|
+
// above the project no longer leaves it unable to tell which one installs it.
|
|
72
|
+
const options: BundleBuildInput['options'] = scripts ? {} : { packageManager: 'soldeer' }
|
|
73
|
+
let recorded: BundleBuildConditions | null = null
|
|
74
|
+
if (scripts && conditions != null) {
|
|
75
|
+
if (typeof conditions !== 'object' || Array.isArray(conditions)) return fail('bad-conditions')
|
|
76
|
+
const { preset, conditions: names, platforms } = conditions as Record<string, unknown>
|
|
77
|
+
if (typeof preset !== 'string' || !['node', 'browser', 'metro'].includes(preset) || !Array.isArray(names) || names.length > 16
|
|
78
|
+
|| !names.every(name => typeof name === 'string' && name.length > 0 && name.length <= 64
|
|
79
|
+
&& !/^\.|^\d+$|[\s,/\\\p{Cc}]/u.test(name) && !['default', 'import', 'require'].includes(name))) return fail('bad-conditions')
|
|
80
|
+
if (preset === 'metro') {
|
|
81
|
+
if (names.length !== 1 || names[0] !== 'react-native') return fail('metro-conditions')
|
|
82
|
+
if (!Array.isArray(platforms) || platforms.length === 0 || platforms.length > 2
|
|
83
|
+
|| !platforms.every(platform => ['ios', 'android'].includes(platform))) return fail('bad-conditions')
|
|
84
|
+
// React Native's convention puts JSX in .js files, which Stasis parses as
|
|
85
|
+
// JSX only on request. TypeScript is left to Stasis to detect.
|
|
86
|
+
Object.assign(options, { metro: true, platforms: [...new Set(platforms)], jsx: true })
|
|
87
|
+
} else {
|
|
88
|
+
options.conditions = [...new Set(names)]
|
|
89
|
+
if (preset === 'browser') options.mainFields = ['browser', 'module', 'main']
|
|
90
|
+
}
|
|
91
|
+
recorded = { preset: preset as BundleBuildConditions['preset'], conditions: [...new Set(names as string[])],
|
|
92
|
+
platforms: options.platforms ?? [] }
|
|
93
|
+
}
|
|
94
|
+
return { repoId, commit, entries: selected, directory: parts.join('/'), options, conditions: recorded, ...(branchName(branch) && { branch }) }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// A package name as a filename base: `@scope/name` as `scope-name`, or as
|
|
98
|
+
// `name` alone where it is `scope` or already starts with `scope-`. Null for
|
|
99
|
+
// a name npm could not publish by its length or leading dot.
|
|
100
|
+
function packageBase(name: string): string | null {
|
|
101
|
+
const match = name.length <= 214 ? /^(?:@([^/.][^/]*)\/)?([^/.][^/]*)$/u.exec(name) : null
|
|
102
|
+
if (!match) return null
|
|
103
|
+
const base = match[2]!, scope = match[1]
|
|
104
|
+
return scope === undefined || base === scope || base.startsWith(`${scope}-`) ? base : `${scope}-${base}`
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Same portable name and 255-character limit as Stasis's githubBundleFile
|
|
108
|
+
// (src/cmd/github-bundle.js), which is not a public package export, except
|
|
109
|
+
// that a usable `packageName` replaces both the repo and the directory; a
|
|
110
|
+
// .stasis.tgz's (`format` tgz) ends in `.stasis.tgz`, as Stasis's does.
|
|
111
|
+
export function githubBundleFilename(github: string, directory: string, commit: string, packageName: string | null = null, format: 'br' | 'tgz' = 'br'): string {
|
|
112
|
+
const portable = (value: string) => value.replaceAll(/[^\w.-]/gu, '_')
|
|
113
|
+
const tail = `.${portable(commit.slice(0, 7))}.${format === 'tgz' ? 'stasis.tgz' : 'stasis.code.br'}`
|
|
114
|
+
const named = packageName === null ? null : packageBase(packageName)
|
|
115
|
+
if (named !== null) return `${portable(named)}${tail}`
|
|
116
|
+
const repo = portable(github.replace('/', '-'))
|
|
117
|
+
if (!directory) return `${repo}${tail}`
|
|
118
|
+
const room = 255 - `${repo}.${tail}`.length
|
|
119
|
+
let dir = portable(directory.replaceAll('/', '-'))
|
|
120
|
+
if (dir.length > room) dir = `${dir.slice(0, room - 9)}_${createHash('sha256').update(directory).digest('hex').slice(0, 8)}`
|
|
121
|
+
return `${repo}.${dir}${tail}`
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
interface BuiltBundle { bytes: Buffer; directory: string; filename: string }
|
|
125
|
+
interface BuildRequest {
|
|
126
|
+
input: BundleBuildInput; github: string; token: string | null; maxBytes: number; scopes: (string | null)[]
|
|
127
|
+
// Upstream's disk cache for what a build fetches (setCacheDir), or null for
|
|
128
|
+
// none, as on Vercel. Resolved here, as the worker's env is workerEnv's.
|
|
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), with the files of it
|
|
133
|
+
// the build reaches, each path's integrity (StasisReached); and what it is
|
|
134
|
+
// asked to build one of, with the `branch` the commit is of, where its asker
|
|
135
|
+
// knows it, as a bundle's is (BundleBuildInput).
|
|
136
|
+
export interface StasisDependency { name: string; version: string; integrity?: string; patch?: string }
|
|
137
|
+
export type StasisReached = StasisDependency & { files: Record<string, string> }
|
|
138
|
+
export interface LockfileInput { repoId: number; commit: string; config: string; branch?: string }
|
|
139
|
+
interface LockfileRequest { input: LockfileInput; github: string; token: string | null; cacheDir: string | null }
|
|
140
|
+
// An extra per-process ceiling, one build at a time, its worker given the heap
|
|
141
|
+
// buildHeapLimitMib sizes; admission must also hold the shared DB lease.
|
|
142
|
+
const active = new Set<string>()
|
|
143
|
+
const MAX_ACTIVE_BUILDS = 1
|
|
144
|
+
// The build running behind no request (buildRepositoryLockfile), which one
|
|
145
|
+
// asked for takes the slot and the lease of: told to yield
|
|
146
|
+
// (`build-yielded`), and gone once its lease is released.
|
|
147
|
+
let behind: { yield: () => void; gone: Promise<void> } | null = null
|
|
148
|
+
// Who builds behind no request, as `active` and the shared lease name it.
|
|
149
|
+
const LOCKFILE_BUILDER = 'dependency-review'
|
|
150
|
+
// Where builds keep what they download of npm for those after them in this
|
|
151
|
+
// instance, where no cache directory is set, as on Vercel
|
|
152
|
+
// (bundle-build-worker.js instanceCache).
|
|
153
|
+
const INSTANCE_DIR = join(tmpdir(), 'triage-stasis-cache')
|
|
154
|
+
async function yielded(): Promise<void> {
|
|
155
|
+
const running = behind
|
|
156
|
+
if (!running) return
|
|
157
|
+
running.yield()
|
|
158
|
+
await running.gone
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// What a build's worker may take of the JS heap, in MiB: the memory the
|
|
162
|
+
// process may use, its container's limit else the machine's, less
|
|
163
|
+
// RESERVED_MIB, at least the 512 MiB a build always had. A large project's
|
|
164
|
+
// tree, as a React Native app's, laid out and scanned in memory, takes more
|
|
165
|
+
// than 2 GiB, as `stasis github-bundle` takes what Node's default heap gives
|
|
166
|
+
// it. What is reserved is the server's, and the worker's own beyond its heap:
|
|
167
|
+
// the bytes of the files it lays out, its bundle's JSON (512 MiB at most, the
|
|
168
|
+
// worker's MAX_SERIALIZED_BYTES) and that compressed. Past it, Node
|
|
169
|
+
// terminates the worker (build-memory), not the process.
|
|
170
|
+
const RESERVED_MIB = 512
|
|
171
|
+
const MIN_BUILD_HEAP_MIB = 512
|
|
172
|
+
const processMemory = () => Math.min(process.constrainedMemory() || Infinity, totalmem())
|
|
173
|
+
export function buildHeapLimitMib(memory = processMemory()): number {
|
|
174
|
+
return Math.max(MIN_BUILD_HEAP_MIB, Math.floor(memory / 1024 ** 2) - RESERVED_MIB)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// `work` under one of the deployment's leases, `userId`'s one at a time. One
|
|
178
|
+
// asked for first has this instance's build behind no request yield, and
|
|
179
|
+
// waits for its lease to be released, lest that hold a lease against it.
|
|
180
|
+
export async function withBundleBuildLease<T>(db: BundleBuildLeaseStore, userId: string, signal: AbortSignal,
|
|
181
|
+
work: (signal: AbortSignal) => Promise<T>): Promise<T> {
|
|
182
|
+
signal.throwIfAborted()
|
|
183
|
+
const owner = randomUUID(), started = performance.now(), timeout = new AbortController()
|
|
184
|
+
const expired = () => timeout.abort(new BundleBuildError(504, 'build-timeout'))
|
|
185
|
+
const timer = setTimeout(expired, BUNDLE_BUILD_TIMEOUT_MS)
|
|
186
|
+
const combined = AbortSignal.any([signal, timeout.signal])
|
|
187
|
+
let claimed = false
|
|
188
|
+
try {
|
|
189
|
+
if (userId !== LOCKFILE_BUILDER && behind) await yielded()
|
|
190
|
+
claimed = await db.claimBundleBuildLease(userId, owner)
|
|
191
|
+
if (!claimed) throw new BundleBuildError(429, 'build-busy')
|
|
192
|
+
// Account for a slow/lost claim response or a suspended invocation before
|
|
193
|
+
// starting work. The three-minute budget starts before lease acquisition.
|
|
194
|
+
if (performance.now() - started >= BUNDLE_BUILD_TIMEOUT_MS) expired()
|
|
195
|
+
combined.throwIfAborted()
|
|
196
|
+
return await work(combined)
|
|
197
|
+
} catch (error) {
|
|
198
|
+
if (timeout.signal.aborted && !signal.aborted) throw timeout.signal.reason
|
|
199
|
+
throw error
|
|
200
|
+
} finally {
|
|
201
|
+
clearTimeout(timer)
|
|
202
|
+
// buildRepositoryBundle waits for worker termination before settling.
|
|
203
|
+
// Unknown claim/release outcomes expire safely without starting more work.
|
|
204
|
+
if (claimed) await db.releaseBundleBuildLease(owner)
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// The npm tokens, for private scoped packages, and VERCEL_ENV, by which Stasis
|
|
209
|
+
// skips oxc-parser's raw transfer on Vercel; no other credential.
|
|
210
|
+
export function workerEnv(env: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
|
211
|
+
const passed = Object.entries(env).filter((entry): entry is [string, string] => isNpmTokenName(entry[0]) && Boolean(entry[1]))
|
|
212
|
+
return Object.fromEntries(env['VERCEL_ENV'] === undefined ? passed : [...passed, ['VERCEL_ENV', env['VERCEL_ENV']]])
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Parsing repositories and compressing bundles stays off the HTTP event loop.
|
|
216
|
+
// Cap concurrent builds, terminate disconnected/timed-out work, and share no
|
|
217
|
+
// credentials or mutable Stasis state between requests.
|
|
218
|
+
export function buildRepositoryBundle(userId: string, request: BuildRequest, signal: AbortSignal): Promise<BuiltBundle> {
|
|
219
|
+
const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, directory: request.input.directory, entryCount: request.input.entries.length }
|
|
220
|
+
const asked = { ...request, instanceDir: INSTANCE_DIR }
|
|
221
|
+
return runBuild<BuiltBundle & { bytes: Uint8Array }, BuiltBundle>(userId, asked, context, signal, message => {
|
|
222
|
+
// A view of the bytes the worker handed over, not a copy of them.
|
|
223
|
+
const { bytes } = message
|
|
224
|
+
return { value: { bytes: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength), directory: message.directory, filename: message.filename }, logged: { byteSize: bytes.length } }
|
|
225
|
+
})
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// A Stasis lockfile's dependencies in place of a bundle, for a repository's
|
|
229
|
+
// dependency review (stasis-dependencies.ts), built behind no request, under
|
|
230
|
+
// the deployment's lease as its one builder of them: in the same one slot,
|
|
231
|
+
// which it gives up to a build asked for, with its lease (`build-yielded`),
|
|
232
|
+
// and is refused while another holds (`build-busy`), to be built later.
|
|
233
|
+
export async function buildRepositoryLockfile(db: BundleBuildLeaseStore, request: LockfileRequest, signal: AbortSignal): Promise<StasisReached[]> {
|
|
234
|
+
if (behind || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
|
|
235
|
+
const context = { repoId: request.input.repoId, github: request.github, commit: request.input.commit, config: request.input.config, branch: request.input.branch, lockfileOnly: true }
|
|
236
|
+
const asked = { ...request, instanceDir: INSTANCE_DIR, lockfileOnly: true }
|
|
237
|
+
const yielding = new AbortController()
|
|
238
|
+
let gone = () => {}
|
|
239
|
+
behind = { yield: () => yielding.abort(new BundleBuildError(429, 'build-yielded')), gone: new Promise(resolve => { gone = resolve }) }
|
|
240
|
+
try {
|
|
241
|
+
return await withBundleBuildLease(db, LOCKFILE_BUILDER, AbortSignal.any([signal, yielding.signal]), leased => runBuild<{ dependencies: StasisReached[] }, StasisReached[]>(
|
|
242
|
+
LOCKFILE_BUILDER, asked, context, leased, ({ dependencies }) => ({ value: dependencies, logged: { dependencies: dependencies.length } }), true))
|
|
243
|
+
} finally {
|
|
244
|
+
behind = null
|
|
245
|
+
gone()
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// What a build's worker told last, by its type: its progress, memory or a
|
|
250
|
+
// note, its failure, else what it built.
|
|
251
|
+
type WorkerMessage<M> = M & { type?: string; stage?: BundleBuildStage; error?: string; status?: number; diagnostic?: BundleBuildDiagnostic
|
|
252
|
+
memory?: Record<string, number>; event?: string; details?: Record<string, unknown> }
|
|
253
|
+
|
|
254
|
+
// `request` built in a worker of its own, `owner`'s one build at a time, what
|
|
255
|
+
// it built told by `built` of its last message, with what its log keeps of
|
|
256
|
+
// it; `background`, behind no request.
|
|
257
|
+
async function runBuild<M, T>(owner: string, request: { token: string | null }, about: Record<string, unknown>, signal: AbortSignal,
|
|
258
|
+
built: (message: M) => { value: T; logged: Record<string, unknown> }, background = false): Promise<T> {
|
|
259
|
+
const { token } = request
|
|
260
|
+
// One asked for takes the slot of one running behind no request, where its lease didn't already.
|
|
261
|
+
if (!background && behind) await yielded()
|
|
262
|
+
if (active.has(owner) || active.size >= MAX_ACTIVE_BUILDS) throw new BundleBuildError(429, 'build-busy')
|
|
263
|
+
signal.throwIfAborted()
|
|
264
|
+
active.add(owner)
|
|
265
|
+
let worker: Worker | undefined
|
|
266
|
+
let workerUrl: URL | undefined
|
|
267
|
+
let stage: BundleBuildStage = 'worker-start'
|
|
268
|
+
const buildId = randomUUID(), started = performance.now()
|
|
269
|
+
const heapLimitMib = buildHeapLimitMib()
|
|
270
|
+
// How this Node was built, as it decides what a heap holds the same objects in.
|
|
271
|
+
const { v8_enable_pointer_compression: pointerCompression, v8_enable_sandbox: v8Sandbox } = process.config.variables as Record<string, unknown>
|
|
272
|
+
const context = { buildId, ...about, node: process.version, v8: process.versions.v8, pointerCompression, v8Sandbox,
|
|
273
|
+
memoryMib: Math.round(processMemory() / 1024 ** 2), heapLimitMib }
|
|
274
|
+
const log = (event: string, details: Record<string, unknown> = {}) => {
|
|
275
|
+
const write = event === 'failed' ? console.error : console.info
|
|
276
|
+
write('managed-bundle-build:', JSON.stringify({ ...context, workerUrl: workerUrl?.href, event, stage, elapsedMs: Math.round(performance.now() - started), ...details }))
|
|
277
|
+
}
|
|
278
|
+
try {
|
|
279
|
+
workerUrl = new URL('./bundle-build-worker.js', import.meta.url)
|
|
280
|
+
log('started')
|
|
281
|
+
worker = new Worker(workerUrl, {
|
|
282
|
+
workerData: { ...request, type: 'managed-bundle-build' }, env: workerEnv(), execArgv: [], resourceLimits: { maxOldGenerationSizeMb: heapLimitMib },
|
|
283
|
+
})
|
|
284
|
+
const running = worker
|
|
285
|
+
return await new Promise((resolve, reject) => {
|
|
286
|
+
let settled = false
|
|
287
|
+
const cleanup = () => { clearTimeout(timer); signal.removeEventListener('abort', abort) }
|
|
288
|
+
const fail = (status: number, code: string, details: Record<string, unknown> = {}) => {
|
|
289
|
+
if (settled) return
|
|
290
|
+
settled = true
|
|
291
|
+
cleanup()
|
|
292
|
+
log(code === 'build-cancelled' || code === 'build-yielded' ? 'cancelled' : 'failed', { code, ...details })
|
|
293
|
+
reject(new BundleBuildError(status, code))
|
|
294
|
+
}
|
|
295
|
+
const timer = setTimeout(() => fail(504, 'build-timeout'), BUNDLE_BUILD_TIMEOUT_MS)
|
|
296
|
+
const abort = () => signal.reason instanceof BundleBuildError ? fail(signal.reason.status, signal.reason.code) : fail(499, 'build-cancelled')
|
|
297
|
+
signal.addEventListener('abort', abort, { once: true })
|
|
298
|
+
// The worker's memory and notes are the log's alone: the response tells
|
|
299
|
+
// what it built, or the error's code, and nothing of them.
|
|
300
|
+
running.on('message', (message: WorkerMessage<M>) => {
|
|
301
|
+
if (settled) return
|
|
302
|
+
if (message.type === 'progress' && message.stage) { stage = message.stage; log('progress', { memory: message.memory }); return }
|
|
303
|
+
if (message.type === 'memory') { log('memory', { memory: message.memory }); return }
|
|
304
|
+
if (message.type === 'note' && typeof message.event === 'string') { log(message.event, message.details ?? {}); return }
|
|
305
|
+
if (message.error) { fail(message.status ?? 422, message.error, { diagnostic: message.diagnostic, memory: message.memory }); return }
|
|
306
|
+
settled = true
|
|
307
|
+
cleanup()
|
|
308
|
+
const { value, logged } = built(message)
|
|
309
|
+
log('completed', logged)
|
|
310
|
+
resolve(value)
|
|
311
|
+
})
|
|
312
|
+
// Past its heap (heapLimitMib), Node terminates the worker with ERR_WORKER_OUT_OF_MEMORY.
|
|
313
|
+
running.once('error', error => {
|
|
314
|
+
const outOfMemory = (error as { code?: unknown }).code === 'ERR_WORKER_OUT_OF_MEMORY'
|
|
315
|
+
fail(outOfMemory ? 413 : 422, outOfMemory ? 'build-memory' : 'build-failed', { diagnostic: bundleBuildDiagnostic(error, token) })
|
|
316
|
+
})
|
|
317
|
+
running.once('exit', exitCode => fail(422, 'build-failed', { exitCode }))
|
|
318
|
+
if (signal.aborted) abort()
|
|
319
|
+
})
|
|
320
|
+
} catch (error) {
|
|
321
|
+
if (!(error instanceof BundleBuildError)) {
|
|
322
|
+
log('failed', { code: 'build-failed', diagnostic: bundleBuildDiagnostic(error, token) })
|
|
323
|
+
}
|
|
324
|
+
throw error
|
|
325
|
+
} finally {
|
|
326
|
+
try { await worker?.terminate() } finally { active.delete(owner) }
|
|
327
|
+
}
|
|
328
|
+
}
|
|
@@ -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
|
+
}
|