@usethrottle/storefront-react 0.0.0-stage → 0.1.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/CLAUDE.md +67 -0
- package/README.md +119 -2
- package/dist/StorefrontProvider-Br4wUHui.d.cts +559 -0
- package/dist/StorefrontProvider-DLEPEjg6.d.ts +559 -0
- package/dist/account/index.cjs +69 -0
- package/dist/account/index.cjs.map +1 -0
- package/dist/account/index.d.cts +23 -0
- package/dist/account/index.d.ts +23 -0
- package/dist/account/index.js +68 -0
- package/dist/account/index.js.map +1 -0
- package/dist/chunk-2LCPIY2P.cjs +16 -0
- package/dist/chunk-2LCPIY2P.cjs.map +1 -0
- package/dist/chunk-3A72UY6T.js +2126 -0
- package/dist/chunk-3A72UY6T.js.map +1 -0
- package/dist/chunk-3JMIVAHN.js +185 -0
- package/dist/chunk-3JMIVAHN.js.map +1 -0
- package/dist/chunk-4J6AGWNC.cjs +24 -0
- package/dist/chunk-4J6AGWNC.cjs.map +1 -0
- package/dist/chunk-4U6MYDZV.js +17 -0
- package/dist/chunk-4U6MYDZV.js.map +1 -0
- package/dist/chunk-66HDJVPS.js +22 -0
- package/dist/chunk-66HDJVPS.js.map +1 -0
- package/dist/chunk-6X2OZSNV.cjs +83 -0
- package/dist/chunk-6X2OZSNV.cjs.map +1 -0
- package/dist/chunk-6ZMMZ245.cjs +2127 -0
- package/dist/chunk-6ZMMZ245.cjs.map +1 -0
- package/dist/chunk-7R37CVAB.cjs +23 -0
- package/dist/chunk-7R37CVAB.cjs.map +1 -0
- package/dist/chunk-A3IFWQUV.js +368 -0
- package/dist/chunk-A3IFWQUV.js.map +1 -0
- package/dist/chunk-AYC2YK4E.cjs +95 -0
- package/dist/chunk-AYC2YK4E.cjs.map +1 -0
- package/dist/chunk-AZV5U7YB.cjs +18 -0
- package/dist/chunk-AZV5U7YB.cjs.map +1 -0
- package/dist/chunk-CE2SKNQP.cjs +71 -0
- package/dist/chunk-CE2SKNQP.cjs.map +1 -0
- package/dist/chunk-D76CRI4X.js +2175 -0
- package/dist/chunk-D76CRI4X.js.map +1 -0
- package/dist/chunk-DOAII637.cjs +186 -0
- package/dist/chunk-DOAII637.cjs.map +1 -0
- package/dist/chunk-DYHHAOMG.cjs +17 -0
- package/dist/chunk-DYHHAOMG.cjs.map +1 -0
- package/dist/chunk-EYSVU5SJ.js +196 -0
- package/dist/chunk-EYSVU5SJ.js.map +1 -0
- package/dist/chunk-HSUUDZWS.js +37 -0
- package/dist/chunk-HSUUDZWS.js.map +1 -0
- package/dist/chunk-HZ6VEN6Q.cjs +101 -0
- package/dist/chunk-HZ6VEN6Q.cjs.map +1 -0
- package/dist/chunk-IJOTLGPT.js +16 -0
- package/dist/chunk-IJOTLGPT.js.map +1 -0
- package/dist/chunk-ISDATHVC.js +219 -0
- package/dist/chunk-ISDATHVC.js.map +1 -0
- package/dist/chunk-LW2A6USV.js +100 -0
- package/dist/chunk-LW2A6USV.js.map +1 -0
- package/dist/chunk-M4YXSLRG.cjs +369 -0
- package/dist/chunk-M4YXSLRG.cjs.map +1 -0
- package/dist/chunk-NDUEJJLP.cjs +2176 -0
- package/dist/chunk-NDUEJJLP.cjs.map +1 -0
- package/dist/chunk-NNE4FYRT.js +820 -0
- package/dist/chunk-NNE4FYRT.js.map +1 -0
- package/dist/chunk-NW3EFHY2.js +15 -0
- package/dist/chunk-NW3EFHY2.js.map +1 -0
- package/dist/chunk-NZRUQUN5.js +167 -0
- package/dist/chunk-NZRUQUN5.js.map +1 -0
- package/dist/chunk-P6HHE57S.cjs +38 -0
- package/dist/chunk-P6HHE57S.cjs.map +1 -0
- package/dist/chunk-PHY7AY27.cjs +197 -0
- package/dist/chunk-PHY7AY27.cjs.map +1 -0
- package/dist/chunk-PNJOFFTL.cjs +128 -0
- package/dist/chunk-PNJOFFTL.cjs.map +1 -0
- package/dist/chunk-PXZQ4ONA.js +127 -0
- package/dist/chunk-PXZQ4ONA.js.map +1 -0
- package/dist/chunk-Q3VTUBPP.js +82 -0
- package/dist/chunk-Q3VTUBPP.js.map +1 -0
- package/dist/chunk-Q3XFD5UI.js +45 -0
- package/dist/chunk-Q3XFD5UI.js.map +1 -0
- package/dist/chunk-QM7KTT7F.js +94 -0
- package/dist/chunk-QM7KTT7F.js.map +1 -0
- package/dist/chunk-RLWZOLXL.js +70 -0
- package/dist/chunk-RLWZOLXL.js.map +1 -0
- package/dist/chunk-SV53BRP2.js +23 -0
- package/dist/chunk-SV53BRP2.js.map +1 -0
- package/dist/chunk-VWXJO427.cjs +821 -0
- package/dist/chunk-VWXJO427.cjs.map +1 -0
- package/dist/chunk-WIIOJDHR.cjs +220 -0
- package/dist/chunk-WIIOJDHR.cjs.map +1 -0
- package/dist/chunk-XQHGFWLG.cjs +46 -0
- package/dist/chunk-XQHGFWLG.cjs.map +1 -0
- package/dist/chunk-ZHCXI2ZZ.cjs +168 -0
- package/dist/chunk-ZHCXI2ZZ.cjs.map +1 -0
- package/dist/index-RSj2Rg62.d.cts +8 -0
- package/dist/index-RSj2Rg62.d.ts +8 -0
- package/dist/index.cjs +2829 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1718 -0
- package/dist/index.d.ts +1718 -0
- package/dist/index.js +2828 -0
- package/dist/index.js.map +1 -0
- package/dist/metadata-QhKw-tvz.d.cts +188 -0
- package/dist/metadata-QhKw-tvz.d.ts +188 -0
- package/dist/next/client.cjs +84 -0
- package/dist/next/client.cjs.map +1 -0
- package/dist/next/client.d.cts +40 -0
- package/dist/next/client.d.ts +40 -0
- package/dist/next/client.js +83 -0
- package/dist/next/client.js.map +1 -0
- package/dist/next/index.cjs +1090 -0
- package/dist/next/index.cjs.map +1 -0
- package/dist/next/index.d.cts +218 -0
- package/dist/next/index.d.ts +218 -0
- package/dist/next/index.js +1049 -0
- package/dist/next/index.js.map +1 -0
- package/dist/server/index.cjs +994 -0
- package/dist/server/index.cjs.map +1 -0
- package/dist/server/index.d.cts +229 -0
- package/dist/server/index.d.ts +229 -0
- package/dist/server/index.js +951 -0
- package/dist/server/index.js.map +1 -0
- package/dist/styles.css +2111 -0
- package/dist/use-part-DCfFk7kf.d.ts +24 -0
- package/dist/use-part-DgjPBL_O.d.cts +24 -0
- package/package.json +121 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/next/index.ts","../../src/next/routes.tsx","../../src/server/client.ts","../../src/server/loaders.ts","../../src/settings/defaults.ts","../../src/settings/guards.ts","../../src/settings/normalize.ts","../../src/url/shop-list-query.ts","../../src/url/shop-query.ts","../../src/url/routes.ts","../../src/server/reviews-page.ts","../../src/site/resolve.ts","../../src/site/menu.ts","../../src/site/catalog-adapter.ts","../../src/seo/metadata.ts","../../src/next/generation-sync.ts","../../src/next/sync-handler.ts","../../src/next/coalesce.ts","../../src/next/revalidate.ts"],"sourcesContent":["// Server-only helpers for Next's App Router. No \"use client\": import these from a route file or a server component.\nexport { createAccountPage, createProductPage, createSearchPage, createShopAllPage } from './routes';\nexport type { StorefrontRoute, StorefrontRouteOptions } from './routes';\nexport { createGenerationSync } from './generation-sync';\nexport type { GenerationSyncDeps, GenerationSyncResult } from './generation-sync';\nexport { createGenerationSyncHandler } from './sync-handler';\nexport type { GenerationSyncHandlerOptions } from './sync-handler';\nexport { createRevalidateHandler } from './revalidate';\nexport type { RevalidateHandlerOptions } from './revalidate';\nexport { CATALOG_TAG, REVALIDATE_WINDOW_MS, createCoalescedRevalidate } from './coalesce';\nexport type { CoalescedRevalidate, CoalescedRevalidateOptions } from './coalesce';\nexport { getPreviewToken, previewMiddleware } from '@usethrottle/catalog/next';\n","import { t } from '@usethrottle/catalog';\nimport { staticProductParams } from '@usethrottle/catalog/server';\nimport type { SiteDesign } from '@usethrottle/ui';\nimport type { ReactElement } from 'react';\n// The page components are client code. The build leaves these two imports as the package's own entries\n// (`@usethrottle/storefront-react`, `.../account`; see `tsup.config.ts`), so `./next` carries none of a\n// \"use client\" file's code and the entries' directive keeps the components on the client side.\nimport { ProductPage, SearchResults, ShopAll } from '../index';\nimport { AccountPage } from '../account';\nimport { createStorefrontServerClient } from '../server/client';\nimport { loadProduct, loadSearch, loadSettings, loadShopAll } from '../server/loaders';\nimport type { ProductData, RedirectData, ShopAllData } from '../server/types';\nimport { productMetadata, searchMetadata, shopAllMetadata, type StorefrontMetadata } from '../seo/metadata';\nimport { routeHref } from '../url/routes';\nimport type { SearchParamsInput, ShopSource } from '../url/shop-query';\n\n/** Options shared by every `create*Page` helper. */\nexport type StorefrontRouteOptions = {\n /** The catalog's publishable key. */\n catalogKey: string;\n /** The store's origin (`https://shop.example`), for canonical URLs. */\n baseUrl: string;\n /**\n * The preview token of the request (`getPreviewToken`): draft settings and pages, read uncached. It reads\n * the request's cookies, which makes every route built with this option render dynamically. Pass it\n * only where that is wanted (a preview deployment or a preview-only route group), never on the\n * statically cached production routes.\n */\n previewToken?: () => Promise<string | undefined>;\n /** The site design, for the title template and the share image (a Builder store passes its `loadSite`). */\n site?: () => Promise<SiteDesign | null>;\n /**\n * How the product, collection or category the page is about is read (`LoaderInput.primaryCache`).\n * `'no-store'` reads it live on every request, so a deleted product is a 404 at once, never a cached 200;\n * the route then renders on demand (no ISR write). Default `'default'`: the long cache, cleared by the\n * revalidate webhook, which a store that has set it up can keep.\n */\n primaryCache?: 'default' | 'no-store';\n};\n\ntype RouteProps = {\n params: Promise<Record<string, string>>;\n searchParams: Promise<SearchParamsInput>;\n};\n\n/**\n * What a `create*Page` helper returns: a route's `Page` and `generateMetadata` (and `generateStaticParams` for products), ready to re-export from `page.tsx`.\n */\nexport type StorefrontRoute = {\n Page: (p: RouteProps) => Promise<ReactElement>;\n generateMetadata: (p: RouteProps) => Promise<StorefrontMetadata>;\n generateStaticParams?: () => Promise<Array<Record<string, string>>>;\n};\n\nconst clientOf = async (o: StorefrontRouteOptions) => {\n const previewToken = await o.previewToken?.();\n return createStorefrontServerClient({ catalogKey: o.catalogKey, ...(previewToken ? { previewToken } : {}) });\n};\n\nconst siteOf = async (o: StorefrontRouteOptions): Promise<SiteDesign | null> => (await o.site?.()) ?? null;\n\nconst origin = (baseUrl: string) => baseUrl.replace(/\\/+$/u, '');\n\nconst first = (value: string | string[] | undefined): string => (Array.isArray(value) ? value[0] : value) ?? '';\n\n/** `notFound()` for a missing answer, `permanentRedirect()` (308) for a renamed handle; otherwise the data. */\nasync function resolveAnswer<T extends object>(\n answer: T | RedirectData | null,\n where: { client: ReturnType<typeof createStorefrontServerClient>; kind: 'product' | 'collection' | 'category' | 'tag' },\n): Promise<T> {\n const { notFound, permanentRedirect } = await import('next/navigation');\n if (answer === null) return notFound();\n if ('redirectTo' in answer) {\n const settings = await loadSettings({ client: where.client });\n return permanentRedirect(routeHref(settings, where.kind, answer.redirectTo));\n }\n return answer;\n}\n\n/** The shop, a collection, a category or a tag listing. The handle is the `handle` param (`tag` for a tag). */\nexport function createShopAllPage(\n o: StorefrontRouteOptions & { source?: 'all' | 'collection' | 'category' | 'tag' },\n): StorefrontRoute {\n const kind = o.source ?? 'all';\n const sourceOf = (params: Record<string, string>): ShopSource =>\n kind === 'all' ? { kind: 'all' } : { kind, handle: params[kind === 'tag' ? 'tag' : 'handle'] ?? '' };\n const load = async ({ params, searchParams }: RouteProps) => {\n const client = await clientOf(o);\n const answer = await loadShopAll({ client, source: sourceOf(await params), searchParams: await searchParams, ...(o.primaryCache ? { primaryCache: o.primaryCache } : {}) });\n return { client, answer };\n };\n return {\n async Page(p) {\n const { client, answer } = await load(p);\n const data: ShopAllData = await resolveAnswer(answer, { client, kind: kind === 'all' ? 'collection' : kind });\n return <ShopAll source={data.source} initialData={data} baseUrl={origin(o.baseUrl)} />;\n },\n async generateMetadata(p) {\n const { client, answer } = await load(p);\n // A page that is missing answers 404 and a renamed one 308, here as in `Page`: Next sets the status.\n const data: ShopAllData = await resolveAnswer(answer, { client, kind: kind === 'all' ? 'collection' : kind });\n return shopAllMetadata(data, { baseUrl: o.baseUrl, site: await siteOf(o) });\n },\n };\n}\n\n/**\n * A product page, `handle` param. By default no product is prerendered at build: each is rendered on its first\n * visit and then cached until the catalog changes, because every deploy writes all of its prerendered pages\n * (ISR writes on Vercel). `staticParams: n` prerenders the `n` most recently updated products at build, capped at 50:\n * each prerendered product is an ISR write (its HTML and its data) on every deploy, so 50 is about 100 writes per deploy\n * and a larger number is never accepted. The rest render on their first visit and are cached until the catalog changes.\n */\nexport function createProductPage(o: StorefrontRouteOptions & { staticParams?: number }): StorefrontRoute {\n // The route never reads `searchParams` on the server: reading it makes the page dynamic, and a dynamic page\n // cannot also be prerendered by `generateStaticParams`. The server renders the default variant; the browser\n // takes `?variant=` from the URL (`useSearchParams`, through the provider's router).\n const load = async ({ params }: RouteProps) => {\n const client = await clientOf(o);\n const answer = await loadProduct({\n client,\n handle: (await params).handle ?? '',\n searchParams: {},\n ...(o.primaryCache ? { primaryCache: o.primaryCache } : {}),\n ...(o.site ? { builder: (await siteOf(o)) !== null } : {}),\n });\n return { client, answer };\n };\n return {\n async Page(p) {\n const { client, answer } = await load(p);\n const data: ProductData = await resolveAnswer(answer, { client, kind: 'product' });\n return <ProductPage initialData={data} baseUrl={origin(o.baseUrl)} />;\n },\n async generateMetadata(p) {\n const { client, answer } = await load(p);\n const data: ProductData = await resolveAnswer(answer, { client, kind: 'product' });\n return productMetadata(data, { baseUrl: o.baseUrl, site: await siteOf(o) });\n },\n async generateStaticParams() {\n const limit = o.staticParams ?? 0;\n if (limit <= 0) return [];\n try {\n return await staticProductParams(await clientOf({ catalogKey: o.catalogKey, baseUrl: o.baseUrl }), { limit: Math.min(limit, 50) });\n } catch (error) {\n // A catalog that cannot be read at build time must not fail the build: the products render on their first visit instead.\n console.warn('[storefront-react] generateStaticParams: the catalog could not be read; no product is prerendered.', error);\n return [];\n }\n },\n };\n}\n\n/**\n * The search results page, query in `?q=`. It reads `searchParams`, so Next renders it per request, and its\n * list is read with `cache: 'no-store'`: nothing about a search is cached or written as a static page.\n */\nexport function createSearchPage(o: StorefrontRouteOptions): StorefrontRoute {\n const queryOf = async (p: RouteProps) => first((await p.searchParams).q).trim();\n return {\n async Page(p) {\n const q = await queryOf(p);\n if (q === '') return <SearchResults q=\"\" />;\n const data = await loadSearch({ client: await clientOf(o), q, searchParams: await p.searchParams });\n return <SearchResults q={q} initialData={data} />;\n },\n async generateMetadata(p) {\n const q = await queryOf(p);\n const client = await clientOf(o);\n if (q === '') {\n const settings = await loadSettings({ client });\n return {\n title: t(settings, 'search.title'),\n alternates: { canonical: `${origin(o.baseUrl)}${settings.routes.search.split('?')[0]}` },\n robots: { index: false, follow: true },\n };\n }\n const data = await loadSearch({ client, q, searchParams: await p.searchParams });\n return searchMetadata(data, { baseUrl: o.baseUrl, site: await siteOf(o) });\n },\n };\n}\n\n/** The account page: the dashboard, or the sign-in or sign-up form. Never indexed. */\nexport function createAccountPage(\n o: StorefrontRouteOptions & { view?: 'dashboard' | 'sign-in' | 'sign-up' },\n): StorefrontRoute {\n return {\n async Page() {\n return <AccountPage view={o.view ?? 'dashboard'} />;\n },\n async generateMetadata() {\n const settings = await loadSettings({ client: await clientOf(o) });\n return {\n title: t(settings, 'nav.account'),\n alternates: { canonical: origin(o.baseUrl) },\n robots: { index: false, follow: false },\n };\n },\n };\n}\n","import type { CatalogClient } from '@usethrottle/catalog';\nimport { createServerCatalogClient, type DEFAULT_CACHE_POLICY } from '@usethrottle/catalog/server';\n\ntype CachePolicy = NonNullable<Parameters<typeof createServerCatalogClient>[0]['cachePolicy']>;\n\n/**\n * How long each kind of catalog read is cached on the server: long, with coarse\n * invalidation. Everything but search is `'until-changed'`: kept (the SDK caps\n * it at an hour as a safety TTL) and cleared sooner by the catalog's\n * `throttle-catalog` cache tags and the generation watcher\n * (`createRevalidateHandler`, `syncCatalogGeneration`). Next regenerates a page\n * on its lowest revalidate, so a short window on any one read (the SDK's own\n * default is 60 s for lists, filters, related and reviews) would regenerate\n * every shop, collection and product page, per filter, sort and page, that often.\n *\n * Search is `'no-store'` (the SDK's `search` kind is the suggest endpoint). A\n * search page's own list request, `products.list?q=`, is a `listings` read, so\n * `loadSearch` (and any listing carrying `q`) sends it with\n * `fetchInit: { cache: 'no-store' }`. Its URLs are unbounded, so the search\n * route must render dynamically (read `searchParams`, or\n * `export const dynamic = 'force-dynamic'`). A customer-token, cart or preview\n * request is never cached whatever this says.\n */\nexport const STOREFRONT_CACHE_POLICY: typeof DEFAULT_CACHE_POLICY = {\n settings: 'until-changed',\n navigation: 'until-changed',\n pages: 'until-changed',\n product: 'until-changed',\n listings: 'until-changed',\n facets: 'until-changed',\n related: 'until-changed',\n reviews: 'until-changed',\n search: 'no-store',\n};\n\n/**\n * The catalog client for server components, on `STOREFRONT_CACHE_POLICY`.\n * `cachePolicy` overrides single kinds (`{ listings: '120m' }`). Keep an\n * override at an hour or more: a shorter one makes every page that reads that\n * kind regenerate that often (ISR writes on Vercel). `previewToken` reads draft\n * settings and pages, uncached.\n */\nexport function createStorefrontServerClient(o: {\n catalogKey: string;\n previewToken?: string;\n baseUrl?: string;\n cachePolicy?: CachePolicy;\n}): CatalogClient {\n return createServerCatalogClient({\n publishableKey: o.catalogKey,\n cachePolicy: { ...STOREFRONT_CACHE_POLICY, ...o.cachePolicy },\n ...(o.baseUrl ? { baseUrl: o.baseUrl } : {}),\n ...(o.previewToken ? { previewToken: o.previewToken } : {}),\n });\n}\n","import { isCatalogError, t, type CatalogClient, type CallOptions } from '@usethrottle/catalog';\nimport { normalizeSettings, type NormalizedSettings } from '../settings/normalize';\nimport { cardFields, shopListQuery } from '../url/shop-list-query';\nimport { parseShopQuery, variantFromSearch, type ShopQuery, type ShopSource } from '../url/shop-query';\nimport { routeHref } from '../url/routes';\nimport { REVIEWS_PAGE_SIZE } from './reviews-page';\nimport type {\n Crumb,\n LoadProductInput,\n LoadSearchInput,\n LoadSettingsInput,\n LoadShopAllInput,\n LoaderInput,\n ProductData,\n RedirectData,\n ShopAllData,\n} from './types';\n\nconst callOf = ({ locale, currency }: Pick<LoaderInput, 'locale' | 'currency'>): CallOptions => ({\n ...(locale ? { locale } : {}),\n ...(currency ? { currency } : {}),\n});\n\n/** The call of the page's own subject: live when the loader was asked for `primaryCache: 'no-store'`. */\nconst primaryCall = (i: Pick<LoaderInput, 'locale' | 'currency' | 'primaryCache'>): CallOptions => ({\n ...callOf(i),\n ...(i.primaryCache === 'no-store' ? { fetchInit: { cache: 'no-store' } } : {}),\n});\n\nconst generatedAt = (): string => new Date().toISOString();\n\n/** The answer, or null when the catalog says the thing does not exist. Any other failure is thrown. */\nasync function orNull<T>(request: Promise<T>): Promise<T | null> {\n try {\n return await request;\n } catch (error) {\n if (isCatalogError(error) && error.code === 'NOT_FOUND') return null;\n throw error;\n }\n}\n\n/** The store's settings, normalised, whether its lists carry ratings, and the keys of its range-type facets. */\nasync function loadConfig({ client, locale }: LoadSettingsInput) {\n const config = await client.config(locale ? { locale } : undefined);\n const definitions: unknown = config.filters;\n return {\n settings: normalizeSettings(config.settings),\n // `/config` says whether reviews are on and shown on lists; absent (an older catalog) means they are.\n reviewsOnLists: config.reviews?.enabled !== false && config.reviews?.onLists !== false,\n reviewsEnabled: config.reviews?.enabled !== false,\n // Undefined (every `a..b` value is a range) when the catalog sends no facet definitions.\n rangeKeys: Array.isArray(definitions)\n ? definitions.filter((f) => f?.display === 'range').map((f) => String(f.key))\n : undefined,\n };\n}\n\n/** The store's settings, normalised: a partial or missing answer takes the defaults. */\nexport async function loadSettings(i: LoadSettingsInput): Promise<NormalizedSettings> {\n return (await loadConfig(i)).settings;\n}\n\ntype Entity = {\n title: string;\n seoTitle?: string;\n description?: string;\n breadcrumbs: Crumb[];\n /** A collection's kind: only a manual one can be sorted by `manual`. */\n kind?: 'manual' | 'rule';\n};\n\nconst text = (value: string | null | undefined): string | undefined => (value && value.trim() ? value : undefined);\n\nfunction baseCrumbs(settings: NormalizedSettings): Crumb[] {\n const store = settings.brand.storeName.trim();\n return store ? [{ name: store, href: '/' }] : [];\n}\n\n/** What the page's path names: its heading, SEO text and breadcrumbs. `null`: the catalog has no such thing; `{ redirectTo }`: it was renamed. */\nasync function loadEntity(\n client: CatalogClient,\n source: ShopSource,\n settings: NormalizedSettings,\n call: CallOptions,\n primary: CallOptions,\n): Promise<Entity | RedirectData | null> {\n const shop: Crumb = { name: t(settings, 'shop.title'), href: settings.routes.shop };\n const home = baseCrumbs(settings);\n switch (source.kind) {\n case 'all':\n return {\n title: shop.name,\n description: text(t(settings, 'shop.description')),\n breadcrumbs: [...home, shop],\n };\n case 'search': {\n const title = t(settings, 'search.results', { q: source.q });\n return { title, breadcrumbs: [...home, { name: title, href: routeHref(settings, 'search', source.q) }] };\n }\n case 'tag':\n return {\n title: source.handle,\n breadcrumbs: [...home, shop, { name: source.handle, href: routeHref(settings, 'tag', source.handle) }],\n };\n case 'collection': {\n const answer = await orNull(client.collections.get(source.handle, primary));\n if (!answer) return null;\n if ('redirectTo' in answer) return { redirectTo: answer.redirectTo };\n const { collection } = answer;\n const description = text(collection.seo.description) ?? text(collection.description);\n return {\n title: collection.title,\n ...(text(collection.seo.title) ? { seoTitle: text(collection.seo.title) } : {}),\n ...(description ? { description } : {}),\n kind: collection.kind,\n breadcrumbs: [\n ...home,\n shop,\n { name: collection.title, href: routeHref(settings, 'collection', collection.handle) },\n ],\n };\n }\n case 'category': {\n const answer = await orNull(client.categories.get(source.handle, primary));\n if (!answer) return null;\n const { category } = answer;\n const trail = answer.breadcrumbs.map((c) => ({ name: c.name, href: routeHref(settings, 'category', c.handle) }));\n if (answer.breadcrumbs.at(-1)?.handle !== category.handle)\n trail.push({ name: category.name, href: routeHref(settings, 'category', category.handle) });\n return {\n title: category.name,\n ...(text(category.seoTitle) ? { seoTitle: text(category.seoTitle) } : {}),\n ...(text(category.description) ? { description: text(category.description) } : {}),\n breadcrumbs: [...home, shop, ...trail],\n };\n }\n }\n}\n\nasync function loadListing(i: LoadShopAllInput): Promise<ShopAllData | RedirectData | null> {\n const { client, source } = i;\n const call = callOf(i);\n const { settings, reviewsOnLists, rangeKeys } = await loadConfig(i);\n const parsed = parseShopQuery(i.searchParams, settings, rangeKeys);\n const query: ShopQuery = source.kind === 'search' ? { ...parsed, q: source.q } : parsed;\n\n // Only a manual collection can be sorted by `manual`, so that URL needs the collection's kind first.\n const entityRequest = loadEntity(client, source, settings, call, primaryCall(i));\n const first = source.kind === 'collection' && query.sort === 'manual' ? await entityRequest : undefined;\n if (first && 'redirectTo' in first) return first;\n const manualCollection = first !== undefined && first !== null && 'kind' in first && first.kind === 'manual';\n\n // A search's URLs are unbounded: its list (facets come in the same request) is never written to the cache.\n const listCall: CallOptions = query.q ? { ...call, fetchInit: { cache: 'no-store' } } : call;\n const [entity, list] = await Promise.all([\n entityRequest,\n orNull(client.products.list(shopListQuery(query, source, settings, { fields: cardFields(settings), manualCollection }), listCall)),\n ]);\n if (entity === null || list === null) return null;\n if ('redirectTo' in entity) return entity;\n // A tag the catalog does not know answers an empty list; a 404 keeps arbitrary tag URLs from becoming cached pages.\n const narrowed = Object.keys(query.filters).length > 0 || Object.keys(query.ranges).length > 0 || Boolean(query.q);\n if (source.kind === 'tag' && list.products.length === 0 && !narrowed) return null;\n return {\n source,\n query,\n list,\n facets: list.filters ?? [],\n title: entity.title,\n ...(entity.seoTitle ? { seoTitle: entity.seoTitle } : {}),\n ...(entity.description ? { description: entity.description } : {}),\n ...(entity.kind ? { collectionKind: entity.kind } : {}),\n breadcrumbs: entity.breadcrumbs,\n settings,\n reviewsOnLists,\n generatedAt: generatedAt(),\n };\n}\n\n/**\n * The first page of a shop, collection, category or tag listing for the URL's\n * query. `null`: the collection, category or list does not exist, or the tag has no products; `{ redirectTo }`:\n * a collection was renamed (the handle it has now). Other catalog failures are thrown.\n */\nexport const loadShopAll: (i: LoadShopAllInput) => Promise<ShopAllData | RedirectData | null> = loadListing;\n\n/** A search's results: the same data as a listing, `source.kind` `'search'`. */\nexport async function loadSearch({ q, ...rest }: LoadSearchInput): Promise<ShopAllData> {\n const data = await loadListing({ ...rest, source: { kind: 'search', q } });\n if (data === null || 'redirectTo' in data) throw new Error('A search listing answered with no data.');\n return data;\n}\n\n/**\n * A product page's data. `null`: no such product; `{ redirectTo }`: the handle\n * was renamed. Related products come with it (none when the section is off, or\n * when only that request fails).\n */\nexport async function loadProduct(i: LoadProductInput): Promise<ProductData | RedirectData | null> {\n const { client, handle } = i;\n const call = callOf(i);\n const { settings, reviewsOnLists, reviewsEnabled } = await loadConfig(i);\n const sections = settings.product.sections;\n const relatedOn = sections.some((s) => s.key === 'related' && s.enabled);\n const reviewsSection = sections.some((s) => s.key === 'reviews' && s.enabled);\n const shippingHandle = sections.find((s) => s.key === 'shipping' && s.enabled)?.pageHandle ?? null;\n const [answer, related, reviews, shippingPage] = await Promise.all([\n orNull(client.products.get(handle, primaryCall(i))),\n relatedOn\n ? client.products\n .related(handle, { ...call, limit: settings.product.relatedLimit })\n .then((r) => r.products)\n .catch((error: unknown) => {\n if (isCatalogError(error)) return [];\n throw error;\n })\n : Promise.resolve([]),\n // The first page of reviews, the reviews cache kind of the client's policy: a 404 is \"no reviews to show\".\n reviewsSection && reviewsEnabled\n ? client.reviews\n .list(handle, { sort: 'newest', limit: REVIEWS_PAGE_SIZE, ...call })\n .then((r) => ('redirectTo' in r ? undefined : r))\n .catch((error: unknown) => {\n if (!isCatalogError(error)) throw error;\n return error.code === 'NOT_FOUND' ? null : undefined;\n })\n : Promise.resolve(reviewsSection ? null : undefined),\n // The shipping page's body, for a store with no Builder; a missing page is null. Any other failure leaves it to the client.\n shippingHandle && i.builder\n ? Promise.resolve(null)\n : shippingHandle\n ? client.pages\n .get(shippingHandle, call)\n .then((p) => p.bodyHtml || null)\n .catch((error: unknown) => {\n if (!isCatalogError(error)) throw error;\n return error.code === 'PAGE_NOT_FOUND' || error.code === 'NOT_FOUND' ? null : undefined;\n })\n : Promise.resolve(undefined),\n ]);\n if (answer === null) return null;\n if ('redirectTo' in answer) return { redirectTo: answer.redirectTo };\n return {\n product: answer.product,\n variantSku: variantFromSearch(i.searchParams, answer.product),\n related,\n ...(reviews !== undefined ? { reviews } : {}),\n ...(shippingPage !== undefined ? { shippingPage } : {}),\n settings,\n reviewsOnLists,\n generatedAt: generatedAt(),\n };\n}\n","import { DEFAULT_STRINGS, type ResolvedStorefrontSettings } from '@usethrottle/catalog';\n\n/**\n * The settings document a catalog that never opened the design screens answers\n * with, as the resolved shape (`GET /v1/storefront/config`): the catalog\n * contract's schema defaults. The SDK ships the type and `DEFAULT_STRINGS` but\n * not these values, so they are written out here; `presets.test.ts` pins the\n * theme to `@usethrottle/ui`'s `clean` preset.\n */\nexport const DEFAULT_SETTINGS: ResolvedStorefrontSettings = {\n storefrontId: 'default',\n brand: { storeName: '', logo: { light: null, dark: null }, favicon: null },\n theme: {\n light: {\n colorPrimary: '#18181b',\n colorPrimaryForeground: '#fafafa',\n colorBackground: '#ffffff',\n colorSurface: '#f4f4f5',\n colorForeground: '#18181b',\n colorMuted: '#f4f4f5',\n colorMutedForeground: '#71717a',\n colorBorder: '#e4e4e7',\n colorBorderControl: '#d4d4d8',\n colorAccent: '#2563eb',\n colorSale: '#b91c1c',\n colorSuccess: '#15803d',\n colorWarning: '#b45309',\n colorDanger: '#b91c1c',\n },\n dark: {\n colorPrimary: '#fafafa',\n colorPrimaryForeground: '#18181b',\n colorBackground: '#09090b',\n colorSurface: '#18181b',\n colorForeground: '#fafafa',\n colorMuted: '#27272a',\n colorMutedForeground: '#a1a1aa',\n colorBorder: '#27272a',\n colorBorderControl: '#3f3f46',\n colorAccent: '#60a5fa',\n colorSale: '#f87171',\n colorSuccess: '#4ade80',\n colorWarning: '#fbbf24',\n colorDanger: '#f87171',\n },\n fonts: { heading: 'system-sans', body: 'system-sans', mono: 'system-mono' },\n radius: 8,\n spacingScale: 'comfortable',\n colorScheme: 'auto',\n },\n navigation: { header: [], footer: [] },\n home: {\n hero: { image: null, heading: '', subheading: '', ctaLabel: '', ctaTarget: null },\n shelves: [\n { kind: 'featured', limit: 8 },\n { kind: 'newest', limit: 8 },\n ],\n },\n announcement: { enabled: false, message: '', target: null, startsAt: null, endsAt: null },\n listing: {\n pageSize: 24,\n pagination: 'numbered',\n columns: { desktop: 4, mobile: 2 },\n defaultSort: 'featured',\n filterLayout: 'sidebar',\n sorts: [\n { key: 'relevance', enabled: true, label: 'Best match' },\n { key: 'featured', enabled: true, label: 'Featured' },\n { key: 'manual', enabled: true, label: 'Collection order' },\n { key: 'title_asc', enabled: true, label: 'Name: A–Z' },\n { key: 'title_desc', enabled: true, label: 'Name: Z–A' },\n { key: 'price_asc', enabled: true, label: 'Price: low to high' },\n { key: 'price_desc', enabled: true, label: 'Price: high to low' },\n { key: 'newest', enabled: true, label: 'Newest' },\n { key: 'updated', enabled: true, label: 'Recently updated' },\n { key: 'best_rated', enabled: true, label: 'Best rated' },\n ],\n },\n card: {\n style: 'standard',\n showRating: true,\n showSwatches: true,\n showBrand: true,\n showCompareAt: true,\n showBadges: true,\n secondImageOnHover: false,\n quickAdd: false,\n },\n badges: {\n sale: { enabled: true, label: 'Sale', colour: '#b91c1c' },\n new: { enabled: true, label: 'New', colour: '#2563eb', days: 30 },\n lowStock: { enabled: true, label: 'Low stock' },\n custom: [],\n },\n stock: {\n hideOutOfStock: false,\n showExactCount: false,\n words: {\n inStock: 'In stock',\n lowStock: 'Only {count} left',\n outOfStock: 'Out of stock',\n backorder: 'Available on backorder',\n preorder: 'Pre-order',\n },\n lowStockThreshold: null,\n },\n product: {\n layout: 'classic',\n sectionsStyle: 'auto',\n sections: [\n { key: 'description', enabled: true, title: 'Description', pageHandle: null },\n { key: 'specs', enabled: true, title: 'Specifications', pageHandle: null },\n { key: 'shipping', enabled: false, title: 'Shipping', pageHandle: null },\n { key: 'tags', enabled: false, title: 'Tags', pageHandle: null },\n { key: 'categories', enabled: false, title: 'Categories', pageHandle: null },\n { key: 'related', enabled: true, title: 'You may also like', pageHandle: null },\n { key: 'reviews', enabled: true, title: 'Reviews', pageHandle: null },\n ],\n relatedLimit: 8,\n relatedTitle: 'You may also like',\n },\n seo: { titleTemplate: '{page} – {store}', defaultDescription: '', shareImage: null },\n strings: { ...DEFAULT_STRINGS },\n routes: {\n product: '/p/{handle}',\n category: '/c/{handle}',\n collection: '/collections/{handle}',\n tag: '/tags/{tag}',\n page: '/pages/{handle}',\n search: '/search?q={q}',\n shop: '/shop',\n },\n preview: { storeUrl: null },\n};\n","/** Plain-object check shared by the merge and normalisation code (server-safe, no imports). */\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n\n/**\n * Keys that must never be copied from JSON a catalog or a Builder sent:\n * `JSON.parse('{\"__proto__\":{...}}')` makes an own `__proto__` property, and\n * assigning it onto another object replaces that object's prototype.\n */\nexport const isUnsafeKey = (key: string): boolean =>\n key === '__proto__' || key === 'constructor' || key === 'prototype';\n","import type { ResolvedStorefrontSettings } from '@usethrottle/catalog';\nimport { DEFAULT_SETTINGS } from './defaults';\nimport { isRecord, isUnsafeKey } from './guards';\n\n/** The settings a component reads: the catalog's resolved document with every field present. */\nexport type NormalizedSettings = ResolvedStorefrontSettings;\n\nconst SORT_KEYS = [\n 'relevance', 'featured', 'manual', 'title_asc', 'title_desc', 'price_asc', 'price_desc', 'newest', 'updated', 'best_rated',\n];\n\n/** Where an enum-valued setting lives and what it may hold. */\nconst ENUMS: ReadonlyArray<readonly [path: readonly string[], values: readonly string[]]> = [\n [['theme', 'colorScheme'], ['light', 'dark', 'auto']],\n [['theme', 'spacingScale'], ['compact', 'comfortable', 'roomy']],\n [['listing', 'pagination'], ['numbered', 'load_more', 'infinite']],\n [['listing', 'filterLayout'], ['sidebar', 'topbar', 'drawer']],\n [['listing', 'defaultSort'], SORT_KEYS],\n [['card', 'style'], ['standard', 'minimal', 'overlay', 'row']],\n [['product', 'layout'], ['classic', 'stacked', 'editorial']],\n [['product', 'sectionsStyle'], ['auto', 'tabs', 'accordion', 'stacked']],\n];\n\nconst SECTION_KEYS = ['description', 'specs', 'shipping', 'tags', 'categories', 'related', 'reviews'];\n\n\n/**\n * Fills `raw` from `defaults`, value by value: a missing or wrong-typed value\n * takes the default, an object recurses, an array is kept whole when it is an\n * array (the lists have no per-item defaults). A default of `null` accepts any\n * non-undefined value (a media ref, a menu target, a nullable number).\n */\nfunction fill(defaults: unknown, raw: unknown): unknown {\n if (isRecord(defaults)) {\n const given = isRecord(raw) ? raw : {};\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(defaults)) out[key] = fill(defaults[key], given[key]);\n // Unknown keys are kept as they came: a newer catalog may send more.\n for (const key of Object.keys(given)) if (!isUnsafeKey(key) && !(key in out)) out[key] = given[key];\n return out;\n }\n if (Array.isArray(defaults)) return Array.isArray(raw) ? raw : defaults;\n if (defaults === null) return raw === undefined ? null : raw;\n if (typeof defaults === 'number') return typeof raw === 'number' && Number.isFinite(raw) ? raw : defaults;\n return typeof raw === typeof defaults ? raw : defaults;\n}\n\n/** Menu items with a string label and an object target; a malformed item (and its subtree) is dropped, `children` must be an array. */\nfunction cleanMenu(items: unknown): unknown[] {\n if (!Array.isArray(items)) return [];\n return items.flatMap((item): unknown[] => {\n if (!isRecord(item) || typeof item.label !== 'string' || !isRecord(item.target)) return [];\n if (item.children === undefined) return [item];\n if (!Array.isArray(item.children)) return [];\n return [{ ...item, children: cleanMenu(item.children) }];\n });\n}\n\nconst warned = new Set<string>();\nfunction warnOnce(key: string, message: string): void {\n if (process.env.NODE_ENV === 'production' || warned.has(key)) return;\n warned.add(key);\n // eslint-disable-next-line no-console\n console.warn(`[@usethrottle/storefront-react] ${message}`);\n}\n\n/** Test seam: forgets which warnings were already logged. */\nexport function resetSettingsWarnings(): void {\n warned.clear();\n}\n\nfunction get(obj: Record<string, unknown>, path: readonly string[]): unknown {\n let at: unknown = obj;\n for (const key of path) at = isRecord(at) ? at[key] : undefined;\n return at;\n}\n\nfunction set(obj: Record<string, unknown>, path: readonly string[], value: unknown): void {\n let at: Record<string, unknown> = obj;\n for (const key of path.slice(0, -1)) at = at[key] as Record<string, unknown>;\n at[path[path.length - 1]!] = value;\n}\n\n/**\n * Settings from whatever the catalog answered (or nothing): deep-filled from\n * `DEFAULT_SETTINGS`, an unknown enum value replaced by its default with one\n * development warning. Never throws, so a partial or newer answer renders.\n */\nexport function normalizeSettings(raw: unknown): NormalizedSettings {\n const out = fill(DEFAULT_SETTINGS, raw) as Record<string, unknown>;\n\n // An empty string is \"not set\" for a catalog string, as the SDK's own `t` reads it.\n const strings = out.strings as Record<string, unknown>;\n const defaultStrings = DEFAULT_SETTINGS.strings as Record<string, string>;\n for (const key of Object.keys(defaultStrings)) if (strings[key] === '') strings[key] = defaultStrings[key];\n\n for (const [path, allowed] of ENUMS) {\n const value = get(out, path);\n if (typeof value === 'string' && allowed.includes(value)) continue;\n const dotted = path.join('.');\n warnOnce(`enum:${dotted}`, `settings.${dotted} has an unknown value (${JSON.stringify(value)}); using the default.`);\n set(out, path, get(DEFAULT_SETTINGS as unknown as Record<string, unknown>, path));\n }\n\n // Lists whose items carry an enum key: drop an item the components could not place.\n const listing = out.listing as Record<string, unknown>;\n listing.sorts = (listing.sorts as unknown[]).filter(\n (s) => isRecord(s) && typeof s.key === 'string' && SORT_KEYS.includes(s.key),\n );\n const product = out.product as Record<string, unknown>;\n product.sections = (product.sections as unknown[]).filter(\n (s) => isRecord(s) && typeof s.key === 'string' && SECTION_KEYS.includes(s.key),\n );\n\n // A list item that is not an object would crash the component that reads its fields.\n const nav = out.navigation as Record<string, unknown>;\n nav.header = cleanMenu(nav.header);\n nav.footer = cleanMenu(nav.footer);\n const badges = out.badges as Record<string, unknown>;\n badges.custom = (badges.custom as unknown[]).filter(isRecord);\n const home = out.home as Record<string, unknown>;\n home.shelves = (home.shelves as unknown[]).filter(isRecord);\n\n return out as unknown as NormalizedSettings;\n}\n","import type { ProductsQuery } from '@usethrottle/catalog';\nimport { formatRange } from '@usethrottle/catalog/url';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport type { ShopQuery, ShopSource } from './shop-query';\n\n/** What the catalog's list answer carries by default (`fields: 'lite'`), as the keys `fields` takes. */\nconst LITE_FIELDS = [\n 'availability',\n 'badges',\n 'brand',\n 'featured',\n 'handle',\n 'images',\n 'lowStock',\n 'optionSwatches',\n 'priceRange',\n 'productType',\n 'rating',\n 'seo',\n 'title',\n 'variantCount',\n] as const;\n\n/**\n * The `fields` a product list asks for. A custom tag badge needs the product's\n * tags, which the default (lite) answer leaves out. Undefined otherwise, so the\n * request is the default one.\n */\nexport function cardFields(settings: NormalizedSettings): readonly string[] | undefined {\n return settings.card.showBadges && settings.badges.custom.length > 0 ? [...LITE_FIELDS, 'tags'] : undefined;\n}\n\n/**\n * The `products.list` query for a listing. Pure, and the one place it is built:\n * the server loader and a client island both call it, so the island's request\n * matches the server's and starts on its answer (`initialData`).\n *\n * The page's path (`source`) names the collection, category or tag. A sort that\n * is not the store's default counts as asked for (the URL omits the default):\n * it is kept when it makes sense, `relevance` only with a search and `manual`\n * only on a manual collection (`manualCollection`). With no sort asked for, the\n * shop, a category or a tag takes `listing.defaultSort` (`featured` is the\n * catalog's own default); a collection keeps its own order and a search keeps\n * relevance. Pass `fields` from `cardFields(settings)`.\n */\nexport function shopListQuery(\n query: ShopQuery,\n source: ShopSource,\n settings: NormalizedSettings,\n o: { fields?: readonly string[]; manualCollection?: boolean } = {},\n): ProductsQuery {\n const { listing } = settings;\n const filters: Record<string, string[]> = {};\n for (const [key, values] of Object.entries(query.filters)) filters[key] = [...values];\n for (const [key, range] of Object.entries(query.ranges)) (filters[key] ??= []).push(formatRange(range));\n const out: ProductsQuery = {\n limit: listing.pageSize,\n facets: true,\n ...(o.fields ? { fields: o.fields } : {}),\n ...(query.page > 1 ? { page: query.page } : {}),\n ...(query.q ? { q: query.q } : {}),\n ...(Object.keys(filters).length > 0 ? { filters } : {}),\n ...(source.kind === 'collection' ? { collection: source.handle } : {}),\n ...(source.kind === 'category' ? { category: source.handle } : {}),\n ...(source.kind === 'tag' ? { tags: [source.handle] } : {}),\n };\n if (query.sort !== listing.defaultSort) {\n const usable =\n query.sort === 'relevance' ? Boolean(query.q) : query.sort === 'manual' ? o.manualCollection === true : true;\n if (usable) out.sort = query.sort;\n } else if (\n (source.kind === 'all' || source.kind === 'category' || source.kind === 'tag') &&\n !['featured', 'relevance', 'manual'].includes(listing.defaultSort)\n ) {\n out.sort = listing.defaultSort;\n }\n return out;\n}\n","import {\n formatRange,\n parseRange,\n parseShopQuery as parseCatalogQuery,\n serializeShopQuery,\n type ShopQueryInput,\n} from '@usethrottle/catalog/url';\nimport type { StorefrontProduct } from '@usethrottle/catalog';\nimport { isUnsafeKey } from '../settings/guards';\nimport type { NormalizedSettings } from '../settings/normalize';\n\n/** What `searchParams` is in a Next page: a plain record (a value may repeat). */\nexport type SearchParamsInput = Record<string, string | string[] | undefined>;\n\n/**\n * The shop selection as URL state. Filters and ranges are `filter.<key>` URL\n * parameters (the catalog SDK's wire form: a range is one `min..max` value).\n * `sort` is always the effective sort: the URL's, or the store's default.\n */\nexport type ShopQuery = {\n filters: Record<string, string[]>;\n ranges: Record<string, { min?: number; max?: number }>;\n sort: string;\n page: number;\n q?: string;\n};\n\n/** What a listing shows: the whole shop, one collection, category or tag (by path), or a search. */\nexport type ShopSource =\n | { kind: 'all' }\n | { kind: 'collection' | 'category' | 'tag'; handle: string }\n | { kind: 'search'; q: string };\n\nconst enabledSorts = (settings: NormalizedSettings): Set<string> =>\n new Set(settings.listing.sorts.filter((s) => s.enabled).map((s) => s.key as string));\n\n/** The sort the URL names when the store offers it, else null. */\nexport function explicitSort(params: URLSearchParams | SearchParamsInput, settings: NormalizedSettings): string | null {\n const { sort } = parseCatalogQuery(params as ShopQueryInput);\n return sort !== undefined && enabledSorts(settings).has(sort) ? sort : null;\n}\n\n/**\n * Reads the URL state. A sort the store has disabled (or does not know) falls\n * back to `listing.defaultSort`; a page below 1 or not a number is 1.\n * Parameters follow the catalog SDK's shop URL: `filter.<key>`, `sort`, `page`, `q`.\n *\n * `rangeKeys` names the range-type facets (`display: 'range'`). Only their\n * `a..b` values become `ranges`; on any other key the text stays a filter\n * value. Left out, every `a..b` value is read as a range.\n */\nexport function parseShopQuery(\n params: URLSearchParams | SearchParamsInput,\n settings: NormalizedSettings,\n rangeKeys?: Iterable<string>,\n): ShopQuery {\n const ranged = rangeKeys === undefined ? null : new Set(rangeKeys);\n const raw = parseCatalogQuery(params as ShopQueryInput);\n const filters: ShopQuery['filters'] = {};\n const ranges: ShopQuery['ranges'] = {};\n for (const key of Object.keys(raw.filters ?? {})) {\n if (isUnsafeKey(key)) continue;\n for (const value of raw.filters![key]!) {\n const range = ranged === null || ranged.has(key) ? parseRange(value) : null;\n if (range) {\n if (!Object.hasOwn(ranges, key)) ranges[key] = range;\n } else (filters[key] ??= []).push(value);\n }\n }\n for (const key of Object.keys(filters)) filters[key] = [...new Set(filters[key])].sort();\n const query: ShopQuery = {\n filters,\n ranges,\n sort: explicitSort(params, settings) ?? settings.listing.defaultSort,\n page: raw.page !== undefined && raw.page >= 1 ? raw.page : 1,\n };\n if (raw.q) query.q = raw.q;\n return query;\n}\n\nfunction toCatalogQuery(q: ShopQuery, settings: NormalizedSettings) {\n const filters: Record<string, string[]> = {};\n for (const key of Object.keys(q.filters)) filters[key] = [...q.filters[key]!];\n for (const key of Object.keys(q.ranges)) (filters[key] ??= []).push(formatRange(q.ranges[key]!));\n for (const key of Object.keys(filters)) filters[key] = [...new Set(filters[key])].sort();\n return {\n ...(q.q ? { q: q.q } : {}),\n ...(Object.keys(filters).length > 0 ? { filters } : {}),\n ...(q.sort !== settings.listing.defaultSort ? { sort: q.sort } : {}),\n ...(q.page > 1 ? { page: q.page } : {}),\n };\n}\n\n/** The canonical query string (no leading `?`): keys sorted, values sorted, defaults (the default sort, page 1) omitted. */\nexport function shopQueryToSearch(q: ShopQuery, settings: NormalizedSettings): string {\n return serializeShopQuery(toCatalogQuery(q, settings));\n}\n\n/** The page numbers to show: the first, the last and the current one's neighbours, `null` for a gap. */\nexport function pageWindow(current: number, count: number): Array<number | null> {\n const pages = [...new Set([1, current - 1, current, current + 1, count])]\n .filter((p) => p >= 1 && p <= count)\n .sort((a, b) => a - b);\n const out: Array<number | null> = [];\n for (const [i, p] of pages.entries()) {\n if (i > 0 && p - pages[i - 1]! > 1) out.push(null);\n out.push(p);\n }\n return out;\n}\n\n/** The variant a product URL names (`?variant=<sku>`), or null when it names none the product has. */\nexport function variantFromSearch(\n params: URLSearchParams | SearchParamsInput,\n product: Pick<StorefrontProduct, 'variants'>,\n): string | null {\n const value = params instanceof URLSearchParams ? params.get('variant') : params.variant;\n const sku = Array.isArray(value) ? value[0] : value;\n return sku !== undefined && product.variants.some((v) => v.sku === sku) ? sku : null;\n}\n\n/** Filter values a URL carries: each checked value, each range counts one. */\nconst filterValueCount = (q: ShopQuery): number =>\n Object.values(q.filters).reduce((n, values) => n + values.length, 0) + Object.keys(q.ranges).length;\n\n/**\n * R4: a shop URL is `noindex,follow` when it carries two or more filter\n * values, a sort other than the store's default, or a search term (`q` on a\n * listing; a search page is `noindex` on its own). Links are always followed.\n */\nexport function robotsForShopQuery(q: ShopQuery, settings: NormalizedSettings): { index: boolean; follow: true } {\n return { index: filterValueCount(q) <= 1 && q.sort === settings.listing.defaultSort && !q.q, follow: true };\n}\n\n/**\n * R4: the canonical URL keeps at most one filter value (the first by key, then\n * value) and `page` above 1, and drops the sort. `q` stays only on a search\n * page (`source.kind === 'search'`); on a listing it is dropped. Absolute:\n * `baseUrl` + `pathname`.\n */\nexport function canonicalForShopQuery(\n baseUrl: string,\n pathname: string,\n q: ShopQuery,\n settings: NormalizedSettings,\n source?: ShopSource,\n): string {\n const first = [\n ...Object.entries(q.filters).flatMap(([key, values]) => values.map((value) => ({ key, value }))),\n ...Object.entries(q.ranges).map(([key, range]) => ({ key, value: formatRange(range) })),\n ].sort((a, b) => (a.key === b.key ? a.value.localeCompare(b.value) : a.key.localeCompare(b.key)))[0];\n const kept: ShopQuery = {\n filters: {},\n ranges: {},\n sort: settings.listing.defaultSort,\n page: q.page,\n ...(q.q && source?.kind === 'search' ? { q: q.q } : {}),\n };\n if (first) {\n const range = parseRange(first.value);\n if (range) kept.ranges[first.key] = range;\n else kept.filters[first.key] = [first.value];\n }\n const search = shopQueryToSearch(kept, settings);\n return `${baseUrl.replace(/\\/+$/u, '')}${pathname}${search ? `?${search}` : ''}`;\n}\n","import type { NormalizedSettings } from '../settings/normalize';\nimport type { ResolvedSiteDesign } from '../site/resolve';\n\nconst fill = (pattern: string, name: string, value: string) =>\n pattern.split(`{${name}}`).join(encodeURIComponent(value));\n\n/**\n * A link by the store's route patterns (`settings.routes`). `'page'` uses the\n * site design's page route when it names one (a Builder site owns it), and\n * `'search'` fills `{q}`. Ported from Meridian `lib/menu.ts`\n * (`routeHref` / `searchHref`). Server-safe.\n */\nexport function routeHref(\n settings: NormalizedSettings,\n kind: 'product' | 'collection' | 'category' | 'tag' | 'page' | 'search',\n value: string,\n site?: ResolvedSiteDesign,\n): string {\n if (kind === 'search') return fill(settings.routes.search, 'q', value);\n const pattern = kind === 'page' && site?.routes.page ? site.routes.page : settings.routes[kind];\n return fill(pattern, kind === 'tag' ? 'tag' : 'handle', value);\n}\n","/** How many reviews a product page asks for at a time; the loader's first page is this long too. */\nexport const REVIEWS_PAGE_SIZE = 10;\n","import { PRESET_NAMES, PRESET_TOKENS } from '@usethrottle/ui/presets';\nimport type { PresetName, SiteDesign, SiteMenuItem, SlotRenderer, ThemeTokens } from '@usethrottle/ui';\nimport { isRecord, isUnsafeKey } from '../settings/guards';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { catalogSiteDesign } from './catalog-adapter';\n\n/** A site design with every field decided (R11): what the components read. */\nexport type ResolvedSiteDesign = {\n source: 'builder' | 'catalog-adapter';\n preset: PresetName;\n scheme: 'light' | 'dark' | 'auto';\n theme: ThemeTokens;\n brand: { storeName: string; logo: { light?: string; dark?: string } | null };\n menus: Record<string, SiteMenuItem[]>;\n announcement: { message: string; href?: string } | null;\n /** The site strings: the Builder's over the catalog adapter's. */\n strings: Record<string, string>;\n /** Only what the Builder provided. It outranks the `localization` prop; the adapter's strings are catalog text and do not. */\n builderStrings: Record<string, string>;\n seo: { titleTemplate: string; defaultDescription?: string; shareImage?: string };\n routes: { page: string };\n throttlePublishableKey: string | null;\n pageOutlet: ((handle: string) => SlotRenderer | null) | null;\n};\n\n/**\n * The inputs of `resolveSiteDesign`: the Builder's site (or `null`), the catalog's settings and the developer's props. The theme group resolves Builder, props, catalog, defaults; every other field Builder, then catalog.\n */\nexport type ResolveSiteDesignInput = {\n site: SiteDesign | null;\n settings: NormalizedSettings;\n preset?: PresetName;\n theme?: Partial<ThemeTokens>;\n scheme?: 'light' | 'dark' | 'auto';\n throttlePublishableKey?: string;\n};\n\n/** Deep merge for theme tokens: later layers win, `undefined` never does, `0` and `''` do. Unsafe keys are skipped. */\nfunction mergeTokens(base: unknown, ...layers: unknown[]): unknown {\n let out = base;\n for (const layer of layers) {\n if (layer === undefined) continue;\n if (isRecord(out) && isRecord(layer)) {\n const next: Record<string, unknown> = { ...out };\n for (const key of Object.keys(layer)) {\n if (isUnsafeKey(key)) continue;\n next[key] = mergeTokens(out[key], layer[key]);\n }\n out = next;\n } else {\n out = layer;\n }\n }\n return out;\n}\n\n/** The entries of a Builder-provided map that carry a value of the right kind, so `undefined` falls through. */\nfunction definedEntries<T>(map: Record<string, unknown> | undefined, ok: (v: unknown) => v is T): Record<string, T> {\n const out: Record<string, T> = {};\n if (!isRecord(map)) return out;\n for (const [key, value] of Object.entries(map)) if (ok(value) && !isUnsafeKey(key)) out[key] = value;\n return out;\n}\nconst isMenu = (v: unknown): v is SiteMenuItem[] => Array.isArray(v);\nconst isString = (v: unknown): v is string => typeof v === 'string';\n\nconst isPreset = (v: unknown): v is PresetName => PRESET_NAMES.includes(v as PresetName);\n\nconst warned = new Set<string>();\nconst SHADOW_MESSAGE = {\n preset: 'The `preset` prop is ignored: the site design (the Throttle Builder) sets the preset and takes precedence.',\n theme:\n \"The `theme` prop is merged under the site design's theme values (the Throttle Builder): any token the site sets wins over it.\",\n scheme: 'The `scheme` prop is ignored: the site design (the Throttle Builder) sets the colour scheme and takes precedence.',\n} as const;\n\nfunction warnShadowed(prop: keyof typeof SHADOW_MESSAGE): void {\n if (process.env.NODE_ENV === 'production' || warned.has(prop)) return;\n warned.add(prop);\n // eslint-disable-next-line no-console\n console.warn(`[@usethrottle/storefront-react] ${SHADOW_MESSAGE[prop]} Remove the prop, or change it in the Builder.`);\n}\n\n/** @internal Test seam: forgets which shadowed props were already warned about. */\nexport function resetSiteDesignWarnings(): void {\n warned.clear();\n}\n\n/**\n * Decides every site-design field (R11, owner ruling 2026-11-15). Pure and\n * server-safe.\n *\n * - **Theme group** (`preset`, tokens, colour scheme): Builder, then the\n * developer's `preset` / `theme` / `scheme` props, then the catalog adapter,\n * then the defaults (`clean`, `auto`). An explicit `preset` or `theme` prop\n * skips the adapter's theme. A Builder with `customized: false` contributes\n * only its preset and colour scheme. Tokens are `PRESET_TOKENS[preset]`, then\n * the `theme` prop, then the winning source's values, deep-merged.\n * - **Every other field**: Builder, then the catalog adapter, field by field; a\n * field a source leaves `undefined` falls through and `null` is a value.\n * - **Account key**: the `throttlePublishableKey` prop, then the Builder's\n * `connections`, then `null`.\n *\n * A `preset` / `theme` / `scheme` prop that a Builder theme shadows logs one\n * development warning naming the prop.\n */\nexport function resolveSiteDesign(input: ResolveSiteDesignInput): ResolvedSiteDesign {\n const { site, settings } = input;\n const adapter = catalogSiteDesign(settings);\n const siteTheme = site?.theme;\n const adapterTheme = adapter.theme;\n\n const propsGiven = input.preset !== undefined || input.theme !== undefined;\n const adapterThemeActive = siteTheme === undefined && !propsGiven;\n\n const sitePreset = isPreset(siteTheme?.preset) ? siteTheme.preset : undefined;\n const preset: PresetName = sitePreset ?? (isPreset(input.preset) ? input.preset : 'clean');\n const siteValues = siteTheme && siteTheme.customized !== false ? siteTheme.values : undefined;\n const winningValues = siteTheme ? siteValues : adapterThemeActive ? adapterTheme?.values : undefined;\n const theme = mergeTokens(PRESET_TOKENS[preset], input.theme, winningValues) as ThemeTokens;\n\n const scheme =\n siteTheme?.colorScheme ??\n input.scheme ??\n (adapterThemeActive ? adapterTheme?.colorScheme : undefined) ??\n 'auto';\n\n if (siteTheme) {\n if (input.preset !== undefined && siteTheme.preset !== undefined) warnShadowed('preset');\n if (input.theme !== undefined && siteValues !== undefined) warnShadowed('theme');\n if (input.scheme !== undefined && siteTheme.colorScheme !== undefined) warnShadowed('scheme');\n }\n\n const brand = {\n storeName: site?.brand?.storeName ?? adapter.brand?.storeName ?? '',\n logo: site?.brand?.logo !== undefined ? site.brand.logo : (adapter.brand?.logo ?? null),\n };\n const builderStrings = definedEntries(site?.strings, isString);\n const siteSeo = site?.seo;\n const adapterSeo = adapter.seo;\n const defaultDescription = siteSeo?.defaultDescription ?? adapterSeo?.defaultDescription;\n const shareImage = siteSeo?.shareImage ?? adapterSeo?.shareImage;\n\n return {\n source: site ? site.source : 'catalog-adapter',\n preset,\n scheme,\n theme,\n brand,\n menus: { ...adapter.menus, ...definedEntries(site?.menus, isMenu) },\n announcement: site?.announcement !== undefined ? site.announcement : (adapter.announcement ?? null),\n strings: { ...adapter.strings, ...builderStrings },\n builderStrings,\n seo: {\n titleTemplate: siteSeo?.titleTemplate ?? adapterSeo?.titleTemplate ?? settings.seo.titleTemplate,\n ...(defaultDescription !== undefined ? { defaultDescription } : {}),\n ...(shareImage !== undefined ? { shareImage } : {}),\n },\n routes: { page: site?.routes?.page ?? adapter.routes?.page ?? settings.routes.page },\n throttlePublishableKey:\n input.throttlePublishableKey ?? site?.connections?.throttlePublishableKey ?? null,\n pageOutlet: site?.pageOutlet ?? null,\n };\n}\n","import {\n resolveMenuTarget,\n type ResolvedMenuTarget,\n type StorefrontMenuItem,\n type StorefrontSettings,\n} from '@usethrottle/catalog';\nimport type { SiteMenuItem } from '@usethrottle/ui';\n\ntype Routes = StorefrontSettings['routes'];\n\n/**\n * The URL a menu, announcement or hero target points to, from the store's route patterns. Null when the\n * target has nothing to point at (no handle, or a link that is not http(s) or a site path).\n * (Ported from Meridian `lib/menu.ts`.)\n */\nexport function menuHref(settings: { routes: Routes }, target: ResolvedMenuTarget): string | null {\n return resolveMenuTarget(settings, target);\n}\n\n/**\n * The menu as site-design items: each item's target resolved by `menuHref`. An item that points nowhere\n * (a deleted target) is left out, its children with it, so the nav never renders a dead entry. A renamed\n * target already carries its current handle in the settings answer, so it resolves to the new URL.\n */\nexport function menuItems(\n settings: { routes: Routes },\n items: readonly StorefrontMenuItem[],\n): SiteMenuItem[] {\n if (!Array.isArray(items)) return [];\n return items.flatMap((item): SiteMenuItem[] => {\n // The answer is data from the network: skip an item that is not shaped like a menu item.\n if (typeof item !== 'object' || item === null || typeof item.label !== 'string') return [];\n if (typeof item.target !== 'object' || item.target === null) return [];\n if (item.children !== undefined && !Array.isArray(item.children)) return [];\n const href = menuHref(settings, item.target);\n if (typeof href !== 'string') return [];\n const children = menuItems(settings, item.children ?? []);\n const out: SiteMenuItem = { label: item.label, href, kind: item.target.kind };\n if (typeof item.target.handle === 'string') out.handle = item.target.handle;\n if (children.length > 0) out.children = children;\n return [out];\n });\n}\n","import type { SiteDesign } from '@usethrottle/ui';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport { menuHref, menuItems } from './menu';\n\n/** A media ref is an object with a string `url`; anything else the catalog sent counts as none. */\nconst mediaUrl = (media: unknown): string | undefined =>\n typeof media === 'object' && media !== null && typeof (media as { url?: unknown }).url === 'string'\n ? (media as { url: string }).url\n : undefined;\n\n/** The site-design strings the catalog settings may supply (Builder §12). */\nconst SITE_STRING_KEYS = ['footer.copyright', 'nav.menu', 'nav.account'] as const;\n\n/**\n * The catalog settings read as a site design: what a store without a Builder\n * shows for its theme, brand, menus, announcement, SEO defaults and site\n * strings (each only when the settings carry a non-empty value).\n *\n * @deprecated A bridge for Phase 1 catalogs. It is removed when the Throttle\n * Builder takes over site design (Builder M4); provide a site design instead.\n */\nexport function catalogSiteDesign(settings: NormalizedSettings): SiteDesign {\n const { brand, theme, announcement, seo } = settings;\n\n const logo = {\n ...(mediaUrl(brand.logo?.light) ? { light: mediaUrl(brand.logo?.light)! } : {}),\n ...(mediaUrl(brand.logo?.dark) ? { dark: mediaUrl(brand.logo?.dark)! } : {}),\n };\n\n const strings: Record<string, string> = {};\n for (const key of SITE_STRING_KEYS) {\n const value = settings.strings[key];\n if (value) strings[key] = value;\n }\n\n const href =\n announcement.enabled && typeof announcement.target === 'object' && announcement.target !== null\n ? menuHref(settings, announcement.target)\n : null;\n\n return {\n source: 'catalog-adapter',\n brand: {\n storeName: brand.storeName,\n logo: Object.keys(logo).length > 0 ? logo : null,\n favicon: mediaUrl(brand.favicon) ?? null,\n },\n theme: {\n customized: true,\n values: {\n light: theme.light,\n dark: theme.dark,\n fonts: theme.fonts,\n radius: theme.radius,\n spacingScale: theme.spacingScale,\n },\n colorScheme: theme.colorScheme,\n },\n menus: {\n header: menuItems(settings, settings.navigation.header),\n footer: menuItems(settings, settings.navigation.footer),\n },\n announcement:\n announcement.enabled && announcement.message\n ? { message: announcement.message, ...(href ? { href } : {}) }\n : null,\n strings,\n seo: {\n titleTemplate: seo.titleTemplate,\n ...(seo.defaultDescription ? { defaultDescription: seo.defaultDescription } : {}),\n ...(mediaUrl(seo.shareImage) ? { shareImage: mediaUrl(seo.shareImage)! } : {}),\n },\n routes: { page: settings.routes.page },\n };\n}\n","import type { SiteDesign } from '@usethrottle/ui';\nimport { resolveSiteDesign } from '../site/resolve';\nimport type { NormalizedSettings } from '../settings/normalize';\nimport type { ProductData, ShopAllData } from '../server/types';\nimport { routeHref } from '../url/routes';\nimport { canonicalForShopQuery, robotsForShopQuery, type ShopSource } from '../url/shop-query';\n\n/** Page metadata, assignable to Next's `Metadata`. */\nexport type StorefrontMetadata = {\n title: string;\n description?: string;\n alternates: { canonical: string };\n robots?: { index: boolean; follow: boolean };\n openGraph?: { title: string; description?: string; images?: string[] };\n};\n\ntype MetadataOptions = { baseUrl: string; site?: SiteDesign | null };\n\nconst origin = (baseUrl: string): string => baseUrl.replace(/\\/+$/u, '');\nconst absolute = (baseUrl: string, path: string): string => `${origin(baseUrl)}${path}`;\n\n/** A tab title from `seo.titleTemplate` (`{page}`, `{store}`). With no store name, or no page name, the other side stands alone. */\nfunction pageTitle(template: string, store: string, page: string): string {\n const name = page.trim();\n const shop = store.trim();\n if (name === '') return shop;\n if (shop === '') return name;\n return template.split('{page}').join(name).split('{store}').join(shop);\n}\n\nfunction resolved(data: { settings: NormalizedSettings }, o: MetadataOptions) {\n return resolveSiteDesign({ site: o.site ?? null, settings: data.settings });\n}\n\nconst nonEmpty = (value: string | null | undefined): string | undefined => (value && value.trim() ? value : undefined);\n\nfunction openGraph(title: string, description: string | undefined, images: Array<string | undefined>): StorefrontMetadata['openGraph'] {\n const urls = images.filter((u): u is string => Boolean(u));\n return { title, ...(description ? { description } : {}), ...(urls.length > 0 ? { images: urls } : {}) };\n}\n\n/** The path a listing lives at (without its query string). */\nfunction listingPath(settings: NormalizedSettings, source: ShopSource): string {\n switch (source.kind) {\n case 'all':\n return settings.routes.shop;\n case 'search':\n return settings.routes.search.split('?')[0]!;\n default:\n return routeHref(settings, source.kind, source.handle);\n }\n}\n\n/** A shop, collection, category or tag page: the entity's SEO title, the canonical and robots of R4. */\nexport function shopAllMetadata(data: ShopAllData, o: MetadataOptions): StorefrontMetadata {\n const site = resolved(data, o);\n const title = pageTitle(site.seo.titleTemplate, site.brand.storeName, data.seoTitle ?? data.title);\n const description = nonEmpty(data.description) ?? nonEmpty(site.seo.defaultDescription);\n return {\n title,\n ...(description ? { description } : {}),\n alternates: {\n canonical: canonicalForShopQuery(o.baseUrl, listingPath(data.settings, data.source), data.query, data.settings, data.source),\n },\n robots: robotsForShopQuery(data.query, data.settings),\n openGraph: openGraph(title, description, [site.seo.shareImage]),\n };\n}\n\n/** Search results: indexable search pages only add near-duplicates, so they are `noindex,follow`. */\nexport function searchMetadata(data: ShopAllData, o: MetadataOptions): StorefrontMetadata {\n return { ...shopAllMetadata(data, o), robots: { index: false, follow: true } };\n}\n\n/** A product page: the merchant's SEO title and description, the first image, a canonical without `?variant=`. */\nexport function productMetadata(data: ProductData, o: MetadataOptions): StorefrontMetadata {\n const { product } = data;\n const site = resolved(data, o);\n const name = nonEmpty(product.seoTitle) ?? nonEmpty(product.seo?.title) ?? product.title ?? product.handle;\n const title = pageTitle(site.seo.titleTemplate, site.brand.storeName, name);\n const description =\n nonEmpty(product.seoDescription) ??\n nonEmpty(product.seo?.description) ??\n nonEmpty(product.shortDescription) ??\n nonEmpty(product.description) ??\n nonEmpty(site.seo.defaultDescription);\n return {\n title,\n ...(description ? { description } : {}),\n alternates: { canonical: absolute(o.baseUrl, routeHref(data.settings, 'product', product.handle)) },\n openGraph: openGraph(title, description, [product.images[0]?.url ?? site.seo.shareImage]),\n };\n}\n","/**\n * The server-side half of the generation backstop. `useGenerationWatch` sees the catalog's generation\n * change in an open tab, but `router.refresh()` re-renders from Next's data cache, which only the\n * `storefront.changed` webhook clears. With the webhook off or lost, nothing would. This is the check\n * the tab asks for first: read the generation uncached, and when it differs from the last one this\n * instance knew, clear the catalog's cache tags so the refresh that follows renders fresh.\n *\n * Pure: the clock, the reads and the tag clearing are injected (`createGenerationSyncHandler` wires\n * the SDK's `syncCatalogGeneration` and Next's `revalidateTag`). One upstream read per `minIntervalMs`\n * per instance; a request inside the window, or while a read is running, shares or skips it, so the\n * route cannot be used to hammer the catalog. Nothing is cleared unless the generation really changed,\n * so it cannot be used to empty the cache either.\n */\nexport type GenerationSyncDeps = {\n now(): number;\n /** The generation of the config Next's cache holds (cached read); undefined if it cannot be read. */\n cachedGeneration(): Promise<number | undefined>;\n /** The SDK's `syncCatalogGeneration` shape: reads uncached, calls `onChange` when `previous` differs. */\n sync(\n previous: number | undefined,\n onChange: (generation: number) => Promise<void>,\n ): Promise<{ generation: number; changed: boolean }>;\n /**\n * Clears the catalog's cache tag. It runs inside the request that asked for it (Next applies a\n * `revalidateTag` when that request ends). Answer `{ deferredMs }` when the clearing was not made (a\n * minute has not passed since the last one): the change is then not recorded as applied, so the next\n * call finds it again, and the answer tells the tab when to ask.\n */\n revalidate(): void | { deferredMs: number } | Promise<void | { deferredMs: number }>;\n /** Default 5000. */\n minIntervalMs?: number;\n};\n\n/**\n * What the generation sync answers: whether the catalog changed, whether the read was throttled, and when to ask again.\n */\nexport type GenerationSyncResult = {\n changed: boolean;\n throttled?: true;\n /** A change was found but its clearing is deferred: ask again after this many ms. */\n retryAfterMs?: number;\n};\n\n/**\n * Builds the generation check behind `createGenerationSyncHandler`, for a store that writes its own route. The returned function reads the live generation at most once per `minIntervalMs` and clears the cache only when the generation really moved.\n */\nexport function createGenerationSync(deps: GenerationSyncDeps): () => Promise<GenerationSyncResult> {\n const minIntervalMs = deps.minIntervalMs ?? 5000;\n let lastKnown: number | undefined;\n let lastReadAt: number | undefined;\n let running: Promise<GenerationSyncResult> | undefined;\n\n const run = async (): Promise<GenerationSyncResult> => {\n // A cold instance has seen nothing: take the generation the data cache holds, so a change missed\n // before this instance started still counts as one.\n const previous = lastKnown ?? (await deps.cachedGeneration());\n let deferredMs: number | undefined;\n const { generation, changed } = await deps.sync(previous, async () => {\n const outcome = await deps.revalidate();\n if (outcome) deferredMs = outcome.deferredMs;\n });\n // A deferred change is not applied: `lastKnown` stays, so the next window finds it again.\n if (deferredMs !== undefined) return { changed: true, retryAfterMs: deferredMs };\n lastKnown = generation;\n return { changed };\n };\n\n return () => {\n if (running) return running;\n const now = deps.now();\n if (lastReadAt !== undefined && now - lastReadAt < minIntervalMs)\n return Promise.resolve({ changed: false, throttled: true });\n lastReadAt = now;\n running = run().finally(() => {\n running = undefined;\n });\n return running;\n };\n}\n","import type { CatalogClient } from '@usethrottle/catalog';\nimport { syncCatalogGeneration } from '@usethrottle/catalog/server';\nimport { CATALOG_TAG, createCoalescedRevalidate, sharedCatalogRevalidate, type CoalescedRevalidate, type TagRevalidator } from './coalesce';\nimport { createGenerationSync } from './generation-sync';\n\n/** Options of `createGenerationSyncHandler`. */\nexport type GenerationSyncHandlerOptions = {\n /** A server catalog client (`createStorefrontServerClient`): its cached `config()` is the generation the data cache holds. */\n client: CatalogClient;\n /** The tags to clear when the generation moved. Default `['throttle-catalog']`, the one coarse tag. */\n tags?: string[];\n /** The least time between two upstream reads, default 5000. */\n minIntervalMs?: number;\n /** Replaces Next's `revalidateTag` (tests). The clearing is still limited to once a minute. */\n revalidateTag?: TagRevalidator;\n};\n\nconst NO_STORE = { 'cache-control': 'no-store' };\n\n/**\n * The generation backstop's server half, for `app/api/throttle/sync/route.ts`:\n * `export const { POST } = createGenerationSyncHandler({ client })`.\n *\n * The open tab's watcher POSTs here when it sees the generation move, before it refreshes. It reads the live\n * generation (at most once per `minIntervalMs`), and only when that differs from the one the data cache holds\n * it clears the catalog tag, and at most once a minute. Answers `200 { changed, throttled? }`, or\n * `502 { changed: false }` when the catalog cannot be read. No auth: it cannot empty the cache unless the\n * catalog's generation really moved.\n *\n * The once-a-minute limit is per server instance. A change found inside the window is not recorded as\n * applied: the answer carries `retryAfterMs`, the tab asks again then, and that call clears the tag inside\n * its own request (Next applies `revalidateTag` when the request ends, so nothing is cleared by a timer).\n */\nexport function createGenerationSyncHandler(o: GenerationSyncHandlerOptions): { POST(): Promise<Response> } {\n const coalesced: CoalescedRevalidate =\n o.revalidateTag || o.tags\n ? createCoalescedRevalidate({ tags: o.tags ?? [CATALOG_TAG], ...(o.revalidateTag ? { revalidateTag: o.revalidateTag } : {}) })\n : sharedCatalogRevalidate();\n const sync = createGenerationSync({\n now: () => Date.now(),\n cachedGeneration: async () => {\n try {\n return (await o.client.config()).generation;\n } catch {\n return undefined;\n }\n },\n sync: (previous, onChange) => syncCatalogGeneration({ client: o.client, previous, onChange }),\n revalidate: async () => {\n const outcome = await coalesced.tryClear();\n return outcome === 'cleared' ? undefined : outcome;\n },\n ...(o.minIntervalMs !== undefined ? { minIntervalMs: o.minIntervalMs } : {}),\n });\n\n return {\n async POST() {\n try {\n await coalesced.flushIfDue();\n return Response.json(await sync(), { headers: NO_STORE });\n } catch (error) {\n console.error('[storefront-react] generation sync failed', error instanceof Error ? error.name : 'error');\n return Response.json({ changed: false }, { status: 502, headers: NO_STORE });\n }\n },\n };\n}\n","/**\n * The one cache tag the storefront clears. Every catalog read of `createStorefrontServerClient` carries it,\n * so clearing it is enough; clearing per scope, per product or per route would regenerate pages (ISR\n * writes on Vercel) once for each.\n */\nexport const CATALOG_TAG = 'throttle-catalog';\n\n/** Clearing happens at most once in this window per server instance. */\nexport const REVALIDATE_WINDOW_MS = 60_000;\n\n/** Clears one tag. Next 16's `revalidateTag(tag, { expire: 0 })`; Next 15 ignores the second argument. */\nexport type TagRevalidator = (tag: string) => void | Promise<void>;\n\ntype NextCache = { revalidateTag(tag: string, profile?: { expire?: number }): void };\n\nasync function nextRevalidator(): Promise<TagRevalidator> {\n const { revalidateTag } = (await import('next/cache')) as unknown as NextCache;\n return (tag) => revalidateTag(tag, { expire: 0 });\n}\n\n/** The cache-clearing gate: it turns any number of change notices into at most one clearing per window. */\nexport type CoalescedRevalidate = {\n /**\n * A change was seen (a verified webhook). Clears now when the window is over, else leaves it pending\n * for the next call. Resolves `'cleared'` or `{ deferredMs }`, the time until a call can clear it.\n */\n request(): Promise<'cleared' | { deferredMs: number }>;\n /** Clears now when a change is pending and the window is over, else does nothing. */\n flushIfDue(): Promise<void>;\n /**\n * Like `request` for a caller that keeps the change itself (the generation sync keeps the generation it\n * has not applied): nothing is left pending here when the window is not over.\n */\n tryClear(): Promise<'cleared' | { deferredMs: number }>;\n};\n\n/**\n * Options of `createCoalescedRevalidate`. The defaults are the cost-safe ones; there is rarely a reason to change them.\n */\nexport type CoalescedRevalidateOptions = {\n /** Default `[CATALOG_TAG]`. */\n tags?: readonly string[];\n /** Default Next's `revalidateTag`. */\n revalidateTag?: TagRevalidator;\n /** Never below `REVALIDATE_WINDOW_MS`. */\n windowMs?: number;\n};\n\n/**\n * At most one clearing per window, per server instance (another instance has its own window, so a\n * multi-instance deployment can clear once a minute on each).\n *\n * There is no timer. Next applies `revalidateTag` when the request that called it ends, so a clearing\n * made from a timer, after the response, would do nothing. A change inside the window is instead left\n * pending (the webhook) or unrecorded (the generation sync), and the first later call that finds the\n * window over clears it inside its own request.\n */\nexport function createCoalescedRevalidate(options: CoalescedRevalidateOptions = {}): CoalescedRevalidate {\n const tags = options.tags ?? [CATALOG_TAG];\n const windowMs = Math.max(options.windowMs ?? REVALIDATE_WINDOW_MS, REVALIDATE_WINDOW_MS);\n let lastClearedAt: number | undefined;\n let pending = false;\n\n const waitMs = (): number => (lastClearedAt === undefined ? 0 : Math.max(0, windowMs - (Date.now() - lastClearedAt)));\n\n const clear = async (): Promise<void> => {\n const revalidate = options.revalidateTag ?? (await nextRevalidator());\n for (const tag of tags) await revalidate(tag);\n lastClearedAt = Date.now();\n pending = false;\n };\n\n const tryClear = async (): Promise<'cleared' | { deferredMs: number }> => {\n const wait = waitMs();\n if (wait > 0) return { deferredMs: wait };\n await clear();\n return 'cleared';\n };\n\n return {\n async request() {\n pending = true;\n return tryClear();\n },\n async flushIfDue() {\n if (pending && waitMs() === 0) await clear();\n },\n tryClear,\n };\n}\n\nlet shared: CoalescedRevalidate | undefined;\n\n/** The instance's one coalescer, so the webhook route and the sync route share a single window. */\nexport function sharedCatalogRevalidate(): CoalescedRevalidate {\n shared ??= createCoalescedRevalidate();\n return shared;\n}\n","import { createRevalidateHandler as createCatalogRevalidateHandler } from '@usethrottle/catalog/next';\nimport { CATALOG_TAG, sharedCatalogRevalidate, type CoalescedRevalidate } from './coalesce';\n\n/** Options of `createRevalidateHandler`. */\nexport type RevalidateHandlerOptions = {\n /** The webhook's signing secret; pass `process.env.THROTTLE_WEBHOOK_SECRET` straight in. A list accepts any of them. */\n secret: string | undefined | readonly (string | undefined)[];\n /** The store's generation floor key, as `createRevalidateHandler` of `@usethrottle/catalog/next` takes it. */\n floorKey?: string;\n /** Default: the instance's shared coalescer on `throttle-catalog`. */\n revalidate?: CoalescedRevalidate;\n};\n\nconst json = (status: number, body: unknown): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json', 'cache-control': 'no-store' },\n });\n\n/**\n * The route handler for the catalog's signed `storefront.changed` webhook, the primary way a change reaches\n * the storefront. The catalog SDK's handler checks the signature first and refuses (401) an unsigned or wrong\n * one before anything is read or cleared. What this adds is the cost rule: whatever scopes the notice names, one\n * coarse tag (`throttle-catalog`) is cleared, and at most once a minute however many notices arrive, so a\n * burst of merchant edits is one regeneration, not one per product. A `test` event clears nothing.\n *\n * The limit is per server instance. A notice inside the window is left pending, and the next webhook or\n * sync call after the window clears it inside its own request (Next applies `revalidateTag` when the\n * request ends, so there is no timer); the answer then says `deferred`.\n */\nexport function createRevalidateHandler(options: RevalidateHandlerOptions): (req: Request) => Promise<Response> {\n const delegate = createCatalogRevalidateHandler({\n secret: options.secret,\n ...(options.floorKey !== undefined ? { floorKey: options.floorKey } : {}),\n // The SDK clears each scope's tags itself; here that is switched off and the one clearing is made below.\n revalidateTag: () => undefined,\n });\n return async (req) => {\n const coalesced = options.revalidate ?? sharedCatalogRevalidate();\n const answer = await delegate(req);\n // Only a verified notice gets this far: the SDK handler answered 401, 400, 413 or 500 otherwise.\n if (answer.status !== 200) return answer;\n // This reads the SDK handler's own answer shape (`{ revalidated: string[] }`); its tests (and the\n // build-output contract) would catch a change there.\n const body = (await answer.json()) as { revalidated?: string[] };\n if (!body.revalidated || body.revalidated.length === 0) {\n await coalesced.flushIfDue();\n return json(200, { revalidated: [] });\n }\n const outcome = await coalesced.request();\n return outcome === 'cleared'\n ? json(200, { revalidated: [CATALOG_TAG] })\n : json(200, { revalidated: [], deferred: true, retryAfterMs: outcome.deferredMs });\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAA,kBAAkB;AAClB,IAAAC,iBAAoC;AAMpC,eAAoD;AACpD,qBAA4B;;;ACP5B,oBAAq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AwB,SAAwE;AAC9G,QAAM,eAAW,YAAAC,yBAA+B;AAAA,IAC9C,QAAQ,QAAQ;AAAA,IAChB,GAAI,QAAQ,aAAa,SAAY,EAAE,UAAU,QAAQ,SAAS,IAAI,CAAC;AAAA;AAAA,IAEvE,eAAe,MAAM;AAAA,EACvB,CAAC;AACD,SAAO,OAAO,QAAQ;AACpB,UAAM,YAAY,QAAQ,cAAc,wBAAwB;AAChE,UAAM,SAAS,MAAM,SAAS,GAAG;AAEjC,QAAI,OAAO,WAAW,IAAK,QAAO;AAGlC,UAAM,OAAQ,MAAM,OAAO,KAAK;AAChC,QAAI,CAAC,KAAK,eAAe,KAAK,YAAY,WAAW,GAAG;AACtD,YAAM,UAAU,WAAW;AAC3B,aAAO,KAAK,KAAK,EAAE,aAAa,CAAC,EAAE,CAAC;AAAA,IACtC;AACA,UAAM,UAAU,MAAM,UAAU,QAAQ;AACxC,WAAO,YAAY,YACf,KAAK,KAAK,EAAE,aAAa,CAAC,WAAW,EAAE,CAAC,IACxC,KAAK,KAAK,EAAE,aAAa,CAAC,GAAG,UAAU,MAAM,cAAc,QAAQ,WAAW,CAAC;AAAA,EACrF;AACF;;;AlB3CA,IAAAC,eAAmD;","names":["import_catalog","import_server","import_catalog","import_url","parseCatalogQuery","first","fill","first","import_catalog","warned","origin","import_server","createCatalogRevalidateHandler","import_next"]}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { SiteDesign } from '@usethrottle/ui';
|
|
2
|
+
import { ReactElement } from 'react';
|
|
3
|
+
import { S as SearchParamsInput, h as StorefrontMetadata } from '../metadata-QhKw-tvz.cjs';
|
|
4
|
+
import { CatalogClient } from '@usethrottle/catalog';
|
|
5
|
+
export { getPreviewToken, previewMiddleware } from '@usethrottle/catalog/next';
|
|
6
|
+
|
|
7
|
+
/** Options shared by every `create*Page` helper. */
|
|
8
|
+
type StorefrontRouteOptions = {
|
|
9
|
+
/** The catalog's publishable key. */
|
|
10
|
+
catalogKey: string;
|
|
11
|
+
/** The store's origin (`https://shop.example`), for canonical URLs. */
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
/**
|
|
14
|
+
* The preview token of the request (`getPreviewToken`): draft settings and pages, read uncached. It reads
|
|
15
|
+
* the request's cookies, which makes every route built with this option render dynamically. Pass it
|
|
16
|
+
* only where that is wanted (a preview deployment or a preview-only route group), never on the
|
|
17
|
+
* statically cached production routes.
|
|
18
|
+
*/
|
|
19
|
+
previewToken?: () => Promise<string | undefined>;
|
|
20
|
+
/** The site design, for the title template and the share image (a Builder store passes its `loadSite`). */
|
|
21
|
+
site?: () => Promise<SiteDesign | null>;
|
|
22
|
+
/**
|
|
23
|
+
* How the product, collection or category the page is about is read (`LoaderInput.primaryCache`).
|
|
24
|
+
* `'no-store'` reads it live on every request, so a deleted product is a 404 at once, never a cached 200;
|
|
25
|
+
* the route then renders on demand (no ISR write). Default `'default'`: the long cache, cleared by the
|
|
26
|
+
* revalidate webhook, which a store that has set it up can keep.
|
|
27
|
+
*/
|
|
28
|
+
primaryCache?: 'default' | 'no-store';
|
|
29
|
+
};
|
|
30
|
+
type RouteProps = {
|
|
31
|
+
params: Promise<Record<string, string>>;
|
|
32
|
+
searchParams: Promise<SearchParamsInput>;
|
|
33
|
+
};
|
|
34
|
+
/**
|
|
35
|
+
* What a `create*Page` helper returns: a route's `Page` and `generateMetadata` (and `generateStaticParams` for products), ready to re-export from `page.tsx`.
|
|
36
|
+
*/
|
|
37
|
+
type StorefrontRoute = {
|
|
38
|
+
Page: (p: RouteProps) => Promise<ReactElement>;
|
|
39
|
+
generateMetadata: (p: RouteProps) => Promise<StorefrontMetadata>;
|
|
40
|
+
generateStaticParams?: () => Promise<Array<Record<string, string>>>;
|
|
41
|
+
};
|
|
42
|
+
/** The shop, a collection, a category or a tag listing. The handle is the `handle` param (`tag` for a tag). */
|
|
43
|
+
declare function createShopAllPage(o: StorefrontRouteOptions & {
|
|
44
|
+
source?: 'all' | 'collection' | 'category' | 'tag';
|
|
45
|
+
}): StorefrontRoute;
|
|
46
|
+
/**
|
|
47
|
+
* A product page, `handle` param. By default no product is prerendered at build: each is rendered on its first
|
|
48
|
+
* visit and then cached until the catalog changes, because every deploy writes all of its prerendered pages
|
|
49
|
+
* (ISR writes on Vercel). `staticParams: n` prerenders the `n` most recently updated products at build, capped at 50:
|
|
50
|
+
* each prerendered product is an ISR write (its HTML and its data) on every deploy, so 50 is about 100 writes per deploy
|
|
51
|
+
* and a larger number is never accepted. The rest render on their first visit and are cached until the catalog changes.
|
|
52
|
+
*/
|
|
53
|
+
declare function createProductPage(o: StorefrontRouteOptions & {
|
|
54
|
+
staticParams?: number;
|
|
55
|
+
}): StorefrontRoute;
|
|
56
|
+
/**
|
|
57
|
+
* The search results page, query in `?q=`. It reads `searchParams`, so Next renders it per request, and its
|
|
58
|
+
* list is read with `cache: 'no-store'`: nothing about a search is cached or written as a static page.
|
|
59
|
+
*/
|
|
60
|
+
declare function createSearchPage(o: StorefrontRouteOptions): StorefrontRoute;
|
|
61
|
+
/** The account page: the dashboard, or the sign-in or sign-up form. Never indexed. */
|
|
62
|
+
declare function createAccountPage(o: StorefrontRouteOptions & {
|
|
63
|
+
view?: 'dashboard' | 'sign-in' | 'sign-up';
|
|
64
|
+
}): StorefrontRoute;
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The server-side half of the generation backstop. `useGenerationWatch` sees the catalog's generation
|
|
68
|
+
* change in an open tab, but `router.refresh()` re-renders from Next's data cache, which only the
|
|
69
|
+
* `storefront.changed` webhook clears. With the webhook off or lost, nothing would. This is the check
|
|
70
|
+
* the tab asks for first: read the generation uncached, and when it differs from the last one this
|
|
71
|
+
* instance knew, clear the catalog's cache tags so the refresh that follows renders fresh.
|
|
72
|
+
*
|
|
73
|
+
* Pure: the clock, the reads and the tag clearing are injected (`createGenerationSyncHandler` wires
|
|
74
|
+
* the SDK's `syncCatalogGeneration` and Next's `revalidateTag`). One upstream read per `minIntervalMs`
|
|
75
|
+
* per instance; a request inside the window, or while a read is running, shares or skips it, so the
|
|
76
|
+
* route cannot be used to hammer the catalog. Nothing is cleared unless the generation really changed,
|
|
77
|
+
* so it cannot be used to empty the cache either.
|
|
78
|
+
*/
|
|
79
|
+
type GenerationSyncDeps = {
|
|
80
|
+
now(): number;
|
|
81
|
+
/** The generation of the config Next's cache holds (cached read); undefined if it cannot be read. */
|
|
82
|
+
cachedGeneration(): Promise<number | undefined>;
|
|
83
|
+
/** The SDK's `syncCatalogGeneration` shape: reads uncached, calls `onChange` when `previous` differs. */
|
|
84
|
+
sync(previous: number | undefined, onChange: (generation: number) => Promise<void>): Promise<{
|
|
85
|
+
generation: number;
|
|
86
|
+
changed: boolean;
|
|
87
|
+
}>;
|
|
88
|
+
/**
|
|
89
|
+
* Clears the catalog's cache tag. It runs inside the request that asked for it (Next applies a
|
|
90
|
+
* `revalidateTag` when that request ends). Answer `{ deferredMs }` when the clearing was not made (a
|
|
91
|
+
* minute has not passed since the last one): the change is then not recorded as applied, so the next
|
|
92
|
+
* call finds it again, and the answer tells the tab when to ask.
|
|
93
|
+
*/
|
|
94
|
+
revalidate(): void | {
|
|
95
|
+
deferredMs: number;
|
|
96
|
+
} | Promise<void | {
|
|
97
|
+
deferredMs: number;
|
|
98
|
+
}>;
|
|
99
|
+
/** Default 5000. */
|
|
100
|
+
minIntervalMs?: number;
|
|
101
|
+
};
|
|
102
|
+
/**
|
|
103
|
+
* What the generation sync answers: whether the catalog changed, whether the read was throttled, and when to ask again.
|
|
104
|
+
*/
|
|
105
|
+
type GenerationSyncResult = {
|
|
106
|
+
changed: boolean;
|
|
107
|
+
throttled?: true;
|
|
108
|
+
/** A change was found but its clearing is deferred: ask again after this many ms. */
|
|
109
|
+
retryAfterMs?: number;
|
|
110
|
+
};
|
|
111
|
+
/**
|
|
112
|
+
* Builds the generation check behind `createGenerationSyncHandler`, for a store that writes its own route. The returned function reads the live generation at most once per `minIntervalMs` and clears the cache only when the generation really moved.
|
|
113
|
+
*/
|
|
114
|
+
declare function createGenerationSync(deps: GenerationSyncDeps): () => Promise<GenerationSyncResult>;
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* The one cache tag the storefront clears. Every catalog read of `createStorefrontServerClient` carries it,
|
|
118
|
+
* so clearing it is enough; clearing per scope, per product or per route would regenerate pages (ISR
|
|
119
|
+
* writes on Vercel) once for each.
|
|
120
|
+
*/
|
|
121
|
+
declare const CATALOG_TAG = "throttle-catalog";
|
|
122
|
+
/** Clearing happens at most once in this window per server instance. */
|
|
123
|
+
declare const REVALIDATE_WINDOW_MS = 60000;
|
|
124
|
+
/** Clears one tag. Next 16's `revalidateTag(tag, { expire: 0 })`; Next 15 ignores the second argument. */
|
|
125
|
+
type TagRevalidator = (tag: string) => void | Promise<void>;
|
|
126
|
+
/** The cache-clearing gate: it turns any number of change notices into at most one clearing per window. */
|
|
127
|
+
type CoalescedRevalidate = {
|
|
128
|
+
/**
|
|
129
|
+
* A change was seen (a verified webhook). Clears now when the window is over, else leaves it pending
|
|
130
|
+
* for the next call. Resolves `'cleared'` or `{ deferredMs }`, the time until a call can clear it.
|
|
131
|
+
*/
|
|
132
|
+
request(): Promise<'cleared' | {
|
|
133
|
+
deferredMs: number;
|
|
134
|
+
}>;
|
|
135
|
+
/** Clears now when a change is pending and the window is over, else does nothing. */
|
|
136
|
+
flushIfDue(): Promise<void>;
|
|
137
|
+
/**
|
|
138
|
+
* Like `request` for a caller that keeps the change itself (the generation sync keeps the generation it
|
|
139
|
+
* has not applied): nothing is left pending here when the window is not over.
|
|
140
|
+
*/
|
|
141
|
+
tryClear(): Promise<'cleared' | {
|
|
142
|
+
deferredMs: number;
|
|
143
|
+
}>;
|
|
144
|
+
};
|
|
145
|
+
/**
|
|
146
|
+
* Options of `createCoalescedRevalidate`. The defaults are the cost-safe ones; there is rarely a reason to change them.
|
|
147
|
+
*/
|
|
148
|
+
type CoalescedRevalidateOptions = {
|
|
149
|
+
/** Default `[CATALOG_TAG]`. */
|
|
150
|
+
tags?: readonly string[];
|
|
151
|
+
/** Default Next's `revalidateTag`. */
|
|
152
|
+
revalidateTag?: TagRevalidator;
|
|
153
|
+
/** Never below `REVALIDATE_WINDOW_MS`. */
|
|
154
|
+
windowMs?: number;
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* At most one clearing per window, per server instance (another instance has its own window, so a
|
|
158
|
+
* multi-instance deployment can clear once a minute on each).
|
|
159
|
+
*
|
|
160
|
+
* There is no timer. Next applies `revalidateTag` when the request that called it ends, so a clearing
|
|
161
|
+
* made from a timer, after the response, would do nothing. A change inside the window is instead left
|
|
162
|
+
* pending (the webhook) or unrecorded (the generation sync), and the first later call that finds the
|
|
163
|
+
* window over clears it inside its own request.
|
|
164
|
+
*/
|
|
165
|
+
declare function createCoalescedRevalidate(options?: CoalescedRevalidateOptions): CoalescedRevalidate;
|
|
166
|
+
|
|
167
|
+
/** Options of `createGenerationSyncHandler`. */
|
|
168
|
+
type GenerationSyncHandlerOptions = {
|
|
169
|
+
/** A server catalog client (`createStorefrontServerClient`): its cached `config()` is the generation the data cache holds. */
|
|
170
|
+
client: CatalogClient;
|
|
171
|
+
/** The tags to clear when the generation moved. Default `['throttle-catalog']`, the one coarse tag. */
|
|
172
|
+
tags?: string[];
|
|
173
|
+
/** The least time between two upstream reads, default 5000. */
|
|
174
|
+
minIntervalMs?: number;
|
|
175
|
+
/** Replaces Next's `revalidateTag` (tests). The clearing is still limited to once a minute. */
|
|
176
|
+
revalidateTag?: TagRevalidator;
|
|
177
|
+
};
|
|
178
|
+
/**
|
|
179
|
+
* The generation backstop's server half, for `app/api/throttle/sync/route.ts`:
|
|
180
|
+
* `export const { POST } = createGenerationSyncHandler({ client })`.
|
|
181
|
+
*
|
|
182
|
+
* The open tab's watcher POSTs here when it sees the generation move, before it refreshes. It reads the live
|
|
183
|
+
* generation (at most once per `minIntervalMs`), and only when that differs from the one the data cache holds
|
|
184
|
+
* it clears the catalog tag, and at most once a minute. Answers `200 { changed, throttled? }`, or
|
|
185
|
+
* `502 { changed: false }` when the catalog cannot be read. No auth: it cannot empty the cache unless the
|
|
186
|
+
* catalog's generation really moved.
|
|
187
|
+
*
|
|
188
|
+
* The once-a-minute limit is per server instance. A change found inside the window is not recorded as
|
|
189
|
+
* applied: the answer carries `retryAfterMs`, the tab asks again then, and that call clears the tag inside
|
|
190
|
+
* its own request (Next applies `revalidateTag` when the request ends, so nothing is cleared by a timer).
|
|
191
|
+
*/
|
|
192
|
+
declare function createGenerationSyncHandler(o: GenerationSyncHandlerOptions): {
|
|
193
|
+
POST(): Promise<Response>;
|
|
194
|
+
};
|
|
195
|
+
|
|
196
|
+
/** Options of `createRevalidateHandler`. */
|
|
197
|
+
type RevalidateHandlerOptions = {
|
|
198
|
+
/** The webhook's signing secret; pass `process.env.THROTTLE_WEBHOOK_SECRET` straight in. A list accepts any of them. */
|
|
199
|
+
secret: string | undefined | readonly (string | undefined)[];
|
|
200
|
+
/** The store's generation floor key, as `createRevalidateHandler` of `@usethrottle/catalog/next` takes it. */
|
|
201
|
+
floorKey?: string;
|
|
202
|
+
/** Default: the instance's shared coalescer on `throttle-catalog`. */
|
|
203
|
+
revalidate?: CoalescedRevalidate;
|
|
204
|
+
};
|
|
205
|
+
/**
|
|
206
|
+
* The route handler for the catalog's signed `storefront.changed` webhook, the primary way a change reaches
|
|
207
|
+
* the storefront. The catalog SDK's handler checks the signature first and refuses (401) an unsigned or wrong
|
|
208
|
+
* one before anything is read or cleared. What this adds is the cost rule: whatever scopes the notice names, one
|
|
209
|
+
* coarse tag (`throttle-catalog`) is cleared, and at most once a minute however many notices arrive, so a
|
|
210
|
+
* burst of merchant edits is one regeneration, not one per product. A `test` event clears nothing.
|
|
211
|
+
*
|
|
212
|
+
* The limit is per server instance. A notice inside the window is left pending, and the next webhook or
|
|
213
|
+
* sync call after the window clears it inside its own request (Next applies `revalidateTag` when the
|
|
214
|
+
* request ends, so there is no timer); the answer then says `deferred`.
|
|
215
|
+
*/
|
|
216
|
+
declare function createRevalidateHandler(options: RevalidateHandlerOptions): (req: Request) => Promise<Response>;
|
|
217
|
+
|
|
218
|
+
export { CATALOG_TAG, type CoalescedRevalidate, type CoalescedRevalidateOptions, type GenerationSyncDeps, type GenerationSyncHandlerOptions, type GenerationSyncResult, REVALIDATE_WINDOW_MS, type RevalidateHandlerOptions, type StorefrontRoute, type StorefrontRouteOptions, createAccountPage, createCoalescedRevalidate, createGenerationSync, createGenerationSyncHandler, createProductPage, createRevalidateHandler, createSearchPage, createShopAllPage };
|