@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.
- package/README.md +174 -156
- package/VENDOR.md +69 -0
- package/assets/openspec/config.yaml +38 -0
- package/assets/templates/AGENTS.md +76 -0
- package/assets/templates/app/app/[[...slug]]/page.tsx +56 -2
- package/assets/templates/app/app/[[...slug]]/renderer.tsx +44 -2
- package/assets/templates/app/app/globals.css +5 -8
- package/assets/templates/app/app/layout.tsx +1 -5
- package/assets/templates/app/app/robots.ts +9 -3
- package/assets/templates/app/app/sitemap.ts +64 -5
- package/assets/templates/app/lib/__STOREFRONT__/account-boundary.client.tsx +76 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx +461 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-mutation.client.ts +46 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-private.core.ts +103 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-reconcile.client.ts +465 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-session.core.ts +177 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-session.ts +44 -0
- package/assets/templates/app/lib/__STOREFRONT__/account-user.core.ts +65 -0
- package/assets/templates/app/lib/__STOREFRONT__/actions.ts +135 -16
- package/assets/templates/app/lib/__STOREFRONT__/catalog.ts +19 -9
- package/assets/templates/app/lib/__STOREFRONT__/commerce.ts +61 -0
- package/assets/templates/app/lib/__STOREFRONT__/composition.ts +26 -0
- package/assets/templates/app/lib/__STOREFRONT__/handlers.core.ts +36 -4
- package/assets/templates/app/lib/__STOREFRONT__/mappers.ts +17 -18
- package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.client.tsx +209 -0
- package/assets/templates/app/lib/__STOREFRONT__/projection-ownership.ts +247 -0
- package/assets/templates/app/lib/__STOREFRONT__/registry.tsx +123 -62
- package/assets/templates/app/lib/__STOREFRONT__/runtime.ts +3 -0
- package/assets/templates/app/lib/__STOREFRONT__/schema.ts +78 -25
- package/assets/templates/app/lib/__STOREFRONT__/section-observation.ts +182 -0
- package/assets/templates/app/lib/__STOREFRONT__/section-sources.ts +128 -0
- package/assets/templates/app/lib/__STOREFRONT__/shell/content.ts +31 -7
- package/assets/templates/app/lib/__STOREFRONT__/shell/props.ts +4 -0
- package/assets/templates/app/lib/__STOREFRONT__/spec/index.ts +81 -26
- package/assets/templates/app/lib/__STOREFRONT__/spec/seo.ts +165 -0
- package/assets/templates/app/lib/__STOREFRONT__/state.core.ts +4 -2
- package/assets/templates/app/lib/__STOREFRONT__/store-context.ts +26 -7
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/cta.client.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/faq.client.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/index.ts +2 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/logoCloud.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/pricing.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.client.tsx +100 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/products.tsx +19 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/schema.products.ts +39 -0
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/statistics.tsx +1 -1
- package/assets/templates/app/lib/__STOREFRONT__/views/sections/testimonials.tsx +1 -1
- package/assets/templates/features/checkout/handlers.ts +6 -0
- package/assets/templates/features/customer-auth/handlers.ts +19 -23
- package/assets/templates/features/customer-auth/state.ts +31 -1
- package/assets/templates/views/account/index.tsx +20 -8
- package/assets/templates/views/account/registry.tsx +294 -154
- package/assets/templates/views/account/schema.ts +1 -0
- package/assets/templates/views/cart/content.ts +11 -0
- package/assets/templates/views/cart/data.ts +23 -0
- package/assets/templates/views/cart/index.tsx +53 -0
- package/assets/templates/views/cart/props.ts +12 -0
- package/assets/templates/views/cart/registry.tsx +82 -0
- package/assets/templates/views/cart/schema.ts +52 -0
- package/assets/templates/views/category/assembly/assembly.json +2 -1
- package/assets/templates/views/category/assembly/index.skeleton.tsx +64 -6
- package/assets/templates/views/category/assembly/registry.skeleton.tsx +7 -6
- package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/binding.json +5 -0
- package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/catalog.part +4 -0
- package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/element.part +7 -0
- package/assets/templates/views/category/assembly/slots/breadcrumb/Breadcrumb/registry.part +18 -0
- package/assets/templates/views/category/index.tsx +76 -7
- package/assets/templates/views/category/props.ts +7 -0
- package/assets/templates/views/category/registry.tsx +25 -6
- package/assets/templates/views/category/schema.ts +13 -0
- package/assets/templates/views/checkout/registry.tsx +3 -5
- package/assets/templates/views/home/assembly/assembly.json +12 -3
- package/assets/templates/views/home/assembly/index.skeleton.tsx +24 -5
- package/assets/templates/views/home/assembly/registry.skeleton.tsx +4 -1
- package/assets/templates/views/home/assembly/slots/benefits/cards/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/benefits/cards/registry.part +17 -0
- package/assets/templates/views/home/assembly/slots/benefits/split/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → split}/registry.part +6 -2
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/catalog.part +8 -0
- package/assets/templates/views/home/assembly/slots/categories/{ProductCategory2 → CategoryGrid}/element.part +1 -1
- package/assets/templates/views/home/assembly/slots/categories/CategoryGrid/registry.part +31 -0
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/binding.json +5 -0
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/catalog.part +4 -0
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero/element.part +5 -0
- package/assets/templates/views/home/assembly/slots/hero/{StorefrontHero1 → StorefrontHero}/registry.part +5 -3
- package/assets/templates/views/home/content.ts +22 -0
- package/assets/templates/views/home/data.ts +9 -0
- package/assets/templates/views/home/index.tsx +34 -11
- package/assets/templates/views/home/props.ts +1 -0
- package/assets/templates/views/home/registry.tsx +41 -17
- package/assets/templates/views/home/schema.ts +141 -24
- package/assets/templates/views/product/data.ts +5 -3
- package/assets/templates/views/product/index.tsx +49 -5
- package/assets/templates/views/product/props.ts +7 -0
- package/assets/templates/views/product/registry.tsx +34 -5
- package/assets/templates/views/product/schema.ts +49 -1
- package/assets/templates/views/static/content.ts +4 -4
- package/assets/templates/views/static/index.tsx +1 -1
- package/bin/storefront.js +1231 -154
- package/examples/merchandising/category-led.json +37 -0
- package/examples/merchandising/collection-led.json +37 -0
- package/package.json +10 -7
- package/recipes/archetypes.json +33 -46
- package/recipes/catalog.json +245 -153
- package/recipes/catalog.mjs +10 -0
- package/recipes/catalog.schema.json +4 -0
- package/recipes/features.json +28 -5
- package/recipes/recipe.schema.json +1 -1
- package/recipes/recipes.json +159 -59
- package/recipes/sections.json +10 -0
- package/recipes/validate.mjs +75 -4
- package/scripts/candidate.mjs +4 -4
- package/scripts/composers.mjs +25 -5
- package/scripts/env-file.mjs +86 -0
- package/scripts/file-classes.mjs +15 -0
- package/scripts/migrate-english-routes.mjs +276 -0
- package/scripts/ownership-conflict.mjs +5 -2
- package/scripts/pinning.mjs +74 -5
- package/scripts/plan-apply.mjs +149 -5
- package/scripts/reconcile.mjs +49 -11
- package/scripts/render-templates.mjs +97 -44
- package/scripts/section-config.mjs +253 -0
- package/scripts/starter.mjs +17 -0
- package/scripts/theme/color.mjs +185 -0
- package/scripts/theme/css-theme.mjs +233 -0
- package/scripts/theme/fonts.mjs +123 -0
- package/scripts/theme/import-export.mjs +125 -0
- package/scripts/theme/preset.mjs +93 -0
- package/scripts/theme/theme-plan.mjs +292 -0
- package/scripts/theme/tokens.mjs +137 -0
- package/scripts/view-assembly.mjs +57 -3
- package/scripts/view-selection.mjs +1 -1
- package/skills/sf-feature/SKILL.md +32 -19
- package/skills/sf-setup/SKILL.md +79 -0
- package/skills/sf-theme-gen/SKILL.md +99 -36
- package/skills/sf-theme-gen/references/shadcn-theming.md +87 -0
- package/skills/{shadcn-theming/references/templates → sf-theme-gen/references}/theme-setup.md +15 -19
- package/skills/{shadcn-theming → sf-theme-gen}/references/theming-guide.md +6 -11
- package/skills/sf-view-gen/SKILL.md +63 -40
- package/skills/sf-view-gen/assets/recipes/archetypes.json +33 -46
- package/skills/sf-view-gen/assets/recipes/catalog.json +245 -153
- package/skills/sf-view-gen/assets/recipes/catalog.schema.json +4 -0
- package/skills/sf-view-gen/assets/recipes/features.json +28 -5
- package/skills/sf-view-gen/assets/recipes/recipes.json +159 -59
- package/skills/sf-view-gen/assets/recipes/sections.json +10 -0
- package/skills/sf-view-gen/assets/templates/views/sections/cta.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/faq.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/logoCloud.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/pricing.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/products.client.tsx +100 -0
- package/skills/sf-view-gen/assets/templates/views/sections/products.tsx +19 -0
- package/skills/sf-view-gen/assets/templates/views/sections/schema.products.ts +39 -0
- package/skills/sf-view-gen/assets/templates/views/sections/statistics.client.tsx +1 -1
- package/skills/sf-view-gen/assets/templates/views/sections/testimonials.client.tsx +1 -1
- package/skills/{json-render-core/SKILL.md → sf-view-gen/references/json-render-core.md} +4 -27
- package/skills/{json-render-next/SKILL.md → sf-view-gen/references/json-render-next.md} +5 -8
- package/skills/{json-render-react/SKILL.md → sf-view-gen/references/json-render-react.md} +3 -5
- package/skills/{json-render-shadcn/SKILL.md → sf-view-gen/references/json-render-shadcn.md} +3 -5
- package/skills/sf-view-gen/references/views.md +28 -37
- package/skills/sf-view-gen/scripts/catalog.mjs +10 -0
- package/skills/sf-view-gen/scripts/validate.mjs +75 -4
- package/skills/storefront-workflow/SKILL.md +94 -31
- package/skills/{storefront-best-practices/reference/design.md → storefront-workflow/references/design-consistency.md} +13 -29
- package/CHANGELOG.md +0 -84
- package/assets/templates/views/home/assembly/slots/benefits/Feature1/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/benefits/Feature2/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/benefits/Feature2/registry.part +0 -10
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/catalog.part +0 -4
- package/assets/templates/views/home/assembly/slots/categories/ProductCategory2/registry.part +0 -16
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/binding.json +0 -5
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/catalog.part +0 -4
- package/assets/templates/views/home/assembly/slots/hero/StorefrontHero1/element.part +0 -5
- package/assets/templates/views/user-panel/index.tsx +0 -106
- package/assets/templates/views/user-panel/registry.tsx +0 -54
- package/assets/templates/views/user-panel/schema.ts +0 -79
- package/commands/sf-add-view.md +0 -57
- package/commands/sf-feature.md +0 -28
- package/commands/sf-theme.md +0 -26
- package/commands/sf-view.md +0 -67
- package/skills/building-storefronts/SKILL.md +0 -178
- package/skills/building-storefronts/references/frontend-integration.md +0 -229
- package/skills/json-render-remotion/SKILL.md +0 -111
- package/skills/json-render-solid/SKILL.md +0 -204
- package/skills/nextjs-shadcn/SKILL.md +0 -367
- package/skills/nextjs-shadcn/references/architecture.md +0 -499
- package/skills/nextjs-shadcn/references/project-setup.md +0 -162
- package/skills/nextjs-shadcn/references/shadcn-platform.md +0 -261
- package/skills/nextjs-shadcn/references/sidebar.md +0 -274
- package/skills/nextjs-shadcn/references/styling.md +0 -555
- package/skills/shadcn-component-discovery/SKILL.md +0 -273
- package/skills/shadcn-component-discovery/references/registries.md +0 -226
- package/skills/shadcn-theming/SKILL.md +0 -104
- package/skills/storefront-best-practices/SKILL.md +0 -421
- package/skills/storefront-best-practices/reference/components/breadcrumbs.md +0 -123
- package/skills/storefront-best-practices/reference/components/cart-popup.md +0 -189
- package/skills/storefront-best-practices/reference/components/country-selector.md +0 -298
- package/skills/storefront-best-practices/reference/components/footer.md +0 -112
- package/skills/storefront-best-practices/reference/components/hero.md +0 -241
- package/skills/storefront-best-practices/reference/components/megamenu.md +0 -239
- package/skills/storefront-best-practices/reference/components/navbar.md +0 -397
- package/skills/storefront-best-practices/reference/components/popups.md +0 -221
- package/skills/storefront-best-practices/reference/components/product-card.md +0 -125
- package/skills/storefront-best-practices/reference/components/product-reviews.md +0 -217
- package/skills/storefront-best-practices/reference/components/product-slider.md +0 -174
- package/skills/storefront-best-practices/reference/components/search.md +0 -101
- package/skills/storefront-best-practices/reference/connecting-to-backend.md +0 -391
- package/skills/storefront-best-practices/reference/features/promotions.md +0 -307
- package/skills/storefront-best-practices/reference/features/wishlist.md +0 -230
- package/skills/storefront-best-practices/reference/layouts/account.md +0 -380
- package/skills/storefront-best-practices/reference/layouts/cart.md +0 -316
- package/skills/storefront-best-practices/reference/layouts/checkout.md +0 -486
- package/skills/storefront-best-practices/reference/layouts/home-page.md +0 -264
- package/skills/storefront-best-practices/reference/layouts/order-confirmation.md +0 -231
- package/skills/storefront-best-practices/reference/layouts/product-details.md +0 -527
- package/skills/storefront-best-practices/reference/layouts/product-listing.md +0 -520
- package/skills/storefront-best-practices/reference/layouts/static-pages.md +0 -356
- package/skills/storefront-best-practices/reference/medusa.md +0 -307
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/catalog.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature1 → cards}/element.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/catalog.part +0 -0
- /package/assets/templates/views/home/assembly/slots/benefits/{Feature2 → split}/element.part +0 -0
- /package/skills/{storefront-best-practices/reference → storefront-workflow/references}/mobile-responsiveness.md +0 -0
- /package/skills/{storefront-best-practices/reference → storefront-workflow/references}/seo.md +0 -0
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-lifecycle.client.tsx)
|
|
4
|
+
//
|
|
5
|
+
// The single shared client account lifecycle for a mounted customer-auth
|
|
6
|
+
// capability. It is mounted once by the globally composed feature handlers
|
|
7
|
+
// (`useCustomerAuthHandlers` -> `useAccountLifecycleMount`) and consumed by the
|
|
8
|
+
// shell chrome, the `/account` panel, and the account boundary. It NEVER fetches
|
|
9
|
+
// on mount or navigation: the catch-all server render already seeds
|
|
10
|
+
// `accountCustomer`/`accountAuthenticated`/`accountResolution` (tasks 2.1/2.2),
|
|
11
|
+
// and this module only reads that seed. Identity is re-resolved only when the
|
|
12
|
+
// shopper (today) or a future cross-tab transport (4.x) explicitly asks.
|
|
13
|
+
//
|
|
14
|
+
// It is the coordinator + reconciliation + mutation API for tasks 3.2/4.x:
|
|
15
|
+
// - `applyProjection(projection, guard)` claims the account slice atomically
|
|
16
|
+
// (ownership overlay + store write) so an older server snapshot can never
|
|
17
|
+
// overwrite a newer result;
|
|
18
|
+
// - `login`/`register`/`logout` run the auth Server Actions (data results,
|
|
19
|
+
// never direct HTTP), capture a pre-action generation guard, keep the three
|
|
20
|
+
// account keys in lockstep, prevent duplicate submissions, and refresh the
|
|
21
|
+
// server projection after success WITHOUT releasing the authoritative
|
|
22
|
+
// overlay;
|
|
23
|
+
// - `retryResolution()` re-resolves the session through the allowlisted
|
|
24
|
+
// `loadAccountAction` Server Action and claims either the resolved identity
|
|
25
|
+
// or the unavailable outcome;
|
|
26
|
+
// - `reconcileAccount()` / `releaseAccount(token)` / `isCurrent(token)` hand
|
|
27
|
+
// authority back to the server for an explicit next refresh;
|
|
28
|
+
// - `identityKey` (customer id or `anonymous`) names the identity-dependent
|
|
29
|
+
// private state. The identity-CHANGE invalidation is owned by the ownership
|
|
30
|
+
// WRITE PATH (`claimAccount`), not by this hook: every authoritative claim
|
|
31
|
+
// (login/register/logout, `retryResolution`, and the 4.2 `claimResolved`
|
|
32
|
+
// path) clears the seven private order keys in the SAME call that writes the
|
|
33
|
+
// trio, so the reset fires AT the trigger even when the `/account` panel is
|
|
34
|
+
// unmounted and no effect can run. `invalidatePrivateState()` is the same
|
|
35
|
+
// clear exposed for an explicit shell/4.2 invalidation without a claim. A
|
|
36
|
+
// same-identity claim is a no-op; the guest cart is never touched.
|
|
37
|
+
// CONTRACT FOR 4.2: adopt an authoritative re-resolution via
|
|
38
|
+
// `claimResolved(result, guard)` — the identity-key change clears private
|
|
39
|
+
// state atomically; a same-identity re-resolution keeps it. No token, order
|
|
40
|
+
// row, or identity crosses the seam.
|
|
41
|
+
//
|
|
42
|
+
// The three account keys always agree (accountResolution never contradicts
|
|
43
|
+
// accountAuthenticated/accountCustomer): every write goes through the projection
|
|
44
|
+
// helpers in `account-session.core`. No token, customer metadata, or secret ever
|
|
45
|
+
// enters this module's state: the projection carries only the allowlisted
|
|
46
|
+
// display identity.
|
|
47
|
+
|
|
48
|
+
import { useCallback, useEffect, useMemo, useRef } from 'react'
|
|
49
|
+
import { useRouter } from 'next/navigation'
|
|
50
|
+
import { useActions, useStateStore } from '@json-render/react'
|
|
51
|
+
import {
|
|
52
|
+
accountProjectionFromIdentity,
|
|
53
|
+
unavailableAccountProjection,
|
|
54
|
+
type AccountIdentity,
|
|
55
|
+
type AccountProjection,
|
|
56
|
+
type AccountResolution,
|
|
57
|
+
} from './account-session.core'
|
|
58
|
+
import { accountIdentityKey, clearAccountPrivateOrders } from './account-private.core'
|
|
59
|
+
import { loadAccountAction, loginAction, logoutAction, registerAction } from './actions'
|
|
60
|
+
import { emitAuthMutation, subscribeAuthMutations, type AuthMutationKind } from './account-mutation.client'
|
|
61
|
+
import { createAuthReconcileReceiver, publishAuthInvalidation } from './account-reconcile.client'
|
|
62
|
+
import type { OwnershipToken } from './projection-ownership'
|
|
63
|
+
import { useAccountOwnership, type AccountOwnership } from './projection-ownership.client'
|
|
64
|
+
|
|
65
|
+
/** The recognized login credentials (never written to shared state). */
|
|
66
|
+
export interface LoginInput {
|
|
67
|
+
email: string
|
|
68
|
+
password: string
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** The recognized registration input; names are split client-side. */
|
|
72
|
+
export interface RegisterInput {
|
|
73
|
+
email: string
|
|
74
|
+
password: string
|
|
75
|
+
firstName: string
|
|
76
|
+
lastName: string
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* A settled auth mutation: the authoritative state change (or error) is done.
|
|
81
|
+
* `blocked` marks a call that was dropped because another auth
|
|
82
|
+
* mutation/reconciliation already held the shared per-tab gate, so a caller can
|
|
83
|
+
* tell a deduped request from a real failure (never an empty error string).
|
|
84
|
+
*/
|
|
85
|
+
export type AuthMutationOutcome =
|
|
86
|
+
| { ok: true }
|
|
87
|
+
| { ok: false; error: string; blocked?: true }
|
|
88
|
+
|
|
89
|
+
/** The truthful account projection the shared lifecycle reads and writes. */
|
|
90
|
+
export interface AccountLifecycle {
|
|
91
|
+
/** The allowlisted display identity, or null when not authenticated. */
|
|
92
|
+
identity: AccountIdentity | null
|
|
93
|
+
/** True only for a resolved authenticated session. */
|
|
94
|
+
authenticated: boolean
|
|
95
|
+
/** The truthful resolution status; `unresolved` is the pre-projection default. */
|
|
96
|
+
resolution: AccountResolution | 'unresolved'
|
|
97
|
+
/** True once the server resolved the session (authenticated or anonymous). */
|
|
98
|
+
resolved: boolean
|
|
99
|
+
/** True while the session could not be resolved (a retryable outage). */
|
|
100
|
+
unavailable: boolean
|
|
101
|
+
/**
|
|
102
|
+
* True while a cross-tab invalidation or a foreground/resume recheck is in
|
|
103
|
+
* flight. The `/account` authenticated region and the 5.x navbar present a
|
|
104
|
+
* neutral pending surface instead of previously held identity/orders while it
|
|
105
|
+
* is true; it settles false when the authoritative re-resolution completes
|
|
106
|
+
* (including an unavailable/error outcome). It is never a fake signed-out
|
|
107
|
+
* state and never destroys held data (a same-identity re-resolution is a
|
|
108
|
+
* no-op, so the held rows re-present without a refetch).
|
|
109
|
+
*/
|
|
110
|
+
reconciling: boolean
|
|
111
|
+
/**
|
|
112
|
+
* The stable identity key for identity-dependent private state: the customer
|
|
113
|
+
* id, or `anonymous` for a resolved-anonymous/unavailable/unresolved session.
|
|
114
|
+
* It changes EXACTLY when the authorized customer changes, so a consumer keys
|
|
115
|
+
* a customer-scoped fetch or selection to it and a same-identity
|
|
116
|
+
* re-resolution is a no-op.
|
|
117
|
+
*/
|
|
118
|
+
identityKey: string
|
|
119
|
+
/**
|
|
120
|
+
* Clear every identity-dependent private account key (orders/count/page/
|
|
121
|
+
* selection/pending/error) through ONE seam. The AUTOMATIC clear on an
|
|
122
|
+
* identity-key change happens inside the ownership write path
|
|
123
|
+
* (`claimAccount`, which every authoritative claim — login/register/logout,
|
|
124
|
+
* `retryResolution`, and 4.x `claimResolved` — goes through), so it fires at
|
|
125
|
+
* the trigger even when the `/account` panel is unmounted. This explicit
|
|
126
|
+
* method is exposed for a shell/4.2 path that wants to invalidate private UI
|
|
127
|
+
* BEFORE it re-resolves, without a claim. It never writes a guest cart key, so
|
|
128
|
+
* the cart survives.
|
|
129
|
+
*/
|
|
130
|
+
invalidatePrivateState(): void
|
|
131
|
+
claimAccount: AccountOwnership['claimAccount']
|
|
132
|
+
claimResolved: AccountOwnership['claimResolved']
|
|
133
|
+
releaseAccount: AccountOwnership['releaseAccount']
|
|
134
|
+
reconcileAccount: AccountOwnership['reconcileAccount']
|
|
135
|
+
isCurrent: AccountOwnership['isCurrent']
|
|
136
|
+
/**
|
|
137
|
+
* Apply an authoritative projection ATOMICALLY with its generation guard: a
|
|
138
|
+
* stale guard is discarded (null); otherwise the slice is claimed so it wins
|
|
139
|
+
* over any later-arriving older server projection.
|
|
140
|
+
*/
|
|
141
|
+
applyProjection(
|
|
142
|
+
projection: AccountProjection,
|
|
143
|
+
guard?: OwnershipToken | null,
|
|
144
|
+
): OwnershipToken | null
|
|
145
|
+
/**
|
|
146
|
+
* Capture a pre-mutation guard: claim the CURRENT projection (bumping the
|
|
147
|
+
* ownership generation) so a result that arrives after a newer mutation/
|
|
148
|
+
* reconciliation can be discarded. Every mutation/retry captures one of these
|
|
149
|
+
* BEFORE it starts.
|
|
150
|
+
*/
|
|
151
|
+
beginMutation(): OwnershipToken
|
|
152
|
+
/** Authenticate; on success claims the identity, emits success, refreshes. */
|
|
153
|
+
login(input: LoginInput): Promise<AuthMutationOutcome>
|
|
154
|
+
/** Register; on success claims the identity, emits success, refreshes. */
|
|
155
|
+
register(input: RegisterInput): Promise<AuthMutationOutcome>
|
|
156
|
+
/** Sign out; on success claims anonymous, emits success, refreshes. A
|
|
157
|
+
* failure keeps the current valid session (never a fake sign-out). */
|
|
158
|
+
logout(): Promise<AuthMutationOutcome>
|
|
159
|
+
/**
|
|
160
|
+
* Re-resolve the session from the server. Explicit and user/foreground driven
|
|
161
|
+
* — never automatic — so navigation introduces no competing bootstrap. On an
|
|
162
|
+
* outage it claims the unavailable projection, never a fake sign-out.
|
|
163
|
+
*/
|
|
164
|
+
retryResolution(): Promise<void>
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The shared account lifecycle. Call it from any client component inside the
|
|
169
|
+
* storefront renderer (the shell, the `/account` panel, or the globally mounted
|
|
170
|
+
* feature handlers) — every consumer sees the same provider-backed state and the
|
|
171
|
+
* same per-tab ownership ledger, so there is no second identity source.
|
|
172
|
+
*/
|
|
173
|
+
export function useAccountLifecycle(): AccountLifecycle {
|
|
174
|
+
const { state, set, getSnapshot } = useStateStore() as {
|
|
175
|
+
state: Record<string, unknown>
|
|
176
|
+
set: (path: string, value: unknown) => void
|
|
177
|
+
getSnapshot: () => Record<string, unknown>
|
|
178
|
+
}
|
|
179
|
+
const ownership = useAccountOwnership()
|
|
180
|
+
const router = useRouter()
|
|
181
|
+
|
|
182
|
+
const identity = (state.accountCustomer ?? null) as AccountIdentity | null
|
|
183
|
+
const authenticated = state.accountAuthenticated === true
|
|
184
|
+
const resolution = (
|
|
185
|
+
typeof state.accountResolution === 'string' ? state.accountResolution : 'unresolved'
|
|
186
|
+
) as AccountResolution | 'unresolved'
|
|
187
|
+
const reconciling = state.accountReconciling === true
|
|
188
|
+
|
|
189
|
+
const identityKey = accountIdentityKey(identity)
|
|
190
|
+
|
|
191
|
+
// Explicit clear for an identity-dependent private-state invalidation without
|
|
192
|
+
// a claim (the AUTOMATIC clear on an identity change lives in the ownership
|
|
193
|
+
// write path — `claimAccount` — so it fires at the trigger even with the
|
|
194
|
+
// `/account` panel unmounted). Exposed for a shell/4.2 path that wants to drop
|
|
195
|
+
// private UI before it re-resolves. The guest cart keys are never written.
|
|
196
|
+
const invalidatePrivateState = useCallback(() => {
|
|
197
|
+
clearAccountPrivateOrders(set)
|
|
198
|
+
}, [set])
|
|
199
|
+
|
|
200
|
+
// Read the LIVE projection from the store (not the render snapshot) so a guard
|
|
201
|
+
// captured inside an async callback reflects the latest claim, not a stale
|
|
202
|
+
// render. `unresolved` (pre-projection) is treated as the anonymous slate, the
|
|
203
|
+
// truthful "no authenticated identity" claim.
|
|
204
|
+
const projectionFromSnapshot = useCallback((): AccountProjection => {
|
|
205
|
+
const snapshot = getSnapshot()
|
|
206
|
+
const currentIdentity = (snapshot.accountCustomer ?? null) as AccountIdentity | null
|
|
207
|
+
const currentAuthenticated = snapshot.accountAuthenticated === true
|
|
208
|
+
const raw =
|
|
209
|
+
typeof snapshot.accountResolution === 'string' ? snapshot.accountResolution : 'unresolved'
|
|
210
|
+
return {
|
|
211
|
+
accountCustomer: currentIdentity,
|
|
212
|
+
accountAuthenticated: currentAuthenticated,
|
|
213
|
+
accountResolution: raw === 'unresolved' ? 'anonymous' : (raw as AccountResolution),
|
|
214
|
+
}
|
|
215
|
+
}, [getSnapshot])
|
|
216
|
+
|
|
217
|
+
const beginMutation = useCallback(
|
|
218
|
+
() => ownership.claimAccount(projectionFromSnapshot()),
|
|
219
|
+
[ownership, projectionFromSnapshot],
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
const applyProjection = useCallback(
|
|
223
|
+
(projection: AccountProjection, guard: OwnershipToken | null = null) =>
|
|
224
|
+
ownership.claimResolved(projection, guard),
|
|
225
|
+
[ownership],
|
|
226
|
+
)
|
|
227
|
+
|
|
228
|
+
const retryResolution = useCallback(async () => {
|
|
229
|
+
// Shared per-tab gate (the ownership ledger): one auth request at a time
|
|
230
|
+
// across EVERY consumer in this renderer — the global mount, the account
|
|
231
|
+
// forms, a future nav sign-out. A same-tick double click, or a retry racing
|
|
232
|
+
// a mutation in another instance, must not issue a second request. The gate
|
|
233
|
+
// is per-tab ledger state, never a module global, so tabs/stores stay
|
|
234
|
+
// isolated.
|
|
235
|
+
if (!ownership.acquireAuthMutation()) return
|
|
236
|
+
// Capture the generation BEFORE the request; a newer mutation/
|
|
237
|
+
// reconciliation supersedes this retry and the delayed response is then
|
|
238
|
+
// discarded.
|
|
239
|
+
const guard = beginMutation()
|
|
240
|
+
try {
|
|
241
|
+
set('/accountPending', true)
|
|
242
|
+
set('/accountError', null)
|
|
243
|
+
const result = await loadAccountAction()
|
|
244
|
+
if (result.ok) {
|
|
245
|
+
applyProjection(accountProjectionFromIdentity(result.customer), guard)
|
|
246
|
+
} else {
|
|
247
|
+
set('/accountError', result.error)
|
|
248
|
+
applyProjection(unavailableAccountProjection(), guard)
|
|
249
|
+
}
|
|
250
|
+
} catch (error) {
|
|
251
|
+
// Never swallow: log a non-secret context line and surface a message. A
|
|
252
|
+
// rejected read is a retryable outage, never a fake sign-out.
|
|
253
|
+
console.error(
|
|
254
|
+
'[storefront/account] retryResolution failed',
|
|
255
|
+
error instanceof Error ? error.message : error,
|
|
256
|
+
)
|
|
257
|
+
set('/accountError', 'No se pudo cargar la cuenta. Inténtalo de nuevo.')
|
|
258
|
+
applyProjection(unavailableAccountProjection(), guard)
|
|
259
|
+
} finally {
|
|
260
|
+
set('/accountPending', false)
|
|
261
|
+
ownership.releaseAuthMutation()
|
|
262
|
+
}
|
|
263
|
+
}, [applyProjection, beginMutation, ownership, set])
|
|
264
|
+
|
|
265
|
+
// Run one auth Server Action with the full mutation contract: duplicate
|
|
266
|
+
// prevention, a pre-action guard, truthful feedback, an authoritative guarded
|
|
267
|
+
// claim (never a release-to-server), a mutation-success seam for 4.1, and a
|
|
268
|
+
// server refresh whose projection cannot overwrite the claimed overlay.
|
|
269
|
+
const runMutation = useCallback(
|
|
270
|
+
async (
|
|
271
|
+
kind: AuthMutationKind,
|
|
272
|
+
run: () => Promise<
|
|
273
|
+
{ ok: true; customer: AccountIdentity | null } | { ok: false; error: string }
|
|
274
|
+
>,
|
|
275
|
+
): Promise<AuthMutationOutcome> => {
|
|
276
|
+
if (!ownership.acquireAuthMutation()) {
|
|
277
|
+
// Another auth mutation/reconciliation (any consumer sharing this tab)
|
|
278
|
+
// already holds the gate: drop this same-tick duplicate without touching
|
|
279
|
+
// the shared pending/error feedback, and report it distinctly.
|
|
280
|
+
return { ok: false, error: 'Ya hay una operación en curso.', blocked: true }
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
set('/accountPending', true)
|
|
284
|
+
set('/accountError', null)
|
|
285
|
+
const guard = beginMutation()
|
|
286
|
+
const result = await run()
|
|
287
|
+
if (result.ok) {
|
|
288
|
+
// Guarded claim: only a result that is still the latest authority is
|
|
289
|
+
// displayed; a superseded older response is discarded (a newer
|
|
290
|
+
// mutation/reconciliation already won).
|
|
291
|
+
const applied = applyProjection(accountProjectionFromIdentity(result.customer), guard)
|
|
292
|
+
if (applied) {
|
|
293
|
+
set('/accountMode', 'login')
|
|
294
|
+
// The 4.1 cross-tab invalidation seam: no identity, just the kind.
|
|
295
|
+
emitAuthMutation(kind)
|
|
296
|
+
// Refresh the server projection; the claimed overlay protects the
|
|
297
|
+
// authoritative result against an older refreshed RSC payload.
|
|
298
|
+
router.refresh()
|
|
299
|
+
}
|
|
300
|
+
return { ok: true }
|
|
301
|
+
}
|
|
302
|
+
set('/accountError', result.error)
|
|
303
|
+
return { ok: false, error: result.error }
|
|
304
|
+
} catch (error) {
|
|
305
|
+
// A rejected Server Action (network/RPC) must not be swallowed. Only a
|
|
306
|
+
// non-secret context line is logged; the current identity is untouched.
|
|
307
|
+
console.error(
|
|
308
|
+
'[storefront/account] mutation failed',
|
|
309
|
+
kind,
|
|
310
|
+
error instanceof Error ? error.message : error,
|
|
311
|
+
)
|
|
312
|
+
const message = 'No se pudo completar la operación. Inténtalo de nuevo.'
|
|
313
|
+
set('/accountError', message)
|
|
314
|
+
return { ok: false, error: message }
|
|
315
|
+
} finally {
|
|
316
|
+
set('/accountPending', false)
|
|
317
|
+
ownership.releaseAuthMutation()
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
[applyProjection, beginMutation, ownership, router, set],
|
|
321
|
+
)
|
|
322
|
+
|
|
323
|
+
const login = useCallback(
|
|
324
|
+
(input: LoginInput) =>
|
|
325
|
+
runMutation('login', () => loginAction({ email: input.email, password: input.password })),
|
|
326
|
+
[runMutation],
|
|
327
|
+
)
|
|
328
|
+
|
|
329
|
+
const register = useCallback(
|
|
330
|
+
(input: RegisterInput) =>
|
|
331
|
+
runMutation('register', () =>
|
|
332
|
+
registerAction({
|
|
333
|
+
email: input.email,
|
|
334
|
+
password: input.password,
|
|
335
|
+
first_name: input.firstName,
|
|
336
|
+
last_name: input.lastName,
|
|
337
|
+
}),
|
|
338
|
+
),
|
|
339
|
+
[runMutation],
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
const logout = useCallback(
|
|
343
|
+
() =>
|
|
344
|
+
runMutation('logout', async () => {
|
|
345
|
+
const result = await logoutAction()
|
|
346
|
+
return result.ok ? { ok: true, customer: null } : { ok: false, error: result.error }
|
|
347
|
+
}),
|
|
348
|
+
[runMutation],
|
|
349
|
+
)
|
|
350
|
+
|
|
351
|
+
return useMemo(
|
|
352
|
+
() => ({
|
|
353
|
+
identity,
|
|
354
|
+
authenticated,
|
|
355
|
+
resolution,
|
|
356
|
+
resolved: resolution === 'authenticated' || resolution === 'anonymous',
|
|
357
|
+
unavailable: resolution === 'unavailable',
|
|
358
|
+
reconciling,
|
|
359
|
+
identityKey,
|
|
360
|
+
invalidatePrivateState,
|
|
361
|
+
claimAccount: ownership.claimAccount,
|
|
362
|
+
claimResolved: ownership.claimResolved,
|
|
363
|
+
releaseAccount: ownership.releaseAccount,
|
|
364
|
+
reconcileAccount: ownership.reconcileAccount,
|
|
365
|
+
isCurrent: ownership.isCurrent,
|
|
366
|
+
applyProjection,
|
|
367
|
+
beginMutation,
|
|
368
|
+
login,
|
|
369
|
+
register,
|
|
370
|
+
logout,
|
|
371
|
+
retryResolution,
|
|
372
|
+
}),
|
|
373
|
+
[
|
|
374
|
+
identity,
|
|
375
|
+
authenticated,
|
|
376
|
+
resolution,
|
|
377
|
+
reconciling,
|
|
378
|
+
identityKey,
|
|
379
|
+
invalidatePrivateState,
|
|
380
|
+
ownership,
|
|
381
|
+
applyProjection,
|
|
382
|
+
beginMutation,
|
|
383
|
+
login,
|
|
384
|
+
register,
|
|
385
|
+
logout,
|
|
386
|
+
retryResolution,
|
|
387
|
+
],
|
|
388
|
+
)
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* The global mount of the shared lifecycle. The composed feature handlers call
|
|
393
|
+
* this once per mounted tab (only when customer-auth is installed), so the
|
|
394
|
+
* lifecycle is active on every storefront route without a route-level fetch.
|
|
395
|
+
* It registers the `retryAccountSession` action the account boundary emits and
|
|
396
|
+
* returns the same lifecycle instance consumers read.
|
|
397
|
+
*/
|
|
398
|
+
export function useAccountLifecycleMount(): AccountLifecycle {
|
|
399
|
+
const lifecycle = useAccountLifecycle()
|
|
400
|
+
// The shared per-tab mutation gate lives on this ledger (one per renderer/tab);
|
|
401
|
+
// the 4.2 receiver probes it so a reconciliation cannot race a local mutation.
|
|
402
|
+
const ownership = useAccountOwnership()
|
|
403
|
+
const { registerHandler } = useActions()
|
|
404
|
+
const { set } = useStateStore()
|
|
405
|
+
const retryResolution = lifecycle.retryResolution
|
|
406
|
+
|
|
407
|
+
useEffect(() => {
|
|
408
|
+
registerHandler('retryAccountSession', () => {
|
|
409
|
+
void retryResolution()
|
|
410
|
+
})
|
|
411
|
+
// registerHandler uses functional updates; retry is stable per ownership.
|
|
412
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
413
|
+
}, [])
|
|
414
|
+
|
|
415
|
+
// The ids this tab published (task 4.1) so the 4.2 receiver ignores its own
|
|
416
|
+
// broadcast echo — the listen channel sees the sender's own message. Bounded:
|
|
417
|
+
// only the most recent ids can realistically echo back.
|
|
418
|
+
const publishedIds = useRef<Set<string>>(new Set())
|
|
419
|
+
|
|
420
|
+
// Task 4.1: publish a non-secret, store-scoped auth invalidation to other
|
|
421
|
+
// same-store tabs after every successful mutation. The unsubscribe releases
|
|
422
|
+
// the seam on unmount (full listener cleanup is task 4.3).
|
|
423
|
+
useEffect(() => {
|
|
424
|
+
const unsubscribe = subscribeAuthMutations((kind) => {
|
|
425
|
+
const payload = publishAuthInvalidation(kind)
|
|
426
|
+
const ids = publishedIds.current
|
|
427
|
+
ids.add(payload.id)
|
|
428
|
+
// Evict the OLDEST id past the bound (rather than dropping them all) so a
|
|
429
|
+
// recent self-echo is still recognized; only a very delayed one could miss.
|
|
430
|
+
if (ids.size > 32) {
|
|
431
|
+
const oldest = ids.values().next().value
|
|
432
|
+
if (oldest !== undefined) ids.delete(oldest)
|
|
433
|
+
}
|
|
434
|
+
})
|
|
435
|
+
return unsubscribe
|
|
436
|
+
}, [])
|
|
437
|
+
|
|
438
|
+
// Task 4.2: receive same-store invalidations — and foreground/resume
|
|
439
|
+
// transitions — and re-resolve the session authoritatively through the shared
|
|
440
|
+
// `retryResolution` (never a new fetch/direct HTTP), applying the result via
|
|
441
|
+
// the existing generation guard. The receiver is inert until a signal/resume
|
|
442
|
+
// (no fetch on mount/navigation), never re-publishes on receipt (no loops),
|
|
443
|
+
// ignores this tab's own echo, and skips while a local mutation holds the
|
|
444
|
+
// shared gate. The unsubscribe releases every listener on unmount.
|
|
445
|
+
useEffect(() => {
|
|
446
|
+
return createAuthReconcileReceiver({
|
|
447
|
+
retryResolution,
|
|
448
|
+
isAuthMutationPending: () => ownership.isAuthMutationPending(),
|
|
449
|
+
isOwnSignal: (payload) => publishedIds.current.has(payload.id),
|
|
450
|
+
// Publish the pending window to the shared store so the `/account`
|
|
451
|
+
// authenticated region (and the 5.x navbar) present a neutral pending
|
|
452
|
+
// surface instead of previously held identity/orders until the
|
|
453
|
+
// authoritative re-resolution settles.
|
|
454
|
+
onReconcileChange: (reconciling) => set('/accountReconciling', reconciling),
|
|
455
|
+
})
|
|
456
|
+
// retryResolution is stable per ownership; the gate probe is read live.
|
|
457
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
458
|
+
}, [])
|
|
459
|
+
|
|
460
|
+
return lifecycle
|
|
461
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
'use client'
|
|
2
|
+
|
|
3
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-mutation.client.ts)
|
|
4
|
+
//
|
|
5
|
+
// The auth-mutation SUCCESS seam for cross-tab reconciliation (task 4.1).
|
|
6
|
+
//
|
|
7
|
+
// The shared account lifecycle calls `emitAuthMutation(kind)` AFTER an
|
|
8
|
+
// authoritative login/register/logout result has been claimed and displayed.
|
|
9
|
+
// Task 4.1 subscribes here with `subscribeAuthMutations` to publish a
|
|
10
|
+
// store-scoped, NON-SECRET invalidation signal to other same-store tabs; the
|
|
11
|
+
// mutation kind is the ONLY payload — no identity, orders, credentials, or
|
|
12
|
+
// tokens ever pass through this seam. Registering no listener (today) is a
|
|
13
|
+
// no-op, so mounting this module performs no cross-tab work and opens no
|
|
14
|
+
// channel. This module is deliberately tiny and framework-free apart from the
|
|
15
|
+
// client directive so the transport can be added without touching the
|
|
16
|
+
// lifecycle.
|
|
17
|
+
|
|
18
|
+
/** The authoritative auth mutations that require cross-tab reconciliation. */
|
|
19
|
+
export type AuthMutationKind = 'login' | 'register' | 'logout'
|
|
20
|
+
|
|
21
|
+
type AuthMutationListener = (kind: AuthMutationKind) => void
|
|
22
|
+
|
|
23
|
+
// Per-tab listener set (a browser module instance is per tab). It holds no
|
|
24
|
+
// identity or secret — only the seam's subscribers.
|
|
25
|
+
const listeners = new Set<AuthMutationListener>()
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Subscribe to successful auth mutations. Returns an unsubscribe function that
|
|
29
|
+
* removes the listener (call it on unmount so a capability removal drops every
|
|
30
|
+
* listener — task 4.3).
|
|
31
|
+
*/
|
|
32
|
+
export function subscribeAuthMutations(listener: AuthMutationListener): () => void {
|
|
33
|
+
listeners.add(listener)
|
|
34
|
+
return () => {
|
|
35
|
+
listeners.delete(listener)
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Emit a successful authoritative auth mutation. The shared lifecycle calls this
|
|
41
|
+
* only after the result is claimed; a failure to publish (no listeners) is a
|
|
42
|
+
* no-op, never an error.
|
|
43
|
+
*/
|
|
44
|
+
export function emitAuthMutation(kind: AuthMutationKind): void {
|
|
45
|
+
for (const listener of listeners) listener(kind)
|
|
46
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Generated by Thor Commerce storefront (template: assets/templates/app/lib/__STOREFRONT__/account-private.core.ts)
|
|
2
|
+
//
|
|
3
|
+
// Pure, framework-free core for the identity-dependent account-PRIVATE state
|
|
4
|
+
// (the customer order slice). It is the one seam that clears what belongs to a
|
|
5
|
+
// resolved customer and nothing else:
|
|
6
|
+
//
|
|
7
|
+
// - `accountIdentityKey` collapses the account projection to a stable key
|
|
8
|
+
// (the customer id, or `anonymous` for a resolved-anonymous / unavailable /
|
|
9
|
+
// unresolved session). A key CHANGE means the displayed private state is no
|
|
10
|
+
// longer the current shopper's.
|
|
11
|
+
// - `clearAccountPrivateOrders` writes the reset for exactly the order keys;
|
|
12
|
+
// the guest cart keys are never touched, so a logout/expiry/switch keeps the
|
|
13
|
+
// cart.
|
|
14
|
+
//
|
|
15
|
+
// The shared account lifecycle (task 3.3) exposes `identityKey`, and the
|
|
16
|
+
// identity-change invalidation is owned by the ownership WRITE PATH
|
|
17
|
+
// (`claimAccount`), which calls `clearAccountPrivateOrders` on a key change —
|
|
18
|
+
// atomically with the account trio write, so the reset happens at the trigger
|
|
19
|
+
// even when the `/account` panel is unmounted. `invalidatePrivateState()` is the
|
|
20
|
+
// same clear exposed for an explicit shell/4.x invalidation without a claim. It
|
|
21
|
+
// imports no React/Next, holds no state, and carries no token: callers pass a
|
|
22
|
+
// json-render-style `set(path, value)`.
|
|
23
|
+
|
|
24
|
+
import type { AccountOrderView } from './state.core'
|
|
25
|
+
|
|
26
|
+
/** The bounded page size the account order window starts from. */
|
|
27
|
+
export const ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE = 10
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The identity-dependent account-PRIVATE order keys. Every one is cleared when
|
|
31
|
+
* the shopper identity changes or is invalidated. The guest cart keys
|
|
32
|
+
* (`cart`, `cartTotals`, `cartId`, `cartQuantity`, `cartCompleted`,
|
|
33
|
+
* `cartSelectedShippingOptionId`) are deliberately absent and MUST survive.
|
|
34
|
+
*/
|
|
35
|
+
export const ACCOUNT_PRIVATE_ORDER_KEYS = [
|
|
36
|
+
'accountOrders',
|
|
37
|
+
'accountOrdersCount',
|
|
38
|
+
'accountOrdersPage',
|
|
39
|
+
'accountOrdersPageSize',
|
|
40
|
+
'accountSelectedOrderId',
|
|
41
|
+
'accountOrdersPending',
|
|
42
|
+
'accountOrdersError',
|
|
43
|
+
] as const
|
|
44
|
+
|
|
45
|
+
export type AccountPrivateOrderKey = (typeof ACCOUNT_PRIVATE_ORDER_KEYS)[number]
|
|
46
|
+
|
|
47
|
+
/** The reset value of every identity-dependent private order key. */
|
|
48
|
+
export interface AccountPrivateOrderState {
|
|
49
|
+
accountOrders: AccountOrderView[]
|
|
50
|
+
accountOrdersCount: number
|
|
51
|
+
accountOrdersPage: number
|
|
52
|
+
accountOrdersPageSize: number
|
|
53
|
+
accountSelectedOrderId: string | null
|
|
54
|
+
accountOrdersPending: boolean
|
|
55
|
+
accountOrdersError: string | null
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* The reset value of the private order slice: no rows, no count, page 1, the
|
|
60
|
+
* default page size, no selection, not pending, no error. Deterministic so the
|
|
61
|
+
* lifecycle and the feature's initial state cannot drift.
|
|
62
|
+
*/
|
|
63
|
+
export function emptyAccountPrivateOrderState(
|
|
64
|
+
pageSize: number = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE,
|
|
65
|
+
): AccountPrivateOrderState {
|
|
66
|
+
return {
|
|
67
|
+
accountOrders: [],
|
|
68
|
+
accountOrdersCount: 0,
|
|
69
|
+
accountOrdersPage: 1,
|
|
70
|
+
accountOrdersPageSize: pageSize,
|
|
71
|
+
accountSelectedOrderId: null,
|
|
72
|
+
accountOrdersPending: false,
|
|
73
|
+
accountOrdersError: null,
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The stable identity key for the private slice. An authenticated shopper keys
|
|
79
|
+
* by the customer id; a resolved-anonymous, unavailable, or unresolved session
|
|
80
|
+
* all key as `anonymous` because none carries an authorized customer. A change
|
|
81
|
+
* of key is the single trigger to discard private state.
|
|
82
|
+
*/
|
|
83
|
+
export function accountIdentityKey(identity: { id?: string | null } | null | undefined): string {
|
|
84
|
+
return identity && typeof identity.id === 'string' && identity.id !== ''
|
|
85
|
+
? identity.id
|
|
86
|
+
: 'anonymous'
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Clear the identity-dependent private order state through a json-render-style
|
|
91
|
+
* setter. Writes exactly `ACCOUNT_PRIVATE_ORDER_KEYS`; it never writes a guest
|
|
92
|
+
* cart key, so the cart survives a logout, expiry, switch, or unavailable
|
|
93
|
+
* resolution. Idempotent: a repeated clear is harmless.
|
|
94
|
+
*/
|
|
95
|
+
export function clearAccountPrivateOrders(
|
|
96
|
+
set: (path: string, value: unknown) => void,
|
|
97
|
+
pageSize: number = ACCOUNT_ORDERS_DEFAULT_PAGE_SIZE,
|
|
98
|
+
): void {
|
|
99
|
+
const reset = emptyAccountPrivateOrderState(pageSize)
|
|
100
|
+
for (const key of ACCOUNT_PRIVATE_ORDER_KEYS) {
|
|
101
|
+
set(`/${key}`, reset[key])
|
|
102
|
+
}
|
|
103
|
+
}
|