@tokenoftrust/storefront-runner 7.3.1 → 7.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (414) hide show
  1. package/agency-kit/tools/lib/catalog-model/files.mjs +11 -4
  2. package/agency-kit/tools/lib/catalog-model/model.mjs +5 -1
  3. package/agency-kit/tools/lib/redirect-shadows.mjs +261 -0
  4. package/apps/storefront/astro.config.mjs +8 -2
  5. package/apps/storefront/package.json +1 -2
  6. package/apps/storefront/src/components/catalog/storefront/ProductCard.astro +20 -6
  7. package/apps/storefront/src/components/catalog/storefront/islands/ImageGallery.tsx +17 -6
  8. package/apps/storefront/src/components/compliance/storefront/islands/CheckoutComplianceGate.tsx +1 -32
  9. package/apps/storefront/src/config/compliance/rulesets.ts +1 -1
  10. package/apps/storefront/src/layouts/Layout.astro +17 -0
  11. package/apps/storefront/src/lib/access/auth/agentRoles.ts +20 -0
  12. package/apps/storefront/src/lib/access/auth/agentSessionGate.ts +147 -0
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +67 -1
  14. package/apps/storefront/src/lib/access/auth/contactReaderAuthority.ts +39 -0
  15. package/apps/storefront/src/lib/access/auth/loginGate.ts +15 -17
  16. package/apps/storefront/src/lib/access/auth/session.ts +79 -0
  17. package/apps/storefront/src/lib/access/dashboard/staffAdmission.ts +5 -0
  18. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  19. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  20. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  21. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  22. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  23. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  24. package/apps/storefront/src/lib/activity/store.ts +9 -3
  25. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  26. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  27. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  28. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  29. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  30. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  31. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +447 -0
  32. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  33. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  34. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  35. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  36. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  37. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  38. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  39. package/apps/storefront/src/middleware/index.ts +40 -1
  40. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  41. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  42. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  43. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  44. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  45. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  46. package/apps/storefront/tsconfig.astro.json +11 -0
  47. package/package.json +1 -1
  48. package/packages/public-runtime/src/activity/README.md +12 -0
  49. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  50. package/packages/public-runtime/src/activity/event.ts +19 -0
  51. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  52. package/packages/public-runtime/src/catalog-files.ts +3 -2
  53. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  54. package/packages/public-runtime/src/checkout.ts +70 -0
  55. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  56. package/packages/public-runtime/src/compliance/index.ts +1 -1
  57. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  58. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  59. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  60. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  61. package/packages/public-runtime/src/product.ts +9 -1
  62. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  63. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  64. package/pnpm-lock.runner.yaml +0 -15
  65. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  66. package/scripts/tenant/validate.mjs +128 -0
  67. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  68. package/apps/storefront/drizzle.config.apps.ts +0 -13
  69. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  70. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  71. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  72. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  73. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  74. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  75. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  76. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  77. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  78. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  79. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  80. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  81. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  82. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  83. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  84. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  85. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  86. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  87. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  88. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  89. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  90. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  91. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  92. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  93. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  94. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  95. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  96. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  97. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  98. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  99. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  100. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  101. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  102. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  103. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  104. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  105. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  106. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  107. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  108. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  109. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  110. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  111. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  112. package/apps/storefront/perf/README.md +0 -64
  113. package/apps/storefront/perf/assert-budgets.ts +0 -159
  114. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  115. package/apps/storefront/playwright.config.ts +0 -23
  116. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  117. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  118. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  119. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  120. package/apps/storefront/public/js/dashboard-team.js +0 -356
  121. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  122. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  123. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  124. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  125. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  126. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  127. package/apps/storefront/src/config/storeName.ts +0 -34
  128. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  129. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  130. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  131. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  132. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  133. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  134. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  135. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  136. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  137. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -150
  138. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -452
  139. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  140. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  141. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  142. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  143. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  144. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  145. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  146. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  147. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  148. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  149. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  150. package/apps/storefront/src/lib/activity/query.ts +0 -403
  151. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  152. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  153. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  154. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  155. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  156. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  157. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  158. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  159. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  160. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  161. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  162. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  163. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  164. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  165. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  166. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  167. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  168. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  169. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  172. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  173. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  174. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  175. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  176. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  177. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  178. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  179. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  180. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  181. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  182. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  183. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  184. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  185. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  186. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  187. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  188. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  189. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  190. package/apps/storefront/src/lib/content/index.ts +0 -27
  191. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  192. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  193. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  194. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  195. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  196. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  197. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  198. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  199. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  200. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  201. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  202. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  203. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  204. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  205. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  206. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  207. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  208. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  209. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  210. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  211. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  212. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  213. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  214. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  215. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  216. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  221. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  222. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  223. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  224. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  225. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  226. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  227. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  228. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  229. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  230. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  231. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  232. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  233. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  234. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  235. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  236. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  237. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  238. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  239. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  240. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  241. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  242. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  243. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  244. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  245. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  246. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  247. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  248. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  249. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  250. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  251. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  252. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  253. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  254. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  255. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  256. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  257. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  258. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  259. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  260. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  261. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  262. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  263. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  264. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  265. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  266. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  267. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  268. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  269. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  270. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  271. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  272. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  273. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  274. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  275. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  276. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  277. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  278. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  279. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  280. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  281. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  282. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  283. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  284. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  285. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  286. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  287. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  288. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  289. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  290. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  291. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  292. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  293. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  294. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  295. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  296. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  297. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  298. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  299. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  300. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  301. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  302. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  303. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  304. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  305. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  306. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  307. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  308. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  309. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  310. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  311. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  312. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  313. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  314. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  315. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  316. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  317. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  318. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  319. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  320. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  321. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  322. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  323. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  324. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  325. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  326. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  327. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  328. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  329. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  330. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  331. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  332. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  333. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  334. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  335. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  336. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  337. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  338. package/apps/storefront/src/pages/api/contact.ts +0 -144
  339. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  340. package/apps/storefront/src/styles/admin.css +0 -1161
  341. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  342. package/apps/storefront/test/pipeline/harness.ts +0 -209
  343. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  344. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  345. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  346. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  347. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  348. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  349. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  350. package/apps/storefront/vitest.config.cts +0 -44
  351. package/apps/storefront/vitest.faults.config.cts +0 -13
  352. package/apps/storefront/vitest.workers.config.cts +0 -7
  353. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  354. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  355. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  356. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  357. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  358. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  359. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  360. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  361. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  362. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  363. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  364. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  365. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  366. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  367. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  368. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  369. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  370. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  371. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  372. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  373. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  374. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  375. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  376. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  377. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  378. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  379. package/packages/feedback/package.json +0 -35
  380. package/packages/feedback/scripts/build-player.mjs +0 -28
  381. package/packages/feedback/src/index.ts +0 -1
  382. package/packages/feedback/src/primitives/composer.ts +0 -639
  383. package/packages/feedback/src/primitives/dialog.ts +0 -263
  384. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  385. package/packages/feedback/src/primitives/index.ts +0 -10
  386. package/packages/feedback/src/primitives/launcher.ts +0 -200
  387. package/packages/feedback/src/primitives/picker.ts +0 -663
  388. package/packages/feedback/src/primitives/redaction.ts +0 -204
  389. package/packages/feedback/src/primitives/selection.ts +0 -49
  390. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  391. package/packages/feedback/src/primitives/styles.ts +0 -77
  392. package/packages/feedback/src/primitives/surface.ts +0 -124
  393. package/packages/feedback/src/primitives/target.ts +0 -293
  394. package/packages/feedback/src/tour/canonical.ts +0 -27
  395. package/packages/feedback/src/tour/index.ts +0 -3
  396. package/packages/feedback/src/tour/player/browser.ts +0 -5
  397. package/packages/feedback/src/tour/player/host.ts +0 -12
  398. package/packages/feedback/src/tour/player/index.ts +0 -205
  399. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  400. package/packages/feedback/src/tour/player/player.css +0 -130
  401. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  402. package/packages/feedback/src/tour/player/surface.ts +0 -295
  403. package/packages/feedback/src/tour/player/types.ts +0 -8
  404. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  405. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  406. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  407. package/packages/feedback/src/tour/sanitize.ts +0 -76
  408. package/packages/feedback/src/tour/schema.ts +0 -362
  409. package/packages/feedback/src/v1/guards.ts +0 -335
  410. package/packages/feedback/src/v1/index.ts +0 -3
  411. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  412. package/packages/feedback/src/v1/types.ts +0 -177
  413. package/packages/feedback/tsconfig.json +0 -9
  414. package/packages/feedback/vitest.config.cts +0 -21
