@bettercms-ai/sdk 1.38.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.
Files changed (43) hide show
  1. package/dist/bindings.cjs +146 -0
  2. package/dist/bindings.cjs.map +1 -0
  3. package/dist/bindings.d.cts +174 -0
  4. package/dist/bindings.d.ts +174 -0
  5. package/dist/bindings.js +109 -0
  6. package/dist/bindings.js.map +1 -0
  7. package/dist/draft.cjs +8 -0
  8. package/dist/draft.cjs.map +1 -1
  9. package/dist/draft.d.cts +9 -1
  10. package/dist/draft.d.ts +9 -1
  11. package/dist/draft.js +6 -0
  12. package/dist/draft.js.map +1 -1
  13. package/dist/in-editor-D1vXPgJh.d.cts +63 -0
  14. package/dist/in-editor-D1vXPgJh.d.ts +63 -0
  15. package/dist/index.cjs +5 -0
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +6 -218
  18. package/dist/index.d.ts +6 -218
  19. package/dist/index.js +5 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/live.cjs +158 -0
  22. package/dist/live.cjs.map +1 -0
  23. package/dist/live.d.cts +95 -0
  24. package/dist/live.d.ts +95 -0
  25. package/dist/live.js +120 -0
  26. package/dist/live.js.map +1 -0
  27. package/dist/read-AYzXKCU-.d.cts +191 -0
  28. package/dist/read-Bb60mWmW.d.ts +191 -0
  29. package/dist/{read-client-B1uDVNKk.d.cts → read-client-CnkVzNP0.d.cts} +5 -0
  30. package/dist/{read-client-B1uDVNKk.d.ts → read-client-CnkVzNP0.d.ts} +5 -0
  31. package/dist/read.cjs +54 -0
  32. package/dist/read.cjs.map +1 -1
  33. package/dist/read.d.cts +2 -39
  34. package/dist/read.d.ts +2 -39
  35. package/dist/read.js +49 -0
  36. package/dist/read.js.map +1 -1
  37. package/dist/sections.cjs +144 -75
  38. package/dist/sections.cjs.map +1 -1
  39. package/dist/sections.d.cts +56 -4
  40. package/dist/sections.d.ts +56 -4
  41. package/dist/sections.js +138 -75
  42. package/dist/sections.js.map +1 -1
  43. package/package.json +11 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/bindings.ts"],"sourcesContent":["/**\n * The attributes a site's OWN markup spreads so the BetterCMS editor binds it: a page field, a\n * collection entry, a section root and its content column. Plain objects of string attributes\n * (the style is a CSS string), so they spread as they are in every template language:\n *\n * Astro / Svelte <h1 {...fieldAttrs(\"hero-title\", page.fieldStyles)}>…</h1>\n * Vue <h1 v-bind=\"fieldAttrs('hero-title', page.fieldStyles)\">…</h1>\n *\n * @bettercms-ai/astro, /sveltekit and /nuxt re-export these; @bettercms-ai/next keeps twins whose\n * `style` is a React style object.\n */\nimport imageUrlBuilder, {\n focalInCrop,\n normalizeImageCrop,\n normalizeImageFocal,\n objectPosition,\n type ImageFit,\n type ImageFormat,\n type ImageSource,\n} from \"@bettercms-ai/image-url\";\nimport { blockStyleToColumnCss, blockStyleToCss, fieldStyleCssText, hideOnAttr, type BlockStyle, type FieldStyle, type FieldStyles } from \"@bettercms-ai/types\";\n\n/**\n * C3 — `fieldAttrs(path, fieldStyles)`: the attributes a site's OWN element spreads to bind a PAGE\n * FIELD and apply that field's stored style, so the BetterCMS editor offers its width and spacing\n * handles and its Align / Size / Weight controls.\n *\n * ---\n * const page = await loadPage(Astro, \"home\");\n * ---\n * <h1 class=\"title\" {...fieldAttrs(\"hero-title\", page?.fieldStyles)}>{entry.data[\"hero-title\"]}</h1>\n *\n * `data-bcms-style` is the site's promise that \"this element's inline style is\n * `fieldStyleToCss(fieldStyles[path])`\". The editor offers a field's handles only on an element that\n * carries it: a handle on one that does not would paint the canvas and never ship. The marker is\n * present even when the field has no style (then there is no `style` attribute at all, byte for\n * byte the element it was): an unstyled field is the one an author is about to give its first edit.\n */\nexport interface FieldAttrs {\n \"data-bcms-field\": string;\n /** The marker's revision: \"2\" promises `size` (zoom) too. Section roots keep \"\". */\n \"data-bcms-style\": \"2\";\n /** `fieldStyleToCss(fieldStyles[path])` as a CSS string; absent when the field has no style. */\n style?: string;\n}\n\n/** The stored style for `path`, by OWN key only — a path like `constructor` never reads the prototype. */\nexport function fieldStyleOf(path: string, fieldStyles: FieldStyles | Record<string, unknown> | null | undefined): FieldStyle | undefined {\n if (!fieldStyles || typeof fieldStyles !== \"object\" || !Object.prototype.hasOwnProperty.call(fieldStyles, path)) return undefined;\n const style = (fieldStyles as Record<string, unknown>)[path];\n return style && typeof style === \"object\" ? (style as FieldStyle) : undefined;\n}\n\nexport function fieldAttrs(path: string, fieldStyles?: FieldStyles | Record<string, unknown> | null): FieldAttrs {\n const style = fieldStyleCssText(fieldStyleOf(path, fieldStyles));\n return { \"data-bcms-field\": path, \"data-bcms-style\": \"2\", ...(style ? { style } : {}) };\n}\n\n/**\n * P7 — `entryAttrs(entry)` and `entryField(entry, path)`: the attributes a site's OWN card spreads to\n * declare a collection ENTRY, so the editor binds it without guessing from the rendered text.\n *\n * <article {...entryAttrs(post)}><h3 {...entryField(post, \"title\")}>{post.fields.title}</h3></article>\n *\n * The field address is ABSOLUTE (`entry:<id>:<path>`). With a `transform` the value is shown\n * changed (a date formatted, text truncated), so it is declared as `data-bcms-entry-from`: the\n * editor knows where it is but cannot re-render it.\n */\nexport type EntryRef = { id?: string } | string;\nexport type EntryTransform = \"format\" | \"truncate\" | \"rendition\" | \"route\";\n/** One key is present: `data-bcms-entry-field`, or `data-bcms-entry-from` when transformed; none without an id. */\nexport interface EntryFieldAttrs {\n \"data-bcms-entry-field\"?: string;\n \"data-bcms-entry-from\"?: string;\n}\n\nfunction entryIdOf(entry: EntryRef): string | null {\n const id = typeof entry === \"string\" ? entry : entry?.id;\n return typeof id === \"string\" && id.trim() !== \"\" ? id : null;\n}\n\n/** An entry with no id (a snapshot written before ids were kept) renders unbound, never fails the build. */\nexport function entryAttrs(entry: EntryRef): { \"data-bcms-entry\"?: string } {\n const id = entryIdOf(entry);\n return id ? { \"data-bcms-entry\": id } : {};\n}\n\nexport function entryField(entry: EntryRef, path: string, opts?: { transform?: EntryTransform }): EntryFieldAttrs {\n const id = entryIdOf(entry);\n if (typeof path !== \"string\" || path.trim() === \"\") throw new Error(`entryField: no field path given for entry ${id ?? \"(no id)\"}`);\n if (!id) return {};\n const address = `entry:${id}:${path}`;\n return opts?.transform ? { \"data-bcms-entry-from\": `${address}|${opts.transform}` } : { \"data-bcms-entry-field\": address };\n}\n\n/**\n * C3/C4 — `sectionRootAttrs(block)`: the attributes a site's OWN section root spreads so the\n * BetterCMS editor offers that section's spacing and style handles.\n *\n * <section class=\"hero\" {...sectionRootAttrs(block)}>…</section>\n *\n * The editor shows those handles on a site-rendered page only when EVERY root the site stamps\n * with `data-bcms-block` also carries `data-bcms-style`, which is the site's promise that \"this\n * root's inline style is `blockStyleToCss(block.style)`\" — the same declarations `<BcmsBlocks>`\n * puts on its own wrapper. A root that stamps the block without applying its style would get a\n * capsule that paints the canvas and never ships, so the marker must travel with the style.\n *\n * The marker is present even when the style is EMPTY (then there is no `style` attribute at all):\n * an unstyled section is exactly the one an author is about to give its first spacing edit.\n */\nexport interface SectionRootBlock {\n id?: string | null;\n style?: BlockStyle | Record<string, unknown> | null;\n}\n\nexport interface SectionRootAttrs {\n \"data-bcms-block\"?: string;\n \"data-bcms-style\": \"\";\n /** `\"mobile tablet\"` when `style.hideOn` hides it there; the site ships `RESPONSIVE_CSS` for it. */\n \"data-bcms-hide\"?: string;\n /** `blockStyleToCss(block.style)` as a CSS string; absent when the block has no style. */\n style?: string;\n}\n\n/** `paddingTop` → `padding-top`, joined the way `<BcmsBlocks>` writes its wrapper's attribute. */\nfunction cssText(css: Record<string, string | number>): string {\n return Object.entries(css)\n .map(([k, v]) => `${k.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}:${v}`)\n .join(\";\");\n}\n\nexport function sectionRootAttrs(block: SectionRootBlock | null | undefined): SectionRootAttrs {\n const css = blockStyleToCss((block?.style ?? undefined) as BlockStyle | undefined);\n const id = typeof block?.id === \"string\" && block.id !== \"\" ? block.id : undefined;\n const hide = hideOnAttr(block?.style);\n return {\n ...(id !== undefined ? { \"data-bcms-block\": id } : {}),\n \"data-bcms-style\": \"\",\n ...(hide ? { \"data-bcms-hide\": hide } : {}),\n ...(css ? { style: cssText(css) } : {}),\n };\n}\n\nexport interface SectionColumnAttrs {\n \"data-bcms-column\": \"\";\n /** `blockStyleToColumnCss(block.style)` as a CSS string; absent when the section has no column. */\n style?: string;\n}\n\n/**\n * C3 — `sectionColumnAttrs(block)`: the attributes a site's own INNER container spreads so the\n * section's content WIDTH (`style.contentWidth`, placed by `contentAlign`) ships.\n *\n * <section {...sectionRootAttrs(block)}>\n * <div class=\"container\" {...sectionColumnAttrs(block)}>…</div>\n * </section>\n *\n * The width is the column BetterCMS draws as `.bcms-block-inner` inside the section's styled box —\n * never on the root itself, whose background must stay full-bleed. `data-bcms-column` is the\n * site's promise that this box's inline style is the column; the editor offers the width handle\n * on a site-rendered page only where every styled root holds one. Max-width plus left/right\n * margins, so the container keeps its own vertical margins and, with no column, its own width.\n */\nexport function sectionColumnAttrs(block: SectionRootBlock | null | undefined): SectionColumnAttrs {\n const css = blockStyleToColumnCss((block?.style ?? undefined) as BlockStyle | undefined);\n return { \"data-bcms-column\": \"\", ...(css ? { style: cssText(css) } : {}) };\n}\n\n/** The image facts a value or asset may carry beside its URL. */\ntype ImageFacts = { altText?: string | null; alt?: string | null; width?: number | null; height?: number | null; focalX?: number | null; focalY?: number | null };\n\nexport interface ImageOptions {\n /** The field this image renders, in the editor grammar (`cover`, `hero.image`). */\n path?: string;\n alt?: string;\n width?: number;\n height?: number;\n format?: ImageFormat;\n quality?: number;\n fit?: ImageFit;\n sizes?: string;\n loading?: \"lazy\" | \"eager\";\n /** Focal point override, 0–1. Normally omitted: the value and the asset carry their own. */\n focalX?: number | null;\n focalY?: number | null;\n /** Media host for a `src` that is only an asset id. Defaults to the platform's. */\n baseUrl?: string;\n}\n\n/** The widths a `sizes` image offers: phone to desktop, and never an upscale of the picture. */\nconst LADDER = [480, 768, 1080, 1440, 1920];\nconst num = (v: unknown): number | undefined => (typeof v === \"number\" && Number.isFinite(v) ? v : undefined);\n\n/**\n * What every `<BcmsImage>` renders, computed once for all of them: the transform URL, a srcset\n * (a WIDTH ladder with `sizes` and no `width`, else 1x/2x), the alt (the value's `altText` unless\n * `alt` says otherwise) and the style declarations, camel-cased. The value's crop and focal point\n * are applied by image-url itself; a source-relative focal is re-expressed inside the crop.\n */\nexport function imageCore(src: ImageSource | (Exclude<ImageSource, string> & ImageFacts), opts: ImageOptions = {}) {\n const { width, height, format = \"webp\", quality, fit, sizes, focalX, focalY, baseUrl } = opts;\n const asset = (typeof src === \"object\" && src !== null ? src : {}) as Record<string, unknown>;\n const explicit = focalX != null || focalY != null;\n const stored =\n normalizeImageFocal(asset.focal) ??\n (num(asset.focalX) != null || num(asset.focalY) != null ? { x: num(asset.focalX) ?? 0.5, y: num(asset.focalY) ?? 0.5 } : null);\n const inWindow = stored ? focalInCrop(stored, normalizeImageCrop(asset.crop)) : null;\n const fx = explicit ? focalX : inWindow?.x;\n const fy = explicit ? focalY : inWindow?.y;\n const hasFocal = fx != null || fy != null;\n const builder = imageUrlBuilder({ baseUrl });\n const make = () => {\n let b = builder(src as ImageSource);\n if (width) b = b.width(width);\n if (height) b = b.height(height);\n if (format) b = b.format(format);\n if (quality) b = b.quality(quality);\n if (fit) b = b.fit(fit);\n if (hasFocal) b = b.focal(fx ?? 0.5, fy ?? 0.5);\n return b;\n };\n const url = make().url();\n const own = num(asset.width);\n const ladder = own ? [...new Set([...LADDER.filter((w) => w < own), Math.min(own, LADDER[LADDER.length - 1]!)])] : LADDER;\n const srcset = sizes && !width ? ladder.map((w) => `${make().width(w).url()} ${w}w`).join(\", \") : `${url} 1x, ${make().dpr(2).url()} 2x`;\n // A pixel width is the author's size for THIS image, so it also goes on as a style (a site rule\n // like `img { width: 100% }` beats a bare attribute), capped at the column it sits in. The focal\n // point rides as object-position, inert unless the site's CSS sets object-fit.\n const css: Record<string, string> = {\n ...(width ? { width: `${width}px`, maxWidth: \"100%\", height: \"auto\" } : {}),\n ...(hasFocal ? { objectPosition: objectPosition({ x: fx, y: fy }) } : {}),\n };\n const alt = opts.alt ?? (typeof asset.altText === \"string\" ? asset.altText : typeof asset.alt === \"string\" ? asset.alt : \"\");\n return { src: url, srcset, alt, css };\n}\n\nexport interface ImageAttrs {\n src: string;\n srcset: string;\n alt: string;\n loading: \"lazy\" | \"eager\";\n sizes?: string;\n width?: number;\n height?: number;\n style?: string;\n \"data-bcms-field\"?: string;\n \"data-bcms-kind\"?: \"image\";\n}\n\n/**\n * The `<img>` attributes for an image value, the same markup as every `<BcmsImage>`. Given `path`,\n * the image declares its field, so the editor binds it and a publish writes the new picture in:\n *\n * <img {...imageAttrs(page.hero.image, { path: \"hero.image\", sizes: \"100vw\" })} class=\"hero\" />\n */\nexport function imageAttrs(src: Parameters<typeof imageCore>[0], opts: ImageOptions = {}): ImageAttrs {\n const { src: url, srcset, alt, css } = imageCore(src, opts);\n const style = cssText(css);\n return {\n src: url,\n srcset,\n alt,\n loading: opts.loading ?? \"lazy\",\n ...(opts.sizes ? { sizes: opts.sizes } : {}),\n ...(opts.width ? { width: opts.width } : {}),\n ...(opts.height ? { height: opts.height } : {}),\n ...(style ? { style } : {}),\n ...(opts.path ? { \"data-bcms-field\": opts.path, \"data-bcms-kind\": \"image\" as const } : {}),\n };\n}\n"],"mappings":";AAWA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAIK;AACP,SAAS,uBAAuB,iBAAiB,mBAAmB,kBAAsE;AA2BnI,SAAS,aAAa,MAAc,aAA+F;AACxI,MAAI,CAAC,eAAe,OAAO,gBAAgB,YAAY,CAAC,OAAO,UAAU,eAAe,KAAK,aAAa,IAAI,EAAG,QAAO;AACxH,QAAM,QAAS,YAAwC,IAAI;AAC3D,SAAO,SAAS,OAAO,UAAU,WAAY,QAAuB;AACtE;AAEO,SAAS,WAAW,MAAc,aAAwE;AAC/G,QAAM,QAAQ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,GAAG;AACzB,SAAO;AAAA,IACL,KAAK;AAAA,IACL;AAAA,IACA;AAAA,IACA,SAAS,KAAK,WAAW;AAAA,IACzB,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,IAC1C,GAAI,KAAK,QAAQ,EAAE,OAAO,KAAK,MAAM,IAAI,CAAC;AAAA,IAC1C,GAAI,KAAK,SAAS,EAAE,QAAQ,KAAK,OAAO,IAAI,CAAC;AAAA,IAC7C,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC;AAAA,IACzB,GAAI,KAAK,OAAO,EAAE,mBAAmB,KAAK,MAAM,kBAAkB,QAAiB,IAAI,CAAC;AAAA,EAC1F;AACF;","names":[]}
