import { BrainerceClient } from 'brainerce'; import { cache } from 'react'; import { SALES_CHANNEL_ID } from '@/core/lib/brainerce'; import { pickPublicStoreInfo, type PublicStoreInfo } from '@/core/lib/store-info'; import { getRequestOrigin } from '@/core/lib/site-url'; import { installHostedReadCache } from '@/core/lib/hosted-read-cache'; /** * SERVER-ONLY half of the SDK wiring. Kept apart from `brainerce.ts` on * purpose: everything here reaches `next/headers` (to resolve the request's * origin), and ~30 client components import `getClient` from `brainerce.ts`. * A single shared module would drag `next/headers` into the client bundle and * fail the build outright — which is exactly what happened when these two * functions still lived there. * * Import from here in Server Components, `generateMetadata`, route handlers, * `sitemap.ts` / `robots.ts`. Never from a `'use client'` file. */ /** * Server-side client — calls the backend directly (no proxy needed for public * data). Used by Server Components for SSR data fetching. * * ⛔ ASYNC on purpose. The backend compares the `Origin` we send against the * domain configured on the sales channel, and a LIVE channel rejects both a * mismatched Origin AND a missing one with 403. The correct value is only * knowable from the request when no `SITE_URL` is configured — the norm for * AI-builder deploys — so resolving it needs an await. This previously read * `process.env.NEXT_PUBLIC_SITE_URL || 'http://localhost:3000'`, which sent * localhost from every such deploy, so every SSR call failed the moment the * channel went Live. */ export async function getServerClient(locale?: string): Promise { const apiUrl = process.env.BRAINERCE_API_URL || 'https://api.brainerce.com'; // On Cloudflare Workers many storefronts can share the same egress addresses, and the API limits per address: this puts a read // cache in front of the API (honouring its own Cache-Control, merging identical in-flight reads, failing fast on a 429). // A no-op anywhere else. See `hosted-read-cache.ts`. installHostedReadCache(apiUrl); const client = new BrainerceClient({ salesChannelId: SALES_CHANNEL_ID, baseUrl: apiUrl, origin: await getRequestOrigin(), }); if (locale) { client.setLocale(locale); } return client; } /** * Reads a fetch `Response` body as text, self-healing an observed runtime bug: * on Next.js 15.5.26, a `fetch()` made from a Route Handler or Server * Component can return a Response whose body is still gzip-compressed bytes, * even though an identical request (same URL, same headers) made via plain * Node `fetch()` outside Next decompresses correctly — confirmed by diffing * the raw response bytes both ways. The exact point inside Next's * server-side fetch instrumentation that causes this isn't confirmed, only * the externally observable symptom is. Calling `.text()`/`.json()` on a * Response like that UTF-8-decodes still-gzipped bytes — lossy (replacement * characters) and unparseable as JSON. * * A correctly-behaving fetch (browsers; plain Node; this bug's absence) never * hands back bytes that still start with gzip's magic number (`1f 8b`) — real * compression has already been undone by the time a body reaches here — so * checking for it before ever decoding as text can't misfire into * double-decompressing an already-plain body. * * This only works because the fetch below pins `Accept-Encoding: gzip` * instead of the runtime default (which also offers Brotli) — Brotli has no * reliable magic-number signature and no Web Streams API decoder, so this * self-healing has no fallback for it. That header is correctness-critical * here, not a tuning choice: reverting it to the runtime default reintroduces * this exact corruption, just for Brotli-compressed responses instead of * gzip ones. */ async function readBackendBody(response: Response): Promise { const buffer = new Uint8Array(await response.arrayBuffer()); if (buffer.length >= 2 && buffer[0] === 0x1f && buffer[1] === 0x8b) { const decompressed = new Blob([buffer]).stream().pipeThrough(new DecompressionStream('gzip')); return new TextDecoder('utf-8').decode(await new Response(decompressed).arrayBuffer()); } return new TextDecoder('utf-8').decode(buffer); } /** * One read per render for a page's main record. * * `generateMetadata` and the page body both need the same product / category / post, and each used * to build its own client and ask the API again, so every render of those pages made the same * request twice. React `cache()` shares ONE read between them for the duration of the render. It * does not outlive the render, so price and stock stay fresh: this is deliberately not a * cross-request cache (a product's price and stock must be live). Arguments are primitives so the * cache key is stable; a failure is shared too, and each caller still handles it its own way. */ export const getProductBySlugOnce = cache( async (locale: string | undefined, slug: string, regionId: string | undefined) => (await getServerClient(locale)).getProductBySlug(slug, { regionId }) ); export const getCategoryBySlugOnce = cache(async (locale: string | undefined, slug: string) => (await getServerClient(locale)).getCategoryBySlug(slug) ); export const getBlogPostOnce = cache(async (locale: string | undefined, slug: string) => (await getServerClient(locale)).blog.getPost(slug) ); /** * Server-side cached fetch of store info, used to seed `` at * SSR so client components don't render with `null` storeInfo and bake the * wrong currency symbol into the HTML Googlebot indexes. * * Two cache layers: * - React `cache()` dedupes calls within a single request render so the * layout + `generateMetadata` share one fetch. * - Next.js `fetch({ next: { revalidate, tags } })` caches the response * across requests for ~60s and lets the dashboard bust the cache via * `revalidateTag('store-info')` on store-config save. * * Returns `null` on hard failure so the provider's client-side `useEffect` * fallback can take over — behaviour identical to pre-SSR-hydration. * * Bypasses {@link getServerClient} on purpose: the SDK's internal `fetch` * does not forward `next:` options, so it cannot participate in the Next.js * Data Cache today. Switch back to the SDK once it accepts `fetchOptions`. */ export const fetchStoreInfo = cache(async (locale?: string): Promise => { const apiUrl = process.env.BRAINERCE_API_URL || 'https://api.brainerce.com'; const siteOrigin = await getRequestOrigin(); const url = `${apiUrl}/api/vc/${encodeURIComponent(SALES_CHANNEL_ID)}/info`; try { const res = await fetch(url, { headers: { Origin: siteOrigin, // Pinned to gzip — see readBackendBody() for why. 'Accept-Encoding': 'gzip', ...(locale ? { 'Accept-Language': locale } : {}), }, next: { revalidate: 60, tags: ['store-info'] }, }); if (!res.ok) return null; const text = await readBackendBody(res); return pickPublicStoreInfo(text ? JSON.parse(text) : {}); } catch { return null; } });