@bettercms-ai/sdk 1.39.0 → 1.40.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/dist/live.js ADDED
@@ -0,0 +1,120 @@
1
+ // src/in-editor.ts
2
+ var EDITOR_FRAME_NAME = "bcms-editor";
3
+ function inEditor(win = globalThis.window) {
4
+ try {
5
+ return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;
6
+ } catch {
7
+ return false;
8
+ }
9
+ }
10
+
11
+ // src/content-applied.ts
12
+ var CONTENT_APPLIED = "bcms:content-applied";
13
+ function onContentApplied(handler, target = globalThis.window) {
14
+ if (!target) return () => {
15
+ };
16
+ const listener = (event) => {
17
+ const data = event.data;
18
+ if (!data || typeof data !== "object" || data.type !== CONTENT_APPLIED) return;
19
+ handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f) => typeof f === "string") : [] });
20
+ };
21
+ target.addEventListener("message", listener);
22
+ return () => target.removeEventListener("message", listener);
23
+ }
24
+
25
+ // src/live.ts
26
+ var pools = /* @__PURE__ */ new Map();
27
+ function subscribeLive(src, fn) {
28
+ let pool = pools.get(src);
29
+ if (!pool) {
30
+ const es = new EventSource(src);
31
+ pool = { es, listeners: /* @__PURE__ */ new Set() };
32
+ es.addEventListener("change", (e) => {
33
+ let parsed;
34
+ try {
35
+ parsed = JSON.parse(e.data);
36
+ } catch {
37
+ return;
38
+ }
39
+ for (const l of pools.get(src)?.listeners ?? []) l(parsed);
40
+ });
41
+ pools.set(src, pool);
42
+ }
43
+ pool.listeners.add(fn);
44
+ return () => {
45
+ const p = pools.get(src);
46
+ if (!p) return;
47
+ p.listeners.delete(fn);
48
+ if (p.listeners.size === 0) {
49
+ p.es.close();
50
+ pools.delete(src);
51
+ }
52
+ };
53
+ }
54
+ function onCanvasRefresh(refresh) {
55
+ if (typeof window === "undefined" || window.parent === window) return () => {
56
+ };
57
+ const onMessage = (e) => {
58
+ if (e.origin !== window.location.origin || e.source !== window.parent) return;
59
+ if (e.data?.type !== "bcms:refresh") return;
60
+ window.parent.postMessage({ type: "bcms:refreshed" }, e.origin);
61
+ void refresh();
62
+ };
63
+ window.addEventListener("message", onMessage);
64
+ return () => window.removeEventListener("message", onMessage);
65
+ }
66
+ function loadVisualEditing(studioUrl = "https://bettercms.ai") {
67
+ if (typeof document === "undefined") return;
68
+ const src = `${studioUrl.replace(/\/+$/, "")}/bcms-visual-editing.js`;
69
+ if (document.querySelector(`script[src="${src}"]`)) return;
70
+ const el = document.createElement("script");
71
+ el.src = src;
72
+ el.defer = true;
73
+ el.dataset.bcmsStudio = studioUrl;
74
+ document.head.appendChild(el);
75
+ }
76
+ function startBcmsLive(opts) {
77
+ if (typeof window === "undefined") return () => {
78
+ };
79
+ if (opts.draft ?? document.documentElement.hasAttribute("data-bcms-draft")) loadVisualEditing(opts.studioUrl);
80
+ const stopRefresh = onCanvasRefresh(opts.refresh);
81
+ const stopLive = opts.src ? subscribeLive(opts.src, (event) => {
82
+ if (opts.tags?.length && !event.tags.some((t) => opts.tags.includes(t))) return;
83
+ opts.onChange?.(event);
84
+ void opts.refresh();
85
+ }) : () => {
86
+ };
87
+ return () => {
88
+ stopRefresh();
89
+ stopLive();
90
+ };
91
+ }
92
+ var GENERATOR_META = '<meta name="generator" content="BetterCMS">';
93
+ function withGenerator(html) {
94
+ const at = html.search(/<\/head>/i);
95
+ return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);
96
+ }
97
+ function markDraft(html) {
98
+ return html.includes("data-bcms-draft=") ? html : html.replace(/<html(?=[\s>])/i, '<html data-bcms-draft="1"');
99
+ }
100
+ function liveSrc(opts) {
101
+ const q = new URLSearchParams({ key: opts.apiKey });
102
+ if (opts.depth !== void 0) q.set("depth", String(opts.depth));
103
+ if (opts.drafts) q.set("drafts", "1");
104
+ return `${opts.apiUrl.replace(/\/+$/, "")}/api/v1/delivery/${opts.workspace}/live?${q}`;
105
+ }
106
+ export {
107
+ CONTENT_APPLIED,
108
+ EDITOR_FRAME_NAME,
109
+ GENERATOR_META,
110
+ inEditor,
111
+ liveSrc,
112
+ loadVisualEditing,
113
+ markDraft,
114
+ onCanvasRefresh,
115
+ onContentApplied,
116
+ startBcmsLive,
117
+ subscribeLive,
118
+ withGenerator
119
+ };
120
+ //# sourceMappingURL=live.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/in-editor.ts","../src/content-applied.ts","../src/live.ts"],"sourcesContent":["/**\n * `inEditor()`: is this page running inside the BetterCMS Visual Editor's canvas?\n *\n * The editor frames the site and names the frame, so the answer is the page's own `window.name`:\n * there from the first script, kept through every navigation inside the frame, and never set on\n * a published page a visitor opens. A site asks before it starts what the canvas cannot share:\n *\n * const smooth = inEditor() ? null : new LocomotiveScroll({ el, smooth: true });\n *\n * The canvas owns the scroll, the pointer and the place on the page; the site's motion (scroll\n * triggers, timelines, WebGL scenes) runs there as it does live. What has to stand down is only\n * what takes those three away: scroll that is not the window's own, an intro that holds the\n * page, a cursor drawn over it.\n */\n\n/** The canvas frame's name. The dashboard sets this exact word (`EDITOR_FRAME_NAME`). */\nexport const EDITOR_FRAME_NAME = \"bcms-editor\";\n\n/** The least of `window` this needs. */\ninterface FramedWindow {\n name: string;\n self: unknown;\n top: unknown;\n}\n\n/** True inside the editor's canvas. Safe where there is no window (a server render): false. */\nexport function inEditor(win: FramedWindow | undefined = (globalThis as { window?: FramedWindow }).window): boolean {\n try {\n return !!win && win.name === EDITOR_FRAME_NAME && win.self !== win.top;\n } catch {\n return false;\n }\n}\n","/**\n * `bcms:content-applied` — what the visual editor tells a page after it has applied an edit to\n * the page's DOM.\n *\n * An edit changes how tall a heading is. Everything on the page that measured the layout once\n * (ScrollTrigger's start and end positions, Lenis's scroll limit, a carousel's slide widths, a\n * text splitter's lines) is now wrong, and only the page's own code can measure again. So the\n * editor posts one message to the frame's window after each applied edit, and the site listens:\n *\n * onContentApplied(() => ScrollTrigger.refresh());\n *\n * A published page receives no such message: nothing there posts it, and the listener is inert.\n */\n\n/** The `type` of the message. */\nexport const CONTENT_APPLIED = \"bcms:content-applied\";\n\nexport interface ContentAppliedMessage {\n type: typeof CONTENT_APPLIED;\n /** The field addresses whose rendering changed; empty when the editor does not say. */\n fields: string[];\n}\n\n/** The message the editor posts: `frame.contentWindow.postMessage(contentApplied(fields), origin)`. */\nexport const contentApplied = (fields: readonly string[] = []): ContentAppliedMessage => ({ type: CONTENT_APPLIED, fields: [...fields] });\n\n/** The least of `window` this needs. */\ninterface MessageTarget {\n addEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n removeEventListener(type: \"message\", listener: (event: { data: unknown }) => void): void;\n}\n\n/**\n * Run `handler` after every edit the editor applies to this page. Returns the function that\n * stops listening. Safe to call where there is no window (a server render): it does nothing.\n */\nexport function onContentApplied(\n handler: (message: ContentAppliedMessage) => void,\n target: MessageTarget | undefined = (globalThis as { window?: MessageTarget }).window,\n): () => void {\n if (!target) return () => {};\n const listener = (event: { data: unknown }) => {\n const data = event.data as Partial<ContentAppliedMessage> | null;\n if (!data || typeof data !== \"object\" || data.type !== CONTENT_APPLIED) return;\n handler({ type: CONTENT_APPLIED, fields: Array.isArray(data.fields) ? data.fields.filter((f): f is string => typeof f === \"string\") : [] });\n };\n target.addEventListener(\"message\", listener);\n return () => target.removeEventListener(\"message\", listener);\n}\n","/// <reference lib=\"dom\" />\n/**\n * The site half of BetterCMS live editing, framework-agnostic. Every adapter wires its own\n * re-render into it (Next `router.refresh`, SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`,\n * a React app's refetch), so the protocol lives here once:\n *\n * const stop = startBcmsLive({ src: liveSrc, refresh: () => invalidateAll() });\n *\n * - The delivery SSE stream (`src`): a publish elsewhere re-renders this page.\n * - The canvas soft refresh: the editor asks for a re-render after a STRUCTURAL draft write and\n * waits for the ack, so it does not remount the frame (which ends an inline text session).\n * - In draft mode, the click-to-edit overlay script from the studio origin.\n */\n\n/** A `change` frame off the live stream (the backend's routes/delivery/live.ts). */\nexport interface BcmsChangeEvent<T = unknown> {\n type: \"entry\" | \"page\";\n slug: string;\n reason: \"publish\" | \"unpublish\" | \"draft\";\n /** Cache tags, `bcms:{ws}:all` + `bcms:{ws}:{type}:{slug}`. */\n tags: string[];\n projectId: string | null;\n /** When the change was committed. */\n at: string;\n /** When the server flushed this frame — `at`→`sentAt` is its own cost. */\n sentAt?: string;\n /**\n * The finished delivery payload. Absent on `unpublish`, and when the server could not hydrate\n * it (over quota, deleted, larger than the frame cap): then the client refetches.\n */\n doc?: T;\n}\n\n// One EventSource per URL, refcounted, because HTTP/1.1 browsers cap ~6 sockets per host: a page\n// with a handful of live components would otherwise spend its whole connection budget on this\n// stream and stall its own image loads.\ntype Listener = (e: BcmsChangeEvent) => void;\nconst pools = new Map<string, { es: EventSource; listeners: Set<Listener> }>();\n\n/** Listen to the live stream at `src`. Returns the function that stops listening. */\nexport function subscribeLive(src: string, fn: Listener): () => void {\n let pool = pools.get(src);\n if (!pool) {\n const es = new EventSource(src);\n pool = { es, listeners: new Set() };\n es.addEventListener(\"change\", (e) => {\n let parsed: BcmsChangeEvent;\n try {\n parsed = JSON.parse((e as MessageEvent).data) as BcmsChangeEvent;\n } catch {\n return; // malformed frame — ignore, the next one will do\n }\n for (const l of pools.get(src)?.listeners ?? []) l(parsed);\n });\n pools.set(src, pool);\n }\n pool.listeners.add(fn);\n return () => {\n const p = pools.get(src);\n if (!p) return;\n p.listeners.delete(fn);\n if (p.listeners.size === 0) {\n p.es.close();\n pools.delete(src);\n }\n };\n}\n\n/**\n * Answer the canvas's soft-refresh request with `refresh`. The editor — not the page — decides\n * which of its writes are structural; the page must never re-render on draft events itself, which\n * fire on every autosave, including the inline edit the author is in the middle of.\n *\n * Accepted only from the page's own origin AND from the parent frame (the editor serves the site\n * through a same-origin proxy), so a third-party page framing the live site can trigger nothing.\n * The ack goes out BEFORE the refresh: after a reload this frame is gone.\n */\nexport function onCanvasRefresh(refresh: () => unknown): () => void {\n if (typeof window === \"undefined\" || window.parent === window) return () => {};\n const onMessage = (e: MessageEvent) => {\n if (e.origin !== window.location.origin || e.source !== window.parent) return;\n if ((e.data as { type?: unknown } | null)?.type !== \"bcms:refresh\") return;\n window.parent.postMessage({ type: \"bcms:refreshed\" }, e.origin);\n void refresh();\n };\n window.addEventListener(\"message\", onMessage);\n return () => window.removeEventListener(\"message\", onMessage);\n}\n\n/**\n * Load the click-to-edit overlay (`/bcms-visual-editing.js` on the studio origin). Served, never\n * bundled: a customer build is un-upgradable, so a copy baked into one could never be fixed. The\n * tag is its own guard; it is never removed, because removing it would not detach its listeners.\n */\nexport function loadVisualEditing(studioUrl = \"https://bettercms.ai\"): void {\n if (typeof document === \"undefined\") return;\n const src = `${studioUrl.replace(/\\/+$/, \"\")}/bcms-visual-editing.js`;\n if (document.querySelector(`script[src=\"${src}\"]`)) return;\n const el = document.createElement(\"script\");\n el.src = src;\n el.defer = true;\n el.dataset.bcmsStudio = studioUrl;\n document.head.appendChild(el);\n}\n\nexport interface StartBcmsLiveOptions {\n /** The page's own re-render: SvelteKit `invalidateAll`, Nuxt `refreshNuxtData`, a refetch. */\n refresh: () => unknown;\n /** The live SSE URL (a content:read key rides in it: EventSource cannot send headers). */\n src?: string;\n /** Only react to changes carrying one of these tags. Omit to react to all. */\n tags?: string[];\n /** Every matching change, with the pushed `doc` when there is one. */\n onChange?: (event: BcmsChangeEvent) => void;\n /** Where the click-to-edit overlay loads from in drafts. Default `https://bettercms.ai`. */\n studioUrl?: string;\n /** Drafts on? Default: the page's `<html data-bcms-draft>` marker, which the server stamps. */\n draft?: boolean;\n}\n\n/** Live stream + canvas soft refresh + (in drafts) the overlay. Returns the function that stops it. */\nexport function startBcmsLive(opts: StartBcmsLiveOptions): () => void {\n if (typeof window === \"undefined\") return () => {};\n if (opts.draft ?? document.documentElement.hasAttribute(\"data-bcms-draft\")) loadVisualEditing(opts.studioUrl);\n const stopRefresh = onCanvasRefresh(opts.refresh);\n const stopLive = opts.src\n ? subscribeLive(opts.src, (event) => {\n if (opts.tags?.length && !event.tags.some((t) => opts.tags!.includes(t))) return;\n opts.onChange?.(event);\n void opts.refresh();\n })\n : () => {};\n return () => {\n stopRefresh();\n stopLive();\n };\n}\n\n/** The standard tag Wappalyzer and BuiltWith read to name the CMS. */\nexport const GENERATOR_META = '<meta name=\"generator\" content=\"BetterCMS\">';\n\n/** The tag before the first `</head>`; unchanged without one, or when the page already has it. */\nexport function withGenerator(html: string): string {\n const at = html.search(/<\\/head>/i);\n return at < 0 || html.includes(GENERATOR_META) ? html : html.slice(0, at) + GENERATOR_META + html.slice(at);\n}\n\n/**\n * `<html data-bcms-draft=\"1\">`: the only thing the canvas trusts as proof that the frame really is\n * this site rendering a draft, not the published page it falls back to. Server renders stamp it.\n */\nexport function markDraft(html: string): string {\n return html.includes(\"data-bcms-draft=\") ? html : html.replace(/<html(?=[\\s>])/i, '<html data-bcms-draft=\"1\"');\n}\n\n// The other two halves of living inside the editor's canvas, browser-safe here too.\nexport { inEditor, EDITOR_FRAME_NAME } from \"./in-editor.js\";\nexport { onContentApplied, CONTENT_APPLIED, type ContentAppliedMessage } from \"./content-applied.js\";\n\nexport interface LiveSrcOptions {\n /** Backend base, e.g. `https://api.bettercms.ai`. */\n apiUrl: string;\n workspace: string;\n /** A content:read key — exposed to the browser in the URL (EventSource cannot send headers). */\n apiKey: string;\n /** Reference hydration depth of the pushed document; default 1, like the delivery API. */\n depth?: 0 | 1 | 2;\n /**\n * Stream draft autosaves too. Needs a `content:read:draft` key (the server ignores the flag for\n * any other key). Never on a public site: that key reads unpublished content.\n */\n drafts?: boolean;\n}\n\n/** The live SSE URL for `startBcmsLive({ src })`. */\nexport function liveSrc(opts: LiveSrcOptions): string {\n const q = new URLSearchParams({ key: opts.apiKey });\n if (opts.depth !== undefined) q.set(\"depth\", String(opts.depth));\n if (opts.drafts) q.set(\"drafts\", \"1\");\n return `${opts.apiUrl.replace(/\\/+$/, \"\")}/api/v1/delivery/${opts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AAK,KAAK,CAAC,MAAM,KAAK,KAAM,SAAS,CAAC,CAAC,EAAG;AAC1E,SAAK,WAAW,KAAK;AACrB,SAAK,KAAK,QAAQ;AAAA,EACpB,CAAC,IACD,MAAM;AAAA,EAAC;AACX,SAAO,MAAM;AACX,gBAAY;AACZ,aAAS;AAAA,EACX;AACF;AAGO,IAAM,iBAAiB;AAGvB,SAAS,cAAc,MAAsB;AAClD,QAAM,KAAK,KAAK,OAAO,WAAW;AAClC,SAAO,KAAK,KAAK,KAAK,SAAS,cAAc,IAAI,OAAO,KAAK,MAAM,GAAG,EAAE,IAAI,iBAAiB,KAAK,MAAM,EAAE;AAC5G;AAMO,SAAS,UAAU,MAAsB;AAC9C,SAAO,KAAK,SAAS,kBAAkB,IAAI,OAAO,KAAK,QAAQ,mBAAmB,2BAA2B;AAC/G;AAsBO,SAAS,QAAQ,MAA8B;AACpD,QAAM,IAAI,IAAI,gBAAgB,EAAE,KAAK,KAAK,OAAO,CAAC;AAClD,MAAI,KAAK,UAAU,OAAW,GAAE,IAAI,SAAS,OAAO,KAAK,KAAK,CAAC;AAC/D,MAAI,KAAK,OAAQ,GAAE,IAAI,UAAU,GAAG;AACpC,SAAO,GAAG,KAAK,OAAO,QAAQ,QAAQ,EAAE,CAAC,oBAAoB,KAAK,SAAS,SAAS,CAAC;AACvF;","names":[]}
@@ -0,0 +1,191 @@
1
+ import './read-client-CnkVzNP0.cjs';
2
+ import { RichTextResolved, RichTextEmbeds } from '@bettercms-ai/types';
3
+
4
+ /**
5
+ * Reading a rich-text field, for any site.
6
+ *
7
+ * A `text` field delivers a bare string. A `richtext` field delivers the canonical envelope
8
+ * `{ format, value, html }`. Those are different shapes, and switching a field's type in the
9
+ * CMS switches which one your site receives — the Visual Editor offers exactly that switch,
10
+ * so it happens on live projects. A template that interpolates the value directly then
11
+ * renders `[object Object]` (or, in React, throws `Objects are not valid as a React child`).
12
+ *
13
+ * No payload can be both structured and safe to interpolate, which is why every headless CMS
14
+ * requires a renderer for rich text. These are ours:
15
+ *
16
+ * plain(v) → text, for <title>, meta descriptions, JSON-LD, alt text, aria-label
17
+ * rich(v) → HTML, for `set:html` / `dangerouslySetInnerHTML`
18
+ *
19
+ * Both accept a bare string, so a field can be switched in the CMS without touching the site.
20
+ *
21
+ * <h1 set:html={rich(page.heroTitle)} /> // Astro
22
+ * <h1 dangerouslySetInnerHTML={{ __html: rich(f.heroTitle) }}/> // React
23
+ * seo({ title: plain(page.heroTitle) })
24
+ */
25
+
26
+ /**
27
+ * A block in a Body field's `doc`. Bounded vocabulary — the server only emits what it can
28
+ * parse back, so an unknown `type` means your SDK is older than the content, not that the
29
+ * content is malformed. Handle the default case rather than exhausting on it.
30
+ */
31
+ type DocBlock = {
32
+ /**
33
+ * Stable within THIS document only — never a global key. Two different entries both have a
34
+ * block called "0.0". A cross-document anchor is (entryId, fieldKey, id).
35
+ *
36
+ * Ids on content authored before block ids existed are derived from position, so they SHIFT
37
+ * when that document is edited. Do not persist an id as a bookmark unless you know it came
38
+ * from the editor rather than from the positional fallback.
39
+ */
40
+ readonly id: string;
41
+ readonly type: string;
42
+ readonly [key: string]: unknown;
43
+ };
44
+ /** The `doc` rendition of a Body field — a versioned block array. */
45
+ type DocValue = {
46
+ readonly version: 1;
47
+ readonly blocks: readonly DocBlock[];
48
+ };
49
+ /** The canonical rich-text envelope returned by the Delivery API. */
50
+ interface RichTextValue {
51
+ readonly format?: string;
52
+ readonly value?: unknown;
53
+ /** Server-rendered, sanitized HTML. Computed on write. */
54
+ readonly html?: string;
55
+ /**
56
+ * Structured blocks — present on `document` (Body) fields only, and NOT guaranteed even
57
+ * there: it is derived at write time, so an entry saved before this existed carries none
58
+ * until its next save. There is no backfill. Always branch on its absence; `html` is the
59
+ * field that is always there.
60
+ */
61
+ readonly doc?: DocValue;
62
+ /**
63
+ * The embeds the server resolved when it built `html`: X cards keyed by canonical url (X's
64
+ * script, when a site opts in, is the page's, never the value's). `html` already holds each card, so `rich()` never needs this; it is
65
+ * for renderers of the STRUCTURE (`<PortableText embeds={…}>`). Absent on a value with no embed
66
+ * and on any envelope written before it existed: read it through `embeds()`.
67
+ */
68
+ readonly embeds?: RichTextEmbeds;
69
+ /**
70
+ * What the value's related posts and author bios point at, resolved by the server for THIS
71
+ * response from the published entries (never stored). `html` already draws them; this is for
72
+ * renderers of the structure (`<PortableText resolved={…}>`). Absent on a value with neither block.
73
+ * Read it through `resolved()`.
74
+ */
75
+ readonly resolved?: RichTextResolved;
76
+ }
77
+ /** The marker on a Portable Text envelope. `format` is a plain string, never a union — see below. */
78
+ declare const PORTABLE_TEXT_FORMAT = "portable-text-1";
79
+ /**
80
+ * Structured blocks, when the field stores Portable Text.
81
+ *
82
+ * ── The compatibility guarantee, stated once ────────────────────────────────────────────
83
+ * Portable Text did NOT change this envelope. `format`, `value` and `html` are the same three
84
+ * keys they always were, so `isRichText`, `plain()` and `rich()` keep working untouched — and
85
+ * they have to, because sites compiled months ago read `.html` directly and cannot be
86
+ * rebuilt. `bettercms-starter-modern/lib/cms.ts` even carries its OWN copy of `rich()`, baked
87
+ * into deployments nobody can reach. Storing a bare array instead would have made
88
+ * `isRichText` return false (it rejects arrays), every shipped `rich()` call return "", and
89
+ * every one of those pages go blank at 200 OK.
90
+ *
91
+ * `portableText()` is therefore ADDITIVE: `html` remains the always-present field, and this is
92
+ * the opt-in for consumers that want to render structure with `@portabletext/react` instead.
93
+ */
94
+ declare function portableText(value: TextOrRich): readonly unknown[] | null;
95
+ /**
96
+ * The value's resolved embeds, for a renderer of its structure (`<PortableText embeds>`), or null:
97
+ * a bare string, a value with no embed, or an envelope written before embeds existed. Additive,
98
+ * like `portableText()`: `rich()` reads `html`, which already holds the cards.
99
+ */
100
+ declare function embeds(value: TextOrRich): RichTextEmbeds | null;
101
+ /** A delivered entry as far as `resolved()` reads it: its entry-level map. */
102
+ interface ResolvedHolder {
103
+ readonly resolved?: RichTextResolved | null;
104
+ readonly data?: unknown;
105
+ }
106
+ /**
107
+ * What a rich-text value's related posts and author bios resolved to, for a renderer of its
108
+ * structure (`<PortableText resolved>`), or null when there is nothing.
109
+ *
110
+ * resolved(entry.data.body, entry) // a field value, with the entry it came in
111
+ * resolved(entry) // the entry's merged map
112
+ *
113
+ * An envelope value carries its own (`value.resolved`), which wins. A Body stored as a bare block
114
+ * array has nowhere to carry one, so delivery puts the entry's merged map beside `data`
115
+ * (`entry.resolved`): pass the entry and that is what you get. Additive, like `embeds()`: `rich()`
116
+ * reads `html`, which already draws them.
117
+ */
118
+ declare function resolved(value: TextOrRich | readonly unknown[] | ResolvedHolder, entry?: ResolvedHolder | null): RichTextResolved | null;
119
+ /**
120
+ * A field that may arrive as either shape. Type author-editable text fields with this and the
121
+ * compiler routes you through `plain()`/`rich()`, so a type switch in the CMS can never reach
122
+ * production as `[object Object]`.
123
+ */
124
+ type TextOrRich = string | RichTextValue | null | undefined;
125
+ /** True when the value is a rich-text envelope rather than a bare string. */
126
+ declare function isRichText(value: unknown): value is RichTextValue;
127
+ /**
128
+ * Plain text for an attribute context — `<title>`, meta description, JSON-LD, `alt`.
129
+ * Strips tags and decodes the entities that survive stripping, so the result is text the
130
+ * consumer can escape once without double-escaping.
131
+ */
132
+ declare function plain(value: TextOrRich): string;
133
+ /**
134
+ * Renderable HTML. Rich text keeps its inline marks (the server sanitizes `html` on write);
135
+ * a bare string is escaped, so a plain field can never inject markup.
136
+ *
137
+ * A lone wrapping block is unwrapped: a field switched from `text` stores its value as
138
+ * `<p>…</p>`, but it renders inside the element that already is the block — and
139
+ * `<h1><p>…</p></h1>` is invalid, the parser closes the heading at the `<p>` and the text
140
+ * falls out of it. Values with real block structure (several paragraphs, a list) are left
141
+ * alone, so a body field still renders as a document.
142
+ */
143
+ declare function rich(value: TextOrRich, fallback?: string): string;
144
+ /**
145
+ * Renderable HTML for a ONE-LINE place: a heading, a button, a caption. `rich()`, except that several
146
+ * paragraphs are that place's LINES, joined with `<br>` (a heading-styled first block counts as one).
147
+ *
148
+ * An author who presses Enter in a heading's editor stores a second paragraph. `rich()` leaves it a
149
+ * paragraph, and `<h1><p>…</p><p>…</p></h1>` is what the build then draws, while a publish between
150
+ * builds writes the same value into the built heading as lines. This draws what the publish draws.
151
+ * A value holding anything else (a list, an image, a table) is returned as `rich()` returns it.
152
+ */
153
+ declare function lines(value: TextOrRich, fallback?: string): string;
154
+
155
+ /**
156
+ * Public site search — the headless surface for the visitor-facing search box.
157
+ *
158
+ * Queries `GET /api/v1/delivery/search?project=…&q=…`, the same key-less public
159
+ * endpoint the embeddable widget uses. Powers <BcmsSearch> in @bettercms-ai/next
160
+ * and @bettercms-ai/astro, so the component and any custom UI never drift.
161
+ *
162
+ * `snippet` is HTML-safe: the server escapes the field content and keeps only the
163
+ * <mark> highlight wrappers, so it can be rendered with dangerouslySetInnerHTML.
164
+ */
165
+ interface SearchHit {
166
+ title: string;
167
+ slug: string;
168
+ type: "page" | "entry";
169
+ /** HTML-safe snippet with <mark> highlights around matched terms. */
170
+ snippet: string;
171
+ /** Site-relative URL, e.g. "/about". */
172
+ url: string;
173
+ }
174
+ interface SearchOptions {
175
+ /** The project id (from the dashboard's Site Search settings). */
176
+ project: string;
177
+ /** The query string. Calls with fewer than 1 char resolve to []. */
178
+ q: string;
179
+ /** Max hits, 1–20 (default 8). */
180
+ limit?: number;
181
+ /** API origin. Defaults to https://api.bettercms.ai. */
182
+ baseUrl?: string;
183
+ /** Injectable fetch for tests / non-browser runtimes. */
184
+ fetchImpl?: typeof fetch;
185
+ /** AbortSignal so callers can cancel a stale in-flight search. */
186
+ signal?: AbortSignal;
187
+ }
188
+ /** Search a published site. Resolves with hits, or [] on an empty query / network error. */
189
+ declare function search(opts: SearchOptions): Promise<SearchHit[]>;
190
+
191
+ export { PORTABLE_TEXT_FORMAT as P, type ResolvedHolder as R, type SearchHit as S, type TextOrRich as T, type RichTextValue as a, type SearchOptions as b, portableText as c, rich as d, embeds as e, isRichText as i, lines as l, plain as p, resolved as r, search as s };
@@ -0,0 +1,191 @@
1
+ import './read-client-CnkVzNP0.js';
2
+ import { RichTextResolved, RichTextEmbeds } from '@bettercms-ai/types';
3
+
4
+ /**
5
+ * Reading a rich-text field, for any site.
6
+ *
7
+ * A `text` field delivers a bare string. A `richtext` field delivers the canonical envelope
8
+ * `{ format, value, html }`. Those are different shapes, and switching a field's type in the
9
+ * CMS switches which one your site receives — the Visual Editor offers exactly that switch,
10
+ * so it happens on live projects. A template that interpolates the value directly then
11
+ * renders `[object Object]` (or, in React, throws `Objects are not valid as a React child`).
12
+ *
13
+ * No payload can be both structured and safe to interpolate, which is why every headless CMS
14
+ * requires a renderer for rich text. These are ours:
15
+ *
16
+ * plain(v) → text, for <title>, meta descriptions, JSON-LD, alt text, aria-label
17
+ * rich(v) → HTML, for `set:html` / `dangerouslySetInnerHTML`
18
+ *
19
+ * Both accept a bare string, so a field can be switched in the CMS without touching the site.
20
+ *
21
+ * <h1 set:html={rich(page.heroTitle)} /> // Astro
22
+ * <h1 dangerouslySetInnerHTML={{ __html: rich(f.heroTitle) }}/> // React
23
+ * seo({ title: plain(page.heroTitle) })
24
+ */
25
+
26
+ /**
27
+ * A block in a Body field's `doc`. Bounded vocabulary — the server only emits what it can
28
+ * parse back, so an unknown `type` means your SDK is older than the content, not that the
29
+ * content is malformed. Handle the default case rather than exhausting on it.
30
+ */
31
+ type DocBlock = {
32
+ /**
33
+ * Stable within THIS document only — never a global key. Two different entries both have a
34
+ * block called "0.0". A cross-document anchor is (entryId, fieldKey, id).
35
+ *
36
+ * Ids on content authored before block ids existed are derived from position, so they SHIFT
37
+ * when that document is edited. Do not persist an id as a bookmark unless you know it came
38
+ * from the editor rather than from the positional fallback.
39
+ */
40
+ readonly id: string;
41
+ readonly type: string;
42
+ readonly [key: string]: unknown;
43
+ };
44
+ /** The `doc` rendition of a Body field — a versioned block array. */
45
+ type DocValue = {
46
+ readonly version: 1;
47
+ readonly blocks: readonly DocBlock[];
48
+ };
49
+ /** The canonical rich-text envelope returned by the Delivery API. */
50
+ interface RichTextValue {
51
+ readonly format?: string;
52
+ readonly value?: unknown;
53
+ /** Server-rendered, sanitized HTML. Computed on write. */
54
+ readonly html?: string;
55
+ /**
56
+ * Structured blocks — present on `document` (Body) fields only, and NOT guaranteed even
57
+ * there: it is derived at write time, so an entry saved before this existed carries none
58
+ * until its next save. There is no backfill. Always branch on its absence; `html` is the
59
+ * field that is always there.
60
+ */
61
+ readonly doc?: DocValue;
62
+ /**
63
+ * The embeds the server resolved when it built `html`: X cards keyed by canonical url (X's
64
+ * script, when a site opts in, is the page's, never the value's). `html` already holds each card, so `rich()` never needs this; it is
65
+ * for renderers of the STRUCTURE (`<PortableText embeds={…}>`). Absent on a value with no embed
66
+ * and on any envelope written before it existed: read it through `embeds()`.
67
+ */
68
+ readonly embeds?: RichTextEmbeds;
69
+ /**
70
+ * What the value's related posts and author bios point at, resolved by the server for THIS
71
+ * response from the published entries (never stored). `html` already draws them; this is for
72
+ * renderers of the structure (`<PortableText resolved={…}>`). Absent on a value with neither block.
73
+ * Read it through `resolved()`.
74
+ */
75
+ readonly resolved?: RichTextResolved;
76
+ }
77
+ /** The marker on a Portable Text envelope. `format` is a plain string, never a union — see below. */
78
+ declare const PORTABLE_TEXT_FORMAT = "portable-text-1";
79
+ /**
80
+ * Structured blocks, when the field stores Portable Text.
81
+ *
82
+ * ── The compatibility guarantee, stated once ────────────────────────────────────────────
83
+ * Portable Text did NOT change this envelope. `format`, `value` and `html` are the same three
84
+ * keys they always were, so `isRichText`, `plain()` and `rich()` keep working untouched — and
85
+ * they have to, because sites compiled months ago read `.html` directly and cannot be
86
+ * rebuilt. `bettercms-starter-modern/lib/cms.ts` even carries its OWN copy of `rich()`, baked
87
+ * into deployments nobody can reach. Storing a bare array instead would have made
88
+ * `isRichText` return false (it rejects arrays), every shipped `rich()` call return "", and
89
+ * every one of those pages go blank at 200 OK.
90
+ *
91
+ * `portableText()` is therefore ADDITIVE: `html` remains the always-present field, and this is
92
+ * the opt-in for consumers that want to render structure with `@portabletext/react` instead.
93
+ */
94
+ declare function portableText(value: TextOrRich): readonly unknown[] | null;
95
+ /**
96
+ * The value's resolved embeds, for a renderer of its structure (`<PortableText embeds>`), or null:
97
+ * a bare string, a value with no embed, or an envelope written before embeds existed. Additive,
98
+ * like `portableText()`: `rich()` reads `html`, which already holds the cards.
99
+ */
100
+ declare function embeds(value: TextOrRich): RichTextEmbeds | null;
101
+ /** A delivered entry as far as `resolved()` reads it: its entry-level map. */
102
+ interface ResolvedHolder {
103
+ readonly resolved?: RichTextResolved | null;
104
+ readonly data?: unknown;
105
+ }
106
+ /**
107
+ * What a rich-text value's related posts and author bios resolved to, for a renderer of its
108
+ * structure (`<PortableText resolved>`), or null when there is nothing.
109
+ *
110
+ * resolved(entry.data.body, entry) // a field value, with the entry it came in
111
+ * resolved(entry) // the entry's merged map
112
+ *
113
+ * An envelope value carries its own (`value.resolved`), which wins. A Body stored as a bare block
114
+ * array has nowhere to carry one, so delivery puts the entry's merged map beside `data`
115
+ * (`entry.resolved`): pass the entry and that is what you get. Additive, like `embeds()`: `rich()`
116
+ * reads `html`, which already draws them.
117
+ */
118
+ declare function resolved(value: TextOrRich | readonly unknown[] | ResolvedHolder, entry?: ResolvedHolder | null): RichTextResolved | null;
119
+ /**
120
+ * A field that may arrive as either shape. Type author-editable text fields with this and the
121
+ * compiler routes you through `plain()`/`rich()`, so a type switch in the CMS can never reach
122
+ * production as `[object Object]`.
123
+ */
124
+ type TextOrRich = string | RichTextValue | null | undefined;
125
+ /** True when the value is a rich-text envelope rather than a bare string. */
126
+ declare function isRichText(value: unknown): value is RichTextValue;
127
+ /**
128
+ * Plain text for an attribute context — `<title>`, meta description, JSON-LD, `alt`.
129
+ * Strips tags and decodes the entities that survive stripping, so the result is text the
130
+ * consumer can escape once without double-escaping.
131
+ */
132
+ declare function plain(value: TextOrRich): string;
133
+ /**
134
+ * Renderable HTML. Rich text keeps its inline marks (the server sanitizes `html` on write);
135
+ * a bare string is escaped, so a plain field can never inject markup.
136
+ *
137
+ * A lone wrapping block is unwrapped: a field switched from `text` stores its value as
138
+ * `<p>…</p>`, but it renders inside the element that already is the block — and
139
+ * `<h1><p>…</p></h1>` is invalid, the parser closes the heading at the `<p>` and the text
140
+ * falls out of it. Values with real block structure (several paragraphs, a list) are left
141
+ * alone, so a body field still renders as a document.
142
+ */
143
+ declare function rich(value: TextOrRich, fallback?: string): string;
144
+ /**
145
+ * Renderable HTML for a ONE-LINE place: a heading, a button, a caption. `rich()`, except that several
146
+ * paragraphs are that place's LINES, joined with `<br>` (a heading-styled first block counts as one).
147
+ *
148
+ * An author who presses Enter in a heading's editor stores a second paragraph. `rich()` leaves it a
149
+ * paragraph, and `<h1><p>…</p><p>…</p></h1>` is what the build then draws, while a publish between
150
+ * builds writes the same value into the built heading as lines. This draws what the publish draws.
151
+ * A value holding anything else (a list, an image, a table) is returned as `rich()` returns it.
152
+ */
153
+ declare function lines(value: TextOrRich, fallback?: string): string;
154
+
155
+ /**
156
+ * Public site search — the headless surface for the visitor-facing search box.
157
+ *
158
+ * Queries `GET /api/v1/delivery/search?project=…&q=…`, the same key-less public
159
+ * endpoint the embeddable widget uses. Powers <BcmsSearch> in @bettercms-ai/next
160
+ * and @bettercms-ai/astro, so the component and any custom UI never drift.
161
+ *
162
+ * `snippet` is HTML-safe: the server escapes the field content and keeps only the
163
+ * <mark> highlight wrappers, so it can be rendered with dangerouslySetInnerHTML.
164
+ */
165
+ interface SearchHit {
166
+ title: string;
167
+ slug: string;
168
+ type: "page" | "entry";
169
+ /** HTML-safe snippet with <mark> highlights around matched terms. */
170
+ snippet: string;
171
+ /** Site-relative URL, e.g. "/about". */
172
+ url: string;
173
+ }
174
+ interface SearchOptions {
175
+ /** The project id (from the dashboard's Site Search settings). */
176
+ project: string;
177
+ /** The query string. Calls with fewer than 1 char resolve to []. */
178
+ q: string;
179
+ /** Max hits, 1–20 (default 8). */
180
+ limit?: number;
181
+ /** API origin. Defaults to https://api.bettercms.ai. */
182
+ baseUrl?: string;
183
+ /** Injectable fetch for tests / non-browser runtimes. */
184
+ fetchImpl?: typeof fetch;
185
+ /** AbortSignal so callers can cancel a stale in-flight search. */
186
+ signal?: AbortSignal;
187
+ }
188
+ /** Search a published site. Resolves with hits, or [] on an empty query / network error. */
189
+ declare function search(opts: SearchOptions): Promise<SearchHit[]>;
190
+
191
+ export { PORTABLE_TEXT_FORMAT as P, type ResolvedHolder as R, type SearchHit as S, type TextOrRich as T, type RichTextValue as a, type SearchOptions as b, portableText as c, rich as d, embeds as e, isRichText as i, lines as l, plain as p, resolved as r, search as s };
package/dist/read.cjs CHANGED
@@ -24,6 +24,11 @@ __export(read_exports, {
24
24
  createClient: () => createClient,
25
25
  formInitialValues: () => formInitialValues,
26
26
  isMultiValueField: () => isMultiValueField,
27
+ isRichText: () => isRichText,
28
+ lines: () => lines,
29
+ plain: () => plain,
30
+ portableText: () => portableText,
31
+ rich: () => rich,
27
32
  search: () => search,
28
33
  shouldShowField: () => shouldShowField,
29
34
  submitForm: () => submitForm,
@@ -454,12 +459,56 @@ async function search(opts) {
454
459
  return [];
455
460
  }
456
461
  }
462
+
463
+ // src/richtext.ts
464
+ var PORTABLE_TEXT_FORMAT = "portable-text-1";
465
+ function portableText(value) {
466
+ if (!isRichText(value)) return null;
467
+ const v = value;
468
+ return v.format === PORTABLE_TEXT_FORMAT && Array.isArray(v.value) ? v.value : null;
469
+ }
470
+ function isRichText(value) {
471
+ return typeof value === "object" && value !== null && !Array.isArray(value) && ("html" in value || "format" in value);
472
+ }
473
+ function plain(value) {
474
+ if (typeof value === "string") return value;
475
+ if (!isRichText(value) || typeof value.html !== "string") return "";
476
+ return decodeEntities(value.html.replace(/<[^>]+>/g, "")).trim();
477
+ }
478
+ function rich(value, fallback = "") {
479
+ const html = (typeof value === "string" ? escapeHtml(value) : isRichText(value) ? value.html ?? "" : "").trim();
480
+ return html ? unwrapLoneBlock(html) : escapeHtml(fallback);
481
+ }
482
+ function lines(value, fallback = "") {
483
+ const html = rich(value, fallback);
484
+ const block = /<(p|h[1-6])(?:\s[^>]*)?>([\s\S]*?)<\/\1>/gi;
485
+ if (html.length > 1e4) return html;
486
+ const found = [...html.matchAll(block)];
487
+ if (found.length < 2 || html.replace(block, "").trim() !== "") return html;
488
+ const shown = found.map((m) => m[2].trim()).filter((line) => line.replace(/<br\s*\/?>/gi, "").trim() !== "");
489
+ return shown.length ? shown.join("<br>") : html;
490
+ }
491
+ function unwrapLoneBlock(html) {
492
+ const m = html.match(/^<(p|div|h[1-6])(?:\s[^>]*)?>([\s\S]*)<\/\1>$/i);
493
+ return m && !new RegExp(`</${m[1]}>`, "i").test(m[2]) ? m[2] : html;
494
+ }
495
+ function escapeHtml(s) {
496
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
497
+ }
498
+ function decodeEntities(s) {
499
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#0?39;/g, "'").replace(/&nbsp;/g, " ").replace(/&amp;/g, "&");
500
+ }
457
501
  // Annotate the CommonJS export names for ESM import in node:
458
502
  0 && (module.exports = {
459
503
  asStringArray,
460
504
  createClient,
461
505
  formInitialValues,
462
506
  isMultiValueField,
507
+ isRichText,
508
+ lines,
509
+ plain,
510
+ portableText,
511
+ rich,
463
512
  search,
464
513
  shouldShowField,
465
514
  submitForm,