package/dist/draft.cjs CHANGED
@@ -20,6 +20,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // src/draft.ts
21
21
  var draft_exports = {};
22
22
  __export(draft_exports, {
23
+ BRANCH_SIGNATURE_HEADER: () => BRANCH_SIGNATURE_HEADER,
23
24
  DRAFT_COOKIE: () => DRAFT_COOKIE,
24
25
  decodeTokenBranch: () => decodeTokenBranch,
25
26
  decodeTokenSlug: () => decodeTokenSlug,
@@ -28,6 +29,7 @@ __export(draft_exports, {
28
29
  draftTokenFrom: () => draftTokenFrom,
29
30
  previewTokenValid: () => previewTokenValid,
30
31
  safeRedirectPath: () => safeRedirectPath,
32
+ signBranchRead: () => signBranchRead,
31
33
  signValue: () => signValue,
32
34
  verifyValue: () => verifyValue
33
35
  });
@@ -56,6 +58,10 @@ async function verifyValue(signed, secret) {
56
58
  for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);
57
59
  return diff === 0 ? value : null;
58
60
  }
61
+ var BRANCH_SIGNATURE_HEADER = "X-BCMS-Branch-Signature";
62
+ async function signBranchRead(branch, secret, now = Date.now()) {
63
+ return signValue(`${Math.floor(now / 1e3)}:${branch}`, secret);
64
+ }
59
65
  function safeRedirectPath(to) {
60
66
  return to.startsWith("/") && !to.startsWith("//") && !to.startsWith("/\\") ? to : "/";
61
67
  }
@@ -119,6 +125,7 @@ function draftDisableResponse(request) {
119
125
  }
120
126
  // Annotate the CommonJS export names for ESM import in node:
121
127
  0 && (module.exports = {
128
+ BRANCH_SIGNATURE_HEADER,
122
129
  DRAFT_COOKIE,
123
130
  decodeTokenBranch,
124
131
  decodeTokenSlug,
@@ -127,6 +134,7 @@ function draftDisableResponse(request) {
127
134
  draftTokenFrom,
128
135
  previewTokenValid,
129
136
  safeRedirectPath,
137
+ signBranchRead,
130
138
  signValue,
131
139
  verifyValue
132
140
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/draft.ts"],"sourcesContent":["/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n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,UAAU,iBAAiB,IAAI,aAAa,IAAI,UAAU,KAAK,GAAG,GAAG,cAAc,GAAG,YAAY,+CAA+C;AAAA,EAC9J,CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/draft.ts"],"sourcesContent":["/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new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AAG,GAAG,cAAc,OAAO,EAAE,CAAC;AACnJ;AAGO,SAAS,qBAAqB,SAA4B;AAC/D,QAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;AAC/B,SAAO,IAAI,SAAS,MAAM;AAAA,IACxB,QAAQ;AAAA,IACR,SAAS,EAAE,UAAU,iBAAiB,IAAI,aAAa,IAAI,UAAU,KAAK,GAAG,GAAG,cAAc,GAAG,YAAY,+CAA+C;AAAA,EAC9J,CAAC;AACH;","names":[]}
package/dist/draft.d.cts CHANGED
@@ -11,6 +11,14 @@ declare const DRAFT_COOKIE = "bcms-draft";
11
11
  declare function signValue(value: string, secret: string): Promise<string>;
12
12
  /** The original value of a signed one, or null when it was tampered with. */
13
13
  declare function verifyValue(signed: string, secret: string): Promise<string | null>;
14
+ /** The header a server signs a content-branch read with (@see signBranchRead). */
15
+ declare const BRANCH_SIGNATURE_HEADER = "X-BCMS-Branch-Signature";
16
+ /**
17
+ * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a
18
+ * server it runs (and nothing else has). The Delivery API serves the branch to this signature with
19
+ * no draft key. A signature is good for five minutes: sign per request.
20
+ */
21
+ declare function signBranchRead(branch: string, secret: string, now?: number): Promise<string>;
14
22
  /** Only same-origin relative paths: blocks "//evil.com", "https://evil.com" and "/\\evil.com". */
15
23
  declare function safeRedirectPath(to: string): string;
16
24
  /**
@@ -41,4 +49,4 @@ declare function draftEnableResponse(request: Request, opts: {
41
49
  /** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */
42
50
  declare function draftDisableResponse(request: Request): Response;
43
51
 
44
- export { DRAFT_COOKIE, decodeTokenBranch, decodeTokenSlug, draftDisableResponse, draftEnableResponse, draftTokenFrom, previewTokenValid, safeRedirectPath, signValue, verifyValue };
52
+ export { BRANCH_SIGNATURE_HEADER, DRAFT_COOKIE, decodeTokenBranch, decodeTokenSlug, draftDisableResponse, draftEnableResponse, draftTokenFrom, previewTokenValid, safeRedirectPath, signBranchRead, signValue, verifyValue };
package/dist/draft.d.ts CHANGED
@@ -11,6 +11,14 @@ declare const DRAFT_COOKIE = "bcms-draft";
11
11
  declare function signValue(value: string, secret: string): Promise<string>;
12
12
  /** The original value of a signed one, or null when it was tampered with. */
13
13
  declare function verifyValue(signed: string, secret: string): Promise<string | null>;
14
+ /** The header a server signs a content-branch read with (@see signBranchRead). */
15
+ declare const BRANCH_SIGNATURE_HEADER = "X-BCMS-Branch-Signature";
16
+ /**
17
+ * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a
18
+ * server it runs (and nothing else has). The Delivery API serves the branch to this signature with
19
+ * no draft key. A signature is good for five minutes: sign per request.
20
+ */
21
+ declare function signBranchRead(branch: string, secret: string, now?: number): Promise<string>;
14
22
  /** Only same-origin relative paths: blocks "//evil.com", "https://evil.com" and "/\\evil.com". */
15
23
  declare function safeRedirectPath(to: string): string;
16
24
  /**
@@ -41,4 +49,4 @@ declare function draftEnableResponse(request: Request, opts: {
41
49
  /** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */
42
50
  declare function draftDisableResponse(request: Request): Response;
43
51
 
44
- export { DRAFT_COOKIE, decodeTokenBranch, decodeTokenSlug, draftDisableResponse, draftEnableResponse, draftTokenFrom, previewTokenValid, safeRedirectPath, signValue, verifyValue };
52
+ export { BRANCH_SIGNATURE_HEADER, DRAFT_COOKIE, decodeTokenBranch, decodeTokenSlug, draftDisableResponse, draftEnableResponse, draftTokenFrom, previewTokenValid, safeRedirectPath, signBranchRead, signValue, verifyValue };
package/dist/draft.js CHANGED
@@ -23,6 +23,10 @@ async function verifyValue(signed, secret) {
23
23
  for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);
24
24
  return diff === 0 ? value : null;
25
25
  }
26
+ var BRANCH_SIGNATURE_HEADER = "X-BCMS-Branch-Signature";
27
+ async function signBranchRead(branch, secret, now = Date.now()) {
28
+ return signValue(`${Math.floor(now / 1e3)}:${branch}`, secret);
29
+ }
26
30
  function safeRedirectPath(to) {
27
31
  return to.startsWith("/") && !to.startsWith("//") && !to.startsWith("/\\") ? to : "/";
28
32
  }
@@ -85,6 +89,7 @@ function draftDisableResponse(request) {
85
89
  });
86
90
  }
87
91
  export {
92
+ BRANCH_SIGNATURE_HEADER,
88
93
  DRAFT_COOKIE,
89
94
  decodeTokenBranch,
90
95
  decodeTokenSlug,
@@ -93,6 +98,7 @@ export {
93
98
  draftTokenFrom,
94
99
  previewTokenValid,
95
100
  safeRedirectPath,
101
+ signBranchRead,
96
102
  signValue,
97
103
  verifyValue
98
104
  };
package/dist/draft.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/draft.ts"],"sourcesContent":["/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new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CAAC;AACH;","names":[]}
1
+ {"version":3,"sources":["../src/draft.ts"],"sourcesContent":["/**\n * Draft mode, shared by every framework adapter: the signed cookie that says \"this visitor is\n * previewing\", the preview token's slug, and the redirect a draft route may follow.\n *\n * Web Crypto and `atob` only, so it runs in Node, edge runtimes and workers alike. Each adapter\n * mounts its own routes around these; the rules live here once.\n */\n\n/** The draft cookie every adapter sets: one name, so an editor link works on any framework. */\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nconst enc = new TextEncoder();\n\nfunction base64url(bytes: ArrayBuffer): string {\n const b = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n return b.replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nasync function hmac(value: string, secret: string): Promise<string> {\n const key = await crypto.subtle.importKey(\"raw\", enc.encode(secret), { name: \"HMAC\", hash: \"SHA-256\" }, false, [\"sign\"]);\n return base64url(await crypto.subtle.sign(\"HMAC\", key, enc.encode(value)));\n}\n\n/** Sign a value as `value.sig` for tamper-evident cookie storage (HMAC-SHA256, base64url). */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** The original value of a signed one, or null when it was tampered with. */\nexport async function verifyValue(signed: string, secret: string): Promise<string | null> {\n const idx = signed.lastIndexOf(\".\");\n if (idx < 0) return null;\n const value = signed.slice(0, idx);\n const sig = signed.slice(idx + 1);\n const expected = await hmac(value, secret);\n if (sig.length !== expected.length) return null;\n let diff = 0;\n for (let i = 0; i < sig.length; i++) diff |= sig.charCodeAt(i) ^ expected.charCodeAt(i);\n return diff === 0 ? value : null;\n}\n\n/** The header a server signs a content-branch read with (@see signBranchRead). */\nexport const BRANCH_SIGNATURE_HEADER = \"X-BCMS-Branch-Signature\";\n\n/**\n * Sign a read of content branch `branch` with `BCMS_BRANCH_SECRET`, which BetterCMS hosting gives a\n * server it runs (and nothing else has). The Delivery API serves the branch to this signature with\n * no draft key. A signature is good for five minutes: sign per request.\n */\nexport async function signBranchRead(branch: string, secret: string, now = Date.now()): Promise<string> {\n return signValue(`${Math.floor(now / 1000)}:${branch}`, secret);\n}\n\n/** Only same-origin relative paths: blocks \"//evil.com\", \"https://evil.com\" and \"/\\\\evil.com\". */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") && !to.startsWith(\"/\\\\\") ? to : \"/\";\n}\n\nfunction tokenPayload(token: string): { entrySlug?: string; branch?: string } | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n return JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string; branch?: string };\n } catch {\n return null;\n }\n}\n\n/**\n * The content branch a preview token was minted on, or null for main. Read UNVERIFIED: an adapter\n * only stores a token the backend accepted, and branch reads need the site's draft key regardless.\n * Pass it as the client's `branch` in draft mode and the whole site previews from that branch.\n */\nexport function decodeTokenBranch(token: string | null | undefined): string | null {\n return (token && tokenPayload(token)?.branch) || null;\n}\n\n/** A preview token's `entrySlug`, read from its payload UNVERIFIED (the backend verifies it). */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n // atob gives bytes as Latin-1: decoded as UTF-8, a slug like `über-uns` survives.\n const bytes = Uint8Array.from(atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")), (c) => c.charCodeAt(0));\n const json = JSON.parse(new TextDecoder().decode(bytes)) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n\n/**\n * Ask the backend whether a preview token is good: the backend is the signature authority, so a\n * draft route enables draft mode only on its yes.\n */\nexport async function previewTokenValid(apiUrl: string, token: string, fetchImpl: typeof fetch = fetch): Promise<boolean> {\n const slug = decodeTokenSlug(token);\n if (!slug) return false;\n const res = await fetchImpl(`${apiUrl.replace(/\\/+$/, \"\")}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`);\n await res.body?.cancel().catch(() => {});\n return res.ok;\n}\n\n/** The draft cookie's preview token from a `Cookie` header, or null when absent or tampered with. */\nexport async function draftTokenFrom(cookieHeader: string | null | undefined, secret: string | undefined): Promise<string | null> {\n if (!cookieHeader || !secret) return null;\n const m = new RegExp(`(?:^|;\\\\s*)${DRAFT_COOKIE}=([^;]+)`).exec(cookieHeader);\n if (!m) return null;\n try {\n return await verifyValue(decodeURIComponent(m[1]!), secret);\n } catch {\n return null;\n }\n}\n\n/**\n * The draft-enable route for any server that speaks Web `Request`/`Response` (SvelteKit `+server.ts`,\n * Nuxt via `toWebRequest`, Remix, Hono): `GET ?token=…&redirect=/x` checks the token with the\n * backend, sets the signed draft cookie and redirects. 401 on a refused token; 500 without a secret.\n */\nexport async function draftEnableResponse(request: Request, opts: { apiUrl: string; secret: string | undefined; fetchImpl?: typeof fetch }): Promise<Response> {\n const url = new URL(request.url);\n const token = url.searchParams.get(\"token\");\n if (!opts.secret) return new Response(\"BCMS_DRAFT_SECRET is not configured\", { status: 500 });\n if (!token) return new Response(\"Missing token\", { status: 400 });\n if (!(await previewTokenValid(opts.apiUrl, token, opts.fetchImpl))) return new Response(\"Invalid or expired token\", { status: 401 });\n const cookie = `${DRAFT_COOKIE}=${encodeURIComponent(await signValue(token, opts.secret))}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${url.protocol === \"https:\" ? \"; Secure\" : \"\"}`;\n return new Response(null, { status: 302, headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": cookie } });\n}\n\n/** Leave draft mode: clear the cookie and redirect (`?redirect=/x`, same-origin only). */\nexport function draftDisableResponse(request: Request): Response {\n const url = new URL(request.url);\n return new Response(null, {\n status: 302,\n headers: { Location: safeRedirectPath(url.searchParams.get(\"redirect\") ?? \"/\"), \"Set-Cookie\": `${DRAFT_COOKIE}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AI,UAAU,KAAK,GAAG,GAAG,cAAc,GAAG,YAAY,+CAA+C;AAAA,EAC9J,CAAC;AACH;","names":[]}
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `bcms:content-applied` — what the visual editor tells a page after it has applied an edit to
3
+ * the page's DOM.
4
+ *
5
+ * An edit changes how tall a heading is. Everything on the page that measured the layout once
6
+ * (ScrollTrigger's start and end positions, Lenis's scroll limit, a carousel's slide widths, a
7
+ * text splitter's lines) is now wrong, and only the page's own code can measure again. So the
8
+ * editor posts one message to the frame's window after each applied edit, and the site listens:
9
+ *
10
+ * onContentApplied(() => ScrollTrigger.refresh());
11
+ *
12
+ * A published page receives no such message: nothing there posts it, and the listener is inert.
13
+ */
14
+ /** The `type` of the message. */
15
+ declare const CONTENT_APPLIED = "bcms:content-applied";
16
+ interface ContentAppliedMessage {
17
+ type: typeof CONTENT_APPLIED;
18
+ /** The field addresses whose rendering changed; empty when the editor does not say. */
19
+ fields: string[];
20
+ }
21
+ /** The message the editor posts: `frame.contentWindow.postMessage(contentApplied(fields), origin)`. */
22
+ declare const contentApplied: (fields?: readonly string[]) => ContentAppliedMessage;
23
+ /** The least of `window` this needs. */
24
+ interface MessageTarget {
25
+ addEventListener(type: "message", listener: (event: {
26
+ data: unknown;
27
+ }) => void): void;
28
+ removeEventListener(type: "message", listener: (event: {
29
+ data: unknown;
30
+ }) => void): void;
31
+ }
32
+ /**
33
+ * Run `handler` after every edit the editor applies to this page. Returns the function that
34
+ * stops listening. Safe to call where there is no window (a server render): it does nothing.
35
+ */
36
+ declare function onContentApplied(handler: (message: ContentAppliedMessage) => void, target?: MessageTarget | undefined): () => void;
37
+
38
+ /**
39
+ * `inEditor()`: is this page running inside the BetterCMS Visual Editor's canvas?
40
+ *
41
+ * The editor frames the site and names the frame, so the answer is the page's own `window.name`:
42
+ * there from the first script, kept through every navigation inside the frame, and never set on
43
+ * a published page a visitor opens. A site asks before it starts what the canvas cannot share:
44
+ *
45
+ * const smooth = inEditor() ? null : new LocomotiveScroll({ el, smooth: true });
46
+ *
47
+ * The canvas owns the scroll, the pointer and the place on the page; the site's motion (scroll
48
+ * triggers, timelines, WebGL scenes) runs there as it does live. What has to stand down is only
49
+ * what takes those three away: scroll that is not the window's own, an intro that holds the
50
+ * page, a cursor drawn over it.
51
+ */
52
+ /** The canvas frame's name. The dashboard sets this exact word (`EDITOR_FRAME_NAME`). */
53
+ declare const EDITOR_FRAME_NAME = "bcms-editor";
54
+ /** The least of `window` this needs. */
55
+ interface FramedWindow {
56
+ name: string;
57
+ self: unknown;
58
+ top: unknown;
59
+ }
60
+ /** True inside the editor's canvas. Safe where there is no window (a server render): false. */
61
+ declare function inEditor(win?: FramedWindow | undefined): boolean;
62
+
63
+ export { CONTENT_APPLIED as C, EDITOR_FRAME_NAME as E, type ContentAppliedMessage as a, contentApplied as c, inEditor as i, onContentApplied as o };
@@ -0,0 +1,63 @@
1
+ /**
2
+ * `bcms:content-applied` — what the visual editor tells a page after it has applied an edit to
3
+ * the page's DOM.
4
+ *
5
+ * An edit changes how tall a heading is. Everything on the page that measured the layout once
6
+ * (ScrollTrigger's start and end positions, Lenis's scroll limit, a carousel's slide widths, a
7
+ * text splitter's lines) is now wrong, and only the page's own code can measure again. So the
8
+ * editor posts one message to the frame's window after each applied edit, and the site listens:
9
+ *
10
+ * onContentApplied(() => ScrollTrigger.refresh());
11
+ *
12
+ * A published page receives no such message: nothing there posts it, and the listener is inert.
13
+ */
14
+ /** The `type` of the message. */
15
+ declare const CONTENT_APPLIED = "bcms:content-applied";
16
+ interface ContentAppliedMessage {
17
+ type: typeof CONTENT_APPLIED;
18
+ /** The field addresses whose rendering changed; empty when the editor does not say. */
19
+ fields: string[];
20
+ }
21
+ /** The message the editor posts: `frame.contentWindow.postMessage(contentApplied(fields), origin)`. */
22
+ declare const contentApplied: (fields?: readonly string[]) => ContentAppliedMessage;
23
+ /** The least of `window` this needs. */
24
+ interface MessageTarget {
25
+ addEventListener(type: "message", listener: (event: {
26
+ data: unknown;
27
+ }) => void): void;
28
+ removeEventListener(type: "message", listener: (event: {
29
+ data: unknown;
30
+ }) => void): void;
31
+ }
32
+ /**
33
+ * Run `handler` after every edit the editor applies to this page. Returns the function that
34
+ * stops listening. Safe to call where there is no window (a server render): it does nothing.
35
+ */
36
+ declare function onContentApplied(handler: (message: ContentAppliedMessage) => void, target?: MessageTarget | undefined): () => void;
37
+
38
+ /**
39
+ * `inEditor()`: is this page running inside the BetterCMS Visual Editor's canvas?
40
+ *
41
+ * The editor frames the site and names the frame, so the answer is the page's own `window.name`:
42
+ * there from the first script, kept through every navigation inside the frame, and never set on
43
+ * a published page a visitor opens. A site asks before it starts what the canvas cannot share:
44
+ *
45
+ * const smooth = inEditor() ? null : new LocomotiveScroll({ el, smooth: true });
46
+ *
47
+ * The canvas owns the scroll, the pointer and the place on the page; the site's motion (scroll
48
+ * triggers, timelines, WebGL scenes) runs there as it does live. What has to stand down is only
49
+ * what takes those three away: scroll that is not the window's own, an intro that holds the
50
+ * page, a cursor drawn over it.
51
+ */
52
+ /** The canvas frame's name. The dashboard sets this exact word (`EDITOR_FRAME_NAME`). */
53
+ declare const EDITOR_FRAME_NAME = "bcms-editor";
54
+ /** The least of `window` this needs. */
55
+ interface FramedWindow {
56
+ name: string;
57
+ self: unknown;
58
+ top: unknown;
59
+ }
60
+ /** True inside the editor's canvas. Safe where there is no window (a server render): false. */
61
+ declare function inEditor(win?: FramedWindow | undefined): boolean;
62
+
63
+ export { CONTENT_APPLIED as C, EDITOR_FRAME_NAME as E, type ContentAppliedMessage as a, contentApplied as c, inEditor as i, onContentApplied as o };
package/dist/index.cjs CHANGED
@@ -1301,6 +1301,10 @@ var BetterCMS = {
1301
1301
  }
1302
1302
  };
1303
1303
 
1304
+ // src/draft.ts
1305
+ var enc = new TextEncoder();
1306
+ var BRANCH_SIGNATURE_HEADER = "X-BCMS-Branch-Signature";
1307
+
1304
1308
  // src/read-client.ts
1305
1309
  var DEFAULT_TIMEOUT3 = 1e4;
1306
1310
  function qs(params2) {
@@ -1360,6 +1364,7 @@ function createClient(options) {
1360
1364
  const headers = () => {
1361
1365
  const h = { "Content-Type": "application/json" };
1362
1366
  if (apiKey) h["X-API-Key"] = apiKey;
1367
+ if (branch && options.branchSignature) h[BRANCH_SIGNATURE_HEADER] = options.branchSignature;
1363
1368
  return h;
1364
1369
  };
1365
1370
  const collapse = options.cache && perspective === "published" ? createRequestCache() : void 0;