@bettercms-ai/sdk 1.45.0 → 1.46.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sections.ts","../src/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/config.ts","../src/bindings.ts"],"sourcesContent":["/// <reference lib=\"dom\" />\n/**\n * A published page's sections as server-rendered HTML, for a front end that renders its own\n * document (SvelteKit, Nuxt, any server): the hosted renderer's markup, its scoped stylesheet and\n * the runtime its forms, sliders and tabs need (`GET /api/v1/sites/fragment/:projectId/:slug`).\n * One renderer for every site, so the markup is the hosted site's and the editor's.\n */\nimport { BetterCMSError, ErrorCodes } from \"./errors.js\";\nimport { createClient, type BetterCMSReadClient } from \"./read-client.js\";\nimport { resolveBcmsConfig, type BcmsSiteConfig, type BcmsSiteOptions } from \"./config.js\";\nimport { draftDisableResponse, draftEnableResponse, draftTokenFrom } from \"./draft.js\";\nimport { RESPONSIVE_CSS } from \"@bettercms-ai/types\";\nimport { sectionRootAttrs } from \"./bindings.js\";\n\n/**\n * One thing a page that draws its own sections renders, in order: one of the page's own sections\n * (`slot`, with the CMS placement that names it) or a CMS block, drawn by the hosted renderer.\n */\nexport type SectionsFragmentItem =\n | { slot: string; block: { id: string; style?: Record<string, unknown> } | null }\n | { id: string; html: string };\n\nexport interface SectionsFragment {\n html: string;\n css: string;\n scripts: string;\n /**\n * The page in plan order (`planSections`, as `<BcmsSections>` renders it): the `slots` the fetch\n * named, each with its placement, and the CMS blocks between them. Absent from an older API.\n */\n items?: SectionsFragmentItem[];\n}\n\n/**\n * Fetch a page's sections (`home` is `/`). Null when the page is not published.\n *\n * `entry`: a collection's item template drawn for one of its entries (`blog/[slug]` → `slug` is the\n * collection page, `entry` the post): the collection's list, its CMS blocks filled with that entry.\n */\nexport async function fetchSections(\n opts: { apiUrl: string; projectId: string; slug: string; fetch?: typeof fetch; previewToken?: string | null; slots?: readonly string[]; entry?: string | null },\n): Promise<SectionsFragment | null> {\n const doFetch = opts.fetch ?? fetch;\n // With the editor session's preview token the answer is the page's DRAFT, every section and\n // value bound for the canvas; without it, the published page. `slots`: the sections the page\n // draws itself, in source order, which `items` interleaves with the CMS's.\n const params = [\n ...(opts.previewToken ? [`token=${encodeURIComponent(opts.previewToken)}`] : []),\n ...(opts.slots?.length ? [`slots=${opts.slots.map(encodeURIComponent).join(\",\")}`] : []),\n ...(opts.entry ? [`entry=${encodeURIComponent(opts.entry)}`] : []),\n ];\n const query = params.length > 0 ? `?${params.join(\"&\")}` : \"\";\n const url = `${opts.apiUrl.replace(/\\/+$/, \"\")}/api/v1/sites/fragment/${encodeURIComponent(opts.projectId)}/${encodeURIComponent(opts.slug || \"home\")}${query}`;\n const res = await doFetch(url, { headers: { accept: \"application/json\" } });\n if (res.status === 404) return null;\n if (!res.ok) throw new BetterCMSError(`Sections for \"${opts.slug}\" could not be read (${res.status})`, res.status, res.status === 403 ? ErrorCodes.FORBIDDEN : ErrorCodes.INTERNAL_ERROR);\n return ((await res.json()) as { data: SectionsFragment }).data;\n}\n\n/** The fragment as one string for `{@html}` / `v-html`: its stylesheet, its markup, its scripts. */\nexport function sectionsMarkup(fragment: SectionsFragment | null | undefined): string {\n if (!fragment) return \"\";\n return `<style>${fragment.css}</style>${fragment.html}${fragment.scripts}`;\n}\n\n/**\n * What a page that draws its own sections loops over (`--sections` writes the loop): one item per\n * thing it renders, in the CMS page's order.\n *\n * - `slot`: one of the page's own sections. `root` goes on the section's own root element (the\n * placement's `data-bcms-block` and style, as `sectionRootAttrs` writes them); a section whose\n * root is a component, a list or a conditional sits in a box of ours carrying `box` instead,\n * `display:contents` while the placement has no style, as `<BcmsSections>` does in React.\n * - `slot: null`: a CMS block; `html` is the hosted renderer's markup for it, drawn inside\n * `<div data-bcms-rendered=\"platform\">`. The first carries the stylesheet, the last the runtime\n * of its forms, sliders and tabs.\n *\n * With no fragment, or one from an API that has no `items`, every slot renders in source order:\n * the page as it was written.\n */\nexport interface SectionItem {\n /** Unique in the list: the slot's name, or `block:<position>:<id>`. */\n key: string;\n slot: string | null;\n root: Record<string, string>;\n box: Record<string, string>;\n html: string;\n}\n\nexport function sectionItems(fragment: Pick<SectionsFragment, \"items\" | \"css\" | \"scripts\"> | null | undefined, slots: readonly string[], page: string): SectionItem[] {\n const planned: SectionsFragmentItem[] = fragment?.items ?? slots.map((slot) => ({ slot, block: null }));\n const items = planned.map((item, at): SectionItem => {\n if (\"slot\" in item) {\n if (!item.block) return { key: item.slot, slot: item.slot, root: {}, box: { style: \"display:contents\" }, html: \"\" };\n const { style, ...stamp } = sectionRootAttrs(item.block);\n const marks = { ...stamp, \"data-bcms-sections\": page } as Record<string, string>;\n const box = !style ? \"display:contents\" : /(^|;)display:/.test(style) ? style : `display:flow-root;${style}`;\n return { key: item.slot, slot: item.slot, root: style ? { ...marks, style } : marks, box: { ...marks, \"data-bcms-box\": \"\", style: box }, html: \"\" };\n }\n // The position too: an id-less block (or two of one id) must never share a key in a keyed loop.\n return { key: `block:${at}:${item.id}`, slot: null, root: {}, box: {}, html: item.html };\n });\n const drawn = items.filter((item) => item.slot === null);\n // A placed section hidden on a breakpoint needs the rule even where no CMS block brings the sheet.\n if (drawn.length === 0 && items.some((item) => item.root[\"data-bcms-hide\"])) {\n items.unshift({ key: \"block:bcms-responsive\", slot: null, root: {}, box: {}, html: `<style>${RESPONSIVE_CSS}</style>` });\n } else if (drawn.length > 0) {\n drawn[0]!.html = `<style>${fragment?.css ?? \"\"}</style>${drawn[0]!.html}`;\n drawn[drawn.length - 1]!.html += fragment?.scripts ?? \"\";\n }\n return items;\n}\n\n/**\n * The scripts the document held when this module loaded: the HTML parser ran each of them. An\n * app's bundle loads after the parse, so this is the server-rendered page's own scripts.\n * ponytail: a module that loads lazily after a client-side navigation would also count that\n * navigation's (never-run) scripts as parsed; mark them at hydration if a lazy loader ever needs it.\n */\nconst parsed: WeakSet<Element> | null = typeof document === \"undefined\" ? null : new WeakSet(Array.from(document.getElementsByTagName(\"script\")));\n\n/**\n * Run the scripts inside `root`. A server-rendered first load runs them itself; a client-side\n * navigation inserts the markup with innerHTML, where a <script> never runs, so the forms,\n * sliders and tabs of the new page would be dead. Each script runs once per element.\n */\nexport function runSectionScripts(root: Element): void {\n for (const old of Array.from(root.querySelectorAll(\"script\"))) {\n if (old.hasAttribute(\"data-bcms-ran\")) continue;\n // The server-rendered first load: the browser's parser already ran it. Only markup inserted\n // later (innerHTML, a client-side navigation) holds scripts that never ran.\n if (parsed?.has(old)) {\n old.setAttribute(\"data-bcms-ran\", \"\");\n continue;\n }\n const fresh = document.createElement(\"script\");\n for (const attr of Array.from(old.attributes)) fresh.setAttribute(attr.name, attr.value);\n fresh.setAttribute(\"data-bcms-ran\", \"\");\n fresh.textContent = old.textContent;\n old.replaceWith(fresh);\n }\n}\n\n\nexport interface BcmsSite {\n config: BcmsSiteConfig;\n /** The read client for a request: drafts while its draft cookie holds a valid token. */\n client(request?: Request): Promise<BetterCMSReadClient>;\n /** Whether the request previews drafts (its draft cookie holds a valid token). */\n isDraft(request: Request): Promise<boolean>;\n /**\n * A page's sections (`home` is `/`); pass the framework's `fetch` on the server. Pass the\n * request too and an editor session (its draft cookie) gets the draft, bound for the canvas.\n * `entry`: the collection page `slug`'s item template, drawn for that entry (a `[slug]` route).\n * Null without the API url, workspace or project: the page renders its own sections in source order.\n */\n sections(slug: string, fetchImpl?: typeof fetch, request?: Request, opts?: { slots?: readonly string[]; entry?: string | null }): Promise<SectionsFragment | null>;\n /** GET handler for the draft path the editor opens (`/api/draft`). */\n draftEnable(request: Request): Promise<Response>;\n /** GET handler that leaves draft mode. */\n draftDisable(request: Request): Response;\n}\n\n/**\n * Everything a server-rendered site needs from BetterCMS, built once from its settings: the\n * precedence every adapter shares (options, `<PREFIX>BCMS_*`, `BCMS_*`), the read client per\n * request, the sections fragment and the draft routes. The SvelteKit and Nuxt adapters are this\n * with their env prefix.\n */\nexport function createBcmsSite(\n options: BcmsSiteOptions & { env?: Record<string, string | undefined>; draftSecret?: string; prefixes: string[]; adapter: string },\n): BcmsSite {\n const env = options.env ?? {};\n const { config, missing } = resolveBcmsConfig({ options, env, prefixes: [...options.prefixes, \"\"] });\n /**\n * 🔴 MISSING SETTINGS FAIL AT FIRST USE, NEVER HERE. A site constructs this at import time\n * (`export const bcms = createBcms(…)`, the module `--sections` writes), so throwing here failed\n * every build and prerender that ran without the env, before a single page was asked for.\n */\n const named = (keys: readonly (\"apiUrl\" | \"workspace\" | \"projectId\")[]) =>\n keys.map((m) => `${options.prefixes[0]}BCMS_${m === \"apiUrl\" ? \"API_URL\" : m === \"workspace\" ? \"WORKSPACE\" : \"PROJECT_ID\"}`).join(\" and \");\n const configured = (): void => {\n if (missing.length > 0) throw new Error(`[${options.adapter}] Missing ${named(missing)}: set them, or pass them to createBcms().`);\n };\n let warned = false;\n const secret = options.draftSecret ?? env.BCMS_DRAFT_SECRET;\n const tokenOf = (request: Request) => draftTokenFrom(request.headers.get(\"cookie\"), secret);\n return {\n config,\n isDraft: async (request) => Boolean(await tokenOf(request)),\n async client(request) {\n configured();\n const token = request ? await tokenOf(request) : null;\n return createClient({\n apiUrl: config.apiUrl,\n workspace: config.workspace,\n projectId: config.projectId,\n ...(token ? { perspective: \"drafts\" as const, previewToken: token } : {}),\n });\n },\n async sections(slug, fetchImpl, request, opts) {\n // Unconfigured, the page renders its own sections in source order (`sectionItems(null, …)`):\n // a build without the env is a build of the site as written, and says so once.\n const projectId = config.projectId;\n const absent = [...missing, ...(projectId ? [] : ([\"projectId\"] as const))];\n if (absent.length > 0 || !projectId) {\n if (!warned) console.warn(`[${options.adapter}] ${named(absent)} not set: sections render in source order.`);\n warned = true;\n return null;\n }\n const previewToken = request ? await tokenOf(request) : null;\n return fetchSections({ apiUrl: config.apiUrl, projectId, slug, fetch: fetchImpl, previewToken, slots: opts?.slots, entry: opts?.entry });\n },\n draftEnable: async (request) => {\n configured();\n return draftEnableResponse(request, { apiUrl: config.apiUrl, secret });\n },\n draftDisable: draftDisableResponse,\n };\n}\n","import type { BetterCMSErrorCode } from \"@bettercms-ai/types\";\n\n/** Semantic error codes used by the SDK. */\nexport const ErrorCodes = {\n CONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n RATE_LIMITED: \"RATE_LIMITED\",\n INTERNAL_ERROR: \"INTERNAL_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n ADMIN_NOT_IMPLEMENTED: \"ADMIN_NOT_IMPLEMENTED\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Maps HTTP status codes to semantic error codes. */\nfunction statusToCode(status: number): BetterCMSErrorCode {\n if (status === 404) return ErrorCodes.CONTENT_NOT_FOUND;\n if (status === 401) return ErrorCodes.UNAUTHORIZED;\n if (status === 403) return ErrorCodes.FORBIDDEN;\n if (status === 429) return ErrorCodes.RATE_LIMITED;\n if (status >= 500) return ErrorCodes.INTERNAL_ERROR;\n if (status === 422) return ErrorCodes.VALIDATION_ERROR;\n return ErrorCodes.INTERNAL_ERROR;\n}\n\n/**\n * BetterCMSError — normalized SDK error with a semantic code.\n */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: BetterCMSErrorCode;\n /**\n * Raw machine-readable `code` from the response body (e.g. \"PROJECT_DELETED\"),\n * when the API supplies one. Distinct from `code` (which is derived from the\n * HTTP status), this lets callers branch on a specific server condition that\n * shares a status with others (e.g. 409 slug-conflict vs 409 project-deleted).\n */\n readonly bodyCode?: string;\n /**\n * Per-field validation messages from a 400 `{ errors: { field: message } }` body.\n * The backend returns validation failures in this shape (not `message`/`error`), so\n * without this the SDK collapsed every validation 400 to a bare \"Bad Request\" with no\n * hint which field or rule failed (FLO-474). Mirrors the forms client's `fieldErrors`.\n */\n readonly fieldErrors?: Record<string, string>;\n /**\n * The parsed response body, when there was one.\n *\n * Several refusals carry STRUCTURED detail that neither `message` nor `fieldErrors` can hold,\n * and which is the whole point of the refusal: a component publish 409s with the full\n * `readiness` tuple (what evidence is missing, whether a human still has to approve it) and\n * 422s with the `issues` naming the Layouts it would break. Collapsing those to a sentence\n * leaves a caller able to report that something failed and not what to do about it.\n */\n readonly body?: unknown;\n\n constructor(\n message: string,\n status: number,\n code: BetterCMSErrorCode,\n bodyCode?: string,\n fieldErrors?: Record<string, string>,\n body?: unknown,\n ) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n this.bodyCode = bodyCode;\n this.fieldErrors = fieldErrors;\n this.body = body;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BetterCMSError);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n code: this.code,\n bodyCode: this.bodyCode,\n fieldErrors: this.fieldErrors,\n };\n }\n\n /**\n * Factory — creates a BetterCMSError from a failed fetch Response. Reads the body's\n * `message` (or `error`) for the human message and `code` for a machine-readable\n * condition surfaced as `bodyCode`. Validation failures arrive as `{ errors: {...} }`\n * (no `message`/`error`), so fall back to the first field error for the message and\n * expose the full map as `fieldErrors` (FLO-474).\n */\n static async from(res: Response): Promise<BetterCMSError> {\n let message = res.statusText || \"An error occurred\";\n let bodyCode: string | undefined;\n let fieldErrors: Record<string, string> | undefined;\n let code = statusToCode(res.status);\n let raw: unknown;\n try {\n const body = (await res.json()) as {\n message?: string;\n error?: string;\n code?: string;\n errors?: Record<string, string>;\n };\n if (body?.errors && typeof body.errors === \"object\") {\n fieldErrors = body.errors;\n code = ErrorCodes.VALIDATION_ERROR;\n }\n if (body?.message) message = body.message;\n else if (body?.error) message = body.error;\n else if (fieldErrors) {\n const [field, detail] = Object.entries(fieldErrors).find(\n ([, v]) => typeof v === \"string\" && v.length > 0,\n ) ?? [];\n if (field) message = `${field}: ${detail}`;\n }\n if (body?.code) bodyCode = body.code;\n raw = body;\n } catch {\n // ignore parse errors\n }\n return new BetterCMSError(message, res.status, code, bodyCode, fieldErrors, raw);\n }\n}\n","/**\n * Shared 429/503 backoff for every SDK client.\n *\n * ── Why this exists ─────────────────────────────────────────────────────────\n * The backend limiter (src/lib/ratelimit.ts, windowHit) is a FIXED 60-SECOND\n * WINDOW: 100 requests per workspace per endpoint, and a denial answers\n * `Retry-After: <seconds until the window resets>` — anything up to 60.\n *\n * Every client here used to climb a private ladder that topped out at 7 seconds\n * ([250,750,1500] in read-client, [1000,2000,4000] in admin/management) and none\n * of them read Retry-After. So all three retries landed INSIDE the same exhausted\n * window and a 429 was fatal roughly whenever it was thrown. The retry code looked\n * like resilience but could only ever recover from a denial raised in the final\n * seconds of a window.\n *\n * That is what failed customer builds: `action/fetch-content.mjs` spends ~65 of the\n * 100 `delivery-content-entries-list` slots pulling a large workspace, `npm run build`\n * starts seconds later in the SAME window, and the first per-route delivery read past\n * the ceiling killed the deploy with \"Too many requests. Please retry later.\"\n *\n * ── The rule ────────────────────────────────────────────────────────────────\n * Obey Retry-After when the server sends one, and let a single request outlast a\n * whole window. A build waiting 60s is slow; a build that dies is a broken product.\n */\n\n/** Statuses worth retrying. 429 = rate limited, 503 = limiter/backend unavailable. */\nexport const RETRY_STATUSES = [429, 503] as const;\n\n/** Retries after the first attempt. 3 retries × up to ~65s spans three full windows. */\nexport const MAX_RETRIES = 3;\n\n/**\n * Hard ceiling on a single wait, jitter included. Must exceed the limiter's 60s\n * window, or a denial raised at the very start of a window still cannot be waited\n * out — and must be finite, so a hostile or mis-set Retry-After cannot hang a build.\n */\nexport const MAX_DELAY_MS = 65_000;\n\n/** Fallback ladder when the server sends no Retry-After: 1s, 2s, 4s, 8s. */\nconst BASE_DELAY_MS = 1_000;\n\n/**\n * De-sync jitter, added to every wait.\n *\n * Deliberately a small FLAT amount, not a percentage. Requests denied by one window\n * only need to stop firing in the same millisecond — the server's counter serialises\n * them after that. A proportional jitter would add up to 15 seconds to a 60-second\n * wait for no benefit, and would push the total past MAX_DELAY_MS.\n */\nconst JITTER_MS = 250;\n\nexport function isRetryableStatus(status: number): boolean {\n return (RETRY_STATUSES as readonly number[]).includes(status);\n}\n\n/**\n * Parse `Retry-After`, which RFC 9110 allows in either form: delay-seconds\n * (\"47\") or an HTTP-date (\"Wed, 21 Oct 2015 07:28:00 GMT\"). Returns ms to wait,\n * or null when the header is absent or unparseable.\n */\nexport function retryAfterMs(res: Pick<Response, \"headers\">): number | null {\n const raw = res.headers?.get?.(\"retry-after\");\n if (!raw) return null;\n\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) {\n return Math.min(Math.max(seconds, 0) * 1000, MAX_DELAY_MS);\n }\n\n const at = Date.parse(raw);\n if (!Number.isNaN(at)) {\n return Math.min(Math.max(0, at - Date.now()), MAX_DELAY_MS);\n }\n return null;\n}\n\n/**\n * How long to wait before retry `attempt` (0-based).\n *\n * Server instruction wins; otherwise exponential. Jitter is added in both cases:\n * when a build's requests are all denied by the same window they would otherwise\n * wake in lockstep at the reset and re-exhaust it immediately (thundering herd).\n */\nexport function backoffMs(attempt: number, res?: Pick<Response, \"headers\">): number {\n const fromServer = res ? retryAfterMs(res) : null;\n // Base is capped with the jitter's headroom already reserved, so the total never\n // exceeds MAX_DELAY_MS AND the jitter is never clamped away at the ceiling — which\n // would put every capped caller back in lockstep, the exact thing jitter prevents.\n const base = Math.min(fromServer ?? BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS - JITTER_MS);\n // Jitter is ADDED, never subtracted: waking before the server's Retry-After elapses\n // just burns a retry on a window that has not reset.\n return base + Math.random() * JITTER_MS;\n}\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n status: 302,\n headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": `${DRAFT_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` },\n });\n}\n","/**\n * createClient — framework-agnostic typed read client for the Delivery API.\n *\n * Shared by @bettercms-ai/astro and @bettercms-ai/next so the fetch/typing/retry\n * logic lives in one place. Read-only; for schema authoring use the\n * Management client, for sessions use the Admin client.\n *\n * const client = createClient({ apiUrl, workspace, apiKey });\n * await client.getPage(\"home\");\n * await client.listEntries({ model: \"post\", perPage: 50 });\n */\nimport type {\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n DeliveredLayout,\n Perspective,\n} from \"@bettercms-ai/types\";\nimport { BetterCMSError } from \"./errors.js\";\nimport { MAX_RETRIES, backoffMs, isRetryableStatus, sleep } from \"./retry.js\";\nimport type { DeliveryForm } from \"./forms.js\";\nimport { BRANCH_SIGNATURE_HEADER } from \"./draft.js\";\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport interface CreateClientOptions {\n /** Backend base, e.g. `https://api.bettercms.ai` (no trailing slash needed). */\n apiUrl: string;\n /** Workspace slug. */\n workspace: string;\n /** Delivery API key. Use a `content:read:draft` key for drafts. */\n apiKey?: string;\n /**\n * The project every read is addressed to. A workspace holds many projects whose slugs\n * collide (each has a `blog` model and a `home` page), so a site names its own; published\n * reads need no key for it. BetterCMS hosting supplies `PUBLIC_BCMS_PROJECT_ID`.\n */\n projectId?: string;\n /**\n * A content branch (its slug) to read instead of the live site, like a Sanity release\n * perspective: every read answers from the branch. Needs a `content:read:draft` key and a\n * `projectId`; a branch that is not open answers 404 (BRANCH_NOT_FOUND).\n */\n branch?: string;\n /**\n * `signBranchRead(branch, BCMS_BRANCH_SECRET)`: on a server BetterCMS hosts, reads the `branch`\n * with no draft key. `@bettercms-ai/astro` signs for you on a branch preview.\n */\n branchSignature?: string;\n /** `published` (default) or `drafts`. */\n perspective?: Perspective;\n /**\n * Preview-token JWT for token-based single-document draft reads via the\n * `/preview/:slug` endpoint. Only used when `perspective === \"drafts\"`.\n */\n previewToken?: string;\n /**\n * Embed invisible visual-editing provenance in draft reads, so a preview build can\n * deep-link each rendered value back to its editor. Requires `perspective: \"drafts\"`,\n * and then either a `previewToken` or a `content:read:draft` key. Ignored on published\n * reads — the payload must never reach a production build.\n *\n * **Defaults to `true` on `perspective: \"drafts\"`** (since 1.15.0). Provenance is the whole\n * reason the drafts perspective exists in a preview build, and an option nobody knew to pass\n * meant every such build rendered anonymous strings: the editor could bind them only by\n * guessing at their text. It stays OFF on every other perspective, unconditionally, so a\n * published build cannot acquire a payload by accident — pass `stega: false` to opt a draft\n * read out (a diff or a checksum over draft content is the case that wants it).\n */\n stega?: boolean;\n /** Per-attempt timeout in ms. Defaults to 10000. */\n timeout?: number;\n /**\n * Collapse identical GETs to one network round-trip for the life of this client.\n * Default false.\n *\n * Only correct where the content is a POINT-IN-TIME SNAPSHOT — i.e. a static build,\n * where every route renders from the same published dataset. `@bettercms-ai/astro`\n * turns this on automatically when Astro's `command === \"build\"` and never for `dev`,\n * SSR or the drafts perspective, where a repeat read must see the current row.\n *\n * A static build without it re-fetches the same nav/settings/collection once PER ROUTE.\n * That is what made a large site exhaust the delivery rate limit: hundreds of identical\n * requests, and `getPage()` re-scanning every page of the paginated list each time it is\n * called.\n */\n cache?: boolean;\n}\n\nexport interface ListEntriesOptions {\n /** Filter by content-model slug. */\n model?: string;\n page?: number;\n perPage?: number;\n /** Reference hydration depth (lists cap at 1). */\n depth?: 0 | 1;\n /** Projection — field names to return. */\n select?: string[];\n}\n\nexport interface GetEntryOptions {\n depth?: 0 | 1 | 2;\n select?: string[];\n}\n\nexport interface ListPagesOptions {\n page?: number;\n perPage?: number;\n /** Only the page with this slug (the list's `?slug=`). */\n slug?: string;\n}\n\nexport interface BetterCMSReadClient {\n readonly perspective: Perspective;\n getEntry<T = Record<string, unknown>>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<DeliveryEntry<T>>;\n listEntries<T = Record<string, unknown>>(\n opts?: ListEntriesOptions,\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n getPage(slug: string): Promise<DeliveryPage | null>;\n listPages(opts?: ListPagesOptions): Promise<DeliveryList<DeliveryPage>>;\n /**\n * The workspace's reusable component definitions, for resolving `component` blocks.\n * Under `perspective: \"drafts\"` this is the DRAFT definition — what makes an SSR render\n * of a draft page look like the page the editor is showing.\n */\n listComponents(): Promise<DeliveryComponent[]>;\n /** Fetch the project-scoped Global Layout for the active perspective. */\n getLayout(): Promise<DeliveredLayout | null>;\n listForms(opts?: {\n projectId?: string;\n }): Promise<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>;\n /** Build a deterministic Next/cache tag for a resource. */\n tag(resource: \"entry\" | \"page\" | \"forms\", id?: string): string;\n}\n\n/** Drop undefined values, stringify the rest into a query string. */\nfunction qs(params: Record<string, string | number | undefined>): string {\n const sp = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && v !== \"\") sp.set(k, String(v));\n }\n const s = sp.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * Unwrap a `{ data: ... }` list/legacy envelope when present. A bare entry is\n * already the payload (it has `id`/`slug` and its own `data` field), so we only\n * unwrap when no payload markers are at the top level.\n */\nfunction unwrap<T>(json: unknown): T {\n if (json && typeof json === \"object\") {\n const o = json as Record<string, unknown>;\n const isPayload = \"id\" in o || \"slug\" in o || \"items\" in o;\n if (!isPayload && \"data\" in o) return o.data as T;\n }\n return json as T;\n}\n\n/**\n * The `entrySlug` claim of a preview-token JWT, UNVERIFIED.\n *\n * The backend is the signature authority — this read only decides WHICH url to call, and a\n * forged claim buys nothing: `/preview/:slug` re-verifies and 401s. Kept private to this file\n * (`@bettercms-ai/astro` has its own copy for the same reason: neither package may depend on\n * the other).\n */\nfunction tokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return (JSON.parse(json) as { entrySlug?: string }).entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Per-URL request collapsing.\n *\n * Two jobs, both needed: coalesce requests that are IN FLIGHT (Astro renders routes\n * concurrently, so identical GETs overlap) and retain the ones that have COMPLETED\n * (routes render in batches, so the same GET recurs long after the first settled).\n *\n * Values are cloned on the way out. Callers get a fresh object graph, so a template that\n * sorts `items` in place — an easy thing to write and a brutal thing to debug — cannot\n * corrupt what every other route sees. Cloning costs memory bandwidth; the request it\n * replaces costs a network round-trip and a slot in the rate-limit window.\n *\n * A rejected request is never retained, so a transient failure does not become permanent.\n */\nfunction createRequestCache() {\n const inflight = new Map<string, Promise<unknown>>();\n const settled = new Map<string, unknown>();\n\n const copy = <T>(value: T): T =>\n typeof structuredClone === \"function\" ? structuredClone(value) : (JSON.parse(JSON.stringify(value)) as T);\n\n return async function collapse<T>(url: string, fetcher: () => Promise<T>): Promise<T> {\n if (settled.has(url)) return copy(settled.get(url) as T);\n\n const pending = inflight.get(url) as Promise<T> | undefined;\n if (pending) return copy(await pending);\n\n const run = (async () => {\n try {\n const value = await fetcher();\n settled.set(url, value);\n return value;\n } finally {\n inflight.delete(url);\n }\n })();\n inflight.set(url, run);\n return copy(await run);\n };\n}\n\nexport function createClient(options: CreateClientOptions): BetterCMSReadClient {\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const { workspace, apiKey, perspective = \"published\", previewToken } = options;\n const defaultProjectId = options.projectId;\n // Every delivery read names the project and, for a branch preview, the branch.\n const branch = options.branch && options.branch !== \"main\" ? options.branch : undefined;\n const timeout = options.timeout ?? DEFAULT_TIMEOUT;\n const base = `${apiUrl}/api/v1/delivery/${workspace}`;\n\n const headers = (): Record<string, string> => {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) h[\"X-API-Key\"] = apiKey;\n if (branch && options.branchSignature) h[BRANCH_SIGNATURE_HEADER] = options.branchSignature;\n return h;\n };\n\n // Drafts must never be collapsed even if a caller asks: a preview surface re-reads to\n // see the edit that just happened, and serving it a retained copy would show stale content.\n const collapse =\n options.cache && perspective === \"published\" ? createRequestCache() : undefined;\n\n const fetchJSON = <T>(url: string): Promise<T> =>\n collapse ? collapse(url, () => request<T>(url)) : request<T>(url);\n\n async function request<T>(url: string): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await globalThis.fetch(url, {\n headers: headers(),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (res.ok) return (await res.json()) as T;\n\n const retryable = attempt < MAX_RETRIES && isRetryableStatus(res.status);\n if (!retryable) throw await BetterCMSError.from(res);\n // Honour Retry-After: the limiter's window is up to 60s, far longer than\n // any fixed ladder, so the server's own number is the only one that works.\n await sleep(backoffMs(attempt, res));\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new BetterCMSError(\"Request timeout\", 408, \"NETWORK_ERROR\");\n }\n if (err instanceof BetterCMSError) throw err;\n lastError = err;\n if (attempt < MAX_RETRIES) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n }\n throw lastError ?? new BetterCMSError(\"Unreachable\", 0, \"NETWORK_ERROR\");\n }\n\n const draft = perspective === \"drafts\";\n /**\n * Resolved ONCE, here, so the three call sites below cannot drift apart — they did exactly\n * that before (`options.stega` alone on the preview branch, `draft && options.stega` on the\n * other two), and a default expressed three times is a default that will eventually be two.\n * `??` and not `||`: an explicit `stega: false` on a draft read must win.\n */\n const stega = options.stega ?? draft;\n\n return {\n perspective,\n\n async getEntry<T = Record<string, unknown>>(slug: string, opts?: GetEntryOptions) {\n // Token-based draft reads go through the dedicated preview endpoint.\n // Without a token the drafts perspective is served by delivery itself, which needs\n // to be TOLD — `?perspective=draft` (honoured only for a `content:read:draft` key).\n // Until this branch sent it, `perspective: \"drafts\"` was silently inert here, and\n // with it `stega`, so a static build could never obtain provenance without minting\n // a preview token per entry.\n // The token names ONE entry (as on getPage below): any other slug reads delivery, or the\n // preview endpoint 404s the post list, related posts and nav a draft page also renders.\n const url =\n draft && previewToken && tokenSlug(previewToken) === slug\n ? `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n stega: stega ? \"1\" : undefined,\n })}`\n : `${base}/content-entries/${encodeURIComponent(slug)}${qs({\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryEntry<T>>(await fetchJSON(url));\n },\n\n async listEntries<T = Record<string, unknown>>(opts?: ListEntriesOptions) {\n const url = `${base}/content-entries${qs({\n model: opts?.model,\n page: opts?.page,\n perPage: opts?.perPage,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryEntry<T>>>(await fetchJSON(url));\n },\n\n async getPage(slug: string) {\n // The token names ONE page, and for that page the preview endpoint is the only read\n // that returns the DRAFT block tree — the paginated delivery list is published-only, so\n // an SSR draft render would otherwise be the live structure with draft field values.\n // Any other slug falls through to the published scan, which is what a token for /about\n // rendering the site's nav or footer pages must keep doing.\n if (draft && previewToken && tokenSlug(previewToken) === slug) {\n const url = `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n stega: stega ? \"1\" : undefined,\n })}`;\n const d = unwrap<Record<string, unknown>>(await fetchJSON(url));\n return {\n slug: d.slug as string,\n title: d.title as string,\n metaTitle: (d.metaTitle as string | null) ?? null,\n metaDescription: (d.metaDescription as string | null) ?? null,\n metaJson: (d.metaJson as DeliveryPage[\"metaJson\"]) ?? null,\n blocks: (d.blockJson as DeliveryPage[\"blocks\"]) ?? [],\n // C3: the DRAFT field styles, present only when the page styles a field.\n ...(d.fieldStyles ? { fieldStyles: d.fieldStyles as NonNullable<DeliveryPage[\"fieldStyles\"]> } : {}),\n updatedAt: (d.updatedAt as string | null) ?? null,\n publishedAt: (d.publishedAt as string | null) ?? null,\n } satisfies DeliveryPage;\n }\n // No dedicated single-page delivery endpoint: the list, narrowed to this slug. Unnarrowed, every\n // client-rendered page view read every page of the site (a converted React SPA's <BcmsSections>:\n // ~50 KB for one page's order). A server that ignores `slug` answers the whole list, scanned as before.\n let page = 1;\n for (;;) {\n const list = await this.listPages({ page, perPage: 100, slug });\n const found = list.items.find((p) => p.slug === slug);\n if (found) return found;\n if (!list.hasNextPage) return null;\n page += 1;\n }\n },\n\n async listPages(opts?: ListPagesOptions) {\n const url = `${base}/pages${qs({\n page: opts?.page,\n perPage: opts?.perPage,\n slug: opts?.slug,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryPage>>(await fetchJSON(url));\n },\n\n async listComponents() {\n // Same shape as getLayout: `?perspective=draft` alone is the key-scoped path (the server\n // ignores it for a published key), and a preview token is the page-scoped one.\n const url = `${base}/components${qs({\n perspective: draft ? \"draft\" : undefined,\n token: draft ? previewToken : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryComponent[]>(await fetchJSON(url));\n },\n\n async getLayout() {\n const url = `${base}/layout${qs({ perspective: draft ? \"draft\" : undefined, projectId: defaultProjectId, branch })}`;\n try {\n return unwrap<DeliveredLayout>(await fetchJSON(url));\n } catch (error) {\n if (error instanceof BetterCMSError && error.status === 404) return null;\n throw error;\n }\n },\n\n async listForms(opts?: { projectId?: string }) {\n const url = `${base}/forms${qs({\n projectId: opts?.projectId ?? defaultProjectId,\n branch,\n })}`;\n return unwrap<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>(\n await fetchJSON(url),\n );\n },\n\n tag(resource, id) {\n return id ? `bcms:${workspace}:${resource}:${id}` : `bcms:${workspace}:${resource}`;\n },\n };\n}\n","/**\n * Where a site's BetterCMS settings come from, the same way on every framework: explicit options,\n * then `<PREFIX>BCMS_*` env (each framework exposes env to the browser under its own prefix:\n * `PUBLIC_` for Astro and SvelteKit, `NEXT_PUBLIC_` for Next, `VITE_` for Vite React,\n * `NUXT_PUBLIC_` for Nuxt), then the build snapshot `bettercms pull-content` writes.\n *\n * Pure: the adapter passes its env and reads the snapshot (this module touches no filesystem).\n */\n\nexport const DEFAULT_MEDIA_URL = \"https://cdn.bettercms.ai\";\n\nexport interface BcmsSiteOptions {\n apiUrl?: string;\n workspace?: string;\n projectId?: string;\n mediaUrl?: string;\n studioUrl?: string;\n}\n\nexport interface BcmsSiteConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n mediaUrl: string;\n studioUrl?: string;\n}\n\nexport interface ResolveBcmsConfigInput {\n options?: BcmsSiteOptions;\n env?: Record<string, string | undefined>;\n /** Env prefixes, first match wins: `[\"NEXT_PUBLIC_\", \"\"]` reads NEXT_PUBLIC_BCMS_API_URL, then BCMS_API_URL. */\n prefixes: string[];\n /** The build snapshot's identity, read only when options and env both miss. */\n snapshot?: () => { apiUrl?: string; workspace?: string; projectId?: string };\n}\n\n/** The resolved settings, and which essentials are missing (the adapter words the error). */\nexport function resolveBcmsConfig(input: ResolveBcmsConfigInput): { config: BcmsSiteConfig; missing: (\"apiUrl\" | \"workspace\")[] } {\n const env = input.env ?? {};\n const fromEnv = (name: string) => {\n for (const p of input.prefixes) {\n const v = env[`${p}BCMS_${name}`];\n if (v) return v;\n }\n return undefined;\n };\n let snap: ReturnType<NonNullable<ResolveBcmsConfigInput[\"snapshot\"]>> | undefined;\n const snapshot = () => (snap ??= input.snapshot?.() ?? {});\n const o = input.options ?? {};\n const config: BcmsSiteConfig = {\n apiUrl: (o.apiUrl ?? fromEnv(\"API_URL\") ?? snapshot().apiUrl ?? \"\").replace(/\\/+$/, \"\"),\n workspace: o.workspace ?? fromEnv(\"WORKSPACE\") ?? snapshot().workspace ?? \"\",\n projectId: o.projectId ?? fromEnv(\"PROJECT_ID\") ?? snapshot().projectId,\n mediaUrl: (o.mediaUrl ?? fromEnv(\"MEDIA_URL\") ?? DEFAULT_MEDIA_URL).replace(/\\/+$/, \"\"),\n studioUrl: o.studioUrl ?? fromEnv(\"STUDIO_URL\"),\n };\n const missing = ([\"apiUrl\", \"workspace\"] as const).filter((k) => !config[k]);\n return { config, missing };\n}\n","/**\n * The attributes a site's OWN markup spreads so the BetterCMS editor binds it: a page field, a\n * collection entry, a section root and its content column. Plain objects of string attributes\n * (the style is a CSS string), so they spread as they are in every template language:\n *\n * Astro / Svelte <h1 {...fieldAttrs(\"hero-title\", page.fieldStyles)}>…</h1>\n * Vue <h1 v-bind=\"fieldAttrs('hero-title', page.fieldStyles)\">…</h1>\n *\n * @bettercms-ai/astro, /sveltekit and /nuxt re-export these; @bettercms-ai/next keeps twins whose\n * `style` is a React style object.\n */\nimport imageUrlBuilder, {\n focalInCrop,\n normalizeImageCrop,\n normalizeImageFocal,\n objectPosition,\n type ImageFit,\n type ImageFormat,\n type ImageSource,\n} from \"@bettercms-ai/image-url\";\nimport { blockStyleToColumnCss, blockStyleToCss, fieldStyleCssText, hideOnAttr, sectionIdentityAttrs, type BlockStyle, type FieldStyle, type FieldStyles } from \"@bettercms-ai/types\";\n\n/**\n * C3 — `fieldAttrs(path, fieldStyles)`: the attributes a site's OWN element spreads to bind a PAGE\n * FIELD and apply that field's stored style, so the BetterCMS editor offers its width and spacing\n * handles and its Align / Size / Weight controls.\n *\n * ---\n * const page = await loadPage(Astro, \"home\");\n * ---\n * <h1 class=\"title\" {...fieldAttrs(\"hero-title\", page?.fieldStyles)}>{entry.data[\"hero-title\"]}</h1>\n *\n * `data-bcms-style` is the site's promise that \"this element's inline style is\n * `fieldStyleToCss(fieldStyles[path])`\". The editor offers a field's handles only on an element that\n * carries it: a handle on one that does not would paint the canvas and never ship. The marker is\n * present even when the field has no style (then there is no `style` attribute at all, byte for\n * byte the element it was): an unstyled field is the one an author is about to give its first edit.\n */\nexport interface FieldAttrs {\n \"data-bcms-field\": string;\n /** The marker's revision: \"2\" promises `size` (zoom) too. Section roots keep \"\". */\n \"data-bcms-style\": \"2\";\n /** `fieldStyleToCss(fieldStyles[path])` as a CSS string; absent when the field has no style. */\n style?: string;\n}\n\n/** The stored style for `path`, by OWN key only — a path like `constructor` never reads the prototype. */\nexport function fieldStyleOf(path: string, fieldStyles: FieldStyles | Record<string, unknown> | null | undefined): FieldStyle | undefined {\n if (!fieldStyles || typeof fieldStyles !== \"object\" || !Object.prototype.hasOwnProperty.call(fieldStyles, path)) return undefined;\n const style = (fieldStyles as Record<string, unknown>)[path];\n return style && typeof style === \"object\" ? (style as FieldStyle) : undefined;\n}\n\nexport function fieldAttrs(path: string, fieldStyles?: FieldStyles | Record<string, unknown> | null): FieldAttrs {\n const style = fieldStyleCssText(fieldStyleOf(path, fieldStyles));\n return { \"data-bcms-field\": path, \"data-bcms-style\": \"2\", ...(style ? { style } : {}) };\n}\n\n/**\n * P7 — `entryAttrs(entry)` and `entryField(entry, path)`: the attributes a site's OWN card spreads to\n * declare a collection ENTRY, so the editor binds it without guessing from the rendered text.\n *\n * <article {...entryAttrs(post)}><h3 {...entryField(post, \"title\")}>{post.fields.title}</h3></article>\n *\n * The field address is ABSOLUTE (`entry:<id>:<path>`). With a `transform` the value is shown\n * changed (a date formatted, text truncated), so it is declared as `data-bcms-entry-from`: the\n * editor knows where it is but cannot re-render it.\n */\nexport type EntryRef = { id?: string } | string;\nexport type EntryTransform = \"format\" | \"truncate\" | \"rendition\" | \"route\";\n/** One key is present: `data-bcms-entry-field`, or `data-bcms-entry-from` when transformed; none without an id. */\nexport interface EntryFieldAttrs {\n \"data-bcms-entry-field\"?: string;\n \"data-bcms-entry-from\"?: string;\n}\n\nfunction entryIdOf(entry: EntryRef): string | null {\n const id = typeof entry === \"string\" ? entry : entry?.id;\n return typeof id === \"string\" && id.trim() !== \"\" ? id : null;\n}\n\n/** An entry with no id (a snapshot written before ids were kept) renders unbound, never fails the build. */\nexport function entryAttrs(entry: EntryRef): { \"data-bcms-entry\"?: string } {\n const id = entryIdOf(entry);\n return id ? { \"data-bcms-entry\": id } : {};\n}\n\nexport function entryField(entry: EntryRef, path: string, opts?: { transform?: EntryTransform }): EntryFieldAttrs {\n const id = entryIdOf(entry);\n if (typeof path !== \"string\" || path.trim() === \"\") throw new Error(`entryField: no field path given for entry ${id ?? \"(no id)\"}`);\n if (!id) return {};\n const address = `entry:${id}:${path}`;\n return opts?.transform ? { \"data-bcms-entry-from\": `${address}|${opts.transform}` } : { \"data-bcms-entry-field\": address };\n}\n\n/**\n * C3/C4 — `sectionRootAttrs(block)`: the attributes a site's OWN section root spreads so the\n * BetterCMS editor offers that section's spacing and style handles.\n *\n * <section class=\"hero\" {...sectionRootAttrs(block)}>…</section>\n *\n * The editor shows those handles on a site-rendered page only when EVERY root the site stamps\n * with `data-bcms-block` also carries `data-bcms-style`, which is the site's promise that \"this\n * root's inline style is `blockStyleToCss(block.style)`\" — the same declarations `<BcmsBlocks>`\n * puts on its own wrapper. A root that stamps the block without applying its style would get a\n * capsule that paints the canvas and never ships, so the marker must travel with the style.\n *\n * The marker is present even when the style is EMPTY (then there is no `style` attribute at all):\n * an unstyled section is exactly the one an author is about to give its first spacing edit.\n */\nexport interface SectionRootBlock {\n id?: string | null;\n style?: BlockStyle | Record<string, unknown> | null;\n}\n\nexport interface SectionRootAttrs {\n /**\n * The section's Anchor ID (`style.anchor`), present only when one is set, so a root with its own\n * `id` keeps it otherwise. The section's CSS class (`style.cssClass`) is NOT spread: it would\n * replace the root's own class. Read it with `sectionIdentityAttrs(block.style).className` and\n * join it into the root's class list.\n */\n id?: string;\n \"data-bcms-block\"?: string;\n \"data-bcms-style\": \"\";\n /** `\"mobile tablet\"` when `style.hideOn` hides it there; the site ships `RESPONSIVE_CSS` for it. */\n \"data-bcms-hide\"?: string;\n /** `blockStyleToCss(block.style)` as a CSS string; absent when the block has no style. */\n style?: string;\n}\n\n/** `paddingTop` → `padding-top`, joined the way `<BcmsBlocks>` writes its wrapper's attribute. */\nfunction cssText(css: Record<string, string | number>): string {\n return Object.entries(css)\n .map(([k, v]) => `${k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}:${v}`)\n .join(\";\");\n}\n\nexport function sectionRootAttrs(block: SectionRootBlock | null | undefined): SectionRootAttrs {\n const css = blockStyleToCss((block?.style ?? undefined) as BlockStyle | undefined);\n const id = typeof block?.id === \"string\" && block.id !== \"\" ? block.id : undefined;\n const hide = hideOnAttr(block?.style);\n const anchor = sectionIdentityAttrs(block?.style).id;\n return {\n ...(anchor ? { id: anchor } : {}),\n ...(id !== undefined ? { \"data-bcms-block\": id } : {}),\n \"data-bcms-style\": \"\",\n ...(hide ? { \"data-bcms-hide\": hide } : {}),\n ...(css ? { style: cssText(css) } : {}),\n };\n}\n\nexport interface SectionColumnAttrs {\n \"data-bcms-column\": \"\";\n /** `blockStyleToColumnCss(block.style)` as a CSS string; absent when the section has no column. */\n style?: string;\n}\n\n/**\n * C3 — `sectionColumnAttrs(block)`: the attributes a site's own INNER container spreads so the\n * section's content WIDTH (`style.contentWidth`, placed by `contentAlign`) ships.\n *\n * <section {...sectionRootAttrs(block)}>\n * <div class=\"container\" {...sectionColumnAttrs(block)}>…</div>\n * </section>\n *\n * The width is the column BetterCMS draws as `.bcms-block-inner` inside the section's styled box —\n * never on the root itself, whose background must stay full-bleed. `data-bcms-column` is the\n * site's promise that this box's inline style is the column; the editor offers the width handle\n * on a site-rendered page only where every styled root holds one. Max-width plus left/right\n * margins, so the container keeps its own vertical margins and, with no column, its own width.\n */\nexport function sectionColumnAttrs(block: SectionRootBlock | null | undefined): SectionColumnAttrs {\n const css = blockStyleToColumnCss((block?.style ?? undefined) as BlockStyle | undefined);\n return { \"data-bcms-column\": \"\", ...(css ? { style: cssText(css) } : {}) };\n}\n\n/** The image facts a value or asset may carry beside its URL. */\ntype ImageFacts = { altText?: string | null; alt?: string | null; width?: number | null; height?: number | null; focalX?: number | null; focalY?: number | null };\n\nexport interface ImageOptions {\n /** The field this image renders, in the editor grammar (`cover`, `hero.image`). */\n path?: string;\n alt?: string;\n width?: number;\n height?: number;\n format?: ImageFormat;\n quality?: number;\n fit?: ImageFit;\n sizes?: string;\n loading?: \"lazy\" | \"eager\";\n /** Focal point override, 0–1. Normally omitted: the value and the asset carry their own. */\n focalX?: number | null;\n focalY?: number | null;\n /** Media host for a `src` that is only an asset id. Defaults to the platform's. */\n baseUrl?: string;\n}\n\n/** The widths a `sizes` image offers: phone to desktop, and never an upscale of the picture. */\nconst LADDER = [480, 768, 1080, 1440, 1920];\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" && Number.isFinite(v) ? v : undefined);\n\n/**\n * What every `<BcmsImage>` renders, computed once for all of them: the transform URL, a srcset\n * (a WIDTH ladder with `sizes` and no `width`, else 1x/2x), the alt (the value's `altText` unless\n * `alt` says otherwise) and the style declarations, camel-cased. The value's crop and focal point\n * are applied by image-url itself; a source-relative focal is re-expressed inside the crop.\n */\nexport function imageCore(src: ImageSource | (Exclude<ImageSource, string> & ImageFacts), opts: ImageOptions = {}) {\n const { width, height, format = \"webp\", quality, fit, sizes, focalX, focalY, baseUrl } = opts;\n const asset = (typeof src === \"object\" && src !== null ? src : {}) as Record<string, unknown>;\n const explicit = focalX != null || focalY != null;\n const stored =\n normalizeImageFocal(asset.focal) ??\n (num(asset.focalX) != null || num(asset.focalY) != null ? { x: num(asset.focalX) ?? 0.5, y: num(asset.focalY) ?? 0.5 } : null);\n const inWindow = stored ? focalInCrop(stored, normalizeImageCrop(asset.crop)) : null;\n const fx = explicit ? focalX : inWindow?.x;\n const fy = explicit ? focalY : inWindow?.y;\n const hasFocal = fx != null || fy != null;\n const builder = imageUrlBuilder({ baseUrl });\n const make = () => {\n let b = builder(src as ImageSource);\n if (width) b = b.width(width);\n if (height) b = b.height(height);\n if (format) b = b.format(format);\n if (quality) b = b.quality(quality);\n if (fit) b = b.fit(fit);\n if (hasFocal) b = b.focal(fx ?? 0.5, fy ?? 0.5);\n return b;\n };\n const url = make().url();\n const own = num(asset.width);\n const ladder = own ? [...new Set([...LADDER.filter((w) => w < own), Math.min(own, LADDER[LADDER.length - 1]!)])] : LADDER;\n const srcset = sizes && !width ? ladder.map((w) => `${make().width(w).url()} ${w}w`).join(\", \") : `${url} 1x, ${make().dpr(2).url()} 2x`;\n // A pixel width is the author's size for THIS image, so it also goes on as a style (a site rule\n // like `img { width: 100% }` beats a bare attribute), capped at the column it sits in. The focal\n // point rides as object-position, inert unless the site's CSS sets object-fit.\n const css: Record<string, string> = {\n ...(width ? { width: `${width}px`, maxWidth: \"100%\", height: \"auto\" } : {}),\n ...(hasFocal ? { objectPosition: objectPosition({ x: fx, y: fy }) } : {}),\n };\n const alt = opts.alt ?? (typeof asset.altText === \"string\" ? asset.altText : typeof asset.alt === \"string\" ? asset.alt : \"\");\n return { src: url, srcset, alt, css };\n}\n\nexport interface ImageAttrs {\n src: string;\n srcset: string;\n alt: string;\n loading: \"lazy\" | \"eager\";\n sizes?: string;\n width?: number;\n height?: number;\n style?: string;\n \"data-bcms-field\"?: string;\n \"data-bcms-kind\"?: \"image\";\n}\n\n/**\n * The `<img>` attributes for an image value, the same markup as every `<BcmsImage>`. Given `path`,\n * the image declares its field, so the editor binds it and a publish writes the new picture in:\n *\n * <img {...imageAttrs(page.hero.image, { path: \"hero.image\", sizes: \"100vw\" })} class=\"hero\" />\n */\nexport function imageAttrs(src: Parameters<typeof imageCore>[0], opts: ImageOptions = {}): ImageAttrs {\n const { src: url, srcset, alt, css } = imageCore(src, opts);\n const style = cssText(css);\n return {\n src: url,\n srcset,\n alt,\n loading: opts.loading ?? \"lazy\",\n ...(opts.sizes ? { sizes: opts.sizes } : {}),\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n ...(style ? { style } : {}),\n ...(opts.path ? { \"data-bcms-field\": opts.path, \"data-bcms-kind\": \"image\" as const } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAa;AAAA,EACxB,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,gBAAgB;AAAA,EACh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,OAAO,YAAY,QAAQ,MAAM,QAAQ,OAAO,CAAC;AAAA,IAC1D,MAAM,OAAO,SAAS;AACpB,iBAAW;AACX,YAAM,QAAQ,UAAU,MAAM,QAAQ,OAAO,IAAI;AACjD,aAAO,aAAa;AAAA,QAClB,QAAQ,OAAO;AAAA,QACf,WAAW,OAAO;AAAA,QAClB,WAAW,OAAO;AAAA,QAClB,GAAI,QAAQ,EAAE,aAAa,UAAmB,cAAc,MAAM,IAAI,CAAC;AAAA,MACzE,CAAC;AAAA,IACH;AAAA,IACA,MAAM,SAAS,MAAM,WAAW,SAAS,MAAM;AAG7C,YAAM,YAAY,OAAO;AACzB,YAAM,SAAS,CAAC,GAAG,SAAS,GAAI,YAAY,CAAC,IAAK,CAAC,WAAW,CAAY;AAC1E,UAAI,OAAO,SAAS,KAAK,CAAC,WAAW;AACnC,YAAI,CAAC,OAAQ,SAAQ,KAAK,IAAI,QAAQ,OAAO,KAAK,MAAM,MAAM,CAAC,4CAA4C;AAC3G,iBAAS;AACT,eAAO;AAAA,MACT;AACA,YAAM,eAAe,UAAU,MAAM,QAAQ,OAAO,IAAI;AACxD,aAAO,cAAc,EAAE,QAAQ,OAAO,QAAQ,WAAW,MAAM,OAAO,WAAW,cAAc,OAAO,MAAM,OAAO,OAAO,MAAM,MAAM,CAAC;AAAA,IACzI;AAAA,IACA,aAAa,OAAO,YAAY;AAC9B,iBAAW;AACX,aAAO,oBAAoB,SAAS,EAAE,QAAQ,OAAO,QAAQ,OAAO,CAAC;AAAA,IACvE;AAAA,IACA,cAAc;AAAA,EAChB;AACF;","names":["import_types"]}
1
+ {"version":3,"sources":["../src/sections.ts","../src/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/config.ts","../src/bindings.ts"],"sourcesContent":["/// <reference lib=\"dom\" />\n/**\n * A published page's sections as server-rendered HTML, for a front end that renders its own\n * document (SvelteKit, Nuxt, any server): the hosted renderer's markup, its scoped stylesheet and\n * the runtime its forms, sliders and tabs need (`GET /api/v1/sites/fragment/:projectId/:slug`).\n * One renderer for every site, so the markup is the hosted site's and the editor's.\n */\nimport { BetterCMSError, ErrorCodes } from \"./errors.js\";\nimport { createClient, type BetterCMSReadClient } from \"./read-client.js\";\nimport { resolveBcmsConfig, type BcmsSiteConfig, type BcmsSiteOptions } from \"./config.js\";\nimport { draftDisableResponse, draftEnableResponse, draftTokenFrom } from \"./draft.js\";\nimport { RESPONSIVE_CSS } from \"@bettercms-ai/types\";\nimport { sectionRootAttrs } from \"./bindings.js\";\n\n/**\n * One thing a page that draws its own sections renders, in order: one of the page's own sections\n * (`slot`, with the CMS placement that names it) or a CMS block, drawn by the hosted renderer.\n */\nexport type SectionsFragmentItem =\n | { slot: string; block: { id: string; style?: Record<string, unknown> } | null }\n | { id: string; html: string };\n\nexport interface SectionsFragment {\n html: string;\n css: string;\n scripts: string;\n /**\n * The page in plan order (`planSections`, as `<BcmsSections>` renders it): the `slots` the fetch\n * named, each with its placement, and the CMS blocks between them. Absent from an older API.\n */\n items?: SectionsFragmentItem[];\n}\n\n/**\n * Fetch a page's sections (`home` is `/`). Null when the page is not published.\n *\n * `entry`: a collection's item template drawn for one of its entries (`blog/[slug]` → `slug` is the\n * collection page, `entry` the post): the collection's list, its CMS blocks filled with that entry.\n */\nexport async function fetchSections(\n opts: { apiUrl: string; projectId: string; slug: string; fetch?: typeof fetch; previewToken?: string | null; slots?: readonly string[]; entry?: string | null },\n): Promise<SectionsFragment | null> {\n const doFetch = opts.fetch ?? fetch;\n // With the editor session's preview token the answer is the page's DRAFT, every section and\n // value bound for the canvas; without it, the published page. `slots`: the sections the page\n // draws itself, in source order, which `items` interleaves with the CMS's.\n const params = [\n ...(opts.previewToken ? [`token=${encodeURIComponent(opts.previewToken)}`] : []),\n ...(opts.slots?.length ? [`slots=${opts.slots.map(encodeURIComponent).join(\",\")}`] : []),\n ...(opts.entry ? [`entry=${encodeURIComponent(opts.entry)}`] : []),\n ];\n const query = params.length > 0 ? `?${params.join(\"&\")}` : \"\";\n const url = `${opts.apiUrl.replace(/\\/+$/, \"\")}/api/v1/sites/fragment/${encodeURIComponent(opts.projectId)}/${encodeURIComponent(opts.slug || \"home\")}${query}`;\n const res = await doFetch(url, { headers: { accept: \"application/json\" } });\n if (res.status === 404) return null;\n if (!res.ok) throw new BetterCMSError(`Sections for \"${opts.slug}\" could not be read (${res.status})`, res.status, res.status === 403 ? ErrorCodes.FORBIDDEN : ErrorCodes.INTERNAL_ERROR);\n return ((await res.json()) as { data: SectionsFragment }).data;\n}\n\n/** The fragment as one string for `{@html}` / `v-html`: its stylesheet, its markup, its scripts. */\nexport function sectionsMarkup(fragment: SectionsFragment | null | undefined): string {\n if (!fragment) return \"\";\n return `<style>${fragment.css}</style>${fragment.html}${fragment.scripts}`;\n}\n\n/**\n * What a page that draws its own sections loops over (`--sections` writes the loop): one item per\n * thing it renders, in the CMS page's order.\n *\n * - `slot`: one of the page's own sections. `root` goes on the section's own root element (the\n * placement's `data-bcms-block` and style, as `sectionRootAttrs` writes them); a section whose\n * root is a component, a list or a conditional sits in a box of ours carrying `box` instead,\n * `display:contents` while the placement has no style, as `<BcmsSections>` does in React.\n * - `slot: null`: a CMS block; `html` is the hosted renderer's markup for it, drawn inside\n * `<div data-bcms-rendered=\"platform\">`. The first carries the stylesheet, the last the runtime\n * of its forms, sliders and tabs.\n *\n * With no fragment, or one from an API that has no `items`, every slot renders in source order:\n * the page as it was written.\n */\nexport interface SectionItem {\n /** Unique in the list: the slot's name, or `block:<position>:<id>`. */\n key: string;\n slot: string | null;\n root: Record<string, string>;\n box: Record<string, string>;\n html: string;\n}\n\nexport function sectionItems(fragment: Pick<SectionsFragment, \"items\" | \"css\" | \"scripts\"> | null | undefined, slots: readonly string[], page: string): SectionItem[] {\n const planned: SectionsFragmentItem[] = fragment?.items ?? slots.map((slot) => ({ slot, block: null }));\n const items = planned.map((item, at): SectionItem => {\n if (\"slot\" in item) {\n if (!item.block) return { key: item.slot, slot: item.slot, root: {}, box: { style: \"display:contents\" }, html: \"\" };\n const { style, ...stamp } = sectionRootAttrs(item.block);\n const marks = { ...stamp, \"data-bcms-sections\": page } as Record<string, string>;\n const box = !style ? \"display:contents\" : /(^|;)display:/.test(style) ? style : `display:flow-root;${style}`;\n return { key: item.slot, slot: item.slot, root: style ? { ...marks, style } : marks, box: { ...marks, \"data-bcms-box\": \"\", style: box }, html: \"\" };\n }\n // The position too: an id-less block (or two of one id) must never share a key in a keyed loop.\n return { key: `block:${at}:${item.id}`, slot: null, root: {}, box: {}, html: item.html };\n });\n const drawn = items.filter((item) => item.slot === null);\n // A placed section hidden on a breakpoint needs the rule even where no CMS block brings the sheet.\n if (drawn.length === 0 && items.some((item) => item.root[\"data-bcms-hide\"])) {\n items.unshift({ key: \"block:bcms-responsive\", slot: null, root: {}, box: {}, html: `<style>${RESPONSIVE_CSS}</style>` });\n } else if (drawn.length > 0) {\n drawn[0]!.html = `<style>${fragment?.css ?? \"\"}</style>${drawn[0]!.html}`;\n drawn[drawn.length - 1]!.html += fragment?.scripts ?? \"\";\n }\n return items;\n}\n\n/**\n * The scripts the document held when this module loaded: the HTML parser ran each of them. An\n * app's bundle loads after the parse, so this is the server-rendered page's own scripts.\n * ponytail: a module that loads lazily after a client-side navigation would also count that\n * navigation's (never-run) scripts as parsed; mark them at hydration if a lazy loader ever needs it.\n */\nconst parsed: WeakSet<Element> | null = typeof document === \"undefined\" ? null : new WeakSet(Array.from(document.getElementsByTagName(\"script\")));\n\n/**\n * Run the scripts inside `root`. A server-rendered first load runs them itself; a client-side\n * navigation inserts the markup with innerHTML, where a <script> never runs, so the forms,\n * sliders and tabs of the new page would be dead. Each script runs once per element.\n */\nexport function runSectionScripts(root: Element): void {\n for (const old of Array.from(root.querySelectorAll(\"script\"))) {\n if (old.hasAttribute(\"data-bcms-ran\")) continue;\n // The server-rendered first load: the browser's parser already ran it. Only markup inserted\n // later (innerHTML, a client-side navigation) holds scripts that never ran.\n if (parsed?.has(old)) {\n old.setAttribute(\"data-bcms-ran\", \"\");\n continue;\n }\n const fresh = document.createElement(\"script\");\n for (const attr of Array.from(old.attributes)) fresh.setAttribute(attr.name, attr.value);\n fresh.setAttribute(\"data-bcms-ran\", \"\");\n fresh.textContent = old.textContent;\n old.replaceWith(fresh);\n }\n}\n\n\nexport interface BcmsSite {\n config: BcmsSiteConfig;\n /** The read client for a request: drafts while its draft cookie holds a valid token. */\n client(request?: Request): Promise<BetterCMSReadClient>;\n /** Whether the request previews drafts (its draft cookie holds a valid token). */\n isDraft(request: Request): Promise<boolean>;\n /**\n * A page's sections (`home` is `/`); pass the framework's `fetch` on the server. Pass the\n * request too and an editor session (its draft cookie) gets the draft, bound for the canvas.\n * `entry`: the collection page `slug`'s item template, drawn for that entry (a `[slug]` route).\n * Null without the API url, workspace or project: the page renders its own sections in source order.\n */\n sections(slug: string, fetchImpl?: typeof fetch, request?: Request, opts?: { slots?: readonly string[]; entry?: string | null }): Promise<SectionsFragment | null>;\n /** GET handler for the draft path the editor opens (`/api/draft`). */\n draftEnable(request: Request): Promise<Response>;\n /** GET handler that leaves draft mode. */\n draftDisable(request: Request): Response;\n}\n\n/**\n * Everything a server-rendered site needs from BetterCMS, built once from its settings: the\n * precedence every adapter shares (options, `<PREFIX>BCMS_*`, `BCMS_*`), the read client per\n * request, the sections fragment and the draft routes. The SvelteKit and Nuxt adapters are this\n * with their env prefix.\n */\nexport function createBcmsSite(\n options: BcmsSiteOptions & { env?: Record<string, string | undefined>; draftSecret?: string; prefixes: string[]; adapter: string },\n): BcmsSite {\n const env = options.env ?? {};\n const { config, missing } = resolveBcmsConfig({ options, env, prefixes: [...options.prefixes, \"\"] });\n /**\n * 🔴 MISSING SETTINGS FAIL AT FIRST USE, NEVER HERE. A site constructs this at import time\n * (`export const bcms = createBcms(…)`, the module `--sections` writes), so throwing here failed\n * every build and prerender that ran without the env, before a single page was asked for.\n */\n const named = (keys: readonly (\"apiUrl\" | \"workspace\" | \"projectId\")[]) =>\n keys.map((m) => `${options.prefixes[0]}BCMS_${m === \"apiUrl\" ? \"API_URL\" : m === \"workspace\" ? \"WORKSPACE\" : \"PROJECT_ID\"}`).join(\" and \");\n const configured = (): void => {\n if (missing.length > 0) throw new Error(`[${options.adapter}] Missing ${named(missing)}: set them, or pass them to createBcms().`);\n };\n let warned = false;\n const secret = options.draftSecret ?? env.BCMS_DRAFT_SECRET;\n const tokenOf = (request: Request) => draftTokenFrom(request.headers.get(\"cookie\"), secret);\n return {\n config,\n isDraft: async (request) => Boolean(await tokenOf(request)),\n async client(request) {\n configured();\n const token = request ? await tokenOf(request) : null;\n return createClient({\n apiUrl: config.apiUrl,\n workspace: config.workspace,\n projectId: config.projectId,\n ...(token ? { perspective: \"drafts\" as const, previewToken: token } : {}),\n });\n },\n async sections(slug, fetchImpl, request, opts) {\n // Unconfigured, the page renders its own sections in source order (`sectionItems(null, …)`):\n // a build without the env is a build of the site as written, and says so once.\n const projectId = config.projectId;\n const absent = [...missing, ...(projectId ? [] : ([\"projectId\"] as const))];\n if (absent.length > 0 || !projectId) {\n if (!warned) console.warn(`[${options.adapter}] ${named(absent)} not set: sections render in source order.`);\n warned = true;\n return null;\n }\n const previewToken = request ? await tokenOf(request) : null;\n return fetchSections({ apiUrl: config.apiUrl, projectId, slug, fetch: fetchImpl, previewToken, slots: opts?.slots, entry: opts?.entry });\n },\n draftEnable: async (request) => {\n configured();\n return draftEnableResponse(request, { apiUrl: config.apiUrl, secret });\n },\n draftDisable: draftDisableResponse,\n };\n}\n","import type { BetterCMSErrorCode } from \"@bettercms-ai/types\";\n\n/** Semantic error codes used by the SDK. */\nexport const ErrorCodes = {\n CONTENT_NOT_FOUND: \"CONTENT_NOT_FOUND\",\n UNAUTHORIZED: \"UNAUTHORIZED\",\n FORBIDDEN: \"FORBIDDEN\",\n RATE_LIMITED: \"RATE_LIMITED\",\n INTERNAL_ERROR: \"INTERNAL_ERROR\",\n VALIDATION_ERROR: \"VALIDATION_ERROR\",\n NETWORK_ERROR: \"NETWORK_ERROR\",\n ADMIN_NOT_IMPLEMENTED: \"ADMIN_NOT_IMPLEMENTED\",\n} as const;\n\nexport type ErrorCode = (typeof ErrorCodes)[keyof typeof ErrorCodes];\n\n/** Maps HTTP status codes to semantic error codes. */\nfunction statusToCode(status: number): BetterCMSErrorCode {\n if (status === 404) return ErrorCodes.CONTENT_NOT_FOUND;\n if (status === 401) return ErrorCodes.UNAUTHORIZED;\n if (status === 403) return ErrorCodes.FORBIDDEN;\n if (status === 429) return ErrorCodes.RATE_LIMITED;\n if (status >= 500) return ErrorCodes.INTERNAL_ERROR;\n if (status === 422) return ErrorCodes.VALIDATION_ERROR;\n return ErrorCodes.INTERNAL_ERROR;\n}\n\n/**\n * BetterCMSError — normalized SDK error with a semantic code.\n */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: BetterCMSErrorCode;\n /**\n * Raw machine-readable `code` from the response body (e.g. \"PROJECT_DELETED\"),\n * when the API supplies one. Distinct from `code` (which is derived from the\n * HTTP status), this lets callers branch on a specific server condition that\n * shares a status with others (e.g. 409 slug-conflict vs 409 project-deleted).\n */\n readonly bodyCode?: string;\n /**\n * Per-field validation messages from a 400 `{ errors: { field: message } }` body.\n * The backend returns validation failures in this shape (not `message`/`error`), so\n * without this the SDK collapsed every validation 400 to a bare \"Bad Request\" with no\n * hint which field or rule failed (FLO-474). Mirrors the forms client's `fieldErrors`.\n */\n readonly fieldErrors?: Record<string, string>;\n /**\n * The parsed response body, when there was one.\n *\n * Several refusals carry STRUCTURED detail that neither `message` nor `fieldErrors` can hold,\n * and which is the whole point of the refusal: a component publish 409s with the full\n * `readiness` tuple (what evidence is missing, whether a human still has to approve it) and\n * 422s with the `issues` naming the Layouts it would break. Collapsing those to a sentence\n * leaves a caller able to report that something failed and not what to do about it.\n */\n readonly body?: unknown;\n\n constructor(\n message: string,\n status: number,\n code: BetterCMSErrorCode,\n bodyCode?: string,\n fieldErrors?: Record<string, string>,\n body?: unknown,\n ) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n this.bodyCode = bodyCode;\n this.fieldErrors = fieldErrors;\n this.body = body;\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, BetterCMSError);\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n status: this.status,\n code: this.code,\n bodyCode: this.bodyCode,\n fieldErrors: this.fieldErrors,\n };\n }\n\n /**\n * Factory — creates a BetterCMSError from a failed fetch Response. Reads the body's\n * `message` (or `error`) for the human message and `code` for a machine-readable\n * condition surfaced as `bodyCode`. Validation failures arrive as `{ errors: {...} }`\n * (no `message`/`error`), so fall back to the first field error for the message and\n * expose the full map as `fieldErrors` (FLO-474).\n */\n static async from(res: Response): Promise<BetterCMSError> {\n let message = res.statusText || \"An error occurred\";\n let bodyCode: string | undefined;\n let fieldErrors: Record<string, string> | undefined;\n let code = statusToCode(res.status);\n let raw: unknown;\n try {\n const body = (await res.json()) as {\n message?: string;\n error?: string;\n code?: string;\n errors?: Record<string, string>;\n };\n if (body?.errors && typeof body.errors === \"object\") {\n fieldErrors = body.errors;\n code = ErrorCodes.VALIDATION_ERROR;\n }\n if (body?.message) message = body.message;\n else if (body?.error) message = body.error;\n else if (fieldErrors) {\n const [field, detail] = Object.entries(fieldErrors).find(\n ([, v]) => typeof v === \"string\" && v.length > 0,\n ) ?? [];\n if (field) message = `${field}: ${detail}`;\n }\n if (body?.code) bodyCode = body.code;\n raw = body;\n } catch {\n // ignore parse errors\n }\n return new BetterCMSError(message, res.status, code, bodyCode, fieldErrors, raw);\n }\n}\n","/**\n * Shared 429/503 backoff for every SDK client.\n *\n * ── Why this exists ─────────────────────────────────────────────────────────\n * The backend limiter (src/lib/ratelimit.ts, windowHit) is a FIXED 60-SECOND\n * WINDOW: 100 requests per workspace per endpoint, and a denial answers\n * `Retry-After: <seconds until the window resets>` — anything up to 60.\n *\n * Every client here used to climb a private ladder that topped out at 7 seconds\n * ([250,750,1500] in read-client, [1000,2000,4000] in admin/management) and none\n * of them read Retry-After. So all three retries landed INSIDE the same exhausted\n * window and a 429 was fatal roughly whenever it was thrown. The retry code looked\n * like resilience but could only ever recover from a denial raised in the final\n * seconds of a window.\n *\n * That is what failed customer builds: `action/fetch-content.mjs` spends ~65 of the\n * 100 `delivery-content-entries-list` slots pulling a large workspace, `npm run build`\n * starts seconds later in the SAME window, and the first per-route delivery read past\n * the ceiling killed the deploy with \"Too many requests. Please retry later.\"\n *\n * ── The rule ────────────────────────────────────────────────────────────────\n * Obey Retry-After when the server sends one, and let a single request outlast a\n * whole window. A build waiting 60s is slow; a build that dies is a broken product.\n */\n\n/** Statuses worth retrying. 429 = rate limited, 503 = limiter/backend unavailable. */\nexport const RETRY_STATUSES = [429, 503] as const;\n\n/** Retries after the first attempt. 3 retries × up to ~65s spans three full windows. */\nexport const MAX_RETRIES = 3;\n\n/**\n * Hard ceiling on a single wait, jitter included. Must exceed the limiter's 60s\n * window, or a denial raised at the very start of a window still cannot be waited\n * out — and must be finite, so a hostile or mis-set Retry-After cannot hang a build.\n */\nexport const MAX_DELAY_MS = 65_000;\n\n/** Fallback ladder when the server sends no Retry-After: 1s, 2s, 4s, 8s. */\nconst BASE_DELAY_MS = 1_000;\n\n/**\n * De-sync jitter, added to every wait.\n *\n * Deliberately a small FLAT amount, not a percentage. Requests denied by one window\n * only need to stop firing in the same millisecond — the server's counter serialises\n * them after that. A proportional jitter would add up to 15 seconds to a 60-second\n * wait for no benefit, and would push the total past MAX_DELAY_MS.\n */\nconst JITTER_MS = 250;\n\nexport function isRetryableStatus(status: number): boolean {\n return (RETRY_STATUSES as readonly number[]).includes(status);\n}\n\n/**\n * Parse `Retry-After`, which RFC 9110 allows in either form: delay-seconds\n * (\"47\") or an HTTP-date (\"Wed, 21 Oct 2015 07:28:00 GMT\"). Returns ms to wait,\n * or null when the header is absent or unparseable.\n */\nexport function retryAfterMs(res: Pick<Response, \"headers\">): number | null {\n const raw = res.headers?.get?.(\"retry-after\");\n if (!raw) return null;\n\n const seconds = Number(raw);\n if (Number.isFinite(seconds)) {\n return Math.min(Math.max(seconds, 0) * 1000, MAX_DELAY_MS);\n }\n\n const at = Date.parse(raw);\n if (!Number.isNaN(at)) {\n return Math.min(Math.max(0, at - Date.now()), MAX_DELAY_MS);\n }\n return null;\n}\n\n/**\n * How long to wait before retry `attempt` (0-based).\n *\n * Server instruction wins; otherwise exponential. Jitter is added in both cases:\n * when a build's requests are all denied by the same window they would otherwise\n * wake in lockstep at the reset and re-exhaust it immediately (thundering herd).\n */\nexport function backoffMs(attempt: number, res?: Pick<Response, \"headers\">): number {\n const fromServer = res ? retryAfterMs(res) : null;\n // Base is capped with the jitter's headroom already reserved, so the total never\n // exceeds MAX_DELAY_MS AND the jitter is never clamped away at the ceiling — which\n // would put every capped caller back in lockstep, the exact thing jitter prevents.\n const base = Math.min(fromServer ?? BASE_DELAY_MS * 2 ** attempt, MAX_DELAY_MS - JITTER_MS);\n // Jitter is ADDED, never subtracted: waking before the server's Retry-After elapses\n // just burns a retry on a window that has not reset.\n return base + Math.random() * JITTER_MS;\n}\n\nexport const sleep = (ms: number): Promise<void> =>\n new Promise((resolve) => setTimeout(resolve, ms));\n","/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n status: 302,\n headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": `${DRAFT_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0` },\n });\n}\n","/**\n * createClient — framework-agnostic typed read client for the Delivery API.\n *\n * Shared by @bettercms-ai/astro and @bettercms-ai/next so the fetch/typing/retry\n * logic lives in one place. Read-only; for schema authoring use the\n * Management client, for sessions use the Admin client.\n *\n * const client = createClient({ apiUrl, workspace, apiKey });\n * await client.getPage(\"home\");\n * await client.listEntries({ model: \"post\", perPage: 50 });\n */\nimport type {\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n DeliveredLayout,\n Perspective,\n} from \"@bettercms-ai/types\";\nimport { BetterCMSError } from \"./errors.js\";\nimport { MAX_RETRIES, backoffMs, isRetryableStatus, sleep } from \"./retry.js\";\nimport type { DeliveryForm } from \"./forms.js\";\nimport { BRANCH_SIGNATURE_HEADER } from \"./draft.js\";\n\nconst DEFAULT_TIMEOUT = 10_000;\n\nexport interface CreateClientOptions {\n /** Backend base, e.g. `https://api.bettercms.ai` (no trailing slash needed). */\n apiUrl: string;\n /** Workspace slug. */\n workspace: string;\n /** Delivery API key. Use a `content:read:draft` key for drafts. */\n apiKey?: string;\n /**\n * The project every read is addressed to. A workspace holds many projects whose slugs\n * collide (each has a `blog` model and a `home` page), so a site names its own; published\n * reads need no key for it. BetterCMS hosting supplies `PUBLIC_BCMS_PROJECT_ID`.\n */\n projectId?: string;\n /**\n * A content branch (its slug) to read instead of the live site, like a Sanity release\n * perspective: every read answers from the branch. Needs a `content:read:draft` key and a\n * `projectId`; a branch that is not open answers 404 (BRANCH_NOT_FOUND).\n */\n branch?: string;\n /**\n * `signBranchRead(branch, BCMS_BRANCH_SECRET)`: on a server BetterCMS hosts, reads the `branch`\n * with no draft key. `@bettercms-ai/astro` signs for you on a branch preview.\n */\n branchSignature?: string;\n /** `published` (default) or `drafts`. */\n perspective?: Perspective;\n /**\n * Preview-token JWT for token-based single-document draft reads via the\n * `/preview/:slug` endpoint. Only used when `perspective === \"drafts\"`.\n */\n previewToken?: string;\n /**\n * Embed invisible visual-editing provenance in draft reads, so a preview build can\n * deep-link each rendered value back to its editor. Requires `perspective: \"drafts\"`,\n * and then either a `previewToken` or a `content:read:draft` key. Ignored on published\n * reads — the payload must never reach a production build.\n *\n * **Defaults to `true` on `perspective: \"drafts\"`** (since 1.15.0). Provenance is the whole\n * reason the drafts perspective exists in a preview build, and an option nobody knew to pass\n * meant every such build rendered anonymous strings: the editor could bind them only by\n * guessing at their text. It stays OFF on every other perspective, unconditionally, so a\n * published build cannot acquire a payload by accident — pass `stega: false` to opt a draft\n * read out (a diff or a checksum over draft content is the case that wants it).\n */\n stega?: boolean;\n /** Per-attempt timeout in ms. Defaults to 10000. */\n timeout?: number;\n /**\n * Collapse identical GETs to one network round-trip for the life of this client.\n * Default false.\n *\n * Only correct where the content is a POINT-IN-TIME SNAPSHOT — i.e. a static build,\n * where every route renders from the same published dataset. `@bettercms-ai/astro`\n * turns this on automatically when Astro's `command === \"build\"` and never for `dev`,\n * SSR or the drafts perspective, where a repeat read must see the current row.\n *\n * A static build without it re-fetches the same nav/settings/collection once PER ROUTE.\n * That is what made a large site exhaust the delivery rate limit: hundreds of identical\n * requests, and `getPage()` re-scanning every page of the paginated list each time it is\n * called.\n */\n cache?: boolean;\n}\n\n/** A value a list filter compares against. */\ntype FilterValue = string | number | boolean;\ntype FilterOps = Partial<Record<\"eq\" | \"ne\" | \"gt\" | \"gte\" | \"lt\" | \"lte\" | \"contains\", FilterValue>> & { in?: FilterValue[] };\n\n/**\n * The delivery list's filter grammar as an object: `{ category: \"news\" }` is `filter[category]=news`,\n * `{ startsAt: { gte: \"2026-01-01\" } }` is `filter[startsAt][gte]=…`, `{ tags: [\"a\", \"b\"] }` is\n * `filter[tags][in]=a,b`. A content field needs `model`; `slug`, `status`, `publishedAt` and `locale`\n * do not. The server allowlists the fields (src/lib/delivery/list-query.ts) and 400s anything else.\n */\nexport type EntryFilter = Record<string, FilterValue | FilterValue[] | FilterOps | undefined>;\n\nexport interface ListEntriesOptions {\n /** Filter by content-model slug. */\n model?: string;\n page?: number;\n perPage?: number;\n /** Reference hydration depth (lists cap at 1). */\n depth?: 0 | 1;\n /** Projection — field names to return. */\n select?: string[];\n /** Field filters, ANDed. */\n filter?: EntryFilter;\n /** `\"-publishedAt\"` or `[\"startsAt\", \"title\"]`: a leading `-` sorts descending. Default: newest published first. */\n sort?: string | string[];\n}\n\nexport interface GetEntryOptions {\n depth?: 0 | 1 | 2;\n select?: string[];\n}\n\nexport interface ListPagesOptions {\n page?: number;\n perPage?: number;\n /** Only the page with this slug (the list's `?slug=`). */\n slug?: string;\n}\n\nexport interface BetterCMSReadClient {\n readonly perspective: Perspective;\n getEntry<T = Record<string, unknown>>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<DeliveryEntry<T>>;\n listEntries<T = Record<string, unknown>>(\n opts?: ListEntriesOptions,\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n getPage(slug: string): Promise<DeliveryPage | null>;\n listPages(opts?: ListPagesOptions): Promise<DeliveryList<DeliveryPage>>;\n /**\n * The workspace's reusable component definitions, for resolving `component` blocks.\n * Under `perspective: \"drafts\"` this is the DRAFT definition — what makes an SSR render\n * of a draft page look like the page the editor is showing.\n */\n listComponents(): Promise<DeliveryComponent[]>;\n /** Fetch the project-scoped Global Layout for the active perspective. */\n getLayout(): Promise<DeliveredLayout | null>;\n listForms(opts?: {\n projectId?: string;\n }): Promise<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>;\n /** Build a deterministic Next/cache tag for a resource. */\n tag(resource: \"entry\" | \"page\" | \"forms\", id?: string): string;\n}\n\n/**\n * `filter` and `sort` as the list route's params, in the order given: the same grammar the MCP's\n * `where` serialises to (packages/mcp/src/entry-query.ts).\n */\nfunction listQueryParams(filter?: EntryFilter, sort?: string | string[]): Record<string, string> {\n const text = (v: FilterValue | FilterValue[]) => (Array.isArray(v) ? v.join(\",\") : String(v));\n const out: Record<string, string> = {};\n for (const [field, cond] of Object.entries(filter ?? {})) {\n if (cond == null) continue;\n if (Array.isArray(cond)) out[`filter[${field}][in]`] = text(cond);\n else if (typeof cond === \"object\") {\n for (const [op, v] of Object.entries(cond)) if (v != null) out[`filter[${field}][${op}]`] = text(v);\n } else out[`filter[${field}]`] = text(cond);\n }\n const order = Array.isArray(sort) ? sort.join(\",\") : sort;\n if (order) out.sort = order;\n return out;\n}\n\n/**\n * Drop undefined and empty values, stringify the rest into a query string. An empty filter value\n * is kept, as createBetterCMS sends it: dropped, `filter: { author: [] }` would list every entry;\n * sent, the route answers it (an empty `in` list is a 400, list-query.ts).\n */\nfunction qs(params: Record<string, string | number | undefined>): string {\n const sp = new URLSearchParams();\n for (const [k, v] of Object.entries(params)) {\n if (v !== undefined && (v !== \"\" || k.startsWith(\"filter[\"))) sp.set(k, String(v));\n }\n const s = sp.toString();\n return s ? `?${s}` : \"\";\n}\n\n/**\n * Unwrap a `{ data: ... }` list/legacy envelope when present. A bare entry is\n * already the payload (it has `id`/`slug` and its own `data` field), so we only\n * unwrap when no payload markers are at the top level.\n */\nfunction unwrap<T>(json: unknown): T {\n if (json && typeof json === \"object\") {\n const o = json as Record<string, unknown>;\n const isPayload = \"id\" in o || \"slug\" in o || \"items\" in o;\n if (!isPayload && \"data\" in o) return o.data as T;\n }\n return json as T;\n}\n\n/**\n * The `entrySlug` claim of a preview-token JWT, UNVERIFIED.\n *\n * The backend is the signature authority — this read only decides WHICH url to call, and a\n * forged claim buys nothing: `/preview/:slug` re-verifies and 401s. Kept private to this file\n * (`@bettercms-ai/astro` has its own copy for the same reason: neither package may depend on\n * the other).\n */\nfunction tokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n return (JSON.parse(json) as { entrySlug?: string }).entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Per-URL request collapsing.\n *\n * Two jobs, both needed: coalesce requests that are IN FLIGHT (Astro renders routes\n * concurrently, so identical GETs overlap) and retain the ones that have COMPLETED\n * (routes render in batches, so the same GET recurs long after the first settled).\n *\n * Values are cloned on the way out. Callers get a fresh object graph, so a template that\n * sorts `items` in place — an easy thing to write and a brutal thing to debug — cannot\n * corrupt what every other route sees. Cloning costs memory bandwidth; the request it\n * replaces costs a network round-trip and a slot in the rate-limit window.\n *\n * A rejected request is never retained, so a transient failure does not become permanent.\n */\nfunction createRequestCache() {\n const inflight = new Map<string, Promise<unknown>>();\n const settled = new Map<string, unknown>();\n\n const copy = <T>(value: T): T =>\n typeof structuredClone === \"function\" ? structuredClone(value) : (JSON.parse(JSON.stringify(value)) as T);\n\n return async function collapse<T>(url: string, fetcher: () => Promise<T>): Promise<T> {\n if (settled.has(url)) return copy(settled.get(url) as T);\n\n const pending = inflight.get(url) as Promise<T> | undefined;\n if (pending) return copy(await pending);\n\n const run = (async () => {\n try {\n const value = await fetcher();\n settled.set(url, value);\n return value;\n } finally {\n inflight.delete(url);\n }\n })();\n inflight.set(url, run);\n return copy(await run);\n };\n}\n\nexport function createClient(options: CreateClientOptions): BetterCMSReadClient {\n const apiUrl = options.apiUrl.replace(/\\/+$/, \"\");\n const { workspace, apiKey, perspective = \"published\", previewToken } = options;\n const defaultProjectId = options.projectId;\n // Every delivery read names the project and, for a branch preview, the branch.\n const branch = options.branch && options.branch !== \"main\" ? options.branch : undefined;\n const timeout = options.timeout ?? DEFAULT_TIMEOUT;\n const base = `${apiUrl}/api/v1/delivery/${workspace}`;\n\n const headers = (): Record<string, string> => {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (apiKey) h[\"X-API-Key\"] = apiKey;\n if (branch && options.branchSignature) h[BRANCH_SIGNATURE_HEADER] = options.branchSignature;\n return h;\n };\n\n // Drafts must never be collapsed even if a caller asks: a preview surface re-reads to\n // see the edit that just happened, and serving it a retained copy would show stale content.\n const collapse =\n options.cache && perspective === \"published\" ? createRequestCache() : undefined;\n\n const fetchJSON = <T>(url: string): Promise<T> =>\n collapse ? collapse(url, () => request<T>(url)) : request<T>(url);\n\n async function request<T>(url: string): Promise<T> {\n let lastError: unknown;\n for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeout);\n try {\n const res = await globalThis.fetch(url, {\n headers: headers(),\n signal: controller.signal,\n });\n clearTimeout(timer);\n if (res.ok) return (await res.json()) as T;\n\n const retryable = attempt < MAX_RETRIES && isRetryableStatus(res.status);\n if (!retryable) throw await BetterCMSError.from(res);\n // Honour Retry-After: the limiter's window is up to 60s, far longer than\n // any fixed ladder, so the server's own number is the only one that works.\n await sleep(backoffMs(attempt, res));\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new BetterCMSError(\"Request timeout\", 408, \"NETWORK_ERROR\");\n }\n if (err instanceof BetterCMSError) throw err;\n lastError = err;\n if (attempt < MAX_RETRIES) {\n await sleep(backoffMs(attempt));\n continue;\n }\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n }\n throw lastError ?? new BetterCMSError(\"Unreachable\", 0, \"NETWORK_ERROR\");\n }\n\n const draft = perspective === \"drafts\";\n /**\n * Resolved ONCE, here, so the three call sites below cannot drift apart — they did exactly\n * that before (`options.stega` alone on the preview branch, `draft && options.stega` on the\n * other two), and a default expressed three times is a default that will eventually be two.\n * `??` and not `||`: an explicit `stega: false` on a draft read must win.\n */\n const stega = options.stega ?? draft;\n\n return {\n perspective,\n\n async getEntry<T = Record<string, unknown>>(slug: string, opts?: GetEntryOptions) {\n // Token-based draft reads go through the dedicated preview endpoint.\n // Without a token the drafts perspective is served by delivery itself, which needs\n // to be TOLD — `?perspective=draft` (honoured only for a `content:read:draft` key).\n // Until this branch sent it, `perspective: \"drafts\"` was silently inert here, and\n // with it `stega`, so a static build could never obtain provenance without minting\n // a preview token per entry.\n // The token names ONE entry (as on getPage below): any other slug reads delivery, or the\n // preview endpoint 404s the post list, related posts and nav a draft page also renders.\n const url =\n draft && previewToken && tokenSlug(previewToken) === slug\n ? `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n stega: stega ? \"1\" : undefined,\n })}`\n : `${base}/content-entries/${encodeURIComponent(slug)}${qs({\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryEntry<T>>(await fetchJSON(url));\n },\n\n async listEntries<T = Record<string, unknown>>(opts?: ListEntriesOptions) {\n const url = `${base}/content-entries${qs({\n model: opts?.model,\n page: opts?.page,\n perPage: opts?.perPage,\n depth: opts?.depth,\n select: opts?.select?.join(\",\"),\n ...listQueryParams(opts?.filter, opts?.sort),\n perspective: draft ? \"draft\" : undefined,\n stega: draft && stega ? \"1\" : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryEntry<T>>>(await fetchJSON(url));\n },\n\n async getPage(slug: string) {\n // The token names ONE page, and for that page the preview endpoint is the only read\n // that returns the DRAFT block tree — the paginated delivery list is published-only, so\n // an SSR draft render would otherwise be the live structure with draft field values.\n // Any other slug falls through to the published scan, which is what a token for /about\n // rendering the site's nav or footer pages must keep doing.\n if (draft && previewToken && tokenSlug(previewToken) === slug) {\n const url = `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}${qs({\n token: previewToken,\n stega: stega ? \"1\" : undefined,\n })}`;\n const d = unwrap<Record<string, unknown>>(await fetchJSON(url));\n return {\n slug: d.slug as string,\n title: d.title as string,\n metaTitle: (d.metaTitle as string | null) ?? null,\n metaDescription: (d.metaDescription as string | null) ?? null,\n metaJson: (d.metaJson as DeliveryPage[\"metaJson\"]) ?? null,\n blocks: (d.blockJson as DeliveryPage[\"blocks\"]) ?? [],\n // C3: the DRAFT field styles, present only when the page styles a field.\n ...(d.fieldStyles ? { fieldStyles: d.fieldStyles as NonNullable<DeliveryPage[\"fieldStyles\"]> } : {}),\n updatedAt: (d.updatedAt as string | null) ?? null,\n publishedAt: (d.publishedAt as string | null) ?? null,\n } satisfies DeliveryPage;\n }\n // No dedicated single-page delivery endpoint: the list, narrowed to this slug. Unnarrowed, every\n // client-rendered page view read every page of the site (a converted React SPA's <BcmsSections>:\n // ~50 KB for one page's order). A server that ignores `slug` answers the whole list, scanned as before.\n let page = 1;\n for (;;) {\n const list = await this.listPages({ page, perPage: 100, slug });\n const found = list.items.find((p) => p.slug === slug);\n if (found) return found;\n if (!list.hasNextPage) return null;\n page += 1;\n }\n },\n\n async listPages(opts?: ListPagesOptions) {\n const url = `${base}/pages${qs({\n page: opts?.page,\n perPage: opts?.perPage,\n slug: opts?.slug,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryList<DeliveryPage>>(await fetchJSON(url));\n },\n\n async listComponents() {\n // Same shape as getLayout: `?perspective=draft` alone is the key-scoped path (the server\n // ignores it for a published key), and a preview token is the page-scoped one.\n const url = `${base}/components${qs({\n perspective: draft ? \"draft\" : undefined,\n token: draft ? previewToken : undefined,\n projectId: defaultProjectId, branch,\n })}`;\n return unwrap<DeliveryComponent[]>(await fetchJSON(url));\n },\n\n async getLayout() {\n const url = `${base}/layout${qs({ perspective: draft ? \"draft\" : undefined, projectId: defaultProjectId, branch })}`;\n try {\n return unwrap<DeliveredLayout>(await fetchJSON(url));\n } catch (error) {\n if (error instanceof BetterCMSError && error.status === 404) return null;\n throw error;\n }\n },\n\n async listForms(opts?: { projectId?: string }) {\n const url = `${base}/forms${qs({\n projectId: opts?.projectId ?? defaultProjectId,\n branch,\n })}`;\n return unwrap<{ items: DeliveryForm[]; turnstileSiteKey: string | null }>(\n await fetchJSON(url),\n );\n },\n\n tag(resource, id) {\n return id ? `bcms:${workspace}:${resource}:${id}` : `bcms:${workspace}:${resource}`;\n },\n };\n}\n","/**\n * Where a site's BetterCMS settings come from, the same way on every framework: explicit options,\n * then `<PREFIX>BCMS_*` env (each framework exposes env to the browser under its own prefix:\n * `PUBLIC_` for Astro and SvelteKit, `NEXT_PUBLIC_` for Next, `VITE_` for Vite React,\n * `NUXT_PUBLIC_` for Nuxt), then the build snapshot `bettercms pull-content` writes.\n *\n * Pure: the adapter passes its env and reads the snapshot (this module touches no filesystem).\n */\n\nexport const DEFAULT_MEDIA_URL = \"https://cdn.bettercms.ai\";\n\nexport interface BcmsSiteOptions {\n apiUrl?: string;\n workspace?: string;\n projectId?: string;\n mediaUrl?: string;\n studioUrl?: string;\n}\n\nexport interface BcmsSiteConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n mediaUrl: string;\n studioUrl?: string;\n}\n\nexport interface ResolveBcmsConfigInput {\n options?: BcmsSiteOptions;\n env?: Record<string, string | undefined>;\n /** Env prefixes, first match wins: `[\"NEXT_PUBLIC_\", \"\"]` reads NEXT_PUBLIC_BCMS_API_URL, then BCMS_API_URL. */\n prefixes: string[];\n /** The build snapshot's identity, read only when options and env both miss. */\n snapshot?: () => { apiUrl?: string; workspace?: string; projectId?: string };\n}\n\n/** The resolved settings, and which essentials are missing (the adapter words the error). */\nexport function resolveBcmsConfig(input: ResolveBcmsConfigInput): { config: BcmsSiteConfig; missing: (\"apiUrl\" | \"workspace\")[] } {\n const env = input.env ?? {};\n const fromEnv = (name: string) => {\n for (const p of input.prefixes) {\n const v = env[`${p}BCMS_${name}`];\n if (v) return v;\n }\n return undefined;\n };\n let snap: ReturnType<NonNullable<ResolveBcmsConfigInput[\"snapshot\"]>> | undefined;\n const snapshot = () => (snap ??= input.snapshot?.() ?? {});\n const o = input.options ?? {};\n const config: BcmsSiteConfig = {\n apiUrl: (o.apiUrl ?? fromEnv(\"API_URL\") ?? snapshot().apiUrl ?? \"\").replace(/\\/+$/, \"\"),\n workspace: o.workspace ?? fromEnv(\"WORKSPACE\") ?? snapshot().workspace ?? \"\",\n projectId: o.projectId ?? fromEnv(\"PROJECT_ID\") ?? snapshot().projectId,\n mediaUrl: (o.mediaUrl ?? fromEnv(\"MEDIA_URL\") ?? DEFAULT_MEDIA_URL).replace(/\\/+$/, \"\"),\n studioUrl: o.studioUrl ?? fromEnv(\"STUDIO_URL\"),\n };\n const missing = ([\"apiUrl\", \"workspace\"] as const).filter((k) => !config[k]);\n return { config, missing };\n}\n","/**\n * The attributes a site's OWN markup spreads so the BetterCMS editor binds it: a page field, a\n * collection entry, a section root and its content column. Plain objects of string attributes\n * (the style is a CSS string), so they spread as they are in every template language:\n *\n * Astro / Svelte <h1 {...fieldAttrs(\"hero-title\", page.fieldStyles)}>…</h1>\n * Vue <h1 v-bind=\"fieldAttrs('hero-title', page.fieldStyles)\">…</h1>\n *\n * @bettercms-ai/astro, /sveltekit and /nuxt re-export these; @bettercms-ai/next keeps twins whose\n * `style` is a React style object.\n */\nimport imageUrlBuilder, {\n focalInCrop,\n normalizeImageCrop,\n normalizeImageFocal,\n objectPosition,\n type ImageFit,\n type ImageFormat,\n type ImageSource,\n} from \"@bettercms-ai/image-url\";\nimport { blockStyleToColumnCss, blockStyleToCss, fieldStyleCssText, hideOnAttr, sectionIdentityAttrs, type BlockStyle, type FieldStyle, type FieldStyles } from \"@bettercms-ai/types\";\n\n/**\n * C3 — `fieldAttrs(path, fieldStyles)`: the attributes a site's OWN element spreads to bind a PAGE\n * FIELD and apply that field's stored style, so the BetterCMS editor offers its width and spacing\n * handles and its Align / Size / Weight controls.\n *\n * ---\n * const page = await loadPage(Astro, \"home\");\n * ---\n * <h1 class=\"title\" {...fieldAttrs(\"hero-title\", page?.fieldStyles)}>{entry.data[\"hero-title\"]}</h1>\n *\n * `data-bcms-style` is the site's promise that \"this element's inline style is\n * `fieldStyleToCss(fieldStyles[path])`\". The editor offers a field's handles only on an element that\n * carries it: a handle on one that does not would paint the canvas and never ship. The marker is\n * present even when the field has no style (then there is no `style` attribute at all, byte for\n * byte the element it was): an unstyled field is the one an author is about to give its first edit.\n */\nexport interface FieldAttrs {\n \"data-bcms-field\": string;\n /** The marker's revision: \"2\" promises `size` (zoom) too. Section roots keep \"\". */\n \"data-bcms-style\": \"2\";\n /** `fieldStyleToCss(fieldStyles[path])` as a CSS string; absent when the field has no style. */\n style?: string;\n}\n\n/** The stored style for `path`, by OWN key only — a path like `constructor` never reads the prototype. */\nexport function fieldStyleOf(path: string, fieldStyles: FieldStyles | Record<string, unknown> | null | undefined): FieldStyle | undefined {\n if (!fieldStyles || typeof fieldStyles !== \"object\" || !Object.prototype.hasOwnProperty.call(fieldStyles, path)) return undefined;\n const style = (fieldStyles as Record<string, unknown>)[path];\n return style && typeof style === \"object\" ? (style as FieldStyle) : undefined;\n}\n\nexport function fieldAttrs(path: string, fieldStyles?: FieldStyles | Record<string, unknown> | null): FieldAttrs {\n const style = fieldStyleCssText(fieldStyleOf(path, fieldStyles));\n return { \"data-bcms-field\": path, \"data-bcms-style\": \"2\", ...(style ? { style } : {}) };\n}\n\n/**\n * P7 — `entryAttrs(entry)` and `entryField(entry, path)`: the attributes a site's OWN card spreads to\n * declare a collection ENTRY, so the editor binds it without guessing from the rendered text.\n *\n * <article {...entryAttrs(post)}><h3 {...entryField(post, \"title\")}>{post.fields.title}</h3></article>\n *\n * The field address is ABSOLUTE (`entry:<id>:<path>`). With a `transform` the value is shown\n * changed (a date formatted, text truncated), so it is declared as `data-bcms-entry-from`: the\n * editor knows where it is but cannot re-render it.\n */\nexport type EntryRef = { id?: string } | string;\nexport type EntryTransform = \"format\" | \"truncate\" | \"rendition\" | \"route\";\n/** One key is present: `data-bcms-entry-field`, or `data-bcms-entry-from` when transformed; none without an id. */\nexport interface EntryFieldAttrs {\n \"data-bcms-entry-field\"?: string;\n \"data-bcms-entry-from\"?: string;\n}\n\nfunction entryIdOf(entry: EntryRef): string | null {\n const id = typeof entry === \"string\" ? entry : entry?.id;\n return typeof id === \"string\" && id.trim() !== \"\" ? id : null;\n}\n\n/** An entry with no id (a snapshot written before ids were kept) renders unbound, never fails the build. */\nexport function entryAttrs(entry: EntryRef): { \"data-bcms-entry\"?: string } {\n const id = entryIdOf(entry);\n return id ? { \"data-bcms-entry\": id } : {};\n}\n\nexport function entryField(entry: EntryRef, path: string, opts?: { transform?: EntryTransform }): EntryFieldAttrs {\n const id = entryIdOf(entry);\n if (typeof path !== \"string\" || path.trim() === \"\") throw new Error(`entryField: no field path given for entry ${id ?? \"(no id)\"}`);\n if (!id) return {};\n const address = `entry:${id}:${path}`;\n return opts?.transform ? { \"data-bcms-entry-from\": `${address}|${opts.transform}` } : { \"data-bcms-entry-field\": address };\n}\n\n/**\n * C3/C4 — `sectionRootAttrs(block)`: the attributes a site's OWN section root spreads so the\n * BetterCMS editor offers that section's spacing and style handles.\n *\n * <section class=\"hero\" {...sectionRootAttrs(block)}>…</section>\n *\n * The editor shows those handles on a site-rendered page only when EVERY root the site stamps\n * with `data-bcms-block` also carries `data-bcms-style`, which is the site's promise that \"this\n * root's inline style is `blockStyleToCss(block.style)`\" — the same declarations `<BcmsBlocks>`\n * puts on its own wrapper. A root that stamps the block without applying its style would get a\n * capsule that paints the canvas and never ships, so the marker must travel with the style.\n *\n * The marker is present even when the style is EMPTY (then there is no `style` attribute at all):\n * an unstyled section is exactly the one an author is about to give its first spacing edit.\n */\nexport interface SectionRootBlock {\n id?: string | null;\n style?: BlockStyle | Record<string, unknown> | null;\n}\n\nexport interface SectionRootAttrs {\n /**\n * The section's Anchor ID (`style.anchor`), present only when one is set, so a root with its own\n * `id` keeps it otherwise. The section's CSS class (`style.cssClass`) is NOT spread: it would\n * replace the root's own class. Read it with `sectionIdentityAttrs(block.style).className` and\n * join it into the root's class list.\n */\n id?: string;\n \"data-bcms-block\"?: string;\n \"data-bcms-style\": \"\";\n /** `\"mobile tablet\"` when `style.hideOn` hides it there; the site ships `RESPONSIVE_CSS` for it. */\n \"data-bcms-hide\"?: string;\n /** `blockStyleToCss(block.style)` as a CSS string; absent when the block has no style. */\n style?: string;\n}\n\n/** `paddingTop` → `padding-top`, joined the way `<BcmsBlocks>` writes its wrapper's attribute. */\nfunction cssText(css: Record<string, string | number>): string {\n return Object.entries(css)\n .map(([k, v]) => `${k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}:${v}`)\n .join(\";\");\n}\n\nexport function sectionRootAttrs(block: SectionRootBlock | null | undefined): SectionRootAttrs {\n const css = blockStyleToCss((block?.style ?? undefined) as BlockStyle | undefined);\n const id = typeof block?.id === \"string\" && block.id !== \"\" ? block.id : undefined;\n const hide = hideOnAttr(block?.style);\n const anchor = sectionIdentityAttrs(block?.style).id;\n return {\n ...(anchor ? { id: anchor } : {}),\n ...(id !== undefined ? { \"data-bcms-block\": id } : {}),\n \"data-bcms-style\": \"\",\n ...(hide ? { \"data-bcms-hide\": hide } : {}),\n ...(css ? { style: cssText(css) } : {}),\n };\n}\n\nexport interface SectionColumnAttrs {\n \"data-bcms-column\": \"\";\n /** `blockStyleToColumnCss(block.style)` as a CSS string; absent when the section has no column. */\n style?: string;\n}\n\n/**\n * C3 — `sectionColumnAttrs(block)`: the attributes a site's own INNER container spreads so the\n * section's content WIDTH (`style.contentWidth`, placed by `contentAlign`) ships.\n *\n * <section {...sectionRootAttrs(block)}>\n * <div class=\"container\" {...sectionColumnAttrs(block)}>…</div>\n * </section>\n *\n * The width is the column BetterCMS draws as `.bcms-block-inner` inside the section's styled box —\n * never on the root itself, whose background must stay full-bleed. `data-bcms-column` is the\n * site's promise that this box's inline style is the column; the editor offers the width handle\n * on a site-rendered page only where every styled root holds one. Max-width plus left/right\n * margins, so the container keeps its own vertical margins and, with no column, its own width.\n */\nexport function sectionColumnAttrs(block: SectionRootBlock | null | undefined): SectionColumnAttrs {\n const css = blockStyleToColumnCss((block?.style ?? undefined) as BlockStyle | undefined);\n return { \"data-bcms-column\": \"\", ...(css ? { style: cssText(css) } : {}) };\n}\n\n/** The image facts a value or asset may carry beside its URL. */\ntype ImageFacts = { altText?: string | null; alt?: string | null; width?: number | null; height?: number | null; focalX?: number | null; focalY?: number | null };\n\nexport interface ImageOptions {\n /** The field this image renders, in the editor grammar (`cover`, `hero.image`). */\n path?: string;\n alt?: string;\n width?: number;\n height?: number;\n format?: ImageFormat;\n quality?: number;\n fit?: ImageFit;\n sizes?: string;\n loading?: \"lazy\" | \"eager\";\n /** Focal point override, 0–1. Normally omitted: the value and the asset carry their own. */\n focalX?: number | null;\n focalY?: number | null;\n /** Media host for a `src` that is only an asset id. Defaults to the platform's. */\n baseUrl?: string;\n}\n\n/** The widths a `sizes` image offers: phone to desktop, and never an upscale of the picture. */\nconst LADDER = [480, 768, 1080, 1440, 1920];\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" && Number.isFinite(v) ? v : undefined);\n\n/**\n * What every `<BcmsImage>` renders, computed once for all of them: the transform URL, a srcset\n * (a WIDTH ladder with `sizes` and no `width`, else 1x/2x), the alt (the value's `altText` unless\n * `alt` says otherwise) and the style declarations, camel-cased. The value's crop and focal point\n * are applied by image-url itself; a source-relative focal is re-expressed inside the crop.\n */\nexport function imageCore(src: ImageSource | (Exclude<ImageSource, string> & ImageFacts), opts: ImageOptions = {}) {\n const { width, height, format = \"webp\", quality, fit, sizes, focalX, focalY, baseUrl } = opts;\n const asset = (typeof src === \"object\" && src !== null ? src : {}) as Record<string, unknown>;\n const explicit = focalX != null || focalY != null;\n const stored =\n normalizeImageFocal(asset.focal) ??\n (num(asset.focalX) != null || num(asset.focalY) != null ? { x: num(asset.focalX) ?? 0.5, y: num(asset.focalY) ?? 0.5 } : null);\n const inWindow = stored ? focalInCrop(stored, normalizeImageCrop(asset.crop)) : null;\n const fx = explicit ? focalX : inWindow?.x;\n const fy = explicit ? focalY : inWindow?.y;\n const hasFocal = fx != null || fy != null;\n const builder = imageUrlBuilder({ baseUrl });\n const make = () => {\n let b = builder(src as ImageSource);\n if (width) b = b.width(width);\n if (height) b = b.height(height);\n if (format) b = b.format(format);\n if (quality) b = b.quality(quality);\n if (fit) b = b.fit(fit);\n if (hasFocal) b = b.focal(fx ?? 0.5, fy ?? 0.5);\n return b;\n };\n const url = make().url();\n const own = num(asset.width);\n const ladder = own ? [...new Set([...LADDER.filter((w) => w < own), Math.min(own, LADDER[LADDER.length - 1]!)])] : LADDER;\n const srcset = sizes && !width ? ladder.map((w) => `${make().width(w).url()} ${w}w`).join(\", \") : `${url} 1x, ${make().dpr(2).url()} 2x`;\n // A pixel width is the author's size for THIS image, so it also goes on as a style (a site rule\n // like `img { width: 100% }` beats a bare attribute), capped at the column it sits in. The focal\n // point rides as object-position, inert unless the site's CSS sets object-fit.\n const css: Record<string, string> = {\n ...(width ? { width: `${width}px`, maxWidth: \"100%\", height: \"auto\" } : {}),\n ...(hasFocal ? { objectPosition: objectPosition({ x: fx, y: fy }) } : {}),\n };\n const alt = opts.alt ?? (typeof asset.altText === \"string\" ? asset.altText : typeof asset.alt === \"string\" ? asset.alt : \"\");\n return { src: url, srcset, alt, css };\n}\n\nexport interface ImageAttrs {\n src: string;\n srcset: string;\n alt: string;\n loading: \"lazy\" | \"eager\";\n sizes?: string;\n width?: number;\n height?: number;\n style?: string;\n \"data-bcms-field\"?: string;\n \"data-bcms-kind\"?: \"image\";\n}\n\n/**\n * The `<img>` attributes for an image value, the same markup as every `<BcmsImage>`. Given `path`,\n * the image declares its field, so the editor binds it and a publish writes the new picture in:\n *\n * <img {...imageAttrs(page.hero.image, { path: \"hero.image\", sizes: \"100vw\" })} class=\"hero\" />\n */\nexport function imageAttrs(src: Parameters<typeof imageCore>[0], opts: ImageOptions = {}): ImageAttrs {\n const { src: url, srcset, alt, css } = imageCore(src, opts);\n const style = cssText(css);\n return {\n src: url,\n srcset,\n alt,\n loading: opts.loading ?? \"lazy\",\n ...(opts.sizes ? { sizes: opts.sizes } : {}),\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n ...(style ? { style } : {}),\n ...(opts.path ? { \"data-bcms-field\": opts.path, \"data-bcms-kind\": \"image\" as const } : {}),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGO,IAAM,aAAa;AAAA,EACxB,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,WAAW;AAAA,EACX,cAAc;AAAA,EACd,gBAAgB;AAAA,EAChB,kBAAkB;AAAA,EAClB,eAAe;AAAA,EACf,uBAAuB;AACzB;AAKA,SAAS,aAAa,QAAoC;AACxD,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,MAAI,UAAU,IAAK,QAAO,WAAW;AACrC,MAAI,WAAW,IAAK,QAAO,WAAW;AACtC,SAAO,WAAW;AACpB;AAKO,IAAM,iBAAN,MAAM,wBAAuB,MAAM;AAAA,EAC/B;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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AE,QAAQ,OAAO,QAAQ,OAAO,CAAC;AAAA,IACvE;AAAA,IACA,cAAc;AAAA,EAChB;AACF;","names":["import_types"]}
@@ -1,4 +1,4 @@
1
- import { B as BetterCMSReadClient } from './read-client-E9OHtQAW.cjs';
1
+ import { B as BetterCMSReadClient } from './read-client-DQhWuKf4.cjs';
2
2
  import { BcmsSiteConfig, BcmsSiteOptions } from './config.cjs';
3
3
  import '@bettercms-ai/types';
4
4
 
@@ -1,4 +1,4 @@
1
- import { B as BetterCMSReadClient } from './read-client-E9OHtQAW.js';
1
+ import { B as BetterCMSReadClient } from './read-client-DQhWuKf4.js';
2
2
  import { BcmsSiteConfig, BcmsSiteOptions } from './config.js';
3
3
  import '@bettercms-ai/types';
4
4
 
package/dist/sections.js CHANGED
@@ -208,10 +208,24 @@ function draftDisableResponse(request) {
208
208
 
209
209
  // src/read-client.ts
210
210
  var DEFAULT_TIMEOUT = 1e4;
211
+ function listQueryParams(filter, sort) {
212
+ const text = (v) => Array.isArray(v) ? v.join(",") : String(v);
213
+ const out = {};
214
+ for (const [field, cond] of Object.entries(filter ?? {})) {
215
+ if (cond == null) continue;
216
+ if (Array.isArray(cond)) out[`filter[${field}][in]`] = text(cond);
217
+ else if (typeof cond === "object") {
218
+ for (const [op, v] of Object.entries(cond)) if (v != null) out[`filter[${field}][${op}]`] = text(v);
219
+ } else out[`filter[${field}]`] = text(cond);
220
+ }
221
+ const order = Array.isArray(sort) ? sort.join(",") : sort;
222
+ if (order) out.sort = order;
223
+ return out;
224
+ }
211
225
  function qs(params) {
212
226
  const sp = new URLSearchParams();
213
227
  for (const [k, v] of Object.entries(params)) {
214
- if (v !== void 0 && v !== "") sp.set(k, String(v));
228
+ if (v !== void 0 && (v !== "" || k.startsWith("filter["))) sp.set(k, String(v));
215
229
  }
216
230
  const s = sp.toString();
217
231
  return s ? `?${s}` : "";
@@ -332,6 +346,7 @@ function createClient(options) {
332
346
  perPage: opts?.perPage,
333
347
  depth: opts?.depth,
334
348
  select: opts?.select?.join(","),
349
+ ...listQueryParams(opts?.filter, opts?.sort),
335
350
  perspective: draft ? "draft" : void 0,
336
351
  stega: draft && stega ? "1" : void 0,
337
352
  projectId: defaultProjectId,