@thorprovider/storefront 0.4.0-mvp.0 → 0.4.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 (225) hide show
  1. package/README.md +174 -156
  2. package/VENDOR.md +69 -0
  3. package/assets/openspec/config.yaml +38 -0
  4. package/assets/templates/AGENTS.md +76 -0
  5. package/assets/templates/app/app/[[...slug]]/page.tsx +56 -2
  6. package/assets/templates/app/app/[[...slug]]/renderer.tsx +44 -2
  7. package/assets/templates/app/app/globals.css +5 -8
  8. package/assets/templates/app/app/layout.tsx +1 -5
  9. package/assets/templates/app/app/robots.ts +9 -3
  10. package/assets/templates/app/app/sitemap.ts +64 -5
  11. package/assets/templates/app/lib/__STOREFRONT__/account-boundary.client.tsx +76 -0
  12. package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +461 -0
  13. package/assets/templates/app/lib/__STOREFRONT__/account-mutation.client.ts +46 -0
  14. package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +103 -0
  15. package/assets/templates/app/lib/__STOREFRONT__/account-reconcile.client.ts +465 -0
  16. package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +177 -0
  17. package/assets/templates/app/lib/__STOREFRONT__/account-session.ts +44 -0
  18. package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +65 -0
  19. package/assets/templates/app/lib/__STOREFRONT__/actions.ts +135 -16
  20. package/assets/templates/app/lib/__STOREFRONT__/catalog.ts +19 -9
  21. package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +61 -0
  22. package/assets/templates/app/lib/__STOREFRONT__/composition.ts +26 -0
  23. package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +36 -4
  24. package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +17 -18
  25. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +209 -0
  26. package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.ts +247 -0
  27. package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +123 -62
  28. package/assets/templates/app/lib/__STOREFRONT__/runtime.ts +3 -0
  29. package/assets/templates/app/lib/__STOREFRONT__/schema.ts +78 -25
  30. package/assets/templates/app/lib/__STOREFRONT__/section-observation.ts +182 -0
  31. package/assets/templates/app/lib/__STOREFRONT__/section-sources.ts +128 -0
  32. package/assets/templates/app/lib/__STOREFRONT__/shell/content.ts +31 -7
  33. package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +4 -0
  34. package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +81 -26
  35. package/assets/templates/app/lib/__STOREFRONT__/spec/seo.ts +165 -0
  36. package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +4 -2
  37. package/assets/templates/app/lib/__STOREFRONT__/store-context.ts +26 -7
  38. package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.client.tsx +1 -1
  39. package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.client.tsx +1 -1
  40. package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +2 -1
  41. package/assets/templates/app/lib/__STOREFRONT__/views/sections/logoCloud.tsx +1 -1
  42. package/assets/templates/app/lib/__STOREFRONT__/views/sections/pricing.tsx +1 -1
  43. package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.client.tsx +100 -0
  44. package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.tsx +19 -0
  45. package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.products.ts +39 -0
  46. package/assets/templates/app/lib/__STOREFRONT__/views/sections/statistics.tsx +1 -1
  47. package/assets/templates/app/lib/__STOREFRONT__/views/sections/testimonials.tsx +1 -1
  48. package/assets/templates/features/checkout/handlers.ts +6 -0
  49. package/assets/templates/features/customer-auth/handlers.ts +19 -23
  50. package/assets/templates/features/customer-auth/state.ts +31 -1
  51. package/assets/templates/views/account/index.tsx +20 -8
  52. package/assets/templates/views/account/registry.tsx +294 -154
  53. package/assets/templates/views/account/schema.ts +1 -0
  54. package/assets/templates/views/cart/content.ts +11 -0
  55. package/assets/templates/views/cart/data.ts +23 -0
  56. package/assets/templates/views/cart/index.tsx +53 -0
  57. package/assets/templates/views/cart/props.ts +12 -0
  58. package/assets/templates/views/cart/registry.tsx +82 -0
  59. package/assets/templates/views/cart/schema.ts +52 -0
  60. package/assets/templates/views/category/assembly/assembly.json +2 -1
  61. package/assets/templates/views/category/assembly/index.skeleton.tsx +64 -6
  62. package/assets/templates/views/category/assembly/registry.skeleton.tsx +7 -6
  63. package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/binding.json +5 -0
  64. package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/catalog.part +4 -0
  65. package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/element.part +7 -0
  66. package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/registry.part +18 -0
  67. package/assets/templates/views/category/index.tsx +76 -7
  68. package/assets/templates/views/category/props.ts +7 -0
  69. package/assets/templates/views/category/registry.tsx +25 -6
  70. package/assets/templates/views/category/schema.ts +13 -0
  71. package/assets/templates/views/checkout/registry.tsx +3 -5
  72. package/assets/templates/views/home/assembly/assembly.json +12 -3
  73. package/assets/templates/views/home/assembly/index.skeleton.tsx +24 -5
  74. package/assets/templates/views/home/assembly/registry.skeleton.tsx +4 -1
  75. package/assets/templates/views/home/assembly/slots/benefits/cards/binding.json +5 -0
  76. package/assets/templates/views/home/assembly/slots/benefits/cards/registry.part +17 -0
  77. package/assets/templates/views/home/assembly/slots/benefits/split/binding.json +5 -0
  78. package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → split}/registry.part +6 -2
  79. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/binding.json +5 -0
  80. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/catalog.part +8 -0
  81. package/assets/templates/views/home/assembly/slots/categories/{ProductCategory2 → CategoryGrid}/element.part +1 -1
  82. package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/registry.part +31 -0
  83. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/binding.json +5 -0
  84. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/catalog.part +4 -0
  85. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/element.part +5 -0
  86. package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/registry.part +5 -3
  87. package/assets/templates/views/home/content.ts +22 -0
  88. package/assets/templates/views/home/data.ts +9 -0
  89. package/assets/templates/views/home/index.tsx +34 -11
  90. package/assets/templates/views/home/props.ts +1 -0
  91. package/assets/templates/views/home/registry.tsx +41 -17
  92. package/assets/templates/views/home/schema.ts +141 -24
  93. package/assets/templates/views/product/data.ts +5 -3
  94. package/assets/templates/views/product/index.tsx +49 -5
  95. package/assets/templates/views/product/props.ts +7 -0
  96. package/assets/templates/views/product/registry.tsx +34 -5
  97. package/assets/templates/views/product/schema.ts +49 -1
  98. package/assets/templates/views/static/content.ts +4 -4
  99. package/assets/templates/views/static/index.tsx +1 -1
  100. package/bin/storefront.js +1231 -154
  101. package/examples/merchandising/category-led.json +37 -0
  102. package/examples/merchandising/collection-led.json +37 -0
  103. package/package.json +10 -7
  104. package/recipes/archetypes.json +33 -46
  105. package/recipes/catalog.json +245 -153
  106. package/recipes/catalog.mjs +10 -0
  107. package/recipes/catalog.schema.json +4 -0
  108. package/recipes/features.json +28 -5
  109. package/recipes/recipe.schema.json +1 -1
  110. package/recipes/recipes.json +159 -59
  111. package/recipes/sections.json +10 -0
  112. package/recipes/validate.mjs +75 -4
  113. package/scripts/candidate.mjs +4 -4
  114. package/scripts/composers.mjs +25 -5
  115. package/scripts/env-file.mjs +86 -0
  116. package/scripts/file-classes.mjs +15 -0
  117. package/scripts/migrate-english-routes.mjs +276 -0
  118. package/scripts/ownership-conflict.mjs +5 -2
  119. package/scripts/pinning.mjs +74 -5
  120. package/scripts/plan-apply.mjs +149 -5
  121. package/scripts/reconcile.mjs +49 -11
  122. package/scripts/render-templates.mjs +97 -44
  123. package/scripts/section-config.mjs +253 -0
  124. package/scripts/starter.mjs +17 -0
  125. package/scripts/theme/color.mjs +185 -0
  126. package/scripts/theme/css-theme.mjs +233 -0
  127. package/scripts/theme/fonts.mjs +123 -0
  128. package/scripts/theme/import-export.mjs +125 -0
  129. package/scripts/theme/preset.mjs +93 -0
  130. package/scripts/theme/theme-plan.mjs +292 -0
  131. package/scripts/theme/tokens.mjs +137 -0
  132. package/scripts/view-assembly.mjs +57 -3
  133. package/scripts/view-selection.mjs +1 -1
  134. package/skills/sf-feature/SKILL.md +32 -19
  135. package/skills/sf-setup/SKILL.md +79 -0
  136. package/skills/sf-theme-gen/SKILL.md +99 -36
  137. package/skills/sf-theme-gen/references/shadcn-theming.md +87 -0
  138. package/skills/{shadcn-theming/references/templates → sf-theme-gen/references}/theme-setup.md +15 -19
  139. package/skills/{shadcn-theming → sf-theme-gen}/references/theming-guide.md +6 -11
  140. package/skills/sf-view-gen/SKILL.md +63 -40
  141. package/skills/sf-view-gen/assets/recipes/archetypes.json +33 -46
  142. package/skills/sf-view-gen/assets/recipes/catalog.json +245 -153
  143. package/skills/sf-view-gen/assets/recipes/catalog.schema.json +4 -0
  144. package/skills/sf-view-gen/assets/recipes/features.json +28 -5
  145. package/skills/sf-view-gen/assets/recipes/recipes.json +159 -59
  146. package/skills/sf-view-gen/assets/recipes/sections.json +10 -0
  147. package/skills/sf-view-gen/assets/templates/views/sections/cta.client.tsx +1 -1
  148. package/skills/sf-view-gen/assets/templates/views/sections/faq.client.tsx +1 -1
  149. package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.client.tsx +1 -1
  150. package/skills/sf-view-gen/assets/templates/views/sections/pricing.client.tsx +1 -1
  151. package/skills/sf-view-gen/assets/templates/views/sections/products.client.tsx +100 -0
  152. package/skills/sf-view-gen/assets/templates/views/sections/products.tsx +19 -0
  153. package/skills/sf-view-gen/assets/templates/views/sections/schema.products.ts +39 -0
  154. package/skills/sf-view-gen/assets/templates/views/sections/statistics.client.tsx +1 -1
  155. package/skills/sf-view-gen/assets/templates/views/sections/testimonials.client.tsx +1 -1
  156. package/skills/{json-render-core/SKILL.md → sf-view-gen/references/json-render-core.md} +4 -27
  157. package/skills/{json-render-next/SKILL.md → sf-view-gen/references/json-render-next.md} +5 -8
  158. package/skills/{json-render-react/SKILL.md → sf-view-gen/references/json-render-react.md} +3 -5
  159. package/skills/{json-render-shadcn/SKILL.md → sf-view-gen/references/json-render-shadcn.md} +3 -5
  160. package/skills/sf-view-gen/references/views.md +28 -37
  161. package/skills/sf-view-gen/scripts/catalog.mjs +10 -0
  162. package/skills/sf-view-gen/scripts/validate.mjs +75 -4
  163. package/skills/storefront-workflow/SKILL.md +94 -31
  164. package/skills/{storefront-best-practices/reference/design.md → storefront-workflow/references/design-consistency.md} +13 -29
  165. package/CHANGELOG.md +0 -84
  166. package/assets/templates/views/home/assembly/slots/benefits/Feature1/binding.json +0 -5
  167. package/assets/templates/views/home/assembly/slots/benefits/Feature2/binding.json +0 -5
  168. package/assets/templates/views/home/assembly/slots/benefits/Feature2/registry.part +0 -10
  169. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/binding.json +0 -5
  170. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/catalog.part +0 -4
  171. package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/registry.part +0 -16
  172. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/binding.json +0 -5
  173. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/catalog.part +0 -4
  174. package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/element.part +0 -5
  175. package/assets/templates/views/user-panel/index.tsx +0 -106
  176. package/assets/templates/views/user-panel/registry.tsx +0 -54
  177. package/assets/templates/views/user-panel/schema.ts +0 -79
  178. package/commands/sf-add-view.md +0 -57
  179. package/commands/sf-feature.md +0 -28
  180. package/commands/sf-theme.md +0 -26
  181. package/commands/sf-view.md +0 -67
  182. package/skills/building-storefronts/SKILL.md +0 -178
  183. package/skills/building-storefronts/references/frontend-integration.md +0 -229
  184. package/skills/json-render-remotion/SKILL.md +0 -111
  185. package/skills/json-render-solid/SKILL.md +0 -204
  186. package/skills/nextjs-shadcn/SKILL.md +0 -367
  187. package/skills/nextjs-shadcn/references/architecture.md +0 -499
  188. package/skills/nextjs-shadcn/references/project-setup.md +0 -162
  189. package/skills/nextjs-shadcn/references/shadcn-platform.md +0 -261
  190. package/skills/nextjs-shadcn/references/sidebar.md +0 -274
  191. package/skills/nextjs-shadcn/references/styling.md +0 -555
  192. package/skills/shadcn-component-discovery/SKILL.md +0 -273
  193. package/skills/shadcn-component-discovery/references/registries.md +0 -226
  194. package/skills/shadcn-theming/SKILL.md +0 -104
  195. package/skills/storefront-best-practices/SKILL.md +0 -421
  196. package/skills/storefront-best-practices/reference/components/breadcrumbs.md +0 -123
  197. package/skills/storefront-best-practices/reference/components/cart-popup.md +0 -189
  198. package/skills/storefront-best-practices/reference/components/country-selector.md +0 -298
  199. package/skills/storefront-best-practices/reference/components/footer.md +0 -112
  200. package/skills/storefront-best-practices/reference/components/hero.md +0 -241
  201. package/skills/storefront-best-practices/reference/components/megamenu.md +0 -239
  202. package/skills/storefront-best-practices/reference/components/navbar.md +0 -397
  203. package/skills/storefront-best-practices/reference/components/popups.md +0 -221
  204. package/skills/storefront-best-practices/reference/components/product-card.md +0 -125
  205. package/skills/storefront-best-practices/reference/components/product-reviews.md +0 -217
  206. package/skills/storefront-best-practices/reference/components/product-slider.md +0 -174
  207. package/skills/storefront-best-practices/reference/components/search.md +0 -101
  208. package/skills/storefront-best-practices/reference/connecting-to-backend.md +0 -391
  209. package/skills/storefront-best-practices/reference/features/promotions.md +0 -307
  210. package/skills/storefront-best-practices/reference/features/wishlist.md +0 -230
  211. package/skills/storefront-best-practices/reference/layouts/account.md +0 -380
  212. package/skills/storefront-best-practices/reference/layouts/cart.md +0 -316
  213. package/skills/storefront-best-practices/reference/layouts/checkout.md +0 -486
  214. package/skills/storefront-best-practices/reference/layouts/home-page.md +0 -264
  215. package/skills/storefront-best-practices/reference/layouts/order-confirmation.md +0 -231
  216. package/skills/storefront-best-practices/reference/layouts/product-details.md +0 -527
  217. package/skills/storefront-best-practices/reference/layouts/product-listing.md +0 -520
  218. package/skills/storefront-best-practices/reference/layouts/static-pages.md +0 -356
  219. package/skills/storefront-best-practices/reference/medusa.md +0 -307
  220. /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/catalog.part +0 -0
  221. /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/element.part +0 -0
  222. /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/catalog.part +0 -0
  223. /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/element.part +0 -0
  224. /package/skills/{storefront-best-practices/reference → storefront-workflow/references}/mobile-responsiveness.md +0 -0
  225. /package/skills/{storefront-best-practices/reference → storefront-workflow/references}/seo.md +0 -0
