@thorprovider/storefront 0.6.3 → 0.9.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 (161) hide show
  1. package/README.md +22 -2
  2. package/assets/templates/AGENTS.md +14 -2
  3. package/assets/templates/app/app/[[...slug]]/page.tsx +9 -2
  4. package/assets/templates/app/lib/__STOREFRONT__/account-address.ts +129 -0
  5. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +2 -2
  6. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +143 -0
  7. package/assets/templates/app/lib/__STOREFRONT__/account-profile.ts +220 -0
  8. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +1234 -75
  9. package/assets/templates/app/lib/__STOREFRONT__/addresses-port.ts +107 -0
  10. package/assets/templates/app/lib/__STOREFRONT__/checkout-shipping.core.ts +37 -0
  11. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +460 -35
  12. package/assets/templates/app/lib/__STOREFRONT__/confirmation.core.ts +240 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/customer-profile-port.ts +103 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/order-detail-port.ts +26 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/orders-port.ts +30 -0
  16. package/assets/templates/app/lib/__STOREFRONT__/ports.ts +18 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +4 -4
  18. package/assets/templates/app/lib/__STOREFRONT__/session.ts +24 -6
  19. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +28 -1
  20. package/assets/templates/app/lib/__STOREFRONT__/views/sections/address-book-advanced.client.tsx +29 -0
  21. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.client.tsx +19 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/views/sections/checkout-commerce-v1.tsx +16 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/views/sections/customer-profile.client.tsx +27 -0
  24. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +5 -1
  25. package/assets/templates/app/lib/__STOREFRONT__/views/sections/marketplace-product-card.client.tsx +19 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/views/sections/marketplace-product-card.tsx +16 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.client.tsx +19 -0
  28. package/assets/templates/app/lib/__STOREFRONT__/views/sections/mega-menu-universal.tsx +16 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.address-book-advanced.ts +437 -0
  30. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.checkout-commerce-v1.ts +398 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.customer-profile.ts +138 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.marketplace-product-card.ts +67 -0
  33. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.mega-menu-universal.ts +76 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.universal-banner.ts +217 -0
  35. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.client.tsx +24 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/views/sections/universal-banner.tsx +16 -0
  37. package/assets/templates/features/checkout/handlers.ts +348 -33
  38. package/assets/templates/features/checkout/state.ts +79 -3
  39. package/assets/templates/features/customer-addresses/handlers.ts +11 -0
  40. package/assets/templates/features/customer-addresses/state.ts +33 -0
  41. package/assets/templates/features/customer-auth/state.ts +10 -0
  42. package/assets/templates/features/customer-profile/handlers.ts +11 -0
  43. package/assets/templates/features/customer-profile/state.ts +18 -0
  44. package/assets/templates/views/account/address-book-advanced.defaults.ts +534 -0
  45. package/assets/templates/views/account/assembly/assembly.json +41 -0
  46. package/assets/templates/views/account/assembly/index.skeleton.tsx +229 -0
  47. package/assets/templates/views/account/assembly/registry.skeleton.tsx +1116 -0
  48. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/binding.json +5 -0
  49. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/catalog.part +4 -0
  50. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/element.part +5 -0
  51. package/assets/templates/views/account/assembly/slots/addresses/AddressBookAdvanced/registry.part +1 -0
  52. package/assets/templates/views/account/assembly/slots/addresses/cards/catalog.part +5 -0
  53. package/assets/templates/views/account/assembly/slots/addresses/cards/element.part +10 -0
  54. package/assets/templates/views/account/assembly/slots/addresses/cards/registry.part +1 -0
  55. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/catalog.part +5 -0
  56. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/element.part +5 -0
  57. package/assets/templates/views/account/assembly/slots/boot/AccountBoot/registry.part +1 -0
  58. package/assets/templates/views/account/assembly/slots/login/card/catalog.part +4 -0
  59. package/assets/templates/views/account/assembly/slots/login/card/element.part +13 -0
  60. package/assets/templates/views/account/assembly/slots/login/card/registry.part +1 -0
  61. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/catalog.part +5 -0
  62. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/element.part +5 -0
  63. package/assets/templates/views/account/assembly/slots/orders/OrderHistory/registry.part +2 -0
  64. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/binding.json +5 -0
  65. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/catalog.part +5 -0
  66. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/element.part +5 -0
  67. package/assets/templates/views/account/assembly/slots/orders/OrderHistoryAdvanced/registry.part +1 -0
  68. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/binding.json +5 -0
  69. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/catalog.part +4 -0
  70. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/element.part +5 -0
  71. package/assets/templates/views/account/assembly/slots/profile/CustomerProfileAdvanced/registry.part +1 -0
  72. package/assets/templates/views/account/assembly/slots/profile/form/catalog.part +5 -0
  73. package/assets/templates/views/account/assembly/slots/profile/form/element.part +10 -0
  74. package/assets/templates/views/account/assembly/slots/profile/form/registry.part +1 -0
  75. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/catalog.part +4 -0
  76. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/element.part +13 -0
  77. package/assets/templates/views/account/assembly/slots/register/SignUpPage1/registry.part +1 -0
  78. package/assets/templates/views/account/assembly/slots/summary/stack/catalog.part +5 -0
  79. package/assets/templates/views/account/assembly/slots/summary/stack/element.part +5 -0
  80. package/assets/templates/views/account/assembly/slots/summary/stack/registry.part +1 -0
  81. package/assets/templates/views/account/assembly/slots/summary/tabs/catalog.part +5 -0
  82. package/assets/templates/views/account/assembly/slots/summary/tabs/element.part +5 -0
  83. package/assets/templates/views/account/assembly/slots/summary/tabs/registry.part +1 -0
  84. package/assets/templates/views/account/content.ts +326 -0
  85. package/assets/templates/views/account/customer-profile.defaults.ts +136 -0
  86. package/assets/templates/views/account/index.tsx +218 -35
  87. package/assets/templates/views/account/order-detail.client.tsx +35 -0
  88. package/assets/templates/views/account/order-detail.defaults.ts +457 -0
  89. package/assets/templates/views/account/orders-advanced.client.tsx +166 -0
  90. package/assets/templates/views/account/orders-advanced.defaults.ts +230 -0
  91. package/assets/templates/views/account/registry.tsx +944 -369
  92. package/assets/templates/views/account/schema.ts +50 -0
  93. package/assets/templates/views/account/sections-data.ts +2 -0
  94. package/assets/templates/views/cart/content.ts +1 -0
  95. package/assets/templates/views/category/assembly/index.skeleton.tsx +1 -0
  96. package/assets/templates/views/category/assembly/slots/filter/CategoryListing/element.part +1 -0
  97. package/assets/templates/views/category/content.ts +2 -0
  98. package/assets/templates/views/category/index.tsx +2 -0
  99. package/assets/templates/views/category/sections-data.ts +2 -0
  100. package/assets/templates/views/checkout/checkout-commerce-hosted.tsx +1089 -0
  101. package/assets/templates/views/checkout/content.ts +114 -2
  102. package/assets/templates/views/checkout/index.tsx +7 -1
  103. package/assets/templates/views/checkout/props.ts +70 -22
  104. package/assets/templates/views/checkout/registry.tsx +400 -71
  105. package/assets/templates/views/checkout/schema.ts +260 -9
  106. package/assets/templates/views/home/assembly/assembly.json +28 -0
  107. package/assets/templates/views/home/assembly/index.skeleton.tsx +1 -0
  108. package/assets/templates/views/home/content.ts +2 -0
  109. package/assets/templates/views/home/index.tsx +1 -0
  110. package/assets/templates/views/home/sections-data.ts +2 -0
  111. package/assets/templates/views/product/content.ts +1 -0
  112. package/assets/templates/views/static/content.ts +1 -0
  113. package/bin/storefront.js +343 -13
  114. package/package.json +2 -1
  115. package/recipes/adapter-surface.json +158 -0
  116. package/recipes/archetypes.json +38 -3
  117. package/recipes/catalog.json +138 -1
  118. package/recipes/feature.schema.json +9 -0
  119. package/recipes/features.json +72 -1
  120. package/recipes/manifest.schema.json +5 -0
  121. package/recipes/recipe.schema.json +14 -2
  122. package/recipes/recipes.json +35 -5
  123. package/recipes/section.schema.json +112 -0
  124. package/recipes/sections.json +289 -3
  125. package/recipes/validate.mjs +83 -1
  126. package/scripts/adapter-surface.mjs +41 -0
  127. package/scripts/agent-blocks.mjs +700 -0
  128. package/scripts/block-validator.mjs +45 -0
  129. package/scripts/candidate.mjs +5 -4
  130. package/scripts/composers.mjs +7 -2
  131. package/scripts/default-sections.mjs +78 -0
  132. package/scripts/file-classes.mjs +15 -0
  133. package/scripts/generate-adapter-surface.mjs +148 -0
  134. package/scripts/operations.mjs +100 -0
  135. package/scripts/reconcile.mjs +67 -39
  136. package/scripts/section-configure.mjs +316 -0
  137. package/scripts/sync-assets.mjs +1 -0
  138. package/scripts/view-assembly.mjs +101 -14
  139. package/skills/sf-feature/SKILL.md +19 -0
  140. package/skills/sf-view-gen/SKILL.md +79 -7
  141. package/skills/sf-view-gen/assets/recipes/archetypes.json +38 -3
  142. package/skills/sf-view-gen/assets/recipes/catalog.json +138 -1
  143. package/skills/sf-view-gen/assets/recipes/features.json +72 -1
  144. package/skills/sf-view-gen/assets/recipes/recipes.json +35 -5
  145. package/skills/sf-view-gen/assets/recipes/section.schema.json +112 -0
  146. package/skills/sf-view-gen/assets/recipes/sections.json +289 -3
  147. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.client.tsx +19 -0
  148. package/skills/sf-view-gen/assets/templates/views/sections/checkout-commerce-v1.tsx +16 -0
  149. package/skills/sf-view-gen/assets/templates/views/sections/marketplace-product-card.client.tsx +19 -0
  150. package/skills/sf-view-gen/assets/templates/views/sections/marketplace-product-card.tsx +16 -0
  151. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.client.tsx +19 -0
  152. package/skills/sf-view-gen/assets/templates/views/sections/mega-menu-universal.tsx +16 -0
  153. package/skills/sf-view-gen/assets/templates/views/sections/schema.checkout-commerce-v1.ts +398 -0
  154. package/skills/sf-view-gen/assets/templates/views/sections/schema.marketplace-product-card.ts +67 -0
  155. package/skills/sf-view-gen/assets/templates/views/sections/schema.mega-menu-universal.ts +76 -0
  156. package/skills/sf-view-gen/assets/templates/views/sections/schema.universal-banner.ts +217 -0
  157. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.client.tsx +24 -0
  158. package/skills/sf-view-gen/assets/templates/views/sections/universal-banner.tsx +16 -0
  159. package/skills/sf-view-gen/scripts/validate.mjs +83 -1
  160. package/skills/storefront-workflow/SKILL.md +5 -0
  161. package/skills/storefront-workflow/references/mobile-responsiveness.md +1 -1
