@bettercms-ai/astro 0.23.0 → 0.25.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/components/BcmsField.astro +13 -4
- package/components/BcmsImage.astro +22 -3
- package/dist/bindings.d.ts +15 -1
- package/dist/bindings.js +62 -1
- package/dist/bindings.js.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/package.json +5 -5
|
@@ -6,8 +6,10 @@
|
|
|
6
6
|
* hand-render field values (`f.title`, `f.body.html`), so the field `path` is
|
|
7
7
|
* declared here by the author — the delivery payload carries no source-map.
|
|
8
8
|
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
9
|
+
* When the slot is ONE element, the attributes go on that element and nothing is added to
|
|
10
|
+
* the page: `.hero > h1` and every animation target stay what the author wrote. Text, or
|
|
11
|
+
* several elements, are wrapped in a `display:contents` span as before; pass `as` to carry
|
|
12
|
+
* the attributes on a real wrapper instead.
|
|
11
13
|
*
|
|
12
14
|
* `path` follows the editor grammar: `title` · `hero.title` · `columns[0].links[2].href`
|
|
13
15
|
* (dotted keys and any number of `[n]` indices). For images, put the attributes on the
|
|
@@ -19,12 +21,19 @@ interface Props {
|
|
|
19
21
|
path: string;
|
|
20
22
|
/** Kind hint the editor's reflection branches on. Omit for plain text/number. */
|
|
21
23
|
kind?: "richtext" | "image";
|
|
22
|
-
/** Wrapper element.
|
|
24
|
+
/** Wrapper element. Without it: no wrapper around a single element, a `display:contents` span around anything else. */
|
|
23
25
|
as?: string;
|
|
24
26
|
}
|
|
27
|
+
import { stampSoleElement } from "../dist/bindings.js";
|
|
28
|
+
|
|
25
29
|
const { path, kind, as } = Astro.props;
|
|
26
30
|
const Tag = (as ?? "span") as keyof HTMLElementTagNameMap;
|
|
31
|
+
// Rendered once, here: the same markup is either stamped or wrapped below.
|
|
32
|
+
const slot = await Astro.slots.render("default");
|
|
33
|
+
const sole = as ? null : stampSoleElement(slot, { "data-bcms-field": path, "data-bcms-kind": kind });
|
|
27
34
|
---
|
|
35
|
+
{sole !== null ? <Fragment set:html={sole} /> : (
|
|
28
36
|
<Tag data-bcms-field={path} data-bcms-kind={kind} style={as ? undefined : "display:contents"}>
|
|
29
|
-
<slot />
|
|
37
|
+
<Fragment set:html={slot} />
|
|
30
38
|
</Tag>
|
|
39
|
+
)}
|
|
@@ -4,6 +4,16 @@
|
|
|
4
4
|
* endpoint, with a 1x/2x srcset. Accepts an asset id, a MediaAsset, a URL, or an image
|
|
5
5
|
* VALUE (`{ url, altText, focal?, crop? }`) — whose per-placement crop and focal point are
|
|
6
6
|
* applied by image-url itself (`rect`, and fx/fy inside the crop), the same as on every lane.
|
|
7
|
+
*
|
|
8
|
+
* Given `path`, the <img> declares its field (`data-bcms-field`, kind `image`), so the visual
|
|
9
|
+
* editor binds it and a publish writes the new picture into it — and the page reads the value
|
|
10
|
+
* through this component, so the next build renders that same picture:
|
|
11
|
+
*
|
|
12
|
+
* <BcmsImage path="hero.image" src={page.hero.image} sizes="(min-width: 800px) 50vw, 100vw" />
|
|
13
|
+
*
|
|
14
|
+
* With `sizes` and no `width` the srcset is a WIDTH ladder (never wider than the picture), which
|
|
15
|
+
* is what `sizes` selects from. The value's `altText` is the alt unless `alt` says otherwise.
|
|
16
|
+
* The same markup as @bettercms-ai/next's <BcmsImage>.
|
|
7
17
|
*/
|
|
8
18
|
import config from "bettercms:config";
|
|
9
19
|
import imageUrlBuilder, {
|
|
@@ -34,13 +44,15 @@ interface Props {
|
|
|
34
44
|
*/
|
|
35
45
|
focalX?: number | null;
|
|
36
46
|
focalY?: number | null;
|
|
47
|
+
/** The field this image renders, in the editor grammar (`cover`, `hero.image`). */
|
|
48
|
+
path?: string;
|
|
37
49
|
/** Any other attribute (e.g. `data-bcms-field`) is forwarded to the <img>. */
|
|
38
50
|
[attr: string]: unknown;
|
|
39
51
|
}
|
|
40
52
|
|
|
41
53
|
const {
|
|
42
54
|
src,
|
|
43
|
-
alt
|
|
55
|
+
alt,
|
|
44
56
|
width,
|
|
45
57
|
height,
|
|
46
58
|
format = "webp",
|
|
@@ -51,6 +63,7 @@ const {
|
|
|
51
63
|
class: className,
|
|
52
64
|
focalX,
|
|
53
65
|
focalY,
|
|
66
|
+
path,
|
|
54
67
|
style,
|
|
55
68
|
...rest
|
|
56
69
|
} = Astro.props;
|
|
@@ -84,6 +97,10 @@ const make = () => {
|
|
|
84
97
|
};
|
|
85
98
|
|
|
86
99
|
const src1x = make().url();
|
|
100
|
+
// The widths a `sizes` image offers: phone to desktop, and never an upscale of the picture.
|
|
101
|
+
const LADDER = [480, 768, 1080, 1440, 1920];
|
|
102
|
+
const own = num(asset.width);
|
|
103
|
+
const ladder = own ? [...new Set([...LADDER.filter((w) => w < own), Math.min(own, LADDER[LADDER.length - 1])])] : LADDER;
|
|
87
104
|
// A pixel width is the author's size for THIS image, so it goes on as a style (a site rule like
|
|
88
105
|
// `img { width: 100% }` beats a bare attribute) — paired with max-width so it never overflows a
|
|
89
106
|
// narrower column, and height:auto so shrinking keeps the aspect ratio.
|
|
@@ -100,8 +117,10 @@ const mergedStyle = [widthStyle, focalStyle, typeof style === "string" ? style :
|
|
|
100
117
|
|
|
101
118
|
<img
|
|
102
119
|
src={src1x}
|
|
103
|
-
srcset={`${src1x} 1x, ${src2x} 2x`}
|
|
104
|
-
alt={alt}
|
|
120
|
+
srcset={sizes && !width ? ladder.map((w) => `${make().width(w).url()} ${w}w`).join(", ") : `${src1x} 1x, ${src2x} 2x`}
|
|
121
|
+
alt={alt ?? (typeof asset.altText === "string" ? asset.altText : typeof asset.alt === "string" ? asset.alt : "")}
|
|
122
|
+
data-bcms-field={path}
|
|
123
|
+
data-bcms-kind={path ? "image" : undefined}
|
|
105
124
|
width={width}
|
|
106
125
|
height={height}
|
|
107
126
|
sizes={sizes}
|
package/dist/bindings.d.ts
CHANGED
|
@@ -38,5 +38,19 @@ declare function bindProps(id: string | undefined, entries: readonly {
|
|
|
38
38
|
attr: string;
|
|
39
39
|
present: boolean;
|
|
40
40
|
}[], ctx: BindingCtx): Record<string, string>;
|
|
41
|
+
/**
|
|
42
|
+
* `<BcmsField>`'s child, when it is ONE element: the same markup with the binding attributes on
|
|
43
|
+
* that element's own tag. Null when the rendered slot is anything else (text, several elements,
|
|
44
|
+
* an element that already declares a field, a framework island), and the caller wraps as before.
|
|
45
|
+
*
|
|
46
|
+
* Why not always wrap: the wrapper is a `<span>` between the author's parent and the author's
|
|
47
|
+
* element. `.hero > h1`, `gsap.utils.toArray(".hero > *")` and `:first-child` all stop matching,
|
|
48
|
+
* and an animation that targeted the heading targets nothing. With the attributes on the element
|
|
49
|
+
* itself the page's DOM is exactly the one the author wrote.
|
|
50
|
+
*
|
|
51
|
+
* A scan, not a parser: it only has to find where the first element ends. Anything it is not
|
|
52
|
+
* sure of answers null, which is the old behaviour.
|
|
53
|
+
*/
|
|
54
|
+
declare function stampSoleElement(html: string, attrs: Record<string, string | undefined>): string | null;
|
|
41
55
|
|
|
42
|
-
export { type BindingCtx, addressFor, bind, bindProps };
|
|
56
|
+
export { type BindingCtx, addressFor, bind, bindProps, stampSoleElement };
|
package/dist/bindings.js
CHANGED
|
@@ -18,9 +18,70 @@ function bindProps(id, entries, ctx) {
|
|
|
18
18
|
});
|
|
19
19
|
return resolved.length ? { "data-bcms-props": formatPropsAttribute(resolved) } : {};
|
|
20
20
|
}
|
|
21
|
+
var VOID_TAGS = /* @__PURE__ */ new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
|
22
|
+
var RAW_TEXT_TAGS = /* @__PURE__ */ new Set(["script", "style", "textarea", "title"]);
|
|
23
|
+
function tagEnd(html, from) {
|
|
24
|
+
let quote = "";
|
|
25
|
+
for (let i = from; i < html.length; i++) {
|
|
26
|
+
const c = html[i];
|
|
27
|
+
if (quote) {
|
|
28
|
+
if (c === quote) quote = "";
|
|
29
|
+
} else if (c === '"' || c === "'") quote = c;
|
|
30
|
+
else if (c === ">") return i;
|
|
31
|
+
}
|
|
32
|
+
return -1;
|
|
33
|
+
}
|
|
34
|
+
function stampSoleElement(html, attrs) {
|
|
35
|
+
const start = html.search(/\S/);
|
|
36
|
+
const open = /^<([a-zA-Z][\w:-]*)/.exec(html.slice(start));
|
|
37
|
+
if (start < 0 || !open) return null;
|
|
38
|
+
const tag = open[1].toLowerCase();
|
|
39
|
+
const openEnd = tagEnd(html, start);
|
|
40
|
+
if (openEnd < 0 || tag.includes("-") || /\sdata-bcms-(?:layout-)?field[\s=>/]/.test(html.slice(start, openEnd + 1))) return null;
|
|
41
|
+
let i = openEnd + 1;
|
|
42
|
+
if (!VOID_TAGS.has(tag) && html[openEnd - 1] !== "/") {
|
|
43
|
+
let depth = 1;
|
|
44
|
+
let raw = RAW_TEXT_TAGS.has(tag) ? tag : "";
|
|
45
|
+
while (depth > 0) {
|
|
46
|
+
const lt = html.indexOf("<", i);
|
|
47
|
+
if (lt < 0) return null;
|
|
48
|
+
if (raw) {
|
|
49
|
+
const close = html.toLowerCase().indexOf(`</${raw}`, i);
|
|
50
|
+
if (close < 0) return null;
|
|
51
|
+
i = tagEnd(html, close) + 1;
|
|
52
|
+
if (i === 0) return null;
|
|
53
|
+
raw = "";
|
|
54
|
+
depth--;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (html.startsWith("<!--", lt)) {
|
|
58
|
+
const end2 = html.indexOf("-->", lt + 4);
|
|
59
|
+
if (end2 < 0) return null;
|
|
60
|
+
i = end2 + 3;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const end = tagEnd(html, lt);
|
|
64
|
+
if (end < 0) return null;
|
|
65
|
+
const name = /^<\/?([a-zA-Z][\w:-]*)/.exec(html.slice(lt, end + 1))?.[1]?.toLowerCase();
|
|
66
|
+
if (name && html[lt + 1] === "/") depth--;
|
|
67
|
+
else if (name && !VOID_TAGS.has(name) && html[end - 1] !== "/") {
|
|
68
|
+
depth++;
|
|
69
|
+
if (RAW_TEXT_TAGS.has(name)) raw = name;
|
|
70
|
+
}
|
|
71
|
+
i = end + 1;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
if (html.slice(i).trim() !== "") return null;
|
|
75
|
+
const escape = (value) => value.replace(/&/g, "&").replace(/"/g, """);
|
|
76
|
+
const added = Object.entries(attrs).filter((entry) => entry[1] !== void 0).map(([name, value]) => ` ${name}="${escape(value)}"`).join("");
|
|
77
|
+
const selfClosed = html[openEnd - 1] === "/";
|
|
78
|
+
const at = selfClosed ? openEnd - 1 : openEnd;
|
|
79
|
+
return html.slice(0, at).replace(/\s+$/, "") + added + (selfClosed ? " " : "") + html.slice(at);
|
|
80
|
+
}
|
|
21
81
|
export {
|
|
22
82
|
addressFor,
|
|
23
83
|
bind,
|
|
24
|
-
bindProps
|
|
84
|
+
bindProps,
|
|
85
|
+
stampSoleElement
|
|
25
86
|
};
|
|
26
87
|
//# sourceMappingURL=bindings.js.map
|
package/dist/bindings.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/bindings.ts"],"sourcesContent":["/**\n * Visual Editor addresses for the Astro renderer.\n *\n * Identical contract to `@bettercms-ai/next`'s `bindings.ts`, and the SAME reason for existing:\n * inside a component instance the definition's block ids address nothing, because they are\n * shared by every instance of it. Stamping them produces an orphan on one placement and a\n * duplicate that drops BOTH on two.\n *\n * Kept as a `.ts` module rather than inlined in the `.astro` frontmatter so the logic is\n * testable without an Astro compiler, and so the two SDKs cannot drift from each other by\n * having one file edited and not the other.\n */\nimport type { BindingKind } from \"@bettercms-ai/types\";\nimport { formatPropsAttribute } from \"@bettercms-ai/types\";\n\nexport interface BindingCtx {\n /** Present only inside a component instance, where it is AUTHORITATIVE. */\n fieldAddresses?: Map<string, string>;\n}\n\n/** The address a write lands on, or null when none exists. */\nexport function addressFor(id: string | undefined, prop: string, ctx: BindingCtx): string | null {\n if (!id) return null;\n const key = `${id}__${prop}`;\n if (ctx.fieldAddresses) return ctx.fieldAddresses.get(key) ?? null;\n return key;\n}\n\n/**\n * Attributes for a value rendered as this element's own content. Astro omits `undefined`\n * attributes, so an empty object spreads to nothing.\n */\nexport function bind(\n id: string | undefined,\n prop: string,\n kind: BindingKind,\n ctx: BindingCtx,\n): Record<string, string> {\n const address = addressFor(id, prop, ctx);\n return address ? { \"data-bcms-field\": address, \"data-bcms-kind\": kind } : {};\n}\n\n/**\n * Attributes for values that live in an ATTRIBUTE of this element. `data-bcms-field` addresses\n * one element and an element cannot hold two, so these ride `data-bcms-props`:\n * `<address>|<kind>|<domAttribute>`, semicolon separated.\n *\n * An entry whose value is absent is dropped — `setFieldPath` refuses to create a final key, so\n * the address would be a write the editor rejects.\n */\nexport function bindProps(\n id: string | undefined,\n entries: readonly { prop: string; kind: BindingKind; attr: string; present: boolean }[],\n ctx: BindingCtx,\n): Record<string, string> {\n const resolved = entries.flatMap(({ prop, kind, attr, present }) => {\n if (!present) return [];\n const address = addressFor(id, prop, ctx);\n return address ? [{ address, kind, attr }] : [];\n });\n return resolved.length ? { \"data-bcms-props\": formatPropsAttribute(resolved) } : {};\n}\n"],"mappings":";AAaA,SAAS,4BAA4B;AAQ9B,SAAS,WAAW,IAAwB,MAAc,KAAgC;AAC/F,MAAI,CAAC,GAAI,QAAO;AAChB,QAAM,MAAM,GAAG,EAAE,KAAK,IAAI;AAC1B,MAAI,IAAI,eAAgB,QAAO,IAAI,eAAe,IAAI,GAAG,KAAK;AAC9D,SAAO;AACT;AAMO,SAAS,KACd,IACA,MACA,MACA,KACwB;AACxB,QAAM,UAAU,WAAW,IAAI,MAAM,GAAG;AACxC,SAAO,UAAU,EAAE,mBAAmB,SAAS,kBAAkB,KAAK,IAAI,CAAC;AAC7E;AAUO,SAAS,UACd,IACA,SACA,KACwB;AACxB,QAAM,WAAW,QAAQ,QAAQ,CAAC,EAAE,MAAM,MAAM,MAAM,QAAQ,MAAM;AAClE,QAAI,CAAC,QAAS,QAAO,CAAC;AACtB,UAAM,UAAU,WAAW,IAAI,MAAM,GAAG;AACxC,WAAO,UAAU,CAAC,EAAE,SAAS,MAAM,KAAK,CAAC,IAAI,CAAC;AAAA,EAChD,CAAC;AACD,SAAO,SAAS,SAAS,EAAE,mBAAmB,qBAAqB,QAAQ,EAAE,IAAI,CAAC;AACpF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/bindings.ts"],"sourcesContent":["/**\n * Visual Editor addresses for the Astro renderer.\n *\n * Identical contract to `@bettercms-ai/next`'s `bindings.ts`, and the SAME reason for existing:\n * inside a component instance the definition's block ids address nothing, because they are\n * shared by every instance of it. Stamping them produces an orphan on one placement and a\n * duplicate that drops BOTH on two.\n *\n * Kept as a `.ts` module rather than inlined in the `.astro` frontmatter so the logic is\n * testable without an Astro compiler, and so the two SDKs cannot drift from each other by\n * having one file edited and not the other.\n */\nimport type { BindingKind } from \"@bettercms-ai/types\";\nimport { formatPropsAttribute } from \"@bettercms-ai/types\";\n\nexport interface BindingCtx {\n /** Present only inside a component instance, where it is AUTHORITATIVE. */\n fieldAddresses?: Map<string, string>;\n}\n\n/** The address a write lands on, or null when none exists. */\nexport function addressFor(id: string | undefined, prop: string, ctx: BindingCtx): string | null {\n if (!id) return null;\n const key = `${id}__${prop}`;\n if (ctx.fieldAddresses) return ctx.fieldAddresses.get(key) ?? null;\n return key;\n}\n\n/**\n * Attributes for a value rendered as this element's own content. Astro omits `undefined`\n * attributes, so an empty object spreads to nothing.\n */\nexport function bind(\n id: string | undefined,\n prop: string,\n kind: BindingKind,\n ctx: BindingCtx,\n): Record<string, string> {\n const address = addressFor(id, prop, ctx);\n return address ? { \"data-bcms-field\": address, \"data-bcms-kind\": kind } : {};\n}\n\n/**\n * Attributes for values that live in an ATTRIBUTE of this element. `data-bcms-field` addresses\n * one element and an element cannot hold two, so these ride `data-bcms-props`:\n * `<address>|<kind>|<domAttribute>`, semicolon separated.\n *\n * An entry whose value is absent is dropped — `setFieldPath` refuses to create a final key, so\n * the address would be a write the editor rejects.\n */\nexport function bindProps(\n id: string | undefined,\n entries: readonly { prop: string; kind: BindingKind; attr: string; present: boolean }[],\n ctx: BindingCtx,\n): Record<string, string> {\n const resolved = entries.flatMap(({ prop, kind, attr, present }) => {\n if (!present) return [];\n const address = addressFor(id, prop, ctx);\n return address ? [{ address, kind, attr }] : [];\n });\n return resolved.length ? { \"data-bcms-props\": formatPropsAttribute(resolved) } : {};\n}\n\nconst VOID_TAGS = new Set([\"area\", \"base\", \"br\", \"col\", \"embed\", \"hr\", \"img\", \"input\", \"link\", \"meta\", \"source\", \"track\", \"wbr\"]);\nconst RAW_TEXT_TAGS = new Set([\"script\", \"style\", \"textarea\", \"title\"]);\n\n/** Where the tag opened at `from` (`<`) ends, quotes respected; -1 when it never does. */\nfunction tagEnd(html: string, from: number): number {\n let quote = \"\";\n for (let i = from; i < html.length; i++) {\n const c = html[i]!;\n if (quote) {\n if (c === quote) quote = \"\";\n } else if (c === '\"' || c === \"'\") quote = c;\n else if (c === \">\") return i;\n }\n return -1;\n}\n\n/**\n * `<BcmsField>`'s child, when it is ONE element: the same markup with the binding attributes on\n * that element's own tag. Null when the rendered slot is anything else (text, several elements,\n * an element that already declares a field, a framework island), and the caller wraps as before.\n *\n * Why not always wrap: the wrapper is a `<span>` between the author's parent and the author's\n * element. `.hero > h1`, `gsap.utils.toArray(\".hero > *\")` and `:first-child` all stop matching,\n * and an animation that targeted the heading targets nothing. With the attributes on the element\n * itself the page's DOM is exactly the one the author wrote.\n *\n * A scan, not a parser: it only has to find where the first element ends. Anything it is not\n * sure of answers null, which is the old behaviour.\n */\nexport function stampSoleElement(html: string, attrs: Record<string, string | undefined>): string | null {\n const start = html.search(/\\S/);\n const open = /^<([a-zA-Z][\\w:-]*)/.exec(html.slice(start));\n if (start < 0 || !open) return null;\n const tag = open[1]!.toLowerCase();\n const openEnd = tagEnd(html, start);\n // A custom element is a framework's own wrapper (`astro-island`): not the author's element.\n if (openEnd < 0 || tag.includes(\"-\") || /\\sdata-bcms-(?:layout-)?field[\\s=>/]/.test(html.slice(start, openEnd + 1))) return null;\n let i = openEnd + 1;\n if (!VOID_TAGS.has(tag) && html[openEnd - 1] !== \"/\") {\n let depth = 1;\n let raw = RAW_TEXT_TAGS.has(tag) ? tag : \"\";\n while (depth > 0) {\n const lt = html.indexOf(\"<\", i);\n if (lt < 0) return null;\n if (raw) {\n const close = html.toLowerCase().indexOf(`</${raw}`, i);\n if (close < 0) return null;\n i = tagEnd(html, close) + 1;\n if (i === 0) return null;\n raw = \"\";\n depth--;\n continue;\n }\n if (html.startsWith(\"<!--\", lt)) {\n const end = html.indexOf(\"-->\", lt + 4);\n if (end < 0) return null;\n i = end + 3;\n continue;\n }\n const end = tagEnd(html, lt);\n if (end < 0) return null;\n const name = /^<\\/?([a-zA-Z][\\w:-]*)/.exec(html.slice(lt, end + 1))?.[1]?.toLowerCase();\n if (name && html[lt + 1] === \"/\") depth--;\n else if (name && !VOID_TAGS.has(name) && html[end - 1] !== \"/\") {\n depth++;\n if (RAW_TEXT_TAGS.has(name)) raw = name;\n }\n i = end + 1;\n }\n }\n if (html.slice(i).trim() !== \"\") return null;\n const escape = (value: string) => value.replace(/&/g, \"&\").replace(/\"/g, \""\");\n const added = Object.entries(attrs)\n .filter((entry): entry is [string, string] => entry[1] !== undefined)\n .map(([name, value]) => ` ${name}=\"${escape(value)}\"`)\n .join(\"\");\n // Last on the tag, where React's `cloneElement` puts them: the two lanes emit the same bytes.\n const selfClosed = html[openEnd - 1] === \"/\";\n const at = selfClosed ? openEnd - 1 : openEnd;\n return html.slice(0, at).replace(/\\s+$/, \"\") + added + (selfClosed ? \" \" : \"\") + html.slice(at);\n}\n"],"mappings":";AAaA,SAAS,4BAA4B;AAQ9B,SAAS,WAAW,IAAwB,MAAc,KAAgC;AAC/F,MAAI,CAAC,GAAI,QAAO;AAChB,QAAM,MAAM,GAAG,EAAE,KAAK,IAAI;AAC1B,MAAI,IAAI,eAAgB,QAAO,IAAI,eAAe,IAAI,GAAG,KAAK;AAC9D,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AAC,UAAkB,MAAM,QAAQ,MAAM,OAAO,EAAE,QAAQ,MAAM,QAAQ;AACrF,QAAM,QAAQ,OAAO,QAAQ,KAAK,EAC/B,OAAO,CAAC,UAAqC,MAAM,CAAC,MAAM,MAAS,EACnE,IAAI,CAAC,CAAC,MAAM,KAAK,MAAM,IAAI,IAAI,KAAK,OAAO,KAAK,CAAC,GAAG,EACpD,KAAK,EAAE;AAEV,QAAM,aAAa,KAAK,UAAU,CAAC,MAAM;AACzC,QAAM,KAAK,aAAa,UAAU,IAAI;AACtC,SAAO,KAAK,MAAM,GAAG,EAAE,EAAE,QAAQ,QAAQ,EAAE,IAAI,SAAS,aAAa,MAAM,MAAM,KAAK,MAAM,EAAE;AAChG;","names":["end"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { AstroIntegration } from 'astro';
|
|
2
2
|
export { BcmsLocals, BetterCMSRuntime, RuntimeConfig, liveSrc } from './runtime.js';
|
|
3
3
|
import { BlockStyle, FieldStyles, FieldStyle } from '@bettercms-ai/types';
|
|
4
|
-
export { ContentBlock, DeliveredLayout, DeliveryEntry, DeliveryList, DeliveryPage, PageMetaJson, Perspective, RESPONSIVE_CSS, SiteSeoDefaults } from '@bettercms-ai/types';
|
|
4
|
+
export { ContentBlock, DeliveredLayout, DeliveryEntry, DeliveryList, DeliveryPage, LinkValue, PageMetaJson, Perspective, RESPONSIVE_CSS, SiteSeoDefaults, linkHref } from '@bettercms-ai/types';
|
|
5
5
|
export { ImageCrop, ImageFit, ImageFocal, ImageFormat, ImageSource, ImageUrlBuilder, ImageValueUrlOptions, imageUrl, default as imageUrlBuilder, imageValueObjectPosition, imageValueUrl } from '@bettercms-ai/image-url';
|
|
6
6
|
export { DeliveryForm, DeliveryFormField, ResolvedSeo, SeoInput, resolveSeo } from '@bettercms-ai/sdk';
|
|
7
7
|
|
|
@@ -129,7 +129,8 @@ declare function sectionColumnAttrs(block: SectionRootBlock | null | undefined):
|
|
|
129
129
|
|
|
130
130
|
interface FieldAttrs {
|
|
131
131
|
"data-bcms-field": string;
|
|
132
|
-
"
|
|
132
|
+
/** The marker's revision: "2" promises `size` (zoom) too. Section roots keep "". */
|
|
133
|
+
"data-bcms-style": "2";
|
|
133
134
|
/** `fieldStyleToCss(fieldStyles[path])` as a CSS string; absent when the field has no style. */
|
|
134
135
|
style?: string;
|
|
135
136
|
}
|
package/dist/index.js
CHANGED
|
@@ -183,6 +183,7 @@ var enc = new TextEncoder();
|
|
|
183
183
|
|
|
184
184
|
// src/index.ts
|
|
185
185
|
import { RESPONSIVE_CSS } from "@bettercms-ai/types";
|
|
186
|
+
import { linkHref } from "@bettercms-ai/types";
|
|
186
187
|
|
|
187
188
|
// src/section-root.ts
|
|
188
189
|
import { blockStyleToColumnCss, blockStyleToCss, hideOnAttr } from "@bettercms-ai/types";
|
|
@@ -214,7 +215,7 @@ function fieldStyleOf(path, fieldStyles) {
|
|
|
214
215
|
}
|
|
215
216
|
function fieldAttrs(path, fieldStyles) {
|
|
216
217
|
const style = fieldStyleCssText(fieldStyleOf(path, fieldStyles));
|
|
217
|
-
return { "data-bcms-field": path, "data-bcms-style": "", ...style ? { style } : {} };
|
|
218
|
+
return { "data-bcms-field": path, "data-bcms-style": "2", ...style ? { style } : {} };
|
|
218
219
|
}
|
|
219
220
|
|
|
220
221
|
// src/index.ts
|
|
@@ -236,6 +237,7 @@ export {
|
|
|
236
237
|
default2 as imageUrlBuilder,
|
|
237
238
|
imageValueObjectPosition,
|
|
238
239
|
imageValueUrl,
|
|
240
|
+
linkHref,
|
|
239
241
|
liveSrc,
|
|
240
242
|
resolveConfig,
|
|
241
243
|
resolveSeo,
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/config.ts","../src/integration.ts","../src/runtime.ts","../src/index.ts","../src/section-root.ts","../src/field-attrs.ts"],"sourcesContent":["/**\n * Resolved configuration shared by the integration, runtime, middleware and\n * draft routes. Public values are safe to ship to the browser; the API key and\n * draft secret are read from server env at runtime and never live here.\n *\n * Resolution order is options → `PUBLIC_BCMS_*` env → the build snapshot. Config-time\n * only: this module is reached exclusively through `dist/index.js`, which only an\n * `astro.config.*` imports, so the `node:fs` read below never enters a client bundle.\n * Browser code gets the `bettercms:config` virtual module instead.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n/**\n * The platform's canonical media host, matching `@bettercms-ai/image-url`'s own\n * `DEFAULT_BASE_URL` and the `CDN_URL` the backend mints asset URLs on.\n *\n * This used to be `media.bettercms.ai`. Both hostnames route to the backend — they are both in\n * `$bcms_api_host` in infra/nginx/backend-lb.conf — so nothing was broken, but a site built by\n * this integration disagreed with the URL the server itself hands out for the same asset. That\n * splits the CDN cache for identical bytes and makes an asset URL's origin depend on which code\n * path produced it, which is the exact drift image-url was moved off this host to end.\n *\n * A project that serves media from the API origin instead (`useCdn: false`) overrides this with\n * `PUBLIC_BCMS_MEDIA_URL` or the `mediaUrl` option.\n */\nconst DEFAULT_MEDIA_URL = \"https://cdn.bettercms.ai\";\nconst SNAPSHOT_FILE = \"bcms-content.json\";\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nexport interface BetterCMSAstroOptions {\n /** Backend base, e.g. `https://api.bettercms.ai`. Falls back to `PUBLIC_BCMS_API_URL`. */\n apiUrl?: string;\n /** Workspace slug. Falls back to `PUBLIC_BCMS_WORKSPACE`. */\n workspace?: string;\n /** Optional project scope for forms. Falls back to `PUBLIC_BCMS_PROJECT_ID`. */\n projectId?: string;\n /** Media host for the image-url builder. Defaults to the prod media host. */\n mediaUrl?: string;\n /** Dashboard base for visual-editing deep links. */\n studioUrl?: string;\n /** Enable the draft-mode middleware + injected draft routes. Default true. */\n draft?: boolean;\n}\n\n/** Browser-safe config — exposed via the `bettercms:config` virtual module. */\nexport interface PublicConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n mediaUrl: string;\n studioUrl?: string;\n draftCookie: string;\n}\n\nexport interface ResolvedConfig extends PublicConfig {\n draft: boolean;\n}\n\n/** The fields of the deploy Action's content snapshot that identify the site. */\ninterface Snapshot {\n apiUrl?: string;\n workspace?: string;\n projectId?: string;\n}\n\n/**\n * Read `bcms-content.json` — the snapshot the deploy Action writes next to the build,\n * BEFORE `astro build` runs — which already carries the workspace this site belongs to.\n *\n * This is what lets `bettercms()` work with no arguments and no env at all. Not reading it\n * was the whole bug: a hosted build had the answer sitting in its own working directory and\n * threw anyway, and every starter template had to reimplement this by hand to survive.\n *\n * Lazy: only consulted when options and env both miss, so the configured path does no I/O.\n * Absent/corrupt file ⇒ `{}`, and the caller raises the actionable error below.\n */\nlet snapshotCache: Snapshot | undefined;\nfunction snapshot(cwd: string): Snapshot {\n if (snapshotCache === undefined) {\n try {\n snapshotCache = JSON.parse(readFileSync(resolve(cwd, SNAPSHOT_FILE), \"utf8\")) as Snapshot;\n } catch {\n snapshotCache = {};\n }\n }\n return snapshotCache;\n}\n\n/** Test seam — the snapshot is memoised for the life of the process. */\nexport function resetSnapshotCache(): void {\n snapshotCache = undefined;\n}\n\nconst required = (name: string, envVar: string, extra: string) =>\n new Error(\n `[@bettercms-ai/astro] \\`${name}\\` is required. Pass \\`bettercms({ ${name} })\\`, set ` +\n `${envVar}, or ${extra}\\n` +\n `On BetterCMS hosting these are injected automatically — if this failed in a hosted ` +\n `build, the repository is running an outdated deploy workflow: publish once, or save ` +\n `Hosting settings, to refresh it.`,\n );\n\n/**\n * Merge integration options with `PUBLIC_BCMS_*` env and the build snapshot, validating the\n * essentials. Precedence: explicit options → env → snapshot.\n */\nexport function resolveConfig(\n options: BetterCMSAstroOptions,\n env: Record<string, string | undefined> = process.env,\n cwd: string = process.cwd(),\n): ResolvedConfig {\n const snap = (): Snapshot => snapshot(cwd);\n\n const apiUrl = (options.apiUrl ?? env.PUBLIC_BCMS_API_URL ?? snap().apiUrl ?? \"\").replace(/\\/+$/, \"\");\n const workspace = options.workspace ?? env.PUBLIC_BCMS_WORKSPACE ?? snap().workspace ?? \"\";\n // No default origin on purpose: guessing one produces a site that builds cleanly against\n // the wrong backend, which is far harder to notice than this error.\n if (!apiUrl) throw required(\"apiUrl\", \"PUBLIC_BCMS_API_URL\", `run the content fetch so ${SNAPSHOT_FILE} is present.`);\n if (!workspace) {\n throw required(\"workspace\", \"PUBLIC_BCMS_WORKSPACE\", `run the content fetch so ${SNAPSHOT_FILE} is present.`);\n }\n\n return {\n apiUrl,\n workspace,\n projectId: options.projectId ?? env.PUBLIC_BCMS_PROJECT_ID ?? snap().projectId,\n mediaUrl: (options.mediaUrl ?? env.PUBLIC_BCMS_MEDIA_URL ?? DEFAULT_MEDIA_URL).replace(/\\/+$/, \"\"),\n studioUrl: options.studioUrl ?? env.PUBLIC_BCMS_STUDIO_URL,\n draftCookie: DRAFT_COOKIE,\n draft: options.draft ?? true,\n };\n}\n\nexport function toPublicConfig(c: ResolvedConfig): PublicConfig {\n const { draft: _draft, ...pub } = c;\n return pub;\n}\n","/**\n * `bettercms()` — the Astro integration.\n *\n * - Registers two virtual modules:\n * `bettercms:client` → server runtime (client + typed loaders) — has the key.\n * `bettercms:config` → browser-safe public config — no secrets.\n * - Adds the draft-mode middleware and injects the draft enable/disable routes.\n */\nimport type { AstroIntegration } from \"astro\";\nimport {\n resolveConfig,\n toPublicConfig,\n type BetterCMSAstroOptions,\n type ResolvedConfig,\n} from \"./config.js\";\n\nconst CLIENT_ID = \"bettercms:client\";\nconst CONFIG_ID = \"bettercms:config\";\nconst RESOLVED = (id: string) => `\\0${id}`;\n\nfunction configModule(cfg: ResolvedConfig): string {\n return `export const config = ${JSON.stringify(toPublicConfig(cfg))};\\nexport default config;\\n`;\n}\n\nfunction clientModule(cfg: ResolvedConfig, buildCache: boolean): string {\n // The key is optional: published reads are addressed by the inlined projectId. When one is\n // set it is read from the server's env at run time (a server-output site gets it from its\n // host, not the build), falling back to the build's env; it never lands in a client bundle.\n return [\n `import { createRuntime } from \"@bettercms-ai/astro/runtime\";`,\n `const runtime = createRuntime({`,\n ` apiUrl: ${JSON.stringify(cfg.apiUrl)},`,\n ` workspace: ${JSON.stringify(cfg.workspace)},`,\n ` projectId: ${JSON.stringify(cfg.projectId)},`,\n ` apiKey: globalThis.process?.env?.BCMS_API_KEY ?? import.meta.env.BCMS_API_KEY,`,\n ` buildCache: ${JSON.stringify(buildCache)},`,\n `});`,\n `export const client = runtime.client;`,\n `export const getClient = runtime.getClient;`,\n `export const loadEntry = runtime.loadEntry;`,\n `export const loadEntries = runtime.loadEntries;`,\n `export const loadPage = runtime.loadPage;`,\n `export const loadComponents = runtime.loadComponents;`,\n `export const loadForms = runtime.loadForms;`,\n `export const loadLayout = runtime.loadLayout;`,\n `export default runtime;`,\n ].join(\"\\n\");\n}\n\nfunction virtualPlugin(cfg: ResolvedConfig, buildCache: () => boolean) {\n return {\n name: \"@bettercms-ai/astro:virtual\",\n resolveId(id: string) {\n if (id === CLIENT_ID || id === CONFIG_ID) return RESOLVED(id);\n return null;\n },\n load(id: string) {\n if (id === RESOLVED(CONFIG_ID)) return configModule(cfg);\n if (id === RESOLVED(CLIENT_ID)) return clientModule(cfg, buildCache());\n return null;\n },\n };\n}\n\nexport function bettercms(options: BetterCMSAstroOptions = {}): AstroIntegration {\n /**\n * Whether identical delivery GETs may be collapsed for the life of the process.\n *\n * Read lazily by the virtual module (see `astro:config:done` below) because only the\n * FINAL config settles `output` and `adapter` — another integration can add an adapter\n * after `astro:config:setup` runs.\n */\n const buildCache = { on: false, command: \"\", resolved: false };\n /** Set in `astro:config:done`, re-run in `astro:build:start` — see both hooks below. */\n let decide: (() => void) | undefined;\n\n return {\n name: \"@bettercms-ai/astro\",\n hooks: {\n \"astro:config:setup\": ({ command, updateConfig, addMiddleware, injectRoute, logger }) => {\n const cfg = resolveConfig(options);\n buildCache.command = command;\n\n updateConfig({ vite: { plugins: [virtualPlugin(cfg, () => buildCache.on)] } });\n\n if (cfg.draft) {\n addMiddleware({ entrypoint: \"@bettercms-ai/astro/middleware\", order: \"pre\" });\n injectRoute({\n pattern: \"/api/bcms/draft/enable\",\n entrypoint: \"@bettercms-ai/astro/draft-enable\",\n prerender: false,\n });\n injectRoute({\n pattern: \"/api/bcms/draft/disable\",\n entrypoint: \"@bettercms-ai/astro/draft-disable\",\n prerender: false,\n });\n logger.info(\"draft mode enabled — /api/bcms/draft/{enable,disable} injected\");\n }\n },\n\n /**\n * Decide whether the build-time request cache is safe, on the FINAL config.\n *\n * A fully static build renders every route from one published dataset, so identical\n * delivery GETs can collapse to a single round-trip. Without that a large site\n * re-fetched its nav/settings/collections once PER ROUTE and exhausted the delivery\n * rate limit mid-build — a 429 the build could not avoid.\n *\n * `command === \"build\"` is NOT sufficient to detect that, and getting this wrong is\n * far worse than the problem it solves: Astro also reports `command === \"build\"` when\n * it compiles `output: \"server\"`, whose bundle then runs as a LONG-LIVED process. A\n * module-lifetime cache there would pin the first response for every URL and serve it\n * to unrelated visitors until the process restarted — permanent stale content on a\n * production site.\n *\n * `buildOutput` (Astro 5) is Astro's OWN answer to \"will this emit a server?\", so it\n * is what we trust when present. Inferring it from `config.adapter` is not equivalent:\n * `setAdapter()` is documented as being called from inside `astro:config:done`, so an\n * adapter integration whose hook runs after this one would still read as absent here.\n *\n * On Astro 4 there is no `buildOutput`, and there `output: \"static\"` genuinely\n * prerenders everything — on-demand rendering required `\"server\"` or `\"hybrid\"`, both\n * of which fail this check. The adapter test stays as a second line of defence.\n */\n \"astro:config:done\": ({ config, logger, ...rest }) => {\n // Astro >= 5 only; undefined on 4, hence the fallback rather than a bare read.\n const buildOutput = (rest as { buildOutput?: \"static\" | \"server\" }).buildOutput;\n const staticOutput =\n buildOutput !== undefined\n ? buildOutput === \"static\"\n : config.output === \"static\" && !config.adapter;\n\n buildCache.on = buildCache.command === \"build\" && staticOutput;\n // Re-checked in astro:build:start below; only announce once it is final.\n decide = () => {\n const late = (rest as { buildOutput?: \"static\" | \"server\" }).buildOutput;\n const stillStatic =\n late !== undefined ? late === \"static\" : config.output === \"static\" && !config.adapter;\n buildCache.on = buildCache.command === \"build\" && stillStatic;\n buildCache.resolved = true;\n if (buildCache.on) {\n logger.info(\"static build — identical content reads will be fetched once\");\n }\n };\n },\n\n /**\n * Last word on the cache, and the reason this is not decided in `astro:config:done`\n * alone: Astro runs every integration's `config:done` in order, and `setAdapter()` is\n * called FROM that hook. An adapter registered by an integration ordered after this one\n * would flip the project to on-demand rendering *after* we had already recorded\n * \"static\" — and the stale `true` would ship a module-lifetime cache into a\n * long-lived server. `astro:build:start` runs after all of them and before Vite loads\n * the virtual module, so re-reading here is the value that is actually true.\n *\n * It never fires for `dev` or `preview`, which is exactly right: both must stay\n * uncached, and `buildCache.on` is only ever set to true under `command === \"build\"`.\n */\n \"astro:build:start\": () => {\n decide?.();\n },\n },\n };\n}\n\nexport default bettercms;\n","/**\n * Runtime for @bettercms-ai/astro — the code the `bettercms:client` virtual\n * module binds to. Provides a published client, per-request draft client\n * selection, typed loaders, and signed-cookie helpers for draft mode.\n *\n * Read-only; no I/O at import time. Safe in Node and edge runtimes (uses Web\n * Crypto + global fetch only).\n */\nimport { createClient, type BetterCMSReadClient } from \"@bettercms-ai/sdk\";\nimport type {\n DeliveredLayout,\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n} from \"@bettercms-ai/types\";\n\nexport interface RuntimeConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n /** Server-only delivery key (a `content:read:draft` key for drafts). */\n apiKey?: string;\n /**\n * Collapse identical delivery GETs for the life of the process. Set by the integration\n * when Astro's `command === \"build\"` — a static build renders every route from one\n * published dataset, so a repeat read cannot legitimately differ.\n *\n * Never set for `dev` or SSR, where each request must see current content.\n */\n buildCache?: boolean;\n}\n\n/** Per-request draft state, set on `Astro.locals.bcms` by the middleware. */\nexport interface BcmsLocals {\n draft: boolean;\n token?: string;\n}\n\ninterface HasLocals {\n locals: { bcms?: BcmsLocals };\n}\n\nexport interface BetterCMSRuntime {\n /** Published-perspective client (use for SSG / non-draft reads). */\n client: BetterCMSReadClient;\n /** Pick the right client for a request (draft client when draft mode is on). */\n getClient(astro?: HasLocals): BetterCMSReadClient;\n loadEntry<T = Record<string, unknown>>(\n astro: HasLocals,\n slug: string,\n opts?: Parameters<BetterCMSReadClient[\"getEntry\"]>[1],\n ): Promise<DeliveryEntry<T>>;\n loadEntries<T = Record<string, unknown>>(\n astro: HasLocals,\n opts?: Parameters<BetterCMSReadClient[\"listEntries\"]>[0],\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n loadPage(astro: HasLocals, slug: string): Promise<DeliveryPage | null>;\n /** Component definitions for `<BcmsBlocks components={…}>` — draft-side in draft mode. */\n loadComponents(astro: HasLocals): Promise<DeliveryComponent[]>;\n loadLayout(astro: HasLocals): Promise<DeliveredLayout | null>;\n loadForms(\n astro: HasLocals,\n opts?: Parameters<BetterCMSReadClient[\"listForms\"]>[0],\n ): Promise<Awaited<ReturnType<BetterCMSReadClient[\"listForms\"]>>>;\n}\n\nexport function createRuntime(config: RuntimeConfig): BetterCMSRuntime {\n const { buildCache, ...clientConfig } = config;\n // One client for the whole build, so the cache below is shared across every route\n // rather than rebuilt per render.\n const published = createClient({ ...clientConfig, perspective: \"published\", cache: buildCache });\n\n const getClient = (astro?: HasLocals): BetterCMSReadClient => {\n const bcms = astro?.locals?.bcms;\n if (bcms?.draft) {\n // Explicitly uncached: a draft read exists to show the edit that just happened.\n return createClient({\n ...clientConfig,\n perspective: \"drafts\",\n previewToken: bcms.token,\n cache: false,\n });\n }\n return published;\n };\n\n return {\n client: published,\n getClient,\n loadEntry: (astro, slug, opts) => getClient(astro).getEntry(slug, opts),\n loadEntries: (astro, opts) => getClient(astro).listEntries(opts),\n loadPage: (astro, slug) => getClient(astro).getPage(slug),\n loadComponents: (astro) => getClient(astro).listComponents(),\n loadLayout: (astro) => getClient(astro).getLayout(),\n loadForms: (astro, opts) => getClient(astro).listForms(opts),\n };\n}\n\n/**\n * Build the live SSE URL for `<BcmsLive>`. The key is a query param because\n * browser EventSource cannot send headers — use a content:read key.\n *\n * `depth` sets the hydration depth of the document the stream pushes (default 1,\n * matching the delivery API). `drafts` streams autosaves so a preview surface\n * repaints as the editor types — it needs a `content:read:draft` key, and the\n * server ignores the flag for any other key rather than failing the connection.\n * Never enable it on a public site.\n */\nexport function liveSrc(opts: {\n apiUrl: string;\n workspace: string;\n apiKey: string;\n depth?: 0 | 1 | 2;\n drafts?: boolean;\n}): string {\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\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 `${base}/api/v1/delivery/${opts.workspace}/live?${q}`;\n}\n\n/**\n * The published content snapshot, read at request time on a server BetterCMS hosts (it rewrites the\n * file on every publish) and from `bcms-content.json` at build time. Read content through this —\n * never `import` bcms-content.json or `import.meta.glob` it: a bundled copy is frozen at build, and\n * the platform has to rebuild the whole site for every publish to change it.\n */\nexport { readPublishedContent, publishedEntry, type PublishedContent } from \"@bettercms-ai/sdk\";\n\n// ── Signed-cookie helpers (HMAC-SHA256, base64url) ──────────────────────────\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(\n \"raw\",\n enc.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\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. */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** Verify a signed value, returning the original value or null if tampered. */\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 // Constant-time-ish compare via length + char accumulation.\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/**\n * The draft-cookie signing secret, `process.env` FIRST.\n *\n * Vite may INLINE `import.meta.env.BCMS_DRAFT_SECRET` at build time, and the value present\n * when the customer's site is built is not the value the hosting container is given at start\n * — BetterCMS derives it per project and injects it as a real env var. Reading the runtime\n * env first is what makes managed hosting work without asking anyone to rebuild. The\n * `import.meta.env` read stays as the fallback for `astro dev` and for adapters with no\n * `process` (guarded, since touching `import.meta.env` outside Vite throws).\n */\nexport function draftSecret(): string | undefined {\n const fromProcess =\n typeof process !== \"undefined\" ? (process.env?.BCMS_DRAFT_SECRET as string | undefined) : undefined;\n if (fromProcess) return fromProcess;\n try {\n return import.meta.env?.BCMS_DRAFT_SECRET as string | undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Only same-origin relative paths. Blocks \"//evil.com\", \"https://evil.com\", etc. */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") ? to : \"/\";\n}\n\n/** Decode a preview-token JWT payload (UNVERIFIED) to read its `entrySlug`. */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = JSON.parse(\n atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")),\n ) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n","/**\n * @bettercms-ai/astro — the BetterCMS adapter for Astro.\n *\n * import { defineConfig } from \"astro/config\";\n * import bettercms from \"@bettercms-ai/astro\";\n *\n * export default defineConfig({\n * integrations: [bettercms({ apiUrl, workspace })],\n * output: \"server\",\n * });\n *\n * Then in any page: `import { loadPage } from \"bettercms:client\"`.\n */\nexport { bettercms, default } from \"./integration.js\";\nexport {\n resolveConfig,\n DRAFT_COOKIE,\n type BetterCMSAstroOptions,\n type PublicConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nexport { liveSrc } from \"./runtime.js\";\n// C3/C4: a site's own section root declares that it paints block.style.\nexport { RESPONSIVE_CSS } from \"@bettercms-ai/types\";\nexport { sectionRootAttrs, type SectionRootAttrs, type SectionRootBlock } from \"./section-root.js\";\nexport { fieldAttrs, fieldStyleOf, type FieldAttrs } from \"./field-attrs.js\";\nexport { sectionColumnAttrs, type SectionColumnAttrs } from \"./section-root.js\";\nexport type { BcmsLocals, BetterCMSRuntime, RuntimeConfig } from \"./runtime.js\";\n\n// Image URL builder, re-exported for `<BcmsImage>` and host code.\nexport {\n default as imageUrlBuilder,\n imageUrl,\n imageValueUrl,\n imageValueObjectPosition,\n} from \"@bettercms-ai/image-url\";\nexport type {\n ImageUrlBuilder,\n ImageSource,\n ImageFormat,\n ImageFit,\n ImageCrop,\n ImageFocal,\n ImageValueUrlOptions,\n} from \"@bettercms-ai/image-url\";\n\n// Delivery read types, re-exported for typing page/entry data.\nexport type {\n Perspective,\n DeliveryEntry,\n DeliveryPage,\n DeliveryList,\n PageMetaJson,\n SiteSeoDefaults,\n ContentBlock,\n DeliveredLayout,\n} from \"@bettercms-ai/types\";\nexport type { DeliveryForm, DeliveryFormField } from \"@bettercms-ai/sdk\";\n\n// SEO (FLO-302): page-over-site meta resolver. In a page's frontmatter,\n// `const seo = resolveSeo(page, siteDefaults)`, then map `seo.*` into `<head>`.\nexport { resolveSeo } from \"@bettercms-ai/sdk\";\nexport type { SeoInput, ResolvedSeo } from \"@bettercms-ai/sdk\";\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 */\nimport { blockStyleToColumnCss, blockStyleToCss, hideOnAttr, type BlockStyle } from \"@bettercms-ai/types\";\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 * 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 * Twin: `fieldAttrs` in @bettercms-ai/next (a React style object there).\n */\nimport { fieldStyleCssText, type FieldStyle, type FieldStyles } from \"@bettercms-ai/types\";\n\nexport interface FieldAttrs {\n \"data-bcms-field\": string;\n \"data-bcms-style\": \"\";\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\": \"\", ...(style ? { style } : {}) };\n}\n"],"mappings":";AAWA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AAexB,IAAM,oBAAoB;AAC1B,IAAM,gBAAgB;AACf,IAAM,eAAe;AAiD5B,IAAI;AACJ,SAAS,SAAS,KAAuB;AACvC,MAAI,kBAAkB,QAAW;AAC/B,QAAI;AACF,sBAAgB,KAAK,MAAM,aAAa,QAAQ,KAAK,aAAa,GAAG,MAAM,CAAC;AAAA,IAC9E,QAAQ;AACN,sBAAgB,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AACT;AAOA,IAAM,WAAW,CAAC,MAAc,QAAgB,UAC9C,IAAI;AAAA,EACF,2BAA2B,IAAI,sCAAsC,IAAI,cACpE,MAAM,QAAQ,KAAK;AAAA;AAI1B;AAMK,SAAS,cACd,SACA,MAA0C,QAAQ,KAClD,MAAc,QAAQ,IAAI,GACV;AAChB,QAAM,OAAO,MAAgB,SAAS,GAAG;AAEzC,QAAM,UAAU,QAAQ,UAAU,IAAI,uBAAuB,KAAK,EAAE,UAAU,IAAI,QAAQ,QAAQ,EAAE;AACpG,QAAM,YAAY,QAAQ,aAAa,IAAI,yBAAyB,KAAK,EAAE,aAAa;AAGxF,MAAI,CAAC,OAAQ,OAAM,SAAS,UAAU,uBAAuB,4BAA4B,aAAa,cAAc;AACpH,MAAI,CAAC,WAAW;AACd,UAAM,SAAS,aAAa,yBAAyB,4BAA4B,aAAa,cAAc;AAAA,EAC9G;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,W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AI,OAAO,EAAE,kBAAkB,KAAK,IAAI,CAAC;AAAA,IACzC,GAAI,MAAM,EAAE,OAAO,QAAQ,GAAG,EAAE,IAAI,CAAC;AAAA,EACvC;AACF;AAsBO,SAAS,mBAAmB,OAAgE;AACjG,QAAM,MAAM,sBAAuB,OAAO,SAAS,MAAoC;AACvF,SAAO,EAAE,oBAAoB,IAAI,GAAI,MAAM,EAAE,OAAO,QAAQ,GAAG,EAAE,IAAI,CAAC,EAAG;AAC3E;;;ACxDA,SAAS,yBAA4D;AAU9D,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,kBAAkB,aAAa,MAAM,WAAW,CAAC;AAC/D,SAAO,EAAE,mBAAmB,MAAM,mBAAmB,IAAI,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG;AACvF;;;AFNA;AAAA,EACa,WAAXA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA0BP,SAAS,kBAAkB;","names":["default"]}
|
|
1
|
+
{"version":3,"sources":["../src/config.ts","../src/integration.ts","../src/runtime.ts","../src/index.ts","../src/section-root.ts","../src/field-attrs.ts"],"sourcesContent":["/**\n * Resolved configuration shared by the integration, runtime, middleware and\n * draft routes. Public values are safe to ship to the browser; the API key and\n * draft secret are read from server env at runtime and never live here.\n *\n * Resolution order is options → `PUBLIC_BCMS_*` env → the build snapshot. Config-time\n * only: this module is reached exclusively through `dist/index.js`, which only an\n * `astro.config.*` imports, so the `node:fs` read below never enters a client bundle.\n * Browser code gets the `bettercms:config` virtual module instead.\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\n\n/**\n * The platform's canonical media host, matching `@bettercms-ai/image-url`'s own\n * `DEFAULT_BASE_URL` and the `CDN_URL` the backend mints asset URLs on.\n *\n * This used to be `media.bettercms.ai`. Both hostnames route to the backend — they are both in\n * `$bcms_api_host` in infra/nginx/backend-lb.conf — so nothing was broken, but a site built by\n * this integration disagreed with the URL the server itself hands out for the same asset. That\n * splits the CDN cache for identical bytes and makes an asset URL's origin depend on which code\n * path produced it, which is the exact drift image-url was moved off this host to end.\n *\n * A project that serves media from the API origin instead (`useCdn: false`) overrides this with\n * `PUBLIC_BCMS_MEDIA_URL` or the `mediaUrl` option.\n */\nconst DEFAULT_MEDIA_URL = \"https://cdn.bettercms.ai\";\nconst SNAPSHOT_FILE = \"bcms-content.json\";\nexport const DRAFT_COOKIE = \"bcms-draft\";\n\nexport interface BetterCMSAstroOptions {\n /** Backend base, e.g. `https://api.bettercms.ai`. Falls back to `PUBLIC_BCMS_API_URL`. */\n apiUrl?: string;\n /** Workspace slug. Falls back to `PUBLIC_BCMS_WORKSPACE`. */\n workspace?: string;\n /** Optional project scope for forms. Falls back to `PUBLIC_BCMS_PROJECT_ID`. */\n projectId?: string;\n /** Media host for the image-url builder. Defaults to the prod media host. */\n mediaUrl?: string;\n /** Dashboard base for visual-editing deep links. */\n studioUrl?: string;\n /** Enable the draft-mode middleware + injected draft routes. Default true. */\n draft?: boolean;\n}\n\n/** Browser-safe config — exposed via the `bettercms:config` virtual module. */\nexport interface PublicConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n mediaUrl: string;\n studioUrl?: string;\n draftCookie: string;\n}\n\nexport interface ResolvedConfig extends PublicConfig {\n draft: boolean;\n}\n\n/** The fields of the deploy Action's content snapshot that identify the site. */\ninterface Snapshot {\n apiUrl?: string;\n workspace?: string;\n projectId?: string;\n}\n\n/**\n * Read `bcms-content.json` — the snapshot the deploy Action writes next to the build,\n * BEFORE `astro build` runs — which already carries the workspace this site belongs to.\n *\n * This is what lets `bettercms()` work with no arguments and no env at all. Not reading it\n * was the whole bug: a hosted build had the answer sitting in its own working directory and\n * threw anyway, and every starter template had to reimplement this by hand to survive.\n *\n * Lazy: only consulted when options and env both miss, so the configured path does no I/O.\n * Absent/corrupt file ⇒ `{}`, and the caller raises the actionable error below.\n */\nlet snapshotCache: Snapshot | undefined;\nfunction snapshot(cwd: string): Snapshot {\n if (snapshotCache === undefined) {\n try {\n snapshotCache = JSON.parse(readFileSync(resolve(cwd, SNAPSHOT_FILE), \"utf8\")) as Snapshot;\n } catch {\n snapshotCache = {};\n }\n }\n return snapshotCache;\n}\n\n/** Test seam — the snapshot is memoised for the life of the process. */\nexport function resetSnapshotCache(): void {\n snapshotCache = undefined;\n}\n\nconst required = (name: string, envVar: string, extra: string) =>\n new Error(\n `[@bettercms-ai/astro] \\`${name}\\` is required. Pass \\`bettercms({ ${name} })\\`, set ` +\n `${envVar}, or ${extra}\\n` +\n `On BetterCMS hosting these are injected automatically — if this failed in a hosted ` +\n `build, the repository is running an outdated deploy workflow: publish once, or save ` +\n `Hosting settings, to refresh it.`,\n );\n\n/**\n * Merge integration options with `PUBLIC_BCMS_*` env and the build snapshot, validating the\n * essentials. Precedence: explicit options → env → snapshot.\n */\nexport function resolveConfig(\n options: BetterCMSAstroOptions,\n env: Record<string, string | undefined> = process.env,\n cwd: string = process.cwd(),\n): ResolvedConfig {\n const snap = (): Snapshot => snapshot(cwd);\n\n const apiUrl = (options.apiUrl ?? env.PUBLIC_BCMS_API_URL ?? snap().apiUrl ?? \"\").replace(/\\/+$/, \"\");\n const workspace = options.workspace ?? env.PUBLIC_BCMS_WORKSPACE ?? snap().workspace ?? \"\";\n // No default origin on purpose: guessing one produces a site that builds cleanly against\n // the wrong backend, which is far harder to notice than this error.\n if (!apiUrl) throw required(\"apiUrl\", \"PUBLIC_BCMS_API_URL\", `run the content fetch so ${SNAPSHOT_FILE} is present.`);\n if (!workspace) {\n throw required(\"workspace\", \"PUBLIC_BCMS_WORKSPACE\", `run the content fetch so ${SNAPSHOT_FILE} is present.`);\n }\n\n return {\n apiUrl,\n workspace,\n projectId: options.projectId ?? env.PUBLIC_BCMS_PROJECT_ID ?? snap().projectId,\n mediaUrl: (options.mediaUrl ?? env.PUBLIC_BCMS_MEDIA_URL ?? DEFAULT_MEDIA_URL).replace(/\\/+$/, \"\"),\n studioUrl: options.studioUrl ?? env.PUBLIC_BCMS_STUDIO_URL,\n draftCookie: DRAFT_COOKIE,\n draft: options.draft ?? true,\n };\n}\n\nexport function toPublicConfig(c: ResolvedConfig): PublicConfig {\n const { draft: _draft, ...pub } = c;\n return pub;\n}\n","/**\n * `bettercms()` — the Astro integration.\n *\n * - Registers two virtual modules:\n * `bettercms:client` → server runtime (client + typed loaders) — has the key.\n * `bettercms:config` → browser-safe public config — no secrets.\n * - Adds the draft-mode middleware and injects the draft enable/disable routes.\n */\nimport type { AstroIntegration } from \"astro\";\nimport {\n resolveConfig,\n toPublicConfig,\n type BetterCMSAstroOptions,\n type ResolvedConfig,\n} from \"./config.js\";\n\nconst CLIENT_ID = \"bettercms:client\";\nconst CONFIG_ID = \"bettercms:config\";\nconst RESOLVED = (id: string) => `\\0${id}`;\n\nfunction configModule(cfg: ResolvedConfig): string {\n return `export const config = ${JSON.stringify(toPublicConfig(cfg))};\\nexport default config;\\n`;\n}\n\nfunction clientModule(cfg: ResolvedConfig, buildCache: boolean): string {\n // The key is optional: published reads are addressed by the inlined projectId. When one is\n // set it is read from the server's env at run time (a server-output site gets it from its\n // host, not the build), falling back to the build's env; it never lands in a client bundle.\n return [\n `import { createRuntime } from \"@bettercms-ai/astro/runtime\";`,\n `const runtime = createRuntime({`,\n ` apiUrl: ${JSON.stringify(cfg.apiUrl)},`,\n ` workspace: ${JSON.stringify(cfg.workspace)},`,\n ` projectId: ${JSON.stringify(cfg.projectId)},`,\n ` apiKey: globalThis.process?.env?.BCMS_API_KEY ?? import.meta.env.BCMS_API_KEY,`,\n ` buildCache: ${JSON.stringify(buildCache)},`,\n `});`,\n `export const client = runtime.client;`,\n `export const getClient = runtime.getClient;`,\n `export const loadEntry = runtime.loadEntry;`,\n `export const loadEntries = runtime.loadEntries;`,\n `export const loadPage = runtime.loadPage;`,\n `export const loadComponents = runtime.loadComponents;`,\n `export const loadForms = runtime.loadForms;`,\n `export const loadLayout = runtime.loadLayout;`,\n `export default runtime;`,\n ].join(\"\\n\");\n}\n\nfunction virtualPlugin(cfg: ResolvedConfig, buildCache: () => boolean) {\n return {\n name: \"@bettercms-ai/astro:virtual\",\n resolveId(id: string) {\n if (id === CLIENT_ID || id === CONFIG_ID) return RESOLVED(id);\n return null;\n },\n load(id: string) {\n if (id === RESOLVED(CONFIG_ID)) return configModule(cfg);\n if (id === RESOLVED(CLIENT_ID)) return clientModule(cfg, buildCache());\n return null;\n },\n };\n}\n\nexport function bettercms(options: BetterCMSAstroOptions = {}): AstroIntegration {\n /**\n * Whether identical delivery GETs may be collapsed for the life of the process.\n *\n * Read lazily by the virtual module (see `astro:config:done` below) because only the\n * FINAL config settles `output` and `adapter` — another integration can add an adapter\n * after `astro:config:setup` runs.\n */\n const buildCache = { on: false, command: \"\", resolved: false };\n /** Set in `astro:config:done`, re-run in `astro:build:start` — see both hooks below. */\n let decide: (() => void) | undefined;\n\n return {\n name: \"@bettercms-ai/astro\",\n hooks: {\n \"astro:config:setup\": ({ command, updateConfig, addMiddleware, injectRoute, logger }) => {\n const cfg = resolveConfig(options);\n buildCache.command = command;\n\n updateConfig({ vite: { plugins: [virtualPlugin(cfg, () => buildCache.on)] } });\n\n if (cfg.draft) {\n addMiddleware({ entrypoint: \"@bettercms-ai/astro/middleware\", order: \"pre\" });\n injectRoute({\n pattern: \"/api/bcms/draft/enable\",\n entrypoint: \"@bettercms-ai/astro/draft-enable\",\n prerender: false,\n });\n injectRoute({\n pattern: \"/api/bcms/draft/disable\",\n entrypoint: \"@bettercms-ai/astro/draft-disable\",\n prerender: false,\n });\n logger.info(\"draft mode enabled — /api/bcms/draft/{enable,disable} injected\");\n }\n },\n\n /**\n * Decide whether the build-time request cache is safe, on the FINAL config.\n *\n * A fully static build renders every route from one published dataset, so identical\n * delivery GETs can collapse to a single round-trip. Without that a large site\n * re-fetched its nav/settings/collections once PER ROUTE and exhausted the delivery\n * rate limit mid-build — a 429 the build could not avoid.\n *\n * `command === \"build\"` is NOT sufficient to detect that, and getting this wrong is\n * far worse than the problem it solves: Astro also reports `command === \"build\"` when\n * it compiles `output: \"server\"`, whose bundle then runs as a LONG-LIVED process. A\n * module-lifetime cache there would pin the first response for every URL and serve it\n * to unrelated visitors until the process restarted — permanent stale content on a\n * production site.\n *\n * `buildOutput` (Astro 5) is Astro's OWN answer to \"will this emit a server?\", so it\n * is what we trust when present. Inferring it from `config.adapter` is not equivalent:\n * `setAdapter()` is documented as being called from inside `astro:config:done`, so an\n * adapter integration whose hook runs after this one would still read as absent here.\n *\n * On Astro 4 there is no `buildOutput`, and there `output: \"static\"` genuinely\n * prerenders everything — on-demand rendering required `\"server\"` or `\"hybrid\"`, both\n * of which fail this check. The adapter test stays as a second line of defence.\n */\n \"astro:config:done\": ({ config, logger, ...rest }) => {\n // Astro >= 5 only; undefined on 4, hence the fallback rather than a bare read.\n const buildOutput = (rest as { buildOutput?: \"static\" | \"server\" }).buildOutput;\n const staticOutput =\n buildOutput !== undefined\n ? buildOutput === \"static\"\n : config.output === \"static\" && !config.adapter;\n\n buildCache.on = buildCache.command === \"build\" && staticOutput;\n // Re-checked in astro:build:start below; only announce once it is final.\n decide = () => {\n const late = (rest as { buildOutput?: \"static\" | \"server\" }).buildOutput;\n const stillStatic =\n late !== undefined ? late === \"static\" : config.output === \"static\" && !config.adapter;\n buildCache.on = buildCache.command === \"build\" && stillStatic;\n buildCache.resolved = true;\n if (buildCache.on) {\n logger.info(\"static build — identical content reads will be fetched once\");\n }\n };\n },\n\n /**\n * Last word on the cache, and the reason this is not decided in `astro:config:done`\n * alone: Astro runs every integration's `config:done` in order, and `setAdapter()` is\n * called FROM that hook. An adapter registered by an integration ordered after this one\n * would flip the project to on-demand rendering *after* we had already recorded\n * \"static\" — and the stale `true` would ship a module-lifetime cache into a\n * long-lived server. `astro:build:start` runs after all of them and before Vite loads\n * the virtual module, so re-reading here is the value that is actually true.\n *\n * It never fires for `dev` or `preview`, which is exactly right: both must stay\n * uncached, and `buildCache.on` is only ever set to true under `command === \"build\"`.\n */\n \"astro:build:start\": () => {\n decide?.();\n },\n },\n };\n}\n\nexport default bettercms;\n","/**\n * Runtime for @bettercms-ai/astro — the code the `bettercms:client` virtual\n * module binds to. Provides a published client, per-request draft client\n * selection, typed loaders, and signed-cookie helpers for draft mode.\n *\n * Read-only; no I/O at import time. Safe in Node and edge runtimes (uses Web\n * Crypto + global fetch only).\n */\nimport { createClient, type BetterCMSReadClient } from \"@bettercms-ai/sdk\";\nimport type {\n DeliveredLayout,\n DeliveryComponent,\n DeliveryEntry,\n DeliveryList,\n DeliveryPage,\n} from \"@bettercms-ai/types\";\n\nexport interface RuntimeConfig {\n apiUrl: string;\n workspace: string;\n projectId?: string;\n /** Server-only delivery key (a `content:read:draft` key for drafts). */\n apiKey?: string;\n /**\n * Collapse identical delivery GETs for the life of the process. Set by the integration\n * when Astro's `command === \"build\"` — a static build renders every route from one\n * published dataset, so a repeat read cannot legitimately differ.\n *\n * Never set for `dev` or SSR, where each request must see current content.\n */\n buildCache?: boolean;\n}\n\n/** Per-request draft state, set on `Astro.locals.bcms` by the middleware. */\nexport interface BcmsLocals {\n draft: boolean;\n token?: string;\n}\n\ninterface HasLocals {\n locals: { bcms?: BcmsLocals };\n}\n\nexport interface BetterCMSRuntime {\n /** Published-perspective client (use for SSG / non-draft reads). */\n client: BetterCMSReadClient;\n /** Pick the right client for a request (draft client when draft mode is on). */\n getClient(astro?: HasLocals): BetterCMSReadClient;\n loadEntry<T = Record<string, unknown>>(\n astro: HasLocals,\n slug: string,\n opts?: Parameters<BetterCMSReadClient[\"getEntry\"]>[1],\n ): Promise<DeliveryEntry<T>>;\n loadEntries<T = Record<string, unknown>>(\n astro: HasLocals,\n opts?: Parameters<BetterCMSReadClient[\"listEntries\"]>[0],\n ): Promise<DeliveryList<DeliveryEntry<T>>>;\n loadPage(astro: HasLocals, slug: string): Promise<DeliveryPage | null>;\n /** Component definitions for `<BcmsBlocks components={…}>` — draft-side in draft mode. */\n loadComponents(astro: HasLocals): Promise<DeliveryComponent[]>;\n loadLayout(astro: HasLocals): Promise<DeliveredLayout | null>;\n loadForms(\n astro: HasLocals,\n opts?: Parameters<BetterCMSReadClient[\"listForms\"]>[0],\n ): Promise<Awaited<ReturnType<BetterCMSReadClient[\"listForms\"]>>>;\n}\n\nexport function createRuntime(config: RuntimeConfig): BetterCMSRuntime {\n const { buildCache, ...clientConfig } = config;\n // One client for the whole build, so the cache below is shared across every route\n // rather than rebuilt per render.\n const published = createClient({ ...clientConfig, perspective: \"published\", cache: buildCache });\n\n const getClient = (astro?: HasLocals): BetterCMSReadClient => {\n const bcms = astro?.locals?.bcms;\n if (bcms?.draft) {\n // Explicitly uncached: a draft read exists to show the edit that just happened.\n return createClient({\n ...clientConfig,\n perspective: \"drafts\",\n previewToken: bcms.token,\n cache: false,\n });\n }\n return published;\n };\n\n return {\n client: published,\n getClient,\n loadEntry: (astro, slug, opts) => getClient(astro).getEntry(slug, opts),\n loadEntries: (astro, opts) => getClient(astro).listEntries(opts),\n loadPage: (astro, slug) => getClient(astro).getPage(slug),\n loadComponents: (astro) => getClient(astro).listComponents(),\n loadLayout: (astro) => getClient(astro).getLayout(),\n loadForms: (astro, opts) => getClient(astro).listForms(opts),\n };\n}\n\n/**\n * Build the live SSE URL for `<BcmsLive>`. The key is a query param because\n * browser EventSource cannot send headers — use a content:read key.\n *\n * `depth` sets the hydration depth of the document the stream pushes (default 1,\n * matching the delivery API). `drafts` streams autosaves so a preview surface\n * repaints as the editor types — it needs a `content:read:draft` key, and the\n * server ignores the flag for any other key rather than failing the connection.\n * Never enable it on a public site.\n */\nexport function liveSrc(opts: {\n apiUrl: string;\n workspace: string;\n apiKey: string;\n depth?: 0 | 1 | 2;\n drafts?: boolean;\n}): string {\n const base = opts.apiUrl.replace(/\\/+$/, \"\");\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 `${base}/api/v1/delivery/${opts.workspace}/live?${q}`;\n}\n\n/**\n * The published content snapshot, read at request time on a server BetterCMS hosts (it rewrites the\n * file on every publish) and from `bcms-content.json` at build time. Read content through this —\n * never `import` bcms-content.json or `import.meta.glob` it: a bundled copy is frozen at build, and\n * the platform has to rebuild the whole site for every publish to change it.\n */\nexport { readPublishedContent, publishedEntry, type PublishedContent } from \"@bettercms-ai/sdk\";\n\n// ── Signed-cookie helpers (HMAC-SHA256, base64url) ──────────────────────────\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(\n \"raw\",\n enc.encode(secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\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. */\nexport async function signValue(value: string, secret: string): Promise<string> {\n return `${value}.${await hmac(value, secret)}`;\n}\n\n/** Verify a signed value, returning the original value or null if tampered. */\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 // Constant-time-ish compare via length + char accumulation.\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/**\n * The draft-cookie signing secret, `process.env` FIRST.\n *\n * Vite may INLINE `import.meta.env.BCMS_DRAFT_SECRET` at build time, and the value present\n * when the customer's site is built is not the value the hosting container is given at start\n * — BetterCMS derives it per project and injects it as a real env var. Reading the runtime\n * env first is what makes managed hosting work without asking anyone to rebuild. The\n * `import.meta.env` read stays as the fallback for `astro dev` and for adapters with no\n * `process` (guarded, since touching `import.meta.env` outside Vite throws).\n */\nexport function draftSecret(): string | undefined {\n const fromProcess =\n typeof process !== \"undefined\" ? (process.env?.BCMS_DRAFT_SECRET as string | undefined) : undefined;\n if (fromProcess) return fromProcess;\n try {\n return import.meta.env?.BCMS_DRAFT_SECRET as string | undefined;\n } catch {\n return undefined;\n }\n}\n\n/** Only same-origin relative paths. Blocks \"//evil.com\", \"https://evil.com\", etc. */\nexport function safeRedirectPath(to: string): string {\n return to.startsWith(\"/\") && !to.startsWith(\"//\") ? to : \"/\";\n}\n\n/** Decode a preview-token JWT payload (UNVERIFIED) to read its `entrySlug`. */\nexport function decodeTokenSlug(token: string): string | null {\n try {\n const part = token.split(\".\")[1];\n if (!part) return null;\n const json = JSON.parse(\n atob(part.replace(/-/g, \"+\").replace(/_/g, \"/\")),\n ) as { entrySlug?: string };\n return json.entrySlug ?? null;\n } catch {\n return null;\n }\n}\n","/**\n * @bettercms-ai/astro — the BetterCMS adapter for Astro.\n *\n * import { defineConfig } from \"astro/config\";\n * import bettercms from \"@bettercms-ai/astro\";\n *\n * export default defineConfig({\n * integrations: [bettercms({ apiUrl, workspace })],\n * output: \"server\",\n * });\n *\n * Then in any page: `import { loadPage } from \"bettercms:client\"`.\n */\nexport { bettercms, default } from \"./integration.js\";\nexport {\n resolveConfig,\n DRAFT_COOKIE,\n type BetterCMSAstroOptions,\n type PublicConfig,\n type ResolvedConfig,\n} from \"./config.js\";\nexport { liveSrc } from \"./runtime.js\";\n// C3/C4: a site's own section root declares that it paints block.style.\nexport { RESPONSIVE_CSS } from \"@bettercms-ai/types\";\n// A `link` value (or a button's `href`) is a string or a link object: `linkHref` reads either as the href.\nexport { linkHref, type LinkValue } from \"@bettercms-ai/types\";\nexport { sectionRootAttrs, type SectionRootAttrs, type SectionRootBlock } from \"./section-root.js\";\nexport { fieldAttrs, fieldStyleOf, type FieldAttrs } from \"./field-attrs.js\";\nexport { sectionColumnAttrs, type SectionColumnAttrs } from \"./section-root.js\";\nexport type { BcmsLocals, BetterCMSRuntime, RuntimeConfig } from \"./runtime.js\";\n\n// Image URL builder, re-exported for `<BcmsImage>` and host code.\nexport {\n default as imageUrlBuilder,\n imageUrl,\n imageValueUrl,\n imageValueObjectPosition,\n} from \"@bettercms-ai/image-url\";\nexport type {\n ImageUrlBuilder,\n ImageSource,\n ImageFormat,\n ImageFit,\n ImageCrop,\n ImageFocal,\n ImageValueUrlOptions,\n} from \"@bettercms-ai/image-url\";\n\n// Delivery read types, re-exported for typing page/entry data.\nexport type {\n Perspective,\n DeliveryEntry,\n DeliveryPage,\n DeliveryList,\n PageMetaJson,\n SiteSeoDefaults,\n ContentBlock,\n DeliveredLayout,\n} from \"@bettercms-ai/types\";\nexport type { DeliveryForm, DeliveryFormField } from \"@bettercms-ai/sdk\";\n\n// SEO (FLO-302): page-over-site meta resolver. In a page's frontmatter,\n// `const seo = resolveSeo(page, siteDefaults)`, then map `seo.*` into `<head>`.\nexport { resolveSeo } from \"@bettercms-ai/sdk\";\nexport type { SeoInput, ResolvedSeo } from \"@bettercms-ai/sdk\";\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 */\nimport { blockStyleToColumnCss, blockStyleToCss, hideOnAttr, type BlockStyle } from \"@bettercms-ai/types\";\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 * 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 * Twin: `fieldAttrs` in @bettercms-ai/next (a React style object there).\n */\nimport { fieldStyleCssText, type FieldStyle, type FieldStyles } from \"@bettercms-ai/types\";\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"],"mappings":";AAWA,SAAS,oBAAoB;AAC7B,SAAS,eAAe;AAexB,IAAM,oBAAoB;AAC1B,IAAM,gBAAgB;AACf,IAAM,eAAe;AAiD5B,IAAI;AACJ,SAAS,SAAS,KAAuB;AACvC,MAAI,kBAAkB,QAAW;AAC/B,QAAI;AACF,sBAAgB,KAAK,MAAM,aAAa,QAAQ,KAAK,aAAa,GAAG,MAAM,CAAC;AAAA,IAC9E,QAAQ;AACN,sBAAgB,CAAC;AAAA,IACnB;AAAA,EACF;AACA,SAAO;AACT;AAOA,IAAM,WAAW,CAAC,MAAc,QAAgB,UAC9C,IAAI;AAAA,EACF,2BAA2B,IAAI,sCAAsC,IAAI,cACpE,MAAM,QAAQ,KAAK;AAAA;AAI1B;AAMK,SAAS,cACd,SACA,MAA0C,QAAQ,KAClD,MAAc,QAAQ,IAAI,GACV;AAChB,QAAM,OAAO,MAAgB,SAAS,GAAG;AAEzC,QAAM,UAAU,QAAQ,UAAU,IAAI,uBAAuB,KAAK,EAAE,UAAU,IAAI,QAAQ,QAAQ,EAAE;AACpG,QAAM,YAAY,QAAQ,aAAa,IAAI,yBAAyB,KAAK,EAAE,aAAa;AAGxF,MAAI,CAAC,OAAQ,OAAM,SAAS,UAAU,uBAAuB,4BAA4B,aAAa,cAAc;AACpH,MAAI,CAAC,WAAW;AACd,UAAM,SAAS,aAAa,yBAAyB,4BAA4B,aAAa,cAAc;AAAA,EAC9G;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,WAAW,QAAQ,aAAa,IAAI,0BAA0B,KAAK,EAAE;AAAA,IACrE,WAAW,QAAQ,YAAY,IAAI,yBAAyB,mBAAmB,QAAQ,QAAQ,EAAE;AAAA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,CAAC;AAAA,EACvC;AACF;AAsBO,SAAS,mBAAmB,OAAgE;AACjG,QAAM,MAAM,sBAAuB,OAAO,SAAS,MAAoC;AACvF,SAAO,EAAE,oBAAoB,IAAI,GAAI,MAAM,EAAE,OAAO,QAAQ,GAAG,EAAE,IAAI,CAAC,EAAG;AAC3E;;;ACxDA,SAAS,yBAA4D;AAW9D,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,kBAAkB,aAAa,MAAM,WAAW,CAAC;AAC/D,SAAO,EAAE,mBAAmB,MAAM,mBAAmB,KAAK,GAAI,QAAQ,EAAE,MAAM,IAAI,CAAC,EAAG;AACxF;;;AFLA;AAAA,EACa,WAAXA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AA0BP,SAAS,kBAAkB;","names":["default"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@bettercms-ai/astro",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "The BetterCMS adapter for Astro — a `bettercms()` integration, a `bettercms:client` virtual module, typed content loaders, draft preview, and native .astro rendering components.",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -55,11 +55,11 @@
|
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
57
|
"@bettercms-ai/image-url": "^0.4.0",
|
|
58
|
-
"@bettercms-ai/next": "^0.
|
|
58
|
+
"@bettercms-ai/next": "^0.24.0",
|
|
59
59
|
"@bettercms-ai/richtext": "^0.8.1",
|
|
60
|
-
"@bettercms-ai/sdk": "^1.
|
|
61
|
-
"@bettercms-ai/types": "^1.
|
|
62
|
-
"@bettercms-ai/ui": "^0.15.
|
|
60
|
+
"@bettercms-ai/sdk": "^1.29.0",
|
|
61
|
+
"@bettercms-ai/types": "^1.41.0",
|
|
62
|
+
"@bettercms-ai/ui": "^0.15.1",
|
|
63
63
|
"libphonenumber-js": "^1.13.13"
|
|
64
64
|
},
|
|
65
65
|
"peerDependencies": {
|