@growupsell/commerce 1.0.0-alpha.2 → 1.0.0-alpha.3
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/dist/{checkout-CwpFl6qt.d.ts → checkout-DDNMdKbR.d.ts} +27 -3
- package/dist/{chunk-AI2CWQ22.js → chunk-BORVKACK.js} +12 -4
- package/dist/chunk-BORVKACK.js.map +1 -0
- package/dist/{chunk-DHBRITDW.js → chunk-HGCKDE7D.js} +16 -8
- package/dist/chunk-HGCKDE7D.js.map +1 -0
- package/dist/{client-D4JNDM6j.d.ts → client-RzekAHeO.d.ts} +2 -9
- package/dist/http/index.d.ts +2 -2
- package/dist/http/index.js +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/rules/index.d.ts +1 -1
- package/dist/{sku-C3SGyRqT.d.ts → sku-ViHXTvEw.d.ts} +1 -1
- package/dist/stores/index.d.ts +8 -1
- package/dist/stores/index.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-AI2CWQ22.js.map +0 -1
- package/dist/chunk-DHBRITDW.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/stores/runtime/concurrency.ts","../src/stores/runtime/errors.ts","../src/stores/runtime/store.ts","../src/stores/auth.ts","../src/stores/business.ts","../src/stores/cart.ts","../src/stores/catalog.ts","../src/stores/selectors.ts","../src/stores/checkout.ts","../src/stores/listing.ts","../src/stores/productDetail.ts","../src/stores/referral.ts","../src/stores/runtime/events.ts","../src/stores/runtime/storage.ts","../src/stores/runtime/context.ts","../src/stores/searchSuggestions.ts","../src/stores/session.ts","../src/stores/themeConfig.ts","../src/stores/wishlist.ts","../src/stores/create.ts"],"sourcesContent":["/**\n * Concurrency policies for store actions (M3 plan Part B5). Each store declares one per action:\n *\n * | Kind of action | Policy |\n * | ----------------------------------------- | --------------------------------------------- |\n * | Read of a resource | `createLatest` |\n * | Create-once / never-twice | `createSingleFlight` |\n * | Mutations of one resource | `createSerialQueue`, then one latest refresh |\n * | Absolute values set repeatedly (quantity) | `createCoalescer` |\n *\n * And every async action checks the identity epoch (`runInEpoch`), so one shopper's result\n * never lands in another shopper's state.\n */\n\n/** The outcome of a call that may have been replaced by a newer one. */\nexport type Current<T> = { current: true; value: T } | { current: false };\n\n/** Calls `run` and turns a synchronous throw into a rejected promise. */\nfunction start<T>(run: () => Promise<T>): Promise<T> {\n try {\n return Promise.resolve(run());\n } catch (error) {\n return Promise.reject(error);\n }\n}\n\n/**\n * Latest-wins: only the newest call's result is applied; older ones resolve\n * `{ current: false }`, whether they succeeded or failed. The newest call's rejection is passed on.\n */\nexport function createLatest(): <T>(run: () => Promise<T>) => Promise<Current<T>> {\n let generation = 0;\n return async <T>(run: () => Promise<T>): Promise<Current<T>> => {\n const mine = ++generation;\n try {\n const value = await start(run);\n return mine === generation ? { current: true, value } : { current: false };\n } catch (error) {\n if (mine !== generation) return { current: false };\n throw error;\n }\n };\n}\n\n/** Single-flight: while a call for `key` runs, further calls get the same promise. */\nexport function createSingleFlight<K>(): <T>(key: K, run: () => Promise<T>) => Promise<T> {\n const inFlight = new Map<K, Promise<unknown>>();\n return <T>(key: K, run: () => Promise<T>): Promise<T> => {\n const existing = inFlight.get(key);\n if (existing) return existing as Promise<T>;\n const promise = start(run).finally(() => {\n if (inFlight.get(key) === promise) inFlight.delete(key);\n });\n inFlight.set(key, promise);\n return promise;\n };\n}\n\n/**\n * Serial: calls run one after another in call order (mutations on one resource). A call that\n * fails does not stop the next one.\n */\nexport function createSerialQueue(): <T>(run: () => Promise<T>) => Promise<T> {\n let tail: Promise<unknown> = Promise.resolve();\n return <T>(run: () => Promise<T>): Promise<T> => {\n const next = tail.then(\n () => start(run),\n () => start(run),\n );\n tail = next.catch(() => {});\n return next;\n };\n}\n\n/**\n * Coalescing for absolute values set repeatedly (a line's quantity): per key at most one\n * `send` is in flight; values set meanwhile replace each other and only the newest is sent\n * when the request in flight settles. A call is `current` only when its value was sent and no\n * newer value was waiting when it settled; every other call resolves `{ current: false }`\n * (also when its send failed: the newer value decides). The current call's failure rejects.\n */\nexport function createCoalescer<K>(): <V, R>(\n key: K,\n value: V,\n send: (value: V) => Promise<R>,\n) => Promise<Current<R>> {\n interface Waiting {\n value: unknown;\n send: (value: unknown) => Promise<unknown>;\n settle: (outcome: Promise<Current<unknown>>) => void;\n }\n const slots = new Map<K, { waiting: Waiting | null }>();\n\n function launch(key: K, slot: { waiting: Waiting | null }, job: Waiting) {\n const sent = start(() => job.send(job.value));\n job.settle(\n sent.then(\n (value) => (slot.waiting ? { current: false } : { current: true, value }),\n (error: unknown) => {\n if (slot.waiting) return { current: false };\n throw error;\n },\n ),\n );\n void sent\n .catch(() => {})\n .then(() => {\n const next = slot.waiting;\n slot.waiting = null;\n if (next) launch(key, slot, next);\n else slots.delete(key);\n });\n }\n\n return <V, R>(key: K, value: V, send: (value: V) => Promise<R>): Promise<Current<R>> =>\n new Promise<Current<R>>((resolve, reject) => {\n const job: Waiting = {\n value,\n send: send as (value: unknown) => Promise<unknown>,\n settle: (outcome) => (outcome as Promise<Current<R>>).then(resolve, reject),\n };\n const slot = slots.get(key);\n if (!slot) {\n const fresh = { waiting: null };\n slots.set(key, fresh);\n launch(key, fresh, job);\n return;\n }\n slot.waiting?.settle(Promise.resolve({ current: false }));\n slot.waiting = job;\n });\n}\n\n/**\n * Runs `run` and reports whether the identity epoch (M3 plan B5) is still the one it started\n * in. A result or failure that arrives after the epoch changed belongs to a previous shopper:\n * it resolves `{ current: false }` and the caller drops it (`superseded`).\n */\nexport async function runInEpoch<T>(\n epoch: () => number,\n run: () => Promise<T>,\n): Promise<Current<T>> {\n const started = epoch();\n try {\n const value = await start(run);\n return epoch() === started ? { current: true, value } : { current: false };\n } catch (error) {\n if (epoch() !== started) return { current: false };\n throw error;\n }\n}\n","/**\n * Errors and action results (M3 plan Part B3, decision O1). Store actions never reject: they\n * resolve an `ActionResult`, whose error is plain data that can sit in a snapshot.\n */\nimport { GrowupsellApiError } from '../../http/errors';\n\nexport type StoreErrorKind =\n | 'http'\n | 'network'\n | 'timeout'\n | 'parse' // from GrowupsellApiError.kind\n | 'validation' // refused before sending (bad input, rule says no)\n | 'signed-out' // the action needs a customer login\n | 'session' // the guest session died during the action; it has been replaced\n | 'superseded' // a newer call replaced this one (latest-wins), or the identity changed\n | 'unknown';\n\n/** Plain data: safe to keep in a snapshot and to render. */\nexport interface StoreError {\n kind: StoreErrorKind;\n /** The backend's message (`GrowupsellApiError.message`) or a library message in English. */\n message: string;\n status: number | null;\n fieldErrors: Readonly<Record<string, readonly string[]>>;\n /** A throttled request (429): seconds until it may be retried (`Retry-After`). Absent otherwise. */\n retryAfterSeconds?: number;\n}\n\nexport type ActionResult<T = void> = { ok: true; value: T } | { ok: false; error: StoreError };\n\nexport const ok = <T>(value: T): ActionResult<T> => ({ ok: true, value });\n\nexport const fail = (error: StoreError): ActionResult<never> => ({ ok: false, error });\n\n/** Builds a `StoreError` the library raises itself (`validation`, `signed-out`, `superseded`…). */\nexport function storeError(\n kind: StoreErrorKind,\n message: string,\n extra: { status?: number | null; fieldErrors?: Record<string, readonly string[]> } = {},\n): StoreError {\n return { kind, message, status: extra.status ?? null, fieldErrors: extra.fieldErrors ?? {} };\n}\n\nconst KINDS: ReadonlySet<string> = new Set<StoreErrorKind>([\n 'http',\n 'network',\n 'timeout',\n 'parse',\n 'validation',\n 'signed-out',\n 'session',\n 'superseded',\n 'unknown',\n]);\n\nfunction isStoreError(value: unknown): value is StoreError {\n if (!value || typeof value !== 'object' || value instanceof Error) return false;\n const v = value as Partial<StoreError>;\n return typeof v.kind === 'string' && KINDS.has(v.kind) && typeof v.message === 'string';\n}\n\n/**\n * Turns anything an action caught into a `StoreError`:\n *\n * - `GrowupsellApiError` keeps its kind, status, message and field errors (copied), and\n * `retryAfterSeconds` when it has one (a 429).\n * - `TypeError` / `RangeError` are the http modules' input checks: `validation`.\n * - An HTML 404 to a request that sent the guest session token is `session` (the backend\n * forgot the session, ADR-023); pass `sentSession` when the request carried one.\n * - Anything else is `unknown`.\n */\nexport function toStoreError(error: unknown, context: { sentSession?: boolean } = {}): StoreError {\n if (isStoreError(error)) return error;\n if (error instanceof GrowupsellApiError) {\n const deadSession =\n context.sentSession === true &&\n error.kind === 'http' &&\n error.status === 404 &&\n typeof error.body === 'string';\n const converted = storeError(deadSession ? 'session' : error.kind, error.message, {\n status: error.status ?? null,\n fieldErrors: Object.fromEntries(\n Object.entries(error.fieldErrors).map(([field, messages]) => [field, [...messages]]),\n ),\n });\n if (error.retryAfterSeconds != null) converted.retryAfterSeconds = error.retryAfterSeconds;\n return converted;\n }\n if (error instanceof TypeError || error instanceof RangeError) {\n return storeError('validation', error.message);\n }\n if (error instanceof Error) return storeError('unknown', error.message);\n if (typeof error === 'string') return storeError('unknown', error);\n return storeError('unknown', 'Unknown error');\n}\n","/**\n * The store primitive (ADR-002, ADR-024; M3 plan Part B2). Every store is a `Store<T>`:\n * immutable snapshots, synchronous notification, a constant server snapshot.\n */\n\n/** What adapters consume. Shaped for React's `useSyncExternalStore` (ADR-002). */\nexport interface Store<T> {\n /** The current snapshot. Returns the same reference until the state changes. */\n getSnapshot(): T;\n /** The snapshot before hydration, constant for the instance: SSR and the first client render. */\n getServerSnapshot(): T;\n /**\n * Calls `listener` (no arguments) after every change, synchronously, after the snapshot\n * is updated. Not called on subscribe. Returns an idempotent unsubscribe.\n */\n subscribe(listener: () => void): () => void;\n}\n\n/** Internal: what a store implementation holds. Never exported from the package. */\nexport interface WritableStore<T> extends Store<T> {\n /** Replaces the snapshot; no-op (no notification) when `Object.is(next, current)`. */\n set(next: T): void;\n /** `set(fn(current))`. */\n update(fn: (current: T) => T): void;\n}\n\n/** The public view of a writable store: what a store factory returns, without `set`/`update`. */\nexport function readOnly<T>(store: Store<T>): Store<T> {\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe: store.subscribe,\n };\n}\n\n/** `idle`: nothing requested (e.g. a guest with no session has no cart yet). */\nexport type LoadStatus = 'idle' | 'loading' | 'ready' | 'error';\n\n/** Timers through `globalThis`: `commerce` compiles without DOM or Node types (ADR-009). */\ninterface Runtime {\n setTimeout(handler: () => void, ms: number): unknown;\n}\nconst runtime = globalThis as unknown as Runtime;\n\n/** The default for listener and storage errors: rethrown on a later tick, so nothing is lost. */\nexport function rethrowAsync(error: unknown): void {\n runtime.setTimeout(() => {\n throw error;\n }, 0);\n}\n\n/**\n * Creates a store. Listeners run in insertion order over a copy of the list taken when the\n * change happens, so (un)subscribing during a notification never breaks the loop: a listener\n * added then is first called on the next change; one removed then is still called this round.\n * A throwing listener goes to `onListenerError` (default: rethrown asynchronously).\n */\nexport function createStore<T>(\n initial: T,\n options: { onListenerError?: (error: unknown) => void } = {},\n): WritableStore<T> {\n const onListenerError = options.onListenerError ?? rethrowAsync;\n let snapshot = initial;\n // One entry object per subscribe call: the same function subscribed twice is two entries.\n let listeners: Array<{ listener: () => void }> = [];\n\n function set(next: T) {\n if (Object.is(next, snapshot)) return;\n snapshot = next;\n for (const entry of listeners.slice()) {\n try {\n entry.listener();\n } catch (error) {\n onListenerError(error);\n }\n }\n }\n\n return {\n getSnapshot: () => snapshot,\n getServerSnapshot: () => initial,\n subscribe(listener) {\n const entry = { listener };\n listeners = [...listeners, entry];\n return () => {\n listeners = listeners.filter((e) => e !== entry);\n };\n },\n set,\n update: (fn) => set(fn(snapshot)),\n };\n}\n","/**\n * The customer login store (M3 plan D2, Task 7; ADR-025). Login and sign-up go through the\n * guest session (created when there is none) so the guest cart moves to the customer, and the\n * session is rotated after every sign-in and on logout (W32: a merged session token must never\n * reach another login). An account that still needs its OTP never yields a token (W22).\n *\n * The token lives only in the runtime's holder and the stored login record: never in a\n * snapshot or an event. A stored login is dropped at hydration after `customerTokenTtlMs`\n * (24 h, the token's own lifetime); a 401 for the current token signs out once (`expired`).\n */\nimport type { LoginInput, RegisterInput } from '../http/auth';\nimport type { UpdateProfileInput } from '../http/customer';\nimport type { AuthResult, CustomerSettings, SignedInCustomer } from '../types/auth';\nimport type { CustomerProfile } from '../types/customer';\nimport { createSingleFlight } from './runtime/concurrency';\nimport type { AuthRecord, StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore } from './runtime/store';\nimport type { AuthOutcome, AuthState, AuthStore } from './types/auth';\n\ntype Pending = NonNullable<AuthState['pending']>;\ntype Via = 'login' | 'register' | 'otp';\n/** Actions whose request carries the guest session: an HTML 404 there means it died. */\nconst SENDS_SESSION: ReadonlySet<Pending> = new Set<Pending>(['login', 'register', 'verify']);\n\nconst SUPERSEDED = () =>\n storeError('superseded', 'The shopper changed while the request was running.');\n\nexport function createAuthStore(ctx: StoreContext): AuthStore {\n const store = createStore<AuthState>(\n {\n status: 'unknown',\n customer: null,\n rewardPoints: null,\n verification: null,\n settings: null,\n pending: null,\n error: null,\n },\n { onListenerError: ctx.onListenerError },\n );\n const patch = (next: Partial<AuthState>) => store.update((s) => ({ ...s, ...next }));\n const flight = createSingleFlight<Pending>();\n\n /** Where the current login is stored: `secureStorage` (remembered) or `ephemeralStorage`. */\n let remembered = true;\n /** The stored login's `savedAt`, kept when the profile changes. */\n let savedAt = 0;\n\n ctx.onHydrate(({ auth, remembered: fromSecure }) => {\n remembered = fromSecure;\n savedAt = auth?.savedAt ?? 0;\n patch(\n auth\n ? {\n status: 'signed-in',\n customer: auth.customer,\n rewardPoints: auth.rewardPoints,\n verification: null,\n }\n : { status: 'signed-out', customer: null, rewardPoints: null },\n );\n });\n\n // Helpers -----------------------------------------------------------------------------\n\n /** Runs one action: `pending`, error cleared at the start, kept and emitted on failure. */\n function action<T>(name: Pending, run: () => Promise<ActionResult<T>>): Promise<ActionResult<T>> {\n return flight(name, async () => {\n patch({ pending: name, error: null });\n let result: ActionResult<T>;\n try {\n result = await run();\n } catch (error) {\n result = fail(toStoreError(error, { sentSession: SENDS_SESSION.has(name) }));\n }\n if (result.ok) {\n if (store.getSnapshot().pending === name) patch({ pending: null });\n } else {\n failed(name, result.error);\n }\n return result;\n });\n }\n\n function failed(name: string, error: StoreError) {\n const pending = store.getSnapshot().pending;\n patch({ pending: pending === name ? null : pending, error });\n ctx.events.emit({ type: 'error', store: 'auth', action: name, error });\n }\n\n function refuse(name: string, kind: StoreError['kind'], message: string) {\n const error = storeError(kind, message);\n patch({ error });\n ctx.events.emit({ type: 'error', store: 'auth', action: name, error });\n return Promise.resolve(fail(error));\n }\n\n const signedIn = () => store.getSnapshot().status === 'signed-in';\n\n /**\n * The sign-in: token held, login stored, guest session rotated (W32), state and identity set\n * once, then the events. Rotation comes before the events, so their listeners (the cart\n * reloading the merged cart) run in the final identity epoch.\n */\n function signIn(session: SignedInCustomer, via: Via, remember: boolean) {\n const rotated = ctx.hasSession();\n ctx.tokens.setSessionToken(null);\n ctx.records.session.remove();\n ctx.tokens.setCustomerToken(session.token);\n remembered = remember;\n savedAt = Date.now();\n persist(session.customer, session.token, session.rewardPoints);\n patch({\n status: 'signed-in',\n customer: session.customer,\n rewardPoints: session.rewardPoints,\n verification: null,\n pending: null,\n error: null,\n });\n ctx.setIdentity({ kind: 'customer', customerId: session.customer.id });\n if (rotated) ctx.events.emit({ type: 'session:replaced', reason: 'rotated' });\n ctx.events.emit({ type: 'auth:signed-in', customerId: session.customer.id, via });\n }\n\n function persist(customer: CustomerProfile, token: string, rewardPoints: number | null) {\n const record: AuthRecord = { token, customer, rewardPoints, savedAt };\n (remembered ? ctx.records.auth : ctx.records.ephemeralAuth).write(record);\n (remembered ? ctx.records.ephemeralAuth : ctx.records.auth).remove();\n }\n\n /** Logout and expiry: everything about the login goes, the guest session is rotated. */\n function signOut(reason: 'logout' | 'expired') {\n const rotated = ctx.hasSession();\n ctx.tokens.setCustomerToken(null);\n ctx.tokens.setSessionToken(null);\n ctx.records.auth.remove();\n ctx.records.ephemeralAuth.remove();\n ctx.records.session.remove();\n patch({ status: 'signed-out', customer: null, rewardPoints: null, verification: null });\n ctx.setIdentity({ kind: 'guest', customerId: null });\n if (rotated) ctx.events.emit({ type: 'session:replaced', reason: 'rotated' });\n ctx.events.emit({ type: 'auth:signed-out', reason });\n }\n\n // The runtime calls this only for the current token, so five parallel 401s sign out once.\n ctx.hooks.customerExpired = () => signOut('expired');\n\n // An order spent points: the balance becomes a local estimate, kept with the stored login\n // (O9). No endpoint returns the real balance until the backend fixes `/customer/detail` (S63).\n ctx.events.on('checkout:points-spent', ({ points }) => {\n const { status, customer, rewardPoints } = store.getSnapshot();\n const token = ctx.tokens.getCustomerToken();\n if (status !== 'signed-in' || !customer || rewardPoints === null || !token) return;\n const estimate = Math.max(rewardPoints - points, 0);\n persist(customer, token, estimate);\n patch({ rewardPoints: estimate });\n });\n\n /** Login and register: session first (C14, merge), then the request, in one epoch. */\n function authenticate(\n name: 'login' | 'register',\n remember: boolean | undefined,\n send: () => Promise<AuthResult>,\n ): Promise<ActionResult<AuthOutcome>> {\n return action<AuthOutcome>(name, async () => {\n await ctx.ready();\n if (signedIn()) return fail(storeError('validation', 'Already signed in; log out first.'));\n await ctx.ensureSession();\n const answer = await ctx.inEpoch(send);\n if (!answer.current) return fail(SUPERSEDED());\n const result = answer.value;\n if (result.status === 'signed-in') {\n signIn(result.session, name, remember !== false);\n return ok({ status: 'signed-in' as const });\n }\n // No token anywhere for an unverified account (W22).\n patch({ verification: { customerId: result.customerId, contact: result.contact } });\n return ok({ status: 'verification-required' as const, contact: result.contact });\n });\n }\n\n // Actions -----------------------------------------------------------------------------\n\n function login({ remember, ...input }: LoginInput & { remember?: boolean }) {\n return authenticate('login', remember, () => ctx.client.auth.login(input));\n }\n\n function register({ remember, ...input }: RegisterInput & { remember?: boolean }) {\n return authenticate('register', remember, () => ctx.client.auth.register(input));\n }\n\n function verifyOtp(otp: string): Promise<ActionResult<{ status: 'signed-in' }>> {\n const verification = store.getSnapshot().verification;\n if (!verification) {\n return refuse('verify', 'validation', 'There is no verification in progress.');\n }\n return action('verify', async () => {\n await ctx.ready();\n await ctx.ensureSession(); // the guest cart merges here too\n const answer = await ctx.inEpoch(() =>\n ctx.client.auth.verifyOtp({ customerId: verification.customerId, otp }),\n );\n if (!answer.current) return fail(SUPERSEDED());\n if (!answer.value.customer.isActive) {\n // The old modal closed anyway; the step stays open and the token is not kept.\n return fail(storeError('validation', 'The account is still not verified.'));\n }\n signIn(answer.value, 'otp', true);\n return ok({ status: 'signed-in' as const });\n });\n }\n\n function resendOtp(): Promise<ActionResult> {\n const contact = store.getSnapshot().verification?.contact;\n if (!contact) {\n return refuse('resend', 'validation', 'There is no contact to send a new OTP to.');\n }\n return action('resend', async () => {\n await ctx.client.auth.sendOtp(contact);\n return ok(undefined);\n });\n }\n\n function cancelVerification() {\n if (store.getSnapshot().verification) patch({ verification: null });\n }\n\n async function logout(): Promise<ActionResult> {\n await ctx.ready();\n if (signedIn() || ctx.tokens.getCustomerToken() !== null) signOut('logout');\n return ok(undefined);\n }\n\n function loadSettings(): Promise<ActionResult<CustomerSettings>> {\n return action('settings', async () => {\n const settings = await ctx.client.auth.settings();\n patch({ settings });\n return ok(settings);\n });\n }\n\n async function updateProfile(input: UpdateProfileInput): Promise<ActionResult<CustomerProfile>> {\n await ctx.ready();\n const customer = store.getSnapshot().customer;\n if (!signedIn() || !customer) {\n return refuse('profile', 'signed-out', 'Log in to change the profile.');\n }\n return action('profile', async () => {\n const answer = await ctx.inEpoch(() => ctx.client.customer.updateProfile(customer.id, input));\n if (!answer.current) return fail(SUPERSEDED());\n const token = ctx.tokens.getCustomerToken();\n if (token) persist(answer.value, token, store.getSnapshot().rewardPoints);\n patch({ customer: answer.value });\n return ok(answer.value);\n });\n }\n\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe: store.subscribe,\n loadSettings,\n login,\n register,\n verifyOtp,\n resendOtp,\n cancelVerification,\n logout,\n updateProfile,\n };\n}\n","/**\n * The business store (M3 part 2 plan 5.4, Task 9): the business the app resolved, and its\n * settings, theme settings, logos and social links. Each section loads on its own: the old\n * `BusinessProvider` loaded them with one `Promise.all`, so one failure left all of them empty.\n */\nimport type { ThemeSettings } from '../types/business';\nimport { createSerialQueue, createSingleFlight } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore, readOnly, type LoadStatus } from './runtime/store';\nimport type { BusinessSection, BusinessState, BusinessStore } from './types/business';\n\nconst SECTIONS: readonly BusinessSection[] = ['settings', 'themeSettings', 'media', 'socialLinks'];\nconst NO_FEATURES: readonly string[] = Object.freeze([]);\n\ntype Base = Omit<BusinessState, 'currency' | 'themeId' | 'features'>;\n\n/** Adds the derived fields. */\nfunction derive(state: Base): BusinessState {\n return {\n ...state,\n currency: state.settings?.currency ?? null,\n themeId: state.themeSettings?.id ?? null,\n features: state.business?.features ?? NO_FEATURES,\n };\n}\n\n/** `ready` once every section settled (`error` when all failed); never back from `ready`. */\nfunction overall(sections: Record<BusinessSection, LoadStatus>, current: LoadStatus): LoadStatus {\n const values = SECTIONS.map((section) => sections[section]);\n if (values.every((v) => v === 'error')) return 'error';\n if (values.every((v) => v === 'ready' || v === 'error')) return 'ready';\n if (current === 'ready') return 'ready';\n return values.includes('loading') ? 'loading' : 'idle';\n}\n\n/** Starts from `ctx.seeds.business`: seeded sections are `ready` and never requested. */\nexport function createBusinessStore(ctx: StoreContext): BusinessStore {\n const seed = ctx.seeds.business;\n const sections = Object.fromEntries(\n SECTIONS.map((section) => [section, seed?.[section] !== undefined ? 'ready' : 'idle']),\n ) as Record<BusinessSection, LoadStatus>;\n const store = createStore<BusinessState>(\n derive({\n status: overall(sections, 'idle'),\n refreshing: false,\n error: null,\n business: seed?.business ?? null,\n settings: seed?.settings ?? null,\n themeSettings: seed?.themeSettings ?? null,\n media: seed?.media ?? null,\n socialLinks: seed?.socialLinks ?? null,\n sections,\n pending: { themeSettings: false },\n }),\n { onListenerError: ctx.onListenerError },\n );\n\n const fetchers: Record<BusinessSection, () => Promise<unknown>> = {\n settings: () => ctx.client.business.settings(),\n themeSettings: () => ctx.client.business.themeSettings(),\n media: () => ctx.client.business.media(),\n socialLinks: () => ctx.client.business.socialLinks(),\n };\n /** Per section: only the newest request (or a theme settings save) may write it. */\n const generation: Record<BusinessSection, number> = {\n settings: 0,\n themeSettings: 0,\n media: 0,\n socialLinks: 0,\n };\n const flight = createSingleFlight<'load'>();\n const saves = createSerialQueue();\n let loadsRunning = 0;\n let savesWaiting = 0;\n\n function set(next: Base) {\n store.set(derive(next));\n }\n\n function failed(action: string, error: StoreError): ActionResult<never> {\n ctx.events.emit({ type: 'error', store: 'business', action, error });\n return fail(error);\n }\n\n async function run(wanted: readonly BusinessSection[]): Promise<ActionResult> {\n const mine = wanted.map((section) => ++generation[section]);\n loadsRunning += 1;\n const before = store.getSnapshot();\n const starting = { ...before.sections };\n for (const section of wanted) if (starting[section] !== 'ready') starting[section] = 'loading';\n set({\n ...before,\n sections: starting,\n status: overall(starting, before.status),\n refreshing: before.status === 'ready',\n error: null,\n });\n\n const results = await Promise.allSettled(wanted.map((section) => fetchers[section]()));\n loadsRunning -= 1;\n if (ctx.isDisposed()) return fail(storeError('superseded', 'The stores were disposed.'));\n\n const now = store.getSnapshot();\n const next: Base = { ...now, sections: { ...now.sections } };\n const writable = next as unknown as Record<BusinessSection, unknown>;\n const statuses = next.sections as Record<BusinessSection, LoadStatus>;\n let error: StoreError | null = null;\n for (const [i, result] of results.entries()) {\n const section = wanted[i]!;\n if (generation[section] !== mine[i]) continue; // a newer request owns this section\n if (result.status === 'fulfilled') {\n writable[section] = result.value;\n statuses[section] = 'ready';\n } else {\n error = toStoreError(result.reason);\n if (statuses[section] !== 'ready') statuses[section] = 'error';\n }\n }\n const status = overall(statuses, now.status);\n set({ ...next, status, refreshing: loadsRunning > 0 && status === 'ready', error });\n return error ? failed('load', error) : ok(undefined);\n }\n\n return {\n ...readOnly(store),\n load(options = {}) {\n if (options.force) return run(SECTIONS);\n const sectionsNow = store.getSnapshot().sections;\n const missing = SECTIONS.filter((section) => sectionsNow[section] !== 'ready');\n if (missing.length === 0) return Promise.resolve(ok(undefined));\n return flight('load', () => run(missing));\n },\n updateThemeSettings(changes) {\n savesWaiting += 1;\n const s = store.getSnapshot();\n set({ ...s, pending: { themeSettings: true }, error: null });\n return saves(async (): Promise<ActionResult<ThemeSettings>> => {\n let outcome: ActionResult<ThemeSettings>;\n try {\n const saved = await ctx.client.business.updateThemeSettings(changes);\n outcome = ok(saved);\n } catch (error) {\n outcome = fail(toStoreError(error));\n }\n savesWaiting -= 1;\n if (ctx.isDisposed()) return fail(storeError('superseded', 'The stores were disposed.'));\n const now = store.getSnapshot();\n const pending = { themeSettings: savesWaiting > 0 };\n if (!outcome.ok) {\n set({ ...now, pending, error: outcome.error });\n return failed('updateThemeSettings', outcome.error);\n }\n generation.themeSettings += 1; // an older theme settings load must not overwrite this\n const statuses = { ...now.sections, themeSettings: 'ready' as const };\n set({\n ...now,\n themeSettings: outcome.value,\n sections: statuses,\n status: overall(statuses, now.status),\n pending,\n error: null,\n });\n return outcome;\n });\n },\n hasFeature: (name) => store.getSnapshot().features.includes(name),\n };\n}\n","/**\n * The cart store (M3 plan D3; ADR-024, ADR-025). The backend owns the cart and every total\n * (ADR-001): the store shows the backend's cart with the shopper's optimistic changes laid over\n * it (a quantity, a removed line, the order type) and reloads after every change. While a change\n * is not reflected by a reload yet, the totals are the backend's previous ones, flagged\n * `totalsStale` (O12); they are never recomputed here.\n *\n * Concurrency (B5): reloads are latest-wins; mutations go through one serial queue, so the\n * backend sees them one at a time in call order; quantities are coalesced per line; every\n * result is dropped when the shopper changed meanwhile (identity epoch).\n */\nimport type { AddCartItemInput, CartAddressesInput } from '../http/cart';\nimport { GrowupsellApiError } from '../http/errors';\nimport type { Cart, CartLine, DeliveryEstimate, OrderType, TaxDetails } from '../types/cart';\nimport type { PromoCode } from '../types/promotions';\nimport {\n createCoalescer,\n createLatest,\n createSerialQueue,\n type Current,\n} from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreErrorKind,\n} from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport type { CartLinePending, CartPending, CartState, CartStore } from './types/cart';\n\n/** An optimistic change, shown over the backend's cart until a reload that started after it settled. */\ninterface Change<V> {\n value: V;\n settled: boolean;\n}\n\n/** One action call: its epoch, its error handling. */\ninterface Act {\n alive(): boolean;\n fail(error: unknown, patch?: Partial<CartState>): ActionResult<never>;\n refuse(kind: StoreErrorKind, message: string): ActionResult<never>;\n}\n\nconst NO_PENDING: CartPending = {\n adding: [],\n lines: {},\n orderType: false,\n discount: false,\n addresses: false,\n taxDetails: false,\n};\n\nconst INITIAL: CartState = {\n status: 'idle',\n refreshing: false,\n cart: null,\n totalsStale: false,\n pending: NO_PENDING,\n delivery: { status: 'idle', estimate: null, error: null },\n mergeWarning: null,\n error: null,\n};\n\nconst SUPERSEDED = storeError(\n 'superseded',\n 'A newer change, or a change of shopper, replaced this result.',\n);\n\nfunction withLine(\n pending: CartPending,\n lineId: number,\n kind: CartLinePending | null,\n only?: CartLinePending,\n): CartPending {\n if (only && pending.lines[lineId] !== only) return pending;\n if (!kind && !(lineId in pending.lines)) return pending;\n const lines = { ...pending.lines };\n if (kind) lines[lineId] = kind;\n else delete lines[lineId];\n return { ...pending, lines };\n}\n\nfunction withoutOne(list: readonly number[], value: number): readonly number[] {\n const index = list.indexOf(value);\n return index < 0 ? list : [...list.slice(0, index), ...list.slice(index + 1)];\n}\n\nexport function createCartStore(ctx: StoreContext): CartStore {\n const store = createStore<CartState>(INITIAL, { onListenerError: ctx.onListenerError });\n const latest = createLatest();\n const latestQuote = createLatest();\n const serial = createSerialQueue();\n const coalesce = createCoalescer<number>();\n\n /** The last cart the backend sent. */\n let server: Cart | null = null;\n const quantities = new Map<number, Change<number>>();\n const removals = new Map<number, Change<true>>();\n let orderType: Change<OrderType> | null = null;\n /** Lines the backend deleted: a quantity still queued for one is not sent. */\n const gone = new Set<number>();\n /** Signed in, and the customer's cart has not loaded yet. */\n let needsLoad = false;\n /** The guest cart's SKUs at sign-in, checked against the first customer cart (W33). */\n let mergeCheck: readonly number[] | null = null;\n\n // Snapshot -------------------------------------------------------------------------------\n\n let version = 0;\n let memo: { version: number; value: Pick<CartState, 'cart' | 'totalsStale'> } | null = null;\n const touch = () => {\n version++;\n };\n\n /** The backend's cart with the optimistic changes over it (same reference until one changes). */\n function view(): Pick<CartState, 'cart' | 'totalsStale'> {\n if (memo?.version === version) return memo.value;\n const stale = quantities.size > 0 || removals.size > 0 || orderType !== null;\n let value: Pick<CartState, 'cart' | 'totalsStale'> = { cart: server, totalsStale: false };\n if (server && stale) {\n const lines = server.lines\n .filter((line) => !removals.has(line.id))\n .map((line): CartLine => {\n const quantity = quantities.get(line.id)?.value;\n return quantity === undefined || quantity === line.quantity\n ? line\n : { ...line, quantity };\n });\n value = {\n cart: { ...server, lines, type: orderType?.value ?? server.type },\n totalsStale: true,\n };\n }\n memo = { version, value };\n return value;\n }\n\n /** One step = one `set`; nothing is set when nothing changed. */\n function update(patch: Partial<CartState>) {\n const current = store.getSnapshot();\n const keys = Object.keys(patch) as (keyof CartState)[];\n if (keys.every((key) => Object.is(patch[key], current[key]))) return;\n store.set({ ...current, ...patch });\n }\n\n /** `update` with the optimistic view recomputed. */\n const render = (patch: Partial<CartState> = {}) => update({ ...view(), ...patch });\n const pending = () => store.getSnapshot().pending;\n\n function reset(patch: Partial<CartState>) {\n server = null;\n quantities.clear();\n removals.clear();\n orderType = null;\n gone.clear();\n touch();\n store.set({ ...INITIAL, ...patch });\n }\n\n // Actions --------------------------------------------------------------------------------\n\n const epoch = () => ctx.identity.getSnapshot().epoch;\n\n /** Starts an action: clears the previous error (B3, unless `keepError`) and remembers the epoch. */\n function act(name: string, keepError = false): Act {\n const at = epoch();\n const sentSession = ctx.hasSession();\n if (!keepError && store.getSnapshot().error) update({ error: null });\n const alive = () => !ctx.isDisposed() && epoch() === at;\n const self: Act = {\n alive,\n fail(cause, patch = {}) {\n const error = toStoreError(cause, { sentSession });\n // The shopper changed: the new state is not this action's to touch.\n if (!alive()) return fail(error.kind === 'session' ? error : SUPERSEDED);\n if (error.kind === 'superseded') return fail(error);\n update({ ...patch, error });\n ctx.events.emit({ type: 'error', store: 'cart', action: name, error });\n return fail(error);\n },\n refuse: (kind, message) => self.fail(storeError(kind, message)),\n };\n return self;\n }\n\n /**\n * Runs a request for `action` and reports whether its result still belongs to the shopper\n * who started it. A dead session's error is passed on even then (`kind: 'session'`).\n */\n async function guard<T>(action: Act, run: () => Promise<T>): Promise<Current<T>> {\n try {\n const value = await run();\n return action.alive() ? { current: true, value } : { current: false };\n } catch (error) {\n if (action.alive() || toStoreError(error, { sentSession: true }).kind === 'session') {\n throw error;\n }\n return { current: false };\n }\n }\n\n const isCustomer = () => ctx.identity.getSnapshot().kind === 'customer';\n const findLine = (lineId: number) => view().cart?.lines.find((line) => line.id === lineId);\n\n /** Reloads the cart (latest wins). Does not clear the error: mutations call it after failing. */\n async function load(): Promise<ActionResult<Cart | null>> {\n await ctx.ready();\n const action = act('refresh', true);\n if (!isCustomer() && !ctx.hasSession()) {\n // No cart for a visitor who never added anything (W47); older loads are superseded.\n void latest(() => Promise.resolve(null));\n needsLoad = false;\n server = null;\n touch();\n render({ status: 'ready', refreshing: false });\n return ok(null);\n }\n update(store.getSnapshot().status === 'ready' ? { refreshing: true } : { status: 'loading' });\n const settled = settledChanges();\n try {\n const result = await guard(action, () => latest(() => ctx.client.cart.get()));\n if (!result.current || !result.value.current) return fail(SUPERSEDED);\n server = result.value.value;\n for (const forget of settled) forget();\n touch();\n needsLoad = false;\n const missing = checkMerge(server);\n render({ status: 'ready', refreshing: false, ...(missing && { mergeWarning: missing }) });\n if (missing) ctx.events.emit({ type: 'cart:merge-incomplete', ...missing });\n return ok(view().cart);\n } catch (error) {\n // A cart already shown stays shown; without one, the load failed.\n const status = store.getSnapshot().status === 'ready' && server ? 'ready' : 'error';\n return action.fail(error, { status, refreshing: false });\n }\n }\n\n /**\n * After a sign-in, the guest SKUs the merged cart lacks: the backend swallows merge errors\n * (W33). Reported once; never re-added, which could double quantities of a partial merge.\n */\n function checkMerge(cart: Cart): { missingSkuIds: readonly number[] } | null {\n const guestSkus = mergeCheck;\n mergeCheck = null;\n if (!guestSkus) return null;\n const present = new Set(cart.lines.map((line) => line.skuId));\n const missingSkuIds = guestSkus.filter((skuId) => !present.has(skuId));\n return missingSkuIds.length ? { missingSkuIds } : null;\n }\n\n /** Forgets each change that settled before this reload started, once the reload landed. */\n function settledChanges(): Array<() => void> {\n const forget: Array<() => void> = [];\n for (const [map, entries] of [\n [quantities, [...quantities]],\n [removals, [...removals]],\n ] as const) {\n for (const [lineId, change] of entries) {\n if (!change.settled) continue;\n forget.push(() => {\n if ((map as Map<number, unknown>).get(lineId) === change) map.delete(lineId);\n });\n }\n }\n const type = orderType;\n if (type?.settled) {\n forget.push(() => {\n if (orderType === type) orderType = null;\n });\n }\n return forget;\n }\n\n async function refresh(): Promise<ActionResult<Cart | null>> {\n await ctx.ready();\n act('refresh'); // clears the previous error\n return load();\n }\n\n async function add(input: AddCartItemInput): Promise<ActionResult<{ lineId: number }>> {\n await ctx.ready();\n const action = act('add');\n update({ pending: { ...pending(), adding: [...pending().adding, input.skuId] } });\n try {\n if (!isCustomer()) await ctx.ensureSession();\n // The backend adds to a line of the same SKU: no client lookup, no lost increments.\n const result = await guard(action, () => serial(() => ctx.client.cart.addItem(input)));\n if (!result.current) return fail(SUPERSEDED);\n update({ pending: { ...pending(), adding: withoutOne(pending().adding, input.skuId) } });\n await load();\n return ok({ lineId: result.value.lineId });\n } catch (error) {\n return action.fail(error, {\n pending: { ...pending(), adding: withoutOne(pending().adding, input.skuId) },\n });\n }\n }\n\n async function setQuantity(lineId: number, quantity: number): Promise<ActionResult> {\n await ctx.ready();\n if (quantity === 0) return remove(lineId);\n const action = act('setQuantity');\n if (!Number.isInteger(quantity) || quantity < 0) {\n return action.refuse('validation', `Cart quantity must be a whole number: ${quantity}.`);\n }\n const line = findLine(lineId);\n if (!line) return action.refuse('validation', `There is no cart line ${lineId}.`);\n if (line.maxQuantity !== null && quantity > line.maxQuantity) {\n return action.refuse(\n 'validation',\n `At most ${line.maxQuantity} of this item can be ordered.`,\n );\n }\n\n const change: Change<number> = { value: quantity, settled: false };\n quantities.set(lineId, change);\n touch();\n render({ pending: withLine(pending(), lineId, 'quantity') });\n try {\n const result = await guard(action, () =>\n coalesce(lineId, quantity, (value) =>\n serial(async () => {\n if (gone.has(lineId) || removals.has(lineId)) return;\n await ctx.client.cart.setQuantity(lineId, value);\n }),\n ),\n );\n if (!result.current || !result.value.current) return fail(SUPERSEDED);\n change.settled = true;\n update({ pending: withLine(pending(), lineId, null, 'quantity') });\n await load();\n return ok(undefined);\n } catch (error) {\n if (quantities.get(lineId) === change) quantities.delete(lineId);\n touch();\n const failed = action.fail(error, {\n ...view(),\n pending: withLine(pending(), lineId, null, 'quantity'),\n });\n if (action.alive()) await load();\n return failed;\n }\n }\n\n async function remove(lineId: number): Promise<ActionResult> {\n await ctx.ready();\n const action = act('remove');\n if (!findLine(lineId)) return action.refuse('validation', `There is no cart line ${lineId}.`);\n\n const change: Change<true> = { value: true, settled: false };\n removals.set(lineId, change);\n touch();\n render({ pending: withLine(pending(), lineId, 'remove') });\n try {\n const result = await guard(action, () => serial(() => ctx.client.cart.removeItem(lineId)));\n if (!result.current) return fail(SUPERSEDED);\n change.settled = true;\n gone.add(lineId);\n update({ pending: withLine(pending(), lineId, null) });\n await load();\n return ok(undefined);\n } catch (error) {\n // Back where it was: the view keeps the backend's line order.\n if (removals.get(lineId) === change) removals.delete(lineId);\n touch();\n const failed = action.fail(error, { ...view(), pending: withLine(pending(), lineId, null) });\n if (action.alive()) await load();\n return failed;\n }\n }\n\n async function setOrderType(type: OrderType): Promise<ActionResult> {\n await ctx.ready();\n const action = act('setOrderType');\n const cart = view().cart;\n if (!cart) return action.refuse('validation', 'There is no cart yet.');\n if (cart.type === type) return ok(undefined);\n\n const change: Change<OrderType> = { value: type, settled: false };\n orderType = change;\n touch();\n render({ pending: { ...pending(), orderType: true } });\n try {\n const result = await guard(action, () => serial(() => ctx.client.cart.setOrderType(type)));\n if (!result.current) return fail(SUPERSEDED);\n change.settled = true;\n update({ pending: { ...pending(), orderType: false } });\n await load(); // the delivery charge changed: the old code kept stale totals\n return ok(undefined);\n } catch (error) {\n if (orderType === change) orderType = null;\n touch();\n const failed = action.fail(error, { ...view(), pending: { ...pending(), orderType: false } });\n if (action.alive()) await load();\n return failed;\n }\n }\n\n async function setAddresses(input: CartAddressesInput): Promise<ActionResult> {\n await ctx.ready();\n const action = act('setAddresses');\n // The backend crashes for guests (C28): refused before sending.\n if (!isCustomer()) return action.refuse('signed-out', 'Sign in to choose addresses.');\n update({ pending: { ...pending(), addresses: true } });\n try {\n const result = await guard(action, () => serial(() => ctx.client.cart.setAddresses(input)));\n if (!result.current) return fail(SUPERSEDED);\n update({ pending: { ...pending(), addresses: false } });\n await load();\n return ok(undefined);\n } catch (error) {\n return action.fail(error, { pending: { ...pending(), addresses: false } });\n }\n }\n\n async function setTaxDetails(input: TaxDetails): Promise<ActionResult<TaxDetails>> {\n await ctx.ready();\n const action = act('setTaxDetails');\n update({ pending: { ...pending(), taxDetails: true } });\n try {\n // The endpoint needs a guest session even with a login (`HasSessionToken`); an upsert (W45).\n await ctx.ensureSession();\n const result = await guard(action, () => serial(() => ctx.client.cart.setTaxDetails(input)));\n if (!result.current) return fail(SUPERSEDED);\n update({ pending: { ...pending(), taxDetails: false } });\n return ok(result.value);\n } catch (error) {\n return action.fail(error, { pending: { ...pending(), taxDetails: false } });\n }\n }\n\n /** Runs a discount change with `pending.discount` set; guests get a session first (ADR-023 D6). */\n async function discount<T>(\n action: Act,\n run: () => Promise<ActionResult<T>>,\n ): Promise<ActionResult<T>> {\n update({ pending: { ...pending(), discount: true } });\n let result: ActionResult<T>;\n try {\n if (!isCustomer()) await ctx.ensureSession();\n result = await run();\n } catch (error) {\n result = action.fail(error);\n }\n if (action.alive()) update({ pending: { ...pending(), discount: false } });\n return result;\n }\n\n /**\n * Sends one discount update, then reloads the cart whatever happened: the backend removes\n * the other discount before it validates the new one, so even a failed apply changed it (W55).\n */\n async function sendDiscount(action: Act, send: () => Promise<void>): Promise<ActionResult> {\n let sent: Current<void>;\n try {\n sent = await guard(action, () => serial(send));\n } catch (error) {\n const failed = action.fail(error);\n if (action.alive()) await load();\n return failed;\n }\n if (!sent.current) return fail(SUPERSEDED);\n await load();\n return ok(undefined);\n }\n\n async function applyOffer(offerId: number | null): Promise<ActionResult> {\n await ctx.ready();\n const action = act('applyOffer');\n return discount(action, () => sendDiscount(action, () => ctx.client.cart.applyOffer(offerId)));\n }\n\n async function applyPromoCode(code: string | null): Promise<ActionResult<PromoCode | null>> {\n await ctx.ready();\n const action = act('applyPromoCode');\n if (code !== null && !code.trim()) return action.refuse('validation', 'Enter a promo code.');\n return discount(action, async () => {\n if (code === null) {\n const removed = await sendDiscount(action, () => ctx.client.cart.applyPromoCode(null));\n return removed.ok ? ok(null) : removed;\n }\n const found = await guard(action, () => ctx.client.promotions.promoCode(code));\n if (!found.current) return fail(SUPERSEDED);\n const promo = found.value;\n if (!promo) return action.refuse('validation', 'This promo code does not exist.');\n if (promo.status !== 'active') {\n return action.fail(\n storeError('validation', `This promo code is ${promo.status}.`, {\n fieldErrors: { code: [promo.status] },\n }),\n );\n }\n const applied = await sendDiscount(action, () => ctx.client.cart.applyPromoCode(promo.id));\n return applied.ok ? ok(promo) : applied;\n });\n }\n\n async function estimateDelivery(pincode?: string): Promise<ActionResult<DeliveryEstimate>> {\n await ctx.ready();\n const action = act('estimateDelivery');\n const delivery = store.getSnapshot().delivery;\n const refuse = (message: string) => {\n const error = storeError('validation', message);\n update({ delivery: { ...delivery, error } });\n return fail(error);\n };\n const cart = view().cart;\n if (!cart) return refuse('There is no cart yet.');\n if (cart.deliveryChargeType !== 'as_per_delivery_partner') {\n return refuse('This business does not quote delivery charges.');\n }\n update({ delivery: { ...delivery, status: 'loading', error: null } });\n try {\n const result = await guard(action, () =>\n latestQuote(() => ctx.client.cart.deliveryEstimate(cart.id, { pincode })),\n );\n if (!result.current || !result.value.current) return fail(SUPERSEDED);\n const estimate = result.value.value;\n update({ delivery: { status: 'ready', estimate, error: null } });\n await load(); // the backend stored the quote in the cart's totals\n return ok(estimate);\n } catch (error) {\n const failed = action.fail(error);\n if (failed.ok || !action.alive() || failed.error.kind === 'superseded') return failed;\n const { estimate } = store.getSnapshot().delivery;\n update({ delivery: { status: 'error', estimate, error: failed.error } });\n // A refused quote may still have changed the payable (the old cart page kept it).\n if (storedPayable(error)) await load();\n return failed;\n }\n }\n\n function dismissMergeWarning() {\n update({ mergeWarning: null });\n }\n\n async function moveToWishlist(lineId: number): Promise<ActionResult> {\n await ctx.ready();\n const action = act('moveToWishlist');\n if (!isCustomer()) return action.refuse('signed-out', 'Sign in to save items.');\n const skuId = findLine(lineId)?.skuId;\n if (skuId == null) {\n return action.refuse('validation', `Cart line ${lineId} has no item to save.`);\n }\n update({ pending: withLine(pending(), lineId, 'wishlist') });\n const wishlist = ctx.stores.wishlist;\n if (!wishlist.has(skuId)) {\n const added = await wishlist.add(skuId);\n if (!action.alive()) return fail(SUPERSEDED);\n if (!added.ok) {\n // Saved nothing: the line stays in the cart.\n return action.fail(added.error, { pending: withLine(pending(), lineId, null) });\n }\n }\n update({ pending: withLine(pending(), lineId, null) });\n return remove(lineId);\n }\n\n // Wiring ---------------------------------------------------------------------------------\n\n ctx.autoLoad(() => void load());\n ctx.onHydrate((read) => {\n if (read.phase === 'rehydrate') reset({}); // another tab changed the login or session\n });\n ctx.events.on('auth:signed-in', () => {\n // The backend merges the guest cart into the customer's during the login, silently (W33).\n const guestSkus = new Set<number>();\n for (const line of server?.lines ?? []) if (line.skuId !== null) guestSkus.add(line.skuId);\n mergeCheck = guestSkus.size ? [...guestSkus] : null;\n needsLoad = true;\n reset({ status: 'loading' });\n void load();\n });\n ctx.events.on('auth:signed-out', () => {\n // The session was rotated: there is no cart to show, and none is requested.\n needsLoad = false;\n mergeCheck = null;\n reset({ status: 'ready' });\n });\n ctx.events.on('session:replaced', ({ reason }) => {\n if (isCustomer()) {\n // The rotation after a sign-in superseded the customer's first load: start it again.\n if (needsLoad && ctx.tokens.getCustomerToken()) void load();\n return;\n }\n if (reason === 'dead') {\n reset({ status: 'ready' });\n void load();\n }\n });\n ctx.events.on('order:placed', () => {\n // The cart became an order; the next load creates a new cart.\n reset({ status: 'loading' });\n void load();\n });\n\n return {\n ...readOnly(store),\n refresh,\n add,\n setQuantity,\n remove,\n setOrderType,\n setAddresses,\n setTaxDetails,\n applyOffer,\n applyPromoCode,\n estimateDelivery,\n moveToWishlist,\n dismissMergeWarning,\n };\n}\n\n/** A 400 to a delivery quote whose body still carries the payable: the backend stored it. */\nfunction storedPayable(error: unknown): boolean {\n return (\n error instanceof GrowupsellApiError &&\n error.status === 400 &&\n typeof error.body === 'object' &&\n error.body !== null &&\n 'final_payable_amount' in error.body\n );\n}\n","/**\n * The catalog store (M3 part 2 plan 5.2, Task 7): the category tree and the catalog settings,\n * loaded once per app and shared by every screen (the old storefront fetched categories in 12\n * places; LB11: overlapping loads sent duplicate requests).\n */\nimport type { CatalogSettings, CategoryTree } from '../types/catalog';\nimport { createLatest, createSingleFlight } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport { fail, ok, storeError, toStoreError, type ActionResult } from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport type { CatalogState, CatalogStore } from './types/catalog';\n\ntype Part = 'categories' | 'settings';\n\n/**\n * Starts from `ctx.seeds.catalog`: seeded parts count as loaded and are never requested. Loads\n * itself at the first `subscribe()` while still `idle` (option `autoLoad`), like the per-screen\n * stores: adapters never subscribe on the server (ADR-028), so a server render sends nothing.\n */\nexport function createCatalogStore(ctx: StoreContext): CatalogStore {\n const seed = ctx.seeds.catalog;\n const loaded: Record<Part, boolean> = {\n categories: seed?.categories !== undefined,\n settings: seed?.settings !== undefined,\n };\n const complete = () => loaded.categories && loaded.settings;\n const store = createStore<CatalogState>(\n {\n status: complete() ? 'ready' : 'idle',\n refreshing: false,\n error: null,\n categories: seed?.categories ?? [],\n settings: seed?.settings ?? null,\n },\n { onListenerError: ctx.onListenerError },\n );\n const flight = createSingleFlight<'load'>();\n const latest = createLatest();\n\n async function run(parts: readonly Part[]): Promise<ActionResult> {\n store.update((s) =>\n s.status === 'ready'\n ? { ...s, refreshing: true, error: null }\n : { ...s, status: 'loading', error: null },\n );\n const outcome = await latest(() =>\n Promise.allSettled([\n parts.includes('categories') ? ctx.client.catalog.categories() : undefined,\n parts.includes('settings') ? ctx.client.catalog.settings() : undefined,\n ]),\n );\n if (!outcome.current || ctx.isDisposed()) {\n return fail(storeError('superseded', 'A newer catalog load replaced this one.'));\n }\n const [categories, settings] = outcome.value;\n let error = null;\n const next = { ...store.getSnapshot() };\n if (categories.status === 'fulfilled' && parts.includes('categories')) {\n next.categories = categories.value as CategoryTree[];\n loaded.categories = true;\n } else if (categories.status === 'rejected') error = toStoreError(categories.reason);\n if (settings.status === 'fulfilled' && parts.includes('settings')) {\n next.settings = settings.value as CatalogSettings;\n loaded.settings = true;\n } else if (settings.status === 'rejected') error = toStoreError(settings.reason);\n store.set({\n ...next,\n status: complete() ? 'ready' : 'error',\n refreshing: false,\n error,\n });\n if (!error) return ok(undefined);\n ctx.events.emit({ type: 'error', store: 'catalog', action: 'load', error });\n return fail(error);\n }\n\n function load(options: { force?: boolean } = {}): Promise<ActionResult> {\n if (options.force) return run(['categories', 'settings']);\n const missing = (['categories', 'settings'] as const).filter((part) => !loaded[part]);\n if (missing.length === 0) return Promise.resolve(ok(undefined));\n return flight('load', () => run(missing));\n }\n\n return {\n ...readOnly(store),\n subscribe(listener) {\n const unsubscribe = store.subscribe(listener);\n // Only before the first load: a failed load is retried by the app (`load()`), never by a\n // re-subscribing screen.\n if (ctx.config.autoLoad && !ctx.isDisposed() && store.getSnapshot().status === 'idle') {\n void load();\n }\n return unsubscribe;\n },\n load,\n };\n}\n","/**\n * Pure selectors over store snapshots (M3 plan D3–D5). Adapters call them inside their own\n * selector, e.g. React's `useSyncExternalStore(cart.subscribe, () => cartItemCount(cart.getSnapshot()))`,\n * so a component re-renders only when the selected value changes. No state, no requests.\n */\nimport {\n checkoutPreview,\n paymentOptions,\n type CheckoutPreview,\n type PaymentOptions,\n} from '../rules/checkout';\nimport type { Cart, CartLine } from '../types/cart';\nimport type { CartState } from './types/cart';\nimport type { CheckoutState } from './types/checkout';\nimport type { WishlistState } from './types/wishlist';\n\n// Cart -----------------------------------------------------------------------------------------\n\n/** The cart badge: the sum of line quantities (0 without a cart). */\nexport function cartItemCount(state: Pick<CartState, 'cart'>): number {\n return state.cart?.lines.reduce((sum, line) => sum + line.quantity, 0) ?? 0;\n}\n\n/**\n * The cart line of a SKU added without custom data, or null. Lines with custom data (a ring\n * size…) share their SKU with other lines, so address those by `CartLine.id` instead.\n */\nexport function cartLineForSku(state: Pick<CartState, 'cart'>, skuId: number): CartLine | null {\n return state.cart?.lines.find((line) => line.skuId === skuId && line.customData == null) ?? null;\n}\n\n// Wishlist -------------------------------------------------------------------------------------\n\n/** Whether `skuId` (a SKU id, never a product id) is saved in a wishlist snapshot. */\nexport function isInWishlist(state: Pick<WishlistState, 'items'>, skuId: number): boolean {\n return state.items.some((item) => item.sku?.id === skuId);\n}\n\n// Checkout -------------------------------------------------------------------------------------\n\n/**\n * The checkout preview for the current selections (`rules/checkout.ts` `checkoutPreview`):\n * gift cards, then reward points when switched on, against the cart's payable. Null without a\n * cart. Reward points count only with the reward settings loaded.\n *\n * `checkoutPreviewFor(stores.cart.getSnapshot(), stores.checkout.getSnapshot(), stores.auth.getSnapshot())`\n */\nexport function checkoutPreviewFor(\n cart: { cart: Pick<Cart, 'payable' | 'subtotal'> | null },\n checkout: Pick<CheckoutState, 'giftCards' | 'useRewardPoints' | 'rewardSettings'>,\n auth: { rewardPoints: number | null },\n): CheckoutPreview | null {\n if (!cart.cart) return null;\n const { rewardSettings } = checkout;\n return checkoutPreview({\n payable: cart.cart.payable,\n subtotal: cart.cart.subtotal,\n giftCards: checkout.giftCards,\n rewardPoints:\n checkout.useRewardPoints && rewardSettings\n ? { available: auth.rewardPoints ?? 0, currencyPerPoint: rewardSettings.currencyPerPoint }\n : undefined,\n });\n}\n\n/**\n * Which payment options to offer (`rules/checkout.ts` `paymentOptions`). Null until the cart\n * and both checkout settings are loaded. `features`: the business's enabled features\n * (`stores.business.getSnapshot().features`).\n */\nexport function paymentOptionsFor(\n cart: { cart: Pick<Cart, 'type' | 'lines'> | null },\n checkout: Pick<CheckoutState, 'settings' | 'rewardSettings' | 'giftCards'>,\n auth: { rewardPoints: number | null },\n features: readonly string[],\n): PaymentOptions | null {\n if (!cart.cart || !checkout.settings || !checkout.rewardSettings) return null;\n return paymentOptions({\n cart: cart.cart,\n settings: checkout.settings,\n rewardPoints: checkout.rewardSettings,\n availablePoints: auth.rewardPoints ?? 0,\n features,\n giftCardsSelected: checkout.giftCards.length > 0,\n });\n}\n","/**\n * The checkout store (M3 plan D5; ADR-023, ADR-025): gift cards, reward points, placing the\n * order once, and payment confirmation.\n *\n * - The cart belongs to the cart store: checkout only reads `ctx.stores.cart` (its `cart`) and\n * asks it to `refresh()`; it reloads by itself on `order:placed`.\n * - \"Place order\" is single-flight and never retried. After a timeout or a lost answer it reads\n * the order once to learn whether the charge went through.\n * - Every confirmation is single-flight and followed by a read of the order detail: the\n * backend's confirmation answers cannot be trusted (W37, S30).\n * - Gift cards and reward points are never combined (W36). After an order the reward point\n * balance is a local estimate (`checkout:points-spent`, O9).\n * - A pending payment lives in memory only; it is not persisted across reloads (O8). PhonePe's\n * redirect carries the ids, so `confirmPhonePe` works on a fresh page.\n */\nimport type { UploadFile } from '../http/multipart';\nimport type { RazorpayResult } from '../http/payments';\nimport { requiresShippingAddress, type CheckoutPreview } from '../rules/checkout';\nimport type { Cart } from '../types/cart';\nimport type { PendingPayment, PlaceOrderResult } from '../types/checkout';\nimport type { OrderDetail, PaymentStatus } from '../types/orders';\nimport type { GiftCard } from '../types/promotions';\nimport type { StoreContext } from './runtime/context';\nimport { createSingleFlight } from './runtime/concurrency';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport { checkoutPreviewFor, paymentOptionsFor } from './selectors';\nimport type { CheckoutOrder, CheckoutPhase, CheckoutState, CheckoutStore } from './types/checkout';\n\n// The store ------------------------------------------------------------------------------------\n\nconst INITIAL: CheckoutState = {\n settings: null,\n rewardSettings: null,\n settingsStatus: 'idle',\n giftCards: [],\n useRewardPoints: false,\n phase: 'idle',\n order: null,\n pending: { settings: false, giftCard: false },\n error: null,\n};\n\n/** Phases in which an order exists that must not be placed again. */\nconst ORDER_IN_PROGRESS: ReadonlySet<CheckoutPhase> = new Set<CheckoutPhase>([\n 'placing',\n 'awaiting-payment',\n 'confirming',\n 'outcome-unknown',\n]);\n\nconst superseded = () => storeError('superseded', 'The shopper changed while checkout ran.');\n\n/** The payment's status in the order detail (by id), else the order's latest payment's. */\nfunction paymentStatusOf(detail: OrderDetail, paymentId?: number): PaymentStatus | null {\n const entry =\n (paymentId != null && detail.payments.find((p) => p.id === paymentId)) ||\n detail.payments.at(-1);\n return entry?.status ?? null;\n}\n\nexport function createCheckoutStore(ctx: StoreContext): CheckoutStore {\n const store = createStore<CheckoutState>(INITIAL, { onListenerError: ctx.onListenerError });\n const flight = createSingleFlight<'settings' | 'place' | 'confirm'>();\n\n // Other stores, read lazily (never during construction).\n const currentCart = (): Cart | null => ctx.stores.cart.getSnapshot().cart;\n const rewardPoints = (): number | null => ctx.stores.auth.getSnapshot().rewardPoints;\n /** `Business.features` of the business store (resolved by the app, seeded); null when unknown. */\n const features = (): readonly string[] | null =>\n ctx.stores.business.getSnapshot().business?.features ?? null;\n\n /**\n * `ctx.ready()`, without a tick once hydrated: the action's first state change (`placing`,\n * pending flags) is then visible right after the call.\n */\n const whenReady = (): Promise<void> | void =>\n ctx.identity.getSnapshot().kind === 'unknown' ? ctx.ready() : undefined;\n\n const patch = (changes: Partial<CheckoutState>) => store.update((s) => ({ ...s, ...changes }));\n const setPending = (key: keyof CheckoutState['pending'], value: boolean) =>\n store.update((s) => ({ ...s, pending: { ...s.pending, [key]: value } }));\n\n /** Keeps the error in the snapshot and emits it (M3 plan B3); `superseded` is only returned. */\n function failWith(action: string, error: StoreError, changes: Partial<CheckoutState> = {}) {\n if (error.kind !== 'superseded') {\n patch({ ...changes, error });\n ctx.events.emit({ type: 'error', store: 'checkout', action, error });\n } else if (Object.keys(changes).length) {\n patch(changes);\n }\n return fail(error);\n }\n const refuse = (\n action: string,\n message: string,\n kind: 'validation' | 'signed-out' = 'validation',\n ) => failWith(action, storeError(kind, message));\n const startAction = () => {\n if (store.getSnapshot().error) patch({ error: null });\n };\n\n /** Selections never survive a switch to cash on delivery (old: sent `[]`/`false`). */\n let watching = false;\n function watchCart() {\n if (watching) return;\n watching = true;\n const unsubscribe = ctx.stores.cart.subscribe(() => {\n const s = store.getSnapshot();\n if (currentCart()?.type === 'cod' && (s.giftCards.length > 0 || s.useRewardPoints)) {\n patch({ giftCards: [], useRewardPoints: false });\n }\n });\n ctx.onDispose(unsubscribe);\n }\n\n // A previous shopper's checkout never shows for the next one.\n ctx.events.on('auth:signed-out', () => {\n const { settings, rewardSettings, settingsStatus } = store.getSnapshot();\n store.set({ ...INITIAL, settings, rewardSettings, settingsStatus });\n });\n\n function preview(): CheckoutPreview | null {\n return checkoutPreviewFor({ cart: currentCart() }, store.getSnapshot(), {\n rewardPoints: rewardPoints(),\n });\n }\n\n // Settings -----------------------------------------------------------------------------------\n\n function loadSettings(): Promise<ActionResult> {\n return flight('settings', async () => {\n startAction();\n store.update((s) => ({\n ...s,\n settingsStatus: s.settingsStatus === 'ready' ? 'ready' : 'loading',\n pending: { ...s.pending, settings: true },\n }));\n try {\n await ctx.ready();\n const [settings, rewardSettings] = await Promise.all([\n ctx.client.checkout.settings(),\n ctx.client.promotions.rewardPointSettings(),\n ]);\n store.update((s) => ({\n ...s,\n settings,\n rewardSettings,\n settingsStatus: 'ready',\n pending: { ...s.pending, settings: false },\n }));\n return ok(undefined);\n } catch (error) {\n setPending('settings', false);\n const failed = toStoreError(error);\n return failWith('loadSettings', failed, {\n settingsStatus: store.getSnapshot().settingsStatus === 'ready' ? 'ready' : 'error',\n });\n }\n });\n }\n\n // Gift cards and reward points ----------------------------------------------------------------\n\n /** Why a gift card cannot be added now, or null. */\n function giftCardRefusal(): string | null {\n const s = store.getSnapshot();\n if (s.useRewardPoints) {\n return 'Gift cards and reward points cannot be combined; turn reward points off first.';\n }\n if (currentCart()?.type === 'cod') return 'Gift cards cannot pay a cash-on-delivery order.';\n if (s.giftCards.length > 0 && preview()?.toPay === 0) {\n return 'The gift cards already pay the whole order.';\n }\n return null;\n }\n\n async function addGiftCard(input: {\n code: string;\n pin: string;\n }): Promise<ActionResult<GiftCard>> {\n await ctx.ready();\n startAction();\n const code = input.code?.trim() ?? '';\n const pin = input.pin?.trim() ?? '';\n if (!code || !pin) return refuse('addGiftCard', 'Enter the gift card code and PIN.');\n const held = store.getSnapshot().giftCards;\n if (held.some((c) => c.code.toUpperCase() === code.toUpperCase())) {\n return refuse('addGiftCard', 'This gift card is already applied.');\n }\n const refusal = giftCardRefusal();\n if (refusal) return refuse('addGiftCard', refusal);\n watchCart();\n\n setPending('giftCard', true);\n let card: GiftCard;\n try {\n const result = await ctx.inEpoch(() => ctx.client.promotions.validateGiftCard({ code, pin }));\n if (!result.current) {\n setPending('giftCard', false);\n return fail(superseded());\n }\n card = result.value;\n } catch (error) {\n setPending('giftCard', false);\n return failWith('addGiftCard', toStoreError(error));\n }\n setPending('giftCard', false);\n // Checked again: the state may have changed while the card was validated.\n if (store.getSnapshot().giftCards.some((c) => c.id === card.id)) {\n return refuse('addGiftCard', 'This gift card is already applied.');\n }\n const late = giftCardRefusal();\n if (late) return refuse('addGiftCard', late);\n store.update((s) => ({ ...s, giftCards: [...s.giftCards, card] }));\n return ok(card);\n }\n\n function removeGiftCard(giftCardId: number): void {\n store.update((s) =>\n s.giftCards.some((c) => c.id === giftCardId)\n ? { ...s, giftCards: s.giftCards.filter((c) => c.id !== giftCardId) }\n : s,\n );\n }\n\n function setUseRewardPoints(use: boolean): ActionResult {\n startAction();\n const s = store.getSnapshot();\n if (!use) {\n if (s.useRewardPoints) patch({ useRewardPoints: false });\n return ok(undefined);\n }\n if (s.giftCards.length > 0) {\n return refuse(\n 'setUseRewardPoints',\n 'Gift cards and reward points cannot be combined; remove the gift cards first.',\n );\n }\n const cart = currentCart();\n if (!cart) return refuse('setUseRewardPoints', 'The cart is not loaded.');\n if (cart.type === 'cod') {\n return refuse('setUseRewardPoints', 'Reward points cannot pay a cash-on-delivery order.');\n }\n if (!s.settings || !s.rewardSettings) {\n return refuse('setUseRewardPoints', 'Load the checkout settings first.');\n }\n // Unknown features (no business loaded or seeded) do not block: the backend decides.\n const options = paymentOptionsFor(\n { cart },\n s,\n { rewardPoints: rewardPoints() },\n features() ?? ['giftcard', 'reward-point'],\n );\n if (!options?.rewardPoints) {\n return refuse('setUseRewardPoints', 'Reward points cannot be used for this order.');\n }\n watchCart();\n patch({ useRewardPoints: true });\n return ok(undefined);\n }\n\n // Placing the order ---------------------------------------------------------------------------\n\n /** After the order left `cart`: selections cleared, events emitted (state first). */\n function orderPlaced(order: CheckoutOrder, pointsUsed: number, payment: 'none' | 'required') {\n store.update((s) => ({\n ...s,\n phase: payment === 'none' ? 'placed' : 'awaiting-payment',\n order,\n giftCards: [],\n useRewardPoints: false,\n error: null,\n }));\n if (pointsUsed > 0) ctx.events.emit({ type: 'checkout:points-spent', points: pointsUsed });\n ctx.events.emit({ type: 'order:placed', orderId: order.orderId, payment });\n }\n\n async function place(): Promise<ActionResult<PlaceOrderResult>> {\n const ready = whenReady();\n if (ready) await ready;\n startAction();\n const s = store.getSnapshot();\n if (ctx.identity.getSnapshot().kind !== 'customer') {\n return refuse('placeOrder', 'Log in to place the order.', 'signed-out');\n }\n if (ORDER_IN_PROGRESS.has(s.phase)) {\n return refuse('placeOrder', 'This order is already placed; finish or check its payment.');\n }\n const cart = currentCart();\n if (!cart || cart.lines.length === 0) return refuse('placeOrder', 'The cart is empty.');\n if (s.order && s.order.orderId === cart.id) {\n return refuse('placeOrder', 'This cart has already been placed as an order.');\n }\n if (requiresShippingAddress(cart.lines) && cart.shippingAddressId == null) {\n return refuse('placeOrder', 'Choose a shipping address.');\n }\n if (cart.type === 'cod' && (s.giftCards.length > 0 || s.useRewardPoints)) {\n return refuse('placeOrder', 'Gift cards and reward points cannot pay cash on delivery.');\n }\n const pointsUsed = s.useRewardPoints ? (preview()?.pointsUsed ?? 0) : 0;\n const giftCardIds = s.giftCards.map((c) => c.id);\n const useRewardPoints = s.useRewardPoints;\n\n patch({ phase: 'placing' });\n let outcome;\n try {\n outcome = await ctx.inEpoch(() =>\n ctx.client.checkout.placeOrder(cart.id, { giftCardIds, useRewardPoints }),\n );\n } catch (error) {\n const failed = toStoreError(error);\n if (failed.kind === 'timeout' || failed.kind === 'network') {\n return afterUnknownOutcome(cart.id, failed, pointsUsed);\n }\n return failWith('placeOrder', failed, { phase: 'idle' });\n }\n if (!outcome.current) return failWith('placeOrder', superseded(), { phase: 'idle' });\n const result = outcome.value;\n if (result.status === 'placed') {\n orderPlaced(\n { orderId: result.orderId, payment: null, paymentStatus: null },\n pointsUsed,\n 'none',\n );\n } else {\n orderPlaced(\n { orderId: result.orderId, payment: result.payment, paymentStatus: null },\n pointsUsed,\n 'required',\n );\n }\n return ok(result);\n }\n\n /**\n * The charge may or may not have gone through: read the order once. Never charged again\n * automatically (the backend does not detect a repeated charge).\n */\n async function afterUnknownOutcome(\n cartId: number,\n cause: StoreError,\n pointsUsed: number,\n ): Promise<ActionResult<PlaceOrderResult>> {\n patch({ phase: 'outcome-unknown' });\n let read;\n try {\n read = await ctx.inEpoch(() => ctx.client.orders.detail(cartId));\n } catch {\n return failWith('placeOrder', cause, { phase: 'outcome-unknown' });\n }\n if (!read.current) return failWith('placeOrder', superseded(), { phase: 'idle' });\n const detail = read.value;\n if (detail.status === 'cart') return failWith('placeOrder', cause, { phase: 'idle' });\n // Placed. The pending payment (SDK keys) is not in the detail: the app shows the order.\n orderPlaced(\n { orderId: cartId, payment: null, paymentStatus: paymentStatusOf(detail) },\n pointsUsed,\n 'none',\n );\n return ok({ status: 'placed', orderId: cartId });\n }\n\n // Payments ------------------------------------------------------------------------------------\n\n /**\n * Checks the phase and method, then runs one confirmation (single-flight across all\n * methods), reads the order detail whatever the confirmation answered, and keeps its status.\n */\n function confirm(\n action: string,\n method: string | null,\n send: (payment: PendingPayment) => Promise<unknown>,\n options: { endPlaced?: boolean } = {},\n ): Promise<ActionResult<PaymentStatus>> {\n return flight('confirm', async () => {\n const ready = whenReady();\n if (ready) await ready;\n startAction();\n const s = store.getSnapshot();\n const order = s.order;\n if (s.phase !== 'awaiting-payment' || !order?.payment) {\n return refuse(action, 'There is no payment waiting for confirmation.');\n }\n if (method && order.payment.method !== method) {\n return refuse(action, `The pending payment is not a ${method} payment.`);\n }\n return runConfirmation(\n action,\n order.orderId,\n order.payment,\n () => send(order.payment!),\n options,\n );\n });\n }\n\n async function runConfirmation(\n action: string,\n orderId: number,\n payment: PendingPayment | null,\n send: () => Promise<unknown>,\n options: { endPlaced?: boolean; paymentId?: number } = {},\n ): Promise<ActionResult<PaymentStatus>> {\n const paymentId = options.paymentId ?? payment?.id;\n patch({\n phase: 'confirming',\n order: { orderId, payment, paymentStatus: store.getSnapshot().order?.paymentStatus ?? null },\n });\n let sendError: StoreError | null = null;\n try {\n const sent = await ctx.inEpoch(send);\n if (!sent.current) return failWith(action, superseded());\n } catch (error) {\n sendError = toStoreError(error);\n }\n // Always read the order: the confirmation's answer is only a hint (W37, S30).\n let status: PaymentStatus | null;\n try {\n const read = await ctx.inEpoch(() => ctx.client.orders.detail(orderId));\n if (!read.current) return failWith(action, superseded());\n status = paymentStatusOf(read.value, paymentId);\n } catch (error) {\n return failWith(action, sendError ?? toStoreError(error), { phase: 'awaiting-payment' });\n }\n const done = status === 'paid' || (options.endPlaced === true && sendError == null);\n store.update((st) => ({\n ...st,\n phase: done ? 'placed' : 'awaiting-payment',\n order: { orderId, payment, paymentStatus: status },\n }));\n if (done) {\n ctx.events.emit({ type: 'payment:confirmed', orderId, paymentStatus: status ?? 'unpaid' });\n return ok(status ?? 'unpaid');\n }\n if (sendError) return failWith(action, sendError);\n return ok(status ?? 'unpaid');\n }\n\n function confirmPhonePe(input: { paymentId: number; orderId: number }) {\n return flight('confirm', async () => {\n const ready = whenReady();\n if (ready) await ready;\n startAction();\n const s = store.getSnapshot();\n if (s.phase === 'placing') {\n return refuse('confirmPhonePe', 'The order is still being placed.');\n }\n const known = s.order?.payment?.id === input.paymentId ? s.order.payment : null;\n return runConfirmation(\n 'confirmPhonePe',\n input.orderId,\n known,\n () => ctx.client.payments.confirmPhonePe(input.paymentId),\n { paymentId: input.paymentId },\n );\n });\n }\n\n function reset(): void {\n const { settings, rewardSettings, settingsStatus } = store.getSnapshot();\n store.set({ ...INITIAL, settings, rewardSettings, settingsStatus });\n }\n\n return {\n ...readOnly(store),\n loadSettings,\n addGiftCard,\n removeGiftCard,\n setUseRewardPoints,\n placeOrder: () => flight('place', place),\n confirmStripe: () =>\n confirm('confirmStripe', 'stripe', (payment) => ctx.client.payments.confirmStripe(payment)),\n confirmRazorpay: (result: RazorpayResult) =>\n confirm('confirmRazorpay', 'razorpay', (payment) =>\n ctx.client.payments.confirmRazorpay(payment, result),\n ),\n confirmPhonePe,\n submitTransferProof: (screenshot: UploadFile) =>\n confirm(\n 'submitTransferProof',\n 'direct-transfer',\n (payment) => ctx.client.payments.submitTransferProof(payment.id, screenshot),\n { endPlaced: true },\n ),\n paymentDismissed: () => {\n // Keep `awaiting-payment` and the same payment: \"Pay\" retries it, never places again.\n },\n reset,\n };\n}\n","/**\n * The product listing store (M3 part 2 plan 5.3, Task 8): one per listing screen, created with\n * `stores.createListing(input)`. Criteria and their URL form come from `rules/listing.ts`;\n * category expansion from `rules/catalog.ts` over the catalog store's tree (W71).\n */\nimport { categoryAndDescendants } from '../rules/catalog';\nimport {\n DEFAULT_LISTING_CRITERIA,\n LISTING_PAGE_SIZE,\n listingQuery,\n listingSearchOptions,\n parseListingQuery,\n withCategory,\n} from '../rules/listing';\nimport type { ListingCriteria } from '../types/listing';\nimport type { Page, ProductListItem } from '../types/product';\nimport { createLatest } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore } from './runtime/store';\nimport type { ListingFacets, ListingInput, ListingState, ListingStore } from './types/listing';\n\n/** Microtasks through `globalThis`: `commerce` compiles without DOM or Node types (ADR-009). */\ninterface Runtime {\n queueMicrotask(task: () => void): void;\n}\nconst runtime = globalThis as unknown as Runtime;\n\ntype Base = Omit<ListingState, 'pageCount' | 'query'>;\n\nfunction derive(base: Base): ListingState {\n return {\n ...base,\n pageCount: Math.max(1, Math.ceil(base.total / base.pageSize)),\n query: listingQuery(base.criteria),\n };\n}\n\nconst sameCriteria = (a: ListingCriteria, b: ListingCriteria) =>\n JSON.stringify(a) === JSON.stringify(b);\n\nconst toggle = <T>(list: readonly T[], value: T): T[] =>\n list.includes(value) ? list.filter((v) => v !== value) : [...list, value];\n\nconst emptyFacets: ListingFacets = {\n status: 'idle',\n price: null,\n specifications: [],\n brands: [],\n variantGroups: [],\n};\n\nfunction initialCriteria(input: ListingInput): ListingCriteria {\n const criteria = parseListingQuery(input.query ?? {});\n if (criteria.categoryId === null && input.categoryId != null) {\n return { ...criteria, categoryId: input.categoryId };\n }\n return criteria;\n}\n\n/**\n * Creates the store of one listing screen. Creating it does no I/O: the first search starts at\n * the first `subscribe()` (the screen mounting) or the first action. Every search waits for\n * hydration and the guest session (ADR-019 point 2: without one the backend lists drafts, W1).\n */\nexport function createListingStore(ctx: StoreContext, input: ListingInput = {}): ListingStore {\n const pageSize =\n input.pageSize && Number.isInteger(input.pageSize) && input.pageSize > 0\n ? input.pageSize\n : LISTING_PAGE_SIZE;\n const store = createStore<ListingState>(\n derive({\n criteria: initialCriteria(input),\n status: 'idle',\n refreshing: false,\n items: [],\n total: 0,\n pageSize,\n error: null,\n facets: emptyFacets,\n }),\n { onListenerError: ctx.onListenerError },\n );\n const searches = createLatest();\n const facetLoads = createLatest();\n let disposed = false;\n let started = false;\n let scheduled = false;\n /** The category the facets were loaded for; `undefined` before the first load. */\n let facetsFor: number | null | undefined;\n\n /** `derive` recomputes `pageCount` and `query` from the rest of the snapshot. */\n const set = (changes: Partial<Base>) => {\n if (!disposed) store.set(derive({ ...store.getSnapshot(), ...changes }));\n };\n\n // Categories ---------------------------------------------------------------------------\n\n /**\n * The category and all its descendants, from the catalog store's tree (loaded once, shared\n * by every screen). When the tree failed to load the category is missing from it, so this is\n * the category alone (L2).\n */\n async function expand(categoryId: number): Promise<number[]> {\n const { catalog } = ctx.stores;\n await catalog.load();\n return categoryAndDescendants(catalog.getSnapshot().categories, categoryId);\n }\n\n // Search -------------------------------------------------------------------------------\n\n type Attempt = { page: Page<ProductListItem> } | { error: StoreError };\n\n async function attempt(criteria: ListingCriteria): Promise<Attempt & { epochChanged: boolean }> {\n await ctx.ready();\n const epoch = ctx.identity.getSnapshot().epoch;\n const changed = () => ctx.identity.getSnapshot().epoch !== epoch;\n try {\n await ctx.ensureSession();\n const ids = criteria.categoryId === null ? [] : await expand(criteria.categoryId);\n const page = await ctx.client.products.search(listingSearchOptions(criteria, ids, pageSize));\n return { page, epochChanged: changed() };\n } catch (caught) {\n return { error: toStoreError(caught, { sentSession: true }), epochChanged: changed() };\n }\n }\n\n /** One search; when the shopper's session was replaced meanwhile, it is run once more. */\n async function fetchPage(criteria: ListingCriteria): Promise<Page<ProductListItem>> {\n let result = await attempt(criteria);\n if (result.epochChanged && !disposed) result = await attempt(criteria);\n if ('error' in result) throw result.error;\n return result.page;\n }\n\n async function search(): Promise<ActionResult> {\n if (disposed) return fail(storeError('superseded', 'listing: the store was disposed.'));\n const { criteria, status } = store.getSnapshot();\n set(status === 'ready' ? { refreshing: true } : { status: 'loading', refreshing: false });\n try {\n const result = await searches(() => fetchPage(criteria));\n if (!result.current || disposed) {\n return fail(storeError('superseded', 'listing: a newer search replaced this one.'));\n }\n set({\n status: 'ready',\n refreshing: false,\n items: result.value.items,\n total: result.value.total,\n error: null,\n });\n return ok(undefined);\n } catch (caught) {\n const error = toStoreError(caught);\n if (disposed) return fail(error);\n const shown = store.getSnapshot().status === 'ready';\n set(shown ? { refreshing: false, error } : { status: 'error', refreshing: false, error });\n ctx.events.emit({ type: 'error', store: 'listing', action: 'search', error });\n return fail(error);\n }\n }\n\n // Facets -------------------------------------------------------------------------------\n\n async function loadFacets(categoryId: number | null): Promise<void> {\n facetsFor = categoryId;\n set({\n facets: {\n ...(categoryId === null ? emptyFacets : store.getSnapshot().facets),\n status: 'loading',\n },\n });\n const result = await facetLoads(async () => {\n const ids = categoryId === null ? [] : await expand(categoryId);\n return Promise.allSettled([\n ctx.client.products.filterConfig(categoryId === null ? {} : { categoryId }),\n categoryId === null ? [] : ctx.client.catalog.brands({ categoryIds: ids }),\n categoryId === null ? [] : ctx.client.products.variantFilters(ids),\n ] as const);\n });\n if (!result.current || disposed) return;\n const [config, brands, variants] = result.value;\n const failed = [config, brands, variants].find((r) => r.status === 'rejected');\n const facets: ListingFacets = {\n status: failed ? 'error' : 'ready',\n price: config.status === 'fulfilled' ? config.value.price : null,\n specifications: config.status === 'fulfilled' ? config.value.specifications : [],\n brands: brands.status === 'fulfilled' ? brands.value : [],\n variantGroups: variants.status === 'fulfilled' ? variants.value : [],\n };\n if (failed) {\n ctx.events.emit({\n type: 'error',\n store: 'listing',\n action: 'facets',\n error: toStoreError(failed.reason),\n });\n }\n // Specification selections the category no longer offers are dropped (L8).\n const { criteria } = store.getSnapshot();\n if (config.status === 'fulfilled' && criteria.specifications.length > 0) {\n const offered = new Set(config.value.specifications.map((s) => s.id));\n const kept = criteria.specifications.filter((s) => offered.has(s.id));\n if (kept.length !== criteria.specifications.length) {\n set({ facets, criteria: { ...criteria, specifications: kept, page: 1 } });\n schedule();\n return;\n }\n }\n set({ facets });\n }\n\n // Scheduling ---------------------------------------------------------------------------\n\n function run(): Promise<ActionResult> {\n started = true;\n const { criteria, facets } = store.getSnapshot();\n if (facetsFor === undefined || facetsFor !== criteria.categoryId || facets.status === 'error') {\n void loadFacets(criteria.categoryId);\n }\n return search();\n }\n\n /** Batches the changes of one tick into one search. */\n function schedule() {\n started = true;\n if (scheduled || disposed) return;\n scheduled = true;\n runtime.queueMicrotask(() => {\n scheduled = false;\n if (!disposed) void run();\n });\n }\n\n /** Applies new criteria (one `set`) and schedules a search; a new category clears the list (L4). */\n function change(next: ListingCriteria) {\n if (disposed) return;\n const { criteria } = store.getSnapshot();\n if (sameCriteria(next, criteria)) return;\n if (next.categoryId !== criteria.categoryId) {\n set({\n criteria: next,\n items: [],\n total: 0,\n status: 'loading',\n refreshing: false,\n error: null,\n });\n } else {\n set({ criteria: next });\n }\n schedule();\n }\n\n const filter = (changes: Partial<ListingCriteria>) =>\n change({ ...store.getSnapshot().criteria, ...changes, page: 1 });\n\n // Actions ------------------------------------------------------------------------------\n\n const criteria = () => store.getSnapshot().criteria;\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n unregister();\n }\n const unregister = ctx.onDispose(dispose);\n\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe(listener) {\n if (disposed) return () => {};\n const unsubscribe = store.subscribe(() => {\n if (!disposed) listener();\n });\n if (!started) schedule();\n return unsubscribe;\n },\n setCategory: (id) => change(withCategory(criteria(), id)),\n setSearch: (text) => filter({ search: text?.trim() || null }),\n toggleBrand: (id) =>\n filter({ brandIds: toggle(criteria().brandIds, id).sort((a, b) => a - b) }),\n toggleVariant: (label) => filter({ variantLabels: toggle(criteria().variantLabels, label) }),\n toggleSpecification(id, value) {\n const current = criteria().specifications;\n const found = current.find((s) => s.id === id);\n const specifications = found\n ? current\n .map((s) => (s.id === id ? { id, values: toggle(s.values, value) } : s))\n .filter((s) => s.values.length > 0)\n : [...current, { id, values: [value] }];\n filter({ specifications });\n },\n setPriceRange(min, max) {\n const [minPrice, maxPrice] =\n min !== null && max !== null && min > max ? [max, min] : [min, max];\n filter({ minPrice, maxPrice });\n },\n setMinDiscount: (percent) => filter({ minDiscountPercent: percent }),\n setMinRating: (rating) => filter({ minRating: rating }),\n setSort: (sortBy) => filter({ sortBy }),\n setPage(page) {\n if (Number.isInteger(page) && page >= 1) change({ ...criteria(), page });\n },\n clearFilters() {\n const { categoryId, search, sortBy } = criteria();\n change({ ...DEFAULT_LISTING_CRITERIA, categoryId, search, sortBy });\n },\n applyQuery: (query) => change(parseListingQuery(query)),\n retry: () => (disposed ? search() : run()),\n dispose,\n };\n}\n","/**\n * The product page store (M3 part 2 plan 5.1, Task 6): one per product screen, created with\n * `stores.createProductDetail(input)`. Selection, SKU, price, images and specifications come\n * from the M2 rules; the store only holds the product and the selection.\n */\nimport { formatSelectedVariants } from '../rules/listing';\nimport { productPricing } from '../rules/pricing';\nimport {\n defaultSelection,\n isSelectionComplete,\n resolveSku,\n selectOption,\n variantChoices,\n} from '../rules/sku';\nimport { imagesFor } from '../rules/content';\nimport { specificationsFor } from '../rules/specifications';\nimport type { ProductDetail } from '../types/product';\nimport { createLatest } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport { fail, ok, storeError, toStoreError, type ActionResult } from './runtime/errors';\nimport { createStore } from './runtime/store';\nimport type {\n ProductDetailInput,\n ProductDetailState,\n ProductDetailStore,\n} from './types/productDetail';\n\ntype Base = Pick<\n ProductDetailState,\n 'productId' | 'status' | 'refreshing' | 'product' | 'error' | 'selection'\n>;\n\n/** Everything the snapshot derives from the product and the selection, in one place. */\nfunction derive(base: Base): ProductDetailState {\n const { product, selection } = base;\n if (!product) {\n return {\n ...base,\n sku: null,\n price: null,\n mrp: null,\n discountPercent: 0,\n complete: false,\n purchasable: false,\n choices: [],\n specifications: [],\n images: [],\n selectedVariantsParam: formatSelectedVariants(selection),\n };\n }\n const complete = isSelectionComplete(product.variantGroups, selection);\n const sku = complete ? resolveSku(product.skus, selection) : null;\n const pricing = sku ? productPricing(sku) : null;\n const scope = { skuId: sku?.id ?? null, variantIds: selection };\n return {\n ...base,\n sku,\n price: pricing?.price ?? null,\n mrp: pricing?.compareAtPrice ?? null,\n discountPercent: pricing?.discountPercent ?? 0,\n complete,\n purchasable: sku !== null && sku.active && sku.stockQty > 0,\n choices: variantChoices(product, selection),\n specifications: specificationsFor(product.specifications, scope),\n images: imagesFor(product.images, scope),\n selectedVariantsParam: formatSelectedVariants(selection),\n };\n}\n\n/**\n * The selection after a (re)load: the current one while it still names a sellable SKU, else\n * the default with it as the preference (`defaultSelection` does both).\n */\nfunction selectionFor(product: ProductDetail, current: readonly number[]): number[] {\n return defaultSelection(product, current);\n}\n\n/**\n * Creates the store of one product page. Creating it does no I/O: the first load starts at the\n * first `subscribe()` (the screen mounting) or `reload()`. With `initial` (server data) the\n * product is shown at once and that first load is a background refresh.\n */\nexport function createProductDetailStore(\n ctx: StoreContext,\n input: ProductDetailInput,\n): ProductDetailStore {\n const { productId, initial } = input;\n const preferred = [...(input.selectedVariantIds ?? [])];\n const store = createStore<ProductDetailState>(\n derive({\n productId,\n status: initial ? 'ready' : 'idle',\n refreshing: false,\n product: initial ?? null,\n error: null,\n selection: initial ? defaultSelection(initial, preferred) : [],\n }),\n { onListenerError: ctx.onListenerError },\n );\n const latest = createLatest();\n let disposed = false;\n let started = false;\n\n const base = (): Base => {\n const { productId, status, refreshing, product, error, selection } = store.getSnapshot();\n return { productId, status, refreshing, product, error, selection };\n };\n const set = (changes: Partial<Base>) => {\n if (!disposed) store.set(derive({ ...base(), ...changes }));\n };\n\n async function reload(): Promise<ActionResult> {\n started = true;\n if (disposed) return fail(storeError('superseded', 'productDetail: the store was disposed.'));\n const shown = store.getSnapshot().product !== null;\n set(shown ? { refreshing: true } : { status: 'loading', error: null });\n try {\n const result = await latest(() => ctx.client.products.detail(productId));\n if (!result.current || disposed) {\n return fail(storeError('superseded', 'productDetail: a newer load replaced this one.'));\n }\n const product = result.value;\n const current = store.getSnapshot();\n set({\n status: 'ready',\n refreshing: false,\n error: null,\n product,\n selection: selectionFor(product, current.product ? current.selection : preferred),\n });\n return ok(undefined);\n } catch (caught) {\n const error = toStoreError(caught);\n if (disposed) return fail(error);\n set(shown ? { refreshing: false, error } : { status: 'error', refreshing: false, error });\n ctx.events.emit({ type: 'error', store: 'productDetail', action: 'reload', error });\n return fail(error);\n }\n }\n\n function select(groupId: number, optionId: number): ActionResult {\n const { product, selection } = store.getSnapshot();\n const group = product?.variantGroups.find((g) => g.id === groupId);\n if (!group?.options.some((option) => option.id === optionId)) {\n return fail(\n storeError('validation', `productDetail: group ${groupId} has no option ${optionId}.`),\n );\n }\n set({ selection: selectOption(product!.variantGroups, selection, optionId) });\n return ok(undefined);\n }\n\n function dispose() {\n if (disposed) return;\n disposed = true;\n unregister();\n }\n const unregister = ctx.onDispose(dispose);\n\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe(listener) {\n if (disposed) return () => {};\n const unsubscribe = store.subscribe(() => {\n if (!disposed) listener();\n });\n if (!started) void reload();\n return unsubscribe;\n },\n select,\n reload,\n dispose,\n };\n}\n","/**\n * The referral store (M3 part 2 plan 5.6, Task 11; ADR-025 D2). The old storefront kept the\n * code in `sessionStorage` (gone when the tab closed, nothing on phones) and never cleared it\n * after sign-up. Now: the injected storage, 7 days from capture (`referralTtlMs`), last\n * capture wins, cleared after a sign-up.\n */\nimport type { StoreContext } from './runtime/context';\nimport { fail, ok, storeError } from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport type { ReferralState, ReferralStore } from './types/referral';\n\n/** The backend's `ReferralLink.code` is at most 64 characters. */\nconst MAX_LENGTH = 64;\n\ninterface ReferralRecord {\n code: string;\n capturedAt: number;\n}\n\nfunction isReferralRecord(raw: unknown): raw is ReferralRecord {\n if (!raw || typeof raw !== 'object') return false;\n const r = raw as Partial<ReferralRecord>;\n return (\n typeof r.code === 'string' &&\n r.code.trim() !== '' &&\n r.code.length <= MAX_LENGTH &&\n typeof r.capturedAt === 'number' &&\n Number.isFinite(r.capturedAt)\n );\n}\n\n/**\n * Record `gs.<businessId>.referral` in the general `storage`, read at hydration. A capture or\n * clear made before the read finished wins over what was stored.\n */\nexport function createReferralStore(\n ctx: StoreContext,\n options: { ttlMs?: number } = {},\n): ReferralStore {\n // Default: the `referralTtlMs` option, 7 days unless set (D2).\n const ttlMs = options.ttlMs ?? ctx.config.referralTtlMs;\n const record = ctx.persisted('referral', 1, isReferralRecord);\n const store = createStore<ReferralState>(\n { status: 'idle', code: null, capturedAt: null },\n { onListenerError: ctx.onListenerError },\n );\n /** Increases on every capture and clear: a read that started before one is stale. */\n let changes = 0;\n /** The read of the stored code started at hydration; actions resolve after it. */\n let reading: Promise<void> = Promise.resolve();\n\n const expired = (capturedAt: number) => Date.now() - capturedAt >= ttlMs;\n\n function forget() {\n changes += 1;\n record.remove();\n store.update((s) => ({ ...s, code: null, capturedAt: null }));\n }\n\n function restore() {\n const startedAt = changes;\n store.update((s) => (s.status === 'ready' ? s : { ...s, status: 'loading' }));\n reading = record.read().then((read) => {\n if (ctx.isDisposed()) return;\n if (changes !== startedAt) {\n store.update((s) => ({ ...s, status: 'ready' }));\n return;\n }\n let stored = read;\n if (stored && expired(stored.capturedAt)) {\n record.remove();\n stored = null;\n }\n store.set({\n status: 'ready',\n code: stored?.code ?? null,\n capturedAt: stored?.capturedAt ?? null,\n });\n });\n }\n\n /** Hydration and the stored-code read have finished. */\n async function settled() {\n await ctx.ready();\n await reading;\n }\n\n ctx.onHydrate(restore);\n ctx.events.on('auth:signed-in', (event) => {\n // A new account was created: the link has done its job (and must not attribute another).\n if (event.via === 'register' || event.via === 'otp') forget();\n });\n\n return {\n ...readOnly(store),\n async capture(code) {\n const trimmed = typeof code === 'string' ? code.trim() : '';\n if (!trimmed || trimmed.length > MAX_LENGTH) {\n const error = storeError(\n 'validation',\n trimmed\n ? `A referral code has at most ${MAX_LENGTH} characters.`\n : 'A referral code is required.',\n );\n ctx.events.emit({ type: 'error', store: 'referral', action: 'capture', error });\n return fail(error);\n }\n changes += 1;\n const capturedAt = Date.now();\n store.update((s) => ({ ...s, code: trimmed, capturedAt }));\n record.write({ code: trimmed, capturedAt });\n await settled();\n return ok(undefined);\n },\n current() {\n const { code, capturedAt } = store.getSnapshot();\n if (code === null || capturedAt === null) return null;\n if (!expired(capturedAt)) return code;\n forget();\n return null;\n },\n async clear() {\n forget();\n await settled();\n return ok(undefined);\n },\n };\n}\n","/**\n * The typed event bus (M3 plan Part B8). Stores use it for wiring; apps use it for toasts,\n * analytics and navigation. Events never carry tokens.\n */\nimport type { PaymentStatus } from '../../types/orders';\nimport type { StoreError } from './errors';\n\nexport type GrowupsellEvent =\n | { type: 'auth:signed-in'; customerId: number; via: 'login' | 'register' | 'otp' }\n | { type: 'auth:signed-out'; reason: 'logout' | 'expired' }\n | { type: 'session:replaced'; reason: 'dead' | 'rotated' }\n | { type: 'cart:merge-incomplete'; missingSkuIds: readonly number[] }\n | { type: 'order:placed'; orderId: number; payment: 'none' | 'required' }\n | { type: 'payment:confirmed'; orderId: number; paymentStatus: PaymentStatus }\n | { type: 'checkout:points-spent'; points: number }\n | { type: 'error'; store: string; action: string; error: StoreError };\n// further stores add their members here (one line each)\n\nexport interface EventBus {\n /** Listens to one event type. Returns an idempotent unsubscribe. */\n on<K extends GrowupsellEvent['type']>(\n type: K,\n listener: (event: Extract<GrowupsellEvent, { type: K }>) => void,\n ): () => void;\n /**\n * Calls the type's listeners synchronously, in subscription order, over a copy of the list.\n * A throwing listener goes to `onListenerError`; the others still run.\n */\n emit(event: GrowupsellEvent): void;\n}\n\nexport function createEventBus(onListenerError: (error: unknown) => void): EventBus {\n type Listener = (event: GrowupsellEvent) => void;\n const listeners = new Map<GrowupsellEvent['type'], Array<{ listener: Listener }>>();\n\n return {\n on(type, listener) {\n const entry = { listener: listener as Listener };\n listeners.set(type, [...(listeners.get(type) ?? []), entry]);\n return () => {\n const current = listeners.get(type);\n if (current)\n listeners.set(\n type,\n current.filter((e) => e !== entry),\n );\n };\n },\n emit(event) {\n for (const entry of listeners.get(event.type)?.slice() ?? []) {\n try {\n entry.listener(event);\n } catch (error) {\n onListenerError(error);\n }\n }\n },\n };\n}\n","/**\n * Injected storage (ADR-009, ADR-024; M3 plan Part B6). The library never touches\n * `localStorage`, `sessionStorage` or a native module: the app passes adapters. Memory is the\n * source of truth; storage catches up in order and never blocks an action.\n */\n\n/** Sync (localStorage) or async (AsyncStorage, SecureStore) key/value strings. */\nexport interface StorageAdapter {\n getItem(key: string): string | null | Promise<string | null>;\n setItem(key: string, value: string): void | Promise<void>;\n removeItem(key: string): void | Promise<void>;\n}\n\n/** In-memory adapter: the default, for SSR, tests and apps that persist nothing. */\nexport function createMemoryStorage(): StorageAdapter {\n const data = new Map<string, string>();\n return {\n getItem: (key) => data.get(key) ?? null,\n setItem: (key, value) => {\n data.set(key, value);\n },\n removeItem: (key) => {\n data.delete(key);\n },\n };\n}\n\n/** The three adapters a stores instance uses (M3 plan A3). */\nexport interface ResolvedStorage {\n /** General data (e.g. the referral code). */\n storage: StorageAdapter;\n /** Token records: Expo SecureStore on mobile; defaults to `storage`. */\n secure: StorageAdapter;\n /** Logins without \"remember me\" (`sessionStorage` on the web); defaults to memory. */\n ephemeral: StorageAdapter;\n}\n\nexport function resolveStorage(options: {\n storage?: StorageAdapter;\n secureStorage?: StorageAdapter;\n ephemeralStorage?: StorageAdapter;\n}): ResolvedStorage {\n const storage = options.storage ?? createMemoryStorage();\n return {\n storage,\n secure: options.secureStorage ?? storage,\n ephemeral: options.ephemeralStorage ?? createMemoryStorage(),\n };\n}\n\nconst ID_PART = /^[A-Za-z0-9_-]+$/;\nconst NAME_PART = /^[A-Za-z0-9._-]+$/;\n\n/**\n * `gs.<businessId>.<name>`: scoped by business (a token of another business is silently a\n * guest, M3 plan A2) and limited to `[A-Za-z0-9._-]`, the characters Expo SecureStore accepts.\n * Throws `TypeError` for a business id or name that would make an unsafe or ambiguous key.\n */\nexport function storageKey(businessId: number | string, name: string): string {\n const id = String(businessId);\n if (!ID_PART.test(id)) {\n throw new TypeError(`businessId must contain only letters, digits, \"_\" and \"-\": \"${id}\".`);\n }\n if (!NAME_PART.test(name)) {\n throw new TypeError(`storage name must contain only letters, digits, \".\", \"_\" and \"-\".`);\n }\n return `gs.${id}.${name}`;\n}\n\nexport type StorageOperation = 'read' | 'write' | 'remove';\n\n/** Internal: one versioned JSON record under `gs.<businessId>.<name>`. */\nexport interface Persisted<T> {\n /** Missing, unparsable, wrong version, failing `validate` or failing adapter → `null`. */\n read(): Promise<T | null>;\n /** Fire-and-forget, serialised per key; failures go to `onError`. */\n write(value: T): void;\n /** Same as `write`. */\n remove(): void;\n}\n\n/**\n * A versioned record `{\"v\": <version>, \"data\": …}`. Every operation on the record (reads\n * included) runs after the previous one settled, so storage ends in the order the calls were\n * made, also with async adapters. A record with the wrong version or failing `validate` is\n * removed and reads as `null`. Nothing here throws or rejects: failures are passed to\n * `onError` with the operation and otherwise ignored.\n */\nexport function createPersisted<T>(\n adapter: StorageAdapter,\n key: string,\n version: number,\n validate: (raw: unknown) => raw is T,\n onError: (error: unknown, operation: StorageOperation) => void,\n): Persisted<T> {\n let tail: Promise<unknown> = Promise.resolve();\n\n /** Queues `run`; its result (or `fallback` after reporting a failure) resolves the promise. */\n function enqueue<R>(operation: StorageOperation, run: () => Promise<R>, fallback: R) {\n const next = tail.then(run).catch((error: unknown) => {\n onError(error, operation);\n return fallback;\n });\n tail = next;\n return next;\n }\n\n async function removeQuietly() {\n try {\n await adapter.removeItem(key);\n } catch (error) {\n onError(error, 'remove');\n }\n }\n\n async function readNow(): Promise<T | null> {\n const raw = await adapter.getItem(key);\n if (raw == null) return null;\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n await removeQuietly();\n return null;\n }\n const record = parsed as { v?: unknown; data?: unknown } | null;\n if (!record || typeof record !== 'object' || record.v !== version || !validate(record.data)) {\n await removeQuietly();\n return null;\n }\n return record.data;\n }\n\n return {\n read: () => enqueue('read', readNow, null),\n write(value) {\n void enqueue(\n 'write',\n async () => adapter.setItem(key, JSON.stringify({ v: version, data: value })),\n undefined,\n );\n },\n remove() {\n void enqueue('remove', async () => adapter.removeItem(key), undefined);\n },\n };\n}\n","/**\n * The runtime behind one `createGrowupsellStores()` instance (ADR-024; M3 plan B7, B9): the\n * private client, the in-memory token holder, identity, events, storage records, hydration and\n * the 401 routing. Store factories receive its `StoreContext`. Nothing here is module-level\n * state: two runtimes share nothing.\n */\nimport { createClient, type Client } from '../../http/client';\nimport type { AnyFetch, UnauthorizedEvent } from '../../http/types';\nimport type {\n Business,\n BusinessMedia,\n BusinessSettings,\n SocialLinks,\n ThemeSettings,\n} from '../../types/business';\nimport type { CatalogSettings, CategoryTree } from '../../types/catalog';\nimport type { CustomerProfile } from '../../types/customer';\nimport type { ThemeContent } from '../../types/theme-content';\nimport type { AuthStore } from '../types/auth';\nimport type { BusinessStore } from '../types/business';\nimport type { CartStore } from '../types/cart';\nimport type { CatalogStore } from '../types/catalog';\nimport type { CheckoutStore } from '../types/checkout';\nimport type { ReferralStore } from '../types/referral';\nimport type { SessionStore } from '../types/session';\nimport type { ThemeConfigStore } from '../types/themeConfig';\nimport type { WishlistStore } from '../types/wishlist';\nimport { createSingleFlight, runInEpoch, type Current } from './concurrency';\nimport { storeError, toStoreError } from './errors';\nimport { createEventBus, type EventBus } from './events';\nimport {\n createPersisted,\n resolveStorage,\n storageKey,\n type Persisted,\n type StorageAdapter,\n} from './storage';\nimport { createStore, readOnly, rethrowAsync, type Store } from './store';\n\nexport interface GrowupsellStoresOptions {\n /** Backend base URL. Required: there is no default backend. */\n baseURL: string;\n /** Resolve the business first (`client.business.detail(domain)`); scopes requests and storage keys. */\n businessId: number | string;\n /** Sent where a store needs it (theme settings). Never guessed (ADR-009). */\n platform: 'website' | 'app';\n /** General data. Default: memory (nothing persists). */\n storage?: StorageAdapter;\n /** Token records (Expo SecureStore). Default: `storage`. */\n secureStorage?: StorageAdapter;\n /** Logins without \"remember me\" (`sessionStorage` on the web). Default: memory. */\n ephemeralStorage?: StorageAdapter;\n fetch?: AnyFetch;\n timeoutMs?: number;\n /**\n * The merchant token for merchant requests (theme editing; ADR-021). Read for every request,\n * never stored and never put in a snapshot or event.\n */\n merchantToken?: () => string | null;\n /** Called after the stores reacted (signed out, session replaced): navigate to login, etc. */\n onUnauthorized?: (event: { kind: 'customer' | 'merchant' | 'session' }) => void;\n /** Listener and storage errors. Default: rethrown asynchronously. */\n onError?: (error: unknown) => void;\n /** A stored login older than this is dropped at hydration without a request. Default 24 h. */\n customerTokenTtlMs?: number;\n /** How long a captured referral code is kept. Default 7 days (ADR-025, D2). */\n referralTtlMs?: number;\n /**\n * After hydration, load the cart (when a token exists) and the wishlist (when signed in); load\n * the catalog at its first `subscribe()` unless seeded. Default true.\n */\n autoLoad?: boolean;\n /** Server-fetched data the stores start with (SSR). */\n seeds?: Partial<StoreSeeds>;\n}\n\nexport interface Identity {\n /** `unknown` until hydrated. */\n kind: 'unknown' | 'guest' | 'customer';\n customerId: number | null;\n /** Increases on sign-in, sign-out, expiry and session replacement (M3 plan B5). */\n epoch: number;\n}\n\n/** One line per store (M3 plan B1). */\nexport interface StoreRegistry {\n session: SessionStore;\n auth: AuthStore;\n cart: CartStore;\n wishlist: WishlistStore;\n checkout: CheckoutStore;\n business: BusinessStore;\n catalog: CatalogStore;\n themeConfig: ThemeConfigStore;\n referral: ReferralStore;\n}\n\n/** Server-fetched data a store may start with (SSR). One optional line per store. */\nexport interface StoreSeeds {\n business?: {\n business: Business;\n settings?: BusinessSettings;\n themeSettings?: ThemeSettings;\n media?: BusinessMedia;\n socialLinks?: SocialLinks;\n };\n catalog?: { categories?: CategoryTree[]; settings?: CatalogSettings };\n themeContent?: Readonly<Record<string, ThemeContent | null>>;\n}\n\n/** Internal: the only place tokens live in memory. Never exported from the package. */\nexport interface TokenHolder {\n getCustomerToken(): string | null;\n setCustomerToken(token: string | null): void;\n getSessionToken(): string | null;\n setSessionToken(token: string | null): void;\n}\n\n/** `gs.<biz>.session`, in `secureStorage` (M3 plan D1). */\nexport interface SessionRecord {\n id: number;\n token: string;\n}\n\n/** `gs.<biz>.auth`, in `secureStorage` (remembered) or `ephemeralStorage` (M3 plan D2). */\nexport interface AuthRecord {\n token: string;\n customer: CustomerProfile;\n rewardPoints: number | null;\n /** `Date.now()` when the login happened; checked against `customerTokenTtlMs`. */\n savedAt: number;\n}\n\n/** What hydration (and a rehydration that found changed tokens) read from storage. */\nexport interface HydratedRecords {\n phase: 'hydrate' | 'rehydrate';\n session: SessionRecord | null;\n auth: AuthRecord | null;\n /** The auth record came from `secureStorage` (\"remember me\"); false for ephemeral or none. */\n remembered: boolean;\n}\n\n/**\n * Internal wiring points with working defaults. The session store (Task 6) and the auth store\n * (Task 7) replace them at construction to add their state, e.g.\n * `ctx.hooks.sessionDead = () => { … }`.\n */\nexport interface RuntimeHooks {\n /**\n * Creates a guest session and holds its token; `ctx.ensureSession()` calls it single-flight\n * after hydration. Default: `client.session.create()`, hold the token, write the record.\n */\n createSession(): Promise<string>;\n /**\n * The backend rejected the **current** customer token (401). Must drop it. Default:\n * `clearCustomerCredentials(ctx)`, then `auth:signed-out { reason: 'expired' }`.\n */\n customerExpired(): void;\n /**\n * The backend forgot the **current** guest session (HTML 404). Must drop it. Default:\n * `dropSession(ctx, 'dead')`; the session store adds the immediate re-creation and loop guard.\n */\n sessionDead(): void;\n}\n\n/** What a store factory receives (M3 plan B7). */\nexport interface StoreContext {\n /** The instance's private client; credentials and 401 handling are already wired. */\n readonly client: Client;\n readonly businessId: number | string;\n readonly platform: 'website' | 'app';\n readonly events: EventBus;\n readonly identity: Store<Identity>;\n readonly seeds: Readonly<StoreSeeds>;\n /** Resolves when hydration finished; starts it if nobody has. Every action awaits it first. */\n ready(): Promise<void>;\n /**\n * The guest session token, creating a session when there is none (single-flight). Rejects\n * when creation fails, or with a `superseded` `StoreError` after `dispose()`.\n */\n ensureSession(): Promise<string>;\n /** Whether a guest session token is held right now (no request). */\n hasSession(): boolean;\n /**\n * `createPersisted` bound to the instance's adapters and key prefix (`gs.<businessId>.<name>`).\n * One record per adapter and key, so writes to a key stay in order. Failures become `error`\n * events (`store: 'storage'`) and reach `onError`.\n */\n persisted<T>(\n name: string,\n version: number,\n validate: (raw: unknown) => raw is T,\n where?: 'storage' | 'secure' | 'ephemeral',\n ): Persisted<T>;\n /** Other stores, for wiring (read lazily inside actions, never during construction). */\n readonly stores: StoreRegistry;\n readonly onListenerError: (error: unknown) => void;\n\n // Internal: for the store implementations only; none of this is exported from the package.\n\n /** Resolved options. */\n readonly config: Readonly<{\n customerTokenTtlMs: number;\n referralTtlMs: number;\n autoLoad: boolean;\n }>;\n /** The private token holder. Tokens never go into a snapshot or an event. */\n readonly tokens: TokenHolder;\n /** The credential records the runtime hydrates from. */\n readonly records: Readonly<{\n session: Persisted<SessionRecord>;\n auth: Persisted<AuthRecord>;\n ephemeralAuth: Persisted<AuthRecord>;\n }>;\n readonly hooks: RuntimeHooks;\n /** Sets who the shopper is; always increments the epoch. */\n setIdentity(next: { kind: 'guest' | 'customer'; customerId: number | null }): void;\n /**\n * Runs `run` and resolves `{ current: false }` when the identity epoch changed or the\n * instance was disposed meanwhile (M3 plan B5): drop that result, answer `superseded`.\n */\n inEpoch<T>(run: () => Promise<T>): Promise<Current<T>>;\n /** Called with the stored records at hydration (and rehydration), before identity is set. */\n onHydrate(listener: (records: HydratedRecords) => void): void;\n /** Called after `hydrated` turned true (and after a rehydration changed tokens), if `autoLoad`. */\n autoLoad(load: () => void): void;\n /**\n * Registers a cleanup for `dispose()` (per-screen stores register their own `dispose`).\n * Returns an unregister, for a store disposed on its own.\n */\n onDispose(cleanup: () => void): () => void;\n isDisposed(): boolean;\n}\n\n/** What `createRuntime` returns to `createGrowupsellStores`. */\nexport interface StoreRuntime {\n readonly ctx: StoreContext;\n readonly hydrated: Store<boolean>;\n hydrate(): Promise<void>;\n rehydrate(): Promise<void>;\n dispose(): void;\n /** Makes the registry readable through `ctx.stores`, once every store is built. */\n attach(stores: StoreRegistry): void;\n}\n\nconst HOUR = 60 * 60 * 1000;\nconst DEFAULT_CUSTOMER_TOKEN_TTL_MS = 24 * HOUR;\n/** How long a captured referral code is kept by default: 7 days (ADR-025, D2; `referralTtlMs`). */\nexport const REFERRAL_TTL_MS = 7 * 24 * HOUR;\n\nfunction isObject(raw: unknown): raw is Record<string, unknown> {\n return !!raw && typeof raw === 'object' && !Array.isArray(raw);\n}\n\nfunction isSessionRecord(raw: unknown): raw is SessionRecord {\n return (\n isObject(raw) && typeof raw.id === 'number' && typeof raw.token === 'string' && !!raw.token\n );\n}\n\nfunction isAuthRecord(raw: unknown): raw is AuthRecord {\n return (\n isObject(raw) &&\n typeof raw.token === 'string' &&\n !!raw.token &&\n isObject(raw.customer) &&\n typeof raw.customer.id === 'number' &&\n (raw.rewardPoints === null || typeof raw.rewardPoints === 'number') &&\n typeof raw.savedAt === 'number'\n );\n}\n\nfunction validateOptions(options: GrowupsellStoresOptions) {\n if (typeof options?.baseURL !== 'string' || !options.baseURL) {\n throw new TypeError('createGrowupsellStores: baseURL is required.');\n }\n if (options.businessId == null || options.businessId === '') {\n throw new TypeError(\n 'createGrowupsellStores: businessId is required (resolve the business first).',\n );\n }\n storageKey(options.businessId, 'check'); // throws TypeError for an id unusable in keys\n if (options.platform !== 'website' && options.platform !== 'app') {\n throw new TypeError(\"createGrowupsellStores: platform must be 'website' or 'app'.\");\n }\n}\n\n/**\n * Drops the guest session: token, record, epoch + 1, `session:replaced { reason }`. Returns\n * false (and does nothing) when no session is held.\n */\nexport function dropSession(ctx: StoreContext, reason: 'dead' | 'rotated'): boolean {\n if (!ctx.tokens.getSessionToken()) return false;\n ctx.tokens.setSessionToken(null);\n ctx.records.session.remove();\n const { kind, customerId } = ctx.identity.getSnapshot();\n ctx.setIdentity({ kind: kind === 'customer' ? 'customer' : 'guest', customerId });\n ctx.events.emit({ type: 'session:replaced', reason });\n return true;\n}\n\n/**\n * The credential part of logout and expiry (M3 plan D2): drop the customer token, remove both\n * auth records, rotate the session (W32), identity → guest. Emits no `auth:` event: the caller\n * sets its state first, then emits `auth:signed-out`.\n */\nexport function clearCustomerCredentials(ctx: StoreContext): void {\n ctx.tokens.setCustomerToken(null);\n ctx.records.auth.remove();\n ctx.records.ephemeralAuth.remove();\n dropSession(ctx, 'rotated');\n ctx.setIdentity({ kind: 'guest', customerId: null });\n}\n\n/** Builds the runtime. Synchronous and free of I/O: nothing is read, sent or scheduled. */\nexport function createRuntime(options: GrowupsellStoresOptions): StoreRuntime {\n validateOptions(options);\n const onListenerError = options.onError ?? rethrowAsync;\n const config = {\n customerTokenTtlMs: options.customerTokenTtlMs ?? DEFAULT_CUSTOMER_TOKEN_TTL_MS,\n referralTtlMs: options.referralTtlMs ?? REFERRAL_TTL_MS,\n autoLoad: options.autoLoad ?? true,\n };\n const adapters = resolveStorage(options);\n const seeds: Readonly<StoreSeeds> = { ...options.seeds };\n\n let disposed = false;\n let customerToken: string | null = null;\n let sessionToken: string | null = null;\n const tokens: TokenHolder = {\n getCustomerToken: () => customerToken,\n setCustomerToken: (token) => {\n customerToken = token;\n },\n getSessionToken: () => sessionToken,\n setSessionToken: (token) => {\n sessionToken = token;\n },\n };\n\n const bus = createEventBus(onListenerError);\n const events: EventBus = {\n on: bus.on,\n emit: (event) => {\n if (!disposed) bus.emit(event);\n },\n };\n\n const identity = createStore<Identity>(\n { kind: 'unknown', customerId: null, epoch: 0 },\n { onListenerError },\n );\n const hydrated = createStore(false, { onListenerError });\n\n /** One `Persisted` per adapter and key: a single queue keeps a key's writes in order. */\n const persistedByAdapter = new Map<StorageAdapter, Map<string, Persisted<unknown>>>();\n function persisted<T>(\n name: string,\n version: number,\n validate: (raw: unknown) => raw is T,\n where: 'storage' | 'secure' | 'ephemeral' = 'storage',\n ): Persisted<T> {\n const adapter = adapters[where];\n const key = storageKey(options.businessId, name);\n let byKey = persistedByAdapter.get(adapter);\n if (!byKey) persistedByAdapter.set(adapter, (byKey = new Map()));\n let record = byKey.get(key);\n if (!record) {\n record = createPersisted(adapter, key, version, validate, (error, operation) => {\n events.emit({\n type: 'error',\n store: 'storage',\n action: operation,\n error: toStoreError(error),\n });\n onListenerError(error);\n }) as Persisted<unknown>;\n byKey.set(key, record);\n }\n return record as Persisted<T>;\n }\n\n const records = {\n session: persisted('session', 1, isSessionRecord, 'secure'),\n auth: persisted('auth', 1, isAuthRecord, 'secure'),\n ephemeralAuth: persisted('auth', 1, isAuthRecord, 'ephemeral'),\n };\n\n // Hydration -----------------------------------------------------------------------------\n\n let hydration: Promise<void> | null = null;\n let rehydration: Promise<void> | null = null;\n const hydrateListeners: Array<(records: HydratedRecords) => void> = [];\n const loaders: Array<() => void> = [];\n\n function safely(run: () => void) {\n try {\n run();\n } catch (error) {\n onListenerError(error);\n }\n }\n\n async function readRecords(phase: HydratedRecords['phase']): Promise<HydratedRecords> {\n const [session, secureAuth, ephemeralAuth] = await Promise.all([\n records.session.read(),\n records.auth.read(),\n records.ephemeralAuth.read(),\n ]);\n let auth = secureAuth ?? ephemeralAuth;\n const remembered = !!secureAuth;\n if (auth && Date.now() - auth.savedAt > config.customerTokenTtlMs) {\n // The token cannot outlive its 24 h (M3 plan O7). Not a sign-out: nobody was signed in.\n (remembered ? records.auth : records.ephemeralAuth).remove();\n auth = null;\n }\n return { phase, session, auth, remembered: !!auth && remembered };\n }\n\n function apply(read: HydratedRecords, epoch: number) {\n tokens.setSessionToken(read.session?.token ?? null);\n tokens.setCustomerToken(read.auth?.token ?? null);\n for (const listener of hydrateListeners.slice()) safely(() => listener(read));\n identity.set({\n kind: read.auth ? 'customer' : 'guest',\n customerId: read.auth?.customer.id ?? null,\n epoch,\n });\n hydrated.set(true);\n }\n\n function runLoaders() {\n if (!config.autoLoad) return;\n for (const load of loaders.slice()) safely(load);\n }\n\n function hydrate(): Promise<void> {\n hydration ??= readRecords('hydrate').then((read) => {\n if (disposed) return;\n apply(read, 1);\n runLoaders();\n }, onListenerError);\n return hydration;\n }\n\n function rehydrate(): Promise<void> {\n if (!hydrated.getSnapshot()) return hydrate();\n rehydration ??= readRecords('rehydrate')\n .then((read) => {\n if (disposed) return;\n const sameSession = (read.session?.token ?? null) === tokens.getSessionToken();\n const sameCustomer = (read.auth?.token ?? null) === tokens.getCustomerToken();\n if (sameSession && sameCustomer) return;\n const wasCustomer = tokens.getCustomerToken() !== null;\n apply(read, identity.getSnapshot().epoch + 1);\n // Logged out in another tab: the stores clear the previous customer's data.\n if (wasCustomer && !read.auth) events.emit({ type: 'auth:signed-out', reason: 'logout' });\n runLoaders();\n }, onListenerError)\n .finally(() => {\n rehydration = null;\n });\n return rehydration;\n }\n\n // Sessions and 401s -------------------------------------------------------------------\n\n const flight = createSingleFlight<'session'>();\n const disposedError = () => storeError('superseded', 'The stores were disposed.');\n\n const reported = new Set<string>();\n function routeUnauthorized({ kind, token }: UnauthorizedEvent) {\n if (disposed) return;\n if (kind === 'customer') {\n if (token !== tokens.getCustomerToken()) return; // a request sent with an older login\n safely(() => ctx.hooks.customerExpired());\n } else if (kind === 'session') {\n if (token !== tokens.getSessionToken()) return; // an already replaced session\n safely(() => ctx.hooks.sessionDead());\n }\n const key = `${kind}\\u0000${token}`;\n if (reported.has(key)) return;\n reported.add(key);\n safely(() => options.onUnauthorized?.({ kind }));\n }\n\n const credentials = () => ({\n businessId: options.businessId,\n customerToken: tokens.getCustomerToken(),\n sessionToken: tokens.getSessionToken(),\n merchantToken: options.merchantToken?.() ?? null,\n });\n\n const client = createClient({\n baseURL: options.baseURL,\n fetch: options.fetch,\n timeoutMs: options.timeoutMs,\n // Synchronous once hydrated; a request made earlier waits for (and starts) hydration.\n credentials: () =>\n hydrated.getSnapshot() || disposed ? credentials() : hydrate().then(credentials),\n onUnauthorized: routeUnauthorized,\n });\n\n let registry: StoreRegistry | null = null;\n const cleanups = new Set<{ run: () => void }>();\n\n const ctx: StoreContext = {\n client,\n businessId: options.businessId,\n platform: options.platform,\n events,\n identity: readOnly(identity),\n seeds,\n ready: hydrate,\n async ensureSession() {\n await hydrate();\n if (disposed) throw disposedError();\n const held = tokens.getSessionToken();\n if (held) return held;\n return flight('session', () => ctx.hooks.createSession());\n },\n hasSession: () => tokens.getSessionToken() !== null,\n persisted,\n get stores(): StoreRegistry {\n if (!registry) {\n throw new Error('ctx.stores is not available during construction: read it inside actions.');\n }\n return registry;\n },\n onListenerError,\n config,\n tokens,\n records,\n hooks: {\n async createSession() {\n const session = await client.session.create();\n if (disposed) throw disposedError();\n tokens.setSessionToken(session.token);\n records.session.write({ id: session.id, token: session.token });\n return session.token;\n },\n customerExpired() {\n clearCustomerCredentials(ctx);\n events.emit({ type: 'auth:signed-out', reason: 'expired' });\n },\n sessionDead() {\n dropSession(ctx, 'dead');\n },\n },\n setIdentity(next) {\n identity.set({ ...next, epoch: identity.getSnapshot().epoch + 1 });\n },\n inEpoch: (run) => runInEpoch(() => (disposed ? -1 : identity.getSnapshot().epoch), run),\n onHydrate(listener) {\n hydrateListeners.push(listener);\n },\n autoLoad(load) {\n loaders.push(load);\n },\n onDispose(cleanup) {\n const entry = { run: cleanup };\n cleanups.add(entry);\n return () => {\n cleanups.delete(entry);\n };\n },\n isDisposed: () => disposed,\n };\n\n return {\n ctx,\n hydrated: readOnly(hydrated),\n hydrate,\n rehydrate,\n dispose() {\n if (disposed) return;\n disposed = true;\n for (const entry of [...cleanups]) safely(entry.run);\n cleanups.clear();\n },\n attach(stores) {\n registry = stores;\n },\n };\n}\n","/**\n * Search suggestions (M3 part 2 plan 5.7, Task 12): one per search box, created with\n * `stores.createSearchSuggestions(options)`. Replaces the storefront's two debounce + cancel\n * implementations (header and search page).\n */\nimport type { StoreContext } from './runtime/context';\nimport { toStoreError } from './runtime/errors';\nimport { createStore } from './runtime/store';\nimport type {\n SearchSuggestionsOptions,\n SearchSuggestionsState,\n SearchSuggestionsStore,\n} from './types/searchSuggestions';\n\n/** Timers through `globalThis`: `commerce` compiles without DOM or Node types (ADR-009). */\ninterface Runtime {\n setTimeout(handler: () => void, ms: number): unknown;\n clearTimeout(timer: unknown): void;\n}\nconst runtime = globalThis as unknown as Runtime;\n\nconst DEFAULT_DEBOUNCE_MS = 300;\n\nexport function createSearchSuggestionsStore(\n ctx: StoreContext,\n options: SearchSuggestionsOptions = {},\n): SearchSuggestionsStore {\n const debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;\n const store = createStore<SearchSuggestionsState>(\n { query: '', status: 'idle', items: [], error: null },\n { onListenerError: ctx.onListenerError },\n );\n let timer: unknown = null;\n /** Bumped by every request, blank query and clear: only the newest request's answer lands. */\n let generation = 0;\n let disposed = false;\n\n const update = (changes: Partial<SearchSuggestionsState>) => {\n if (!disposed) store.set({ ...store.getSnapshot(), ...changes });\n };\n\n function cancelTimer() {\n if (timer !== null) runtime.clearTimeout(timer);\n timer = null;\n }\n\n async function ask(word: string) {\n const mine = ++generation;\n update({ status: 'loading', error: null });\n try {\n const items = await ctx.client.products.suggestions(word);\n if (mine === generation) update({ status: 'ready', items, error: null });\n } catch (caught) {\n if (mine !== generation) return;\n const error = toStoreError(caught);\n update({ status: 'error', items: [], error });\n if (!disposed) {\n ctx.events.emit({ type: 'error', store: 'searchSuggestions', action: 'setQuery', error });\n }\n }\n }\n\n function setQuery(text: string) {\n if (disposed) return;\n cancelTimer();\n const word = text.trim();\n if (!word) {\n generation += 1;\n update({ query: text, status: 'idle', items: [], error: null });\n return;\n }\n update({ query: text });\n timer = runtime.setTimeout(() => {\n timer = null;\n void ask(word);\n }, debounceMs);\n }\n\n function clear() {\n if (disposed) return;\n cancelTimer();\n generation += 1;\n update({ query: '', status: 'idle', items: [], error: null });\n }\n\n function dispose() {\n if (disposed) return;\n cancelTimer();\n generation += 1;\n disposed = true;\n unregister();\n }\n const unregister = ctx.onDispose(dispose);\n\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe: store.subscribe,\n setQuery,\n clear,\n dispose,\n };\n}\n","/**\n * The guest session store (M3 plan D1, Task 6; ADR-025). Sessions are created lazily, on first\n * need (guest cart, login), never at start: bots browsing public pages create nothing. The\n * token stays in the runtime's holder; this store shows only whether one is held.\n *\n * It takes over two runtime hooks:\n *\n * - `createSession`: the runtime's creation, plus `creating` / `status` / `error` here.\n * - `sessionDead`: the backend forgot the current session (HTML 404, C15/C27): drop it and\n * create a new one at once (single-flight), at most 3 times per 60 s; beyond that stop until\n * the next explicit `ensure()`, so a backend that forgets every session is not hammered.\n *\n * Rotation (W32: after every sign-in and on logout) is the runtime's `dropSession(ctx,\n * 'rotated')`; this store follows it through the `session:replaced` event.\n */\nimport type { StoreContext } from './runtime/context';\nimport { dropSession } from './runtime/context';\nimport { fail, ok, storeError, toStoreError, type StoreError } from './runtime/errors';\nimport { createStore } from './runtime/store';\nimport type { SessionState, SessionStore } from './types/session';\n\nconst LOOP_LIMIT = 3;\nconst LOOP_WINDOW_MS = 60_000;\n\nexport function createSessionStore(ctx: StoreContext): SessionStore {\n const store = createStore<SessionState>(\n { status: 'unknown', creating: false, error: null },\n { onListenerError: ctx.onListenerError },\n );\n const patch = (next: Partial<SessionState>) => store.update((s) => ({ ...s, ...next }));\n const status = (): SessionState['status'] => (ctx.hasSession() ? 'active' : 'none');\n\n function failed(action: string, error: StoreError) {\n patch({ status: status(), creating: false, error });\n ctx.events.emit({ type: 'error', store: 'session', action, error });\n }\n\n ctx.onHydrate(() => patch({ status: status() }));\n ctx.events.on('session:replaced', () => patch({ status: status() }));\n\n const create = ctx.hooks.createSession;\n ctx.hooks.createSession = async () => {\n patch({ creating: true, error: null });\n try {\n const token = await create();\n patch({ status: status(), creating: false });\n return token;\n } catch (error) {\n patch({ status: status(), creating: false, error: toStoreError(error) });\n throw error;\n }\n };\n\n /** When the recent dead-session re-creations happened (`Date.now()`). */\n let replacements: number[] = [];\n let stopped = false;\n\n ctx.hooks.sessionDead = () => {\n dropSession(ctx, 'dead');\n const now = Date.now();\n replacements = replacements.filter((at) => now - at < LOOP_WINDOW_MS);\n if (stopped || replacements.length >= LOOP_LIMIT) {\n stopped = true;\n failed(\n 'replace',\n storeError('session', 'The guest session keeps being rejected; call ensure() to retry.'),\n );\n return;\n }\n replacements.push(now);\n ctx.ensureSession().then(\n () => {},\n (error: unknown) => failed('replace', toStoreError(error)),\n );\n };\n\n async function ensure() {\n stopped = false;\n replacements = [];\n try {\n await ctx.ensureSession();\n patch({ status: status(), error: null });\n return ok(undefined);\n } catch (error) {\n const storeErr = toStoreError(error);\n failed('ensure', storeErr);\n return fail(storeErr);\n }\n }\n\n return {\n getSnapshot: store.getSnapshot,\n getServerSnapshot: store.getServerSnapshot,\n subscribe: store.subscribe,\n ensure,\n };\n}\n","/**\n * The theme content store (M3 part 2 plan 5.5, Task 10): the merchant's documents for the\n * storefront sections, and the edit-mode saves. Fixes the old providers: `platform` was guessed\n * with `typeof window` (TB1), a save while another ran was dropped (TB2), every save was\n * followed by a GET (TB4), and a failed save left unsaved content on screen (TB5).\n */\nimport type { ThemeContent } from '../types/theme-content';\nimport { createSingleFlight } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport type { ThemeConfigState, ThemeConfigStore, ThemeSectionState } from './types/themeConfig';\n\nconst IDLE: ThemeSectionState = Object.freeze({\n status: 'idle',\n content: null,\n saving: false,\n error: null,\n});\n\nconst superseded = () => storeError('superseded', 'A newer save of this section replaced it.');\nconst disposedError = () => storeError('superseded', 'The stores were disposed.');\n\ninterface SaveJob {\n data: unknown;\n resolve(result: ActionResult<ThemeContent>): void;\n}\n\n/** One section's save line: one save in flight, at most one waiting (the newest). */\ninterface SaveSlot {\n running: boolean;\n waiting: SaveJob | null;\n}\n\n/**\n * Starts from `ctx.seeds.themeContent` (seeded sections are `ready` and not reloaded). The\n * theme id comes from `ctx.stores.business`, read when an action runs.\n */\nexport function createThemeConfigStore(ctx: StoreContext): ThemeConfigStore {\n /** The last content the backend confirmed (loaded or saved): what a failed save rolls back to. */\n const confirmed = new Map<string, ThemeContent | null>();\n const sections: Record<string, ThemeSectionState> = {};\n for (const [slug, content] of Object.entries(ctx.seeds.themeContent ?? {})) {\n confirmed.set(slug, content);\n sections[slug] = { status: 'ready', content, saving: false, error: null };\n }\n const store = createStore<ThemeConfigState>(\n {\n platform: ctx.platform,\n themeId: ctx.seeds.business?.themeSettings?.id ?? null,\n sections,\n },\n { onListenerError: ctx.onListenerError },\n );\n const flight = createSingleFlight<string>();\n /** Per section: only the newest load may write it; a save also moves it on. */\n const generation = new Map<string, number>();\n const slots = new Map<string, SaveSlot>();\n\n const section = (slug: string): ThemeSectionState => store.getSnapshot().sections[slug] ?? IDLE;\n\n /** Changes several sections in one `set`. */\n function patch(changes: Record<string, Partial<ThemeSectionState>>, themeId?: number) {\n const s = store.getSnapshot();\n const next = { ...s.sections };\n for (const [slug, change] of Object.entries(changes)) {\n next[slug] = { ...(next[slug] ?? IDLE), ...change };\n }\n store.set({ ...s, sections: next, themeId: themeId ?? s.themeId });\n }\n\n function failed<T>(action: string, error: StoreError): ActionResult<T> {\n ctx.events.emit({ type: 'error', store: 'themeConfig', action, error });\n return fail(error);\n }\n\n /** The theme settings id; loads the business's sections first when it is not known yet. */\n async function resolveThemeId(): Promise<number | StoreError> {\n const business = ctx.stores.business;\n let id = business.getSnapshot().themeId;\n if (id == null) {\n await business.load();\n id = business.getSnapshot().themeId;\n }\n if (id == null) return storeError('validation', 'themeConfig: theme settings are not loaded');\n return id;\n }\n\n function checkSlug(slug: unknown): string | StoreError {\n const key = typeof slug === 'string' ? slug.trim() : '';\n if (!key) return storeError('validation', 'themeConfig: a section slug is required.');\n if (key.includes(',')) {\n return storeError('validation', `themeConfig: slug \"${key}\" contains a comma.`);\n }\n return key;\n }\n\n async function runLoad(slugs: readonly string[]): Promise<ActionResult> {\n const mine = new Map(slugs.map((slug) => [slug, (generation.get(slug) ?? 0) + 1]));\n for (const [slug, gen] of mine) generation.set(slug, gen);\n const isMine = (slug: string) => generation.get(slug) === mine.get(slug);\n patch(\n Object.fromEntries(\n slugs.map((slug) => [\n slug,\n { status: section(slug).status === 'ready' ? 'ready' : 'loading', error: null },\n ]),\n ),\n );\n\n const settle = (error: StoreError) => {\n patch(\n Object.fromEntries(\n slugs\n .filter(isMine)\n .map((slug) => [\n slug,\n { status: section(slug).status === 'ready' ? 'ready' : 'error', error },\n ]),\n ),\n );\n return failed<void>('load', error);\n };\n\n const themeId = await resolveThemeId();\n if (ctx.isDisposed()) return fail(disposedError());\n if (typeof themeId !== 'number') return settle(themeId);\n let contents: Array<ThemeContent | null>;\n try {\n contents = await ctx.client.themeContent.getMany(themeId, slugs);\n } catch (error) {\n if (ctx.isDisposed()) return fail(disposedError());\n return settle(toStoreError(error));\n }\n if (ctx.isDisposed()) return fail(disposedError());\n const changes: Record<string, Partial<ThemeSectionState>> = {};\n slugs.forEach((slug, i) => {\n if (!isMine(slug)) return; // a newer load or a save owns this section\n const content = contents[i] ?? null;\n confirmed.set(slug, content);\n // While a save runs, the section keeps showing what is being saved.\n changes[slug] = section(slug).saving\n ? { status: 'ready', error: null }\n : { status: 'ready', content, error: null };\n });\n patch(changes, themeId);\n return ok(undefined);\n }\n\n async function send(slug: string, slot: SaveSlot, job: SaveJob): Promise<void> {\n slot.running = true;\n let outcome: ActionResult<ThemeContent>;\n const themeId = await resolveThemeId();\n if (typeof themeId !== 'number') outcome = fail(themeId);\n else {\n try {\n const saved = await ctx.client.themeContent.update(themeId, slug, {\n platform: ctx.platform,\n data: job.data,\n });\n outcome = ok(saved);\n } catch (error) {\n outcome = fail(toStoreError(error));\n }\n }\n if (ctx.isDisposed()) {\n slot.running = false;\n slot.waiting?.resolve(fail(disposedError()));\n slot.waiting = null;\n job.resolve(fail(disposedError()));\n return;\n }\n const next = slot.waiting;\n slot.waiting = null;\n if (outcome.ok) {\n confirmed.set(slug, outcome.value);\n generation.set(slug, (generation.get(slug) ?? 0) + 1); // older loads must not undo it\n // With a newer save waiting, the section keeps showing that one.\n if (!next) {\n patch(\n { [slug]: { status: 'ready', content: outcome.value, saving: false, error: null } },\n outcome.value.themeId,\n );\n }\n job.resolve(outcome);\n } else {\n if (!next) {\n patch({\n [slug]: { content: confirmed.get(slug) ?? null, saving: false, error: outcome.error },\n });\n }\n job.resolve(failed('save', outcome.error));\n }\n if (next) void send(slug, slot, next);\n else slot.running = false;\n }\n\n return {\n ...readOnly(store),\n load(slugs, options = {}) {\n const keys: string[] = [];\n for (const slug of slugs) {\n const key = checkSlug(slug);\n if (typeof key !== 'string') return Promise.resolve(fail(key));\n if (!keys.includes(key)) keys.push(key);\n }\n const wanted = options.force ? keys : keys.filter((key) => section(key).status !== 'ready');\n if (wanted.length === 0) return Promise.resolve(ok(undefined));\n return flight(`${options.force ? 'force' : 'load'}:${wanted.join(',')}`, () =>\n runLoad(wanted),\n );\n },\n save<T>(slug: string, data: T) {\n const key = checkSlug(slug);\n if (typeof key !== 'string') {\n return Promise.resolve(fail(key)) as Promise<ActionResult<ThemeContent<T>>>;\n }\n const s = store.getSnapshot();\n const base = section(key).content;\n const optimistic: ThemeContent = base\n ? { ...base, platform: ctx.platform, data }\n : { id: 0, themeId: s.themeId ?? 0, slug: key, platform: ctx.platform, data };\n patch({ [key]: { content: optimistic, saving: true, error: null } });\n return new Promise<ActionResult<ThemeContent>>((resolve) => {\n const job: SaveJob = { data, resolve };\n let slot = slots.get(key);\n if (!slot) slots.set(key, (slot = { running: false, waiting: null }));\n if (slot.running) {\n slot.waiting?.resolve(fail(superseded()));\n slot.waiting = job;\n return;\n }\n void send(key, slot, job);\n }) as Promise<ActionResult<ThemeContent<T>>>;\n },\n section: <T>(slug: string) => section(slug) as ThemeSectionState<T>,\n };\n}\n","/**\n * The wishlist store (T3.5; M3 plan D4). The signed-in customer's saved SKUs; empty and `idle`\n * for everyone else. Fixes from the old `WishlistProvider` (characterisation cases `wish-*`):\n * cleared when the customer changes, a saved SKU is not sent again, removal is optimistic, and\n * \"move to cart\" deletes the entry only after the cart add worked.\n */\nimport type { WishlistItem } from '../types/wishlist';\nimport { createLatest, createSerialQueue, type Current } from './runtime/concurrency';\nimport type { StoreContext } from './runtime/context';\nimport {\n fail,\n ok,\n storeError,\n toStoreError,\n type ActionResult,\n type StoreError,\n} from './runtime/errors';\nimport { createStore, readOnly } from './runtime/store';\nimport { isInWishlist } from './selectors';\nimport type { WishlistState, WishlistStore } from './types/wishlist';\n\ntype Action = 'refresh' | 'add' | 'remove' | 'toggle' | 'moveToCart';\n\nconst INITIAL: WishlistState = {\n status: 'idle',\n refreshing: false,\n items: [],\n pending: { adding: [], removing: [], moving: [] },\n error: null,\n};\n\nconst isId = (value: number) => Number.isInteger(value) && value > 0;\nconst without = (list: readonly number[], value: number) => list.filter((v) => v !== value);\nconst superseded = () =>\n fail(storeError('superseded', 'The shopper changed while the wishlist was being updated.'));\n\nexport function createWishlistStore(ctx: StoreContext): WishlistStore {\n const store = createStore<WishlistState>(INITIAL, { onListenerError: ctx.onListenerError });\n const latest = createLatest();\n const queue = createSerialQueue();\n const adds = new Map<number, Promise<ActionResult>>();\n const removes = new Map<number, Promise<ActionResult>>();\n const moves = new Map<number, Promise<ActionResult>>();\n\n const customerId = () => {\n const identity = ctx.identity.getSnapshot();\n return identity.kind === 'customer' ? identity.customerId : null;\n };\n const epoch = () => (ctx.isDisposed() ? -1 : ctx.identity.getSnapshot().epoch);\n const snapshot = () => store.getSnapshot();\n const has = (skuId: number) => isInWishlist(snapshot(), skuId);\n\n /** Keeps the error in the snapshot and emits it; `superseded` belongs to nobody's screen. */\n function report(action: Action, error: StoreError, started: number | null = null) {\n if (error.kind === 'superseded' || (started !== null && epoch() !== started)) return;\n store.update((s) => ({ ...s, error }));\n ctx.events.emit({ type: 'error', store: 'wishlist', action, error });\n }\n\n function refuse(action: Action, error: StoreError): ActionResult<never> {\n report(action, error);\n return fail(error);\n }\n\n /** Waits for hydration; answers `signed-out` (kept in the snapshot) without a request. */\n async function guard(action: Action): Promise<ActionResult<never> | null> {\n await ctx.ready();\n if (customerId() !== null) return null;\n return refuse(action, storeError('signed-out', 'Sign in to use the wishlist.'));\n }\n\n /**\n * Sends one mutation in call order, only while the shopper is still the one who started it\n * (`started`). `{ current: false }`: the shopper changed; the state was already reset.\n */\n function send<T>(started: number, run: () => Promise<T>): Promise<Current<T>> {\n return queue(async () =>\n epoch() === started ? ctx.inEpoch(run) : ({ current: false } as const),\n );\n }\n\n /** Runs `run` once per key at a time: a second call while it runs gets the same promise. */\n function once(\n flights: Map<number, Promise<ActionResult>>,\n key: number,\n run: () => Promise<ActionResult>,\n ): Promise<ActionResult> {\n const existing = flights.get(key);\n if (existing) return existing;\n const promise = run().finally(() => flights.delete(key));\n flights.set(key, promise);\n return promise;\n }\n\n // Identity: the items belong to one customer. Any other shopper sees the initial state.\n let owner: number | null = null;\n ctx.onDispose(\n ctx.identity.subscribe(() => {\n const id = customerId();\n if (id === owner) return;\n owner = id;\n store.set(INITIAL);\n }),\n );\n ctx.onDispose(ctx.events.on('auth:signed-in', () => void refresh()));\n ctx.autoLoad(() => {\n if (customerId() !== null) void refresh();\n });\n\n async function refresh(): Promise<ActionResult<readonly WishlistItem[]>> {\n const refused = await guard('refresh');\n if (refused) return refused;\n const loadedFor = customerId();\n store.update((s) => ({\n ...s,\n status: s.status === 'ready' ? 'ready' : 'loading',\n refreshing: s.status === 'ready',\n error: null,\n }));\n let outcome: Current<Current<WishlistItem[]>>;\n try {\n outcome = await latest(() => ctx.inEpoch(() => ctx.client.wishlist.list()));\n } catch (caught) {\n const error = toStoreError(caught);\n store.update((s) => ({\n ...s,\n status: s.status === 'ready' ? 'ready' : 'error',\n refreshing: false,\n }));\n report('refresh', error);\n return fail(error);\n }\n if (!outcome.current) return superseded(); // a newer refresh owns the flags\n if (!outcome.value.current) {\n // The epoch moved. The same customer (e.g. their guest session was replaced): ask again.\n // Anyone else: the state was reset for them.\n if (!ctx.isDisposed() && customerId() === loadedFor) return refresh();\n return superseded();\n }\n const items = outcome.value.value;\n store.update((s) => ({\n ...s,\n status: 'ready',\n refreshing: false,\n // An entry being removed stays hidden, although the server listed it a moment ago.\n items: items.filter((item) => !s.pending.removing.includes(item.id)),\n }));\n return ok(items);\n }\n\n /** `add` after its guards. Registers the flight synchronously (`toggle` relies on that). */\n function addNow(skuId: number): Promise<ActionResult> {\n return once(adds, skuId, async () => {\n if (has(skuId)) {\n // Already saved: the backend would answer 400 (wish-02).\n if (snapshot().error) store.update((s) => ({ ...s, error: null }));\n return ok(undefined);\n }\n const started = epoch();\n store.update((s) => ({\n ...s,\n error: null,\n pending: { ...s.pending, adding: [...s.pending.adding, skuId] },\n }));\n const done = () => {\n if (epoch() === started) {\n store.update((s) => ({\n ...s,\n pending: { ...s.pending, adding: without(s.pending.adding, skuId) },\n }));\n }\n };\n try {\n const sent = await send(started, () => ctx.client.wishlist.add(skuId));\n if (!sent.current) return superseded();\n // The create answer has no item data: reload, then the button stops spinning.\n await refresh();\n done();\n return epoch() === started ? ok(undefined) : superseded();\n } catch (caught) {\n const error = toStoreError(caught);\n if (error.kind === 'http' && error.status === 400) {\n // Saved meanwhile on another device: the backend refuses duplicates with a 400.\n await refresh();\n if (epoch() === started && has(skuId)) {\n done();\n return ok(undefined);\n }\n }\n done();\n report('add', error, started);\n return epoch() === started ? fail(error) : superseded();\n }\n });\n }\n\n /**\n * `remove` after its guards: optimistic, rolled back to the same place on failure. Only ids\n * of the loaded list are sent: the backend deletes any customer's entry by id and answers\n * 204 even when nothing matched (S2), so its answer proves nothing about our own list.\n */\n function removeNow(wishlistId: number, action: Action): Promise<ActionResult> {\n return once(removes, wishlistId, async () => {\n const state = snapshot();\n const index = state.items.findIndex((item) => item.id === wishlistId);\n if (index < 0) {\n return refuse(action, storeError('validation', 'This entry is not in the wishlist.'));\n }\n const item = state.items[index]!;\n const started = epoch();\n store.set({\n ...state,\n error: null,\n items: state.items.filter((i) => i !== item),\n pending: { ...state.pending, removing: [...state.pending.removing, wishlistId] },\n });\n const settle = (items: (s: WishlistState) => readonly WishlistItem[]) =>\n store.update((s) => ({\n ...s,\n items: items(s),\n pending: { ...s.pending, removing: without(s.pending.removing, wishlistId) },\n }));\n try {\n const sent = await send(started, () => ctx.client.wishlist.remove(wishlistId));\n if (!sent.current) return superseded();\n settle((s) => s.items);\n return ok(undefined);\n } catch (caught) {\n const error = toStoreError(caught);\n settle((s) =>\n s.items.some((i) => i.id === wishlistId)\n ? s.items\n : [...s.items.slice(0, index), item, ...s.items.slice(index)],\n );\n report(action, error);\n return fail(error);\n }\n });\n }\n\n async function add(skuId: number): Promise<ActionResult> {\n const refused = await guard('add');\n if (refused) return refused;\n if (!isId(skuId)) {\n return refuse('add', storeError('validation', 'A SKU id is a positive integer.'));\n }\n return addNow(skuId);\n }\n\n async function remove(wishlistId: number): Promise<ActionResult> {\n const refused = await guard('remove');\n return refused ?? removeNow(wishlistId, 'remove');\n }\n\n async function toggle(skuId: number): Promise<ActionResult<{ saved: boolean }>> {\n const refused = await guard('toggle');\n if (refused) return refused;\n if (!isId(skuId)) {\n return refuse('toggle', storeError('validation', 'A SKU id is a positive integer.'));\n }\n // A second tap while the first add runs means \"remove it again\": wait for the add.\n const adding = adds.get(skuId);\n if (adding) {\n const added = await adding;\n if (!added.ok) return added;\n }\n const saved = snapshot().items.find((item) => item.sku?.id === skuId);\n if (saved) {\n const removed = await removeNow(saved.id, 'toggle');\n return removed.ok ? ok({ saved: false }) : removed;\n }\n const added = await addNow(skuId);\n return added.ok ? ok({ saved: true }) : added;\n }\n\n async function moveToCart(wishlistId: number, quantity = 1): Promise<ActionResult> {\n const refused = await guard('moveToCart');\n if (refused) return refused;\n const moving = moves.get(wishlistId);\n if (moving) return moving;\n const item = snapshot().items.find((i) => i.id === wishlistId);\n if (!item) {\n return refuse('moveToCart', storeError('validation', 'This entry is not in the wishlist.'));\n }\n // The backend still lists deleted and hidden products (W9); old entries may lack a SKU.\n if (!item.available || !item.sku) {\n return refuse('moveToCart', storeError('validation', 'This item is no longer available.'));\n }\n if (!isId(quantity)) {\n return refuse('moveToCart', storeError('validation', 'The quantity is a positive integer.'));\n }\n const skuId = item.sku.id;\n return once(moves, wishlistId, async () => {\n const started = epoch();\n store.update((s) => ({\n ...s,\n error: null,\n pending: { ...s.pending, moving: [...s.pending.moving, wishlistId] },\n }));\n const done = () => {\n if (epoch() === started) {\n store.update((s) => ({\n ...s,\n pending: { ...s.pending, moving: without(s.pending.moving, wishlistId) },\n }));\n }\n };\n // Read lazily: the cart store is built next to this one (ctx.stores, M3 plan B7).\n const added = await ctx.stores.cart.add({ skuId, quantity });\n if (epoch() !== started) return superseded();\n if (!added.ok) {\n // The entry stays: the old provider deleted it anyway and the item was lost (wish-03).\n done();\n report('moveToCart', added.error, started);\n return fail(added.error);\n }\n // If this fails the item is in both places: reported, nothing lost.\n const removed = await removeNow(wishlistId, 'moveToCart');\n done();\n return removed;\n });\n }\n\n return {\n ...readOnly(store),\n refresh,\n add,\n remove,\n toggle,\n moveToCart,\n has,\n };\n}\n","/**\n * `createGrowupsellStores`: one call per app instance, i.e. per browser session or per server\n * request, never at module level (ADR-024; M3 plan B9). Synchronous, no I/O.\n */\nimport type { Client } from '../http/client';\nimport { createAuthStore } from './auth';\nimport { createBusinessStore } from './business';\nimport { createCartStore } from './cart';\nimport { createCatalogStore } from './catalog';\nimport { createCheckoutStore } from './checkout';\nimport { createListingStore } from './listing';\nimport { createProductDetailStore } from './productDetail';\nimport { createReferralStore } from './referral';\nimport {\n createRuntime,\n type GrowupsellStoresOptions,\n type Identity,\n type StoreRegistry,\n} from './runtime/context';\nimport type { EventBus } from './runtime/events';\nimport type { Store } from './runtime/store';\nimport { createSearchSuggestionsStore } from './searchSuggestions';\nimport { createSessionStore } from './session';\nimport { createThemeConfigStore } from './themeConfig';\nimport type { ListingInput, ListingStore } from './types/listing';\nimport type { ProductDetailInput, ProductDetailStore } from './types/productDetail';\nimport type { SearchSuggestionsOptions, SearchSuggestionsStore } from './types/searchSuggestions';\nimport { createWishlistStore } from './wishlist';\n\nexport type { GrowupsellStoresOptions } from './runtime/context';\n\n/**\n * Factories for per-screen stores (listing, product detail, search suggestions; M3 plan B11).\n * One line each: `createListing(input: ListingInput): ListingStore`. Each returned store has\n * `dispose()` and is also disposed by the root `dispose()` (it registers with `ctx.onDispose`).\n */\ninterface ScreenStoreFactories {\n createListing(input?: ListingInput): ListingStore;\n createProductDetail(input: ProductDetailInput): ProductDetailStore;\n createSearchSuggestions(options?: SearchSuggestionsOptions): SearchSuggestionsStore;\n}\n\nexport interface GrowupsellStores extends StoreRegistry, ScreenStoreFactories {\n /** Same credentials as the stores: for stateless calls (orders, returns, profile). */\n readonly client: Client;\n readonly identity: Store<Identity>;\n readonly hydrated: Store<boolean>;\n readonly events: EventBus;\n /** Idempotent: the same promise every time. Never rejects. */\n hydrate(): Promise<void>;\n /** Re-reads storage (e.g. on the web `storage` event from another tab). Never rejects. */\n rehydrate(): Promise<void>;\n /** Stops wiring and drops every later result. Stores keep their last snapshot. */\n dispose(): void;\n}\n\n/**\n * Builds the stores of one shopper. Throws `TypeError` when `baseURL`, `businessId` or\n * `platform` is missing or invalid. Then call `hydrate()` on the client (not on the server):\n * until it finishes, every store shows its `getServerSnapshot()`.\n */\nexport function createGrowupsellStores(options: GrowupsellStoresOptions): GrowupsellStores {\n const runtime = createRuntime(options);\n const { ctx } = runtime;\n\n const registry: StoreRegistry = {\n session: createSessionStore(ctx),\n auth: createAuthStore(ctx),\n cart: createCartStore(ctx),\n wishlist: createWishlistStore(ctx),\n checkout: createCheckoutStore(ctx),\n business: createBusinessStore(ctx),\n catalog: createCatalogStore(ctx),\n themeConfig: createThemeConfigStore(ctx),\n referral: createReferralStore(ctx),\n };\n runtime.attach(registry);\n\n const screens: ScreenStoreFactories = {\n createListing: (input) => createListingStore(ctx, input),\n createProductDetail: (input) => createProductDetailStore(ctx, input),\n createSearchSuggestions: (options) => createSearchSuggestionsStore(ctx, options),\n };\n\n return {\n ...registry,\n ...screens,\n client: ctx.client,\n identity: ctx.identity,\n hydrated: runtime.hydrated,\n events: ctx.events,\n hydrate: runtime.hydrate,\n rehydrate: runtime.rehydrate,\n dispose: runtime.dispose,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAkBA,SAAS,MAAS,KAAmC;AACnD,MAAI;AACF,WAAO,QAAQ,QAAQ,IAAI,CAAC;AAAA,EAC9B,SAAS,OAAO;AACd,WAAO,QAAQ,OAAO,KAAK;AAAA,EAC7B;AACF;AAMO,SAAS,eAAkE;AAChF,MAAI,aAAa;AACjB,SAAO,OAAU,QAA+C;AAC9D,UAAM,OAAO,EAAE;AACf,QAAI;AACF,YAAM,QAAQ,MAAM,MAAM,GAAG;AAC7B,aAAO,SAAS,aAAa,EAAE,SAAS,MAAM,MAAM,IAAI,EAAE,SAAS,MAAM;AAAA,IAC3E,SAAS,OAAO;AACd,UAAI,SAAS,WAAY,QAAO,EAAE,SAAS,MAAM;AACjD,YAAM;AAAA,IACR;AAAA,EACF;AACF;AAGO,SAAS,qBAA0E;AACxF,QAAM,WAAW,oBAAI,IAAyB;AAC9C,SAAO,CAAI,KAAQ,QAAsC;AACvD,UAAM,WAAW,SAAS,IAAI,GAAG;AACjC,QAAI,SAAU,QAAO;AACrB,UAAM,UAAU,MAAM,GAAG,EAAE,QAAQ,MAAM;AACvC,UAAI,SAAS,IAAI,GAAG,MAAM,QAAS,UAAS,OAAO,GAAG;AAAA,IACxD,CAAC;AACD,aAAS,IAAI,KAAK,OAAO;AACzB,WAAO;AAAA,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OAAO,OAAO;AACzC,eAAO,KAAK,MAAM,KAAK;AAAA,MACzB;AAEA,YAAM,UAAU,MAAM,UAAU,YAAY,YAAY;AACxD,WAAK;AACL,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAEA,SAAO;AAAA,IACL,GAAG,SAAS,KAAK;AAAA,IACjB;AAAA,IACA;AAAA,IACA;AAAA,IACA,QAAAE;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;AC/QO,SAAS,uBAAuB,SAAoD;AACzF,QAAME,WAAU,cAAc,OAAO;AACrC,QAAM,EAAE,IAAI,IAAIA;AAEhB,QAAM,WAA0B;AAAA,IAC9B,SAAS,mBAAmB,GAAG;AAAA,IAC/B,MAAM,gBAAgB,GAAG;AAAA,IACzB,MAAM,gBAAgB,GAAG;AAAA,IACzB,UAAU,oBAAoB,GAAG;AAAA,IACjC,UAAU,oBAAoB,GAAG;AAAA,IACjC,UAAU,oBAAoB,GAAG;AAAA,IACjC,SAAS,mBAAmB,GAAG;AAAA,IAC/B,aAAa,uBAAuB,GAAG;AAAA,IACvC,UAAU,oBAAoB,GAAG;AAAA,EACnC;AACA,EAAAA,SAAQ,OAAO,QAAQ;AAEvB,QAAM,UAAgC;AAAA,IACpC,eAAe,CAAC,UAAU,mBAAmB,KAAK,KAAK;AAAA,IACvD,qBAAqB,CAAC,UAAU,yBAAyB,KAAK,KAAK;AAAA,IACnE,yBAAyB,CAACC,aAAY,6BAA6B,KAAKA,QAAO;AAAA,EACjF;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,GAAG;AAAA,IACH,QAAQ,IAAI;AAAA,IACZ,UAAU,IAAI;AAAA,IACd,UAAUD,SAAQ;AAAA,IAClB,QAAQ,IAAI;AAAA,IACZ,SAASA,SAAQ;AAAA,IACjB,WAAWA,SAAQ;AAAA,IACnB,SAASA,SAAQ;AAAA,EACnB;AACF;","names":["SUPERSEDED","INITIAL","runtime","derive","criteria","search","derive","productId","disposedError","runtime","superseded","INITIAL","superseded","item","toggle","added","runtime","options"]}
|