@@ -1,903 +0,0 @@
1
- /**
2
- * Webhook event/delivery storage. Owns the `webhook_events` / `webhook_deliveries` /
3
- * `webhook_delivery_attempts` / `webhook_install_health` rows described in
4
- * `../d1/schema.ts`. Signing, the retry/backoff dispatcher, event
5
- * emission/targeting, and the `/webhooks/*` routes all build on this store; none
6
- * of that policy lives here.
7
- *
8
- * Pure over the `Queryable` seam (see `../d1/catalog.ts`) — the same shape
9
- * `AppRegistryService` uses, so this runs unchanged against real D1 in the
10
- * Worker and an in-memory `node:sqlite` in tests.
11
- *
12
- * Two ids matter and are easy to conflate:
13
- * - `eventId` (`webhook_events.id`) — the semantic event; ONE per business
14
- * occurrence (e.g. one order.created). Never sent on the wire directly.
15
- * - `deliveryId` (`webhook_deliveries.delivery_id`) — the CloudEvents
16
- * envelope `id` for one (event × target install) delivery. This is what
17
- * goes on the wire and is what receivers dedupe on; it stays stable
18
- * across that delivery's own retries AND across a manual replay
19
- * (`requeueForReplay` resets state/attempts on the SAME row rather
20
- * than minting a new one — a receiver that already acked a delivered
21
- * delivery must still dedupe a replayed resend of it).
22
- *
23
- * Responsibility split for the two mutating paths a dispatcher
24
- * drives per attempt:
25
- * - `recordAttempt` is dumb bookkeeping of ONE HTTP attempt's outcome: it
26
- * appends to `webhook_delivery_attempts`, bumps the delivery's
27
- * `attempts`/`last_*` columns, and folds the outcome into the install's
28
- * health rollup (`lastSuccessAt`/`failureStreak`/`last_*`/recent trace
29
- * ids). It never changes `state`.
30
- * - `transitionState` is the retry-POLICY decision (how many attempts,
31
- * what backoff, when to give up) — deliberately left to the caller, not
32
- * computed here. It only moves `state` (and `next_attempt_at`), and
33
- * bumps `dlqCount` on the one transition that means "gave up":
34
- * dead-lettering.
35
- *
36
- * The `Queryable` seam has no multi-statement transaction primitive, so
37
- * "transactionally-in-spirit" here means: do the writes in a fixed order
38
- * (attempt row, then delivery row, then health rollup) and always re-read
39
- * the delivery via `getOrThrowDelivery` before returning it, the same
40
- * read-after-write discipline `AppRegistryService` uses.
41
- */
42
- import type { Queryable } from "../../catalog/d1/catalog.js";
43
- import { TOPIC_REQUIRED_SCOPE } from "./events.js";
44
- import { COMMERCE_TOPICS, commercePayloadAdmissible, type CommerceTopic } from "./commercePayloads.js";
45
- import { appInstallEnvForStage } from "../apps/appInstallEnv.js";
46
- import type { CommerceStage } from "@tot/public-runtime";
47
-
48
- /** Mirrors the `Delivery.topic` / CloudEvents channel enum in the D1/D2 contract. */
49
- export type WebhookTopic =
50
- | "app.installed"
51
- | "app.uninstalled"
52
- | "catalog.product.updated"
53
- | "inventory.changed"
54
- | "order.created"
55
- | "order.paid"
56
- | "order.fulfilled"
57
- | "order.partially_fulfilled"
58
- | "order.cancelled"
59
- | "order.updated"
60
- | "customer.marketing_consent.updated"
61
- | "attribution.finalized"
62
- | "fulfillment.assignment.created"
63
- | "fulfillment.assignment.updated"
64
- | "fulfillment.label.voided";
65
-
66
- /** Mirrors `Delivery.state` in `docs/private-apps/contract/openapi.yaml` EXACTLY. */
67
- export type DeliveryState = "pending" | "retrying" | "delivered" | "dead-lettered";
68
-
69
- export interface WebhookEvent {
70
- id: string;
71
- tenantId: string;
72
- topic: WebhookTopic;
73
- dataschemaVersion: string;
74
- /** The CloudEvents `data` payload — event-specific shape, opaque to the store. */
75
- payload: unknown;
76
- createdAt: string;
77
- }
78
-
79
- export interface WebhookDelivery {
80
- deliveryId: string;
81
- eventId: string;
82
- installId: string;
83
- tenantId: string;
84
- topic: WebhookTopic;
85
- state: DeliveryState;
86
- attempts: number;
87
- lastStatus: number | null;
88
- lastErrorClass: string | null;
89
- lastTraceId: string | null;
90
- nextAttemptAt: string | null;
91
- createdAt: string;
92
- updatedAt: string;
93
- }
94
-
95
- /** The openapi `InstallHealth` shape — no field is required there, so a fresh install reads as healthy/zeroed. */
96
- export interface InstallHealth {
97
- status: "healthy" | "degraded" | "unhealthy";
98
- lastSuccessAt?: string;
99
- failureStreak: number;
100
- dlqCount: number;
101
- /** p95 delivery latency (ms) across the install's recent attempts — see {@link WebhookDeliveryStore.getInstallHealth}. Absent when no attempt has a recorded duration. */
102
- p95DeliveryMs?: number;
103
- lastStatus?: number;
104
- lastErrorClass?: string;
105
- recentTraceIds: string[];
106
- }
107
-
108
- /** The install's current dead-lettered deliveries: how many, and when the oldest parked. */
109
- export interface DeadLetterSummary {
110
- count: number;
111
- oldestAt: string | null;
112
- }
113
-
114
- export interface CreateEventInput {
115
- /** Optional caller-supplied event id (e.g. for a caller-owned idempotency key). Defaults to a fresh UUID. */
116
- eventId?: string;
117
- tenantId: string;
118
- topic: WebhookTopic;
119
- dataschemaVersion: string;
120
- payload: unknown;
121
- }
122
-
123
- export interface DeliveryTarget {
124
- installId: string;
125
- /** Optional caller-supplied delivery id. Defaults to a fresh UUID (the wire CloudEvents `id`). */
126
- deliveryId?: string;
127
- }
128
-
129
- export interface CreateEventResult {
130
- event: WebhookEvent;
131
- deliveries: WebhookDelivery[];
132
- }
133
-
134
- export interface ListDeliveriesOptions {
135
- state?: DeliveryState;
136
- /** Cap the result, newest first. Used internally by {@link WebhookDeliveryStore.getInstallHealth} to bound its p95 sample; unset means unbounded. */
137
- limit?: number;
138
- }
139
-
140
- export interface RecordAttemptInput {
141
- deliveryId: string;
142
- attemptNo: number;
143
- startedAt: string;
144
- durationMs?: number | null;
145
- httpStatus?: number | null;
146
- errorClass?: string | null;
147
- traceId?: string | null;
148
- }
149
-
150
- export interface TransitionStateInput {
151
- deliveryId: string;
152
- toState: DeliveryState;
153
- /** Required (and only meaningful) when `toState` is `"retrying"`. */
154
- nextAttemptAt?: string | null;
155
- }
156
-
157
- export interface ScanDueRetriesInput {
158
- /** Deliveries with `next_attempt_at <= now` are due. */
159
- now: string;
160
- limit?: number;
161
- }
162
-
163
- export type WebhookStoreErrorCode = "not_found" | "invalid_transition";
164
-
165
- /** Thrown by every rule violation below — callers branch on `.code`. */
166
- export class WebhookStoreError extends Error {
167
- constructor(
168
- message: string,
169
- readonly code: WebhookStoreErrorCode,
170
- ) {
171
- super(message);
172
- this.name = "WebhookStoreError";
173
- }
174
- }
175
-
176
- const MAX_RECENT_TRACE_IDS = 10;
177
-
178
- // How many of an install's most recent deliveries feed the p95 sample in
179
- // `getInstallHealth` — a bound, not a precise percentile guarantee; recent
180
- // behavior is what the health view cares about, not all-time history.
181
- const P95_SAMPLE_SIZE = 50;
182
-
183
- // A delivery only ever moves forward via `transitionState`; `delivered`/
184
- // `dead-lettered` are terminal THERE. A manual replay (`requeueForReplay`)
185
- // is the one deliberate exception: it resets a delivery
186
- // out of a terminal state back to `pending` on the SAME row, bypassing this
187
- // table entirely — see that method's own doc comment for why.
188
- const ALLOWED_TRANSITIONS: Record<DeliveryState, readonly DeliveryState[]> = {
189
- pending: ["retrying", "delivered", "dead-lettered"],
190
- retrying: ["retrying", "delivered", "dead-lettered"],
191
- delivered: [],
192
- "dead-lettered": [],
193
- };
194
-
195
- // Failure-streak thresholds for the `InstallHealth.status` rollup. A DLQ hit
196
- // always reads as unhealthy, regardless of streak.
197
- const DEGRADED_FAILURE_STREAK = 1;
198
- const UNHEALTHY_FAILURE_STREAK = 5;
199
-
200
- function isSuccessAttempt(httpStatus: number | null | undefined): boolean {
201
- return httpStatus != null && httpStatus >= 200 && httpStatus < 300;
202
- }
203
-
204
- /** Prepend a trace id (if present) and cap the list, newest first. */
205
- function pushTraceId(existing: string[], traceId: string | null | undefined): string[] {
206
- if (!traceId) return existing;
207
- return [traceId, ...existing].slice(0, MAX_RECENT_TRACE_IDS);
208
- }
209
-
210
- /** Raw `webhook_events` row shape (snake_case columns). */
211
- interface EventRow {
212
- id: string;
213
- tenant_id: string;
214
- topic: string;
215
- dataschema_version: string;
216
- payload: string;
217
- created_at: string;
218
- }
219
-
220
- /** Raw `webhook_deliveries` row shape (snake_case columns). */
221
- interface DeliveryRow {
222
- delivery_id: string;
223
- event_id: string;
224
- install_id: string;
225
- tenant_id: string;
226
- topic: string;
227
- state: string;
228
- attempts: number;
229
- last_status: number | null;
230
- last_error_class: string | null;
231
- last_trace_id: string | null;
232
- next_attempt_at: string | null;
233
- created_at: string;
234
- updated_at: string;
235
- }
236
-
237
- /** Raw `webhook_install_health` row shape (snake_case columns). */
238
- interface HealthRow {
239
- install_id: string;
240
- last_success_at: string | null;
241
- failure_streak: number;
242
- dlq_count: number;
243
- last_status: number | null;
244
- last_error_class: string | null;
245
- recent_trace_ids: string;
246
- updated_at: string;
247
- }
248
-
249
- function toDomain(row: DeliveryRow): WebhookDelivery {
250
- return {
251
- deliveryId: row.delivery_id,
252
- eventId: row.event_id,
253
- installId: row.install_id,
254
- tenantId: row.tenant_id,
255
- topic: row.topic as WebhookTopic,
256
- state: row.state as DeliveryState,
257
- attempts: row.attempts,
258
- lastStatus: row.last_status,
259
- lastErrorClass: row.last_error_class,
260
- lastTraceId: row.last_trace_id,
261
- nextAttemptAt: row.next_attempt_at,
262
- createdAt: row.created_at,
263
- updatedAt: row.updated_at,
264
- };
265
- }
266
-
267
- function toEventDomain(row: EventRow): WebhookEvent {
268
- return {
269
- id: row.id,
270
- tenantId: row.tenant_id,
271
- topic: row.topic as WebhookTopic,
272
- dataschemaVersion: row.dataschema_version,
273
- payload: JSON.parse(row.payload) as unknown,
274
- createdAt: row.created_at,
275
- };
276
- }
277
-
278
- function healthStatus(row: HealthRow | null): InstallHealth["status"] {
279
- if (!row) return "healthy";
280
- if (row.dlq_count > 0 || row.failure_streak >= UNHEALTHY_FAILURE_STREAK) return "unhealthy";
281
- if (row.failure_streak >= DEGRADED_FAILURE_STREAK) return "degraded";
282
- return "healthy";
283
- }
284
-
285
- function toInstallHealth(row: HealthRow | null): InstallHealth {
286
- return {
287
- status: healthStatus(row),
288
- lastSuccessAt: row?.last_success_at ?? undefined,
289
- failureStreak: row?.failure_streak ?? 0,
290
- dlqCount: row?.dlq_count ?? 0,
291
- lastStatus: row?.last_status ?? undefined,
292
- lastErrorClass: row?.last_error_class ?? undefined,
293
- recentTraceIds: row ? (JSON.parse(row.recent_trace_ids) as string[]) : [],
294
- };
295
- }
296
-
297
- export class WebhookDeliveryStore {
298
- constructor(
299
- private readonly db: Queryable,
300
- private readonly now: () => string = () => new Date().toISOString(),
301
- ) {}
302
-
303
- /**
304
- * Write one immutable event, then fan it out to one `pending` delivery per
305
- * target install. Targeting (which installs get the event) is the caller's
306
- * job — this just persists whatever target list it's handed.
307
- */
308
- async createEvent(input: CreateEventInput, targets: readonly DeliveryTarget[]): Promise<CreateEventResult> {
309
- const eventId = input.eventId ?? crypto.randomUUID();
310
- const now = this.now();
311
-
312
- await this.db.run(
313
- `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
314
- VALUES (?,?,?,?,?,?)`,
315
- eventId,
316
- input.tenantId,
317
- input.topic,
318
- input.dataschemaVersion,
319
- JSON.stringify(input.payload),
320
- now,
321
- );
322
-
323
- const deliveries: WebhookDelivery[] = [];
324
- for (const target of targets) {
325
- const deliveryId = target.deliveryId ?? crypto.randomUUID();
326
- await this.db.run(
327
- `INSERT INTO webhook_deliveries
328
- (delivery_id, event_id, install_id, tenant_id, topic, state, attempts, created_at, updated_at)
329
- VALUES (?,?,?,?,?,'pending',0,?,?)`,
330
- deliveryId,
331
- eventId,
332
- target.installId,
333
- input.tenantId,
334
- input.topic,
335
- now,
336
- now,
337
- );
338
- deliveries.push(await this.getOrThrowDelivery(deliveryId));
339
- }
340
-
341
- return {
342
- event: {
343
- id: eventId,
344
- tenantId: input.tenantId,
345
- topic: input.topic,
346
- dataschemaVersion: input.dataschemaVersion,
347
- payload: input.payload,
348
- createdAt: now,
349
- },
350
- deliveries,
351
- };
352
- }
353
-
354
- /** Read one delivery by id, or `null` if it doesn't exist. */
355
- async getDelivery(deliveryId: string): Promise<WebhookDelivery | null> {
356
- const row = await this.db.first<DeliveryRow>(
357
- `SELECT * FROM webhook_deliveries WHERE delivery_id = ?`,
358
- deliveryId,
359
- );
360
- return row ? toDomain(row) : null;
361
- }
362
-
363
- /**
364
- * Read one event by id, or `null` if it doesn't exist. The dispatcher/delivery
365
- * engine uses it: `attemptDelivery` resolves a
366
- * delivery's `eventId` via `getDelivery`, then needs this to fetch the
367
- * `payload`/`dataschemaVersion` that only `webhook_events` (not
368
- * `webhook_deliveries`) carries, in order to build the CloudEvents
369
- * envelope's `data`.
370
- */
371
- async getEvent(eventId: string): Promise<WebhookEvent | null> {
372
- const row = await this.db.first<EventRow>(`SELECT * FROM webhook_events WHERE id = ?`, eventId);
373
- return row ? toEventDomain(row) : null;
374
- }
375
-
376
- /** All deliveries for one install (an install only ever sees its own — enforced by the caller), newest first. Optionally capped via `opts.limit`. */
377
- async listDeliveriesByInstall(
378
- installId: string,
379
- opts: ListDeliveriesOptions = {},
380
- ): Promise<WebhookDelivery[]> {
381
- const params: unknown[] = [installId];
382
- let sql = `SELECT * FROM webhook_deliveries WHERE install_id = ?`;
383
- if (opts.state) {
384
- sql += ` AND state = ?`;
385
- params.push(opts.state);
386
- }
387
- sql += ` ORDER BY created_at DESC`;
388
- if (opts.limit != null) {
389
- sql += ` LIMIT ?`;
390
- params.push(opts.limit);
391
- }
392
- const rows = await this.db.all<DeliveryRow>(sql, ...params);
393
- return rows.map(toDomain);
394
- }
395
-
396
- /**
397
- * All deliveries for a tenant, across every install (the ops/support admin
398
- * view — an install only ever sees its OWN deliveries via
399
- * {@link listDeliveriesByInstall}; this is the tenant-wide superset), newest
400
- * first.
401
- */
402
- async listDeliveriesByTenant(
403
- tenantId: string,
404
- opts: ListDeliveriesOptions = {},
405
- ): Promise<WebhookDelivery[]> {
406
- const rows = opts.state
407
- ? await this.db.all<DeliveryRow>(
408
- `SELECT * FROM webhook_deliveries WHERE tenant_id = ? AND state = ? ORDER BY created_at DESC`,
409
- tenantId,
410
- opts.state,
411
- )
412
- : await this.db.all<DeliveryRow>(
413
- `SELECT * FROM webhook_deliveries WHERE tenant_id = ? ORDER BY created_at DESC`,
414
- tenantId,
415
- );
416
- return rows.map(toDomain);
417
- }
418
-
419
- /**
420
- * Record the outcome of one HTTP delivery attempt: append it to
421
- * `webhook_delivery_attempts`, bump the delivery's `attempts`/`last_*`
422
- * columns, and fold the outcome into the install's health rollup. Does
423
- * NOT change `state` — see {@link transitionState}.
424
- */
425
- async recordAttempt(input: RecordAttemptInput): Promise<WebhookDelivery> {
426
- const row = await this.mustFindDeliveryRow(input.deliveryId);
427
- const now = this.now();
428
-
429
- await this.db.run(
430
- `INSERT INTO webhook_delivery_attempts
431
- (id, delivery_id, attempt_no, started_at, duration_ms, http_status, error_class, trace_id)
432
- VALUES (?,?,?,?,?,?,?,?)`,
433
- crypto.randomUUID(),
434
- input.deliveryId,
435
- input.attemptNo,
436
- input.startedAt,
437
- input.durationMs ?? null,
438
- input.httpStatus ?? null,
439
- input.errorClass ?? null,
440
- input.traceId ?? null,
441
- );
442
-
443
- await this.db.run(
444
- `UPDATE webhook_deliveries
445
- SET attempts = ?, last_status = ?, last_error_class = ?, last_trace_id = ?, updated_at = ?
446
- WHERE delivery_id = ?`,
447
- row.attempts + 1,
448
- input.httpStatus ?? null,
449
- input.errorClass ?? null,
450
- input.traceId ?? null,
451
- now,
452
- input.deliveryId,
453
- );
454
-
455
- await this.foldAttemptIntoHealth(row.install_id, input, now);
456
-
457
- return this.getOrThrowDelivery(input.deliveryId);
458
- }
459
-
460
- /**
461
- * Move a delivery's `state` forward per `ALLOWED_TRANSITIONS`. The
462
- * caller (the dispatcher) decides WHEN to retry vs. give up; this
463
- * only records that decision. Dead-lettering bumps the install's
464
- * `dlqCount` — the one rollup field {@link recordAttempt} doesn't own.
465
- */
466
- async transitionState(input: TransitionStateInput): Promise<WebhookDelivery> {
467
- const row = await this.mustFindDeliveryRow(input.deliveryId);
468
- const from = row.state as DeliveryState;
469
- if (!ALLOWED_TRANSITIONS[from].includes(input.toState)) {
470
- throw new WebhookStoreError(
471
- `Cannot transition delivery from "${from}" to "${input.toState}".`,
472
- "invalid_transition",
473
- );
474
- }
475
- if (input.toState === "retrying" && !input.nextAttemptAt) {
476
- throw new WebhookStoreError(`A transition to "retrying" requires nextAttemptAt.`, "invalid_transition");
477
- }
478
-
479
- const now = this.now();
480
- const nextAttemptAt = input.toState === "retrying" ? (input.nextAttemptAt as string) : null;
481
- await this.db.run(
482
- `UPDATE webhook_deliveries SET state = ?, next_attempt_at = ?, updated_at = ? WHERE delivery_id = ?`,
483
- input.toState,
484
- nextAttemptAt,
485
- now,
486
- input.deliveryId,
487
- );
488
-
489
- if (input.toState === "dead-lettered") {
490
- await this.bumpDlqCount(row.install_id, now);
491
- }
492
-
493
- return this.getOrThrowDelivery(input.deliveryId);
494
- }
495
-
496
- /**
497
- * Replay support: force a delivery back to `pending` with a
498
- * fresh attempt budget — from ANY current state, INCLUDING the terminal
499
- * `delivered`/`dead-lettered` states `transitionState`/`ALLOWED_TRANSITIONS`
500
- * refuse to leave. This is deliberately a separate write path, not a call
501
- * through `transitionState`: a replay is an operator/app decision to retry
502
- * something the normal retry policy already gave up on (or already
503
- * finished), not a policy-driven transition.
504
- *
505
- * The delivery's `deliveryId` is NEVER reassigned — see the header note on
506
- * why it must stay stable across a replay (a receiver that already acked a
507
- * `delivered` delivery needs the resend to carry the same wire id to
508
- * dedupe it). `attempts` resets to 0 (a fresh {@link MAX_DELIVERY_ATTEMPTS}
509
- * budget, tracked in `dispatcher.ts`) rather than continuing the old count
510
- * — a replay is a new delivery cycle, not "attempt 7" of the old one.
511
- * `webhook_delivery_attempts` — the append-only audit trail — is NEVER
512
- * touched here; only this row's own counters move.
513
- *
514
- * A delivery leaving `dead-lettered` is no longer parked in the DLQ, so the
515
- * install health rollup's `dlqCount` — read here as a CURRENT gauge of
516
- * still-dead-lettered deliveries, not a lifetime counter — is decremented
517
- * (floored at 0) to match.
518
- */
519
- async requeueForReplay(deliveryId: string): Promise<WebhookDelivery> {
520
- const row = await this.mustFindDeliveryRow(deliveryId);
521
- const now = this.now();
522
-
523
- await this.db.run(
524
- `UPDATE webhook_deliveries
525
- SET state = 'pending', attempts = 0, next_attempt_at = ?, updated_at = ?
526
- WHERE delivery_id = ?`,
527
- now,
528
- now,
529
- deliveryId,
530
- );
531
-
532
- if (row.state === "dead-lettered") {
533
- await this.decrementDlqCount(row.install_id, now);
534
- }
535
-
536
- return this.getOrThrowDelivery(deliveryId);
537
- }
538
-
539
- /**
540
- * The `InstallHealth` rollup for one install — a never-attempted install
541
- * reads as healthy/zeroed. `p95DeliveryMs` is computed here at READ time
542
- * (not tracked as a running rollup column): no migration, no extra write
543
- * on the `recordAttempt` hot path, just this one bounded read.
544
- */
545
- async getInstallHealth(installId: string): Promise<InstallHealth> {
546
- const row = await this.db.first<HealthRow>(
547
- `SELECT * FROM webhook_install_health WHERE install_id = ?`,
548
- installId,
549
- );
550
- const health = toInstallHealth(row);
551
- const p95DeliveryMs = await this.computeP95DeliveryMs(installId);
552
- return p95DeliveryMs != null ? { ...health, p95DeliveryMs } : health;
553
- }
554
-
555
- /** Counts the install's deliveries in `dead-lettered` now; `oldestAt` is when the oldest one parked. */
556
- async deadLetterSummary(installId: string): Promise<DeadLetterSummary> {
557
- const row = await this.db.first<{ count: number; oldest_at: string | null }>(
558
- `SELECT COUNT(*) AS count, MIN(updated_at) AS oldest_at
559
- FROM webhook_deliveries WHERE install_id = ? AND state = 'dead-lettered'`,
560
- installId,
561
- );
562
- return { count: Number(row?.count ?? 0), oldestAt: row?.oldest_at ?? null };
563
- }
564
-
565
- /**
566
- * p95 across `webhook_delivery_attempts.duration_ms` for the install's
567
- * {@link P95_SAMPLE_SIZE} most recent deliveries — one bounded `IN (...)`
568
- * read over that fixed set of delivery ids, sorted in JS (the sample is
569
- * small enough that a DB-side percentile isn't worth the SQL). Nearest-rank
570
- * method: `ceil(n * 0.95)`th smallest value, 1-indexed. `undefined` when no
571
- * attempt in the sample has a recorded duration.
572
- */
573
- private async computeP95DeliveryMs(installId: string): Promise<number | undefined> {
574
- const recent = await this.listDeliveriesByInstall(installId, { limit: P95_SAMPLE_SIZE });
575
- if (recent.length === 0) return undefined;
576
-
577
- const placeholders = recent.map(() => "?").join(",");
578
- const rows = await this.db.all<{ duration_ms: number | null }>(
579
- `SELECT duration_ms FROM webhook_delivery_attempts WHERE delivery_id IN (${placeholders})`,
580
- ...recent.map((d) => d.deliveryId),
581
- );
582
- const durations = rows
583
- .map((r) => r.duration_ms)
584
- .filter((d): d is number => d != null)
585
- .sort((a, b) => a - b);
586
- if (durations.length === 0) return undefined;
587
-
588
- const index = Math.min(durations.length - 1, Math.ceil(durations.length * 0.95) - 1);
589
- return durations[index];
590
- }
591
-
592
- /** Deliveries in `retrying` whose `next_attempt_at` is due, earliest first. Uses `idx_webhook_deliveries_due`. */
593
- async scanDueRetries(params: ScanDueRetriesInput): Promise<WebhookDelivery[]> {
594
- const limit = params.limit ?? 100;
595
- const rows = await this.db.all<DeliveryRow>(
596
- `SELECT * FROM webhook_deliveries
597
- WHERE state = 'retrying' AND next_attempt_at <= ?
598
- ORDER BY next_attempt_at ASC
599
- LIMIT ?`,
600
- params.now,
601
- limit,
602
- );
603
- return rows.map(toDomain);
604
- }
605
-
606
- private async foldAttemptIntoHealth(installId: string, attempt: RecordAttemptInput, now: string): Promise<void> {
607
- const existing = await this.findHealthRow(installId);
608
- const success = isSuccessAttempt(attempt.httpStatus);
609
- const recentTraceIds = pushTraceId(
610
- existing ? (JSON.parse(existing.recent_trace_ids) as string[]) : [],
611
- attempt.traceId,
612
- );
613
-
614
- await this.writeHealthRow(installId, now, {
615
- lastSuccessAt: success ? now : existing?.last_success_at ?? null,
616
- failureStreak: success ? 0 : (existing?.failure_streak ?? 0) + 1,
617
- dlqCount: existing?.dlq_count ?? 0,
618
- lastStatus: attempt.httpStatus ?? existing?.last_status ?? null,
619
- lastErrorClass: success ? null : attempt.errorClass ?? existing?.last_error_class ?? null,
620
- recentTraceIds,
621
- });
622
- }
623
-
624
- private async bumpDlqCount(installId: string, now: string): Promise<void> {
625
- const existing = await this.findHealthRow(installId);
626
- await this.writeHealthRow(installId, now, {
627
- lastSuccessAt: existing?.last_success_at ?? null,
628
- failureStreak: existing?.failure_streak ?? 0,
629
- dlqCount: (existing?.dlq_count ?? 0) + 1,
630
- lastStatus: existing?.last_status ?? null,
631
- lastErrorClass: existing?.last_error_class ?? null,
632
- recentTraceIds: existing ? (JSON.parse(existing.recent_trace_ids) as string[]) : [],
633
- });
634
- }
635
-
636
- /** {@link requeueForReplay}'s counterpart to `bumpDlqCount` — floors at 0; a no-op if the install has no health row yet. */
637
- private async decrementDlqCount(installId: string, now: string): Promise<void> {
638
- const existing = await this.findHealthRow(installId);
639
- if (!existing) return;
640
- await this.writeHealthRow(installId, now, {
641
- lastSuccessAt: existing.last_success_at,
642
- failureStreak: existing.failure_streak,
643
- dlqCount: Math.max(0, existing.dlq_count - 1),
644
- lastStatus: existing.last_status,
645
- lastErrorClass: existing.last_error_class,
646
- recentTraceIds: JSON.parse(existing.recent_trace_ids) as string[],
647
- });
648
- }
649
-
650
- private async findHealthRow(installId: string): Promise<HealthRow | null> {
651
- return this.db.first<HealthRow>(`SELECT * FROM webhook_install_health WHERE install_id = ?`, installId);
652
- }
653
-
654
- private async writeHealthRow(
655
- installId: string,
656
- now: string,
657
- patch: {
658
- lastSuccessAt: string | null;
659
- failureStreak: number;
660
- dlqCount: number;
661
- lastStatus: number | null;
662
- lastErrorClass: string | null;
663
- recentTraceIds: string[];
664
- },
665
- ): Promise<void> {
666
- await this.db.run(
667
- `INSERT OR REPLACE INTO webhook_install_health
668
- (install_id, last_success_at, failure_streak, dlq_count, last_status, last_error_class, recent_trace_ids, updated_at)
669
- VALUES (?,?,?,?,?,?,?,?)`,
670
- installId,
671
- patch.lastSuccessAt,
672
- patch.failureStreak,
673
- patch.dlqCount,
674
- patch.lastStatus,
675
- patch.lastErrorClass,
676
- JSON.stringify(patch.recentTraceIds),
677
- now,
678
- );
679
- }
680
-
681
- /** Fetch a row or throw the generic fail-closed `not_found` — no enumeration detail. */
682
- private async mustFindDeliveryRow(deliveryId: string): Promise<DeliveryRow> {
683
- const row = await this.db.first<DeliveryRow>(
684
- `SELECT * FROM webhook_deliveries WHERE delivery_id = ?`,
685
- deliveryId,
686
- );
687
- if (!row) throw new WebhookStoreError(`Webhook delivery not found.`, "not_found");
688
- return row;
689
- }
690
-
691
- private async getOrThrowDelivery(deliveryId: string): Promise<WebhookDelivery> {
692
- return toDomain(await this.mustFindDeliveryRow(deliveryId));
693
- }
694
- }
695
-
696
- /** A commerce delivery enqueued after its commit becomes the tenant commerce alarm's only after this long. */
697
- export const COMMERCE_DELIVERY_GRACE_MS = 60_000;
698
-
699
- /** `asyncapi.yaml`'s `dataschemaversion` for V1. */
700
- export const COMMERCE_DATASCHEMA_VERSION = "1";
701
-
702
- /** Thrown before any statement is built when a commerce payload fails its topic's closed schema. */
703
- export class CommercePayloadRefused extends Error {
704
- constructor(readonly topic: CommerceTopic) {
705
- super("commerce-payload-refused");
706
- this.name = "CommercePayloadRefused";
707
- }
708
- }
709
-
710
- export interface CommerceEventStatement {
711
- sql: string;
712
- params: unknown[];
713
- }
714
-
715
- /**
716
- * SQL condition an eligible install row `i` satisfies; binds the tenant id, the install env the
717
- * event's stage admits (`appInstallEnvForStage`), then the topic's required scope. A `test` install
718
- * never receives a `publication` event and a `production` install never a `preview` one.
719
- */
720
- const ELIGIBLE_INSTALL_CONDITION = `i.tenant_id = ? AND i.env = ? AND i.status = 'active' AND i.managed_kind IS NULL
721
- AND COALESCE(i.webhook_endpoint, '') != ''
722
- AND EXISTS (SELECT 1 FROM json_each(i.scopes) WHERE json_each.value = ?)`;
723
-
724
- /** Installs on `tenantId` in `stage`'s install env that would receive `topic` now, oldest first. Statements re-check this at write. */
725
- export function commerceTargetsQuery(tenantId: string, topic: CommerceTopic, stage: CommerceStage): CommerceEventStatement {
726
- return {
727
- sql: `SELECT i.install_id AS install_id FROM app_installs AS i
728
- WHERE ${ELIGIBLE_INSTALL_CONDITION}
729
- ORDER BY i.created_at ASC, i.install_id ASC`,
730
- params: [tenantId, appInstallEnvForStage(stage), TOPIC_REQUIRED_SCOPE[topic]],
731
- };
732
- }
733
-
734
- /**
735
- * The single commerce emitter: one `webhook_events` row written only when `gate` holds, and one
736
- * pending `webhook_deliveries` row per target written only when that event row exists and the
737
- * target install is still eligible — including belonging to the install env `stage` admits. Ids are
738
- * minted by the caller so the statements run inside the batch of the change they report; the
739
- * delivery id is the CloudEvents `id`.
740
- */
741
- export function commerceEventStatements(input: {
742
- eventId: string;
743
- tenantId: string;
744
- stage: CommerceStage;
745
- topic: CommerceTopic;
746
- payload: unknown;
747
- gate: CommerceEventStatement;
748
- targets: readonly { installId: string; deliveryId: string }[];
749
- now: string;
750
- }): CommerceEventStatement[] {
751
- if (!commercePayloadAdmissible(input.topic, input.payload)) throw new CommercePayloadRefused(input.topic);
752
- const statements: CommerceEventStatement[] = [
753
- {
754
- sql: `INSERT INTO webhook_events (id, tenant_id, topic, dataschema_version, payload, created_at)
755
- SELECT ?, ?, ?, ?, ?, ? WHERE (${input.gate.sql})`,
756
- params: [
757
- input.eventId,
758
- input.tenantId,
759
- input.topic,
760
- COMMERCE_DATASCHEMA_VERSION,
761
- JSON.stringify(input.payload),
762
- input.now,
763
- ...input.gate.params,
764
- ],
765
- },
766
- ];
767
- for (const target of input.targets) {
768
- statements.push({
769
- sql: `INSERT INTO webhook_deliveries
770
- (delivery_id, event_id, install_id, tenant_id, topic, state, attempts, created_at, updated_at)
771
- SELECT ?, ?, i.install_id, i.tenant_id, ?, 'pending', 0, ?, ?
772
- FROM app_installs AS i
773
- WHERE i.install_id = ? AND ${ELIGIBLE_INSTALL_CONDITION}
774
- AND EXISTS (SELECT 1 FROM webhook_events WHERE id = ? AND tenant_id = ? AND topic = ?)
775
- AND NOT EXISTS (SELECT 1 FROM webhook_deliveries WHERE event_id = ? AND install_id = ?)`,
776
- params: [
777
- target.deliveryId,
778
- input.eventId,
779
- input.topic,
780
- input.now,
781
- input.now,
782
- target.installId,
783
- input.tenantId,
784
- appInstallEnvForStage(input.stage),
785
- TOPIC_REQUIRED_SCOPE[input.topic],
786
- input.eventId,
787
- input.tenantId,
788
- input.topic,
789
- input.eventId,
790
- target.installId,
791
- ],
792
- });
793
- }
794
- return statements;
795
- }
796
-
797
- /**
798
- * Commerce-topic deliveries for one tenant that the alarm owns: `pending` rows older than the
799
- * enqueue grace, and `retrying` rows whose next attempt is due.
800
- */
801
- export async function dueCommerceDeliveries(
802
- db: Queryable,
803
- tenantId: string,
804
- now: string,
805
- graceMs: number,
806
- ): Promise<{ due: string[]; nextAt: string | null }> {
807
- const cutoff = new Date(Date.parse(now) - graceMs).toISOString();
808
- const topics = [...COMMERCE_TOPICS];
809
- const marks = topics.map(() => "?").join(",");
810
- const rows = await db.all<{ delivery_id: string }>(
811
- `SELECT delivery_id FROM webhook_deliveries
812
- WHERE tenant_id = ? AND topic IN (${marks})
813
- AND ((state = 'pending' AND created_at <= ?) OR (state = 'retrying' AND next_attempt_at <= ?))
814
- ORDER BY created_at ASC, delivery_id ASC LIMIT 100`,
815
- tenantId,
816
- ...topics,
817
- cutoff,
818
- now,
819
- );
820
- const next = await db.first<{ next_at: string | null }>(
821
- `SELECT MIN(CASE WHEN state = 'pending' THEN strftime('%Y-%m-%dT%H:%M:%fZ', created_at, ?) ELSE next_attempt_at END) AS next_at
822
- FROM webhook_deliveries
823
- WHERE tenant_id = ? AND topic IN (${marks})
824
- AND ((state = 'pending' AND created_at > ?) OR (state = 'retrying' AND next_attempt_at > ?))`,
825
- `+${graceMs / 1000} seconds`,
826
- tenantId,
827
- ...topics,
828
- cutoff,
829
- now,
830
- );
831
- return { due: rows.map((row) => row.delivery_id), nextAt: next?.next_at ?? null };
832
- }
833
-
834
- export interface CommerceOutboxDue {
835
- order_id: string;
836
- outbox_id: string;
837
- tenant_id: string;
838
- stage: string;
839
- payload: string;
840
- attempt_count: number;
841
- available_at: string;
842
- }
843
-
844
- /** Due commerce outbox rows. The order ledger owns the insert; this port owns sweep progress. */
845
- export class ScrappyCommerceOutbox {
846
- constructor(private readonly db: Queryable) {}
847
-
848
- async due(now: string, tenantId?: string, stage?: string): Promise<CommerceOutboxDue[]> {
849
- const rows = await this.db.all<CommerceOutboxDue>(
850
- `SELECT outbox_id, tenant_id, stage, order_id, payload, attempt_count, available_at
851
- FROM scrappy_commerce_outbox
852
- WHERE state = 'pending' AND available_at <= ? AND (? IS NULL OR tenant_id=?) AND (? IS NULL OR stage=?)
853
- ORDER BY available_at LIMIT 100`,
854
- now, tenantId ?? null, tenantId ?? null, stage ?? null, stage ?? null,
855
- );
856
- return rows.map((row) => ({ ...row, attempt_count: Number(row.attempt_count) }));
857
- }
858
-
859
- async markDelivered(outboxId: string): Promise<void> {
860
- await this.db.run(
861
- `UPDATE scrappy_commerce_outbox SET state = 'delivered' WHERE outbox_id = ? AND state = 'pending'`,
862
- outboxId,
863
- );
864
- }
865
-
866
- async markRetry(outboxId: string, attemptCount: number, availableAt: string): Promise<void> {
867
- await this.db.run(
868
- `UPDATE scrappy_commerce_outbox
869
- SET state = 'pending', attempt_count = ?, available_at = ?
870
- WHERE outbox_id = ? AND state = 'pending'`,
871
- attemptCount,
872
- availableAt,
873
- outboxId,
874
- );
875
- }
876
-
877
- async markDead(outboxId: string, attemptCount?: number): Promise<void> {
878
- if (attemptCount === undefined) {
879
- await this.db.run(
880
- `UPDATE scrappy_commerce_outbox SET state = 'dead' WHERE outbox_id = ? AND state = 'pending'`,
881
- outboxId,
882
- );
883
- return;
884
- }
885
- await this.db.run(
886
- `UPDATE scrappy_commerce_outbox
887
- SET state = 'dead', attempt_count = ?
888
- WHERE outbox_id = ? AND state = 'pending'`,
889
- attemptCount,
890
- outboxId,
891
- );
892
- }
893
-
894
- async noteCursor(tenantId: string, stage: string, cursor: string): Promise<void> {
895
- await this.db.run(
896
- `INSERT INTO scrappy_sweep_cursor (tenant_id, stage, cursor) VALUES (?,?,?)
897
- ON CONFLICT(tenant_id, stage) DO UPDATE SET cursor = excluded.cursor`,
898
- tenantId,
899
- stage,
900
- cursor,
901
- );
902
- }
903
- }