@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,906 +0,0 @@
1
- /**
2
- * Private Apps inventory writes. An installed app with scope `inventory:write` reports stock into
3
- * the tenant's mirror ledger (`commerce_inventory_movements`, ADR 0033) and declares the locations
4
- * it reports for. It is a merchant-consented mirror: it never decrements for an order, never
5
- * reserves, and is never an authoritative provider.
6
- *
7
- * - `applyAppInventoryDelta`: one per-sku, per-location delta (optionally with a WMS reason).
8
- * - `applyAppInventoryMovements`: a batch of 1..250 WMS movements, each with its reason.
9
- * - `applyAppInventoryLevels`: a batch of 1..250 absolute on-hand levels (reason `reconcile`).
10
- * - `upsertAppInventoryLocation`: declares or updates one location.
11
- *
12
- * Each write is one D1 transaction holding admission, the ledger rows, the audit row, the
13
- * idempotency receipt, the `inventory.changed` events with their pending deliveries, and the
14
- * recomputed availability per sku. A refused batch item rolls the whole transaction back: nothing
15
- * is written. Every field the caller could forge is derived here: `asOf` is the server receive
16
- * time, `source` the app namespace of the install, `sourceEventId` a digest of the namespaced
17
- * idempotency key, `actorId` the authenticated install.
18
- */
19
- import { isStoredSku, parseSku, skuKey } from "@tot/public-runtime/sku";
20
- import type { CatalogProduct, CommerceStage } from "@tot/public-runtime";
21
- import type { Queryable, QueryStatement } from "../../catalog/d1/catalog.js";
22
- import {
23
- availabilitySyncStatements,
24
- availabilityToken,
25
- BATCH_REFUSED_CONSTRAINT,
26
- guardedCorrectionStatement,
27
- itemScope,
28
- LOCATION_KINDS,
29
- LOCATION_STATUSES,
30
- locationAdmittedSql,
31
- locationBalanceSql,
32
- locationScope,
33
- MIRROR_BALANCE_MAX,
34
- MIRROR_LOCATION_UNSPECIFIED,
35
- mirrorLocationKnown,
36
- MOVEMENT_REASONS,
37
- movementEventStatements,
38
- notifyInventoryDeliveries,
39
- onHandDeltaSql,
40
- readInventoryLocation,
41
- RECONCILE_REASON,
42
- type InventoryChangedNotify,
43
- type InventoryLocation,
44
- type LocationKind,
45
- type LocationStatus,
46
- type MovementReason,
47
- type SqlCondition,
48
- type SqlStatement,
49
- } from "../../inventory/mirrorStock.js";
50
- import { checkIdempotency, computeBodyHash } from "./orders/idempotency.js";
51
- import { appInstallEnvForStage } from "./appInstallEnv.js";
52
-
53
- export const INVENTORY_WRITE_SCOPE = "inventory:write";
54
- export const INVENTORY_AUDIT_EVENT = "inventory.corrected";
55
- export const INVENTORY_BATCH_AUDIT_EVENT = "inventory.movements.recorded";
56
- export const INVENTORY_LEVELS_AUDIT_EVENT = "inventory.levels.reconciled";
57
- export const INVENTORY_LOCATION_AUDIT_EVENT = "inventory.location.declared";
58
- /** Most items one movements or levels batch may carry. */
59
- export const INVENTORY_BATCH_MAX = 250;
60
- /** How far ahead of the server clock an `observedAt` may be. */
61
- export const OBSERVED_AT_SKEW_MS = 5 * 60 * 1000;
62
-
63
- const ID = /^[A-Za-z0-9._:-]{1,128}$/;
64
- const IDEMPOTENCY_KEY = /^[\x21-\x7e]{8,128}$/;
65
- const DELTA_KEYS = new Set(["sku", "locationId", "quantityDelta", "reason"]);
66
- const BATCH_MOVEMENT_KEYS = new Set(["sku", "locationId", "quantityDelta", "reason"]);
67
- const LEVEL_KEYS = new Set(["sku", "locationId", "onHand", "observedAt"]);
68
- const LOCATION_KEYS = new Set(["name", "kind", "isFulfillable", "status"]);
69
- const NAME_MAX = 200;
70
- /** An unknown body key a refusal may name back: identifier-shaped and short. Any other is named `body`. */
71
- const ECHOABLE_KEY = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
72
- /** Fields the platform derives; a body naming any of them is refused, never trusted or ignored. */
73
- export const SERVER_DERIVED_FIELDS = ["asOf", "source", "sourceEventId", "actorId"] as const;
74
-
75
- export type InventoryRefusalCode =
76
- | "malformed"
77
- | "server-derived-field"
78
- | "invalid_token"
79
- | "scope_denied"
80
- | "denied"
81
- | "unknown-sku"
82
- | "unknown-location"
83
- | "location-protected"
84
- | "balance-out-of-range"
85
- | "idempotency-conflict"
86
- | "unavailable";
87
-
88
- const STATUS: Record<InventoryRefusalCode, number> = {
89
- malformed: 400,
90
- "server-derived-field": 400,
91
- invalid_token: 401,
92
- scope_denied: 403,
93
- denied: 403,
94
- "unknown-sku": 422,
95
- "unknown-location": 422,
96
- "location-protected": 409,
97
- "balance-out-of-range": 409,
98
- "idempotency-conflict": 409,
99
- unavailable: 503,
100
- };
101
-
102
- export interface InventoryRefusal {
103
- code: InventoryRefusalCode;
104
- error: string;
105
- /** The batch item the refusal names, when it names one. */
106
- index?: number;
107
- /**
108
- * The request part a 400 names: a body field (`kind`, `quantityDelta`, ...), a server-derived
109
- * key, an identifier-shaped unknown key as sent, `body` for any other unknown key and for an
110
- * empty, oversized, non-JSON or non-object body, `items` for the batch array, the path
111
- * parameter `locationId`, or the header `Idempotency-Key`.
112
- */
113
- field?: string;
114
- }
115
-
116
- export interface InventoryReceipt {
117
- receiptId: string;
118
- sku: string;
119
- locationId: string;
120
- quantityDelta: number;
121
- asOf: string;
122
- balance: number;
123
- }
124
-
125
- export interface InventoryMovementsReceipt {
126
- receiptId: string;
127
- asOf: string;
128
- items: { sku: string; locationId: string; quantityDelta: number; reason: MovementReason; balance: number }[];
129
- }
130
-
131
- export interface InventoryLevelsReceipt {
132
- receiptId: string;
133
- asOf: string;
134
- items: { sku: string; locationId: string; onHand: number; observedAt: string; quantityDelta: number; balance: number }[];
135
- }
136
-
137
- export interface InventoryWriteResponse<T = InventoryReceipt> {
138
- status: number;
139
- body: T | InventoryRefusal;
140
- }
141
-
142
- export interface AppInventoryDelta {
143
- sku: string;
144
- locationId: string;
145
- quantityDelta: number;
146
- reason?: MovementReason;
147
- }
148
-
149
- export interface AppInventoryMovement {
150
- sku: string;
151
- locationId: string;
152
- quantityDelta: number;
153
- reason: MovementReason;
154
- }
155
-
156
- export interface AppInventoryLevel {
157
- sku: string;
158
- locationId: string;
159
- onHand: number;
160
- observedAt: string;
161
- }
162
-
163
- export interface AppInventoryLocationInput {
164
- name: string;
165
- kind: LocationKind;
166
- isFulfillable: boolean;
167
- status: LocationStatus;
168
- }
169
-
170
- /** The authenticated install a write runs as. Built by the route from the verified token, never from the body. */
171
- export interface InventoryWriteActor {
172
- tenantId: string;
173
- stage: CommerceStage;
174
- installId: string;
175
- appId: string;
176
- }
177
-
178
- export function inventoryRefusal(code: InventoryRefusalCode, index?: number, field?: string): InventoryWriteResponse<never> {
179
- if (code === "invalid_token") return { status: 401, body: { code, error: "Unauthorized" } };
180
- return {
181
- status: STATUS[code],
182
- body: {
183
- code,
184
- error: field === undefined ? code : `${code}: ${field}`,
185
- ...(index === undefined ? {} : { index }),
186
- ...(field === undefined ? {} : { field }),
187
- },
188
- };
189
- }
190
-
191
- export function isInventoryRefusal(body: unknown): body is InventoryRefusal {
192
- return isRecord(body) && typeof body.code === "string" && typeof body.error === "string";
193
- }
194
-
195
- function isRecord(value: unknown): value is Record<string, unknown> {
196
- return typeof value === "object" && value !== null && !Array.isArray(value);
197
- }
198
-
199
- type ParseRefusal = "malformed" | "server-derived-field";
200
-
201
- /** Why a body is outside its closed schema: the code, the request part it names, and the batch item. */
202
- export interface ParseFailure {
203
- refused: ParseRefusal;
204
- field?: string;
205
- index?: number;
206
- }
207
-
208
- function fail(refused: ParseRefusal, field: string): ParseFailure {
209
- return { refused, field };
210
- }
211
-
212
- function isParseFailure(value: unknown): value is ParseFailure {
213
- return isRecord(value) && (value.refused === "malformed" || value.refused === "server-derived-field");
214
- }
215
-
216
- function closedKeys(body: Record<string, unknown>, allowed: ReadonlySet<string>): ParseFailure | null {
217
- const keys = Object.keys(body);
218
- const derived = keys.find((key) => (SERVER_DERIVED_FIELDS as readonly string[]).includes(key));
219
- if (derived !== undefined) return fail("server-derived-field", derived);
220
- const unknown = keys.find((key) => !allowed.has(key));
221
- if (unknown === undefined) return null;
222
- return fail("malformed", ECHOABLE_KEY.test(unknown) ? unknown : "body");
223
- }
224
-
225
- function parseLocation(value: unknown): string | null {
226
- const location = value ?? MIRROR_LOCATION_UNSPECIFIED;
227
- return typeof location === "string" && ID.test(location) ? location : null;
228
- }
229
-
230
- function parseReason(value: unknown): MovementReason | null {
231
- return typeof value === "string" && (MOVEMENT_REASONS as readonly string[]).includes(value) ? (value as MovementReason) : null;
232
- }
233
-
234
- function isDelta(value: unknown): value is number {
235
- return typeof value === "number" && Number.isSafeInteger(value) && value !== 0;
236
- }
237
-
238
- /** The body in the closed schema, or why it is not. */
239
- export function parseInventoryDelta(body: unknown): AppInventoryDelta | ParseFailure {
240
- if (!isRecord(body)) return fail("malformed", "body");
241
- const refused = closedKeys(body, DELTA_KEYS);
242
- if (refused) return refused;
243
- const sku = parseSku(body.sku);
244
- if (!sku.ok) return fail("malformed", "sku");
245
- const delta = body.quantityDelta;
246
- if (!isDelta(delta)) return fail("malformed", "quantityDelta");
247
- const location = parseLocation(body.locationId);
248
- if (location === null) return fail("malformed", "locationId");
249
- if (body.reason === undefined) return { sku: sku.sku, locationId: location, quantityDelta: delta };
250
- const reason = parseReason(body.reason);
251
- if (reason === null) return fail("malformed", "reason");
252
- return { sku: sku.sku, locationId: location, quantityDelta: delta, reason };
253
- }
254
-
255
- /** True when the body is the batch form (`{ items: [...] }`) rather than one delta. */
256
- export function isInventoryBatchBody(body: unknown): boolean {
257
- return isRecord(body) && "items" in body;
258
- }
259
-
260
- function parseItems<T>(
261
- body: unknown,
262
- parseItem: (item: Record<string, unknown>) => T | ParseFailure,
263
- ): { items: T[] } | ParseFailure {
264
- if (!isRecord(body)) return fail("malformed", "body");
265
- const refused = closedKeys(body, new Set(["items"]));
266
- if (refused) return refused;
267
- const raw = body.items;
268
- if (!Array.isArray(raw) || raw.length < 1 || raw.length > INVENTORY_BATCH_MAX) return fail("malformed", "items");
269
- const items: T[] = [];
270
- for (const [index, entry] of raw.entries()) {
271
- if (!isRecord(entry)) return { refused: "malformed", field: "items", index };
272
- const parsed = parseItem(entry);
273
- if (isParseFailure(parsed)) return { ...parsed, index };
274
- items.push(parsed);
275
- }
276
- return { items };
277
- }
278
-
279
- /** A movements batch in the closed schema: 1..250 items, each with a WMS reason. */
280
- export function parseInventoryMovements(body: unknown): { items: AppInventoryMovement[] } | ParseFailure {
281
- return parseItems(body, (entry) => {
282
- const refused = closedKeys(entry, BATCH_MOVEMENT_KEYS);
283
- if (refused) return refused;
284
- const sku = parseSku(entry.sku);
285
- if (!sku.ok) return fail("malformed", "sku");
286
- const delta = entry.quantityDelta;
287
- if (!isDelta(delta) || Math.abs(delta) > MIRROR_BALANCE_MAX) return fail("malformed", "quantityDelta");
288
- const location = parseLocation(entry.locationId);
289
- if (location === null) return fail("malformed", "locationId");
290
- const reason = parseReason(entry.reason);
291
- if (reason === null) return fail("malformed", "reason");
292
- return { sku: sku.sku, locationId: location, quantityDelta: delta, reason };
293
- });
294
- }
295
-
296
- /** A levels batch in the closed schema: 1..250 absolute on-hand readings, one per (sku, location). */
297
- export function parseInventoryLevels(body: unknown, nowMs: number): { items: AppInventoryLevel[] } | ParseFailure {
298
- const parsed = parseItems<AppInventoryLevel>(body, (entry) => {
299
- const refused = closedKeys(entry, LEVEL_KEYS);
300
- if (refused) return refused;
301
- const sku = parseSku(entry.sku);
302
- if (!sku.ok) return fail("malformed", "sku");
303
- const location = parseLocation(entry.locationId);
304
- if (location === null) return fail("malformed", "locationId");
305
- const onHand = entry.onHand;
306
- if (typeof onHand !== "number" || !Number.isSafeInteger(onHand) || onHand < 0 || onHand > MIRROR_BALANCE_MAX) {
307
- return fail("malformed", "onHand");
308
- }
309
- const observedAt = entry.observedAt;
310
- if (typeof observedAt !== "string" || observedAt.length > 64) return fail("malformed", "observedAt");
311
- const observedMs = Date.parse(observedAt);
312
- if (!Number.isFinite(observedMs) || observedMs > nowMs + OBSERVED_AT_SKEW_MS) return fail("malformed", "observedAt");
313
- return { sku: sku.sku, locationId: location, onHand, observedAt };
314
- });
315
- if (!("items" in parsed)) return parsed;
316
- const seen = new Set<string>();
317
- for (const [index, item] of parsed.items.entries()) {
318
- const key = `${skuKey(item.sku)}\n${item.locationId}`;
319
- if (seen.has(key)) return { refused: "malformed", field: "items", index };
320
- seen.add(key);
321
- }
322
- return parsed;
323
- }
324
-
325
- /** A location declaration in the closed schema, or why it is not. */
326
- export function parseInventoryLocation(body: unknown): AppInventoryLocationInput | ParseFailure {
327
- if (!isRecord(body)) return fail("malformed", "body");
328
- const refused = closedKeys(body, LOCATION_KEYS);
329
- if (refused) return refused;
330
- const { name, kind } = body;
331
- const isFulfillable = body.isFulfillable ?? true;
332
- const status = body.status ?? "active";
333
- if (typeof name !== "string" || name.trim() === "" || name.length > NAME_MAX || /[\u0000-\u001f]/.test(name)) {
334
- return fail("malformed", "name");
335
- }
336
- if (typeof kind !== "string" || !(LOCATION_KINDS as readonly string[]).includes(kind)) return fail("malformed", "kind");
337
- if (typeof isFulfillable !== "boolean") return fail("malformed", "isFulfillable");
338
- if (typeof status !== "string" || !(LOCATION_STATUSES as readonly string[]).includes(status)) return fail("malformed", "status");
339
- return { name, kind: kind as LocationKind, isFulfillable, status: status as LocationStatus };
340
- }
341
-
342
- export function isLocationId(value: unknown): value is string {
343
- return typeof value === "string" && ID.test(value);
344
- }
345
-
346
- async function hex(text: string): Promise<string> {
347
- const bytes = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)));
348
- return [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
349
- }
350
-
351
- /** The idempotency ledger key: tenant, stage, operation and caller key. The install is the ledger's other key column. */
352
- export function namespacedKey(actor: InventoryWriteActor, key: string): string {
353
- return ["inventory.write", actor.tenantId, actor.stage, key].join("\n");
354
- }
355
-
356
- /** The movement source: the app namespace of the install. */
357
- export async function appSource(appId: string): Promise<string> {
358
- const raw = `app:${appId}`;
359
- return ID.test(raw) ? raw : `app:${(await hex(appId)).slice(0, 40)}`;
360
- }
361
-
362
- /** SQL condition (no leading AND): the install is active on the tenant, in the stage's env, with `inventory:write` live. */
363
- export function installAdmissionCondition(actor: InventoryWriteActor): SqlCondition {
364
- return {
365
- sql: `EXISTS (
366
- SELECT 1 FROM app_installs AS ai
367
- WHERE ai.install_id = ? AND ai.tenant_id = ? AND ai.env = ? AND ai.status = 'active'
368
- AND EXISTS (SELECT 1 FROM json_each(ai.scopes) WHERE json_each.value = '${INVENTORY_WRITE_SCOPE}')
369
- )`,
370
- params: [actor.installId, actor.tenantId, appInstallEnvForStage(actor.stage)],
371
- };
372
- }
373
-
374
- function errorIncludes(error: unknown, text: string): boolean {
375
- for (let cause: unknown = error, depth = 0; cause instanceof Error && depth < 4; depth++, cause = cause.cause) {
376
- if (cause.message.includes(text)) return true;
377
- }
378
- return false;
379
- }
380
-
381
- const lostRace = (error: unknown) => errorIncludes(error, "UNIQUE constraint failed");
382
- const batchRefused = (error: unknown) => errorIncludes(error, BATCH_REFUSED_CONSTRAINT);
383
-
384
- /** Runs the statements as one transaction and returns each one's changed-row count; a unique-key loss is all zeros. */
385
- async function transact(db: Queryable, statements: readonly QueryStatement[]): Promise<number[]> {
386
- if (!db.batchResults) throw new Error("transaction-results-required");
387
- let results: readonly { results: readonly Record<string, unknown>[] }[];
388
- try {
389
- results = await db.batchResults(statements.flatMap((statement) => [statement, { sql: "SELECT changes() AS affected" }]));
390
- } catch (error) {
391
- if (lostRace(error)) return statements.map(() => 0);
392
- throw error;
393
- }
394
- return statements.map((_, index) => Number(results[index * 2 + 1]?.results[0]?.affected ?? 0));
395
- }
396
-
397
- function receiptFrom<T>(recorded: unknown): InventoryWriteResponse<T> | null {
398
- if (!isRecord(recorded) || !Number.isSafeInteger(recorded.status) || !isRecord(recorded.body)) return null;
399
- return { status: Number(recorded.status), body: recorded.body as unknown as T };
400
- }
401
-
402
- async function priorAnswer<T>(db: Queryable, installId: string, key: string, bodyHash: string): Promise<InventoryWriteResponse<T> | null> {
403
- const check = await checkIdempotency(db, installId, key, bodyHash);
404
- if (check.status === "proceed") return null;
405
- if (check.status === "conflict") return inventoryRefusal("idempotency-conflict");
406
- return receiptFrom<T>(check.responseBody) ?? inventoryRefusal("idempotency-conflict");
407
- }
408
-
409
- /** The install's standing, read after a refused write: null when it may write. */
410
- async function installRefusal(db: Queryable, actor: InventoryWriteActor): Promise<InventoryWriteResponse<never> | null> {
411
- const install = await db.first<{ tenant_id: string; env: string; status: string; scopes: string }>(
412
- `SELECT tenant_id, env, status, scopes FROM app_installs WHERE install_id = ?`,
413
- actor.installId,
414
- );
415
- if (!install || install.tenant_id !== actor.tenantId || install.status !== "active") return inventoryRefusal("invalid_token");
416
- if (install.env !== appInstallEnvForStage(actor.stage)) return inventoryRefusal("denied");
417
- let scopes: unknown = null;
418
- try {
419
- scopes = JSON.parse(install.scopes);
420
- } catch {
421
- scopes = null;
422
- }
423
- if (!Array.isArray(scopes) || !scopes.includes(INVENTORY_WRITE_SCOPE)) return inventoryRefusal("scope_denied");
424
- return null;
425
- }
426
-
427
- /** Common request shape for the ledger writes. */
428
- interface LedgerWriteRequest {
429
- actor: InventoryWriteActor;
430
- idempotencyKey: string;
431
- /** The tenant catalog's stored form of `sku`, or null when the catalog has no such sku. */
432
- resolveSku: (sku: string) => Promise<string | null>;
433
- now: () => string;
434
- notify?: InventoryChangedNotify;
435
- }
436
-
437
- export interface InventoryWriteRequest extends LedgerWriteRequest {
438
- delta: AppInventoryDelta;
439
- }
440
-
441
- export interface InventoryMovementsRequest extends LedgerWriteRequest {
442
- items: readonly AppInventoryMovement[];
443
- }
444
-
445
- export interface InventoryLevelsRequest extends LedgerWriteRequest {
446
- items: readonly AppInventoryLevel[];
447
- }
448
-
449
- function preflight(request: LedgerWriteRequest): InventoryWriteResponse<never> | null {
450
- if (!IDEMPOTENCY_KEY.test(request.idempotencyKey)) return inventoryRefusal("malformed", undefined, "Idempotency-Key");
451
- if (!ID.test(request.actor.installId) || !request.actor.tenantId) return inventoryRefusal("invalid_token");
452
- return null;
453
- }
454
-
455
- async function receiptIdFor(actor: InventoryWriteActor, key: string): Promise<string> {
456
- return `app.${(await hex(`${actor.installId}\n${key}`)).slice(0, 48)}`;
457
- }
458
-
459
- /** Resolves every item's sku to the catalog's stored form, or names the first unknown item. */
460
- async function resolveItems<T extends { sku: string }>(
461
- items: readonly T[],
462
- resolveSku: (sku: string) => Promise<string | null>,
463
- ): Promise<T[] | InventoryWriteResponse<never>> {
464
- const resolved: T[] = [];
465
- for (const [index, item] of items.entries()) {
466
- const sku = await resolveSku(item.sku);
467
- if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku", index);
468
- resolved.push({ ...item, sku });
469
- }
470
- return resolved;
471
- }
472
-
473
- /** Applies one app delta; every answer is a receipt or a coded refusal. */
474
- export async function applyAppInventoryDelta(db: Queryable, request: InventoryWriteRequest): Promise<InventoryWriteResponse> {
475
- const refused = preflight(request);
476
- if (refused) return refused;
477
- const { actor, delta } = request;
478
- const key = namespacedKey(actor, request.idempotencyKey);
479
- const bodyHash = await computeBodyHash({ operation: "inventory.write", ...delta });
480
- const prior = await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash);
481
- if (prior) return prior;
482
-
483
- const sku = await request.resolveSku(delta.sku);
484
- if (sku === null || !isStoredSku(sku)) return inventoryRefusal("unknown-sku");
485
- const asOf = request.now();
486
- const receiptId = await receiptIdFor(actor, key);
487
- const actorId = `app:${actor.installId}`;
488
- const source = await appSource(actor.appId);
489
- const movement = guardedCorrectionStatement(
490
- {
491
- tenantId: actor.tenantId,
492
- stage: actor.stage,
493
- source,
494
- sourceEventId: receiptId,
495
- sku,
496
- locationId: delta.locationId,
497
- quantityDelta: delta.quantityDelta,
498
- asOf,
499
- actorId,
500
- reason: delta.reason ?? null,
501
- },
502
- installAdmissionCondition(actor),
503
- );
504
- const detail = JSON.stringify({
505
- receiptId,
506
- sku,
507
- locationId: delta.locationId,
508
- quantityDelta: delta.quantityDelta,
509
- ...(delta.reason ? { reason: delta.reason } : {}),
510
- });
511
- const committed: SqlCondition = {
512
- sql: `EXISTS (SELECT 1 FROM commerce_inventory_movements WHERE tenant_id = ? AND stage = ? AND source = ? AND source_event_id = ?)`,
513
- params: [actor.tenantId, actor.stage, source, receiptId],
514
- };
515
- const changes = await transact(db, [
516
- { sql: movement.sql, params: movement.params },
517
- {
518
- sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
519
- SELECT ?, ?, ?, '${INVENTORY_AUDIT_EVENT}', ?, NULL, ?, ? WHERE changes() = 1`,
520
- params: [crypto.randomUUID(), actor.installId, actor.tenantId, actorId, detail, asOf],
521
- },
522
- {
523
- sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
524
- SELECT ?, ?, ?, json_object('status', 201, 'body', json_object(
525
- 'receiptId', ?, 'sku', ?, 'locationId', ?, 'quantityDelta', CAST(? AS INTEGER), 'asOf', ?,
526
- 'balance', ${locationBalanceSql("?", "?")})), ?
527
- WHERE changes() = 1`,
528
- params: [
529
- actor.installId,
530
- key,
531
- bodyHash,
532
- receiptId,
533
- sku,
534
- delta.locationId,
535
- delta.quantityDelta,
536
- asOf,
537
- actor.tenantId,
538
- actor.stage,
539
- sku,
540
- delta.locationId,
541
- actor.tenantId,
542
- actor.stage,
543
- sku,
544
- delta.locationId,
545
- asOf,
546
- ],
547
- },
548
- ...movementEventStatements({ tenantId: actor.tenantId, stage: actor.stage, source, sourceEventId: receiptId, now: asOf }),
549
- ...availabilitySyncStatements({
550
- tenantId: actor.tenantId,
551
- stage: actor.stage,
552
- now: asOf,
553
- scope: itemScope([{ sku, locationId: delta.locationId }]),
554
- emit: false,
555
- token: availabilityToken(),
556
- when: committed,
557
- }),
558
- ]);
559
- if ((changes[0] ?? 0) === 1 && (changes[2] ?? 0) === 1) {
560
- await notifyInventoryDeliveries(sqlAll(db), {
561
- tenantId: actor.tenantId,
562
- idEquals: `inv.${receiptId}`,
563
- idPrefix: `inv.${receiptId}.`,
564
- notify: request.notify,
565
- });
566
- return (await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash)) ?? inventoryRefusal("unavailable");
567
- }
568
- const winner = await priorAnswer<InventoryReceipt>(db, actor.installId, key, bodyHash);
569
- if (winner) return winner;
570
- const install = await installRefusal(db, actor);
571
- if (install) return install;
572
- if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: delta.locationId }))) {
573
- return inventoryRefusal("unknown-location");
574
- }
575
- return inventoryRefusal("balance-out-of-range");
576
- }
577
-
578
- function sqlAll(db: Queryable) {
579
- return (sql: string, params: unknown[]) => db.all<Record<string, unknown>>(sql, ...params);
580
- }
581
-
582
- /** Inserts into the guard table (aborting the transaction) when `violation` holds. */
583
- function guardStatement(violation: SqlCondition): SqlStatement {
584
- return {
585
- sql: `INSERT INTO commerce_inventory_batch_guard (refused) SELECT 1 WHERE ${violation.sql}`,
586
- params: [...violation.params],
587
- };
588
- }
589
-
590
- const ITEMS = `(SELECT CAST(key AS INTEGER) AS idx, json_extract(value, '$.sku') AS sku,
591
- json_extract(value, '$.locationId') AS location_id, value AS item FROM json_each(?))`;
592
-
593
- /** Runs a batch transaction; a guard abort answers "refused", a same-key race answers "raced". */
594
- async function runBatch(db: Queryable, statements: readonly SqlStatement[]): Promise<"committed" | "refused" | "raced"> {
595
- if (!db.batch) throw new Error("transaction-required");
596
- try {
597
- await db.batch(statements);
598
- return "committed";
599
- } catch (error) {
600
- if (batchRefused(error)) return "refused";
601
- if (lostRace(error)) return "raced";
602
- throw error;
603
- }
604
- }
605
-
606
- /** Why a batch was refused, read after the rollback: the install, then the first unknown location, then the first out-of-range key. */
607
- async function classifyBatchRefusal(
608
- db: Queryable,
609
- actor: InventoryWriteActor,
610
- items: readonly { sku: string; locationId: string; quantityDelta?: number }[],
611
- ): Promise<InventoryWriteResponse<never>> {
612
- const install = await installRefusal(db, actor);
613
- if (install) return install;
614
- for (const [index, item] of items.entries()) {
615
- if (!(await mirrorLocationKnown(db, { tenantId: actor.tenantId, stage: actor.stage, locationId: item.locationId }))) {
616
- return inventoryRefusal("unknown-location", index);
617
- }
618
- }
619
- const nets = new Map<string, { index: number; net: number; sku: string; locationId: string }>();
620
- for (const [index, item] of items.entries()) {
621
- const key = `${item.sku}\n${item.locationId}`;
622
- const entry = nets.get(key) ?? { index, net: 0, sku: item.sku, locationId: item.locationId };
623
- entry.net += item.quantityDelta ?? 0;
624
- nets.set(key, entry);
625
- }
626
- for (const entry of nets.values()) {
627
- const row = await db.first<{ balance: number }>(
628
- `SELECT ${locationBalanceSql("?", "?")} AS balance`,
629
- actor.tenantId,
630
- actor.stage,
631
- entry.sku,
632
- entry.locationId,
633
- actor.tenantId,
634
- actor.stage,
635
- entry.sku,
636
- entry.locationId,
637
- );
638
- const after = Number(row?.balance ?? 0) + entry.net;
639
- if (after > MIRROR_BALANCE_MAX || (after < 0 && entry.net < 0)) return inventoryRefusal("balance-out-of-range", entry.index);
640
- }
641
- return inventoryRefusal("unavailable");
642
- }
643
-
644
- /** Statements shared by both batch forms after the movement insert: events, deliveries, availability. */
645
- function batchTail(actor: InventoryWriteActor, input: { source: string; receiptId: string; asOf: string; scope: { sku: string; locationId: string }[] }): SqlStatement[] {
646
- return [
647
- ...movementEventStatements({
648
- tenantId: actor.tenantId,
649
- stage: actor.stage,
650
- source: input.source,
651
- sourceEventId: input.receiptId,
652
- now: input.asOf,
653
- }),
654
- ...availabilitySyncStatements({
655
- tenantId: actor.tenantId,
656
- stage: actor.stage,
657
- now: input.asOf,
658
- scope: itemScope(input.scope),
659
- emit: false,
660
- token: availabilityToken(),
661
- }),
662
- ];
663
- }
664
-
665
- async function finishBatch<T>(
666
- db: Queryable,
667
- request: LedgerWriteRequest,
668
- outcome: "committed" | "refused" | "raced",
669
- ctx: { key: string; bodyHash: string; receiptId: string; items: readonly { sku: string; locationId: string; quantityDelta?: number }[] },
670
- ): Promise<InventoryWriteResponse<T>> {
671
- const { actor } = request;
672
- if (outcome === "committed") {
673
- await notifyInventoryDeliveries(sqlAll(db), {
674
- tenantId: actor.tenantId,
675
- idEquals: `inv.${ctx.receiptId}`,
676
- idPrefix: `inv.${ctx.receiptId}.`,
677
- notify: request.notify,
678
- });
679
- }
680
- const answer = await priorAnswer<T>(db, actor.installId, ctx.key, ctx.bodyHash);
681
- if (answer) return answer;
682
- if (outcome === "committed") return inventoryRefusal("unavailable");
683
- return classifyBatchRefusal(db, actor, ctx.items);
684
- }
685
-
686
- /** Applies a batch of WMS movements as one transaction: every item commits, or none does. */
687
- export async function applyAppInventoryMovements(
688
- db: Queryable,
689
- request: InventoryMovementsRequest,
690
- ): Promise<InventoryWriteResponse<InventoryMovementsReceipt>> {
691
- const refused = preflight(request);
692
- if (refused) return refused;
693
- const { actor } = request;
694
- const key = namespacedKey(actor, request.idempotencyKey);
695
- const bodyHash = await computeBodyHash({ operation: "inventory.movements", items: request.items });
696
- const prior = await priorAnswer<InventoryMovementsReceipt>(db, actor.installId, key, bodyHash);
697
- if (prior) return prior;
698
- const items = await resolveItems(request.items, request.resolveSku);
699
- if (!Array.isArray(items)) return items;
700
-
701
- const asOf = request.now();
702
- const receiptId = await receiptIdFor(actor, key);
703
- const actorId = `app:${actor.installId}`;
704
- const source = await appSource(actor.appId);
705
- const itemsJson = JSON.stringify(items);
706
- const t = actor.tenantId;
707
- const s = actor.stage;
708
- const admission = installAdmissionCondition(actor);
709
- const violation: SqlCondition = {
710
- sql: `(NOT ${admission.sql}
711
- OR EXISTS (SELECT 1 FROM ${ITEMS} AS it WHERE NOT ${locationAdmittedSql("it.location_id")})
712
- OR EXISTS (SELECT 1 FROM (
713
- SELECT it.sku AS sku, it.location_id AS location_id, SUM(json_extract(it.item, '$.quantityDelta')) AS net
714
- FROM ${ITEMS} AS it GROUP BY it.sku, it.location_id
715
- ) AS g
716
- WHERE ${locationBalanceSql("g.sku", "g.location_id")} + g.net > ${MIRROR_BALANCE_MAX}
717
- OR (${locationBalanceSql("g.sku", "g.location_id")} + g.net < 0 AND g.net < 0)))`,
718
- params: [...admission.params, itemsJson, t, s, itemsJson, t, s, t, s, t, s, t, s],
719
- };
720
- const detail = JSON.stringify({ receiptId, items: items.length });
721
- const outcome = await runBatch(db, [
722
- guardStatement(violation),
723
- {
724
- sql: `INSERT INTO commerce_inventory_movements
725
- (tenant_id, stage, source, source_event_id, sku, location_id, quantity_delta, as_of, actor_id, reason)
726
- SELECT ?, ?, ?, ? || '.' || it.idx, it.sku, it.location_id, CAST(json_extract(it.item, '$.quantityDelta') AS INTEGER), ?, ?,
727
- json_extract(it.item, '$.reason')
728
- FROM ${ITEMS} AS it WHERE true
729
- ON CONFLICT DO NOTHING`,
730
- params: [t, s, source, receiptId, asOf, actorId, itemsJson],
731
- },
732
- {
733
- sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
734
- VALUES (?, ?, ?, '${INVENTORY_BATCH_AUDIT_EVENT}', ?, NULL, ?, ?)`,
735
- params: [crypto.randomUUID(), actor.installId, t, actorId, detail, asOf],
736
- },
737
- {
738
- sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
739
- SELECT ?, ?, ?, json_object('status', 201, 'body', json_object('receiptId', ?, 'asOf', ?, 'items', json((
740
- SELECT json_group_array(json(line)) FROM (
741
- SELECT json_object('sku', it.sku, 'locationId', it.location_id,
742
- 'quantityDelta', CAST(json_extract(it.item, '$.quantityDelta') AS INTEGER),
743
- 'reason', json_extract(it.item, '$.reason'),
744
- 'balance', ${locationBalanceSql("it.sku", "it.location_id")}) AS line
745
- FROM ${ITEMS} AS it ORDER BY it.idx))))), ?`,
746
- params: [actor.installId, key, bodyHash, receiptId, asOf, t, s, t, s, itemsJson, asOf],
747
- },
748
- ...batchTail(actor, { source, receiptId, asOf, scope: items }),
749
- ]);
750
- return finishBatch<InventoryMovementsReceipt>(db, request, outcome, { key, bodyHash, receiptId, items });
751
- }
752
-
753
- /**
754
- * Reconciles a batch of absolute on-hand levels as one transaction. Each item writes the movement
755
- * that makes its (sku, location) ledger equal `onHand` (reason `reconcile`); an item already at its
756
- * level writes a zero movement, which refreshes freshness and emits no event.
757
- */
758
- export async function applyAppInventoryLevels(
759
- db: Queryable,
760
- request: InventoryLevelsRequest,
761
- ): Promise<InventoryWriteResponse<InventoryLevelsReceipt>> {
762
- const refused = preflight(request);
763
- if (refused) return refused;
764
- const { actor } = request;
765
- const key = namespacedKey(actor, request.idempotencyKey);
766
- const bodyHash = await computeBodyHash({ operation: "inventory.levels", items: request.items });
767
- const prior = await priorAnswer<InventoryLevelsReceipt>(db, actor.installId, key, bodyHash);
768
- if (prior) return prior;
769
- const items = await resolveItems(request.items, request.resolveSku);
770
- if (!Array.isArray(items)) return items;
771
- const seen = new Set<string>();
772
- for (const [index, item] of items.entries()) {
773
- const pair = `${item.sku}\n${item.locationId}`;
774
- if (seen.has(pair)) return inventoryRefusal("malformed", index, "items");
775
- seen.add(pair);
776
- }
777
-
778
- const asOf = request.now();
779
- const receiptId = await receiptIdFor(actor, key);
780
- const actorId = `app:${actor.installId}`;
781
- const source = await appSource(actor.appId);
782
- const itemsJson = JSON.stringify(items);
783
- const t = actor.tenantId;
784
- const s = actor.stage;
785
- const admission = installAdmissionCondition(actor);
786
- const violation: SqlCondition = {
787
- sql: `(NOT ${admission.sql} OR EXISTS (SELECT 1 FROM ${ITEMS} AS it WHERE NOT ${locationAdmittedSql("it.location_id")}))`,
788
- params: [...admission.params, itemsJson, t, s],
789
- };
790
- const detail = JSON.stringify({ receiptId, items: items.length });
791
- const outcome = await runBatch(db, [
792
- guardStatement(violation),
793
- {
794
- sql: `INSERT INTO commerce_inventory_movements
795
- (tenant_id, stage, source, source_event_id, sku, location_id, quantity_delta, as_of, actor_id, reason)
796
- SELECT ?, ?, ?, ? || '.' || it.idx, it.sku, it.location_id,
797
- ${onHandDeltaSql("json_extract(it.item, '$.onHand')", "it.sku", "it.location_id")}, ?, ?, '${RECONCILE_REASON}'
798
- FROM ${ITEMS} AS it WHERE true
799
- ON CONFLICT DO NOTHING`,
800
- params: [t, s, source, receiptId, t, s, asOf, actorId, itemsJson],
801
- },
802
- {
803
- sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
804
- VALUES (?, ?, ?, '${INVENTORY_LEVELS_AUDIT_EVENT}', ?, NULL, ?, ?)`,
805
- params: [crypto.randomUUID(), actor.installId, t, actorId, detail, asOf],
806
- },
807
- {
808
- sql: `INSERT INTO idempotency_keys (install_id, idempotency_key, body_hash, response_body, created_at)
809
- SELECT ?, ?, ?, json_object('status', 200, 'body', json_object('receiptId', ?, 'asOf', ?, 'items', json((
810
- SELECT json_group_array(json(line)) FROM (
811
- SELECT json_object('sku', it.sku, 'locationId', it.location_id,
812
- 'onHand', CAST(json_extract(it.item, '$.onHand') AS INTEGER),
813
- 'observedAt', json_extract(it.item, '$.observedAt'),
814
- 'quantityDelta', (SELECT m.quantity_delta FROM commerce_inventory_movements AS m
815
- WHERE m.tenant_id = ? AND m.stage = ? AND m.source = ? AND m.source_event_id = ? || '.' || it.idx),
816
- 'balance', ${locationBalanceSql("it.sku", "it.location_id")}) AS line
817
- FROM ${ITEMS} AS it ORDER BY it.idx))))), ?`,
818
- params: [actor.installId, key, bodyHash, receiptId, asOf, t, s, source, receiptId, t, s, t, s, itemsJson, asOf],
819
- },
820
- ...batchTail(actor, { source, receiptId, asOf, scope: items }),
821
- ]);
822
- return finishBatch<InventoryLevelsReceipt>(db, request, outcome, { key, bodyHash, receiptId, items });
823
- }
824
-
825
- export interface InventoryLocationRequest {
826
- actor: InventoryWriteActor;
827
- locationId: string;
828
- location: AppInventoryLocationInput;
829
- now: () => string;
830
- notify?: InventoryChangedNotify;
831
- }
832
-
833
- /**
834
- * Declares or updates one location. Archiving keeps its history and stops new writes to it;
835
- * `unspecified` is never archived. Availability for every sku held at the location is
836
- * recomputed in the same transaction, emitting `inventory.changed` where it moved.
837
- */
838
- export async function upsertAppInventoryLocation(
839
- db: Queryable,
840
- request: InventoryLocationRequest,
841
- ): Promise<InventoryWriteResponse<InventoryLocation>> {
842
- const { actor, locationId, location } = request;
843
- if (!ID.test(actor.installId) || !actor.tenantId) return inventoryRefusal("invalid_token");
844
- if (!ID.test(locationId)) return inventoryRefusal("malformed", undefined, "locationId");
845
- if (locationId === MIRROR_LOCATION_UNSPECIFIED && location.status !== "active") return inventoryRefusal("location-protected");
846
- const now = request.now();
847
- const admission = installAdmissionCondition(actor);
848
- const actorId = `app:${actor.installId}`;
849
- const token = availabilityToken();
850
- const detail = JSON.stringify({ locationId, ...location });
851
- const changes = await transact(db, [
852
- {
853
- sql: `INSERT INTO commerce_inventory_locations (tenant_id, stage, location_id, name, kind, is_fulfillable, status, updated_at)
854
- SELECT ?, ?, ?, ?, ?, ?, ?, ? WHERE ${admission.sql}
855
- ON CONFLICT (tenant_id, stage, location_id) DO UPDATE SET
856
- name = excluded.name, kind = excluded.kind, is_fulfillable = excluded.is_fulfillable,
857
- status = excluded.status, updated_at = excluded.updated_at`,
858
- params: [
859
- actor.tenantId,
860
- actor.stage,
861
- locationId,
862
- location.name,
863
- location.kind,
864
- location.isFulfillable ? 1 : 0,
865
- location.status,
866
- now,
867
- ...admission.params,
868
- ],
869
- },
870
- {
871
- sql: `INSERT INTO app_audit_log (id, install_id, tenant_id, event, actor, trace_id, detail, at)
872
- SELECT ?, ?, ?, '${INVENTORY_LOCATION_AUDIT_EVENT}', ?, NULL, ?, ? WHERE changes() = 1`,
873
- params: [crypto.randomUUID(), actor.installId, actor.tenantId, actorId, detail, now],
874
- },
875
- ...availabilitySyncStatements({
876
- tenantId: actor.tenantId,
877
- stage: actor.stage,
878
- now,
879
- scope: locationScope({ tenantId: actor.tenantId, stage: actor.stage, locationId }),
880
- emit: true,
881
- token,
882
- when: admission,
883
- }),
884
- ]);
885
- if ((changes[0] ?? 0) !== 1) return (await installRefusal(db, actor)) ?? inventoryRefusal("unavailable");
886
- await notifyInventoryDeliveries(sqlAll(db), {
887
- tenantId: actor.tenantId,
888
- idEquals: "",
889
- idPrefix: `${token}.`,
890
- notify: request.notify,
891
- });
892
- const stored = await readInventoryLocation(db, { tenantId: actor.tenantId, stage: actor.stage, locationId });
893
- return stored ? { status: 200, body: stored } : inventoryRefusal("unavailable");
894
- }
895
-
896
- /** Every stored sku of the catalog's variants: the skus an app may write for this tenant. */
897
- export function catalogSkus(products: readonly CatalogProduct[]): string[] {
898
- return products.flatMap((product) => product.variants.flatMap((variant) => (variant.sku ? [variant.sku] : [])));
899
- }
900
-
901
- /** The stored catalog sku matching `sku` under the platform sku comparison, or null. */
902
- export function matchCatalogSku(catalogSkus: Iterable<string>, sku: string): string | null {
903
- const wanted = skuKey(sku);
904
- for (const candidate of catalogSkus) if (skuKey(candidate) === wanted) return candidate;
905
- return null;
906
- }