@bettercms-ai/next 0.10.1 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +11 -1
- package/dist/blocks.js +155 -35
- package/dist/blocks.js.map +1 -1
- package/dist/draft-bridge.d.ts +41 -0
- package/dist/draft-bridge.js +664 -0
- package/dist/draft-bridge.js.map +1 -0
- package/dist/index.d.ts +14 -5
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/visual-editing.d.ts +4 -2
- package/dist/visual-editing.js +1 -1
- package/dist/visual-editing.js.map +1 -1
- package/package.json +9 -4
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/draft-bridge.tsx","../src/blocks.tsx","../src/form.tsx","../src/bindings.ts"],"sourcesContent":["\"use client\";\n/**\n * BcmsDraftBridge — the site half of the visual editor's draft bridge (FLO-1178).\n *\n * Wrap your page's blocks in this instead of calling <BcmsBlocks> directly and the BetterCMS\n * visual editor can re-render your DRAFTS — structure included — with YOUR components and CSS,\n * so the canvas never falls back to the platform's approximate renderer for this site:\n *\n * import { BcmsDraftBridge } from \"@bettercms-ai/next/draft-bridge\";\n * <BcmsDraftBridge slug={slug} blocks={page.blocks} components={readComponents()} … />\n *\n * Standalone (not framed) it renders byte-for-byte what <BcmsBlocks> renders — the bridge\n * never wakes. Inside the editor, the EDITOR feeds the bridge over postMessage (Storyblok's\n * model): the site never fetches drafts itself, so no credentials ever enter the page.\n *\n * Protocol, all same-origin (the editor serves the site through a same-origin proxy):\n *\n * editor → site { type: \"bcms:bridge-init\" }\n * site → editor { type: \"bcms:bridge-ready\", slug }\n * editor → site { type: \"bcms:draft-doc\", slug, blocks, components? }\n *\n * The acceptance predicate has three parts, all required — (i) `event.origin` equals this\n * page's own origin, (ii) the sender IS the parent frame, (iii) a draft doc is accepted only\n * after this component's own init→ready handshake. A third-party page that iframes the live\n * site sits on a foreign origin, so every message fails (i): the bridge adds zero attack\n * surface to visitors. Draft content riding a push is the same trust tier the site already\n * renders from the CMS snapshot — the editor is the same author surface.\n *\n * Hydration-safe by construction: initial state IS the server-rendered snapshot; a draft doc\n * can only arrive after mount.\n */\nimport { useEffect, useState, type ReactElement } from \"react\";\nimport { BcmsBlocks, type BcmsBlocksProps } from \"./blocks.js\";\n\ntype Doc = { blocks: BcmsBlocksProps[\"blocks\"]; components?: BcmsBlocksProps[\"components\"] };\n\nexport function BcmsDraftBridge({\n slug,\n blocks,\n components,\n ...rest\n}: BcmsBlocksProps & { slug: string }): ReactElement {\n const [doc, setDoc] = useState<Doc>({ blocks, components });\n\n useEffect(() => {\n if (window.parent === window) return;\n let handshaken = false;\n const onMessage = (e: MessageEvent) => {\n if (e.origin !== window.location.origin) return;\n if (e.source !== window.parent) return;\n const d = e.data as { type?: unknown; slug?: unknown; blocks?: unknown; components?: unknown } | null;\n if (!d || typeof d !== \"object\") return;\n if (d.type === \"bcms:bridge-init\") {\n handshaken = true;\n window.parent.postMessage({ type: \"bcms:bridge-ready\", slug }, e.origin);\n return;\n }\n if (!handshaken) return;\n if (d.type === \"bcms:draft-doc\" && d.slug === slug && Array.isArray(d.blocks)) {\n setDoc({\n blocks: d.blocks as Doc[\"blocks\"],\n components: Array.isArray(d.components) ? (d.components as Doc[\"components\"]) : components,\n });\n }\n };\n window.addEventListener(\"message\", onMessage);\n return () => window.removeEventListener(\"message\", onMessage);\n }, [slug, components]);\n\n return <BcmsBlocks blocks={doc.blocks} components={doc.components} {...rest} />;\n}\n","\"use client\";\n\n/**\n * <BcmsBlocks> — render a BetterCMS page's block_json natively in React.\n *\n * Pass the `blocks` from a page (delivery API `/content/:slug` → `entry.blocks`)\n * plus the `forms` you read with `readForms()`. Every block type renders to plain,\n * class-driven markup (the host site owns the styling); a `form` block resolves its\n * `formId` against `forms` and renders `<BcmsForm>` inline exactly where the user\n * placed it in the page builder. This is the turnkey \"Webflow\" path — forms show up\n * wherever they were dropped on the page, with no manual wiring.\n *\n * Ships from its own \"use client\" entry (like <BcmsForm>) so it can be rendered from\n * a Next App Router Server Component without breaking the RSC boundary.\n */\n\nimport {\n cloneElement,\n isValidElement,\n useState,\n type CSSProperties,\n type ReactElement,\n type ReactNode,\n} from \"react\";\nimport { blockStyleToCss } from \"@bettercms-ai/types\";\nimport type {\n ContentBlock,\n HeadingBlock,\n TextBlock,\n ImageBlock,\n ButtonBlock,\n SpacerBlock,\n VideoBlock,\n ColumnsBlock,\n FormBlock,\n SectionBlock,\n NavbarBlock,\n FooterBlock,\n SliderBlock,\n TabsBlock,\n ComponentBlock,\n DeliveryComponent,\n} from \"@bettercms-ai/types\";\nimport type { DeliveryForm } from \"@bettercms-ai/sdk\";\nimport { componentInstanceAddresses } from \"@bettercms-ai/types\";\nimport { applyOverrides } from \"@bettercms-ai/ui/resolve\";\nimport { BcmsForm } from \"./form.js\";\n\nconst MAX_COMPONENT_DEPTH = 10;\n\nexport interface BcmsBlocksProps {\n /** A page's blocks (delivery API `/content/:slug` → `entry.blocks`). */\n blocks: ContentBlock[];\n /** Forms available to `form` blocks — from `readForms().forms`. */\n forms?: DeliveryForm[];\n /** Reusable components available to `component` blocks — from `readComponents()`. */\n components?: DeliveryComponent[];\n /** Turnstile site key — forwarded to `<BcmsForm>` for form blocks. */\n turnstileSiteKey?: string;\n /** API origin forwarded to `<BcmsForm>`. Defaults to the SDK default. */\n apiBase?: string;\n /** Class for the wrapping <div>. */\n className?: string;\n}\n\n/** Render a page's blocks. Unknown/empty blocks render nothing (fail-soft). */\nexport function BcmsBlocks({\n blocks,\n forms,\n components,\n turnstileSiteKey,\n apiBase,\n className,\n}: BcmsBlocksProps): ReactElement {\n const formsById = new Map((forms ?? []).map((f) => [f.id, f]));\n const componentsById = new Map((components ?? []).map((cmp) => [cmp.id, cmp]));\n const ctx: RenderCtx = { formsById, componentsById, turnstileSiteKey, apiBase, depth: 0, seen: new Set() };\n return (\n /**\n * 🔴 `data-bcms-page` marks THIS SUBTREE as ours to edit — the SDK's equivalent of the hosted\n * renderer's `<main class=\"bcms-page\">` (render-page.ts).\n *\n * The Visual Editor decides whether to show section controls by asking the page what it is.\n * Its only test was that hosted wrapper, which an SDK-rendered site never has — so every\n * headless site was treated as \"not ours\", and move/duplicate/delete/reorder stayed hidden\n * on pages that fully support them. Measured on a live SDK site: 34 blocks rendered,\n * 0 recognised.\n *\n * It must sit on the CONTAINER rather than be inferred from the blocks, so that a page with\n * NO blocks yet is still recognised — otherwise there is no way to add the first section,\n * which is exactly the state a new page starts in.\n */\n <div className={className} data-bcms-page=\"\">\n {blocks.map((block) => tagTopLevel(block, renderBlock(block, ctx)))}\n </div>\n );\n}\n\n/**\n * Stamp a TOP-LEVEL block's own id onto the element it rendered.\n *\n * The editor hit-tests `[data-bcms-block]` to find sections — for hover chrome, reorder targets,\n * drop indicators and per-section presence. Blocks already carried `bcms-block` CLASSES, which\n * look equivalent and are not: they are on every block at every depth and carry no id, so they\n * can identify neither which section you are pointing at nor which one to move.\n *\n * 🔴 `cloneElement`, NOT a wrapper `<div>`. The hosted renderer wraps because it assembles HTML\n * strings and has no other option; here an extra element would land inside the customer's own\n * layout, breaking `>` child selectors and any grid/flex parent that counts its children. This\n * adds an attribute and changes no structure.\n *\n * Only the top level is tagged, deliberately: a section is a top-level block, and tagging nested\n * ones would make a column's child look like a section you could drag out of its parent.\n */\nfunction tagTopLevel(block: ContentBlock, node: ReactNode): ReactNode {\n // A block that rendered nothing (unknown type, fail-soft) has nothing to stamp — and stamping\n // a fragment or string would throw.\n if (!isValidElement(node)) return node;\n return cloneElement(node as ReactElement<Record<string, unknown>>, {\n \"data-bcms-block\": block.id,\n });\n}\n\nimport { bind, bindProps } from \"./bindings.js\";\n\ninterface RenderCtx {\n formsById: Map<string, DeliveryForm>;\n componentsById: Map<string, DeliveryComponent>;\n turnstileSiteKey?: string;\n apiBase?: string;\n depth: number;\n seen: Set<string>;\n /**\n * Present only inside a component instance, where it is AUTHORITATIVE: it maps the\n * DEFINITION's `<blockId>__<prop>` to this instance's `<id>__overrides.<key>`. A prop the\n * definition does not declare resolves to nothing and is left unannotated, rather than\n * carrying a definition-scoped address that binds to no field.\n */\n fieldAddresses?: Map<string, string>;\n}\n\nfunction renderBlock(block: ContentBlock, ctx: RenderCtx): ReactNode {\n const node = renderBlockInner(block, ctx);\n const style = blockStyleToCss(block.style);\n if (!style || node == null) return node;\n // FLO-264: honor the block's bounded style tokens in the headless render too, so\n // @bettercms-ai/next output matches the builder canvas + hosted site.\n return (\n <div key={block.id} style={style as CSSProperties}>\n {node}\n </div>\n );\n}\n\nfunction renderBlockInner(block: ContentBlock, ctx: RenderCtx): ReactNode {\n switch (block.type) {\n case \"heading\":\n return renderHeading(block, ctx);\n // `richtext` and `text` carry the same payload and differ only in the authoring surface,\n // so delivery renders them identically — Astro (BcmsBlocks.astro) and the hosted renderer\n // (render-page.ts) both alias them. Next did not, so `richtext` fell to `default: null`\n // and a richtext block rendered NOTHING on a Next site: 200 OK, green build, blank region.\n case \"text\":\n case \"richtext\":\n return renderText(block as TextBlock, ctx);\n case \"image\":\n return renderImage(block, ctx);\n case \"button\":\n return renderButton(block, ctx);\n case \"spacer\":\n return renderSpacer(block);\n case \"video\":\n return renderVideo(block, ctx);\n case \"columns\":\n return renderColumns(block, ctx);\n case \"form\":\n return renderForm(block, ctx);\n case \"section\":\n return renderSection(block, ctx);\n case \"navbar\":\n return renderNavbar(block, ctx);\n case \"footer\":\n return renderFooter(block, ctx);\n case \"slider\":\n return <BcmsSlider key={block.id} block={block} ctx={ctx} />;\n case \"tabs\":\n return <BcmsTabs key={block.id} block={block} ctx={ctx} />;\n case \"component\":\n return renderComponent(block, ctx);\n default:\n return renderUnhandledBlock(block);\n }\n}\n\nfunction renderHeading({ id, props }: HeadingBlock, ctx: RenderCtx): ReactNode {\n const Tag = `h${props.level ?? 2}` as \"h1\" | \"h2\" | \"h3\";\n return (\n <Tag key={id} className=\"bcms-block bcms-block--heading\" {...bind(id, \"text\", \"text\", ctx)}>\n {props.text}\n </Tag>\n );\n}\n\nfunction renderText({ id, props }: TextBlock, ctx: RenderCtx): ReactNode {\n // `html` is sanitized server-side before storage.\n return (\n <div\n key={id}\n className=\"bcms-block bcms-block--text\"\n {...bind(id, \"html\", \"richtext\", ctx)}\n dangerouslySetInnerHTML={{ __html: props.html }}\n />\n );\n}\n\nfunction renderImage({ id, props }: ImageBlock, ctx: RenderCtx): ReactNode {\n const img = (\n <img\n src={props.src}\n alt={props.alt}\n width={props.width}\n height={props.height}\n loading=\"lazy\"\n // Heading/text/button have always been click-to-edit on the Visual Editor canvas because\n // they carry this attribute; the image block did not, so a block page's images were the\n // one thing you could only change from the dock. `kind=\"image\"` keeps it selection-only\n // (no contentEditable on an <img>) while letting the editor reflect a new src live.\n {...bind(id, \"src\", \"image\", ctx)}\n // `alt` rides the props lane: this <img> already carries the src binding and an element\n // cannot hold two addresses. It is also the one image property a screen-reader user\n // depends on, so leaving it dock-only made the canvas worse at the accessibility half.\n {...bindProps(id, [{ prop: \"alt\", kind: \"text\", attr: \"alt\", present: props.alt != null }], ctx)}\n />\n );\n if (!props.caption) {\n return (\n <figure key={id} className=\"bcms-block bcms-block--image\">\n {img}\n </figure>\n );\n }\n return (\n <figure key={id} className=\"bcms-block bcms-block--image\">\n {img}\n <figcaption {...bind(id, \"caption\", \"text\", ctx)}>{props.caption}</figcaption>\n </figure>\n );\n}\n\nfunction renderButton({ id, props }: ButtonBlock, ctx: RenderCtx): ReactNode {\n return (\n <a\n key={id}\n href={props.href}\n className={`bcms-block bcms-block--button bcms-button--${props.variant ?? \"primary\"}`}\n {...bind(id, \"text\", \"text\", ctx)}\n // A URL never takes a caret — typing one onto the page has nowhere to report a malformed\n // value — so it is addressed here and edited in the element toolbar.\n {...bindProps(id, [{ prop: \"href\", kind: \"url\", attr: \"href\", present: props.href != null }], ctx)}\n >\n {props.text}\n </a>\n );\n}\n\nfunction renderSpacer({ id, props }: SpacerBlock): ReactNode {\n return (\n <div\n key={id}\n className=\"bcms-block bcms-block--spacer\"\n style={{ height: props.height }}\n aria-hidden=\"true\"\n />\n );\n}\n\nfunction renderVideo({ id, props }: VideoBlock, ctx: RenderCtx): ReactNode {\n return (\n <video\n key={id}\n className=\"bcms-block bcms-block--video\"\n src={props.url}\n poster={props.poster}\n // A video has no text node at all, so it was the one block a click could not reach: no\n // binding meant no `data-node-id` and nothing to hit-test. Both its values are attributes,\n // so the props lane carries the whole block.\n {...bindProps(\n id,\n [\n { prop: \"url\", kind: \"url\", attr: \"src\", present: props.url != null },\n { prop: \"poster\", kind: \"url\", attr: \"poster\", present: props.poster != null },\n ],\n ctx,\n )}\n autoPlay={props.autoplay}\n loop={props.loop}\n controls\n />\n );\n}\n\nfunction renderColumns({ id, props }: ColumnsBlock, ctx: RenderCtx): ReactNode {\n return (\n <div\n key={id}\n className=\"bcms-block bcms-block--columns\"\n style={{\n display: \"grid\",\n gridTemplateColumns: `repeat(${props.columns.length || 1}, 1fr)`,\n gap: props.gap,\n }}\n >\n {props.columns.map((column, i) => (\n <div key={i} className=\"bcms-column\">\n {column.map((child) => renderBlock(child, ctx))}\n </div>\n ))}\n </div>\n );\n}\n\nfunction renderForm({ id, props }: FormBlock, ctx: RenderCtx): ReactNode {\n const form = ctx.formsById.get(props.formId);\n if (!form) return null; // form deleted or not delivered — render nothing\n return (\n <div key={id} className=\"bcms-block bcms-block--form\">\n <BcmsForm form={form} turnstileSiteKey={ctx.turnstileSiteKey} apiBase={ctx.apiBase} />\n </div>\n );\n}\n\nfunction renderSection({ id, props }: SectionBlock, ctx: RenderCtx): ReactNode {\n const inner = props.children.map((child) => renderBlock(child, ctx));\n return (\n <section\n key={id}\n className=\"bcms-block bcms-block--section\"\n style={{ background: props.background, padding: props.paddingY != null ? `${props.paddingY}px 0` : undefined }}\n >\n {/* 🔴 `bcms-section-inner` — the Astro package and the hosted renderer both class this\n wrapper; Next was the only lane that left it bare. That is not cosmetic: the wrapper\n is CONDITIONAL on `maxWidth`, so a host stylesheet that wants to reach a section's\n children has to target `> div`, which also matches every classed block that happens\n to render as a div (a columns grid, a text block) and restyles their internals. With\n the class there, one selector covers all three lanes and nothing reaches past it.\n Toggling `maxWidth` in the editor must not silently retune a section's rhythm. */}\n {props.maxWidth ? (\n <div className=\"bcms-section-inner\" style={{ maxWidth: props.maxWidth, margin: \"0 auto\" }}>{inner}</div>\n ) : (\n inner\n )}\n </section>\n );\n}\n\n/**\n * Every link is addressed individually, by index. This was the flagship \"nested under arrays\"\n * exclusion, on the grounds that the writer could not reach it — but `parseFieldPath` and\n * `setFieldPath` have walked N indices since FLO-949 and `setValue` takes any path. Only the\n * offer was missing, so a site's navigation was uneditable on the canvas while being perfectly\n * writable through the dock.\n */\nfunction renderNavbar({ id, props }: NavbarBlock, ctx: RenderCtx): ReactNode {\n return (\n <nav key={id} className=\"bcms-block bcms-block--navbar\">\n {props.logo?.src ? (\n <a className=\"bcms-navbar-logo\" href={props.logo.href ?? \"/\"}>\n <img\n src={props.logo.src}\n alt={props.logo.alt}\n {...bind(id, \"logo.src\", \"image\", ctx)}\n {...bindProps(id, [{ prop: \"logo.alt\", kind: \"text\", attr: \"alt\", present: props.logo.alt != null }], ctx)}\n />\n </a>\n ) : null}\n <div className=\"bcms-navbar-links\">\n {props.links.map((l, i) => (\n <a\n key={i}\n href={l.href}\n {...bind(id, `links[${i}].label`, \"text\", ctx)}\n {...bindProps(id, [{ prop: `links[${i}].href`, kind: \"url\", attr: \"href\", present: l.href != null }], ctx)}\n >\n {l.label}\n </a>\n ))}\n </div>\n {props.cta ? (\n <a\n className=\"bcms-button bcms-button--primary\"\n href={props.cta.href}\n {...bind(id, \"cta.text\", \"text\", ctx)}\n {...bindProps(id, [{ prop: \"cta.href\", kind: \"url\", attr: \"href\", present: props.cta.href != null }], ctx)}\n >\n {props.cta.text}\n </a>\n ) : null}\n </nav>\n );\n}\n\n/**\n * A footer link is the deepest addressable thing on a page: `columns[i].links[j].label`, two\n * indices. That is the shape the old grammar note called unaddressable, and the shape the ENTRY\n * lane still refuses — but the two are different problems. The entry cap is about resolving a\n * repeater row's `_id` identity; a block path is direct, so there is no identity to resolve.\n */\nfunction renderFooter({ id, props }: FooterBlock, ctx: RenderCtx): ReactNode {\n return (\n <footer key={id} className=\"bcms-block bcms-block--footer\">\n <div className=\"bcms-footer-cols\">\n {props.columns.map((col, i) => (\n <div key={i} className=\"bcms-footer-col\">\n {col.heading ? <h4 {...bind(id, `columns[${i}].heading`, \"text\", ctx)}>{col.heading}</h4> : null}\n <ul>\n {col.links.map((l, j) => (\n <li key={j}>\n <a\n href={l.href}\n {...bind(id, `columns[${i}].links[${j}].label`, \"text\", ctx)}\n {...bindProps(\n id,\n [{ prop: `columns[${i}].links[${j}].href`, kind: \"url\", attr: \"href\", present: l.href != null }],\n ctx,\n )}\n >\n {l.label}\n </a>\n </li>\n ))}\n </ul>\n </div>\n ))}\n </div>\n {props.copyright ? (\n <p className=\"bcms-footer-copy\" {...bind(id, \"copyright\", \"text\", ctx)}>\n {props.copyright}\n </p>\n ) : null}\n </footer>\n );\n}\n\n/**\n * 🔴 `...rest` is load-bearing, not tidiness. `tagTopLevel` stamps a top-level block by\n * `cloneElement`, which sets `data-bcms-block` as a PROP on this component — and a component\n * that does not spread it drops the attribute with no error and no warning. A top-level slider\n * or tabs block then renders perfectly and is invisible to the Visual Editor's section lane:\n * no move, no duplicate, no delete, no presence. Intrinsic elements do not have this failure\n * mode, which is why every other block type was fine and these two were not.\n */\nfunction BcmsSlider({ block, ctx, ...rest }: { block: SliderBlock; ctx: RenderCtx }): ReactElement {\n const { slides } = block.props;\n const [i, setI] = useState(0);\n const go = (n: number) => setI((n + slides.length) % (slides.length || 1));\n return (\n <div className=\"bcms-block bcms-block--slider\" style={{ position: \"relative\" }} {...rest}>\n {slides.map((s, idx) => (\n <div key={s.id} className=\"bcms-slide\" hidden={idx !== i}>\n {s.children.map((child) => renderBlock(child, ctx))}\n </div>\n ))}\n <button type=\"button\" className=\"bcms-slider-prev\" aria-label=\"Previous\" onClick={() => go(i - 1)}>\n ‹\n </button>\n <button type=\"button\" className=\"bcms-slider-next\" aria-label=\"Next\" onClick={() => go(i + 1)}>\n ›\n </button>\n </div>\n );\n}\n\n/** `...rest` for the same reason as <BcmsSlider> above — see its comment. */\nfunction BcmsTabs({ block, ctx, ...rest }: { block: TabsBlock; ctx: RenderCtx }): ReactElement {\n const { tabs } = block.props;\n const [active, setActive] = useState(0);\n return (\n <div className=\"bcms-block bcms-block--tabs\" {...rest}>\n <div className=\"bcms-tablist\" role=\"tablist\">\n {tabs.map((t, idx) => (\n <button\n key={t.id}\n role=\"tab\"\n type=\"button\"\n className=\"bcms-tab\"\n aria-selected={idx === active}\n onClick={() => setActive(idx)}\n {...bind(block.id, `tabs[${idx}].label`, \"text\", ctx)}\n >\n {t.label}\n </button>\n ))}\n </div>\n {tabs.map((t, idx) => (\n <div key={t.id} role=\"tabpanel\" className=\"bcms-tabpanel\" hidden={idx !== active}>\n {t.children.map((child) => renderBlock(child, ctx))}\n </div>\n ))}\n </div>\n );\n}\n\n/**\n * Missing-component ids already reported. Module-level so a page that places the same section\n * twenty times logs once, not twenty times — a wall of identical lines is skipped, and this\n * message has to be read.\n */\nconst warnedMissing = new Set<string>();\n\nfunction renderComponent({ id, props }: ComponentBlock, ctx: RenderCtx): ReactNode {\n const def = ctx.componentsById.get(props.componentId);\n if (!def) return renderMissingComponent(props.componentId, ctx);\n if (ctx.depth >= MAX_COMPONENT_DEPTH || ctx.seen.has(def.id)) return null; // cycle/depth guard\n const resolved = applyOverrides<ContentBlock>(def.blockJson, def.props ?? [], props.overrides ?? {});\n // The instance's own addresses replace the definition's for the whole subtree. Without this\n // every stamp inside a component named a block shared by every instance of it: an orphan on\n // one placement, and a duplicate that drops BOTH on two.\n const childCtx: RenderCtx = {\n ...ctx,\n depth: ctx.depth + 1,\n seen: new Set([...ctx.seen, def.id]),\n fieldAddresses: componentInstanceAddresses(id, def.props),\n };\n return (\n <div key={id} className=\"bcms-block bcms-block--component\">\n {resolved.map((child) => renderBlock(child, childCtx))}\n </div>\n );\n}\n\n/**\n * A `component` block whose definition was not delivered.\n *\n * 🔴 This used to be `return null // fail-soft`, and that comment was the bug. A page authored\n * as SECTIONS is a list of `component` blocks and nothing else, so \"fail-soft\" meant the entire\n * page body rendered as nothing while the build stayed green and the site answered 200 — what\n * remained on screen was the layout's own nav and footer. Two live sites were replaced by that\n * on 2026-08-18, and the only reason it was caught is that a human looked at the page.\n *\n * The near-universal cause is a host site that never passes `components` — the SDK's own README\n * example omitted it — so the message names the fix rather than the symptom.\n *\n * Still renders nothing in production: a placeholder box would be worse than a gap on a live\n * customer site. The console line ships in BOTH modes, because it is emitted during the build\n * and the build log is the one place a headless deploy can be inspected after the fact.\n */\nconst warnedUnhandled = new Set<string>();\n\n/**\n * A block type this renderer has no case for.\n *\n * `default: return null` is how `richtext` rendered NOTHING on a Next site for a whole release\n * — 200 OK, green build, blank region, no error anywhere. `collection` is in that state today:\n * it is delivered, the hosted renderer draws it, and this one silently drops it. Saying so out\n * loud does not implement the missing renderer, but it converts an invisible blank into a\n * message that names the type, which is the difference between a bug you find and one you ship.\n */\nfunction renderUnhandledBlock(block: ContentBlock): ReactNode {\n if (!warnedUnhandled.has(block.type)) {\n warnedUnhandled.add(block.type);\n // eslint-disable-next-line no-console\n console.warn(\n `[BcmsBlocks] block type \"${block.type}\" has no renderer here, so it rendered NOTHING. ` +\n `The hosted renderer draws it; this SDK does not yet.`,\n );\n }\n return null;\n}\n\nfunction renderMissingComponent(componentId: string, ctx: RenderCtx): ReactNode {\n if (!warnedMissing.has(componentId)) {\n warnedMissing.add(componentId);\n // eslint-disable-next-line no-console\n console.warn(\n `[BcmsBlocks] component \"${componentId}\" was not delivered, so this section rendered NOTHING.` +\n (ctx.componentsById.size === 0\n ? ` No components were passed at all — add components={readComponents()} to <BcmsBlocks>.`\n : ` ${ctx.componentsById.size} component(s) were passed but none match. It is probably still a DRAFT: publish it, then rebuild.`),\n );\n }\n if (process.env.NODE_ENV === \"production\") return null;\n return (\n <div\n className=\"bcms-block bcms-block--component-missing\"\n data-bcms-missing-component={componentId}\n style={{\n padding: \"12px 16px\",\n border: \"1px dashed #d4d4d8\",\n borderRadius: 8,\n color: \"#71717a\",\n font: \"500 13px/1.5 system-ui, -apple-system, sans-serif\",\n }}\n >\n Section <code>{componentId}</code> was not delivered.{\" \"}\n {ctx.componentsById.size === 0\n ? \"Pass components={readComponents()} to <BcmsBlocks>.\"\n : \"Publish the component, then rebuild.\"}\n </div>\n );\n}\n\n","\"use client\";\n\n/**\n * <BcmsForm> — render a BetterCMS form natively in React, the headless way.\n *\n * Pass a form straight from your content snapshot (`readSnapshot().forms[n]`) or\n * the delivery API. It renders real inputs (no iframe), handles conditional\n * `showIf` fields, URL-query prefill, the honeypot, an optional Turnstile widget,\n * and submits via `@bettercms-ai/sdk`'s `submitForm`. All visible markup is\n * unstyled and class-driven, so the host site owns the look.\n */\n\nimport { useEffect, useMemo, useState, type FormEvent, type ReactElement } from \"react\";\nimport {\n submitForm,\n shouldShowField,\n formInitialValues,\n asStringArray,\n toggleOption,\n type DeliveryForm,\n type DeliveryFormField,\n type FormValue,\n type FormValues,\n type FormSubmitError,\n} from \"@bettercms-ai/sdk\";\n\nconst TURNSTILE_SRC = \"https://challenges.cloudflare.com/turnstile/v0/api.js\";\n\n// Field type → native <input type>. Other types render their own element.\nconst INPUT_TYPES: Partial<Record<DeliveryFormField[\"type\"], string>> = {\n text: \"text\",\n email: \"email\",\n phone: \"tel\",\n url: \"url\",\n number: \"number\",\n date: \"date\",\n};\n\nexport interface BcmsFormProps {\n /** A form from your content snapshot or the delivery API. */\n form: DeliveryForm;\n /** API origin. Defaults to the SDK default (https://api.bettercms.ai). */\n apiBase?: string;\n /** Turnstile site key — needed to render the widget when `form.turnstileEnabled`. */\n turnstileSiteKey?: string;\n /** Called with the new submission id after a successful submit (before any redirect). */\n onSubmitted?: (submissionId: string) => void;\n /** Class for the <form> element; field wrappers/status use `bcms-*` classes. */\n className?: string;\n}\n\ntype Status = { state: \"idle\" | \"submitting\" | \"error\" | \"success\"; message?: string };\n\nfunction readPrefill(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const out: Record<string, string> = {};\n new URLSearchParams(window.location.search).forEach((v, k) => {\n out[k] = v;\n });\n return out;\n}\n\nfunction resetTurnstile(): void {\n const t = (globalThis as { turnstile?: { reset: () => void } }).turnstile;\n if (t) {\n try {\n t.reset();\n } catch {\n /* widget not mounted yet */\n }\n }\n}\n\nexport function BcmsForm({\n form,\n apiBase,\n turnstileSiteKey,\n onSubmitted,\n className,\n}: BcmsFormProps): ReactElement {\n const showTurnstile = Boolean(form.turnstileEnabled && turnstileSiteKey);\n const [values, setValues] = useState<FormValues>(() => {\n const init = formInitialValues(form, readPrefill());\n if (form.honeypotField) init[form.honeypotField] = \"\";\n return init;\n });\n const [status, setStatus] = useState<Status>({ state: \"idle\" });\n const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\n\n // Cloudflare auto-renders any `.cf-turnstile` element once its script is present.\n useEffect(() => {\n if (!showTurnstile || document.querySelector(`script[src=\"${TURNSTILE_SRC}\"]`)) return;\n const script = document.createElement(\"script\");\n script.src = TURNSTILE_SRC;\n script.async = true;\n script.defer = true;\n document.head.appendChild(script);\n }, [showTurnstile]);\n\n const visibleFields = useMemo(\n () => form.fields.filter((f) => f.type !== \"hidden\" && shouldShowField(f, values)),\n [form.fields, values],\n );\n\n const setValue = (key: string, value: FormValue) =>\n setValues((prev) => ({ ...prev, [key]: value }));\n\n async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {\n e.preventDefault();\n setStatus({ state: \"submitting\" });\n setFieldErrors({});\n\n const tokenEl = e.currentTarget.querySelector<HTMLInputElement>(\n '[name=\"cf-turnstile-response\"]',\n );\n const turnstileToken = tokenEl?.value || undefined;\n\n // Drop conditionally-hidden fields so a hidden required field can't block submit;\n // keep hidden-type fields and the honeypot (the API classifies bots on it).\n const data: FormValues = {};\n for (const field of form.fields) {\n if (field.type === \"hidden\" || shouldShowField(field, values)) {\n data[field.key] = values[field.key];\n }\n }\n if (form.honeypotField) data[form.honeypotField] = values[form.honeypotField] ?? \"\";\n\n try {\n const { id } = await submitForm({ formId: form.id, data, turnstileToken, baseUrl: apiBase });\n onSubmitted?.(id);\n if (form.redirectUrl) {\n window.location.href = form.redirectUrl;\n return;\n }\n const reset = formInitialValues(form);\n if (form.honeypotField) reset[form.honeypotField] = \"\";\n setValues(reset);\n setStatus({\n state: \"success\",\n message: form.successMessage ?? \"Thanks! Your submission was received.\",\n });\n resetTurnstile();\n } catch (err) {\n const e2 = err as FormSubmitError;\n if (e2.fieldErrors) setFieldErrors(e2.fieldErrors);\n setStatus({ state: \"error\", message: e2.message || \"Something went wrong. Please try again.\" });\n resetTurnstile();\n }\n }\n\n return (\n // `data-bcms-form` carries the id so the Visual Editor can find THIS form in the\n // preview frame and patch its copy live. Valued rather than bare: the runtime\n // selectors are `form[data-bcms-form]`, which a valued attribute still matches.\n <form className={className} onSubmit={handleSubmit} noValidate data-bcms-form={form.id}>\n {visibleFields.map((field) => (\n <Field\n key={field.key}\n field={field}\n value={values[field.key]}\n error={fieldErrors[field.key]}\n onChange={(v) => setValue(field.key, v)}\n />\n ))}\n\n {form.honeypotField ? (\n <span aria-hidden=\"true\" style={{ position: \"absolute\", left: \"-9999px\" }}>\n <input\n type=\"text\"\n name={form.honeypotField}\n tabIndex={-1}\n autoComplete=\"off\"\n value={String(values[form.honeypotField] ?? \"\")}\n onChange={(e) => setValue(form.honeypotField as string, e.target.value)}\n />\n </span>\n ) : null}\n\n {showTurnstile ? <div className=\"cf-turnstile\" data-sitekey={turnstileSiteKey} /> : null}\n\n <button type=\"submit\" disabled={status.state === \"submitting\"} data-bcms-form-part=\"submit\">\n {status.state === \"submitting\" ? \"Submitting…\" : form.submitLabel ?? \"Submit\"}\n </button>\n\n {status.message ? (\n <p\n className={`bcms-form-status bcms-form-status--${status.state}`}\n role=\"status\"\n aria-live=\"polite\"\n >\n {status.message}\n </p>\n ) : null}\n </form>\n );\n}\n\ninterface FieldProps {\n field: DeliveryFormField;\n value: FormValue;\n error?: string;\n onChange: (value: FormValue) => void;\n}\n\nfunction Field({ field, value, error, onChange }: FieldProps): ReactElement {\n const required = field.required;\n const errorNode = error ? (\n <span className=\"bcms-field-error\" role=\"alert\">\n {error}\n </span>\n ) : null;\n // Every author-editable string carries a `data-bcms-form-part` so the Visual Editor can\n // repaint it live. A string the dock can edit but cannot mark shows stale on the canvas.\n const helpNode = field.helpText ? (\n <span className=\"bcms-field-help\" data-bcms-form-part=\"help\">\n {field.helpText}\n </span>\n ) : null;\n\n if (field.type === \"checkbox\" || field.type === \"consent\") {\n return (\n <label\n className=\"bcms-field bcms-field--checkbox\"\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <input\n type=\"checkbox\"\n name={field.key}\n required={required}\n checked={Boolean(value)}\n onChange={(e) => onChange(e.target.checked)}\n />{\" \"}\n <span data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </span>\n {helpNode}\n {errorNode}\n </label>\n );\n }\n\n // Pick-one and pick-many are groups of controls, not a single element, so they\n // return their own <fieldset> rather than flowing into the label+control shape\n // below. Without these two branches both fell through to `<input type=\"text\">`.\n if (field.type === \"radio\" || field.type === \"checkboxes\") {\n const multi = field.type === \"checkboxes\";\n const selected = asStringArray(value);\n return (\n <fieldset\n className={`bcms-field bcms-field--${multi ? \"checkboxes\" : \"radio\"}`}\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <legend data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </legend>\n {(field.options ?? []).map((opt) => (\n <label key={opt} className=\"bcms-option\">\n <input\n type={multi ? \"checkbox\" : \"radio\"}\n name={field.key}\n value={opt}\n // `required` on every radio in a group is the native way to demand one\n // choice. On checkboxes it would demand ALL of them, so it is omitted —\n // the API enforces non-empty instead.\n required={!multi && required}\n checked={multi ? selected.includes(opt) : value === opt}\n onChange={(e) =>\n onChange(multi ? toggleOption(value, opt, e.target.checked) : opt)\n }\n />{\" \"}\n <span data-bcms-form-part=\"option\">{opt}</span>\n </label>\n ))}\n {helpNode}\n {errorNode}\n </fieldset>\n );\n }\n\n const str = String(value ?? \"\");\n let control: ReactElement;\n if (field.type === \"textarea\") {\n control = (\n <textarea\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n } else if (field.type === \"select\") {\n control = (\n <select name={field.key} required={required} value={str} onChange={(e) => onChange(e.target.value)}>\n <option value=\"\" disabled>\n Choose…\n </option>\n {(field.options ?? []).map((opt) => (\n <option key={opt} value={opt} data-bcms-form-part=\"option\">\n {opt}\n </option>\n ))}\n </select>\n );\n } else {\n control = (\n <input\n type={INPUT_TYPES[field.type] ?? \"text\"}\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n }\n\n return (\n <p className=\"bcms-field\" data-field={field.key} data-bcms-form-field={field.key}>\n <label data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </label>\n <br />\n {control}\n {helpNode}\n {errorNode}\n </p>\n );\n}\n","/**\n * Visual Editor addresses for the Next renderer.\n *\n * The attributes are ALWAYS on, deliberately — a headless site's HTML is the customer's own,\n * `data-bcms-*` is inert for visitors, and there is no request-time draft render to gate them\n * against. That has been true since they were introduced; what was wrong is WHICH address they\n * carried inside a component.\n *\n * A component's block ids belong to the DEFINITION and are shared by every instance of it, so a\n * definition-scoped `<defBlockId>__text` resolves to no field in the loaded entry — the editor\n * logs it as an orphan — and two instances of one component produce the SAME address twice,\n * which `stampNodeIds` drops from BOTH. The hosted renderer avoided this by rendering component\n * subtrees unannotated; this one had no equivalent, so it emitted live-looking attributes that\n * bound to nothing. `addresses` fixes it at the source instead: inside an instance the map is\n * authoritative and resolves each declared prop to `<instanceId>__overrides.<key>`.\n */\nimport type { BindingKind } from \"@bettercms-ai/types\";\nimport { formatPropsAttribute } from \"@bettercms-ai/types\";\n\n/** The subset of the render context binding needs. */\nexport interface BindingCtx {\n /** Present only inside a component instance, where it is AUTHORITATIVE. */\n fieldAddresses?: Map<string, string>;\n}\n\n/** The address a write lands on, or null when none exists and nothing should be advertised. */\nexport function addressFor(id: string | undefined, prop: string, ctx: BindingCtx): string | null {\n if (!id) return null;\n const key = `${id}__${prop}`;\n if (ctx.fieldAddresses) return ctx.fieldAddresses.get(key) ?? null;\n return key;\n}\n\n/**\n * Attributes for a value rendered as this element's own content — spread onto the JSX tag.\n * Returns an empty object when unaddressable, so it spreads to nothing.\n */\nexport function bind(\n id: string | undefined,\n prop: string,\n kind: BindingKind,\n ctx: BindingCtx,\n): Record<string, string> {\n const address = addressFor(id, prop, ctx);\n return address ? { \"data-bcms-field\": address, \"data-bcms-kind\": kind } : {};\n}\n\n/**\n * Attributes for values that live in an ATTRIBUTE of this element (`alt`, `href`, a video's\n * `src`). `data-bcms-field` addresses one element and an element cannot hold two, so these ride\n * `data-bcms-props`: `<address>|<kind>|<domAttribute>`, semicolon separated.\n *\n * Entries whose value is absent are dropped: `setFieldPath` refuses to create a final key, so\n * an address for a key the block does not carry is a write the editor would reject.\n */\nexport function bindProps(\n id: string | undefined,\n entries: readonly { prop: string; kind: BindingKind; attr: string; present: boolean }[],\n ctx: BindingCtx,\n): Record<string, string> {\n const resolved = entries.flatMap(({ prop, kind, attr, present }) => {\n if (!present) return [];\n const address = addressFor(id, prop, ctx);\n return address ? [{ address, kind, attr }] : [];\n });\n return resolved.length ? { \"data-bcms-props\": formatPropsAttribute(resolved) } : {};\n}\n"],"mappings":";;;;AA+BA,SAAS,aAAAA,YAAW,YAAAC,iBAAmC;;;ACfvD;AAAA,EACE;AAAA,EACA;AAAA,EACA,YAAAC;AAAA,OAIK;AACP,SAAS,uBAAuB;AAoBhC,SAAS,kCAAkC;AAC3C,SAAS,sBAAsB;;;ACjC/B,SAAS,WAAW,SAAS,gBAAmD;AAChF;AAAA,EACE;AAAA,EACA;AAAA,EACA;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IAAI,eAAe,SAAS,IACzB,wDACA;AAAA;AAAA;AAAA,EACN;AAEJ;;;ADlhBS,gBAAAG,YAAA;AAjCF,SAAS,gBAAgB;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA,GAAG;AACL,GAAqD;AACnD,QAAM,CAAC,KAAK,MAAM,IAAIC,UAAc,EAAE,QAAQ,WAAW,CAAC;AAE1D,EAAAC,WAAU,MAAM;AACd,QAAI,OAAO,WAAW,OAAQ;AAC9B,QAAI,aAAa;AACjB,UAAM,YAAY,CAAC,MAAoB;AACrC,UAAI,EAAE,WAAW,OAAO,SAAS,OAAQ;AACzC,UAAI,EAAE,WAAW,OAAO,OAAQ;AAChC,YAAM,IAAI,EAAE;AACZ,UAAI,CAAC,KAAK,OAAO,MAAM,SAAU;AACjC,UAAI,EAAE,SAAS,oBAAoB;AACjC,qBAAa;AACb,eAAO,OAAO,YAAY,EAAE,MAAM,qBAAqB,KAAK,GAAG,EAAE,MAAM;AACvE;AAAA,MACF;AACA,UAAI,CAAC,WAAY;AACjB,UAAI,EAAE,SAAS,oBAAoB,EAAE,SAAS,QAAQ,MAAM,QAAQ,EAAE,MAAM,GAAG;AAC7E,eAAO;AAAA,UACL,QAAQ,EAAE;AAAA,UACV,YAAY,MAAM,QAAQ,EAAE,UAAU,IAAK,EAAE,aAAmC;AAAA,QAClF,CAAC;AAAA,MACH;AAAA,IACF;AACA,WAAO,iBAAiB,WAAW,SAAS;AAC5C,WAAO,MAAM,OAAO,oBAAoB,WAAW,SAAS;AAAA,EAC9D,GAAG,CAAC,MAAM,UAAU,CAAC;AAErB,SAAO,gBAAAF,KAAC,cAAW,QAAQ,IAAI,QAAQ,YAAY,IAAI,YAAa,GAAG,MAAM;AAC/E;","names":["useEffect","useState","useState","jsx","jsxs","useState","jsx","useState","useEffect"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PageMetaJson, ContentBlock, DeliveredLayout, SiteSeoDefaults, DeliveryComponent } from '@bettercms-ai/types';
|
|
2
2
|
export { DeliveredLayout, PageMetaJson, SiteSeoDefaults } from '@bettercms-ai/types';
|
|
3
3
|
import { Metadata } from 'next';
|
|
4
|
-
import { SeoInput, DeliveryForm } from '@bettercms-ai/sdk';
|
|
4
|
+
import { SeoInput, SeoLocation, DeliveryForm } from '@bettercms-ai/sdk';
|
|
5
5
|
export { ResolvedSeo, SeoInput, resolveSeo } from '@bettercms-ai/sdk';
|
|
6
6
|
export { ImageFit, ImageFormat, ImageSource, ImageUrlBuilder, imageUrl, default as imageUrlBuilder } from '@bettercms-ai/image-url';
|
|
7
7
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
@@ -169,8 +169,15 @@ declare function createBetterCMS<Schema extends Record<string, unknown> = Record
|
|
|
169
169
|
* resolver the Astro adapter uses — so every surface stays consistent.
|
|
170
170
|
*/
|
|
171
171
|
|
|
172
|
-
/**
|
|
173
|
-
|
|
172
|
+
/**
|
|
173
|
+
* Build a Next.js `Metadata` from a BetterCMS page, layering page meta over site defaults.
|
|
174
|
+
*
|
|
175
|
+
* Pass `location` — `{ siteUrl, path }` — to get a canonical (and `og:url`) on pages that set
|
|
176
|
+
* none of their own. Omit it and both tags are absent, which is what a headless app shipped
|
|
177
|
+
* before this parameter existed. The hosted renderer always emits them, so a headless site
|
|
178
|
+
* without `location` is the ONE surface that silently differs from its hosted twin.
|
|
179
|
+
*/
|
|
180
|
+
declare function buildMetadata(page: SeoInput, siteDefaults?: SiteSeoDefaults, location?: SeoLocation): Metadata;
|
|
174
181
|
|
|
175
182
|
/**
|
|
176
183
|
* Build-time content snapshot — the writer + reader of `bcms-content.json`.
|
|
@@ -565,8 +572,10 @@ declare function createRevalidateRoute(config?: RevalidateRouteConfig): {
|
|
|
565
572
|
interface VisualEditingProps {
|
|
566
573
|
/**
|
|
567
574
|
* Studio origin, for the deep links and for the script itself. Defaults to
|
|
568
|
-
* `https://
|
|
569
|
-
* `NEXT_PUBLIC_BCMS_STUDIO_URL
|
|
575
|
+
* `https://bettercms.ai` — the same origin the dashboard hands out as
|
|
576
|
+
* `NEXT_PUBLIC_BCMS_STUDIO_URL`, confirmed canonical 2026-08-16.
|
|
577
|
+
* (`dashboard.bettercms.ai` resolves but 404s; `demo.bettercms.ai` still serves
|
|
578
|
+
* but is a stale alias we no longer hand out.)
|
|
570
579
|
*/
|
|
571
580
|
studioUrl?: string;
|
|
572
581
|
}
|
package/dist/index.js
CHANGED
|
@@ -176,8 +176,8 @@ function createBetterCMS(config) {
|
|
|
176
176
|
|
|
177
177
|
// src/metadata.ts
|
|
178
178
|
import { resolveSeo } from "@bettercms-ai/sdk";
|
|
179
|
-
function buildMetadata(page, siteDefaults = {}) {
|
|
180
|
-
const seo = resolveSeo(page, siteDefaults);
|
|
179
|
+
function buildMetadata(page, siteDefaults = {}, location = {}) {
|
|
180
|
+
const seo = resolveSeo(page, siteDefaults, location);
|
|
181
181
|
return {
|
|
182
182
|
title: seo.title || void 0,
|
|
183
183
|
description: seo.description || void 0,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/metadata.ts","../src/index.ts","../src/snapshot.ts","../src/llms-txt.ts","../src/preview.ts","../src/draft-route.ts","../src/forms-read.ts","../src/pages-read.ts","../src/components-read.ts","../src/field.tsx","../src/live-config.ts","../src/revalidate-route.ts"],"sourcesContent":["/**\n * Public types for @bettercms-ai/next.\n *\n * `BetterCMSEntry` mirrors the envelope emitted by @bettercms-ai/codegen's generated\n * file. The adapter normalizes the raw Delivery API response into exactly this shape,\n * so `getEntry`/`listEntries` line up 1:1 with your generated model types.\n */\n\n/** Normalized error thrown by adapter reads. Mirrors the SDK's BetterCMSError, but kept\n * local so the adapter carries no heavy runtime dependency into a consumer's bundle. */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: string;\n\n constructor(message: string, status: number, code: string) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/**\n * Delivery envelope around a model's typed `fields`. Returned by `getEntry`/`listEntries`.\n * Identical to the `BetterCMSEntry<TFields>` your generated types declare.\n *\n * `publishedAt`/`updatedAt` are ISO-8601 strings, or `null` when absent — never a\n * fabricated empty string (so `new Date(...)` is safe to attempt only on non-null).\n */\nexport interface BetterCMSEntry<TFields> {\n readonly slug: string;\n readonly status: \"draft\" | \"published\";\n readonly fields: TFields;\n readonly publishedAt: string | null;\n readonly updatedAt: string | null;\n}\n\nexport interface BetterCMSConfig {\n /** Workspace slug — the `:workspace` segment of the Delivery API path. */\n workspace: string;\n /** Optional delivery API key (sent as `Authorization: Bearer`). */\n apiKey?: string;\n /** Delivery API base. Default: `https://api.bettercms.ai/api/v1/delivery`. */\n baseUrl?: string;\n /** Preview API base. Default: derived from `baseUrl` (`/delivery` → `/preview`). */\n previewBaseUrl?: string;\n /**\n * Default Next.js revalidation for reads (seconds). `false` = always fresh\n * (`cache: \"no-store\"`). Per-call `revalidate` overrides this. Default: `60`.\n */\n revalidate?: number | false;\n}\n\n/** Per-read options shared by `getEntry` and `listEntries`. */\nexport interface ReadOptions {\n /** ISR window in seconds, or `false` for `cache: \"no-store\"`. Overrides config default. */\n revalidate?: number | false;\n /** Next.js cache tags for on-demand `revalidateTag()` invalidation. */\n tags?: string[];\n /** Reference hydration depth (0 = none, 1 = direct refs, 2 = nested). */\n depth?: 0 | 1 | 2;\n /** Field projection — only these field keys are returned. */\n select?: string[];\n}\n\n/** Options for `getEntry`, including draft-preview access. */\nexport interface GetEntryOptions extends ReadOptions {\n /** Fetch draft content via the preview endpoint. Requires `previewToken`. */\n preview?: boolean;\n /** Signed preview token (from `POST .../preview-token`). */\n previewToken?: string;\n}\n\n/** Options for `listEntries`. */\nexport interface ListEntriesOptions extends ReadOptions {\n /** 1-based page number. Default: 1. */\n page?: number;\n /** Items per page (max 100). Default: 20. */\n perPage?: number;\n}\n\n/** Paginated result returned by `listEntries`. */\nexport interface EntryList<TFields> {\n items: BetterCMSEntry<TFields>[];\n page: number;\n perPage: number;\n totalItems: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n}\n","/**\n * createBetterCMS — the Next.js delivery client.\n *\n * Reads run through the standard `fetch`, which the Next.js App Router patches to\n * participate in the data cache. We pass `next: { revalidate, tags }` so content is\n * cached/ISR'd and can be invalidated on publish via `revalidateTag()`.\n *\n * The raw Delivery API response is normalized into `BetterCMSEntry<TFields>` so the\n * return types match what @bettercms-ai/codegen generates.\n */\n\nimport type { ContentBlock, DeliveredLayout, PageMetaJson } from \"@bettercms-ai/types\";\nimport {\n BetterCMSError,\n type BetterCMSConfig,\n type BetterCMSEntry,\n type EntryList,\n type GetEntryOptions,\n type ListEntriesOptions,\n} from \"./types.js\";\n\n/** A published page with its block_json — feed `blocks` to `<BcmsBlocks>`.\n * The SEO fields (FLO-302) feed `buildMetadata` for the route's `generateMetadata`. */\nexport interface BetterCMSPage {\n slug: string;\n title: string;\n metaTitle: string | null;\n metaDescription: string | null;\n /** Rich SEO (OG / Twitter / canonical / JSON-LD). `null` when unset. */\n metaJson: PageMetaJson | null;\n blocks: ContentBlock[];\n layout?: DeliveredLayout | null;\n publishedAt: string | null;\n updatedAt: string | null;\n}\n\n/** Raw single-page shape returned by the Delivery API (`/content/:slug`). */\ninterface RawPageResponse {\n data: {\n slug: string;\n entry: {\n slug: string;\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n blocks?: ContentBlock[];\n layout?: DeliveredLayout | null;\n updatedAt?: string | null;\n };\n publishedAt: string | null;\n };\n}\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai/api/v1/delivery\";\nconst DEFAULT_REVALIDATE = 60;\n\n/** `fetch`'s init augmented with Next.js's `next` cache directives. (`cache` is declared\n * explicitly because this package compiles without the DOM lib.) */\ntype NextRequestInit = RequestInit & {\n cache?: \"default\" | \"no-store\" | \"force-cache\";\n next?: { revalidate?: number | false; tags?: string[] };\n};\n\n/** Raw single-entry shape returned by the Delivery API. */\ninterface RawEntry {\n id: string;\n slug: string;\n status: \"draft\" | \"published\";\n publishedAt: string | null;\n updatedAt?: string | null;\n data: Record<string, unknown>;\n}\n\ninterface RawListResponse {\n data: {\n items: RawEntry[];\n page: number;\n perPage: number;\n totalItems: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n };\n}\n\nfunction statusToCode(status: number): string {\n if (status === 404) return \"CONTENT_NOT_FOUND\";\n if (status === 401) return \"UNAUTHORIZED\";\n if (status === 403) return \"FORBIDDEN\";\n if (status === 429) return \"RATE_LIMITED\";\n if (status === 422) return \"VALIDATION_ERROR\";\n return \"INTERNAL_ERROR\";\n}\n\n/** Normalize a raw delivery entry into the codegen-aligned envelope. `publishedAt`\n * and `updatedAt` are kept distinct and pass through `null` rather than being\n * conflated or fabricated as \"\" (which would parse to an Invalid Date). */\nfunction mapEntry<TFields>(raw: RawEntry): BetterCMSEntry<TFields> {\n return {\n slug: raw.slug,\n status: raw.status,\n fields: raw.data as TFields,\n publishedAt: raw.publishedAt ?? null,\n updatedAt: raw.updatedAt ?? null,\n };\n}\n\n/**\n * The typed BetterCMS reader for Next.js.\n *\n * @typeParam Schema - your generated `BetterCMSSchema` (slug → fields registry). When\n * supplied, `listEntries(\"blog\")` is typed by the model's fields and the model name\n * autocompletes. Defaults to an open record so it also works untyped.\n */\nexport interface BetterCMSNext<Schema extends Record<string, unknown>> {\n /** Fetch one published entry by its content slug. Returns `null` when not found.\n * Passing `select` narrows the result to `Partial<TFields>` (projection drops fields). */\n getEntry<TFields = unknown>(\n slug: string,\n opts: GetEntryOptions & { select: string[] },\n ): Promise<BetterCMSEntry<Partial<TFields>> | null>;\n getEntry<TFields = unknown>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<BetterCMSEntry<TFields> | null>;\n\n /** List published entries, filtered to one model. Throws `BetterCMSError`\n * (CONTENT_NOT_FOUND) for an unknown workspace/model — an empty model returns an\n * empty page. Passing `select` narrows fields to `Partial`. */\n listEntries<M extends keyof Schema & string>(\n model: M,\n opts: ListEntriesOptions & { select: string[] },\n ): Promise<EntryList<Partial<Schema[M]>>>;\n listEntries<M extends keyof Schema & string>(\n model: M,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<Schema[M]>>;\n listEntries<TFields = unknown>(\n model?: string,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<TFields>>;\n\n /** Fetch one published page (with its `blocks` for `<BcmsBlocks>`) by slug.\n * Returns `null` when not found. */\n getPage(\n slug: string,\n opts?: { revalidate?: number | false; tags?: string[] },\n ): Promise<BetterCMSPage | null>;\n /** Fetch the project-scoped published Global Layout. */\n getLayout(opts?: { revalidate?: number | false; tags?: string[] }): Promise<DeliveredLayout | null>;\n}\n\nexport function createBetterCMS<\n Schema extends Record<string, unknown> = Record<string, unknown>,\n>(config: BetterCMSConfig): BetterCMSNext<Schema> {\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const previewBaseUrl = (\n config.previewBaseUrl ?? baseUrl.replace(/\\/delivery$/, \"/preview\")\n ).replace(/\\/+$/, \"\");\n const defaultRevalidate = config.revalidate ?? DEFAULT_REVALIDATE;\n\n function headers(): Record<string, string> {\n const h: Record<string, string> = { Accept: \"application/json\" };\n if (config.apiKey) h[\"Authorization\"] = `Bearer ${config.apiKey}`;\n return h;\n }\n\n function cacheInit(\n revalidate: number | false | undefined,\n tags: string[] | undefined,\n forceNoStore = false,\n ): NextRequestInit {\n const rv = revalidate ?? defaultRevalidate;\n // Preview is always uncached.\n if (forceNoStore) return { headers: headers(), cache: \"no-store\" };\n if (rv === false) {\n // With tags, \"false\" means cache until `revalidateTag` (the canonical CMS\n // publish-invalidation pattern) — we must NOT drop the tags to no-store, or\n // revalidateTag could never invalidate. Without tags, it means truly fresh.\n return tags?.length\n ? { headers: headers(), next: { revalidate: false, tags } }\n : { headers: headers(), cache: \"no-store\" };\n }\n return { headers: headers(), next: { revalidate: rv, tags } };\n }\n\n async function requestJSON<T>(\n url: string,\n init: NextRequestInit,\n { nullOn404 = false }: { nullOn404?: boolean } = {},\n ): Promise<T | null> {\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n // A single-entry 404 is \"no such entry\" (→ null). A list 404 is a real error\n // (unknown workspace/model) and must surface, not masquerade as an empty list.\n if (res.status === 404 && nullOn404) return null;\n if (!res.ok) {\n let message = res.statusText || \"Request failed\";\n try {\n const body = (await res.json()) as { error?: string; message?: string };\n message = body.error ?? body.message ?? message;\n } catch {\n /* ignore parse errors */\n }\n throw new BetterCMSError(message, res.status, statusToCode(res.status));\n }\n return (await res.json()) as T;\n }\n\n function entryQuery(opts?: { depth?: 0 | 1 | 2; select?: string[] }): string {\n const params = new URLSearchParams();\n if (opts?.depth != null) params.set(\"depth\", String(opts.depth));\n if (opts?.select?.length) params.set(\"select\", opts.select.join(\",\"));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n }\n\n const client = {\n async getEntry<TFields = unknown>(slug: string, opts?: GetEntryOptions) {\n const encoded = encodeURIComponent(slug);\n const query = entryQuery(opts);\n\n // Preview: drafts are only reachable through the signed preview endpoint, and\n // must never be cached (every request re-validates the token server-side).\n if (opts?.preview) {\n if (!opts.previewToken) {\n throw new BetterCMSError(\n \"preview: true requires a previewToken\",\n 400,\n \"VALIDATION_ERROR\",\n );\n }\n const tokenParam = `token=${encodeURIComponent(opts.previewToken)}`;\n const sep = query ? \"&\" : \"?\";\n const url = `${previewBaseUrl}/${encoded}${query}${sep}${tokenParam}`;\n const body = await requestJSON<{ data: RawEntry }>(\n url,\n cacheInit(undefined, undefined, true),\n { nullOn404: true },\n );\n return body ? mapEntry<TFields>(body.data) : null;\n }\n\n const url = `${baseUrl}/${config.workspace}/content-entries/${encoded}${query}`;\n const raw = await requestJSON<RawEntry>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n return raw ? mapEntry<TFields>(raw) : null;\n },\n\n async listEntries<TFields = unknown>(\n model?: string,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<TFields>> {\n const params = new URLSearchParams();\n if (model) params.set(\"model\", model);\n if (opts?.page != null) params.set(\"page\", String(opts.page));\n if (opts?.perPage != null) params.set(\"perPage\", String(opts.perPage));\n if (opts?.depth != null) params.set(\"depth\", String(opts.depth));\n if (opts?.select?.length) params.set(\"select\", opts.select.join(\",\"));\n\n const url = `${baseUrl}/${config.workspace}/content-entries?${params}`;\n const body = await requestJSON<RawListResponse>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n );\n\n const data = body?.data;\n if (!data) {\n return {\n items: [],\n page: opts?.page ?? 1,\n perPage: opts?.perPage ?? 20,\n totalItems: 0,\n totalPages: 1,\n hasNextPage: false,\n hasPreviousPage: false,\n };\n }\n return {\n items: data.items.map((r) => mapEntry<TFields>(r)),\n page: data.page,\n perPage: data.perPage,\n totalItems: data.totalItems,\n totalPages: data.totalPages,\n hasNextPage: data.hasNextPage,\n hasPreviousPage: data.hasPreviousPage,\n };\n },\n\n async getPage(\n slug: string,\n opts?: { revalidate?: number | false; tags?: string[] },\n ): Promise<BetterCMSPage | null> {\n const url = `${baseUrl}/${config.workspace}/content/${encodeURIComponent(slug)}`;\n const body = await requestJSON<RawPageResponse>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n if (!body) return null;\n const { entry, publishedAt } = body.data;\n return {\n slug: entry.slug,\n title: entry.title,\n metaTitle: entry.metaTitle ?? null,\n metaDescription: entry.metaDescription ?? null,\n metaJson: entry.metaJson ?? null,\n blocks: entry.blocks ?? [],\n layout: entry.layout ?? null,\n publishedAt: publishedAt ?? null,\n updatedAt: entry.updatedAt ?? null,\n };\n },\n\n async getLayout(opts?: { revalidate?: number | false; tags?: string[] }) {\n const body = await requestJSON<{ data: DeliveredLayout }>(\n `${baseUrl}/${config.workspace}/layout`,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n return body?.data ?? null;\n },\n };\n\n // The concrete impls use single generic signatures; the public interface exposes\n // richer overloads (select→Partial, model-keyed typing). Cast once here.\n return client as unknown as BetterCMSNext<Schema>;\n}\n","/**\n * buildMetadata — map a BetterCMS page's SEO onto a Next.js `Metadata` object.\n *\n * Wire it into a route's `generateMetadata` so per-page Meta Title / Description and\n * the rich OG / Twitter / canonical the dashboard saves drive the live `<head>`:\n *\n * import { createBetterCMS, buildMetadata } from \"@bettercms-ai/next\";\n * const bcms = createBetterCMS({ workspace: \"acme\" });\n *\n * export async function generateMetadata({ params }): Promise<Metadata> {\n * const page = await bcms.getPage(params.slug);\n * if (!page) return {};\n * return buildMetadata(page, siteDefaults); // siteDefaults optional\n * }\n *\n * JSON-LD isn't part of Next's `Metadata`; render `resolveSeo(page, defaults).jsonLd`\n * as a `<script type=\"application/ld+json\">` in the page component (see the README).\n *\n * The merge (page-over-site) is delegated to `resolveSeo` (@bettercms-ai/sdk), the same\n * resolver the Astro adapter uses — so every surface stays consistent.\n */\nimport type { Metadata } from \"next\";\nimport { resolveSeo, type SeoInput } from \"@bettercms-ai/sdk\";\nimport type { SiteSeoDefaults } from \"@bettercms-ai/types\";\n\n/** Build a Next.js `Metadata` from a BetterCMS page, layering page meta over site defaults. */\nexport function buildMetadata(page: SeoInput, siteDefaults: SiteSeoDefaults = {}): Metadata {\n const seo = resolveSeo(page, siteDefaults);\n return {\n title: seo.title || undefined,\n description: seo.description || undefined,\n alternates: seo.canonical ? { canonical: seo.canonical } : undefined,\n openGraph: {\n title: seo.og.title || undefined,\n description: seo.og.description || undefined,\n type: (seo.og.type || \"website\") as \"website\",\n url: seo.og.url || undefined,\n images: seo.og.image ? [{ url: seo.og.image }] : undefined,\n },\n twitter: {\n card: (seo.twitter.card || \"summary\") as \"summary\" | \"summary_large_image\",\n title: seo.twitter.title || undefined,\n description: seo.twitter.description || undefined,\n images: seo.twitter.image ? [seo.twitter.image] : undefined,\n site: seo.twitter.site || undefined,\n },\n };\n}\n","/**\n * @bettercms-ai/next — the BetterCMS adapter for Next.js.\n *\n * Pair with @bettercms-ai/codegen: generate `BetterCMSSchema` from your content models,\n * then `createBetterCMS<BetterCMSSchema>(...)` for typed, cache-aware reads in the App Router.\n */\n\nexport { createBetterCMS } from \"./client.js\";\nexport type { BetterCMSNext, BetterCMSPage } from \"./client.js\";\n\n// SEO (FLO-302): map a page's per-page-over-site SEO into a Next `Metadata` for\n// `generateMetadata`. `resolveSeo` (+ its types) is re-exported for JSON-LD / custom heads.\nexport { buildMetadata } from \"./metadata.js\";\nexport { resolveSeo } from \"@bettercms-ai/sdk\";\nexport type { SeoInput, ResolvedSeo } from \"@bettercms-ai/sdk\";\nexport type { PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\nexport type { DeliveredLayout } from \"@bettercms-ai/types\";\n\nexport { BetterCMSError } from \"./types.js\";\nexport type {\n BetterCMSConfig,\n BetterCMSEntry,\n ReadOptions,\n GetEntryOptions,\n ListEntriesOptions,\n EntryList,\n} from \"./types.js\";\n\nexport {\n getContent,\n buildSnapshot,\n writeSnapshot,\n readSnapshot,\n serializeSnapshot,\n parseSnapshot,\n SNAPSHOT_VERSION,\n DEFAULT_SNAPSHOT_FILE,\n} from \"./snapshot.js\";\nexport type { ContentSource, ContentSnapshot } from \"./snapshot.js\";\n\nexport { generateLlmsTxt, llmsTxtRoute, fetchModels } from \"./llms-txt.js\";\nexport type {\n LlmsModel,\n LlmsModelField,\n LlmsTxtOptions,\n LlmsTxtRouteConfig,\n} from \"./llms-txt.js\";\n\nexport { isDraftEnabled, getPreviewToken } from \"./preview.js\";\n\n// Draft-mode route-handler factories for the App Router.\nexport {\n createDraftModeRoute,\n createDisableDraftRoute,\n PREVIEW_TOKEN_COOKIE,\n} from \"./draft-route.js\";\nexport type { DraftModeRouteConfig } from \"./draft-route.js\";\n\n// Image URL builder — `import { imageUrlBuilder } from \"@bettercms-ai/next\"`.\nexport { default as imageUrlBuilder, imageUrl } from \"@bettercms-ai/image-url\";\nexport type {\n ImageUrlBuilder,\n ImageSource,\n ImageFormat,\n ImageFit,\n} from \"@bettercms-ai/image-url\";\n\n// Build-time forms reader for the deploy Action's snapshot (server-side).\nexport { readForms, getForm } from \"./forms-read.js\";\nexport type { SnapshotForms } from \"./forms-read.js\";\n\n// Build-time pages reader for the deploy Action's snapshot (server-side). Pair with\n// <BcmsBlocks> to render a page's block_json: readPages()/getPage(slug) → page.blocks.\nexport { readPages, getPage } from \"./pages-read.js\";\nexport type { SnapshotPage } from \"./pages-read.js\";\n\n// Build-time components reader — pass to <BcmsBlocks components={…} /> so `component`\n// blocks resolve their reusable definitions.\nexport { readComponents, getComponent } from \"./components-read.js\";\n\n// <BcmsForm> / <BcmsBlocks> are client components and ship from their own \"use client\"\n// entries so the React Server Components boundary survives bundling:\n// import { BcmsForm } from \"@bettercms-ai/next/form\";\n// import { BcmsBlocks } from \"@bettercms-ai/next/blocks\";\nexport type { BcmsFormProps } from \"./form.js\";\nexport type { BcmsBlocksProps } from \"./blocks.js\";\n\n// <BcmsField> tags an entry field's value so the visual editor binds click-to-edit\n// deterministically. Server-safe (no \"use client\"): import from \"@bettercms-ai/next\".\nexport { BcmsField } from \"./field.js\";\nexport type { BcmsFieldProps } from \"./field.js\";\n\n// Live content + revalidation (mirrors next-sanity defineLive/<SanityLive>).\n// import { BcmsLive } from \"@bettercms-ai/next/live\";\nexport type { BcmsLiveProps } from \"./live.js\";\nexport { defineBetterCMSLive } from \"./live-config.js\";\nexport type { BetterCMSLiveConfig } from \"./live-config.js\";\nexport { createRevalidateRoute } from \"./revalidate-route.js\";\nexport type { RevalidateRouteConfig } from \"./revalidate-route.js\";\n\n// Visual editing overlay (client). import { VisualEditing } from \"@bettercms-ai/next/visual-editing\"\nexport type { VisualEditingProps } from \"./visual-editing.js\";\n","/**\n * Build-time content snapshot — the writer + reader of `bcms-content.json`.\n *\n * Why this exists: a static (`output: \"export\"`) build must resolve all content at\n * build time. If a page instead falls back to a live `cache: \"no-store\"` fetch, its\n * route becomes dynamic and `output: \"export\"` silently drops it — you get an empty\n * `out/`. The fix is a single build-time snapshot the pages read synchronously.\n *\n * The WRITER (`buildSnapshot`/`writeSnapshot`, used by the `bettercms-snapshot` bin)\n * and the READER (`getContent`) share ONE serializer (`serializeSnapshot`/\n * `parseSnapshot`) so the on-disk shape can never drift between the two halves.\n *\n * This is intentionally separate from {@link createBetterCMS}: that stays the live,\n * network-backed client. `getContent` is the snapshot-preferring reader a static\n * site uses. Existing consumers that deliberately rely on the live fallback are\n * unaffected — only `getContent` enforces \"snapshot or bust\".\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n BetterCMSError,\n type BetterCMSConfig,\n type BetterCMSEntry,\n type EntryList,\n type ListEntriesOptions,\n} from \"./types.js\";\nimport { createBetterCMS } from \"./client.js\";\n\n/** Bump when the on-disk shape changes incompatibly — readers reject mismatches. */\nexport const SNAPSHOT_VERSION = 1;\n/** Default snapshot filename, resolved against `process.cwd()`. */\nexport const DEFAULT_SNAPSHOT_FILE = \"bcms-content.json\";\n\n/** The full-site content snapshot. Entries are grouped by model slug so the reader\n * can serve `listEntries(model)` offline without a per-entry model tag. */\nexport interface ContentSnapshot {\n version: number;\n workspace: string;\n generatedAt: string;\n models: Record<string, BetterCMSEntry<unknown>[]>;\n}\n\n// ── Serializer (shared by writer + reader — single source of on-disk shape) ──────\n\n/** Serialize a snapshot to the canonical JSON form written to disk. */\nexport function serializeSnapshot(snapshot: ContentSnapshot): string {\n return JSON.stringify(snapshot, null, 2);\n}\n\n/** Parse + validate a snapshot JSON string. Throws on a version mismatch so a stale\n * snapshot fails loudly rather than feeding the build the wrong shape. */\nexport function parseSnapshot(json: string): ContentSnapshot {\n const parsed = JSON.parse(json) as ContentSnapshot;\n if (parsed.version !== SNAPSHOT_VERSION) {\n throw new BetterCMSError(\n `Unsupported bcms-content.json version ${parsed.version} (expected ${SNAPSHOT_VERSION}). ` +\n `Regenerate it with \"bettercms-snapshot\".`,\n 0,\n \"SNAPSHOT_VERSION_MISMATCH\",\n );\n }\n return parsed;\n}\n\n// ── Disk I/O ─────────────────────────────────────────────────────────────────────\n\n/** Write a snapshot to `path` (relative paths resolve against cwd), creating dirs. */\nexport function writeSnapshot(path: string, snapshot: ContentSnapshot): void {\n const out = resolve(process.cwd(), path);\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, serializeSnapshot(snapshot), \"utf8\");\n}\n\n/** Read + parse a snapshot from `path`. Returns `null` only when the file is absent;\n * a present-but-corrupt/stale file throws (callers must not treat that as \"missing\"). */\nexport function readSnapshot(path: string): ContentSnapshot | null {\n const out = resolve(process.cwd(), path);\n let json: string;\n try {\n json = readFileSync(out, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code === \"ENOENT\") return null;\n throw err;\n }\n return parseSnapshot(json);\n}\n\n// ── Writer: build a snapshot from the live API ────────────────────────────────────\n\n/** Minimal client surface `buildSnapshot` needs — lets tests inject a fake. Kept\n * non-generic so a simple fake (and the live client's matching overload) both fit. */\ntype ListOnly = {\n listEntries(model?: string, opts?: ListEntriesOptions): Promise<EntryList<unknown>>;\n};\n\n/**\n * Page through every model's published entries and assemble a full-site snapshot.\n * `modelSlugs` come from the Management API (`fetchModels`) so the snapshot covers\n * exactly this project's schema. Pass `client` in tests; defaults to the live client.\n */\nexport async function buildSnapshot(opts: {\n config: BetterCMSConfig;\n modelSlugs: string[];\n client?: ListOnly;\n /** Stamped into `generatedAt`; injectable for deterministic tests. */\n now?: string;\n}): Promise<ContentSnapshot> {\n const client = opts.client ?? createBetterCMS(opts.config);\n const models: Record<string, BetterCMSEntry<unknown>[]> = {};\n for (const slug of opts.modelSlugs) {\n const all: BetterCMSEntry<unknown>[] = [];\n let page = 1;\n for (;;) {\n // revalidate:false → bypass any data cache; this is a one-shot build fetch.\n const res = await client.listEntries(slug, { page, perPage: 100, revalidate: false });\n all.push(...res.items);\n if (!res.hasNextPage) break;\n page += 1;\n }\n models[slug] = all;\n }\n return {\n version: SNAPSHOT_VERSION,\n workspace: opts.config.workspace,\n generatedAt: opts.now ?? new Date().toISOString(),\n models,\n };\n}\n\n// ── Reader: getContent (snapshot-preferring, loud on absence) ─────────────────────\n\n/** Snapshot-backed content reader. Async so it can transparently fall back to the\n * live client in preview without changing the call sites. */\nexport interface ContentSource {\n getEntry<TFields = unknown>(slug: string): Promise<BetterCMSEntry<TFields> | null>;\n listEntries<TFields = unknown>(model?: string): Promise<EntryList<TFields>>;\n}\n\n/** `BETTERCMS_PREVIEW` truthy → read live (uncached), never the snapshot. */\nfunction isPreview(): boolean {\n const v = (\n globalThis as { process?: { env?: Record<string, string | undefined> } }\n ).process?.env?.BETTERCMS_PREVIEW;\n return v != null && v !== \"\" && v !== \"0\" && v !== \"false\";\n}\n\n/** Parsed snapshots keyed by resolved path — read+parse once per build process. */\nconst snapshotCache = new Map<string, ContentSnapshot>();\n\n/** Test-only: clear the module-scope snapshot cache between cases. */\nexport function __resetSnapshotCacheForTests(): void {\n snapshotCache.clear();\n}\n\nfunction emptyPage<TFields>(items: BetterCMSEntry<TFields>[]): EntryList<TFields> {\n return {\n items,\n page: 1,\n perPage: items.length,\n totalItems: items.length,\n totalPages: 1,\n hasNextPage: false,\n hasPreviousPage: false,\n };\n}\n\n/**\n * The reader a static site should use. In a normal (export) build it reads the\n * memoized `bcms-content.json` and serves entries from memory. If the snapshot is\n * absent it THROWS a clear, actionable error — the whole point is to turn the old\n * silent empty-`out/` failure into a loud build error. Set `BETTERCMS_PREVIEW=1`\n * for a preview build that reads live instead.\n */\nexport function getContent<\n Schema extends Record<string, unknown> = Record<string, unknown>,\n>(config: BetterCMSConfig, opts: { snapshotPath?: string } = {}): ContentSource {\n const path = opts.snapshotPath ?? DEFAULT_SNAPSHOT_FILE;\n\n if (isPreview()) {\n const live = createBetterCMS<Schema>(config);\n return {\n getEntry: (slug) => live.getEntry(slug, { revalidate: false }),\n listEntries: (model) => live.listEntries(model, { revalidate: false }),\n };\n }\n\n const resolved = resolve(process.cwd(), path);\n function load(): ContentSnapshot {\n const cached = snapshotCache.get(resolved);\n if (cached) return cached;\n const snap = readSnapshot(path);\n if (!snap) {\n throw new BetterCMSError(\n `BetterCMS content snapshot \"${path}\" not found. A static (output: \"export\") build reads ` +\n `content from this snapshot; without it pages fall back to a live no-store fetch, become ` +\n `dynamic routes, and output: \"export\" silently drops them (empty out/). Run ` +\n `\"bettercms-snapshot\" before \"next build\" (make it your build:preview prestep), or set ` +\n `BETTERCMS_PREVIEW=1 to read live in a preview build.`,\n 0,\n \"SNAPSHOT_MISSING\",\n );\n }\n snapshotCache.set(resolved, snap);\n return snap;\n }\n\n return {\n async getEntry<TFields = unknown>(slug: string) {\n const snap = load();\n for (const entries of Object.values(snap.models)) {\n const found = entries.find((e) => e.slug === slug);\n if (found) return found as BetterCMSEntry<TFields>;\n }\n return null;\n },\n async listEntries<TFields = unknown>(model?: string) {\n const snap = load();\n const items = (\n model ? (snap.models[model] ?? []) : Object.values(snap.models).flat()\n ) as BetterCMSEntry<TFields>[];\n return emptyPage(items);\n },\n };\n}\n","/**\n * llms.txt generation — the AI-discovery surface of the deterministic floor.\n *\n * `generateLlmsTxt` is pure (models in → string out), so it is trivially testable and\n * deterministic. `llmsTxtRoute` wraps it as an App Router `route.ts` handler. `fetchModels`\n * pulls the live schema from the Management API for sites that want a self-updating file.\n *\n * Output follows the llmstxt.org convention: an H1 title, a `>` summary, then sections.\n */\n\n/** Minimal field shape needed to describe a model in llms.txt. */\nexport interface LlmsModelField {\n key: string;\n label?: string;\n type: string;\n required?: boolean;\n}\n\n/** Minimal model shape — a subset of the Management API model row. */\nexport interface LlmsModel {\n slug: string;\n name?: string;\n description?: string | null;\n fields: LlmsModelField[];\n}\n\nexport interface LlmsTxtOptions {\n /** H1 title. Default: \"BetterCMS content\". */\n title?: string;\n /** One-line `>` summary under the title. */\n description?: string;\n /** Delivery API base used to render example endpoints. */\n baseUrl?: string;\n /** Workspace slug used in example endpoints. */\n workspace?: string;\n /** Extra free-form lines appended under a \"## Notes\" section. */\n notes?: string[];\n}\n\n// Model name/slug/description and field key/label/type are author/agent-controlled\n// (the same content the sibling codegen package treats as hostile via escapeJsDoc).\n// llms.txt is fed to AI crawlers, so unescaped values could forge headings/blockquotes\n// or break out of code spans — a structure-spoofing / prompt-injection vector.\n\n/** Collapse to a single line — kills newline-based block injection. */\nfunction oneLine(text: string): string {\n return text.replace(/[\\r\\n]+/g, \" \").trim();\n}\n\n/** For text rendered OUTSIDE a code span (titles, descriptions, labels): single-line +\n * escape a leading markdown block-control char so it can't start a heading/list/quote. */\nfunction inlineText(text: string): string {\n return oneLine(text).replace(/^([#>\\-*+=|])/, \"\\\\$1\");\n}\n\n/** For text rendered INSIDE a code span: strip backticks (which would close the span)\n * and newlines. */\nfunction codeSpan(text: string): string {\n return oneLine(text).replace(/`/g, \"\");\n}\n\nfunction fieldLine(f: LlmsModelField): string {\n const req = f.required ? \", required\" : \"\";\n const label = f.label && f.label !== f.key ? ` — ${inlineText(f.label)}` : \"\";\n return ` - \\`${codeSpan(f.key)}\\` (${codeSpan(f.type)}${req})${label}`;\n}\n\n/**\n * Render an llms.txt document describing the available content models. Deterministic:\n * models are sorted by slug; field order is preserved as authored.\n */\nexport function generateLlmsTxt(models: LlmsModel[], opts: LlmsTxtOptions = {}): string {\n const title = opts.title ?? \"BetterCMS content\";\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const lines: string[] = [`# ${inlineText(title)}`, \"\"];\n if (opts.description) {\n lines.push(`> ${inlineText(opts.description)}`, \"\");\n }\n\n const base =\n opts.baseUrl && opts.workspace\n ? `${opts.baseUrl.replace(/\\/+$/, \"\")}/${opts.workspace}/content-entries`\n : undefined;\n\n lines.push(\"## Content models\", \"\");\n if (sorted.length === 0) {\n lines.push(\"_No content models are defined yet._\", \"\");\n }\n for (const model of sorted) {\n const name = model.name ?? model.slug;\n lines.push(`### ${inlineText(name)} (\\`${codeSpan(model.slug)}\\`)`);\n if (model.description) lines.push(\"\", inlineText(model.description));\n if (base) {\n lines.push(\"\", `- List: \\`GET ${base}?model=${codeSpan(model.slug)}\\``);\n lines.push(`- Entry: \\`GET ${base}/{slug}\\``);\n }\n if (model.fields.length) {\n lines.push(\"\", \"Fields:\");\n for (const f of model.fields) lines.push(fieldLine(f));\n }\n lines.push(\"\");\n }\n\n if (opts.notes?.length) {\n lines.push(\"## Notes\", \"\");\n for (const note of opts.notes) lines.push(`- ${inlineText(note)}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Integration SKILL.md ────────────────────────────────────────────────────────\n// A framework-agnostic agent skill (frontmatter + lean body) that teaches an AI how\n// to READ this project's content from the Delivery API. Unlike llms.txt it does NOT\n// dump every field — it points at the live types endpoint so the schema can't go\n// stale, and names content types by slug only. Drop at .claude/skills/<name>/SKILL.md.\n\n/** A content type named in the skill — slug + kind only (no fields). */\nexport interface SkillContentType {\n kind: \"page\" | \"model\";\n slug: string;\n /** \"singleton\" | \"dynamic\" for pages; omitted for models. */\n pageType?: string | null;\n}\n\nexport interface SkillOptions {\n /** Human project name (skill title + description). */\n projectName: string;\n /** Project slug → the skill's kebab-case `name:`. */\n projectSlug: string;\n /** Delivery + management API base, e.g. https://api.bettercms.ai/api/v1. */\n apiUrl: string;\n /** Workspace slug used in the delivery paths. */\n workspace: string;\n /** Where to mint a content:read delivery key. */\n mintUrl: string;\n /** Key-authed live TypeScript types endpoint. */\n typesUrl: string;\n /** This project's content types (pages + models), by slug — no field dump. */\n contentTypes: SkillContentType[];\n}\n\n/**\n * Render a concise, framework-agnostic SKILL.md describing how to read THIS\n * project's content from the BetterCMS Delivery API. Deterministic: content types\n * sorted by slug. Author-controlled strings (project name, slugs, pageType) are\n * injection-escaped, same as {@link generateLlmsTxt}.\n */\nexport type SkillTarget = \"claude\" | \"cursor\" | \"agents\";\n\nexport interface SkillVariant {\n /** The agent/IDE this variant targets. */\n target: SkillTarget;\n /** Human label for a tab/picker. */\n label: string;\n /** Suggested path to save the file, e.g. `.claude/skills/<name>/SKILL.md`. */\n filename: string;\n /** Full file content (target-specific frontmatter + the shared body). */\n content: string;\n}\n\n/** The shared, tool-agnostic instruction body — no frontmatter, no save hint. */\nfunction skillBody(opts: SkillOptions): string {\n const proj = inlineText(opts.projectName);\n const api = opts.apiUrl.replace(/\\/+$/, \"\");\n const deliveryBase = `${api}/delivery/${codeSpan(opts.workspace)}`;\n const sorted = [...opts.contentTypes].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const lines: string[] = [\n `# BetterCMS — ${proj}`,\n \"\",\n `${proj}'s content lives in BetterCMS. Read it through the Delivery API with a project ` +\n \"`content:read` key. Pull field shapes live from the types endpoint below — don't hardcode \" +\n \"them, the schema can change.\",\n \"\",\n \"## Auth\",\n \"Send `X-API-Key: <key>` on every read. Mint a long-lived `content:read` key (reads PUBLISHED \" +\n `content, never expires) at ${opts.mintUrl}. For drafts, mint a \\`content:read:draft\\` key ` +\n \"(force-expired to ≤1h), then publish and switch to the long-lived key.\",\n \"\",\n \"## Content types\",\n ];\n if (sorted.length === 0) {\n lines.push(\"_None yet — create pages or models first (e.g. via the BetterCMS MCP)._\");\n } else {\n for (const ct of sorted) {\n const kind =\n ct.kind === \"page\"\n ? `page${ct.pageType ? ` (${codeSpan(ct.pageType)})` : \"\"}`\n : \"model\";\n lines.push(`- \\`${codeSpan(ct.slug)}\\` — ${kind}`);\n }\n }\n lines.push(\n \"\",\n `## Reading (Delivery API · base \\`${deliveryBase}\\`)`,\n \"- Page: `GET .../content/{slug}`\",\n \"- Entries (list): `GET .../content-entries?model={slug}`\",\n \"- Entry: `GET .../content-entries/{slug}`\",\n \"\",\n \"## Typed client\",\n `- Live TypeScript types: \\`GET ${opts.typesUrl}\\` — authoritative field shapes; generate/refresh from here.`,\n \"- `npm i @bettercms-ai/next @bettercms-ai/codegen`, then construct the client. \" +\n \"`baseUrl` + `workspace` are required — there is no `apiUrl`/`endpoint` option:\",\n \"\",\n \"```ts\",\n 'import { createBetterCMS } from \"@bettercms-ai/next\";',\n \"const cms = createBetterCMS<BetterCMSSchema>({\",\n ` baseUrl: \"${api}/delivery\",`,\n ` workspace: \"${codeSpan(opts.workspace)}\",`,\n \" apiKey: process.env.BETTERCMS_API_KEY,\",\n \"});\",\n \"```\",\n \"\",\n \"## Field shapes you'll read\",\n \"Canonical READ shapes the Delivery API returns. Per-field types come from the types \" +\n \"endpoint; these container shapes are stable:\",\n '- **richtext** → `{ html, value: { root: … }, format: \"lexical-…\" }`. Render `html`, ' +\n \"or walk `value.root` for structured rendering.\",\n \"- **image** → `{ url, altText?, width?, height?, id? }` — an object, use `.url` (the \" +\n \"write value is a bare CDN URL string, but reads are normalized to this object).\",\n \"- **array + zones** → `{ nonRepeatable?: { <key>: value }, repeatable?: Array<{ <key>: \" +\n \"value }> }`. `nonRepeatable` is one fixed block; `repeatable` is a list — map over it.\",\n '- **array (primitive)** → a flat list (e.g. `string[]`). `type: \"array\"` alone is ' +\n \"ambiguous — the generated type tells you which.\",\n \"\",\n \"Example entry `fields` (a `sections` zone field + a `tags` primitive array):\",\n \"```jsonc\",\n \"{\",\n ' \"sections\": {',\n ' \"nonRepeatable\": { \"eyebrow\": \"New\", \"heading\": \"Welcome\" },',\n ' \"repeatable\": [{ \"label\": \"Docs\", \"url\": \"/docs\", \"icon\": { \"url\": \"https://cdn…\" } }]',\n \" },\",\n ' \"tags\": [\"alpha\", \"beta\"]',\n \"}\",\n \"```\",\n \"\",\n \"## Live Preview bindings (makes the site visually editable)\",\n \"Generate a bindings module alongside the types and spread it so the dashboard's Live \" +\n \"Preview can edit each field in place:\",\n \"```bash\",\n `BETTERCMS_API_KEY=<key> npx bettercms-codegen --api-url ${api} --bindings-out src/bettercms.bindings.generated.ts`,\n \"```\",\n \"```tsx\",\n 'import { bcms } from \"./bettercms.bindings.generated\";',\n \"// scalar: <h1 {...bcms.<model>.<field>}>{entry.fields.field}</h1>\",\n \"// list item: <article {...bcms.<model>.<arr>.$(i)}><h3 {...bcms.<model>.<arr>.<sub>(i)}>{item.sub}</h3></article>\",\n \"// primitive list:<li {...bcms.<model>.<arr>.value(i)}>{tag}</li>\",\n \"```\",\n \"Bindings emit two inert `data-*` attributes on every build, so spreading them is \" +\n \"always safe.\",\n );\n return lines.join(\"\\n\");\n}\n\nfunction skillDescription(proj: string): string {\n return (\n `Read ${proj}'s content from BetterCMS via the Delivery API — auth, listing and fetching ` +\n \"pages and content entries, pulling live TypeScript types, and the @bettercms-ai/next typed \" +\n \"client. Use whenever fetching, rendering, or typing this project's CMS content.\"\n );\n}\n\n/**\n * Render the integration skill for a specific agent `target`. The instruction body is\n * identical across tools; only the frontmatter (and where you save it) differ:\n * - claude → Claude Code skill (`name` + `description`)\n * - cursor → Cursor `.mdc` rule (`description` + `globs` + `alwaysApply`, \"Agent Requested\")\n * - agents → plain Markdown, no frontmatter (drop into a repo-root `AGENTS.md`)\n */\nexport function generateSkill(opts: SkillOptions, target: SkillTarget = \"claude\"): string {\n const name = `bettercms-${codeSpan(opts.projectSlug)}`;\n const desc = skillDescription(inlineText(opts.projectName));\n const body = skillBody(opts);\n\n let frontmatter = \"\";\n if (target === \"claude\") {\n frontmatter = `---\\nname: ${name}\\ndescription: ${desc}\\n---\\n\\n`;\n } else if (target === \"cursor\") {\n frontmatter = `---\\ndescription: ${desc}\\nglobs:\\nalwaysApply: false\\n---\\n\\n`;\n }\n return `${frontmatter}${body}\\n`;\n}\n\nconst TARGET_META: Record<SkillTarget, { label: string; file: (name: string) => string }> = {\n claude: { label: \"Claude Code\", file: (n) => `.claude/skills/${n}/SKILL.md` },\n cursor: { label: \"Cursor\", file: (n) => `.cursor/rules/${n}.mdc` },\n agents: { label: \"AGENTS.md (generic)\", file: () => \"AGENTS.md\" },\n};\n\n/** Render the skill for every supported agent target — drives a tabbed picker in the UI. */\nexport function generateSkillVariants(opts: SkillOptions): SkillVariant[] {\n const name = `bettercms-${codeSpan(opts.projectSlug)}`;\n return (Object.keys(TARGET_META) as SkillTarget[]).map((target) => ({\n target,\n label: TARGET_META[target].label,\n filename: TARGET_META[target].file(name),\n content: generateSkill(opts, target),\n }));\n}\n\n/** Options for {@link llmsTxtRoute}. Provide one of `models` or `getModels`. */\nexport interface LlmsTxtRouteConfig extends LlmsTxtOptions {\n /** Static model list (e.g. fetched at build time). */\n models?: LlmsModel[];\n /** Dynamic provider — called per request (wrap in your own caching if needed). */\n getModels?: () => Promise<LlmsModel[]> | LlmsModel[];\n /** Cache-Control header value. Default: `public, max-age=3600`. */\n cacheControl?: string;\n}\n\n/**\n * Build an App Router route handler that serves llms.txt as `text/plain`.\n *\n * ```ts\n * // app/llms.txt/route.ts\n * import { llmsTxtRoute } from \"@bettercms-ai/next\";\n * export const GET = llmsTxtRoute({ models, title: \"Acme\", workspace: \"acme\" });\n * ```\n */\nexport function llmsTxtRoute(config: LlmsTxtRouteConfig): () => Promise<Response> {\n const { models, getModels, cacheControl, ...opts } = config;\n return async () => {\n const resolved = getModels ? await getModels() : (models ?? []);\n const body = generateLlmsTxt(resolved, opts);\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"Cache-Control\": cacheControl ?? \"public, max-age=3600\",\n },\n });\n };\n}\n\n/**\n * Fetch content models from the Management API (`GET /management/content/models`).\n * The key is project-scoped server-side, so this returns exactly this site's schema.\n * Dependency-free so it runs in any runtime (Edge route, build script, Node).\n */\nexport async function fetchModels(opts: {\n /** Management API base, e.g. \"https://api.bettercms.ai/api/v1\". */\n apiUrl: string;\n /** A management-scoped key (content:manage). */\n apiKey: string;\n /** Optional fetch override (testing / custom runtime). */\n fetchImpl?: typeof fetch;\n}): Promise<LlmsModel[]> {\n const doFetch = opts.fetchImpl ?? fetch;\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\n const res = await doFetch(`${base}/management/content/models`, {\n headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: \"application/json\" },\n });\n if (!res.ok) {\n throw new Error(`Management API returned ${res.status} ${res.statusText}`);\n }\n const body = (await res.json()) as { data?: LlmsModel[] };\n return (body.data ?? []).map((m) => ({\n slug: m.slug,\n name: m.name,\n description: m.description ?? null,\n fields: m.fields ?? [],\n }));\n}\n","/**\n * Draft-preview helpers. `next/headers` is imported dynamically so this module is safe\n * to load outside a Next.js request scope (tests, build scripts) without throwing.\n */\n\n/** True when Next.js Draft Mode is enabled for the current request. */\nexport async function isDraftEnabled(): Promise<boolean> {\n const { draftMode } = await import(\"next/headers\");\n const dm = await draftMode();\n return dm.isEnabled;\n}\n\n/**\n * The preview token stored by `createDraftModeRoute`, or null. Pass it to\n * `getEntry(slug, { preview: true, previewToken })` to read drafts.\n */\nexport async function getPreviewToken(): Promise<string | null> {\n const { cookies } = await import(\"next/headers\");\n const jar = await cookies();\n return jar.get(\"bcms-preview-token\")?.value ?? null;\n}\n","/**\n * createDraftModeRoute — an App Router route-handler factory for entering draft\n * preview. Mount it at e.g. `app/api/draft/route.ts`:\n *\n * import { createDraftModeRoute } from \"@bettercms-ai/next\";\n * export const { GET } = createDraftModeRoute({ apiUrl: \"https://api.bettercms.ai\" });\n *\n * Visiting `/api/draft?token=<jwt>&redirect=/path` validates the preview token\n * against the backend (the signature authority), enables Next Draft Mode, stores\n * the token in an httpOnly cookie, and redirects. Reads can then pass the token\n * via `getPreviewToken()` to `getEntry({ preview: true, previewToken })`.\n */\n\nexport const PREVIEW_TOKEN_COOKIE = \"bcms-preview-token\";\n\nexport interface DraftModeRouteConfig {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n}\n\n/** Only same-origin relative paths. Blocks \"//evil.com\", \"https://evil.com\", etc. */\nfunction safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") ? to : \"/\";\n}\n\n/** Decode a preview-token JWT payload (UNVERIFIED) to read its `entrySlug`. */\nfunction decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = JSON.parse(\n Buffer.from(part, \"base64url\").toString(\"utf8\"),\n ) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\nexport function createDraftModeRoute(config: DraftModeRouteConfig) {\n const apiUrl = config.apiUrl.replace(/\\/+$/, \"\");\n\n async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n const redirectTo = url.searchParams.get(\"redirect\") ?? \"/\";\n\n if (!token) return new Response(\"Missing token\", { status: 400 });\n const slug = decodeTokenSlug(token);\n if (!slug) return new Response(\"Malformed token\", { status: 400 });\n\n const res = await fetch(\n `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`,\n );\n if (!res.ok) return new Response(\"Invalid or expired token\", { status: 401 });\n\n const { draftMode, cookies } = await import(\"next/headers\");\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_TOKEN_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: url.protocol === \"https:\",\n path: \"/\",\n maxAge: 60 * 60 * 24,\n });\n\n return Response.redirect(new URL(safeRedirectPath(redirectTo), url.origin), 302);\n }\n\n return { GET };\n}\n\n/** Exit draft mode and clear the preview-token cookie. */\nexport function createDisableDraftRoute() {\n async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const redirectTo = url.searchParams.get(\"redirect\") ?? \"/\";\n const { draftMode, cookies } = await import(\"next/headers\");\n (await draftMode()).disable();\n (await cookies()).delete(PREVIEW_TOKEN_COOKIE);\n return Response.redirect(new URL(safeRedirectPath(redirectTo), url.origin), 302);\n }\n return { GET };\n}\n","/**\n * Build-time reader for the forms the deploy Action injects into the content\n * snapshot (schema \"bcms-content/v1\": `{ ...collections, forms, turnstileSiteKey }`).\n *\n * This is intentionally separate from `readSnapshot()` — that reads the\n * `@bettercms-ai/next` \"bettercms-snapshot\" format (`{ version, models }`), which is a\n * different file shape. Connected-repo sites on <name>.bettercms.site get the Action\n * snapshot, so forms live here. Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { DeliveryForm } from \"@bettercms-ai/sdk\";\n\nexport interface SnapshotForms {\n forms: DeliveryForm[];\n /** Public Turnstile site key for any form with `turnstileEnabled`, or null. */\n turnstileSiteKey: string | null;\n}\n\n/**\n * Read forms from the Action's `bcms-content.json`. Missing file or no forms →\n * an empty set (a content-only build never throws). `path` resolves against cwd.\n */\nexport function readForms(path = \"bcms-content.json\"): SnapshotForms {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return { forms: [], turnstileSiteKey: null };\n }\n const snap = JSON.parse(raw) as { forms?: DeliveryForm[]; turnstileSiteKey?: string | null };\n return { forms: snap.forms ?? [], turnstileSiteKey: snap.turnstileSiteKey ?? null };\n}\n\n/** Find a single form by `id` or `name` from the Action snapshot. */\nexport function getForm(idOrName: string, path?: string): DeliveryForm | undefined {\n return readForms(path).forms.find((f) => f.id === idOrName || f.name === idOrName);\n}\n","/**\n * Build-time reader for the pages the deploy Action injects into the content\n * snapshot (schema \"bcms-content/v1\": `{ ...collections, forms, pages, turnstileSiteKey }`).\n *\n * Sibling to `forms-read.ts`. Connected-repo sites on <name>.bettercms.site get the\n * Action snapshot, so published pages (with their block_json) live here. Render a page\n * with `<BcmsBlocks blocks={page.blocks} forms={readForms().forms} />`. The same data\n * is also available at runtime via `createBetterCMS(...).getPage(slug)`.\n * Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { ContentBlock, PageMetaJson, DeliveredLayout } from \"@bettercms-ai/types\";\n\nexport interface SnapshotPage {\n projectId?: string | null;\n slug: string;\n title: string;\n metaTitle: string | null;\n metaDescription: string | null;\n /** Rich SEO (OG / Twitter / canonical / JSON-LD) — FLO-302. Feed to `buildMetadata`. */\n metaJson: PageMetaJson | null;\n /** The page's block_json — pass to `<BcmsBlocks blocks={...} />`. */\n blocks: ContentBlock[];\n /** Resolved published project/page chrome, shared with runtime Delivery reads. */\n layout?: DeliveredLayout | null;\n updatedAt: string | null;\n publishedAt: string | null;\n}\n\n/**\n * Read published pages from the Action's `bcms-content.json`. Missing file or no\n * pages → an empty list (a pages-less build never throws). `path` resolves against cwd.\n */\nexport function readPages(path = \"bcms-content.json\"): SnapshotPage[] {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return [];\n }\n const snap = JSON.parse(raw) as { pages?: SnapshotPage[] };\n return snap.pages ?? [];\n}\n\n/** Find a single published page by `slug` from the Action snapshot. */\nexport function getPage(slug: string, path?: string): SnapshotPage | undefined {\n return readPages(path).find((p) => p.slug === slug);\n}\n","/**\n * Build-time reader for the reusable components the deploy Action injects into the\n * content snapshot (`bcms-content.json` → `components`). Mirrors `forms-read.ts`.\n *\n * Pass the result to `<BcmsBlocks components={readComponents()} … />` so `component`\n * blocks resolve their definitions. Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { DeliveryComponent } from \"@bettercms-ai/types\";\n\n/**\n * Read components from the Action's `bcms-content.json`. Missing file or no\n * components → an empty array (a content-only build never throws).\n */\nexport function readComponents(path = \"bcms-content.json\"): DeliveryComponent[] {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return [];\n }\n const snap = JSON.parse(raw) as { components?: DeliveryComponent[] };\n return snap.components ?? [];\n}\n\n/** Find a single component by `id`, `slug`, or `name` from the Action snapshot. */\nexport function getComponent(idOrSlug: string, path?: string): DeliveryComponent | undefined {\n return readComponents(path).find(\n (c) => c.id === idOrSlug || c.slug === idOrSlug || c.name === idOrSlug,\n );\n}\n","/**\n * <BcmsField> — tag an entry field's rendered value with its identity so the\n * BetterCMS visual editor can bind click-to-edit deterministically (mirrors\n * Sanity's `data-sanity` / BaseHub's `data-basehub`). Entry-backed templates\n * hand-render field values (`f.title`, `f.body.html`), so the field `path` is\n * declared here by the author — the delivery payload carries no source-map.\n *\n * Server-safe (no hooks): renders in a Next Server Component. By default it wraps\n * children in a `display:contents` span, invisible to layout/GSAP; pass `as` to\n * carry the attributes on a real element instead.\n *\n * `path` follows the editor grammar: `title` · `hero.title` · `facts[2].label`\n * (dotted keys, at most one array index). For images, put the attributes on the\n * `<img>` itself (`kind=\"image\"` reflection patches `.src`), not on a wrapper:\n * <img src={f.cover.url} data-bcms-field=\"cover\" data-bcms-kind=\"image\" />\n */\nimport type { ElementType, ReactNode } from \"react\";\n\nexport interface BcmsFieldProps {\n /** Field path in the editor grammar, e.g. `title` or `facts[2].label`. */\n path: string;\n /** Kind hint the editor's reflection branches on. Omit for plain text/number. */\n kind?: \"richtext\" | \"image\";\n /** Wrapper element. Defaults to a `display:contents` span. */\n as?: ElementType;\n children: ReactNode;\n}\n\nexport function BcmsField({ path, kind, as, children }: BcmsFieldProps) {\n const Tag = as ?? \"span\";\n return (\n <Tag\n data-bcms-field={path}\n data-bcms-kind={kind}\n style={as ? undefined : { display: \"contents\" }}\n >\n {children}\n </Tag>\n );\n}\n","/**\n * defineBetterCMSLive — build the live SSE URL for `<BcmsLive>` from your config.\n * Server-safe (no React); pass the returned `liveSrc` to the client component.\n */\nexport interface BetterCMSLiveConfig {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n workspace: string;\n /** A content:read key — exposed to the browser via the SSE URL query. */\n apiKey: string;\n /**\n * Reference hydration depth for the pushed document. Default 1, matching the\n * delivery API. Set 0 when you only render top-level fields — a smaller doc is\n * a faster frame.\n */\n depth?: 0 | 1 | 2;\n /**\n * Stream draft autosaves too, so a preview surface repaints as the editor types.\n * Requires a `content:read:draft` key; the server ignores the flag for any other\n * key rather than failing the connection. Never enable this on a public site —\n * the key it needs can read unpublished content.\n */\n drafts?: boolean;\n}\n\nexport function defineBetterCMSLive(config: BetterCMSLiveConfig): { liveSrc: string } {\n const base = config.apiUrl.replace(/\\/+$/, \"\");\n const q = new URLSearchParams({ key: config.apiKey });\n if (config.depth !== undefined) q.set(\"depth\", String(config.depth));\n if (config.drafts) q.set(\"drafts\", \"1\");\n const liveSrc = `${base}/api/v1/delivery/${config.workspace}/live?${q}`;\n return { liveSrc };\n}\n","/**\n * createRevalidateRoute — App Router POST handler that receives the backend's\n * revalidation webhook and calls `revalidateTag()` for each affected tag. This is\n * the production live path (publish → backend webhook → revalidate ISR cache).\n *\n * import { createRevalidateRoute } from \"@bettercms-ai/next\";\n * export const { POST } = createRevalidateRoute({ secret: process.env.BCMS_REVALIDATE_SECRET });\n *\n * When `secret` is set, the `X-BetterCMS-Signature` HMAC-SHA256 header is verified\n * against the raw body (the same secret configured on the project in the dashboard).\n */\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\n\nexport interface RevalidateRouteConfig {\n /** Shared secret matching the project's revalidation webhook secret. */\n secret?: string;\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const ab = Buffer.from(a);\n const bb = Buffer.from(b);\n return ab.length === bb.length && timingSafeEqual(ab, bb);\n}\n\nexport function createRevalidateRoute(config: RevalidateRouteConfig = {}) {\n async function POST(request: Request): Promise<Response> {\n const body = await request.text();\n\n if (config.secret) {\n const provided = request.headers.get(\"x-bettercms-signature\") ?? \"\";\n const expected = `sha256=${createHmac(\"sha256\", config.secret).update(body).digest(\"hex\")}`;\n if (!safeEqual(provided, expected)) {\n return new Response(\"Invalid signature\", { status: 401 });\n }\n }\n\n let payload: { data?: { tags?: string[] } };\n try {\n payload = JSON.parse(body);\n } catch {\n return new Response(\"Invalid JSON\", { status: 400 });\n }\n\n const tags = payload.data?.tags ?? [];\n const { revalidateTag } = await import(\"next/cache\");\n for (const tag of tags) revalidateTag(tag);\n\n return Response.json({ revalidated: true, tags });\n }\n\n return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U,QAAQ,GAAG;AAClC,eAAO,IAAI,SAAS,qBAAqB,EAAE,QAAQ,IAAI,CAAC;AAAA,MAC1D;AAAA,IACF;AAEA,QAAI;AACJ,QAAI;AACF,gBAAU,KAAK,MAAM,IAAI;AAAA,IAC3B,QAAQ;AACN,aAAO,IAAI,SAAS,gBAAgB,EAAE,QAAQ,IAAI,CAAC;AAAA,IACrD;AAEA,UAAM,OAAO,QAAQ,MAAM,QAAQ,CAAC;AACpC,UAAM,EAAE,cAAc,IAAI,MAAM,OAAO,YAAY;AACnD,eAAW,OAAO,KAAM,eAAc,GAAG;AAEzC,WAAO,SAAS,KAAK,EAAE,aAAa,MAAM,KAAK,CAAC;AAAA,EAClD;AAEA,SAAO,EAAE,KAAK;AAChB;","names":["url","resolveSeo","default","readFileSync","resolve","readFileSync","resolve","readFileSync","resolve"]}
|
|
1
|
+
{"version":3,"sources":["../src/types.ts","../src/client.ts","../src/metadata.ts","../src/index.ts","../src/snapshot.ts","../src/llms-txt.ts","../src/preview.ts","../src/draft-route.ts","../src/forms-read.ts","../src/pages-read.ts","../src/components-read.ts","../src/field.tsx","../src/live-config.ts","../src/revalidate-route.ts"],"sourcesContent":["/**\n * Public types for @bettercms-ai/next.\n *\n * `BetterCMSEntry` mirrors the envelope emitted by @bettercms-ai/codegen's generated\n * file. The adapter normalizes the raw Delivery API response into exactly this shape,\n * so `getEntry`/`listEntries` line up 1:1 with your generated model types.\n */\n\n/** Normalized error thrown by adapter reads. Mirrors the SDK's BetterCMSError, but kept\n * local so the adapter carries no heavy runtime dependency into a consumer's bundle. */\nexport class BetterCMSError extends Error {\n readonly status: number;\n readonly code: string;\n\n constructor(message: string, status: number, code: string) {\n super(message);\n this.name = \"BetterCMSError\";\n this.status = status;\n this.code = code;\n }\n}\n\n/**\n * Delivery envelope around a model's typed `fields`. Returned by `getEntry`/`listEntries`.\n * Identical to the `BetterCMSEntry<TFields>` your generated types declare.\n *\n * `publishedAt`/`updatedAt` are ISO-8601 strings, or `null` when absent — never a\n * fabricated empty string (so `new Date(...)` is safe to attempt only on non-null).\n */\nexport interface BetterCMSEntry<TFields> {\n readonly slug: string;\n readonly status: \"draft\" | \"published\";\n readonly fields: TFields;\n readonly publishedAt: string | null;\n readonly updatedAt: string | null;\n}\n\nexport interface BetterCMSConfig {\n /** Workspace slug — the `:workspace` segment of the Delivery API path. */\n workspace: string;\n /** Optional delivery API key (sent as `Authorization: Bearer`). */\n apiKey?: string;\n /** Delivery API base. Default: `https://api.bettercms.ai/api/v1/delivery`. */\n baseUrl?: string;\n /** Preview API base. Default: derived from `baseUrl` (`/delivery` → `/preview`). */\n previewBaseUrl?: string;\n /**\n * Default Next.js revalidation for reads (seconds). `false` = always fresh\n * (`cache: \"no-store\"`). Per-call `revalidate` overrides this. Default: `60`.\n */\n revalidate?: number | false;\n}\n\n/** Per-read options shared by `getEntry` and `listEntries`. */\nexport interface ReadOptions {\n /** ISR window in seconds, or `false` for `cache: \"no-store\"`. Overrides config default. */\n revalidate?: number | false;\n /** Next.js cache tags for on-demand `revalidateTag()` invalidation. */\n tags?: string[];\n /** Reference hydration depth (0 = none, 1 = direct refs, 2 = nested). */\n depth?: 0 | 1 | 2;\n /** Field projection — only these field keys are returned. */\n select?: string[];\n}\n\n/** Options for `getEntry`, including draft-preview access. */\nexport interface GetEntryOptions extends ReadOptions {\n /** Fetch draft content via the preview endpoint. Requires `previewToken`. */\n preview?: boolean;\n /** Signed preview token (from `POST .../preview-token`). */\n previewToken?: string;\n}\n\n/** Options for `listEntries`. */\nexport interface ListEntriesOptions extends ReadOptions {\n /** 1-based page number. Default: 1. */\n page?: number;\n /** Items per page (max 100). Default: 20. */\n perPage?: number;\n}\n\n/** Paginated result returned by `listEntries`. */\nexport interface EntryList<TFields> {\n items: BetterCMSEntry<TFields>[];\n page: number;\n perPage: number;\n totalItems: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n}\n","/**\n * createBetterCMS — the Next.js delivery client.\n *\n * Reads run through the standard `fetch`, which the Next.js App Router patches to\n * participate in the data cache. We pass `next: { revalidate, tags }` so content is\n * cached/ISR'd and can be invalidated on publish via `revalidateTag()`.\n *\n * The raw Delivery API response is normalized into `BetterCMSEntry<TFields>` so the\n * return types match what @bettercms-ai/codegen generates.\n */\n\nimport type { ContentBlock, DeliveredLayout, PageMetaJson } from \"@bettercms-ai/types\";\nimport {\n BetterCMSError,\n type BetterCMSConfig,\n type BetterCMSEntry,\n type EntryList,\n type GetEntryOptions,\n type ListEntriesOptions,\n} from \"./types.js\";\n\n/** A published page with its block_json — feed `blocks` to `<BcmsBlocks>`.\n * The SEO fields (FLO-302) feed `buildMetadata` for the route's `generateMetadata`. */\nexport interface BetterCMSPage {\n slug: string;\n title: string;\n metaTitle: string | null;\n metaDescription: string | null;\n /** Rich SEO (OG / Twitter / canonical / JSON-LD). `null` when unset. */\n metaJson: PageMetaJson | null;\n blocks: ContentBlock[];\n layout?: DeliveredLayout | null;\n publishedAt: string | null;\n updatedAt: string | null;\n}\n\n/** Raw single-page shape returned by the Delivery API (`/content/:slug`). */\ninterface RawPageResponse {\n data: {\n slug: string;\n entry: {\n slug: string;\n title: string;\n metaTitle?: string | null;\n metaDescription?: string | null;\n metaJson?: PageMetaJson | null;\n blocks?: ContentBlock[];\n layout?: DeliveredLayout | null;\n updatedAt?: string | null;\n };\n publishedAt: string | null;\n };\n}\n\nconst DEFAULT_BASE_URL = \"https://api.bettercms.ai/api/v1/delivery\";\nconst DEFAULT_REVALIDATE = 60;\n\n/** `fetch`'s init augmented with Next.js's `next` cache directives. (`cache` is declared\n * explicitly because this package compiles without the DOM lib.) */\ntype NextRequestInit = RequestInit & {\n cache?: \"default\" | \"no-store\" | \"force-cache\";\n next?: { revalidate?: number | false; tags?: string[] };\n};\n\n/** Raw single-entry shape returned by the Delivery API. */\ninterface RawEntry {\n id: string;\n slug: string;\n status: \"draft\" | \"published\";\n publishedAt: string | null;\n updatedAt?: string | null;\n data: Record<string, unknown>;\n}\n\ninterface RawListResponse {\n data: {\n items: RawEntry[];\n page: number;\n perPage: number;\n totalItems: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n };\n}\n\nfunction statusToCode(status: number): string {\n if (status === 404) return \"CONTENT_NOT_FOUND\";\n if (status === 401) return \"UNAUTHORIZED\";\n if (status === 403) return \"FORBIDDEN\";\n if (status === 429) return \"RATE_LIMITED\";\n if (status === 422) return \"VALIDATION_ERROR\";\n return \"INTERNAL_ERROR\";\n}\n\n/** Normalize a raw delivery entry into the codegen-aligned envelope. `publishedAt`\n * and `updatedAt` are kept distinct and pass through `null` rather than being\n * conflated or fabricated as \"\" (which would parse to an Invalid Date). */\nfunction mapEntry<TFields>(raw: RawEntry): BetterCMSEntry<TFields> {\n return {\n slug: raw.slug,\n status: raw.status,\n fields: raw.data as TFields,\n publishedAt: raw.publishedAt ?? null,\n updatedAt: raw.updatedAt ?? null,\n };\n}\n\n/**\n * The typed BetterCMS reader for Next.js.\n *\n * @typeParam Schema - your generated `BetterCMSSchema` (slug → fields registry). When\n * supplied, `listEntries(\"blog\")` is typed by the model's fields and the model name\n * autocompletes. Defaults to an open record so it also works untyped.\n */\nexport interface BetterCMSNext<Schema extends Record<string, unknown>> {\n /** Fetch one published entry by its content slug. Returns `null` when not found.\n * Passing `select` narrows the result to `Partial<TFields>` (projection drops fields). */\n getEntry<TFields = unknown>(\n slug: string,\n opts: GetEntryOptions & { select: string[] },\n ): Promise<BetterCMSEntry<Partial<TFields>> | null>;\n getEntry<TFields = unknown>(\n slug: string,\n opts?: GetEntryOptions,\n ): Promise<BetterCMSEntry<TFields> | null>;\n\n /** List published entries, filtered to one model. Throws `BetterCMSError`\n * (CONTENT_NOT_FOUND) for an unknown workspace/model — an empty model returns an\n * empty page. Passing `select` narrows fields to `Partial`. */\n listEntries<M extends keyof Schema & string>(\n model: M,\n opts: ListEntriesOptions & { select: string[] },\n ): Promise<EntryList<Partial<Schema[M]>>>;\n listEntries<M extends keyof Schema & string>(\n model: M,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<Schema[M]>>;\n listEntries<TFields = unknown>(\n model?: string,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<TFields>>;\n\n /** Fetch one published page (with its `blocks` for `<BcmsBlocks>`) by slug.\n * Returns `null` when not found. */\n getPage(\n slug: string,\n opts?: { revalidate?: number | false; tags?: string[] },\n ): Promise<BetterCMSPage | null>;\n /** Fetch the project-scoped published Global Layout. */\n getLayout(opts?: { revalidate?: number | false; tags?: string[] }): Promise<DeliveredLayout | null>;\n}\n\nexport function createBetterCMS<\n Schema extends Record<string, unknown> = Record<string, unknown>,\n>(config: BetterCMSConfig): BetterCMSNext<Schema> {\n const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\");\n const previewBaseUrl = (\n config.previewBaseUrl ?? baseUrl.replace(/\\/delivery$/, \"/preview\")\n ).replace(/\\/+$/, \"\");\n const defaultRevalidate = config.revalidate ?? DEFAULT_REVALIDATE;\n\n function headers(): Record<string, string> {\n const h: Record<string, string> = { Accept: \"application/json\" };\n if (config.apiKey) h[\"Authorization\"] = `Bearer ${config.apiKey}`;\n return h;\n }\n\n function cacheInit(\n revalidate: number | false | undefined,\n tags: string[] | undefined,\n forceNoStore = false,\n ): NextRequestInit {\n const rv = revalidate ?? defaultRevalidate;\n // Preview is always uncached.\n if (forceNoStore) return { headers: headers(), cache: \"no-store\" };\n if (rv === false) {\n // With tags, \"false\" means cache until `revalidateTag` (the canonical CMS\n // publish-invalidation pattern) — we must NOT drop the tags to no-store, or\n // revalidateTag could never invalidate. Without tags, it means truly fresh.\n return tags?.length\n ? { headers: headers(), next: { revalidate: false, tags } }\n : { headers: headers(), cache: \"no-store\" };\n }\n return { headers: headers(), next: { revalidate: rv, tags } };\n }\n\n async function requestJSON<T>(\n url: string,\n init: NextRequestInit,\n { nullOn404 = false }: { nullOn404?: boolean } = {},\n ): Promise<T | null> {\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n throw new BetterCMSError(\n `Network error: ${err instanceof Error ? err.message : String(err)}`,\n 0,\n \"NETWORK_ERROR\",\n );\n }\n // A single-entry 404 is \"no such entry\" (→ null). A list 404 is a real error\n // (unknown workspace/model) and must surface, not masquerade as an empty list.\n if (res.status === 404 && nullOn404) return null;\n if (!res.ok) {\n let message = res.statusText || \"Request failed\";\n try {\n const body = (await res.json()) as { error?: string; message?: string };\n message = body.error ?? body.message ?? message;\n } catch {\n /* ignore parse errors */\n }\n throw new BetterCMSError(message, res.status, statusToCode(res.status));\n }\n return (await res.json()) as T;\n }\n\n function entryQuery(opts?: { depth?: 0 | 1 | 2; select?: string[] }): string {\n const params = new URLSearchParams();\n if (opts?.depth != null) params.set(\"depth\", String(opts.depth));\n if (opts?.select?.length) params.set(\"select\", opts.select.join(\",\"));\n const qs = params.toString();\n return qs ? `?${qs}` : \"\";\n }\n\n const client = {\n async getEntry<TFields = unknown>(slug: string, opts?: GetEntryOptions) {\n const encoded = encodeURIComponent(slug);\n const query = entryQuery(opts);\n\n // Preview: drafts are only reachable through the signed preview endpoint, and\n // must never be cached (every request re-validates the token server-side).\n if (opts?.preview) {\n if (!opts.previewToken) {\n throw new BetterCMSError(\n \"preview: true requires a previewToken\",\n 400,\n \"VALIDATION_ERROR\",\n );\n }\n const tokenParam = `token=${encodeURIComponent(opts.previewToken)}`;\n const sep = query ? \"&\" : \"?\";\n const url = `${previewBaseUrl}/${encoded}${query}${sep}${tokenParam}`;\n const body = await requestJSON<{ data: RawEntry }>(\n url,\n cacheInit(undefined, undefined, true),\n { nullOn404: true },\n );\n return body ? mapEntry<TFields>(body.data) : null;\n }\n\n const url = `${baseUrl}/${config.workspace}/content-entries/${encoded}${query}`;\n const raw = await requestJSON<RawEntry>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n return raw ? mapEntry<TFields>(raw) : null;\n },\n\n async listEntries<TFields = unknown>(\n model?: string,\n opts?: ListEntriesOptions,\n ): Promise<EntryList<TFields>> {\n const params = new URLSearchParams();\n if (model) params.set(\"model\", model);\n if (opts?.page != null) params.set(\"page\", String(opts.page));\n if (opts?.perPage != null) params.set(\"perPage\", String(opts.perPage));\n if (opts?.depth != null) params.set(\"depth\", String(opts.depth));\n if (opts?.select?.length) params.set(\"select\", opts.select.join(\",\"));\n\n const url = `${baseUrl}/${config.workspace}/content-entries?${params}`;\n const body = await requestJSON<RawListResponse>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n );\n\n const data = body?.data;\n if (!data) {\n return {\n items: [],\n page: opts?.page ?? 1,\n perPage: opts?.perPage ?? 20,\n totalItems: 0,\n totalPages: 1,\n hasNextPage: false,\n hasPreviousPage: false,\n };\n }\n return {\n items: data.items.map((r) => mapEntry<TFields>(r)),\n page: data.page,\n perPage: data.perPage,\n totalItems: data.totalItems,\n totalPages: data.totalPages,\n hasNextPage: data.hasNextPage,\n hasPreviousPage: data.hasPreviousPage,\n };\n },\n\n async getPage(\n slug: string,\n opts?: { revalidate?: number | false; tags?: string[] },\n ): Promise<BetterCMSPage | null> {\n const url = `${baseUrl}/${config.workspace}/content/${encodeURIComponent(slug)}`;\n const body = await requestJSON<RawPageResponse>(\n url,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n if (!body) return null;\n const { entry, publishedAt } = body.data;\n return {\n slug: entry.slug,\n title: entry.title,\n metaTitle: entry.metaTitle ?? null,\n metaDescription: entry.metaDescription ?? null,\n metaJson: entry.metaJson ?? null,\n blocks: entry.blocks ?? [],\n layout: entry.layout ?? null,\n publishedAt: publishedAt ?? null,\n updatedAt: entry.updatedAt ?? null,\n };\n },\n\n async getLayout(opts?: { revalidate?: number | false; tags?: string[] }) {\n const body = await requestJSON<{ data: DeliveredLayout }>(\n `${baseUrl}/${config.workspace}/layout`,\n cacheInit(opts?.revalidate, opts?.tags),\n { nullOn404: true },\n );\n return body?.data ?? null;\n },\n };\n\n // The concrete impls use single generic signatures; the public interface exposes\n // richer overloads (select→Partial, model-keyed typing). Cast once here.\n return client as unknown as BetterCMSNext<Schema>;\n}\n","/**\n * buildMetadata — map a BetterCMS page's SEO onto a Next.js `Metadata` object.\n *\n * Wire it into a route's `generateMetadata` so per-page Meta Title / Description and\n * the rich OG / Twitter / canonical the dashboard saves drive the live `<head>`:\n *\n * import { createBetterCMS, buildMetadata } from \"@bettercms-ai/next\";\n * const bcms = createBetterCMS({ workspace: \"acme\" });\n *\n * export async function generateMetadata({ params }): Promise<Metadata> {\n * const page = await bcms.getPage(params.slug);\n * if (!page) return {};\n * return buildMetadata(page, siteDefaults); // siteDefaults optional\n * }\n *\n * JSON-LD isn't part of Next's `Metadata`; render `resolveSeo(page, defaults).jsonLd`\n * as a `<script type=\"application/ld+json\">` in the page component (see the README).\n *\n * The merge (page-over-site) is delegated to `resolveSeo` (@bettercms-ai/sdk), the same\n * resolver the Astro adapter uses — so every surface stays consistent.\n */\nimport type { Metadata } from \"next\";\nimport { resolveSeo, type SeoInput, type SeoLocation } from \"@bettercms-ai/sdk\";\nimport type { SiteSeoDefaults } from \"@bettercms-ai/types\";\n\n/**\n * Build a Next.js `Metadata` from a BetterCMS page, layering page meta over site defaults.\n *\n * Pass `location` — `{ siteUrl, path }` — to get a canonical (and `og:url`) on pages that set\n * none of their own. Omit it and both tags are absent, which is what a headless app shipped\n * before this parameter existed. The hosted renderer always emits them, so a headless site\n * without `location` is the ONE surface that silently differs from its hosted twin.\n */\nexport function buildMetadata(\n page: SeoInput,\n siteDefaults: SiteSeoDefaults = {},\n location: SeoLocation = {},\n): Metadata {\n const seo = resolveSeo(page, siteDefaults, location);\n return {\n title: seo.title || undefined,\n description: seo.description || undefined,\n alternates: seo.canonical ? { canonical: seo.canonical } : undefined,\n openGraph: {\n title: seo.og.title || undefined,\n description: seo.og.description || undefined,\n type: (seo.og.type || \"website\") as \"website\",\n url: seo.og.url || undefined,\n images: seo.og.image ? [{ url: seo.og.image }] : undefined,\n },\n twitter: {\n card: (seo.twitter.card || \"summary\") as \"summary\" | \"summary_large_image\",\n title: seo.twitter.title || undefined,\n description: seo.twitter.description || undefined,\n images: seo.twitter.image ? [seo.twitter.image] : undefined,\n site: seo.twitter.site || undefined,\n },\n };\n}\n","/**\n * @bettercms-ai/next — the BetterCMS adapter for Next.js.\n *\n * Pair with @bettercms-ai/codegen: generate `BetterCMSSchema` from your content models,\n * then `createBetterCMS<BetterCMSSchema>(...)` for typed, cache-aware reads in the App Router.\n */\n\nexport { createBetterCMS } from \"./client.js\";\nexport type { BetterCMSNext, BetterCMSPage } from \"./client.js\";\n\n// SEO (FLO-302): map a page's per-page-over-site SEO into a Next `Metadata` for\n// `generateMetadata`. `resolveSeo` (+ its types) is re-exported for JSON-LD / custom heads.\nexport { buildMetadata } from \"./metadata.js\";\nexport { resolveSeo } from \"@bettercms-ai/sdk\";\nexport type { SeoInput, ResolvedSeo } from \"@bettercms-ai/sdk\";\nexport type { PageMetaJson, SiteSeoDefaults } from \"@bettercms-ai/types\";\nexport type { DeliveredLayout } from \"@bettercms-ai/types\";\n\nexport { BetterCMSError } from \"./types.js\";\nexport type {\n BetterCMSConfig,\n BetterCMSEntry,\n ReadOptions,\n GetEntryOptions,\n ListEntriesOptions,\n EntryList,\n} from \"./types.js\";\n\nexport {\n getContent,\n buildSnapshot,\n writeSnapshot,\n readSnapshot,\n serializeSnapshot,\n parseSnapshot,\n SNAPSHOT_VERSION,\n DEFAULT_SNAPSHOT_FILE,\n} from \"./snapshot.js\";\nexport type { ContentSource, ContentSnapshot } from \"./snapshot.js\";\n\nexport { generateLlmsTxt, llmsTxtRoute, fetchModels } from \"./llms-txt.js\";\nexport type {\n LlmsModel,\n LlmsModelField,\n LlmsTxtOptions,\n LlmsTxtRouteConfig,\n} from \"./llms-txt.js\";\n\nexport { isDraftEnabled, getPreviewToken } from \"./preview.js\";\n\n// Draft-mode route-handler factories for the App Router.\nexport {\n createDraftModeRoute,\n createDisableDraftRoute,\n PREVIEW_TOKEN_COOKIE,\n} from \"./draft-route.js\";\nexport type { DraftModeRouteConfig } from \"./draft-route.js\";\n\n// Image URL builder — `import { imageUrlBuilder } from \"@bettercms-ai/next\"`.\nexport { default as imageUrlBuilder, imageUrl } from \"@bettercms-ai/image-url\";\nexport type {\n ImageUrlBuilder,\n ImageSource,\n ImageFormat,\n ImageFit,\n} from \"@bettercms-ai/image-url\";\n\n// Build-time forms reader for the deploy Action's snapshot (server-side).\nexport { readForms, getForm } from \"./forms-read.js\";\nexport type { SnapshotForms } from \"./forms-read.js\";\n\n// Build-time pages reader for the deploy Action's snapshot (server-side). Pair with\n// <BcmsBlocks> to render a page's block_json: readPages()/getPage(slug) → page.blocks.\nexport { readPages, getPage } from \"./pages-read.js\";\nexport type { SnapshotPage } from \"./pages-read.js\";\n\n// Build-time components reader — pass to <BcmsBlocks components={…} /> so `component`\n// blocks resolve their reusable definitions.\nexport { readComponents, getComponent } from \"./components-read.js\";\n\n// <BcmsForm> / <BcmsBlocks> are client components and ship from their own \"use client\"\n// entries so the React Server Components boundary survives bundling:\n// import { BcmsForm } from \"@bettercms-ai/next/form\";\n// import { BcmsBlocks } from \"@bettercms-ai/next/blocks\";\nexport type { BcmsFormProps } from \"./form.js\";\nexport type { BcmsBlocksProps } from \"./blocks.js\";\n\n// <BcmsField> tags an entry field's value so the visual editor binds click-to-edit\n// deterministically. Server-safe (no \"use client\"): import from \"@bettercms-ai/next\".\nexport { BcmsField } from \"./field.js\";\nexport type { BcmsFieldProps } from \"./field.js\";\n\n// Live content + revalidation (mirrors next-sanity defineLive/<SanityLive>).\n// import { BcmsLive } from \"@bettercms-ai/next/live\";\nexport type { BcmsLiveProps } from \"./live.js\";\nexport { defineBetterCMSLive } from \"./live-config.js\";\nexport type { BetterCMSLiveConfig } from \"./live-config.js\";\nexport { createRevalidateRoute } from \"./revalidate-route.js\";\nexport type { RevalidateRouteConfig } from \"./revalidate-route.js\";\n\n// Visual editing overlay (client). import { VisualEditing } from \"@bettercms-ai/next/visual-editing\"\nexport type { VisualEditingProps } from \"./visual-editing.js\";\n","/**\n * Build-time content snapshot — the writer + reader of `bcms-content.json`.\n *\n * Why this exists: a static (`output: \"export\"`) build must resolve all content at\n * build time. If a page instead falls back to a live `cache: \"no-store\"` fetch, its\n * route becomes dynamic and `output: \"export\"` silently drops it — you get an empty\n * `out/`. The fix is a single build-time snapshot the pages read synchronously.\n *\n * The WRITER (`buildSnapshot`/`writeSnapshot`, used by the `bettercms-snapshot` bin)\n * and the READER (`getContent`) share ONE serializer (`serializeSnapshot`/\n * `parseSnapshot`) so the on-disk shape can never drift between the two halves.\n *\n * This is intentionally separate from {@link createBetterCMS}: that stays the live,\n * network-backed client. `getContent` is the snapshot-preferring reader a static\n * site uses. Existing consumers that deliberately rely on the live fallback are\n * unaffected — only `getContent` enforces \"snapshot or bust\".\n */\n\nimport { readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport {\n BetterCMSError,\n type BetterCMSConfig,\n type BetterCMSEntry,\n type EntryList,\n type ListEntriesOptions,\n} from \"./types.js\";\nimport { createBetterCMS } from \"./client.js\";\n\n/** Bump when the on-disk shape changes incompatibly — readers reject mismatches. */\nexport const SNAPSHOT_VERSION = 1;\n/** Default snapshot filename, resolved against `process.cwd()`. */\nexport const DEFAULT_SNAPSHOT_FILE = \"bcms-content.json\";\n\n/** The full-site content snapshot. Entries are grouped by model slug so the reader\n * can serve `listEntries(model)` offline without a per-entry model tag. */\nexport interface ContentSnapshot {\n version: number;\n workspace: string;\n generatedAt: string;\n models: Record<string, BetterCMSEntry<unknown>[]>;\n}\n\n// ── Serializer (shared by writer + reader — single source of on-disk shape) ──────\n\n/** Serialize a snapshot to the canonical JSON form written to disk. */\nexport function serializeSnapshot(snapshot: ContentSnapshot): string {\n return JSON.stringify(snapshot, null, 2);\n}\n\n/** Parse + validate a snapshot JSON string. Throws on a version mismatch so a stale\n * snapshot fails loudly rather than feeding the build the wrong shape. */\nexport function parseSnapshot(json: string): ContentSnapshot {\n const parsed = JSON.parse(json) as ContentSnapshot;\n if (parsed.version !== SNAPSHOT_VERSION) {\n throw new BetterCMSError(\n `Unsupported bcms-content.json version ${parsed.version} (expected ${SNAPSHOT_VERSION}). ` +\n `Regenerate it with \"bettercms-snapshot\".`,\n 0,\n \"SNAPSHOT_VERSION_MISMATCH\",\n );\n }\n return parsed;\n}\n\n// ── Disk I/O ─────────────────────────────────────────────────────────────────────\n\n/** Write a snapshot to `path` (relative paths resolve against cwd), creating dirs. */\nexport function writeSnapshot(path: string, snapshot: ContentSnapshot): void {\n const out = resolve(process.cwd(), path);\n mkdirSync(dirname(out), { recursive: true });\n writeFileSync(out, serializeSnapshot(snapshot), \"utf8\");\n}\n\n/** Read + parse a snapshot from `path`. Returns `null` only when the file is absent;\n * a present-but-corrupt/stale file throws (callers must not treat that as \"missing\"). */\nexport function readSnapshot(path: string): ContentSnapshot | null {\n const out = resolve(process.cwd(), path);\n let json: string;\n try {\n json = readFileSync(out, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code === \"ENOENT\") return null;\n throw err;\n }\n return parseSnapshot(json);\n}\n\n// ── Writer: build a snapshot from the live API ────────────────────────────────────\n\n/** Minimal client surface `buildSnapshot` needs — lets tests inject a fake. Kept\n * non-generic so a simple fake (and the live client's matching overload) both fit. */\ntype ListOnly = {\n listEntries(model?: string, opts?: ListEntriesOptions): Promise<EntryList<unknown>>;\n};\n\n/**\n * Page through every model's published entries and assemble a full-site snapshot.\n * `modelSlugs` come from the Management API (`fetchModels`) so the snapshot covers\n * exactly this project's schema. Pass `client` in tests; defaults to the live client.\n */\nexport async function buildSnapshot(opts: {\n config: BetterCMSConfig;\n modelSlugs: string[];\n client?: ListOnly;\n /** Stamped into `generatedAt`; injectable for deterministic tests. */\n now?: string;\n}): Promise<ContentSnapshot> {\n const client = opts.client ?? createBetterCMS(opts.config);\n const models: Record<string, BetterCMSEntry<unknown>[]> = {};\n for (const slug of opts.modelSlugs) {\n const all: BetterCMSEntry<unknown>[] = [];\n let page = 1;\n for (;;) {\n // revalidate:false → bypass any data cache; this is a one-shot build fetch.\n const res = await client.listEntries(slug, { page, perPage: 100, revalidate: false });\n all.push(...res.items);\n if (!res.hasNextPage) break;\n page += 1;\n }\n models[slug] = all;\n }\n return {\n version: SNAPSHOT_VERSION,\n workspace: opts.config.workspace,\n generatedAt: opts.now ?? new Date().toISOString(),\n models,\n };\n}\n\n// ── Reader: getContent (snapshot-preferring, loud on absence) ─────────────────────\n\n/** Snapshot-backed content reader. Async so it can transparently fall back to the\n * live client in preview without changing the call sites. */\nexport interface ContentSource {\n getEntry<TFields = unknown>(slug: string): Promise<BetterCMSEntry<TFields> | null>;\n listEntries<TFields = unknown>(model?: string): Promise<EntryList<TFields>>;\n}\n\n/** `BETTERCMS_PREVIEW` truthy → read live (uncached), never the snapshot. */\nfunction isPreview(): boolean {\n const v = (\n globalThis as { process?: { env?: Record<string, string | undefined> } }\n ).process?.env?.BETTERCMS_PREVIEW;\n return v != null && v !== \"\" && v !== \"0\" && v !== \"false\";\n}\n\n/** Parsed snapshots keyed by resolved path — read+parse once per build process. */\nconst snapshotCache = new Map<string, ContentSnapshot>();\n\n/** Test-only: clear the module-scope snapshot cache between cases. */\nexport function __resetSnapshotCacheForTests(): void {\n snapshotCache.clear();\n}\n\nfunction emptyPage<TFields>(items: BetterCMSEntry<TFields>[]): EntryList<TFields> {\n return {\n items,\n page: 1,\n perPage: items.length,\n totalItems: items.length,\n totalPages: 1,\n hasNextPage: false,\n hasPreviousPage: false,\n };\n}\n\n/**\n * The reader a static site should use. In a normal (export) build it reads the\n * memoized `bcms-content.json` and serves entries from memory. If the snapshot is\n * absent it THROWS a clear, actionable error — the whole point is to turn the old\n * silent empty-`out/` failure into a loud build error. Set `BETTERCMS_PREVIEW=1`\n * for a preview build that reads live instead.\n */\nexport function getContent<\n Schema extends Record<string, unknown> = Record<string, unknown>,\n>(config: BetterCMSConfig, opts: { snapshotPath?: string } = {}): ContentSource {\n const path = opts.snapshotPath ?? DEFAULT_SNAPSHOT_FILE;\n\n if (isPreview()) {\n const live = createBetterCMS<Schema>(config);\n return {\n getEntry: (slug) => live.getEntry(slug, { revalidate: false }),\n listEntries: (model) => live.listEntries(model, { revalidate: false }),\n };\n }\n\n const resolved = resolve(process.cwd(), path);\n function load(): ContentSnapshot {\n const cached = snapshotCache.get(resolved);\n if (cached) return cached;\n const snap = readSnapshot(path);\n if (!snap) {\n throw new BetterCMSError(\n `BetterCMS content snapshot \"${path}\" not found. A static (output: \"export\") build reads ` +\n `content from this snapshot; without it pages fall back to a live no-store fetch, become ` +\n `dynamic routes, and output: \"export\" silently drops them (empty out/). Run ` +\n `\"bettercms-snapshot\" before \"next build\" (make it your build:preview prestep), or set ` +\n `BETTERCMS_PREVIEW=1 to read live in a preview build.`,\n 0,\n \"SNAPSHOT_MISSING\",\n );\n }\n snapshotCache.set(resolved, snap);\n return snap;\n }\n\n return {\n async getEntry<TFields = unknown>(slug: string) {\n const snap = load();\n for (const entries of Object.values(snap.models)) {\n const found = entries.find((e) => e.slug === slug);\n if (found) return found as BetterCMSEntry<TFields>;\n }\n return null;\n },\n async listEntries<TFields = unknown>(model?: string) {\n const snap = load();\n const items = (\n model ? (snap.models[model] ?? []) : Object.values(snap.models).flat()\n ) as BetterCMSEntry<TFields>[];\n return emptyPage(items);\n },\n };\n}\n","/**\n * llms.txt generation — the AI-discovery surface of the deterministic floor.\n *\n * `generateLlmsTxt` is pure (models in → string out), so it is trivially testable and\n * deterministic. `llmsTxtRoute` wraps it as an App Router `route.ts` handler. `fetchModels`\n * pulls the live schema from the Management API for sites that want a self-updating file.\n *\n * Output follows the llmstxt.org convention: an H1 title, a `>` summary, then sections.\n */\n\n/** Minimal field shape needed to describe a model in llms.txt. */\nexport interface LlmsModelField {\n key: string;\n label?: string;\n type: string;\n required?: boolean;\n}\n\n/** Minimal model shape — a subset of the Management API model row. */\nexport interface LlmsModel {\n slug: string;\n name?: string;\n description?: string | null;\n fields: LlmsModelField[];\n}\n\nexport interface LlmsTxtOptions {\n /** H1 title. Default: \"BetterCMS content\". */\n title?: string;\n /** One-line `>` summary under the title. */\n description?: string;\n /** Delivery API base used to render example endpoints. */\n baseUrl?: string;\n /** Workspace slug used in example endpoints. */\n workspace?: string;\n /** Extra free-form lines appended under a \"## Notes\" section. */\n notes?: string[];\n}\n\n// Model name/slug/description and field key/label/type are author/agent-controlled\n// (the same content the sibling codegen package treats as hostile via escapeJsDoc).\n// llms.txt is fed to AI crawlers, so unescaped values could forge headings/blockquotes\n// or break out of code spans — a structure-spoofing / prompt-injection vector.\n\n/** Collapse to a single line — kills newline-based block injection. */\nfunction oneLine(text: string): string {\n return text.replace(/[\\r\\n]+/g, \" \").trim();\n}\n\n/** For text rendered OUTSIDE a code span (titles, descriptions, labels): single-line +\n * escape a leading markdown block-control char so it can't start a heading/list/quote. */\nfunction inlineText(text: string): string {\n return oneLine(text).replace(/^([#>\\-*+=|])/, \"\\\\$1\");\n}\n\n/** For text rendered INSIDE a code span: strip backticks (which would close the span)\n * and newlines. */\nfunction codeSpan(text: string): string {\n return oneLine(text).replace(/`/g, \"\");\n}\n\nfunction fieldLine(f: LlmsModelField): string {\n const req = f.required ? \", required\" : \"\";\n const label = f.label && f.label !== f.key ? ` — ${inlineText(f.label)}` : \"\";\n return ` - \\`${codeSpan(f.key)}\\` (${codeSpan(f.type)}${req})${label}`;\n}\n\n/**\n * Render an llms.txt document describing the available content models. Deterministic:\n * models are sorted by slug; field order is preserved as authored.\n */\nexport function generateLlmsTxt(models: LlmsModel[], opts: LlmsTxtOptions = {}): string {\n const title = opts.title ?? \"BetterCMS content\";\n const sorted = [...models].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const lines: string[] = [`# ${inlineText(title)}`, \"\"];\n if (opts.description) {\n lines.push(`> ${inlineText(opts.description)}`, \"\");\n }\n\n const base =\n opts.baseUrl && opts.workspace\n ? `${opts.baseUrl.replace(/\\/+$/, \"\")}/${opts.workspace}/content-entries`\n : undefined;\n\n lines.push(\"## Content models\", \"\");\n if (sorted.length === 0) {\n lines.push(\"_No content models are defined yet._\", \"\");\n }\n for (const model of sorted) {\n const name = model.name ?? model.slug;\n lines.push(`### ${inlineText(name)} (\\`${codeSpan(model.slug)}\\`)`);\n if (model.description) lines.push(\"\", inlineText(model.description));\n if (base) {\n lines.push(\"\", `- List: \\`GET ${base}?model=${codeSpan(model.slug)}\\``);\n lines.push(`- Entry: \\`GET ${base}/{slug}\\``);\n }\n if (model.fields.length) {\n lines.push(\"\", \"Fields:\");\n for (const f of model.fields) lines.push(fieldLine(f));\n }\n lines.push(\"\");\n }\n\n if (opts.notes?.length) {\n lines.push(\"## Notes\", \"\");\n for (const note of opts.notes) lines.push(`- ${inlineText(note)}`);\n lines.push(\"\");\n }\n\n return lines.join(\"\\n\");\n}\n\n// ── Integration SKILL.md ────────────────────────────────────────────────────────\n// A framework-agnostic agent skill (frontmatter + lean body) that teaches an AI how\n// to READ this project's content from the Delivery API. Unlike llms.txt it does NOT\n// dump every field — it points at the live types endpoint so the schema can't go\n// stale, and names content types by slug only. Drop at .claude/skills/<name>/SKILL.md.\n\n/** A content type named in the skill — slug + kind only (no fields). */\nexport interface SkillContentType {\n kind: \"page\" | \"model\";\n slug: string;\n /** \"singleton\" | \"dynamic\" for pages; omitted for models. */\n pageType?: string | null;\n}\n\nexport interface SkillOptions {\n /** Human project name (skill title + description). */\n projectName: string;\n /** Project slug → the skill's kebab-case `name:`. */\n projectSlug: string;\n /** Delivery + management API base, e.g. https://api.bettercms.ai/api/v1. */\n apiUrl: string;\n /** Workspace slug used in the delivery paths. */\n workspace: string;\n /** Where to mint a content:read delivery key. */\n mintUrl: string;\n /** Key-authed live TypeScript types endpoint. */\n typesUrl: string;\n /** This project's content types (pages + models), by slug — no field dump. */\n contentTypes: SkillContentType[];\n}\n\n/**\n * Render a concise, framework-agnostic SKILL.md describing how to read THIS\n * project's content from the BetterCMS Delivery API. Deterministic: content types\n * sorted by slug. Author-controlled strings (project name, slugs, pageType) are\n * injection-escaped, same as {@link generateLlmsTxt}.\n */\nexport type SkillTarget = \"claude\" | \"cursor\" | \"agents\";\n\nexport interface SkillVariant {\n /** The agent/IDE this variant targets. */\n target: SkillTarget;\n /** Human label for a tab/picker. */\n label: string;\n /** Suggested path to save the file, e.g. `.claude/skills/<name>/SKILL.md`. */\n filename: string;\n /** Full file content (target-specific frontmatter + the shared body). */\n content: string;\n}\n\n/** The shared, tool-agnostic instruction body — no frontmatter, no save hint. */\nfunction skillBody(opts: SkillOptions): string {\n const proj = inlineText(opts.projectName);\n const api = opts.apiUrl.replace(/\\/+$/, \"\");\n const deliveryBase = `${api}/delivery/${codeSpan(opts.workspace)}`;\n const sorted = [...opts.contentTypes].sort((a, b) =>\n a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0,\n );\n\n const lines: string[] = [\n `# BetterCMS — ${proj}`,\n \"\",\n `${proj}'s content lives in BetterCMS. Read it through the Delivery API with a project ` +\n \"`content:read` key. Pull field shapes live from the types endpoint below — don't hardcode \" +\n \"them, the schema can change.\",\n \"\",\n \"## Auth\",\n \"Send `X-API-Key: <key>` on every read. Mint a long-lived `content:read` key (reads PUBLISHED \" +\n `content, never expires) at ${opts.mintUrl}. For drafts, mint a \\`content:read:draft\\` key ` +\n \"(force-expired to ≤1h), then publish and switch to the long-lived key.\",\n \"\",\n \"## Content types\",\n ];\n if (sorted.length === 0) {\n lines.push(\"_None yet — create pages or models first (e.g. via the BetterCMS MCP)._\");\n } else {\n for (const ct of sorted) {\n const kind =\n ct.kind === \"page\"\n ? `page${ct.pageType ? ` (${codeSpan(ct.pageType)})` : \"\"}`\n : \"model\";\n lines.push(`- \\`${codeSpan(ct.slug)}\\` — ${kind}`);\n }\n }\n lines.push(\n \"\",\n `## Reading (Delivery API · base \\`${deliveryBase}\\`)`,\n \"- Page: `GET .../content/{slug}`\",\n \"- Entries (list): `GET .../content-entries?model={slug}`\",\n \"- Entry: `GET .../content-entries/{slug}`\",\n \"\",\n \"## Typed client\",\n `- Live TypeScript types: \\`GET ${opts.typesUrl}\\` — authoritative field shapes; generate/refresh from here.`,\n \"- `npm i @bettercms-ai/next @bettercms-ai/codegen`, then construct the client. \" +\n \"`baseUrl` + `workspace` are required — there is no `apiUrl`/`endpoint` option:\",\n \"\",\n \"```ts\",\n 'import { createBetterCMS } from \"@bettercms-ai/next\";',\n \"const cms = createBetterCMS<BetterCMSSchema>({\",\n ` baseUrl: \"${api}/delivery\",`,\n ` workspace: \"${codeSpan(opts.workspace)}\",`,\n \" apiKey: process.env.BETTERCMS_API_KEY,\",\n \"});\",\n \"```\",\n \"\",\n \"## Field shapes you'll read\",\n \"Canonical READ shapes the Delivery API returns. Per-field types come from the types \" +\n \"endpoint; these container shapes are stable:\",\n '- **richtext** → `{ html, value: { root: … }, format: \"lexical-…\" }`. Render `html`, ' +\n \"or walk `value.root` for structured rendering.\",\n \"- **image** → `{ url, altText?, width?, height?, id? }` — an object, use `.url` (the \" +\n \"write value is a bare CDN URL string, but reads are normalized to this object).\",\n \"- **array + zones** → `{ nonRepeatable?: { <key>: value }, repeatable?: Array<{ <key>: \" +\n \"value }> }`. `nonRepeatable` is one fixed block; `repeatable` is a list — map over it.\",\n '- **array (primitive)** → a flat list (e.g. `string[]`). `type: \"array\"` alone is ' +\n \"ambiguous — the generated type tells you which.\",\n \"\",\n \"Example entry `fields` (a `sections` zone field + a `tags` primitive array):\",\n \"```jsonc\",\n \"{\",\n ' \"sections\": {',\n ' \"nonRepeatable\": { \"eyebrow\": \"New\", \"heading\": \"Welcome\" },',\n ' \"repeatable\": [{ \"label\": \"Docs\", \"url\": \"/docs\", \"icon\": { \"url\": \"https://cdn…\" } }]',\n \" },\",\n ' \"tags\": [\"alpha\", \"beta\"]',\n \"}\",\n \"```\",\n \"\",\n \"## Live Preview bindings (makes the site visually editable)\",\n \"Generate a bindings module alongside the types and spread it so the dashboard's Live \" +\n \"Preview can edit each field in place:\",\n \"```bash\",\n `BETTERCMS_API_KEY=<key> npx bettercms-codegen --api-url ${api} --bindings-out src/bettercms.bindings.generated.ts`,\n \"```\",\n \"```tsx\",\n 'import { bcms } from \"./bettercms.bindings.generated\";',\n \"// scalar: <h1 {...bcms.<model>.<field>}>{entry.fields.field}</h1>\",\n \"// list item: <article {...bcms.<model>.<arr>.$(i)}><h3 {...bcms.<model>.<arr>.<sub>(i)}>{item.sub}</h3></article>\",\n \"// primitive list:<li {...bcms.<model>.<arr>.value(i)}>{tag}</li>\",\n \"```\",\n \"Bindings emit two inert `data-*` attributes on every build, so spreading them is \" +\n \"always safe.\",\n );\n return lines.join(\"\\n\");\n}\n\nfunction skillDescription(proj: string): string {\n return (\n `Read ${proj}'s content from BetterCMS via the Delivery API — auth, listing and fetching ` +\n \"pages and content entries, pulling live TypeScript types, and the @bettercms-ai/next typed \" +\n \"client. Use whenever fetching, rendering, or typing this project's CMS content.\"\n );\n}\n\n/**\n * Render the integration skill for a specific agent `target`. The instruction body is\n * identical across tools; only the frontmatter (and where you save it) differ:\n * - claude → Claude Code skill (`name` + `description`)\n * - cursor → Cursor `.mdc` rule (`description` + `globs` + `alwaysApply`, \"Agent Requested\")\n * - agents → plain Markdown, no frontmatter (drop into a repo-root `AGENTS.md`)\n */\nexport function generateSkill(opts: SkillOptions, target: SkillTarget = \"claude\"): string {\n const name = `bettercms-${codeSpan(opts.projectSlug)}`;\n const desc = skillDescription(inlineText(opts.projectName));\n const body = skillBody(opts);\n\n let frontmatter = \"\";\n if (target === \"claude\") {\n frontmatter = `---\\nname: ${name}\\ndescription: ${desc}\\n---\\n\\n`;\n } else if (target === \"cursor\") {\n frontmatter = `---\\ndescription: ${desc}\\nglobs:\\nalwaysApply: false\\n---\\n\\n`;\n }\n return `${frontmatter}${body}\\n`;\n}\n\nconst TARGET_META: Record<SkillTarget, { label: string; file: (name: string) => string }> = {\n claude: { label: \"Claude Code\", file: (n) => `.claude/skills/${n}/SKILL.md` },\n cursor: { label: \"Cursor\", file: (n) => `.cursor/rules/${n}.mdc` },\n agents: { label: \"AGENTS.md (generic)\", file: () => \"AGENTS.md\" },\n};\n\n/** Render the skill for every supported agent target — drives a tabbed picker in the UI. */\nexport function generateSkillVariants(opts: SkillOptions): SkillVariant[] {\n const name = `bettercms-${codeSpan(opts.projectSlug)}`;\n return (Object.keys(TARGET_META) as SkillTarget[]).map((target) => ({\n target,\n label: TARGET_META[target].label,\n filename: TARGET_META[target].file(name),\n content: generateSkill(opts, target),\n }));\n}\n\n/** Options for {@link llmsTxtRoute}. Provide one of `models` or `getModels`. */\nexport interface LlmsTxtRouteConfig extends LlmsTxtOptions {\n /** Static model list (e.g. fetched at build time). */\n models?: LlmsModel[];\n /** Dynamic provider — called per request (wrap in your own caching if needed). */\n getModels?: () => Promise<LlmsModel[]> | LlmsModel[];\n /** Cache-Control header value. Default: `public, max-age=3600`. */\n cacheControl?: string;\n}\n\n/**\n * Build an App Router route handler that serves llms.txt as `text/plain`.\n *\n * ```ts\n * // app/llms.txt/route.ts\n * import { llmsTxtRoute } from \"@bettercms-ai/next\";\n * export const GET = llmsTxtRoute({ models, title: \"Acme\", workspace: \"acme\" });\n * ```\n */\nexport function llmsTxtRoute(config: LlmsTxtRouteConfig): () => Promise<Response> {\n const { models, getModels, cacheControl, ...opts } = config;\n return async () => {\n const resolved = getModels ? await getModels() : (models ?? []);\n const body = generateLlmsTxt(resolved, opts);\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/plain; charset=utf-8\",\n \"Cache-Control\": cacheControl ?? \"public, max-age=3600\",\n },\n });\n };\n}\n\n/**\n * Fetch content models from the Management API (`GET /management/content/models`).\n * The key is project-scoped server-side, so this returns exactly this site's schema.\n * Dependency-free so it runs in any runtime (Edge route, build script, Node).\n */\nexport async function fetchModels(opts: {\n /** Management API base, e.g. \"https://api.bettercms.ai/api/v1\". */\n apiUrl: string;\n /** A management-scoped key (content:manage). */\n apiKey: string;\n /** Optional fetch override (testing / custom runtime). */\n fetchImpl?: typeof fetch;\n}): Promise<LlmsModel[]> {\n const doFetch = opts.fetchImpl ?? fetch;\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\n const res = await doFetch(`${base}/management/content/models`, {\n headers: { Authorization: `Bearer ${opts.apiKey}`, Accept: \"application/json\" },\n });\n if (!res.ok) {\n throw new Error(`Management API returned ${res.status} ${res.statusText}`);\n }\n const body = (await res.json()) as { data?: LlmsModel[] };\n return (body.data ?? []).map((m) => ({\n slug: m.slug,\n name: m.name,\n description: m.description ?? null,\n fields: m.fields ?? [],\n }));\n}\n","/**\n * Draft-preview helpers. `next/headers` is imported dynamically so this module is safe\n * to load outside a Next.js request scope (tests, build scripts) without throwing.\n */\n\n/** True when Next.js Draft Mode is enabled for the current request. */\nexport async function isDraftEnabled(): Promise<boolean> {\n const { draftMode } = await import(\"next/headers\");\n const dm = await draftMode();\n return dm.isEnabled;\n}\n\n/**\n * The preview token stored by `createDraftModeRoute`, or null. Pass it to\n * `getEntry(slug, { preview: true, previewToken })` to read drafts.\n */\nexport async function getPreviewToken(): Promise<string | null> {\n const { cookies } = await import(\"next/headers\");\n const jar = await cookies();\n return jar.get(\"bcms-preview-token\")?.value ?? null;\n}\n","/**\n * createDraftModeRoute — an App Router route-handler factory for entering draft\n * preview. Mount it at e.g. `app/api/draft/route.ts`:\n *\n * import { createDraftModeRoute } from \"@bettercms-ai/next\";\n * export const { GET } = createDraftModeRoute({ apiUrl: \"https://api.bettercms.ai\" });\n *\n * Visiting `/api/draft?token=<jwt>&redirect=/path` validates the preview token\n * against the backend (the signature authority), enables Next Draft Mode, stores\n * the token in an httpOnly cookie, and redirects. Reads can then pass the token\n * via `getPreviewToken()` to `getEntry({ preview: true, previewToken })`.\n */\n\nexport const PREVIEW_TOKEN_COOKIE = \"bcms-preview-token\";\n\nexport interface DraftModeRouteConfig {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n}\n\n/** Only same-origin relative paths. Blocks \"//evil.com\", \"https://evil.com\", etc. */\nfunction safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") ? to : \"/\";\n}\n\n/** Decode a preview-token JWT payload (UNVERIFIED) to read its `entrySlug`. */\nfunction decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = JSON.parse(\n Buffer.from(part, \"base64url\").toString(\"utf8\"),\n ) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\nexport function createDraftModeRoute(config: DraftModeRouteConfig) {\n const apiUrl = config.apiUrl.replace(/\\/+$/, \"\");\n\n async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n const redirectTo = url.searchParams.get(\"redirect\") ?? \"/\";\n\n if (!token) return new Response(\"Missing token\", { status: 400 });\n const slug = decodeTokenSlug(token);\n if (!slug) return new Response(\"Malformed token\", { status: 400 });\n\n const res = await fetch(\n `${apiUrl}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`,\n );\n if (!res.ok) return new Response(\"Invalid or expired token\", { status: 401 });\n\n const { draftMode, cookies } = await import(\"next/headers\");\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_TOKEN_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: url.protocol === \"https:\",\n path: \"/\",\n maxAge: 60 * 60 * 24,\n });\n\n return Response.redirect(new URL(safeRedirectPath(redirectTo), url.origin), 302);\n }\n\n return { GET };\n}\n\n/** Exit draft mode and clear the preview-token cookie. */\nexport function createDisableDraftRoute() {\n async function GET(request: Request): Promise<Response> {\n const url = new URL(request.url);\n const redirectTo = url.searchParams.get(\"redirect\") ?? \"/\";\n const { draftMode, cookies } = await import(\"next/headers\");\n (await draftMode()).disable();\n (await cookies()).delete(PREVIEW_TOKEN_COOKIE);\n return Response.redirect(new URL(safeRedirectPath(redirectTo), url.origin), 302);\n }\n return { GET };\n}\n","/**\n * Build-time reader for the forms the deploy Action injects into the content\n * snapshot (schema \"bcms-content/v1\": `{ ...collections, forms, turnstileSiteKey }`).\n *\n * This is intentionally separate from `readSnapshot()` — that reads the\n * `@bettercms-ai/next` \"bettercms-snapshot\" format (`{ version, models }`), which is a\n * different file shape. Connected-repo sites on <name>.bettercms.site get the Action\n * snapshot, so forms live here. Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { DeliveryForm } from \"@bettercms-ai/sdk\";\n\nexport interface SnapshotForms {\n forms: DeliveryForm[];\n /** Public Turnstile site key for any form with `turnstileEnabled`, or null. */\n turnstileSiteKey: string | null;\n}\n\n/**\n * Read forms from the Action's `bcms-content.json`. Missing file or no forms →\n * an empty set (a content-only build never throws). `path` resolves against cwd.\n */\nexport function readForms(path = \"bcms-content.json\"): SnapshotForms {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return { forms: [], turnstileSiteKey: null };\n }\n const snap = JSON.parse(raw) as { forms?: DeliveryForm[]; turnstileSiteKey?: string | null };\n return { forms: snap.forms ?? [], turnstileSiteKey: snap.turnstileSiteKey ?? null };\n}\n\n/** Find a single form by `id` or `name` from the Action snapshot. */\nexport function getForm(idOrName: string, path?: string): DeliveryForm | undefined {\n return readForms(path).forms.find((f) => f.id === idOrName || f.name === idOrName);\n}\n","/**\n * Build-time reader for the pages the deploy Action injects into the content\n * snapshot (schema \"bcms-content/v1\": `{ ...collections, forms, pages, turnstileSiteKey }`).\n *\n * Sibling to `forms-read.ts`. Connected-repo sites on <name>.bettercms.site get the\n * Action snapshot, so published pages (with their block_json) live here. Render a page\n * with `<BcmsBlocks blocks={page.blocks} forms={readForms().forms} />`. The same data\n * is also available at runtime via `createBetterCMS(...).getPage(slug)`.\n * Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { ContentBlock, PageMetaJson, DeliveredLayout } from \"@bettercms-ai/types\";\n\nexport interface SnapshotPage {\n projectId?: string | null;\n slug: string;\n title: string;\n metaTitle: string | null;\n metaDescription: string | null;\n /** Rich SEO (OG / Twitter / canonical / JSON-LD) — FLO-302. Feed to `buildMetadata`. */\n metaJson: PageMetaJson | null;\n /** The page's block_json — pass to `<BcmsBlocks blocks={...} />`. */\n blocks: ContentBlock[];\n /** Resolved published project/page chrome, shared with runtime Delivery reads. */\n layout?: DeliveredLayout | null;\n updatedAt: string | null;\n publishedAt: string | null;\n}\n\n/**\n * Read published pages from the Action's `bcms-content.json`. Missing file or no\n * pages → an empty list (a pages-less build never throws). `path` resolves against cwd.\n */\nexport function readPages(path = \"bcms-content.json\"): SnapshotPage[] {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return [];\n }\n const snap = JSON.parse(raw) as { pages?: SnapshotPage[] };\n return snap.pages ?? [];\n}\n\n/** Find a single published page by `slug` from the Action snapshot. */\nexport function getPage(slug: string, path?: string): SnapshotPage | undefined {\n return readPages(path).find((p) => p.slug === slug);\n}\n","/**\n * Build-time reader for the reusable components the deploy Action injects into the\n * content snapshot (`bcms-content.json` → `components`). Mirrors `forms-read.ts`.\n *\n * Pass the result to `<BcmsBlocks components={readComponents()} … />` so `component`\n * blocks resolve their definitions. Server/build-time only (uses node:fs).\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { DeliveryComponent } from \"@bettercms-ai/types\";\n\n/**\n * Read components from the Action's `bcms-content.json`. Missing file or no\n * components → an empty array (a content-only build never throws).\n */\nexport function readComponents(path = \"bcms-content.json\"): DeliveryComponent[] {\n let raw: string;\n try {\n raw = readFileSync(resolve(process.cwd(), path), \"utf8\");\n } catch {\n return [];\n }\n const snap = JSON.parse(raw) as { components?: DeliveryComponent[] };\n return snap.components ?? [];\n}\n\n/** Find a single component by `id`, `slug`, or `name` from the Action snapshot. */\nexport function getComponent(idOrSlug: string, path?: string): DeliveryComponent | undefined {\n return readComponents(path).find(\n (c) => c.id === idOrSlug || c.slug === idOrSlug || c.name === idOrSlug,\n );\n}\n","/**\n * <BcmsField> — tag an entry field's rendered value with its identity so the\n * BetterCMS visual editor can bind click-to-edit deterministically (mirrors\n * Sanity's `data-sanity` / BaseHub's `data-basehub`). Entry-backed templates\n * hand-render field values (`f.title`, `f.body.html`), so the field `path` is\n * declared here by the author — the delivery payload carries no source-map.\n *\n * Server-safe (no hooks): renders in a Next Server Component. By default it wraps\n * children in a `display:contents` span, invisible to layout/GSAP; pass `as` to\n * carry the attributes on a real element instead.\n *\n * `path` follows the editor grammar: `title` · `hero.title` · `facts[2].label`\n * (dotted keys, at most one array index). For images, put the attributes on the\n * `<img>` itself (`kind=\"image\"` reflection patches `.src`), not on a wrapper:\n * <img src={f.cover.url} data-bcms-field=\"cover\" data-bcms-kind=\"image\" />\n */\nimport type { ElementType, ReactNode } from \"react\";\n\nexport interface BcmsFieldProps {\n /** Field path in the editor grammar, e.g. `title` or `facts[2].label`. */\n path: string;\n /** Kind hint the editor's reflection branches on. Omit for plain text/number. */\n kind?: \"richtext\" | \"image\";\n /** Wrapper element. Defaults to a `display:contents` span. */\n as?: ElementType;\n children: ReactNode;\n}\n\nexport function BcmsField({ path, kind, as, children }: BcmsFieldProps) {\n const Tag = as ?? \"span\";\n return (\n <Tag\n data-bcms-field={path}\n data-bcms-kind={kind}\n style={as ? undefined : { display: \"contents\" }}\n >\n {children}\n </Tag>\n );\n}\n","/**\n * defineBetterCMSLive — build the live SSE URL for `<BcmsLive>` from your config.\n * Server-safe (no React); pass the returned `liveSrc` to the client component.\n */\nexport interface BetterCMSLiveConfig {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n workspace: string;\n /** A content:read key — exposed to the browser via the SSE URL query. */\n apiKey: string;\n /**\n * Reference hydration depth for the pushed document. Default 1, matching the\n * delivery API. Set 0 when you only render top-level fields — a smaller doc is\n * a faster frame.\n */\n depth?: 0 | 1 | 2;\n /**\n * Stream draft autosaves too, so a preview surface repaints as the editor types.\n * Requires a `content:read:draft` key; the server ignores the flag for any other\n * key rather than failing the connection. Never enable this on a public site —\n * the key it needs can read unpublished content.\n */\n drafts?: boolean;\n}\n\nexport function defineBetterCMSLive(config: BetterCMSLiveConfig): { liveSrc: string } {\n const base = config.apiUrl.replace(/\\/+$/, \"\");\n const q = new URLSearchParams({ key: config.apiKey });\n if (config.depth !== undefined) q.set(\"depth\", String(config.depth));\n if (config.drafts) q.set(\"drafts\", \"1\");\n const liveSrc = `${base}/api/v1/delivery/${config.workspace}/live?${q}`;\n return { liveSrc };\n}\n","/**\n * createRevalidateRoute — App Router POST handler that receives the backend's\n * revalidation webhook and calls `revalidateTag()` for each affected tag. This is\n * the production live path (publish → backend webhook → revalidate ISR cache).\n *\n * import { createRevalidateRoute } from \"@bettercms-ai/next\";\n * export const { POST } = createRevalidateRoute({ secret: process.env.BCMS_REVALIDATE_SECRET });\n *\n * When `secret` is set, the `X-BetterCMS-Signature` HMAC-SHA256 header is verified\n * against the raw body (the same secret configured on the project in the dashboard).\n */\nimport { createHmac, timingSafeEqual } from \"node:crypto\";\n\nexport interface RevalidateRouteConfig {\n /** Shared secret matching the project's revalidation webhook secret. */\n secret?: string;\n}\n\nfunction safeEqual(a: string, b: string): boolean {\n const ab = Buffer.from(a);\n const bb = Buffer.from(b);\n return ab.length === bb.length && timingSafeEqual(ab, bb);\n}\n\nexport function createRevalidateRoute(config: RevalidateRouteConfig = {}) {\n async function POST(request: Request): Promise<Response> {\n const body = await request.text();\n\n if (config.secret) {\n const provided = request.headers.get(\"x-bettercms-signature\") ?? \"\";\n const expected = `sha256=${createHmac(\"sha256\", config.secret).update(body).digest(\"hex\")}`;\n if (!safeEqual(provided, expected)) {\n return new Response(\"Invalid signature\", { status: 401 });\n }\n }\n\n let payload: { data?: { tags?: string[] } };\n try {\n payload = JSON.parse(body);\n } catch {\n return new Response(\"Invalid JSON\", { status: 400 });\n }\n\n const tags = payload.data?.tags ?? [];\n const { revalidateTag } = await import(\"next/cache\");\n for (const tag of tags) revalid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