@@ -11,22 +11,17 @@
11
11
  // written to the json-render state store, so no password reaches client state,
12
12
  // HTML, or logs. Only the non-secret result (customer/error) is stored.
13
13
 
14
- import { useEffect, useRef } from 'react'
15
- import {
16
- Button,
17
- LoginPage1 as LoginBlock,
18
- OrderHistory2,
19
- SignUpPage1 as SignUpBlock,
20
- } from '@thorprovider/blocks'
14
+ import { useCallback, useEffect, useRef } from 'react'
15
+ import { Button } from '@thorprovider/blocks/ui/button'
16
+ import LoginBlock from '@thorprovider/blocks/blocks/application/login-forms/login-page-1'
17
+ import OrderHistory2 from '@thorprovider/blocks/blocks/e-commerce/order-history/order-history-2'
18
+ import SignUpBlock from '@thorprovider/blocks/blocks/application/signup-forms/signup-page-1'
21
19
  import { useStateStore } from '@json-render/react'
22
20
  import type { Customer } from '@thorprovider/types'
23
- import {
24
- loadAccountAction,
25
- loadOrdersAction,
26
- loginAction,
27
- logoutAction,
28
- registerAction,
29
- } from '../../actions'
21
+ import { loadOrdersPageAction } from '../../actions'
22
+ import { ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE, accountIdentityKey } from '../../account-private.core'
23
+ import { AccountBoundary } from '../../account-boundary.client'
24
+ import { useAccountLifecycle } from '../../account-lifecycle.client'
30
25
  import type { AccountOrderView } from '../../state.core'