@@ -19,46 +19,71 @@
19
19
  // the committed cart (`completedAt`) and completes once only when committed.
20
20
 
21
21
  import type {
22
+ Address,
22
23
  Cart,
24
+ CheckoutAddressOption,
25
+ CreateAddressData,
23
26
  Customer,
24
27
  LoginCredentials,
25
28
  Money,
26
29
  Order,
27
30
  PaymentMethod,
28
31
  RegisterData,
32
+ ShippingGroupQuote,
33
+ ShippingGroupSelection,
29
34
  ShippingMethod,
30
35
  StoreContext,
36
+ UpdateCustomerData,
31
37
  } from '@thorprovider/types'
38
+ import {
39
+ toStorefrontConfirmation,
40
+ type StorefrontConfirmation,
41
+ } from './confirmation.core'
32
42
  import {
33
43
  addCartLines,
34
- applyManualTestPayment,
44
+ applyCheckoutShippingGroups as applyCheckoutShippingGroupsRuntime,
45
+ applyPaymentMethod as applyPaymentMethodRuntime,
35
46
  APPROVED_MANUAL_TEST_PROVIDER_ID,
47
+ assignCartToCustomer as assignCartToCustomerRuntime,
36
48
  completeCart,
37
49
  createCartForContext,
50
+ createCustomerAddress as createCustomerAddressRuntime,
51
+ deleteCustomerAddress as deleteCustomerAddressRuntime,
38
52
  getCartForContext,
39
53
  getCheckoutCountries,
54
+ getCommerceClientWithToken,
55
+ getCheckoutShippingGroups as getCheckoutShippingGroupsRuntime,
40
56
  getCurrentCustomer,
57
+ getCustomerAddresses,
41
58
  getCustomerOrders,
59
+ getGeoCities,
60
+ getGeoProvinces,
42
61
  getCustomerOrdersPage,
43
62
  getEligibleShippingMethods,
44
63
  getPaymentMethodsByRegion,
45
64
  getProductDetailByHandle,
46
65
  loginCustomer,
47
66
  logoutCustomer,
67
+ updateCustomer as updateCustomerRuntime,
48
68
  reconcileCart,
49
69
  registerCustomer,
50
70
  removeCartLines,
51
71
  selectFirstPurchasableVariant,
52
72
  selectShippingMethod,
53
73
  toAbsoluteLineUpdate,
74
+ updateBillingAddress,
54
75
  updateCartLines,
76
+ updateCustomerAddress as updateCustomerAddressRuntime,
55
77
  updateShippingAddress,
56
78
  validateCheckoutAddressForRegion,
79
+ validateCustomerAddressForRegion,
57
80
  type AuthOutcome,
81
+ type BillingAddressInput,
58
82
  type CartCompletionResult,
59
83
  type CatalogProductDetail,
60
84
  type CheckoutAddress,
61
85
  type CheckoutFieldError,
86
+ type CustomerAddress,
62
87
  type RegionCountry,
63
88
  } from '@thorprovider/runtime/commerce'
