@mastra/factory 0.29.0-alpha.4 → 0.29.0-alpha.6
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/README.md +172 -89
- package/dist/boards/board-events.d.ts +89 -9
- package/dist/boards/board-events.d.ts.map +1 -1
- package/dist/boards/board-events.js +176 -13
- package/dist/boards/board-events.js.map +1 -1
- package/dist/boards/board-writes.d.ts.map +1 -1
- package/dist/boards/board-writes.js +14 -1
- package/dist/boards/board-writes.js.map +1 -1
- package/dist/boards/busy-card.d.ts +11 -0
- package/dist/boards/busy-card.d.ts.map +1 -0
- package/dist/boards/busy-card.js +15 -0
- package/dist/boards/busy-card.js.map +1 -0
- package/dist/boards/card-facts.d.ts.map +1 -1
- package/dist/boards/card-facts.js +18 -4
- package/dist/boards/card-facts.js.map +1 -1
- package/dist/boards/index.d.ts +2 -1
- package/dist/boards/index.d.ts.map +1 -1
- package/dist/boards/index.js +3 -2
- package/dist/boards/intake-dry-run.d.ts +109 -0
- package/dist/boards/intake-dry-run.d.ts.map +1 -0
- package/dist/boards/intake-dry-run.js +158 -0
- package/dist/boards/intake-dry-run.js.map +1 -0
- package/dist/boards/intake-lookup.d.ts +32 -0
- package/dist/boards/intake-lookup.d.ts.map +1 -0
- package/dist/boards/intake-lookup.js +12 -0
- package/dist/boards/intake-lookup.js.map +1 -0
- package/dist/boards/intake-order.d.ts +32 -0
- package/dist/boards/intake-order.d.ts.map +1 -0
- package/dist/boards/intake-order.js +60 -0
- package/dist/boards/intake-order.js.map +1 -0
- package/dist/boards/intake-routing.d.ts +246 -35
- package/dist/boards/intake-routing.d.ts.map +1 -1
- package/dist/boards/intake-routing.js +437 -52
- package/dist/boards/intake-routing.js.map +1 -1
- package/dist/boards/reroute.d.ts +7 -3
- package/dist/boards/reroute.d.ts.map +1 -1
- package/dist/boards/reroute.js +21 -4
- package/dist/boards/reroute.js.map +1 -1
- package/dist/boards/semantics.d.ts +8 -28
- package/dist/boards/semantics.d.ts.map +1 -1
- package/dist/boards/semantics.js +14 -40
- package/dist/boards/semantics.js.map +1 -1
- package/dist/boards/work-routes.d.ts +31 -11
- package/dist/boards/work-routes.d.ts.map +1 -1
- package/dist/boards/work-routes.js +104 -20
- package/dist/boards/work-routes.js.map +1 -1
- package/dist/factory.d.ts +37 -1
- package/dist/factory.d.ts.map +1 -1
- package/dist/factory.js +127 -48
- package/dist/factory.js.map +1 -1
- package/dist/integrations/base.d.ts +9 -0
- package/dist/integrations/base.d.ts.map +1 -1
- package/dist/integrations/dependabot/rules.js +1 -1
- package/dist/integrations/dependabot/rules.js.map +1 -1
- package/dist/integrations/github/default-rules.d.ts +22 -1
- package/dist/integrations/github/default-rules.d.ts.map +1 -1
- package/dist/integrations/github/default-rules.js +23 -5
- package/dist/integrations/github/default-rules.js.map +1 -1
- package/dist/integrations/github/intake-lookup.d.ts +16 -0
- package/dist/integrations/github/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/github/intake-lookup.js +76 -0
- package/dist/integrations/github/intake-lookup.js.map +1 -0
- package/dist/integrations/github/integration.d.ts +19 -5
- package/dist/integrations/github/integration.d.ts.map +1 -1
- package/dist/integrations/github/integration.js +21 -6
- package/dist/integrations/github/integration.js.map +1 -1
- package/dist/integrations/github/issue-intake.d.ts +15 -0
- package/dist/integrations/github/issue-intake.d.ts.map +1 -0
- package/dist/integrations/github/issue-intake.js +50 -0
- package/dist/integrations/github/issue-intake.js.map +1 -0
- package/dist/integrations/github/issue-reconciler.d.ts.map +1 -1
- package/dist/integrations/github/issue-reconciler.js +10 -1
- package/dist/integrations/github/issue-reconciler.js.map +1 -1
- package/dist/integrations/github/review-status-reporter.js +1 -1
- package/dist/integrations/github/routes.d.ts.map +1 -1
- package/dist/integrations/github/routes.js +14 -2
- package/dist/integrations/github/routes.js.map +1 -1
- package/dist/integrations/github/rules.d.ts +14 -1
- package/dist/integrations/github/rules.d.ts.map +1 -1
- package/dist/integrations/github/rules.js +221 -30
- package/dist/integrations/github/rules.js.map +1 -1
- package/dist/integrations/github/sandbox.d.ts.map +1 -1
- package/dist/integrations/github/sandbox.js +30 -4
- package/dist/integrations/github/sandbox.js.map +1 -1
- package/dist/integrations/gitlab/default-rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/default-rules.js +19 -3
- package/dist/integrations/gitlab/default-rules.js.map +1 -1
- package/dist/integrations/gitlab/intake-lookup.d.ts +17 -0
- package/dist/integrations/gitlab/intake-lookup.d.ts.map +1 -0
- package/dist/integrations/gitlab/intake-lookup.js +85 -0
- package/dist/integrations/gitlab/intake-lookup.js.map +1 -0
- package/dist/integrations/gitlab/integration.d.ts +5 -0
- package/dist/integrations/gitlab/integration.d.ts.map +1 -1
- package/dist/integrations/gitlab/integration.js +21 -1
- package/dist/integrations/gitlab/integration.js.map +1 -1
- package/dist/integrations/gitlab/rules.d.ts +20 -0
- package/dist/integrations/gitlab/rules.d.ts.map +1 -1
- package/dist/integrations/gitlab/rules.js +108 -12
- package/dist/integrations/gitlab/rules.js.map +1 -1
- package/dist/integrations/incidentio/rules.d.ts.map +1 -1
- package/dist/integrations/incidentio/rules.js +14 -4
- package/dist/integrations/incidentio/rules.js.map +1 -1
- package/dist/integrations/jira/rules.d.ts.map +1 -1
- package/dist/integrations/jira/rules.js +12 -2
- package/dist/integrations/jira/rules.js.map +1 -1
- package/dist/integrations/linear/rules.d.ts.map +1 -1
- package/dist/integrations/linear/rules.js +13 -2
- package/dist/integrations/linear/rules.js.map +1 -1
- package/dist/integrations/platform/connect/routes.d.ts +43 -1
- package/dist/integrations/platform/connect/routes.d.ts.map +1 -1
- package/dist/integrations/platform/connect/routes.js +82 -7
- package/dist/integrations/platform/connect/routes.js.map +1 -1
- package/dist/integrations/platform/connect/session-tools.d.ts +12 -0
- package/dist/integrations/platform/connect/session-tools.d.ts.map +1 -1
- package/dist/integrations/platform/connect/session-tools.js +28 -10
- package/dist/integrations/platform/connect/session-tools.js.map +1 -1
- package/dist/integrations/platform/github/event-worker.js +9 -1
- package/dist/integrations/platform/github/event-worker.js.map +1 -1
- package/dist/integrations/platform/github/integration.d.ts +6 -6
- package/dist/integrations/platform/github/integration.d.ts.map +1 -1
- package/dist/integrations/platform/github/integration.js +22 -3
- package/dist/integrations/platform/github/integration.js.map +1 -1
- package/dist/integrations/platform/vanta/integration.d.ts.map +1 -1
- package/dist/integrations/platform/vanta/integration.js +3 -3
- package/dist/integrations/platform/vanta/integration.js.map +1 -1
- package/dist/integrations/pull-request-head.d.ts +1 -1
- package/dist/integrations/pull-request-head.d.ts.map +1 -1
- package/dist/integrations/pull-request-head.js +5 -0
- package/dist/integrations/pull-request-head.js.map +1 -1
- package/dist/integrations/vanta/rules.js +1 -1
- package/dist/integrations/vanta/rules.js.map +1 -1
- package/dist/integrations/vanta/sync.d.ts +9 -0
- package/dist/integrations/vanta/sync.d.ts.map +1 -1
- package/dist/integrations/vanta/sync.js +10 -1
- package/dist/integrations/vanta/sync.js.map +1 -1
- package/dist/routes/board-snapshot.d.ts +13 -6
- package/dist/routes/board-snapshot.d.ts.map +1 -1
- package/dist/routes/board-snapshot.js +42 -20
- package/dist/routes/board-snapshot.js.map +1 -1
- package/dist/routes/boards.js.map +1 -1
- package/dist/routes/config.d.ts +17 -2
- package/dist/routes/config.d.ts.map +1 -1
- package/dist/routes/config.js +247 -77
- package/dist/routes/config.js.map +1 -1
- package/dist/routes/contracts.d.ts +1294 -7
- package/dist/routes/contracts.d.ts.map +1 -1
- package/dist/routes/contracts.js +603 -20
- package/dist/routes/contracts.js.map +1 -1
- package/dist/routes/custom-endpoint-url.d.ts +8 -0
- package/dist/routes/custom-endpoint-url.d.ts.map +1 -0
- package/dist/routes/custom-endpoint-url.js +45 -0
- package/dist/routes/custom-endpoint-url.js.map +1 -0
- package/dist/routes/custom-provider-source.d.ts +24 -8
- package/dist/routes/custom-provider-source.d.ts.map +1 -1
- package/dist/routes/custom-provider-source.js +93 -43
- package/dist/routes/custom-provider-source.js.map +1 -1
- package/dist/routes/intake-check.d.ts +92 -0
- package/dist/routes/intake-check.d.ts.map +1 -0
- package/dist/routes/intake-check.js +322 -0
- package/dist/routes/intake-check.js.map +1 -0
- package/dist/routes/intake-routes.d.ts +10 -2
- package/dist/routes/intake-routes.d.ts.map +1 -1
- package/dist/routes/intake-routes.js +292 -11
- package/dist/routes/intake-routes.js.map +1 -1
- package/dist/routes/intake.d.ts +6 -0
- package/dist/routes/intake.d.ts.map +1 -1
- package/dist/routes/intake.js +20 -0
- package/dist/routes/intake.js.map +1 -1
- package/dist/routes/mastra-gateway.d.ts.map +1 -1
- package/dist/routes/mastra-gateway.js +3 -2
- package/dist/routes/mastra-gateway.js.map +1 -1
- package/dist/routes/project-sessions.d.ts +61 -0
- package/dist/routes/project-sessions.d.ts.map +1 -0
- package/dist/routes/project-sessions.js +135 -0
- package/dist/routes/project-sessions.js.map +1 -0
- package/dist/routes/projects.d.ts +6 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/projects.js +19 -3
- package/dist/routes/projects.js.map +1 -1
- package/dist/routes/provider-credentials.d.ts +10 -1
- package/dist/routes/provider-credentials.d.ts.map +1 -1
- package/dist/routes/provider-credentials.js +13 -16
- package/dist/routes/provider-credentials.js.map +1 -1
- package/dist/routes/run-queue.d.ts +6 -6
- package/dist/routes/run-queue.d.ts.map +1 -1
- package/dist/routes/run-queue.js +28 -8
- package/dist/routes/run-queue.js.map +1 -1
- package/dist/routes/session-rows.d.ts +30 -0
- package/dist/routes/session-rows.d.ts.map +1 -0
- package/dist/routes/session-rows.js +94 -0
- package/dist/routes/session-rows.js.map +1 -0
- package/dist/routes/source-control-sessions.d.ts +4 -5
- package/dist/routes/source-control-sessions.d.ts.map +1 -1
- package/dist/routes/source-control-sessions.js +8 -87
- package/dist/routes/source-control-sessions.js.map +1 -1
- package/dist/routes/surface.d.ts +16 -1
- package/dist/routes/surface.d.ts.map +1 -1
- package/dist/routes/surface.js +41 -30
- package/dist/routes/surface.js.map +1 -1
- package/dist/routes/tenant-credentials.d.ts.map +1 -1
- package/dist/routes/tenant-credentials.js +4 -4
- package/dist/routes/tenant-credentials.js.map +1 -1
- package/dist/routes/work-item-starters.d.ts +1 -0
- package/dist/routes/work-item-starters.d.ts.map +1 -1
- package/dist/routes/work-item-starters.js +14 -2
- package/dist/routes/work-item-starters.js.map +1 -1
- package/dist/routes/work-items.d.ts +22 -3
- package/dist/routes/work-items.d.ts.map +1 -1
- package/dist/routes/work-items.js +124 -48
- package/dist/routes/work-items.js.map +1 -1
- package/dist/rules/binding-context.d.ts +5 -0
- package/dist/rules/binding-context.d.ts.map +1 -1
- package/dist/rules/binding-context.js +51 -5
- package/dist/rules/binding-context.js.map +1 -1
- package/dist/rules/dispatch-errors.js +1 -1
- package/dist/rules/dispatch-errors.js.map +1 -1
- package/dist/rules/dispatcher.d.ts +39 -7
- package/dist/rules/dispatcher.d.ts.map +1 -1
- package/dist/rules/dispatcher.js +363 -123
- package/dist/rules/dispatcher.js.map +1 -1
- package/dist/rules/event-rules.d.ts +69 -1
- package/dist/rules/event-rules.d.ts.map +1 -1
- package/dist/rules/event-rules.js +151 -5
- package/dist/rules/event-rules.js.map +1 -1
- package/dist/rules/review-source-tool.js +1 -1
- package/dist/rules/rule-group.d.ts +18 -1
- package/dist/rules/rule-group.d.ts.map +1 -1
- package/dist/rules/rule-group.js +52 -8
- package/dist/rules/rule-group.js.map +1 -1
- package/dist/rules/run-bearing.d.ts +8 -0
- package/dist/rules/run-bearing.d.ts.map +1 -0
- package/dist/rules/run-bearing.js +11 -0
- package/dist/rules/run-bearing.js.map +1 -0
- package/dist/rules/start-coordinator.d.ts +2 -3
- package/dist/rules/start-coordinator.d.ts.map +1 -1
- package/dist/rules/start-coordinator.js +25 -38
- package/dist/rules/start-coordinator.js.map +1 -1
- package/dist/rules/tools.js +2 -1
- package/dist/rules/tools.js.map +1 -1
- package/dist/rules/transition-service.d.ts +16 -0
- package/dist/rules/transition-service.d.ts.map +1 -1
- package/dist/rules/transition-service.js +34 -10
- package/dist/rules/transition-service.js.map +1 -1
- package/dist/rules/types.d.ts +18 -5
- package/dist/rules/types.d.ts.map +1 -1
- package/dist/rules/types.js +2 -1
- package/dist/rules/types.js.map +1 -1
- package/dist/rules/update-fold.d.ts +32 -0
- package/dist/rules/update-fold.d.ts.map +1 -0
- package/dist/rules/update-fold.js +60 -0
- package/dist/rules/update-fold.js.map +1 -0
- package/dist/rules/validation.d.ts.map +1 -1
- package/dist/rules/validation.js +54 -6
- package/dist/rules/validation.js.map +1 -1
- package/dist/sandbox/session-retirement.d.ts +6 -0
- package/dist/sandbox/session-retirement.d.ts.map +1 -1
- package/dist/sandbox/session-retirement.js +17 -0
- package/dist/sandbox/session-retirement.js.map +1 -1
- package/dist/session/factory-session.d.ts.map +1 -1
- package/dist/session/factory-session.js +2 -1
- package/dist/session/factory-session.js.map +1 -1
- package/dist/session/live-sessions.d.ts +6 -1
- package/dist/session/live-sessions.d.ts.map +1 -1
- package/dist/session/live-sessions.js +4 -0
- package/dist/session/live-sessions.js.map +1 -1
- package/dist/session/resource-migration.d.ts.map +1 -1
- package/dist/session/resource-migration.js +2 -3
- package/dist/session/resource-migration.js.map +1 -1
- package/dist/session/run-audit.d.ts +10 -1
- package/dist/session/run-audit.d.ts.map +1 -1
- package/dist/session/run-audit.js +9 -1
- package/dist/session/run-audit.js.map +1 -1
- package/dist/session/self-review-gate.d.ts +26 -2
- package/dist/session/self-review-gate.d.ts.map +1 -1
- package/dist/session/self-review-gate.js +60 -10
- package/dist/session/self-review-gate.js.map +1 -1
- package/dist/session/session-row-query.d.ts +25 -0
- package/dist/session/session-row-query.d.ts.map +1 -0
- package/dist/session/session-row-query.js +47 -0
- package/dist/session/session-row-query.js.map +1 -0
- package/dist/session/session-row-status.d.ts +16 -0
- package/dist/session/session-row-status.d.ts.map +1 -0
- package/dist/session/session-row-status.js +14 -0
- package/dist/session/session-row-status.js.map +1 -0
- package/dist/session/session-row-view.d.ts +13 -0
- package/dist/session/session-row-view.d.ts.map +1 -0
- package/dist/session/session-row-view.js +118 -0
- package/dist/session/session-row-view.js.map +1 -0
- package/dist/session/session-rows.d.ts +60 -0
- package/dist/session/session-rows.d.ts.map +1 -0
- package/dist/session/session-rows.js +307 -0
- package/dist/session/session-rows.js.map +1 -0
- package/dist/session/session-threads.d.ts.map +1 -1
- package/dist/session/session-threads.js +1 -0
- package/dist/session/session-threads.js.map +1 -1
- package/dist/session/session-unloader.d.ts +101 -0
- package/dist/session/session-unloader.d.ts.map +1 -0
- package/dist/session/session-unloader.js +278 -0
- package/dist/session/session-unloader.js.map +1 -0
- package/dist/session/source-control-tools.d.ts +14 -7
- package/dist/session/source-control-tools.d.ts.map +1 -1
- package/dist/session/source-control-tools.js +10 -2
- package/dist/session/source-control-tools.js.map +1 -1
- package/dist/session/work-item-repository.d.ts +49 -1
- package/dist/session/work-item-repository.d.ts.map +1 -1
- package/dist/session/work-item-repository.js +118 -15
- package/dist/session/work-item-repository.js.map +1 -1
- package/dist/session/work-item-state-processor.d.ts.map +1 -1
- package/dist/session/work-item-state-processor.js +44 -8
- package/dist/session/work-item-state-processor.js.map +1 -1
- package/dist/session-list-changes.d.ts +9 -0
- package/dist/session-list-changes.d.ts.map +1 -0
- package/dist/session-list-changes.js +54 -0
- package/dist/session-list-changes.js.map +1 -0
- package/dist/storage/announced-lists.d.ts +14 -0
- package/dist/storage/announced-lists.d.ts.map +1 -0
- package/dist/storage/announced-lists.js +78 -0
- package/dist/storage/announced-lists.js.map +1 -0
- package/dist/storage/domains/audit/actions.d.ts +2 -1
- package/dist/storage/domains/audit/actions.d.ts.map +1 -1
- package/dist/storage/domains/audit/actions.js +3 -1
- package/dist/storage/domains/audit/actions.js.map +1 -1
- package/dist/storage/domains/boards/base.d.ts +163 -15
- package/dist/storage/domains/boards/base.d.ts.map +1 -1
- package/dist/storage/domains/boards/base.js +440 -48
- package/dist/storage/domains/boards/base.js.map +1 -1
- package/dist/storage/domains/boards/schemas.d.ts +6 -0
- package/dist/storage/domains/boards/schemas.d.ts.map +1 -1
- package/dist/storage/domains/boards/schemas.js +95 -1
- package/dist/storage/domains/boards/schemas.js.map +1 -1
- package/dist/storage/domains/custom-providers/base.d.ts +62 -19
- package/dist/storage/domains/custom-providers/base.d.ts.map +1 -1
- package/dist/storage/domains/custom-providers/base.js +131 -100
- package/dist/storage/domains/custom-providers/base.js.map +1 -1
- package/dist/storage/domains/intake/base.d.ts +25 -7
- package/dist/storage/domains/intake/base.d.ts.map +1 -1
- package/dist/storage/domains/intake/base.js +83 -19
- package/dist/storage/domains/intake/base.js.map +1 -1
- package/dist/storage/domains/projects/base.d.ts.map +1 -1
- package/dist/storage/domains/projects/base.js +19 -10
- package/dist/storage/domains/projects/base.js.map +1 -1
- package/dist/storage/domains/source-control/base.d.ts +8 -0
- package/dist/storage/domains/source-control/base.d.ts.map +1 -1
- package/dist/storage/domains/source-control/base.js +110 -61
- package/dist/storage/domains/source-control/base.js.map +1 -1
- package/dist/storage/domains/source-control/inmemory.d.ts +4 -0
- package/dist/storage/domains/source-control/inmemory.d.ts.map +1 -1
- package/dist/storage/domains/source-control/inmemory.js +8 -5
- package/dist/storage/domains/source-control/inmemory.js.map +1 -1
- package/dist/storage/domains/work-items/base.d.ts +57 -18
- package/dist/storage/domains/work-items/base.d.ts.map +1 -1
- package/dist/storage/domains/work-items/base.js +168 -83
- package/dist/storage/domains/work-items/base.js.map +1 -1
- package/dist/storage/domains/work-items/cards.d.ts +3 -2
- package/dist/storage/domains/work-items/cards.d.ts.map +1 -1
- package/dist/storage/domains/work-items/cards.js +4 -2
- package/dist/storage/domains/work-items/cards.js.map +1 -1
- package/dist/tools/audit-events-tool.d.ts +2 -2
- package/dist/tools/read-tools.d.ts +9 -5
- package/dist/tools/read-tools.d.ts.map +1 -1
- package/dist/tools/read-tools.js +61 -54
- package/dist/tools/read-tools.js.map +1 -1
- package/dist/tools/session-tools.d.ts +0 -13
- package/dist/tools/session-tools.d.ts.map +1 -1
- package/dist/tools/session-tools.js +128 -341
- package/dist/tools/session-tools.js.map +1 -1
- package/dist/tools/work-item-tools.d.ts +3 -0
- package/dist/tools/work-item-tools.d.ts.map +1 -1
- package/dist/tools/work-item-tools.js +99 -27
- package/dist/tools/work-item-tools.js.map +1 -1
- package/dist/work-item-branch.d.ts +4 -0
- package/dist/work-item-branch.d.ts.map +1 -1
- package/dist/work-item-branch.js +7 -1
- package/dist/work-item-branch.js.map +1 -1
- package/dist/work-items/card-context-sessions.d.ts +50 -0
- package/dist/work-items/card-context-sessions.d.ts.map +1 -0
- package/dist/work-items/card-context-sessions.js +84 -0
- package/dist/work-items/card-context-sessions.js.map +1 -0
- package/dist/work-items/card-reference.d.ts +21 -0
- package/dist/work-items/card-reference.d.ts.map +1 -0
- package/dist/work-items/card-reference.js +58 -0
- package/dist/work-items/card-reference.js.map +1 -0
- package/dist/work-items/change-requests.d.ts +87 -0
- package/dist/work-items/change-requests.d.ts.map +1 -0
- package/dist/work-items/change-requests.js +134 -0
- package/dist/work-items/change-requests.js.map +1 -0
- package/dist/work-items/create-work-item.d.ts +7 -2
- package/dist/work-items/create-work-item.d.ts.map +1 -1
- package/dist/work-items/create-work-item.js +44 -13
- package/dist/work-items/create-work-item.js.map +1 -1
- package/dist/work-items/list-related-cards.d.ts.map +1 -1
- package/dist/work-items/list-related-cards.js +1 -1
- package/dist/work-items/list-related-cards.js.map +1 -1
- package/dist/work-items/providers/github.d.ts.map +1 -1
- package/dist/work-items/providers/github.js +1 -0
- package/dist/work-items/providers/github.js.map +1 -1
- package/factory-skills/factory-build/SKILL.md +1 -1
- package/factory-skills/factory-plan/SKILL.md +5 -3
- package/factory-skills/factory-self-review/SKILL.md +2 -0
- package/factory-skills/factory-triage/SKILL.md +1 -1
- package/package.json +10 -10
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { loose } from "../../../routes/route.js";
|
|
2
2
|
import { IssueReconcileWorker } from "../../issue-reconcile-worker.js";
|
|
3
3
|
import { attachVantaRules } from "../../vanta/rules.js";
|
|
4
|
-
import { VANTA_VULNERABILITIES_SOURCE_ID, createVantaSync } from "../../vanta/sync.js";
|
|
4
|
+
import { VANTA_VULNERABILITIES_SOURCE_ID, createVantaSync, vantaVulnerabilitiesSelected } from "../../vanta/sync.js";
|
|
5
5
|
import { PlatformApiClient, platformApiClientConfigFromEnv } from "../api-client.js";
|
|
6
6
|
import { registerApiRoute } from "@mastra/core/server";
|
|
7
7
|
// src/integrations/platform/vanta/integration.ts
|
|
@@ -91,10 +91,10 @@ var PlatformVantaIntegration = class {
|
|
|
91
91
|
connected: async () => (await this.#activeConnections()).length > 0,
|
|
92
92
|
listVulnerabilities: async (orgId) => this.listVulnerabilitiesForOrg(orgId, await projects.listAll()),
|
|
93
93
|
listProjects: () => projects.listAll(),
|
|
94
|
-
intakeEnabled: async (orgId) => (await intake.getConfig({
|
|
94
|
+
intakeEnabled: async (orgId) => vantaVulnerabilitiesSelected((await intake.getConfig({
|
|
95
95
|
orgId,
|
|
96
96
|
integrationIds: [this.id]
|
|
97
|
-
}))[this.id]
|
|
97
|
+
}))[this.id]),
|
|
98
98
|
boundProjectIds: async (orgId) => (await intake.listBindings({
|
|
99
99
|
orgId,
|
|
100
100
|
integrationId: this.id
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration.js","names":[],"sources":["../../../../src/integrations/platform/vanta/integration.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { Intake, IntakeSource } from '../../../capabilities/intake.js';\nimport { loose } from '../../../routes/route.js';\nimport type { FactoryIntegration, IntegrationContext } from '../../base.js';\nimport { IssueReconcileWorker } from '../../issue-reconcile-worker.js';\nimport { attachVantaRules } from '../../vanta/rules.js';\nimport { createVantaSync, DEFAULT_VANTA_SYNC_INTERVAL_MS, VANTA_VULNERABILITIES_SOURCE_ID } from '../../vanta/sync.js';\nimport type { VantaVulnerability } from '../../vanta/sync.js';\nimport { PlatformApiClient, platformApiClientConfigFromEnv } from '../api-client.js';\nimport type { PlatformApiClientConfig } from '../api-client.js';\n\nexport interface PlatformVantaIntegrationConfig {\n clientConfig?: PlatformApiClientConfig;\n syncIntervalMs?: number;\n}\n\n/** Provider key registered for Vanta in Mastra Platform's integrations catalog. */\nconst PLATFORM_VANTA_PROVIDER_KEY = 'vanta';\nconst PAGE_SIZE = 100;\nconst MAX_PAGES = 50;\n\ninterface PlatformIntegrationConnection {\n id: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n resourceId: string | null;\n}\n\ninterface VantaVulnerabilityPage {\n results: {\n data: VantaVulnerability[];\n pageInfo: { endCursor: string | null; hasNextPage: boolean };\n };\n}\n\n/**\n * Files Vanta vulnerabilities as `security`-labeled cards through Platform-managed (MastraConnect)\n * Vanta connections. Vanta has no webhooks Factory can consume, so a worker polls the active list.\n */\nexport class PlatformVantaIntegration implements FactoryIntegration {\n readonly id = 'vanta';\n readonly #client: PlatformApiClient;\n readonly #syncIntervalMs: number;\n\n readonly intake: Intake = {\n listSources: () => this.#listSources(),\n listItems: async () => ({ items: [], nextCursor: null }),\n listIssues: async () => ({ issues: [], nextCursor: null }),\n getIssue: async () => null,\n createComment: async () => null,\n updateIssue: async () => null,\n };\n\n constructor(config: PlatformVantaIntegrationConfig = {}) {\n this.#client = new PlatformApiClient(config.clientConfig ?? platformApiClientConfigFromEnv());\n this.#syncIntervalMs = config.syncIntervalMs ?? DEFAULT_VANTA_SYNC_INTERVAL_MS;\n }\n\n async listConnections(): Promise<PlatformIntegrationConnection[]> {\n const result = await this.#client.request<{ connections: PlatformIntegrationConnection[] }>(\n 'GET',\n `/v2/connections?providerKey=${PLATFORM_VANTA_PROVIDER_KEY}`,\n );\n return result.connections;\n }\n\n async #activeConnections(): Promise<PlatformIntegrationConnection[]> {\n const connections = await this.listConnections();\n return connections.filter(connection => connection.status === 'active').sort((a, b) => a.id.localeCompare(b.id));\n }\n\n async #listSources(): Promise<IntakeSource[]> {\n if ((await this.#activeConnections()).length === 0) return [];\n return [{ id: VANTA_VULNERABILITIES_SOURCE_ID, name: 'Vulnerabilities', type: 'vulnerabilities' }];\n }\n\n /** Every active vulnerability from the supplied connections, de-duplicated by id. */\n async listVulnerabilities(connections?: PlatformIntegrationConnection[]): Promise<VantaVulnerability[]> {\n const selected = connections ?? (await this.listConnections()).sort((a, b) => a.id.localeCompare(b.id));\n if (selected.length === 0) throw new Error('There is no active Vanta connection.');\n const unreadable = selected.find(connection => connection.status !== 'active');\n if (unreadable) throw new Error(`Vanta connection ${unreadable.id} is ${unreadable.status}.`);\n const byId = new Map<string, VantaVulnerability>();\n for (const connection of selected) {\n let cursor: string | null = null;\n for (let page = 0; ; page++) {\n if (page === MAX_PAGES) {\n // A cut-off list would read as the rest being resolved.\n throw new Error(`Vanta connection ${connection.id} has more than ${MAX_PAGES} pages of vulnerabilities.`);\n }\n const query = new URLSearchParams({ isDeactivated: 'false', pageSize: String(PAGE_SIZE) });\n if (cursor) query.set('pageCursor', cursor);\n const result: VantaVulnerabilityPage = await this.#client.request<VantaVulnerabilityPage>(\n 'GET',\n `/v2/connections/${encodeURIComponent(connection.id)}/proxy/v1/vulnerabilities?${query}`,\n );\n for (const vulnerability of result.results.data) byId.set(vulnerability.id, vulnerability);\n if (!result.results.pageInfo.hasNextPage) break;\n if (!result.results.pageInfo.endCursor || page === MAX_PAGES - 1) {\n throw new Error(`Incomplete Vanta vulnerability snapshot for connection ${connection.id}`);\n }\n cursor = result.results.pageInfo.endCursor;\n }\n }\n return [...byId.values()];\n }\n\n async listVulnerabilitiesForOrg(orgId: string, factoryProjects: ReadonlyArray<{ id: string; orgId: string }>): Promise<VantaVulnerability[] | null> {\n const connections = await this.listConnections();\n const ownerByProject = new Map(factoryProjects.map(project => [project.id, project.orgId]));\n // A global or unrecognized connection cannot be attributed safely across organizations.\n if (connections.some(connection => connection.resourceId && !ownerByProject.has(connection.resourceId))) return null;\n if (new Set(factoryProjects.map(project => project.orgId)).size > 1 &&\n connections.some(connection => !connection.resourceId)) return null;\n const owned = connections.filter(connection =>\n connection.resourceId ? ownerByProject.get(connection.resourceId) === orgId : true,\n );\n if (owned.length === 0 || owned.some(connection => connection.status === 'needs_reauth')) return null;\n return this.listVulnerabilities(owned.filter(connection => connection.status === 'active'));\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const ingest = attachVantaRules(ctx);\n if (!ingest) return [];\n const { projects, intake } = ctx.storage;\n const sync = createVantaSync({\n connected: async () => (await this.#activeConnections()).length > 0,\n listVulnerabilities: async orgId => this.listVulnerabilitiesForOrg(orgId, await projects.listAll()),\n listProjects: () => projects.listAll(),\n intakeEnabled: async orgId =>\n (await intake.getConfig({ orgId, integrationIds: [this.id] }))[this.id]?.enabled ?? false,\n boundProjectIds: async orgId =>\n (await intake.listBindings({ orgId, integrationId: this.id })).map(binding => binding.factoryProjectId),\n ingest,\n userId: 'factory-rule-dispatcher',\n });\n return [new IssueReconcileWorker({ integrationId: this.id, reconcile: sync, intervalMs: this.#syncIntervalMs })];\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n return [\n registerApiRoute('/web/vanta/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!ctx.auth.enabled()) return c.json({ enabled: false, configured: true, reason: 'missing_config' });\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) return c.json({ enabled: true, configured: true, reason: 'organization_required' });\n return c.json({ enabled: true, configured: true, reason: 'ready' });\n },\n }),\n ];\n }\n\n diagnostics(): Record<string, unknown> {\n return { configured: true, mode: 'platform' };\n }\n}\n"],"mappings":";;;;;;;;AAoBA,MAAM,8BAA8B;AACpC,MAAM,YAAY;AAClB,MAAM,YAAY;;;;;AAoBlB,IAAa,2BAAb,MAAoE;CAClE,KAAc;CACd;CACA;CAEA,SAA0B;EACxB,mBAAmB,KAAK,aAAa;EACrC,WAAW,aAAa;GAAE,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;IAAQ,CAAC;GACpE;EACF,CAAC,CACH;CACF;CAEA,cAAuC;EACrC,OAAO;GAAE,YAAY;GAAM,MAAM;EAAW;CAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"integration.js","names":[],"sources":["../../../../src/integrations/platform/vanta/integration.ts"],"sourcesContent":["import type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { MastraWorker } from '@mastra/core/worker';\n\nimport type { Intake, IntakeSource } from '../../../capabilities/intake.js';\nimport { loose } from '../../../routes/route.js';\nimport type { FactoryIntegration, IntegrationContext } from '../../base.js';\nimport { IssueReconcileWorker } from '../../issue-reconcile-worker.js';\nimport { attachVantaRules } from '../../vanta/rules.js';\nimport {\n createVantaSync,\n DEFAULT_VANTA_SYNC_INTERVAL_MS,\n VANTA_VULNERABILITIES_SOURCE_ID,\n vantaVulnerabilitiesSelected,\n} from '../../vanta/sync.js';\nimport type { VantaVulnerability } from '../../vanta/sync.js';\nimport { PlatformApiClient, platformApiClientConfigFromEnv } from '../api-client.js';\nimport type { PlatformApiClientConfig } from '../api-client.js';\n\nexport interface PlatformVantaIntegrationConfig {\n clientConfig?: PlatformApiClientConfig;\n syncIntervalMs?: number;\n}\n\n/** Provider key registered for Vanta in Mastra Platform's integrations catalog. */\nconst PLATFORM_VANTA_PROVIDER_KEY = 'vanta';\nconst PAGE_SIZE = 100;\nconst MAX_PAGES = 50;\n\ninterface PlatformIntegrationConnection {\n id: string;\n status: 'active' | 'needs_reauth';\n accountLabel: string | null;\n resourceId: string | null;\n}\n\ninterface VantaVulnerabilityPage {\n results: {\n data: VantaVulnerability[];\n pageInfo: { endCursor: string | null; hasNextPage: boolean };\n };\n}\n\n/**\n * Files Vanta vulnerabilities as `security`-labeled cards through Platform-managed (MastraConnect)\n * Vanta connections. Vanta has no webhooks Factory can consume, so a worker polls the active list.\n */\nexport class PlatformVantaIntegration implements FactoryIntegration {\n readonly id = 'vanta';\n readonly #client: PlatformApiClient;\n readonly #syncIntervalMs: number;\n\n readonly intake: Intake = {\n listSources: () => this.#listSources(),\n listItems: async () => ({ items: [], nextCursor: null }),\n listIssues: async () => ({ issues: [], nextCursor: null }),\n getIssue: async () => null,\n createComment: async () => null,\n updateIssue: async () => null,\n };\n\n constructor(config: PlatformVantaIntegrationConfig = {}) {\n this.#client = new PlatformApiClient(config.clientConfig ?? platformApiClientConfigFromEnv());\n this.#syncIntervalMs = config.syncIntervalMs ?? DEFAULT_VANTA_SYNC_INTERVAL_MS;\n }\n\n async listConnections(): Promise<PlatformIntegrationConnection[]> {\n const result = await this.#client.request<{ connections: PlatformIntegrationConnection[] }>(\n 'GET',\n `/v2/connections?providerKey=${PLATFORM_VANTA_PROVIDER_KEY}`,\n );\n return result.connections;\n }\n\n async #activeConnections(): Promise<PlatformIntegrationConnection[]> {\n const connections = await this.listConnections();\n return connections.filter(connection => connection.status === 'active').sort((a, b) => a.id.localeCompare(b.id));\n }\n\n async #listSources(): Promise<IntakeSource[]> {\n if ((await this.#activeConnections()).length === 0) return [];\n return [{ id: VANTA_VULNERABILITIES_SOURCE_ID, name: 'Vulnerabilities', type: 'vulnerabilities' }];\n }\n\n /** Every active vulnerability from the supplied connections, de-duplicated by id. */\n async listVulnerabilities(connections?: PlatformIntegrationConnection[]): Promise<VantaVulnerability[]> {\n const selected = connections ?? (await this.listConnections()).sort((a, b) => a.id.localeCompare(b.id));\n if (selected.length === 0) throw new Error('There is no active Vanta connection.');\n const unreadable = selected.find(connection => connection.status !== 'active');\n if (unreadable) throw new Error(`Vanta connection ${unreadable.id} is ${unreadable.status}.`);\n const byId = new Map<string, VantaVulnerability>();\n for (const connection of selected) {\n let cursor: string | null = null;\n for (let page = 0; ; page++) {\n if (page === MAX_PAGES) {\n // A cut-off list would read as the rest being resolved.\n throw new Error(`Vanta connection ${connection.id} has more than ${MAX_PAGES} pages of vulnerabilities.`);\n }\n const query = new URLSearchParams({ isDeactivated: 'false', pageSize: String(PAGE_SIZE) });\n if (cursor) query.set('pageCursor', cursor);\n const result: VantaVulnerabilityPage = await this.#client.request<VantaVulnerabilityPage>(\n 'GET',\n `/v2/connections/${encodeURIComponent(connection.id)}/proxy/v1/vulnerabilities?${query}`,\n );\n for (const vulnerability of result.results.data) byId.set(vulnerability.id, vulnerability);\n if (!result.results.pageInfo.hasNextPage) break;\n if (!result.results.pageInfo.endCursor || page === MAX_PAGES - 1) {\n throw new Error(`Incomplete Vanta vulnerability snapshot for connection ${connection.id}`);\n }\n cursor = result.results.pageInfo.endCursor;\n }\n }\n return [...byId.values()];\n }\n\n async listVulnerabilitiesForOrg(orgId: string, factoryProjects: ReadonlyArray<{ id: string; orgId: string }>): Promise<VantaVulnerability[] | null> {\n const connections = await this.listConnections();\n const ownerByProject = new Map(factoryProjects.map(project => [project.id, project.orgId]));\n // A global or unrecognized connection cannot be attributed safely across organizations.\n if (connections.some(connection => connection.resourceId && !ownerByProject.has(connection.resourceId))) return null;\n if (new Set(factoryProjects.map(project => project.orgId)).size > 1 &&\n connections.some(connection => !connection.resourceId)) return null;\n const owned = connections.filter(connection =>\n connection.resourceId ? ownerByProject.get(connection.resourceId) === orgId : true,\n );\n if (owned.length === 0 || owned.some(connection => connection.status === 'needs_reauth')) return null;\n return this.listVulnerabilities(owned.filter(connection => connection.status === 'active'));\n }\n\n workers(ctx: IntegrationContext): MastraWorker[] {\n const ingest = attachVantaRules(ctx);\n if (!ingest) return [];\n const { projects, intake } = ctx.storage;\n const sync = createVantaSync({\n connected: async () => (await this.#activeConnections()).length > 0,\n listVulnerabilities: async orgId => this.listVulnerabilitiesForOrg(orgId, await projects.listAll()),\n listProjects: () => projects.listAll(),\n intakeEnabled: async orgId =>\n vantaVulnerabilitiesSelected((await intake.getConfig({ orgId, integrationIds: [this.id] }))[this.id]),\n boundProjectIds: async orgId =>\n (await intake.listBindings({ orgId, integrationId: this.id })).map(binding => binding.factoryProjectId),\n ingest,\n userId: 'factory-rule-dispatcher',\n });\n return [new IssueReconcileWorker({ integrationId: this.id, reconcile: sync, intervalMs: this.#syncIntervalMs })];\n }\n\n routes(ctx: IntegrationContext): ApiRoute[] {\n return [\n registerApiRoute('/web/vanta/status', {\n method: 'GET',\n requiresAuth: false,\n handler: async c => {\n if (!ctx.auth.enabled()) return c.json({ enabled: false, configured: true, reason: 'missing_config' });\n await ctx.auth.ensureUser(loose(c));\n const tenant = ctx.auth.tenant(loose(c));\n if (!tenant) return c.json({ error: 'unauthorized', reason: 'auth_required' }, 401);\n if (!tenant.orgId) return c.json({ enabled: true, configured: true, reason: 'organization_required' });\n return c.json({ enabled: true, configured: true, reason: 'ready' });\n },\n }),\n ];\n }\n\n diagnostics(): Record<string, unknown> {\n return { configured: true, mode: 'platform' };\n }\n}\n"],"mappings":";;;;;;;;AAyBA,MAAM,8BAA8B;AACpC,MAAM,YAAY;AAClB,MAAM,YAAY;;;;;AAoBlB,IAAa,2BAAb,MAAoE;CAClE,KAAc;CACd;CACA;CAEA,SAA0B;EACxB,mBAAmB,KAAK,aAAa;EACrC,WAAW,aAAa;GAAE,OAAO,CAAC;GAAG,YAAY;EAAK;EACtD,YAAY,aAAa;GAAE,QAAQ,CAAC;GAAG,YAAY;EAAK;EACxD,UAAU,YAAY;EACtB,eAAe,YAAY;EAC3B,aAAa,YAAY;CAC3B;CAEA,YAAY,SAAyC,CAAC,GAAG;EACvD,KAAK,UAAU,IAAI,kBAAkB,OAAO,gBAAgB,+BAA+B,CAAC;EAC5F,KAAK,kBAAkB,OAAO,kBAAA;CAChC;CAEA,MAAM,kBAA4D;EAKhE,QAAO,MAJc,KAAK,QAAQ,QAChC,OACA,+BAA+B,6BACjC,EAAA,CACc;CAChB;CAEA,MAAM,qBAA+D;EAEnE,QAAO,MADmB,KAAK,gBAAgB,EAAA,CAC5B,QAAO,eAAc,WAAW,WAAW,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,cAAc,EAAE,EAAE,CAAC;CACjH;CAEA,MAAM,eAAwC;EAC5C,KAAK,MAAM,KAAK,m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AE,eAAe,KAAK;GAAI,WAAW;GAAM,YAAY,KAAK;EAAgB,CAAC,CAAC;CACjH;CAEA,OAAO,KAAqC;EAC1C,OAAO,CACL,iBAAiB,qBAAqB;GACpC,QAAQ;GACR,cAAc;GACd,SAAS,OAAM,MAAK;IAClB,IAAI,CAAC,IAAI,KAAK,QAAQ,GAAG,OAAO,EAAE,KAAK;KAAE,SAAS;KAAO,YAAY;KAAM,QAAQ;IAAiB,CAAC;IACrG,MAAM,IAAI,KAAK,WAAW,MAAM,CAAC,CAAC;IAClC,MAAM,SAAS,IAAI,KAAK,OAAO,MAAM,CAAC,CAAC;IACvC,IAAI,CAAC,QAAQ,OAAO,EAAE,KAAK;KAAE,OAAO;KAAgB,QAAQ;IAAgB,GAAG,GAAG;IAClF,IAAI,CAAC,OAAO,OAAO,OAAO,EAAE,KAAK;KAAE,SAAS;KAAM,YAAY;KAAM,QAAQ;IAAwB,CAAC;IACrG,OAAO,EAAE,KAAK;KAAE,SAAS;KAAM,YAAY;KAAM,QAAQ;IAAQ,CAAC;GACpE;EACF,CAAC,CACH;CACF;CAEA,cAAuC;EACrC,OAAO;GAAE,YAAY;GAAM,MAAM;EAAW;CAC9C;AACF"}
|
|
@@ -13,7 +13,7 @@ export declare function recordPullRequestHead(storage: WorkItemsStorage, input:
|
|
|
13
13
|
headSha: string;
|
|
14
14
|
headAt: number | undefined;
|
|
15
15
|
deliveryId?: string;
|
|
16
|
-
/** Only write while the card
|
|
16
|
+
/** Only write while this is the card's pull request: the one it has out, or its working one. */
|
|
17
17
|
ownedPullRequestNumber?: number;
|
|
18
18
|
}): Promise<void>;
|
|
19
19
|
//# sourceMappingURL=pull-request-head.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pull-request-head.d.ts","sourceRoot":"","sources":["../../src/integrations/pull-request-head.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;
|
|
1
|
+
{"version":3,"file":"pull-request-head.d.ts","sourceRoot":"","sources":["../../src/integrations/pull-request-head.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,uCAAuC,CAAC;AAG9E;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,OAAO,EAAE,gBAAgB,EACzB,KAAK,EAAE;IACL,KAAK,EAAE,MAAM,CAAC;IACd,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC;IAC3B,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,gGAAgG;IAChG,sBAAsB,CAAC,EAAE,MAAM,CAAC;CACjC,GACA,OAAO,CAAC,IAAI,CAAC,CAyCf"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { WorkItemUpdateConflictError } from "../storage/domains/work-items/base.js";
|
|
2
|
+
import { pullRequestSourceNumber, pullRequestSources, workingPullRequest } from "../work-items/change-requests.js";
|
|
2
3
|
// src/integrations/pull-request-head.ts
|
|
3
4
|
/**
|
|
4
5
|
* Records the head a pull request or merge request was observed at, so a
|
|
@@ -19,6 +20,10 @@ async function recordPullRequestHead(storage, input) {
|
|
|
19
20
|
if (input.ownedPullRequestNumber !== void 0) {
|
|
20
21
|
const recorded = card.metadata?.openPullRequestNumber;
|
|
21
22
|
if (typeof recorded === "number" && recorded !== input.ownedPullRequestNumber) return;
|
|
23
|
+
if (typeof recorded !== "number" && pullRequestSources(card).length > 0) {
|
|
24
|
+
const working = workingPullRequest(card);
|
|
25
|
+
if (!working || pullRequestSourceNumber(working) !== input.ownedPullRequestNumber) return;
|
|
26
|
+
}
|
|
22
27
|
}
|
|
23
28
|
const recordedAt = card.metadata?.pullRequestHeadAt;
|
|
24
29
|
if (typeof recordedAt === "number" && recordedAt >= input.headAt) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pull-request-head.js","names":[],"sources":["../../src/integrations/pull-request-head.ts"],"sourcesContent":["import { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\n\n/**\n * Records the head a pull request or merge request was observed at, so a\n * review verdict given on an earlier head can be shown as outdated. Webhooks\n * arrive out of order and get redelivered, so a write only lands when its\n * event is newer than the one the card last recorded; an event without a\n * timestamp cannot be ordered and is dropped. The check and the write run\n * against the same revision, so a concurrent delivery cannot slip between them.\n */\nexport async function recordPullRequestHead(\n storage: WorkItemsStorage,\n input: {\n orgId: string;\n id: string;\n headSha: string;\n headAt: number | undefined;\n deliveryId?: string;\n /** Only write while the card
|
|
1
|
+
{"version":3,"file":"pull-request-head.js","names":[],"sources":["../../src/integrations/pull-request-head.ts"],"sourcesContent":["import { WorkItemUpdateConflictError } from '../storage/domains/work-items/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { pullRequestSourceNumber, pullRequestSources, workingPullRequest } from '../work-items/change-requests.js';\n\n/**\n * Records the head a pull request or merge request was observed at, so a\n * review verdict given on an earlier head can be shown as outdated. Webhooks\n * arrive out of order and get redelivered, so a write only lands when its\n * event is newer than the one the card last recorded; an event without a\n * timestamp cannot be ordered and is dropped. The check and the write run\n * against the same revision, so a concurrent delivery cannot slip between them.\n */\nexport async function recordPullRequestHead(\n storage: WorkItemsStorage,\n input: {\n orgId: string;\n id: string;\n headSha: string;\n headAt: number | undefined;\n deliveryId?: string;\n /** Only write while this is the card's pull request: the one it has out, or its working one. */\n ownedPullRequestNumber?: number;\n },\n): Promise<void> {\n if (input.headAt === undefined) return;\n for (let attempt = 0; attempt < 3; attempt++) {\n const card = await storage.get({ orgId: input.orgId, id: input.id });\n if (!card) return;\n if (input.ownedPullRequestNumber !== undefined) {\n const recorded = card.metadata?.openPullRequestNumber;\n if (typeof recorded === 'number' && recorded !== input.ownedPullRequestNumber) return;\n // With no pointer, an issue's card with pull requests linked records only its working one's\n // head: an outsider's push never becomes the head a review covers until a person picks it.\n if (typeof recorded !== 'number' && pullRequestSources(card).length > 0) {\n const working = workingPullRequest(card);\n if (!working || pullRequestSourceNumber(working) !== input.ownedPullRequestNumber) return;\n }\n }\n const recordedAt = card.metadata?.pullRequestHeadAt;\n if (typeof recordedAt === 'number' && recordedAt >= input.headAt) return;\n try {\n // The time advances even when the head is unchanged: a head that returns\n // to an earlier commit must still beat a late event for the one between.\n await storage.update({\n orgId: card.orgId,\n id: card.id,\n userId: 'factory-rule-dispatcher',\n expectedRevision: card.revision,\n patch: {\n metadata: {\n pullRequestHeadSha: input.headSha,\n pullRequestHeadAt: input.headAt,\n pullRequestHeadDeliveryId:\n card.metadata?.pullRequestHeadSha === input.headSha\n ? (card.metadata?.pullRequestHeadDeliveryId ?? null)\n : (input.deliveryId ?? null),\n },\n },\n });\n return;\n } catch (error) {\n if (!(error instanceof WorkItemUpdateConflictError)) throw error;\n }\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,eAAsB,sBACpB,SACA,OASe;CACf,IAAI,MAAM,WAAW,KAAA,GAAW;CAChC,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW;EAC5C,MAAM,OAAO,MAAM,QAAQ,IAAI;GAAE,OAAO,MAAM;GAAO,IAAI,MAAM;EAAG,CAAC;EACnE,IAAI,CAAC,MAAM;EACX,IAAI,MAAM,2BAA2B,KAAA,GAAW;GAC9C,MAAM,WAAW,KAAK,UAAU;GAChC,IAAI,OAAO,aAAa,YAAY,aAAa,MAAM,wBAAwB;GAG/E,IAAI,OAAO,aAAa,YAAY,mBAAmB,IAAI,CAAC,CAAC,SAAS,GAAG;IACvE,MAAM,UAAU,mBAAmB,IAAI;IACvC,IAAI,CAAC,WAAW,wBAAwB,OAAO,MAAM,MAAM,wBAAwB;GACrF;EACF;EACA,MAAM,aAAa,KAAK,UAAU;EAClC,IAAI,OAAO,eAAe,YAAY,cAAc,MAAM,QAAQ;EAClE,IAAI;GAGF,MAAM,QAAQ,OAAO;IACnB,OAAO,KAAK;IACZ,IAAI,KAAK;IACT,QAAQ;IACR,kBAAkB,KAAK;IACvB,OAAO,EACL,UAAU;KACR,oBAAoB,MAAM;KAC1B,mBAAmB,MAAM;KACzB,2BACE,KAAK,UAAU,uBAAuB,MAAM,UACvC,KAAK,UAAU,6BAA6B,OAC5C,MAAM,cAAc;IAC7B,EACF;GACF,CAAC;GACD;EACF,SAAS,OAAO;GACd,IAAI,EAAE,iBAAiB,8BAA8B,MAAM;EAC7D;CACF;AACF"}
|
|
@@ -21,7 +21,7 @@ function boardEventFor(context) {
|
|
|
21
21
|
type: "work_item.closed",
|
|
22
22
|
reason: closeReason(false)
|
|
23
23
|
};
|
|
24
|
-
return context.item ? void 0 : { type: "work_item.
|
|
24
|
+
return context.item ? void 0 : { type: "work_item.opened" };
|
|
25
25
|
}
|
|
26
26
|
/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */
|
|
27
27
|
function resolvedFromCard(sourceKey, item) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/vanta/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { routeEventDecision } from '../../rules/event-rules.js';\nimport type { FactoryVantaRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { defaultVantaRules } from './default-rules.js';\nimport type { VantaEventRules } from './default-rules.js';\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\n/** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */\nexport function vantaLabels(severity: string | null): string[] {\n return ['security', 'vanta', ...(severity ? [`severity:${severity.toLowerCase()}`] : [])];\n}\n\nexport type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];\n\nexport interface VantaRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry | ProjectBoardSource;\n rules?: VantaEventRules;\n}\n\nexport interface VantaRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */\n vulnerabilities: VantaVulnerabilityIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */\nexport function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'vulnerabilityClosed') {\n return { type: 'work_item.closed', reason: closeReason(false) };\n }\n return context.item ? undefined : { type: 'work_item.created' };\n}\n\n/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */\nfunction resolvedFromCard(sourceKey: string, item: Card): VantaVulnerabilityIngress {\n const metadata = item.metadata ?? {};\n const text = (key: string) => (typeof metadata[key] === 'string' ? (metadata[key] as string) : null);\n return {\n id: sourceKey,\n name: text('identifier') ?? sourceKey,\n title: item.title,\n description: null,\n url: item.externalSource?.url ?? null,\n state: 'resolved',\n severity: text('severity'),\n packageIdentifier: text('packageIdentifier'),\n fixable: null,\n remediateBy: text('remediateBy'),\n labels: [],\n createdAt: text('sourceCreatedAt') ?? new Date(0).toISOString(),\n };\n}\n\nexport class VantaRules {\n readonly #rules: VantaEventRules;\n\n constructor(private readonly options: VantaRulesOptions) {\n this.#rules = options.rules ?? defaultVantaRules;\n }\n\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: VantaRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(\n items\n .filter(item => item.externalSource?.integrationId === 'vanta' && item.externalSource.type === 'vulnerability')\n .map(item => [item.externalSource?.externalId, item]),\n );\n const statuses: IngressStatus[] = [];\n const active = new Set(input.vulnerabilities.map(vulnerability => vulnerability.id));\n for (const vulnerability of input.vulnerabilities) {\n const relatedItem = itemsBySourceKey.get(vulnerability.id);\n statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));\n }\n for (const [sourceKey, item] of itemsBySourceKey) {\n if (!sourceKey || active.has(sourceKey) || item.metadata?.state === 'resolved') continue;\n statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));\n }\n if (statuses.includes('committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.includes('replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestAlert(\n input: VantaRulesIngress,\n alert: VantaVulnerabilityIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const closed = alert.state === 'resolved';\n // A resolved vulnerability Factory never filed stays off the board.\n if (closed && !relatedItem) return 'missing';\n\n const ingressId = `vanta:${alert.id}:${alert.state}`;\n const actor = { type: 'human' as const, id: input.userId };\n const event = closed ? 'vulnerabilityClosed' : 'vulnerabilityObserved';\n const boards = this.#boards(input);\n const context: FactoryVantaRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'vanta', id: ingressId },\n cause: `vanta.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'vanta-vulnerability',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(boards, relatedItem),\n ...rulePhaseField(boards, relatedItem),\n }\n : {}),\n ...withIntakeTarget(boards),\n event,\n vulnerability: alert,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const rule = this.#rules[event];\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await rule(Object.freeze(context)) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : undefined);\n return { ...entry };\n });\n }\n } catch (error) {\n outcome = {\n status: 'rejected',\n code: 'rule_error',\n reason: error instanceof Error ? error.message.slice(0, 2_000) : 'Factory Vanta rule failed.',\n };\n }\n if (!decision && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestAlert(input, alert, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachVantaRules(\n context: IntegrationContext,\n): ((input: VantaRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new VantaRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,0BAA0B;;AAGhC,SAAgB,YAAY,UAAmC;CAC7D,OAAO;EAAC;EAAY;EAAS,GAAI,WAAW,CAAC,YAAY,SAAS,YAAY,GAAG,IAAI,CAAC;CAAE;AAC1F;;AAuBA,SAAgB,cAAc,SAAuF;CACnH,IAAI,QAAQ,UAAU,uBACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,KAAK;CAAE;CAEhE,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,oBAAoB;AAChE;;AAGA,SAAS,iBAAiB,WAAmB,MAAuC;CAClF,MAAM,WAAW,KAAK,YAAY,CAAC;CACnC,MAAM,QAAQ,QAAiB,OAAO,SAAS,SAAS,WAAY,SAAS,OAAkB;CAC/F,OAAO;EACL,IAAI;EACJ,MAAM,KAAK,YAAY,KAAK;EAC5B,OAAO,KAAK;EACZ,aAAa;EACb,KAAK,KAAK,gBAAgB,OAAO;EACjC,OAAO;EACP,UAAU,KAAK,UAAU;EACzB,mBAAmB,KAAK,mBAAmB;EAC3C,SAAS;EACT,aAAa,KAAK,aAAa;EAC/B,QAAQ,CAAC;EACT,WAAW,KAAK,iBAAiB,sBAAK,IAAI,KAAK,CAAC,EAAA,C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AClC,OAAO,KAAK,aAAa,OAAO,OAAO,SAAS,KAAA,GAAW,UAAU,CAAC;EACxE;EACA,OAAO,UAAU;CACnB;AACF;AAEA,SAAgB,iBACd,SAC8D;CAC9D,IAAI,CAAC,QAAQ,SAAS,OAAO,KAAA;CAC7B,MAAM,QAAQ,IAAI,WAAW;EAC3B,UAAU,QAAQ,QAAQ;EAC1B,SAAS,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;CAC1B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
|
|
1
|
+
{"version":3,"file":"rules.js","names":[],"sources":["../../../src/integrations/vanta/rules.ts"],"sourcesContent":["import { closeReason } from '../../boards/board-events.js';\nimport type { BoardEventFacts } from '../../boards/board-events.js';\nimport { boardForWorkItem, rulePhaseField, withBoardClosure, withIntakeTarget } from '../../boards/index.js';\nimport type { BoardRegistry } from '../../boards/index.js';\nimport { toBoardSource } from '../../boards/project-boards.js';\nimport type { ProjectBoardSource } from '../../boards/project-boards.js';\nimport { routeEventDecision } from '../../rules/event-rules.js';\nimport type { FactoryVantaRuleContext, FactoryRuleDecision } from '../../rules/types.js';\nimport { assertFactoryDecisionTarget, validateFactoryRuleDecisions } from '../../rules/validation.js';\nimport type { StoredBoardScope } from '../../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../../storage/domains/projects/base.js';\nimport type { Card, WorkItemsStorage } from '../../storage/domains/work-items/base.js';\nimport type { IntegrationContext } from '../base.js';\nimport { defaultVantaRules } from './default-rules.js';\nimport type { VantaEventRules } from './default-rules.js';\n\nconst MAX_STALE_RULE_ATTEMPTS = 3;\n\n/** Labels every Vanta card carries, so the Security intake route matches them like any `security`-labeled issue. */\nexport function vantaLabels(severity: string | null): string[] {\n return ['security', 'vanta', ...(severity ? [`severity:${severity.toLowerCase()}`] : [])];\n}\n\nexport type VantaVulnerabilityIngress = FactoryVantaRuleContext['vulnerability'];\n\nexport interface VantaRulesOptions {\n projects: Pick<FactoryProjectsStorage, 'get'>;\n storage: WorkItemsStorage;\n configVersion: string;\n boards: BoardRegistry | ProjectBoardSource;\n rules?: VantaEventRules;\n}\n\nexport interface VantaRulesIngress {\n orgId: string;\n userId: string;\n factoryProjectId: string;\n /** Every vulnerability Vanta currently lists as active. Open cards missing from it are closed. */\n vulnerabilities: VantaVulnerabilityIngress[];\n}\n\ntype IngressStatus = 'committed' | 'replayed' | 'missing';\n\n/** A first sighting of an active vulnerability creates its card; dropping off Vanta's active list closes it. */\nexport function boardEventFor(context: Pick<FactoryVantaRuleContext, 'event' | 'item'>): BoardEventFacts | undefined {\n if (context.event === 'vulnerabilityClosed') {\n return { type: 'work_item.closed', reason: closeReason(false) };\n }\n return context.item ? undefined : { type: 'work_item.opened' };\n}\n\n/** The closing ingress for a card whose vulnerability Vanta stopped listing, rebuilt from the card. */\nfunction resolvedFromCard(sourceKey: string, item: Card): VantaVulnerabilityIngress {\n const metadata = item.metadata ?? {};\n const text = (key: string) => (typeof metadata[key] === 'string' ? (metadata[key] as string) : null);\n return {\n id: sourceKey,\n name: text('identifier') ?? sourceKey,\n title: item.title,\n description: null,\n url: item.externalSource?.url ?? null,\n state: 'resolved',\n severity: text('severity'),\n packageIdentifier: text('packageIdentifier'),\n fixable: null,\n remediateBy: text('remediateBy'),\n labels: [],\n createdAt: text('sourceCreatedAt') ?? new Date(0).toISOString(),\n };\n}\n\nexport class VantaRules {\n readonly #rules: VantaEventRules;\n\n constructor(private readonly options: VantaRulesOptions) {\n this.#rules = options.rules ?? defaultVantaRules;\n }\n\n #boards(scope: StoredBoardScope): BoardRegistry {\n return toBoardSource(this.options.boards).forProject(scope);\n }\n\n async ingest(input: VantaRulesIngress): Promise<{ status: IngressStatus; ingested: number }> {\n const project = await this.options.projects.get({ orgId: input.orgId, id: input.factoryProjectId });\n if (!project) return { status: 'missing', ingested: 0 };\n await toBoardSource(this.options.boards).load(input);\n\n const items = await this.options.storage.listShared({ orgId: input.orgId, factoryProjectId: input.factoryProjectId });\n const itemsBySourceKey = new Map(\n items\n .filter(item => item.externalSource?.integrationId === 'vanta' && item.externalSource.type === 'vulnerability')\n .map(item => [item.externalSource?.externalId, item]),\n );\n const statuses: IngressStatus[] = [];\n const active = new Set(input.vulnerabilities.map(vulnerability => vulnerability.id));\n for (const vulnerability of input.vulnerabilities) {\n const relatedItem = itemsBySourceKey.get(vulnerability.id);\n statuses.push(await this.#ingestAlert(input, vulnerability, relatedItem && structuredClone(relatedItem)));\n }\n for (const [sourceKey, item] of itemsBySourceKey) {\n if (!sourceKey || active.has(sourceKey) || item.metadata?.state === 'resolved') continue;\n statuses.push(await this.#ingestAlert(input, resolvedFromCard(sourceKey, item), structuredClone(item)));\n }\n if (statuses.includes('committed')) return { status: 'committed', ingested: statuses.length };\n if (statuses.includes('replayed')) return { status: 'replayed', ingested: statuses.length };\n return { status: 'missing', ingested: statuses.length };\n }\n\n async #ingestAlert(\n input: VantaRulesIngress,\n alert: VantaVulnerabilityIngress,\n relatedItem: Card | undefined,\n attempt = 1,\n ): Promise<IngressStatus> {\n const closed = alert.state === 'resolved';\n // A resolved vulnerability Factory never filed stays off the board.\n if (closed && !relatedItem) return 'missing';\n\n const ingressId = `vanta:${alert.id}:${alert.state}`;\n const actor = { type: 'human' as const, id: input.userId };\n const event = closed ? 'vulnerabilityClosed' : 'vulnerabilityObserved';\n const boards = this.#boards(input);\n const context: FactoryVantaRuleContext = {\n tenant: { orgId: input.orgId, projectId: input.factoryProjectId },\n actor,\n ingress: { type: 'vanta', id: ingressId },\n cause: `vanta.${event}`,\n causalChain: [],\n configVersion: this.options.configVersion,\n ...(relatedItem\n ? {\n item: {\n id: relatedItem.id,\n source: 'vanta-vulnerability',\n sourceKey: relatedItem.externalSource?.externalId ?? null,\n parentWorkItemId: relatedItem.parentWorkItemId,\n title: relatedItem.title,\n url: relatedItem.externalSource?.url ?? null,\n stages: relatedItem.stages,\n workItem: relatedItem.workItem,\n acceptedAt: relatedItem.acceptedAt,\n metadata: relatedItem.metadata,\n },\n board: boardForWorkItem(relatedItem),\n itemRevision: relatedItem.revision,\n ...withBoardClosure(boards, relatedItem),\n ...rulePhaseField(boards, relatedItem),\n }\n : {}),\n ...withIntakeTarget(boards),\n event,\n vulnerability: alert,\n };\n const boardEvent = boardEventFor(context);\n if (boardEvent) context.boardEvent = boardEvent;\n\n const rule = this.#rules[event];\n let decision: FactoryRuleDecision | void = undefined;\n let decisions: Record<string, unknown>[] = [];\n let outcome: { status: 'accepted' | 'rejected'; code?: string; reason?: string } = { status: 'accepted' };\n try {\n decision = rule ? await rule(Object.freeze(context)) : undefined;\n if (decision?.type === 'reject') {\n outcome = { status: 'rejected', code: decision.code, reason: decision.reason };\n } else if (decision) {\n decisions = validateFactoryRuleDecisions([decision]).map(entry => {\n assertFactoryDecisionTarget(entry, boards, relatedItem ? boardForWorkItem(relatedItem) : undefined);\n return { ...entry };\n });\n }\n } catch (error) {\n outcome = {\n status: 'rejected',\n code: 'rule_error',\n reason: error instanceof Error ? error.message.slice(0, 2_000) : 'Factory Vanta rule failed.',\n };\n }\n if (!decision && outcome.status === 'accepted') {\n const routed = await routeEventDecision(context, this.options.storage, {\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n });\n if (routed) decisions = [{ ...routed }];\n }\n\n const committed = await this.options.storage.commitRuleEvaluation({\n orgId: input.orgId,\n factoryProjectId: input.factoryProjectId,\n workItemId: relatedItem?.id ?? null,\n ingress: { identity: ingressId },\n expectedRevision: relatedItem?.revision ?? null,\n actor,\n outcome,\n decisions,\n causalChain: [],\n now: new Date(),\n });\n if (committed.status === 'stale') {\n if (attempt >= MAX_STALE_RULE_ATTEMPTS) {\n throw new Error(`Factory Vanta rule evaluation for ${ingressId} kept losing revision races.`);\n }\n const fresh = relatedItem ? await this.options.storage.get({ orgId: input.orgId, id: relatedItem.id }) : null;\n if (relatedItem && !fresh) return 'missing';\n return this.#ingestAlert(input, alert, fresh ?? undefined, attempt + 1);\n }\n return committed.status;\n }\n}\n\nexport function attachVantaRules(\n context: IntegrationContext,\n): ((input: VantaRulesIngress) => Promise<unknown>) | undefined {\n if (!context.runtime) return undefined;\n const rules = new VantaRules({\n projects: context.storage.projects,\n storage: context.runtime.workItems,\n configVersion: context.runtime.configVersion,\n boards: context.runtime.boards,\n });\n return input => rules.ingest(input);\n}\n"],"mappings":";;;;;;;;AAgBA,MAAM,0BAA0B;;AAGhC,SAAgB,YAAY,UAAmC;CAC7D,OAAO;EAAC;EAAY;EAAS,GAAI,WAAW,CAAC,YAAY,SAAS,YAAY,GAAG,IAAI,CAAC;CAAE;AAC1F;;AAuBA,SAAgB,cAAc,SAAuF;CACnH,IAAI,QAAQ,UAAU,uBACpB,OAAO;EAAE,MAAM;EAAoB,QAAQ,YAAY,KAAK;CAAE;CAEhE,OAAO,QAAQ,OAAO,KAAA,IAAY,EAAE,MAAM,mBAAmB;AAC/D;;AAGA,SAAS,iBAAiB,WAAmB,MAAuC;CAClF,MAAM,WAAW,KAAK,YAAY,CAAC;CACnC,MAAM,QAAQ,QAAiB,OAAO,SAAS,SAAS,WAAY,SAAS,OAAkB;CAC/F,OAAO;EACL,IAAI;EACJ,MAAM,KAAK,YAAY,KAAK;EAC5B,OAAO,KAAK;EACZ,aAAa;EACb,KAAK,KAAK,gBAAgB,OAAO;EACjC,OAAO;EACP,UAAU,KAAK,UAAU;EACzB,mBAAmB,KAAK,mBAAmB;EAC3C,SAAS;EACT,aAAa,KAAK,aAAa;EAC/B,QAAQ,CAAC;EACT,WAAW,KAAK,iBAAiB,sBAAK,IAAI,KAAK,CAAC,EAAA,CAAE,YAAY;CAChE;AACF;AAEA,IAAa,aAAb,MAAwB;CAGO;CAF7B;CAEA,YAAY,SAA6C;EAA5B,KAAA,UAAA;EAC3B,KAAK,SAAS,QAAQ,SAAS;CACjC;CAEA,QAAQ,OAAwC;EAC9C,OAAO,cAAc,KAAK,QAAQ,MAAM,CAAC,CAAC,WAAW,KAAK;CAC5D;CAEA,MAAM,O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S,QAAQ,QAAQ;EACzB,eAAe,QAAQ,QAAQ;EAC/B,QAAQ,QAAQ,QAAQ;CAC1B,CAAC;CACD,QAAO,UAAS,MAAM,OAAO,KAAK;AACpC"}
|
|
@@ -1,6 +1,15 @@
|
|
|
1
|
+
import type { IntakeConfig, IntakeSelection } from '../../storage/domains/intake/base.js';
|
|
1
2
|
import type { IssueReconcileSummary } from '../issue-reconciler.js';
|
|
2
3
|
import type { VantaRulesIngress, VantaVulnerabilityIngress } from './rules.js';
|
|
3
4
|
export declare const VANTA_VULNERABILITIES_SOURCE_ID = "vanta:vulnerabilities";
|
|
5
|
+
export declare const SELECT_VANTA_VULNERABILITIES_MIGRATION = "select_vanta_vulnerabilities_where_sync_was_on";
|
|
6
|
+
/** Vulnerabilities sync only once selected in Work Intake, like every other source. */
|
|
7
|
+
export declare function vantaVulnerabilitiesSelected(selection: IntakeSelection | undefined): boolean;
|
|
8
|
+
/** Orgs whose old sync switch was on with nothing selected, so selecting vulnerabilities keeps them syncing. */
|
|
9
|
+
export declare function vantaOrgsSyncingWithoutSource(configs: ReadonlyArray<{
|
|
10
|
+
orgId: string;
|
|
11
|
+
config: IntakeConfig;
|
|
12
|
+
}>): Map<string, string[]>;
|
|
4
13
|
export declare const DEFAULT_VANTA_SYNC_INTERVAL_MS: number;
|
|
5
14
|
/** The subset of Vanta's `GET /v1/vulnerabilities` item Factory reads. */
|
|
6
15
|
export interface VantaVulnerability {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.d.ts","sourceRoot":"","sources":["../../../src/integrations/vanta/sync.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AAEpE,OAAO,KAAK,EAAE,iBAAiB,EAAE,yBAAyB,EAAE,MAAM,YAAY,CAAC;AAE/E,eAAO,MAAM,+BAA+B,0BAA0B,CAAC;AACvE,eAAO,MAAM,8BAA8B,QAAc,CAAC;AAE1D,0EAA0E;AAC1E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M,KAAK,OAAO,CAAC,kBAAkB,EAAE,GAAG,IAAI,CAAC,CAAC;AAE/F,wBAAgB,cAAc,CAAC,aAAa,EAAE,kBAAkB,GAAG,yBAAyB,CAkB3F;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE;IACvC;;;OAGG;IACH,SAAS,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAC;IAClC,mBAAmB,EAAE,wBAAwB,CAAC;IAC9C,YAAY,EAAE,MAAM,OAAO,CAAC,aAAa,CAAC;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,EAAE,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC,CAAC;IAC1E,aAAa,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACnD,eAAe,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACtD,MAAM,EAAE,CAAC,KAAK,EAAE,iBAAiB,KAAK,OAAO,CAAC,OAAO,CAAC,CAAC;IACvD,MAAM,EAAE,MAAM,CAAC;CAChB,GAAG,MAAM,OAAO,CAAC,qBAAqB,CAAC,CAkDvC"}
|
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import { vantaLabels } from "./rules.js";
|
|
2
2
|
// src/integrations/vanta/sync.ts
|
|
3
3
|
const VANTA_VULNERABILITIES_SOURCE_ID = "vanta:vulnerabilities";
|
|
4
|
+
const SELECT_VANTA_VULNERABILITIES_MIGRATION = "select_vanta_vulnerabilities_where_sync_was_on";
|
|
5
|
+
/** Vulnerabilities sync only once selected in Work Intake, like every other source. */
|
|
6
|
+
function vantaVulnerabilitiesSelected(selection) {
|
|
7
|
+
return Boolean(selection?.enabled && selection.sourceIds?.includes("vanta:vulnerabilities"));
|
|
8
|
+
}
|
|
9
|
+
/** Orgs whose old sync switch was on with nothing selected, so selecting vulnerabilities keeps them syncing. */
|
|
10
|
+
function vantaOrgsSyncingWithoutSource(configs) {
|
|
11
|
+
return new Map(configs.filter(({ config }) => config.vanta?.enabled && !config.vanta.sourceIds?.length).map(({ orgId }) => [orgId, [VANTA_VULNERABILITIES_SOURCE_ID]]));
|
|
12
|
+
}
|
|
4
13
|
const DEFAULT_VANTA_SYNC_INTERVAL_MS = 9e5;
|
|
5
14
|
function toVantaIngress(vulnerability) {
|
|
6
15
|
const severity = vulnerability.severity?.toLowerCase() ?? null;
|
|
@@ -76,6 +85,6 @@ function createVantaSync(options) {
|
|
|
76
85
|
return summary;
|
|
77
86
|
};
|
|
78
87
|
}
|
|
79
|
-
export { DEFAULT_VANTA_SYNC_INTERVAL_MS, VANTA_VULNERABILITIES_SOURCE_ID, createVantaSync, toVantaIngress };
|
|
88
|
+
export { DEFAULT_VANTA_SYNC_INTERVAL_MS, SELECT_VANTA_VULNERABILITIES_MIGRATION, VANTA_VULNERABILITIES_SOURCE_ID, createVantaSync, toVantaIngress, vantaOrgsSyncingWithoutSource, vantaVulnerabilitiesSelected };
|
|
80
89
|
|
|
81
90
|
//# sourceMappingURL=sync.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.js","names":[],"sources":["../../../src/integrations/vanta/sync.ts"],"sourcesContent":["import type { IssueReconcileSummary } from '../issue-reconciler.js';\nimport { vantaLabels } from './rules.js';\nimport type { VantaRulesIngress, VantaVulnerabilityIngress } from './rules.js';\n\nexport const VANTA_VULNERABILITIES_SOURCE_ID = 'vanta:vulnerabilities';\nexport const DEFAULT_VANTA_SYNC_INTERVAL_MS = 15 * 60_000;\n\n/** The subset of Vanta's `GET /v1/vulnerabilities` item Factory reads. */\nexport interface VantaVulnerability {\n id: string;\n name: string;\n description?: string | null;\n packageIdentifier?: string | null;\n severity?: string | null;\n isFixable?: boolean | null;\n remediateByDate?: string | null;\n firstDetectedDate?: string | null;\n externalURL?: string | null;\n}\n\n/** Lists a complete snapshot for one org, or null when its connections cannot be reconciled safely. */\nexport type VantaVulnerabilityLister = (orgId: string) => Promise<VantaVulnerability[] | null>;\n\nexport function toVantaIngress(vulnerability: VantaVulnerability): VantaVulnerabilityIngress {\n const severity = vulnerability.severity?.toLowerCase() ?? null;\n const packageIdentifier = vulnerability.packageIdentifier ?? null;\n return {\n id: vulnerability.id,\n name: vulnerability.name,\n title: packageIdentifier ? `${packageIdentifier}: ${vulnerability.name}` : vulnerability.name,\n description:\n vulnerability.description && vulnerability.description !== vulnerability.name ? vulnerability.description : null,\n url: vulnerability.externalURL ?? null,\n state: 'open',\n severity,\n packageIdentifier,\n fixable: vulnerability.isFixable ?? null,\n remediateBy: vulnerability.remediateByDate ?? null,\n labels: vantaLabels(severity),\n createdAt: vulnerability.firstDetectedDate ?? new Date(0).toISOString(),\n };\n}\n\n/**\n * Reads a complete snapshot for each organization and hands it to that organization's\n * Factory projects taking Vanta intake. Unavailable snapshots are never reconciled.\n */\nexport function createVantaSync(options: {\n /**\n * Whether any Vanta connection is active. Without one the vulnerability list\n * is empty, which would read as every filed vulnerability being resolved.\n */\n connected: () => Promise<boolean>;\n listVulnerabilities: VantaVulnerabilityLister;\n listProjects: () => Promise<ReadonlyArray<{ orgId: string; id: string }>>;\n intakeEnabled: (orgId: string) => Promise<boolean>;\n boundProjectIds: (orgId: string) => Promise<string[]>;\n ingest: (input: VantaRulesIngress) => Promise<unknown>;\n userId: string;\n}): () => Promise<IssueReconcileSummary> {\n return async () => {\n const summary: IssueReconcileSummary = {\n projects: 0,\n checked: 0,\n updated: 0,\n closed: 0,\n missing: 0,\n failed: 0,\n errors: [],\n };\n if (!(await options.connected())) return summary;\n const projects = await options.listProjects();\n if (projects.length === 0) return summary;\n const orgTargets = new Map<string, { enabled: boolean; bound: string[]; loaded: boolean; vulnerabilities: VantaVulnerabilityIngress[] | null }>();\n for (const project of projects) {\n try {\n let target = orgTargets.get(project.orgId);\n if (!target) {\n const enabled = await options.intakeEnabled(project.orgId);\n target = {\n enabled,\n bound: enabled ? await options.boundProjectIds(project.orgId) : [],\n loaded: false,\n vulnerabilities: null,\n };\n orgTargets.set(project.orgId, target);\n }\n if (!target.enabled || (target.bound.length > 0 && !target.bound.includes(project.id))) continue;\n if (!target.loaded) {\n const snapshot = await options.listVulnerabilities(project.orgId);\n target.vulnerabilities = snapshot?.map(toVantaIngress) ?? null;\n target.loaded = true;\n }\n if (target.vulnerabilities === null) continue;\n await options.ingest({\n orgId: project.orgId,\n userId: options.userId,\n factoryProjectId: project.id,\n vulnerabilities: target.vulnerabilities,\n });\n summary.projects += 1;\n summary.checked += target.vulnerabilities.length;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n }\n }\n return summary;\n };\n}\n"],"mappings":";;
|
|
1
|
+
{"version":3,"file":"sync.js","names":[],"sources":["../../../src/integrations/vanta/sync.ts"],"sourcesContent":["import type { IntakeConfig, IntakeSelection } from '../../storage/domains/intake/base.js';\nimport type { IssueReconcileSummary } from '../issue-reconciler.js';\nimport { vantaLabels } from './rules.js';\nimport type { VantaRulesIngress, VantaVulnerabilityIngress } from './rules.js';\n\nexport const VANTA_VULNERABILITIES_SOURCE_ID = 'vanta:vulnerabilities';\nexport const SELECT_VANTA_VULNERABILITIES_MIGRATION = 'select_vanta_vulnerabilities_where_sync_was_on';\n\n/** Vulnerabilities sync only once selected in Work Intake, like every other source. */\nexport function vantaVulnerabilitiesSelected(selection: IntakeSelection | undefined): boolean {\n return Boolean(selection?.enabled && selection.sourceIds?.includes(VANTA_VULNERABILITIES_SOURCE_ID));\n}\n\n/** Orgs whose old sync switch was on with nothing selected, so selecting vulnerabilities keeps them syncing. */\nexport function vantaOrgsSyncingWithoutSource(\n configs: ReadonlyArray<{ orgId: string; config: IntakeConfig }>,\n): Map<string, string[]> {\n return new Map(\n configs\n .filter(({ config }) => config.vanta?.enabled && !config.vanta.sourceIds?.length)\n .map(({ orgId }) => [orgId, [VANTA_VULNERABILITIES_SOURCE_ID]]),\n );\n}\nexport const DEFAULT_VANTA_SYNC_INTERVAL_MS = 15 * 60_000;\n\n/** The subset of Vanta's `GET /v1/vulnerabilities` item Factory reads. */\nexport interface VantaVulnerability {\n id: string;\n name: string;\n description?: string | null;\n packageIdentifier?: string | null;\n severity?: string | null;\n isFixable?: boolean | null;\n remediateByDate?: string | null;\n firstDetectedDate?: string | null;\n externalURL?: string | null;\n}\n\n/** Lists a complete snapshot for one org, or null when its connections cannot be reconciled safely. */\nexport type VantaVulnerabilityLister = (orgId: string) => Promise<VantaVulnerability[] | null>;\n\nexport function toVantaIngress(vulnerability: VantaVulnerability): VantaVulnerabilityIngress {\n const severity = vulnerability.severity?.toLowerCase() ?? null;\n const packageIdentifier = vulnerability.packageIdentifier ?? null;\n return {\n id: vulnerability.id,\n name: vulnerability.name,\n title: packageIdentifier ? `${packageIdentifier}: ${vulnerability.name}` : vulnerability.name,\n description:\n vulnerability.description && vulnerability.description !== vulnerability.name ? vulnerability.description : null,\n url: vulnerability.externalURL ?? null,\n state: 'open',\n severity,\n packageIdentifier,\n fixable: vulnerability.isFixable ?? null,\n remediateBy: vulnerability.remediateByDate ?? null,\n labels: vantaLabels(severity),\n createdAt: vulnerability.firstDetectedDate ?? new Date(0).toISOString(),\n };\n}\n\n/**\n * Reads a complete snapshot for each organization and hands it to that organization's\n * Factory projects taking Vanta intake. Unavailable snapshots are never reconciled.\n */\nexport function createVantaSync(options: {\n /**\n * Whether any Vanta connection is active. Without one the vulnerability list\n * is empty, which would read as every filed vulnerability being resolved.\n */\n connected: () => Promise<boolean>;\n listVulnerabilities: VantaVulnerabilityLister;\n listProjects: () => Promise<ReadonlyArray<{ orgId: string; id: string }>>;\n intakeEnabled: (orgId: string) => Promise<boolean>;\n boundProjectIds: (orgId: string) => Promise<string[]>;\n ingest: (input: VantaRulesIngress) => Promise<unknown>;\n userId: string;\n}): () => Promise<IssueReconcileSummary> {\n return async () => {\n const summary: IssueReconcileSummary = {\n projects: 0,\n checked: 0,\n updated: 0,\n closed: 0,\n missing: 0,\n failed: 0,\n errors: [],\n };\n if (!(await options.connected())) return summary;\n const projects = await options.listProjects();\n if (projects.length === 0) return summary;\n const orgTargets = new Map<string, { enabled: boolean; bound: string[]; loaded: boolean; vulnerabilities: VantaVulnerabilityIngress[] | null }>();\n for (const project of projects) {\n try {\n let target = orgTargets.get(project.orgId);\n if (!target) {\n const enabled = await options.intakeEnabled(project.orgId);\n target = {\n enabled,\n bound: enabled ? await options.boundProjectIds(project.orgId) : [],\n loaded: false,\n vulnerabilities: null,\n };\n orgTargets.set(project.orgId, target);\n }\n if (!target.enabled || (target.bound.length > 0 && !target.bound.includes(project.id))) continue;\n if (!target.loaded) {\n const snapshot = await options.listVulnerabilities(project.orgId);\n target.vulnerabilities = snapshot?.map(toVantaIngress) ?? null;\n target.loaded = true;\n }\n if (target.vulnerabilities === null) continue;\n await options.ingest({\n orgId: project.orgId,\n userId: options.userId,\n factoryProjectId: project.id,\n vulnerabilities: target.vulnerabilities,\n });\n summary.projects += 1;\n summary.checked += target.vulnerabilities.length;\n } catch (error) {\n summary.failed += 1;\n summary.errors.push({ projectId: project.id, error: error instanceof Error ? error.message : String(error) });\n }\n }\n return summary;\n };\n}\n"],"mappings":";;AAKA,MAAa,kCAAkC;AAC/C,MAAa,yCAAyC;;AAGtD,SAAgB,6BAA6B,WAAiD;CAC5F,OAAO,QAAQ,WAAW,WAAW,UAAU,WAAW,SAAA,uBAAwC,CAAC;AACrG;;AAGA,SAAgB,8BACd,SACuB;CACvB,OAAO,IAAI,IACT,QACG,QAAQ,EAAE,aAAa,OAAO,OAAO,WAAW,CAAC,OAAO,MAAM,WAAW,MAAM,CAAC,CAChF,KAAK,EAAE,YAAY,CAAC,OAAO,CAAC,+BAA+B,CAAC,CAAC,CAClE;AACF;AACA,MAAa,iCAAiC;AAkB9C,SAAgB,eAAe,eAA8D;CAC3F,MAAM,WAAW,cAAc,UAAU,YAAY,KAAK;CAC1D,MAAM,oBAAoB,cAAc,qBAAqB;CAC7D,OAAO;EACL,IAAI,cAAc;EAClB,MAAM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;GACrC,MAAM,QAAQ,OAAO;IACnB,OAAO,QAAQ;IACf,QAAQ,QAAQ;IAChB,kBAAkB,QAAQ;IAC1B,iBAAiB,OAAO;GAC1B,CAAC;GACD,QAAQ,YAAY;GACpB,QAAQ,WAAW,OAAO,gBAAgB;EAC5C,SAAS,OAAO;GACd,QAAQ,UAAU;GAClB,QAAQ,OAAO,KAAK;IAAE,WAAW,QAAQ;IAAI,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAAE,CAAC;EAC9G;EAEF,OAAO;CACT;AACF"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Context } from 'hono';
|
|
1
2
|
import type { Card } from '../storage/domains/work-items/base.js';
|
|
2
3
|
export interface BoardSnapshot {
|
|
3
4
|
etag: string;
|
|
@@ -5,18 +6,18 @@ export interface BoardSnapshot {
|
|
|
5
6
|
gzipped(): Promise<Buffer>;
|
|
6
7
|
}
|
|
7
8
|
/**
|
|
8
|
-
* The listing's wire body for one board version
|
|
9
|
-
*
|
|
10
|
-
*
|
|
9
|
+
* The listing's wire body for one board version. Every tab polling an unchanged board shares one
|
|
10
|
+
* serialization and one gzip, and its ETag lets the browser revalidate instead of downloading the
|
|
11
|
+
* board again.
|
|
11
12
|
*/
|
|
12
|
-
export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown,
|
|
13
|
+
export declare function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, cursor?: string): BoardSnapshot;
|
|
13
14
|
/**
|
|
14
15
|
* The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of
|
|
15
16
|
* their body, not by the board version: a write to a card outside the scope leaves it unchanged,
|
|
16
17
|
* so the tab gets a 304. A caller that passes the same list again shares its serialization.
|
|
17
18
|
* `total` is how many cards matched when `items` is only the first of them.
|
|
18
19
|
*/
|
|
19
|
-
export declare function scopedSnapshot(items: readonly Card[], toWire: (item: Card) => unknown,
|
|
20
|
+
export declare function scopedSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, total?: number): BoardSnapshot;
|
|
20
21
|
/** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */
|
|
21
22
|
export declare function movedBody(body: unknown): Pick<BoardSnapshot, 'json' | 'gzipped'>;
|
|
22
23
|
/**
|
|
@@ -32,7 +33,13 @@ export declare function namedBody(names: object, bodies?: () => object): BoardSn
|
|
|
32
33
|
/** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */
|
|
33
34
|
export declare function listCheck(items: readonly Card[]): string;
|
|
34
35
|
/** Names a text: a reader holding another text holds another name. */
|
|
35
|
-
export declare function
|
|
36
|
+
export declare function etagDigest(text: string): string;
|
|
36
37
|
/** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */
|
|
37
38
|
export declare function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean;
|
|
39
|
+
/** Session ids of the listed cards that the predicate picks, each once. */
|
|
40
|
+
export declare function sessionIdsWhere(items: readonly Card[], predicate: (sessionId: string) => boolean): string[];
|
|
41
|
+
/** Sends a JSON body, gzipped for a reader that accepts it. */
|
|
42
|
+
export declare function sendJson(c: Context, body: Pick<BoardSnapshot, 'json' | 'gzipped'>, headers: Record<string, string>): Promise<Response>;
|
|
43
|
+
/** Sends an answer its reader revalidates: a 304 without a body when the reader holds it already. */
|
|
44
|
+
export declare function sendRevalidated(c: Context, answer: BoardSnapshot): Promise<Response>;
|
|
38
45
|
//# sourceMappingURL=board-snapshot.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"board-snapshot.d.ts","sourceRoot":"","sources":["../../src/routes/board-snapshot.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AAEpC,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uCAAuC,CAAC;AAYlE,MAAM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/D,wBAAsB,QAAQ,CAC5B,CAAC,EAAE,OAAO,EACV,IAAI,EAAE,IAAI,CAAC,aAAa,EAAE,MAAM,GAAG,SAAS,CAAC,EAC7C,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAC9B,OAAO,CAAC,QAAQ,CAAC,CAMnB;AAED,qGAAqG;AACrG,wBAAsB,eAAe,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,QAAQ,CAAC,CAM1F"}
|
|
@@ -6,12 +6,12 @@ import { gzip } from "zlib";
|
|
|
6
6
|
const gzip$1 = promisify(gzip);
|
|
7
7
|
const cardsJson = /* @__PURE__ */ new WeakMap();
|
|
8
8
|
/**
|
|
9
|
-
* The listing's wire body for one board version
|
|
10
|
-
*
|
|
11
|
-
*
|
|
9
|
+
* The listing's wire body for one board version. Every tab polling an unchanged board shares one
|
|
10
|
+
* serialization and one gzip, and its ETag lets the browser revalidate instead of downloading the
|
|
11
|
+
* board again.
|
|
12
12
|
*/
|
|
13
|
-
function boardSnapshot(items, toWire,
|
|
14
|
-
return snapshot(items, toWire,
|
|
13
|
+
function boardSnapshot(items, toWire, cursor) {
|
|
14
|
+
return snapshot(items, toWire, () => randomUUID(), { cursor });
|
|
15
15
|
}
|
|
16
16
|
/**
|
|
17
17
|
* The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of
|
|
@@ -19,8 +19,8 @@ function boardSnapshot(items, toWire, runningSessionIds, parkedSessionIds, curso
|
|
|
19
19
|
* so the tab gets a 304. A caller that passes the same list again shares its serialization.
|
|
20
20
|
* `total` is how many cards matched when `items` is only the first of them.
|
|
21
21
|
*/
|
|
22
|
-
function scopedSnapshot(items, toWire,
|
|
23
|
-
return snapshot(items, toWire,
|
|
22
|
+
function scopedSnapshot(items, toWire, total) {
|
|
23
|
+
return snapshot(items, toWire, etagDigest, { total });
|
|
24
24
|
}
|
|
25
25
|
/** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */
|
|
26
26
|
function movedBody(body) {
|
|
@@ -37,7 +37,7 @@ function movedBody(body) {
|
|
|
37
37
|
function hashedBody(body) {
|
|
38
38
|
const json = JSON.stringify(body);
|
|
39
39
|
return {
|
|
40
|
-
etag: `W/"${
|
|
40
|
+
etag: `W/"${etagDigest(json)}"`,
|
|
41
41
|
json,
|
|
42
42
|
gzipped: () => gzip$1(json)
|
|
43
43
|
};
|
|
@@ -54,7 +54,7 @@ function namedBody(names, bodies) {
|
|
|
54
54
|
...bodies()
|
|
55
55
|
}) : named;
|
|
56
56
|
return {
|
|
57
|
-
etag: `W/"${
|
|
57
|
+
etag: `W/"${etagDigest(named)}${bodies ? ".bodies" : ""}"`,
|
|
58
58
|
get json() {
|
|
59
59
|
return json();
|
|
60
60
|
},
|
|
@@ -68,7 +68,7 @@ function listCheck(items) {
|
|
|
68
68
|
if (check === void 0) checks.set(items, check = boardCheck(items));
|
|
69
69
|
return check;
|
|
70
70
|
}
|
|
71
|
-
function snapshot(items, toWire,
|
|
71
|
+
function snapshot(items, toWire, cardsId, more) {
|
|
72
72
|
let cards = cardsJson.get(items);
|
|
73
73
|
if (!cards) {
|
|
74
74
|
const json = JSON.stringify(items.map(toWire));
|
|
@@ -78,14 +78,10 @@ function snapshot(items, toWire, runningSessionIds, parkedSessionIds, cardsId, m
|
|
|
78
78
|
};
|
|
79
79
|
cardsJson.set(items, cards);
|
|
80
80
|
}
|
|
81
|
-
const rest = JSON.stringify(
|
|
82
|
-
|
|
83
|
-
parkedSessionIds,
|
|
84
|
-
...more
|
|
85
|
-
});
|
|
86
|
-
const etag = `W/"${cards.id}.${sha1(rest)}"`;
|
|
81
|
+
const rest = JSON.stringify(more);
|
|
82
|
+
const etag = `W/"${cards.id}.${etagDigest(rest)}"`;
|
|
87
83
|
if (cards.latest?.etag === etag) return cards.latest;
|
|
88
|
-
const json = `{"workItems":${cards.json}
|
|
84
|
+
const json = `{"workItems":${cards.json}${rest === "{}" ? "}" : `,${rest.slice(1)}`}`;
|
|
89
85
|
let gzipped;
|
|
90
86
|
cards.latest = {
|
|
91
87
|
etag,
|
|
@@ -95,8 +91,8 @@ function snapshot(items, toWire, runningSessionIds, parkedSessionIds, cardsId, m
|
|
|
95
91
|
return cards.latest;
|
|
96
92
|
}
|
|
97
93
|
/** Names a text: a reader holding another text holds another name. */
|
|
98
|
-
function
|
|
99
|
-
return createHash("
|
|
94
|
+
function etagDigest(text) {
|
|
95
|
+
return createHash("sha256").update(text).digest("base64url");
|
|
100
96
|
}
|
|
101
97
|
/** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */
|
|
102
98
|
function matchesEtag(ifNoneMatch, etag) {
|
|
@@ -104,6 +100,32 @@ function matchesEtag(ifNoneMatch, etag) {
|
|
|
104
100
|
const bare = (tag) => tag.trim().replace(/^W\//, "");
|
|
105
101
|
return ifNoneMatch.split(",").some((tag) => tag.trim() === "*" || bare(tag) === bare(etag));
|
|
106
102
|
}
|
|
107
|
-
|
|
103
|
+
/** Session ids of the listed cards that the predicate picks, each once. */
|
|
104
|
+
function sessionIdsWhere(items, predicate) {
|
|
105
|
+
const picked = /* @__PURE__ */ new Set();
|
|
106
|
+
for (const item of items) for (const { sessionId } of Object.values(item.sessions)) if (predicate(sessionId)) picked.add(sessionId);
|
|
107
|
+
return [...picked];
|
|
108
|
+
}
|
|
109
|
+
/** Sends a JSON body, gzipped for a reader that accepts it. */
|
|
110
|
+
async function sendJson(c, body, headers) {
|
|
111
|
+
headers["Content-Type"] = "application/json; charset=UTF-8";
|
|
112
|
+
headers.Vary = "Accept-Encoding";
|
|
113
|
+
if (!/\bgzip\b/.test(c.req.header("accept-encoding") ?? "")) return c.body(body.json, 200, headers);
|
|
114
|
+
headers["Content-Encoding"] = "gzip";
|
|
115
|
+
return c.body(new Uint8Array(await body.gzipped()), 200, headers);
|
|
116
|
+
}
|
|
117
|
+
/** Sends an answer its reader revalidates: a 304 without a body when the reader holds it already. */
|
|
118
|
+
async function sendRevalidated(c, answer) {
|
|
119
|
+
const headers = {
|
|
120
|
+
ETag: answer.etag,
|
|
121
|
+
"Cache-Control": "private, no-cache"
|
|
122
|
+
};
|
|
123
|
+
if (matchesEtag(c.req.header("if-none-match"), answer.etag)) return c.body(null, 304, {
|
|
124
|
+
...headers,
|
|
125
|
+
Vary: "Accept-Encoding"
|
|
126
|
+
});
|
|
127
|
+
return sendJson(c, answer, headers);
|
|
128
|
+
}
|
|
129
|
+
export { boardSnapshot, etagDigest, hashedBody, listCheck, matchesEtag, movedBody, namedBody, scopedSnapshot, sendJson, sendRevalidated, sessionIdsWhere };
|
|
108
130
|
|
|
109
131
|
//# sourceMappingURL=board-snapshot.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"board-snapshot.js","names":["gzip","gzipCallback"],"sources":["../../src/routes/board-snapshot.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { promisify } from 'node:util';\nimport { gzip as gzipCallback } from 'node:zlib';\n\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { boardCheck } from '../work-items/board-check.js';\n\nconst gzip = promisify(gzipCallback);\n\ninterface CardsJson {\n /** Names the cards in the ETag. */\n id: string;\n json: string;\n latest?: BoardSnapshot;\n}\n\nexport interface BoardSnapshot {\n etag: string;\n json: string;\n gzipped(): Promise<Buffer>;\n}\n\n// Keyed on the list a caller keeps per board version: `listShared` returns one frozen array until\n// a card changes, so a new version or an evicted list drops its entry with it.\nconst cardsJson = new WeakMap<readonly Card[], CardsJson>();\n\n/**\n * The listing's wire body for one board version
|
|
1
|
+
{"version":3,"file":"board-snapshot.js","names":["gzip","gzipCallback"],"sources":["../../src/routes/board-snapshot.ts"],"sourcesContent":["import { createHash, randomUUID } from 'node:crypto';\nimport { promisify } from 'node:util';\nimport { gzip as gzipCallback } from 'node:zlib';\nimport type { Context } from 'hono';\n\nimport type { Card } from '../storage/domains/work-items/base.js';\nimport { boardCheck } from '../work-items/board-check.js';\n\nconst gzip = promisify(gzipCallback);\n\ninterface CardsJson {\n /** Names the cards in the ETag. */\n id: string;\n json: string;\n latest?: BoardSnapshot;\n}\n\nexport interface BoardSnapshot {\n etag: string;\n json: string;\n gzipped(): Promise<Buffer>;\n}\n\n// Keyed on the list a caller keeps per board version: `listShared` returns one frozen array until\n// a card changes, so a new version or an evicted list drops its entry with it.\nconst cardsJson = new WeakMap<readonly Card[], CardsJson>();\n\n/**\n * The listing's wire body for one board version. Every tab polling an unchanged board shares one\n * serialization and one gzip, and its ETag lets the browser revalidate instead of downloading the\n * board again.\n */\nexport function boardSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, cursor?: string): BoardSnapshot {\n // Random per cached list, so an ETag from before a restart never matches a different board.\n return snapshot(items, toWire, () => randomUUID(), { cursor });\n}\n\n/**\n * The wire body for the cards a scoped listing picked. Its ETag names the cards by a hash of\n * their body, not by the board version: a write to a card outside the scope leaves it unchanged,\n * so the tab gets a 304. A caller that passes the same list again shares its serialization.\n * `total` is how many cards matched when `items` is only the first of them.\n */\nexport function scopedSnapshot(items: readonly Card[], toWire: (item: Card) => unknown, total?: number): BoardSnapshot {\n return snapshot(items, toWire, etagDigest, { total });\n}\n\n/** What moved on a board, for the one reader whose cursor it answers: nothing of it is kept. */\nexport function movedBody(body: unknown): Pick<BoardSnapshot, 'json' | 'gzipped'> {\n const json = JSON.stringify(body);\n return { json, gzipped: () => gzip(json) };\n}\n\n/**\n * A computed answer's wire body, named by a hash of itself: a reader that kept it revalidates\n * instead of downloading it again.\n */\nexport function hashedBody(body: unknown): BoardSnapshot {\n const json = JSON.stringify(body);\n return { etag: `W/\"${etagDigest(json)}\"`, json, gzipped: () => gzip(json) };\n}\n\n/**\n * An answer whose `names` hold the version of every card body `bodies` adds: its ETag is a hash of\n * `names`, and the bodies are serialized only for a reader that does not hold the answer.\n */\nexport function namedBody(names: object, bodies?: () => object): BoardSnapshot {\n const named = JSON.stringify(names);\n let whole: string | undefined;\n const json = () => (whole ??= bodies ? JSON.stringify({ ...names, ...bodies() }) : named);\n return {\n // An answer with bodies is not one a reader of the names alone holds.\n etag: `W/\"${etagDigest(named)}${bodies ? '.bodies' : ''}\"`,\n get json() {\n return json();\n },\n gzipped: () => gzip(json()),\n };\n}\n\nconst checks = new WeakMap<readonly Card[], string>();\n\n/** {@link boardCheck} of a cached list, computed once for every reader that sends its cursor. */\nexport function listCheck(items: readonly Card[]): string {\n let check = checks.get(items);\n if (check === undefined) checks.set(items, (check = boardCheck(items)));\n return check;\n}\n\nfunction snapshot(\n items: readonly Card[],\n toWire: (item: Card) => unknown,\n cardsId: (json: string) => string,\n more: { total?: number; cursor?: string },\n): BoardSnapshot {\n let cards = cardsJson.get(items);\n if (!cards) {\n const json = JSON.stringify(items.map(toWire));\n cards = { id: cardsId(json), json };\n cardsJson.set(items, cards);\n }\n // Everything the body holds beside the cards: a 304 must never hide a change to any of it.\n const rest = JSON.stringify(more);\n const etag = `W/\"${cards.id}.${etagDigest(rest)}\"`;\n if (cards.latest?.etag === etag) return cards.latest;\n\n const json = `{\"workItems\":${cards.json}${rest === '{}' ? '}' : `,${rest.slice(1)}`}`;\n let gzipped: Promise<Buffer> | undefined;\n // zlib runs on the libuv pool, off the event loop.\n cards.latest = { etag, json, gzipped: () => (gzipped ??= gzip(json)) };\n return cards.latest;\n}\n\n/** Names a text: a reader holding another text holds another name. */\nexport function etagDigest(text: string): string {\n return createHash('sha256').update(text).digest('base64url');\n}\n\n/** Whether an `If-None-Match` header names this ETag (weak comparison, as for GET). */\nexport function matchesEtag(ifNoneMatch: string | undefined, etag: string): boolean {\n if (!ifNoneMatch) return false;\n const bare = (tag: string) => tag.trim().replace(/^W\\//, '');\n return ifNoneMatch.split(',').some(tag => tag.trim() === '*' || bare(tag) === bare(etag));\n}\n\n/** Session ids of the listed cards that the predicate picks, each once. */\nexport function sessionIdsWhere(items: readonly Card[], predicate: (sessionId: string) => boolean): string[] {\n const picked = new Set<string>();\n for (const item of items) {\n for (const { sessionId } of Object.values(item.sessions)) {\n if (predicate(sessionId)) picked.add(sessionId);\n }\n }\n return [...picked];\n}\n\n/** Sends a JSON body, gzipped for a reader that accepts it. */\nexport async function sendJson(\n c: Context,\n body: Pick<BoardSnapshot, 'json' | 'gzipped'>,\n headers: Record<string, string>,\n): Promise<Response> {\n headers['Content-Type'] = 'application/json; charset=UTF-8';\n headers.Vary = 'Accept-Encoding';\n if (!/\\bgzip\\b/.test(c.req.header('accept-encoding') ?? '')) return c.body(body.json, 200, headers);\n headers['Content-Encoding'] = 'gzip';\n return c.body(new Uint8Array(await body.gzipped()), 200, headers);\n}\n\n/** Sends an answer its reader revalidates: a 304 without a body when the reader holds it already. */\nexport async function sendRevalidated(c: Context, answer: BoardSnapshot): Promise<Response> {\n const headers = { ETag: answer.etag, 'Cache-Control': 'private, no-cache' };\n if (matchesEtag(c.req.header('if-none-match'), answer.etag)) {\n return c.body(null, 304, { ...headers, Vary: 'Accept-Encoding' });\n }\n return sendJson(c, answer, headers);\n}\n"],"mappings":";;;;;AAQA,MAAMA,SAAO,UAAUC,IAAY;AAiBnC,MAAM,4BAAY,IAAI,QAAoC;;;;;;AAO1D,SAAgB,cAAc,OAAwB,QAAiC,QAAgC;CAErH,OAAO,SAAS,OAAO,cAAc,WAAW,GAAG,EAAE,OAAO,CAAC;AAC/D;;;;;;;AAQA,SAAgB,eAAe,OAAwB,QAAiC,OAA+B;CACrH,OAAO,SAAS,OAAO,QAAQ,YAAY,EAAE,MAAM,CAAC;AACtD;;AAGA,SAAgB,UAAU,MAAwD;CAChF,MAAM,OAAO,KAAK,UAAU,IAAI;CAChC,OAAO;EAAE;EAAM,eAAeD,OAAK,IAAI;CAAE;AAC3C;;;;;AAMA,SAAgB,WAAW,MAA8B;CACvD,MAAM,OAAO,KAAK,UAAU,IAAI;CAChC,OAAO;EAAE,MAAM,MAAM,WAAW,IAAI,EAAE;EAAI;EAAM,eAAeA,OAAK,IAAI;CAAE;AAC5E;;;;;AAMA,SAAgB,UAAU,OAAe,QAAsC;CAC7E,MAAM,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QAAgB,IAAI,KAAK,CAAC,CAAC,QAAQ,QAAQ,EAAE;CAC3D,OAAO,YAAY,MAAM,GAAG,CAAC,CAAC,MAAK,QAAO,IAAI,KAAK,MAAM,OAAO,KAAK,GAAG,MAAM,KAAK,IAAI,CAAC;AAC1F;;AAGA,SAAgB,gBAAgB,OAAwB,WAAqD;CAC3G,MAAM,yBAAS,IAAI,IAAY;CAC/B,KAAK,MAAM,QAAQ,OACjB,KAAK,MAAM,EAAE,eAAe,OAAO,OAAO,KAAK,QAAQ,GACrD,IAAI,UAAU,SAAS,GAAG,OAAO,IAAI,SAAS;CAGlD,OAAO,CAAC,GAAG,MAAM;AACnB;;AAGA,eAAsB,SACpB,GACA,MACA,SACmB;CACnB,QAAQ,kBAAkB;CAC1B,QAAQ,OAAO;CACf,IAAI,CAAC,WAAW,KAAK,EAAE,IAAI,OAAO,iBAAiB,KAAK,EAAE,GAAG,OAAO,EAAE,KAAK,KAAK,MAAM,KAAK,OAAO;CAClG,QAAQ,sBAAsB;CAC9B,OAAO,EAAE,KAAK,IAAI,WAAW,MAAM,KAAK,QAAQ,CAAC,GAAG,KAAK,OAAO;AAClE;;AAGA,eAAsB,gBAAgB,GAAY,QAA0C;CAC1F,MAAM,UAAU;EAAE,MAAM,OAAO;EAAM,iBAAiB;CAAoB;CAC1E,IAAI,YAAY,EAAE,IAAI,OAAO,eAAe,GAAG,OAAO,IAAI,GACxD,OAAO,EAAE,KAAK,MAAM,KAAK;EAAE,GAAG;EAAS,MAAM;CAAkB,CAAC;CAElE,OAAO,SAAS,GAAG,QAAQ,OAAO;AACpC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boards.js","names":[],"sources":["../../src/routes/boards.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for managing a project's stored boards.\n *\n * Reads need project membership; writes need an organization admin in tenant mode. Factory stores\n * the built-in Work board and app boards in each project once, and they are edited under their own\n * key; their code behaviour stays attached, so an edit it can't honour is refused\n * (`code_behaviour`), and reset rewrites Factory's current definition at the next revision. They\n * can't be created over, and Work can't be deleted. The writes themselves are `BoardWrites`.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\n\nimport { BoardWriteError, BoardWrites, issueMessage } from '../boards/board-writes.js';\nimport type { BoardWriter } from '../boards/board-writes.js';\nimport type { ProjectBoardCache } from '../boards/project-boards.js';\nimport { codeBehaviourOf } from '../boards/stored-board.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { StoredBoardScope, StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface BoardRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n projects: FactoryProjectsStorage;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n}\n\ntype Resolved = StoredBoardScope & { userId: string };\n\n/** A response the handler returns as is: a refusal or an error. */\nclass Refusal {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422,\n readonly body: Record<string, unknown>,\n ) {}\n}\n\nexport class BoardRoutes extends Route<BoardRoutesDeps> {\n readonly #writes = new BoardWrites(this.deps);\n\n async #resolve(c: Context): Promise<Resolved> {\n const { auth, projects } = this.deps;\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) throw new Refusal(401, { error: 'unauthorized' });\n if (!tenant.orgId) {\n throw new Refusal(403, { error: 'organization_required', message: 'Boards belong to an organization.' });\n }\n const parsed = FACTORY_ROUTE_CONTRACTS.boardCatalog.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsed.success) throw new Refusal(404, { error: 'Project not found' });\n await projects.ensureReady();\n if (!(await projects.get({ orgId: tenant.orgId, id: parsed.data.id }))) {\n throw new Refusal(404, { error: 'Project not found' });\n }\n return { orgId: tenant.orgId, userId: tenant.userId, factoryProjectId: parsed.data.id };\n }\n\n async #requireAdmin(c: Context, scope: Resolved): Promise<void> {\n const { auth } = this.deps;\n if (auth.enabled() && !(await auth.isOrganizationAdmin(c, scope.orgId))) {\n throw new Refusal(403, {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to change boards.',\n });\n }\n }\n\n async #body(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n throw new Refusal(400, { error: 'invalid_request', message: 'Invalid JSON body.' });\n }\n }\n\n #boardKey(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.boardGet.pathSchema.safeParse({\n id: c.req.param('id'),\n boardKey: c.req.param('boardKey'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'board_not_found' });\n return parsed.data.boardKey;\n }\n\n async #respond(c: Context, scope: Resolved, key: string, status: 200 | 201 = 200) {\n const { auth } = this.deps;\n const canEdit = !auth.enabled() || (await auth.isOrganizationAdmin(c, scope.orgId));\n const project = await this.deps.boards.describe(scope);\n const details = project.details.get(key);\n const code = this.deps.boards.codeRegistry.get(key);\n const row = await this.deps.storage.get(scope, key);\n if (!row) return c.json({ error: 'board_not_found', message: `Board \"${key}\" does not exist.` }, 404);\n // A board that failed to load, or a stored row its code board hides, is a project problem.\n const rowProblems = project.problems.filter(\n problem =>\n problem.startsWith(`Board '${key}' could not be loaded:`) || problem.startsWith(`Stored board \"${key}\" `),\n );\n return c.json(\n {\n board: {\n key: row.key,\n name: row.name,\n description: row.description,\n phases: row.phases.map(({ position: _position, ...phase }) => phase),\n revision: row.revision,\n source: details?.source ?? 'stored',\n editable: true,\n codeBehaviour: code ? codeBehaviourOf(code) : null,\n problems: [...(details?.problems ?? []), ...rowProblems.filter(p => !details?.problems.includes(p))],\n },\n canEdit,\n },\n status,\n );\n }\n\n #route(\n contract: { path: string; method: 'GET' | 'POST' | 'PATCH' | 'DELETE' },\n handle: (c: Context) => Promise<Response>,\n ): ApiRoute {\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n try {\n return await handle(context);\n } catch (error) {\n if (error instanceof Refusal) return context.json(error.body, error.status);\n if (error instanceof BoardWriteError) return context.json(error.body, error.status);\n throw error;\n }\n },\n });\n }\n\n /** The request's user, as the board's author and the audit event's actor. */\n #writer(c: Context, scope: Resolved): BoardWriter {\n return { id: scope.userId, audit: input => this.deps.audit.emit({ context: c, input }) };\n }\n\n routes(): ApiRoute[] {\n const contracts = FACTORY_ROUTE_CONTRACTS;\n const writes = this.#writes;\n return [\n this.#route(contracts.boardGet, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n return this.#respond(c, scope, key);\n }),\n\n this.#route(contracts.boardCreate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const row = await writes.create(scope, await this.#body(c), this.#writer(c, scope));\n return this.#respond(c, scope, row.key, 201);\n }),\n\n this.#route(contracts.boardReplace, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n writes.refuseCodeBoard(key, 'edit');\n const parsed = contracts.boardReplace.bodySchema.safeParse(await this.#body(c));\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const { expectedRevision, ...definition } = parsed.data;\n await writes.replace(scope, key, definition, { expectedRevision, writer: this.#writer(c, scope) });\n return this.#respond(c, scope, key);\n }),\n\n this.#route(contracts.boardDelete, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n writes.refuseCodeBoard(key, 'delete');\n const parsed = contracts.boardDelete.querySchema.safeParse({\n expectedRevision: c.req.query('expectedRevision'),\n });\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n await writes.remove(scope, key, {\n expectedRevision: parsed.data.expectedRevision,\n writer: this.#writer(c, scope),\n });\n return c.body(null, 204);\n }),\n\n this.#route(contracts.boardReset, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n const parsed = contracts.boardReset.bodySchema.safeParse(await this.#body(c));\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n await writes.reset(scope, key, {\n expectedRevision: parsed.data.expectedRevision,\n writer: this.#writer(c, scope),\n });\n return this.#respond(c, scope, key);\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;AAuCA,IAAM,UAAN,MAAc;CAED;CACA;CAFX,YACE,QACA,MACA;EAFS,KAAA,SAAA;EACA,KAAA,OAAA;CACR;AACL;AAEA,IAAa,cAAb,cAAiC,MAAuB;CACtD,UAAmB,IAAI,YAAY,KAAK,IAAI;CAE5C,MAAM,SAAS,GAA+B;EAC5C,MAAM,EAAE,MAAM,aAAa,KAAK;EAChC,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,eAAe,CAAC;EAC7D,IAAI,CAAC,OAAO,OACV,MAAM,IAAI,QAAQ,KAAK;GAAE,OAAO;GAAyB,SAAS;EAAoC,CAAC;EAEzG,MAAM,SAAS,wBAAwB,aAAa,WAAW,UAAU,EAAE,IAAI,EAAE,IAAI,MAAM,IAAI,EAAE,CAAC;EAClG,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,oBAAoB,CAAC;EAC1E,MAAM,SAAS,YAAY;EAC3B,IAAI,CAAE,MAAM,SAAS,IAAI;GA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D,kBAAkB,EAAE,IAAI,MAAM,kBAAkB,EAClD,CAAC;IACD,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,QAAQ,KAAK;KAAE,OAAO;KAAmB,SAAS,aAAa,OAAO,MAAM,MAAM;IAAE,CAAC;IAEjG,MAAM,OAAO,OAAO,OAAO,KAAK;KAC9B,kBAAkB,OAAO,KAAK;KAC9B,QAAQ,KAAK,QAAQ,GAAG,KAAK;IAC/B,CAAC;IACD,OAAO,EAAE,KAAK,MAAM,GAAG;GACzB,CAAC;GAED,KAAK,OAAO,UAAU,YAAY,OAAM,MAAK;IAC3C,MAAM,QAAQ,MAAM,KAAK,SAAS,CAAC;IACnC,MAAM,MAAM,KAAK,UAAU,CAAC;IAC5B,MAAM,KAAK,cAAc,GAAG,KAAK;IACjC,MAAM,SAAS,UAAU,WAAW,WAAW,UAAU,MAAM,KAAK,MAAM,CAAC,CAAC;IAC5E,IAAI,CAAC,OAAO,SACV,MAAM,IAAI,QAAQ,KAAK;KAAE,OAAO;KAAmB,SAAS,aAAa,OAAO,MAAM,MAAM;IAAE,CAAC;IAEjG,MAAM,OAAO,MAAM,OAAO,KAAK;KAC7B,kBAAkB,OAAO,KAAK;KAC9B,QAAQ,KAAK,QAAQ,GAAG,KAAK;IAC/B,CAAC;IACD,OAAO,KAAK,SAAS,GAAG,OAAO,GAAG;GACpC,CAAC;EACH;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"boards.js","names":[],"sources":["../../src/routes/boards.ts"],"sourcesContent":["/**\n * Mastra `apiRoutes` for managing a project's stored boards.\n *\n * Reads need project membership; writes need an organization admin in tenant mode. Factory stores\n * the built-in Work board and app boards in each project once, and they are edited under their own\n * key; their code behaviour stays attached, so an edit it can't honour is refused\n * (`code_behaviour`), and reset rewrites Factory's current definition at the next revision. They\n * can't be created over, and Work can't be deleted. The writes themselves are `BoardWrites`.\n */\n\nimport type { ApiRoute } from '@mastra/core/server';\nimport { registerApiRoute } from '@mastra/core/server';\nimport type { Context } from 'hono';\nimport { BoardWriteError, BoardWrites, issueMessage } from '../boards/board-writes.js';\n\nimport type { BoardWriter } from '../boards/board-writes.js';\nimport type { ProjectBoardCache } from '../boards/project-boards.js';\nimport { codeBehaviourOf } from '../boards/stored-board.js';\nimport type { AuditEmitter } from '../storage/domains/audit/domain.js';\nimport type { StoredBoardScope, StoredBoardsStorage } from '../storage/domains/boards/base.js';\nimport type { FactoryProjectsStorage } from '../storage/domains/projects/base.js';\nimport type { WorkItemsStorage } from '../storage/domains/work-items/base.js';\nimport { FACTORY_ROUTE_CONTRACTS } from './contracts.js';\nimport type { RouteDependencies } from './route.js';\nimport { loose, Route } from './route.js';\n\nexport interface BoardRoutesDeps extends RouteDependencies {\n audit: AuditEmitter;\n projects: FactoryProjectsStorage;\n /** Read to refuse edits that would strand cards. */\n workItems: Pick<WorkItemsStorage, 'listShared' | 'releaseReviewCards'>;\n storage: StoredBoardsStorage;\n /** The per-project boards: the code boards and their seeds, skills, and the cache to invalidate. */\n boards: Pick<ProjectBoardCache, 'describe' | 'invalidate' | 'codeRegistry' | 'codeSkills' | 'seedFor'>;\n}\n\ntype Resolved = StoredBoardScope & { userId: string };\n\n/** A response the handler returns as is: a refusal or an error. */\nclass Refusal {\n constructor(\n readonly status: 400 | 401 | 403 | 404 | 409 | 422,\n readonly body: Record<string, unknown>,\n ) {}\n}\n\nexport class BoardRoutes extends Route<BoardRoutesDeps> {\n readonly #writes = new BoardWrites(this.deps);\n\n async #resolve(c: Context): Promise<Resolved> {\n const { auth, projects } = this.deps;\n await auth.ensureUser(c);\n const tenant = auth.tenant(c);\n if (!tenant) throw new Refusal(401, { error: 'unauthorized' });\n if (!tenant.orgId) {\n throw new Refusal(403, { error: 'organization_required', message: 'Boards belong to an organization.' });\n }\n const parsed = FACTORY_ROUTE_CONTRACTS.boardCatalog.pathSchema.safeParse({ id: c.req.param('id') });\n if (!parsed.success) throw new Refusal(404, { error: 'Project not found' });\n await projects.ensureReady();\n if (!(await projects.get({ orgId: tenant.orgId, id: parsed.data.id }))) {\n throw new Refusal(404, { error: 'Project not found' });\n }\n return { orgId: tenant.orgId, userId: tenant.userId, factoryProjectId: parsed.data.id };\n }\n\n async #requireAdmin(c: Context, scope: Resolved): Promise<void> {\n const { auth } = this.deps;\n if (auth.enabled() && !(await auth.isOrganizationAdmin(c, scope.orgId))) {\n throw new Refusal(403, {\n error: 'organization_admin_required',\n message: 'Organization administrator access is required to change boards.',\n });\n }\n }\n\n async #body(c: Context): Promise<unknown> {\n try {\n return await c.req.json();\n } catch {\n throw new Refusal(400, { error: 'invalid_request', message: 'Invalid JSON body.' });\n }\n }\n\n #boardKey(c: Context): string {\n const parsed = FACTORY_ROUTE_CONTRACTS.boardGet.pathSchema.safeParse({\n id: c.req.param('id'),\n boardKey: c.req.param('boardKey'),\n });\n if (!parsed.success) throw new Refusal(404, { error: 'board_not_found' });\n return parsed.data.boardKey;\n }\n\n async #respond(c: Context, scope: Resolved, key: string, status: 200 | 201 = 200) {\n const { auth } = this.deps;\n const canEdit = !auth.enabled() || (await auth.isOrganizationAdmin(c, scope.orgId));\n const project = await this.deps.boards.describe(scope);\n const details = project.details.get(key);\n const code = this.deps.boards.codeRegistry.get(key);\n const row = await this.deps.storage.get(scope, key);\n if (!row) return c.json({ error: 'board_not_found', message: `Board \"${key}\" does not exist.` }, 404);\n // A board that failed to load, or a stored row its code board hides, is a project problem.\n const rowProblems = project.problems.filter(\n problem =>\n problem.startsWith(`Board '${key}' could not be loaded:`) || problem.startsWith(`Stored board \"${key}\" `),\n );\n return c.json(\n {\n board: {\n key: row.key,\n name: row.name,\n description: row.description,\n phases: row.phases.map(({ position: _position, ...phase }) => phase),\n revision: row.revision,\n source: details?.source ?? 'stored',\n editable: true,\n codeBehaviour: code ? codeBehaviourOf(code) : null,\n problems: [...(details?.problems ?? []), ...rowProblems.filter(p => !details?.problems.includes(p))],\n },\n canEdit,\n },\n status,\n );\n }\n\n #route(\n contract: { path: string; method: 'GET' | 'POST' | 'PATCH' | 'DELETE' },\n handle: (c: Context) => Promise<Response>,\n ): ApiRoute {\n return registerApiRoute(contract.path, {\n method: contract.method,\n requiresAuth: false,\n handler: async c => {\n const context = loose(c);\n try {\n return await handle(context);\n } catch (error) {\n if (error instanceof Refusal) return context.json(error.body, error.status);\n if (error instanceof BoardWriteError) return context.json(error.body, error.status);\n throw error;\n }\n },\n });\n }\n\n /** The request's user, as the board's author and the audit event's actor. */\n #writer(c: Context, scope: Resolved): BoardWriter {\n return { id: scope.userId, audit: input => this.deps.audit.emit({ context: c, input }) };\n }\n\n routes(): ApiRoute[] {\n const contracts = FACTORY_ROUTE_CONTRACTS;\n const writes = this.#writes;\n return [\n this.#route(contracts.boardGet, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n return this.#respond(c, scope, key);\n }),\n\n this.#route(contracts.boardCreate, async c => {\n const scope = await this.#resolve(c);\n await this.#requireAdmin(c, scope);\n const row = await writes.create(scope, await this.#body(c), this.#writer(c, scope));\n return this.#respond(c, scope, row.key, 201);\n }),\n\n this.#route(contracts.boardReplace, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n writes.refuseCodeBoard(key, 'edit');\n const parsed = contracts.boardReplace.bodySchema.safeParse(await this.#body(c));\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_board', message: issueMessage(parsed.error.issues) });\n }\n const { expectedRevision, ...definition } = parsed.data;\n await writes.replace(scope, key, definition, { expectedRevision, writer: this.#writer(c, scope) });\n return this.#respond(c, scope, key);\n }),\n\n this.#route(contracts.boardDelete, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n writes.refuseCodeBoard(key, 'delete');\n const parsed = contracts.boardDelete.querySchema.safeParse({\n expectedRevision: c.req.query('expectedRevision'),\n });\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n await writes.remove(scope, key, {\n expectedRevision: parsed.data.expectedRevision,\n writer: this.#writer(c, scope),\n });\n return c.body(null, 204);\n }),\n\n this.#route(contracts.boardReset, async c => {\n const scope = await this.#resolve(c);\n const key = this.#boardKey(c);\n await this.#requireAdmin(c, scope);\n const parsed = contracts.boardReset.bodySchema.safeParse(await this.#body(c));\n if (!parsed.success) {\n throw new Refusal(422, { error: 'invalid_request', message: issueMessage(parsed.error.issues) });\n }\n await writes.reset(scope, key, {\n expectedRevision: parsed.data.expectedRevision,\n writer: this.#writer(c, scope),\n });\n return this.#respond(c, scope, key);\n }),\n ];\n }\n}\n"],"mappings":";;;;;;;AAuCA,IAAM,UAAN,MAAc;CAED;CACA;CAFX,YACE,QACA,MACA;EAFS,KAAA,SAAA;EACA,KAAA,OAAA;CACR;AACL;AAEA,IAAa,cAAb,cAAiC,MAAuB;CACtD,UAAmB,IAAI,YAAY,KAAK,IAAI;CAE5C,MAAM,SAAS,GAA+B;EAC5C,MAAM,EAAE,MAAM,aAAa,KAAK;EAChC,MAAM,KAAK,WAAW,CAAC;EACvB,MAAM,SAAS,KAAK,OAAO,CAAC;EAC5B,IAAI,CAAC,QAAQ,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,eAAe,CAAC;EAC7D,IAAI,CAAC,OAAO,OACV,MAAM,IAAI,QAAQ,KAAK;GAAE,OAAO;GAAyB,SAAS;EAAoC,CAAC;EAEzG,MAAM,SAAS,wBAAwB,aAAa,WAAW,UAAU,EAAE,IAAI,EAAE,IAAI,MAAM,IAAI,EAAE,CAAC;EAClG,IAAI,CAAC,OAAO,SAAS,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,oBAAoB,CAAC;EAC1E,MAAM,SAAS,YAAY;EAC3B,IAAI,CAAE,MAAM,SAAS,IAAI;GAAE,OAAO,OAAO;GAAO,IAAI,OAAO,KAAK;EAAG,CAAC,GAClE,MAAM,IAAI,QAAQ,KAAK,EAAE,OAAO,oBAAoB,CAAC;EAEvD,OAAO;GAAE,OAAO,OAAO;GAAO,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