@bettercms-ai/sdk 1.46.0 → 1.47.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/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/config.ts","../src/sections.ts","../src/bindings.ts"],"sourcesContent":["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","/// <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","/**\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":";AAGO,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,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AAI,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":[]}
1
+ {"version":3,"sources":["../src/errors.ts","../src/retry.ts","../src/draft.ts","../src/read-client.ts","../src/config.ts","../src/sections.ts","../src/bindings.ts"],"sourcesContent":["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 * `2` asks for the field-ref frame (since 1.47.0): each value carries `<target>:<id>:<path>`\n * and an open marker, so a value a library splits still resolves whole (`resolveStega`,\n * `markEditable`); what is framed is decided by the model's field types (a `select`, `slug`,\n * `link` or `date` never carries one); and a branch read's page blocks and the draft Layout are\n * framed too. About half the bytes of `true`, still not the default: a framed draft page measured\n * about twice its unframed size gzipped. Clean what you compare with `stegaClean`.\n */\n stega?: boolean | 2;\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 /** The `stega` query value a read sends: `2` only when asked for, `1` for `true`. */\n const stegaParam = stega === 2 ? \"2\" : stega ? \"1\" : undefined;\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: stegaParam,\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 ? stegaParam : 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 ? stegaParam : 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: stegaParam,\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 // Framed only on a branch, the draft lane of this list; never v1, which frames no blocks.\n stega: draft && stega === 2 ? \"2\" : undefined,\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, stega: draft && stega === 2 ? \"2\" : 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","/// <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","/**\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":";AAGO,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,EAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA;AAAA,EAET,YACE,SACA,QACA,MACA,UACA,aACA,MACA;AACA,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SA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C;AAAA,IACvE;AAAA,IACA,cAAc;AAAA,EAChB;AACF;","names":[]}
package/dist/seo.cjs CHANGED
@@ -24,6 +24,28 @@ __export(seo_exports, {
24
24
  resolveSeo: () => resolveSeo
25
25
  });
26
26
  module.exports = __toCommonJS(seo_exports);
27
+
28
+ // src/stega.ts
29
+ var ZERO = "\u200B";
30
+ var ONE = "\u200C";
31
+ var START = "\u2060";
32
+ var END = "\u2061";
33
+ var FRAMES = new RegExp(`${START}([${ZERO}${ONE}]*)${END}`, "g");
34
+ var STEGA_OPEN = `${START}${END}`;
35
+ function stegaClean(value) {
36
+ if (typeof value === "string") return value.includes(START) ? value.replace(FRAMES, "") : value;
37
+ if (Array.isArray(value)) {
38
+ const out = value.map((v) => stegaClean(v));
39
+ return out.some((v, i) => v !== value[i]) ? out : value;
40
+ }
41
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
42
+ const entries = Object.entries(value).map(([k, v]) => [k, stegaClean(v)]);
43
+ return entries.some(([k, v]) => v !== value[k]) ? Object.fromEntries(entries) : value;
44
+ }
45
+ return value;
46
+ }
47
+
48
+ // src/seo.ts
27
49
  function derivedCanonical({ siteUrl, path }) {
28
50
  if (!siteUrl || !path) return "";
29
51
  try {
@@ -113,7 +135,10 @@ function entrySeoInput(entry) {
113
135
  noindex: noindex === true
114
136
  };
115
137
  }
116
- function resolveSeo(page, defaults = {}, location = {}) {
138
+ function resolveSeo(framedPage, framedDefaults = {}, location = {}) {
139
+ const { title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex } = framedPage;
140
+ const page = stegaClean({ title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex });
141
+ const defaults = stegaClean(framedDefaults);
117
142
  const meta = page.metaJson ?? {};
118
143
  const title = page.metaTitle || page.title || "";
119
144
  const description = page.metaDescription || defaults.metaDescription || "";
package/dist/seo.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/seo.ts"],"sourcesContent":["/**\n * resolveSeo — framework-agnostic page-over-site SEO merge for headless consumers.\n *\n * The single source of truth for \"per-page meta layered over project defaults\",\n * mirroring the server renderer's `mergeSeoMeta` so `*.bettercms.site` and headless\n * sites (@bettercms-ai/next, @bettercms-ai/astro) emit identical <head> SEO. Pure: empty\n * inputs collapse to empty strings (\"omit the tag\"), never fabricated values.\n *\n * const seo = resolveSeo(page, siteDefaults);\n * // → { title, description, canonical, og, twitter, jsonLd }\n *\n * Next consumers map this to a `Metadata` via `buildMetadata` (@bettercms-ai/next);\n * Astro consumers read the fields straight into `<head>`.\n */\nimport type { DeliveryEntrySeo, PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\n\n/** Minimal page shape `resolveSeo` reads — a `DeliveryPage`/`BetterCMSPage` satisfies it. */\nexport interface SeoInput {\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n /** `\"home\"` makes the Automatic JSON-LD a WebSite, as the hosted renderer does. */\n slug?: string | null;\n /** Exclude from search engines. Surfaces as `ResolvedSeo.noindex` / `robots`. */\n noindex?: boolean | null;\n}\n\n/** Fully-resolved SEO values, page-over-site. Empty string ⇒ omit that tag. */\nexport interface ResolvedSeo {\n title: string;\n description: string;\n /**\n * Canonical URL — the page's own `canonical`, else `siteUrl` + `path` when both are given,\n * else \"\". Empty means the consumer must omit the tag: a RELATIVE canonical is worse than\n * none at all.\n */\n canonical: string;\n og: {\n title: string;\n description: string;\n type: string;\n image: string;\n url: string;\n };\n twitter: {\n card: string;\n title: string;\n description: string;\n image: string;\n site: string;\n };\n /**\n * JSON-LD nodes (site schema first, then the page's), already flattened + de-empted. The page's\n * part follows the renderer's precedence: Custom (`metaJson.schema`) > `metaJson.schemaType` >\n * Automatic (WebPage; WebSite on the home page).\n */\n jsonLd: Array<Record<string, unknown>>;\n /** True when the page is excluded from search engines (the renderer's `<meta name=\"robots\" content=\"noindex\">`). */\n noindex: boolean;\n /** `noindex` in the `{ index, follow }` shape Next's `Metadata.robots` takes. */\n robots: { index: boolean; follow: boolean };\n}\n\n/**\n * `siteUrl` + `path` → an absolute canonical, or \"\" when either is missing or unparseable.\n * Never returns a relative URL: a relative canonical is worse than no canonical.\n */\nfunction derivedCanonical({ siteUrl, path }: SeoLocation): string {\n if (!siteUrl || !path) return \"\";\n try {\n return new URL(path, siteUrl.endsWith(\"/\") ? siteUrl : `${siteUrl}/`).toString();\n } catch {\n return \"\";\n }\n}\n\n/** Flatten one-or-many JSON-LD into a node array, dropping empty objects. */\nfunction jsonLdNodes(\n schema: Record<string, unknown> | Array<Record<string, unknown>> | undefined,\n): Array<Record<string, unknown>> {\n if (!schema) return [];\n const arr = Array.isArray(schema) ? schema : [schema];\n const out: Array<Record<string, unknown>> = [];\n for (const node of arr) {\n if (!node || Object.keys(node).length === 0) continue;\n const graph = node[\"@graph\"];\n if (Array.isArray(graph)) {\n for (const child of graph) {\n if (child && typeof child === \"object\" && !Array.isArray(child) && Object.keys(child).length > 0) {\n out.push(child as Record<string, unknown>);\n }\n }\n continue;\n }\n out.push(node);\n }\n return out;\n}\n\n/*\n * Structured data for a page whose `metaJson.schema` is empty. A port of the page path of\n * `resolveStructuredData` in the backend (src/lib/seo/structured-data.ts, called from\n * `pageStructuredData` in src/lib/sites/render-page.ts), with `site.include: false` as the\n * Delivery API calls it: the site-wide schema is emitted separately, from `siteSchema`.\n * A page has no field data, so only the properties the page's own meta supplies are filled.\n * Keep in step with that file; the parity test imports it.\n */\nconst SCHEMA_TYPE_CHOICES = [\n \"WebPage\",\n \"AboutPage\",\n \"ContactPage\",\n \"CollectionPage\",\n \"Blog\",\n \"BlogPosting\",\n \"Article\",\n \"Product\",\n \"FAQPage\",\n \"Event\",\n \"Organization\",\n \"LocalBusiness\",\n] as const;\n\ntype PageProps = { name: string; description: string; image: string; url: string };\n\n/** Drop \"\", null and undefined so a node never carries a blank. */\nfunction compact(node: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(node).filter(([, value]) => value != null && value !== \"\"));\n}\n\nfunction schemaNode(type: string, { name, description, image, url }: PageProps): Record<string, unknown> {\n switch (type) {\n case \"BlogPosting\":\n case \"Article\":\n return compact({ \"@type\": type, headline: name, description, image, url, mainEntityOfPage: url });\n case \"Product\":\n case \"Event\":\n return compact({ \"@type\": type, name, description, image, url });\n case \"FAQPage\":\n case \"WebSite\":\n return compact({ \"@type\": type, name, description, url });\n case \"Organization\":\n return compact({ \"@type\": type, name, description, url, logo: image });\n default:\n // WebPage, AboutPage, ContactPage, CollectionPage, Blog, LocalBusiness\n return compact({ \"@type\": type, name, description, url, image });\n }\n}\n\n/** The page's own JSON-LD nodes: Custom > explicit `schemaType` > Automatic. */\nfunction pageJsonLd(\n page: SeoInput,\n meta: PageMetaJson,\n canonical: string,\n siteSchema: SiteSeoDefaults[\"siteSchema\"],\n): Array<Record<string, unknown>> {\n const custom = jsonLdNodes(meta.schema);\n if (custom.length > 0) return custom;\n const props: PageProps = {\n name: (page.metaTitle || page.title || \"\").trim(),\n description: (page.metaDescription || \"\").trim(),\n image: (meta.og?.image || \"\").trim(),\n url: canonical.trim(),\n };\n const schemaType = (meta as { schemaType?: unknown }).schemaType;\n if (typeof schemaType === \"string\" && (SCHEMA_TYPE_CHOICES as readonly string[]).includes(schemaType)) {\n return [schemaNode(schemaType, props)];\n }\n if (page.slug === \"home\") {\n // The home page IS the WebSite, unless the site-wide schema already describes it.\n return jsonLdNodes(siteSchema).length > 0 ? [] : [schemaNode(\"WebSite\", props)];\n }\n return [schemaNode(\"WebPage\", props)];\n}\n\n/**\n * A Delivery API entry as a `resolveSeo` input. The server already resolved the collection\n * template's `{{field}}` tokens for this entry and merged the entry's own SEO over it, so this is\n * a reshape, not a resolver:\n *\n * const entry = await bcms.getEntry(\"astro\");\n * const seo = resolveSeo(entrySeoInput(entry), siteDefaults, { siteUrl, path: `/tags/${entry.slug}` });\n * // seo.jsonLd holds the template's schema, resolved for this entry\n */\nexport function entrySeoInput(entry: { slug: string; seo?: DeliveryEntrySeo | null }): SeoInput {\n const { metaTitle, metaDescription, noindex, ...metaJson } = entry.seo ?? {};\n return {\n title: metaTitle || entry.slug,\n metaTitle: metaTitle ?? null,\n metaDescription: metaDescription ?? null,\n metaJson,\n noindex: noindex === true,\n };\n}\n\n/** Where this page lives, so a canonical can be derived when the page sets none. */\nexport interface SeoLocation {\n /** Absolute site origin, e.g. `https://acme.com`. Trailing slash optional. */\n siteUrl?: string;\n /** This page's path, e.g. `/about` or `/`. */\n path?: string;\n}\n\n/**\n * Merge a page's own SEO over the site defaults: page meta wins, then site defaults, then\n * sensible fallbacks.\n *\n * The CANONICAL is the one field that cannot be resolved from content alone, and getting this\n * wrong is silent. The hosted renderer (`mergeSeoMeta` in the backend) falls back to a canonical\n * it derives from the request's own origin and path — headless consumers have no request, so\n * they must pass `location`. Without it this returns \"\" and the caller ships no\n * `<link rel=\"canonical\">` and no `og:url`, exactly as it did before `location` existed.\n */\nexport function resolveSeo(\n page: SeoInput,\n defaults: SiteSeoDefaults = {},\n location: SeoLocation = {},\n): ResolvedSeo {\n const meta = page.metaJson ?? {};\n const title = page.metaTitle || page.title || \"\";\n const description = page.metaDescription || defaults.metaDescription || \"\";\n const ogImage = meta.og?.image || defaults.og?.image || defaults.ogImage || \"\";\n const ogTitle = meta.og?.title || title;\n const ogDescription = meta.og?.description || description;\n const twImage = meta.twitter?.image || ogImage;\n const canonical = meta.canonical || derivedCanonical(location);\n return {\n title,\n description,\n canonical,\n og: {\n title: ogTitle,\n description: ogDescription,\n type: meta.og?.type || defaults.og?.type || \"website\",\n image: ogImage,\n url: canonical,\n },\n twitter: {\n card: meta.twitter?.card || defaults.twitter?.card || (twImage ? \"summary_large_image\" : \"summary\"),\n title: meta.twitter?.title || ogTitle,\n description: meta.twitter?.description || ogDescription,\n image: twImage,\n site: defaults.twitterHandle || \"\",\n },\n jsonLd: [...jsonLdNodes(defaults.siteSchema), ...pageJsonLd(page, meta, canonical, defaults.siteSchema)],\n noindex: page.noindex === true,\n robots: { index: page.noindex !==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":[]}
1
+ {"version":3,"sources":["../src/seo.ts","../src/stega.ts"],"sourcesContent":["/**\n * resolveSeo — framework-agnostic page-over-site SEO merge for headless consumers.\n *\n * The single source of truth for \"per-page meta layered over project defaults\",\n * mirroring the server renderer's `mergeSeoMeta` so `*.bettercms.site` and headless\n * sites (@bettercms-ai/next, @bettercms-ai/astro) emit identical <head> SEO. Pure: empty\n * inputs collapse to empty strings (\"omit the tag\"), never fabricated values.\n *\n * const seo = resolveSeo(page, siteDefaults);\n * // → { title, description, canonical, og, twitter, jsonLd }\n *\n * Next consumers map this to a `Metadata` via `buildMetadata` (@bettercms-ai/next);\n * Astro consumers read the fields straight into `<head>`.\n */\nimport type { DeliveryEntrySeo, PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\nimport { stegaClean } from \"./stega.js\";\n\n/** Minimal page shape `resolveSeo` reads — a `DeliveryPage`/`BetterCMSPage` satisfies it. */\nexport interface SeoInput {\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n /** `\"home\"` makes the Automatic JSON-LD a WebSite, as the hosted renderer does. */\n slug?: string | null;\n /** Exclude from search engines. Surfaces as `ResolvedSeo.noindex` / `robots`. */\n noindex?: boolean | null;\n}\n\n/** Fully-resolved SEO values, page-over-site. Empty string ⇒ omit that tag. */\nexport interface ResolvedSeo {\n title: string;\n description: string;\n /**\n * Canonical URL — the page's own `canonical`, else `siteUrl` + `path` when both are given,\n * else \"\". Empty means the consumer must omit the tag: a RELATIVE canonical is worse than\n * none at all.\n */\n canonical: string;\n og: {\n title: string;\n description: string;\n type: string;\n image: string;\n url: string;\n };\n twitter: {\n card: string;\n title: string;\n description: string;\n image: string;\n site: string;\n };\n /**\n * JSON-LD nodes (site schema first, then the page's), already flattened + de-empted. The page's\n * part follows the renderer's precedence: Custom (`metaJson.schema`) > `metaJson.schemaType` >\n * Automatic (WebPage; WebSite on the home page).\n */\n jsonLd: Array<Record<string, unknown>>;\n /** True when the page is excluded from search engines (the renderer's `<meta name=\"robots\" content=\"noindex\">`). */\n noindex: boolean;\n /** `noindex` in the `{ index, follow }` shape Next's `Metadata.robots` takes. */\n robots: { index: boolean; follow: boolean };\n}\n\n/**\n * `siteUrl` + `path` → an absolute canonical, or \"\" when either is missing or unparseable.\n * Never returns a relative URL: a relative canonical is worse than no canonical.\n */\nfunction derivedCanonical({ siteUrl, path }: SeoLocation): string {\n if (!siteUrl || !path) return \"\";\n try {\n return new URL(path, siteUrl.endsWith(\"/\") ? siteUrl : `${siteUrl}/`).toString();\n } catch {\n return \"\";\n }\n}\n\n/** Flatten one-or-many JSON-LD into a node array, dropping empty objects. */\nfunction jsonLdNodes(\n schema: Record<string, unknown> | Array<Record<string, unknown>> | undefined,\n): Array<Record<string, unknown>> {\n if (!schema) return [];\n const arr = Array.isArray(schema) ? schema : [schema];\n const out: Array<Record<string, unknown>> = [];\n for (const node of arr) {\n if (!node || Object.keys(node).length === 0) continue;\n const graph = node[\"@graph\"];\n if (Array.isArray(graph)) {\n for (const child of graph) {\n if (child && typeof child === \"object\" && !Array.isArray(child) && Object.keys(child).length > 0) {\n out.push(child as Record<string, unknown>);\n }\n }\n continue;\n }\n out.push(node);\n }\n return out;\n}\n\n/*\n * Structured data for a page whose `metaJson.schema` is empty. A port of the page path of\n * `resolveStructuredData` in the backend (src/lib/seo/structured-data.ts, called from\n * `pageStructuredData` in src/lib/sites/render-page.ts), with `site.include: false` as the\n * Delivery API calls it: the site-wide schema is emitted separately, from `siteSchema`.\n * A page has no field data, so only the properties the page's own meta supplies are filled.\n * Keep in step with that file; the parity test imports it.\n */\nconst SCHEMA_TYPE_CHOICES = [\n \"WebPage\",\n \"AboutPage\",\n \"ContactPage\",\n \"CollectionPage\",\n \"Blog\",\n \"BlogPosting\",\n \"Article\",\n \"Product\",\n \"FAQPage\",\n \"Event\",\n \"Organization\",\n \"LocalBusiness\",\n] as const;\n\ntype PageProps = { name: string; description: string; image: string; url: string };\n\n/** Drop \"\", null and undefined so a node never carries a blank. */\nfunction compact(node: Record<string, unknown>): Record<string, unknown> {\n return Object.fromEntries(Object.entries(node).filter(([, value]) => value != null && value !== \"\"));\n}\n\nfunction schemaNode(type: string, { name, description, image, url }: PageProps): Record<string, unknown> {\n switch (type) {\n case \"BlogPosting\":\n case \"Article\":\n return compact({ \"@type\": type, headline: name, description, image, url, mainEntityOfPage: url });\n case \"Product\":\n case \"Event\":\n return compact({ \"@type\": type, name, description, image, url });\n case \"FAQPage\":\n case \"WebSite\":\n return compact({ \"@type\": type, name, description, url });\n case \"Organization\":\n return compact({ \"@type\": type, name, description, url, logo: image });\n default:\n // WebPage, AboutPage, ContactPage, CollectionPage, Blog, LocalBusiness\n return compact({ \"@type\": type, name, description, url, image });\n }\n}\n\n/** The page's own JSON-LD nodes: Custom > explicit `schemaType` > Automatic. */\nfunction pageJsonLd(\n page: SeoInput,\n meta: PageMetaJson,\n canonical: string,\n siteSchema: SiteSeoDefaults[\"siteSchema\"],\n): Array<Record<string, unknown>> {\n const custom = jsonLdNodes(meta.schema);\n if (custom.length > 0) return custom;\n const props: PageProps = {\n name: (page.metaTitle || page.title || \"\").trim(),\n description: (page.metaDescription || \"\").trim(),\n image: (meta.og?.image || \"\").trim(),\n url: canonical.trim(),\n };\n const schemaType = (meta as { schemaType?: unknown }).schemaType;\n if (typeof schemaType === \"string\" && (SCHEMA_TYPE_CHOICES as readonly string[]).includes(schemaType)) {\n return [schemaNode(schemaType, props)];\n }\n if (page.slug === \"home\") {\n // The home page IS the WebSite, unless the site-wide schema already describes it.\n return jsonLdNodes(siteSchema).length > 0 ? [] : [schemaNode(\"WebSite\", props)];\n }\n return [schemaNode(\"WebPage\", props)];\n}\n\n/**\n * A Delivery API entry as a `resolveSeo` input. The server already resolved the collection\n * template's `{{field}}` tokens for this entry and merged the entry's own SEO over it, so this is\n * a reshape, not a resolver:\n *\n * const entry = await bcms.getEntry(\"astro\");\n * const seo = resolveSeo(entrySeoInput(entry), siteDefaults, { siteUrl, path: `/tags/${entry.slug}` });\n * // seo.jsonLd holds the template's schema, resolved for this entry\n */\nexport function entrySeoInput(entry: { slug: string; seo?: DeliveryEntrySeo | null }): SeoInput {\n const { metaTitle, metaDescription, noindex, ...metaJson } = entry.seo ?? {};\n return {\n title: metaTitle || entry.slug,\n metaTitle: metaTitle ?? null,\n metaDescription: metaDescription ?? null,\n metaJson,\n noindex: noindex === true,\n };\n}\n\n/** Where this page lives, so a canonical can be derived when the page sets none. */\nexport interface SeoLocation {\n /** Absolute site origin, e.g. `https://acme.com`. Trailing slash optional. */\n siteUrl?: string;\n /** This page's path, e.g. `/about` or `/`. */\n path?: string;\n}\n\n/**\n * Merge a page's own SEO over the site defaults: page meta wins, then site defaults, then\n * sensible fallbacks.\n *\n * The CANONICAL is the one field that cannot be resolved from content alone, and getting this\n * wrong is silent. The hosted renderer (`mergeSeoMeta` in the backend) falls back to a canonical\n * it derives from the request's own origin and path — headless consumers have no request, so\n * they must pass `location`. Without it this returns \"\" and the caller ships no\n * `<link rel=\"canonical\">` and no `og:url`, exactly as it did before `location` existed.\n */\nexport function resolveSeo(\n framedPage: SeoInput,\n framedDefaults: SiteSeoDefaults = {},\n location: SeoLocation = {},\n): ResolvedSeo {\n // A draft read's strings carry stega frames; none may reach a <title>, a meta tag or JSON-LD. Only\n // what is read here is cleaned: a whole DeliveryPage passed in keeps its block tree unwalked.\n const { title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex } = framedPage;\n const page: SeoInput = stegaClean({ title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex });\n const defaults = stegaClean(framedDefaults);\n const meta = page.metaJson ?? {};\n const title = page.metaTitle || page.title || \"\";\n const description = page.metaDescription || defaults.metaDescription || \"\";\n const ogImage = meta.og?.image || defaults.og?.image || defaults.ogImage || \"\";\n const ogTitle = meta.og?.title || title;\n const ogDescription = meta.og?.description || description;\n const twImage = meta.twitter?.image || ogImage;\n const canonical = meta.canonical || derivedCanonical(location);\n return {\n title,\n description,\n canonical,\n og: {\n title: ogTitle,\n description: ogDescription,\n type: meta.og?.type || defaults.og?.type || \"website\",\n image: ogImage,\n url: canonical,\n },\n twitter: {\n card: meta.twitter?.card || defaults.twitter?.card || (twImage ? \"summary_large_image\" : \"summary\"),\n title: meta.twitter?.title || ogTitle,\n description: meta.twitter?.description || ogDescription,\n image: twImage,\n site: defaults.twitterHandle || \"\",\n },\n jsonLd: [...jsonLdNodes(defaults.siteSchema), ...pageJsonLd(page, meta, canonical, defaults.siteSchema)],\n noindex: page.noindex === true,\n robots: { index: page.noindex !== true, follow: true },\n };\n}\n","/**\n * Stega — embed invisible content-provenance into string values for visual\n * editing, then decode it in the browser overlay to open the right dashboard\n * editor. Uses zero-width characters so the payload is invisible and copy-safe.\n *\n * Scheme: `<clean text><START><bits…><END>` where each byte of the UTF-8 JSON\n * payload is 8 zero-width bits (ZERO=U+200B, ONE=U+200C), framed by START\n * (U+2060) and END (U+2061). The backend encodes draft responses; the overlay\n * decodes. Both sides MUST share this module's scheme.\n */\nconst ZERO = \"​\";\nconst ONE = \"‌\";\nconst START = \"⁠\";\nconst END = \"⁡\";\nconst FRAMES = new RegExp(`${START}([${ZERO}${ONE}]*)${END}`, \"g\");\n\n/**\n * Provenance describing where a string came from, for editor deep-linking. A `stega=2` payload\n * (`{t, id, f}`) is read into this same shape: `type` from `t`, `field` from `f`, and `ws`/`slug`\n * empty, because v2 does not carry them.\n */\nexport interface StegaPayload {\n /** Workspace slug (v1 only; \"\" from a v2 payload). */\n ws: string;\n type: \"entry\" | \"page\" | \"layout\" | \"component\";\n /** Entry/page id. */\n id: string;\n /** v1 only; \"\" from a v2 payload. */\n slug: string;\n /** Field key (or block id) the value belongs to. */\n field: string;\n /** The binding kind (`text`), where the encoder knows it. */\n kind?: string;\n}\n\nfunction toBits(s: string): string {\n const bytes = new TextEncoder().encode(s);\n let out = \"\";\n for (const b of bytes) {\n for (let i = 7; i >= 0; i--) out += (b >> i) & 1 ? ONE : ZERO;\n }\n return out;\n}\n\nfunction fromBits(bits: string): string {\n const bytes: number[] = [];\n for (let i = 0; i + 8 <= bits.length; i += 8) {\n let b = 0;\n for (let j = 0; j < 8; j++) b = (b << 1) | (bits[i + j] === ONE ? 1 : 0);\n bytes.push(b);\n }\n return new TextDecoder().decode(new Uint8Array(bytes));\n}\n\n/** Append an invisible provenance payload to a string (the v1 frame). */\nexport function encodeStega(clean: string, payload: StegaPayload): string {\n return `${clean}${START}${toBits(JSON.stringify(payload))}${END}`;\n}\n\nconst V2_TYPES = { e: \"entry\", p: \"page\", l: \"layout\", c: \"component\" } as const;\n\n/**\n * A frame's bits as a payload, or null when they are not JSON. A v2 payload is read into the v1\n * shape; any other JSON is returned as it decodes (v1, or the convert helper's source-map payload).\n */\nfunction payloadOf(bits: string): StegaPayload | null {\n try {\n const raw = JSON.parse(fromBits(bits)) as Record<string, unknown>;\n if (typeof raw.t === \"string\" && raw.t in V2_TYPES && typeof raw.id === \"string\" && typeof raw.f === \"string\") {\n return { ws: \"\", type: V2_TYPES[raw.t as keyof typeof V2_TYPES], id: raw.id, slug: \"\", field: raw.f };\n }\n return raw as unknown as StegaPayload;\n } catch {\n return null;\n }\n}\n\n/**\n * The field ref a payload addresses, `<target>:<id>:<path>`, the one address grammar every writer\n * reads; null for a payload that names no document (the convert helper's source map).\n */\nconst TARGETS = { entry: 1, page: 1, layout: 1, component: 1 };\nexport const stegaRef = (payload: StegaPayload): string | null =>\n typeof payload.type === \"string\" && payload.type in TARGETS && typeof payload.id === \"string\" && typeof payload.field === \"string\"\n ? `${payload.type}:${payload.id}:${payload.field}`\n : null;\n\n/**\n * Extract `{ clean, payload }` from a stega-encoded string (v1 or v2), or null if absent. `ref` is\n * the field ref, present when the payload names a document.\n */\nexport function decodeStega(value: string): { clean: string; payload: StegaPayload; ref?: string } | null {\n for (const frame of value.matchAll(FRAMES)) {\n // An empty frame is a v2 open marker, not a payload.\n if (!frame[1]) continue;\n const payload = payloadOf(frame[1]);\n if (!payload) return null;\n const ref = stegaRef(payload);\n return { clean: stegaClean(value), payload, ...(ref ? { ref } : {}) };\n }\n return null;\n}\n\n/**\n * A value's clean text and the field ref it carries (`entry:e_1:title`, `page:pg_1:hero.title`,\n * `layout:nav:brand`), or `ref: null` when it carries none. What a template uses when it needs both\n * the string to compare and the address to bind.\n */\nexport function stegaSplit(value: string): { clean: string; ref: string | null } {\n const decoded = decodeStega(value);\n return { clean: decoded?.clean ?? stegaClean(value), ref: decoded?.ref ?? null };\n}\n\n/**\n * Where a value BEGINS in a rendered page: an empty frame. The canvas brackets every bound\n * string with it and the payload frame, so a text node can be told inside a value from text\n * that merely precedes one. @see resolveStega\n */\nexport const STEGA_OPEN = `${START}${END}`;\n\n/**\n * A value with EVERY stega frame taken out, markers included, from every string in it at any depth\n * (arrays and plain objects). The SAME value back when it holds none. What a value passes through\n * before it is compared, used as a key or attribute, saved or published.\n */\nexport function stegaClean<T>(value: T): T {\n if (typeof value === \"string\") return (value.includes(START) ? value.replace(FRAMES, \"\") : value) as T;\n if (Array.isArray(value)) {\n const out = value.map((v) => stegaClean(v));\n return (out.some((v, i) => v !== value[i]) ? out : value) as T;\n }\n if (value && typeof value === \"object\" && Object.getPrototypeOf(value) === Object.prototype) {\n const entries = Object.entries(value).map(([k, v]) => [k, stegaClean(v)] as const);\n return (entries.some(([k, v]) => v !== (value as Record<string, unknown>)[k]) ? Object.fromEntries(entries) : value) as T;\n }\n return value;\n}\n\n/**\n * Remove every stega frame. An alias of {@link stegaClean}: it used to remove only the FIRST frame,\n * which left the payload behind on a `stega=2` value (an open marker, then the payload).\n */\nexport const stripStega = stegaClean;\n\n/** Each frame in `text`, in order: where it starts and ends, and its payload (null for an open marker or bits that are not one). */\nexport function stegaFrames(text: string): Array<{ index: number; end: number; payload: StegaPayload | null; open: boolean }> {\n return [...text.matchAll(FRAMES)].map((m) => ({ index: m.index, end: m.index + m[0].length, payload: m[1] ? payloadOf(m[1]) : null, open: !m[1] }));\n}\n\n/** The least of a DOM node this needs: a real `Node` satisfies it, and so does a test's plain object. */\nexport interface StegaNode {\n textContent: string | null;\n parentNode: StegaNode | null;\n childNodes?: ArrayLike<StegaNode>;\n}\n\n/**\n * Which value does this node render? Its payload and the nearest ancestor that holds the whole\n * value, or null when the node's text belongs to none.\n *\n * By CONTENT, not by attribute: a splitting library cuts a heading into one element per\n * character, a marquee clones its track, a component redraws its children, and the element a\n * build stamped is gone or copied. The string survives all of that, in order, across however\n * many text nodes: climbing from the clicked node, the first ancestor whose text holds a value\n * (its open marker to its payload frame) that overlaps the node is the value's extent.\n * Every copy of a value resolves to the same payload.\n */\nexport function resolveStega(node: StegaNode): { payload: StegaPayload; element: StegaNode } | null {\n let offset = 0;\n const length = node.textContent?.length ?? 0;\n for (let cur = node, up = node.parentNode; up; cur = up, up = up.parentNode) {\n for (const sibling of Array.from(up.childNodes ?? [])) {\n if (sibling === cur) break;\n offset += sibling.textContent?.length ?? 0;\n }\n const text = up.textContent ?? \"\";\n // Values nest (a field inside a field), so the open markers are a stack and a payload closes the last.\n const opens: number[] = [];\n for (const frame of stegaFrames(text)) {\n if (frame.open) {\n opens.push(frame.index);\n continue;\n }\n const open = opens.pop();\n // A value overlaps the node when it ends after the node starts and begins before the node\n // ends: the node that holds a value's first characters holds its open marker too.\n if (frame.end <= offset || open === undefined || open >= offset + length) continue;\n if (!frame.payload) break;\n return { payload: frame.payload, element: up };\n }\n }\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUA,IAAM,OAAO;AACb,IAAM,MAAM;AACZ,IAAM,QAAQ;AACd,IAAM,MAAM;AACZ,IAAM,SAAS,IAAI,OAAO,GAAG,KAAK,KAAK,IAAI,GAAG,GAAG,MAAM,GAAG,IAAI,GAAG;AAwG1D,IAAM,aAAa,GAAG,KAAK,GAAG,GAAG;AAOjC,SAAS,WAAc,OAAa;AACzC,MAAI,OAAO,UAAU,SAAU,QAAQ,MAAM,SAAS,KAAK,IAAI,MAAM,QAAQ,QA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;AAC7D,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA,IAAI;AAAA,MACF,OAAO;AAAA,MACP,aAAa;AAAA,MACb,MAAM,KAAK,IAAI,QAAQ,SAAS,IAAI,QAAQ;AAAA,MAC5C,OAAO;AAAA,MACP,KAAK;AAAA,IACP;AAAA,IACA,SAAS;AAAA,MACP,MAAM,KAAK,SAAS,QAAQ,SAAS,SAAS,SAAS,UAAU,wBAAwB;AAAA,MACzF,OAAO,KAAK,SAAS,SAAS;AAAA,MAC9B,aAAa,KAAK,SAAS,eAAe;AAAA,MAC1C,OAAO;AAAA,MACP,MAAM,SAAS,iBAAiB;AAAA,IAClC;AAAA,IACA,QAAQ,CAAC,GAAG,YAAY,SAAS,UAAU,GAAG,GAAG,WAAW,MAAM,MAAM,WAAW,SAAS,UAAU,CAAC;AAAA,IACvG,SAAS,KAAK,YAAY;AAAA,IAC1B,QAAQ,EAAE,OAAO,KAAK,YAAY,MAAM,QAAQ,KAAK;AAAA,EACvD;AACF;","names":[]}
package/dist/seo.d.cts CHANGED
@@ -94,6 +94,6 @@ interface SeoLocation {
94
94
  * they must pass `location`. Without it this returns "" and the caller ships no
95
95
  * `<link rel="canonical">` and no `og:url`, exactly as it did before `location` existed.
96
96
  */
97
- declare function resolveSeo(page: SeoInput, defaults?: SiteSeoDefaults, location?: SeoLocation): ResolvedSeo;
97
+ declare function resolveSeo(framedPage: SeoInput, framedDefaults?: SiteSeoDefaults, location?: SeoLocation): ResolvedSeo;
98
98
 
99
99
  export { type ResolvedSeo, type SeoInput, type SeoLocation, entrySeoInput, resolveSeo };
package/dist/seo.d.ts CHANGED
@@ -94,6 +94,6 @@ interface SeoLocation {
94
94
  * they must pass `location`. Without it this returns "" and the caller ships no
95
95
  * `<link rel="canonical">` and no `og:url`, exactly as it did before `location` existed.
96
96
  */
97
- declare function resolveSeo(page: SeoInput, defaults?: SiteSeoDefaults, location?: SeoLocation): ResolvedSeo;
97
+ declare function resolveSeo(framedPage: SeoInput, framedDefaults?: SiteSeoDefaults, location?: SeoLocation): ResolvedSeo;
98
98
 
99
99
  export { type ResolvedSeo, type SeoInput, type SeoLocation, entrySeoInput, resolveSeo };
package/dist/seo.js CHANGED
@@ -1,3 +1,23 @@
1
+ // src/stega.ts
2
+ var ZERO = "\u200B";
3
+ var ONE = "\u200C";
4
+ var START = "\u2060";
5
+ var END = "\u2061";
6
+ var FRAMES = new RegExp(`${START}([${ZERO}${ONE}]*)${END}`, "g");
7
+ var STEGA_OPEN = `${START}${END}`;
8
+ function stegaClean(value) {
9
+ if (typeof value === "string") return value.includes(START) ? value.replace(FRAMES, "") : value;
10
+ if (Array.isArray(value)) {
11
+ const out = value.map((v) => stegaClean(v));
12
+ return out.some((v, i) => v !== value[i]) ? out : value;
13
+ }
14
+ if (value && typeof value === "object" && Object.getPrototypeOf(value) === Object.prototype) {
15
+ const entries = Object.entries(value).map(([k, v]) => [k, stegaClean(v)]);
16
+ return entries.some(([k, v]) => v !== value[k]) ? Object.fromEntries(entries) : value;
17
+ }
18
+ return value;
19
+ }
20
+
1
21
  // src/seo.ts
2
22
  function derivedCanonical({ siteUrl, path }) {
3
23
  if (!siteUrl || !path) return "";
@@ -88,7 +108,10 @@ function entrySeoInput(entry) {
88
108
  noindex: noindex === true
89
109
  };
90
110
  }
91
- function resolveSeo(page, defaults = {}, location = {}) {
111
+ function resolveSeo(framedPage, framedDefaults = {}, location = {}) {
112
+ const { title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex } = framedPage;
113
+ const page = stegaClean({ title: pageTitle, metaTitle, metaDescription, metaJson, slug, noindex });
114
+ const defaults = stegaClean(framedDefaults);
92
115
  const meta = page.metaJson ?? {};
93
116
  const title = page.metaTitle || page.title || "";
94
117
  const description = page.metaDescription || defaults.metaDescription || "";