64
89
  import type {
@@ -72,6 +97,9 @@ import type {
72
97
  StorefrontOrderLineView,
73
98
  } from './state.core'
74
99
  import { assertBackendConfigured, getDataSource, getStoreContext, type StoreDataSource } from './store-context'
100
+ import { queryOrderHistoryPage } from '@thorprovider/blocks'
101
+ import type { OrderHistoryAdvancedRecord } from '@thorprovider/blocks'
102
+ import type { OrdersPage, OrdersQuery } from '@thorprovider/blocks/ports'
75
103
 
76
104
  // ---------------------------------------------------------------------------
77
105
  // Projections (serializable; the UI state holds these)
@@ -99,9 +127,24 @@ export const EMPTY_CART_STATE: CartStatePatch = {
99
127
  cartSelectedShippingOptionId: null,
100
128
  }
101
129
 
130
+ /**
131
+ * Request-scoped provider used by the host. A customer token produces a
132
+ * provider whose SDK carries that token; no token produces the guest provider.
133
+ */
134
+ export type HostCommerceProvider = ReturnType<typeof getCommerceClientWithToken>
135
+
136
+ export function getHostCommerceProvider(token: string | null): HostCommerceProvider {
137
+ return getCommerceClientWithToken(token)
138
+ }
139
+
102
140
  /** Result of a completion attempt. `unresolved` must never be blindly retried. */
103
141
  export type PlaceOrderResult =
104
- | { status: 'order'; order: StorefrontOrder; lines: StorefrontOrderLineView[] }
142
+ | {
143
+ status: 'order'
144
+ order: StorefrontOrder
145
+ lines: StorefrontOrderLineView[]
146
+ confirmation: StorefrontConfirmation
147
+ }
105
148
  | { status: 'error'; message: string; code?: string }
106
149
  | { status: 'cart-error'; message: string; code?: string }
107
150
  | { status: 'unresolved'; message: string; code?: string }
@@ -227,6 +270,14 @@ export function toCheckoutShippingOptions(methods: ShippingMethod[]): CheckoutSh
227
270
  }))
228
271
  }
229
272
 
