@tokenoftrust/storefront-runner 7.3.2 → 7.5.1

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 (420) 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 +32 -8
  13. package/apps/storefront/src/lib/access/auth/brokerAssertion.ts +16 -2
  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/dashboard/staffAdmission.ts +5 -0
  17. package/apps/storefront/src/lib/access/dashboard/tenantSelection.ts +2 -0
  18. package/apps/storefront/src/lib/access/shared/capability.ts +14 -6
  19. package/apps/storefront/src/lib/access/shared/generated/capabilityCatalog.generated.ts +161 -0
  20. package/apps/storefront/src/lib/activity/activityScope.ts +36 -0
  21. package/apps/storefront/src/lib/activity/recordActivity.ts +23 -1
  22. package/apps/storefront/src/lib/activity/serverFanOut.ts +31 -0
  23. package/apps/storefront/src/lib/activity/store.ts +9 -3
  24. package/apps/storefront/src/lib/checkout/agent/checkoutProtocol.ts +196 -0
  25. package/apps/storefront/src/lib/checkout/agent/checkoutSession.ts +296 -0
  26. package/apps/storefront/src/lib/checkout/agent/webBotAuth.ts +347 -0
  27. package/apps/storefront/src/lib/checkout/commerce/cardCartForm.ts +2 -0
  28. package/apps/storefront/src/lib/checkout/commerce/cartSession.ts +109 -12
  29. package/apps/storefront/src/lib/checkout/commerce/checkoutHandoffRoute.ts +53 -25
  30. package/apps/storefront/src/lib/checkout/commerce/finalCartAuthorization.ts +48 -6
  31. package/apps/storefront/src/lib/checkout/proposal/cartProposal.ts +388 -0
  32. package/apps/storefront/src/lib/checkout/proposal/listMatcher.ts +149 -0
  33. package/apps/storefront/src/lib/checkout/proposal/proposalRoutes.ts +522 -0
  34. package/apps/storefront/src/lib/checkout/proposal/reviewHtml.ts +100 -0
  35. package/apps/storefront/src/lib/compliance/browser/checkoutVerificationFlow.ts +26 -2
  36. package/apps/storefront/src/lib/content/shared/redirects.ts +21 -4
  37. package/apps/storefront/src/lib/publication/shared/edgeCache.ts +5 -2
  38. package/apps/storefront/src/lib/publication/shared/previewAnnotations/renderDecorator.ts +15 -8
  39. package/apps/storefront/src/lib/publication/shared/runtimeEnv.ts +1 -1
  40. package/apps/storefront/src/middleware/controlPlane.ts +15 -1
  41. package/apps/storefront/src/middleware/index.ts +7 -3
  42. package/apps/storefront/src/middleware/renderChain.ts +46 -33
  43. package/apps/storefront/src/pages/api/cart-proposal/confirm.ts +12 -0
  44. package/apps/storefront/src/pages/api/cart-proposal/review.ts +26 -0
  45. package/apps/storefront/src/pages/api/commerce/checkout-sessions/[id].ts +9 -0
  46. package/apps/storefront/src/pages/api/commerce/checkout-sessions.ts +8 -0
  47. package/apps/storefront/src/pages/api/commerce/final-cart-authorization.ts +29 -6
  48. package/apps/storefront/src/pages/api/compliance/preflight.ts +25 -1
  49. package/apps/storefront/src/pages/products/[handle].astro +2 -15
  50. package/apps/storefront/tsconfig.astro.json +11 -0
  51. package/package.json +1 -1
  52. package/packages/public-runtime/src/activity/README.md +12 -0
  53. package/packages/public-runtime/src/activity/catalog.ts +7 -0
  54. package/packages/public-runtime/src/activity/event.ts +19 -0
  55. package/packages/public-runtime/src/activity/redaction.ts +31 -2
  56. package/packages/public-runtime/src/catalog-files.ts +3 -2
  57. package/packages/public-runtime/src/checkout-orders.ts +18 -19
  58. package/packages/public-runtime/src/checkout.ts +70 -0
  59. package/packages/public-runtime/src/compliance/evaluate.ts +60 -1
  60. package/packages/public-runtime/src/compliance/index.ts +1 -1
  61. package/packages/public-runtime/src/compliance/pact-report.ts +184 -3
  62. package/packages/public-runtime/src/compliance/profile.ts +268 -20
  63. package/packages/public-runtime/src/compliance/ruleset.ts +42 -0
  64. package/packages/public-runtime/src/customization-runtime.ts +1 -1
  65. package/packages/public-runtime/src/product.ts +9 -1
  66. package/packages/public-runtime/src/publication-content-redirects.ts +16 -3
  67. package/packages/public-runtime/tests/fixtures/compliance-decisions.golden.json +252 -52
  68. package/pnpm-lock.runner.yaml +0 -15
  69. package/scripts/tenant/materialize-tenant-content.mjs +3 -0
  70. package/scripts/tenant/validate.mjs +128 -0
  71. package/apps/storefront/dev-plugins/dev-publish.mjs +0 -55
  72. package/apps/storefront/drizzle.config.apps.ts +0 -13
  73. package/apps/storefront/integrations/preview-annotations-client-bundle.mjs +0 -80
  74. package/apps/storefront/migrations-apps/0000_fast_millenium_guard.sql +0 -129
  75. package/apps/storefront/migrations-apps/0001_woozy_lyja.sql +0 -22
  76. package/apps/storefront/migrations-apps/0002_good_switch.sql +0 -26
  77. package/apps/storefront/migrations-apps/0003_mute_marauders.sql +0 -12
  78. package/apps/storefront/migrations-apps/0004_deep_morph.sql +0 -36
  79. package/apps/storefront/migrations-apps/0005_common_mystique.sql +0 -23
  80. package/apps/storefront/migrations-apps/0006_broad_microchip.sql +0 -16
  81. package/apps/storefront/migrations-apps/0007_brave_outlaw_kid.sql +0 -15
  82. package/apps/storefront/migrations-apps/0008_blue_dazzler.sql +0 -11
  83. package/apps/storefront/migrations-apps/0009_bored_shinobi_shaw.sql +0 -15
  84. package/apps/storefront/migrations-apps/0010_ws4_verified_provider_measurement.sql +0 -35
  85. package/apps/storefront/migrations-apps/0011_dt_tracking_tenant_databases.sql +0 -23
  86. package/apps/storefront/migrations-apps/0012_test_destinations.sql +0 -29
  87. package/apps/storefront/migrations-apps/0013_publication_space_editorial.sql +0 -64
  88. package/apps/storefront/migrations-apps/0014_retire_candidate_ledger.sql +0 -12
  89. package/apps/storefront/migrations-apps/0015_merchant_calculation_settings.sql +0 -31
  90. package/apps/storefront/migrations-apps/0016_scrappy_commerce_contract.sql +0 -166
  91. package/apps/storefront/migrations-apps/0017_commerce_durable_projection.sql +0 -28
  92. package/apps/storefront/migrations-apps/0018_commerce_provider_cart_identity.sql +0 -13
  93. package/apps/storefront/migrations-apps/0019_commerce_source_authority.sql +0 -23
  94. package/apps/storefront/migrations-apps/0020_contact_messages.sql +0 -18
  95. package/apps/storefront/migrations-apps/0021_contact_vault.sql +0 -166
  96. package/apps/storefront/migrations-apps/0022_contact_vault_fields.sql +0 -342
  97. package/apps/storefront/migrations-apps/0023_principal_grant_contacts.sql +0 -15
  98. package/apps/storefront/migrations-apps/0024_order_contact_erasure_state.sql +0 -22
  99. package/apps/storefront/migrations-apps/0025_shipment_audit_order_lookup.sql +0 -2
  100. package/apps/storefront/migrations-apps/0026_fulfillment_assignment.sql +0 -44
  101. package/apps/storefront/migrations-apps/0027_app_contact_authority.sql +0 -70
  102. package/apps/storefront/migrations-apps/0028_app_jwk_and_candidates.sql +0 -133
  103. package/apps/storefront/migrations-apps/0029_inventory_locations_wms.sql +0 -38
  104. package/apps/storefront/migrations-apps/0030_assignment_split_shipments.sql +0 -149
  105. package/apps/storefront/migrations-apps/meta/0000_snapshot.json +0 -843
  106. package/apps/storefront/migrations-apps/meta/0001_snapshot.json +0 -990
  107. package/apps/storefront/migrations-apps/meta/0002_snapshot.json +0 -1160
  108. package/apps/storefront/migrations-apps/meta/0003_snapshot.json +0 -1235
  109. package/apps/storefront/migrations-apps/meta/0004_snapshot.json +0 -1474
  110. package/apps/storefront/migrations-apps/meta/0005_snapshot.json +0 -1617
  111. package/apps/storefront/migrations-apps/meta/0006_snapshot.json +0 -1716
  112. package/apps/storefront/migrations-apps/meta/0007_snapshot.json +0 -1812
  113. package/apps/storefront/migrations-apps/meta/0008_snapshot.json +0 -1881
  114. package/apps/storefront/migrations-apps/meta/0009_snapshot.json +0 -1979
  115. package/apps/storefront/migrations-apps/meta/_journal.json +0 -76
  116. package/apps/storefront/perf/README.md +0 -64
  117. package/apps/storefront/perf/assert-budgets.ts +0 -159
  118. package/apps/storefront/platform-reconcile-tenants.json +0 -3
  119. package/apps/storefront/playwright.config.ts +0 -23
  120. package/apps/storefront/public/js/dashboard-access-banner.js +0 -53
  121. package/apps/storefront/public/js/dashboard-apps.js +0 -183
  122. package/apps/storefront/public/js/dashboard-contact-capture.js +0 -52
  123. package/apps/storefront/public/js/dashboard-delegate.js +0 -167
  124. package/apps/storefront/public/js/dashboard-team.js +0 -356
  125. package/apps/storefront/public/js/dashboard-vendor-search.js +0 -115
  126. package/apps/storefront/src/components/content/storefront/AsyncStylesheet.astro +0 -26
  127. package/apps/storefront/src/components/integrations/storefront/WidgetFrame.astro +0 -34
  128. package/apps/storefront/src/config/adminTenantLookup.ts +0 -35
  129. package/apps/storefront/src/config/evidenceTenantRoster.ts +0 -25
  130. package/apps/storefront/src/config/staffProvisionProjection.ts +0 -24
  131. package/apps/storefront/src/config/storeName.ts +0 -34
  132. package/apps/storefront/src/lib/access/admin/README.md +0 -122
  133. package/apps/storefront/src/lib/access/admin/adminShell.ts +0 -281
  134. package/apps/storefront/src/lib/access/admin/envelope.ts +0 -9
  135. package/apps/storefront/src/lib/access/admin/viewmodels/settings.ts +0 -64
  136. package/apps/storefront/src/lib/access/auth/adminApiGuard.ts +0 -66
  137. package/apps/storefront/src/lib/access/auth/adminEntry.ts +0 -126
  138. package/apps/storefront/src/lib/access/auth/mcpClientAssertion.ts +0 -217
  139. package/apps/storefront/src/lib/access/auth/operatorSession.ts +0 -120
  140. package/apps/storefront/src/lib/access/dashboard/agentStoreEntry.ts +0 -253
  141. package/apps/storefront/src/lib/access/dashboard/delegateGate.ts +0 -130
  142. package/apps/storefront/src/lib/access/dashboard/staffStoreEntry.ts +0 -153
  143. package/apps/storefront/src/lib/access/dashboard/staffVendorAccess.ts +0 -474
  144. package/apps/storefront/src/lib/access/dashboard/vendorQuery.ts +0 -61
  145. package/apps/storefront/src/lib/access/fixtures/settings.ts +0 -67
  146. package/apps/storefront/src/lib/access/fixtures/tenants.ts +0 -29
  147. package/apps/storefront/src/lib/access/notifications/magicLinkInviteEmail.ts +0 -62
  148. package/apps/storefront/src/lib/access/shared/grantContactLookup.ts +0 -97
  149. package/apps/storefront/src/lib/access/shared/principalGrants.ts +0 -775
  150. package/apps/storefront/src/lib/activity/alerts.ts +0 -426
  151. package/apps/storefront/src/lib/activity/candidateSubmitLease.ts +0 -87
  152. package/apps/storefront/src/lib/activity/changeActorAttribution.ts +0 -181
  153. package/apps/storefront/src/lib/activity/evidence/evidenceReference.ts +0 -32
  154. package/apps/storefront/src/lib/activity/fixtures/evidence.ts +0 -99
  155. package/apps/storefront/src/lib/activity/query.ts +0 -403
  156. package/apps/storefront/src/lib/activity/uiActor.ts +0 -152
  157. package/apps/storefront/src/lib/admin/services/mock/index.ts +0 -12
  158. package/apps/storefront/src/lib/assets/addons/catalog.ts +0 -60
  159. package/apps/storefront/src/lib/assets/addons/storeEntitlements.ts +0 -260
  160. package/apps/storefront/src/lib/assets/durableAssetsRoute.ts +0 -65
  161. package/apps/storefront/src/lib/assets/durableR2.ts +0 -473
  162. package/apps/storefront/src/lib/assets/durableR2Bindings.ts +0 -33
  163. package/apps/storefront/src/lib/automation/admin/viewmodels/aiWorkflows.ts +0 -65
  164. package/apps/storefront/src/lib/automation/ai/approvalMode.ts +0 -20
  165. package/apps/storefront/src/lib/automation/ai/askEnvelope.ts +0 -47
  166. package/apps/storefront/src/lib/automation/ai/audit.ts +0 -12
  167. package/apps/storefront/src/lib/automation/ai/operationalRuns.ts +0 -155
  168. package/apps/storefront/src/lib/automation/ai/recommendation.ts +0 -20
  169. package/apps/storefront/src/lib/automation/fixtures/aiWorkflows.ts +0 -59
  170. package/apps/storefront/src/lib/catalog/admin/catalogSettingsClient.ts +0 -250
  171. package/apps/storefront/src/lib/catalog/admin/catalogSettingsFields.ts +0 -134
  172. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPreview.ts +0 -37
  173. package/apps/storefront/src/lib/catalog/admin/catalogSettingsPricingView.ts +0 -39
  174. package/apps/storefront/src/lib/catalog/admin/catalogSettingsRuleView.ts +0 -44
  175. package/apps/storefront/src/lib/catalog/admin/catalogSettingsSkuView.ts +0 -21
  176. package/apps/storefront/src/lib/catalog/admin/catalogSettingsState.ts +0 -132
  177. package/apps/storefront/src/lib/catalog/admin/productSetupPhoto.ts +0 -23
  178. package/apps/storefront/src/lib/catalog/admin/productsTabClient.ts +0 -193
  179. package/apps/storefront/src/lib/catalog/admin/services/catalogProducts.ts +0 -32
  180. package/apps/storefront/src/lib/catalog/admin/viewmodels/catalogProducts.ts +0 -164
  181. package/apps/storefront/src/lib/catalog/admin/viewmodels/products.ts +0 -267
  182. package/apps/storefront/src/lib/catalog/fixtures/products.ts +0 -105
  183. package/apps/storefront/src/lib/catalog/tot/syncState.ts +0 -111
  184. package/apps/storefront/src/lib/checkout/admin/checkoutStyleInput.ts +0 -172
  185. package/apps/storefront/src/lib/checkout/admin/checkoutStyleTarget.ts +0 -65
  186. package/apps/storefront/src/lib/checkout/browser/checkoutExciseForm.ts +0 -152
  187. package/apps/storefront/src/lib/checkout/browser/checkoutRequirementsForm.ts +0 -72
  188. package/apps/storefront/src/lib/checkout/browser/checkoutStyleForm.ts +0 -110
  189. package/apps/storefront/src/lib/checkout/browser/settingDraftActions.ts +0 -367
  190. package/apps/storefront/src/lib/checkout/commerce/checkoutSettings.ts +0 -246
  191. package/apps/storefront/src/lib/checkout/fixtures/checkoutSettings.ts +0 -77
  192. package/apps/storefront/src/lib/content/blog/markdown.ts +0 -174
  193. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome-assignments.example.json +0 -6
  194. package/apps/storefront/src/lib/content/chrome/examples/tokenoftrust.chrome.example.json +0 -79
  195. package/apps/storefront/src/lib/content/index.ts +0 -27
  196. package/apps/storefront/src/lib/content/the-build/readingTime.ts +0 -35
  197. package/apps/storefront/src/lib/content/the-build/toc.ts +0 -95
  198. package/apps/storefront/src/lib/customers/admin/viewmodels/customers.ts +0 -56
  199. package/apps/storefront/src/lib/customers/contactVault/blindIndex.ts +0 -28
  200. package/apps/storefront/src/lib/customers/contactVault/contactAudit.ts +0 -149
  201. package/apps/storefront/src/lib/customers/contactVault/dataKeys.ts +0 -283
  202. package/apps/storefront/src/lib/customers/contactVault/fieldEnvelope.ts +0 -88
  203. package/apps/storefront/src/lib/customers/contactVault/isolateMetrics.ts +0 -37
  204. package/apps/storefront/src/lib/customers/contactVault/kms.ts +0 -292
  205. package/apps/storefront/src/lib/customers/contactVault/retention.ts +0 -302
  206. package/apps/storefront/src/lib/customers/contactVault/retentionPolicy.ts +0 -290
  207. package/apps/storefront/src/lib/customers/contactVault/zip3.ts +0 -24
  208. package/apps/storefront/src/lib/customers/fixtures/customers.ts +0 -86
  209. package/apps/storefront/src/lib/developer-experience/admin/memoizeByEnvelope.ts +0 -27
  210. package/apps/storefront/src/lib/developer-experience/admin/seed.ts +0 -54
  211. package/apps/storefront/src/lib/developer-experience/dev/activityIngestToken.ts +0 -85
  212. package/apps/storefront/src/lib/developer-experience/dev/activityStore.ts +0 -82
  213. package/apps/storefront/src/lib/developer-experience/dev/agentGrantAttestation.ts +0 -74
  214. package/apps/storefront/src/lib/developer-experience/dev/ai-widget-client.js +0 -308
  215. package/apps/storefront/src/lib/developer-experience/dev/apiBase.ts +0 -17
  216. package/apps/storefront/src/lib/developer-experience/dev/cliSignInCode.ts +0 -124
  217. package/apps/storefront/src/lib/developer-experience/dev/cockpit/ask.ts +0 -49
  218. package/apps/storefront/src/lib/developer-experience/dev/cockpit/clickToSource.ts +0 -71
  219. package/apps/storefront/src/lib/developer-experience/dev/cockpit/copyCommand.ts +0 -227
  220. package/apps/storefront/src/lib/developer-experience/dev/cockpit/files.ts +0 -249
  221. package/apps/storefront/src/lib/developer-experience/dev/cockpit/hostedActivity.ts +0 -500
  222. package/apps/storefront/src/lib/developer-experience/dev/cockpit/infoPopover.ts +0 -12
  223. package/apps/storefront/src/lib/developer-experience/dev/cockpit/mcpCopy.ts +0 -34
  224. package/apps/storefront/src/lib/developer-experience/dev/cockpit/monitor.ts +0 -107
  225. package/apps/storefront/src/lib/developer-experience/dev/cockpit/stepper.ts +0 -116
  226. package/apps/storefront/src/lib/developer-experience/dev/cockpit/themeToggle.ts +0 -23
  227. package/apps/storefront/src/lib/developer-experience/dev/livePreview.ts +0 -77
  228. package/apps/storefront/src/lib/developer-experience/dev/obstacleStore.ts +0 -214
  229. package/apps/storefront/src/lib/developer-experience/dev/previewStatus.ts +0 -87
  230. package/apps/storefront/src/lib/developer-experience/dev/rendezvousBroker.ts +0 -226
  231. package/apps/storefront/src/lib/developer-experience/dev/runtimeStore.ts +0 -291
  232. package/apps/storefront/src/lib/developer-experience/dev/storeStatus.ts +0 -142
  233. package/apps/storefront/src/lib/developer-experience/dev/subjectReissue.ts +0 -67
  234. package/apps/storefront/src/lib/developer-experience/fixtures/regulated-commerce-truth/index.ts +0 -540
  235. package/apps/storefront/src/lib/developer-experience/fixtures/ws3-readonly-clone-preflight/index.ts +0 -495
  236. package/apps/storefront/src/lib/engagement/contact/contactMessages.ts +0 -671
  237. package/apps/storefront/src/lib/engagement/contact/messagesTabClient.ts +0 -175
  238. package/apps/storefront/src/lib/engagement/contact/submission.ts +0 -112
  239. package/apps/storefront/src/lib/engagement/messaging/messagesClient.ts +0 -149
  240. package/apps/storefront/src/lib/engagement/newsletter/digest.ts +0 -117
  241. package/apps/storefront/src/lib/engagement/newsletter/resendClient.ts +0 -79
  242. package/apps/storefront/src/lib/engagement/newsletter/send.ts +0 -265
  243. package/apps/storefront/src/lib/engagement/social/golive.ts +0 -212
  244. package/apps/storefront/src/lib/engagement/social/notify.ts +0 -32
  245. package/apps/storefront/src/lib/engagement/social/tokenStore.ts +0 -171
  246. package/apps/storefront/src/lib/fulfillment/admin/commerceDesk.ts +0 -180
  247. package/apps/storefront/src/lib/fulfillment/admin/commerceDeskRouting.ts +0 -45
  248. package/apps/storefront/src/lib/fulfillment/admin/viewmodels/fulfillment.ts +0 -1071
  249. package/apps/storefront/src/lib/fulfillment/appShipmentEvidence.ts +0 -271
  250. package/apps/storefront/src/lib/fulfillment/carrierEvidence.ts +0 -105
  251. package/apps/storefront/src/lib/fulfillment/commerceProjection.ts +0 -157
  252. package/apps/storefront/src/lib/fulfillment/commerceReadback.ts +0 -60
  253. package/apps/storefront/src/lib/fulfillment/commerceRecovery.ts +0 -84
  254. package/apps/storefront/src/lib/fulfillment/commerceRuntime.ts +0 -41
  255. package/apps/storefront/src/lib/fulfillment/fulfillmentService.ts +0 -2842
  256. package/apps/storefront/src/lib/fulfillment/readiness.ts +0 -217
  257. package/apps/storefront/src/lib/fulfillment/splitShipments.ts +0 -388
  258. package/apps/storefront/src/lib/fulfillment/syntheticPreviewOrders.ts +0 -292
  259. package/apps/storefront/src/lib/integrations/apps/appContactAuthority.ts +0 -27
  260. package/apps/storefront/src/lib/integrations/apps/appContactConsents.ts +0 -118
  261. package/apps/storefront/src/lib/integrations/apps/appInstallEnv.ts +0 -28
  262. package/apps/storefront/src/lib/integrations/apps/gtmMigrationDraft.ts +0 -103
  263. package/apps/storefront/src/lib/integrations/apps/inventoryWrite.ts +0 -906
  264. package/apps/storefront/src/lib/integrations/apps/orders/customerHash.ts +0 -28
  265. package/apps/storefront/src/lib/integrations/apps/orders/idempotency.ts +0 -100
  266. package/apps/storefront/src/lib/integrations/apps/reports/salesVelocityReport.ts +0 -96
  267. package/apps/storefront/src/lib/integrations/apps/routeParams.ts +0 -45
  268. package/apps/storefront/src/lib/integrations/webhooks/cloudflareQueueDispatcher.ts +0 -82
  269. package/apps/storefront/src/lib/integrations/webhooks/commercePayloads.ts +0 -159
  270. package/apps/storefront/src/lib/integrations/webhooks/deliveryEngine.ts +0 -379
  271. package/apps/storefront/src/lib/integrations/webhooks/deliveryMapper.ts +0 -34
  272. package/apps/storefront/src/lib/integrations/webhooks/deliveryStore.ts +0 -903
  273. package/apps/storefront/src/lib/integrations/webhooks/dispatcher.ts +0 -168
  274. package/apps/storefront/src/lib/integrations/webhooks/emit.ts +0 -245
  275. package/apps/storefront/src/lib/integrations/webhooks/events.ts +0 -105
  276. package/apps/storefront/src/lib/integrations/webhooks/getDispatcher.ts +0 -77
  277. package/apps/storefront/src/lib/integrations/webhooks/orderFulfilledClaim.ts +0 -75
  278. package/apps/storefront/src/lib/measurement/admin/analyticsRegionPolicy.ts +0 -151
  279. package/apps/storefront/src/lib/measurement/admin/analyticsRegionsClient.ts +0 -84
  280. package/apps/storefront/src/lib/measurement/admin/consentSettingsClient.ts +0 -113
  281. package/apps/storefront/src/lib/measurement/analytics/index.ts +0 -44
  282. package/apps/storefront/src/lib/measurement/attribution/attributionService.ts +0 -206
  283. package/apps/storefront/src/lib/measurement/attribution/orderConversionD1.ts +0 -150
  284. package/apps/storefront/src/lib/measurement/attribution/verifiedProviderMeasurement.ts +0 -118
  285. package/apps/storefront/src/lib/measurement/tracking/interactionCollector.ts +0 -205
  286. package/apps/storefront/src/lib/measurement/tracking/pruneRollup.ts +0 -260
  287. package/apps/storefront/src/lib/measurement/tracking/tenantReadAccess.ts +0 -138
  288. package/apps/storefront/src/lib/measurement/tracking-writeback/rewriteTrackingIds.ts +0 -175
  289. package/apps/storefront/src/lib/measurement/tracking-writeback/writebackCandidate.ts +0 -110
  290. package/apps/storefront/src/lib/observability/diag/capture.ts +0 -162
  291. package/apps/storefront/src/lib/observability/diag/consoleLine.ts +0 -76
  292. package/apps/storefront/src/lib/observability/diag/debugConsole.ts +0 -118
  293. package/apps/storefront/src/lib/observability/diag/debugMode.ts +0 -163
  294. package/apps/storefront/src/lib/observability/diag/debugWindow.ts +0 -111
  295. package/apps/storefront/src/lib/observability/diag/redact.ts +0 -17
  296. package/apps/storefront/src/lib/observability/diag/reference.ts +0 -148
  297. package/apps/storefront/src/lib/observability/diag/referenceStore.ts +0 -113
  298. package/apps/storefront/src/lib/observability/diag/report.ts +0 -110
  299. package/apps/storefront/src/lib/observability/diag/serverResponseTime.ts +0 -91
  300. package/apps/storefront/src/lib/observability/diag/session.ts +0 -93
  301. package/apps/storefront/src/lib/observability/monitoring/manifest.ts +0 -301
  302. package/apps/storefront/src/lib/observability/performance/lighthouseReport.ts +0 -109
  303. package/apps/storefront/src/lib/observability/performance/rumAlert.ts +0 -179
  304. package/apps/storefront/src/lib/orders/admin/orderActions.ts +0 -556
  305. package/apps/storefront/src/lib/orders/admin/orderClient.ts +0 -248
  306. package/apps/storefront/src/lib/orders/admin/orderSource.ts +0 -410
  307. package/apps/storefront/src/lib/orders/admin/services/orders.ts +0 -922
  308. package/apps/storefront/src/lib/orders/admin/viewmodels/orders.ts +0 -135
  309. package/apps/storefront/src/lib/orders/data/commerceCallerConfig.ts +0 -37
  310. package/apps/storefront/src/lib/orders/data/ledgerContractOrders.ts +0 -148
  311. package/apps/storefront/src/lib/orders/data/orderForwardReceiver.ts +0 -532
  312. package/apps/storefront/src/lib/orders/data/orderMapper.ts +0 -454
  313. package/apps/storefront/src/lib/orders/data/ordersStore.ts +0 -623
  314. package/apps/storefront/src/lib/orders/data/sourceAuthorityContract.ts +0 -380
  315. package/apps/storefront/src/lib/orders/data/sourceAuthorityStore.ts +0 -830
  316. package/apps/storefront/src/lib/orders/fixtures/orders.ts +0 -186
  317. package/apps/storefront/src/lib/orders/providers/foxyOrderClient.ts +0 -207
  318. package/apps/storefront/src/lib/orders/vault/appRecipientRead.ts +0 -222
  319. package/apps/storefront/src/lib/orders/vault/contactIntake.ts +0 -63
  320. package/apps/storefront/src/lib/orders/vault/contactRoutes.ts +0 -110
  321. package/apps/storefront/src/lib/orders/vault/kmsEnv.ts +0 -11
  322. package/apps/storefront/src/lib/orders/vault/orderContact.ts +0 -96
  323. package/apps/storefront/src/lib/orders/vault/orderContactVault.ts +0 -1427
  324. package/apps/storefront/src/lib/orders/vault/vault-test-support.ts +0 -258
  325. package/apps/storefront/src/lib/publication/d1/schema-apps.ts +0 -808
  326. package/apps/storefront/src/lib/publication/notifications/candidateConflictEmail.ts +0 -80
  327. package/apps/storefront/src/lib/publication/servingMode.ts +0 -52
  328. package/apps/storefront/src/lib/publication/shared/previewAnnotations/moduleAsset.ts +0 -65
  329. package/apps/storefront/src/lib/publication/shared/routedApiParam.ts +0 -38
  330. package/apps/storefront/src/lib/reporting/admin/viewmodels/reporting.ts +0 -34
  331. package/apps/storefront/src/lib/reporting/fixtures/reporting.ts +0 -51
  332. package/apps/storefront/src/lib/subscriptions/admin/viewmodels/subscriptions.ts +0 -106
  333. package/apps/storefront/src/lib/subscriptions/fixtures/subscriptions.ts +0 -398
  334. package/apps/storefront/src/pages/api/admin/activity-alerts.ts +0 -58
  335. package/apps/storefront/src/pages/api/admin/commerce-readiness.ts +0 -172
  336. package/apps/storefront/src/pages/api/admin/fulfillment/batches.ts +0 -59
  337. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id]/address.ts +0 -66
  338. package/apps/storefront/src/pages/api/admin/fulfillment/orders/[id].ts +0 -118
  339. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contact-search.ts +0 -26
  340. package/apps/storefront/src/pages/api/admin/fulfillment/orders/contacts.ts +0 -22
  341. package/apps/storefront/src/pages/api/admin/interaction-insights.ts +0 -101
  342. package/apps/storefront/src/pages/api/admin/orders/[id].ts +0 -63
  343. package/apps/storefront/src/pages/api/admin/orders.ts +0 -65
  344. package/apps/storefront/src/pages/api/contact.ts +0 -144
  345. package/apps/storefront/src/scheduled/contactVaultSweep.ts +0 -113
  346. package/apps/storefront/src/styles/admin.css +0 -1161
  347. package/apps/storefront/test/pipeline/fake-preview-services.ts +0 -288
  348. package/apps/storefront/test/pipeline/harness.ts +0 -209
  349. package/apps/storefront/test/pipeline/intake-worker.mjs +0 -14
  350. package/apps/storefront/test/pipeline/matrix-faults.ts +0 -366
  351. package/apps/storefront/test/pipeline/pipeline-host.ts +0 -418
  352. package/apps/storefront/test/pipeline/pool-config.cjs +0 -85
  353. package/apps/storefront/test/pipeline/publish-kinds.ts +0 -279
  354. package/apps/storefront/test/pipeline/synthetic-job.ts +0 -303
  355. package/apps/storefront/test/pipeline-faults/matrix-lib.ts +0 -696
  356. package/apps/storefront/vitest.config.cts +0 -44
  357. package/apps/storefront/vitest.faults.config.cts +0 -13
  358. package/apps/storefront/vitest.workers.config.cts +0 -7
  359. package/packages/feedback/fixtures/v1/expected-findings.json +0 -16
  360. package/packages/feedback/fixtures/v1/feedback-action/invalid/carries-transport-credential.json +0 -14
  361. package/packages/feedback/fixtures/v1/feedback-action/invalid/control-char-in-description.json +0 -13
  362. package/packages/feedback/fixtures/v1/feedback-action/invalid/legacy-schema-version.json +0 -13
  363. package/packages/feedback/fixtures/v1/feedback-action/invalid/page-path-with-query.json +0 -14
  364. package/packages/feedback/fixtures/v1/feedback-action/invalid/title-too-short.json +0 -13
  365. package/packages/feedback/fixtures/v1/feedback-action/valid/element-problem.json +0 -33
  366. package/packages/feedback/fixtures/v1/feedback-action/valid/page-comment.json +0 -20
  367. package/packages/feedback/fixtures/v1/feedback-action/valid/region-improvement.json +0 -24
  368. package/packages/feedback/fixtures/v1/feedback-action/valid/text-selection-feature.json +0 -30
  369. package/packages/feedback/fixtures/v1/submission-receipt/invalid/accepted-at-not-utc.json +0 -9
  370. package/packages/feedback/fixtures/v1/submission-receipt/invalid/bad-feedback-id.json +0 -9
  371. package/packages/feedback/fixtures/v1/submission-receipt/invalid/legacy-contract-version.json +0 -9
  372. package/packages/feedback/fixtures/v1/submission-receipt/invalid/missing-replayed.json +0 -8
  373. package/packages/feedback/fixtures/v1/submission-receipt/valid/accepted.json +0 -9
  374. package/packages/feedback/fixtures/v1/submission-receipt/valid/fractional-seconds.json +0 -9
  375. package/packages/feedback/fixtures/v1/submission-receipt/valid/replayed.json +0 -9
  376. package/packages/feedback/fixtures/v1/target-evidence/invalid/page-kind-claims-structure.json +0 -6
  377. package/packages/feedback/fixtures/v1/target-evidence/invalid/path-too-deep.json +0 -17
  378. package/packages/feedback/fixtures/v1/target-evidence/invalid/relative-region-out-of-range.json +0 -11
  379. package/packages/feedback/fixtures/v1/target-evidence/invalid/selector-uses-class.json +0 -7
  380. package/packages/feedback/fixtures/v1/target-evidence/invalid/source-precision-without-anchor.json +0 -6
  381. package/packages/feedback/fixtures/v1/target-evidence/valid/element-structure.json +0 -21
  382. package/packages/feedback/fixtures/v1/target-evidence/valid/host-iframe.json +0 -14
  383. package/packages/feedback/fixtures/v1/target-evidence/valid/source-anchor.json +0 -12
  384. package/packages/feedback/fixtures/v1/target-evidence/valid/text-selection.json +0 -26
  385. package/packages/feedback/package.json +0 -35
  386. package/packages/feedback/scripts/build-player.mjs +0 -28
  387. package/packages/feedback/src/index.ts +0 -1
  388. package/packages/feedback/src/primitives/composer.ts +0 -639
  389. package/packages/feedback/src/primitives/dialog.ts +0 -263
  390. package/packages/feedback/src/primitives/hostAdapter.ts +0 -116
  391. package/packages/feedback/src/primitives/index.ts +0 -10
  392. package/packages/feedback/src/primitives/launcher.ts +0 -200
  393. package/packages/feedback/src/primitives/picker.ts +0 -663
  394. package/packages/feedback/src/primitives/redaction.ts +0 -204
  395. package/packages/feedback/src/primitives/selection.ts +0 -49
  396. package/packages/feedback/src/primitives/shiftAccelerator.ts +0 -160
  397. package/packages/feedback/src/primitives/styles.ts +0 -77
  398. package/packages/feedback/src/primitives/surface.ts +0 -124
  399. package/packages/feedback/src/primitives/target.ts +0 -293
  400. package/packages/feedback/src/tour/canonical.ts +0 -27
  401. package/packages/feedback/src/tour/index.ts +0 -3
  402. package/packages/feedback/src/tour/player/browser.ts +0 -5
  403. package/packages/feedback/src/tour/player/host.ts +0 -12
  404. package/packages/feedback/src/tour/player/index.ts +0 -205
  405. package/packages/feedback/src/tour/player/manifest.ts +0 -76
  406. package/packages/feedback/src/tour/player/player.css +0 -130
  407. package/packages/feedback/src/tour/player/resolver.ts +0 -12
  408. package/packages/feedback/src/tour/player/surface.ts +0 -295
  409. package/packages/feedback/src/tour/player/types.ts +0 -8
  410. package/packages/feedback/src/tour/resolve/core.ts +0 -267
  411. package/packages/feedback/src/tour/resolve/dom.ts +0 -115
  412. package/packages/feedback/src/tour/resolve/index.ts +0 -29
  413. package/packages/feedback/src/tour/sanitize.ts +0 -76
  414. package/packages/feedback/src/tour/schema.ts +0 -362
  415. package/packages/feedback/src/v1/guards.ts +0 -335
  416. package/packages/feedback/src/v1/index.ts +0 -3
  417. package/packages/feedback/src/v1/protectedSurfaces.ts +0 -32
  418. package/packages/feedback/src/v1/types.ts +0 -177
  419. package/packages/feedback/tsconfig.json +0 -9
  420. 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
- }