@misiki/gocommerce-connector 0.29.0 → 0.31.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/{index-DOlNI60Y.d.cts → index-CSqvRZQ4.d.cts} +136 -3
- package/dist/{index-DOlNI60Y.d.ts → index-CSqvRZQ4.d.ts} +136 -3
- package/dist/index.cjs +185 -23
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +185 -24
- package/dist/index.js.map +1 -1
- package/dist/services/index.cjs +183 -23
- package/dist/services/index.cjs.map +1 -1
- package/dist/services/index.d.cts +1 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/index.js +183 -23
- package/dist/services/index.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/errors.ts","../../src/rest-guard.ts","../../src/browser.ts","../../src/services/base.service.ts","../../src/money.ts","../../src/map.ts","../../src/cache.ts","../../src/services/facts.ts","../../src/services/catalog.ts","../../src/services/product-service.ts","../../src/services/search-service.ts","../../src/services/meilisearch-service.ts","../../src/services/category-service.ts","../../src/services/collection-service.ts","../../src/services/cart-service.ts","../../src/services/customizer-service.ts","../../src/services/checkout-service.ts","../../src/services/payment-method-service.ts","../../src/services/coupon-service.ts","../../src/services/order-service.ts","../../src/services/user-service.ts","../../src/services/address-service.ts","../../src/services/wishlist-service.ts","../../src/services/review-service.ts","../../src/services/google-review-service.ts","../../src/services/menu-service.ts","../../src/static-store.ts","../../src/services/newsletter-service.ts","../../src/services/store-service.ts","../../src/services/page-service.ts","../../src/services/layout-service.ts","../../src/services/vendor-service.ts","../../src/services/misc-services.ts","../../src/services/variant-service.ts","../../src/services/whatsapp-service.ts","../../src/services/b2b-service.ts"],"names":["id","c","page","limit","env","quote","reported","clean","enc"],"mappings":";AAeO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;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AAA,CAAI,OAAA,EAAyB;AAAA,EAC7G;AACD;AAEA,IAAM,KAAK,CAAC,CAAA,KAAuB,kBAAA,CAAmB,MAAA,CAAO,CAAC,CAAC,CAAA;AAQ/D,IAAM,IAAA,uBAAW,GAAA,EAAoB;AACrC,SAAS,WAAW,OAAA,EAAyB;AAC5C,EAAA,IAAI,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA;AAC1B,EAAA,IAAI,CAAC,GAAA,EAAK;AACT,IAAA,MAAM,IAAK,UAAA,CAA0D,MAAA;AACrE,IAAA,GAAA,GAAM,GAAG,UAAA,IAAa,IAAK,GAAG,IAAA,CAAK,GAAA,GAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,QAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAC5F,IAAA,IAAA,CAAK,GAAA,CAAI,SAAS,GAAG,CAAA;AAAA,EACtB;AACA,EAAA,OAAO,GAAA;AACR;AAEO,IAAM,UAAA,GAAa,IAAI,UAAA","file":"index.js","sourcesContent":["/**\n * The two ways a call through this connector fails.\n *\n * Both carry `message`, because the storefront shows `err.message` in a toast\n * and has no other field it reliably reads.\n */\n\n/**\n * What the engine refused, in a shape the storefront can show a shopper.\n *\n * `status` travels because the difference between 404 and 409 is the\n * difference between \"that product is gone\" and \"somebody just bought the last\n * one\", and a storefront renders those differently. `code` is the engine's own\n * taxonomy (`not_found`, `validation`, `conflict`, `unauthorized`, …).\n */\nexport class GoCommerceError extends Error {\n\treadonly status: number\n\treadonly code: string | undefined\n\treadonly details: unknown\n\n\tconstructor(message: string, status: number, code?: string, details?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'GoCommerceError'\n\t\tthis.status = status\n\t\tthis.code = code\n\t\tthis.details = details\n\t}\n}\n\n/**\n * A storefront feature this engine has no model for — reels, chat, a vendor's\n * commission statement — or one that lives in a module this particular build\n * did not compile in.\n *\n * The name is the one every connector in the family throws, so a storefront\n * that branches on `err.name === 'NotSupportedError'` treats GoCommerce the same\n * as the rest.\n */\nexport class NotSupportedError extends Error {\n\treadonly service: string\n\treadonly method: string\n\n\tconstructor(service: string, method: string, detail?: string) {\n\t\tsuper(`${service}.${method}() is not supported by GoCommerce${detail ? `: ${detail}` : '.'}`)\n\t\tthis.name = 'NotSupportedError'\n\t\tthis.service = service\n\t\tthis.method = method\n\t}\n}\n","/**\n * Litekart REST paths, intercepted.\n *\n * Every connector in the family exposes `get/post/put/patch/delete(path)` on\n * its BaseService because Litekart's does, and a little storefront code still\n * calls them with a Litekart path — `storeService.post('/api/…')`. Those paths\n * are relative, so they would land on the storefront's own origin, where\n * nothing answers.\n *\n * GoCommerce's own routes also start with `/api/`, which is why this connector\n * never sends an engine request through those verbs: every engine call goes\n * through `BaseService.engine()` with an absolute URL, and the storefront's own\n * guard (which patches the same verbs) cannot reach it either. What arrives\n * here is only ever an inherited Litekart path.\n *\n * Reads for a collection resolve empty (a store legitimately has none); reads\n * for one record and every write throw, because a blank detail page reads as\n * broken and a silent success would tell a shopper their enquiry was saved when\n * nothing left the browser. Each distinct path is reported once.\n */\n\nconst COLLECTION_SEGMENTS = new Set([\n\t'all',\n\t'list',\n\t'list-by-parent',\n\t'list-public',\n\t'latest',\n\t'search',\n\t'public',\n\t'public-details',\n\t'me',\n\t'multiple',\n])\n\nconst emptyResult = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 })\n\nconst addressesOneRecord = (url: string) => {\n\tconst segments = url.split('?')[0].split('/').filter(Boolean)\n\tif (segments.length < 3) return false\n\treturn !COLLECTION_SEGMENTS.has(segments[segments.length - 1].toLowerCase())\n}\n\nconst reported = new Set<string>()\n\nconst report = (method: string, url: string) => {\n\tconst key = `${method} ${url.split('?')[0]}`\n\tif (reported.has(key)) return\n\treported.add(key)\n\tconsole.warn(\n\t\t`[gocommerce] no native implementation for \\`${key}\\` — that is a Litekart REST path, and it was not called.`,\n\t)\n}\n\n/**\n * Answers a Litekart REST path from data the storefront holds (menus,\n * countries, plugin toggles…). Return `undefined` to fall through.\n */\nexport type RestResolver = (url: string) => Promise<unknown> | unknown | undefined\n\nlet localResolver: RestResolver | undefined\n\nexport const serveRestLocally = (resolver: RestResolver) => {\n\tlocalResolver = resolver\n}\n\nexport const resolveRestLocally = async (method: string, url: string) => {\n\tif (method === 'get') {\n\t\tconst local = await localResolver?.(url)\n\t\tif (local !== undefined) return local\n\t}\n\treport(method, url)\n\tif (method !== 'get' || addressesOneRecord(url)) {\n\t\tthrow new Error(`This feature is not available on this store (gocommerce).`)\n\t}\n\treturn emptyResult()\n}\n","/**\n * The state this connector keeps in the shopper's browser, and only there.\n *\n * The storefront renders some services from a server singleton shared by every\n * shopper, so nothing about one shopper may live in module scope: a token held\n * in a static field would be served to the next request. Everything here is\n * read from `localStorage` or `document.cookie` at the moment it is needed, and\n * on the server every reader answers \"nothing\".\n *\n * What lives here, and why the engine does not hold it:\n *\n * - the account session token — ext/identity is bearer-only and sets no cookie;\n * - the `me` and `connect.sid` cookies — the storefront's own idea of who is\n * signed in, which every connector in the family writes itself;\n * - `cart_id` — the storefront reads it, the connector writes it;\n * - per-cart checkout details — the engine's cart holds lines and an email, and\n * takes the address, phone and delivery choice only in the checkout request,\n * so they are kept here until then;\n * - order access tokens — returned once, at checkout, and the only way a guest\n * can read an order back;\n * - the wishlist token — ext/wishlist keys a list by its own token.\n */\nimport type { AppliedDiscount, AuthResponse, Customer } from './engine'\n\nexport const inBrowser = (): boolean => typeof window !== 'undefined' && typeof document !== 'undefined'\n\nexport function readLocal(key: string): string | null {\n\tif (!inBrowser()) return null\n\ttry {\n\t\treturn window.localStorage.getItem(key)\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function writeLocal(key: string, value: string): void {\n\tif (!inBrowser()) return\n\ttry {\n\t\twindow.localStorage.setItem(key, value)\n\t} catch {\n\t\t// Private mode or a full quota. The call it belongs to still succeeds;\n\t\t// only the memory of it is lost.\n\t}\n}\n\nexport function removeLocal(key: string): void {\n\tif (!inBrowser()) return\n\ttry {\n\t\twindow.localStorage.removeItem(key)\n\t} catch {\n\t\t// see writeLocal\n\t}\n}\n\nfunction readJSON<T>(key: string): T | null {\n\tconst raw = readLocal(key)\n\tif (!raw) return null\n\ttry {\n\t\treturn JSON.parse(raw) as T\n\t} catch {\n\t\treturn null\n\t}\n}\n\nconst YEAR = 60 * 60 * 24 * 365\n\nfunction setCookie(name: string, value: string, maxAge = YEAR): void {\n\tif (!inBrowser()) return\n\tdocument.cookie = `${name}=${value}; path=/; max-age=${maxAge}; samesite=lax`\n}\n\nfunction clearCookie(name: string): void {\n\tif (!inBrowser()) return\n\tdocument.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`\n}\n\nexport function readCookie(name: string): string | null {\n\tif (!inBrowser()) return null\n\tfor (const pair of document.cookie.split(';')) {\n\t\tconst at = pair.indexOf('=')\n\t\tif (at < 0) continue\n\t\tif (pair.slice(0, at).trim() === name) return pair.slice(at + 1).trim()\n\t}\n\treturn null\n}\n\n// ---------------------------------------------------------------- session\n\nconst TOKEN = 'gocommerce_token'\n\n/** The ext/identity bearer token, when a shopper is signed in in this browser. */\nexport const sessionToken = (): string | null => readLocal(TOKEN)\n\n/**\n * The user object the storefront keeps in its `me` cookie. `userId` is its\n * signed-in test and `role: 'USER'` its shopper test; the rest fills forms.\n */\nexport function toMe(c: Customer) {\n\tconst [firstName, ...rest] = (c.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: String(c.id),\n\t\tuserId: String(c.id),\n\t\temail: c.email,\n\t\tphone: c.phone || null,\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\tname: c.name ?? '',\n\t\tfullName: c.name ?? '',\n\t\tavatar: null,\n\t\trole: 'USER',\n\t\temailVerified: c.email_verified,\n\t\tphoneVerified: !!c.phone_verified,\n\t\tstoreId: null,\n\t}\n}\n\nexport type Me = ReturnType<typeof toMe>\n\n/**\n * Signs this browser in: the token for the engine, the two cookies for the\n * storefront. `connect.sid` carries no secret — the storefront's server only\n * checks that it exists — so it holds a marker rather than the token, which\n * would otherwise ride along on every request to the storefront's origin.\n */\nexport function startSession(auth: AuthResponse): Me {\n\twriteLocal(TOKEN, auth.token)\n\tconst me = toMe(auth.record)\n\tconst expires = Math.max(60, Math.floor((Date.parse(auth.expires_at) - Date.now()) / 1000)) || YEAR\n\tsetCookie('me', encodeURIComponent(JSON.stringify(me)), expires)\n\tsetCookie('connect.sid', 'gocommerce', expires)\n\treturn me\n}\n\n/** Refreshes the `me` cookie after a profile change, keeping the session. */\nexport function updateMe(c: Customer): Me {\n\tconst me = toMe(c)\n\tsetCookie('me', encodeURIComponent(JSON.stringify(me)))\n\treturn me\n}\n\nexport function endSession(): void {\n\tremoveLocal(TOKEN)\n\tclearCookie('me')\n\tclearCookie('connect.sid')\n}\n\n/** The `me` cookie, decoded — the name and email a review is signed with. */\nexport function currentMe(): Partial<Me> | null {\n\tconst raw = readCookie('me')\n\tif (!raw) return null\n\ttry {\n\t\treturn JSON.parse(decodeURIComponent(raw))\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/**\n * The browser Meta's pixel ran in, which the engine's Conversions API module\n * reads off the order as `metadata.meta_capi` (D160): Meta's own first-party\n * cookies, the user agent and the page. Only where the pixel is running on this\n * page and its `_fbp` cookie is there: the storefront starts the pixel only\n * where the shopper allows ad cookies, and the cookie outlives a choice taken\n * back, so the server sends a purchase exactly when the browser was allowed\n * to. The page goes without its query, which can carry anything.\n */\nexport function metaBrowser(): Record<string, string> | undefined {\n\tconst fbp = readCookie('_fbp')\n\tif (!fbp || typeof (window as { fbq?: unknown }).fbq !== 'function') return undefined\n\tconst fbc = readCookie('_fbc')\n\treturn {\n\t\tfbp,\n\t\t...(fbc ? { fbc } : {}),\n\t\tclient_user_agent: window.navigator.userAgent,\n\t\tevent_source_url: window.location.origin + window.location.pathname,\n\t}\n}\n\n// ------------------------------------------------------------- attribution\n\n/**\n * Where the shopper came from, as the storefront recorded it on arrival: the first visit with a\n * source in the last 30 days and the latest, under `gc_attribution` in this browser's storage.\n * The storefront writes it only with the shopper's leave for analytics, and it goes nowhere but\n * the store's own checkout (GoCommerce D168).\n *\n * Only the names the engine reads are passed on, each a short string, and a visit older than 30\n * days is dropped here as well as there, so a tab left open for a month does not credit an old ad.\n */\nexport const ATTRIBUTION_KEY = 'gc_attribution'\nconst ATTRIBUTION_DAYS = 30\nconst TOUCH_FIELDS = [\n\t'utm_source',\n\t'utm_medium',\n\t'utm_campaign',\n\t'utm_content',\n\t'utm_term',\n\t'gclid',\n\t'gbraid',\n\t'wbraid',\n\t'fbclid',\n\t'ttclid',\n\t'msclkid',\n\t'referrer',\n\t'at',\n] as const\n\ntype Touch = Partial<Record<(typeof TOUCH_FIELDS)[number], string>>\n\nfunction cleanTouch(raw: unknown, now: number): Touch | undefined {\n\tif (!raw || typeof raw !== 'object') return undefined\n\tconst at = Date.parse(String((raw as Touch).at ?? ''))\n\t// A date ahead of this clock by more than a day would never expire.\n\tif (!Number.isFinite(at) || now - at > ATTRIBUTION_DAYS * 86_400_000 || at - now > 86_400_000) return undefined\n\tconst out: Touch = {}\n\tfor (const k of TOUCH_FIELDS) {\n\t\tconst v = (raw as Record<string, unknown>)[k]\n\t\tif (typeof v === 'string' && v.trim()) out[k] = v.trim().slice(0, 200)\n\t}\n\t// A visit naming no source is none.\n\treturn Object.keys(out).length > 1 ? out : undefined\n}\n\nexport function landingAttribution(now = Date.now()): { first?: Touch; last?: Touch } | undefined {\n\tconst saved = readJSON<{ first?: unknown; last?: unknown }>(ATTRIBUTION_KEY)\n\tconst last = cleanTouch(saved?.last, now)\n\t// A stale first visit leaves the last one as the first in the window.\n\tconst first = cleanTouch(saved?.first, now) ?? last\n\tif (!first && !last) return undefined\n\treturn { ...(first ? { first } : {}), ...(last ? { last } : {}) }\n}\n\n// ---------------------------------------------------------------- cart\n\n/** `localStorage.cart_id`, the storefront's own key, with its stale spellings refused. */\nexport function storedCartId(): string | null {\n\tconst v = readLocal('cart_id')\n\tif (!v || v === 'undefined' || v === 'null') return null\n\treturn v\n}\n\nexport const rememberCartId = (id: string): void => writeLocal('cart_id', id)\n\n/** The storefront's address shape, as its checkout form builds it. */\nexport type StorefrontAddress = {\n\tid?: string\n\tfirstName?: string\n\tlastName?: string\n\temail?: string\n\tphone?: string\n\taddress_1?: string\n\taddress_2?: string\n\tlocality?: string\n\tcity?: string\n\tstate?: string\n\tzip?: string\n\tcountry?: string\n\tcountryCode?: string\n\t[key: string]: unknown\n}\n\nexport type CartExtras = {\n\tphone?: string\n\tshippingAddress?: StorefrontAddress | null\n\tbillingAddress?: StorefrontAddress | null\n\tshippingRateId?: string | null\n\tshippingRate?: { id: string; name: string; minor: number; currency: string } | null\n\tdiscount?: AppliedDiscount | null\n\t/**\n\t * The Idempotency-Key of the last checkout attempt, the body it was sent with, and where\n\t * Meta's pixel ran then, which a retry sends again unchanged.\n\t */\n\tattempt?: { key: string; body: string; meta?: Record<string, string>; attribution?: Record<string, unknown> } | null\n}\n\nconst extrasKey = (cartId: string) => `gocommerce_cart_${cartId}`\n\nexport const cartExtras = (cartId: string): CartExtras => readJSON<CartExtras>(extrasKey(cartId)) ?? {}\n\nexport function saveCartExtras(cartId: string, patch: CartExtras): CartExtras {\n\tconst next = { ...cartExtras(cartId), ...patch }\n\twriteLocal(extrasKey(cartId), JSON.stringify(next))\n\treturn next\n}\n\nexport const forgetCartExtras = (cartId: string): void => removeLocal(extrasKey(cartId))\n\n// ---------------------------------------------------------------- orders\n\ntype PlacedOrder = { number: string; token: string; cartId: string; reference?: string }\n\nconst ORDERS = 'gocommerce_orders'\n\nexport const placedOrders = (): PlacedOrder[] => readJSON<PlacedOrder[]>(ORDERS) ?? []\n\n/**\n * Keeps an order's access token. The engine returns it exactly once — a\n * replayed checkout leaves it out — and without it a guest cannot read the\n * order back, so losing it here loses the order.\n */\nexport function rememberOrder(o: PlacedOrder): void {\n\tconst kept = placedOrders().filter((p) => p.number !== o.number)\n\t// Bounded: a shared computer should not accumulate a history forever.\n\twriteLocal(ORDERS, JSON.stringify([o, ...kept].slice(0, 50)))\n}\n\nexport const placedOrder = (number: string): PlacedOrder | undefined => placedOrders().find((p) => p.number === number)\n\nexport const placedOrderForCart = (cartId: string): PlacedOrder | undefined =>\n\tplacedOrders().find((p) => p.cartId === cartId)\n\nexport const placedOrderByReference = (reference: string): PlacedOrder | undefined =>\n\tplacedOrders().find((p) => p.reference === reference)\n\n// ---------------------------------------------------------------- wishlist\n\nconst WISHLIST = 'gocommerce_wishlist'\nexport const wishlistToken = (): string | null => readLocal(WISHLIST)\nexport const rememberWishlistToken = (token: string): void => writeLocal(WISHLIST, token)\nexport const forgetWishlistToken = (): void => removeLocal(WISHLIST)\n","import type { Credentials } from '../config'\nimport type { Envelope } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { resolveRestLocally } from '../rest-guard'\nimport { currentMe, sessionToken } from '../browser'\n\ntype Query = Record<string, string | number | boolean | null | undefined | (string | number)[]>\n\nexport type EngineRequest = {\n\tmethod?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\tquery?: Query\n\tbody?: unknown\n\theaders?: Record<string, string>\n\t/** Send the signed-in shopper's bearer token. Only ext/identity reads it. */\n\tauth?: boolean\n}\n\n/**\n * A media URL the shopper's browser can load. The engine answers its own\n * uploads root-relative (`/media/ab12.png`), which a browser resolves against\n * the storefront's origin, where no such file is. Through the proxy path when\n * one is set — a root-relative path that reads the same in SSR and in the\n * browser, so hydration agrees — and otherwise from the engine's origin.\n * Absolute URLs, such as pictures the media library links rather than holds,\n * pass through untouched.\n */\nexport function mediaUrl(url: string | null | undefined): string | null {\n\tif (!url) return null\n\tif (!url.startsWith('/') || url.startsWith('//')) return url\n\tconst { apiUrl, proxyPath } = BaseService.getCredentials()\n\treturn (proxyPath || apiUrl || '').trim().replace(/\\/+$/, '') + url\n}\n\n/**\n * BaseService — the one place this connector talks to the engine.\n *\n * - Credentials arrive through the static `setCredentials` (both hooks), never\n * a constructor, and merge: the storefront drops unset variables rather than\n * sending `undefined`, so a second call must not erase the first.\n * - Server-side, a service is built with SvelteKit's `fetch`; client-side, the\n * prebuilt singletons use the global one. Either way it is called with the\n * global object as receiver, because the browser's native fetch throws\n * \"Illegal invocation\" when called as a method of anything else.\n * - Every engine call goes through `engine()`, with an absolute URL. The\n * engine's own routes start with `/api/`, and the storefront patches this\n * class's `get/post/put/patch/delete` to swallow any relative `/api/` path\n * (see rest-guard.ts), so those verbs are kept for the Litekart paths the\n * storefront still sends and never used for the engine.\n * - Failures throw a `GoCommerceError`: an `Error` with the engine's message,\n * status and code, which is what the storefront toasts.\n */\nexport class BaseService {\n\tprivate static _credentials: Credentials = { apiUrl: '' }\n\tprotected _fetch: typeof fetch\n\n\tconstructor(fetchFn?: typeof fetch) {\n\t\tthis._fetch = fetchFn ?? ((input, init) => globalThis.fetch(input, init))\n\t}\n\n\tstatic setCredentials(creds: Partial<Credentials>): void {\n\t\tBaseService._credentials = { ...BaseService._credentials, ...creds }\n\t}\n\n\tstatic getCredentials(): Credentials {\n\t\treturn BaseService._credentials\n\t}\n\n\tprotected get creds(): Credentials {\n\t\treturn BaseService._credentials\n\t}\n\n\t/**\n\t * The store this call is for: the request host's subdomain under\n\t * `baseDomain`, else the static `store`, else the host itself when it is a\n\t * store's own domain (the engine answers only a verified one). Read per call,\n\t * never stored on the instance, because the server shares one process (and\n\t * one credentials object) across every concurrent request and each may be\n\t * for a different host.\n\t */\n\tprotected get store(): string | undefined {\n\t\tconst { baseDomain, store } = this.creds\n\t\tconst host = typeof window !== 'undefined' ? window.location?.hostname : requestHost?.()\n\t\treturn storeForHost(host, baseDomain) ?? store ?? ownDomain(host, baseDomain)\n\t}\n\n\t/**\n\t * The engine's base URL from wherever this code runs. In the browser a\n\t * configured proxy path wins, because the engine answers no CORS preflight.\n\t */\n\tprotected engineBase(): string {\n\t\tconst { apiUrl, proxyPath } = this.creds\n\t\tif (proxyPath && typeof window !== 'undefined' && window.location) {\n\t\t\treturn new URL(proxyPath, window.location.origin).href.replace(/\\/+$/, '')\n\t\t}\n\t\tconst url = (apiUrl ?? '').trim()\n\t\tif (!url) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'PUBLIC_GOCOMMERCE_API_URL is not set, so this storefront does not know where its commerce ' +\n\t\t\t\t\t'engine is. Point it at a running GoCommerce, e.g. http://127.0.0.1:8080.',\n\t\t\t\t0,\n\t\t\t)\n\t\t}\n\t\treturn url.replace(/\\/+$/, '')\n\t}\n\n\t/** An absolute engine URL for a path and query, without sending anything. */\n\tprotected engineURL(path: string, query?: Query): string {\n\t\treturn this.engineBase() + path + qs(query)\n\t}\n\n\t/**\n\t * One request to the engine, envelope and all.\n\t *\n\t * The body is read as text first, so a proxy's HTML error page is reported\n\t * as what it is rather than as a JSON parse error three frames away.\n\t */\n\tprotected async engine<T>(path: string, req: EngineRequest = {}): Promise<Envelope<T>> {\n\t\t// A language only means something on a read; a write's answer is a cart\n\t\t// or an order, whose lines keep the words they were bought under.\n\t\tconst lang = (req.method ?? 'GET') === 'GET' ? this.creds.language : undefined\n\t\tconst url = this.engineURL(path, lang ? { lang, ...req.query } : req.query)\n\t\tconst headers: Record<string, string> = { Accept: 'application/json', ...req.headers }\n\t\t// A form goes as it is: fetch writes its multipart Content-Type, boundary included.\n\t\tconst form = req.body instanceof FormData ? req.body : undefined\n\t\tif (req.body !== undefined && !form) headers['Content-Type'] = 'application/json'\n\t\tconst store = this.store\n\t\tif (store) headers['X-Store'] = store\n\t\tif (req.auth) {\n\t\t\tconst token = sessionToken()\n\t\t\tif (!token) throw new GoCommerceError('Please sign in to continue.', 401, 'unauthorized')\n\t\t\theaders.Authorization = `Bearer ${token}`\n\t\t}\n\n\t\tconst init: RequestInit = {\n\t\t\tmethod: req.method ?? 'GET',\n\t\t\theaders,\n\t\t\tbody: form ?? (req.body === undefined ? undefined : JSON.stringify(req.body)),\n\t\t}\n\t\tlet res: Response\n\t\ttry {\n\t\t\tres = await this._fetch.call(globalThis, url, init)\n\t\t} catch (cause) {\n\t\t\t// SvelteKit's server-side fetch applies the browser's CORS rule to a\n\t\t\t// universal load, and the engine sends no CORS headers. On the server\n\t\t\t// there is no browser to protect, so ask again with Node's own fetch;\n\t\t\t// in the browser the same call goes through PUBLIC_GOCOMMERCE_PROXY_PATH.\n\t\t\tif (typeof window === 'undefined' && /CORS/i.test(String((cause as Error)?.message))) {\n\t\t\t\ttry {\n\t\t\t\t\tres = await globalThis.fetch(url, init)\n\t\t\t\t} catch (again) {\n\t\t\t\t\tthrow unreachable(this.engineBase(), again)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow unreachable(this.engineBase(), cause)\n\t\t\t}\n\t\t}\n\t\treturn this.unwrap<T>(res)\n\t}\n\n\t/** The envelope opened: the payload, or the engine's error as a GoCommerceError. */\n\tprivate async unwrap<T>(res: Response): Promise<Envelope<T>> {\n\t\tconst text = await res.text()\n\t\tlet parsed: any = null\n\t\tif (text) {\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(text)\n\t\t\t} catch {\n\t\t\t\tthrow new GoCommerceError(\n\t\t\t\t\t`The commerce engine answered ${res.status} with something that is not JSON: ${text.slice(0, 120)}`,\n\t\t\t\t\tres.status,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tconst err = parsed?.error ?? {}\n\t\t\tthrow new GoCommerceError(\n\t\t\t\terr.message ?? `The commerce engine answered ${res.status}.`,\n\t\t\t\tres.status,\n\t\t\t\terr.code,\n\t\t\t\terr.details,\n\t\t\t)\n\t\t}\n\t\t// 204 is a success with nothing to say; the caller decides what that means.\n\t\treturn (parsed ?? { data: null }) as Envelope<T>\n\t}\n\n\t/** The bare payload, for the many callers that never look at `meta`. */\n\tprotected async data<T>(path: string, req: EngineRequest = {}): Promise<T> {\n\t\treturn (await this.engine<T>(path, req)).data\n\t}\n\n\t/**\n\t * Prices a cart at the signed-in shopper's customer-group prices. The\n\t * engine does this only for an account whose email is confirmed (403\n\t * otherwise), and the cart stays the shopper's either way — so a refusal\n\t * is not an error, and neither is a build without ext/identity. A refused\n\t * claim still gives the cart the account's email, which the claim would\n\t * have set, or the checkout asks the shopper for it again.\n\t */\n\tprotected async claimCartForAccount(cartId: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.engine('/x/identity/me/carts', { method: 'POST', body: { cart_id: cartId }, auth: true })\n\t\t} catch {\n\t\t\tconst email = currentMe()?.email\n\t\t\tif (email)\n\t\t\t\tawait this.engine(`/api/carts/${encodeURIComponent(cartId)}/email`, { method: 'PUT', body: { email } }).catch(\n\t\t\t\t\t() => undefined,\n\t\t\t\t)\n\t\t}\n\t}\n\n\t// ------------------------------------------------------------ Litekart verbs\n\n\t/**\n\t * The family's path-addressed verbs. An absolute URL is fetched as-is; a\n\t * relative one is a Litekart REST path, answered from the storefront's own\n\t * data where it has some and refused otherwise (rest-guard.ts).\n\t */\n\tget<T = any>(path: string): Promise<T> {\n\t\treturn this.raw<T>('get', path)\n\t}\n\tpost<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('post', path, data)\n\t}\n\tput<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('put', path, data)\n\t}\n\tpatch<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('patch', path, data)\n\t}\n\tdelete<T = any>(path: string): Promise<T> {\n\t\treturn this.raw<T>('delete', path)\n\t}\n\n\tprivate async raw<T>(method: string, path: string, data?: unknown): Promise<T> {\n\t\tif (!/^https?:\\/\\//i.test(path)) return (await resolveRestLocally(method, path)) as T\n\t\tconst res = await this._fetch.call(globalThis, path, {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: { Accept: 'application/json', ...(data === undefined ? {} : { 'Content-Type': 'application/json' }) },\n\t\t\tbody: data === undefined ? undefined : JSON.stringify(data),\n\t\t})\n\t\tconst body = await res.json().catch(() => ({}))\n\t\tif (!res.ok)\n\t\t\tthrow new GoCommerceError(body?.error?.message ?? `Request failed with status ${res.status}`, res.status)\n\t\treturn body as T\n\t}\n}\n\nlet requestHost: (() => string | undefined) | undefined\n\n/**\n * Where the server learns the current request's host, for `baseDomain`. A\n * SvelteKit storefront registers `() => getRequestEvent().url.hostname` once\n * at boot; the browser needs nothing, it reads `window.location`.\n */\nexport function setRequestHost(fn: () => string | undefined): void {\n\trequestHost = fn\n}\n\n/**\n * `acme.shopnx.in` under `shopnx.in` is store `acme`; anything else is nobody's.\n * The engine's own rule (`Stores.ByHost`): case-insensitive, a port and a\n * trailing dot ignored, and exactly one label, so `a.b.shopnx.in` and\n * `shopnx.in` itself name no store.\n */\nexport function storeForHost(host: string | undefined, baseDomain: string | undefined): string | undefined {\n\tif (!host || !baseDomain) return undefined\n\tconst h = host.toLowerCase().replace(/\\.$/, '').replace(/:\\d+$/, '')\n\tconst suffix = '.' + baseDomain.toLowerCase().replace(/^\\.+/, '').replace(/\\.$/, '')\n\tif (!h.endsWith(suffix)) return undefined\n\tconst slug = h.slice(0, -suffix.length)\n\treturn slug && !slug.includes('.') ? slug : undefined\n}\n\n/**\n * A host outside `baseDomain` is a store's own domain, such as `chillish.in`,\n * which the engine looks up among its verified domains. Only a storefront\n * serving many stores (one with a `baseDomain`) passes it on; the base domain\n * itself, `localhost` and bare addresses are nobody's.\n */\nexport function ownDomain(host: string | undefined, baseDomain: string | undefined): string | undefined {\n\tif (!host || !baseDomain) return undefined\n\tconst h = host.toLowerCase().replace(/:\\d+$/, '').replace(/\\.$/, '')\n\tconst base = baseDomain.toLowerCase().replace(/^\\.+/, '').replace(/\\.$/, '')\n\tif (!h.includes('.') || h === base || h.endsWith('.' + base) || h.endsWith('.localhost')) return undefined\n\tif (/^[\\d.]+$/.test(h) || h.includes(':') || h.startsWith('[')) return undefined\n\treturn h\n}\n\n/** A refused connection is the commonest failure in development; it says which address did not answer. */\nconst unreachable = (base: string, cause: unknown) =>\n\tnew GoCommerceError(`Could not reach the commerce engine at ${base}: ${(cause as Error)?.message ?? cause}`, 0)\n\n/** `?a=1&b=2`, dropping what was not asked for. Arrays repeat the key. */\nexport function qs(query?: Query): string {\n\tif (!query) return ''\n\tconst sp = new URLSearchParams()\n\tfor (const [key, value] of Object.entries(query)) {\n\t\t// Undefined, null and '' are \"did not ask\", not \"asked for nothing\":\n\t\t// `?q=` would filter to the empty string.\n\t\tif (value === undefined || value === null || value === '') continue\n\t\tif (Array.isArray(value)) for (const v of value) sp.append(key, String(v))\n\t\telse sp.append(key, String(value))\n\t}\n\tconst s = sp.toString()\n\treturn s ? `?${s}` : ''\n}\n\n/** The family's list shape, from the engine's `{data, meta}`. Totals are the engine's, never invented. */\nexport function toPage<T, U>(env: Envelope<T[] | null>, map: (row: T) => U) {\n\tconst rows = env.data ?? []\n\tconst meta = env.meta\n\treturn {\n\t\tdata: rows.map(map),\n\t\tcount: meta?.total ?? rows.length,\n\t\tpageSize: meta?.limit ?? rows.length,\n\t\tnoOfPage: meta?.total_pages ?? 1,\n\t\tpage: meta?.page ?? 1,\n\t}\n}\n\nexport const emptyPage = <T = never>() => ({ data: [] as T[], count: 0, pageSize: 0, noOfPage: 0, page: 1 })\n","/**\n * Money, across the one boundary in this connector where it changes shape.\n *\n * The engine speaks minor units and a currency code, always, and never sends a\n * formatted string (AGENTS.md rule 6). Svelte Commerce's types say `price:\n * number`, and every backend it already talks to means \"19.99\" by that. So the\n * conversion happens here, once, in the only file allowed to divide money.\n *\n * The exponent is per currency, not a constant 100: the yen writes no decimals\n * and the dinar writes three. Dividing 2500 JPY by 100 would price a ¥2,500\n * item at ¥25. The table mirrors `currencyExponent` in core/transfer_shopify.go\n * — the same list, because a second opinion about the yen is a bug.\n */\n\nconst ZERO_DECIMAL = new Set([\n\t'BIF',\n\t'CLP',\n\t'DJF',\n\t'GNF',\n\t'ISK',\n\t'JPY',\n\t'KMF',\n\t'KRW',\n\t'PYG',\n\t'RWF',\n\t'UGX',\n\t'VND',\n\t'VUV',\n\t'XAF',\n\t'XOF',\n\t'XPF',\n])\n\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\nexport function currencyExponent(code: string | null | undefined): number {\n\tconst c = (code ?? '').toUpperCase()\n\tif (ZERO_DECIMAL.has(c)) return 0\n\tif (THREE_DECIMAL.has(c)) return 3\n\treturn 2\n}\n\n/** The engine's money object. */\nexport type Money = { amount_minor: number; currency: string }\n\n/**\n * Minor units to the major-unit number the storefront renders.\n *\n * Rounded to the currency's own precision rather than left as raw float\n * division: 1999/100 is 19.99 exactly, but 1 / 1000 for a three-decimal\n * currency is not, and a price that renders as 0.0010000000000000002 is the\n * kind of thing nobody notices until a customer screenshots it.\n */\nexport function toMajor(money: Money | null | undefined): number {\n\tif (!money) return 0\n\treturn minorToMajor(money.amount_minor, money.currency)\n}\n\n/** The same, for the routes that send a bare `*_minor` integer beside a currency. */\nexport function minorToMajor(minor: number | null | undefined, currency: string | null | undefined): number {\n\tif (minor === null || minor === undefined || !Number.isFinite(minor)) return 0\n\tconst exp = currencyExponent(currency)\n\tif (exp === 0) return minor\n\treturn Number((minor / 10 ** exp).toFixed(exp))\n}\n\n/**\n * Back the other way, for the few places the storefront hands us a number —\n * a price filter, mostly.\n *\n * Rounded, not truncated: 19.99 * 100 is 1998.9999999999998 in binary floating\n * point, and truncating that filters out the item priced exactly 19.99.\n */\nexport function toMinor(amount: number, currency: string | null | undefined): number {\n\tconst exp = currencyExponent(currency)\n\treturn Math.round(amount * 10 ** exp)\n}\n","/**\n * Engine shapes to storefront shapes.\n *\n * Svelte Commerce's types were drawn around Litekart's API, so every connector\n * is a translation and this file is most of ours. Four rules run through it:\n *\n * 1. Ids cross as strings. The storefront matches variants and cart lines\n * with `===` against ids it read from a URL.\n * 2. Money crosses as a major-unit number, through money.ts and nowhere else.\n * 3. A field the engine does not have is empty, never invented. There is no\n * popularity score, so none is made up; there is no compare-at price, so\n * `mrp` equals the price rather than 0, which would render as a 100%\n * discount on everything in the shop.\n * 4. Lists are always arrays. Product cards read `variants[0]` unguarded.\n */\nimport type {\n\tAddOn,\n\tAddress,\n\tCart,\n\tCartOffer,\n\tCartLine,\n\tCategory,\n\tCmsPage,\n\tCollection,\n\tCustomer,\n\tIdentityAddress,\n\tOrder,\n\tOrderLine,\n\tProduct,\n\tReview,\n\tSearchDoc,\n\tVariant,\n\tVendor,\n\tFreeShipping,\n} from './engine'\nimport { minorToMajor, toMajor, type Money } from './money'\nimport type { CartExtras, StorefrontAddress } from './browser'\nimport { mediaUrl } from './services/base.service'\n\nconst str = (v: number | string | null | undefined): string => (v === null || v === undefined ? '' : String(v))\n\nconst arr = <T>(v: T[] | null | undefined): T[] => v ?? []\n\n// ---------------------------------------------------------------- products\n\n/** Variants a shopper can see: inactive ones are the merchant's business. */\nconst liveVariants = (p: Product): Variant[] => arr(p.variants).filter((v) => v.active)\n\nfunction variantImages(v: Variant): string[] {\n\tconst out: string[] = []\n\tfor (const img of [v.image, ...arr(v.images)]) {\n\t\tconst url = mediaUrl(img?.url)\n\t\tif (url && (img?.kind ?? 'image') === 'image' && !out.includes(url)) out.push(url)\n\t}\n\treturn out\n}\n\n/**\n * Every picture the public API offers for a product: the lead image, the\n * product's gallery (on the single product, D134), then each variant's.\n */\nexport function productImages(p: Product): string[] {\n\tconst out: string[] = []\n\tconst push = (url?: string | null) => {\n\t\tif (url && !out.includes(url)) out.push(url)\n\t}\n\t// variantImages has already resolved its own; resolving twice would prefix twice.\n\tpush(mediaUrl(p.image_url))\n\tfor (const m of arr(p.media)) if (m.kind === 'image') push(mediaUrl(m.url))\n\tfor (const v of arr(p.variants)) for (const url of variantImages(v)) push(url)\n\treturn out\n}\n\n/**\n * The product's videos, an upload or a YouTube link, in the gallery's order\n * (D134). They follow the pictures in `images`, where the storefront's gallery\n * plays them; a card's thumbnail is never one.\n */\nexport function productVideos(p: Product): string[] {\n\tconst out: string[] = []\n\tfor (const m of arr(p.media)) {\n\t\tconst url = m.kind === 'video' ? mediaUrl(m.url) : null\n\t\tif (url && !out.includes(url)) out.push(url)\n\t}\n\treturn out\n}\n\n/** A product's highlight lines: text only, the empty ones left out (D134). */\nfunction highlightsOf(p: Product): string[] {\n\tconst raw = p.metadata?.highlights\n\tif (!Array.isArray(raw)) return []\n\treturn raw.filter((s): s is string => typeof s === 'string').map((s) => s.trim()).filter(Boolean)\n}\n\nfunction freeGiftOf(p: Product): string | null {\n\tconst raw = p.metadata?.free_gift\n\treturn typeof raw === 'string' && raw.trim() ? raw.trim() : null\n}\n\nexport function toVariant(v: Variant, p: Product, optionless: boolean) {\n\tconst images = variantImages(v)\n\tconst options = arr(p.options)\n\treturn {\n\t\tid: str(v.id),\n\t\tproductId: str(v.product_id),\n\t\t// The storefront picks the default variant of an optionless product by\n\t\t// this exact title, and hides the variant name when it sees it.\n\t\ttitle: optionless ? 'default' : v.label || v.sku,\n\t\tsku: v.sku,\n\t\tbarcode: v.barcode ?? null,\n\t\tprice: toMajor(v.price),\n\t\tmrp: toMajor(v.compare_at_price ?? v.price),\n\t\t// The engine's own vocabulary, unchanged: `available` is on hand minus\n\t\t// reserved; an untracked variant is never managed, so its count is moot.\n\t\tstock: v.active ? v.available : 0,\n\t\tmanageInventory: v.active ? v.track_inventory : true,\n\t\tallowBackorder: v.active && v.continue_selling,\n\t\tactive: v.active,\n\t\tweight: v.weight_grams ?? null,\n\t\tlength: v.dimensions?.length_mm ?? null,\n\t\twidth: v.dimensions?.width_mm ?? null,\n\t\theight: v.dimensions?.height_mm ?? null,\n\t\timages: images.join(','),\n\t\timg: images[0] ?? null,\n\t\timage: images[0] ?? null,\n\t\tthumbnail: images[0] ?? null,\n\t\t// Values in option order — `options[i]` answers `p.options[i]`.\n\t\toptions: arr(v.options).map((value, i) => ({ optionId: str(options[i]?.id), value })),\n\t\tmetadata: v.metadata ?? null,\n\t}\n}\n\n/**\n * The product's category attribute answers — `metadata.category`, keyed by the\n * attribute's handle — as the specs table's rows. The handle is the only name\n * the public API carries, so it is shown humanised rather than looked up.\n */\nfunction attributesOf(p: Product): { name: string; value: string; handle: string }[] {\n\tconst answers = p.metadata?.category\n\tif (!answers || typeof answers !== 'object' || Array.isArray(answers)) return []\n\treturn Object.entries(answers as Record<string, unknown>).flatMap(([handle, raw]) => {\n\t\tconst values = (Array.isArray(raw) ? raw : [raw]).map((v) => String(v ?? '').trim()).filter(Boolean)\n\t\tif (!values.length) return []\n\t\tconst name = handle.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase())\n\t\treturn [{ name, value: values.join(', '), handle }]\n\t})\n}\n\nexport type StorefrontProduct = ReturnType<typeof toProduct>\n\nexport function toProduct(p: Product, extra: { categoryHierarchy?: { name: string; slug: string }[] } = {}) {\n\tconst live = liveVariants(p)\n\tconst lead = live[0] ?? arr(p.variants)[0]\n\tconst optionless = arr(p.options).length === 0\n\tconst images = productImages(p)\n\tconst videos = productVideos(p)\n\tconst prices = live.map((v) => toMajor(v.price))\n\tconst tracked = live.filter((v) => v.track_inventory)\n\tconst category = p.category\n\tconst tags = arr(p.tags)\n\n\treturn {\n\t\tid: str(p.id),\n\t\tslug: p.slug,\n\t\ttitle: p.title,\n\t\tname: p.title,\n\t\tsubtitle: null,\n\t\tdescription: p.description ?? '',\n\t\tstatus: p.status === 'active' ? 'published' : p.status,\n\t\tactive: p.status === 'active',\n\t\ttype: p.product_type ?? '',\n\t\tcurrency: p.currency,\n\t\tcurrencyCode: p.currency,\n\t\tprice: lead ? toMajor(lead.price) : 0,\n\t\tmrp: lead ? toMajor(lead.compare_at_price ?? lead.price) : 0,\n\t\tminPrice: prices.length ? Math.min(...prices) : 0,\n\t\tmaxPrice: prices.length ? Math.max(...prices) : 0,\n\t\tsku: lead?.sku ?? null,\n\t\tbarcode: lead?.barcode ?? null,\n\t\tweight: lead?.weight_grams ?? null,\n\t\toriginCountry: lead?.origin_country ?? null,\n\t\tthumbnail: images[0] ?? null,\n\t\timage_url: images[0] ?? null,\n\t\timages: [...images, ...videos].join(','),\n\t\timageList: images,\n\t\tvideos,\n\t\t// What the buy box says beside the price (D134): plain text, drawn as text.\n\t\thighlights: highlightsOf(p),\n\t\tfreeGift: freeGiftOf(p),\n\t\t// Counted by the engine, rounded down, and absent rather than zero.\n\t\tsoldAtLeast: typeof p.sold_at_least === 'number' && p.sold_at_least > 0 ? p.sold_at_least : null,\n\t\tdesignable: typeof p.designable === 'boolean' ? p.designable : undefined,\n\t\t// Product-level stock is what a card shows before a variant is picked:\n\t\t// buyable when any live variant is, counted only where counting means\n\t\t// something.\n\t\tmanageInventory: live.length > 0 && tracked.length === live.length,\n\t\tallowBackorder: live.some((v) => v.continue_selling),\n\t\tstock: tracked.reduce((n, v) => n + Math.max(0, v.available), 0),\n\t\thasStock: live.some((v) => !v.track_inventory || v.continue_selling || v.available > 0),\n\t\tcategoryId: category ? str(category.id) : null,\n\t\tcategory: category ? { id: str(category.id), name: category.title, slug: category.slug } : null,\n\t\tcategories: category ? [{ category: { id: str(category.id), name: category.title, slug: category.slug } }] : [],\n\t\tcategoryHierarchy: extra.categoryHierarchy ?? (category ? [{ name: category.title, slug: category.slug }] : []),\n\t\tcollections: arr(p.collections).map((c) => ({ id: str(c.id), name: c.title, slug: c.slug })),\n\t\t// Free text on the engine's product, not a vendor record.\n\t\tvendor: p.vendor ? { businessName: p.vendor } : null,\n\t\tproductTags: tags.join(','),\n\t\tkeywords: tags.join(','),\n\t\tmetaTitle: p.seo_title || p.title,\n\t\tmetaDescription: p.seo_description || null,\n\t\tlink: `/products/${p.slug}`,\n\t\toptions: arr(p.options).map((o) => ({\n\t\t\tid: str(o.id),\n\t\t\ttitle: o.name,\n\t\t\tname: o.name,\n\t\t\ttype: 'text',\n\t\t\tvalues: arr(o.values).map((val) => ({ id: str(val.id), value: val.value })),\n\t\t})),\n\t\tvariants: live.map((v) => toVariant(v, p, optionless)),\n\t\t// Filled by the product page from ext/reviews when it is installed.\n\t\tratings: [] as ReturnType<typeof toRating>[],\n\t\trating: null as number | null,\n\t\tratingCount: 0,\n\t\treviewCount: 0,\n\t\tattributes: attributesOf(p),\n\t\tmetadata: p.metadata ?? null,\n\t\tcreatedAt: p.created_at,\n\t\tupdatedAt: p.updated_at,\n\t}\n}\n\n/** A Meilisearch hit — the search index's document, which is thinner than a product. */\nexport function fromSearchDoc(d: SearchDoc) {\n\tconst price = minorToMajor(d.price_minor, d.currency)\n\treturn {\n\t\tid: str(d.id),\n\t\tslug: d.slug,\n\t\ttitle: d.title,\n\t\tname: d.title,\n\t\tdescription: d.description,\n\t\tcurrency: d.currency,\n\t\tprice,\n\t\tmrp: price,\n\t\tminPrice: price,\n\t\tmaxPrice: minorToMajor(d.price_max_minor, d.currency),\n\t\tthumbnail: mediaUrl(d.image),\n\t\timage_url: mediaUrl(d.image),\n\t\timages: mediaUrl(d.image) ?? '',\n\t\tstock: d.in_stock ? 1 : 0,\n\t\thasStock: d.in_stock,\n\t\t// The index cannot say how much is left, only whether any is; a card\n\t\t// built from it must not claim to count.\n\t\tmanageInventory: false,\n\t\tallowBackorder: false,\n\t\tdesignable: typeof d.designable === 'boolean' ? d.designable : undefined,\n\t\tproductTags: arr(d.tags).join(','),\n\t\tcategory: d.category ? { name: d.category.split(' / ').pop() ?? d.category, slug: '' } : null,\n\t\tvendor: d.vendor ? { businessName: d.vendor } : null,\n\t\tvariants: [] as ReturnType<typeof toVariant>[],\n\t\toptions: [],\n\t\tratings: [],\n\t\tlink: `/products/${d.slug}`,\n\t\tupdatedAt: new Date(d.updated_at * 1000).toISOString(),\n\t}\n}\n\n// ---------------------------------------------------------------- taxonomy\n\nexport type StorefrontCategory = {\n\tid: string\n\tname: string\n\ttitle: string\n\tslug: string\n\tlink: string\n\tparentCategoryId: string | null\n\tpath: string\n\tlevel: number\n\trank: number\n\tchildCount: number\n\tthumbnail: string | null\n\tdescription: string | null\n\tisActive: boolean\n\tisFeatured: boolean\n\tisMegamenu: boolean\n\tmetaTitle: string\n\tchildren: StorefrontCategory[]\n\tcreatedAt: string\n\tupdatedAt: string\n}\n\nexport function toCategory(c: Category): StorefrontCategory {\n\treturn {\n\t\tid: str(c.id),\n\t\tname: c.title,\n\t\ttitle: c.title,\n\t\tslug: c.slug,\n\t\tlink: `/${c.slug}`,\n\t\tparentCategoryId: c.parent_id === null || c.parent_id === undefined ? null : str(c.parent_id),\n\t\tpath: c.full_name,\n\t\tlevel: c.depth,\n\t\trank: c.position,\n\t\tchildCount: c.child_count,\n\t\tthumbnail: mediaUrl(c.metadata?.image as string | undefined),\n\t\tdescription: (c.metadata?.description as string | undefined) ?? null,\n\t\tisActive: true,\n\t\tisFeatured: false,\n\t\tisMegamenu: false,\n\t\tmetaTitle: c.title,\n\t\tchildren: arr(c.children).map(toCategory),\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\nexport function toCollection(c: Collection) {\n\treturn {\n\t\tid: str(c.id),\n\t\tname: c.title,\n\t\ttitle: c.title,\n\t\tslug: c.slug,\n\t\tdescription: c.description || null,\n\t\tsubTitle: null,\n\t\trank: str(c.position),\n\t\tthumbnail: mediaUrl(c.metadata?.image as string | undefined),\n\t\tisActive: true,\n\t\tmetaTitle: c.title,\n\t\tmetaDescription: c.description || null,\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\n// ---------------------------------------------------------------- addresses\n\n/** The engine's address — on a checkout or an order — to the storefront's form shape. */\nexport function fromEngineAddress(a: Address | undefined, email?: string) {\n\tif (!a) return null\n\tconst [firstName, ...rest] = (a.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\temail: email ?? null,\n\t\tphone: a.phone ?? null,\n\t\taddress_1: a.line1,\n\t\taddress_2: a.line2 ?? '',\n\t\tcity: a.city,\n\t\tstate: a.state ?? '',\n\t\tzip: a.postal_code,\n\t\tcountry: a.country,\n\t\tcountryCode: a.country,\n\t}\n}\n\n/** The storefront's form shape to the engine's checkout address. */\nexport function toEngineAddress(a: StorefrontAddress): Address {\n\tconst name = [a.firstName, a.lastName].filter(Boolean).join(' ').trim()\n\treturn {\n\t\t...(name ? { name } : {}),\n\t\t...(a.phone ? { phone: String(a.phone) } : {}),\n\t\tline1: String(a.address_1 ?? '').trim(),\n\t\t...(a.address_2 || a.locality ? { line2: [a.address_2, a.locality].filter(Boolean).join(', ') } : {}),\n\t\tcity: String(a.city ?? '').trim(),\n\t\t...(a.state ? { state: String(a.state) } : {}),\n\t\tpostal_code: String(a.zip ?? '').trim(),\n\t\tcountry: String(a.countryCode || a.country || '')\n\t\t\t.trim()\n\t\t\t.toUpperCase(),\n\t}\n}\n\n/** An address-book entry (ext/identity) to the storefront's Address. */\nexport function fromIdentityAddress(a: IdentityAddress, email?: string) {\n\tconst [firstName, ...rest] = (a.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: str(a.id),\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\temail: email ?? null,\n\t\tphone: a.phone || null,\n\t\taddress_1: a.line1,\n\t\taddress_2: a.line2,\n\t\tcity: a.city,\n\t\tstate: a.state,\n\t\tzip: a.postal_code,\n\t\tcountry: a.country,\n\t\tcountryCode: a.country,\n\t\tlabel: a.label,\n\t\tisPrimary: a.is_default,\n\t\tcreatedAt: a.created_at,\n\t\tupdatedAt: a.updated_at,\n\t}\n}\n\n/** The storefront's Address to ext/identity's AddressInput. Only declared fields: the engine refuses others. */\nexport function toIdentityAddress(a: StorefrontAddress & { isPrimary?: boolean; label?: string }) {\n\tconst e = toEngineAddress(a)\n\treturn {\n\t\tname: e.name ?? '',\n\t\tphone: e.phone ?? '',\n\t\tline1: e.line1,\n\t\tline2: e.line2 ?? '',\n\t\tcity: e.city,\n\t\tstate: e.state ?? '',\n\t\tpostal_code: e.postal_code,\n\t\tcountry: e.country,\n\t\t// Sent whenever the form has it, empty included: the engine keeps a label it is not sent, so\n\t\t// leaving out an emptied one would keep the old Home or Work (D134).\n\t\t...(typeof a.label === 'string' ? { label: a.label } : {}),\n\t\t...(a.isPrimary ? { is_default: true } : {}),\n\t}\n}\n\n// ---------------------------------------------------------------- cart\n\nexport function toCartLine(l: CartLine, extra: { slug?: string; thumbnail?: string | null } = {}) {\n\treturn {\n\t\tid: str(l.id),\n\t\tproductId: str(l.product_id),\n\t\tvariantId: str(l.variant_id),\n\t\tsku: l.sku,\n\t\ttitle: l.title,\n\t\tname: l.title,\n\t\tslug: extra.slug ?? '',\n\t\tthumbnail: mediaUrl(extra.thumbnail),\n\t\tvariantTitle: l.variant_label ?? '',\n\t\tqty: l.quantity,\n\t\tprice: toMajor(l.unit_price),\n\t\t// The variant's compare-at price, where the shop set one above what the\n\t\t// line costs: what the basket's \"you save\" is measured from.\n\t\tmrp:\n\t\t\tl.compare_at_price && l.compare_at_price.amount_minor > l.unit_price.amount_minor\n\t\t\t\t? toMajor(l.compare_at_price)\n\t\t\t\t: toMajor(l.unit_price),\n\t\t/** The add-on this line was bought as (D133), or null on an ordinary line. */\n\t\taddOnId: l.add_on_id ? str(l.add_on_id) : null,\n\t\taddOnFor: l.add_on_for ? str(l.add_on_for) : null,\n\t\t/** The shopper's own design this line is made to (D162) and its picture, or null on a line sold as it is. */\n\t\tdesignId: l.design_id ?? null,\n\t\tdesignPreview: mediaUrl(l.design_preview_url),\n\t\tsubtotal: toMajor(l.total),\n\t\ttotal: toMajor(l.total),\n\t\tinStock: l.in_stock,\n\t\tpriceChanged: l.price_changed,\n\t\tcurrentPrice: toMajor(l.current_price),\n\t\t// The storefront's review step lists only lines marked for checkout. The\n\t\t// engine checks a cart out whole, so every line is.\n\t\tisSelectedForCheckout: true,\n\t\tvariant: {\n\t\t\tid: str(l.variant_id),\n\t\t\toptions: l.variant_label ? l.variant_label.split(' / ').map((value) => ({ option: { title: '' }, value })) : [],\n\t\t},\n\t\tproduct: { id: str(l.product_id), categories: [] as unknown[] },\n\t}\n}\n\n/**\n * A cart, with what the engine does not keep laid over it: the coupon and its\n * previewed saving, the delivery choice and the addresses. Totals here are an\n * estimate the engine settles at checkout — tax in particular exists only on\n * the order — and the storefront is told so by `taxIncluded: false`.\n */\nexport function toCart(\n\tc: Cart,\n\textras: CartExtras = {},\n\tlineExtra: (l: CartLine) => { slug?: string; thumbnail?: string | null } = () => ({}),\n) {\n\tconst lines = c.status === 'converted' ? [] : arr(c.line_items)\n\tconst currency = c.currency\n\tconst subtotalMinor = lines.reduce((n, l) => n + l.total.amount_minor, 0)\n\tconst discountMinor = extras.discount && !extras.discount.free_shipping ? extras.discount.amount_minor : 0\n\tconst shippingMinor = extras.discount?.free_shipping ? 0 : (extras.shippingRate?.minor ?? 0)\n\tconst totalMinor = Math.max(0, subtotalMinor - discountMinor) + shippingMinor\n\tconst money = (minor: number) => minorToMajor(minor, currency)\n\tconst ship = extras.shippingAddress ?? null\n\n\treturn {\n\t\tid: c.id,\n\t\tstatus: c.status,\n\t\temail: c.email ?? ship?.email ?? null,\n\t\tphone: extras.phone ?? ship?.phone ?? null,\n\t\tname: ship ? [ship.firstName, ship.lastName].filter(Boolean).join(' ') : null,\n\t\tlineItems: lines.map((l) => toCartLine(l, lineExtra(l))),\n\t\tqty: lines.reduce((n, l) => n + l.quantity, 0),\n\t\tcurrencyCode: currency,\n\t\tcurrency,\n\t\tsubtotal: money(subtotalMinor),\n\t\tdiscountAmount: money(discountMinor),\n\t\tsavingAmount: money(discountMinor),\n\t\tcouponCode: extras.discount?.code ?? null,\n\t\tdiscount: extras.discount ?? null,\n\t\tshippingCharges: money(shippingMinor),\n\t\tshippingRateId: extras.shippingRateId ?? null,\n\t\tshippingMethod: extras.shippingRate?.name ?? null,\n\t\ttax: 0,\n\t\ttaxIncluded: false,\n\t\tcodCharges: 0,\n\t\ttotal: money(totalMinor),\n\t\tshippingAddress: ship,\n\t\tshippingAddressId: ship ? (ship.id && ship.id !== 'new' ? String(ship.id) : 'cart') : null,\n\t\tbillingAddress: extras.billingAddress ?? ship,\n\t\tbillingAddressId: extras.billingAddress\n\t\t\t? extras.billingAddress.id && extras.billingAddress.id !== 'new'\n\t\t\t\t? String(extras.billingAddress.id)\n\t\t\t\t: 'cart-billing'\n\t\t\t: ship\n\t\t\t\t? ship.id && ship.id !== 'new'\n\t\t\t\t\t? String(ship.id)\n\t\t\t\t\t: 'cart'\n\t\t\t\t: null,\n\t\tpaymentMethod: null,\n\t\tneedAddress: lines.length > 0,\n\t\tcompletedAt: c.status === 'converted' ? c.updated_at : null,\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t\texpiresAt: c.expires_at,\n\t}\n}\n\n/** What the storefront shows for \"no bag yet\": its own initial cart, field for field. */\nexport function emptyCart(currency = 'USD') {\n\treturn {\n\t\tid: '',\n\t\tstatus: 'open',\n\t\temail: null,\n\t\tphone: null,\n\t\tlineItems: [] as ReturnType<typeof toCartLine>[],\n\t\tqty: 0,\n\t\tcurrencyCode: currency,\n\t\tsubtotal: 0,\n\t\tdiscountAmount: 0,\n\t\tsavingAmount: 0,\n\t\tcouponCode: null,\n\t\tshippingCharges: 0,\n\t\ttax: 0,\n\t\ttotal: 0,\n\t\tshippingAddress: null,\n\t\tshippingAddressId: null,\n\t\tbillingAddress: null,\n\t\tbillingAddressId: null,\n\t}\n}\n\n// ---------------------------------------------------------------- orders\n\nconst STATUS: Record<string, string> = {\n\tpending: 'Pending',\n\tconfirmed: 'Confirmed',\n\tpartial: 'Partially shipped',\n\tshipped: 'Shipped',\n\tdelivered: 'Delivered',\n\tcancelled: 'Cancelled',\n}\n\nconst PAYMENT_STATUS: Record<string, string> = {\n\tpending: 'Pending',\n\tpaid: 'Paid',\n\tfailed: 'Failed',\n\trefunded: 'Refunded',\n}\n\nfunction toOrderLine(l: OrderLine, currency: string) {\n\treturn {\n\t\tid: str(l.id),\n\t\tproductId: str(l.product_id),\n\t\tvariantId: str(l.variant_id),\n\t\tsku: l.sku,\n\t\ttitle: l.title,\n\t\tname: l.title,\n\t\tslug: '',\n\t\tthumbnail: mediaUrl(l.image_url),\n\t\timg: mediaUrl(l.image_url),\n\t\tvariantTitle: l.variant_label ?? '',\n\t\tqty: l.quantity,\n\t\tshippedQty: l.shipped_quantity,\n\t\tprice: toMajor(l.unit_price),\n\t\tmrp: toMajor(l.unit_price),\n\t\tsubtotal: toMajor(l.total),\n\t\ttotal: toMajor(l.total),\n\t\tcurrencyCode: currency,\n\t\tstatus: l.shipped_quantity >= l.quantity ? 'Shipped' : 'Pending',\n\t\tdesignId: l.metadata?.design?.id ?? null,\n\t\tdesignPreview: mediaUrl(l.metadata?.design?.preview_url),\n\t\tfiles: [],\n\t\tusedOptions: [],\n\t}\n}\n\nexport type StorefrontOrder = ReturnType<typeof toOrder>\n\nexport function toOrder(o: Order) {\n\tconst address = fromEngineAddress(o.address, o.email)\n\tconst code = (o.discounts ?? []).find((d) => d.code)?.code\n\treturn {\n\t\tid: str(o.id),\n\t\torderNo: o.number,\n\t\torderNumber: o.number,\n\t\tnumber: o.number,\n\t\t// The storefront links an order by this; the engine has no sub-orders,\n\t\t// so an order is its own parent.\n\t\tparentOrderNo: o.number,\n\t\tstatus: STATUS[o.status] ?? o.status,\n\t\tengineStatus: o.status,\n\t\tpaymentStatus: PAYMENT_STATUS[o.payment_status] ?? o.payment_status,\n\t\tpaymentMethod: o.payment_provider.toUpperCase(),\n\t\tcurrencyCode: o.currency,\n\t\tsubtotal: toMajor(o.subtotal),\n\t\tshippingCharges: toMajor(o.shipping),\n\t\tdiscount: toMajor(o.discount),\n\t\ttax: toMajor(o.tax),\n\t\ttaxIncluded: o.tax_inclusive,\n\t\ttotal: toMajor(o.total),\n\t\trefunded: toMajor(o.refunded),\n\t\tcodCharges: toMajor(o.payment_fee),\n\t\tcoupon: code ? { code } : null,\n\t\tuserEmail: o.email,\n\t\temail: o.email,\n\t\tphone: o.phone ?? null,\n\t\tshippingAddress: address,\n\t\tbillingAddress: address,\n\t\tshippingMethod: o.shipping_method ?? null,\n\t\tshippingRate: o.shipping_method ? { name: o.shipping_method } : null,\n\t\tlineItems: arr(o.line_items).map((l) => toOrderLine(l, o.currency)),\n\t\tfulfillments: arr(o.fulfillments).map((f) => ({\n\t\t\tid: str(f.id),\n\t\t\tstatus: f.status,\n\t\t\tcarrier: f.carrier_name || f.carrier || f.provider,\n\t\t\ttrackingNumber: f.tracking ?? null,\n\t\t\ttrackingUrl: f.tracking_url ?? null,\n\t\t\tlineItems: arr(f.lines).map((l) => ({ id: str(l.order_line_id), title: l.title, qty: l.quantity })),\n\t\t\tcreatedAt: f.created_at,\n\t\t})),\n\t\ttracking: [],\n\t\torderHistory: [],\n\t\tisReplaceOrReturn: false,\n\t\tcreatedAt: o.created_at,\n\t\tupdatedAt: o.updated_at,\n\t}\n}\n\n// ---------------------------------------------------------------- the rest\n\nexport function toRating(r: Review) {\n\treturn {\n\t\tid: str(r.id),\n\t\trating: r.rating,\n\t\tname: r.name,\n\t\ttitle: r.title ?? '',\n\t\treview: r.body,\n\t\tmessage: r.body,\n\t\treply: r.reply ?? null,\n\t\tverified: r.verified,\n\t\timg: '',\n\t\tcreatedAt: r.created_at,\n\t}\n}\n\nexport function toCmsPage(p: CmsPage) {\n\treturn {\n\t\tid: str(p.id),\n\t\tslug: p.slug,\n\t\tname: p.title,\n\t\ttitle: p.title,\n\t\tcontent: p.body,\n\t\texcerpt: p.excerpt ?? null,\n\t\tlayouts: [],\n\t\tlanguage: p.language,\n\t\tmetaTitle: p.seo?.title || p.title,\n\t\tmetaDescription: p.seo?.description || p.excerpt || null,\n\t\tmetaKeywords: p.seo?.keywords || null,\n\t\tpublishedAt: p.published_at ?? null,\n\t\tcreatedAt: p.created_at,\n\t\tupdatedAt: p.updated_at,\n\t}\n}\n\nexport function toVendor(v: Vendor) {\n\treturn {\n\t\tid: str(v.id),\n\t\tslug: v.slug,\n\t\tname: v.name,\n\t\tbusinessName: v.name,\n\t\tabout: v.about,\n\t\tdescription: v.about,\n\t\twebsite: v.website,\n\t\taddress: v.address,\n\t\tbanners: [],\n\t\trating: null,\n\t}\n}\n\nexport function toUser(c: Customer) {\n\tconst [firstName, ...rest] = (c.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: str(c.id),\n\t\tuserId: str(c.id),\n\t\temail: c.email,\n\t\temailVerified: c.email_verified,\n\t\tphone: c.phone || null,\n\t\tphoneVerified: !!c.phone_verified,\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\tname: c.name,\n\t\tfullName: c.name,\n\t\tavatar: null,\n\t\trole: 'USER',\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\nexport const priceOf = (m: Money | undefined) => (m ? toMajor(m) : 0)\n\n/**\n * An add-on as the buy box draws it (D133): `price` is what ticking it adds,\n * the offer where there is one, and `regularPrice` the add-on's own, struck\n * through beside it. Without an offer the two are the same and nothing is\n * struck.\n */\nexport function toAddOn(a: AddOn) {\n\treturn {\n\t\tid: str(a.id),\n\t\tproductId: str(a.item.product_id),\n\t\tvariantId: str(a.variant_id),\n\t\tslug: a.item.slug,\n\t\ttitle: a.item.title,\n\t\tvariantTitle: a.item.variant_label ?? '',\n\t\tthumbnail: mediaUrl(a.item.image_url ?? null),\n\t\tprice: toMajor(a.offer_price ?? a.price),\n\t\tregularPrice: toMajor(a.price),\n\t\thasOffer: !!a.offer_price && a.offer_price.amount_minor < a.price.amount_minor,\n\t\tinStock: a.item.in_stock,\n\t}\n}\n\n/** A listed code for one basket, in major units (D133). */\nexport function toCartOffer(o: CartOffer, currency: string) {\n\tconst isPercent = o.kind === 'percentage'\n\treturn {\n\t\tcode: o.code,\n\t\ttitle: o.title,\n\t\tisPercent,\n\t\tfreeShipping: o.kind === 'free_shipping',\n\t\t/** The percentage for a percentage code, the amount for a fixed one. */\n\t\tvalue: isPercent ? (o.value_bp ?? 0) / 100 : minorToMajor(o.value_minor ?? 0, currency),\n\t\tminAmount: o.min_subtotal_minor ? minorToMajor(o.min_subtotal_minor, currency) : null,\n\t\tapplies: o.applies,\n\t\tamount: o.amount ? toMajor(o.amount) : null,\n\t\tremaining: o.remaining ? toMajor(o.remaining) : null,\n\t\treason: o.reason ?? '',\n\t}\n}\n\nexport function toFreeShipping(f: FreeShipping) {\n\treturn {\n\t\tqualifies: f.qualifies,\n\t\tthreshold: f.threshold ? toMajor(f.threshold) : null,\n\t\tremaining: f.remaining ? toMajor(f.remaining) : null,\n\t\tsubtotal: toMajor(f.subtotal),\n\t}\n}\n","/**\n * A short memory for store-level facts: which plugins are on, the settlement\n * currency, the category tree.\n *\n * The storefront asks for the store record on every server request, and a\n * category page needs the whole tree to draw one breadcrumb. Asking the engine\n * each time would multiply its load by the page count for answers that change\n * when a merchant edits something, not when a shopper clicks.\n *\n * Only facts that are the same for every shopper may go in here — this module\n * is shared by every request a server process handles. Keyed by engine URL, so\n * a platform storefront talking to several stores keeps them apart.\n */\nconst TTL_MS = 60_000\n\ntype Entry = { at: number; value: Promise<unknown> }\n\nconst entries = new Map<string, Entry>()\n\nexport function remember<T>(key: string, load: () => Promise<T>, ttl = TTL_MS): Promise<T> {\n\tconst hit = entries.get(key)\n\tif (hit && Date.now() - hit.at < ttl) return hit.value as Promise<T>\n\tconst value = load()\n\tentries.set(key, { at: Date.now(), value })\n\t// A failure is not remembered: the next caller tries again.\n\tvalue.catch(() => {\n\t\tif (entries.get(key)?.value === value) entries.delete(key)\n\t})\n\treturn value\n}\n\n/** For tests, and for a storefront that has just changed something itself. */\nexport function forgetAll(): void {\n\tentries.clear()\n}\n","import { remember } from '../cache'\nimport type { Category, CheckoutOptions, Plugin, StoreProfile } from '../engine'\nimport { BaseService } from './base.service'\n\n/**\n * Store-level questions several services ask, answered once a minute.\n *\n * Not exported from the package: it is plumbing the other services share.\n */\nexport class StoreFacts extends BaseService {\n\tprivate key(name: string) {\n\t\treturn `${this.engineBase()}|${this.store ?? ''}|${name}`\n\t}\n\n\t/** Enabled plugins by key. A module that is not installed has no key here. */\n\tplugins(): Promise<Map<string, Plugin>> {\n\t\treturn remember(this.key('plugins'), async () => {\n\t\t\tconst list = (await this.data<Plugin[] | null>('/api/plugins')) ?? []\n\t\t\treturn new Map(list.map((p) => [p.key, p]))\n\t\t})\n\t}\n\n\tasync pluginOn(key: string): Promise<boolean> {\n\t\ttry {\n\t\t\treturn (await this.plugins()).has(key)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * The store's settlement currency and default language, from routes bound\n\t * to the store: `/health/ready` answers for the install, so on a shared\n\t * engine every store read as the install's currency.\n\t */\n\tready(): Promise<{ currency: string; language: string }> {\n\t\treturn remember(this.key('ready'), async () => {\n\t\t\tconst [{ currency }, { language }] = await Promise.all([this.checkoutOptions(), this.profile()])\n\t\t\treturn { currency, language }\n\t\t})\n\t}\n\n\t/** The store's own name and how a buyer reaches it, as set in its panel. */\n\tprofile(): Promise<StoreProfile> {\n\t\treturn remember(this.key('profile'), () => this.data<StoreProfile>('/api/store'))\n\t}\n\n\t/** Where the store delivers (D117): its priced zones' countries, or everywhere. */\n\tshipsTo(): Promise<{ everywhere: boolean; countries: string[] }> {\n\t\treturn remember(this.key('ships-to'), async () => {\n\t\t\tconst r = await this.data<{ everywhere: boolean; countries: string[] } | null>('/api/checkout/countries')\n\t\t\treturn { everywhere: r?.everywhere ?? true, countries: r?.countries ?? [] }\n\t\t})\n\t}\n\n\tcheckoutOptions(): Promise<CheckoutOptions> {\n\t\treturn remember(this.key('checkout'), () => this.data<CheckoutOptions>('/api/checkout'))\n\t}\n\n\t/**\n\t * The whole tree, flat and depth-first. Past 500 categories the engine\n\t * answers a truncated list; the tree then serves what it has, and a\n\t * breadcrumb for a category outside it falls back to the category alone.\n\t */\n\tcategories(): Promise<Category[]> {\n\t\treturn remember(\n\t\t\tthis.key('categories'),\n\t\t\tasync () => (await this.data<Category[] | null>('/api/categories', { query: { flat: 1 } })) ?? [],\n\t\t)\n\t}\n\n\t/** Root → `slug`, by walking parents in the flat tree. */\n\tasync hierarchy(slug: string): Promise<{ name: string; slug: string }[]> {\n\t\tconst all = await this.categories().catch(() => [] as Category[])\n\t\tconst byId = new Map(all.map((c) => [c.id, c]))\n\t\tconst out: { name: string; slug: string }[] = []\n\t\tlet c = all.find((x) => x.slug === slug)\n\t\twhile (c) {\n\t\t\tout.unshift({ name: c.title, slug: c.slug })\n\t\t\tc = c.parent_id === null ? undefined : byId.get(c.parent_id)\n\t\t}\n\t\treturn out\n\t}\n\n\t/** `slug` and every category under it — what a category page sells. */\n\tasync subtree(slug: string): Promise<Category[]> {\n\t\tconst all = await this.categories()\n\t\tconst root = all.find((c) => c.slug === slug)\n\t\tif (!root) return []\n\t\tconst ids = new Set([root.id])\n\t\tconst out = [root]\n\t\t// Depth-first and flat, so a parent always precedes its children.\n\t\tfor (const c of all) {\n\t\t\tif (c.parent_id !== null && ids.has(c.parent_id) && !ids.has(c.id)) {\n\t\t\t\tids.add(c.id)\n\t\t\t\tout.push(c)\n\t\t\t}\n\t\t}\n\t\treturn out\n\t}\n}\n","import type { Category, Product, ProductFacets, SearchResult } from '../engine'\nimport { fromSearchDoc, toProduct } from '../map'\nimport { toMinor } from '../money'\nimport { BaseService, toPage } from './base.service'\nimport { StoreFacts } from './facts'\n\nexport const PAGE_SIZE = 24\n\nexport type CatalogQuery = {\n\tpage?: number\n\tlimit?: number\n\tsearch?: string\n\t/** The family's sort spellings: `-createdAt`, `price`, `price:asc`, `updatedAt:desc`, `-popularity`… */\n\tsort?: string\n\t/** A category slug: the page sells it and everything under it. */\n\tcategory?: string\n\tpriceFrom?: number\n\tpriceTo?: number\n\t/**\n\t * Attribute answers, `{ color: ['Red', 'Blue'] }`: one handle's values OR-ed,\n\t * different handles AND-ed. The engine filters on them in the whole-shop\n\t * listing only — its category route takes none — so inside a category they\n\t * are not applied.\n\t */\n\tattributes?: Record<string, string[]>\n\ttags?: string[]\n\tvendors?: string[]\n\tproductTypes?: string[]\n\t/**\n\t * Ask the engine to count the filter values too. Such a query goes to\n\t * `GET /api/products`, which then also answers the category, the price\n\t * range, the sort and every filter above (D130); an engine too old to count\n\t * them is asked the way it always was, and the page has no facets.\n\t */\n\tfacets?: boolean\n}\n\nexport type CatalogPage = {\n\tdata: ReturnType<typeof toProduct>[] | ReturnType<typeof fromSearchDoc>[]\n\tcount: number\n\tpageSize: number\n\tnoOfPage: number\n\tpage: number\n\tcategoryHierarchy: { name: string; slug: string }[]\n\t/** Whether the answer honoured `sort` and the price range, or had to drop them. */\n\tsorted: boolean\n\tfacets?: ProductFacets\n}\n\n/**\n * The family's sort names, in the search index's terms. The engine's own\n * listing has one order — newest first — so anything else needs the index.\n * Popularity has no answer anywhere: the engine keeps no such score, and\n * inventing one would sort the shop into a plausible-looking lie.\n */\nfunction sortParts(sort: string): [string, 'asc' | 'desc'] {\n\tconst s = sort.trim()\n\tconst [field, dir] = s.startsWith('-') ? [s.slice(1), 'desc'] : s.includes(':') ? s.split(':') : [s, 'asc']\n\treturn [field, dir === 'desc' ? 'desc' : 'asc']\n}\n\nfunction indexSort(sort?: string): string | undefined {\n\tif (!sort) return undefined\n\tconst [field, d] = sortParts(sort)\n\tswitch (field) {\n\t\tcase 'price':\n\t\t\treturn `price_minor:${d}`\n\t\tcase 'updatedAt':\n\t\tcase 'updated_at':\n\t\tcase 'createdAt':\n\t\tcase 'created_at':\n\t\t\treturn `updated_at:${d}`\n\t\tcase 'title':\n\t\tcase 'name':\n\t\t\treturn `title:${d}`\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/** The same names in the engine listing's own `sort` and `order`. */\nfunction engineSort(sort?: string): { sort?: string; order?: string } {\n\tif (!sort || NATURAL.has(sort)) return {}\n\tconst [field, order] = sortParts(sort)\n\tconst key = (\n\t\t{\n\t\t\tprice: 'price',\n\t\t\tcreatedAt: 'created_at',\n\t\t\tcreated_at: 'created_at',\n\t\t\tupdatedAt: 'updated_at',\n\t\t\tupdated_at: 'updated_at',\n\t\t\ttitle: 'title',\n\t\t\tname: 'title',\n\t\t} as Record<string, string>\n\t)[field]\n\treturn key ? { sort: key, order } : {}\n}\n\n/** Newest first is the engine's own order, so these need no index. */\nconst NATURAL = new Set([\n\t'-createdAt',\n\t'createdAt:desc',\n\t'-updatedAt',\n\t'updatedAt:desc',\n\t'-popularity',\n\t'popularity:desc',\n])\n\nconst quote = (s: string) => `\"${s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n\n/**\n * One shelf of products, from whichever engine route can answer the question.\n *\n * - Words, with no tag, vendor, type or attribute ticked, on a store with the\n * Meilisearch plugin on: its index, which forgives typos, with the facet\n * rail the database counts for the same words.\n * - Asked for facets: `GET /api/products?facets=1`, which answers every filter,\n * the category and the sort on its own (D130).\n * - A category, no reordering: `GET /api/categories/{slug}`, which sells the\n * category and its descendants.\n * - A search or the whole shop, no reordering: `GET /api/products?q=`.\n * - Any sort but newest, or a price range: the Meilisearch module, when it is\n * installed and configured. Without it the shelf comes back in the engine's\n * order with `sorted: false`, rather than failing or pretending.\n *\n * Whenever the index cannot answer (Meilisearch down), the database does.\n */\n/** Engines, by base URL, that answered `facets=1` without facets. */\nconst legacyListing = new Set<string>()\n\nexport class CatalogService extends BaseService {\n\tprotected readonly facts = new StoreFacts(this._fetch)\n\n\tprotected async queryCatalog(q: CatalogQuery): Promise<CatalogPage> {\n\t\tconst page = Math.max(1, Number(q.page) || 1)\n\t\tconst limit = Math.min(100, Math.max(1, Number(q.limit) || PAGE_SIZE))\n\t\tconst search = q.search?.trim() || undefined\n\t\tconst wantsRange = Number.isFinite(q.priceFrom) || Number.isFinite(q.priceTo)\n\t\tconst sortKey = q.sort && !NATURAL.has(q.sort) ? indexSort(q.sort) : undefined\n\t\tconst hierarchy = q.category ? await this.facts.hierarchy(q.category) : []\n\t\tconst attr = Object.entries(q.attributes ?? {}).flatMap(([handle, values]) =>\n\t\t\tvalues.filter(Boolean).map((v) => `${handle}:${v}`),\n\t\t)\n\n\t\t// A shopper's words go to the index first: it forgives typos and ranks\n\t\t// by relevance. Not once they have ticked a tag, vendor, type or\n\t\t// attribute, which only the database filters and counts.\n\t\tconst refined = attr.length > 0 || !!(q.tags?.length || q.vendors?.length || q.productTypes?.length)\n\t\tconst triedIndex = !!search && !refined\n\t\tconst counted = q.facets && !legacyListing.has(this.engineBase())\n\t\tconst facetListing = async (page: number, limit: number) => {\n\t\t\tconst { currency } = await this.facts.ready()\n\t\t\tconst minor = (n?: number) => (Number.isFinite(n) ? Math.max(0, toMinor(n as number, currency)) : undefined)\n\t\t\treturn this.engine<Product[] | null>('/api/products', {\n\t\t\t\tquery: {\n\t\t\t\t\tq: search,\n\t\t\t\t\tpage,\n\t\t\t\t\tlimit,\n\t\t\t\t\tchannel: this.creds.channel,\n\t\t\t\t\tcategory: q.category,\n\t\t\t\t\ttag: q.tags,\n\t\t\t\t\tvendor: q.vendors,\n\t\t\t\t\tproduct_type: q.productTypes,\n\t\t\t\t\tattr,\n\t\t\t\t\tprice_min: minor(q.priceFrom),\n\t\t\t\t\tprice_max: minor(q.priceTo),\n\t\t\t\t\t...engineSort(q.sort),\n\t\t\t\t\tfacets: 1,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tif (triedIndex && (await this.facts.pluginOn('meilisearch'))) {\n\t\t\tconst [found, rail] = await Promise.all([\n\t\t\t\tthis.fromIndex(q, { page, limit, search, sortKey, wantsRange, hierarchy }),\n\t\t\t\tcounted ? facetListing(1, 1).catch(() => null) : null,\n\t\t\t])\n\t\t\t// The rail is the database's count for the same words: there to narrow\n\t\t\t// by when they match exactly, empty for a typo only the index forgives.\n\t\t\tif (found) return rail?.meta?.facets ? { ...found, facets: rail.meta.facets } : found\n\t\t}\n\n\t\tif (counted) {\n\t\t\tconst env = await facetListing(page, limit)\n\t\t\tif (env.meta?.facets) {\n\t\t\t\treturn {\n\t\t\t\t\t...toPage(env, (p: Product) => toProduct(p)),\n\t\t\t\t\tcategoryHierarchy: hierarchy,\n\t\t\t\t\tsorted: true,\n\t\t\t\t\tfacets: env.meta.facets,\n\t\t\t\t}\n\t\t\t}\n\t\t\t// ponytail: remembered until restart, so an engine upgraded under a running storefront gets facets after the next deploy.\n\t\t\tlegacyListing.add(this.engineBase())\n\t\t}\n\n\t\tif (!triedIndex && (sortKey || wantsRange)) {\n\t\t\tconst found = await this.fromIndex(q, { page, limit, search, sortKey, wantsRange, hierarchy })\n\t\t\tif (found) return found\n\t\t}\n\n\t\tconst sorted = !sortKey && !wantsRange\n\t\tif (q.category && !search) {\n\t\t\tconst env = await this.engine<{ products: Product[] | null }>(\n\t\t\t\t`/api/categories/${encodeURIComponent(q.category)}`,\n\t\t\t\t{ query: { page, limit } },\n\t\t\t)\n\t\t\tconst products = env.data?.products ?? []\n\t\t\treturn {\n\t\t\t\t...toPage({ data: products, meta: env.meta }, (p: Product) => toProduct(p)),\n\t\t\t\tcategoryHierarchy: hierarchy,\n\t\t\t\tsorted,\n\t\t\t}\n\t\t}\n\t\t// A search inside a category, without the index, searches the whole shop:\n\t\t// the engine's category route takes no query and its search takes no\n\t\t// category, and filtering one page client-side would make the count a lie.\n\t\tconst env = await this.engine<Product[] | null>('/api/products', {\n\t\t\tquery: { q: search, page, limit, channel: this.creds.channel, attr },\n\t\t})\n\t\treturn { ...toPage(env, (p: Product) => toProduct(p)), categoryHierarchy: hierarchy, sorted }\n\t}\n\n\t/**\n\t * The shelf from the Meilisearch module, or null when the store has it off,\n\t * sells through a channel, finds nothing for the words, or it cannot answer (Meilisearch down: the engine says `unavailable`), so\n\t * the caller asks the database instead of showing the shopper an error.\n\t */\n\tprotected async fromIndex(\n\t\tq: CatalogQuery,\n\t\to: { page: number; limit: number; search?: string; sortKey?: string; wantsRange: boolean; hierarchy: CatalogPage['categoryHierarchy'] },\n\t): Promise<CatalogPage | null> {\n\t\t// The index knows nothing of channels: a channel's shopper searches the\n\t\t// database, which shows only what the channel sells, at its prices.\n\t\tif (this.creds.channel || !(await this.facts.pluginOn('meilisearch'))) return null\n\t\tconst filters: string[] = []\n\t\tif (q.category) {\n\t\t\tconst names = (await this.facts.subtree(q.category).catch(() => [] as Category[])).map((c) => quote(c.full_name))\n\t\t\t// A slug the tree does not know sells nothing — say so, don't widen to the shop.\n\t\t\tif (!names.length) return { ...emptyCatalog(o.limit), categoryHierarchy: o.hierarchy, sorted: true }\n\t\t\tfilters.push(`category IN [${names.join(', ')}]`)\n\t\t}\n\t\tif (o.wantsRange) {\n\t\t\tconst { currency } = await this.facts.ready()\n\t\t\tif (Number.isFinite(q.priceFrom)) filters.push(`price_minor >= ${toMinor(q.priceFrom as number, currency)}`)\n\t\t\tif (Number.isFinite(q.priceTo)) filters.push(`price_minor <= ${toMinor(q.priceTo as number, currency)}`)\n\t\t}\n\t\tconst res = await this.data<SearchResult>('/x/meilisearch/search', {\n\t\t\tquery: {\n\t\t\t\tq: o.search ?? '',\n\t\t\t\tlimit: o.limit,\n\t\t\t\toffset: (o.page - 1) * o.limit,\n\t\t\t\tfilter: filters.join(' AND ') || undefined,\n\t\t\t\tsort: o.sortKey,\n\t\t\t},\n\t\t}).catch(() => null)\n\t\t// No hits for words may be an index still being built for a store that\n\t\t// just switched it on, or a sync that keeps failing: the database's\n\t\t// answer costs one query and is never worse than nothing.\n\t\tif (!res || res.unavailable || (o.search && !res.hits?.length)) return null\n\t\tconst total = res.total ?? 0\n\t\treturn {\n\t\t\tdata: (res.hits ?? []).map(fromSearchDoc),\n\t\t\tcount: total,\n\t\t\tpageSize: o.limit,\n\t\t\tnoOfPage: Math.max(1, Math.ceil(total / o.limit)),\n\t\t\tpage: o.page,\n\t\t\tcategoryHierarchy: o.hierarchy,\n\t\t\tsorted: true,\n\t\t}\n\t}\n}\n\nexport function emptyCatalog(limit = PAGE_SIZE) {\n\treturn { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 }\n}\n","import type { AddOn, Product, ReviewPage } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toAddOn, toProduct, toRating } from '../map'\nimport { currentMe } from '../browser'\nimport { CatalogService, PAGE_SIZE, type CatalogQuery } from './catalog'\n\n/**\n * Products: one by slug, and the shelves the homepage and listings draw.\n *\n * \"Featured\" and \"trending\" are curated rather than computed — the engine\n * keeps no sales or view counts to rank by. A collection with the slug\n * `featured` (or `trending`) is that shelf, so a merchant curates it in the\n * panel; without one, the shelf is the newest products, and says nothing more\n * about them than that.\n */\nexport class ProductService extends CatalogService {\n\t/**\n\t * A product page. `slug` may also be a numeric id or a variant SKU, which is\n\t * how an old link or a search hit sometimes arrives.\n\t *\n\t * Reviews ride along when ext/reviews is installed and switched on; a review\n\t * failure never costs the shopper the product page.\n\t */\n\tasync getOne(slug: string) {\n\t\tconst p = await this.findProduct(String(slug))\n\t\tconst product = toProduct(p, {\n\t\t\tcategoryHierarchy: p.category ? await this.facts.hierarchy(p.category.slug) : [],\n\t\t})\n\t\tif (await this.facts.pluginOn('product-reviews')) {\n\t\t\ttry {\n\t\t\t\tconst res = await this.data<ReviewPage>('/x/reviews', { query: { product_id: p.id, limit: 50 } })\n\t\t\t\tproduct.ratings = (res.reviews ?? []).map(toRating)\n\t\t\t\tproduct.rating = res.summary?.count ? res.summary.average : null\n\t\t\t\tproduct.ratingCount = res.summary?.count ?? 0\n\t\t\t\tproduct.reviewCount = res.summary?.count ?? 0\n\t\t\t} catch {\n\t\t\t\t// The page renders without stars rather than not at all.\n\t\t\t}\n\t\t}\n\t\treturn product\n\t}\n\n\tprivate async findProduct(slug: string): Promise<Product> {\n\t\ttry {\n\t\t\treturn await this.data<Product>(`/api/products/slug/${encodeURIComponent(slug)}`)\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t\t// Not a slug. An id or a SKU is worth one more question each, and a\n\t\t\t// miss on all three is the product's 404, not theirs.\n\t\t\tconst fallback = /^\\d+$/.test(slug) ? `/api/products/${slug}` : `/api/products/sku/${encodeURIComponent(slug)}`\n\t\t\ttry {\n\t\t\t\treturn await this.data<Product>(fallback)\n\t\t\t} catch {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The shop's listing: `{ page, search, sort }`, newest first unless the index can reorder it. */\n\tasync list({\n\t\tpage = 1,\n\t\tsearch,\n\t\tq,\n\t\tsort,\n\t\tlimit,\n\t\tcategories,\n\t}: CatalogQuery & { q?: string; categories?: string } = {}) {\n\t\tconst res = await this.queryCatalog({ page, search: search ?? q, sort, limit, category: categories || undefined })\n\t\treturn { data: res.data, count: res.count, pageSize: res.pageSize, noOfPage: res.noOfPage, page: res.page }\n\t}\n\n\tasync listFeaturedProducts({ page = 1, sort, limit }: { page?: number; sort?: string; limit?: number } = {}) {\n\t\treturn this.shelf('featured', { page, sort, limit })\n\t}\n\n\tasync listTrendingProducts({ page = 1, limit }: { page?: number; limit?: number } = {}) {\n\t\treturn this.shelf('trending', { page, limit })\n\t}\n\n\t/**\n\t * More like this product. Given `product` (a slug or id), it is the\n\t * product's category first, then its collections, then the newest — never\n\t * the product itself. Many shops never fill in categories, and an empty\n\t * rail under every product page reads as a broken shop.\n\t *\n\t * Without `product`, it is the old answer: more from `categoryId`.\n\t */\n\tasync listRelatedProducts({\n\t\tpage = 1,\n\t\tcategoryId,\n\t\tproduct,\n\t\tlimit,\n\t}: { page?: number; categoryId?: string; product?: string; limit?: number } = {}) {\n\t\tif (product) return this.relatedTo(String(product), limit)\n\t\tif (!categoryId) return this.list({ page, limit })\n\t\tconst category = (await this.facts.categories()).find((c) => String(c.id) === String(categoryId))\n\t\tif (!category) return this.list({ page, limit })\n\t\treturn this.list({ page, limit, categories: category.slug })\n\t}\n\n\t/**\n\t * What the shop offers with a product, ticked in its buy box (D133): each\n\t * add-on at the price ticking it adds. Only add-ons that can be bought\n\t * arrive; an engine without the route offers none.\n\t */\n\tasync listAddOns({ product }: { product: string }) {\n\t\tconst p = await this.findProduct(String(product))\n\t\ttry {\n\t\t\treturn ((await this.data<AddOn[] | null>('/api/add-ons', { query: { product_id: p.id } })) ?? []).map(toAddOn)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * \"You may also like\": the products the shop chose for this one, at their\n\t * own prices (D133). Curated only, and empty when none were chosen: the\n\t * related products already fill in from the category, and the page should\n\t * not draw the same fill twice.\n\t */\n\tasync listCrossSells({ product, limit }: { product: string; limit?: number }) {\n\t\tconst p = await this.findProduct(String(product))\n\t\ttry {\n\t\t\tconst rows = (await this.data<Product[] | null>('/api/cross-sells', { query: { product_id: p.id, limit } })) ?? []\n\t\t\treturn rows.map((r) => toProduct(r))\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tprivate async relatedTo(slug: string, limit?: number) {\n\t\tconst size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE))\n\t\tconst p = await this.findProduct(slug)\n\t\tconst self = String(p.id)\n\t\t// The listing answers either the engine's cards or the search index's,\n\t\t// so all a pick needs to know is the id.\n\t\tconst picked = new Map<string, { id: string }>()\n\t\tconst add = (rows: readonly { id: string }[]) => {\n\t\t\tfor (const r of rows) {\n\t\t\t\tif (picked.size >= size) return\n\t\t\t\tif (r.id !== self && !picked.has(r.id)) picked.set(r.id, r)\n\t\t\t}\n\t\t}\n\t\t// One more than needed, since the product itself may be among them.\n\t\tif (p.category) add((await this.list({ limit: size + 1, categories: p.category.slug })).data)\n\t\tfor (const c of p.collections ?? []) {\n\t\t\tif (picked.size >= size) break\n\t\t\tadd((await this.shelf(c.slug, { page: 1, limit: size + 1 })).data)\n\t\t}\n\t\tif (picked.size < size) add((await this.list({ limit: size + 1 })).data)\n\t\tconst data = [...picked.values()]\n\t\treturn { data, count: data.length, pageSize: size, noOfPage: 1, page: 1 }\n\t}\n\n\tprivate async shelf(slug: string, { page, sort, limit }: { page: number; sort?: string; limit?: number }) {\n\t\tconst size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE))\n\t\ttry {\n\t\t\tconst env = await this.engine<{ products: Product[] | null }>(`/api/collections/${slug}`, {\n\t\t\t\tquery: { page, limit: size },\n\t\t\t})\n\t\t\tconst rows = env.data?.products ?? []\n\t\t\treturn {\n\t\t\t\tdata: rows.map((p) => toProduct(p)),\n\t\t\t\tcount: env.meta?.total ?? rows.length,\n\t\t\t\tpageSize: env.meta?.limit ?? size,\n\t\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\t\tpage: env.meta?.page ?? page,\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t\treturn this.list({ page, sort, limit: size })\n\t\t}\n\t}\n\n\t/**\n\t * A review, through ext/reviews. The engine asks for a name and an email\n\t * with every review, so a signed-out shopper is asked to sign in rather\n\t * than having one made up for them. Uploaded photos have nowhere to go: the\n\t * module stores text.\n\t */\n\tasync addReview({\n\t\tproductId,\n\t\trating,\n\t\treview,\n\t\ttitle,\n\t}: {\n\t\tproductId: string\n\t\tvariantId?: string\n\t\trating: number\n\t\treview: string\n\t\ttitle?: string\n\t}) {\n\t\tconst me = currentMe()\n\t\tif (!me?.email) throw new GoCommerceError('Please sign in to write a review.', 401, 'unauthorized')\n\t\tconst name = [me.firstName, me.lastName].filter(Boolean).join(' ') || me.email.split('@')[0]\n\t\treturn this.data<{ status: string; verified: boolean }>('/x/reviews', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tproduct_id: Number(productId),\n\t\t\t\tname,\n\t\t\t\temail: me.email,\n\t\t\t\trating: Math.round(Number(rating)),\n\t\t\t\t...(title ? { title } : {}),\n\t\t\t\tbody: String(review ?? ''),\n\t\t\t},\n\t\t})\n\t}\n\n\tasync fetchReels(): Promise<never> {\n\t\tthrow new NotSupportedError('ProductService', 'fetchReels', 'the engine has no reels')\n\t}\n}\n\nexport const productService = new ProductService()\n","import type { Category, ProductFacets } from '../engine'\nimport { toMajor } from '../money'\nimport { CatalogService } from './catalog'\n\nconst num = (v: string | null): number | undefined => {\n\tif (v === null || v.trim() === '') return undefined\n\tconst n = Number(v)\n\treturn Number.isFinite(n) ? n : undefined\n}\n\n/** Decoded once more when it decodes: the storefront's filter rail encodes a value before the URL does. */\nfunction decodeOnce(v: string): string {\n\ttry {\n\t\treturn decodeURIComponent(v)\n\t} catch {\n\t\treturn v\n\t}\n}\n\n/** `?key=a,b` (repeatable) as `['a', 'b']`. */\nfunction listParam(p: URLSearchParams, key: string): string[] | undefined {\n\tconst out = p\n\t\t.getAll(key)\n\t\t.flatMap((v) => decodeOnce(v).split(','))\n\t\t.map((v) => v.trim())\n\t\t.filter(Boolean)\n\treturn out.length ? out : undefined\n}\n\n/** `?attributes.color=Red,Blue` — the storefront's facet params — as `{ color: ['Red', 'Blue'] }`. */\nfunction attributesFrom(p: URLSearchParams): Record<string, string[]> | undefined {\n\tconst out: Record<string, string[]> = {}\n\tfor (const key of new Set(p.keys())) {\n\t\tif (!key.startsWith('attributes.')) continue\n\t\tconst handle = key.slice('attributes.'.length)\n\t\tconst values = listParam(p, key)\n\t\tif (handle && values) out[handle] = values\n\t}\n\treturn Object.keys(out).length ? out : undefined\n}\n\nconst counts = (values: { value: string; count: number }[] | null | undefined) =>\n\tObject.fromEntries((values ?? []).map((v) => [v.value, v.count]))\n\ntype RailCategory = { name: string; slug: string; count: number; depth: number }\n\nfunction categoryFacets(counted: NonNullable<ProductFacets['categories']>, tree: Category[]): RailCategory[] {\n\tconst byId = new Map(tree.map((c) => [c.id, c]))\n\tconst totals = new Map<number, number>()\n\tfor (const { id, count } of counted) {\n\t\tfor (let c = byId.get(id); c; c = c.parent_id === null ? undefined : byId.get(c.parent_id)) {\n\t\t\ttotals.set(c.id, (totals.get(c.id) ?? 0) + count)\n\t\t}\n\t}\n\tconst kept = tree.filter((c) => totals.has(c.id)).sort((a, b) => a.position - b.position || a.id - b.id)\n\tconst parentOf = (c: Category) => (c.parent_id !== null && byId.has(c.parent_id) ? c.parent_id : null)\n\tconst under = (parent: number | null): RailCategory[] =>\n\t\tkept\n\t\t\t.filter((c) => parentOf(c) === parent)\n\t\t\t.flatMap((c) => [{ name: c.title, slug: c.slug, count: totals.get(c.id)!, depth: c.depth }, ...under(c.id)])\n\treturn [\n\t\t...under(null),\n\t\t...counted.filter((c) => !byId.has(c.id)).map((c) => ({ name: c.title, slug: c.slug, count: c.count, depth: 0 })),\n\t]\n}\n\n/**\n * The engine's counts in the shape the storefront's filter rail reads. Each\n * `allFilters` key is also the URL parameter the rail writes when a value is\n * ticked, and `searchWithUrl` reads it back: `vendor`, `product_type` and\n * `attributes.<handle>`. Tags go to the rail's own tag group, written as `tags`.\n */\nexport function toStorefrontFacets(f?: ProductFacets | null, tree: Category[] = []) {\n\tif (!f) return { priceStat: {}, categories: [], tags: [], allFilters: {} }\n\tconst allFilters: Record<string, Record<string, number>> = {}\n\tconst group = (key: string, values: { value: string; count: number }[] | null | undefined) => {\n\t\tif (values?.length) allFilters[key] = counts(values)\n\t}\n\tgroup('vendor', f.vendors)\n\tgroup('product_type', f.product_types)\n\tfor (const [handle, values] of Object.entries(f.attributes ?? {})) group(`attributes.${handle}`, values)\n\treturn {\n\t\tpriceStat: f.price ? { min: toMajor(f.price.min), max: toMajor(f.price.max) } : {},\n\t\tcategories: categoryFacets(f.categories ?? [], tree),\n\t\ttags: (f.tags ?? []).map((t) => ({ name: t.value, count: t.count })),\n\t\tallFilters,\n\t}\n}\n\n/**\n * The listing pages' search: `/products?search=&sort=&page=` and the category\n * catch-all `/{slug}`.\n *\n * Facets come from the engine, counted over the whole listing rather than the\n * page (D130). An engine too old to count them leaves them empty, and an empty\n * `priceStat` hides the price slider rather than drawing one with a made-up\n * range.\n */\nexport class SearchService extends CatalogService {\n\temptyResult() {\n\t\treturn {\n\t\t\tdata: [],\n\t\t\tcount: 0,\n\t\t\ttotalPages: 0,\n\t\t\tcategoryHierarchy: [] as { name: string; slug: string }[],\n\t\t\tfacets: toStorefrontFacets(),\n\t\t}\n\t}\n\n\tasync searchWithUrl(url: URL | string, slug?: string) {\n\t\ttry {\n\t\t\tconst u = typeof url === 'string' ? new URL(url, 'http://localhost') : url\n\t\t\tconst p = u.searchParams\n\t\t\t// `?price=10,50` is the chip form; priceFrom/priceTo the slider's.\n\t\t\tconst [from, to] = (p.get('price') ?? '').split(/[,-]/)\n\t\t\tconst res = await this.queryCatalog({\n\t\t\t\tpage: num(p.get('page')),\n\t\t\t\tsearch: p.get('search') ?? p.get('q') ?? undefined,\n\t\t\t\tsort: p.get('sort') ?? undefined,\n\t\t\t\tcategory: slug || p.get('categories')?.split(',')[0] || undefined,\n\t\t\t\tpriceFrom: num(p.get('priceFrom')) ?? num(from ?? null),\n\t\t\t\tpriceTo: num(p.get('priceTo')) ?? num(to ?? null),\n\t\t\t\tattributes: attributesFrom(p),\n\t\t\t\ttags: listParam(p, 'tags'),\n\t\t\t\tvendors: listParam(p, 'vendor'),\n\t\t\t\tproductTypes: listParam(p, 'product_type'),\n\t\t\t\tfacets: true,\n\t\t\t})\n\t\t\tconst tree = res.facets?.categories?.length ? await this.facts.categories().catch(() => [] as Category[]) : []\n\t\t\treturn {\n\t\t\t\tdata: res.data,\n\t\t\t\tcount: res.count,\n\t\t\t\ttotalPages: res.noOfPage,\n\t\t\t\tpage: res.page,\n\t\t\t\tcategoryHierarchy: res.categoryHierarchy,\n\t\t\t\tfacets: toStorefrontFacets(res.facets, tree),\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// A missing category is an empty result — the route turns that into\n\t\t\t// its 404 — but an engine that cannot be reached is not, and says so.\n\t\t\tif ((err as { status?: number })?.status === 404) return this.emptyResult()\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\nexport const searchService = new SearchService()\n","import type { Product } from '../engine'\nimport { toProduct } from '../map'\nimport { CatalogService } from './catalog'\n\n/**\n * The two places the storefront asks for raw search hits: \"more from this\n * category\" on a product page, and the header's type-ahead.\n *\n * Both go through ext/search-meilisearch when it is installed, and through the\n * engine's own listing when it is not — a type-ahead backed by a LIKE query is\n * slower and unranked, but it is not empty.\n */\nexport class MeilisearchService extends CatalogService {\n\t/** `{ query, categories, page }` → a Meilisearch-shaped answer: `hits`, `totalHits`, `totalPages`. */\n\tasync search({\n\t\tquery,\n\t\tsearch,\n\t\tcategories,\n\t\tpage = 1,\n\t\tlimit,\n\t}: { query?: string; search?: string; categories?: string; page?: number; limit?: number } = {}) {\n\t\tconst res = await this.queryCatalog({ page, limit, search: query ?? search, category: categories || undefined })\n\t\treturn {\n\t\t\thits: res.data,\n\t\t\ttotalHits: res.count,\n\t\t\testimatedTotalHits: res.count,\n\t\t\ttotalPages: res.noOfPage,\n\t\t\tpage: res.page,\n\t\t\tcategories: res.categoryHierarchy,\n\t\t\tfacetDistribution: {},\n\t\t}\n\t}\n\n\t/** The header's type-ahead: `{ data: [{ slug, title, thumbnail, price }] }`. */\n\tasync searchAutoComplete({ query, search, limit = 8 }: { query?: string; search?: string; limit?: number } = {}) {\n\t\tconst q = (query ?? search ?? '').trim()\n\t\tif (!q) return { data: [] }\n\t\tconst found = await this.fromIndex({}, { page: 1, limit, search: q, wantsRange: false, hierarchy: [] })\n\t\tif (found) return { data: found.data }\n\t\tconst rows =\n\t\t\t(await this.data<Product[] | null>('/api/products', { query: { q, limit, channel: this.creds.channel } })) ?? []\n\t\treturn { data: rows.map((p) => toProduct(p)) }\n\t}\n}\n\nexport const meilisearchService = new MeilisearchService()\n","import type { Category } from '../engine'\nimport { toCategory } from '../map'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\n\nconst asList = (rows: ReturnType<typeof toCategory>[]) => ({\n\tdata: rows,\n\tcount: rows.length,\n\tpageSize: rows.length,\n\tnoOfPage: 1,\n\tpage: 1,\n})\n\n/**\n * The category tree. The engine has no \"featured\" flag on a category, so the\n * featured row is the top level of the tree, in the merchant's order — which\n * is what a shop's first row of category tiles usually is anyway.\n */\nexport class CategoryService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/** Every category, flat, each naming its parent. The storefront builds the tree. */\n\tasync fetchAllCategories(_args: Record<string, unknown> = {}) {\n\t\tconst all = await this.facts.categories()\n\t\treturn asList(all.map(flat))\n\t}\n\n\tasync fetchFeaturedCategories({ limit = 18 }: { limit?: number } = {}) {\n\t\tconst roots = (await this.facts.categories()).filter((c) => c.parent_id === null)\n\t\treturn asList(roots.slice(0, Math.max(0, Number(limit) || 18)).map(flat))\n\t}\n\n\tasync fetchFooterCategories(args: { limit?: number } = {}) {\n\t\treturn this.fetchFeaturedCategories(args)\n\t}\n\n\t/** The nested tree, roots first. */\n\tasync getMegamenu(_args: Record<string, unknown> = {}) {\n\t\tconst tree = (await this.data<Category[] | null>('/api/categories')) ?? []\n\t\treturn tree.map(toCategory)\n\t}\n\n\tasync fetchCategory(slug: string) {\n\t\tconst c = await this.data<Category>(`/api/categories/${encodeURIComponent(slug)}`, { query: { limit: 1 } })\n\t\treturn toCategory(c)\n\t}\n\n\t/**\n\t * kitcommerce-core's category filter asks for `/api/categories/all` by path,\n\t * through the family's raw `get`. That is a Litekart path the rest-guard\n\t * would swallow, so it is answered here, from the engine's tree.\n\t */\n\toverride async get<T = any>(path: string): Promise<T> {\n\t\tif (path.split('?')[0] === '/api/categories/all') return (await this.fetchAllCategories()) as T\n\t\treturn super.get<T>(path)\n\t}\n}\n\n/** One row of the flat tree: no `children`, so the storefront's builder is the only one. */\nconst flat = (c: Category) => ({ ...toCategory(c), children: [] })\n\nexport const categoryService = new CategoryService()\n","import type { Collection, Product } from '../engine'\nimport { toCollection, toProduct } from '../map'\nimport { BaseService, toPage } from './base.service'\n\n/** Curated lists. Only collections holding at least one product on sale are listed. */\nexport class CollectionService extends BaseService {\n\tasync list({ page = 1, limit = 24 }: { page?: number; limit?: number; sort?: string; q?: string } = {}) {\n\t\tconst env = await this.engine<Collection[] | null>('/api/collections', { query: { page, limit } })\n\t\treturn toPage(env, toCollection)\n\t}\n\n\t/** A collection page: the collection, and its products in the merchant's order. */\n\tasync getOne(slug: string, { page = 1, limit = 48 }: { page?: number; limit?: number } = {}) {\n\t\tconst env = await this.engine<Collection & { products: Product[] | null }>(\n\t\t\t`/api/collections/${encodeURIComponent(slug)}`,\n\t\t\t{ query: { page, limit } },\n\t\t)\n\t\tconst products = (env.data.products ?? []).map((p) => toProduct(p))\n\t\treturn {\n\t\t\t...toCollection(env.data),\n\t\t\tproducts,\n\t\t\t// The family's shape for a collection's members.\n\t\t\tcollectionvalues: products.map((p) => ({ products: p })),\n\t\t\tcount: env.meta?.total ?? products.length,\n\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\tpage: env.meta?.page ?? page,\n\t\t}\n\t}\n\n\t/** Collection-level ratings are a Litekart aggregate; the engine has none to report. */\n\tasync getAllRatings() {\n\t\treturn { data: [] as unknown[] }\n\t}\n}\n\nexport const collectionService = new CollectionService()\n","import type { AppliedDiscount, Cart, CartLine, CartOffer, FreeShipping, Product } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { emptyCart, toCart, toCartOffer, toFreeShipping, toProduct } from '../map'\nimport { remember } from '../cache'\nimport {\n\tcartExtras,\n\tforgetCartExtras,\n\trememberCartId,\n\tsaveCartExtras,\n\tsessionToken,\n\tstoredCartId,\n\ttype StorefrontAddress,\n} from '../browser'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { ProductService } from './product-service'\n\n/** The storefront's \"take this line out\" sentinel, sent when − is pressed on a quantity of one. */\nconst REMOVE = -9999999\n\n/**\n * The bag.\n *\n * The engine's cart is addressed by an opaque token it mints, held by the\n * storefront in `localStorage.cart_id`. It keeps lines and an email; the\n * coupon, the address and the delivery choice the storefront collects before\n * checkout are kept beside it in the browser (browser.ts) and sent with the\n * checkout request, which is the only place the engine takes them.\n *\n * Every method answers the whole cart, as the storefront assigns it whole.\n */\nexport class CartService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync getCartByCartId(cartId?: string | null) {\n\t\tconst id = clean(cartId)\n\t\tif (!id) return emptyCart(await this.currency())\n\t\ttry {\n\t\t\treturn await this.present(await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`))\n\t\t} catch (err) {\n\t\t\t// A cart expires after a month untouched. A shopper coming back to a\n\t\t\t// dead token sees an empty bag, not an error.\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return emptyCart(await this.currency())\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tasync fetchCartData(cartId?: string | null) {\n\t\treturn this.getCartByCartId(cartId ?? storedCartId())\n\t}\n\n\t/**\n\t * The cart after an order: the engine marks it `converted` and keeps its\n\t * lines, and this answers it with none — which is how the storefront knows\n\t * to clear the bag on the success page.\n\t */\n\tasync refereshCart() {\n\t\tconst id = storedCartId()\n\t\tconst cart = await this.getCartByCartId(id)\n\t\tif (id && (cart as { status?: string }).status === 'converted') forgetCartExtras(id)\n\t\treturn cart\n\t}\n\n\t/**\n\t * `qty` is a change, not a total: +1 from a product page, −1 from a card's\n\t * minus button. With no cart yet, one is opened and remembered. A\n\t * `designId` from `customizerService.saveDesign` makes the variant to the\n\t * shopper's design, on a line of its own.\n\t */\n\tasync addToCart({\n\t\tcartId,\n\t\tlineId,\n\t\tqty = 1,\n\t\tvariantId,\n\t\tdesignId,\n\t}: {\n\t\tcartId?: string | null\n\t\tlineId?: string | null\n\t\tqty?: number\n\t\tproductId?: string\n\t\tvariantId?: string\n\t\tdesignId?: string\n\t}) {\n\t\tlet id = clean(cartId) ?? storedCartId()\n\t\tif (lineId && id) {\n\t\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\t\tconst line = (cart.line_items ?? []).find((l) => String(l.id) === String(lineId))\n\t\t\tif (line) {\n\t\t\t\tconst next = qty === REMOVE ? 0 : line.quantity + Number(qty)\n\t\t\t\treturn this.setQuantity(id, line.id, next)\n\t\t\t}\n\t\t}\n\t\tif (qty === REMOVE || Number(qty) <= 0) return this.getCartByCartId(id)\n\t\tif (!variantId) throw new GoCommerceError('Please choose an option before adding this to your bag.', 400)\n\t\tif (!id) id = await this.open()\n\t\tconst body = { variant_id: Number(variantId), quantity: Number(qty), ...(designId ? { design_id: designId } : {}) }\n\t\ttry {\n\t\t\treturn await this.present(\n\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items`, { method: 'POST', body }),\n\t\t\t)\n\t\t} catch (err) {\n\t\t\t// The remembered cart was checked out in another tab, or expired, so a\n\t\t\t// new one is started rather than refusing the shopper's click. A missing\n\t\t\t// variant or design is a 404 too, and must not leave the bag behind.\n\t\t\tif (cartGone(err)) {\n\t\t\t\tconst fresh = await this.open()\n\t\t\t\treturn this.present(\n\t\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(fresh)}/line-items`, { method: 'POST', body }),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * Adds an add-on from a product's \"Complete the set\" (D133) at its offer\n\t * price. The product it is offered with has to be in the bag already, so\n\t * this is called after adding it; the engine refuses one too many with the\n\t * sentence the shopper is shown.\n\t */\n\tasync addAddOn({ cartId, addOnId, qty = 1 }: { cartId?: string | null; addOnId: string | number; qty?: number }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) throw new GoCommerceError('Add the product to your bag first.', 409)\n\t\treturn this.present(\n\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: { add_on_id: Number(addOnId), quantity: Number(qty) },\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * The codes the shop chose to show (D133), each with what it takes off this\n\t * bag or how much more the bag needs. None without a bag.\n\t */\n\tasync getOffers({ cartId }: { cartId?: string | null } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return []\n\t\ttry {\n\t\t\tconst rows = (await this.data<CartOffer[] | null>(`/api/carts/${encodeURIComponent(id)}/offers`)) ?? []\n\t\t\tconst currency = await this.currency()\n\t\t\treturn rows.map((o) => toCartOffer(o, o.amount?.currency ?? o.remaining?.currency ?? currency))\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * How far the bag is from free delivery (D133), read from the store's own\n\t * rates for the country (the store's own when none is given). Null when\n\t * the engine cannot say: a bar with a made-up figure is worse than none.\n\t */\n\tasync getFreeShipping({ cartId, country, state }: { cartId?: string | null; country?: string; state?: string } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return null\n\t\tconst where = country ?? cartExtras(id).shippingAddress?.country ?? undefined\n\t\ttry {\n\t\t\treturn toFreeShipping(\n\t\t\t\tawait this.data<FreeShipping>(`/api/carts/${encodeURIComponent(id)}/free-shipping`, {\n\t\t\t\t\tquery: { country: where || undefined, state: state || undefined },\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return null\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * \"You may be interested in\" (D133): what the bag's products suggest, less\n\t * what it holds; with nothing curated, the first product's related\n\t * products, still less what it holds.\n\t */\n\tasync listCrossSells({ cartId, limit = 12 }: { cartId?: string | null; limit?: number } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return []\n\t\tlet curated: Product[] = []\n\t\ttry {\n\t\t\tcurated = (await this.data<Product[] | null>(`/api/carts/${encodeURIComponent(id)}/cross-sells`, { query: { limit } })) ?? []\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t}\n\t\tif (curated.length) return curated.map((p) => toProduct(p))\n\t\tlet cart: Cart\n\t\ttry {\n\t\t\tcart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\t} catch {\n\t\t\treturn []\n\t\t}\n\t\tconst held = new Set((cart.line_items ?? []).map((l) => String(l.product_id)))\n\t\tconst first = cart.line_items?.[0]\n\t\tif (!first) return []\n\t\tconst related = await new ProductService(this._fetch).listRelatedProducts({\n\t\t\tproduct: String(first.product_id),\n\t\t\tlimit: limit + held.size,\n\t\t})\n\t\treturn (related.data as { id: string }[]).filter((p) => !held.has(String(p.id))).slice(0, limit)\n\t}\n\n\t/** `qty` is the new total; 0 takes the line out. */\n\tasync updateCart({\n\t\tcartId,\n\t\tlineId,\n\t\tqty,\n\t}: {\n\t\tcartId?: string\n\t\tlineId: string\n\t\tqty: number\n\t\tisSelectedForCheckout?: boolean\n\t}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\treturn this.setQuantity(id, lineId, Number(qty))\n\t}\n\n\tasync removeCart({ cartId, lineId }: { cartId?: string; lineId: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\treturn this.present(\n\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items/${encodeURIComponent(String(lineId))}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * Contact details and addresses, from the checkout's address step. The\n\t * email goes to the engine — it is how an abandoned cart is followed up —\n\t * and the rest is kept for the checkout request.\n\t */\n\tasync updateCart2(args: {\n\t\tcartId?: string\n\t\temail?: string\n\t\tphone?: string\n\t\tshippingAddress?: StorefrontAddress | null\n\t\tbillingAddress?: StorefrontAddress | null\n\t\tisBillingAddressSameAsShipping?: boolean\n\t}) {\n\t\tconst id = clean(args.cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\n\t\tconst patch: Parameters<typeof saveCartExtras>[1] = {}\n\t\tif (args.phone !== undefined) patch.phone = args.phone || undefined\n\t\tif (args.shippingAddress !== undefined) {\n\t\t\tpatch.shippingAddress = args.shippingAddress\n\t\t\tif (args.shippingAddress?.phone && !patch.phone) patch.phone = String(args.shippingAddress.phone)\n\t\t}\n\t\tif (args.billingAddress !== undefined || args.isBillingAddressSameAsShipping) {\n\t\t\tpatch.billingAddress = args.isBillingAddressSameAsShipping ? null : (args.billingAddress ?? null)\n\t\t}\n\t\t// A new destination may not be served by the rate chosen for the old one.\n\t\tconst before = cartExtras(id)\n\t\tconst country = (a?: StorefrontAddress | null) => String(a?.countryCode || a?.country || '').toUpperCase()\n\t\tif (args.shippingAddress !== undefined && country(args.shippingAddress) !== country(before.shippingAddress)) {\n\t\t\tpatch.shippingRateId = null\n\t\t\tpatch.shippingRate = null\n\t\t}\n\t\tsaveCartExtras(id, patch)\n\n\t\tconst email = args.email ?? (args.shippingAddress?.email ? String(args.shippingAddress.email) : undefined)\n\t\tif (email !== undefined) {\n\t\t\treturn this.present(\n\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/email`, { method: 'PUT', body: { email } }),\n\t\t\t)\n\t\t}\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/**\n\t * A discount code. The engine prices it against the basket now and decides\n\t * it again at checkout; what it answers is kept so the bag can show it,\n\t * because the cart itself does not carry the code.\n\t */\n\tasync applyCoupon({ cartId, couponCode }: { cartId?: string; couponCode: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) throw new GoCommerceError('Add something to your bag before applying a code.', 400)\n\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\tconst discount = await this.data<AppliedDiscount>(`/api/carts/${encodeURIComponent(id)}/discount`, {\n\t\t\tmethod: 'PUT',\n\t\t\tbody: { code: String(couponCode ?? '').trim(), ...(cart.email ? { email: cart.email } : {}) },\n\t\t})\n\t\tsaveCartExtras(id, { discount: { ...discount, code: discount.code || String(couponCode).trim() } })\n\t\treturn this.present(cart)\n\t}\n\n\tasync removeCoupon(cartId?: string) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\tawait this.engine(`/api/carts/${encodeURIComponent(id)}/discount`, { method: 'DELETE' })\n\t\tsaveCartExtras(id, { discount: null })\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/** The delivery option the shopper picked, priced from the engine's own quote. */\n\tasync updateShippingRate({ cartId, shippingRateId }: { cartId?: string; shippingRateId: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\tconst ship = cartExtras(id).shippingAddress\n\t\tconst country = String(ship?.countryCode || ship?.country || '').toUpperCase()\n\t\tif (!country) throw new GoCommerceError('Add a delivery address first.', 400)\n\t\tconst quote = await this.data<{\n\t\t\trates: { rate_id: number; name: string; price: { amount_minor: number; currency: string } }[] | null\n\t\t\tcurrency: string\n\t\t}>('/api/checkout/rates', { query: { cart: id, country, state: ship?.state ? String(ship.state) : undefined } })\n\t\tconst rate = (quote.rates ?? []).find((r) => String(r.rate_id) === String(shippingRateId))\n\t\tif (!rate) throw new GoCommerceError('That delivery option is not available for this address any more.', 409)\n\t\tsaveCartExtras(id, {\n\t\t\tshippingRateId: String(rate.rate_id),\n\t\t\tshippingRate: {\n\t\t\t\tid: String(rate.rate_id),\n\t\t\t\tname: rate.name,\n\t\t\t\tminor: rate.price.amount_minor,\n\t\t\t\tcurrency: rate.price.currency,\n\t\t\t},\n\t\t})\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/** The payment method is chosen at checkout, by which checkout route is called. */\n\tasync updateCartPaymentMethod({ cartId }: { cartId?: string; paymentMethod?: string }) {\n\t\treturn this.getCartByCartId(clean(cartId) ?? storedCartId())\n\t}\n\n\tasync completeCart(): Promise<never> {\n\t\tthrow new NotSupportedError('CartService', 'completeCart', 'an order is placed through checkoutService')\n\t}\n\n\t// ------------------------------------------------------------ internals\n\n\tprivate async setQuantity(cartId: string, lineId: string | number, qty: number) {\n\t\tconst path = `/api/carts/${encodeURIComponent(cartId)}/line-items/${encodeURIComponent(String(lineId))}`\n\t\t// Zero is a removal: the engine accepts it on PATCH, and DELETE says it plainly.\n\t\tif (qty <= 0) return this.present(await this.data<Cart>(path, { method: 'DELETE' }))\n\t\treturn this.present(await this.data<Cart>(path, { method: 'PATCH', body: { quantity: qty } }))\n\t}\n\n\t/** A new cart, remembered — and priced for the signed-in shopper's group when the engine allows it. */\n\tprivate async open(): Promise<string> {\n\t\tconst channel = this.creds.channel\n\t\tconst cart = await this.data<Cart>('/api/carts', { method: 'POST', ...(channel ? { body: { channel } } : {}) })\n\t\trememberCartId(cart.id)\n\t\tif (sessionToken()) await this.claimCartForAccount(cart.id)\n\t\treturn cart.id\n\t}\n\n\tprivate async currency(): Promise<string> {\n\t\ttry {\n\t\t\treturn (await this.facts.ready()).currency\n\t\t} catch {\n\t\t\treturn 'USD'\n\t\t}\n\t}\n\n\t/** The engine's cart with the browser-held extras and each line's picture and link. */\n\tprivate async present(cart: Cart) {\n\t\tconst ids = [...new Set((cart.line_items ?? []).map((l) => l.product_id))]\n\t\tconst products = new Map<number, Product | null>()\n\t\tawait Promise.all(\n\t\t\tids.map(async (pid) => {\n\t\t\t\tproducts.set(pid, await this.productFor(pid))\n\t\t\t}),\n\t\t)\n\t\treturn toCart(cart, cartExtras(cart.id), (l: CartLine) => {\n\t\t\tconst p = products.get(l.product_id)\n\t\t\tif (!p) return {}\n\t\t\tconst v = (p.variants ?? []).find((x) => x.id === l.variant_id)\n\t\t\treturn { slug: p.slug, thumbnail: v?.image?.url ?? p.image_url ?? null }\n\t\t})\n\t}\n\n\tprivate productFor(id: number): Promise<Product | null> {\n\t\treturn remember(`${this.engineBase()}|product|${id}`, () =>\n\t\t\tthis.data<Product>(`/api/products/${id}`).catch(() => null),\n\t\t)\n\t}\n}\n\nconst clean = (id?: string | null): string | null => (id && id !== 'undefined' && id !== 'null' ? id : null)\n\nconst cartGone = (err: unknown): boolean =>\n\terr instanceof GoCommerceError &&\n\t(err.code === 'cart_not_found' || err.code === 'cart_checked_out' || cartGoneOnOlderEngine(err))\n\nconst cartGoneOnOlderEngine = (err: GoCommerceError): boolean =>\n\t(err.code === 'not_found' && err.message === 'cart not found') ||\n\t(err.code === 'conflict' && err.message === 'this cart has already been checked out')\n\nexport const cartService = new CartService()\n","import type { CustomizerDesign, CustomizerDocument, CustomizerSetup, CustomizerUpload } from '../engine'\nimport { BaseService, mediaUrl } from './base.service'\nimport { StoreFacts } from './facts'\n\n/** What a product's design editor draws and offers, in the mockup's pixels. */\nexport type CustomizerEditor = {\n\tproductId: string\n\tmockup: { url: string; width: number; height: number }\n\t/** Drawn above the design: the camera cut-out, the case's edges. */\n\toverlayUrl: string | null\n\tprintArea: { x: number; y: number; width: number; height: number; radius: number }\n\tprintSize: { widthMm: number; heightMm: number; dpi: number }\n\ttools: { upload: boolean; text: boolean; shapes: boolean; background: boolean; stickers: boolean }\n\tfonts: { key: string; family: string }[]\n\tstickers: { id: number; url: string; width: number; height: number }[]\n\t/** A photo whose shorter side is below this is likely to print soft: warn, the engine still takes it. */\n\tminPhotoPx: number\n\t/** Shown before the shopper chooses a photo. */\n\tconsent: string\n}\n\nexport type CustomizerFile = { uploadId: string; url: string; width: number; height: number }\n\nexport type CustomizerSavedDesign = { designId: string; previewUrl: string }\n\n/**\n * A shopper's own design on a product (ext/customizer, D162). Every URL goes\n * through the proxy path when one is set, so it is same-origin and a canvas\n * that draws it can still be exported.\n */\nexport class CustomizerService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/** Null when the product cannot be designed, or on any failure: the page draws without the editor. */\n\tasync setup(productId: string | number): Promise<CustomizerEditor | null> {\n\t\tconst plugins = await this.facts.plugins().catch(() => null)\n\t\tif (plugins && !plugins.has('customizer')) return null\n\t\tconst path = `/x/customizer/products/${encodeURIComponent(String(productId))}`\n\t\tconst s = await this.data<CustomizerSetup>(path).catch(() => null)\n\t\tif (!s) return null\n\t\treturn {\n\t\t\tproductId: String(s.product_id),\n\t\t\tmockup: { ...s.mockup, url: media(s.mockup.url) },\n\t\t\toverlayUrl: mediaUrl(s.overlay_url),\n\t\t\tprintArea: s.print_area,\n\t\t\tprintSize: { widthMm: s.print_size.width_mm, heightMm: s.print_size.height_mm, dpi: s.print_size.dpi },\n\t\t\ttools: s.tools,\n\t\t\tfonts: s.fonts,\n\t\t\tstickers: s.stickers.map((k) => ({ ...k, url: media(k.url) })),\n\t\t\tminPhotoPx: s.min_photo_px,\n\t\t\tconsent: s.consent,\n\t\t}\n\t}\n\n\t/** A photo, or the finished preview or print file. The engine's refusal is thrown with its message. */\n\tasync upload(file: Blob, filename?: string): Promise<CustomizerFile> {\n\t\tconst body = new FormData()\n\t\tbody.append('file', file, filename)\n\t\tconst u = await this.data<CustomizerUpload>('/x/customizer/uploads', { method: 'POST', body })\n\t\treturn { uploadId: u.upload_id, url: media(u.url), width: u.width, height: u.height }\n\t}\n\n\t/** The document goes as it is: the order keeps it, and whatever renders the print reads it there. */\n\tasync saveDesign(design: {\n\t\tproductId: string | number\n\t\tvariantId: string | number\n\t\tpreviewUploadId: string\n\t\tprintUploadId: string\n\t\tdocument: CustomizerDocument\n\t}): Promise<CustomizerSavedDesign> {\n\t\tconst d = await this.data<CustomizerDesign>('/x/customizer/designs', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tproduct_id: Number(design.productId),\n\t\t\t\tvariant_id: Number(design.variantId),\n\t\t\t\tpreview_upload_id: design.previewUploadId,\n\t\t\t\tprint_upload_id: design.printUploadId,\n\t\t\t\tdocument: design.document,\n\t\t\t},\n\t\t})\n\t\treturn { designId: d.design_id, previewUrl: media(d.preview_url) }\n\t}\n}\n\nconst media = (url: string) => mediaUrl(url) ?? url\n\nexport const customizerService = new CustomizerService()\n","import type { Cart, CheckoutResult } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toEngineAddress, toOrder } from '../map'\nimport { minorToMajor } from '../money'\nimport {\n\tcartExtras,\n\tlandingAttribution,\n\tmetaBrowser,\n\tplacedOrderByReference,\n\trememberOrder,\n\tsaveCartExtras,\n\tsessionToken,\n\tstoredCartId,\n} from '../browser'\nimport { BaseService } from './base.service'\n\n/**\n * Placing an order.\n *\n * The engine turns a cart into an order in one call, `POST /api/checkout/{code}`,\n * and that call is the only thing that moves stock and asks for money. It takes\n * the address, phone and delivery choice in its body — the cart keeps none of\n * them — so they are read back from what the address step stored (browser.ts).\n *\n * Payment is confirmed by the gateway's webhook to the engine, never by the\n * storefront. So the \"capture\" calls the storefront makes after a gateway's\n * modal closes do not capture anything: they hand back the order number, and\n * the order page shows `payment_status` once the webhook has landed.\n */\nexport class CheckoutService extends BaseService {\n\t/** Delivery options for the address on the cart: `{ data: [{ id, name, base_rate }] }`. */\n\tasync getShippingRates({ cartId }: { cartId?: string } = {}) {\n\t\tconst id = cartId || storedCartId()\n\t\tconst ship = id ? cartExtras(id).shippingAddress : null\n\t\tconst country = String(ship?.countryCode || ship?.country || '').toUpperCase()\n\t\tif (!id || !country) return { data: [] }\n\t\tconst quote = await this.data<{\n\t\t\trates: { rate_id: number; name: string; price: { amount_minor: number; currency: string } }[] | null\n\t\t\tcurrency: string\n\t\t}>('/api/checkout/rates', { query: { cart: id, country, state: ship?.state ? String(ship.state) : undefined } })\n\t\treturn {\n\t\t\tdata: (quote.rates ?? []).map((r) => ({\n\t\t\t\tid: String(r.rate_id),\n\t\t\t\tname: r.name,\n\t\t\t\tdescription: null,\n\t\t\t\tbase_rate: minorToMajor(r.price.amount_minor, r.price.currency),\n\t\t\t\tprice: minorToMajor(r.price.amount_minor, r.price.currency),\n\t\t\t\tcurrencyCode: r.price.currency,\n\t\t\t\t// The engine's rates carry no delivery estimate; none is made up.\n\t\t\t\testimated_min_days: null,\n\t\t\t\testimated_max_days: null,\n\t\t\t})),\n\t\t}\n\t}\n\n\t/** Cash on delivery: the order is confirmed at once and paid on the doorstep. */\n\tasync checkoutCOD({ cartId }: { cartId?: string; origin?: string } = {}) {\n\t\tconst result = await this.place('cod', cartId)\n\t\treturn {\n\t\t\torder_no: result.order.number,\n\t\t\torderNo: result.order.number,\n\t\t\tid: String(result.order.id),\n\t\t\tstatus: result.order.status,\n\t\t}\n\t}\n\n\t/**\n\t * Razorpay's modal. The engine has already created the Razorpay order; this\n\t * hands the storefront what the modal needs. A store running Razorpay's\n\t * hosted (redirect) mode cannot be driven from this storefront's modal flow,\n\t * and says so rather than opening a modal on an order it cannot pay.\n\t */\n\tasync checkoutRazorpay({ cartId }: { cartId?: string; origin?: string } = {}) {\n\t\tconst result = await this.place('razorpay', cartId)\n\t\tconst data = result.payment.client_data ?? {}\n\t\tif (result.payment.kind !== 'client_action' || !data.razorpay_order_id) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'This store takes Razorpay payments on Razorpay’s own page, which this storefront does not support yet.',\n\t\t\t\t0,\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\torder_no: result.order.number,\n\t\t\tid: data.razorpay_order_id,\n\t\t\tkey_id: data.key_id,\n\t\t\tamount: Number(data.amount),\n\t\t\tcurrency: data.currency,\n\t\t}\n\t}\n\n\t/** The modal closed with a payment. The engine learns of it from Razorpay itself. */\n\tasync captureRazorpayPayment({ razorpay_order_id }: { razorpay_order_id: string; razorpay_payment_id?: string }) {\n\t\tconst order = placedOrderByReference(razorpay_order_id)\n\t\tif (!order) throw new GoCommerceError('That payment does not belong to an order placed from this browser.', 404)\n\t\treturn { order_no: order.number, status: 'processing' }\n\t}\n\n\t// The family's other gateway flows. GoCommerce's Stripe is a Payment\n\t// Element (a client secret, not a hosted page) — `checkout('stripe')` returns\n\t// that secret for a storefront that mounts the element. Cashfree, PhonePe and\n\t// Affirm are not engine gateways at all. paymentMethodService never offers\n\t// these codes, so they are reached only by a storefront that hard-codes one.\n\tasync checkoutStripe(): Promise<never> {\n\t\tthrow unsupported(\n\t\t\t'checkoutStripe',\n\t\t\t'GoCommerce’s Stripe gateway uses the Payment Element, not a hosted checkout page',\n\t\t)\n\t}\n\tasync checkoutStripeCapture(): Promise<never> {\n\t\tthrow unsupported('checkoutStripeCapture', 'Stripe confirms payments to the engine by webhook')\n\t}\n\t/**\n\t * The storefront's generic redirect flow, which it reaches through the code\n\t * `PAYPAL`. The engine has no PayPal gateway; paymentMethodService puts the\n\t * store's first hosted-page gateway — Adyen, Paddle, Lemon Squeezy, Creem,\n\t * Hyperswitch or RevenueCat — under that code, with its own name and a\n\t * neutral icon, because this is the one storefront flow that sends a shopper\n\t * to a URL and back. The shopper returns to the success page; the gateway's\n\t * webhook tells the engine the order is paid.\n\t */\n\tasync checkoutPaypal({ cartId, origin }: { cartId?: string; origin?: string; return_url?: string } = {}) {\n\t\tconst gateway = await this.redirectGateway()\n\t\tif (!gateway) throw unsupported('checkoutPaypal', 'this store has no hosted-page payment gateway switched on')\n\t\tconst id = cartId || storedCartId() || ''\n\t\tconst back = origin ? `${origin.replace(/\\/+$/, '')}/checkout/success?cart_id=${encodeURIComponent(id)}` : undefined\n\t\tconst result = await this.place(gateway, id, back ? { return_url: back } : {})\n\t\tconst url = result.payment.client_data?.url\n\t\tif (!url) throw new GoCommerceError('The payment page did not open. Please try again.', 502)\n\t\treturn { redirect_url: url, order_no: result.order.number }\n\t}\n\n\t/**\n\t * Nothing to capture: a hosted-page gateway confirms the payment to the\n\t * engine by webhook. Answering, rather than throwing, sends the storefront's\n\t * process page on to the success page instead of the failure page.\n\t */\n\tasync capturePaypalPayment({\n\t\torder_no,\n\t}: { order_no?: string; token?: string; PayerID?: string; storeId?: string } = {}) {\n\t\treturn { order_no: order_no ?? null, status: 'processing' }\n\t}\n\tasync checkoutCashfree(): Promise<never> {\n\t\tthrow unsupported('checkoutCashfree', 'the engine has no Cashfree gateway')\n\t}\n\tasync captureCashfreePayment(): Promise<never> {\n\t\tthrow unsupported('captureCashfreePayment', 'the engine has no Cashfree gateway')\n\t}\n\tasync checkoutPhonepe(): Promise<never> {\n\t\tthrow unsupported('checkoutPhonepe', 'the engine has no PhonePe gateway')\n\t}\n\tasync createAffirmPayOrder(): Promise<never> {\n\t\tthrow unsupported('createAffirmPayOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync confirmAffirmOrder(): Promise<never> {\n\t\tthrow unsupported('confirmAffirmOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync cancelAffirmOrder(): Promise<never> {\n\t\tthrow unsupported('cancelAffirmOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync checkoutPOS(): Promise<never> {\n\t\tthrow unsupported('checkoutPOS', 'point-of-sale orders are placed from the admin panel')\n\t}\n\n\t/**\n\t * Any payment method the engine has switched on, by its engine code —\n\t * `cod`, `stripe`, `razorpay`, `adyen`, `paddle`, `helcim`… For a storefront\n\t * that drives the payment itself: the answer says what to do next.\n\t *\n\t * - `kind: 'none'` — nothing to pay now (cash on delivery).\n\t * - `kind: 'client_action'` — mount the gateway's own widget with\n\t * `clientData`: Stripe's Payment Element takes `clientSecret`, Razorpay's\n\t * modal `razorpay_order_id` and `key_id`, Helcim's `checkout_token`.\n\t * - `kind: 'redirect'` — send the shopper to `redirectUrl`; `returnUrl` is\n\t * where the gateway brings them back.\n\t *\n\t * Either way the gateway's webhook tells the engine when the money arrives;\n\t * read `orderService.getOrder(orderNo).paymentStatus` to see it.\n\t */\n\tasync checkout(\n\t\tcode: string,\n\t\t{\n\t\t\tcartId,\n\t\t\treturnUrl,\n\t\t\tpaymentData,\n\t\t\tmetadata,\n\t\t}: {\n\t\t\tcartId?: string\n\t\t\treturnUrl?: string\n\t\t\tpaymentData?: Record<string, string>\n\t\t\tmetadata?: Record<string, unknown>\n\t\t} = {},\n\t) {\n\t\tconst result = await this.place(String(code).toLowerCase(), cartId, {\n\t\t\t...(returnUrl ? { return_url: returnUrl } : {}),\n\t\t\t...(paymentData ? { payment_data: paymentData } : {}),\n\t\t\t...(metadata ? { metadata } : {}),\n\t\t})\n\t\tconst data = result.payment.client_data ?? {}\n\t\treturn {\n\t\t\torderNo: result.order.number,\n\t\t\torder: toOrder(result.order),\n\t\t\tpayment: {\n\t\t\t\tkind: result.payment.kind,\n\t\t\t\tprovider: result.payment.provider,\n\t\t\t\treference: result.payment.reference ?? null,\n\t\t\t\tclientSecret: data.client_secret ?? null,\n\t\t\t\tredirectUrl: data.url ?? null,\n\t\t\t\tclientData: data,\n\t\t\t},\n\t\t}\n\t}\n\n\t/** Every payment method the engine has switched on, by engine code and name — drivable here or not. */\n\tasync listMethods() {\n\t\tconst options = await this.data<{ methods: { code: string; name: string }[] | null; currency: string }>(\n\t\t\t'/api/checkout',\n\t\t)\n\t\treturn { methods: options.methods ?? [], currency: options.currency }\n\t}\n\n\tprivate async redirectGateway(): Promise<string | undefined> {\n\t\tconst { methods } = await this.listMethods()\n\t\treturn methods.find((m) => REDIRECT_GATEWAYS.has(m.code))?.code\n\t}\n\n\t/**\n\t * One checkout attempt.\n\t *\n\t * The Idempotency-Key is kept with the cart and reused while the request is\n\t * the same, because a payment gateway that fails after the engine has\n\t * created the order leaves the cart converted: only a retry under the same\n\t * key resumes that order, and without one the shopper is stuck. A changed\n\t * request — a different address, a different method — gets a new key, since\n\t * the engine refuses a key replayed with a different body.\n\t */\n\tprivate async place(\n\t\tcode: string,\n\t\tcartId?: string,\n\t\textra: { return_url?: string; payment_data?: Record<string, string>; metadata?: Record<string, unknown> } = {},\n\t): Promise<CheckoutResult> {\n\t\tconst id = cartId || storedCartId()\n\t\tif (!id) throw new GoCommerceError('Your bag is empty.', 400)\n\t\tconst extras = cartExtras(id)\n\t\tconst ship = extras.shippingAddress\n\t\tif (!ship) throw new GoCommerceError('Add a delivery address first.', 400)\n\n\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\tconst email = cart.email || (ship.email ? String(ship.email) : '')\n\t\tif (!email) throw new GoCommerceError('Add an email address so we can send your receipt.', 400)\n\t\tconst address = toEngineAddress(ship)\n\t\tconst body = {\n\t\t\tcart_id: id,\n\t\t\temail,\n\t\t\t...(extras.phone || address.phone ? { phone: String(extras.phone || address.phone) } : {}),\n\t\t\t...(address.name ? { name: address.name } : {}),\n\t\t\taddress,\n\t\t\t...(extras.shippingRateId ? { shipping_rate_id: Number(extras.shippingRateId) } : {}),\n\t\t\t...extra,\n\t\t}\n\t\tconst serialised = JSON.stringify(body)\n\t\tconst retry = extras.attempt?.body === `${code}:${serialised}`\n\t\tconst key = retry ? extras.attempt!.key : newKey()\n\t\t// Where Meta's pixel ran (metaBrowser) is not part of what makes a retry the same\n\t\t// request: the shopper can accept the cookie banner, or Meta set _fbc, between a failed\n\t\t// attempt and the next. A retry sends the first attempt's, since the engine refuses a key\n\t\t// replayed with a different body.\n\t\tconst meta = retry ? extras.attempt?.meta : metaBrowser()\n\t\t// Where the shopper came from (D168), held the same way: a retry sends what the first attempt did.\n\t\tconst attribution = retry ? extras.attempt?.attribution : landingAttribution()\n\t\tsaveCartExtras(id, {\n\t\t\tattempt: { key, body: `${code}:${serialised}`, ...(meta ? { meta } : {}), ...(attribution ? { attribution } : {}) },\n\t\t})\n\t\tconst metadata = {\n\t\t\t...extra.metadata,\n\t\t\t...(meta ? { meta_capi: meta } : {}),\n\t\t\t...(attribution ? { attribution } : {}),\n\t\t}\n\n\t\tconst result = await this.data<CheckoutResult>(`/api/checkout/${encodeURIComponent(code)}`, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: Object.keys(metadata).length ? { ...body, metadata } : body,\n\t\t\theaders: { 'Idempotency-Key': key },\n\t\t})\n\n\t\t// The access token is returned once; a replayed response leaves it out,\n\t\t// so a replay must not overwrite the one already kept.\n\t\tif (result.order.access_token) {\n\t\t\trememberOrder({\n\t\t\t\tnumber: result.order.number,\n\t\t\t\ttoken: result.order.access_token,\n\t\t\t\tcartId: id,\n\t\t\t\treference: result.payment.client_data?.razorpay_order_id ?? result.payment.reference,\n\t\t\t})\n\t\t\t// A signed-in shopper's order joins their account. The engine never\n\t\t\t// links an order by email, so this call is the only way it appears\n\t\t\t// under \"My orders\".\n\t\t\tif (sessionToken()) {\n\t\t\t\tawait this.engine('/x/identity/me/orders', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: { number: result.order.number, token: result.order.access_token },\n\t\t\t\t\tauth: true,\n\t\t\t\t}).catch(() => undefined)\n\t\t\t}\n\t\t}\n\t\tsaveCartExtras(id, { attempt: null })\n\t\treturn result\n\t}\n}\n\n/** The engine's gateways that take payment on their own hosted page. */\nexport const REDIRECT_GATEWAYS = new Set(['adyen', 'paddle', 'lemonsqueezy', 'creem', 'hyperswitch', 'revenuecat'])\n\nconst unsupported = (method: string, why: string) => new NotSupportedError('CheckoutService', method, why)\n\nfunction newKey(): string {\n\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n\tif (c?.randomUUID) return c.randomUUID()\n\treturn `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`\n}\n\nexport const checkoutService = new CheckoutService()\n","import { toMajor } from '../money'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { REDIRECT_GATEWAYS } from './checkout-service'\n\n/**\n * The engine's payment methods this storefront can actually drive.\n *\n * The storefront dispatches on an upper-cased code from a fixed list, so a\n * method is offered only where one of its flows can complete it: cash on\n * delivery, Razorpay's modal, and — through the storefront's redirect flow,\n * which it reaches by the code `PAYPAL` — the first of the engine's hosted-page\n * gateways. That one keeps its own name and gets a neutral card icon, never a\n * PayPal mark. The flow carries no gateway code, so a second hosted-page\n * gateway cannot be told apart from the first and is not offered; nor is\n * Stripe, whose engine gateway is a Payment Element this storefront does not\n * mount. Each method left off is reported once, and every one stays reachable\n * through `checkoutService.checkout(code)` for a storefront that drives its own.\n */\nconst DRIVABLE: Record<string, { code: string; img?: string }> = {\n\tcod: { code: 'COD', img: '/payment/cod.svg' },\n\trazorpay: { code: 'RAZORPAY' },\n}\n\nconst reported = new Set<string>()\n\nexport class PaymentMethodService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst options = await this.facts.checkoutOptions()\n\t\tconst methods = options.methods ?? []\n\t\tconst redirect = methods.find((m) => REDIRECT_GATEWAYS.has(m.code))?.code\n\t\tconst drive = (code: string) =>\n\t\t\tDRIVABLE[code] ?? (code === redirect ? { code: 'PAYPAL', img: '/payment/card.svg' } : undefined)\n\t\tconst data = methods\n\t\t\t.filter((m) => {\n\t\t\t\tif (drive(m.code)) return true\n\t\t\t\tif (!reported.has(m.code)) {\n\t\t\t\t\treported.add(m.code)\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[gocommerce] payment method \"${m.code}\" is switched on but this storefront cannot drive its flow, so it is not offered here; checkoutService.checkout('${m.code}') still reaches it.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t})\n\t\t\t.map((m, i) => ({\n\t\t\t\tid: m.code,\n\t\t\t\tcode: drive(m.code)!.code,\n\t\t\t\tengineCode: m.code,\n\t\t\t\tname: m.name,\n\t\t\t\ttitle: m.name,\n\t\t\t\tdescription: '',\n\t\t\t\timg: drive(m.code)!.img ?? null,\n\t\t\t\tfee: toMajor(m.fee),\n\t\t\t\trank: i,\n\t\t\t\tactive: true,\n\t\t\t\tisActive: true,\n\t\t\t}))\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\nexport const paymentMethodService = new PaymentMethodService()\n","import { emptyPage } from './base.service'\nimport { BaseService } from './base.service'\nimport { CartService } from './cart-service'\n\n/**\n * Discount codes are typed, not browsed, except the ones the shop chose to\n * show (D133): the engine lists a code only when the shop ticked \"Show in the\n * basket's offers\", judged against the stored bag. Every other code stays\n * known only to whoever was given it, and still works through\n * `cartService.applyCoupon`.\n *\n * The drawer's shape: `amount` is the percentage or the amount,\n * `minAmount` the bag it needs, and `description` says what is\n * still missing.\n */\nexport class CouponService extends BaseService {\n\tasync listCoupons(_args: Record<string, unknown> = {}) {\n\t\tconst offers = await new CartService(this._fetch).getOffers().catch(() => [])\n\t\tif (!offers.length) return emptyPage()\n\t\tconst data = offers.map((o) => ({\n\t\t\tid: o.code,\n\t\t\tcode: o.code,\n\t\t\ttitle: o.title,\n\t\t\tisPercent: o.isPercent,\n\t\t\tamount: o.value,\n\t\t\tminAmount: o.minAmount,\n\t\t\tdescription: o.applies\n\t\t\t\t? o.title\n\t\t\t\t: o.remaining !== null\n\t\t\t\t\t? `${o.title}. Add ${o.remaining} more to use this.`\n\t\t\t\t\t: o.reason || o.title,\n\t\t\tapplies: o.applies,\n\t\t\tremaining: o.remaining,\n\t\t}))\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\nexport const couponService = new CouponService()\n","import type { Order, Product } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toOrder } from '../map'\nimport { toMajor } from '../money'\nimport { inBrowser, placedOrder, placedOrderForCart, rememberOrder, sessionToken } from '../browser'\nimport { BaseService, emptyPage, mediaUrl, toPage } from './base.service'\n\n/**\n * Orders, read back two ways.\n *\n * A guest's order is read with the access token checkout returned, which this\n * connector kept in the browser that placed it (`GET /api/orders/{n}?token=`).\n * A signed-in shopper's orders are the ones joined to their account\n * (ext/identity's `/me/orders`). There is no third way: an order list that\n * answered without either would be every order in the shop.\n */\nexport class OrderService extends BaseService {\n\t/**\n\t * The order-success page's lookup, by the number and cart in its URL.\n\t *\n\t * It runs on the server, where neither the token nor the session exists —\n\t * they live in the shopper's browser — so there it answers nothing and the\n\t * page says the details are not available yet. In the browser it answers\n\t * the order. Inventing a server-side credential from the cart token in the\n\t * URL would make that URL, which lands in history and referrers, a key to\n\t * the shopper's address.\n\t */\n\tasync listOrdersByParent({ orderNo, cartId }: { orderNo?: string; cartId?: string } = {}) {\n\t\tconst number = clean(orderNo) ?? (clean(cartId) ? placedOrderForCart(clean(cartId) as string)?.number : undefined)\n\t\tif (!number) return { data: [] }\n\t\ttry {\n\t\t\treturn { data: [await this.getOrder(number)] }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 404 || err.status === 401)) return { data: [] }\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/** The signed-in shopper's orders, newest claim first. */\n\tasync list({ page = 1, limit = 20 }: { page?: number; limit?: number; q?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<Order[] | null>('/x/identity/me/orders', { query: { page, limit }, auth: true })\n\t\treturn toPage(env, toOrder)\n\t}\n\n\t/** One order by number: the account's when signed in, otherwise one this browser placed. */\n\tasync getOrder(number: string) {\n\t\tconst kept = placedOrder(number)\n\t\tif (kept) {\n\t\t\treturn toOrder(\n\t\t\t\tawait this.data<Order>(`/api/orders/${encodeURIComponent(number)}`, { query: { token: kept.token } }),\n\t\t\t)\n\t\t}\n\t\tif (sessionToken()) {\n\t\t\treturn toOrder(await this.data<Order>(`/x/identity/me/orders/${encodeURIComponent(number)}`, { auth: true }))\n\t\t}\n\t\tthrow new GoCommerceError(\n\t\t\tinBrowser() ? 'Sign in to see this order, or open it from the browser that placed it.' : 'order not found',\n\t\t\t404,\n\t\t\t'not_found',\n\t\t)\n\t}\n\n\t/** Everything the signed-in shopper has bought, once each, most recent first. */\n\tasync buyAgain() {\n\t\tconst orders =\n\t\t\t(await this.data<Order[] | null>('/x/identity/me/orders', { query: { limit: 20 }, auth: true })) ?? []\n\t\tconst seen = new Set<number>()\n\t\tconst lines: {\n\t\t\tproductId: number\n\t\t\tvariantId: number\n\t\t\ttitle: string\n\t\t\timg: string | null\n\t\t\tprice: number\n\t\t\tqty: number\n\t\t\tdesignId: string | null\n\t\t}[] = []\n\t\tfor (const o of orders) {\n\t\t\tfor (const l of o.line_items ?? []) {\n\t\t\t\tif (!l.product_id || !l.variant_id || seen.has(l.variant_id)) continue\n\t\t\t\tseen.add(l.variant_id)\n\t\t\t\tlines.push({\n\t\t\t\t\tproductId: l.product_id,\n\t\t\t\t\tvariantId: l.variant_id,\n\t\t\t\t\ttitle: l.title,\n\t\t\t\t\timg: mediaUrl(l.image_url),\n\t\t\t\t\tprice: toMajor(l.unit_price),\n\t\t\t\t\tqty: l.quantity,\n\t\t\t\t\tdesignId: l.metadata?.design?.id ?? null,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\t// A product taken off sale is no longer something to buy again.\n\t\tconst live = await Promise.all(\n\t\t\tlines.map((l) => this.data<Product>(`/api/products/${l.productId}`).catch(() => null)),\n\t\t)\n\t\treturn lines.flatMap((l, i) => {\n\t\t\tconst p = live[i]\n\t\t\tif (!p) return []\n\t\t\tconst designable = typeof p.designable === 'boolean' ? p.designable : undefined\n\t\t\treturn [{ ...l, productId: String(l.productId), variantId: String(l.variantId), slug: p.slug, designable }]\n\t\t})\n\t}\n\n\t/** The \"someone just bought\" popup would publish other shoppers' purchases; the engine offers none. */\n\tasync listPublic(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\n\t/**\n\t * Opens an order with its number and the email or phone on it, no code. The\n\t * engine answers one 404 for an unknown number and a wrong contact. The\n\t * token it answers is kept like an order placed in this browser, so the\n\t * order page and `getOrder` read it again.\n\t */\n\tasync openOrder({ orderNo, contact }: { orderNo: string; contact: string }) {\n\t\tconst res = await this.data<{ order: Order; access_token: string }>(\n\t\t\t`/api/orders/${encodeURIComponent(orderNo.trim())}/open`,\n\t\t\t{ method: 'POST', body: { contact: contact.trim() } },\n\t\t)\n\t\trememberOrder({ number: res.order.number, token: res.access_token, cartId: '' })\n\t\treturn { data: [toOrder(res.order)] }\n\t}\n\n\t/**\n\t * Opens an order from the link in its emails, which carries the order's key\n\t * (`/order-tracking?order=…&key=…`). The key is kept like an order placed in\n\t * this browser, so the page can drop it from the address bar.\n\t */\n\tasync openOrderWithKey({ orderNo, key }: { orderNo: string; key: string }) {\n\t\tconst number = orderNo.trim()\n\t\tconst order = await this.data<Order>(`/api/orders/${encodeURIComponent(number)}`, { query: { token: key.trim() } })\n\t\trememberOrder({ number: order.number, token: key.trim(), cartId: '' })\n\t\treturn { data: [toOrder(order)] }\n\t}\n\n\t/**\n\t * Sends a 4-digit code to the email or phone on the order, when `contact`\n\t * is that email or phone. The engine answers the same either way, so this\n\t * resolves whether or not anything was sent.\n\t */\n\tasync requestOrderCode({ orderNo, contact }: { orderNo: string; contact: string }) {\n\t\tconst res = await this.data<{ expires_in_minutes: number }>(\n\t\t\t`/api/orders/${encodeURIComponent(orderNo.trim())}/code`,\n\t\t\t{ method: 'POST', body: { contact: contact.trim() } },\n\t\t)\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/**\n\t * Opens an order with the code `requestOrderCode` sent. The token it answers\n\t * is kept like an order placed in this browser, so the order page and\n\t * `getOrder` read it again without another code.\n\t */\n\tasync getOrderByEmailAndOTP({ orderNo, otp }: { orderNo: string; otp: string; email?: string }) {\n\t\tconst number = orderNo.trim()\n\t\tconst res = await this.data<{ order: Order; access_token: string }>(\n\t\t\t`/api/orders/${encodeURIComponent(number)}/code/verify`,\n\t\t\t{ method: 'POST', body: { code: String(otp).trim() } },\n\t\t)\n\t\trememberOrder({ number: res.order.number, token: res.access_token, cartId: '' })\n\t\treturn { data: [toOrder(res.order)] }\n\t}\n}\n\nconst clean = (v?: string | null) => (v && v !== 'undefined' && v !== 'null' ? v : undefined)\n\nexport const orderService = new OrderService()\n","import type { AuthResponse, Customer, Order } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toOrder, toUser } from '../map'\nimport { endSession, placedOrder, startSession, storedCartId, updateMe } from '../browser'\nimport { StoreFacts } from './facts'\nimport { BaseService } from './base.service'\n\n/**\n * Shopper accounts, through ext/identity.\n *\n * Guest checkout stays the engine's default (D22): an account is a place to\n * keep addresses and see past orders, never a requirement to buy. A store\n * built without `-identity` answers every call here with a 404, which arrives\n * as \"Accounts are not available on this store\" rather than as a route error.\n */\nexport class UserService extends BaseService {\n\t/**\n\t * Email and password. The answer is the user object the storefront keeps in its `me` cookie.\n\t * With `phone` and `phoneToken` from `verifyOtp({ askIfNew: true })`, the phone is added to\n\t * the account as it signs in (D123).\n\t */\n\tasync login({\n\t\temail,\n\t\tpassword,\n\t\tphone,\n\t\tphoneToken,\n\t}: {\n\t\temail: string\n\t\tpassword: string\n\t\tphone?: string\n\t\tphoneToken?: string\n\t\tcartId?: string | null\n\t}) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/login', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\temail: String(email ?? '').trim(),\n\t\t\t\tpassword: String(password ?? ''),\n\t\t\t\t...(phoneToken ? { phone: String(phone ?? '').trim(), phone_token: phoneToken } : {}),\n\t\t\t},\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\tasync signup({\n\t\temail,\n\t\tpassword,\n\t\tfirstName,\n\t\tlastName,\n\t\tphone,\n\t}: {\n\t\temail: string\n\t\tpassword: string\n\t\tfirstName?: string\n\t\tlastName?: string\n\t\tphone?: string\n\t\tcartId?: string | null\n\t\torigin?: string\n\t}) {\n\t\tconst name = [firstName, lastName].filter(Boolean).join(' ').trim()\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/register', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\temail: String(email ?? '').trim(),\n\t\t\t\tpassword: String(password ?? ''),\n\t\t\t\t...(name ? { name } : {}),\n\t\t\t\t...(phone ? { phone: String(phone) } : {}),\n\t\t\t},\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\t/** Signs out here and on the engine. The storefront assigns the answer to its user: `null`. */\n\tasync logout() {\n\t\tawait this.engine('/x/identity/logout', { method: 'POST', auth: true }).catch(() => undefined)\n\t\tendSession()\n\t\treturn null\n\t}\n\n\tasync getMe() {\n\t\treturn toUser(await this.account<Customer>('/x/identity/me', { auth: true }))\n\t}\n\n\tasync updateProfile(user: { firstName?: string; lastName?: string; name?: string; email?: string; phone?: string }) {\n\t\tconst name =\n\t\t\tuser.name ??\n\t\t\t[user.firstName, user.lastName]\n\t\t\t\t.filter((v) => v !== undefined)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim()\n\t\tconst c = await this.account<Customer>('/x/identity/me', {\n\t\t\tmethod: 'PATCH',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\t...(name !== undefined ? { name } : {}),\n\t\t\t\t...(user.email ? { email: String(user.email).trim() } : {}),\n\t\t\t\t...(user.phone !== undefined && user.phone !== null ? { phone: String(user.phone) } : {}),\n\t\t\t},\n\t\t})\n\t\tupdateMe(c)\n\t\treturn toUser(c)\n\t}\n\n\t/**\n\t * A password change ends every session the account had, this one included,\n\t * and the engine answers a fresh one — which is kept, so the shopper stays\n\t * signed in here and nowhere else.\n\t */\n\tasync changePassword({ old, oldPassword, password }: { old?: string; oldPassword?: string; password: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/me/password', {\n\t\t\tmethod: 'PUT',\n\t\t\tauth: true,\n\t\t\tbody: { current_password: String(old ?? oldPassword ?? ''), password: String(password ?? '') },\n\t\t})\n\t\tstartSession(auth)\n\t\treturn toUser(auth.record)\n\t}\n\n\t/**\n\t * Mails the signed-in shopper a link to confirm their address. The engine\n\t * sends none at signup, and a confirmed address is what customer-group\n\t * prices are keyed on. 409 once confirmed; 429 within a minute of the last.\n\t */\n\tasync requestEmailVerification() {\n\t\treturn this.account<{ accepted: boolean }>('/x/identity/me/email-verification', { method: 'POST', auth: true })\n\t}\n\n\t/** Extends the session another thirty days. The token stays the same. */\n\tasync refreshSession() {\n\t\treturn startSession(await this.account<AuthResponse>('/x/identity/refresh', { method: 'POST', auth: true }))\n\t}\n\n\t/**\n\t * Files a guest order under the signed-in account, so it appears in their\n\t * order history. The order's access token is the proof of ownership: pass\n\t * it, or leave it out for an order placed from this browser, whose token was\n\t * kept at checkout.\n\t *\n\t * Never done automatically at sign-in. On a shared computer that would file\n\t * one person's orders — address and all — under whoever signed in next.\n\t */\n\tasync claimOrder({ number, token }: { number: string; token?: string }) {\n\t\tconst proof = token ?? placedOrder(number)?.token\n\t\tif (!proof) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'This order was not placed from this browser; enter the code from its confirmation.',\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\t\tconst order = await this.account<Order>('/x/identity/me/orders', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { number: String(number), token: proof },\n\t\t})\n\t\treturn toOrder(order)\n\t}\n\n\tasync deleteUser(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'deleteUser', 'an account is closed by the store, on request')\n\t}\n\n\tasync checkEmail(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'checkEmail', 'the engine does not say which addresses have accounts')\n\t}\n\n\tasync joinAsVendor(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'joinAsVendor', 'sellers are invited by the store')\n\t}\n\n\tprotected async signedIn(auth: AuthResponse) {\n\t\tconst me = startSession(auth)\n\t\tconst cartId = storedCartId()\n\t\tif (cartId) await this.claimCartForAccount(cartId)\n\t\treturn me\n\t}\n\n\t/** An identity call, with a 404 from a build without the module said in words. */\n\tprotected async account<T>(path: string, req: Parameters<BaseService['engine']>[1] = {}): Promise<T> {\n\t\ttry {\n\t\t\treturn await this.data<T>(path, req)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404 && /no route/i.test(err.message)) {\n\t\t\t\tthrow new GoCommerceError('Accounts are not available on this store.', 404, 'not_found')\n\t\t\t}\n\t\t\tif (err instanceof GoCommerceError && err.status === 401 && req.auth) endSession()\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\n/**\n * Password resets, email confirmation, and phone sign-in. A store signs its\n * customers in one way (D116), read from `loginMethod`; the engine refuses\n * the other.\n */\nexport class AuthService extends UserService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/**\n\t * How this store signs customers in: `email_password` or `phone_otp`.\n\t * A store whose accounts module says nothing signs in by email.\n\t */\n\tasync loginMethod(): Promise<'email_password' | 'phone_otp' | 'email_or_phone'> {\n\t\ttry {\n\t\t\tconst method = (await this.facts.plugins()).get('identity')?.settings?.login_method\n\t\t\treturn method === 'phone_otp' || method === 'email_or_phone' ? method : 'email_password'\n\t\t} catch {\n\t\t\treturn 'email_password'\n\t\t}\n\t}\n\n\tasync forgotPassword({ email }: { email: string; referrer?: string }) {\n\t\treturn this.account<{ accepted: boolean }>('/x/identity/password-reset', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { email: String(email ?? '').trim() },\n\t\t})\n\t}\n\n\t/** The token arrives in the link the engine emailed (`GOCOMMERCE_IDENTITY_RESET_URL`). */\n\tasync resetPassword({ token, password }: { userId?: string; token: string; password: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/password-reset/confirm', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { token: String(token ?? ''), password: String(password ?? '') },\n\t\t})\n\t\treturn startSession(auth)\n\t}\n\n\t/** Answers `{ errorCode, message }` on failure rather than throwing: that is how the page reads it. */\n\tasync verifyEmail(_email: string | undefined, token: string) {\n\t\ttry {\n\t\t\tconst c = await this.account<Customer>('/x/identity/email-verification/confirm', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: { token: String(token ?? '') },\n\t\t\t})\n\t\t\treturn { ...toUser(c), message: 'Your email address is confirmed.' }\n\t\t} catch (err) {\n\t\t\treturn { errorCode: (err as GoCommerceError).code ?? 'invalid_token', message: (err as Error).message }\n\t\t}\n\t}\n\n\t/**\n\t * Texts a 4-digit sign-in code to `phone`, which needs its country code. `domain`, the page's\n\t * host and in the browser read from it, lets the engine end the text \"@domain #code\" when the\n\t * host is the store's own, which Chrome on Android reads to fill the code in (D124).\n\t */\n\tasync getOtp({ phone, domain }: { phone: string; domain?: string }) {\n\t\tconst site = domain ?? (typeof window !== 'undefined' ? window.location?.hostname : undefined)\n\t\tconst res = await this.account<{ expires_in_minutes: number }>('/x/identity/otp', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { phone: String(phone ?? '').trim(), ...(site ? { domain: site } : {}) },\n\t\t})\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/**\n\t * Signs in the account on `phone` with the code it was sent, opening one the first time.\n\t * With `askIfNew`, on a store that signs in either way, a phone with no account opens none:\n\t * the answer is `{ newPhone: true, phoneToken }`, and the storefront asks \"Already have an\n\t * account?\" — `login` with the token adds the phone to it, `openPhoneAccount` opens a new one (D123).\n\t */\n\tasync verifyOtp({ phone, otp, askIfNew }: { phone: string; otp: string; askIfNew?: boolean }) {\n\t\tconst res = await this.account<AuthResponse | { new_phone: true; phone_token: string }>('/x/identity/otp/verify', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tphone: String(phone ?? '').trim(),\n\t\t\t\tcode: String(otp ?? '').trim(),\n\t\t\t\t...(askIfNew ? { ask_if_new: true } : {}),\n\t\t\t},\n\t\t})\n\t\tif ('new_phone' in res && res.new_phone) return { newPhone: true as const, phoneToken: res.phone_token }\n\t\treturn this.signedIn(res as AuthResponse)\n\t}\n\n\t/** Opens a new account on a phone `verifyOtp({ askIfNew: true })` proved, and signs it in (D123). */\n\tasync openPhoneAccount({ phone, phoneToken }: { phone: string; phoneToken: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/otp/new-account', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { phone: String(phone ?? '').trim(), phone_token: phoneToken },\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\tasync joinAsAdmin(): Promise<never> {\n\t\tthrow new NotSupportedError('AuthService', 'joinAsAdmin', 'operators are invited from the admin panel')\n\t}\n}\n\n/** The `/my/profile` form: the same account, read and saved. */\nexport class ProfileService extends UserService {\n\tasync getOne() {\n\t\treturn this.getMe()\n\t}\n\n\tasync save(profile: { firstName?: string; lastName?: string; email?: string; phone?: string }) {\n\t\treturn this.updateProfile(profile)\n\t}\n\n\t/** Texts a code to a phone the signed-in shopper wants to add (D118). */\n\tasync requestPhoneLink({ phone }: { phone: string }) {\n\t\tconst res = await this.account<{ expires_in_minutes: number }>('/x/identity/me/phone', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { phone: String(phone ?? '').trim() },\n\t\t})\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/** Adds the phone with its code; from then on it signs in to this account too. */\n\tasync verifyPhoneLink({ phone, otp }: { phone: string; otp: string }) {\n\t\tconst c = await this.account<Customer>('/x/identity/me/phone/verify', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { phone: String(phone ?? '').trim(), code: String(otp ?? '').trim() },\n\t\t})\n\t\tupdateMe(c)\n\t\treturn toUser(c)\n\t}\n}\n\nexport const userService = new UserService()\nexport const authService = new AuthService()\nexport const profileService = new ProfileService()\n","import type { IdentityAddress, Postcode } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { fromIdentityAddress, toIdentityAddress } from '../map'\nimport { currentMe, type StorefrontAddress } from '../browser'\nimport { BaseService } from './base.service'\n\ntype AddressArg = StorefrontAddress & { isPrimary?: boolean; label?: string }\n\n/** The signed-in shopper's address book (ext/identity). A guest's address lives on the cart. */\nexport class AddressService extends BaseService {\n\tasync list({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t}: { page?: number; limit?: number; user?: string; q?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<IdentityAddress[] | null>('/x/identity/me/addresses', {\n\t\t\tquery: { page, limit },\n\t\t\tauth: true,\n\t\t})\n\t\tconst email = currentMe()?.email\n\t\tconst rows = env.data ?? []\n\t\treturn {\n\t\t\tdata: rows.map((a) => fromIdentityAddress(a, email)),\n\t\t\tcount: env.meta?.total ?? rows.length,\n\t\t\tpageSize: env.meta?.limit ?? limit,\n\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\tpage: env.meta?.page ?? page,\n\t\t}\n\t}\n\n\tasync fetchAddress(id: string) {\n\t\treturn fromIdentityAddress(\n\t\t\tawait this.data<IdentityAddress>(`/x/identity/me/addresses/${enc(id)}`, { auth: true }),\n\t\t\tcurrentMe()?.email,\n\t\t)\n\t}\n\n\t/** New when it has no id (or the form's `'new'`), an edit when it has one — the storefront saves both here. */\n\tasync saveAddress(address: AddressArg) {\n\t\tconst id = address?.id && address.id !== 'new' ? String(address.id) : null\n\t\tif (id) return this.editAddress(id, address)\n\t\tconst a = await this.data<IdentityAddress>('/x/identity/me/addresses', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: toIdentityAddress(address),\n\t\t})\n\t\treturn fromIdentityAddress(a, currentMe()?.email)\n\t}\n\n\tasync editAddress(id: string, address: AddressArg) {\n\t\tconst a = await this.data<IdentityAddress>(`/x/identity/me/addresses/${enc(id)}`, {\n\t\t\tmethod: 'PATCH',\n\t\t\tauth: true,\n\t\t\tbody: toIdentityAddress(address),\n\t\t})\n\t\treturn fromIdentityAddress(a, currentMe()?.email)\n\t}\n\n\t/**\n\t * The city and state for a postcode (D134), for the address form to fill\n\t * in. India's six-digit PIN codes only, from the directory the engine was\n\t * given; null for anything it cannot answer, so the form simply leaves the\n\t * fields to the shopper.\n\t */\n\tasync lookupPostcode({ country = 'IN', postcode }: { country?: string; postcode: string }) {\n\t\tconst code = String(postcode ?? '').trim()\n\t\tconst cc = String(country ?? '').trim().toUpperCase()\n\t\tif (cc !== 'IN' || !/^[1-9][0-9]{5}$/.test(code)) return null\n\t\ttry {\n\t\t\tconst p = await this.data<Postcode>(`/api/postcodes/${cc}/${code}`)\n\t\t\treturn { country: p.country, postcode: p.postcode, city: p.city, state: p.state, stateCode: p.state_code }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 404 || err.status === 400)) return null\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tasync deleteAddress(id: string) {\n\t\tawait this.engine(`/x/identity/me/addresses/${enc(id)}`, { method: 'DELETE', auth: true })\n\t\treturn { id: String(id), deleted: true }\n\t}\n}\n\nconst enc = (id: string) => encodeURIComponent(String(id))\n\nexport const addressService = new AddressService()\n","import type { Product, Wishlist } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { toProduct } from '../map'\nimport { currentMe, forgetWishlistToken, rememberWishlistToken, wishlistToken } from '../browser'\nimport { BaseService } from './base.service'\n\n/**\n * Saved products, through ext/wishlist.\n *\n * The module keys a list by a token of its own rather than by an account, so\n * a guest can save things too; this connector keeps that token in the browser.\n * The signed-in shopper's email is attached so the store can tell them when a\n * saved product comes back in stock.\n */\nexport class WishlistService extends BaseService {\n\tasync fetchWishlist(_args: Record<string, unknown> = {}) {\n\t\tconst list = await this.current()\n\t\tif (!list) return { data: [], count: 0 }\n\t\tconst items = (list.items ?? []).filter((i) => !i.deleted)\n\t\tconst products = await Promise.all(\n\t\t\titems.map((i) => this.data<Product>(`/api/products/${i.product_id}`).catch(() => null)),\n\t\t)\n\t\tconst data = items.flatMap((item, n) => {\n\t\t\tconst p = products[n]\n\t\t\tif (!p) return []\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tid: String(item.id),\n\t\t\t\t\tproductId: String(item.product_id),\n\t\t\t\t\tvariantId: item.variant_id ? String(item.variant_id) : null,\n\t\t\t\t\tproduct: toProduct(p),\n\t\t\t\t\tvariant: { id: item.variant_id ? String(item.variant_id) : null },\n\t\t\t\t\tcreatedAt: item.created_at,\n\t\t\t\t},\n\t\t\t]\n\t\t})\n\t\treturn { data, count: data.length }\n\t}\n\n\t/** Saved → removed, removed → saved. `{ active }` is the state after the click. */\n\tasync toggleWishlist({ productId, variantId }: { productId: string; variantId?: string | null }) {\n\t\tconst list = (await this.current()) ?? (await this.create())\n\t\tconst item = (list.items ?? []).find((i) => String(i.product_id) === String(productId))\n\t\tif (item) {\n\t\t\tawait this.data<Wishlist>(`/x/wishlist/${enc(list.token!)}/items/${item.id}`, { method: 'DELETE' })\n\t\t\treturn { active: false, id: String(item.id) }\n\t\t}\n\t\tconst next = await this.data<Wishlist>(`/x/wishlist/${enc(list.token!)}/items`, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { product_id: Number(productId), ...(variantId ? { variant_id: Number(variantId) } : {}) },\n\t\t})\n\t\tconst added = (next.items ?? []).find((i) => String(i.product_id) === String(productId))\n\t\treturn { active: true, id: added ? String(added.id) : null }\n\t}\n\n\tasync checkWishlist({ productId }: { productId: string; variantId?: string | null }) {\n\t\tconst list = await this.current()\n\t\treturn !!list && (list.items ?? []).some((i) => String(i.product_id) === String(productId))\n\t}\n\n\tasync checkWishlistInBulk(pairs: { productId: string; variantId?: string | null }[]) {\n\t\tconst list = await this.current()\n\t\tconst saved = new Set((list?.items ?? []).map((i) => String(i.product_id)))\n\t\treturn (pairs ?? []).map((p) => ({ ...p, exists: saved.has(String(p.productId)) }))\n\t}\n\n\t/**\n\t * The address the store may write to when a saved product is back in stock\n\t * or on sale; `''` takes it off. A list that does not exist yet is made.\n\t */\n\tasync setEmail(email: string) {\n\t\tconst list = (await this.current()) ?? (await this.create())\n\t\tawait this.data<Wishlist>(`/x/wishlist/${enc(list.token)}`, {\n\t\t\tmethod: 'PATCH',\n\t\t\tbody: { email: String(email ?? '').trim() },\n\t\t})\n\t\treturn { email: String(email ?? '').trim() || null }\n\t}\n\n\tprivate async current(): Promise<(Wishlist & { token: string }) | null> {\n\t\tconst token = wishlistToken()\n\t\tif (!token) return null\n\t\ttry {\n\t\t\treturn { ...(await this.data<Wishlist>(`/x/wishlist/${enc(token)}`)), token }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404 && !/no wishlist|no route/i.test(err.message)) {\n\t\t\t\tforgetWishlistToken()\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tprivate async create(): Promise<Wishlist & { token: string }> {\n\t\tconst email = currentMe()?.email\n\t\tconst list = await this.data<Wishlist>('/x/wishlist', { method: 'POST', ...(email ? { body: { email } } : {}) })\n\t\tif (!list.token) throw new GoCommerceError('The store did not return a wishlist token.', 500)\n\t\trememberWishlistToken(list.token)\n\t\treturn { ...list, token: list.token }\n\t}\n}\n\nconst enc = (s: string) => encodeURIComponent(s)\n\nexport const wishlistService = new WishlistService()\n","import type { ReviewPage } from '../engine'\nimport { toRating } from '../map'\nimport { BaseService } from './base.service'\n\n/**\n * Product reviews (ext/reviews). Approved reviews only, newest first. The\n * product page gets them with the product; this is the paged form, and\n * `productService.addReview` writes one.\n */\nexport class ReviewService extends BaseService {\n\tasync fetchReviews({\n\t\tproductId,\n\t\tcurrentPage = 1,\n\t\tpage,\n\t\tlimit = 20,\n\t}: { productId?: string; currentPage?: number; page?: number; limit?: number; search?: string; sort?: string } = {}) {\n\t\t// A vendor's \"all my reviews\" page has no product to ask about.\n\t\tif (!productId) return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 }\n\t\tconst p = Math.max(1, Number(page ?? currentPage) || 1)\n\t\tconst res = await this.data<ReviewPage>('/x/reviews', { query: { product_id: productId, page: p, limit } })\n\t\tconst total = res.meta?.total ?? res.summary?.count ?? 0\n\t\treturn {\n\t\t\tdata: (res.reviews ?? []).map(toRating),\n\t\t\tcount: total,\n\t\t\tpageSize: limit,\n\t\t\tnoOfPage: Math.max(1, Math.ceil(total / limit)),\n\t\t\tpage: p,\n\t\t\tsummary: res.summary ?? null,\n\t\t}\n\t}\n\n\tasync allReviews(args: { productId?: string; page?: number } = {}) {\n\t\treturn this.fetchReviews(args)\n\t}\n}\n\nexport const reviewService = new ReviewService()\n","import { placedOrder } from '../browser'\nimport type { GooglePlace, GoogleSurvey } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\n\nconst PLUGIN = 'google-reviews'\n\n/** A Google review with what Google's attribution policy asks a storefront to show. */\nexport type GoogleReview = {\n\tauthor: string\n\t/** The author's Google profile and photo; https or empty. */\n\tauthorUrl: string\n\tauthorPhoto: string\n\trating: number\n\t/** The reviewer's own words, in their language. Empty for a rating with no words. */\n\ttext: string\n\tlanguage: string\n\t/** Google's own words for when, such as \"a month ago\". */\n\twhen: string\n\t/** YYYY-MM, when Google has one. */\n\tvisited: string\n\t/** The review on Google Maps, and where to report it to Google. */\n\turl: string\n\treportUrl: string\n}\n\nexport type GoogleReviews = {\n\t/** Google's own rating and count, never worked out from `reviews`. */\n\trating: number\n\tcount: number\n\t/** Every review, on Google Maps: `reviews` are at most five of them. */\n\tmapsUrl: string\n\treviews: GoogleReview[]\n}\n\n/**\n * The store's Google reviews and Google Customer Reviews (ext/google-reviews).\n *\n * Both calls answer null when there is nothing to show — the plugin or its\n * switch off, Google refusing, the day's lookups spent — because each is an\n * extra on a page that must render without it.\n */\nexport class GoogleReviewService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/**\n\t * Google's rating and its most relevant reviews, read live. Google's terms\n\t * forbid keeping them, so nothing here caches them either, and every call\n\t * is one the store pays Google for: call it when the section is in view.\n\t */\n\tasync place(): Promise<GoogleReviews | null> {\n\t\tif (!(await this.switchOn('show_place'))) return null\n\t\tconst p = await this.orNull(() => this.data<GooglePlace>('/x/google-reviews/place'))\n\t\tif (!p?.user_rating_count) return null\n\t\treturn {\n\t\t\trating: p.rating,\n\t\t\tcount: p.user_rating_count,\n\t\t\tmapsUrl: p.google_maps_uri ?? '',\n\t\t\treviews: (p.reviews ?? []).map((r) => ({\n\t\t\t\tauthor: r.author?.name ?? '',\n\t\t\t\tauthorUrl: r.author?.uri ?? '',\n\t\t\t\tauthorPhoto: r.author?.photo_uri ?? '',\n\t\t\t\trating: r.rating,\n\t\t\t\ttext: r.text ?? '',\n\t\t\t\tlanguage: r.language ?? '',\n\t\t\t\twhen: r.relative_time ?? '',\n\t\t\t\tvisited: r.visit_date ?? '',\n\t\t\t\turl: r.google_maps_uri ?? '',\n\t\t\t\treportUrl: r.flag_uri ?? '',\n\t\t\t})),\n\t\t}\n\t}\n\n\t/**\n\t * What Google Customer Reviews' opt-in is rendered with, for an order placed\n\t * in this browser: its access token is kept here, and nowhere else can ask.\n\t * Every field is the order's own; the keys are Google's, to pass unchanged\n\t * to `gapi.surveyoptin.render`.\n\t */\n\tasync survey(orderNumber: string): Promise<GoogleSurvey | null> {\n\t\tconst kept = orderNumber ? placedOrder(orderNumber) : undefined\n\t\tif (!kept || !(await this.switchOn('customer_reviews'))) return null\n\t\treturn this.orNull(() =>\n\t\t\tthis.data<GoogleSurvey>(`/x/google-reviews/survey/${encodeURIComponent(orderNumber)}`, {\n\t\t\t\tquery: { token: kept.token },\n\t\t\t}),\n\t\t)\n\t}\n\n\tprivate async switchOn(setting: string): Promise<boolean> {\n\t\ttry {\n\t\t\treturn (await this.facts.plugins()).get(PLUGIN)?.settings?.[setting] === true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/** Off, used up for the day, or refused by Google: nothing to show. Anything else still throws. */\n\tprivate async orNull<T>(call: () => Promise<T>): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await call()\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && [404, 429, 502].includes(err.status)) return null\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\nexport const googleReviewService = new GoogleReviewService()\n","import type { Menu, MenuItem, MenuSummary } from '../engine'\nimport { resolveRestLocally } from '../rest-guard'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { remember } from '../cache'\n\nexport type StorefrontMenu = { menuId: string; name: string; items: StorefrontMenuItem[] }\ntype StorefrontMenuItem = { id: string; name: string; link: string; items: StorefrontMenuItem[] }\n\n/**\n * A link where this storefront serves it. The navigation module resolves URLs\n * from its own patterns, whose defaults suit a different storefront; the\n * targets it names are slugs, so they are re-pointed at this one's routes.\n */\nfunction linkFor(item: MenuItem): string {\n\tconst t = item.target ?? ''\n\tswitch (item.kind) {\n\t\tcase 'home':\n\t\t\treturn '/'\n\t\tcase 'product':\n\t\t\treturn t ? `/products/${t}` : item.url\n\t\tcase 'collection':\n\t\t\treturn t ? `/collections/${t}` : item.url\n\t\tcase 'category':\n\t\t\treturn t ? `/${t}` : item.url\n\t\tcase 'page':\n\t\t\treturn t ? `/p/${t}` : item.url\n\t\tdefault:\n\t\t\treturn item.url\n\t}\n}\n\nconst toItem = (item: MenuItem, i: number): StorefrontMenuItem => ({\n\tid: String(item.id ?? i),\n\tname: item.title,\n\tlink: linkFor(item),\n\titems: (item.children ?? []).map(toItem),\n})\n\n/**\n * Menus from ext/navigation, when it is installed and switched on; otherwise\n * the storefront's own `store.menu`, which is what it shows anyway.\n */\nexport class MenuService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst menus = await this.engineMenus()\n\t\tif (menus) return { data: menus }\n\t\treturn resolveRestLocally('get', '/api/menu')\n\t}\n\n\t/** Every menu the store keeps, by handle — not only the header and footer. */\n\tasync listMenus() {\n\t\treturn (await this.data<MenuSummary[] | null>('/x/navigation/menus')) ?? []\n\t}\n\n\t/** One menu by handle, in the storefront's shape: `{ menuId, name, items: [{ id, name, link, items }] }`. */\n\tasync getMenu(handle: string): Promise<StorefrontMenu> {\n\t\tconst m = await this.data<Menu>(`/x/navigation/menus/${encodeURIComponent(handle)}`)\n\t\treturn { menuId: m.handle, name: m.title, items: (m.items ?? []).map(toItem) }\n\t}\n\n\t/**\n\t * The header and footer menus, or `null` when the module is not there. Cached: a menu is\n\t * store-level. Each is the menu the shop chose for it in the theme editor's header or footer\n\t * (GoCommerce D131), still under the `header` / `footer` id every storefront looks for, so the\n\t * choice reaches every place that draws one; the menus named so are the default.\n\t */\n\tasync engineMenus(): Promise<StorefrontMenu[] | null> {\n\t\tif (!(await this.facts.pluginOn('navigation'))) return null\n\t\treturn remember(`${this.engineBase()}|${this.store ?? ''}|menus`, async () => {\n\t\t\tconst out: StorefrontMenu[] = []\n\t\t\tfor (const part of ['header', 'footer'] as const) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handle = await this.chosenMenu(part)\n\t\t\t\t\tconst m = await this.data<Menu>(`/x/navigation/menus/${encodeURIComponent(handle)}`)\n\t\t\t\t\tout.push({ menuId: part, name: m.title, items: (m.items ?? []).map(toItem) })\n\t\t\t\t} catch {\n\t\t\t\t\t// A store may have deleted one of the two.\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out\n\t\t}).catch(() => null)\n\t}\n\n\t/** The handle of the menu the published header or footer names, else the part's own name. */\n\tprivate async chosenMenu(part: 'header' | 'footer'): Promise<string> {\n\t\tif (!(await this.facts.pluginOn('layouts'))) return part\n\t\ttry {\n\t\t\tconst layout = await this.data<{ sections?: { type: string; settings?: { menu?: unknown } | null }[] | null }>(`/x/layouts/${part}`)\n\t\t\tconst menu = layout?.sections?.find((s) => s.type === part)?.settings?.menu\n\t\t\treturn typeof menu === 'string' && menu ? menu : part\n\t\t} catch {\n\t\t\t// Nothing published, or an engine without the editor.\n\t\t\treturn part\n\t\t}\n\t}\n}\n\nexport const menuService = new MenuService()\n","/**\n * Store identity — name, logo, favicon, menus, theme variables.\n *\n * Some of that the engine has (the settlement currency, the payment methods,\n * the switched-on plugins) and most of it it does not: a logo and a hero banner\n * are the storefront's own business. The storefront registers its static store\n * record here at boot — `default-store.json` merged under the project's\n * `kitcommerce.config.ts` — and `storeService` lays the engine's live facts\n * over it, so the engine wins wherever it has an opinion.\n */\nexport type StaticStoreProvider = () => Promise<Record<string, any>> | Record<string, any>\n\nlet provider: StaticStoreProvider | undefined\n\nexport const setStaticStore = (fn: StaticStoreProvider) => {\n\tprovider = fn\n}\n\nexport const hasStaticStore = () => Boolean(provider)\n\nexport const readStaticStore = async (): Promise<Record<string, any>> => {\n\tif (!provider) return {}\n\treturn (await provider()) ?? {}\n}\n\n/** The marker the storefront reads to tell which backend is active. */\nexport const connectorName = 'gocommerce'\n","import { BaseService } from './base.service'\n\n/**\n * The signup box and its unsubscribe link (ext/newsletter). Subscribing twice\n * is not an error, and unsubscribing answers the same whether or not the token\n * matched, so neither call tells a stranger whether an address is on the list.\n */\nexport class NewsletterService extends BaseService {\n\tasync subscribe({ email, name, source }: { email: string; name?: string; source?: string }) {\n\t\treturn this.data<{ status: 'subscribed' }>('/x/newsletter/subscribe', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { email: String(email ?? '').trim(), ...(name ? { name } : {}), ...(source ? { source } : {}) },\n\t\t})\n\t}\n\n\t/** The token from the unsubscribe link in a newsletter email. */\n\tasync unsubscribe(token: string) {\n\t\treturn this.data<{ status: 'unsubscribed' }>('/x/newsletter/unsubscribe', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { token: String(token ?? '') },\n\t\t})\n\t}\n}\n\nexport const newsletterService = new NewsletterService()\n","import { GoCommerceError } from '../errors'\nimport { readStaticStore } from '../static-store'\nimport { BaseService, mediaUrl } from './base.service'\nimport { StoreFacts } from './facts'\nimport { MenuService } from './menu-service'\nimport { NewsletterService } from './newsletter-service'\n\n/**\n * The engine's \"no such store\" answer to an `X-Store` it cannot resolve, and\n * nothing else: a 404 for a product or a page is a different question.\n */\nconst isStoreMissing = (err: unknown) =>\n\terr instanceof GoCommerceError &&\n\terr.status === 404 &&\n\t(err.code === 'store_not_found' || /store not found|no such store/i.test(err.message))\n\n/** `$`, `€`, `₹` — from the platform's own tables rather than a list kept here. */\nfunction symbolFor(code: string): string {\n\ttry {\n\t\tconst part = new Intl.NumberFormat('en', { style: 'currency', currency: code })\n\t\t\t.formatToParts(0)\n\t\t\t.find((p) => p.type === 'currency')\n\t\treturn part?.value ?? code\n\t} catch {\n\t\treturn code\n\t}\n}\n\n/**\n * The store record every page renders from.\n *\n * Theme and the rest are the storefront's own (its static store, registered\n * through `setStaticStore`); the engine has no opinion on them. Where the\n * engine does have one, it wins:\n * - the store's name, contact, logo and icon, as its owner set them in the\n * panel. One storefront serves every store under `baseDomain`, so a name or\n * a logo in the static record would be every store's;\n * - the settlement currency. Every price on the site is formatted with it, and\n * a store record saying USD over an engine charging INR would print the\n * wrong symbol on every price;\n * - the modules that back a storefront feature, and the menus.\n *\n * This runs on every request and a throw here takes every page down, so the\n * engine's half is best-effort: unreachable, the storefront still renders\n * from its own record, and the failure shows up where a price is fetched.\n */\nexport class StoreService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync getStoreByIdOrDomain(_args: { storeId?: string; domain?: string } = {}) {\n\t\tconst base = await readStaticStore()\n\t\t// The one failure that is not best-effort: a host under `baseDomain` naming\n\t\t// a store the engine has never heard of. That page is a 404, not a render\n\t\t// of the static record, so the storefront's 404 route can take it from here.\n\t\tconst store = this.store\n\t\tif (store) {\n\t\t\tawait this.facts.plugins().catch((err) => {\n\t\t\t\tif (isStoreMissing(err)) {\n\t\t\t\t\tthrow new GoCommerceError(`store not found: no store \"${store}\" on this engine`, 404, 'store_not_found')\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t\tconst live = await this.live().catch(() => ({}))\n\t\t// `id` must be truthy and stable: the storefront keys a cookie on it.\n\t\treturn { ...base, ...live, id: base.id || 'gocommerce' }\n\t}\n\n\tasync getStore(storeId?: string) {\n\t\treturn this.getStoreByIdOrDomain({ storeId })\n\t}\n\n\t/**\n\t * The storefront's sitemap route asks for `/api/stores/<id>` and serves the\n\t * `sitemap` path it gets back from `PUBLIC_SITEMAP_URL`. With ext/sitemaps\n\t * installed, `/sitemaps/sitemap.xml` under `PUBLIC_SITEMAP_URL=<engine>/x`\n\t * is the engine's own sitemap; without it, an empty path is the route's\n\t * clean 404 rather than a crash.\n\t */\n\toverride async get<T = any>(path: string): Promise<T> {\n\t\tif (path.split('?')[0].startsWith('/api/stores/')) {\n\t\t\tconst on = await this.facts.pluginOn('sitemap')\n\t\t\treturn { sitemap: on ? '/sitemaps/sitemap.xml' : '' } as T\n\t\t}\n\t\treturn super.get<T>(path)\n\t}\n\n\t/**\n\t * The storefront's newsletter box posts `{ email }` to Litekart's\n\t * `/api/newsletter/subscribe` through this verb; ext/newsletter is where\n\t * that list lives here.\n\t */\n\toverride async post<T = any>(path: string, data?: unknown): Promise<T> {\n\t\tif (path.split('?')[0] === '/api/newsletter/subscribe') {\n\t\t\tconst { email, name } = (data ?? {}) as { email?: string; name?: string }\n\t\t\treturn (await new NewsletterService(this._fetch).subscribe({\n\t\t\t\temail: email ?? '',\n\t\t\t\tname,\n\t\t\t\tsource: 'storefront',\n\t\t\t})) as T\n\t\t}\n\t\treturn super.post<T>(path, data)\n\t}\n\n\tprivate async live(): Promise<Record<string, unknown>> {\n\t\tconst [ready, plugins, menus, base, profile, ships] = await Promise.all([\n\t\t\tthis.facts.ready(),\n\t\t\tthis.facts.plugins().catch(() => new Map()),\n\t\t\tnew MenuService(this._fetch).engineMenus(),\n\t\t\treadStaticStore(),\n\t\t\tthis.facts.profile().catch(() => null),\n\t\t\t// An engine without the route rules nothing out.\n\t\t\tthis.facts.shipsTo().catch(() => ({ everywhere: true, countries: [] as string[] })),\n\t\t])\n\t\tconst code = ready.currency\n\t\tconst sameCurrency = (base.currency?.code ?? base.currencyCode) === code\n\t\tconst flag = (on: boolean) => ({ ...(on ? { active: true } : { active: false }) })\n\t\tconst basePlugins = (base.plugins ?? {}) as Record<string, Record<string, unknown>>\n\t\treturn {\n\t\t\t// Only what the owner filled in: an empty name keeps the static one.\n\t\t\t...(profile?.name ? { name: profile.name } : {}),\n\t\t\t...(profile?.email ? { businessEmail: profile.email } : {}),\n\t\t\t...(profile?.phone ? { businessPhone: profile.phone } : {}),\n\t\t\t// The store's pictures (D148), the same: one it has not chosen keeps the static one.\n\t\t\t// Its own logo also replaces the static dark logo, which would be the deployment's\n\t\t\t// mark beside this store's; without a dark one of its own, its logo is the fallback.\n\t\t\t...(profile?.logo_url ? { logo: mediaUrl(profile.logo_url), logoDark: undefined } : {}),\n\t\t\t...(profile?.logo_dark_url ? { logoDark: mediaUrl(profile.logo_dark_url) } : {}),\n\t\t\t...(profile?.icon_url ? { favicon: mediaUrl(profile.icon_url) } : {}),\n\t\t\t// What the contact page shows (D156), only what the store published. The address\n\t\t\t// in the shape the storefront's contact page and home-page JSON-LD already read. The\n\t\t\t// country beside it, not over `country`: that is the address form's default country.\n\t\t\t...(profile?.country ? { businessCountry: profile.country } : {}),\n\t\t\t...(profile?.address\n\t\t\t\t? {\n\t\t\t\t\t\taddress: {\n\t\t\t\t\t\t\tstreet: [profile.address.line1, profile.address.line2].filter(Boolean).join(', '),\n\t\t\t\t\t\t\tcity: profile.address.city,\n\t\t\t\t\t\t\tstate: profile.address.state,\n\t\t\t\t\t\t\tpincode: profile.address.postal_code,\n\t\t\t\t\t\t\tcountry: profile.address.country,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(profile?.map_location ? { mapLocation: profile.map_location } : {}),\n\t\t\t...(profile?.opening_hours?.length ? { openingHours: profile.opening_hours } : {}),\n\t\t\tcurrencyCode: code,\n\t\t\tcurrencySymbol: sameCurrency ? (base.currencySymbol ?? symbolFor(code)) : symbolFor(code),\n\t\t\tcurrency: {\n\t\t\t\t...(base.currency ?? {}),\n\t\t\t\tcode,\n\t\t\t\tsymbol: sameCurrency ? (base.currency?.symbol ?? symbolFor(code)) : symbolFor(code),\n\t\t\t\tincludesTax: profile?.prices_include_tax,\n\t\t\t},\n\t\t\tlanguage: ready.language,\n\t\t\tplugins: {\n\t\t\t\t...basePlugins,\n\t\t\t\t// Features this connector serves from a module: on exactly when the\n\t\t\t\t// module is installed and switched on, whatever the static record says.\n\t\t\t\tisWishlist: { ...basePlugins.isWishlist, ...flag(plugins.has('wishlist')) },\n\t\t\t\t// The corner button and the contact page's WhatsApp card read the number from\n\t\t\t\t// here; the engine's plugin holds it, in international digits.\n\t\t\t\twhatsappChatButton: {\n\t\t\t\t\t...basePlugins.whatsappChatButton,\n\t\t\t\t\t...flag(plugins.has('whatsapp-chat')),\n\t\t\t\t\t...(plugins.has('whatsapp-chat')\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tphone: String(plugins.get('whatsapp-chat')?.settings?.phone ?? ''),\n\t\t\t\t\t\t\t\tmessage: String(plugins.get('whatsapp-chat')?.settings?.message ?? ''),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\t// Criteo's OneTag, for this store's own account. The engine decides: on a shared\n\t\t\t\t// deployment the static record is every store's, and one store's account must\n\t\t\t\t// never load on another's pages.\n\t\t\t\tcriteo: {\n\t\t\t\t\t...basePlugins.criteo,\n\t\t\t\t\t...flag(plugins.has('criteo')),\n\t\t\t\t\t...(plugins.has('criteo') ? { accountId: String(plugins.get('criteo')?.settings?.account_id ?? '') } : {}),\n\t\t\t\t},\n\t\t\t\tisProductReviewsAndRatings: {\n\t\t\t\t\t...basePlugins.isProductReviewsAndRatings,\n\t\t\t\t\t...flag(plugins.has('product-reviews')),\n\t\t\t\t},\n\t\t\t\t// Google Customer Reviews (ext/google-reviews): the confirmation page's survey offer,\n\t\t\t\t// whose fields the engine builds from the order, and Google's store widget, which\n\t\t\t\t// belongs to the same programme and so needs the survey on.\n\t\t\t\tgoogleReviewsOptIn: {\n\t\t\t\t\t...basePlugins.googleReviewsOptIn,\n\t\t\t\t\t...flag(googleSetting(plugins, 'customer_reviews') === true),\n\t\t\t\t},\n\t\t\t\tgoogleStoreWidget: storeWidget(plugins),\n\t\t\t\t// The footer's sign-up box posts to ext/newsletter, and the theme editor's footer\n\t\t\t\t// switch (D131) can only show it while that is on.\n\t\t\t\tnewsletter: { ...basePlugins.newsletter, ...flag(plugins.has('newsletter')) },\n\t\t\t\t// The ad and analytics tags (D160). The engine decides, not the static record:\n\t\t\t\t// one storefront serves every store, and one store's pixel must never\n\t\t\t\t// load on another's pages.\n\t\t\t\t...adTags(plugins),\n\t\t\t\tgoogleTagManager: googleTags(plugins),\n\t\t\t\t// Discount codes are core: every GoCommerce store takes them, so\n\t\t\t\t// the code box is shown whatever the static record says.\n\t\t\t\tisDiscountCoupons: { ...basePlugins.isDiscountCoupons, active: true },\n\t\t\t\t// The engine resizes the store's own pictures in Cloudflare's URL shape\n\t\t\t\t// (D139), so the storefront's srcset asks it for each width. Its public\n\t\t\t\t// origin, not the proxy path: an <img> needs no CORS, and the proxy would\n\t\t\t\t// put every picture through the storefront's server.\n\t\t\t\t...(profile?.images_path && this.creds.apiUrl\n\t\t\t\t\t? {\n\t\t\t\t\t\t\timageCdn: {\n\t\t\t\t\t\t\t\tprovider: 'cloudflare',\n\t\t\t\t\t\t\t\turl: this.creds.apiUrl.trim().replace(/\\/+$/, '') + profile.images_path,\n\t\t\t\t\t\t\t\tactive: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t...(menus?.length ? { menu: menus } : {}),\n\t\t\t...deliverable(base, ships),\n\t\t\t// The one way this store signs customers in (D116), which the sign-in\n\t\t\t// form reads as PHONE or EMAIL. Without the accounts module the static\n\t\t\t// record says.\n\t\t\t...(plugins.has('identity')\n\t\t\t\t? { loginType: LOGIN_TYPES[String(plugins.get('identity')?.settings?.login_method)] ?? 'EMAIL' }\n\t\t\t\t: {}),\n\t\t}\n\t}\n}\n\nexport const storeService = new StoreService()\n\n/** Each tag's engine plugin, the setting that holds its ID, and its name on the store record. */\nconst AD_TAGS = [\n\t['meta-pixel', 'pixel_id', 'facebookPixel'],\n\t['microsoft-clarity', 'project_id', 'microsoftClarity'],\n\t['hotjar', 'site_id', 'hotjar'],\n\t['tiktok-pixel', 'pixel_id', 'tiktokPixel'],\n\t['pinterest-tag', 'tag_id', 'pinterestTag'],\n\t['snapchat-pixel', 'pixel_id', 'snapchatPixel'],\n] as const\n\n/** On with its ID, or off with none, so a storefront has nothing to load by mistake. */\nfunction adTags(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\treturn Object.fromEntries(\n\t\tAD_TAGS.map(([key, field, name]) => {\n\t\t\tconst id = String(plugins.get(key)?.settings?.[field] ?? '').trim()\n\t\t\treturn [name, id ? { active: true, id } : { active: false }]\n\t\t}),\n\t)\n}\n\n/**\n * The google-analytics plugin in the shape the storefront has always read under\n * `googleTagManager`: its tag IDs, and the Ads conversion label as the purchase's\n * conversion. Off with no IDs when none is filled in.\n */\nfunction googleTags(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\tconst s = plugins.get('google-analytics')?.settings ?? {}\n\tconst id = (field: string) => String(s[field] ?? '').trim()\n\t// Google Ads shows a conversion as `send_to: 'AW-…/label'`, and an owner may paste all of it.\n\tconst [account, part] = id('conversion_label').split('/')\n\tconst label = part === undefined ? account : part\n\tconst ads = id('google_ads_id') || (part === undefined ? '' : account)\n\tconst tags = [id('ga4_measurement_id'), ads, id('gtm_container_id')].filter(Boolean)\n\tif (!tags.length) return { active: false }\n\treturn { active: true, tags, conversions: ads && label ? [{ event: 'purchase', label }] : [] }\n}\n\ntype Country = { code: string; name: string; [k: string]: unknown }\n\n/**\n * The address form's countries narrowed to where the store delivers (D117).\n * Each keeps the static record's entry, which may carry more than a name; a\n * country the record lacks is named by the browser's own list. One country is\n * also the default, and so is the first when the static default is not one of\n * them. Everywhere changes nothing.\n */\nfunction deliverable(\n\tbase: { country?: Country; countries?: Country[] },\n\tships: { everywhere: boolean; countries: string[] },\n): { countries?: Country[]; country?: Country } {\n\tif (ships.everywhere || !ships.countries.length) return {}\n\tconst known = new Map((base.countries ?? []).map((c) => [String(c.code).toUpperCase(), c]))\n\tconst countries = ships.countries.map((code) => known.get(code) ?? { code, name: regionName(code) })\n\tconst keep = base.country && ships.countries.includes(String(base.country.code).toUpperCase())\n\treturn { countries, ...(keep ? {} : { country: countries[0] }) }\n}\n\nfunction regionName(code: string): string {\n\ttry {\n\t\treturn new Intl.DisplayNames(['en'], { type: 'region' }).of(code) ?? code\n\t} catch {\n\t\treturn code\n\t}\n}\n\nconst googleSetting = (plugins: Map<string, { settings?: Record<string, unknown> }>, key: string) =>\n\tplugins.get('google-reviews')?.settings?.[key]\n\n/** Google's store widget, where the store placed it; off without the survey. */\nfunction storeWidget(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\tconst where = googleSetting(plugins, 'store_widget')\n\tif (googleSetting(plugins, 'customer_reviews') !== true || !where) return { active: false }\n\treturn { active: true, position: where === 'Bottom left' ? 'LEFT_BOTTOM' : 'RIGHT_BOTTOM' }\n}\n\n/** The sign-in form's names for the store's choice (D116, D118). */\nconst LOGIN_TYPES: Record<string, string> = { phone_otp: 'PHONE', email_or_phone: 'BOTH', email_password: 'EMAIL' }\n","import type { CmsPage, Faq } from '../engine'\nimport { toCmsPage as toStorefrontPage } from '../map'\nimport { BaseService, toPage } from './base.service'\n\n/**\n * Content pages from ext/cms, in the shopper's language with the store's\n * default as the fallback. A slug with no page is the page's 404.\n */\nexport class PageService extends BaseService {\n\tasync getOne(slug: string) {\n\t\treturn toStorefrontPage(await this.data<CmsPage>(`/x/cms/pages/${encodeURIComponent(String(slug))}`))\n\t}\n\n\tasync list({ page = 1, limit = 50 }: { page?: number; limit?: number; search?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<CmsPage[] | null>('/x/cms/pages', { query: { page, limit } })\n\t\treturn toPage(env, toStorefrontPage)\n\t}\n}\n\n/** The shop's questions and answers (ext/faq), flattened in the shop's own order. */\nexport class FaqService extends BaseService {\n\tasync listFaqs(_args: Record<string, unknown> = {}) {\n\t\tconst faq = await this.data<Faq>('/x/faq')\n\t\tconst data = (faq.sections ?? []).flatMap((s) =>\n\t\t\t(s.entries ?? []).map((e) => ({\n\t\t\t\tid: String(e.id),\n\t\t\t\tquestion: e.question,\n\t\t\t\tanswer: e.answer,\n\t\t\t\tcategory: s.section || null,\n\t\t\t})),\n\t\t)\n\t\treturn { data, count: data.length, heading: faq.heading, blurb: faq.blurb }\n\t}\n\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.listFaqs(args)\n\t}\n}\n\nexport const pageService = new PageService()\nexport const faqService = new FaqService()\n","import type { Product } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { toProduct, type StorefrontProduct } from '../map'\nimport { BaseService, mediaUrl } from './base.service'\nimport { MenuService, type StorefrontMenu } from './menu-service'\n\n/** A collection list's card, as the engine resolves it. */\ntype EngineLayoutCollection = {\n\tid: number\n\tslug: string\n\ttitle: string\n\timage?: string\n}\n\n/** One section as the engine stores it, before the storefront maps anything. */\ntype EngineLayoutSection = {\n\tid: string\n\ttype: string\n\tsettings: Record<string, unknown> | null\n\tproducts?: Product[] | null\n\tcollections?: EngineLayoutCollection[] | null\n}\n\n/**\n * The store's design tokens (ext/layouts, D127). Every key is optional and\n * an absent one means the storefront keeps its own look: colours are\n * `#rrggbb`, fonts are keys of the storefront's font list, `radius` is\n * none, small, medium or large.\n */\nexport type ThemeSettings = Partial<\n\tRecord<'background' | 'text' | 'accent' | 'accent_text' | 'muted' | 'heading_font' | 'body_font' | 'radius', string>\n>\n\ntype EngineLayout = {\n\tpage: string\n\ttheme: string\n\trevision?: number\n\tpreview?: boolean\n\ttheme_settings?: ThemeSettings | null\n\tsections: EngineLayoutSection[] | null\n}\n\n/** A collection list's card: enough to draw a picture and a title and link to it. */\nexport type LayoutCollection = {\n\tid: string\n\ttitle: string\n\tslug: string\n\tlink: string\n\timage: string | null\n}\n\n/**\n * One section of a composed page. `settings` is the merchant's, as validated\n * by the engine: plain text (never HTML) and links that are `/path` or\n * `http(s)://`. A product grid also carries its products, resolved live and\n * mapped like any other product the storefront renders; a collection list\n * carries its collections.\n */\nexport type HomeLayoutSection = {\n\tid: string\n\ttype: string\n\tsettings: Record<string, unknown>\n\tproducts?: StorefrontProduct[]\n\tcollections?: LayoutCollection[]\n}\n\n/**\n * A page the shop arranges: the home page, or the template every product or\n * every collection is drawn in (ext/layouts, D128). A template holds its\n * core once — `main-product` (the catalogue's pictures, price and buy box)\n * or `main-collection` (the collection's grid) — at the place the shop put\n * it, and the storefront draws its own core there.\n */\nexport type LayoutPage = 'home' | 'product' | 'collection' | 'header' | 'footer'\n\nexport type HomeLayout = {\n\tpage: string\n\ttheme: string\n\t/** The published revision this is; absent on a preview. */\n\trevision?: number\n\t/** True when this is the saved draft shown through a preview key. */\n\tpreview: boolean\n\t/** The design tokens published with the page, or null for none. */\n\tthemeSettings: ThemeSettings | null\n\tsections: HomeLayoutSection[]\n}\n\n/** A composed page of any kind; a template's `themeSettings` is always null. */\nexport type PageLayout = HomeLayout\n\n/** The design tokens alone, for every page the storefront draws. */\nexport type ThemeSettingsResult = {\n\trevision?: number\n\tpreview: boolean\n\tsettings: ThemeSettings\n}\n\n/**\n * The header's settings as the shop set them (ext/layouts, D131): the strip\n * above the header — shown or not, its words, its link, and whether it is on\n * every page or the home page only — and the handle of the menu across it.\n * Plain text, and a link that is `/path` or `http(s)://`.\n */\nexport type HeaderSettings = {\n\tshow_announcement?: boolean\n\tannouncement_text?: string\n\tannouncement_link?: string\n\tannouncement_pages?: 'all' | 'home'\n\tmenu?: string\n}\n\n/** A footer's link to the shop's page on a social network; `url` is always `http(s)://`. */\nexport type SocialLink = { network: 'instagram' | 'facebook' | 'x' | 'youtube' | 'pinterest' | 'linkedin' | 'whatsapp' | 'telegram'; url: string }\n\n/**\n * The footer's settings (D131): the handle of the menu whose top-level links\n * become its columns, a few words about the shop, whether the newsletter\n * sign-up shows (absent while the newsletter is off), social links and the\n * copyright line. An absent one means the storefront keeps its own.\n */\nexport type FooterSettings = {\n\tmenu?: string\n\tabout?: string\n\tnewsletter?: boolean\n\tsocial?: SocialLink[]\n\tcopyright?: string\n}\n\n/**\n * The published header or footer, or a preview key's draft, with the menu\n * it names already read — live, so a menu edited in the panel shows without a\n * publish. `menu` is null when none is named or the named one is gone.\n */\nexport type SiteChrome<S> = {\n\trevision?: number\n\tpreview: boolean\n\tsettings: S\n\tmenu: StorefrontMenu | null\n}\nexport type SiteHeader = SiteChrome<HeaderSettings>\nexport type SiteFooter = SiteChrome<FooterSettings>\n\n/** Settings that hold a picture's or a video's address, which may be the engine's own upload. */\nconst MEDIA_KEYS = new Set(['image', 'mobile_image', 'poster', 'video_file'])\n\n/**\n * Composed pages from ext/layouts. A store without one — the plugin off,\n * nothing published, an engine built without the module, or a preview key\n * that is wrong or expired — answers null, and the storefront renders its\n * built-in page.\n */\nexport class LayoutService extends BaseService {\n\tasync getHomeLayout({ preview }: { preview?: string | null } = {}): Promise<HomeLayout | null> {\n\t\treturn this.getPageLayout('home', { preview })\n\t}\n\n\t/**\n\t * The template every product page is drawn in: the sections around the\n\t * product's core (`main-product`). Null when none is published, so the\n\t * product page draws exactly as it did before templates existed.\n\t */\n\tasync getProductLayout({ preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\treturn this.getPageLayout('product', { preview })\n\t}\n\n\t/** The template every collection page is drawn in, around its grid (`main-collection`). */\n\tasync getCollectionLayout({ preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\treturn this.getPageLayout('collection', { preview })\n\t}\n\n\t/** Any arranged page by its key; null for none, as the three above. */\n\tasync getPageLayout(page: LayoutPage, { preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\tlet layout: EngineLayout\n\t\ttry {\n\t\t\tlayout = await this.data<EngineLayout>(`/x/layouts/${encodeURIComponent(page)}`, {\n\t\t\t\tquery: { preview: preview?.trim() || undefined },\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return null\n\t\t\tthrow err\n\t\t}\n\t\tif (!layout) return null\n\t\treturn {\n\t\t\tpage: layout.page,\n\t\t\ttheme: layout.theme,\n\t\t\trevision: layout.revision,\n\t\t\tpreview: !!layout.preview,\n\t\t\tthemeSettings: tokens(layout.theme_settings),\n\t\t\tsections: (layout.sections ?? []).map(toSection),\n\t\t}\n\t}\n\n\t/**\n\t * The store's design tokens, for a page other than the home page: the\n\t * published ones, or a preview key's draft. Null when there are none to\n\t * apply — nothing published, the editor off, an engine without the\n\t * module — and on any failure too: a missing look must never cost the\n\t * page.\n\t */\n\tasync getThemeSettings({ preview }: { preview?: string | null } = {}): Promise<ThemeSettingsResult | null> {\n\t\ttry {\n\t\t\tconst out = await this.data<{ revision?: number; preview?: boolean; settings?: ThemeSettings | null }>('/x/layouts/theme', {\n\t\t\t\tquery: { preview: preview?.trim() || undefined },\n\t\t\t})\n\t\t\tif (!out) return null\n\t\t\treturn { revision: out.revision, preview: !!out.preview, settings: tokens(out.settings) ?? {} }\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/**\n\t * The header the shop set in the theme editor (D131), drawn on every\n\t * page: the published one, or a preview key's draft. Null — the\n\t * storefront's own header — when none is published, the editor is off, the\n\t * engine is older, or anything fails: a header is never worth an error page.\n\t */\n\tasync getHeader({ preview }: { preview?: string | null } = {}): Promise<SiteHeader | null> {\n\t\treturn this.chrome<HeaderSettings>('header', preview)\n\t}\n\n\t/** The footer the shop set in the theme editor (D131); null for the storefront's own, as getHeader. */\n\tasync getFooter({ preview }: { preview?: string | null } = {}): Promise<SiteFooter | null> {\n\t\treturn this.chrome<FooterSettings>('footer', preview)\n\t}\n\n\tprivate async chrome<S extends { menu?: string }>(page: 'header' | 'footer', preview?: string | null): Promise<SiteChrome<S> | null> {\n\t\tlet layout: PageLayout | null\n\t\ttry {\n\t\t\tlayout = await this.getPageLayout(page, { preview })\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t\tconst section = layout?.sections.find((s) => s.type === page)\n\t\tif (!layout || !section) return null\n\t\tconst settings = { ...section.settings } as S\n\t\tlet menu: StorefrontMenu | null = null\n\t\tif (typeof settings.menu === 'string' && settings.menu) {\n\t\t\tmenu = await new MenuService(this._fetch).getMenu(settings.menu).catch(() => null)\n\t\t}\n\t\treturn { revision: layout.revision, preview: layout.preview, settings, menu }\n\t}\n}\n\nfunction tokens(v: ThemeSettings | null | undefined): ThemeSettings | null {\n\treturn v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length ? { ...v } : null\n}\n\n/**\n * An upload is answered root-relative, which the shopper's browser would\n * resolve against the storefront rather than the engine — at the top of a\n * section's settings and inside its lists (a slideshow's slides) alike.\n */\nfunction withMedia(value: unknown, key: string | null): unknown {\n\tif (Array.isArray(value)) return value.map((x) => withMedia(x, null))\n\tif (value && typeof value === 'object') {\n\t\treturn Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, x]) => [k, withMedia(x, k)]))\n\t}\n\tif (key && MEDIA_KEYS.has(key) && typeof value === 'string') return mediaUrl(value)\n\treturn value\n}\n\nfunction toSection(s: EngineLayoutSection): HomeLayoutSection {\n\tconst settings = withMedia(s.settings ?? {}, null) as Record<string, unknown>\n\tconst out: HomeLayoutSection = { id: s.id, type: s.type, settings }\n\tif (s.type === 'product-grid') out.products = (s.products ?? []).map((p) => toProduct(p))\n\tif (s.type === 'collection-list') {\n\t\tout.collections = (s.collections ?? []).map((c) => ({\n\t\t\tid: String(c.id),\n\t\t\ttitle: c.title,\n\t\t\tslug: c.slug,\n\t\t\tlink: `/collections/${c.slug}`,\n\t\t\timage: mediaUrl(c.image) ?? null,\n\t\t}))\n\t}\n\treturn out\n}\n\nexport const layoutService = new LayoutService()\n","import type { Vendor } from '../engine'\nimport { toVendor } from '../map'\nimport { BaseService, emptyPage, toPage } from './base.service'\n\n/** The marketplace's sellers: approved vendors only. */\nexport class VendorService extends BaseService {\n\tasync list({\n\t\tpage = 1,\n\t\tlimit = 24,\n\t\tq,\n\t\tsearch,\n\t}: { page?: number; limit?: number; q?: string; search?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<Vendor[] | null>('/api/vendors', { query: { page, limit, q: q ?? search } })\n\t\treturn toPage(env, toVendor)\n\t}\n\n\tasync getVendor(slug: string) {\n\t\treturn toVendor(await this.data<Vendor>(`/api/vendors/${encodeURIComponent(String(slug))}`))\n\t}\n\n\t/**\n\t * A seller's shelf. The engine's vendors sell through offers on the shop's\n\t * own variants and the public API lists no products by seller, so the shelf\n\t * is empty — the seller's page still renders, with their details.\n\t */\n\tasync fetchProductsOfVendor(_vendorId?: string) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport const vendorService = new VendorService()\n","/**\n * The rest of the family's service surface.\n *\n * Svelte Commerce imports some four dozen services by name because Litekart\n * has them, and an export that is missing is a TypeError at import. Each one\n * is here. Where the engine has the thing, it is wired; where it does not, a\n * read of a list answers empty (a shop legitimately has no reels) and anything\n * that would write, or that names one record, throws `NotSupportedError` —\n * a silent success would tell a shopper their message was sent when nothing\n * left the browser.\n */\nimport type { Plugin } from '../engine'\nimport { NotSupportedError } from '../errors'\nimport { readStaticStore } from '../static-store'\nimport { resolveRestLocally } from '../rest-guard'\nimport { BaseService, emptyPage } from './base.service'\nimport { StoreFacts } from './facts'\nimport { MeilisearchService } from './meilisearch-service'\nimport { StoreService } from './store-service'\n\nconst refuse = (service: string, method: string, why: string) => new NotSupportedError(service, method, why)\n\n/** The storefront's contact form and product enquiries, through ext/contact's inbox. */\nexport class ContactService extends BaseService {\n\tasync submitContactUsForm({\n\t\tname,\n\t\temail,\n\t\tphone,\n\t\tmessage,\n\t\tsubject,\n\t\twebsite,\n\t}: {\n\t\tname: string\n\t\temail: string\n\t\tphone?: string\n\t\tmessage: string\n\t\tsubject?: string\n\t\t/** The form's hidden honeypot, passed on so the engine drops what a bot filled in. */\n\t\twebsite?: string\n\t}) {\n\t\treturn this.data<{ status: string }>('/x/contact/messages', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tname: String(name ?? ''),\n\t\t\t\temail: String(email ?? ''),\n\t\t\t\t...(phone ? { phone: String(phone) } : {}),\n\t\t\t\t...(subject ? { subject: String(subject) } : {}),\n\t\t\t\tbody: String(message ?? ''),\n\t\t\t\t...(website ? { website: String(website) } : {}),\n\t\t\t},\n\t\t})\n\t}\n}\n\nexport class EnquiryService extends ContactService {\n\tasync create({\n\t\tname,\n\t\temail,\n\t\tphone,\n\t\tmessage,\n\t\tproductId,\n\t}: {\n\t\tname: string\n\t\temail: string\n\t\tphone?: string\n\t\tmessage: string\n\t\tproductId?: string\n\t}) {\n\t\treturn this.submitContactUsForm({\n\t\t\tname,\n\t\t\temail,\n\t\t\tphone,\n\t\t\tsubject: productId ? `Enquiry about product ${productId}` : 'Enquiry',\n\t\t\tmessage,\n\t\t})\n\t}\n}\n\n/** Enabled plugins and their public settings, `{ key, title, settings }`. */\nexport class PluginService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst data: Plugin[] = [...(await this.facts.plugins()).values()]\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\n/** The store record again, for the callers that ask for it as \"settings\" or \"init\". */\nexport class SettingService extends BaseService {\n\tasync fetchSettings(_args: Record<string, unknown> = {}) {\n\t\treturn new StoreService(this._fetch).getStoreByIdOrDomain()\n\t}\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.fetchSettings(args)\n\t}\n}\n\nexport class InitService extends SettingService {\n\tasync fetchInit(_args: Record<string, unknown> = {}) {\n\t\tconst store = await this.fetchSettings()\n\t\treturn { storeOne: store, store, settings: store }\n\t}\n}\n\nexport class HomeService extends BaseService {\n\t/** A homepage is assembled by the storefront from shelves; the engine has no page of its own for it. */\n\tasync getHome(_args: Record<string, unknown> = {}) {\n\t\treturn { banners: [], groupByBanner: [], categories: [], products: [] }\n\t}\n}\n\n/** Countries for the address form: the storefront's own list, which is what it offers anyway. */\nexport class CountryService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn resolveRestLocally('get', '/api/countries')\n\t}\n}\n\n/** The one currency an engine store settles in. */\nexport class CurrencyService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\tasync listCurrencies(_args: Record<string, unknown> = {}) {\n\t\tconst { currency } = await this.facts.ready()\n\t\tconst data = [{ code: currency, name: currency, isDefault: true }]\n\t\treturn { data, count: 1, pageSize: 1, noOfPage: 1, page: 1 }\n\t}\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.listCurrencies(args)\n\t}\n}\n\n/** States are free text on a GoCommerce address; there is no list to offer. */\nexport class StateService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class RegionService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The header's type-ahead, under the name some storefront builds still call it by. */\nexport class AutocompleteService extends MeilisearchService {\n\tasync list({ q, search }: { q?: string; search?: string } = {}) {\n\t\treturn this.searchAutoComplete({ query: q ?? search })\n\t}\n}\n\nexport class PopularSearchService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The engine keeps no popularity score; a page view is not recorded. */\nexport class PopularityService extends BaseService {\n\tasync updatePopularity(_args: Record<string, unknown> = {}) {\n\t\treturn undefined\n\t}\n}\n\nexport class BlogService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync getOne(_slug: string): Promise<never> {\n\t\tthrow refuse('BlogService', 'getOne', 'the engine has no blog; publish articles as pages')\n\t}\n}\n\nexport class BannerService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync listBanners(args: Record<string, unknown> = {}) {\n\t\treturn this.list(args)\n\t}\n\tasync fetchBanners(args: Record<string, unknown> = {}) {\n\t\treturn this.list(args)\n\t}\n}\n\nexport class ReelsService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class DealService extends BaseService {\n\tasync fetchDeals(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class GalleryService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class ChatService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync chats(): Promise<never> {\n\t\tthrow refuse('ChatService', 'chats', 'the engine has no shopper chat')\n\t}\n\tasync save(): Promise<never> {\n\t\tthrow refuse('ChatService', 'save', 'the engine has no shopper chat')\n\t}\n}\n\nexport class FeedbackService extends BaseService {\n\tasync save(): Promise<never> {\n\t\tthrow refuse('FeedbackService', 'save', 'use the contact form')\n\t}\n}\n\nexport class DemoRequestService extends BaseService {\n\tasync save(): Promise<never> {\n\t\tthrow refuse('DemoRequestService', 'save', 'use the contact form')\n\t}\n}\n\nexport class UploadService extends BaseService {\n\tasync uploadMultipleToS3(): Promise<never> {\n\t\tthrow refuse('UploadService', 'uploadMultipleToS3', 'shoppers cannot upload files to the engine')\n\t}\n\tasync upload(): Promise<never> {\n\t\tthrow refuse('UploadService', 'upload', 'shoppers cannot upload files to the engine')\n\t}\n}\n\nexport class WarrantyService extends BaseService {\n\tasync submitWarrantyRegistration(): Promise<never> {\n\t\tthrow refuse('WarrantyService', 'submitWarrantyRegistration', 'the engine has no warranty registrations')\n\t}\n}\n\nexport class VarniCustomDesignService extends BaseService {\n\tasync submitForm(): Promise<never> {\n\t\tthrow refuse('VarniCustomDesignService', 'submitForm', 'custom design requests are a Litekart feature')\n\t}\n}\n\nexport class VarniCustomProductService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The storefront's static store record, for code that wants the raw config. */\nexport const staticStore = () => readStaticStore()\n\nexport const contactService = new ContactService()\nexport const enquiryService = new EnquiryService()\nexport const pluginService = new PluginService()\nexport const settingService = new SettingService()\nexport const initService = new InitService()\nexport const homeService = new HomeService()\nexport const countryService = new CountryService()\nexport const currencyService = new CurrencyService()\nexport const stateService = new StateService()\nexport const regionService = new RegionService()\nexport const autocompleteService = new AutocompleteService()\nexport const popularSearchService = new PopularSearchService()\nexport const popularityService = new PopularityService()\nexport const blogService = new BlogService()\nexport const bannerService = new BannerService()\nexport const reelsService = new ReelsService()\nexport const dealService = new DealService()\nexport const galleryService = new GalleryService()\nexport const chatService = new ChatService()\nexport const feedbackService = new FeedbackService()\nexport const demoRequestService = new DemoRequestService()\nexport const uploadService = new UploadService()\nexport const warrantyService = new WarrantyService()\nexport const varniCustomDesignService = new VarniCustomDesignService()\nexport const varniCustomProductService = new VarniCustomProductService()\n\n// kitcommerce-core reads the plural spellings; the family exports the singular. Both, then.\nexport { PluginService as PluginsService, SettingService as SettingsService }\nexport const pluginsService = pluginService\nexport const settingsService = settingService\n","import type { ListMeta, Offer, Variant } from '../engine'\nimport { toMajor } from '../money'\nimport { BaseService } from './base.service'\n\n/**\n * Variants on their own, and the marketplace's offers on one.\n *\n * Svelte Commerce reads variants through their product, so this service is\n * for code written against GoCommerce: it answers the engine's own shapes —\n * numeric ids, money as `{ amount_minor, currency }` — with a major-unit\n * `amount` added beside each price so a template need not divide.\n */\nexport class VariantService extends BaseService {\n\t/** A product's variants, inactive ones included (filter on `active`), in the merchant's order. */\n\tasync list(productId: string | number, { page = 1, limit = 50 }: { page?: number; limit?: number } = {}) {\n\t\tconst env = await this.engine<Variant[] | null>('/api/variants', { query: { product_id: productId, page, limit } })\n\t\treturn { data: (env.data ?? []).map(withAmounts), meta: env.meta as ListMeta | undefined }\n\t}\n\n\tasync getOne(id: string | number) {\n\t\treturn withAmounts(await this.data<Variant>(`/api/variants/${encodeURIComponent(String(id))}`))\n\t}\n\n\t/**\n\t * What each approved seller asks for this variant, cheapest first. A cart\n\t * line takes a variant, not an offer, so this informs a shopper rather than\n\t * choosing who fulfils.\n\t */\n\tasync offers(variantId: string | number) {\n\t\tconst offers =\n\t\t\t(await this.data<Offer[] | null>(`/api/variants/${encodeURIComponent(String(variantId))}/offers`)) ?? []\n\t\treturn offers.map((o) => ({ ...o, price: { ...o.price, amount: toMajor(o.price) } }))\n\t}\n}\n\nfunction withAmounts(v: Variant) {\n\treturn {\n\t\t...v,\n\t\tprice: { ...v.price, amount: toMajor(v.price) },\n\t\tcompare_at_price: v.compare_at_price ? { ...v.compare_at_price, amount: toMajor(v.compare_at_price) } : undefined,\n\t}\n}\n\nexport const variantService = new VariantService()\n","import { storedCartId } from '../browser'\nimport { BaseService } from './base.service'\n\n/** Which WhatsApp boxes checkout shows. */\nexport type WhatsappConsentOffer = {\n\t/** The store sends order updates on WhatsApp: show the opt-in. */\n\tenabled: boolean\n\t/** It sends basket reminders too: show the marketing box as well. */\n\tmarketing: boolean\n}\n\n/** What the engine kept for a phone: the number as it reads it, in E.164. */\nexport type WhatsappConsent = {\n\tphone: string\n\torderUpdates: boolean\n\tmarketing: boolean\n}\n\n/**\n * The shopper's WhatsApp opt-in at checkout (ext/notify-whatsapp).\n *\n * The engine keeps the latest answer per phone, so an unticked box is sent as\n * `false` rather than left out: it is how a shopper who said yes last time\n * says no now.\n */\nexport class WhatsappService extends BaseService {\n\t/**\n\t * Whether to show the boxes. Never throws: an engine without the module, or\n\t * one that fails, answers both off, because checkout must not depend on it.\n\t */\n\tasync consentOffer(): Promise<WhatsappConsentOffer> {\n\t\ttry {\n\t\t\tconst d = await this.data<Partial<WhatsappConsentOffer> | null>('/x/notify-whatsapp/consent')\n\t\t\tconst enabled = d?.enabled === true\n\t\t\treturn { enabled, marketing: enabled && d?.marketing === true }\n\t\t} catch {\n\t\t\treturn { enabled: false, marketing: false }\n\t\t}\n\t}\n\n\t/**\n\t * Records both answers for the phone as typed, against the bag (with\n\t * `marketing`, the engine keeps the phone on it for basket reminders). Throws\n\t * the engine's 400 (`validation_failed`) when the phone is not a WhatsApp\n\t * number for the store's country.\n\t */\n\tasync setConsent({\n\t\tcartId,\n\t\tphone,\n\t\torderUpdates,\n\t\tmarketing,\n\t}: {\n\t\tcartId?: string | null\n\t\tphone: string\n\t\torderUpdates: boolean\n\t\tmarketing: boolean\n\t}): Promise<WhatsappConsent> {\n\t\tconst d = await this.data<{ phone: string; order_updates: boolean; marketing: boolean }>(\n\t\t\t'/x/notify-whatsapp/consent',\n\t\t\t{\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbody: {\n\t\t\t\t\tcart_id: cartId || storedCartId() || '',\n\t\t\t\t\tphone: String(phone ?? '').trim(),\n\t\t\t\t\torder_updates: orderUpdates === true,\n\t\t\t\t\tmarketing: marketing === true,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t\treturn { phone: d.phone, orderUpdates: d.order_updates, marketing: d.marketing }\n\t}\n}\n\nexport const whatsappService = new WhatsappService()\n","import type { Address, Cart, CheckoutResult, ListMeta, Order, PaymentIntent } from '../engine'\nimport type { Money } from '../money'\nimport { GoCommerceError } from '../errors'\nimport { toCart, toEngineAddress, toOrder } from '../map'\nimport { cartExtras, rememberCartId, rememberOrder, storedCartId, type StorefrontAddress } from '../browser'\nimport { BaseService } from './base.service'\n\n// ---------------------------------------------------------------- ext/b2b shapes\n\nexport type B2bRole = 'admin' | 'approver' | 'buyer'\n\nexport type Company = {\n\tid: number\n\tcode: string\n\tname: string\n\ttax_id: string\n\tstatus: 'active' | 'on_hold' | 'closed'\n\tgroup_id: number | null\n\t/** `null`: no account with the store — the company pays up front. */\n\tcredit_limit: Money | null\n\tnet_days: number\n\t/** `null`: a buyer never needs approval. */\n\tapproval_threshold: Money | null\n\trequire_po: boolean\n\tmember_count: number\n\t/** More than 0: the company is a dealer, and receives leads. */\n\tterritory_count: number\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Credit = {\n\tlimit: Money | null\n\toutstanding: Money\n\tavailable: Money | null\n\toverdue: Money\n\toverdue_orders: number\n\tnet_days: number\n}\n\nexport type Member = {\n\tcompany_id: number\n\tcustomer_id: number\n\temail: string\n\tconfirmed: boolean\n\tname: string\n\trole: B2bRole\n\tcreated_at: string\n}\n\nexport type Invitation = {\n\tid: number\n\tcompany_id: number\n\temail: string\n\trole: B2bRole\n\tinvited_by: string\n\texpires_at: string\n\taccepted_at?: string\n\tcreated_at: string\n}\n\nexport type CompanyOrder = {\n\torder_id: number\n\tnumber: string\n\tstatus: string\n\tpayment_status: string\n\ttotal: Money\n\tpo_number: string\n\tplaced_by: string\n\ton_account: boolean\n\tdue_at?: string\n\toverdue: boolean\n\tcompany_id: number\n\tcompany_name: string\n\tapproval_id?: number\n\tquote_id?: number\n\tcreated_at: string\n}\n\nexport type Approval = {\n\tid: number\n\tcompany_id: number\n\tkind: 'cart' | 'quote'\n\tquote_id?: number\n\tstatus: 'pending' | 'placing' | 'approved' | 'rejected' | 'cancelled'\n\trequested_by: number\n\trequested_by_email: string\n\tlines: { variant_id: number; sku: string; quantity: number; unit_price: Money }[]\n\tsubtotal: Money\n\ttotal: Money\n\tpayment_method: string\n\tpo_number: string\n\tdecided_by?: number\n\tdecided_at?: string\n\treason?: string\n\tlast_error?: string\n\torder_id?: number\n\torder_number?: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Quote = {\n\tid: number\n\tnumber: string\n\tcompany_id: number\n\tcompany_name: string\n\tstatus: 'requested' | 'quoted' | 'awaiting_approval' | 'accepted' | 'declined' | 'expired'\n\trequested_by: number\n\trequested_by_email: string\n\tnote: string\n\treply: string\n\tdeclined_by?: string\n\tlines: { variant_id: number; sku: string; title: string; quantity: number; unit_price: Money | null }[]\n\ttotal: Money | null\n\texpires_at?: string\n\tquoted_at?: string\n\taccepted_at?: string\n\torder_id?: number\n\torder_number?: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Lead = {\n\tid: number\n\tname: string\n\temail: string\n\tphone: string\n\tmessage: string\n\tcountry: string\n\tstate: string\n\tpostal_code: string\n\tvariant_id: number | null\n\tproduct_id: number | null\n\tproduct_title?: string\n\tvariant_sku?: string\n\tstatus: 'new' | 'contacted' | 'won' | 'lost'\n\tcompany_id: number | null\n\tcompany_name?: string\n\trouted_by: 'territory' | 'store' | 'unrouted'\n\tsource: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type RejectedLine = {\n\tsku: string\n\tvariant_id: number | null\n\tquantity: number\n\treason: 'not_found' | 'inactive' | 'insufficient_stock' | 'invalid'\n\tmessage: string\n}\n\ntype Paged<T> = { data: T[]; meta?: ListMeta }\n\ntype PlaceOptions = {\n\t/** An engine payment code; omitted, the company's account (`on_account`) when it has one. */\n\tpaymentMethod?: string\n\t/** Required when the company says so (`company.require_po`). */\n\tpoNumber?: string\n\tname?: string\n\tphone?: string\n\t/** Defaults to the address the checkout's address step kept for this cart. */\n\taddress?: StorefrontAddress | Address\n}\n\n/** A checkout or quote acceptance either placed an order or, for a buyer over the limit, asked for approval. */\nexport type B2bPlaced =\n\t| { kind: 'order'; orderNo: string; order: ReturnType<typeof toOrder>; payment: PaymentIntent }\n\t| { kind: 'approval'; approval: Approval }\n\n/**\n * Buying for a business (ext/b2b): a company with buyers in roles, orders on\n * account against a credit limit, approvals, quotes, a quick order by SKU, a\n * repeat order, and a dealer's leads.\n *\n * Every call but `submitLead` needs a signed-in shopper (ext/identity) who is\n * a member of a company; a signed-in account that is not answers 403, so\n * `me()` is how a storefront tells a business account from a consumer one.\n * Answers are the engine's own shapes — numeric ids, money as\n * `{ amount_minor, currency }` — except carts, which come back as the\n * storefront's bag so a quick-order page can hand them straight to it.\n */\nexport class B2bService extends BaseService {\n\t// ------------------------------------------------------------ company\n\n\t/** The company, the caller's role in it, and its credit: limit, outstanding, available, overdue. */\n\tasync me() {\n\t\tconst me = await this.data<{\n\t\t\tcompany: Company & { notes?: string; metadata?: unknown }\n\t\t\trole: B2bRole\n\t\t\tcredit: Credit\n\t\t}>('/x/b2b/me', { auth: true })\n\t\t// The engine answers the store's own notes on the company to its buyers;\n\t\t// they are not this storefront's to show.\n\t\tconst { notes: _notes, metadata: _metadata, ...company } = me.company\n\t\treturn { company: company as Company, role: me.role, credit: me.credit }\n\t}\n\n\tasync members() {\n\t\treturn (await this.data<Member[] | null>('/x/b2b/members', { auth: true })) ?? []\n\t}\n\n\t/** Admin only. Demoting the last admin is refused (409). */\n\tasync setMemberRole(customerId: number | string, role: B2bRole) {\n\t\treturn this.data<Member>(`/x/b2b/members/${id(customerId)}`, { method: 'PATCH', auth: true, body: { role } })\n\t}\n\n\t/** An admin removes anyone; any member may remove themselves. */\n\tasync removeMember(customerId: number | string) {\n\t\tawait this.engine(`/x/b2b/members/${id(customerId)}`, { method: 'DELETE', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ invitations\n\n\t/** Admin only. Open invitations: not accepted, not expired. */\n\tasync invitations() {\n\t\treturn (await this.data<Invitation[] | null>('/x/b2b/invitations', { auth: true })) ?? []\n\t}\n\n\t/** Admin only. Emails a link; a second invitation to the same address replaces the first. */\n\tasync invite({ email, role }: { email: string; role: B2bRole }) {\n\t\treturn this.data<Invitation>('/x/b2b/invitations', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { email: String(email ?? '').trim(), role },\n\t\t})\n\t}\n\n\tasync withdrawInvitation(invitationId: number | string) {\n\t\tawait this.engine(`/x/b2b/invitations/${id(invitationId)}`, { method: 'DELETE', auth: true })\n\t}\n\n\t/**\n\t * The token from the invitation email, accepted by the account it was sent\n\t * to — which also confirms that account's email address.\n\t */\n\tasync acceptInvitation(token: string) {\n\t\treturn this.data<Member>('/x/b2b/invitations/accept', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { token: String(token ?? '').trim() },\n\t\t})\n\t}\n\n\t// ------------------------------------------------------------ filling a basket\n\n\t/**\n\t * A quick order: up to 500 lines by SKU or variant id, into the bag (or a new\n\t * one), at the company's prices. A line that will not go in is reported in\n\t * `rejected` with its reason; the rest are added.\n\t */\n\tasync addLines({\n\t\tcartId,\n\t\tlines,\n\t}: {\n\t\tcartId?: string\n\t\tlines: { sku?: string; variantId?: number | string; quantity: number }[]\n\t}) {\n\t\tconst res = await this.data<{ cart: Cart; rejected: RejectedLine[] | null }>('/x/b2b/cart/lines', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\t...((cartId ?? storedCartId()) ? { cart_id: cartId ?? storedCartId() } : {}),\n\t\t\t\tlines: (lines ?? []).map((l) => ({\n\t\t\t\t\t...(l.variantId ? { variant_id: Number(l.variantId) } : {}),\n\t\t\t\t\t...(l.sku ? { sku: String(l.sku).trim() } : {}),\n\t\t\t\t\tquantity: Number(l.quantity),\n\t\t\t\t})),\n\t\t\t},\n\t\t})\n\t\trememberCartId(res.cart.id)\n\t\treturn { cart: toCart(res.cart, cartExtras(res.cart.id)), rejected: res.rejected ?? [] }\n\t}\n\n\t/** A past order's lines in a new bag, at today's prices. Nothing is placed. */\n\tasync reorder(orderId: number | string) {\n\t\tconst res = await this.data<{ cart: Cart; rejected: RejectedLine[] | null }>(\n\t\t\t`/x/b2b/orders/${id(orderId)}/reorder`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tauth: true,\n\t\t\t},\n\t\t)\n\t\trememberCartId(res.cart.id)\n\t\treturn { cart: toCart(res.cart, cartExtras(res.cart.id)), rejected: res.rejected ?? [] }\n\t}\n\n\t// ------------------------------------------------------------ placing an order\n\n\t/**\n\t * Places the bag through the company: on account by default, with a PO\n\t * number, optionally only some lines (`lineIds`). A buyer over the company's\n\t * approval threshold gets `{ kind: 'approval' }` instead of an order — the\n\t * bag stays as it was, and an approver places it later.\n\t *\n\t * Over the credit limit is 403 `credit_limit_exceeded`; `me().credit` says\n\t * how much is available before the shopper tries.\n\t */\n\tasync checkout({\n\t\tcartId,\n\t\tlineIds,\n\t\tshippingRateId,\n\t\treturnUrl,\n\t\tpaymentData,\n\t\t...opts\n\t}: PlaceOptions & {\n\t\tcartId?: string\n\t\tlineIds?: (number | string)[]\n\t\tshippingRateId?: number | string\n\t\treturnUrl?: string\n\t\tpaymentData?: Record<string, string>\n\t} = {}): Promise<B2bPlaced> {\n\t\tconst cart = cartId || storedCartId()\n\t\tif (!cart) throw new GoCommerceError('Your bag is empty.', 400)\n\t\tconst extras = cartExtras(cart)\n\t\tconst rate = shippingRateId ?? extras.shippingRateId\n\t\tconst body = {\n\t\t\tcart_id: cart,\n\t\t\t...this.placeBody(opts, extras.shippingAddress ?? undefined),\n\t\t\t...(rate ? { shipping_rate_id: Number(rate) } : {}),\n\t\t\t...(lineIds?.length ? { line_ids: lineIds.map(Number) } : {}),\n\t\t\t...(returnUrl ? { return_url: returnUrl } : {}),\n\t\t\t...(paymentData ? { payment_data: paymentData } : {}),\n\t\t}\n\t\tconst res = await this.data<CheckoutResult & { approval?: Approval }>('/x/b2b/checkout', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody,\n\t\t\theaders: { 'Idempotency-Key': attemptKey(`b2b:${JSON.stringify(body)}`) },\n\t\t})\n\t\treturn this.placed(res, cart)\n\t}\n\n\t// ------------------------------------------------------------ the company's orders\n\n\t/** Admins and approvers see the company's; a buyer sees their own. `q` matches the number, PO or email. */\n\tasync orders({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t\tq,\n\t\toverdue,\n\t}: { page?: number; limit?: number; q?: string; overdue?: boolean } = {}) {\n\t\treturn this.engine<CompanyOrder[]>('/x/b2b/orders', {\n\t\t\tauth: true,\n\t\t\tquery: { page, limit, q, ...(overdue ? { overdue: 'true' } : {}) },\n\t\t}) as Promise<Paged<CompanyOrder>>\n\t}\n\n\t// ------------------------------------------------------------ approvals\n\n\tasync approvals({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t\tstatus,\n\t}: { page?: number; limit?: number; status?: Approval['status'] } = {}) {\n\t\treturn this.engine<Approval[]>('/x/b2b/approvals', { auth: true, query: { page, limit, status } }) as Promise<\n\t\t\tPaged<Approval>\n\t\t>\n\t}\n\n\tasync approval(approvalId: number | string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}`, { auth: true })\n\t}\n\n\t/**\n\t * Admin or approver: places the requested order at the prices it was\n\t * requested at. Credit limits and holds still apply. The payment intent is\n\t * the approver's to act on — for an account order there is nothing to do.\n\t */\n\tasync approve(approvalId: number | string) {\n\t\tconst res = await this.data<CheckoutResult & { approval: Approval }>(`/x/b2b/approvals/${id(approvalId)}/approve`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t})\n\t\treturn { approval: res.approval, orderNo: res.order.number, order: toOrder(res.order), payment: res.payment }\n\t}\n\n\tasync reject(approvalId: number | string, reason?: string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}/reject`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\t...(reason ? { body: { reason } } : {}),\n\t\t})\n\t}\n\n\t/** The buyer who asked withdraws the request. */\n\tasync cancelApproval(approvalId: number | string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}/cancel`, { method: 'POST', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ quotes\n\n\tasync quotes({ page = 1, limit = 20, status }: { page?: number; limit?: number; status?: Quote['status'] } = {}) {\n\t\treturn this.engine<Quote[]>('/x/b2b/quotes', { auth: true, query: { page, limit, status } }) as Promise<\n\t\t\tPaged<Quote>\n\t\t>\n\t}\n\n\tasync quote(quoteId: number | string) {\n\t\treturn this.data<Quote>(`/x/b2b/quotes/${id(quoteId)}`, { auth: true })\n\t}\n\n\t/** Asks the store to price these lines. The store answers with unit prices and an expiry. */\n\tasync requestQuote({ lines, note }: { lines: { variantId: number | string; quantity: number }[]; note?: string }) {\n\t\treturn this.data<Quote>('/x/b2b/quotes', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\tlines: (lines ?? []).map((l) => ({ variant_id: Number(l.variantId), quantity: Number(l.quantity) })),\n\t\t\t\t...(note ? { note } : {}),\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Places the quote at its agreed prices — or, for a buyer over the threshold, asks for approval. */\n\tasync acceptQuote(quoteId: number | string, opts: PlaceOptions = {}): Promise<B2bPlaced> {\n\t\tconst res = await this.data<CheckoutResult & { approval?: Approval }>(`/x/b2b/quotes/${id(quoteId)}/accept`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: this.placeBody(opts),\n\t\t})\n\t\treturn this.placed(res)\n\t}\n\n\tasync declineQuote(quoteId: number | string) {\n\t\treturn this.data<Quote>(`/x/b2b/quotes/${id(quoteId)}/decline`, { method: 'POST', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ dealer leads\n\n\t/**\n\t * The public \"find a dealer\" form: no account needed. The engine routes it to\n\t * the dealer whose territory covers the address — or keeps it — and answers\n\t * the same either way, so the form never reveals who got it.\n\t */\n\tasync submitLead(lead: {\n\t\tname?: string\n\t\temail?: string\n\t\tphone?: string\n\t\tmessage?: string\n\t\tcountry?: string\n\t\tstate?: string\n\t\tpostalCode?: string\n\t\tproductId?: number | string\n\t\tvariantId?: number | string\n\t\tsource?: string\n\t}) {\n\t\treturn this.data<{ accepted: boolean }>('/x/b2b/leads', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\t...(lead.name ? { name: lead.name } : {}),\n\t\t\t\t...(lead.email ? { email: lead.email } : {}),\n\t\t\t\t...(lead.phone ? { phone: lead.phone } : {}),\n\t\t\t\t...(lead.message ? { message: lead.message } : {}),\n\t\t\t\t...(lead.country ? { country: lead.country } : {}),\n\t\t\t\t...(lead.state ? { state: lead.state } : {}),\n\t\t\t\t...(lead.postalCode ? { postal_code: lead.postalCode } : {}),\n\t\t\t\t...(lead.productId ? { product_id: Number(lead.productId) } : {}),\n\t\t\t\t...(lead.variantId ? { variant_id: Number(lead.variantId) } : {}),\n\t\t\t\t...(lead.source ? { source: lead.source } : {}),\n\t\t\t},\n\t\t})\n\t}\n\n\t/** A dealer's admins and approvers: the leads routed to their company. */\n\tasync leads({ page = 1, limit = 20, status }: { page?: number; limit?: number; status?: Lead['status'] } = {}) {\n\t\treturn this.engine<Lead[]>('/x/b2b/leads', { auth: true, query: { page, limit, status } }) as Promise<Paged<Lead>>\n\t}\n\n\tasync setLeadStatus(leadId: number | string, status: Lead['status']) {\n\t\treturn this.data<Lead>(`/x/b2b/leads/${id(leadId)}`, { method: 'PATCH', auth: true, body: { status } })\n\t}\n\n\t// ------------------------------------------------------------ internals\n\n\t/** The fields checkout and quote acceptance share. Only declared ones: the engine refuses the rest. */\n\tprivate placeBody(opts: PlaceOptions, fallback?: StorefrontAddress) {\n\t\tconst raw = opts.address ?? fallback\n\t\tif (!raw) throw new GoCommerceError('Add a delivery address first.', 400)\n\t\tconst address = 'line1' in raw ? (raw as Address) : toEngineAddress(raw as StorefrontAddress)\n\t\treturn {\n\t\t\taddress,\n\t\t\t...(opts.paymentMethod ? { payment_method: String(opts.paymentMethod).toLowerCase() } : {}),\n\t\t\t...(opts.poNumber ? { po_number: String(opts.poNumber).trim() } : {}),\n\t\t\t...((opts.name ?? address.name) ? { name: opts.name ?? address.name } : {}),\n\t\t\t...((opts.phone ?? address.phone) ? { phone: opts.phone ?? address.phone } : {}),\n\t\t}\n\t}\n\n\tprivate placed(res: Partial<CheckoutResult> & { approval?: Approval }, cartId?: string): B2bPlaced {\n\t\tif (res.approval && !res.order) return { kind: 'approval', approval: res.approval }\n\t\tconst order = res.order as Order\n\t\tif (order.access_token && cartId) {\n\t\t\trememberOrder({ number: order.number, token: order.access_token, cartId, reference: res.payment?.reference })\n\t\t}\n\t\treturn { kind: 'order', orderNo: order.number, order: toOrder(order), payment: res.payment as PaymentIntent }\n\t}\n}\n\nconst id = (v: number | string) => encodeURIComponent(String(v))\n\n/**\n * One Idempotency-Key per distinct request, kept for the page's life: a retry\n * of the same checkout — a double click, a timeout — resumes it rather than\n * placing a second order, and a changed request gets a new key, since the\n * engine refuses a key replayed with a different body.\n */\nconst keys = new Map<string, string>()\nfunction attemptKey(request: string): string {\n\tlet key = keys.get(request)\n\tif (!key) {\n\t\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n\t\tkey = c?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n\t\tkeys.set(request, key)\n\t}\n\treturn key\n}\n\nexport const b2bService = new B2bService()\n"]}
|
|
1
|
+
{"version":3,"sources":["../../src/errors.ts","../../src/rest-guard.ts","../../src/browser.ts","../../src/services/base.service.ts","../../src/money.ts","../../src/map.ts","../../src/cache.ts","../../src/services/facts.ts","../../src/services/catalog.ts","../../src/services/product-service.ts","../../src/services/search-service.ts","../../src/services/meilisearch-service.ts","../../src/services/category-service.ts","../../src/services/collection-service.ts","../../src/services/cart-service.ts","../../src/services/customizer-service.ts","../../src/services/checkout-service.ts","../../src/services/payment-method-service.ts","../../src/services/coupon-service.ts","../../src/services/order-service.ts","../../src/services/user-service.ts","../../src/services/address-service.ts","../../src/services/wishlist-service.ts","../../src/services/review-service.ts","../../src/services/google-review-service.ts","../../src/services/menu-service.ts","../../src/static-store.ts","../../src/services/newsletter-service.ts","../../src/services/store-service.ts","../../src/services/page-service.ts","../../src/services/layout-service.ts","../../src/services/vendor-service.ts","../../src/services/misc-services.ts","../../src/services/variant-service.ts","../../src/services/whatsapp-service.ts","../../src/services/b2b-service.ts"],"names":["id","c","page","limit","env","quote","reported","clean","enc","known","keep"],"mappings":";AAeO,IAAM,eAAA,GAAN,cAA8B,KAAA,CAAM;AAAA,EACjC,MAAA;AAAA,EACA,IAAA;AAAA,EACA,OAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,IAAA,EAAe,OAAA,EAAmB;AAC9E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,iBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AACd,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AAAA,EAChB;AACD,CAAA;AAWO,IAAM,iBAAA,GAAN,cAAgC,KAAA,CAAM;AAAA,EACnC,OAAA;AAAA,EACA,MAAA;AAAA,EAET,WAAA,CAAY,OAAA,EAAiB,MAAA,EAAgB,MAAA,EAAiB;AAC7D,IAAA,KAAA,CAAM,CAAA,EAAG,OAAO,CAAA,CAAA,EAAI,MAAM,CAAA,iCAAA,EAAoC,SAAS,CAAA,EAAA,EAAK,MAAM,CAAA,CAAA,GAAK,GAAG,CAAA,CAAE,CAAA;AAC5F,IAAA,IAAA,CAAK,IAAA,GAAO,mBAAA;AACZ,IAAA,IAAA,CAAK,OAAA,GAAU,OAAA;AACf,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EACf;AACD,CAAA;;;AC3BA,IAAM,mBAAA,uBAA0B,GAAA,CAAI;AAAA,EACnC,KAAA;AAAA,EACA,MAAA;AAAA,EACA,gBAAA;AAAA,EACA,aAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EACA,QAAA;AAAA,EAC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mB,MAAA,CAAO,CAAC,CAAC,CAAA;AAQ/D,IAAM,IAAA,uBAAW,GAAA,EAAoB;AACrC,SAAS,WAAW,OAAA,EAAyB;AAC5C,EAAA,IAAI,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,OAAO,CAAA;AAC1B,EAAA,IAAI,CAAC,GAAA,EAAK;AACT,IAAA,MAAM,IAAK,UAAA,CAA0D,MAAA;AACrE,IAAA,GAAA,GAAM,GAAG,UAAA,IAAa,IAAK,GAAG,IAAA,CAAK,GAAA,GAAM,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,QAAO,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,KAAA,CAAM,CAAC,CAAC,CAAA,CAAA;AAC5F,IAAA,IAAA,CAAK,GAAA,CAAI,SAAS,GAAG,CAAA;AAAA,EACtB;AACA,EAAA,OAAO,GAAA;AACR;AAEO,IAAM,UAAA,GAAa,IAAI,UAAA","file":"index.js","sourcesContent":["/**\n * The two ways a call through this connector fails.\n *\n * Both carry `message`, because the storefront shows `err.message` in a toast\n * and has no other field it reliably reads.\n */\n\n/**\n * What the engine refused, in a shape the storefront can show a shopper.\n *\n * `status` travels because the difference between 404 and 409 is the\n * difference between \"that product is gone\" and \"somebody just bought the last\n * one\", and a storefront renders those differently. `code` is the engine's own\n * taxonomy (`not_found`, `validation`, `conflict`, `unauthorized`, …).\n */\nexport class GoCommerceError extends Error {\n\treadonly status: number\n\treadonly code: string | undefined\n\treadonly details: unknown\n\n\tconstructor(message: string, status: number, code?: string, details?: unknown) {\n\t\tsuper(message)\n\t\tthis.name = 'GoCommerceError'\n\t\tthis.status = status\n\t\tthis.code = code\n\t\tthis.details = details\n\t}\n}\n\n/**\n * A storefront feature this engine has no model for — reels, chat, a vendor's\n * commission statement — or one that lives in a module this particular build\n * did not compile in.\n *\n * The name is the one every connector in the family throws, so a storefront\n * that branches on `err.name === 'NotSupportedError'` treats GoCommerce the same\n * as the rest.\n */\nexport class NotSupportedError extends Error {\n\treadonly service: string\n\treadonly method: string\n\n\tconstructor(service: string, method: string, detail?: string) {\n\t\tsuper(`${service}.${method}() is not supported by GoCommerce${detail ? `: ${detail}` : '.'}`)\n\t\tthis.name = 'NotSupportedError'\n\t\tthis.service = service\n\t\tthis.method = method\n\t}\n}\n","/**\n * Litekart REST paths, intercepted.\n *\n * Every connector in the family exposes `get/post/put/patch/delete(path)` on\n * its BaseService because Litekart's does, and a little storefront code still\n * calls them with a Litekart path — `storeService.post('/api/…')`. Those paths\n * are relative, so they would land on the storefront's own origin, where\n * nothing answers.\n *\n * GoCommerce's own routes also start with `/api/`, which is why this connector\n * never sends an engine request through those verbs: every engine call goes\n * through `BaseService.engine()` with an absolute URL, and the storefront's own\n * guard (which patches the same verbs) cannot reach it either. What arrives\n * here is only ever an inherited Litekart path.\n *\n * Reads for a collection resolve empty (a store legitimately has none); reads\n * for one record and every write throw, because a blank detail page reads as\n * broken and a silent success would tell a shopper their enquiry was saved when\n * nothing left the browser. Each distinct path is reported once.\n */\n\nconst COLLECTION_SEGMENTS = new Set([\n\t'all',\n\t'list',\n\t'list-by-parent',\n\t'list-public',\n\t'latest',\n\t'search',\n\t'public',\n\t'public-details',\n\t'me',\n\t'multiple',\n])\n\nconst emptyResult = () => ({ data: [], count: 0, pageSize: 0, noOfPage: 0, page: 1 })\n\nconst addressesOneRecord = (url: string) => {\n\tconst segments = url.split('?')[0].split('/').filter(Boolean)\n\tif (segments.length < 3) return false\n\treturn !COLLECTION_SEGMENTS.has(segments[segments.length - 1].toLowerCase())\n}\n\nconst reported = new Set<string>()\n\nconst report = (method: string, url: string) => {\n\tconst key = `${method} ${url.split('?')[0]}`\n\tif (reported.has(key)) return\n\treported.add(key)\n\tconsole.warn(\n\t\t`[gocommerce] no native implementation for \\`${key}\\` — that is a Litekart REST path, and it was not called.`,\n\t)\n}\n\n/**\n * Answers a Litekart REST path from data the storefront holds (menus,\n * countries, plugin toggles…). Return `undefined` to fall through.\n */\nexport type RestResolver = (url: string) => Promise<unknown> | unknown | undefined\n\nlet localResolver: RestResolver | undefined\n\nexport const serveRestLocally = (resolver: RestResolver) => {\n\tlocalResolver = resolver\n}\n\nexport const resolveRestLocally = async (method: string, url: string) => {\n\tif (method === 'get') {\n\t\tconst local = await localResolver?.(url)\n\t\tif (local !== undefined) return local\n\t}\n\treport(method, url)\n\tif (method !== 'get' || addressesOneRecord(url)) {\n\t\tthrow new Error(`This feature is not available on this store (gocommerce).`)\n\t}\n\treturn emptyResult()\n}\n","/**\n * The state this connector keeps in the shopper's browser, and only there.\n *\n * The storefront renders some services from a server singleton shared by every\n * shopper, so nothing about one shopper may live in module scope: a token held\n * in a static field would be served to the next request. Everything here is\n * read from `localStorage` or `document.cookie` at the moment it is needed, and\n * on the server every reader answers \"nothing\".\n *\n * What lives here, and why the engine does not hold it:\n *\n * - the account session token — ext/identity is bearer-only and sets no cookie;\n * - the `me` and `connect.sid` cookies — the storefront's own idea of who is\n * signed in, which every connector in the family writes itself;\n * - `cart_id` — the storefront reads it, the connector writes it;\n * - per-cart checkout details — the engine's cart holds lines and an email, and\n * takes the address, phone and delivery choice only in the checkout request,\n * so they are kept here until then;\n * - order access tokens — returned once, at checkout, and the only way a guest\n * can read an order back;\n * - the wishlist token — ext/wishlist keys a list by its own token.\n */\nimport type { AppliedDiscount, AuthResponse, Customer } from './engine'\n\nexport const inBrowser = (): boolean => typeof window !== 'undefined' && typeof document !== 'undefined'\n\nexport function readLocal(key: string): string | null {\n\tif (!inBrowser()) return null\n\ttry {\n\t\treturn window.localStorage.getItem(key)\n\t} catch {\n\t\treturn null\n\t}\n}\n\nexport function writeLocal(key: string, value: string): void {\n\tif (!inBrowser()) return\n\ttry {\n\t\twindow.localStorage.setItem(key, value)\n\t} catch {\n\t\t// Private mode or a full quota. The call it belongs to still succeeds;\n\t\t// only the memory of it is lost.\n\t}\n}\n\nexport function removeLocal(key: string): void {\n\tif (!inBrowser()) return\n\ttry {\n\t\twindow.localStorage.removeItem(key)\n\t} catch {\n\t\t// see writeLocal\n\t}\n}\n\nfunction readJSON<T>(key: string): T | null {\n\tconst raw = readLocal(key)\n\tif (!raw) return null\n\ttry {\n\t\treturn JSON.parse(raw) as T\n\t} catch {\n\t\treturn null\n\t}\n}\n\nconst YEAR = 60 * 60 * 24 * 365\n\nfunction setCookie(name: string, value: string, maxAge = YEAR): void {\n\tif (!inBrowser()) return\n\tdocument.cookie = `${name}=${value}; path=/; max-age=${maxAge}; samesite=lax`\n}\n\nfunction clearCookie(name: string): void {\n\tif (!inBrowser()) return\n\tdocument.cookie = `${name}=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT`\n}\n\nexport function readCookie(name: string): string | null {\n\tif (!inBrowser()) return null\n\tfor (const pair of document.cookie.split(';')) {\n\t\tconst at = pair.indexOf('=')\n\t\tif (at < 0) continue\n\t\tif (pair.slice(0, at).trim() === name) return pair.slice(at + 1).trim()\n\t}\n\treturn null\n}\n\n// ---------------------------------------------------------------- session\n\nconst TOKEN = 'gocommerce_token'\n\n/** The ext/identity bearer token, when a shopper is signed in in this browser. */\nexport const sessionToken = (): string | null => readLocal(TOKEN)\n\n/**\n * The user object the storefront keeps in its `me` cookie. `userId` is its\n * signed-in test and `role: 'USER'` its shopper test; the rest fills forms.\n */\nexport function toMe(c: Customer) {\n\tconst [firstName, ...rest] = (c.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: String(c.id),\n\t\tuserId: String(c.id),\n\t\temail: c.email,\n\t\tphone: c.phone || null,\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\tname: c.name ?? '',\n\t\tfullName: c.name ?? '',\n\t\tavatar: null,\n\t\trole: 'USER',\n\t\temailVerified: c.email_verified,\n\t\tphoneVerified: !!c.phone_verified,\n\t\tstoreId: null,\n\t}\n}\n\nexport type Me = ReturnType<typeof toMe>\n\n/**\n * Signs this browser in: the token for the engine, the two cookies for the\n * storefront. `connect.sid` carries no secret — the storefront's server only\n * checks that it exists — so it holds a marker rather than the token, which\n * would otherwise ride along on every request to the storefront's origin.\n */\nexport function startSession(auth: AuthResponse): Me {\n\twriteLocal(TOKEN, auth.token)\n\tconst me = toMe(auth.record)\n\tconst expires = Math.max(60, Math.floor((Date.parse(auth.expires_at) - Date.now()) / 1000)) || YEAR\n\tsetCookie('me', encodeURIComponent(JSON.stringify(me)), expires)\n\tsetCookie('connect.sid', 'gocommerce', expires)\n\treturn me\n}\n\n/** Refreshes the `me` cookie after a profile change, keeping the session. */\nexport function updateMe(c: Customer): Me {\n\tconst me = toMe(c)\n\tsetCookie('me', encodeURIComponent(JSON.stringify(me)))\n\treturn me\n}\n\nexport function endSession(): void {\n\tremoveLocal(TOKEN)\n\tclearCookie('me')\n\tclearCookie('connect.sid')\n}\n\n/** The `me` cookie, decoded — the name and email a review is signed with. */\nexport function currentMe(): Partial<Me> | null {\n\tconst raw = readCookie('me')\n\tif (!raw) return null\n\ttry {\n\t\treturn JSON.parse(decodeURIComponent(raw))\n\t} catch {\n\t\treturn null\n\t}\n}\n\n/**\n * The browser Meta's pixel ran in, which the engine's Conversions API module\n * reads off the order as `metadata.meta_capi` (D160): Meta's own first-party\n * cookies, the user agent and the page. Only where the pixel is running on this\n * page and its `_fbp` cookie is there: the storefront starts the pixel only\n * where the shopper allows ad cookies, and the cookie outlives a choice taken\n * back, so the server sends a purchase exactly when the browser was allowed\n * to. The page goes without its query, which can carry anything.\n */\nexport function metaBrowser(): Record<string, string> | undefined {\n\tconst fbp = readCookie('_fbp')\n\tif (!fbp || typeof (window as { fbq?: unknown }).fbq !== 'function') return undefined\n\tconst fbc = readCookie('_fbc')\n\treturn {\n\t\tfbp,\n\t\t...(fbc ? { fbc } : {}),\n\t\tclient_user_agent: window.navigator.userAgent,\n\t\tevent_source_url: window.location.origin + window.location.pathname,\n\t}\n}\n\n// ------------------------------------------------------------- attribution\n\n/**\n * Where the shopper came from, as the storefront recorded it on arrival: the first visit with a\n * source in the last 30 days and the latest, under `gc_attribution` in this browser's storage.\n * The storefront writes it only with the shopper's leave for analytics, and it goes nowhere but\n * the store's own checkout (GoCommerce D168).\n *\n * Only the names the engine reads are passed on, each a short string, and a visit older than 30\n * days is dropped here as well as there, so a tab left open for a month does not credit an old ad.\n */\nexport const ATTRIBUTION_KEY = 'gc_attribution'\nconst ATTRIBUTION_DAYS = 30\nconst TOUCH_FIELDS = [\n\t'utm_source',\n\t'utm_medium',\n\t'utm_campaign',\n\t'utm_content',\n\t'utm_term',\n\t'gclid',\n\t'gbraid',\n\t'wbraid',\n\t'fbclid',\n\t'ttclid',\n\t'msclkid',\n\t'referrer',\n\t'at',\n] as const\n\ntype Touch = Partial<Record<(typeof TOUCH_FIELDS)[number], string>>\n\nfunction cleanTouch(raw: unknown, now: number): Touch | undefined {\n\tif (!raw || typeof raw !== 'object') return undefined\n\tconst at = Date.parse(String((raw as Touch).at ?? ''))\n\t// A date ahead of this clock by more than a day would never expire.\n\tif (!Number.isFinite(at) || now - at > ATTRIBUTION_DAYS * 86_400_000 || at - now > 86_400_000) return undefined\n\tconst out: Touch = {}\n\tfor (const k of TOUCH_FIELDS) {\n\t\tconst v = (raw as Record<string, unknown>)[k]\n\t\tif (typeof v === 'string' && v.trim()) out[k] = v.trim().slice(0, 200)\n\t}\n\t// A visit naming no source is none.\n\treturn Object.keys(out).length > 1 ? out : undefined\n}\n\nexport function landingAttribution(now = Date.now()): { first?: Touch; last?: Touch } | undefined {\n\tconst saved = readJSON<{ first?: unknown; last?: unknown }>(ATTRIBUTION_KEY)\n\tconst last = cleanTouch(saved?.last, now)\n\t// A stale first visit leaves the last one as the first in the window.\n\tconst first = cleanTouch(saved?.first, now) ?? last\n\tif (!first && !last) return undefined\n\treturn { ...(first ? { first } : {}), ...(last ? { last } : {}) }\n}\n\n// ---------------------------------------------------------------- cart\n\n/** `localStorage.cart_id`, the storefront's own key, with its stale spellings refused. */\nexport function storedCartId(): string | null {\n\tconst v = readLocal('cart_id')\n\tif (!v || v === 'undefined' || v === 'null') return null\n\treturn v\n}\n\nexport const rememberCartId = (id: string): void => writeLocal('cart_id', id)\n\n/** The storefront's address shape, as its checkout form builds it. */\nexport type StorefrontAddress = {\n\tid?: string\n\tfirstName?: string\n\tlastName?: string\n\temail?: string\n\tphone?: string\n\taddress_1?: string\n\taddress_2?: string\n\tlocality?: string\n\tcity?: string\n\tstate?: string\n\tzip?: string\n\tcountry?: string\n\tcountryCode?: string\n\t[key: string]: unknown\n}\n\nexport type CartExtras = {\n\tphone?: string\n\tshippingAddress?: StorefrontAddress | null\n\tbillingAddress?: StorefrontAddress | null\n\tshippingRateId?: string | null\n\tshippingRate?: { id: string; name: string; minor: number; currency: string } | null\n\tdiscount?: AppliedDiscount | null\n\t/**\n\t * The Idempotency-Key of the last checkout attempt, the body it was sent with, and where\n\t * Meta's pixel ran then, which a retry sends again unchanged.\n\t */\n\tattempt?: { key: string; body: string; meta?: Record<string, string>; attribution?: Record<string, unknown> } | null\n}\n\nconst extrasKey = (cartId: string) => `gocommerce_cart_${cartId}`\n\nexport const cartExtras = (cartId: string): CartExtras => readJSON<CartExtras>(extrasKey(cartId)) ?? {}\n\nexport function saveCartExtras(cartId: string, patch: CartExtras): CartExtras {\n\tconst next = { ...cartExtras(cartId), ...patch }\n\twriteLocal(extrasKey(cartId), JSON.stringify(next))\n\treturn next\n}\n\nexport const forgetCartExtras = (cartId: string): void => removeLocal(extrasKey(cartId))\n\n// ---------------------------------------------------------------- orders\n\ntype PlacedOrder = { number: string; token: string; cartId: string; reference?: string }\n\nconst ORDERS = 'gocommerce_orders'\n\nexport const placedOrders = (): PlacedOrder[] => readJSON<PlacedOrder[]>(ORDERS) ?? []\n\n/**\n * Keeps an order's access token. The engine returns it exactly once — a\n * replayed checkout leaves it out — and without it a guest cannot read the\n * order back, so losing it here loses the order.\n */\nexport function rememberOrder(o: PlacedOrder): void {\n\tconst kept = placedOrders().filter((p) => p.number !== o.number)\n\t// Bounded: a shared computer should not accumulate a history forever.\n\twriteLocal(ORDERS, JSON.stringify([o, ...kept].slice(0, 50)))\n}\n\nexport const placedOrder = (number: string): PlacedOrder | undefined => placedOrders().find((p) => p.number === number)\n\nexport const placedOrderForCart = (cartId: string): PlacedOrder | undefined =>\n\tplacedOrders().find((p) => p.cartId === cartId)\n\nexport const placedOrderByReference = (reference: string): PlacedOrder | undefined =>\n\tplacedOrders().find((p) => p.reference === reference)\n\n// ---------------------------------------------------------------- wishlist\n\nconst WISHLIST = 'gocommerce_wishlist'\nexport const wishlistToken = (): string | null => readLocal(WISHLIST)\nexport const rememberWishlistToken = (token: string): void => writeLocal(WISHLIST, token)\nexport const forgetWishlistToken = (): void => removeLocal(WISHLIST)\n","import type { Credentials } from '../config'\nimport type { Envelope } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { resolveRestLocally } from '../rest-guard'\nimport { currentMe, sessionToken } from '../browser'\n\ntype Query = Record<string, string | number | boolean | null | undefined | (string | number)[]>\n\nexport type EngineRequest = {\n\tmethod?: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'\n\tquery?: Query\n\tbody?: unknown\n\theaders?: Record<string, string>\n\t/** Send the signed-in shopper's bearer token. Only ext/identity reads it. */\n\tauth?: boolean\n}\n\n/**\n * A media URL the shopper's browser can load. The engine answers its own\n * uploads root-relative (`/media/ab12.png`), which a browser resolves against\n * the storefront's origin, where no such file is. Through the proxy path when\n * one is set — a root-relative path that reads the same in SSR and in the\n * browser, so hydration agrees — and otherwise from the engine's origin.\n * Absolute URLs, such as pictures the media library links rather than holds,\n * pass through untouched.\n */\nexport function mediaUrl(url: string | null | undefined): string | null {\n\tif (!url) return null\n\tif (!url.startsWith('/') || url.startsWith('//')) return url\n\tconst { apiUrl, proxyPath } = BaseService.getCredentials()\n\treturn (proxyPath || apiUrl || '').trim().replace(/\\/+$/, '') + url\n}\n\n/**\n * BaseService — the one place this connector talks to the engine.\n *\n * - Credentials arrive through the static `setCredentials` (both hooks), never\n * a constructor, and merge: the storefront drops unset variables rather than\n * sending `undefined`, so a second call must not erase the first.\n * - Server-side, a service is built with SvelteKit's `fetch`; client-side, the\n * prebuilt singletons use the global one. Either way it is called with the\n * global object as receiver, because the browser's native fetch throws\n * \"Illegal invocation\" when called as a method of anything else.\n * - Every engine call goes through `engine()`, with an absolute URL. The\n * engine's own routes start with `/api/`, and the storefront patches this\n * class's `get/post/put/patch/delete` to swallow any relative `/api/` path\n * (see rest-guard.ts), so those verbs are kept for the Litekart paths the\n * storefront still sends and never used for the engine.\n * - Failures throw a `GoCommerceError`: an `Error` with the engine's message,\n * status and code, which is what the storefront toasts.\n */\nexport class BaseService {\n\tprivate static _credentials: Credentials = { apiUrl: '' }\n\tprotected _fetch: typeof fetch\n\n\tconstructor(fetchFn?: typeof fetch) {\n\t\tthis._fetch = fetchFn ?? ((input, init) => globalThis.fetch(input, init))\n\t}\n\n\tstatic setCredentials(creds: Partial<Credentials>): void {\n\t\tBaseService._credentials = { ...BaseService._credentials, ...creds }\n\t}\n\n\tstatic getCredentials(): Credentials {\n\t\treturn BaseService._credentials\n\t}\n\n\tprotected get creds(): Credentials {\n\t\treturn BaseService._credentials\n\t}\n\n\t/**\n\t * The store this call is for: the request host's subdomain under\n\t * `baseDomain`, else the static `store`, else the host itself when it is a\n\t * store's own domain (the engine answers only a verified one). Read per call,\n\t * never stored on the instance, because the server shares one process (and\n\t * one credentials object) across every concurrent request and each may be\n\t * for a different host.\n\t */\n\tprotected get store(): string | undefined {\n\t\tconst { baseDomain, store } = this.creds\n\t\tconst host = typeof window !== 'undefined' ? window.location?.hostname : requestHost?.()\n\t\treturn storeForHost(host, baseDomain) ?? store ?? ownDomain(host, baseDomain)\n\t}\n\n\t/**\n\t * The engine's base URL from wherever this code runs. In the browser a\n\t * configured proxy path wins, because the engine answers no CORS preflight.\n\t */\n\tprotected engineBase(): string {\n\t\tconst { apiUrl, proxyPath } = this.creds\n\t\tif (proxyPath && typeof window !== 'undefined' && window.location) {\n\t\t\treturn new URL(proxyPath, window.location.origin).href.replace(/\\/+$/, '')\n\t\t}\n\t\tconst url = (apiUrl ?? '').trim()\n\t\tif (!url) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'PUBLIC_GOCOMMERCE_API_URL is not set, so this storefront does not know where its commerce ' +\n\t\t\t\t\t'engine is. Point it at a running GoCommerce, e.g. http://127.0.0.1:8080.',\n\t\t\t\t0,\n\t\t\t)\n\t\t}\n\t\treturn url.replace(/\\/+$/, '')\n\t}\n\n\t/** An absolute engine URL for a path and query, without sending anything. */\n\tprotected engineURL(path: string, query?: Query): string {\n\t\treturn this.engineBase() + path + qs(query)\n\t}\n\n\t/**\n\t * One request to the engine, envelope and all.\n\t *\n\t * The body is read as text first, so a proxy's HTML error page is reported\n\t * as what it is rather than as a JSON parse error three frames away.\n\t */\n\tprotected async engine<T>(path: string, req: EngineRequest = {}): Promise<Envelope<T>> {\n\t\t// A language only means something on a read; a write's answer is a cart\n\t\t// or an order, whose lines keep the words they were bought under.\n\t\tconst lang = (req.method ?? 'GET') === 'GET' ? this.creds.language : undefined\n\t\tconst url = this.engineURL(path, lang ? { lang, ...req.query } : req.query)\n\t\tconst headers: Record<string, string> = { Accept: 'application/json', ...req.headers }\n\t\t// A form goes as it is: fetch writes its multipart Content-Type, boundary included.\n\t\tconst form = req.body instanceof FormData ? req.body : undefined\n\t\tif (req.body !== undefined && !form) headers['Content-Type'] = 'application/json'\n\t\tconst store = this.store\n\t\tif (store) headers['X-Store'] = store\n\t\tif (req.auth) {\n\t\t\tconst token = sessionToken()\n\t\t\tif (!token) throw new GoCommerceError('Please sign in to continue.', 401, 'unauthorized')\n\t\t\theaders.Authorization = `Bearer ${token}`\n\t\t}\n\n\t\tconst init: RequestInit = {\n\t\t\tmethod: req.method ?? 'GET',\n\t\t\theaders,\n\t\t\tbody: form ?? (req.body === undefined ? undefined : JSON.stringify(req.body)),\n\t\t}\n\t\tlet res: Response\n\t\ttry {\n\t\t\tres = await this._fetch.call(globalThis, url, init)\n\t\t} catch (cause) {\n\t\t\t// SvelteKit's server-side fetch applies the browser's CORS rule to a\n\t\t\t// universal load, and the engine sends no CORS headers. On the server\n\t\t\t// there is no browser to protect, so ask again with Node's own fetch;\n\t\t\t// in the browser the same call goes through PUBLIC_GOCOMMERCE_PROXY_PATH.\n\t\t\tif (typeof window === 'undefined' && /CORS/i.test(String((cause as Error)?.message))) {\n\t\t\t\ttry {\n\t\t\t\t\tres = await globalThis.fetch(url, init)\n\t\t\t\t} catch (again) {\n\t\t\t\t\tthrow unreachable(this.engineBase(), again)\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tthrow unreachable(this.engineBase(), cause)\n\t\t\t}\n\t\t}\n\t\treturn this.unwrap<T>(res)\n\t}\n\n\t/** The envelope opened: the payload, or the engine's error as a GoCommerceError. */\n\tprivate async unwrap<T>(res: Response): Promise<Envelope<T>> {\n\t\tconst text = await res.text()\n\t\tlet parsed: any = null\n\t\tif (text) {\n\t\t\ttry {\n\t\t\t\tparsed = JSON.parse(text)\n\t\t\t} catch {\n\t\t\t\tthrow new GoCommerceError(\n\t\t\t\t\t`The commerce engine answered ${res.status} with something that is not JSON: ${text.slice(0, 120)}`,\n\t\t\t\t\tres.status,\n\t\t\t\t)\n\t\t\t}\n\t\t}\n\t\tif (!res.ok) {\n\t\t\tconst err = parsed?.error ?? {}\n\t\t\tthrow new GoCommerceError(\n\t\t\t\terr.message ?? `The commerce engine answered ${res.status}.`,\n\t\t\t\tres.status,\n\t\t\t\terr.code,\n\t\t\t\terr.details,\n\t\t\t)\n\t\t}\n\t\t// 204 is a success with nothing to say; the caller decides what that means.\n\t\treturn (parsed ?? { data: null }) as Envelope<T>\n\t}\n\n\t/** The bare payload, for the many callers that never look at `meta`. */\n\tprotected async data<T>(path: string, req: EngineRequest = {}): Promise<T> {\n\t\treturn (await this.engine<T>(path, req)).data\n\t}\n\n\t/**\n\t * Prices a cart at the signed-in shopper's customer-group prices. The\n\t * engine does this only for an account whose email is confirmed (403\n\t * otherwise), and the cart stays the shopper's either way — so a refusal\n\t * is not an error, and neither is a build without ext/identity. A refused\n\t * claim still gives the cart the account's email, which the claim would\n\t * have set, or the checkout asks the shopper for it again.\n\t */\n\tprotected async claimCartForAccount(cartId: string): Promise<void> {\n\t\ttry {\n\t\t\tawait this.engine('/x/identity/me/carts', { method: 'POST', body: { cart_id: cartId }, auth: true })\n\t\t} catch {\n\t\t\tconst email = currentMe()?.email\n\t\t\tif (email)\n\t\t\t\tawait this.engine(`/api/carts/${encodeURIComponent(cartId)}/email`, { method: 'PUT', body: { email } }).catch(\n\t\t\t\t\t() => undefined,\n\t\t\t\t)\n\t\t}\n\t}\n\n\t// ------------------------------------------------------------ Litekart verbs\n\n\t/**\n\t * The family's path-addressed verbs. An absolute URL is fetched as-is; a\n\t * relative one is a Litekart REST path, answered from the storefront's own\n\t * data where it has some and refused otherwise (rest-guard.ts).\n\t */\n\tget<T = any>(path: string): Promise<T> {\n\t\treturn this.raw<T>('get', path)\n\t}\n\tpost<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('post', path, data)\n\t}\n\tput<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('put', path, data)\n\t}\n\tpatch<T = any>(path: string, data?: unknown): Promise<T> {\n\t\treturn this.raw<T>('patch', path, data)\n\t}\n\tdelete<T = any>(path: string): Promise<T> {\n\t\treturn this.raw<T>('delete', path)\n\t}\n\n\tprivate async raw<T>(method: string, path: string, data?: unknown): Promise<T> {\n\t\tif (!/^https?:\\/\\//i.test(path)) return (await resolveRestLocally(method, path)) as T\n\t\tconst res = await this._fetch.call(globalThis, path, {\n\t\t\tmethod: method.toUpperCase(),\n\t\t\theaders: { Accept: 'application/json', ...(data === undefined ? {} : { 'Content-Type': 'application/json' }) },\n\t\t\tbody: data === undefined ? undefined : JSON.stringify(data),\n\t\t})\n\t\tconst body = await res.json().catch(() => ({}))\n\t\tif (!res.ok)\n\t\t\tthrow new GoCommerceError(body?.error?.message ?? `Request failed with status ${res.status}`, res.status)\n\t\treturn body as T\n\t}\n}\n\nlet requestHost: (() => string | undefined) | undefined\n\n/**\n * Where the server learns the current request's host, for `baseDomain`. A\n * SvelteKit storefront registers `() => getRequestEvent().url.hostname` once\n * at boot; the browser needs nothing, it reads `window.location`.\n */\nexport function setRequestHost(fn: () => string | undefined): void {\n\trequestHost = fn\n}\n\n/**\n * `acme.shopnx.in` under `shopnx.in` is store `acme`; anything else is nobody's.\n * The engine's own rule (`Stores.ByHost`): case-insensitive, a port and a\n * trailing dot ignored, and exactly one label, so `a.b.shopnx.in` and\n * `shopnx.in` itself name no store.\n */\nexport function storeForHost(host: string | undefined, baseDomain: string | undefined): string | undefined {\n\tif (!host || !baseDomain) return undefined\n\tconst h = host.toLowerCase().replace(/\\.$/, '').replace(/:\\d+$/, '')\n\tconst suffix = '.' + baseDomain.toLowerCase().replace(/^\\.+/, '').replace(/\\.$/, '')\n\tif (!h.endsWith(suffix)) return undefined\n\tconst slug = h.slice(0, -suffix.length)\n\treturn slug && !slug.includes('.') ? slug : undefined\n}\n\n/**\n * A host outside `baseDomain` is a store's own domain, such as `chillish.in`,\n * which the engine looks up among its verified domains. Only a storefront\n * serving many stores (one with a `baseDomain`) passes it on; the base domain\n * itself, `localhost` and bare addresses are nobody's.\n */\nexport function ownDomain(host: string | undefined, baseDomain: string | undefined): string | undefined {\n\tif (!host || !baseDomain) return undefined\n\tconst h = host.toLowerCase().replace(/:\\d+$/, '').replace(/\\.$/, '')\n\tconst base = baseDomain.toLowerCase().replace(/^\\.+/, '').replace(/\\.$/, '')\n\tif (!h.includes('.') || h === base || h.endsWith('.' + base) || h.endsWith('.localhost')) return undefined\n\tif (/^[\\d.]+$/.test(h) || h.includes(':') || h.startsWith('[')) return undefined\n\treturn h\n}\n\n/** A refused connection is the commonest failure in development; it says which address did not answer. */\nconst unreachable = (base: string, cause: unknown) =>\n\tnew GoCommerceError(`Could not reach the commerce engine at ${base}: ${(cause as Error)?.message ?? cause}`, 0)\n\n/** `?a=1&b=2`, dropping what was not asked for. Arrays repeat the key. */\nexport function qs(query?: Query): string {\n\tif (!query) return ''\n\tconst sp = new URLSearchParams()\n\tfor (const [key, value] of Object.entries(query)) {\n\t\t// Undefined, null and '' are \"did not ask\", not \"asked for nothing\":\n\t\t// `?q=` would filter to the empty string.\n\t\tif (value === undefined || value === null || value === '') continue\n\t\tif (Array.isArray(value)) for (const v of value) sp.append(key, String(v))\n\t\telse sp.append(key, String(value))\n\t}\n\tconst s = sp.toString()\n\treturn s ? `?${s}` : ''\n}\n\n/** The family's list shape, from the engine's `{data, meta}`. Totals are the engine's, never invented. */\nexport function toPage<T, U>(env: Envelope<T[] | null>, map: (row: T) => U) {\n\tconst rows = env.data ?? []\n\tconst meta = env.meta\n\treturn {\n\t\tdata: rows.map(map),\n\t\tcount: meta?.total ?? rows.length,\n\t\tpageSize: meta?.limit ?? rows.length,\n\t\tnoOfPage: meta?.total_pages ?? 1,\n\t\tpage: meta?.page ?? 1,\n\t}\n}\n\nexport const emptyPage = <T = never>() => ({ data: [] as T[], count: 0, pageSize: 0, noOfPage: 0, page: 1 })\n","/**\n * Money, across the one boundary in this connector where it changes shape.\n *\n * The engine speaks minor units and a currency code, always, and never sends a\n * formatted string (AGENTS.md rule 6). Svelte Commerce's types say `price:\n * number`, and every backend it already talks to means \"19.99\" by that. So the\n * conversion happens here, once, in the only file allowed to divide money.\n *\n * The exponent is per currency, not a constant 100: the yen writes no decimals\n * and the dinar writes three. Dividing 2500 JPY by 100 would price a ¥2,500\n * item at ¥25. The table mirrors `currencyExponent` in core/transfer_shopify.go\n * — the same list, because a second opinion about the yen is a bug.\n */\n\nconst ZERO_DECIMAL = new Set([\n\t'BIF',\n\t'CLP',\n\t'DJF',\n\t'GNF',\n\t'ISK',\n\t'JPY',\n\t'KMF',\n\t'KRW',\n\t'PYG',\n\t'RWF',\n\t'UGX',\n\t'VND',\n\t'VUV',\n\t'XAF',\n\t'XOF',\n\t'XPF',\n])\n\nconst THREE_DECIMAL = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND'])\n\nexport function currencyExponent(code: string | null | undefined): number {\n\tconst c = (code ?? '').toUpperCase()\n\tif (ZERO_DECIMAL.has(c)) return 0\n\tif (THREE_DECIMAL.has(c)) return 3\n\treturn 2\n}\n\n/** The engine's money object. */\nexport type Money = { amount_minor: number; currency: string }\n\n/**\n * Minor units to the major-unit number the storefront renders.\n *\n * Rounded to the currency's own precision rather than left as raw float\n * division: 1999/100 is 19.99 exactly, but 1 / 1000 for a three-decimal\n * currency is not, and a price that renders as 0.0010000000000000002 is the\n * kind of thing nobody notices until a customer screenshots it.\n */\nexport function toMajor(money: Money | null | undefined): number {\n\tif (!money) return 0\n\treturn minorToMajor(money.amount_minor, money.currency)\n}\n\n/** The same, for the routes that send a bare `*_minor` integer beside a currency. */\nexport function minorToMajor(minor: number | null | undefined, currency: string | null | undefined): number {\n\tif (minor === null || minor === undefined || !Number.isFinite(minor)) return 0\n\tconst exp = currencyExponent(currency)\n\tif (exp === 0) return minor\n\treturn Number((minor / 10 ** exp).toFixed(exp))\n}\n\n/**\n * Back the other way, for the few places the storefront hands us a number —\n * a price filter, mostly.\n *\n * Rounded, not truncated: 19.99 * 100 is 1998.9999999999998 in binary floating\n * point, and truncating that filters out the item priced exactly 19.99.\n */\nexport function toMinor(amount: number, currency: string | null | undefined): number {\n\tconst exp = currencyExponent(currency)\n\treturn Math.round(amount * 10 ** exp)\n}\n","/**\n * Engine shapes to storefront shapes.\n *\n * Svelte Commerce's types were drawn around Litekart's API, so every connector\n * is a translation and this file is most of ours. Four rules run through it:\n *\n * 1. Ids cross as strings. The storefront matches variants and cart lines\n * with `===` against ids it read from a URL.\n * 2. Money crosses as a major-unit number, through money.ts and nowhere else.\n * 3. A field the engine does not have is empty, never invented. There is no\n * popularity score, so none is made up; there is no compare-at price, so\n * `mrp` equals the price rather than 0, which would render as a 100%\n * discount on everything in the shop.\n * 4. Lists are always arrays. Product cards read `variants[0]` unguarded.\n */\nimport type {\n\tAddOn,\n\tAddress,\n\tCart,\n\tCartOffer,\n\tCartLine,\n\tCategory,\n\tCheckoutQuote,\n\tCmsPage,\n\tCollection,\n\tCustomer,\n\tIdentityAddress,\n\tOrder,\n\tOrderLine,\n\tProduct,\n\tReview,\n\tSearchDoc,\n\tVariant,\n\tVendor,\n\tFreeShipping,\n} from './engine'\nimport { minorToMajor, toMajor, type Money } from './money'\nimport type { CartExtras, StorefrontAddress } from './browser'\nimport { mediaUrl } from './services/base.service'\n\nconst str = (v: number | string | null | undefined): string => (v === null || v === undefined ? '' : String(v))\n\nconst arr = <T>(v: T[] | null | undefined): T[] => v ?? []\n\n// ---------------------------------------------------------------- products\n\n/** Variants a shopper can see: inactive ones are the merchant's business. */\nconst liveVariants = (p: Product): Variant[] => arr(p.variants).filter((v) => v.active)\n\nfunction variantImages(v: Variant): string[] {\n\tconst out: string[] = []\n\tfor (const img of [v.image, ...arr(v.images)]) {\n\t\tconst url = mediaUrl(img?.url)\n\t\tif (url && (img?.kind ?? 'image') === 'image' && !out.includes(url)) out.push(url)\n\t}\n\treturn out\n}\n\n/**\n * Every picture the public API offers for a product: the lead image, the\n * product's gallery (on the single product, D134), then each variant's.\n */\nexport function productImages(p: Product): string[] {\n\tconst out: string[] = []\n\tconst push = (url?: string | null) => {\n\t\tif (url && !out.includes(url)) out.push(url)\n\t}\n\t// variantImages has already resolved its own; resolving twice would prefix twice.\n\tpush(mediaUrl(p.image_url))\n\t// A listing has no media list, only the lead and the next picture for a card's hover.\n\tpush(mediaUrl(p.hover_image_url))\n\tfor (const m of arr(p.media)) if (m.kind === 'image') push(mediaUrl(m.url))\n\tfor (const v of arr(p.variants)) for (const url of variantImages(v)) push(url)\n\treturn out\n}\n\n/**\n * The product's videos, an upload or a YouTube link, in the gallery's order\n * (D134). They follow the pictures in `images`, where the storefront's gallery\n * plays them; a card's thumbnail is never one.\n */\nexport function productVideos(p: Product): string[] {\n\tconst out: string[] = []\n\tfor (const m of arr(p.media)) {\n\t\tconst url = m.kind === 'video' ? mediaUrl(m.url) : null\n\t\tif (url && !out.includes(url)) out.push(url)\n\t}\n\treturn out\n}\n\n/** A product's highlight lines: text only, the empty ones left out (D134). */\nfunction highlightsOf(p: Product): string[] {\n\tconst raw = p.metadata?.highlights\n\tif (!Array.isArray(raw)) return []\n\treturn raw.filter((s): s is string => typeof s === 'string').map((s) => s.trim()).filter(Boolean)\n}\n\nfunction freeGiftOf(p: Product): string | null {\n\tconst raw = p.metadata?.free_gift\n\treturn typeof raw === 'string' && raw.trim() ? raw.trim() : null\n}\n\nexport function toVariant(v: Variant, p: Product, optionless: boolean) {\n\tconst images = variantImages(v)\n\tconst options = arr(p.options)\n\treturn {\n\t\tid: str(v.id),\n\t\tproductId: str(v.product_id),\n\t\t// The storefront picks the default variant of an optionless product by\n\t\t// this exact title, and hides the variant name when it sees it.\n\t\ttitle: optionless ? 'default' : v.label || v.sku,\n\t\tsku: v.sku,\n\t\tbarcode: v.barcode ?? null,\n\t\tprice: toMajor(v.price),\n\t\tmrp: toMajor(v.compare_at_price ?? v.price),\n\t\t// The engine's own vocabulary, unchanged: `available` is on hand minus\n\t\t// reserved; an untracked variant is never managed, so its count is moot.\n\t\tstock: v.active ? v.available : 0,\n\t\tmanageInventory: v.active ? v.track_inventory : true,\n\t\tallowBackorder: v.active && v.continue_selling,\n\t\tactive: v.active,\n\t\tweight: v.weight_grams ?? null,\n\t\tlength: v.dimensions?.length_mm ?? null,\n\t\twidth: v.dimensions?.width_mm ?? null,\n\t\theight: v.dimensions?.height_mm ?? null,\n\t\timages: images.join(','),\n\t\timg: images[0] ?? null,\n\t\timage: images[0] ?? null,\n\t\tthumbnail: images[0] ?? null,\n\t\t// Values in option order — `options[i]` answers `p.options[i]`.\n\t\toptions: arr(v.options).map((value, i) => ({ optionId: str(options[i]?.id), value })),\n\t\tmetadata: v.metadata ?? null,\n\t}\n}\n\n/**\n * The product's category attribute answers — `metadata.category`, keyed by the\n * attribute's handle — as the specs table's rows. The handle is the only name\n * the public API carries, so it is shown humanised rather than looked up.\n */\nfunction attributesOf(p: Product): { name: string; value: string; handle: string }[] {\n\tconst answers = p.metadata?.category\n\tif (!answers || typeof answers !== 'object' || Array.isArray(answers)) return []\n\treturn Object.entries(answers as Record<string, unknown>).flatMap(([handle, raw]) => {\n\t\tconst values = (Array.isArray(raw) ? raw : [raw]).map((v) => String(v ?? '').trim()).filter(Boolean)\n\t\tif (!values.length) return []\n\t\tconst name = handle.replace(/[-_]+/g, ' ').replace(/^./, (c) => c.toUpperCase())\n\t\treturn [{ name, value: values.join(', '), handle }]\n\t})\n}\n\nexport type StorefrontProduct = ReturnType<typeof toProduct>\n\nexport function toProduct(p: Product, extra: { categoryHierarchy?: { name: string; slug: string }[] } = {}) {\n\tconst live = liveVariants(p)\n\tconst lead = live[0] ?? arr(p.variants)[0]\n\tconst optionless = arr(p.options).length === 0\n\tconst images = productImages(p)\n\tconst videos = productVideos(p)\n\tconst prices = live.map((v) => toMajor(v.price))\n\tconst tracked = live.filter((v) => v.track_inventory)\n\tconst category = p.category\n\tconst tags = arr(p.tags)\n\n\treturn {\n\t\tid: str(p.id),\n\t\tslug: p.slug,\n\t\ttitle: p.title,\n\t\tname: p.title,\n\t\tsubtitle: null,\n\t\tdescription: p.description ?? '',\n\t\tstatus: p.status === 'active' ? 'published' : p.status,\n\t\tactive: p.status === 'active',\n\t\ttype: p.product_type ?? '',\n\t\tcurrency: p.currency,\n\t\tcurrencyCode: p.currency,\n\t\tprice: lead ? toMajor(lead.price) : 0,\n\t\tmrp: lead ? toMajor(lead.compare_at_price ?? lead.price) : 0,\n\t\tminPrice: prices.length ? Math.min(...prices) : 0,\n\t\tmaxPrice: prices.length ? Math.max(...prices) : 0,\n\t\tsku: lead?.sku ?? null,\n\t\tbarcode: lead?.barcode ?? null,\n\t\tweight: lead?.weight_grams ?? null,\n\t\toriginCountry: lead?.origin_country ?? null,\n\t\tthumbnail: images[0] ?? null,\n\t\timage_url: images[0] ?? null,\n\t\timages: [...images, ...videos].join(','),\n\t\timageList: images,\n\t\tvideos,\n\t\t// What the buy box says beside the price (D134): plain text, drawn as text.\n\t\thighlights: highlightsOf(p),\n\t\tfreeGift: freeGiftOf(p),\n\t\t// Counted by the engine, rounded down, and absent rather than zero.\n\t\tsoldAtLeast: typeof p.sold_at_least === 'number' && p.sold_at_least > 0 ? p.sold_at_least : null,\n\t\tdesignable: typeof p.designable === 'boolean' ? p.designable : undefined,\n\t\t// Product-level stock is what a card shows before a variant is picked:\n\t\t// buyable when any live variant is, counted only where counting means\n\t\t// something.\n\t\tmanageInventory: live.length > 0 && tracked.length === live.length,\n\t\tallowBackorder: live.some((v) => v.continue_selling),\n\t\tstock: tracked.reduce((n, v) => n + Math.max(0, v.available), 0),\n\t\thasStock: live.some((v) => !v.track_inventory || v.continue_selling || v.available > 0),\n\t\tcategoryId: category ? str(category.id) : null,\n\t\tcategory: category ? { id: str(category.id), name: category.title, slug: category.slug } : null,\n\t\tcategories: category ? [{ category: { id: str(category.id), name: category.title, slug: category.slug } }] : [],\n\t\tcategoryHierarchy: extra.categoryHierarchy ?? (category ? [{ name: category.title, slug: category.slug }] : []),\n\t\tcollections: arr(p.collections).map((c) => ({ id: str(c.id), name: c.title, slug: c.slug })),\n\t\t// Free text on the engine's product, not a vendor record.\n\t\tvendor: p.vendor ? { businessName: p.vendor } : null,\n\t\tproductTags: tags.join(','),\n\t\tkeywords: tags.join(','),\n\t\tmetaTitle: p.seo_title || p.title,\n\t\tmetaDescription: p.seo_description || null,\n\t\tlink: `/products/${p.slug}`,\n\t\toptions: arr(p.options).map((o) => ({\n\t\t\tid: str(o.id),\n\t\t\ttitle: o.name,\n\t\t\tname: o.name,\n\t\t\ttype: 'text',\n\t\t\tvalues: arr(o.values).map((val) => ({ id: str(val.id), value: val.value })),\n\t\t})),\n\t\tvariants: live.map((v) => toVariant(v, p, optionless)),\n\t\t// Filled by the product page from ext/reviews when it is installed.\n\t\tratings: [] as ReturnType<typeof toRating>[],\n\t\trating: null as number | null,\n\t\tratingCount: 0,\n\t\treviewCount: 0,\n\t\tattributes: attributesOf(p),\n\t\tmetadata: p.metadata ?? null,\n\t\tcreatedAt: p.created_at,\n\t\tupdatedAt: p.updated_at,\n\t}\n}\n\n/** A Meilisearch hit — the search index's document, which is thinner than a product. */\nexport function fromSearchDoc(d: SearchDoc) {\n\tconst price = minorToMajor(d.price_minor, d.currency)\n\treturn {\n\t\tid: str(d.id),\n\t\tslug: d.slug,\n\t\ttitle: d.title,\n\t\tname: d.title,\n\t\tdescription: d.description,\n\t\tcurrency: d.currency,\n\t\tprice,\n\t\tmrp: price,\n\t\tminPrice: price,\n\t\tmaxPrice: minorToMajor(d.price_max_minor, d.currency),\n\t\tthumbnail: mediaUrl(d.image),\n\t\timage_url: mediaUrl(d.image),\n\t\timages: mediaUrl(d.image) ?? '',\n\t\tstock: d.in_stock ? 1 : 0,\n\t\thasStock: d.in_stock,\n\t\t// The index cannot say how much is left, only whether any is; a card\n\t\t// built from it must not claim to count.\n\t\tmanageInventory: false,\n\t\tallowBackorder: false,\n\t\tdesignable: typeof d.designable === 'boolean' ? d.designable : undefined,\n\t\tproductTags: arr(d.tags).join(','),\n\t\tcategory: d.category ? { name: d.category.split(' / ').pop() ?? d.category, slug: '' } : null,\n\t\tvendor: d.vendor ? { businessName: d.vendor } : null,\n\t\tvariants: [] as ReturnType<typeof toVariant>[],\n\t\toptions: [],\n\t\tratings: [],\n\t\tlink: `/products/${d.slug}`,\n\t\tupdatedAt: new Date(d.updated_at * 1000).toISOString(),\n\t}\n}\n\n// ---------------------------------------------------------------- taxonomy\n\nexport type StorefrontCategory = {\n\tid: string\n\tname: string\n\ttitle: string\n\tslug: string\n\tlink: string\n\tparentCategoryId: string | null\n\tpath: string\n\tlevel: number\n\trank: number\n\tchildCount: number\n\tthumbnail: string | null\n\tdescription: string | null\n\tisActive: boolean\n\tisFeatured: boolean\n\tisMegamenu: boolean\n\tmetaTitle: string\n\tchildren: StorefrontCategory[]\n\tcreatedAt: string\n\tupdatedAt: string\n}\n\nexport function toCategory(c: Category): StorefrontCategory {\n\treturn {\n\t\tid: str(c.id),\n\t\tname: c.title,\n\t\ttitle: c.title,\n\t\tslug: c.slug,\n\t\tlink: `/${c.slug}`,\n\t\tparentCategoryId: c.parent_id === null || c.parent_id === undefined ? null : str(c.parent_id),\n\t\tpath: c.full_name,\n\t\tlevel: c.depth,\n\t\trank: c.position,\n\t\tchildCount: c.child_count,\n\t\tthumbnail: mediaUrl(c.metadata?.image as string | undefined),\n\t\tdescription: (c.metadata?.description as string | undefined) ?? null,\n\t\tisActive: true,\n\t\tisFeatured: false,\n\t\tisMegamenu: false,\n\t\tmetaTitle: c.title,\n\t\tchildren: arr(c.children).map(toCategory),\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\nexport function toCollection(c: Collection) {\n\treturn {\n\t\tid: str(c.id),\n\t\tname: c.title,\n\t\ttitle: c.title,\n\t\tslug: c.slug,\n\t\tdescription: c.description || null,\n\t\tsubTitle: null,\n\t\trank: str(c.position),\n\t\tthumbnail: mediaUrl(c.metadata?.image as string | undefined),\n\t\tisActive: true,\n\t\tmetaTitle: c.title,\n\t\tmetaDescription: c.description || null,\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\n// ---------------------------------------------------------------- addresses\n\n/** The engine's address — on a checkout or an order — to the storefront's form shape. */\nexport function fromEngineAddress(a: Address | undefined, email?: string) {\n\tif (!a) return null\n\tconst [firstName, ...rest] = (a.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\temail: email ?? null,\n\t\tphone: a.phone ?? null,\n\t\taddress_1: a.line1,\n\t\taddress_2: a.line2 ?? '',\n\t\tcity: a.city,\n\t\tstate: a.state ?? '',\n\t\tzip: a.postal_code,\n\t\tcountry: a.country,\n\t\tcountryCode: a.country,\n\t}\n}\n\n/** The storefront's form shape to the engine's checkout address. */\nexport function toEngineAddress(a: StorefrontAddress): Address {\n\tconst name = [a.firstName, a.lastName].filter(Boolean).join(' ').trim()\n\treturn {\n\t\t...(name ? { name } : {}),\n\t\t...(a.phone ? { phone: String(a.phone) } : {}),\n\t\tline1: String(a.address_1 ?? '').trim(),\n\t\t...(a.address_2 || a.locality ? { line2: [a.address_2, a.locality].filter(Boolean).join(', ') } : {}),\n\t\tcity: String(a.city ?? '').trim(),\n\t\t...(a.state ? { state: String(a.state) } : {}),\n\t\tpostal_code: String(a.zip ?? '').trim(),\n\t\tcountry: String(a.countryCode || a.country || '')\n\t\t\t.trim()\n\t\t\t.toUpperCase(),\n\t}\n}\n\n/** An address-book entry (ext/identity) to the storefront's Address. */\nexport function fromIdentityAddress(a: IdentityAddress, email?: string) {\n\tconst [firstName, ...rest] = (a.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: str(a.id),\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\temail: email ?? null,\n\t\tphone: a.phone || null,\n\t\taddress_1: a.line1,\n\t\taddress_2: a.line2,\n\t\tcity: a.city,\n\t\tstate: a.state,\n\t\tzip: a.postal_code,\n\t\tcountry: a.country,\n\t\tcountryCode: a.country,\n\t\tlabel: a.label,\n\t\tisPrimary: a.is_default,\n\t\tcreatedAt: a.created_at,\n\t\tupdatedAt: a.updated_at,\n\t}\n}\n\n/** The storefront's Address to ext/identity's AddressInput. Only declared fields: the engine refuses others. */\nexport function toIdentityAddress(a: StorefrontAddress & { isPrimary?: boolean; label?: string }) {\n\tconst e = toEngineAddress(a)\n\treturn {\n\t\tname: e.name ?? '',\n\t\tphone: e.phone ?? '',\n\t\tline1: e.line1,\n\t\tline2: e.line2 ?? '',\n\t\tcity: e.city,\n\t\tstate: e.state ?? '',\n\t\tpostal_code: e.postal_code,\n\t\tcountry: e.country,\n\t\t// Sent whenever the form has it, empty included: the engine keeps a label it is not sent, so\n\t\t// leaving out an emptied one would keep the old Home or Work (D134).\n\t\t...(typeof a.label === 'string' ? { label: a.label } : {}),\n\t\t...(a.isPrimary ? { is_default: true } : {}),\n\t}\n}\n\n// ---------------------------------------------------------------- cart\n\nexport function toCartLine(l: CartLine, extra: { slug?: string; thumbnail?: string | null } = {}) {\n\treturn {\n\t\tid: str(l.id),\n\t\tproductId: str(l.product_id),\n\t\tvariantId: str(l.variant_id),\n\t\tsku: l.sku,\n\t\ttitle: l.title,\n\t\tname: l.title,\n\t\tslug: extra.slug ?? '',\n\t\tthumbnail: mediaUrl(extra.thumbnail),\n\t\tvariantTitle: l.variant_label ?? '',\n\t\tqty: l.quantity,\n\t\tprice: toMajor(l.unit_price),\n\t\t// The variant's compare-at price, where the shop set one above what the\n\t\t// line costs: what the basket's \"you save\" is measured from.\n\t\tmrp:\n\t\t\tl.compare_at_price && l.compare_at_price.amount_minor > l.unit_price.amount_minor\n\t\t\t\t? toMajor(l.compare_at_price)\n\t\t\t\t: toMajor(l.unit_price),\n\t\t/** The add-on this line was bought as (D133), or null on an ordinary line. */\n\t\taddOnId: l.add_on_id ? str(l.add_on_id) : null,\n\t\taddOnFor: l.add_on_for ? str(l.add_on_for) : null,\n\t\t/** The shopper's own design this line is made to (D162) and its picture, or null on a line sold as it is. */\n\t\tdesignId: l.design_id ?? null,\n\t\tdesignPreview: mediaUrl(l.design_preview_url),\n\t\tsubtotal: toMajor(l.total),\n\t\ttotal: toMajor(l.total),\n\t\tinStock: l.in_stock,\n\t\tpriceChanged: l.price_changed,\n\t\tcurrentPrice: toMajor(l.current_price),\n\t\t// The storefront's review step lists only lines marked for checkout. The\n\t\t// engine checks a cart out whole, so every line is.\n\t\tisSelectedForCheckout: true,\n\t\tvariant: {\n\t\t\tid: str(l.variant_id),\n\t\t\toptions: l.variant_label ? l.variant_label.split(' / ').map((value) => ({ option: { title: '' }, value })) : [],\n\t\t},\n\t\tproduct: { id: str(l.product_id), categories: [] as unknown[] },\n\t}\n}\n\n/**\n * A cart, with what the engine does not keep laid over it: the coupon and its\n * previewed saving, the delivery choice and the addresses. Totals here are an\n * estimate the engine settles at checkout — tax in particular exists only on\n * the order — and the storefront is told so by `taxIncluded: false`.\n */\nexport function toCart(\n\tc: Cart,\n\textras: CartExtras = {},\n\tlineExtra: (l: CartLine) => { slug?: string; thumbnail?: string | null } = () => ({}),\n) {\n\tconst lines = c.status === 'converted' ? [] : arr(c.line_items)\n\tconst currency = c.currency\n\tconst subtotalMinor = lines.reduce((n, l) => n + l.total.amount_minor, 0)\n\tconst discountMinor = extras.discount && !extras.discount.free_shipping ? extras.discount.amount_minor : 0\n\tconst shippingMinor = extras.discount?.free_shipping ? 0 : (extras.shippingRate?.minor ?? 0)\n\tconst totalMinor = Math.max(0, subtotalMinor - discountMinor) + shippingMinor\n\tconst money = (minor: number) => minorToMajor(minor, currency)\n\tconst ship = extras.shippingAddress ?? null\n\n\treturn {\n\t\tid: c.id,\n\t\tstatus: c.status,\n\t\temail: c.email ?? ship?.email ?? null,\n\t\tphone: extras.phone ?? ship?.phone ?? null,\n\t\tname: ship ? [ship.firstName, ship.lastName].filter(Boolean).join(' ') : null,\n\t\tlineItems: lines.map((l) => toCartLine(l, lineExtra(l))),\n\t\tqty: lines.reduce((n, l) => n + l.quantity, 0),\n\t\tcurrencyCode: currency,\n\t\tcurrency,\n\t\tsubtotal: money(subtotalMinor),\n\t\tdiscountAmount: money(discountMinor),\n\t\tsavingAmount: money(discountMinor),\n\t\tcouponCode: extras.discount?.code ?? null,\n\t\tdiscount: extras.discount ?? null,\n\t\tshippingCharges: money(shippingMinor),\n\t\tshippingRateId: extras.shippingRateId ?? null,\n\t\tshippingMethod: extras.shippingRate?.name ?? null,\n\t\ttax: 0,\n\t\ttaxIncluded: false,\n\t\tcodCharges: 0,\n\t\ttotal: money(totalMinor),\n\t\tshippingAddress: ship,\n\t\tshippingAddressId: ship ? (ship.id && ship.id !== 'new' ? String(ship.id) : 'cart') : null,\n\t\tbillingAddress: extras.billingAddress ?? ship,\n\t\tbillingAddressId: extras.billingAddress\n\t\t\t? extras.billingAddress.id && extras.billingAddress.id !== 'new'\n\t\t\t\t? String(extras.billingAddress.id)\n\t\t\t\t: 'cart-billing'\n\t\t\t: ship\n\t\t\t\t? ship.id && ship.id !== 'new'\n\t\t\t\t\t? String(ship.id)\n\t\t\t\t\t: 'cart'\n\t\t\t\t: null,\n\t\tpaymentMethod: null,\n\t\tneedAddress: lines.length > 0,\n\t\tcompletedAt: c.status === 'converted' ? c.updated_at : null,\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t\texpiresAt: c.expires_at,\n\t}\n}\n\n/** What the storefront shows for \"no bag yet\": its own initial cart, field for field. */\nexport function emptyCart(currency = 'USD') {\n\treturn {\n\t\tid: '',\n\t\tstatus: 'open',\n\t\temail: null,\n\t\tphone: null,\n\t\tlineItems: [] as ReturnType<typeof toCartLine>[],\n\t\tqty: 0,\n\t\tcurrencyCode: currency,\n\t\tsubtotal: 0,\n\t\tdiscountAmount: 0,\n\t\tsavingAmount: 0,\n\t\tcouponCode: null,\n\t\tshippingCharges: 0,\n\t\ttax: 0,\n\t\ttotal: 0,\n\t\tshippingAddress: null,\n\t\tshippingAddressId: null,\n\t\tbillingAddress: null,\n\t\tbillingAddressId: null,\n\t}\n}\n\n// ---------------------------------------------------------------- orders\n\nconst STATUS: Record<string, string> = {\n\tpending: 'Pending',\n\tconfirmed: 'Confirmed',\n\tpartial: 'Partially shipped',\n\tshipped: 'Shipped',\n\tdelivered: 'Delivered',\n\tcancelled: 'Cancelled',\n}\n\nconst PAYMENT_STATUS: Record<string, string> = {\n\tpending: 'Pending',\n\tpaid: 'Paid',\n\tfailed: 'Failed',\n\trefunded: 'Refunded',\n}\n\nfunction toOrderLine(l: OrderLine, currency: string) {\n\treturn {\n\t\tid: str(l.id),\n\t\tproductId: str(l.product_id),\n\t\tvariantId: str(l.variant_id),\n\t\tsku: l.sku,\n\t\ttitle: l.title,\n\t\tname: l.title,\n\t\tslug: '',\n\t\tthumbnail: mediaUrl(l.image_url),\n\t\timg: mediaUrl(l.image_url),\n\t\tvariantTitle: l.variant_label ?? '',\n\t\tqty: l.quantity,\n\t\tshippedQty: l.shipped_quantity,\n\t\tprice: toMajor(l.unit_price),\n\t\tmrp: toMajor(l.unit_price),\n\t\tsubtotal: toMajor(l.total),\n\t\ttotal: toMajor(l.total),\n\t\tcurrencyCode: currency,\n\t\tstatus: l.shipped_quantity >= l.quantity ? 'Shipped' : 'Pending',\n\t\tdesignId: l.metadata?.design?.id ?? null,\n\t\tdesignPreview: mediaUrl(l.metadata?.design?.preview_url),\n\t\tfiles: [],\n\t\tusedOptions: [],\n\t}\n}\n\nexport type StorefrontOrder = ReturnType<typeof toOrder>\n\nexport function toOrder(o: Order) {\n\tconst address = fromEngineAddress(o.address, o.email)\n\tconst code = (o.discounts ?? []).find((d) => d.code)?.code\n\treturn {\n\t\tid: str(o.id),\n\t\torderNo: o.number,\n\t\torderNumber: o.number,\n\t\tnumber: o.number,\n\t\t// The storefront links an order by this; the engine has no sub-orders,\n\t\t// so an order is its own parent.\n\t\tparentOrderNo: o.number,\n\t\tstatus: STATUS[o.status] ?? o.status,\n\t\tengineStatus: o.status,\n\t\tpaymentStatus: PAYMENT_STATUS[o.payment_status] ?? o.payment_status,\n\t\tpaymentMethod: o.payment_provider.toUpperCase(),\n\t\tcurrencyCode: o.currency,\n\t\tsubtotal: toMajor(o.subtotal),\n\t\tshippingCharges: toMajor(o.shipping),\n\t\tdiscount: toMajor(o.discount),\n\t\ttax: toMajor(o.tax),\n\t\ttaxIncluded: o.tax_inclusive,\n\t\ttotal: toMajor(o.total),\n\t\trefunded: toMajor(o.refunded),\n\t\tcodCharges: toMajor(o.payment_fee),\n\t\tcoupon: code ? { code } : null,\n\t\tuserEmail: o.email,\n\t\temail: o.email,\n\t\tphone: o.phone ?? null,\n\t\tshippingAddress: address,\n\t\tbillingAddress: address,\n\t\tshippingMethod: o.shipping_method ?? null,\n\t\tshippingRate: o.shipping_method ? { name: o.shipping_method } : null,\n\t\tlineItems: arr(o.line_items).map((l) => toOrderLine(l, o.currency)),\n\t\tfulfillments: arr(o.fulfillments).map((f) => ({\n\t\t\tid: str(f.id),\n\t\t\tstatus: f.status,\n\t\t\tcarrier: f.carrier_name || f.carrier || f.provider,\n\t\t\ttrackingNumber: f.tracking ?? null,\n\t\t\ttrackingUrl: f.tracking_url ?? null,\n\t\t\tlineItems: arr(f.lines).map((l) => ({ id: str(l.order_line_id), title: l.title, qty: l.quantity })),\n\t\t\tcreatedAt: f.created_at,\n\t\t})),\n\t\ttracking: [],\n\t\torderHistory: [],\n\t\tisReplaceOrReturn: false,\n\t\tcreatedAt: o.created_at,\n\t\tupdatedAt: o.updated_at,\n\t}\n}\n\n// ---------------------------------------------------------------- the rest\n\nexport function toRating(r: Review) {\n\treturn {\n\t\tid: str(r.id),\n\t\trating: r.rating,\n\t\tname: r.name,\n\t\ttitle: r.title ?? '',\n\t\treview: r.body,\n\t\tmessage: r.body,\n\t\treply: r.reply ?? null,\n\t\tverified: r.verified,\n\t\timg: '',\n\t\tcreatedAt: r.created_at,\n\t}\n}\n\nexport function toCmsPage(p: CmsPage) {\n\treturn {\n\t\tid: str(p.id),\n\t\tslug: p.slug,\n\t\tname: p.title,\n\t\ttitle: p.title,\n\t\tcontent: p.body,\n\t\texcerpt: p.excerpt ?? null,\n\t\tlayouts: [],\n\t\tlanguage: p.language,\n\t\tmetaTitle: p.seo?.title || p.title,\n\t\tmetaDescription: p.seo?.description || p.excerpt || null,\n\t\tmetaKeywords: p.seo?.keywords || null,\n\t\tpublishedAt: p.published_at ?? null,\n\t\tcreatedAt: p.created_at,\n\t\tupdatedAt: p.updated_at,\n\t}\n}\n\nexport function toVendor(v: Vendor) {\n\treturn {\n\t\tid: str(v.id),\n\t\tslug: v.slug,\n\t\tname: v.name,\n\t\tbusinessName: v.name,\n\t\tabout: v.about,\n\t\tdescription: v.about,\n\t\twebsite: v.website,\n\t\taddress: v.address,\n\t\tbanners: [],\n\t\trating: null,\n\t}\n}\n\nexport function toUser(c: Customer) {\n\tconst [firstName, ...rest] = (c.name ?? '').trim().split(/\\s+/)\n\treturn {\n\t\tid: str(c.id),\n\t\tuserId: str(c.id),\n\t\temail: c.email,\n\t\temailVerified: c.email_verified,\n\t\tphone: c.phone || null,\n\t\tphoneVerified: !!c.phone_verified,\n\t\tfirstName: firstName || '',\n\t\tlastName: rest.join(' '),\n\t\tname: c.name,\n\t\tfullName: c.name,\n\t\tavatar: null,\n\t\trole: 'USER',\n\t\tcreatedAt: c.created_at,\n\t\tupdatedAt: c.updated_at,\n\t}\n}\n\nexport const priceOf = (m: Money | undefined) => (m ? toMajor(m) : 0)\n\n/**\n * An add-on as the buy box draws it (D133): `price` is what ticking it adds,\n * the offer where there is one, and `regularPrice` the add-on's own, struck\n * through beside it. Without an offer the two are the same and nothing is\n * struck.\n */\nexport function toAddOn(a: AddOn) {\n\treturn {\n\t\tid: str(a.id),\n\t\tproductId: str(a.item.product_id),\n\t\tvariantId: str(a.variant_id),\n\t\tslug: a.item.slug,\n\t\ttitle: a.item.title,\n\t\tvariantTitle: a.item.variant_label ?? '',\n\t\tthumbnail: mediaUrl(a.item.image_url ?? null),\n\t\tprice: toMajor(a.offer_price ?? a.price),\n\t\tregularPrice: toMajor(a.price),\n\t\thasOffer: !!a.offer_price && a.offer_price.amount_minor < a.price.amount_minor,\n\t\tinStock: a.item.in_stock,\n\t}\n}\n\n/** A listed code for one basket, in major units (D133). */\nexport function toCartOffer(o: CartOffer, currency: string) {\n\tconst isPercent = o.kind === 'percentage'\n\treturn {\n\t\tcode: o.code,\n\t\ttitle: o.title,\n\t\tisPercent,\n\t\tfreeShipping: o.kind === 'free_shipping',\n\t\t/** The percentage for a percentage code, the amount for a fixed one. */\n\t\tvalue: isPercent ? (o.value_bp ?? 0) / 100 : minorToMajor(o.value_minor ?? 0, currency),\n\t\tminAmount: o.min_subtotal_minor ? minorToMajor(o.min_subtotal_minor, currency) : null,\n\t\tapplies: o.applies,\n\t\tamount: o.amount ? toMajor(o.amount) : null,\n\t\tremaining: o.remaining ? toMajor(o.remaining) : null,\n\t\treason: o.reason ?? '',\n\t\tautoApply: !!o.auto_apply,\n\t}\n}\n\n/**\n * A checkout quote under the names `toOrder` gives the order it becomes, so a\n * page shows the two the same way.\n */\nexport function toCheckoutQuote(q: CheckoutQuote) {\n\tconst d = q.discount\n\treturn {\n\t\tsubtotal: toMajor(q.subtotal),\n\t\tshippingCharges: toMajor(q.shipping),\n\t\tshippingMethod: q.shipping_method ?? null,\n\t\tdiscount: toMajor(d?.amount),\n\t\tcoupon: d ? { code: d.code, title: d.title, autoApplied: d.auto_applied, freeShipping: !!d.free_shipping } : null,\n\t\ttax: toMajor(q.tax),\n\t\ttaxIncluded: q.tax_inclusive,\n\t\tcodCharges: toMajor(q.payment_fee),\n\t\ttotal: toMajor(q.total),\n\t}\n}\n\nexport function toFreeShipping(f: FreeShipping) {\n\treturn {\n\t\tqualifies: f.qualifies,\n\t\tthreshold: f.threshold ? toMajor(f.threshold) : null,\n\t\tremaining: f.remaining ? toMajor(f.remaining) : null,\n\t\tsubtotal: toMajor(f.subtotal),\n\t}\n}\n","/**\n * A short memory for store-level facts: which plugins are on, the settlement\n * currency, the category tree.\n *\n * The storefront asks for the store record on every server request, and a\n * category page needs the whole tree to draw one breadcrumb. Asking the engine\n * each time would multiply its load by the page count for answers that change\n * when a merchant edits something, not when a shopper clicks.\n *\n * Only facts that are the same for every shopper may go in here — this module\n * is shared by every request a server process handles. Keyed by engine URL, so\n * a platform storefront talking to several stores keeps them apart.\n */\nconst TTL_MS = 60_000\n\ntype Entry = { at: number; value: Promise<unknown> }\n\nconst entries = new Map<string, Entry>()\n\nexport function remember<T>(key: string, load: () => Promise<T>, ttl = TTL_MS): Promise<T> {\n\tconst hit = entries.get(key)\n\tif (hit && Date.now() - hit.at < ttl) return hit.value as Promise<T>\n\tconst value = load()\n\tentries.set(key, { at: Date.now(), value })\n\t// A failure is not remembered: the next caller tries again.\n\tvalue.catch(() => {\n\t\tif (entries.get(key)?.value === value) entries.delete(key)\n\t})\n\treturn value\n}\n\nconst known = new Map<string, unknown>()\n\nexport function keep<T>(key: string, value: T): T {\n\tknown.set(key, value)\n\treturn value\n}\n\nexport function recall<T>(key: string): T | undefined {\n\treturn known.get(key) as T | undefined\n}\n\n/** For tests, and for a storefront that has just changed something itself. */\nexport function forgetAll(): void {\n\tentries.clear()\n\tknown.clear()\n}\n","import { remember } from '../cache'\nimport type { Category, CheckoutOptions, Plugin, StoreProfile } from '../engine'\nimport { BaseService } from './base.service'\n\n/**\n * Store-level questions several services ask, answered once a minute.\n *\n * Not exported from the package: it is plumbing the other services share.\n */\nexport class StoreFacts extends BaseService {\n\tprivate key(name: string) {\n\t\treturn `${this.engineBase()}|${this.store ?? ''}|${name}`\n\t}\n\n\t/** Enabled plugins by key. A module that is not installed has no key here. */\n\tplugins(): Promise<Map<string, Plugin>> {\n\t\treturn remember(this.key('plugins'), async () => {\n\t\t\tconst list = (await this.data<Plugin[] | null>('/api/plugins')) ?? []\n\t\t\treturn new Map(list.map((p) => [p.key, p]))\n\t\t})\n\t}\n\n\tasync pluginOn(key: string): Promise<boolean> {\n\t\ttry {\n\t\t\treturn (await this.plugins()).has(key)\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/**\n\t * The store's settlement currency and default language, from routes bound\n\t * to the store: `/health/ready` answers for the install, so on a shared\n\t * engine every store read as the install's currency.\n\t */\n\tready(): Promise<{ currency: string; language: string }> {\n\t\treturn remember(this.key('ready'), async () => {\n\t\t\tconst [{ currency }, { language }] = await Promise.all([this.checkoutOptions(), this.profile()])\n\t\t\treturn { currency, language }\n\t\t})\n\t}\n\n\t/** The store's own name and how a buyer reaches it, as set in its panel. */\n\tprofile(): Promise<StoreProfile> {\n\t\treturn remember(this.key('profile'), () => this.data<StoreProfile>('/api/store'))\n\t}\n\n\t/** Where the store delivers (D117): its priced zones' countries, or everywhere. */\n\tshipsTo(): Promise<{ everywhere: boolean; countries: string[] }> {\n\t\treturn remember(this.key('ships-to'), async () => {\n\t\t\tconst r = await this.data<{ everywhere: boolean; countries: string[] } | null>('/api/checkout/countries')\n\t\t\treturn { everywhere: r?.everywhere ?? true, countries: r?.countries ?? [] }\n\t\t})\n\t}\n\n\tcheckoutOptions(): Promise<CheckoutOptions> {\n\t\treturn remember(this.key('checkout'), () => this.data<CheckoutOptions>('/api/checkout'))\n\t}\n\n\t/**\n\t * The whole tree, flat and depth-first. Past 500 categories the engine\n\t * answers a truncated list; the tree then serves what it has, and a\n\t * breadcrumb for a category outside it falls back to the category alone.\n\t */\n\tcategories(): Promise<Category[]> {\n\t\treturn remember(\n\t\t\tthis.key('categories'),\n\t\t\tasync () => (await this.data<Category[] | null>('/api/categories', { query: { flat: 1 } })) ?? [],\n\t\t)\n\t}\n\n\t/** Root → `slug`, by walking parents in the flat tree. */\n\tasync hierarchy(slug: string): Promise<{ name: string; slug: string }[]> {\n\t\tconst all = await this.categories().catch(() => [] as Category[])\n\t\tconst byId = new Map(all.map((c) => [c.id, c]))\n\t\tconst out: { name: string; slug: string }[] = []\n\t\tlet c = all.find((x) => x.slug === slug)\n\t\twhile (c) {\n\t\t\tout.unshift({ name: c.title, slug: c.slug })\n\t\t\tc = c.parent_id === null ? undefined : byId.get(c.parent_id)\n\t\t}\n\t\treturn out\n\t}\n\n\t/** `slug` and every category under it — what a category page sells. */\n\tasync subtree(slug: string): Promise<Category[]> {\n\t\tconst all = await this.categories()\n\t\tconst root = all.find((c) => c.slug === slug)\n\t\tif (!root) return []\n\t\tconst ids = new Set([root.id])\n\t\tconst out = [root]\n\t\t// Depth-first and flat, so a parent always precedes its children.\n\t\tfor (const c of all) {\n\t\t\tif (c.parent_id !== null && ids.has(c.parent_id) && !ids.has(c.id)) {\n\t\t\t\tids.add(c.id)\n\t\t\t\tout.push(c)\n\t\t\t}\n\t\t}\n\t\treturn out\n\t}\n}\n","import type { Category, Product, ProductFacets, SearchResult } from '../engine'\nimport { fromSearchDoc, toProduct } from '../map'\nimport { toMinor } from '../money'\nimport { BaseService, toPage } from './base.service'\nimport { StoreFacts } from './facts'\n\nexport const PAGE_SIZE = 24\n\nexport type CatalogQuery = {\n\tpage?: number\n\tlimit?: number\n\tsearch?: string\n\t/** The family's sort spellings: `-createdAt`, `price`, `price:asc`, `updatedAt:desc`, `-popularity`… */\n\tsort?: string\n\t/** A category slug: the page sells it and everything under it. */\n\tcategory?: string\n\tpriceFrom?: number\n\tpriceTo?: number\n\t/**\n\t * Attribute answers, `{ color: ['Red', 'Blue'] }`: one handle's values OR-ed,\n\t * different handles AND-ed. The engine filters on them in the whole-shop\n\t * listing only — its category route takes none — so inside a category they\n\t * are not applied.\n\t */\n\tattributes?: Record<string, string[]>\n\ttags?: string[]\n\tvendors?: string[]\n\tproductTypes?: string[]\n\t/**\n\t * Ask the engine to count the filter values too. Such a query goes to\n\t * `GET /api/products`, which then also answers the category, the price\n\t * range, the sort and every filter above (D130); an engine too old to count\n\t * them is asked the way it always was, and the page has no facets.\n\t */\n\tfacets?: boolean\n}\n\nexport type CatalogPage = {\n\tdata: ReturnType<typeof toProduct>[] | ReturnType<typeof fromSearchDoc>[]\n\tcount: number\n\tpageSize: number\n\tnoOfPage: number\n\tpage: number\n\tcategoryHierarchy: { name: string; slug: string }[]\n\t/** Whether the answer honoured `sort` and the price range, or had to drop them. */\n\tsorted: boolean\n\tfacets?: ProductFacets\n}\n\n/**\n * The family's sort names, in the search index's terms. The engine's own\n * listing has one order — newest first — so anything else needs the index.\n * Popularity has no answer anywhere: the engine keeps no such score, and\n * inventing one would sort the shop into a plausible-looking lie.\n */\nfunction sortParts(sort: string): [string, 'asc' | 'desc'] {\n\tconst s = sort.trim()\n\tconst [field, dir] = s.startsWith('-') ? [s.slice(1), 'desc'] : s.includes(':') ? s.split(':') : [s, 'asc']\n\treturn [field, dir === 'desc' ? 'desc' : 'asc']\n}\n\nfunction indexSort(sort?: string): string | undefined {\n\tif (!sort) return undefined\n\tconst [field, d] = sortParts(sort)\n\tswitch (field) {\n\t\tcase 'price':\n\t\t\treturn `price_minor:${d}`\n\t\tcase 'updatedAt':\n\t\tcase 'updated_at':\n\t\tcase 'createdAt':\n\t\tcase 'created_at':\n\t\t\treturn `updated_at:${d}`\n\t\tcase 'title':\n\t\tcase 'name':\n\t\t\treturn `title:${d}`\n\t\tdefault:\n\t\t\treturn undefined\n\t}\n}\n\n/** The same names in the engine listing's own `sort` and `order`. */\nfunction engineSort(sort?: string): { sort?: string; order?: string } {\n\tif (!sort || NATURAL.has(sort)) return {}\n\tconst [field, order] = sortParts(sort)\n\tconst key = (\n\t\t{\n\t\t\tprice: 'price',\n\t\t\tcreatedAt: 'created_at',\n\t\t\tcreated_at: 'created_at',\n\t\t\tupdatedAt: 'updated_at',\n\t\t\tupdated_at: 'updated_at',\n\t\t\ttitle: 'title',\n\t\t\tname: 'title',\n\t\t} as Record<string, string>\n\t)[field]\n\treturn key ? { sort: key, order } : {}\n}\n\n/** Newest first is the engine's own order, so these need no index. */\nconst NATURAL = new Set([\n\t'-createdAt',\n\t'createdAt:desc',\n\t'-updatedAt',\n\t'updatedAt:desc',\n\t'-popularity',\n\t'popularity:desc',\n])\n\nconst quote = (s: string) => `\"${s.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`\n\n/**\n * One shelf of products, from whichever engine route can answer the question.\n *\n * - Words, with no tag, vendor, type or attribute ticked, on a store with the\n * Meilisearch plugin on: its index, which forgives typos, with the facet\n * rail the database counts for the same words.\n * - Asked for facets: `GET /api/products?facets=1`, which answers every filter,\n * the category and the sort on its own (D130).\n * - A category, no reordering: `GET /api/categories/{slug}`, which sells the\n * category and its descendants.\n * - A search or the whole shop, no reordering: `GET /api/products?q=`.\n * - Any sort but newest, or a price range: the Meilisearch module, when it is\n * installed and configured. Without it the shelf comes back in the engine's\n * order with `sorted: false`, rather than failing or pretending.\n *\n * Whenever the index cannot answer (Meilisearch down), the database does.\n */\n/** Engines, by base URL, that answered `facets=1` without facets. */\nconst legacyListing = new Set<string>()\n\nexport class CatalogService extends BaseService {\n\tprotected readonly facts = new StoreFacts(this._fetch)\n\n\tprotected async queryCatalog(q: CatalogQuery): Promise<CatalogPage> {\n\t\tconst page = Math.max(1, Number(q.page) || 1)\n\t\tconst limit = Math.min(100, Math.max(1, Number(q.limit) || PAGE_SIZE))\n\t\tconst search = q.search?.trim() || undefined\n\t\tconst wantsRange = Number.isFinite(q.priceFrom) || Number.isFinite(q.priceTo)\n\t\tconst sortKey = q.sort && !NATURAL.has(q.sort) ? indexSort(q.sort) : undefined\n\t\tconst hierarchy = q.category ? await this.facts.hierarchy(q.category) : []\n\t\tconst attr = Object.entries(q.attributes ?? {}).flatMap(([handle, values]) =>\n\t\t\tvalues.filter(Boolean).map((v) => `${handle}:${v}`),\n\t\t)\n\n\t\t// A shopper's words go to the index first: it forgives typos and ranks\n\t\t// by relevance. Not once they have ticked a tag, vendor, type or\n\t\t// attribute, which only the database filters and counts.\n\t\tconst refined = attr.length > 0 || !!(q.tags?.length || q.vendors?.length || q.productTypes?.length)\n\t\tconst triedIndex = !!search && !refined\n\t\tconst counted = q.facets && !legacyListing.has(this.engineBase())\n\t\tconst facetListing = async (page: number, limit: number) => {\n\t\t\tconst { currency } = await this.facts.ready()\n\t\t\tconst minor = (n?: number) => (Number.isFinite(n) ? Math.max(0, toMinor(n as number, currency)) : undefined)\n\t\t\treturn this.engine<Product[] | null>('/api/products', {\n\t\t\t\tquery: {\n\t\t\t\t\tq: search,\n\t\t\t\t\tpage,\n\t\t\t\t\tlimit,\n\t\t\t\t\tchannel: this.creds.channel,\n\t\t\t\t\tcategory: q.category,\n\t\t\t\t\ttag: q.tags,\n\t\t\t\t\tvendor: q.vendors,\n\t\t\t\t\tproduct_type: q.productTypes,\n\t\t\t\t\tattr,\n\t\t\t\t\tprice_min: minor(q.priceFrom),\n\t\t\t\t\tprice_max: minor(q.priceTo),\n\t\t\t\t\t...engineSort(q.sort),\n\t\t\t\t\tfacets: 1,\n\t\t\t\t},\n\t\t\t})\n\t\t}\n\t\tif (triedIndex && (await this.facts.pluginOn('meilisearch'))) {\n\t\t\tconst [found, rail] = await Promise.all([\n\t\t\t\tthis.fromIndex(q, { page, limit, search, sortKey, wantsRange, hierarchy }),\n\t\t\t\tcounted ? facetListing(1, 1).catch(() => null) : null,\n\t\t\t])\n\t\t\t// The rail is the database's count for the same words: there to narrow\n\t\t\t// by when they match exactly, empty for a typo only the index forgives.\n\t\t\tif (found) return rail?.meta?.facets ? { ...found, facets: rail.meta.facets } : found\n\t\t}\n\n\t\tif (counted) {\n\t\t\tconst env = await facetListing(page, limit)\n\t\t\tif (env.meta?.facets) {\n\t\t\t\treturn {\n\t\t\t\t\t...toPage(env, (p: Product) => toProduct(p)),\n\t\t\t\t\tcategoryHierarchy: hierarchy,\n\t\t\t\t\tsorted: true,\n\t\t\t\t\tfacets: env.meta.facets,\n\t\t\t\t}\n\t\t\t}\n\t\t\t// ponytail: remembered until restart, so an engine upgraded under a running storefront gets facets after the next deploy.\n\t\t\tlegacyListing.add(this.engineBase())\n\t\t}\n\n\t\tif (!triedIndex && (sortKey || wantsRange)) {\n\t\t\tconst found = await this.fromIndex(q, { page, limit, search, sortKey, wantsRange, hierarchy })\n\t\t\tif (found) return found\n\t\t}\n\n\t\tconst sorted = !sortKey && !wantsRange\n\t\tif (q.category && !search) {\n\t\t\tconst env = await this.engine<{ products: Product[] | null }>(\n\t\t\t\t`/api/categories/${encodeURIComponent(q.category)}`,\n\t\t\t\t{ query: { page, limit } },\n\t\t\t)\n\t\t\tconst products = env.data?.products ?? []\n\t\t\treturn {\n\t\t\t\t...toPage({ data: products, meta: env.meta }, (p: Product) => toProduct(p)),\n\t\t\t\tcategoryHierarchy: hierarchy,\n\t\t\t\tsorted,\n\t\t\t}\n\t\t}\n\t\t// A search inside a category, without the index, searches the whole shop:\n\t\t// the engine's category route takes no query and its search takes no\n\t\t// category, and filtering one page client-side would make the count a lie.\n\t\tconst env = await this.engine<Product[] | null>('/api/products', {\n\t\t\tquery: { q: search, page, limit, channel: this.creds.channel, attr },\n\t\t})\n\t\treturn { ...toPage(env, (p: Product) => toProduct(p)), categoryHierarchy: hierarchy, sorted }\n\t}\n\n\t/**\n\t * The shelf from the Meilisearch module, or null when the store has it off,\n\t * sells through a channel, finds nothing for the words, or it cannot answer (Meilisearch down: the engine says `unavailable`), so\n\t * the caller asks the database instead of showing the shopper an error.\n\t */\n\tprotected async fromIndex(\n\t\tq: CatalogQuery,\n\t\to: { page: number; limit: number; search?: string; sortKey?: string; wantsRange: boolean; hierarchy: CatalogPage['categoryHierarchy'] },\n\t): Promise<CatalogPage | null> {\n\t\t// The index knows nothing of channels: a channel's shopper searches the\n\t\t// database, which shows only what the channel sells, at its prices.\n\t\tif (this.creds.channel || !(await this.facts.pluginOn('meilisearch'))) return null\n\t\tconst filters: string[] = []\n\t\tif (q.category) {\n\t\t\tconst names = (await this.facts.subtree(q.category).catch(() => [] as Category[])).map((c) => quote(c.full_name))\n\t\t\t// A slug the tree does not know sells nothing — say so, don't widen to the shop.\n\t\t\tif (!names.length) return { ...emptyCatalog(o.limit), categoryHierarchy: o.hierarchy, sorted: true }\n\t\t\tfilters.push(`category IN [${names.join(', ')}]`)\n\t\t}\n\t\tif (o.wantsRange) {\n\t\t\tconst { currency } = await this.facts.ready()\n\t\t\tif (Number.isFinite(q.priceFrom)) filters.push(`price_minor >= ${toMinor(q.priceFrom as number, currency)}`)\n\t\t\tif (Number.isFinite(q.priceTo)) filters.push(`price_minor <= ${toMinor(q.priceTo as number, currency)}`)\n\t\t}\n\t\tconst res = await this.data<SearchResult>('/x/meilisearch/search', {\n\t\t\tquery: {\n\t\t\t\tq: o.search ?? '',\n\t\t\t\tlimit: o.limit,\n\t\t\t\toffset: (o.page - 1) * o.limit,\n\t\t\t\tfilter: filters.join(' AND ') || undefined,\n\t\t\t\tsort: o.sortKey,\n\t\t\t},\n\t\t}).catch(() => null)\n\t\t// No hits for words may be an index still being built for a store that\n\t\t// just switched it on, or a sync that keeps failing: the database's\n\t\t// answer costs one query and is never worse than nothing.\n\t\tif (!res || res.unavailable || (o.search && !res.hits?.length)) return null\n\t\tconst total = res.total ?? 0\n\t\treturn {\n\t\t\tdata: (res.hits ?? []).map(fromSearchDoc),\n\t\t\tcount: total,\n\t\t\tpageSize: o.limit,\n\t\t\tnoOfPage: Math.max(1, Math.ceil(total / o.limit)),\n\t\t\tpage: o.page,\n\t\t\tcategoryHierarchy: o.hierarchy,\n\t\t\tsorted: true,\n\t\t}\n\t}\n}\n\nexport function emptyCatalog(limit = PAGE_SIZE) {\n\treturn { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 }\n}\n","import type { AddOn, Product, ReviewPage } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toAddOn, toProduct, toRating } from '../map'\nimport { currentMe } from '../browser'\nimport { CatalogService, PAGE_SIZE, type CatalogQuery } from './catalog'\n\n/**\n * Products: one by slug, and the shelves the homepage and listings draw.\n *\n * \"Featured\" and \"trending\" are curated rather than computed — the engine\n * keeps no sales or view counts to rank by. A collection with the slug\n * `featured` (or `trending`) is that shelf, so a merchant curates it in the\n * panel; without one, the shelf is the newest products, and says nothing more\n * about them than that.\n */\nexport class ProductService extends CatalogService {\n\t/**\n\t * A product page. `slug` may also be a numeric id or a variant SKU, which is\n\t * how an old link or a search hit sometimes arrives.\n\t *\n\t * Reviews ride along when ext/reviews is installed and switched on; a review\n\t * failure never costs the shopper the product page.\n\t */\n\tasync getOne(slug: string) {\n\t\tconst p = await this.findProduct(String(slug))\n\t\tconst product = toProduct(p, {\n\t\t\tcategoryHierarchy: p.category ? await this.facts.hierarchy(p.category.slug) : [],\n\t\t})\n\t\tif (await this.facts.pluginOn('product-reviews')) {\n\t\t\ttry {\n\t\t\t\tconst res = await this.data<ReviewPage>('/x/reviews', { query: { product_id: p.id, limit: 50 } })\n\t\t\t\tproduct.ratings = (res.reviews ?? []).map(toRating)\n\t\t\t\tproduct.rating = res.summary?.count ? res.summary.average : null\n\t\t\t\tproduct.ratingCount = res.summary?.count ?? 0\n\t\t\t\tproduct.reviewCount = res.summary?.count ?? 0\n\t\t\t} catch {\n\t\t\t\t// The page renders without stars rather than not at all.\n\t\t\t}\n\t\t}\n\t\treturn product\n\t}\n\n\tprivate async findProduct(slug: string): Promise<Product> {\n\t\ttry {\n\t\t\treturn await this.data<Product>(`/api/products/slug/${encodeURIComponent(slug)}`)\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t\t// Not a slug. An id or a SKU is worth one more question each, and a\n\t\t\t// miss on all three is the product's 404, not theirs.\n\t\t\tconst fallback = /^\\d+$/.test(slug) ? `/api/products/${slug}` : `/api/products/sku/${encodeURIComponent(slug)}`\n\t\t\ttry {\n\t\t\t\treturn await this.data<Product>(fallback)\n\t\t\t} catch {\n\t\t\t\tthrow err\n\t\t\t}\n\t\t}\n\t}\n\n\t/** The shop's listing: `{ page, search, sort }`, newest first unless the index can reorder it. */\n\tasync list({\n\t\tpage = 1,\n\t\tsearch,\n\t\tq,\n\t\tsort,\n\t\tlimit,\n\t\tcategories,\n\t}: CatalogQuery & { q?: string; categories?: string } = {}) {\n\t\tconst res = await this.queryCatalog({ page, search: search ?? q, sort, limit, category: categories || undefined })\n\t\treturn { data: res.data, count: res.count, pageSize: res.pageSize, noOfPage: res.noOfPage, page: res.page }\n\t}\n\n\tasync listFeaturedProducts({ page = 1, sort, limit }: { page?: number; sort?: string; limit?: number } = {}) {\n\t\treturn this.shelf('featured', { page, sort, limit })\n\t}\n\n\tasync listTrendingProducts({ page = 1, limit }: { page?: number; limit?: number } = {}) {\n\t\treturn this.shelf('trending', { page, limit })\n\t}\n\n\t/**\n\t * More like this product. Given `product` (a slug or id), it is the\n\t * product's category first, then its collections, then the newest — never\n\t * the product itself. Many shops never fill in categories, and an empty\n\t * rail under every product page reads as a broken shop.\n\t *\n\t * Without `product`, it is the old answer: more from `categoryId`.\n\t */\n\tasync listRelatedProducts({\n\t\tpage = 1,\n\t\tcategoryId,\n\t\tproduct,\n\t\tlimit,\n\t}: { page?: number; categoryId?: string; product?: string; limit?: number } = {}) {\n\t\tif (product) return this.relatedTo(String(product), limit)\n\t\tif (!categoryId) return this.list({ page, limit })\n\t\tconst category = (await this.facts.categories()).find((c) => String(c.id) === String(categoryId))\n\t\tif (!category) return this.list({ page, limit })\n\t\treturn this.list({ page, limit, categories: category.slug })\n\t}\n\n\t/**\n\t * What the shop offers with a product, ticked in its buy box (D133): each\n\t * add-on at the price ticking it adds. Only add-ons that can be bought\n\t * arrive; an engine without the route offers none.\n\t */\n\tasync listAddOns({ product }: { product: string }) {\n\t\tconst p = await this.findProduct(String(product))\n\t\ttry {\n\t\t\treturn ((await this.data<AddOn[] | null>('/api/add-ons', { query: { product_id: p.id } })) ?? []).map(toAddOn)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * \"You may also like\": the products the shop chose for this one, at their\n\t * own prices (D133). Curated only, and empty when none were chosen: the\n\t * related products already fill in from the category, and the page should\n\t * not draw the same fill twice.\n\t */\n\tasync listCrossSells({ product, limit }: { product: string; limit?: number }) {\n\t\tconst p = await this.findProduct(String(product))\n\t\ttry {\n\t\t\tconst rows = (await this.data<Product[] | null>('/api/cross-sells', { query: { product_id: p.id, limit } })) ?? []\n\t\t\treturn rows.map((r) => toProduct(r))\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tprivate async relatedTo(slug: string, limit?: number) {\n\t\tconst size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE))\n\t\tconst p = await this.findProduct(slug)\n\t\tconst self = String(p.id)\n\t\t// The listing answers either the engine's cards or the search index's,\n\t\t// so all a pick needs to know is the id.\n\t\tconst picked = new Map<string, { id: string }>()\n\t\tconst add = (rows: readonly { id: string }[]) => {\n\t\t\tfor (const r of rows) {\n\t\t\t\tif (picked.size >= size) return\n\t\t\t\tif (r.id !== self && !picked.has(r.id)) picked.set(r.id, r)\n\t\t\t}\n\t\t}\n\t\t// One more than needed, since the product itself may be among them.\n\t\tif (p.category) add((await this.list({ limit: size + 1, categories: p.category.slug })).data)\n\t\tfor (const c of p.collections ?? []) {\n\t\t\tif (picked.size >= size) break\n\t\t\tadd((await this.shelf(c.slug, { page: 1, limit: size + 1 })).data)\n\t\t}\n\t\tif (picked.size < size) add((await this.list({ limit: size + 1 })).data)\n\t\tconst data = [...picked.values()]\n\t\treturn { data, count: data.length, pageSize: size, noOfPage: 1, page: 1 }\n\t}\n\n\tprivate async shelf(slug: string, { page, sort, limit }: { page: number; sort?: string; limit?: number }) {\n\t\tconst size = Math.min(100, Math.max(1, Number(limit) || PAGE_SIZE))\n\t\ttry {\n\t\t\tconst env = await this.engine<{ products: Product[] | null }>(`/api/collections/${slug}`, {\n\t\t\t\tquery: { page, limit: size },\n\t\t\t})\n\t\t\tconst rows = env.data?.products ?? []\n\t\t\treturn {\n\t\t\t\tdata: rows.map((p) => toProduct(p)),\n\t\t\t\tcount: env.meta?.total ?? rows.length,\n\t\t\t\tpageSize: env.meta?.limit ?? size,\n\t\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\t\tpage: env.meta?.page ?? page,\n\t\t\t}\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t\treturn this.list({ page, sort, limit: size })\n\t\t}\n\t}\n\n\t/**\n\t * A review, through ext/reviews. The engine asks for a name and an email\n\t * with every review, so a signed-out shopper is asked to sign in rather\n\t * than having one made up for them. Uploaded photos have nowhere to go: the\n\t * module stores text.\n\t */\n\tasync addReview({\n\t\tproductId,\n\t\trating,\n\t\treview,\n\t\ttitle,\n\t}: {\n\t\tproductId: string\n\t\tvariantId?: string\n\t\trating: number\n\t\treview: string\n\t\ttitle?: string\n\t}) {\n\t\tconst me = currentMe()\n\t\tif (!me?.email) throw new GoCommerceError('Please sign in to write a review.', 401, 'unauthorized')\n\t\tconst name = [me.firstName, me.lastName].filter(Boolean).join(' ') || me.email.split('@')[0]\n\t\treturn this.data<{ status: string; verified: boolean }>('/x/reviews', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tproduct_id: Number(productId),\n\t\t\t\tname,\n\t\t\t\temail: me.email,\n\t\t\t\trating: Math.round(Number(rating)),\n\t\t\t\t...(title ? { title } : {}),\n\t\t\t\tbody: String(review ?? ''),\n\t\t\t},\n\t\t})\n\t}\n\n\tasync fetchReels(): Promise<never> {\n\t\tthrow new NotSupportedError('ProductService', 'fetchReels', 'the engine has no reels')\n\t}\n}\n\nexport const productService = new ProductService()\n","import type { Category, ProductFacets } from '../engine'\nimport { toMajor } from '../money'\nimport { CatalogService } from './catalog'\n\nconst num = (v: string | null): number | undefined => {\n\tif (v === null || v.trim() === '') return undefined\n\tconst n = Number(v)\n\treturn Number.isFinite(n) ? n : undefined\n}\n\n/** Decoded once more when it decodes: the storefront's filter rail encodes a value before the URL does. */\nfunction decodeOnce(v: string): string {\n\ttry {\n\t\treturn decodeURIComponent(v)\n\t} catch {\n\t\treturn v\n\t}\n}\n\n/** `?key=a,b` (repeatable) as `['a', 'b']`. */\nfunction listParam(p: URLSearchParams, key: string): string[] | undefined {\n\tconst out = p\n\t\t.getAll(key)\n\t\t.flatMap((v) => decodeOnce(v).split(','))\n\t\t.map((v) => v.trim())\n\t\t.filter(Boolean)\n\treturn out.length ? out : undefined\n}\n\n/** `?attributes.color=Red,Blue` — the storefront's facet params — as `{ color: ['Red', 'Blue'] }`. */\nfunction attributesFrom(p: URLSearchParams): Record<string, string[]> | undefined {\n\tconst out: Record<string, string[]> = {}\n\tfor (const key of new Set(p.keys())) {\n\t\tif (!key.startsWith('attributes.')) continue\n\t\tconst handle = key.slice('attributes.'.length)\n\t\tconst values = listParam(p, key)\n\t\tif (handle && values) out[handle] = values\n\t}\n\treturn Object.keys(out).length ? out : undefined\n}\n\nconst counts = (values: { value: string; count: number }[] | null | undefined) =>\n\tObject.fromEntries((values ?? []).map((v) => [v.value, v.count]))\n\ntype RailCategory = { name: string; slug: string; count: number; depth: number }\n\nfunction categoryFacets(counted: NonNullable<ProductFacets['categories']>, tree: Category[]): RailCategory[] {\n\tconst byId = new Map(tree.map((c) => [c.id, c]))\n\tconst totals = new Map<number, number>()\n\tfor (const { id, count } of counted) {\n\t\tfor (let c = byId.get(id); c; c = c.parent_id === null ? undefined : byId.get(c.parent_id)) {\n\t\t\ttotals.set(c.id, (totals.get(c.id) ?? 0) + count)\n\t\t}\n\t}\n\tconst kept = tree.filter((c) => totals.has(c.id)).sort((a, b) => a.position - b.position || a.id - b.id)\n\tconst parentOf = (c: Category) => (c.parent_id !== null && byId.has(c.parent_id) ? c.parent_id : null)\n\tconst under = (parent: number | null): RailCategory[] =>\n\t\tkept\n\t\t\t.filter((c) => parentOf(c) === parent)\n\t\t\t.flatMap((c) => [{ name: c.title, slug: c.slug, count: totals.get(c.id)!, depth: c.depth }, ...under(c.id)])\n\treturn [\n\t\t...under(null),\n\t\t...counted.filter((c) => !byId.has(c.id)).map((c) => ({ name: c.title, slug: c.slug, count: c.count, depth: 0 })),\n\t]\n}\n\n/**\n * The engine's counts in the shape the storefront's filter rail reads. Each\n * `allFilters` key is also the URL parameter the rail writes when a value is\n * ticked, and `searchWithUrl` reads it back: `vendor`, `product_type` and\n * `attributes.<handle>`. Tags go to the rail's own tag group, written as `tags`.\n */\nexport function toStorefrontFacets(f?: ProductFacets | null, tree: Category[] = []) {\n\tif (!f) return { priceStat: {}, categories: [], tags: [], allFilters: {} }\n\tconst allFilters: Record<string, Record<string, number>> = {}\n\tconst group = (key: string, values: { value: string; count: number }[] | null | undefined) => {\n\t\tif (values?.length) allFilters[key] = counts(values)\n\t}\n\tgroup('vendor', f.vendors)\n\tgroup('product_type', f.product_types)\n\tfor (const [handle, values] of Object.entries(f.attributes ?? {})) group(`attributes.${handle}`, values)\n\treturn {\n\t\tpriceStat: f.price ? { min: toMajor(f.price.min), max: toMajor(f.price.max) } : {},\n\t\tcategories: categoryFacets(f.categories ?? [], tree),\n\t\ttags: (f.tags ?? []).map((t) => ({ name: t.value, count: t.count })),\n\t\tallFilters,\n\t}\n}\n\n/**\n * The listing pages' search: `/products?search=&sort=&page=` and the category\n * catch-all `/{slug}`.\n *\n * Facets come from the engine, counted over the whole listing rather than the\n * page (D130). An engine too old to count them leaves them empty, and an empty\n * `priceStat` hides the price slider rather than drawing one with a made-up\n * range.\n */\nexport class SearchService extends CatalogService {\n\temptyResult() {\n\t\treturn {\n\t\t\tdata: [],\n\t\t\tcount: 0,\n\t\t\ttotalPages: 0,\n\t\t\tcategoryHierarchy: [] as { name: string; slug: string }[],\n\t\t\tfacets: toStorefrontFacets(),\n\t\t}\n\t}\n\n\tasync searchWithUrl(url: URL | string, slug?: string) {\n\t\ttry {\n\t\t\tconst u = typeof url === 'string' ? new URL(url, 'http://localhost') : url\n\t\t\tconst p = u.searchParams\n\t\t\t// `?price=10,50` is the chip form; priceFrom/priceTo the slider's.\n\t\t\tconst [from, to] = (p.get('price') ?? '').split(/[,-]/)\n\t\t\tconst res = await this.queryCatalog({\n\t\t\t\tpage: num(p.get('page')),\n\t\t\t\tsearch: p.get('search') ?? p.get('q') ?? undefined,\n\t\t\t\tsort: p.get('sort') ?? undefined,\n\t\t\t\tcategory: slug || p.get('categories')?.split(',')[0] || undefined,\n\t\t\t\tpriceFrom: num(p.get('priceFrom')) ?? num(from ?? null),\n\t\t\t\tpriceTo: num(p.get('priceTo')) ?? num(to ?? null),\n\t\t\t\tattributes: attributesFrom(p),\n\t\t\t\ttags: listParam(p, 'tags'),\n\t\t\t\tvendors: listParam(p, 'vendor'),\n\t\t\t\tproductTypes: listParam(p, 'product_type'),\n\t\t\t\tfacets: true,\n\t\t\t})\n\t\t\tconst tree = res.facets?.categories?.length ? await this.facts.categories().catch(() => [] as Category[]) : []\n\t\t\treturn {\n\t\t\t\tdata: res.data,\n\t\t\t\tcount: res.count,\n\t\t\t\ttotalPages: res.noOfPage,\n\t\t\t\tpage: res.page,\n\t\t\t\tcategoryHierarchy: res.categoryHierarchy,\n\t\t\t\tfacets: toStorefrontFacets(res.facets, tree),\n\t\t\t}\n\t\t} catch (err) {\n\t\t\t// A missing category is an empty result — the route turns that into\n\t\t\t// its 404 — but an engine that cannot be reached is not, and says so.\n\t\t\tif ((err as { status?: number })?.status === 404) return this.emptyResult()\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\nexport const searchService = new SearchService()\n","import type { Product } from '../engine'\nimport { toProduct } from '../map'\nimport { CatalogService } from './catalog'\n\n/**\n * The two places the storefront asks for raw search hits: \"more from this\n * category\" on a product page, and the header's type-ahead.\n *\n * Both go through ext/search-meilisearch when it is installed, and through the\n * engine's own listing when it is not — a type-ahead backed by a LIKE query is\n * slower and unranked, but it is not empty.\n */\nexport class MeilisearchService extends CatalogService {\n\t/** `{ query, categories, page }` → a Meilisearch-shaped answer: `hits`, `totalHits`, `totalPages`. */\n\tasync search({\n\t\tquery,\n\t\tsearch,\n\t\tcategories,\n\t\tpage = 1,\n\t\tlimit,\n\t}: { query?: string; search?: string; categories?: string; page?: number; limit?: number } = {}) {\n\t\tconst res = await this.queryCatalog({ page, limit, search: query ?? search, category: categories || undefined })\n\t\treturn {\n\t\t\thits: res.data,\n\t\t\ttotalHits: res.count,\n\t\t\testimatedTotalHits: res.count,\n\t\t\ttotalPages: res.noOfPage,\n\t\t\tpage: res.page,\n\t\t\tcategories: res.categoryHierarchy,\n\t\t\tfacetDistribution: {},\n\t\t}\n\t}\n\n\t/** The header's type-ahead: `{ data: [{ slug, title, thumbnail, price }] }`. */\n\tasync searchAutoComplete({ query, search, limit = 8 }: { query?: string; search?: string; limit?: number } = {}) {\n\t\tconst q = (query ?? search ?? '').trim()\n\t\tif (!q) return { data: [] }\n\t\tconst found = await this.fromIndex({}, { page: 1, limit, search: q, wantsRange: false, hierarchy: [] })\n\t\tif (found) return { data: found.data }\n\t\tconst rows =\n\t\t\t(await this.data<Product[] | null>('/api/products', { query: { q, limit, channel: this.creds.channel } })) ?? []\n\t\treturn { data: rows.map((p) => toProduct(p)) }\n\t}\n}\n\nexport const meilisearchService = new MeilisearchService()\n","import type { Category } from '../engine'\nimport { toCategory } from '../map'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\n\nconst asList = (rows: ReturnType<typeof toCategory>[]) => ({\n\tdata: rows,\n\tcount: rows.length,\n\tpageSize: rows.length,\n\tnoOfPage: 1,\n\tpage: 1,\n})\n\n/**\n * The category tree. The engine has no \"featured\" flag on a category, so the\n * featured row is the top level of the tree, in the merchant's order — which\n * is what a shop's first row of category tiles usually is anyway.\n */\nexport class CategoryService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/** Every category, flat, each naming its parent. The storefront builds the tree. */\n\tasync fetchAllCategories(_args: Record<string, unknown> = {}) {\n\t\tconst all = await this.facts.categories()\n\t\treturn asList(all.map(flat))\n\t}\n\n\tasync fetchFeaturedCategories({ limit = 18 }: { limit?: number } = {}) {\n\t\tconst roots = (await this.facts.categories()).filter((c) => c.parent_id === null)\n\t\treturn asList(roots.slice(0, Math.max(0, Number(limit) || 18)).map(flat))\n\t}\n\n\tasync fetchFooterCategories(args: { limit?: number } = {}) {\n\t\treturn this.fetchFeaturedCategories(args)\n\t}\n\n\t/** The nested tree, roots first. */\n\tasync getMegamenu(_args: Record<string, unknown> = {}) {\n\t\tconst tree = (await this.data<Category[] | null>('/api/categories')) ?? []\n\t\treturn tree.map(toCategory)\n\t}\n\n\tasync fetchCategory(slug: string) {\n\t\tconst c = await this.data<Category>(`/api/categories/${encodeURIComponent(slug)}`, { query: { limit: 1 } })\n\t\treturn toCategory(c)\n\t}\n\n\t/**\n\t * kitcommerce-core's category filter asks for `/api/categories/all` by path,\n\t * through the family's raw `get`. That is a Litekart path the rest-guard\n\t * would swallow, so it is answered here, from the engine's tree.\n\t */\n\toverride async get<T = any>(path: string): Promise<T> {\n\t\tif (path.split('?')[0] === '/api/categories/all') return (await this.fetchAllCategories()) as T\n\t\treturn super.get<T>(path)\n\t}\n}\n\n/** One row of the flat tree: no `children`, so the storefront's builder is the only one. */\nconst flat = (c: Category) => ({ ...toCategory(c), children: [] })\n\nexport const categoryService = new CategoryService()\n","import type { Collection, Product } from '../engine'\nimport { toCollection, toProduct } from '../map'\nimport { BaseService, toPage } from './base.service'\n\n/** Curated lists. Only collections holding at least one product on sale are listed. */\nexport class CollectionService extends BaseService {\n\tasync list({ page = 1, limit = 24 }: { page?: number; limit?: number; sort?: string; q?: string } = {}) {\n\t\tconst env = await this.engine<Collection[] | null>('/api/collections', { query: { page, limit } })\n\t\treturn toPage(env, toCollection)\n\t}\n\n\t/** A collection page: the collection, and its products in the merchant's order. */\n\tasync getOne(slug: string, { page = 1, limit = 48 }: { page?: number; limit?: number } = {}) {\n\t\tconst env = await this.engine<Collection & { products: Product[] | null }>(\n\t\t\t`/api/collections/${encodeURIComponent(slug)}`,\n\t\t\t{ query: { page, limit } },\n\t\t)\n\t\tconst products = (env.data.products ?? []).map((p) => toProduct(p))\n\t\treturn {\n\t\t\t...toCollection(env.data),\n\t\t\tproducts,\n\t\t\t// The family's shape for a collection's members.\n\t\t\tcollectionvalues: products.map((p) => ({ products: p })),\n\t\t\tcount: env.meta?.total ?? products.length,\n\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\tpage: env.meta?.page ?? page,\n\t\t}\n\t}\n\n\t/** Collection-level ratings are a Litekart aggregate; the engine has none to report. */\n\tasync getAllRatings() {\n\t\treturn { data: [] as unknown[] }\n\t}\n}\n\nexport const collectionService = new CollectionService()\n","import type { AppliedDiscount, Cart, CartLine, CartOffer, FreeShipping, Product } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { emptyCart, toCart, toCartOffer, toFreeShipping, toProduct } from '../map'\nimport { remember } from '../cache'\nimport {\n\tcartExtras,\n\tforgetCartExtras,\n\trememberCartId,\n\tsaveCartExtras,\n\tsessionToken,\n\tstoredCartId,\n\ttype StorefrontAddress,\n} from '../browser'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { ProductService } from './product-service'\n\n/** The storefront's \"take this line out\" sentinel, sent when − is pressed on a quantity of one. */\nconst REMOVE = -9999999\n\n/**\n * The bag.\n *\n * The engine's cart is addressed by an opaque token it mints, held by the\n * storefront in `localStorage.cart_id`. It keeps lines and an email; the\n * coupon, the address and the delivery choice the storefront collects before\n * checkout are kept beside it in the browser (browser.ts) and sent with the\n * checkout request, which is the only place the engine takes them.\n *\n * Every method answers the whole cart, as the storefront assigns it whole.\n */\nexport class CartService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync getCartByCartId(cartId?: string | null) {\n\t\tconst id = clean(cartId)\n\t\tif (!id) return emptyCart(await this.currency())\n\t\ttry {\n\t\t\treturn await this.present(await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`))\n\t\t} catch (err) {\n\t\t\t// A cart expires after a month untouched. A shopper coming back to a\n\t\t\t// dead token sees an empty bag, not an error.\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return emptyCart(await this.currency())\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tasync fetchCartData(cartId?: string | null) {\n\t\treturn this.getCartByCartId(cartId ?? storedCartId())\n\t}\n\n\t/**\n\t * The cart after an order: the engine marks it `converted` and keeps its\n\t * lines, and this answers it with none — which is how the storefront knows\n\t * to clear the bag on the success page.\n\t */\n\tasync refereshCart() {\n\t\tconst id = storedCartId()\n\t\tconst cart = await this.getCartByCartId(id)\n\t\tif (id && (cart as { status?: string }).status === 'converted') forgetCartExtras(id)\n\t\treturn cart\n\t}\n\n\t/**\n\t * `qty` is a change, not a total: +1 from a product page, −1 from a card's\n\t * minus button. With no cart yet, one is opened and remembered. A\n\t * `designId` from `customizerService.saveDesign` makes the variant to the\n\t * shopper's design, on a line of its own.\n\t */\n\tasync addToCart({\n\t\tcartId,\n\t\tlineId,\n\t\tqty = 1,\n\t\tvariantId,\n\t\tdesignId,\n\t}: {\n\t\tcartId?: string | null\n\t\tlineId?: string | null\n\t\tqty?: number\n\t\tproductId?: string\n\t\tvariantId?: string\n\t\tdesignId?: string\n\t}) {\n\t\tlet id = clean(cartId) ?? storedCartId()\n\t\tif (lineId && id) {\n\t\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\t\tconst line = (cart.line_items ?? []).find((l) => String(l.id) === String(lineId))\n\t\t\tif (line) {\n\t\t\t\tconst next = qty === REMOVE ? 0 : line.quantity + Number(qty)\n\t\t\t\treturn this.setQuantity(id, line.id, next)\n\t\t\t}\n\t\t}\n\t\tif (qty === REMOVE || Number(qty) <= 0) return this.getCartByCartId(id)\n\t\tif (!variantId) throw new GoCommerceError('Please choose an option before adding this to your bag.', 400)\n\t\tif (!id) id = await this.open()\n\t\tconst body = { variant_id: Number(variantId), quantity: Number(qty), ...(designId ? { design_id: designId } : {}) }\n\t\ttry {\n\t\t\treturn await this.present(\n\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items`, { method: 'POST', body }),\n\t\t\t)\n\t\t} catch (err) {\n\t\t\t// The remembered cart was checked out in another tab, or expired, so a\n\t\t\t// new one is started rather than refusing the shopper's click. A missing\n\t\t\t// variant or design is a 404 too, and must not leave the bag behind.\n\t\t\tif (cartGone(err)) {\n\t\t\t\tconst fresh = await this.open()\n\t\t\t\treturn this.present(\n\t\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(fresh)}/line-items`, { method: 'POST', body }),\n\t\t\t\t)\n\t\t\t}\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * Adds an add-on from a product's \"Complete the set\" (D133) at its offer\n\t * price. The product it is offered with has to be in the bag already, so\n\t * this is called after adding it; the engine refuses one too many with the\n\t * sentence the shopper is shown.\n\t */\n\tasync addAddOn({ cartId, addOnId, qty = 1 }: { cartId?: string | null; addOnId: string | number; qty?: number }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) throw new GoCommerceError('Add the product to your bag first.', 409)\n\t\treturn this.present(\n\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: { add_on_id: Number(addOnId), quantity: Number(qty) },\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * The codes the shop chose to show (D133), each with what it takes off this\n\t * bag or how much more the bag needs. None without a bag.\n\t */\n\tasync getOffers({ cartId }: { cartId?: string | null } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return []\n\t\ttry {\n\t\t\tconst rows = (await this.data<CartOffer[] | null>(`/api/carts/${encodeURIComponent(id)}/offers`)) ?? []\n\t\t\tconst currency = await this.currency()\n\t\t\treturn rows.map((o) => toCartOffer(o, o.amount?.currency ?? o.remaining?.currency ?? currency))\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return []\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * How far the bag is from free delivery (D133), read from the store's own\n\t * rates for the country (the store's own when none is given). Null when\n\t * the engine cannot say: a bar with a made-up figure is worse than none.\n\t */\n\tasync getFreeShipping({ cartId, country, state }: { cartId?: string | null; country?: string; state?: string } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return null\n\t\tconst where = country ?? cartExtras(id).shippingAddress?.country ?? undefined\n\t\ttry {\n\t\t\treturn toFreeShipping(\n\t\t\t\tawait this.data<FreeShipping>(`/api/carts/${encodeURIComponent(id)}/free-shipping`, {\n\t\t\t\t\tquery: { country: where || undefined, state: state || undefined },\n\t\t\t\t}),\n\t\t\t)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return null\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * \"You may be interested in\" (D133): what the bag's products suggest, less\n\t * what it holds; with nothing curated, the first product's related\n\t * products, still less what it holds.\n\t */\n\tasync listCrossSells({ cartId, limit = 12 }: { cartId?: string | null; limit?: number } = {}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return []\n\t\tlet curated: Product[] = []\n\t\ttry {\n\t\t\tcurated = (await this.data<Product[] | null>(`/api/carts/${encodeURIComponent(id)}/cross-sells`, { query: { limit } })) ?? []\n\t\t} catch (err) {\n\t\t\tif (!(err instanceof GoCommerceError) || err.status !== 404) throw err\n\t\t}\n\t\tif (curated.length) return curated.map((p) => toProduct(p))\n\t\tlet cart: Cart\n\t\ttry {\n\t\t\tcart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\t} catch {\n\t\t\treturn []\n\t\t}\n\t\tconst held = new Set((cart.line_items ?? []).map((l) => String(l.product_id)))\n\t\tconst first = cart.line_items?.[0]\n\t\tif (!first) return []\n\t\tconst related = await new ProductService(this._fetch).listRelatedProducts({\n\t\t\tproduct: String(first.product_id),\n\t\t\tlimit: limit + held.size,\n\t\t})\n\t\treturn (related.data as { id: string }[]).filter((p) => !held.has(String(p.id))).slice(0, limit)\n\t}\n\n\t/** `qty` is the new total; 0 takes the line out. */\n\tasync updateCart({\n\t\tcartId,\n\t\tlineId,\n\t\tqty,\n\t}: {\n\t\tcartId?: string\n\t\tlineId: string\n\t\tqty: number\n\t\tisSelectedForCheckout?: boolean\n\t}) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\treturn this.setQuantity(id, lineId, Number(qty))\n\t}\n\n\tasync removeCart({ cartId, lineId }: { cartId?: string; lineId: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\treturn this.present(\n\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/line-items/${encodeURIComponent(String(lineId))}`, {\n\t\t\t\tmethod: 'DELETE',\n\t\t\t}),\n\t\t)\n\t}\n\n\t/**\n\t * Contact details and addresses, from the checkout's address step. The\n\t * email goes to the engine — it is how an abandoned cart is followed up —\n\t * and the rest is kept for the checkout request.\n\t */\n\tasync updateCart2(args: {\n\t\tcartId?: string\n\t\temail?: string\n\t\tphone?: string\n\t\tshippingAddress?: StorefrontAddress | null\n\t\tbillingAddress?: StorefrontAddress | null\n\t\tisBillingAddressSameAsShipping?: boolean\n\t}) {\n\t\tconst id = clean(args.cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\n\t\tconst patch: Parameters<typeof saveCartExtras>[1] = {}\n\t\tif (args.phone !== undefined) patch.phone = args.phone || undefined\n\t\tif (args.shippingAddress !== undefined) {\n\t\t\tpatch.shippingAddress = args.shippingAddress\n\t\t\tif (args.shippingAddress?.phone && !patch.phone) patch.phone = String(args.shippingAddress.phone)\n\t\t}\n\t\tif (args.billingAddress !== undefined || args.isBillingAddressSameAsShipping) {\n\t\t\tpatch.billingAddress = args.isBillingAddressSameAsShipping ? null : (args.billingAddress ?? null)\n\t\t}\n\t\t// A new destination may not be served by the rate chosen for the old one.\n\t\tconst before = cartExtras(id)\n\t\tconst country = (a?: StorefrontAddress | null) => String(a?.countryCode || a?.country || '').toUpperCase()\n\t\tif (args.shippingAddress !== undefined && country(args.shippingAddress) !== country(before.shippingAddress)) {\n\t\t\tpatch.shippingRateId = null\n\t\t\tpatch.shippingRate = null\n\t\t}\n\t\tsaveCartExtras(id, patch)\n\n\t\tconst email = args.email ?? (args.shippingAddress?.email ? String(args.shippingAddress.email) : undefined)\n\t\tif (email !== undefined) {\n\t\t\treturn this.present(\n\t\t\t\tawait this.data<Cart>(`/api/carts/${encodeURIComponent(id)}/email`, { method: 'PUT', body: { email } }),\n\t\t\t)\n\t\t}\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/**\n\t * A discount code. The engine prices it against the basket now and decides\n\t * it again at checkout; what it answers is kept so the bag can show it,\n\t * because the cart itself does not carry the code.\n\t */\n\tasync applyCoupon({ cartId, couponCode }: { cartId?: string; couponCode: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) throw new GoCommerceError('Add something to your bag before applying a code.', 400)\n\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\tconst discount = await this.data<AppliedDiscount>(`/api/carts/${encodeURIComponent(id)}/discount`, {\n\t\t\tmethod: 'PUT',\n\t\t\tbody: { code: String(couponCode ?? '').trim(), ...(cart.email ? { email: cart.email } : {}) },\n\t\t})\n\t\tsaveCartExtras(id, { discount: { ...discount, code: discount.code || String(couponCode).trim() } })\n\t\treturn this.present(cart)\n\t}\n\n\tasync removeCoupon(cartId?: string) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\tawait this.engine(`/api/carts/${encodeURIComponent(id)}/discount`, { method: 'DELETE' })\n\t\tsaveCartExtras(id, { discount: null })\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/** The delivery option the shopper picked, priced from the engine's own quote. */\n\tasync updateShippingRate({ cartId, shippingRateId }: { cartId?: string; shippingRateId: string }) {\n\t\tconst id = clean(cartId) ?? storedCartId()\n\t\tif (!id) return emptyCart(await this.currency())\n\t\tconst ship = cartExtras(id).shippingAddress\n\t\tconst country = String(ship?.countryCode || ship?.country || '').toUpperCase()\n\t\tif (!country) throw new GoCommerceError('Add a delivery address first.', 400)\n\t\tconst quote = await this.data<{\n\t\t\trates: { rate_id: number; name: string; price: { amount_minor: number; currency: string } }[] | null\n\t\t\tcurrency: string\n\t\t}>('/api/checkout/rates', { query: { cart: id, country, state: ship?.state ? String(ship.state) : undefined } })\n\t\tconst rate = (quote.rates ?? []).find((r) => String(r.rate_id) === String(shippingRateId))\n\t\tif (!rate) throw new GoCommerceError('That delivery option is not available for this address any more.', 409)\n\t\tsaveCartExtras(id, {\n\t\t\tshippingRateId: String(rate.rate_id),\n\t\t\tshippingRate: {\n\t\t\t\tid: String(rate.rate_id),\n\t\t\t\tname: rate.name,\n\t\t\t\tminor: rate.price.amount_minor,\n\t\t\t\tcurrency: rate.price.currency,\n\t\t\t},\n\t\t})\n\t\treturn this.getCartByCartId(id)\n\t}\n\n\t/** The payment method is chosen at checkout, by which checkout route is called. */\n\tasync updateCartPaymentMethod({ cartId }: { cartId?: string; paymentMethod?: string }) {\n\t\treturn this.getCartByCartId(clean(cartId) ?? storedCartId())\n\t}\n\n\tasync completeCart(): Promise<never> {\n\t\tthrow new NotSupportedError('CartService', 'completeCart', 'an order is placed through checkoutService')\n\t}\n\n\t// ------------------------------------------------------------ internals\n\n\tprivate async setQuantity(cartId: string, lineId: string | number, qty: number) {\n\t\tconst path = `/api/carts/${encodeURIComponent(cartId)}/line-items/${encodeURIComponent(String(lineId))}`\n\t\t// Zero is a removal: the engine accepts it on PATCH, and DELETE says it plainly.\n\t\tif (qty <= 0) return this.present(await this.data<Cart>(path, { method: 'DELETE' }))\n\t\treturn this.present(await this.data<Cart>(path, { method: 'PATCH', body: { quantity: qty } }))\n\t}\n\n\t/** A new cart, remembered — and priced for the signed-in shopper's group when the engine allows it. */\n\tprivate async open(): Promise<string> {\n\t\tconst channel = this.creds.channel\n\t\tconst cart = await this.data<Cart>('/api/carts', { method: 'POST', ...(channel ? { body: { channel } } : {}) })\n\t\trememberCartId(cart.id)\n\t\tif (sessionToken()) await this.claimCartForAccount(cart.id)\n\t\treturn cart.id\n\t}\n\n\tprivate async currency(): Promise<string> {\n\t\ttry {\n\t\t\treturn (await this.facts.ready()).currency\n\t\t} catch {\n\t\t\treturn 'USD'\n\t\t}\n\t}\n\n\t/** The engine's cart with the browser-held extras and each line's picture and link. */\n\tprivate async present(cart: Cart) {\n\t\tconst ids = [...new Set((cart.line_items ?? []).map((l) => l.product_id))]\n\t\tconst products = new Map<number, Product | null>()\n\t\tawait Promise.all(\n\t\t\tids.map(async (pid) => {\n\t\t\t\tproducts.set(pid, await this.productFor(pid))\n\t\t\t}),\n\t\t)\n\t\treturn toCart(cart, cartExtras(cart.id), (l: CartLine) => {\n\t\t\tconst p = products.get(l.product_id)\n\t\t\tif (!p) return {}\n\t\t\tconst v = (p.variants ?? []).find((x) => x.id === l.variant_id)\n\t\t\treturn { slug: p.slug, thumbnail: v?.image?.url ?? p.image_url ?? null }\n\t\t})\n\t}\n\n\tprivate productFor(id: number): Promise<Product | null> {\n\t\treturn remember(`${this.engineBase()}|product|${id}`, () =>\n\t\t\tthis.data<Product>(`/api/products/${id}`).catch(() => null),\n\t\t)\n\t}\n}\n\nconst clean = (id?: string | null): string | null => (id && id !== 'undefined' && id !== 'null' ? id : null)\n\nconst cartGone = (err: unknown): boolean =>\n\terr instanceof GoCommerceError &&\n\t(err.code === 'cart_not_found' || err.code === 'cart_checked_out' || cartGoneOnOlderEngine(err))\n\nconst cartGoneOnOlderEngine = (err: GoCommerceError): boolean =>\n\t(err.code === 'not_found' && err.message === 'cart not found') ||\n\t(err.code === 'conflict' && err.message === 'this cart has already been checked out')\n\nexport const cartService = new CartService()\n","import type { CustomizerDesign, CustomizerDocument, CustomizerSetup, CustomizerUpload } from '../engine'\nimport { BaseService, mediaUrl } from './base.service'\nimport { StoreFacts } from './facts'\n\n/** What a product's design editor draws and offers, in the mockup's pixels. */\nexport type CustomizerEditor = {\n\tproductId: string\n\tmockup: { url: string; width: number; height: number }\n\t/** Drawn above the design: the camera cut-out, the case's edges. */\n\toverlayUrl: string | null\n\tprintArea: { x: number; y: number; width: number; height: number; radius: number }\n\tprintSize: { widthMm: number; heightMm: number; dpi: number }\n\ttools: { upload: boolean; text: boolean; shapes: boolean; background: boolean; stickers: boolean }\n\tfonts: { key: string; family: string }[]\n\tstickers: { id: number; url: string; width: number; height: number }[]\n\t/** A photo whose shorter side is below this is likely to print soft: warn, the engine still takes it. */\n\tminPhotoPx: number\n\t/** Shown before the shopper chooses a photo. */\n\tconsent: string\n}\n\nexport type CustomizerFile = { uploadId: string; url: string; width: number; height: number }\n\nexport type CustomizerSavedDesign = { designId: string; previewUrl: string }\n\n/**\n * A shopper's own design on a product (ext/customizer, D162). Every URL goes\n * through the proxy path when one is set, so it is same-origin and a canvas\n * that draws it can still be exported.\n */\nexport class CustomizerService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/** Null when the product cannot be designed, or on any failure: the page draws without the editor. */\n\tasync setup(productId: string | number): Promise<CustomizerEditor | null> {\n\t\tconst plugins = await this.facts.plugins().catch(() => null)\n\t\tif (plugins && !plugins.has('customizer')) return null\n\t\tconst path = `/x/customizer/products/${encodeURIComponent(String(productId))}`\n\t\tconst s = await this.data<CustomizerSetup>(path).catch(() => null)\n\t\tif (!s) return null\n\t\treturn {\n\t\t\tproductId: String(s.product_id),\n\t\t\tmockup: { ...s.mockup, url: media(s.mockup.url) },\n\t\t\toverlayUrl: mediaUrl(s.overlay_url),\n\t\t\tprintArea: s.print_area,\n\t\t\tprintSize: { widthMm: s.print_size.width_mm, heightMm: s.print_size.height_mm, dpi: s.print_size.dpi },\n\t\t\ttools: s.tools,\n\t\t\tfonts: s.fonts,\n\t\t\tstickers: s.stickers.map((k) => ({ ...k, url: media(k.url) })),\n\t\t\tminPhotoPx: s.min_photo_px,\n\t\t\tconsent: s.consent,\n\t\t}\n\t}\n\n\t/** A photo, or the finished preview or print file. The engine's refusal is thrown with its message. */\n\tasync upload(file: Blob, filename?: string): Promise<CustomizerFile> {\n\t\tconst body = new FormData()\n\t\tbody.append('file', file, filename)\n\t\tconst u = await this.data<CustomizerUpload>('/x/customizer/uploads', { method: 'POST', body })\n\t\treturn { uploadId: u.upload_id, url: media(u.url), width: u.width, height: u.height }\n\t}\n\n\t/** The document goes as it is: the order keeps it, and whatever renders the print reads it there. */\n\tasync saveDesign(design: {\n\t\tproductId: string | number\n\t\tvariantId: string | number\n\t\tpreviewUploadId: string\n\t\tprintUploadId: string\n\t\tdocument: CustomizerDocument\n\t}): Promise<CustomizerSavedDesign> {\n\t\tconst d = await this.data<CustomizerDesign>('/x/customizer/designs', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tproduct_id: Number(design.productId),\n\t\t\t\tvariant_id: Number(design.variantId),\n\t\t\t\tpreview_upload_id: design.previewUploadId,\n\t\t\t\tprint_upload_id: design.printUploadId,\n\t\t\t\tdocument: design.document,\n\t\t\t},\n\t\t})\n\t\treturn { designId: d.design_id, previewUrl: media(d.preview_url) }\n\t}\n}\n\nconst media = (url: string) => mediaUrl(url) ?? url\n\nexport const customizerService = new CustomizerService()\n","import type { Cart, CheckoutQuote, CheckoutResult } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toCheckoutQuote, toEngineAddress, toOrder } from '../map'\nimport { minorToMajor, toMinor } from '../money'\nimport {\n\tcartExtras,\n\tlandingAttribution,\n\tmetaBrowser,\n\tplacedOrderByReference,\n\trememberOrder,\n\tsaveCartExtras,\n\tsessionToken,\n\tstoredCartId,\n} from '../browser'\nimport { BaseService } from './base.service'\n\n/**\n * Placing an order.\n *\n * The engine turns a cart into an order in one call, `POST /api/checkout/{code}`,\n * and that call is the only thing that moves stock and asks for money. It takes\n * the address, phone and delivery choice in its body — the cart keeps none of\n * them — so they are read back from what the address step stored (browser.ts).\n *\n * Payment is confirmed by the gateway's webhook to the engine, never by the\n * storefront. So the \"capture\" calls the storefront makes after a gateway's\n * modal closes do not capture anything: they hand back the order number, and\n * the order page shows `payment_status` once the webhook has landed.\n */\nexport class CheckoutService extends BaseService {\n\tprivate expected = new Map<string, Expected>()\n\n\t/** Delivery options for the address on the cart: `{ data: [{ id, name, base_rate }] }`. */\n\tasync getShippingRates({ cartId }: { cartId?: string } = {}) {\n\t\tconst id = cartId || storedCartId()\n\t\tconst ship = id ? cartExtras(id).shippingAddress : null\n\t\tconst country = String(ship?.countryCode || ship?.country || '').toUpperCase()\n\t\tif (!id || !country) return { data: [] }\n\t\tconst quote = await this.data<{\n\t\t\trates: { rate_id: number; name: string; price: { amount_minor: number; currency: string } }[] | null\n\t\t\tcurrency: string\n\t\t}>('/api/checkout/rates', { query: { cart: id, country, state: ship?.state ? String(ship.state) : undefined } })\n\t\treturn {\n\t\t\tdata: (quote.rates ?? []).map((r) => ({\n\t\t\t\tid: String(r.rate_id),\n\t\t\t\tname: r.name,\n\t\t\t\tdescription: null,\n\t\t\t\tbase_rate: minorToMajor(r.price.amount_minor, r.price.currency),\n\t\t\t\tprice: minorToMajor(r.price.amount_minor, r.price.currency),\n\t\t\t\tcurrencyCode: r.price.currency,\n\t\t\t\t// The engine's rates carry no delivery estimate; none is made up.\n\t\t\t\testimated_min_days: null,\n\t\t\t\testimated_max_days: null,\n\t\t\t})),\n\t\t}\n\t}\n\n\t/** Cash on delivery: the order is confirmed at once and paid on the doorstep. */\n\tasync checkoutCOD({ cartId }: { cartId?: string; origin?: string } = {}) {\n\t\tconst result = await this.place('cod', cartId)\n\t\treturn {\n\t\t\torder_no: result.order.number,\n\t\t\torderNo: result.order.number,\n\t\t\tid: String(result.order.id),\n\t\t\tstatus: result.order.status,\n\t\t}\n\t}\n\n\t/**\n\t * Razorpay's modal. The engine has already created the Razorpay order; this\n\t * hands the storefront what the modal needs. A store running Razorpay's\n\t * hosted (redirect) mode cannot be driven from this storefront's modal flow,\n\t * and says so rather than opening a modal on an order it cannot pay.\n\t */\n\tasync checkoutRazorpay({ cartId }: { cartId?: string; origin?: string } = {}) {\n\t\tconst result = await this.place('razorpay', cartId)\n\t\tconst data = result.payment.client_data ?? {}\n\t\tif (result.payment.kind !== 'client_action' || !data.razorpay_order_id) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'This store takes Razorpay payments on Razorpay’s own page, which this storefront does not support yet.',\n\t\t\t\t0,\n\t\t\t)\n\t\t}\n\t\treturn {\n\t\t\torder_no: result.order.number,\n\t\t\tid: data.razorpay_order_id,\n\t\t\tkey_id: data.key_id,\n\t\t\tamount: Number(data.amount),\n\t\t\tcurrency: data.currency,\n\t\t}\n\t}\n\n\t/** The modal closed with a payment. The engine learns of it from Razorpay itself. */\n\tasync captureRazorpayPayment({ razorpay_order_id }: { razorpay_order_id: string; razorpay_payment_id?: string }) {\n\t\tconst order = placedOrderByReference(razorpay_order_id)\n\t\tif (!order) throw new GoCommerceError('That payment does not belong to an order placed from this browser.', 404)\n\t\treturn { order_no: order.number, status: 'processing' }\n\t}\n\n\t// The family's other gateway flows. GoCommerce's Stripe is a Payment\n\t// Element (a client secret, not a hosted page) — `checkout('stripe')` returns\n\t// that secret for a storefront that mounts the element. Cashfree, PhonePe and\n\t// Affirm are not engine gateways at all. paymentMethodService never offers\n\t// these codes, so they are reached only by a storefront that hard-codes one.\n\tasync checkoutStripe(): Promise<never> {\n\t\tthrow unsupported(\n\t\t\t'checkoutStripe',\n\t\t\t'GoCommerce’s Stripe gateway uses the Payment Element, not a hosted checkout page',\n\t\t)\n\t}\n\tasync checkoutStripeCapture(): Promise<never> {\n\t\tthrow unsupported('checkoutStripeCapture', 'Stripe confirms payments to the engine by webhook')\n\t}\n\t/**\n\t * The storefront's generic redirect flow, which it reaches through the code\n\t * `PAYPAL`. The engine has no PayPal gateway; paymentMethodService puts the\n\t * store's first hosted-page gateway — Adyen, Paddle, Lemon Squeezy, Creem,\n\t * Hyperswitch or RevenueCat — under that code, with its own name and a\n\t * neutral icon, because this is the one storefront flow that sends a shopper\n\t * to a URL and back. The shopper returns to the success page; the gateway's\n\t * webhook tells the engine the order is paid.\n\t */\n\tasync checkoutPaypal({ cartId, origin }: { cartId?: string; origin?: string; return_url?: string } = {}) {\n\t\tconst gateway = await this.redirectGateway()\n\t\tif (!gateway) throw unsupported('checkoutPaypal', 'this store has no hosted-page payment gateway switched on')\n\t\tconst id = cartId || storedCartId() || ''\n\t\tconst back = origin ? `${origin.replace(/\\/+$/, '')}/checkout/success?cart_id=${encodeURIComponent(id)}` : undefined\n\t\tconst result = await this.place(gateway, id, back ? { return_url: back } : {})\n\t\tconst url = result.payment.client_data?.url\n\t\tif (!url) throw new GoCommerceError('The payment page did not open. Please try again.', 502)\n\t\treturn { redirect_url: url, order_no: result.order.number }\n\t}\n\n\t/**\n\t * Nothing to capture: a hosted-page gateway confirms the payment to the\n\t * engine by webhook. Answering, rather than throwing, sends the storefront's\n\t * process page on to the success page instead of the failure page.\n\t */\n\tasync capturePaypalPayment({\n\t\torder_no,\n\t}: { order_no?: string; token?: string; PayerID?: string; storeId?: string } = {}) {\n\t\treturn { order_no: order_no ?? null, status: 'processing' }\n\t}\n\tasync checkoutCashfree(): Promise<never> {\n\t\tthrow unsupported('checkoutCashfree', 'the engine has no Cashfree gateway')\n\t}\n\tasync captureCashfreePayment(): Promise<never> {\n\t\tthrow unsupported('captureCashfreePayment', 'the engine has no Cashfree gateway')\n\t}\n\tasync checkoutPhonepe(): Promise<never> {\n\t\tthrow unsupported('checkoutPhonepe', 'the engine has no PhonePe gateway')\n\t}\n\tasync createAffirmPayOrder(): Promise<never> {\n\t\tthrow unsupported('createAffirmPayOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync confirmAffirmOrder(): Promise<never> {\n\t\tthrow unsupported('confirmAffirmOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync cancelAffirmOrder(): Promise<never> {\n\t\tthrow unsupported('cancelAffirmOrder', 'the engine has no Affirm gateway')\n\t}\n\tasync checkoutPOS(): Promise<never> {\n\t\tthrow unsupported('checkoutPOS', 'point-of-sale orders are placed from the admin panel')\n\t}\n\n\t/**\n\t * Any payment method the engine has switched on, by its engine code —\n\t * `cod`, `stripe`, `razorpay`, `adyen`, `paddle`, `helcim`… For a storefront\n\t * that drives the payment itself: the answer says what to do next.\n\t *\n\t * - `kind: 'none'` — nothing to pay now (cash on delivery).\n\t * - `kind: 'client_action'` — mount the gateway's own widget with\n\t * `clientData`: Stripe's Payment Element takes `clientSecret`, Razorpay's\n\t * modal `razorpay_order_id` and `key_id`, Helcim's `checkout_token`.\n\t * - `kind: 'redirect'` — send the shopper to `redirectUrl`; `returnUrl` is\n\t * where the gateway brings them back.\n\t *\n\t * Either way the gateway's webhook tells the engine when the money arrives;\n\t * read `orderService.getOrder(orderNo).paymentStatus` to see it.\n\t */\n\tasync checkout(\n\t\tcode: string,\n\t\t{\n\t\t\tcartId,\n\t\t\treturnUrl,\n\t\t\tpaymentData,\n\t\t\tmetadata,\n\t\t}: {\n\t\t\tcartId?: string\n\t\t\treturnUrl?: string\n\t\t\tpaymentData?: Record<string, string>\n\t\t\tmetadata?: Record<string, unknown>\n\t\t} = {},\n\t) {\n\t\tconst result = await this.place(String(code).toLowerCase(), cartId, {\n\t\t\t...(returnUrl ? { return_url: returnUrl } : {}),\n\t\t\t...(paymentData ? { payment_data: paymentData } : {}),\n\t\t\t...(metadata ? { metadata } : {}),\n\t\t})\n\t\tconst data = result.payment.client_data ?? {}\n\t\treturn {\n\t\t\torderNo: result.order.number,\n\t\t\torder: toOrder(result.order),\n\t\t\tpayment: {\n\t\t\t\tkind: result.payment.kind,\n\t\t\t\tprovider: result.payment.provider,\n\t\t\t\treference: result.payment.reference ?? null,\n\t\t\t\tclientSecret: data.client_secret ?? null,\n\t\t\t\tredirectUrl: data.url ?? null,\n\t\t\t\tclientData: data,\n\t\t\t},\n\t\t}\n\t}\n\n\t/** Every payment method the engine has switched on, by engine code and name — drivable here or not. */\n\tasync listMethods() {\n\t\tconst options = await this.data<{ methods: { code: string; name: string }[] | null; currency: string }>(\n\t\t\t'/api/checkout',\n\t\t)\n\t\treturn { methods: options.methods ?? [], currency: options.currency }\n\t}\n\n\t/**\n\t * What checkout would charge for the cart now, by the storefront's method\n\t * code (`COD`, `RAZORPAY`, `PAYPAL`) or none yet (D185). Null until the\n\t * address step has stored an address, and null from an engine before D185.\n\t *\n\t * A refusal is checkout's own: the same GoCommerceError, with the same\n\t * message, that placing the order would raise now.\n\t */\n\tasync getQuote({ cartId, method = '' }: { cartId?: string; method?: string } = {}) {\n\t\tconst id = cartId || storedCartId()\n\t\tif (!id || !cartExtras(id).shippingAddress) return null\n\t\tconst { extras, email, address } = await this.storedCheckout(id)\n\t\tconst code = method.toLowerCase() === 'paypal' ? await this.redirectGateway() : method.toLowerCase()\n\t\ttry {\n\t\t\tconst quote = await this.data<CheckoutQuote>('/api/checkout/quote', {\n\t\t\t\tquery: {\n\t\t\t\t\tcart: id,\n\t\t\t\t\tcountry: address.country,\n\t\t\t\t\tstate: address.state,\n\t\t\t\t\tshipping_rate_id: extras.shippingRateId || undefined,\n\t\t\t\t\tmethod: code || undefined,\n\t\t\t\t\temail: email || undefined,\n\t\t\t\t},\n\t\t\t})\n\t\t\treturn toCheckoutQuote(quote)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 405 || (err.status === 404 && err.message.startsWith('no route for ')))) {\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/**\n\t * The total on screen as the shopper confirms, from getQuote, or null when nothing was quoted\n\t * (D185). Every order placed for the cart then carries it, and checkout refuses one whose own\n\t * total differs instead of charging it: `onChange` gets checkout's figures now and the sentence\n\t * the placing call fails with.\n\t */\n\texpectTotal({\n\t\tcartId,\n\t\ttotal,\n\t\tonChange,\n\t}: {\n\t\tcartId?: string\n\t\ttotal?: number | null\n\t\tonChange?: Expected['onChange']\n\t}) {\n\t\tconst id = cartId || storedCartId()\n\t\tif (!id) return\n\t\tif (typeof total === 'number') this.expected.set(id, { total, onChange })\n\t\telse this.expected.delete(id)\n\t}\n\n\tprivate async storedCheckout(cartId?: string) {\n\t\tconst id = cartId || storedCartId()\n\t\tif (!id) throw new GoCommerceError('Your bag is empty.', 400)\n\t\tconst extras = cartExtras(id)\n\t\tconst ship = extras.shippingAddress\n\t\tif (!ship) throw new GoCommerceError('Add a delivery address first.', 400)\n\t\tconst cart = await this.data<Cart>(`/api/carts/${encodeURIComponent(id)}`)\n\t\tconst email = cart.email || (ship.email ? String(ship.email) : '')\n\t\treturn { id, extras, email, address: toEngineAddress(ship), currency: cart.currency }\n\t}\n\n\tprivate async redirectGateway(): Promise<string | undefined> {\n\t\tconst { methods } = await this.listMethods()\n\t\treturn methods.find((m) => REDIRECT_GATEWAYS.has(m.code))?.code\n\t}\n\n\t/**\n\t * One checkout attempt.\n\t *\n\t * The Idempotency-Key is kept with the cart and reused while the request is\n\t * the same, because a payment gateway that fails after the engine has\n\t * created the order leaves the cart converted: only a retry under the same\n\t * key resumes that order, and without one the shopper is stuck. A changed\n\t * request — a different address, a different method — gets a new key, since\n\t * the engine refuses a key replayed with a different body.\n\t */\n\tprivate async place(\n\t\tcode: string,\n\t\tcartId?: string,\n\t\textra: { return_url?: string; payment_data?: Record<string, string>; metadata?: Record<string, unknown> } = {},\n\t): Promise<CheckoutResult> {\n\t\tconst { id, extras, email, address, currency } = await this.storedCheckout(cartId)\n\t\tif (!email) throw new GoCommerceError('Add an email address so we can send your receipt.', 400)\n\t\tconst body = {\n\t\t\tcart_id: id,\n\t\t\temail,\n\t\t\t...(extras.phone || address.phone ? { phone: String(extras.phone || address.phone) } : {}),\n\t\t\t...(address.name ? { name: address.name } : {}),\n\t\t\taddress,\n\t\t\t...(extras.shippingRateId ? { shipping_rate_id: Number(extras.shippingRateId) } : {}),\n\t\t\t...extra,\n\t\t}\n\t\tconst serialised = JSON.stringify(body)\n\t\tconst retry = extras.attempt?.body === `${code}:${serialised}`\n\t\tconst key = retry ? extras.attempt!.key : newKey()\n\t\t// Where Meta's pixel ran (metaBrowser) is not part of what makes a retry the same\n\t\t// request: the shopper can accept the cookie banner, or Meta set _fbc, between a failed\n\t\t// attempt and the next. A retry sends the first attempt's, since the engine refuses a key\n\t\t// replayed with a different body.\n\t\tconst meta = retry ? extras.attempt?.meta : metaBrowser()\n\t\t// Where the shopper came from (D168), held the same way: a retry sends what the first attempt did.\n\t\tconst attribution = retry ? extras.attempt?.attribution : landingAttribution()\n\t\tsaveCartExtras(id, {\n\t\t\tattempt: { key, body: `${code}:${serialised}`, ...(meta ? { meta } : {}), ...(attribution ? { attribution } : {}) },\n\t\t})\n\t\tconst metadata = {\n\t\t\t...extra.metadata,\n\t\t\t...(meta ? { meta_capi: meta } : {}),\n\t\t\t...(attribution ? { attribution } : {}),\n\t\t}\n\n\t\tconst expected = this.expected.get(id)\n\n\t\tconst result = await this.data<CheckoutResult>(`/api/checkout/${encodeURIComponent(code)}`, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\t...(Object.keys(metadata).length ? { ...body, metadata } : body),\n\t\t\t\t...(expected ? { quoted_total_minor: toMinor(expected.total, currency) } : {}),\n\t\t\t},\n\t\t\theaders: { 'Idempotency-Key': key },\n\t\t}).catch((err: unknown) => {\n\t\t\tif (keyAlreadyUsed(err)) {\n\t\t\t\tthrow new GoCommerceError('This order was already placed in another tab. Check that tab for its confirmation.', 400, err.code)\n\t\t\t}\n\t\t\tconst now = movedTotal(err)\n\t\t\tif (!expected || !now) throw err\n\t\t\tconst message = `Your total changed to ${shopperAmount(now.total, currency)}. Check the new total and confirm again.`\n\t\t\texpected.onChange?.(now, message)\n\t\t\tthrow new GoCommerceError(message, 409, 'total_changed', now)\n\t\t})\n\n\t\t// The access token is returned once; a replayed response leaves it out,\n\t\t// so a replay must not overwrite the one already kept.\n\t\tif (result.order.access_token) {\n\t\t\trememberOrder({\n\t\t\t\tnumber: result.order.number,\n\t\t\t\ttoken: result.order.access_token,\n\t\t\t\tcartId: id,\n\t\t\t\treference: result.payment.client_data?.razorpay_order_id ?? result.payment.reference,\n\t\t\t})\n\t\t\t// A signed-in shopper's order joins their account. The engine never\n\t\t\t// links an order by email, so this call is the only way it appears\n\t\t\t// under \"My orders\".\n\t\t\tif (sessionToken()) {\n\t\t\t\tawait this.engine('/x/identity/me/orders', {\n\t\t\t\t\tmethod: 'POST',\n\t\t\t\t\tbody: { number: result.order.number, token: result.order.access_token },\n\t\t\t\t\tauth: true,\n\t\t\t\t}).catch(() => undefined)\n\t\t\t}\n\t\t}\n\t\tsaveCartExtras(id, { attempt: null })\n\t\treturn result\n\t}\n}\n\n/** The engine's gateways that take payment on their own hosted page. */\nexport const REDIRECT_GATEWAYS = new Set(['adyen', 'paddle', 'lemonsqueezy', 'creem', 'hyperswitch', 'revenuecat'])\n\nconst unsupported = (method: string, why: string) => new NotSupportedError('CheckoutService', method, why)\n\ntype Expected = { total: number; onChange?: (quote: ReturnType<typeof toCheckoutQuote>, message: string) => void }\n\n// The engine stores a key only with the order it placed, so a key it calls used was spent by a tab\n// that showed another total.\nfunction keyAlreadyUsed(err: unknown): err is GoCommerceError {\n\treturn err instanceof GoCommerceError && err.status === 400 && err.message.includes('Idempotency-Key was already used')\n}\n\nfunction movedTotal(err: unknown) {\n\tif (!(err instanceof GoCommerceError) || err.code !== 'total_changed') return null\n\tconst now = err.details as CheckoutQuote | null\n\treturn now?.total ? toCheckoutQuote(now) : null\n}\n\nfunction shopperAmount(amount: number, currency: string): string {\n\treturn new Intl.NumberFormat(currency === 'INR' ? 'en-IN' : 'en', {\n\t\tstyle: 'currency',\n\t\tcurrency,\n\t\t...(Number.isInteger(amount) ? { minimumFractionDigits: 0 } : {}),\n\t}).format(amount)\n}\n\nfunction newKey(): string {\n\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n\tif (c?.randomUUID) return c.randomUUID()\n\treturn `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`\n}\n\nexport const checkoutService = new CheckoutService()\n","import { toMajor } from '../money'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { REDIRECT_GATEWAYS } from './checkout-service'\n\n/**\n * The engine's payment methods this storefront can actually drive.\n *\n * The storefront dispatches on an upper-cased code from a fixed list, so a\n * method is offered only where one of its flows can complete it: cash on\n * delivery, Razorpay's modal, and — through the storefront's redirect flow,\n * which it reaches by the code `PAYPAL` — the first of the engine's hosted-page\n * gateways. That one keeps its own name and gets a neutral card icon, never a\n * PayPal mark. The flow carries no gateway code, so a second hosted-page\n * gateway cannot be told apart from the first and is not offered; nor is\n * Stripe, whose engine gateway is a Payment Element this storefront does not\n * mount. Each method left off is reported once, and every one stays reachable\n * through `checkoutService.checkout(code)` for a storefront that drives its own.\n */\nconst DRIVABLE: Record<string, { code: string; img?: string }> = {\n\tcod: { code: 'COD', img: '/payment/cod.svg' },\n\trazorpay: { code: 'RAZORPAY' },\n}\n\nconst reported = new Set<string>()\n\nexport class PaymentMethodService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst options = await this.facts.checkoutOptions()\n\t\tconst methods = options.methods ?? []\n\t\tconst redirect = methods.find((m) => REDIRECT_GATEWAYS.has(m.code))?.code\n\t\tconst drive = (code: string) =>\n\t\t\tDRIVABLE[code] ?? (code === redirect ? { code: 'PAYPAL', img: '/payment/card.svg' } : undefined)\n\t\tconst data = methods\n\t\t\t.filter((m) => {\n\t\t\t\tif (drive(m.code)) return true\n\t\t\t\tif (!reported.has(m.code)) {\n\t\t\t\t\treported.add(m.code)\n\t\t\t\t\tconsole.warn(\n\t\t\t\t\t\t`[gocommerce] payment method \"${m.code}\" is switched on but this storefront cannot drive its flow, so it is not offered here; checkoutService.checkout('${m.code}') still reaches it.`,\n\t\t\t\t\t)\n\t\t\t\t}\n\t\t\t\treturn false\n\t\t\t})\n\t\t\t.map((m, i) => ({\n\t\t\t\tid: m.code,\n\t\t\t\tcode: drive(m.code)!.code,\n\t\t\t\tengineCode: m.code,\n\t\t\t\tname: m.name,\n\t\t\t\ttitle: m.name,\n\t\t\t\tdescription: '',\n\t\t\t\timg: drive(m.code)!.img ?? null,\n\t\t\t\tfee: toMajor(m.fee),\n\t\t\t\trank: i,\n\t\t\t\tactive: true,\n\t\t\t\tisActive: true,\n\t\t\t}))\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\nexport const paymentMethodService = new PaymentMethodService()\n","import { emptyPage } from './base.service'\nimport { BaseService } from './base.service'\nimport { CartService } from './cart-service'\n\n/**\n * Discount codes are typed, not browsed, except the ones the shop chose to\n * show (D133): the engine lists a code only when the shop ticked \"Show in the\n * basket's offers\", judged against the stored bag. Every other code stays\n * known only to whoever was given it, and still works through\n * `cartService.applyCoupon`.\n *\n * The drawer's shape: `amount` is the percentage or the amount,\n * `minAmount` the bag it needs, `description` says what is\n * still missing, and `autoApply` marks a code checkout applies by\n * itself (D179).\n */\nexport class CouponService extends BaseService {\n\tasync listCoupons(_args: Record<string, unknown> = {}) {\n\t\tconst offers = await new CartService(this._fetch).getOffers().catch(() => [])\n\t\tif (!offers.length) return emptyPage()\n\t\tconst data = offers.map((o) => ({\n\t\t\tid: o.code,\n\t\t\tcode: o.code,\n\t\t\ttitle: o.title,\n\t\t\tisPercent: o.isPercent,\n\t\t\tamount: o.value,\n\t\t\tminAmount: o.minAmount,\n\t\t\tdescription: o.applies\n\t\t\t\t? o.title\n\t\t\t\t: o.remaining !== null\n\t\t\t\t\t? `${o.title}. Add ${o.remaining} more to use this.`\n\t\t\t\t\t: o.reason || o.title,\n\t\t\tapplies: o.applies,\n\t\t\tremaining: o.remaining,\n\t\t\tautoApply: o.autoApply,\n\t\t}))\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\nexport const couponService = new CouponService()\n","import type { Order, Product } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toOrder } from '../map'\nimport { toMajor } from '../money'\nimport { inBrowser, placedOrder, placedOrderForCart, rememberOrder, sessionToken } from '../browser'\nimport { BaseService, emptyPage, mediaUrl, toPage } from './base.service'\n\n/**\n * Orders, read back two ways.\n *\n * A guest's order is read with the access token checkout returned, which this\n * connector kept in the browser that placed it (`GET /api/orders/{n}?token=`).\n * A signed-in shopper's orders are the ones joined to their account\n * (ext/identity's `/me/orders`). There is no third way: an order list that\n * answered without either would be every order in the shop.\n */\nexport class OrderService extends BaseService {\n\t/**\n\t * The order-success page's lookup, by the number and cart in its URL.\n\t *\n\t * It runs on the server, where neither the token nor the session exists —\n\t * they live in the shopper's browser — so there it answers nothing and the\n\t * page says the details are not available yet. In the browser it answers\n\t * the order. Inventing a server-side credential from the cart token in the\n\t * URL would make that URL, which lands in history and referrers, a key to\n\t * the shopper's address.\n\t */\n\tasync listOrdersByParent({ orderNo, cartId }: { orderNo?: string; cartId?: string } = {}) {\n\t\tconst number = clean(orderNo) ?? (clean(cartId) ? placedOrderForCart(clean(cartId) as string)?.number : undefined)\n\t\tif (!number) return { data: [] }\n\t\ttry {\n\t\t\treturn { data: [await this.getOrder(number)] }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 404 || err.status === 401)) return { data: [] }\n\t\t\tthrow err\n\t\t}\n\t}\n\n\t/** The signed-in shopper's orders, newest claim first. */\n\tasync list({ page = 1, limit = 20 }: { page?: number; limit?: number; q?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<Order[] | null>('/x/identity/me/orders', { query: { page, limit }, auth: true })\n\t\treturn toPage(env, toOrder)\n\t}\n\n\t/** One order by number: the account's when signed in, otherwise one this browser placed. */\n\tasync getOrder(number: string) {\n\t\tconst kept = placedOrder(number)\n\t\tif (kept) {\n\t\t\treturn toOrder(\n\t\t\t\tawait this.data<Order>(`/api/orders/${encodeURIComponent(number)}`, { query: { token: kept.token } }),\n\t\t\t)\n\t\t}\n\t\tif (sessionToken()) {\n\t\t\treturn toOrder(await this.data<Order>(`/x/identity/me/orders/${encodeURIComponent(number)}`, { auth: true }))\n\t\t}\n\t\tthrow new GoCommerceError(\n\t\t\tinBrowser() ? 'Sign in to see this order, or open it from the browser that placed it.' : 'order not found',\n\t\t\t404,\n\t\t\t'not_found',\n\t\t)\n\t}\n\n\t/** Everything the signed-in shopper has bought, once each, most recent first. */\n\tasync buyAgain() {\n\t\tconst orders =\n\t\t\t(await this.data<Order[] | null>('/x/identity/me/orders', { query: { limit: 20 }, auth: true })) ?? []\n\t\tconst seen = new Set<number>()\n\t\tconst lines: {\n\t\t\tproductId: number\n\t\t\tvariantId: number\n\t\t\ttitle: string\n\t\t\timg: string | null\n\t\t\tprice: number\n\t\t\tqty: number\n\t\t\tdesignId: string | null\n\t\t}[] = []\n\t\tfor (const o of orders) {\n\t\t\tfor (const l of o.line_items ?? []) {\n\t\t\t\tif (!l.product_id || !l.variant_id || seen.has(l.variant_id)) continue\n\t\t\t\tseen.add(l.variant_id)\n\t\t\t\tlines.push({\n\t\t\t\t\tproductId: l.product_id,\n\t\t\t\t\tvariantId: l.variant_id,\n\t\t\t\t\ttitle: l.title,\n\t\t\t\t\timg: mediaUrl(l.image_url),\n\t\t\t\t\tprice: toMajor(l.unit_price),\n\t\t\t\t\tqty: l.quantity,\n\t\t\t\t\tdesignId: l.metadata?.design?.id ?? null,\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\t\t// A product taken off sale is no longer something to buy again.\n\t\tconst live = await Promise.all(\n\t\t\tlines.map((l) => this.data<Product>(`/api/products/${l.productId}`).catch(() => null)),\n\t\t)\n\t\treturn lines.flatMap((l, i) => {\n\t\t\tconst p = live[i]\n\t\t\tif (!p) return []\n\t\t\tconst designable = typeof p.designable === 'boolean' ? p.designable : undefined\n\t\t\treturn [{ ...l, productId: String(l.productId), variantId: String(l.variantId), slug: p.slug, designable }]\n\t\t})\n\t}\n\n\t/** The \"someone just bought\" popup would publish other shoppers' purchases; the engine offers none. */\n\tasync listPublic(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\n\t/**\n\t * Opens an order with its number and the email or phone on it, no code. The\n\t * engine answers one 404 for an unknown number and a wrong contact. The\n\t * token it answers is kept like an order placed in this browser, so the\n\t * order page and `getOrder` read it again.\n\t */\n\tasync openOrder({ orderNo, contact }: { orderNo: string; contact: string }) {\n\t\tconst res = await this.data<{ order: Order; access_token: string }>(\n\t\t\t`/api/orders/${encodeURIComponent(orderNo.trim())}/open`,\n\t\t\t{ method: 'POST', body: { contact: contact.trim() } },\n\t\t)\n\t\trememberOrder({ number: res.order.number, token: res.access_token, cartId: '' })\n\t\treturn { data: [toOrder(res.order)] }\n\t}\n\n\t/**\n\t * Opens an order from the link in its emails, which carries the order's key\n\t * (`/order-tracking?order=…&key=…`). The key is kept like an order placed in\n\t * this browser, so the page can drop it from the address bar.\n\t */\n\tasync openOrderWithKey({ orderNo, key }: { orderNo: string; key: string }) {\n\t\tconst number = orderNo.trim()\n\t\tconst order = await this.data<Order>(`/api/orders/${encodeURIComponent(number)}`, { query: { token: key.trim() } })\n\t\trememberOrder({ number: order.number, token: key.trim(), cartId: '' })\n\t\treturn { data: [toOrder(order)] }\n\t}\n\n\t/**\n\t * Sends a 4-digit code to the email or phone on the order, when `contact`\n\t * is that email or phone. The engine answers the same either way, so this\n\t * resolves whether or not anything was sent.\n\t */\n\tasync requestOrderCode({ orderNo, contact }: { orderNo: string; contact: string }) {\n\t\tconst res = await this.data<{ expires_in_minutes: number }>(\n\t\t\t`/api/orders/${encodeURIComponent(orderNo.trim())}/code`,\n\t\t\t{ method: 'POST', body: { contact: contact.trim() } },\n\t\t)\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/**\n\t * Opens an order with the code `requestOrderCode` sent. The token it answers\n\t * is kept like an order placed in this browser, so the order page and\n\t * `getOrder` read it again without another code.\n\t */\n\tasync getOrderByEmailAndOTP({ orderNo, otp }: { orderNo: string; otp: string; email?: string }) {\n\t\tconst number = orderNo.trim()\n\t\tconst res = await this.data<{ order: Order; access_token: string }>(\n\t\t\t`/api/orders/${encodeURIComponent(number)}/code/verify`,\n\t\t\t{ method: 'POST', body: { code: String(otp).trim() } },\n\t\t)\n\t\trememberOrder({ number: res.order.number, token: res.access_token, cartId: '' })\n\t\treturn { data: [toOrder(res.order)] }\n\t}\n}\n\nconst clean = (v?: string | null) => (v && v !== 'undefined' && v !== 'null' ? v : undefined)\n\nexport const orderService = new OrderService()\n","import type { AuthResponse, Customer, Order } from '../engine'\nimport { GoCommerceError, NotSupportedError } from '../errors'\nimport { toOrder, toUser } from '../map'\nimport { endSession, placedOrder, startSession, storedCartId, updateMe } from '../browser'\nimport { StoreFacts } from './facts'\nimport { BaseService } from './base.service'\n\n/**\n * Shopper accounts, through ext/identity.\n *\n * Guest checkout stays the engine's default (D22): an account is a place to\n * keep addresses and see past orders, never a requirement to buy. A store\n * built without `-identity` answers every call here with a 404, which arrives\n * as \"Accounts are not available on this store\" rather than as a route error.\n */\nexport class UserService extends BaseService {\n\t/**\n\t * Email and password. The answer is the user object the storefront keeps in its `me` cookie.\n\t * With `phone` and `phoneToken` from `verifyOtp({ askIfNew: true })`, the phone is added to\n\t * the account as it signs in (D123).\n\t */\n\tasync login({\n\t\temail,\n\t\tpassword,\n\t\tphone,\n\t\tphoneToken,\n\t}: {\n\t\temail: string\n\t\tpassword: string\n\t\tphone?: string\n\t\tphoneToken?: string\n\t\tcartId?: string | null\n\t}) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/login', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\temail: String(email ?? '').trim(),\n\t\t\t\tpassword: String(password ?? ''),\n\t\t\t\t...(phoneToken ? { phone: String(phone ?? '').trim(), phone_token: phoneToken } : {}),\n\t\t\t},\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\tasync signup({\n\t\temail,\n\t\tpassword,\n\t\tfirstName,\n\t\tlastName,\n\t\tphone,\n\t}: {\n\t\temail: string\n\t\tpassword: string\n\t\tfirstName?: string\n\t\tlastName?: string\n\t\tphone?: string\n\t\tcartId?: string | null\n\t\torigin?: string\n\t}) {\n\t\tconst name = [firstName, lastName].filter(Boolean).join(' ').trim()\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/register', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\temail: String(email ?? '').trim(),\n\t\t\t\tpassword: String(password ?? ''),\n\t\t\t\t...(name ? { name } : {}),\n\t\t\t\t...(phone ? { phone: String(phone) } : {}),\n\t\t\t},\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\t/** Signs out here and on the engine. The storefront assigns the answer to its user: `null`. */\n\tasync logout() {\n\t\tawait this.engine('/x/identity/logout', { method: 'POST', auth: true }).catch(() => undefined)\n\t\tendSession()\n\t\treturn null\n\t}\n\n\tasync getMe() {\n\t\treturn toUser(await this.account<Customer>('/x/identity/me', { auth: true }))\n\t}\n\n\tasync updateProfile(user: { firstName?: string; lastName?: string; name?: string; email?: string; phone?: string }) {\n\t\tconst name =\n\t\t\tuser.name ??\n\t\t\t[user.firstName, user.lastName]\n\t\t\t\t.filter((v) => v !== undefined)\n\t\t\t\t.join(' ')\n\t\t\t\t.trim()\n\t\tconst c = await this.account<Customer>('/x/identity/me', {\n\t\t\tmethod: 'PATCH',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\t...(name !== undefined ? { name } : {}),\n\t\t\t\t...(user.email ? { email: String(user.email).trim() } : {}),\n\t\t\t\t...(user.phone !== undefined && user.phone !== null ? { phone: String(user.phone) } : {}),\n\t\t\t},\n\t\t})\n\t\tupdateMe(c)\n\t\treturn toUser(c)\n\t}\n\n\t/**\n\t * A password change ends every session the account had, this one included,\n\t * and the engine answers a fresh one — which is kept, so the shopper stays\n\t * signed in here and nowhere else.\n\t */\n\tasync changePassword({ old, oldPassword, password }: { old?: string; oldPassword?: string; password: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/me/password', {\n\t\t\tmethod: 'PUT',\n\t\t\tauth: true,\n\t\t\tbody: { current_password: String(old ?? oldPassword ?? ''), password: String(password ?? '') },\n\t\t})\n\t\tstartSession(auth)\n\t\treturn toUser(auth.record)\n\t}\n\n\t/**\n\t * Mails the signed-in shopper a link to confirm their address. The engine\n\t * sends none at signup, and a confirmed address is what customer-group\n\t * prices are keyed on. 409 once confirmed; 429 within a minute of the last.\n\t */\n\tasync requestEmailVerification() {\n\t\treturn this.account<{ accepted: boolean }>('/x/identity/me/email-verification', { method: 'POST', auth: true })\n\t}\n\n\t/** Extends the session another thirty days. The token stays the same. */\n\tasync refreshSession() {\n\t\treturn startSession(await this.account<AuthResponse>('/x/identity/refresh', { method: 'POST', auth: true }))\n\t}\n\n\t/**\n\t * Files a guest order under the signed-in account, so it appears in their\n\t * order history. The order's access token is the proof of ownership: pass\n\t * it, or leave it out for an order placed from this browser, whose token was\n\t * kept at checkout.\n\t *\n\t * Never done automatically at sign-in. On a shared computer that would file\n\t * one person's orders — address and all — under whoever signed in next.\n\t */\n\tasync claimOrder({ number, token }: { number: string; token?: string }) {\n\t\tconst proof = token ?? placedOrder(number)?.token\n\t\tif (!proof) {\n\t\t\tthrow new GoCommerceError(\n\t\t\t\t'This order was not placed from this browser; enter the code from its confirmation.',\n\t\t\t\t400,\n\t\t\t)\n\t\t}\n\t\tconst order = await this.account<Order>('/x/identity/me/orders', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { number: String(number), token: proof },\n\t\t})\n\t\treturn toOrder(order)\n\t}\n\n\tasync deleteUser(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'deleteUser', 'an account is closed by the store, on request')\n\t}\n\n\tasync checkEmail(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'checkEmail', 'the engine does not say which addresses have accounts')\n\t}\n\n\tasync joinAsVendor(): Promise<never> {\n\t\tthrow new NotSupportedError('UserService', 'joinAsVendor', 'sellers are invited by the store')\n\t}\n\n\tprotected async signedIn(auth: AuthResponse) {\n\t\tconst me = startSession(auth)\n\t\tconst cartId = storedCartId()\n\t\tif (cartId) await this.claimCartForAccount(cartId)\n\t\treturn me\n\t}\n\n\t/** An identity call, with a 404 from a build without the module said in words. */\n\tprotected async account<T>(path: string, req: Parameters<BaseService['engine']>[1] = {}): Promise<T> {\n\t\ttry {\n\t\t\treturn await this.data<T>(path, req)\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404 && /no route/i.test(err.message)) {\n\t\t\t\tthrow new GoCommerceError('Accounts are not available on this store.', 404, 'not_found')\n\t\t\t}\n\t\t\tif (err instanceof GoCommerceError && err.status === 401 && req.auth) endSession()\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\n/**\n * Password resets, email confirmation, and phone sign-in. A store signs its\n * customers in one way (D116), read from `loginMethod`; the engine refuses\n * the other.\n */\nexport class AuthService extends UserService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/**\n\t * How this store signs customers in: `email_password` or `phone_otp`.\n\t * A store whose accounts module says nothing signs in by email.\n\t */\n\tasync loginMethod(): Promise<'email_password' | 'phone_otp' | 'email_or_phone'> {\n\t\ttry {\n\t\t\tconst method = (await this.facts.plugins()).get('identity')?.settings?.login_method\n\t\t\treturn method === 'phone_otp' || method === 'email_or_phone' ? method : 'email_password'\n\t\t} catch {\n\t\t\treturn 'email_password'\n\t\t}\n\t}\n\n\tasync forgotPassword({ email }: { email: string; referrer?: string }) {\n\t\treturn this.account<{ accepted: boolean }>('/x/identity/password-reset', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { email: String(email ?? '').trim() },\n\t\t})\n\t}\n\n\t/** The token arrives in the link the engine emailed (`GOCOMMERCE_IDENTITY_RESET_URL`). */\n\tasync resetPassword({ token, password }: { userId?: string; token: string; password: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/password-reset/confirm', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { token: String(token ?? ''), password: String(password ?? '') },\n\t\t})\n\t\treturn startSession(auth)\n\t}\n\n\t/** Answers `{ errorCode, message }` on failure rather than throwing: that is how the page reads it. */\n\tasync verifyEmail(_email: string | undefined, token: string) {\n\t\ttry {\n\t\t\tconst c = await this.account<Customer>('/x/identity/email-verification/confirm', {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbody: { token: String(token ?? '') },\n\t\t\t})\n\t\t\treturn { ...toUser(c), message: 'Your email address is confirmed.' }\n\t\t} catch (err) {\n\t\t\treturn { errorCode: (err as GoCommerceError).code ?? 'invalid_token', message: (err as Error).message }\n\t\t}\n\t}\n\n\t/**\n\t * Texts a 4-digit sign-in code to `phone`, which needs its country code. `domain`, the page's\n\t * host and in the browser read from it, lets the engine end the text \"@domain #code\" when the\n\t * host is the store's own, which Chrome on Android reads to fill the code in (D124).\n\t */\n\tasync getOtp({ phone, domain }: { phone: string; domain?: string }) {\n\t\tconst site = domain ?? (typeof window !== 'undefined' ? window.location?.hostname : undefined)\n\t\tconst res = await this.account<{ expires_in_minutes: number }>('/x/identity/otp', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { phone: String(phone ?? '').trim(), ...(site ? { domain: site } : {}) },\n\t\t})\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/**\n\t * Signs in the account on `phone` with the code it was sent, opening one the first time.\n\t * With `askIfNew`, on a store that signs in either way, a phone with no account opens none:\n\t * the answer is `{ newPhone: true, phoneToken }`, and the storefront asks \"Already have an\n\t * account?\" — `login` with the token adds the phone to it, `openPhoneAccount` opens a new one (D123).\n\t */\n\tasync verifyOtp({ phone, otp, askIfNew }: { phone: string; otp: string; askIfNew?: boolean }) {\n\t\tconst res = await this.account<AuthResponse | { new_phone: true; phone_token: string }>('/x/identity/otp/verify', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tphone: String(phone ?? '').trim(),\n\t\t\t\tcode: String(otp ?? '').trim(),\n\t\t\t\t...(askIfNew ? { ask_if_new: true } : {}),\n\t\t\t},\n\t\t})\n\t\tif ('new_phone' in res && res.new_phone) return { newPhone: true as const, phoneToken: res.phone_token }\n\t\treturn this.signedIn(res as AuthResponse)\n\t}\n\n\t/** Opens a new account on a phone `verifyOtp({ askIfNew: true })` proved, and signs it in (D123). */\n\tasync openPhoneAccount({ phone, phoneToken }: { phone: string; phoneToken: string }) {\n\t\tconst auth = await this.account<AuthResponse>('/x/identity/otp/new-account', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { phone: String(phone ?? '').trim(), phone_token: phoneToken },\n\t\t})\n\t\treturn this.signedIn(auth)\n\t}\n\n\tasync joinAsAdmin(): Promise<never> {\n\t\tthrow new NotSupportedError('AuthService', 'joinAsAdmin', 'operators are invited from the admin panel')\n\t}\n}\n\n/** The `/my/profile` form: the same account, read and saved. */\nexport class ProfileService extends UserService {\n\tasync getOne() {\n\t\treturn this.getMe()\n\t}\n\n\tasync save(profile: { firstName?: string; lastName?: string; email?: string; phone?: string }) {\n\t\treturn this.updateProfile(profile)\n\t}\n\n\t/** Texts a code to a phone the signed-in shopper wants to add (D118). */\n\tasync requestPhoneLink({ phone }: { phone: string }) {\n\t\tconst res = await this.account<{ expires_in_minutes: number }>('/x/identity/me/phone', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { phone: String(phone ?? '').trim() },\n\t\t})\n\t\treturn { expiresInMinutes: res?.expires_in_minutes ?? 10 }\n\t}\n\n\t/** Adds the phone with its code; from then on it signs in to this account too. */\n\tasync verifyPhoneLink({ phone, otp }: { phone: string; otp: string }) {\n\t\tconst c = await this.account<Customer>('/x/identity/me/phone/verify', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { phone: String(phone ?? '').trim(), code: String(otp ?? '').trim() },\n\t\t})\n\t\tupdateMe(c)\n\t\treturn toUser(c)\n\t}\n}\n\nexport const userService = new UserService()\nexport const authService = new AuthService()\nexport const profileService = new ProfileService()\n","import type { IdentityAddress, Postcode } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { fromIdentityAddress, toIdentityAddress } from '../map'\nimport { currentMe, type StorefrontAddress } from '../browser'\nimport { BaseService } from './base.service'\n\ntype AddressArg = StorefrontAddress & { isPrimary?: boolean; label?: string }\n\n/** The signed-in shopper's address book (ext/identity). A guest's address lives on the cart. */\nexport class AddressService extends BaseService {\n\tasync list({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t}: { page?: number; limit?: number; user?: string; q?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<IdentityAddress[] | null>('/x/identity/me/addresses', {\n\t\t\tquery: { page, limit },\n\t\t\tauth: true,\n\t\t})\n\t\tconst email = currentMe()?.email\n\t\tconst rows = env.data ?? []\n\t\treturn {\n\t\t\tdata: rows.map((a) => fromIdentityAddress(a, email)),\n\t\t\tcount: env.meta?.total ?? rows.length,\n\t\t\tpageSize: env.meta?.limit ?? limit,\n\t\t\tnoOfPage: env.meta?.total_pages ?? 1,\n\t\t\tpage: env.meta?.page ?? page,\n\t\t}\n\t}\n\n\tasync fetchAddress(id: string) {\n\t\treturn fromIdentityAddress(\n\t\t\tawait this.data<IdentityAddress>(`/x/identity/me/addresses/${enc(id)}`, { auth: true }),\n\t\t\tcurrentMe()?.email,\n\t\t)\n\t}\n\n\t/** New when it has no id (or the form's `'new'`), an edit when it has one — the storefront saves both here. */\n\tasync saveAddress(address: AddressArg) {\n\t\tconst id = address?.id && address.id !== 'new' ? String(address.id) : null\n\t\tif (id) return this.editAddress(id, address)\n\t\tconst a = await this.data<IdentityAddress>('/x/identity/me/addresses', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: toIdentityAddress(address),\n\t\t})\n\t\treturn fromIdentityAddress(a, currentMe()?.email)\n\t}\n\n\tasync editAddress(id: string, address: AddressArg) {\n\t\tconst a = await this.data<IdentityAddress>(`/x/identity/me/addresses/${enc(id)}`, {\n\t\t\tmethod: 'PATCH',\n\t\t\tauth: true,\n\t\t\tbody: toIdentityAddress(address),\n\t\t})\n\t\treturn fromIdentityAddress(a, currentMe()?.email)\n\t}\n\n\t/**\n\t * The city and state for a postcode (D134), for the address form to fill\n\t * in. India's six-digit PIN codes only, from the directory the engine was\n\t * given; null for anything it cannot answer, so the form simply leaves the\n\t * fields to the shopper.\n\t */\n\tasync lookupPostcode({ country = 'IN', postcode }: { country?: string; postcode: string }) {\n\t\tconst code = String(postcode ?? '').trim()\n\t\tconst cc = String(country ?? '').trim().toUpperCase()\n\t\tif (cc !== 'IN' || !/^[1-9][0-9]{5}$/.test(code)) return null\n\t\ttry {\n\t\t\tconst p = await this.data<Postcode>(`/api/postcodes/${cc}/${code}`)\n\t\t\treturn { country: p.country, postcode: p.postcode, city: p.city, state: p.state, stateCode: p.state_code }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 404 || err.status === 400)) return null\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tasync deleteAddress(id: string) {\n\t\tawait this.engine(`/x/identity/me/addresses/${enc(id)}`, { method: 'DELETE', auth: true })\n\t\treturn { id: String(id), deleted: true }\n\t}\n}\n\nconst enc = (id: string) => encodeURIComponent(String(id))\n\nexport const addressService = new AddressService()\n","import type { Product, Wishlist } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { toProduct } from '../map'\nimport { currentMe, forgetWishlistToken, rememberWishlistToken, wishlistToken } from '../browser'\nimport { BaseService } from './base.service'\n\n/**\n * Saved products, through ext/wishlist.\n *\n * The module keys a list by a token of its own rather than by an account, so\n * a guest can save things too; this connector keeps that token in the browser.\n * The signed-in shopper's email is attached so the store can tell them when a\n * saved product comes back in stock.\n */\nexport class WishlistService extends BaseService {\n\tasync fetchWishlist(_args: Record<string, unknown> = {}) {\n\t\tconst list = await this.current()\n\t\tif (!list) return { data: [], count: 0 }\n\t\tconst items = (list.items ?? []).filter((i) => !i.deleted)\n\t\tconst products = await Promise.all(\n\t\t\titems.map((i) => this.data<Product>(`/api/products/${i.product_id}`).catch(() => null)),\n\t\t)\n\t\tconst data = items.flatMap((item, n) => {\n\t\t\tconst p = products[n]\n\t\t\tif (!p) return []\n\t\t\treturn [\n\t\t\t\t{\n\t\t\t\t\tid: String(item.id),\n\t\t\t\t\tproductId: String(item.product_id),\n\t\t\t\t\tvariantId: item.variant_id ? String(item.variant_id) : null,\n\t\t\t\t\tproduct: toProduct(p),\n\t\t\t\t\tvariant: { id: item.variant_id ? String(item.variant_id) : null },\n\t\t\t\t\tcreatedAt: item.created_at,\n\t\t\t\t},\n\t\t\t]\n\t\t})\n\t\treturn { data, count: data.length }\n\t}\n\n\t/** Saved → removed, removed → saved. `{ active }` is the state after the click. */\n\tasync toggleWishlist({ productId, variantId }: { productId: string; variantId?: string | null }) {\n\t\tconst list = (await this.current()) ?? (await this.create())\n\t\tconst item = (list.items ?? []).find((i) => String(i.product_id) === String(productId))\n\t\tif (item) {\n\t\t\tawait this.data<Wishlist>(`/x/wishlist/${enc(list.token!)}/items/${item.id}`, { method: 'DELETE' })\n\t\t\treturn { active: false, id: String(item.id) }\n\t\t}\n\t\tconst next = await this.data<Wishlist>(`/x/wishlist/${enc(list.token!)}/items`, {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { product_id: Number(productId), ...(variantId ? { variant_id: Number(variantId) } : {}) },\n\t\t})\n\t\tconst added = (next.items ?? []).find((i) => String(i.product_id) === String(productId))\n\t\treturn { active: true, id: added ? String(added.id) : null }\n\t}\n\n\tasync checkWishlist({ productId }: { productId: string; variantId?: string | null }) {\n\t\tconst list = await this.current()\n\t\treturn !!list && (list.items ?? []).some((i) => String(i.product_id) === String(productId))\n\t}\n\n\tasync checkWishlistInBulk(pairs: { productId: string; variantId?: string | null }[]) {\n\t\tconst list = await this.current()\n\t\tconst saved = new Set((list?.items ?? []).map((i) => String(i.product_id)))\n\t\treturn (pairs ?? []).map((p) => ({ ...p, exists: saved.has(String(p.productId)) }))\n\t}\n\n\t/**\n\t * The address the store may write to when a saved product is back in stock\n\t * or on sale; `''` takes it off. A list that does not exist yet is made.\n\t */\n\tasync setEmail(email: string) {\n\t\tconst list = (await this.current()) ?? (await this.create())\n\t\tawait this.data<Wishlist>(`/x/wishlist/${enc(list.token)}`, {\n\t\t\tmethod: 'PATCH',\n\t\t\tbody: { email: String(email ?? '').trim() },\n\t\t})\n\t\treturn { email: String(email ?? '').trim() || null }\n\t}\n\n\tprivate async current(): Promise<(Wishlist & { token: string }) | null> {\n\t\tconst token = wishlistToken()\n\t\tif (!token) return null\n\t\ttry {\n\t\t\treturn { ...(await this.data<Wishlist>(`/x/wishlist/${enc(token)}`)), token }\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404 && !/no wishlist|no route/i.test(err.message)) {\n\t\t\t\tforgetWishlistToken()\n\t\t\t\treturn null\n\t\t\t}\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tprivate async create(): Promise<Wishlist & { token: string }> {\n\t\tconst email = currentMe()?.email\n\t\tconst list = await this.data<Wishlist>('/x/wishlist', { method: 'POST', ...(email ? { body: { email } } : {}) })\n\t\tif (!list.token) throw new GoCommerceError('The store did not return a wishlist token.', 500)\n\t\trememberWishlistToken(list.token)\n\t\treturn { ...list, token: list.token }\n\t}\n}\n\nconst enc = (s: string) => encodeURIComponent(s)\n\nexport const wishlistService = new WishlistService()\n","import type { ReviewPage } from '../engine'\nimport { toRating } from '../map'\nimport { BaseService } from './base.service'\n\n/**\n * Product reviews (ext/reviews). Approved reviews only, newest first. The\n * product page gets them with the product; this is the paged form, and\n * `productService.addReview` writes one.\n */\nexport class ReviewService extends BaseService {\n\tasync fetchReviews({\n\t\tproductId,\n\t\tcurrentPage = 1,\n\t\tpage,\n\t\tlimit = 20,\n\t}: { productId?: string; currentPage?: number; page?: number; limit?: number; search?: string; sort?: string } = {}) {\n\t\t// A vendor's \"all my reviews\" page has no product to ask about.\n\t\tif (!productId) return { data: [], count: 0, pageSize: limit, noOfPage: 0, page: 1 }\n\t\tconst p = Math.max(1, Number(page ?? currentPage) || 1)\n\t\tconst res = await this.data<ReviewPage>('/x/reviews', { query: { product_id: productId, page: p, limit } })\n\t\tconst total = res.meta?.total ?? res.summary?.count ?? 0\n\t\treturn {\n\t\t\tdata: (res.reviews ?? []).map(toRating),\n\t\t\tcount: total,\n\t\t\tpageSize: limit,\n\t\t\tnoOfPage: Math.max(1, Math.ceil(total / limit)),\n\t\t\tpage: p,\n\t\t\tsummary: res.summary ?? null,\n\t\t}\n\t}\n\n\tasync allReviews(args: { productId?: string; page?: number } = {}) {\n\t\treturn this.fetchReviews(args)\n\t}\n}\n\nexport const reviewService = new ReviewService()\n","import { placedOrder } from '../browser'\nimport type { GooglePlace, GoogleSurvey } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\n\nconst PLUGIN = 'google-reviews'\n\n/** A Google review with what Google's attribution policy asks a storefront to show. */\nexport type GoogleReview = {\n\tauthor: string\n\t/** The author's Google profile and photo; https or empty. */\n\tauthorUrl: string\n\tauthorPhoto: string\n\trating: number\n\t/** The reviewer's own words, in their language. Empty for a rating with no words. */\n\ttext: string\n\tlanguage: string\n\t/** Google's own words for when, such as \"a month ago\". */\n\twhen: string\n\t/** YYYY-MM, when Google has one. */\n\tvisited: string\n\t/** The review on Google Maps, and where to report it to Google. */\n\turl: string\n\treportUrl: string\n}\n\nexport type GoogleReviews = {\n\t/** Google's own rating and count, never worked out from `reviews`. */\n\trating: number\n\tcount: number\n\t/** Every review, on Google Maps: `reviews` are at most five of them. */\n\tmapsUrl: string\n\treviews: GoogleReview[]\n}\n\n/**\n * The store's Google reviews and Google Customer Reviews (ext/google-reviews).\n *\n * Both calls answer null when there is nothing to show — the plugin or its\n * switch off, Google refusing, the day's lookups spent — because each is an\n * extra on a page that must render without it.\n */\nexport class GoogleReviewService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\t/**\n\t * Google's rating and its most relevant reviews, read live. Google's terms\n\t * forbid keeping them, so nothing here caches them either, and every call\n\t * is one the store pays Google for: call it when the section is in view.\n\t */\n\tasync place(): Promise<GoogleReviews | null> {\n\t\tif (!(await this.switchOn('show_place'))) return null\n\t\tconst p = await this.orNull(() => this.data<GooglePlace>('/x/google-reviews/place'))\n\t\tif (!p?.user_rating_count) return null\n\t\treturn {\n\t\t\trating: p.rating,\n\t\t\tcount: p.user_rating_count,\n\t\t\tmapsUrl: p.google_maps_uri ?? '',\n\t\t\treviews: (p.reviews ?? []).map((r) => ({\n\t\t\t\tauthor: r.author?.name ?? '',\n\t\t\t\tauthorUrl: r.author?.uri ?? '',\n\t\t\t\tauthorPhoto: r.author?.photo_uri ?? '',\n\t\t\t\trating: r.rating,\n\t\t\t\ttext: r.text ?? '',\n\t\t\t\tlanguage: r.language ?? '',\n\t\t\t\twhen: r.relative_time ?? '',\n\t\t\t\tvisited: r.visit_date ?? '',\n\t\t\t\turl: r.google_maps_uri ?? '',\n\t\t\t\treportUrl: r.flag_uri ?? '',\n\t\t\t})),\n\t\t}\n\t}\n\n\t/**\n\t * What Google Customer Reviews' opt-in is rendered with, for an order placed\n\t * in this browser: its access token is kept here, and nowhere else can ask.\n\t * Every field is the order's own; the keys are Google's, to pass unchanged\n\t * to `gapi.surveyoptin.render`.\n\t */\n\tasync survey(orderNumber: string): Promise<GoogleSurvey | null> {\n\t\tconst kept = orderNumber ? placedOrder(orderNumber) : undefined\n\t\tif (!kept || !(await this.switchOn('customer_reviews'))) return null\n\t\treturn this.orNull(() =>\n\t\t\tthis.data<GoogleSurvey>(`/x/google-reviews/survey/${encodeURIComponent(orderNumber)}`, {\n\t\t\t\tquery: { token: kept.token },\n\t\t\t}),\n\t\t)\n\t}\n\n\tprivate async switchOn(setting: string): Promise<boolean> {\n\t\ttry {\n\t\t\treturn (await this.facts.plugins()).get(PLUGIN)?.settings?.[setting] === true\n\t\t} catch {\n\t\t\treturn false\n\t\t}\n\t}\n\n\t/** Off, used up for the day, or refused by Google: nothing to show. Anything else still throws. */\n\tprivate async orNull<T>(call: () => Promise<T>): Promise<T | null> {\n\t\ttry {\n\t\t\treturn await call()\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && [404, 429, 502].includes(err.status)) return null\n\t\t\tthrow err\n\t\t}\n\t}\n}\n\nexport const googleReviewService = new GoogleReviewService()\n","import type { Menu, MenuItem, MenuSummary } from '../engine'\nimport { resolveRestLocally } from '../rest-guard'\nimport { BaseService } from './base.service'\nimport { StoreFacts } from './facts'\nimport { remember } from '../cache'\n\nexport type StorefrontMenu = { menuId: string; name: string; items: StorefrontMenuItem[] }\ntype StorefrontMenuItem = { id: string; name: string; link: string; items: StorefrontMenuItem[] }\n\n/**\n * A link where this storefront serves it. The navigation module resolves URLs\n * from its own patterns, whose defaults suit a different storefront; the\n * targets it names are slugs, so they are re-pointed at this one's routes.\n */\nfunction linkFor(item: MenuItem): string {\n\tconst t = item.target ?? ''\n\tswitch (item.kind) {\n\t\tcase 'home':\n\t\t\treturn '/'\n\t\tcase 'product':\n\t\t\treturn t ? `/products/${t}` : item.url\n\t\tcase 'collection':\n\t\t\treturn t ? `/collections/${t}` : item.url\n\t\tcase 'category':\n\t\t\treturn t ? `/${t}` : item.url\n\t\tcase 'page':\n\t\t\treturn t ? `/p/${t}` : item.url\n\t\tdefault:\n\t\t\treturn item.url\n\t}\n}\n\nconst toItem = (item: MenuItem, i: number): StorefrontMenuItem => ({\n\tid: String(item.id ?? i),\n\tname: item.title,\n\tlink: linkFor(item),\n\titems: (item.children ?? []).map(toItem),\n})\n\n/**\n * Menus from ext/navigation, when it is installed and switched on; otherwise\n * the storefront's own `store.menu`, which is what it shows anyway.\n */\nexport class MenuService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst menus = await this.engineMenus()\n\t\tif (menus) return { data: menus }\n\t\treturn resolveRestLocally('get', '/api/menu')\n\t}\n\n\t/** Every menu the store keeps, by handle — not only the header and footer. */\n\tasync listMenus() {\n\t\treturn (await this.data<MenuSummary[] | null>('/x/navigation/menus')) ?? []\n\t}\n\n\t/** One menu by handle, in the storefront's shape: `{ menuId, name, items: [{ id, name, link, items }] }`. */\n\tasync getMenu(handle: string): Promise<StorefrontMenu> {\n\t\tconst m = await this.data<Menu>(`/x/navigation/menus/${encodeURIComponent(handle)}`)\n\t\treturn { menuId: m.handle, name: m.title, items: (m.items ?? []).map(toItem) }\n\t}\n\n\t/**\n\t * The header and footer menus, or `null` when the module is not there. Cached: a menu is\n\t * store-level. Each is the menu the shop chose for it in the theme editor's header or footer\n\t * (GoCommerce D131), still under the `header` / `footer` id every storefront looks for, so the\n\t * choice reaches every place that draws one; the menus named so are the default.\n\t */\n\tasync engineMenus(): Promise<StorefrontMenu[] | null> {\n\t\tif (!(await this.facts.pluginOn('navigation'))) return null\n\t\treturn remember(`${this.engineBase()}|${this.store ?? ''}|menus`, async () => {\n\t\t\tconst out: StorefrontMenu[] = []\n\t\t\tfor (const part of ['header', 'footer'] as const) {\n\t\t\t\ttry {\n\t\t\t\t\tconst handle = await this.chosenMenu(part)\n\t\t\t\t\tconst m = await this.data<Menu>(`/x/navigation/menus/${encodeURIComponent(handle)}`)\n\t\t\t\t\tout.push({ menuId: part, name: m.title, items: (m.items ?? []).map(toItem) })\n\t\t\t\t} catch {\n\t\t\t\t\t// A store may have deleted one of the two.\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out\n\t\t}).catch(() => null)\n\t}\n\n\t/** The handle of the menu the published header or footer names, else the part's own name. */\n\tprivate async chosenMenu(part: 'header' | 'footer'): Promise<string> {\n\t\tif (!(await this.facts.pluginOn('layouts'))) return part\n\t\ttry {\n\t\t\tconst layout = await this.data<{ sections?: { type: string; settings?: { menu?: unknown } | null }[] | null }>(`/x/layouts/${part}`)\n\t\t\tconst menu = layout?.sections?.find((s) => s.type === part)?.settings?.menu\n\t\t\treturn typeof menu === 'string' && menu ? menu : part\n\t\t} catch {\n\t\t\t// Nothing published, or an engine without the editor.\n\t\t\treturn part\n\t\t}\n\t}\n}\n\nexport const menuService = new MenuService()\n","/**\n * Store identity — name, logo, favicon, menus, theme variables.\n *\n * Some of that the engine has (the settlement currency, the payment methods,\n * the switched-on plugins) and most of it it does not: a logo and a hero banner\n * are the storefront's own business. The storefront registers its static store\n * record here at boot — `default-store.json` merged under the project's\n * `kitcommerce.config.ts` — and `storeService` lays the engine's live facts\n * over it, so the engine wins wherever it has an opinion.\n */\nexport type StaticStoreProvider = () => Promise<Record<string, any>> | Record<string, any>\n\nlet provider: StaticStoreProvider | undefined\n\nexport const setStaticStore = (fn: StaticStoreProvider) => {\n\tprovider = fn\n}\n\nexport const hasStaticStore = () => Boolean(provider)\n\nexport const readStaticStore = async (): Promise<Record<string, any>> => {\n\tif (!provider) return {}\n\treturn (await provider()) ?? {}\n}\n\n/** The marker the storefront reads to tell which backend is active. */\nexport const connectorName = 'gocommerce'\n","import { BaseService } from './base.service'\n\n/**\n * The signup box and its unsubscribe link (ext/newsletter). Subscribing twice\n * is not an error, and unsubscribing answers the same whether or not the token\n * matched, so neither call tells a stranger whether an address is on the list.\n */\nexport class NewsletterService extends BaseService {\n\tasync subscribe({ email, name, source }: { email: string; name?: string; source?: string }) {\n\t\treturn this.data<{ status: 'subscribed' }>('/x/newsletter/subscribe', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { email: String(email ?? '').trim(), ...(name ? { name } : {}), ...(source ? { source } : {}) },\n\t\t})\n\t}\n\n\t/** The token from the unsubscribe link in a newsletter email. */\n\tasync unsubscribe(token: string) {\n\t\treturn this.data<{ status: 'unsubscribed' }>('/x/newsletter/unsubscribe', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: { token: String(token ?? '') },\n\t\t})\n\t}\n}\n\nexport const newsletterService = new NewsletterService()\n","import { keep, recall } from '../cache'\nimport type { StorePassAnswer } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { readStaticStore } from '../static-store'\nimport { BaseService, mediaUrl } from './base.service'\nimport { StoreFacts } from './facts'\nimport { MenuService } from './menu-service'\nimport { NewsletterService } from './newsletter-service'\n\n/**\n * The engine's \"no such store\" answer to an `X-Store` it cannot resolve, and\n * nothing else: a 404 for a product or a page is a different question.\n */\nconst isStoreMissing = (err: unknown) =>\n\terr instanceof GoCommerceError &&\n\terr.status === 404 &&\n\t(err.code === 'store_not_found' || /store not found|no such store/i.test(err.message))\n\n/** `$`, `€`, `₹` — from the platform's own tables rather than a list kept here. */\nfunction symbolFor(code: string): string {\n\ttry {\n\t\tconst part = new Intl.NumberFormat('en', { style: 'currency', currency: code })\n\t\t\t.formatToParts(0)\n\t\t\t.find((p) => p.type === 'currency')\n\t\treturn part?.value ?? code\n\t} catch {\n\t\treturn code\n\t}\n}\n\n/**\n * The store record every page renders from.\n *\n * Theme and the rest are the storefront's own (its static store, registered\n * through `setStaticStore`); the engine has no opinion on them. Where the\n * engine does have one, it wins:\n * - the store's name, contact, logo and icon, as its owner set them in the\n * panel. One storefront serves every store under `baseDomain`, so a name or\n * a logo in the static record would be every store's;\n * - the settlement currency. Every price on the site is formatted with it, and\n * a store record saying USD over an engine charging INR would print the\n * wrong symbol on every price;\n * - the modules that back a storefront feature, and the menus.\n *\n * This runs on every request and a throw here takes every page down, so the\n * engine's half is best-effort: unreachable, the storefront still renders\n * from its own record, and the failure shows up where a price is fetched.\n */\nexport class StoreService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\n\tasync getStoreByIdOrDomain(_args: { storeId?: string; domain?: string } = {}) {\n\t\tconst base = await readStaticStore()\n\t\t// The one failure that is not best-effort: a host under `baseDomain` naming\n\t\t// a store the engine has never heard of. That page is a 404, not a render\n\t\t// of the static record, so the storefront's 404 route can take it from here.\n\t\tconst store = this.store\n\t\tconst [plugins, live] = await Promise.all([\n\t\t\tthis.facts.plugins().catch((err) => {\n\t\t\t\tif (store && isStoreMissing(err)) {\n\t\t\t\t\tthrow new GoCommerceError(`store not found: no store \"${store}\" on this engine`, 404, 'store_not_found')\n\t\t\t\t}\n\t\t\t\treturn undefined\n\t\t\t}),\n\t\t\tthis.live().catch(() => ({})),\n\t\t])\n\t\tconst known = `${this.creds.apiUrl ?? ''}|${store ?? ''}|closed`\n\t\tconst closed = plugins ? keep(known, closedOf(plugins)) : recall<StoreClosed>(known)\n\t\t// `id` must be truthy and stable: the storefront keys a cookie on it.\n\t\treturn { ...base, ...live, closed, id: base.id || 'gocommerce' }\n\t}\n\n\tasync getStore(storeId?: string) {\n\t\treturn this.getStoreByIdOrDomain({ storeId })\n\t}\n\n\t/**\n\t * The storefront's sitemap route asks for `/api/stores/<id>` and serves the\n\t * `sitemap` path it gets back from `PUBLIC_SITEMAP_URL`. With ext/sitemaps\n\t * installed, `/sitemaps/sitemap.xml` under `PUBLIC_SITEMAP_URL=<engine>/x`\n\t * is the engine's own sitemap; without it, an empty path is the route's\n\t * clean 404 rather than a crash.\n\t */\n\toverride async get<T = any>(path: string): Promise<T> {\n\t\tif (path.split('?')[0].startsWith('/api/stores/')) {\n\t\t\tconst on = await this.facts.pluginOn('sitemap')\n\t\t\treturn { sitemap: on ? '/sitemaps/sitemap.xml' : '' } as T\n\t\t}\n\t\treturn super.get<T>(path)\n\t}\n\n\t/**\n\t * The storefront's newsletter box posts `{ email }` to Litekart's\n\t * `/api/newsletter/subscribe` through this verb; ext/newsletter is where\n\t * that list lives here.\n\t */\n\toverride async post<T = any>(path: string, data?: unknown): Promise<T> {\n\t\tif (path.split('?')[0] === '/api/newsletter/subscribe') {\n\t\t\tconst { email, name } = (data ?? {}) as { email?: string; name?: string }\n\t\t\treturn (await new NewsletterService(this._fetch).subscribe({\n\t\t\t\temail: email ?? '',\n\t\t\t\tname,\n\t\t\t\tsource: 'storefront',\n\t\t\t})) as T\n\t\t}\n\t\treturn super.post<T>(path, data)\n\t}\n\n\t/**\n\t * A closed store's password (D170), traded for a pass. Never throws. The\n\t * engine allows 20 tries an hour per client, and sees this server as the\n\t * client unless `clientAddress`, the shopper's, travels as `X-Forwarded-For`.\n\t */\n\tasync unlockStore(password: string, { clientAddress }: { clientAddress?: string } = {}): Promise<StoreUnlock> {\n\t\tconst typed = password.trim()\n\t\tif (!typed) return { outcome: 'wrong' }\n\t\ttry {\n\t\t\treturn { outcome: 'unlocked', pass: await this.storePass({ password: typed }, clientAddress) }\n\t\t} catch (err) {\n\t\t\treturn { outcome: (err instanceof GoCommerceError && UNLOCK_REFUSED[err.status]) || 'unavailable' }\n\t\t}\n\t}\n\n\t/**\n\t * A pass checked without spending a try: the pass, or null when it is wrong,\n\t * expired, ended by a new password, or the store takes none now. Throws when\n\t * the engine cannot say.\n\t */\n\tasync checkStorePass(token: string): Promise<StorePass | null> {\n\t\tif (!token) return null\n\t\ttry {\n\t\t\treturn await this.storePass({ token })\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && (err.status === 422 || err.status === 404)) return null\n\t\t\tthrow err\n\t\t}\n\t}\n\n\tprivate async storePass(body: { password: string } | { token: string }, clientAddress?: string): Promise<StorePass> {\n\t\tconst answer = await this.data<StorePassAnswer | null>('/api/store/password', {\n\t\t\tmethod: 'POST',\n\t\t\tbody,\n\t\t\theaders: clientAddress && ONE_IP_ADDRESS.test(clientAddress) ? { 'X-Forwarded-For': clientAddress } : undefined,\n\t\t})\n\t\tconst expiresAt = new Date(answer?.expires_at ?? NaN)\n\t\tif (!answer?.token || Number.isNaN(expiresAt.getTime())) {\n\t\t\tthrow new GoCommerceError('The commerce engine answered a store pass without its token or expiry.', 502)\n\t\t}\n\t\treturn { token: answer.token, expiresAt }\n\t}\n\n\tprivate async live(): Promise<Record<string, unknown>> {\n\t\tconst [ready, plugins, menus, base, profile, ships] = await Promise.all([\n\t\t\tthis.facts.ready(),\n\t\t\tthis.facts.plugins().catch(() => new Map()),\n\t\t\tnew MenuService(this._fetch).engineMenus(),\n\t\t\treadStaticStore(),\n\t\t\tthis.facts.profile().catch(() => null),\n\t\t\t// An engine without the route rules nothing out.\n\t\t\tthis.facts.shipsTo().catch(() => ({ everywhere: true, countries: [] as string[] })),\n\t\t])\n\t\tconst code = ready.currency\n\t\tconst sameCurrency = (base.currency?.code ?? base.currencyCode) === code\n\t\tconst flag = (on: boolean) => ({ ...(on ? { active: true } : { active: false }) })\n\t\tconst basePlugins = (base.plugins ?? {}) as Record<string, Record<string, unknown>>\n\t\treturn {\n\t\t\t// Only what the owner filled in: an empty name keeps the static one.\n\t\t\t...(profile?.name ? { name: profile.name } : {}),\n\t\t\t...(profile?.email ? { businessEmail: profile.email } : {}),\n\t\t\t...(profile?.phone ? { businessPhone: profile.phone } : {}),\n\t\t\t// The store's pictures (D148), the same: one it has not chosen keeps the static one.\n\t\t\t// Its own logo also replaces the static dark logo, which would be the deployment's\n\t\t\t// mark beside this store's; without a dark one of its own, its logo is the fallback.\n\t\t\t...(profile?.logo_url ? { logo: mediaUrl(profile.logo_url), logoDark: undefined } : {}),\n\t\t\t...(profile?.logo_dark_url ? { logoDark: mediaUrl(profile.logo_dark_url) } : {}),\n\t\t\t...(profile?.icon_url ? { favicon: mediaUrl(profile.icon_url) } : {}),\n\t\t\t// What the contact page shows (D156), only what the store published. The address\n\t\t\t// in the shape the storefront's contact page and home-page JSON-LD already read. The\n\t\t\t// country beside it, not over `country`: that is the address form's default country.\n\t\t\t...(profile?.country ? { businessCountry: profile.country } : {}),\n\t\t\t...(profile?.address\n\t\t\t\t? {\n\t\t\t\t\t\taddress: {\n\t\t\t\t\t\t\tstreet: [profile.address.line1, profile.address.line2].filter(Boolean).join(', '),\n\t\t\t\t\t\t\tcity: profile.address.city,\n\t\t\t\t\t\t\tstate: profile.address.state,\n\t\t\t\t\t\t\tpincode: profile.address.postal_code,\n\t\t\t\t\t\t\tcountry: profile.address.country,\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\t...(profile?.map_location ? { mapLocation: profile.map_location } : {}),\n\t\t\t...(profile?.opening_hours?.length ? { openingHours: profile.opening_hours } : {}),\n\t\t\tcurrencyCode: code,\n\t\t\tcurrencySymbol: sameCurrency ? (base.currencySymbol ?? symbolFor(code)) : symbolFor(code),\n\t\t\tcurrency: {\n\t\t\t\t...(base.currency ?? {}),\n\t\t\t\tcode,\n\t\t\t\tsymbol: sameCurrency ? (base.currency?.symbol ?? symbolFor(code)) : symbolFor(code),\n\t\t\t\tincludesTax: profile?.prices_include_tax,\n\t\t\t},\n\t\t\tlanguage: ready.language,\n\t\t\tplugins: {\n\t\t\t\t...basePlugins,\n\t\t\t\t// Features this connector serves from a module: on exactly when the\n\t\t\t\t// module is installed and switched on, whatever the static record says.\n\t\t\t\tisWishlist: { ...basePlugins.isWishlist, ...flag(plugins.has('wishlist')) },\n\t\t\t\t// The corner button and the contact page's WhatsApp card read the number from\n\t\t\t\t// here; the engine's plugin holds it, in international digits.\n\t\t\t\twhatsappChatButton: {\n\t\t\t\t\t...basePlugins.whatsappChatButton,\n\t\t\t\t\t...flag(plugins.has('whatsapp-chat')),\n\t\t\t\t\t...(plugins.has('whatsapp-chat')\n\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\tphone: String(plugins.get('whatsapp-chat')?.settings?.phone ?? ''),\n\t\t\t\t\t\t\t\tmessage: String(plugins.get('whatsapp-chat')?.settings?.message ?? ''),\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t: {}),\n\t\t\t\t},\n\t\t\t\t// Criteo's OneTag, for this store's own account. The engine decides: on a shared\n\t\t\t\t// deployment the static record is every store's, and one store's account must\n\t\t\t\t// never load on another's pages.\n\t\t\t\tcriteo: {\n\t\t\t\t\t...basePlugins.criteo,\n\t\t\t\t\t...flag(plugins.has('criteo')),\n\t\t\t\t\t...(plugins.has('criteo') ? { accountId: String(plugins.get('criteo')?.settings?.account_id ?? '') } : {}),\n\t\t\t\t},\n\t\t\t\tisProductReviewsAndRatings: {\n\t\t\t\t\t...basePlugins.isProductReviewsAndRatings,\n\t\t\t\t\t...flag(plugins.has('product-reviews')),\n\t\t\t\t},\n\t\t\t\t// Google Customer Reviews (ext/google-reviews): the confirmation page's survey offer,\n\t\t\t\t// whose fields the engine builds from the order, and Google's store widget, which\n\t\t\t\t// belongs to the same programme and so needs the survey on.\n\t\t\t\tgoogleReviewsOptIn: {\n\t\t\t\t\t...basePlugins.googleReviewsOptIn,\n\t\t\t\t\t...flag(googleSetting(plugins, 'customer_reviews') === true),\n\t\t\t\t},\n\t\t\t\tgoogleStoreWidget: storeWidget(plugins),\n\t\t\t\t// The footer's sign-up box posts to ext/newsletter, and the theme editor's footer\n\t\t\t\t// switch (D131) can only show it while that is on.\n\t\t\t\tnewsletter: { ...basePlugins.newsletter, ...flag(plugins.has('newsletter')) },\n\t\t\t\t// The ad and analytics tags (D160). The engine decides, not the static record:\n\t\t\t\t// one storefront serves every store, and one store's pixel must never\n\t\t\t\t// load on another's pages.\n\t\t\t\t...adTags(plugins),\n\t\t\t\tgoogleTagManager: googleTags(plugins),\n\t\t\t\t// Discount codes are core: every GoCommerce store takes them, so\n\t\t\t\t// the code box is shown whatever the static record says.\n\t\t\t\tisDiscountCoupons: { ...basePlugins.isDiscountCoupons, active: true },\n\t\t\t\t// The engine resizes the store's own pictures in Cloudflare's URL shape\n\t\t\t\t// (D139), so the storefront's srcset asks it for each width. Its public\n\t\t\t\t// origin, not the proxy path: an <img> needs no CORS, and the proxy would\n\t\t\t\t// put every picture through the storefront's server.\n\t\t\t\t...(profile?.images_path && this.creds.apiUrl\n\t\t\t\t\t? {\n\t\t\t\t\t\t\timageCdn: {\n\t\t\t\t\t\t\t\tprovider: 'cloudflare',\n\t\t\t\t\t\t\t\turl: this.creds.apiUrl.trim().replace(/\\/+$/, '') + profile.images_path,\n\t\t\t\t\t\t\t\tactive: true,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t},\n\t\t\t...(menus?.length ? { menu: menus } : {}),\n\t\t\t...deliverable(base, ships),\n\t\t\t// The one way this store signs customers in (D116), which the sign-in\n\t\t\t// form reads as PHONE or EMAIL. Without the accounts module the static\n\t\t\t// record says.\n\t\t\t...(plugins.has('identity')\n\t\t\t\t? { loginType: LOGIN_TYPES[String(plugins.get('identity')?.settings?.login_method)] ?? 'EMAIL' }\n\t\t\t\t: {}),\n\t\t}\n\t}\n}\n\nexport const storeService = new StoreService()\n\n/** A store its owner closed (D170): the message to show, and whether a password lets a visitor in. */\nexport type StoreClosed = { message: string; password: boolean }\n\nexport type StorePass = { token: string; expiresAt: Date }\n\nexport type StoreUnlock =\n\t{ outcome: 'unlocked'; pass: StorePass } | { outcome: 'wrong' | 'throttled' | 'open' | 'unavailable' }\n\nconst ONE_IP_ADDRESS = /^[\\da-f.:]{2,45}$/i\n\nconst UNLOCK_REFUSED: Partial<Record<number, 'wrong' | 'throttled' | 'open'>> = {\n\t422: 'wrong',\n\t429: 'throttled',\n\t404: 'open',\n}\n\nfunction closedOf(plugins: Map<string, { settings?: Record<string, unknown> }> | undefined): StoreClosed | undefined {\n\tconst plugin = plugins?.get('store-close')\n\tif (!plugin) return undefined\n\treturn { message: String(plugin.settings?.message ?? ''), password: plugin.settings?.password === true }\n}\n\n/** Each tag's engine plugin, the setting that holds its ID, and its name on the store record. */\nconst AD_TAGS = [\n\t['meta-pixel', 'pixel_id', 'facebookPixel'],\n\t['microsoft-clarity', 'project_id', 'microsoftClarity'],\n\t['hotjar', 'site_id', 'hotjar'],\n\t['tiktok-pixel', 'pixel_id', 'tiktokPixel'],\n\t['pinterest-tag', 'tag_id', 'pinterestTag'],\n\t['snapchat-pixel', 'pixel_id', 'snapchatPixel'],\n] as const\n\n/** On with its ID, or off with none, so a storefront has nothing to load by mistake. */\nfunction adTags(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\treturn Object.fromEntries(\n\t\tAD_TAGS.map(([key, field, name]) => {\n\t\t\tconst id = String(plugins.get(key)?.settings?.[field] ?? '').trim()\n\t\t\treturn [name, id ? { active: true, id } : { active: false }]\n\t\t}),\n\t)\n}\n\n/**\n * The google-analytics plugin in the shape the storefront has always read under\n * `googleTagManager`: its tag IDs, and the Ads conversion label as the purchase's\n * conversion. Off with no IDs when none is filled in.\n */\nfunction googleTags(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\tconst s = plugins.get('google-analytics')?.settings ?? {}\n\tconst id = (field: string) => String(s[field] ?? '').trim()\n\t// Google Ads shows a conversion as `send_to: 'AW-…/label'`, and an owner may paste all of it.\n\tconst [account, part] = id('conversion_label').split('/')\n\tconst label = part === undefined ? account : part\n\tconst ads = id('google_ads_id') || (part === undefined ? '' : account)\n\tconst tags = [id('ga4_measurement_id'), ads, id('gtm_container_id')].filter(Boolean)\n\tif (!tags.length) return { active: false }\n\treturn { active: true, tags, conversions: ads && label ? [{ event: 'purchase', label }] : [] }\n}\n\ntype Country = { code: string; name: string; [k: string]: unknown }\n\n/**\n * The address form's countries narrowed to where the store delivers (D117).\n * Each keeps the static record's entry, which may carry more than a name; a\n * country the record lacks is named by the browser's own list. One country is\n * also the default, and so is the first when the static default is not one of\n * them. Everywhere changes nothing.\n */\nfunction deliverable(\n\tbase: { country?: Country; countries?: Country[] },\n\tships: { everywhere: boolean; countries: string[] },\n): { countries?: Country[]; country?: Country } {\n\tif (ships.everywhere || !ships.countries.length) return {}\n\tconst known = new Map((base.countries ?? []).map((c) => [String(c.code).toUpperCase(), c]))\n\tconst countries = ships.countries.map((code) => known.get(code) ?? { code, name: regionName(code) })\n\tconst keep = base.country && ships.countries.includes(String(base.country.code).toUpperCase())\n\treturn { countries, ...(keep ? {} : { country: countries[0] }) }\n}\n\nfunction regionName(code: string): string {\n\ttry {\n\t\treturn new Intl.DisplayNames(['en'], { type: 'region' }).of(code) ?? code\n\t} catch {\n\t\treturn code\n\t}\n}\n\nconst googleSetting = (plugins: Map<string, { settings?: Record<string, unknown> }>, key: string) =>\n\tplugins.get('google-reviews')?.settings?.[key]\n\n/** Google's store widget, where the store placed it; off without the survey. */\nfunction storeWidget(plugins: Map<string, { settings?: Record<string, unknown> }>) {\n\tconst where = googleSetting(plugins, 'store_widget')\n\tif (googleSetting(plugins, 'customer_reviews') !== true || !where) return { active: false }\n\treturn { active: true, position: where === 'Bottom left' ? 'LEFT_BOTTOM' : 'RIGHT_BOTTOM' }\n}\n\n/** The sign-in form's names for the store's choice (D116, D118). */\nconst LOGIN_TYPES: Record<string, string> = { phone_otp: 'PHONE', email_or_phone: 'BOTH', email_password: 'EMAIL' }\n","import type { CmsPage, Faq } from '../engine'\nimport { toCmsPage as toStorefrontPage } from '../map'\nimport { BaseService, toPage } from './base.service'\n\n/**\n * Content pages from ext/cms, in the shopper's language with the store's\n * default as the fallback. A slug with no page is the page's 404.\n */\nexport class PageService extends BaseService {\n\tasync getOne(slug: string) {\n\t\treturn toStorefrontPage(await this.data<CmsPage>(`/x/cms/pages/${encodeURIComponent(String(slug))}`))\n\t}\n\n\tasync list({ page = 1, limit = 50 }: { page?: number; limit?: number; search?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<CmsPage[] | null>('/x/cms/pages', { query: { page, limit } })\n\t\treturn toPage(env, toStorefrontPage)\n\t}\n}\n\n/** The shop's questions and answers (ext/faq), flattened in the shop's own order. */\nexport class FaqService extends BaseService {\n\tasync listFaqs(_args: Record<string, unknown> = {}) {\n\t\tconst faq = await this.data<Faq>('/x/faq')\n\t\tconst data = (faq.sections ?? []).flatMap((s) =>\n\t\t\t(s.entries ?? []).map((e) => ({\n\t\t\t\tid: String(e.id),\n\t\t\t\tquestion: e.question,\n\t\t\t\tanswer: e.answer,\n\t\t\t\tcategory: s.section || null,\n\t\t\t})),\n\t\t)\n\t\treturn { data, count: data.length, heading: faq.heading, blurb: faq.blurb }\n\t}\n\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.listFaqs(args)\n\t}\n}\n\nexport const pageService = new PageService()\nexport const faqService = new FaqService()\n","import type { Product } from '../engine'\nimport { GoCommerceError } from '../errors'\nimport { toProduct, type StorefrontProduct } from '../map'\nimport { BaseService, mediaUrl } from './base.service'\nimport { MenuService, type StorefrontMenu } from './menu-service'\n\n/** A collection list's card, as the engine resolves it. */\ntype EngineLayoutCollection = {\n\tid: number\n\tslug: string\n\ttitle: string\n\timage?: string\n\tdescription?: string\n}\n\n/** One section as the engine stores it, before the storefront maps anything. */\ntype EngineLayoutSection = {\n\tid: string\n\ttype: string\n\tsettings: Record<string, unknown> | null\n\tproducts?: Product[] | null\n\tcollections?: EngineLayoutCollection[] | null\n}\n\n/**\n * The store's design tokens (ext/layouts, D127). Every key is optional and\n * an absent one means the storefront keeps its own look: colours are\n * `#rrggbb`, fonts are keys of the storefront's font list, `radius` is\n * none, small, medium or large.\n */\nexport type ThemeSettings = Partial<\n\tRecord<'background' | 'text' | 'accent' | 'accent_text' | 'muted' | 'heading_font' | 'body_font' | 'radius', string>\n>\n\ntype EngineLayout = {\n\tpage: string\n\ttheme: string\n\trevision?: number\n\tpreview?: boolean\n\ttheme_settings?: ThemeSettings | null\n\tsections: EngineLayoutSection[] | null\n}\n\n/** A collection list's card: enough to draw a picture and a title and link to it. */\nexport type LayoutCollection = {\n\tid: string\n\ttitle: string\n\tslug: string\n\tlink: string\n\timage: string | null\n\tdescription: string | null\n}\n\n/**\n * One section of a composed page. `settings` is the merchant's, as validated\n * by the engine: plain text (never HTML) and links that are `/path` or\n * `http(s)://`. A product grid also carries its products, resolved live and\n * mapped like any other product the storefront renders; a collection list\n * carries its collections.\n */\nexport type HomeLayoutSection = {\n\tid: string\n\ttype: string\n\tsettings: Record<string, unknown>\n\tproducts?: StorefrontProduct[]\n\tcollections?: LayoutCollection[]\n}\n\n/**\n * A page the shop arranges: the home page, or the template every product or\n * every collection is drawn in (ext/layouts, D128). A template holds its\n * core once — `main-product` (the catalogue's pictures, price and buy box)\n * or `main-collection` (the collection's grid) — at the place the shop put\n * it, and the storefront draws its own core there.\n */\nexport type LayoutPage = 'home' | 'product' | 'collection' | 'header' | 'footer'\n\nexport type HomeLayout = {\n\tpage: string\n\ttheme: string\n\t/** The published revision this is; absent on a preview. */\n\trevision?: number\n\t/** True when this is the saved draft shown through a preview key. */\n\tpreview: boolean\n\t/** The design tokens published with the page, or null for none. */\n\tthemeSettings: ThemeSettings | null\n\tsections: HomeLayoutSection[]\n}\n\n/** A composed page of any kind; a template's `themeSettings` is always null. */\nexport type PageLayout = HomeLayout\n\n/** The design tokens alone, for every page the storefront draws. */\nexport type ThemeSettingsResult = {\n\trevision?: number\n\tpreview: boolean\n\tsettings: ThemeSettings\n}\n\n/**\n * The header's settings as the shop set them (ext/layouts, D131): the strip\n * above the header — shown or not, its words, its link, and whether it is on\n * every page or the home page only — and the handle of the menu across it.\n * Plain text, and a link that is `/path` or `http(s)://`.\n */\nexport type HeaderSettings = {\n\tshow_announcement?: boolean\n\tannouncement_text?: string\n\tannouncement_link?: string\n\tannouncement_pages?: 'all' | 'home'\n\tmenu?: string\n}\n\n/** A footer's link to the shop's page on a social network; `url` is always `http(s)://`. */\nexport type SocialLink = { network: 'instagram' | 'facebook' | 'x' | 'youtube' | 'pinterest' | 'linkedin' | 'whatsapp' | 'telegram'; url: string }\n\n/**\n * The footer's settings (D131): the handle of the menu whose top-level links\n * become its columns, a few words about the shop, whether the newsletter\n * sign-up shows (absent while the newsletter is off), social links and the\n * copyright line. An absent one means the storefront keeps its own.\n */\nexport type FooterSettings = {\n\tmenu?: string\n\tabout?: string\n\tnewsletter?: boolean\n\tsocial?: SocialLink[]\n\tcopyright?: string\n}\n\n/**\n * The published header or footer, or a preview key's draft, with the menu\n * it names already read — live, so a menu edited in the panel shows without a\n * publish. `menu` is null when none is named or the named one is gone.\n */\nexport type SiteChrome<S> = {\n\trevision?: number\n\tpreview: boolean\n\tsettings: S\n\tmenu: StorefrontMenu | null\n}\nexport type SiteHeader = SiteChrome<HeaderSettings>\nexport type SiteFooter = SiteChrome<FooterSettings>\n\n/** Settings that hold a picture's or a video's address, which may be the engine's own upload. */\nconst MEDIA_KEYS = new Set(['image', 'mobile_image', 'poster', 'video_file'])\n\n/**\n * Composed pages from ext/layouts. A store without one — the plugin off,\n * nothing published, an engine built without the module, or a preview key\n * that is wrong or expired — answers null, and the storefront renders its\n * built-in page.\n */\nexport class LayoutService extends BaseService {\n\tasync getHomeLayout({ preview }: { preview?: string | null } = {}): Promise<HomeLayout | null> {\n\t\treturn this.getPageLayout('home', { preview })\n\t}\n\n\t/**\n\t * The template every product page is drawn in: the sections around the\n\t * product's core (`main-product`). Null when none is published, so the\n\t * product page draws exactly as it did before templates existed.\n\t */\n\tasync getProductLayout({ preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\treturn this.getPageLayout('product', { preview })\n\t}\n\n\t/** The template every collection page is drawn in, around its grid (`main-collection`). */\n\tasync getCollectionLayout({ preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\treturn this.getPageLayout('collection', { preview })\n\t}\n\n\t/** Any arranged page by its key; null for none, as the three above. */\n\tasync getPageLayout(page: LayoutPage, { preview }: { preview?: string | null } = {}): Promise<PageLayout | null> {\n\t\tlet layout: EngineLayout\n\t\ttry {\n\t\t\tlayout = await this.data<EngineLayout>(`/x/layouts/${encodeURIComponent(page)}`, {\n\t\t\t\tquery: { preview: preview?.trim() || undefined },\n\t\t\t})\n\t\t} catch (err) {\n\t\t\tif (err instanceof GoCommerceError && err.status === 404) return null\n\t\t\tthrow err\n\t\t}\n\t\tif (!layout) return null\n\t\treturn {\n\t\t\tpage: layout.page,\n\t\t\ttheme: layout.theme,\n\t\t\trevision: layout.revision,\n\t\t\tpreview: !!layout.preview,\n\t\t\tthemeSettings: tokens(layout.theme_settings),\n\t\t\tsections: (layout.sections ?? []).map(toSection),\n\t\t}\n\t}\n\n\t/**\n\t * The store's design tokens, for a page other than the home page: the\n\t * published ones, or a preview key's draft. Null when there are none to\n\t * apply — nothing published, the editor off, an engine without the\n\t * module — and on any failure too: a missing look must never cost the\n\t * page.\n\t */\n\tasync getThemeSettings({ preview }: { preview?: string | null } = {}): Promise<ThemeSettingsResult | null> {\n\t\ttry {\n\t\t\tconst out = await this.data<{ revision?: number; preview?: boolean; settings?: ThemeSettings | null }>('/x/layouts/theme', {\n\t\t\t\tquery: { preview: preview?.trim() || undefined },\n\t\t\t})\n\t\t\tif (!out) return null\n\t\t\treturn { revision: out.revision, preview: !!out.preview, settings: tokens(out.settings) ?? {} }\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t}\n\n\t/**\n\t * The header the shop set in the theme editor (D131), drawn on every\n\t * page: the published one, or a preview key's draft. Null — the\n\t * storefront's own header — when none is published, the editor is off, the\n\t * engine is older, or anything fails: a header is never worth an error page.\n\t */\n\tasync getHeader({ preview }: { preview?: string | null } = {}): Promise<SiteHeader | null> {\n\t\treturn this.chrome<HeaderSettings>('header', preview)\n\t}\n\n\t/** The footer the shop set in the theme editor (D131); null for the storefront's own, as getHeader. */\n\tasync getFooter({ preview }: { preview?: string | null } = {}): Promise<SiteFooter | null> {\n\t\treturn this.chrome<FooterSettings>('footer', preview)\n\t}\n\n\tprivate async chrome<S extends { menu?: string }>(page: 'header' | 'footer', preview?: string | null): Promise<SiteChrome<S> | null> {\n\t\tlet layout: PageLayout | null\n\t\ttry {\n\t\t\tlayout = await this.getPageLayout(page, { preview })\n\t\t} catch {\n\t\t\treturn null\n\t\t}\n\t\tconst section = layout?.sections.find((s) => s.type === page)\n\t\tif (!layout || !section) return null\n\t\tconst settings = { ...section.settings } as S\n\t\tlet menu: StorefrontMenu | null = null\n\t\tif (typeof settings.menu === 'string' && settings.menu) {\n\t\t\tmenu = await new MenuService(this._fetch).getMenu(settings.menu).catch(() => null)\n\t\t}\n\t\treturn { revision: layout.revision, preview: layout.preview, settings, menu }\n\t}\n}\n\nfunction tokens(v: ThemeSettings | null | undefined): ThemeSettings | null {\n\treturn v && typeof v === 'object' && !Array.isArray(v) && Object.keys(v).length ? { ...v } : null\n}\n\n/**\n * An upload is answered root-relative, which the shopper's browser would\n * resolve against the storefront rather than the engine — at the top of a\n * section's settings and inside its lists (a slideshow's slides) alike.\n */\nfunction withMedia(value: unknown, key: string | null): unknown {\n\tif (Array.isArray(value)) return value.map((x) => withMedia(x, null))\n\tif (value && typeof value === 'object') {\n\t\treturn Object.fromEntries(Object.entries(value as Record<string, unknown>).map(([k, x]) => [k, withMedia(x, k)]))\n\t}\n\tif (key && MEDIA_KEYS.has(key) && typeof value === 'string') return mediaUrl(value)\n\treturn value\n}\n\nfunction toSection(s: EngineLayoutSection): HomeLayoutSection {\n\tconst settings = withMedia(s.settings ?? {}, null) as Record<string, unknown>\n\tconst out: HomeLayoutSection = { id: s.id, type: s.type, settings }\n\tif (s.type === 'product-grid') out.products = (s.products ?? []).map((p) => toProduct(p))\n\tif (s.type === 'collection-list') {\n\t\tout.collections = (s.collections ?? []).map((c) => ({\n\t\t\tid: String(c.id),\n\t\t\ttitle: c.title,\n\t\t\tslug: c.slug,\n\t\t\tlink: `/collections/${c.slug}`,\n\t\t\timage: mediaUrl(c.image) ?? null,\n\t\t\tdescription: c.description || null,\n\t\t}))\n\t}\n\treturn out\n}\n\nexport const layoutService = new LayoutService()\n","import type { Vendor } from '../engine'\nimport { toVendor } from '../map'\nimport { BaseService, emptyPage, toPage } from './base.service'\n\n/** The marketplace's sellers: approved vendors only. */\nexport class VendorService extends BaseService {\n\tasync list({\n\t\tpage = 1,\n\t\tlimit = 24,\n\t\tq,\n\t\tsearch,\n\t}: { page?: number; limit?: number; q?: string; search?: string; sort?: string } = {}) {\n\t\tconst env = await this.engine<Vendor[] | null>('/api/vendors', { query: { page, limit, q: q ?? search } })\n\t\treturn toPage(env, toVendor)\n\t}\n\n\tasync getVendor(slug: string) {\n\t\treturn toVendor(await this.data<Vendor>(`/api/vendors/${encodeURIComponent(String(slug))}`))\n\t}\n\n\t/**\n\t * A seller's shelf. The engine's vendors sell through offers on the shop's\n\t * own variants and the public API lists no products by seller, so the shelf\n\t * is empty — the seller's page still renders, with their details.\n\t */\n\tasync fetchProductsOfVendor(_vendorId?: string) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport const vendorService = new VendorService()\n","/**\n * The rest of the family's service surface.\n *\n * Svelte Commerce imports some four dozen services by name because Litekart\n * has them, and an export that is missing is a TypeError at import. Each one\n * is here. Where the engine has the thing, it is wired; where it does not, a\n * read of a list answers empty (a shop legitimately has no reels) and anything\n * that would write, or that names one record, throws `NotSupportedError` —\n * a silent success would tell a shopper their message was sent when nothing\n * left the browser.\n */\nimport type { Plugin } from '../engine'\nimport { NotSupportedError } from '../errors'\nimport { readStaticStore } from '../static-store'\nimport { resolveRestLocally } from '../rest-guard'\nimport { BaseService, emptyPage } from './base.service'\nimport { StoreFacts } from './facts'\nimport { MeilisearchService } from './meilisearch-service'\nimport { StoreService } from './store-service'\n\nconst refuse = (service: string, method: string, why: string) => new NotSupportedError(service, method, why)\n\n/** The storefront's contact form and product enquiries, through ext/contact's inbox. */\nexport class ContactService extends BaseService {\n\tasync submitContactUsForm({\n\t\tname,\n\t\temail,\n\t\tphone,\n\t\tmessage,\n\t\tsubject,\n\t\twebsite,\n\t}: {\n\t\tname: string\n\t\temail: string\n\t\tphone?: string\n\t\tmessage: string\n\t\tsubject?: string\n\t\t/** The form's hidden honeypot, passed on so the engine drops what a bot filled in. */\n\t\twebsite?: string\n\t}) {\n\t\treturn this.data<{ status: string }>('/x/contact/messages', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\tname: String(name ?? ''),\n\t\t\t\temail: String(email ?? ''),\n\t\t\t\t...(phone ? { phone: String(phone) } : {}),\n\t\t\t\t...(subject ? { subject: String(subject) } : {}),\n\t\t\t\tbody: String(message ?? ''),\n\t\t\t\t...(website ? { website: String(website) } : {}),\n\t\t\t},\n\t\t})\n\t}\n}\n\nexport class EnquiryService extends ContactService {\n\tasync create({\n\t\tname,\n\t\temail,\n\t\tphone,\n\t\tmessage,\n\t\tproductId,\n\t}: {\n\t\tname: string\n\t\temail: string\n\t\tphone?: string\n\t\tmessage: string\n\t\tproductId?: string\n\t}) {\n\t\treturn this.submitContactUsForm({\n\t\t\tname,\n\t\t\temail,\n\t\t\tphone,\n\t\t\tsubject: productId ? `Enquiry about product ${productId}` : 'Enquiry',\n\t\t\tmessage,\n\t\t})\n\t}\n}\n\n/** Enabled plugins and their public settings, `{ key, title, settings }`. */\nexport class PluginService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\tconst data: Plugin[] = [...(await this.facts.plugins()).values()]\n\t\treturn { data, count: data.length, pageSize: data.length, noOfPage: 1, page: 1 }\n\t}\n}\n\n/** The store record again, for the callers that ask for it as \"settings\" or \"init\". */\nexport class SettingService extends BaseService {\n\tasync fetchSettings(_args: Record<string, unknown> = {}) {\n\t\treturn new StoreService(this._fetch).getStoreByIdOrDomain()\n\t}\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.fetchSettings(args)\n\t}\n}\n\nexport class InitService extends SettingService {\n\tasync fetchInit(_args: Record<string, unknown> = {}) {\n\t\tconst store = await this.fetchSettings()\n\t\treturn { storeOne: store, store, settings: store }\n\t}\n}\n\nexport class HomeService extends BaseService {\n\t/** A homepage is assembled by the storefront from shelves; the engine has no page of its own for it. */\n\tasync getHome(_args: Record<string, unknown> = {}) {\n\t\treturn { banners: [], groupByBanner: [], categories: [], products: [] }\n\t}\n}\n\n/** Countries for the address form: the storefront's own list, which is what it offers anyway. */\nexport class CountryService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn resolveRestLocally('get', '/api/countries')\n\t}\n}\n\n/** The one currency an engine store settles in. */\nexport class CurrencyService extends BaseService {\n\tprivate readonly facts = new StoreFacts(this._fetch)\n\tasync listCurrencies(_args: Record<string, unknown> = {}) {\n\t\tconst { currency } = await this.facts.ready()\n\t\tconst data = [{ code: currency, name: currency, isDefault: true }]\n\t\treturn { data, count: 1, pageSize: 1, noOfPage: 1, page: 1 }\n\t}\n\tasync list(args: Record<string, unknown> = {}) {\n\t\treturn this.listCurrencies(args)\n\t}\n}\n\n/** States are free text on a GoCommerce address; there is no list to offer. */\nexport class StateService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class RegionService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The header's type-ahead, under the name some storefront builds still call it by. */\nexport class AutocompleteService extends MeilisearchService {\n\tasync list({ q, search }: { q?: string; search?: string } = {}) {\n\t\treturn this.searchAutoComplete({ query: q ?? search })\n\t}\n}\n\nexport class PopularSearchService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The engine keeps no popularity score; a page view is not recorded. */\nexport class PopularityService extends BaseService {\n\tasync updatePopularity(_args: Record<string, unknown> = {}) {\n\t\treturn undefined\n\t}\n}\n\nexport class BlogService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync getOne(_slug: string): Promise<never> {\n\t\tthrow refuse('BlogService', 'getOne', 'the engine has no blog; publish articles as pages')\n\t}\n}\n\nexport class BannerService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync listBanners(args: Record<string, unknown> = {}) {\n\t\treturn this.list(args)\n\t}\n\tasync fetchBanners(args: Record<string, unknown> = {}) {\n\t\treturn this.list(args)\n\t}\n}\n\nexport class ReelsService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class DealService extends BaseService {\n\tasync fetchDeals(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class GalleryService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\nexport class ChatService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n\tasync chats(): Promise<never> {\n\t\tthrow refuse('ChatService', 'chats', 'the engine has no shopper chat')\n\t}\n\tasync save(): Promise<never> {\n\t\tthrow refuse('ChatService', 'save', 'the engine has no shopper chat')\n\t}\n}\n\nexport class FeedbackService extends BaseService {\n\tasync save(): Promise<never> {\n\t\tthrow refuse('FeedbackService', 'save', 'use the contact form')\n\t}\n}\n\nexport class DemoRequestService extends BaseService {\n\tasync save(): Promise<never> {\n\t\tthrow refuse('DemoRequestService', 'save', 'use the contact form')\n\t}\n}\n\nexport class UploadService extends BaseService {\n\tasync uploadMultipleToS3(): Promise<never> {\n\t\tthrow refuse('UploadService', 'uploadMultipleToS3', 'shoppers cannot upload files to the engine')\n\t}\n\tasync upload(): Promise<never> {\n\t\tthrow refuse('UploadService', 'upload', 'shoppers cannot upload files to the engine')\n\t}\n}\n\nexport class WarrantyService extends BaseService {\n\tasync submitWarrantyRegistration(): Promise<never> {\n\t\tthrow refuse('WarrantyService', 'submitWarrantyRegistration', 'the engine has no warranty registrations')\n\t}\n}\n\nexport class VarniCustomDesignService extends BaseService {\n\tasync submitForm(): Promise<never> {\n\t\tthrow refuse('VarniCustomDesignService', 'submitForm', 'custom design requests are a Litekart feature')\n\t}\n}\n\nexport class VarniCustomProductService extends BaseService {\n\tasync list(_args: Record<string, unknown> = {}) {\n\t\treturn emptyPage()\n\t}\n}\n\n/** The storefront's static store record, for code that wants the raw config. */\nexport const staticStore = () => readStaticStore()\n\nexport const contactService = new ContactService()\nexport const enquiryService = new EnquiryService()\nexport const pluginService = new PluginService()\nexport const settingService = new SettingService()\nexport const initService = new InitService()\nexport const homeService = new HomeService()\nexport const countryService = new CountryService()\nexport const currencyService = new CurrencyService()\nexport const stateService = new StateService()\nexport const regionService = new RegionService()\nexport const autocompleteService = new AutocompleteService()\nexport const popularSearchService = new PopularSearchService()\nexport const popularityService = new PopularityService()\nexport const blogService = new BlogService()\nexport const bannerService = new BannerService()\nexport const reelsService = new ReelsService()\nexport const dealService = new DealService()\nexport const galleryService = new GalleryService()\nexport const chatService = new ChatService()\nexport const feedbackService = new FeedbackService()\nexport const demoRequestService = new DemoRequestService()\nexport const uploadService = new UploadService()\nexport const warrantyService = new WarrantyService()\nexport const varniCustomDesignService = new VarniCustomDesignService()\nexport const varniCustomProductService = new VarniCustomProductService()\n\n// kitcommerce-core reads the plural spellings; the family exports the singular. Both, then.\nexport { PluginService as PluginsService, SettingService as SettingsService }\nexport const pluginsService = pluginService\nexport const settingsService = settingService\n","import type { ListMeta, Offer, Variant } from '../engine'\nimport { toMajor } from '../money'\nimport { BaseService } from './base.service'\n\n/**\n * Variants on their own, and the marketplace's offers on one.\n *\n * Svelte Commerce reads variants through their product, so this service is\n * for code written against GoCommerce: it answers the engine's own shapes —\n * numeric ids, money as `{ amount_minor, currency }` — with a major-unit\n * `amount` added beside each price so a template need not divide.\n */\nexport class VariantService extends BaseService {\n\t/** A product's variants, inactive ones included (filter on `active`), in the merchant's order. */\n\tasync list(productId: string | number, { page = 1, limit = 50 }: { page?: number; limit?: number } = {}) {\n\t\tconst env = await this.engine<Variant[] | null>('/api/variants', { query: { product_id: productId, page, limit } })\n\t\treturn { data: (env.data ?? []).map(withAmounts), meta: env.meta as ListMeta | undefined }\n\t}\n\n\tasync getOne(id: string | number) {\n\t\treturn withAmounts(await this.data<Variant>(`/api/variants/${encodeURIComponent(String(id))}`))\n\t}\n\n\t/**\n\t * What each approved seller asks for this variant, cheapest first. A cart\n\t * line takes a variant, not an offer, so this informs a shopper rather than\n\t * choosing who fulfils.\n\t */\n\tasync offers(variantId: string | number) {\n\t\tconst offers =\n\t\t\t(await this.data<Offer[] | null>(`/api/variants/${encodeURIComponent(String(variantId))}/offers`)) ?? []\n\t\treturn offers.map((o) => ({ ...o, price: { ...o.price, amount: toMajor(o.price) } }))\n\t}\n}\n\nfunction withAmounts(v: Variant) {\n\treturn {\n\t\t...v,\n\t\tprice: { ...v.price, amount: toMajor(v.price) },\n\t\tcompare_at_price: v.compare_at_price ? { ...v.compare_at_price, amount: toMajor(v.compare_at_price) } : undefined,\n\t}\n}\n\nexport const variantService = new VariantService()\n","import { storedCartId } from '../browser'\nimport { BaseService } from './base.service'\n\n/** Which WhatsApp boxes checkout shows. */\nexport type WhatsappConsentOffer = {\n\t/** The store sends order updates on WhatsApp: show the opt-in. */\n\tenabled: boolean\n\t/** It sends basket reminders too: show the marketing box as well. */\n\tmarketing: boolean\n}\n\n/** What the engine kept for a phone: the number as it reads it, in E.164. */\nexport type WhatsappConsent = {\n\tphone: string\n\torderUpdates: boolean\n\tmarketing: boolean\n}\n\n/**\n * The shopper's WhatsApp opt-in at checkout (ext/notify-whatsapp).\n *\n * The engine keeps the latest answer per phone, so an unticked box is sent as\n * `false` rather than left out: it is how a shopper who said yes last time\n * says no now.\n */\nexport class WhatsappService extends BaseService {\n\t/**\n\t * Whether to show the boxes. Never throws: an engine without the module, or\n\t * one that fails, answers both off, because checkout must not depend on it.\n\t */\n\tasync consentOffer(): Promise<WhatsappConsentOffer> {\n\t\ttry {\n\t\t\tconst d = await this.data<Partial<WhatsappConsentOffer> | null>('/x/notify-whatsapp/consent')\n\t\t\tconst enabled = d?.enabled === true\n\t\t\treturn { enabled, marketing: enabled && d?.marketing === true }\n\t\t} catch {\n\t\t\treturn { enabled: false, marketing: false }\n\t\t}\n\t}\n\n\t/**\n\t * Records both answers for the phone as typed, against the bag (with\n\t * `marketing`, the engine keeps the phone on it for basket reminders). Throws\n\t * the engine's 400 (`validation_failed`) when the phone is not a WhatsApp\n\t * number for the store's country.\n\t */\n\tasync setConsent({\n\t\tcartId,\n\t\tphone,\n\t\torderUpdates,\n\t\tmarketing,\n\t}: {\n\t\tcartId?: string | null\n\t\tphone: string\n\t\torderUpdates: boolean\n\t\tmarketing: boolean\n\t}): Promise<WhatsappConsent> {\n\t\tconst d = await this.data<{ phone: string; order_updates: boolean; marketing: boolean }>(\n\t\t\t'/x/notify-whatsapp/consent',\n\t\t\t{\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbody: {\n\t\t\t\t\tcart_id: cartId || storedCartId() || '',\n\t\t\t\t\tphone: String(phone ?? '').trim(),\n\t\t\t\t\torder_updates: orderUpdates === true,\n\t\t\t\t\tmarketing: marketing === true,\n\t\t\t\t},\n\t\t\t},\n\t\t)\n\t\treturn { phone: d.phone, orderUpdates: d.order_updates, marketing: d.marketing }\n\t}\n}\n\nexport const whatsappService = new WhatsappService()\n","import type { Address, Cart, CheckoutResult, ListMeta, Order, PaymentIntent } from '../engine'\nimport type { Money } from '../money'\nimport { GoCommerceError } from '../errors'\nimport { toCart, toEngineAddress, toOrder } from '../map'\nimport { cartExtras, rememberCartId, rememberOrder, storedCartId, type StorefrontAddress } from '../browser'\nimport { BaseService } from './base.service'\n\n// ---------------------------------------------------------------- ext/b2b shapes\n\nexport type B2bRole = 'admin' | 'approver' | 'buyer'\n\nexport type Company = {\n\tid: number\n\tcode: string\n\tname: string\n\ttax_id: string\n\tstatus: 'active' | 'on_hold' | 'closed'\n\tgroup_id: number | null\n\t/** `null`: no account with the store — the company pays up front. */\n\tcredit_limit: Money | null\n\tnet_days: number\n\t/** `null`: a buyer never needs approval. */\n\tapproval_threshold: Money | null\n\trequire_po: boolean\n\tmember_count: number\n\t/** More than 0: the company is a dealer, and receives leads. */\n\tterritory_count: number\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Credit = {\n\tlimit: Money | null\n\toutstanding: Money\n\tavailable: Money | null\n\toverdue: Money\n\toverdue_orders: number\n\tnet_days: number\n}\n\nexport type Member = {\n\tcompany_id: number\n\tcustomer_id: number\n\temail: string\n\tconfirmed: boolean\n\tname: string\n\trole: B2bRole\n\tcreated_at: string\n}\n\nexport type Invitation = {\n\tid: number\n\tcompany_id: number\n\temail: string\n\trole: B2bRole\n\tinvited_by: string\n\texpires_at: string\n\taccepted_at?: string\n\tcreated_at: string\n}\n\nexport type CompanyOrder = {\n\torder_id: number\n\tnumber: string\n\tstatus: string\n\tpayment_status: string\n\ttotal: Money\n\tpo_number: string\n\tplaced_by: string\n\ton_account: boolean\n\tdue_at?: string\n\toverdue: boolean\n\tcompany_id: number\n\tcompany_name: string\n\tapproval_id?: number\n\tquote_id?: number\n\tcreated_at: string\n}\n\nexport type Approval = {\n\tid: number\n\tcompany_id: number\n\tkind: 'cart' | 'quote'\n\tquote_id?: number\n\tstatus: 'pending' | 'placing' | 'approved' | 'rejected' | 'cancelled'\n\trequested_by: number\n\trequested_by_email: string\n\tlines: { variant_id: number; sku: string; quantity: number; unit_price: Money }[]\n\tsubtotal: Money\n\ttotal: Money\n\tpayment_method: string\n\tpo_number: string\n\tdecided_by?: number\n\tdecided_at?: string\n\treason?: string\n\tlast_error?: string\n\torder_id?: number\n\torder_number?: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Quote = {\n\tid: number\n\tnumber: string\n\tcompany_id: number\n\tcompany_name: string\n\tstatus: 'requested' | 'quoted' | 'awaiting_approval' | 'accepted' | 'declined' | 'expired'\n\trequested_by: number\n\trequested_by_email: string\n\tnote: string\n\treply: string\n\tdeclined_by?: string\n\tlines: { variant_id: number; sku: string; title: string; quantity: number; unit_price: Money | null }[]\n\ttotal: Money | null\n\texpires_at?: string\n\tquoted_at?: string\n\taccepted_at?: string\n\torder_id?: number\n\torder_number?: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type Lead = {\n\tid: number\n\tname: string\n\temail: string\n\tphone: string\n\tmessage: string\n\tcountry: string\n\tstate: string\n\tpostal_code: string\n\tvariant_id: number | null\n\tproduct_id: number | null\n\tproduct_title?: string\n\tvariant_sku?: string\n\tstatus: 'new' | 'contacted' | 'won' | 'lost'\n\tcompany_id: number | null\n\tcompany_name?: string\n\trouted_by: 'territory' | 'store' | 'unrouted'\n\tsource: string\n\tcreated_at: string\n\tupdated_at: string\n}\n\nexport type RejectedLine = {\n\tsku: string\n\tvariant_id: number | null\n\tquantity: number\n\treason: 'not_found' | 'inactive' | 'insufficient_stock' | 'invalid'\n\tmessage: string\n}\n\ntype Paged<T> = { data: T[]; meta?: ListMeta }\n\ntype PlaceOptions = {\n\t/** An engine payment code; omitted, the company's account (`on_account`) when it has one. */\n\tpaymentMethod?: string\n\t/** Required when the company says so (`company.require_po`). */\n\tpoNumber?: string\n\tname?: string\n\tphone?: string\n\t/** Defaults to the address the checkout's address step kept for this cart. */\n\taddress?: StorefrontAddress | Address\n}\n\n/** A checkout or quote acceptance either placed an order or, for a buyer over the limit, asked for approval. */\nexport type B2bPlaced =\n\t| { kind: 'order'; orderNo: string; order: ReturnType<typeof toOrder>; payment: PaymentIntent }\n\t| { kind: 'approval'; approval: Approval }\n\n/**\n * Buying for a business (ext/b2b): a company with buyers in roles, orders on\n * account against a credit limit, approvals, quotes, a quick order by SKU, a\n * repeat order, and a dealer's leads.\n *\n * Every call but `submitLead` needs a signed-in shopper (ext/identity) who is\n * a member of a company; a signed-in account that is not answers 403, so\n * `me()` is how a storefront tells a business account from a consumer one.\n * Answers are the engine's own shapes — numeric ids, money as\n * `{ amount_minor, currency }` — except carts, which come back as the\n * storefront's bag so a quick-order page can hand them straight to it.\n */\nexport class B2bService extends BaseService {\n\t// ------------------------------------------------------------ company\n\n\t/** The company, the caller's role in it, and its credit: limit, outstanding, available, overdue. */\n\tasync me() {\n\t\tconst me = await this.data<{\n\t\t\tcompany: Company & { notes?: string; metadata?: unknown }\n\t\t\trole: B2bRole\n\t\t\tcredit: Credit\n\t\t}>('/x/b2b/me', { auth: true })\n\t\t// The engine answers the store's own notes on the company to its buyers;\n\t\t// they are not this storefront's to show.\n\t\tconst { notes: _notes, metadata: _metadata, ...company } = me.company\n\t\treturn { company: company as Company, role: me.role, credit: me.credit }\n\t}\n\n\tasync members() {\n\t\treturn (await this.data<Member[] | null>('/x/b2b/members', { auth: true })) ?? []\n\t}\n\n\t/** Admin only. Demoting the last admin is refused (409). */\n\tasync setMemberRole(customerId: number | string, role: B2bRole) {\n\t\treturn this.data<Member>(`/x/b2b/members/${id(customerId)}`, { method: 'PATCH', auth: true, body: { role } })\n\t}\n\n\t/** An admin removes anyone; any member may remove themselves. */\n\tasync removeMember(customerId: number | string) {\n\t\tawait this.engine(`/x/b2b/members/${id(customerId)}`, { method: 'DELETE', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ invitations\n\n\t/** Admin only. Open invitations: not accepted, not expired. */\n\tasync invitations() {\n\t\treturn (await this.data<Invitation[] | null>('/x/b2b/invitations', { auth: true })) ?? []\n\t}\n\n\t/** Admin only. Emails a link; a second invitation to the same address replaces the first. */\n\tasync invite({ email, role }: { email: string; role: B2bRole }) {\n\t\treturn this.data<Invitation>('/x/b2b/invitations', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { email: String(email ?? '').trim(), role },\n\t\t})\n\t}\n\n\tasync withdrawInvitation(invitationId: number | string) {\n\t\tawait this.engine(`/x/b2b/invitations/${id(invitationId)}`, { method: 'DELETE', auth: true })\n\t}\n\n\t/**\n\t * The token from the invitation email, accepted by the account it was sent\n\t * to — which also confirms that account's email address.\n\t */\n\tasync acceptInvitation(token: string) {\n\t\treturn this.data<Member>('/x/b2b/invitations/accept', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: { token: String(token ?? '').trim() },\n\t\t})\n\t}\n\n\t// ------------------------------------------------------------ filling a basket\n\n\t/**\n\t * A quick order: up to 500 lines by SKU or variant id, into the bag (or a new\n\t * one), at the company's prices. A line that will not go in is reported in\n\t * `rejected` with its reason; the rest are added.\n\t */\n\tasync addLines({\n\t\tcartId,\n\t\tlines,\n\t}: {\n\t\tcartId?: string\n\t\tlines: { sku?: string; variantId?: number | string; quantity: number }[]\n\t}) {\n\t\tconst res = await this.data<{ cart: Cart; rejected: RejectedLine[] | null }>('/x/b2b/cart/lines', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\t...((cartId ?? storedCartId()) ? { cart_id: cartId ?? storedCartId() } : {}),\n\t\t\t\tlines: (lines ?? []).map((l) => ({\n\t\t\t\t\t...(l.variantId ? { variant_id: Number(l.variantId) } : {}),\n\t\t\t\t\t...(l.sku ? { sku: String(l.sku).trim() } : {}),\n\t\t\t\t\tquantity: Number(l.quantity),\n\t\t\t\t})),\n\t\t\t},\n\t\t})\n\t\trememberCartId(res.cart.id)\n\t\treturn { cart: toCart(res.cart, cartExtras(res.cart.id)), rejected: res.rejected ?? [] }\n\t}\n\n\t/** A past order's lines in a new bag, at today's prices. Nothing is placed. */\n\tasync reorder(orderId: number | string) {\n\t\tconst res = await this.data<{ cart: Cart; rejected: RejectedLine[] | null }>(\n\t\t\t`/x/b2b/orders/${id(orderId)}/reorder`,\n\t\t\t{\n\t\t\t\tmethod: 'POST',\n\t\t\t\tauth: true,\n\t\t\t},\n\t\t)\n\t\trememberCartId(res.cart.id)\n\t\treturn { cart: toCart(res.cart, cartExtras(res.cart.id)), rejected: res.rejected ?? [] }\n\t}\n\n\t// ------------------------------------------------------------ placing an order\n\n\t/**\n\t * Places the bag through the company: on account by default, with a PO\n\t * number, optionally only some lines (`lineIds`). A buyer over the company's\n\t * approval threshold gets `{ kind: 'approval' }` instead of an order — the\n\t * bag stays as it was, and an approver places it later.\n\t *\n\t * Over the credit limit is 403 `credit_limit_exceeded`; `me().credit` says\n\t * how much is available before the shopper tries.\n\t */\n\tasync checkout({\n\t\tcartId,\n\t\tlineIds,\n\t\tshippingRateId,\n\t\treturnUrl,\n\t\tpaymentData,\n\t\t...opts\n\t}: PlaceOptions & {\n\t\tcartId?: string\n\t\tlineIds?: (number | string)[]\n\t\tshippingRateId?: number | string\n\t\treturnUrl?: string\n\t\tpaymentData?: Record<string, string>\n\t} = {}): Promise<B2bPlaced> {\n\t\tconst cart = cartId || storedCartId()\n\t\tif (!cart) throw new GoCommerceError('Your bag is empty.', 400)\n\t\tconst extras = cartExtras(cart)\n\t\tconst rate = shippingRateId ?? extras.shippingRateId\n\t\tconst body = {\n\t\t\tcart_id: cart,\n\t\t\t...this.placeBody(opts, extras.shippingAddress ?? undefined),\n\t\t\t...(rate ? { shipping_rate_id: Number(rate) } : {}),\n\t\t\t...(lineIds?.length ? { line_ids: lineIds.map(Number) } : {}),\n\t\t\t...(returnUrl ? { return_url: returnUrl } : {}),\n\t\t\t...(paymentData ? { payment_data: paymentData } : {}),\n\t\t}\n\t\tconst res = await this.data<CheckoutResult & { approval?: Approval }>('/x/b2b/checkout', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody,\n\t\t\theaders: { 'Idempotency-Key': attemptKey(`b2b:${JSON.stringify(body)}`) },\n\t\t})\n\t\treturn this.placed(res, cart)\n\t}\n\n\t// ------------------------------------------------------------ the company's orders\n\n\t/** Admins and approvers see the company's; a buyer sees their own. `q` matches the number, PO or email. */\n\tasync orders({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t\tq,\n\t\toverdue,\n\t}: { page?: number; limit?: number; q?: string; overdue?: boolean } = {}) {\n\t\treturn this.engine<CompanyOrder[]>('/x/b2b/orders', {\n\t\t\tauth: true,\n\t\t\tquery: { page, limit, q, ...(overdue ? { overdue: 'true' } : {}) },\n\t\t}) as Promise<Paged<CompanyOrder>>\n\t}\n\n\t// ------------------------------------------------------------ approvals\n\n\tasync approvals({\n\t\tpage = 1,\n\t\tlimit = 20,\n\t\tstatus,\n\t}: { page?: number; limit?: number; status?: Approval['status'] } = {}) {\n\t\treturn this.engine<Approval[]>('/x/b2b/approvals', { auth: true, query: { page, limit, status } }) as Promise<\n\t\t\tPaged<Approval>\n\t\t>\n\t}\n\n\tasync approval(approvalId: number | string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}`, { auth: true })\n\t}\n\n\t/**\n\t * Admin or approver: places the requested order at the prices it was\n\t * requested at. Credit limits and holds still apply. The payment intent is\n\t * the approver's to act on — for an account order there is nothing to do.\n\t */\n\tasync approve(approvalId: number | string) {\n\t\tconst res = await this.data<CheckoutResult & { approval: Approval }>(`/x/b2b/approvals/${id(approvalId)}/approve`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t})\n\t\treturn { approval: res.approval, orderNo: res.order.number, order: toOrder(res.order), payment: res.payment }\n\t}\n\n\tasync reject(approvalId: number | string, reason?: string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}/reject`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\t...(reason ? { body: { reason } } : {}),\n\t\t})\n\t}\n\n\t/** The buyer who asked withdraws the request. */\n\tasync cancelApproval(approvalId: number | string) {\n\t\treturn this.data<Approval>(`/x/b2b/approvals/${id(approvalId)}/cancel`, { method: 'POST', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ quotes\n\n\tasync quotes({ page = 1, limit = 20, status }: { page?: number; limit?: number; status?: Quote['status'] } = {}) {\n\t\treturn this.engine<Quote[]>('/x/b2b/quotes', { auth: true, query: { page, limit, status } }) as Promise<\n\t\t\tPaged<Quote>\n\t\t>\n\t}\n\n\tasync quote(quoteId: number | string) {\n\t\treturn this.data<Quote>(`/x/b2b/quotes/${id(quoteId)}`, { auth: true })\n\t}\n\n\t/** Asks the store to price these lines. The store answers with unit prices and an expiry. */\n\tasync requestQuote({ lines, note }: { lines: { variantId: number | string; quantity: number }[]; note?: string }) {\n\t\treturn this.data<Quote>('/x/b2b/quotes', {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: {\n\t\t\t\tlines: (lines ?? []).map((l) => ({ variant_id: Number(l.variantId), quantity: Number(l.quantity) })),\n\t\t\t\t...(note ? { note } : {}),\n\t\t\t},\n\t\t})\n\t}\n\n\t/** Places the quote at its agreed prices — or, for a buyer over the threshold, asks for approval. */\n\tasync acceptQuote(quoteId: number | string, opts: PlaceOptions = {}): Promise<B2bPlaced> {\n\t\tconst res = await this.data<CheckoutResult & { approval?: Approval }>(`/x/b2b/quotes/${id(quoteId)}/accept`, {\n\t\t\tmethod: 'POST',\n\t\t\tauth: true,\n\t\t\tbody: this.placeBody(opts),\n\t\t})\n\t\treturn this.placed(res)\n\t}\n\n\tasync declineQuote(quoteId: number | string) {\n\t\treturn this.data<Quote>(`/x/b2b/quotes/${id(quoteId)}/decline`, { method: 'POST', auth: true })\n\t}\n\n\t// ------------------------------------------------------------ dealer leads\n\n\t/**\n\t * The public \"find a dealer\" form: no account needed. The engine routes it to\n\t * the dealer whose territory covers the address — or keeps it — and answers\n\t * the same either way, so the form never reveals who got it.\n\t */\n\tasync submitLead(lead: {\n\t\tname?: string\n\t\temail?: string\n\t\tphone?: string\n\t\tmessage?: string\n\t\tcountry?: string\n\t\tstate?: string\n\t\tpostalCode?: string\n\t\tproductId?: number | string\n\t\tvariantId?: number | string\n\t\tsource?: string\n\t}) {\n\t\treturn this.data<{ accepted: boolean }>('/x/b2b/leads', {\n\t\t\tmethod: 'POST',\n\t\t\tbody: {\n\t\t\t\t...(lead.name ? { name: lead.name } : {}),\n\t\t\t\t...(lead.email ? { email: lead.email } : {}),\n\t\t\t\t...(lead.phone ? { phone: lead.phone } : {}),\n\t\t\t\t...(lead.message ? { message: lead.message } : {}),\n\t\t\t\t...(lead.country ? { country: lead.country } : {}),\n\t\t\t\t...(lead.state ? { state: lead.state } : {}),\n\t\t\t\t...(lead.postalCode ? { postal_code: lead.postalCode } : {}),\n\t\t\t\t...(lead.productId ? { product_id: Number(lead.productId) } : {}),\n\t\t\t\t...(lead.variantId ? { variant_id: Number(lead.variantId) } : {}),\n\t\t\t\t...(lead.source ? { source: lead.source } : {}),\n\t\t\t},\n\t\t})\n\t}\n\n\t/** A dealer's admins and approvers: the leads routed to their company. */\n\tasync leads({ page = 1, limit = 20, status }: { page?: number; limit?: number; status?: Lead['status'] } = {}) {\n\t\treturn this.engine<Lead[]>('/x/b2b/leads', { auth: true, query: { page, limit, status } }) as Promise<Paged<Lead>>\n\t}\n\n\tasync setLeadStatus(leadId: number | string, status: Lead['status']) {\n\t\treturn this.data<Lead>(`/x/b2b/leads/${id(leadId)}`, { method: 'PATCH', auth: true, body: { status } })\n\t}\n\n\t// ------------------------------------------------------------ internals\n\n\t/** The fields checkout and quote acceptance share. Only declared ones: the engine refuses the rest. */\n\tprivate placeBody(opts: PlaceOptions, fallback?: StorefrontAddress) {\n\t\tconst raw = opts.address ?? fallback\n\t\tif (!raw) throw new GoCommerceError('Add a delivery address first.', 400)\n\t\tconst address = 'line1' in raw ? (raw as Address) : toEngineAddress(raw as StorefrontAddress)\n\t\treturn {\n\t\t\taddress,\n\t\t\t...(opts.paymentMethod ? { payment_method: String(opts.paymentMethod).toLowerCase() } : {}),\n\t\t\t...(opts.poNumber ? { po_number: String(opts.poNumber).trim() } : {}),\n\t\t\t...((opts.name ?? address.name) ? { name: opts.name ?? address.name } : {}),\n\t\t\t...((opts.phone ?? address.phone) ? { phone: opts.phone ?? address.phone } : {}),\n\t\t}\n\t}\n\n\tprivate placed(res: Partial<CheckoutResult> & { approval?: Approval }, cartId?: string): B2bPlaced {\n\t\tif (res.approval && !res.order) return { kind: 'approval', approval: res.approval }\n\t\tconst order = res.order as Order\n\t\tif (order.access_token && cartId) {\n\t\t\trememberOrder({ number: order.number, token: order.access_token, cartId, reference: res.payment?.reference })\n\t\t}\n\t\treturn { kind: 'order', orderNo: order.number, order: toOrder(order), payment: res.payment as PaymentIntent }\n\t}\n}\n\nconst id = (v: number | string) => encodeURIComponent(String(v))\n\n/**\n * One Idempotency-Key per distinct request, kept for the page's life: a retry\n * of the same checkout — a double click, a timeout — resumes it rather than\n * placing a second order, and a changed request gets a new key, since the\n * engine refuses a key replayed with a different body.\n */\nconst keys = new Map<string, string>()\nfunction attemptKey(request: string): string {\n\tlet key = keys.get(request)\n\tif (!key) {\n\t\tconst c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto\n\t\tkey = c?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`\n\t\tkeys.set(request, key)\n\t}\n\treturn key\n}\n\nexport const b2bService = new B2bService()\n"]}
|