273
+ export {
274
+ checkoutShippingGroupId,
275
+ toCheckoutShippingGroups,
276
+ } from '@thorprovider/runtime/commerce/shipping'
277
+ export type {
278
+ CheckoutShippingGroupsMapping,
279
+ } from '@thorprovider/runtime/commerce/shipping'
280
+
230
281
  /** Group the runtime's structured field errors into the block's error shape. */
231
282
  export function toCheckoutFieldErrors(errors: CheckoutFieldError[]): CheckoutFieldErrors {
232
283
  const grouped: CheckoutFieldErrors = {}
@@ -239,7 +290,12 @@ export function toCheckoutFieldErrors(errors: CheckoutFieldError[]): CheckoutFie
239
290
  /** Map the runtime's discriminated completion to the host result union. */
240
291
  export function toPlaceOrderResult(result: CartCompletionResult): PlaceOrderResult {
241
292
  if (result.type === 'order') {
242
- return { status: 'order', order: toStorefrontOrder(result.order), lines: toOrderLines(result.order) }
293
+ return {
294
+ status: 'order',
295
+ order: toStorefrontOrder(result.order),
296
+ lines: toOrderLines(result.order),
297
+ confirmation: toStorefrontConfirmation(result.order),
298
+ }
243
299
  }
244
300
  if (result.type === 'cart') {
245
301
  return { status: 'cart-error', message: result.error.message, code: result.error.code }
@@ -292,26 +348,65 @@ export function resolveProductCartTarget(
292
348
  export async function readCart(
293
349
  cartId: string,
294
350
  context: StoreContext = getStoreContext(),
351
+ provider?: HostCommerceProvider,
295
352
  ): Promise<CartStatePatch | undefined> {
296
353
  assertBackendConfigured()
297
- const cart = await getCartForContext(cartId, context)
354
+ const cart = await getCartForContext(cartId, context, provider)
298
355
  return cart ? toCartState(cart) : undefined
299
356
  }
300
357
 
358
+ /** The backend customer id of a cart, or undefined when the cart is missing. */
359
+ export async function loadCartCustomerId(
360
+ cartId: string,
361
+ context: StoreContext = getStoreContext(),
362
+ provider?: HostCommerceProvider,
363
+ ): Promise<string | null | undefined> {
364
+ assertBackendConfigured()
365
+ const cart = await getCartForContext(cartId, context, provider)
366
+ return cart ? (cart.customerId ?? null) : undefined
367
+ }
368
+
301
369
  export async function loadCheckoutCountries(
302
370
  cartId: string,
303
371
  context: StoreContext = getStoreContext(),
372
+ provider?: HostCommerceProvider,
304
373
  ): Promise<RegionCountry[]> {
305
374
  assertBackendConfigured()
306
- return getCheckoutCountries(cartId, context)
375
+ return getCheckoutCountries(cartId, context, provider)
376
+ }
377
+
378
+ /** Persist a billing address distinct from shipping, when the provider supports it. */
379
+ export async function saveBillingAddress(
380
+ cartId: string,
381
+ address: BillingAddressInput,
382
+ context: StoreContext = getStoreContext(),
383
+ provider?: HostCommerceProvider,
384
+ ): Promise<void> {
385
+ assertBackendConfigured()
386
+ return updateBillingAddress(cartId, address, provider)
307
387
  }
308
388
 
309
389
  export async function loadShippingMethods(
310
390
  cartId: string,
311
391
  context: StoreContext = getStoreContext(),
392
+ provider?: HostCommerceProvider,
312
393
  ): Promise<ShippingMethod[]> {
313
394
  assertBackendConfigured()
314
- return getEligibleShippingMethods(cartId, context)
395
+ return getEligibleShippingMethods(cartId, context, provider)
396
+ }
397
+
398
+ /**
399
+ * Request the backend's grouped shipping quote for the cart. The groups are the
400
+ * backend's own decision (no local grouping); a provider without the grouped
401
+ * capability fails explicitly instead of returning an empty quote.
402
+ */
403
+ export async function loadCheckoutShippingGroups(
404
+ cartId: string,
405
+ context: StoreContext = getStoreContext(),
406
+ provider?: HostCommerceProvider,
407
+ ): Promise<ShippingGroupQuote> {
408
+ assertBackendConfigured()
409
+ return getCheckoutShippingGroupsRuntime(cartId, context, provider)
315
410
  }
316
411
 
317
412
  /**
@@ -333,9 +428,10 @@ export function toDisplayPaymentMethods(methods: PaymentMethod[]): PaymentMethod
333
428
 
334
429
  export async function loadPaymentMethods(
335
430
  context: StoreContext = getStoreContext(),
431
+ provider?: HostCommerceProvider,
336
432
  ): Promise<PaymentMethod[]> {
337
433
  assertBackendConfigured()
338
- const methods = await getPaymentMethodsByRegion(context.regionId)
434
+ const methods = await getPaymentMethodsByRegion(context.regionId, provider)
339
435
  return toDisplayPaymentMethods(methods)
340
436
  }
341
437
 
@@ -343,12 +439,13 @@ export async function loadPaymentMethods(
343
439
  // Cart mutations (context-scoped)
344
440
  // ---------------------------------------------------------------------------
345
441
 
346
- /** Create a fresh backend guest cart in the store context region. */
442
+ /** Create a fresh backend cart in the store context region (guest or token-scoped). */
347
443
  export async function createGuestCart(
348
444
  context: StoreContext = getStoreContext(),
445
+ provider?: HostCommerceProvider,
349
446
  ): Promise<CartStatePatch> {
350
447
  assertBackendConfigured()
351
- const cart = await createCartForContext(context)
448
+ const cart = await createCartForContext(context, provider)
352
449
  return toCartState(cart)
353
450
  }
354
451
 
@@ -358,9 +455,15 @@ export async function addVariant(
358
455
  variantId: string,
359
456
  quantity: number,
360
457
  context: StoreContext = getStoreContext(),
458
+ provider?: HostCommerceProvider,
361
459
  ): Promise<CartStatePatch> {
362
460
  assertBackendConfigured()
363
- const cart = await addCartLines(cartId, [{ merchandiseId: variantId, quantity }], context)
461
+ const cart = await addCartLines(
462
+ cartId,
463
+ [{ merchandiseId: variantId, quantity }],
464
+ context,
465
+ provider,
466
+ )
364
467
  return toCartState(cart)
365
468
  }
366
469
 
@@ -371,9 +474,15 @@ export async function setLineQuantity(
371
474
  merchandiseId: string,
372
475
  quantity: number,
373
476
  context: StoreContext = getStoreContext(),
477
+ provider?: HostCommerceProvider,
374
478
  ): Promise<CartStatePatch> {
375
479
  assertBackendConfigured()
376
- const cart = await updateCartLines(cartId, [{ id: lineId, merchandiseId, quantity }], context)
480
+ const cart = await updateCartLines(
481
+ cartId,
482
+ [{ id: lineId, merchandiseId, quantity }],
483
+ context,
484
+ provider,
485
+ )
377
486
  return toCartState(cart)
378
487
  }
379
488
 
@@ -383,12 +492,13 @@ export async function applyLineDelta(
383
492
  lineId: string,
384
493
  delta: number,
385
494
  context: StoreContext = getStoreContext(),
495
+ provider?: HostCommerceProvider,
386
496
  ): Promise<CartStatePatch> {
387
497
  assertBackendConfigured()
388
- const current = await getCartForContext(cartId, context)
498
+ const current = await getCartForContext(cartId, context, provider)
389
499
  if (!current) throw new Error(`Cart not found: ${cartId}`)
390
500
  const update = toAbsoluteLineUpdate(current, lineId, delta)
391
- const cart = await updateCartLines(cartId, [update], context)
501
+ const cart = await updateCartLines(cartId, [update], context, provider)
392
502
  return toCartState(cart)
393
503
  }
394
504
 
@@ -397,9 +507,10 @@ export async function removeLine(
397
507
  cartId: string,
398
508
  lineId: string,
399
509
  context: StoreContext = getStoreContext(),
510
+ provider?: HostCommerceProvider,
400
511
  ): Promise<CartStatePatch> {
401
512
  assertBackendConfigured()
402
- const cart = await removeCartLines(cartId, [lineId], context)
513
+ const cart = await removeCartLines(cartId, [lineId], context, provider)
403
514
  return toCartState(cart)
404
515
  }
405
516
 
@@ -433,62 +544,110 @@ export async function saveShippingAddress(
433
544
  cartId: string,
434
545
  address: AddressInput,
435
546
  context: StoreContext = getStoreContext(),
547
+ provider?: HostCommerceProvider,
436
548
  ): Promise<CartStatePatch> {
437
549
  assertBackendConfigured()
438
- const current = await getCartForContext(cartId, context)
550
+ const current = await getCartForContext(cartId, context, provider)
439
551
  if (!current) throw new Error(`Cart not found before address update: ${cartId}`)
440
552
  try {
441
553
  // The runtime address validator treats province/phone as optional; the
442
554
  // address-setter input still declares them, so pass an empty string when the
443
555
  // shopper did not supply one rather than failing the type contract.
444
- await updateShippingAddress(cartId, {
445
- email: address.email,
446
- firstName: address.firstName,
447
- lastName: address.lastName,
448
- address1: address.address1,
449
- address2: address.address2,
450
- company: address.company,
451
- city: address.city,
452
- province: address.province ?? '',
453
- postalCode: address.postalCode,
454
- countryCode: address.countryCode,
455
- phone: address.phone ?? '',
456
- })
556
+ await updateShippingAddress(
557
+ cartId,
558
+ {
559
+ email: address.email,
560
+ firstName: address.firstName,
561
+ lastName: address.lastName,
562
+ address1: address.address1,
563
+ address2: address.address2,
564
+ company: address.company,
565
+ city: address.city,
566
+ province: address.province ?? '',
567
+ postalCode: address.postalCode,
568
+ countryCode: address.countryCode,
569
+ phone: address.phone ?? '',
570
+ },
571
+ provider,
572
+ )
457
573
  } catch (error) {
458
574
  if (isUnsupportedAddressUpdate(error)) return toCartState(current)
459
575
  throw error
460
576
  }
461
- const cart = await getCartForContext(cartId, context)
577
+ const cart = await getCartForContext(cartId, context, provider)
462
578
  return toCartState(cart ?? current)
463
579
  }
464
580
 
581
+ /** Transfer a guest cart to the authenticated customer. */
582
+ export async function assignCartToCustomer(
583
+ cartId: string,
584
+ context: StoreContext = getStoreContext(),
585
+ provider?: HostCommerceProvider,
586
+ ): Promise<CartStatePatch> {
587
+ assertBackendConfigured()
588
+ const cart = await assignCartToCustomerRuntime(cartId, context, provider)
589
+ return toCartState(cart)
590
+ }
591
+
465
592
  /** Apply an eligible shipping method and return the recalculated cart. */
466
593
  export async function selectShipping(
467
594
  cartId: string,
468
595
  methodId: string,
469
596
  context: StoreContext = getStoreContext(),
597
+ provider?: HostCommerceProvider,
598
+ ): Promise<CartStatePatch> {
599
+ assertBackendConfigured()
600
+ const cart = await selectShippingMethod(cartId, methodId, context, provider)
601
+ return toCartState(cart)
602
+ }
603
+
604
+ /**
605
+ * Apply one selected option per backend group, then return the RE-READ cart.
606
+ * The runtime validates the cart context and re-reads the authoritative cart;
607
+ * per-group amounts are never summed here or used as totals.
608
+ */
609
+ export async function applyCheckoutShippingGroups(
610
+ cartId: string,
611
+ selections: ShippingGroupSelection[],
612
+ context: StoreContext = getStoreContext(),
613
+ provider?: HostCommerceProvider,
470
614
  ): Promise<CartStatePatch> {
471
615
  assertBackendConfigured()
472
- const cart = await selectShippingMethod(cartId, methodId, context)
616
+ const cart = await applyCheckoutShippingGroupsRuntime(cartId, selections, context, provider)
473
617
  return toCartState(cart)
474
618
  }
475
619
 
476
- /** Apply the single approved manual TEST payment provider (requires shipping). */
620
+ /**
621
+ * Start the shopper's selected payment method after shipping is final.
622
+ *
623
+ * Any provider listed by the backend is accepted here; the runtime validates
624
+ * that it exists, is enabled and does not still require setup. Provider-specific
625
+ * client confirmation (redirect, 3DS, wallet) remains a host surface.
626
+ */
477
627
  export async function applyPayment(
478
628
  cartId: string,
629
+ providerId: string,
479
630
  context: StoreContext = getStoreContext(),
480
- ): Promise<void> {
631
+ provider?: HostCommerceProvider,
632
+ ): Promise<PaymentMethod> {
481
633
  assertBackendConfigured()
482
- await applyManualTestPayment(cartId, context)
634
+ return applyPaymentMethodRuntime(cartId, providerId, context, provider)
483
635
  }
484
636
 
485
637
  /** Complete the cart exactly once, preserving the native discriminator. */
486
638
  export async function completeOrder(
487
639
  cartId: string,
488
640
  context: StoreContext = getStoreContext(),
641
+ customerToken?: string | null,
489
642
  ): Promise<PlaceOrderResult> {
490
643
  assertBackendConfigured()
491
- return toPlaceOrderResult(await completeCart(cartId, context))
644
+ // The host owns the auth cookie and threads the request's customer token
645
+ // into the completion so the backend attributes the order to the session
646
+ // customer (mock) or links it server-side (Medusa). A tokenless completion
647
+ // builds exactly the provider the previous token-blind default built.
648
+ return toPlaceOrderResult(
649
+ await completeCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
650
+ )
492
651
  }
493
652
 
494
653
  /**
@@ -500,9 +659,12 @@ export async function completeOrder(
500
659
  export async function reconcileOrder(
501
660
  cartId: string,
502
661
  context: StoreContext = getStoreContext(),
662
+ customerToken?: string | null,
503
663
  ): Promise<PlaceOrderResult> {
504
664
  assertBackendConfigured()
505
- return toPlaceOrderResult(await reconcileCart(cartId, context))
665
+ return toPlaceOrderResult(
666
+ await reconcileCart(cartId, context, getCommerceClientWithToken(customerToken ?? null)),
667
+ )
506
668
  }
507
669
 
508
670
  // ---------------------------------------------------------------------------
@@ -534,6 +696,68 @@ export async function loadCustomer(token: string | null): Promise<Customer | nul
534
696
  return getCurrentCustomer(token)
535
697
  }
536
698
 
699
+ /** Read the authenticated customer's saved addresses for checkout prefill. */
700
+ export async function loadCustomerAddresses(token: string): Promise<Address[]> {
701
+ return getCustomerAddresses(token)
702
+ }
703
+
704
+ /** Update the authenticated customer's profile (name, phone, and email when supported). */
705
+ export async function updateCustomerProfile(
706
+ token: string,
707
+ data: UpdateCustomerData,
708
+ ): Promise<Customer> {
709
+ return updateCustomerRuntime(token, data)
710
+ }
711
+
712
+ /** Validate a saved-address payload without the contact email. */
713
+ export function validateCustomerAddress(
714
+ input: unknown,
715
+ countries: RegionCountry[],
716
+ ): { success: true; address: CustomerAddress } | { success: false; errors: CheckoutFieldError[] } {
717
+ return validateCustomerAddressForRegion(input, countries)
718
+ }
719
+
720
+ /** Create an address in the authenticated customer's address book. */
721
+ export async function createCustomerAddress(
722
+ token: string,
723
+ data: CreateAddressData,
724
+ ): Promise<Address> {
725
+ return createCustomerAddressRuntime(token, data)
726
+ }
727
+
728
+ /** Update an address in the authenticated customer's address book. */
729
+ export async function updateCustomerAddress(
730
+ token: string,
731
+ addressId: string,
732
+ data: Partial<CreateAddressData>,
733
+ ): Promise<Address> {
734
+ return updateCustomerAddressRuntime(token, addressId, data)
735
+ }
736
+
737
+ /** Delete an address from the authenticated customer's address book. */
738
+ export async function deleteCustomerAddress(
739
+ token: string,
740
+ addressId: string,
741
+ ): Promise<void> {
742
+ return deleteCustomerAddressRuntime(token, addressId)
743
+ }
744
+
745
+ /** Provinces/states from the provider geo-reference for one country. */
746
+ export async function loadGeoProvinces(countryCode: string): Promise<CheckoutAddressOption[]> {
747
+ return getGeoProvinces(countryCode)
748
+ }
749
+
750
+ /** Cities from the provider geo-reference for one province (name or code). */
751
+ export async function loadGeoCities(
752
+ province: string,
753
+ countryCode?: string,
754
+ ): Promise<CheckoutAddressOption[]> {
755
+ return getGeoCities(province, countryCode)
756
+ }
757
+
758
+ /** Pure checkout prefill helper; the host supplies cart, profile, and addresses. */
759
+ export { prefillCheckoutFromCustomer } from '@thorprovider/runtime/commerce'
760
+
537
761
  // ---------------------------------------------------------------------------
538
762
  // Customer orders boundary (change: storefront-customer-orders, task 2.1)
539
763
  // ---------------------------------------------------------------------------
@@ -656,4 +880,205 @@ export async function loadOrdersPage(
656
880
  }
657
881
  }
658
882
 
883
+ // ---------------------------------------------------------------------------
884
+ // Advanced order-history boundary (account.orders default surface)
885
+ // ---------------------------------------------------------------------------
886
+ //
887
+ // The `OrderHistoryAdvanced` block owns its query lifecycle, so the host hands
888
+ // it a `OrdersPort` runner. The runner reads the same token-scoped customer
889
+ // history the canonical surface reads and maps it into the block's normalised
890
+ // `OrderRecord`: amounts cross as integer minor units (the block formats them),
891
+ // dates cross as `YYYY-MM-DD` (the block formats the long date), and a field the
892
+ // backend omits is omitted or reported as the neutral state, never invented.
893
+
894
+ /** Currency fraction digits, read from Intl (USD 2, JPY 0). */
895
+ function currencyFractionDigits(currency: string): number {
896
+ try {
897
+ return (
898
+ new Intl.NumberFormat('en', { style: 'currency', currency }).resolvedOptions()
899
+ .maximumFractionDigits ?? 2
900
+ )
901
+ } catch {
902
+ return 2
903
+ }
904
+ }
905
+
906
+ /** The backend decimal string as integer minor units, the block's money shape. */
907
+ export function toOrderHistoryMoney(money: Money): OrderHistoryAdvancedRecord['total'] {
908
+ const digits = currencyFractionDigits(money.currencyCode)
909
+ return {
910
+ amount: Math.round(Number(money.amount) * 10 ** digits),
911
+ currency: money.currencyCode,
912
+ }
913
+ }
914
+
915
+ /** The date part of an ISO timestamp; the block formats the long date itself. */
916
+ function toOrderHistoryDate(value: string): string {
917
+ return /^\d{4}-\d{2}-\d{2}T/.test(value) ? value.slice(0, 10) : value
918
+ }
919
+
920
+ function toOrderHistoryCommercial(
921
+ status: Order['status'],
922
+ ): OrderHistoryAdvancedRecord['commercial'] {
923
+ switch (status) {
924
+ case 'pending':
925
+ case 'processing':
926
+ case 'completed':
927
+ case 'cancelled':
928
+ return status
929
+ // A refunded order is finished; the refund field carries the refund itself
930
+ // and the block derives the buyer-facing `refunded` status from it.
931
+ case 'refunded':
932
+ return 'completed'
933
+ }
934
+ }
935
+
936
+ function toOrderHistoryPaymentStatus(
937
+ status: Order['paymentStatus'],
938
+ ): OrderHistoryAdvancedRecord['payment']['status'] {
939
+ switch (status) {
940
+ case 'pending':
941
+ return 'unpaid'
942
+ case 'authorized':
943
+ return 'authorized'
944
+ case 'paid':
945
+ case 'partially_refunded':
946
+ case 'refunded':
947
+ return 'paid'
948
+ }
949
+ }
950
+
951
+ function toOrderHistoryRefund(
952
+ status: Order['paymentStatus'],
953
+ ): OrderHistoryAdvancedRecord['refund'] {
954
+ if (status === 'refunded') return 'full'
955
+ if (status === 'partially_refunded') return 'partial'
956
+ return 'none'
957
+ }
958
+
959
+ function toOrderHistoryFulfilmentStatus(
960
+ status: Order['fulfillmentStatus'],
961
+ ): OrderHistoryAdvancedRecord['fulfilment']['status'] {
962
+ switch (status) {
963
+ case 'unfulfilled':
964
+ return 'unfulfilled'
965
+ case 'partially_fulfilled':
966
+ return 'partially_delivered'
967
+ case 'fulfilled':
968
+ case 'returned':
969
+ return 'delivered'
970
+ }
971
+ }
972
+
973
+ function toOrderHistoryDeliveryMode(
974
+ order: Order,
975
+ ): OrderHistoryAdvancedRecord['deliveryMode'] {
976
+ const modes: Array<'shipping' | 'pickup'> = []
977
+ for (const group of order.deliveryGroups ?? []) {
978
+ if (group.mode === 'shipping' || group.mode === 'pickup') modes.push(group.mode)
979
+ }
980
+ const declared = order.shippingMethod?.mode
981
+ if (declared === 'shipping' || declared === 'pickup') modes.push(declared)
982
+ if (modes.length === 0) return 'shipping'
983
+ const pickup = modes.includes('pickup')
984
+ const shipping = modes.includes('shipping')
985
+ return pickup && shipping ? 'mixed' : pickup ? 'pickup' : 'shipping'
986
+ }
987
+
988
+ export function toOrderHistoryItem(
989
+ item: Order['items'][number],
990
+ ): OrderHistoryAdvancedRecord['items'][number] {
991
+ const view: OrderHistoryAdvancedRecord['items'][number] = {
992
+ id: item.id,
993
+ name: item.title,
994
+ // The block requires a searchable line reference; the backend sku wins,
995
+ // then the variant identity, then the line id. Never a blank string.
996
+ sku: item.sku?.trim() || item.variantId || item.id,
997
+ quantity: item.quantity,
998
+ }
999
+ const variant = item.variantTitle?.trim()
1000
+ if (variant) view.variant = variant
1001
+ const image = normalizeImageUrl(item.image?.url)
1002
+ if (image !== undefined) view.image = image
1003
+ return view
1004
+ }
1005
+
1006
+ /** Map one backend order to the advanced block's normalised record. */
1007
+ export function toOrderHistoryRecord(order: Order): OrderHistoryAdvancedRecord {
1008
+ const items = order.items.map(toOrderHistoryItem)
1009
+ return {
1010
+ id: order.id,
1011
+ number: order.orderNumber,
1012
+ placedAt: toOrderHistoryDate(order.createdAt),
1013
+ updatedAt: toOrderHistoryDate(order.updatedAt),
1014
+ total: toOrderHistoryMoney(order.total),
1015
+ items,
1016
+ itemCount: items.reduce((sum, item) => sum + item.quantity, 0),
1017
+ commercial: toOrderHistoryCommercial(order.status),
1018
+ payment: { status: toOrderHistoryPaymentStatus(order.paymentStatus), creditTerms: false },
1019
+ refund: toOrderHistoryRefund(order.paymentStatus),
1020
+ // The order envelope carries no per-shipment records, so the host reports
1021
+ // the aggregate fulfilment status and no fabricated shipment list.
1022
+ fulfilment: {
1023
+ status: toOrderHistoryFulfilmentStatus(order.fulfillmentStatus),
1024
+ shipments: [],
1025
+ },
1026
+ deliveryMode: toOrderHistoryDeliveryMode(order),
1027
+ returns: order.fulfillmentStatus === 'returned' ? 'completed' : 'none',
1028
+ availableActions: ['view'],
1029
+ }
1030
+ }
1031
+
1032
+ // The query ids the block renders. Validated here because a Server Action is a
1033
+ // public endpoint, not only the block's own call site.
1034
+ const ORDER_HISTORY_QUICK = ['all', 'in-progress', 'completed', 'cancelled', 'attention'] as const
1035
+ const ORDER_HISTORY_SORTS = ['newest', 'oldest', 'total-desc', 'total-asc', 'updated'] as const
1036
+
1037
+ /** Guard a port query into the shape the block's engine accepts. */
1038
+ export function normalizeOrdersQuery(input: Partial<OrdersQuery> = {}): OrdersQuery {
1039
+ const page =
1040
+ Number.isInteger(input.page) && (input.page as number) > 0 ? (input.page as number) : 1
1041
+ const requestedSize = Number.isInteger(input.pageSize) ? (input.pageSize as number) : 10
1042
+ const pageSize = Math.min(50, Math.max(1, requestedSize))
1043
+ const quick = ORDER_HISTORY_QUICK.includes(input.quick as (typeof ORDER_HISTORY_QUICK)[number])
1044
+ ? (input.quick as OrdersQuery['quick'])
1045
+ : 'all'
1046
+ const sort = ORDER_HISTORY_SORTS.includes(input.sort as (typeof ORDER_HISTORY_SORTS)[number])
1047
+ ? (input.sort as OrdersQuery['sort'])
1048
+ : 'newest'
1049
+ const filters =
1050
+ input.filters !== null && typeof input.filters === 'object' && !Array.isArray(input.filters)
1051
+ ? input.filters
1052
+ : {}
1053
+ return {
1054
+ search: typeof input.search === 'string' ? input.search.slice(0, 200) : '',
1055
+ quick,
1056
+ filters,
1057
+ ...(input.date !== undefined && typeof input.date === 'object' ? { date: input.date } : {}),
1058
+ ...(input.amount !== undefined && typeof input.amount === 'object'
1059
+ ? { amount: input.amount }
1060
+ : {}),
1061
+ sort,
1062
+ page,
1063
+ pageSize,
1064
+ }
1065
+ }
1066
+
1067
+ /**
1068
+ * One bounded query window for the advanced order-history port. A missing token
1069
+ * yields the empty page without contacting the backend (an unauthenticated
1070
+ * caller has no history); it never fabricates an order. The runtime's
1071
+ * token-scoped `getCustomerOrders` serves both mock mode and Medusa.
1072
+ */
1073
+ export async function loadOrderHistoryPage(
1074
+ token: string | null,
1075
+ query: OrdersQuery,
1076
+ context: StoreContext = getStoreContext(),
1077
+ ): Promise<OrdersPage> {
1078
+ const normalized = normalizeOrdersQuery(query)
1079
+ if (!token) return queryOrderHistoryPage([], normalized)
1080
+ const orders = await getCustomerOrders(token, { salesChannelId: context.salesChannelId })
1081
+ return queryOrderHistoryPage(orders.map(toOrderHistoryRecord), normalized)
1082
+ }
1083
+
659
1084
  export type { Money }