31
26
  import type { ViewRegistry } from '../types'
32
27
  import {
@@ -35,36 +30,8 @@ import {
35
30
  accountRegisterPropsSchema,
36
31
  } from './schema'
37
32
 
38
- // The structured result the auth Server Actions return (see ../../actions).
39
- type AuthResult = { ok: true; customer: Customer | null } | { ok: false; error: string }
40
- type SetState = (path: string, value: unknown) => void
41
-
42
- // Apply a settled auth result truthfully: a failure sets an error and NEVER a
43
- // logged-in state; a success stores the customer (or null) and nothing else.
44
- function applyAuthResult(set: SetState, result: AuthResult): void {
45
- set('/accountPending', false)
46
- if (result.ok) {
47
- set('/accountCustomer', result.customer)
48
- set('/accountAuthenticated', result.customer !== null)
49
- set('/accountError', null)
50
- set('/accountMode', 'login')
51
- return
52
- }
53
- set('/accountError', result.error)
54
- }
55
-
56
- // A rejected Server Action (network/RPC) must clear pending and surface a
57
- // message; never swallow it. Only a non-secret context line is logged.
58
- function authFailure(set: SetState, scope: string) {
59
- return (error: unknown) => {
60
- console.error(
61
- `[storefront/account] ${scope} failed`,
62
- error instanceof Error ? error.message : error,
63
- )
64
- set('/accountPending', false)
65
- set('/accountError', 'No se pudo completar la operación. Inténtalo de nuevo.')
66
- }
67
- }
33
+ /** Bounded page size for the account order-history window. */
34
+ const ORDERS_PAGE_SIZE = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE
68
35
 
69
36
  // Non-secret status surface for the block pages, which expose no error/pending
70
37
  // prop of their own. Renders nothing when there is no pending work or error.
@@ -81,6 +48,24 @@ function AuthNotice({ pending, error }: { pending: boolean; error: string | null
81
48
  )
82
49
  }
83
50
 
51
+ // Neutral pending surface shown while a cross-tab/foreground reconciliation is
52
+ // in flight (task 4.2). It replaces the previously held identity/orders so no
53
+ // stale private data is presented as current during the server round-trip; it
54
+ // is NOT a signed-out or unavailable state, and the held data is never
55
+ // destroyed (a same-identity re-resolution re-presents it without a refetch).
56
+ function ReconcilingStatus() {
57
+ return (
58
+ <p
59
+ role="status"
60
+ aria-live="polite"
61
+ data-account-reconciling="1"
62
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
63
+ >
64
+ Actualizando tu cuenta…
65
+ </p>
66
+ )
67
+ }
68
+
84
69
  // The OrderHistory2 block's order shape (see @thorprovider/blocks). Kept local
85
70
  // so the registry maps the account order rows to the block contract without a
86
71
  // shared dependency on block internals.
@@ -100,9 +85,11 @@ interface BlockOrder {
100
85
  items: BlockOrderItem[]
101
86
  }
102
87
 
103
- // Map a backend-sourced account order row to the block's order shape. The order
104
- // number is the list key; an absent variant/image becomes '' because the block
105
- // contract is a string — never an invented value.
88
+ // Map a backend-sourced account order row to the block's order shape. The block
89
+ // has a single `id` slot which it also renders ("Pedido {id}"), so it carries the
90
+ // display number; the registry keeps a number→backend-id map so selection is
91
+ // keyed by the REAL backend order id. An absent variant/image becomes '' because
92
+ // the block contract is a string — never an invented value.
106
93
  function toBlockOrder(order: AccountOrderView): BlockOrder {
107
94
  return {
108
95
  id: order.number,
@@ -121,8 +108,10 @@ function toBlockOrder(order: AccountOrderView): BlockOrder {
121
108
  }
122
109
 
123
110
  // Inline order detail assembled from the already-fetched list row (no second
124
- // backend request). Only fields the backend supplied are shown.
125
- function OrderDetail({ order }: { order: AccountOrderView }) {
111
+ // backend request). Only fields the backend supplied are shown. `onClose` clears
112
+ // the selection so the detail is dismissible (a real open/close cycle, no
113
+ // navigation and no second destination).
114
+ function OrderDetail({ order, onClose }: { order: AccountOrderView; onClose: () => void }) {
126
115
  const totals = (
127
116
  [
128
117
  { label: 'Subtotal', value: order.subtotal },
@@ -134,10 +123,17 @@ function OrderDetail({ order }: { order: AccountOrderView }) {
134
123
  return (
135
124
  <div className="mx-auto w-full max-w-7xl px-4 pb-12 sm:px-6 lg:px-8">
136
125
  <div className="rounded-lg border p-6">
137
- <h3 className="text-lg font-semibold">Pedido {order.number}</h3>
138
- <p className="text-muted-foreground mt-1 text-sm">
139
- {order.date} · {order.status}
140
- </p>
126
+ <div className="flex items-start justify-between gap-4">
127
+ <div>
128
+ <h3 className="text-lg font-semibold">Pedido {order.number}</h3>
129
+ <p className="text-muted-foreground mt-1 text-sm">
130
+ {order.date} · {order.status}
131
+ </p>
132
+ </div>
133
+ <Button type="button" variant="outline" size="sm" onClick={onClose}>
134
+ Cerrar
135
+ </Button>
136
+ </div>
141
137
  {order.address ? (
142
138
  <p className="text-muted-foreground mt-2 text-sm">{order.address}</p>
143
139
  ) : null}
@@ -170,107 +166,93 @@ function OrderDetail({ order }: { order: AccountOrderView }) {
170
166
 
171
167
  export const registry: ViewRegistry = {
172
168
  /**
173
- * Headless bootstrap rendered on the account route. It resolves the current
174
- * customer from the cookie-authorized Server Action once, so a reload keeps
175
- * the signed-in state without re-entering credentials. It never reads a token.
169
+ * Passive account boundary. It renders only the retryable "unavailable"
170
+ * status (via the shared lifecycle's `retryAccountSession` action) and NEVER
171
+ * fetches or owns identity on mount: the shared lifecycle/SSR seed already
172
+ * supplies the account state on every route, so `/account` introduces no
173
+ * competing identity bootstrap or mount race.
176
174
  */
177
- AccountBoot: () => {
178
- const { set } = useStateStore()
179
- const booted = useRef(false)
180
- useEffect(() => {
181
- if (booted.current) return
182
- booted.current = true
183
- void loadAccountAction()
184
- .then((result) => {
185
- if (!result.ok) {
186
- set('/accountCustomer', null)
187
- set('/accountAuthenticated', false)
188
- set('/accountError', result.error)
189
- return
190
- }
191
- set('/accountCustomer', result.customer)
192
- set('/accountAuthenticated', result.customer !== null)
193
- set('/accountError', null)
194
- })
195
- .catch((error) => {
196
- console.error(
197
- '[storefront/account] loadAccount failed',
198
- error instanceof Error ? error.message : error,
199
- )
200
- set('/accountCustomer', null)
201
- set('/accountAuthenticated', false)
202
- set('/accountError', 'No se pudo cargar la cuenta. Inténtalo de nuevo.')
203
- })
204
- }, [])
205
- return null
206
- },
175
+ AccountBoot: ({ emit }) => <AccountBoundary emit={emit} />,
207
176
  AccountLogin: ({ props, emit }) => {
208
- const { state, set } = useStateStore()
177
+ const { state } = useStateStore()
178
+ const lifecycle = useAccountLifecycle()
209
179
  const parsed = accountLoginPropsSchema.parse(props)
210
180
  const error = typeof state.accountError === 'string' ? state.accountError : null
211
181
  const pending = Boolean(state.accountPending)
212
182
  return (
213
183
  <>
214
184
  <AuthNotice pending={pending} error={error} />
215
- <LoginBlock
216
- logoText={parsed.logoText}
217
- welcomeTitleLabel={parsed.welcomeTitleLabel}
218
- welcomeDescriptionLabel={parsed.welcomeDescriptionLabel}
219
- emailLabel={parsed.emailLabel}
220
- passwordLabel={parsed.passwordLabel}
221
- signInLabel={parsed.signInLabel}
222
- createAccountLabel={parsed.createAccountLabel}
223
- // The credentials stay in the block's local state and go straight to
224
- // the Server Action; they are never written to the store.
225
- onSubmit={(data) => {
226
- set('/accountPending', true)
227
- set('/accountError', null)
228
- void loginAction({ email: data.email, password: data.password })
229
- .then((result) => applyAuthResult(set, result))
230
- .catch(authFailure(set, 'login'))
231
- }}
232
- onCreateAccount={() => emit('showRegister')}
233
- />
185
+ {/* The block exposes no pending/disabled prop, so the registry disables
186
+ the whole form natively while a mutation is pending: a disabled
187
+ fieldset freezes the submit control and the inputs without clearing
188
+ them, and `display: contents` leaves the layout untouched. The
189
+ shared lifecycle also drops a same-tick duplicate before React
190
+ re-renders, so no duplicate request is issued in the interim. */}
191
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
192
+ <LoginBlock
193
+ logoText={parsed.logoText}
194
+ welcomeTitleLabel={parsed.welcomeTitleLabel}
195
+ welcomeDescriptionLabel={parsed.welcomeDescriptionLabel}
196
+ emailLabel={parsed.emailLabel}
197
+ passwordLabel={parsed.passwordLabel}
198
+ signInLabel={parsed.signInLabel}
199
+ createAccountLabel={parsed.createAccountLabel}
200
+ // The credentials stay in the block's local state and go straight to
201
+ // the shared lifecycle (which calls the Server Action); they are never
202
+ // written to the store. The lifecycle owns pending/error, the
203
+ // generation guard, duplicate prevention, and the server refresh, so
204
+ // the mounted form is never remounted and its input survives a failure.
205
+ onSubmit={(data) => {
206
+ void lifecycle.login({ email: data.email, password: data.password })
207
+ }}
208
+ onCreateAccount={() => emit('showRegister')}
209
+ />
210
+ </fieldset>
234
211
  </>
235
212
  )
236
213
  },
237
214
  AccountRegister: ({ props, emit }) => {
238
- const { state, set } = useStateStore()
215
+ const { state } = useStateStore()
216
+ const lifecycle = useAccountLifecycle()
239
217
  const parsed = accountRegisterPropsSchema.parse(props)
240
218
  const error = typeof state.accountError === 'string' ? state.accountError : null
241
219
  const pending = Boolean(state.accountPending)
242
220
  return (
243
221
  <>
244
222
  <AuthNotice pending={pending} error={error} />
245
- <SignUpBlock
246
- logoText={parsed.logoText}
247
- createAccountTitleLabel={parsed.createAccountTitleLabel}
248
- createAccountDescriptionLabel={parsed.createAccountDescriptionLabel}
249
- fullNameLabel={parsed.fullNameLabel}
250
- emailLabel={parsed.emailLabel}
251
- passwordLabel={parsed.passwordLabel}
252
- createAccountLabel={parsed.createAccountLabel}
253
- signInLabel={parsed.signInLabel}
254
- onSubmit={(data) => {
255
- const parts = data.fullName.trim().split(/\s+/).filter(Boolean)
256
- set('/accountPending', true)
257
- set('/accountError', null)
258
- void registerAction({
259
- email: data.email,
260
- password: data.password,
261
- first_name: parts[0] ?? '',
262
- last_name: parts.slice(1).join(' '),
263
- })
264
- .then((result) => applyAuthResult(set, result))
265
- .catch(authFailure(set, 'register'))
266
- }}
267
- onSignIn={() => emit('showLogin')}
268
- />
223
+ {/* Same native pending-disable as the login form (the block exposes no
224
+ pending prop); input values persist across a failed mutation. */}
225
+ <fieldset disabled={pending} aria-busy={pending} className="contents">
226
+ <SignUpBlock
227
+ logoText={parsed.logoText}
228
+ createAccountTitleLabel={parsed.createAccountTitleLabel}
229
+ createAccountDescriptionLabel={parsed.createAccountDescriptionLabel}
230
+ fullNameLabel={parsed.fullNameLabel}
231
+ emailLabel={parsed.emailLabel}
232
+ passwordLabel={parsed.passwordLabel}
233
+ createAccountLabel={parsed.createAccountLabel}
234
+ signInLabel={parsed.signInLabel}
235
+ onSubmit={(data) => {
236
+ const parts = data.fullName.trim().split(/\s+/).filter(Boolean)
237
+ void lifecycle.register({
238
+ email: data.email,
239
+ password: data.password,
240
+ firstName: parts[0] ?? '',
241
+ lastName: parts.slice(1).join(' '),
242
+ })
243
+ }}
244
+ onSignIn={() => emit('showLogin')}
245
+ />
246
+ </fieldset>
269
247
  </>
270
248
  )
271
249
  },
272
250
  AccountPanel: ({ emit }) => {
273
251
  const { state } = useStateStore()
252
+ const { reconciling } = useAccountLifecycle()
253
+ // A reconciliation in flight hides the held identity rather than presenting
254
+ // it as current (task 4.2); the panel stays mounted so nothing is destroyed.
255
+ if (reconciling) return <ReconcilingStatus />
274
256
  const customer = (state.accountCustomer ?? null) as Customer | null
275
257
  const error = typeof state.accountError === 'string' ? state.accountError : null
276
258
  const pending = Boolean(state.accountPending)
@@ -295,32 +277,97 @@ export const registry: ViewRegistry = {
295
277
  )
296
278
  },
297
279
  /**
298
- * Signed-in order history. The load runs once from the cookie-authorized
299
- * Server Action; loading/empty/error are distinct and a failure never renders
300
- * a fabricated order. `onViewDetails` records the selected order in state and
301
- * the detail is assembled below from the already-fetched row — no second
302
- * backend request. No token is read, stored, or rendered here.
280
+ * Signed-in order history, scoped to the CURRENT shopper identity. The first
281
+ * page loads from the cookie-authorized Server Action; later pages load on
282
+ * demand, each scoped to the authenticated customer's channel. Loading is keyed
283
+ * by the shared lifecycle's `identityKey` (customer id, or `anonymous`) plus a
284
+ * per-component generation:
285
+ *
286
+ * - the first-page effect reloads on an identity CHANGE (a boolean flag
287
+ * cannot detect a customer switch) and lazy-loads only on `/account`;
288
+ * - every `loadPage` captures the live key/generation at request time and
289
+ * discards its result if either changed, so a previous customer's rows,
290
+ * count, page, selection, or detail never reappear;
291
+ * - the private STORE slice is cleared by the shared lifecycle write path
292
+ * (`claimAccount`) AT the trigger, not by this view, so it is cleared even
293
+ * when the panel unmounts (logout/expiry/unavailable); this view only
294
+ * HIDES rows whose key is not the current identity until the new
295
+ * identity's page lands (a render guard, never the clear mechanism).
296
+ *
297
+ * The backend's real `count` drives pagination, so a page length is never
298
+ * presented as the total. Selection is keyed by the REAL backend order id (via
299
+ * a number→id map) and the detail is assembled from the fetched row; the
300
+ * selection id survives paging (returning to the order's page reopens it) and
301
+ * is dismissible with the inline close control. A failed page load shows an
302
+ * actionable retry that re-runs the SAME page (never a fabricated empty
303
+ * history). No token is read, stored, or rendered here.
303
304
  */
304
305
  AccountOrders: ({ props }) => {
305
- const { state, set } = useStateStore()
306
+ const { state, set, getSnapshot } = useStateStore()
306
307
  const parsed = accountOrdersPropsSchema.parse(props)
307
- const loaded = useRef(false)
308
- useEffect(() => {
309
- if (loaded.current) return
310
- loaded.current = true
308
+ const { identityKey, reconciling } = useAccountLifecycle()
309
+
310
+ // Bumped on every identity change so a response from a previous identity — or
311
+ // a previous visit to the same identity — is discarded even if the key later
312
+ // returns.
313
+ const generationRef = useRef(0)
314
+ // The identity key the currently DISPLAYED rows belong to; null until a load
315
+ // for the current identity succeeds. A render whose key differs hides the
316
+ // rows immediately, so a previous customer's orders never paint after the
317
+ // identity changes, before the shared clear even runs.
318
+ const loadedKeyRef = useRef<string | null>(null)
319
+ // The page of the MOST RECENT request (not the last successful one), so the
320
+ // error-state retry re-runs the exact page the shopper asked for — including
321
+ // a failed next/prev page. Local to the panel: an identity change unmounts it
322
+ // (the `/accountAuthenticated` gate), so it never leaks across shoppers.
323
+ const requestedPageRef = useRef(1)
324
+
325
+ // Read the LIVE identity key from the store so an async response can discard
326
+ // itself even if this component has since re-rendered or unmounted: the store
327
+ // outlives the component, unlike a render closure.
328
+ const currentIdentityKey = useCallback(
329
+ () =>
330
+ accountIdentityKey(
331
+ (getSnapshot().accountCustomer ?? null) as { id?: string | null } | null,
332
+ ),
333
+ [getSnapshot],
334
+ )
335
+
336
+ const loadPage = (page: number) => {
337
+ // Capture the identity key + generation BEFORE the request; the response is
338
+ // discarded if either changed while it was in flight.
339
+ const capturedKey = currentIdentityKey()
340
+ const capturedGeneration = generationRef.current
341
+ requestedPageRef.current = page
311
342
  set('/accountOrdersPending', true)
312
343
  set('/accountOrdersError', null)
313
- void loadOrdersAction()
344
+ void loadOrdersPageAction({ page, pageSize: ORDERS_PAGE_SIZE })
314
345
  .then((result) => {
346
+ if (
347
+ currentIdentityKey() !== capturedKey ||
348
+ generationRef.current !== capturedGeneration
349
+ ) {
350
+ return
351
+ }
315
352
  set('/accountOrdersPending', false)
316
353
  if (result.ok) {
317
354
  set('/accountOrders', result.orders)
355
+ set('/accountOrdersCount', result.count)
356
+ set('/accountOrdersPage', page)
357
+ set('/accountOrdersPageSize', result.limit)
318
358
  set('/accountOrdersError', null)
359
+ loadedKeyRef.current = capturedKey
319
360
  return
320
361
  }
321
362
  set('/accountOrdersError', result.error)
322
363
  })
323
364
  .catch((error) => {
365
+ if (
366
+ currentIdentityKey() !== capturedKey ||
367
+ generationRef.current !== capturedGeneration
368
+ ) {
369
+ return
370
+ }
324
371
  console.error(
325
372
  '[storefront/account] loadOrders failed',
326
373
  error instanceof Error ? error.message : error,
@@ -328,50 +375,143 @@ export const registry: ViewRegistry = {
328
375
  set('/accountOrdersPending', false)
329
376
  set('/accountOrdersError', parsed.errorLabel ?? 'No se pudieron cargar tus pedidos.')
330
377
  })
378
+ }
379
+
380
+ useEffect(() => {
381
+ // On a real identity CHANGE, bump the generation (discarding the previous
382
+ // identity's in-flight page) and forget the displayed key, then load page
383
+ // 1 for the new identity. The private STORE slice is cleared by the shared
384
+ // lifecycle write path (`claimAccount`) at the trigger — NOT here — so the
385
+ // reset already happened even when this panel was unmounted (logout /
386
+ // expiry / unavailable). This effect only drives the fetch; a
387
+ // same-identity re-resolution leaves `identityKey` unchanged, so it does
388
+ // not re-run and the rows/selection survive. A guest/unavailable identity
389
+ // never fetches.
390
+ if (loadedKeyRef.current !== identityKey) {
391
+ generationRef.current += 1
392
+ loadedKeyRef.current = null
393
+ }
394
+ if (identityKey === 'anonymous') return
395
+ if (loadedKeyRef.current === identityKey) return
396
+ loadPage(1)
331
397
  // eslint-disable-next-line react-hooks/exhaustive-deps
332
- }, [])
398
+ }, [identityKey])
333
399
 
334
400
  const pending = Boolean(state.accountOrdersPending)
335
401
  const error = typeof state.accountOrdersError === 'string' ? state.accountOrdersError : null
336
- const orders = Array.isArray(state.accountOrders)
402
+ const allOrders = Array.isArray(state.accountOrders)
337
403
  ? (state.accountOrders as AccountOrderView[])
338
404
  : []
405
+ // Only rows loaded FOR the current identity may display: a stale row set from
406
+ // a previous customer is hidden until the new identity's page lands.
407
+ const orders = loadedKeyRef.current === identityKey ? allOrders : []
408
+ const count =
409
+ typeof state.accountOrdersCount === 'number' ? state.accountOrdersCount : orders.length
410
+ const page = typeof state.accountOrdersPage === 'number' ? state.accountOrdersPage : 1
411
+ const pageSize =
412
+ typeof state.accountOrdersPageSize === 'number' && state.accountOrdersPageSize > 0
413
+ ? state.accountOrdersPageSize
414
+ : ORDERS_PAGE_SIZE
339
415
  const selectedId =
340
416
  typeof state.accountSelectedOrderId === 'string' ? state.accountSelectedOrderId : null
341
- const selected = selectedId
342
- ? orders.find((order) => order.number === selectedId) ?? null
343
- : null
417
+ // Selection is keyed by the REAL backend order id, never the display number.
418
+ const selected = selectedId ? orders.find((order) => order.id === selectedId) ?? null : null
419
+ // The block row carries the display number; resolve it back to the backend id.
420
+ const backendIdByBlockId = new Map(orders.map((order) => [order.number, order.id]))
344
421
 
422
+ // A reconciliation in flight (task 4.2) hides the held rows rather than
423
+ // presenting them as current. This component stays MOUNTED (its `loadedKeyRef`
424
+ // and generation survive), so a same-identity re-resolution re-presents the
425
+ // held rows after settle WITHOUT a refetch; an identity change still clears
426
+ // through the claim write path.
427
+ if (reconciling) {
428
+ return <ReconcilingStatus />
429
+ }
345
430
  if (pending) {
346
431
  return (
347
- <p className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm">
432
+ <p
433
+ role="status"
434
+ aria-live="polite"
435
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
436
+ >
348
437
  {parsed.loadingLabel ?? 'Cargando pedidos…'}
349
438
  </p>
350
439
  )
351
440
  }
352
441
  if (error) {
442
+ // A failed load is NOT an empty history: the error is announced and the
443
+ // shopper gets an actionable retry that re-runs the page that failed (a
444
+ // button, never inert text). No token, no direct HTTP — the retry calls the
445
+ // same cookie-authorized Server Action as the initial load.
353
446
  return (
354
- <p role="alert" className="text-destructive mx-auto max-w-7xl px-4 py-8 text-sm">
355
- {error}
356
- </p>
447
+ <div className="mx-auto flex w-full max-w-7xl flex-col items-start gap-3 px-4 py-8 sm:px-6 lg:px-8">
448
+ <p role="alert" className="text-destructive text-sm">
449
+ {error}
450
+ </p>
451
+ <Button
452
+ type="button"
453
+ variant="outline"
454
+ size="sm"
455
+ disabled={pending}
456
+ onClick={() => loadPage(requestedPageRef.current)}
457
+ >
458
+ Reintentar
459
+ </Button>
460
+ </div>
357
461
  )
358
462
  }
359
463
  if (orders.length === 0) {
360
464
  return (
361
- <p className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm">
465
+ <p
466
+ role="status"
467
+ className="text-muted-foreground mx-auto max-w-7xl px-4 py-8 text-sm"
468
+ >
362
469
  {parsed.emptyLabel ?? 'Aún no tienes pedidos.'}
363
470
  </p>
364
471
  )
365
472
  }
473
+ const totalPages = Math.max(1, Math.ceil(count / pageSize))
366
474
  return (
367
475
  <>
368
476
  <OrderHistory2
369
477
  orders={orders.map(toBlockOrder)}
370
478
  titleLabel={parsed.titleLabel}
371
479
  descriptionLabel={parsed.descriptionLabel}
372
- onViewDetails={(order) => set('/accountSelectedOrderId', order.id)}
480
+ // The block renders "Total de pedidos: {n}" from the PAGE length; pass a
481
+ // label without `{n}` so a page length is never shown as the total.
482
+ totalOrdersLabel={parsed.totalOrdersLabel ?? 'Pedidos'}
483
+ onViewDetails={(order) =>
484
+ set('/accountSelectedOrderId', backendIdByBlockId.get(order.id) ?? null)
485
+ }
373
486
  />
374
- {selected ? <OrderDetail order={selected} /> : null}
487
+ {count > pageSize ? (
488
+ <div className="mx-auto flex w-full max-w-7xl items-center justify-between gap-4 px-4 pb-6 sm:px-6 lg:px-8">
489
+ <p className="text-muted-foreground text-sm" role="status" aria-live="polite">
490
+ {`${count} pedidos · página ${page} de ${totalPages}`}
491
+ </p>
492
+ <div className="flex gap-2">
493
+ <Button
494
+ variant="outline"
495
+ size="sm"
496
+ disabled={pending || page <= 1}
497
+ onClick={() => loadPage(page - 1)}
498
+ >
499
+ Anterior
500
+ </Button>
501
+ <Button
502
+ variant="outline"
503
+ size="sm"
504
+ disabled={pending || page >= totalPages}
505
+ onClick={() => loadPage(page + 1)}
506
+ >
507
+ Siguiente
508
+ </Button>
509
+ </div>
510
+ </div>
511
+ ) : null}
512
+ {selected ? (
513
+ <OrderDetail order={selected} onClose={() => set('/accountSelectedOrderId', null)} />
514
+ ) : null}
375
515
  </>
376
516
  )
377
517
  },
@@ -38,6 +38,7 @@ export const accountRegisterPropsSchema = z.object({
38
38
  export const accountOrdersPropsSchema = z.object({
39
39
  titleLabel: z.string().optional(),
40
40
  descriptionLabel: z.string().optional(),
41
+ totalOrdersLabel: z.string().optional(),
41
42
  emptyLabel: z.string().optional(),
42
43
  errorLabel: z.string().optional(),
43
44
  loadingLabel: z.string().optional(),
@@ -0,0 +1,11 @@
1
+ // Thor Commerce view content: cart (user-owned)
2
+ // Merchant-editable copy for the standalone cart review page. Seeded once by the
3
+ // scaffolder and never overwritten on sync.
4
+
5
+ export const cartContent = {
6
+ titleLabel: 'Tu carrito',
7
+ checkoutLabel: 'Finalizar compra',
8
+ continueShoppingLabel: 'Seguir comprando',
9
+ emptyLabel: 'Tu carrito está vacío',
10
+ readErrorLabel: 'No se pudo cargar tu carrito.',
11
+ }
@@ -0,0 +1,23 @@
1
+ // Thor Commerce view data: cart (user-owned)
2
+ // Pure mapping from the shared host cart state to the ShoppingCart block props.
3
+ // No React and no server imports so it can be imported from either boundary.
4
+
5
+ import type { ShoppingCartItem } from '@thorprovider/blocks'
6
+ import type { CartLineState } from '../../state'
7
+
8
+ /**
9
+ * Maps backend cart lines to the cart block's item shape. The block renders the
10
+ * canonical `lineTotal` Money verbatim, so only canonical Money fields are
11
+ * supplied — no legacy numeric `price` placeholder. An absent image is left
12
+ * undefined rather than serialized as "".
13
+ */
14
+ export const toCartViewItems = (cart: CartLineState[]): ShoppingCartItem[] =>
15
+ cart.map(line => ({
16
+ id: line.id,
17
+ name: line.name,
18
+ quantity: line.quantity,
19
+ image: line.image,
20
+ variant: line.variant,
21
+ lineTotal: line.lineTotal,
22
+ unitPrice: line.unitPrice,
23
+ }))