@bettercms-ai/next 0.36.2 → 0.38.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/form.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/form.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * <BcmsForm> — render a BetterCMS form natively in React, the headless way.\n *\n * Pass a form straight from your content snapshot (`readSnapshot().forms[n]`) or\n * the delivery API. It renders real inputs (no iframe), handles conditional\n * `showIf` fields, URL-query prefill, the honeypot, an optional Turnstile widget,\n * and submits via `@bettercms-ai/sdk`'s `submitForm`. All visible markup is\n * unstyled and class-driven, so the host site owns the look.\n */\n\nimport { lazy, Suspense, useEffect, useMemo, useRef, useState, type FormEvent, type ReactElement } from \"react\";\nimport {\n submitForm,\n shouldShowField,\n formInitialValues,\n asStringArray,\n toggleOption,\n type DeliveryForm,\n type DeliveryFormField,\n type FormValue,\n type FormValues,\n type FormSubmitError,\n} from \"@bettercms-ai/sdk/read\";\n\nconst TURNSTILE_SRC = \"https://challenges.cloudflare.com/turnstile/v0/api.js\";\n\n/**\n * The country-picker phone control, loaded only when a form actually has one.\n *\n * It carries libphonenumber's metadata (~80KB), which no form without a picker should pay\n * for. The import specifier must survive into `dist/form.js` rather than being inlined —\n * see the `external` entry in tsup.config.ts and the dist greps in the tests.\n */\nconst PhoneField = lazy(() => import(\"./phone-field.js\"));\n\n// Field type → native <input type>. Other types render their own element.\nconst INPUT_TYPES: Partial<Record<DeliveryFormField[\"type\"], string>> = {\n text: \"text\",\n email: \"email\",\n phone: \"tel\",\n url: \"url\",\n number: \"number\",\n date: \"date\",\n};\n\nexport interface BcmsFormProps {\n /** A form from your content snapshot or the delivery API. */\n form: DeliveryForm;\n /** API origin. Defaults to the SDK default (https://api.bettercms.ai). */\n apiBase?: string;\n /** Turnstile site key — needed to render the widget when `form.turnstileEnabled`. */\n turnstileSiteKey?: string;\n /** Called with the new submission id after a successful submit (before any redirect). */\n onSubmitted?: (submissionId: string) => void;\n /** Class for the <form> element; field wrappers/status use `bcms-*` classes. */\n className?: string;\n}\n\ntype Status = { state: \"idle\" | \"submitting\" | \"error\" | \"success\"; message?: string };\n\nfunction readPrefill(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const out: Record<string, string> = {};\n new URLSearchParams(window.location.search).forEach((v, k) => {\n out[k] = v;\n });\n return out;\n}\n\ntype Page = { label: string | null; key: string | null; fields: DeliveryFormField[] };\n\n/**\n * Cut the flat field list into pages at its `step` dividers, or null when it has none. Fields\n * before the first divider are page 1; an empty page is dropped. The hosted renderer and\n * BcmsForm.astro carry the same rule: each package publishes on its own, so none of them can\n * count on a newer shared helper arriving with it.\n */\nfunction splitSteps(fields: DeliveryFormField[]): Page[] | null {\n if (!fields.some((f) => f.type === \"step\")) return null;\n const pages: Page[] = [];\n let cur: Page = { label: null, key: null, fields: [] };\n for (const f of fields) {\n if (f.type !== \"step\") {\n cur.fields.push(f);\n continue;\n }\n if (cur.fields.length) pages.push(cur);\n cur = { label: f.label, key: f.key, fields: [] };\n }\n if (cur.fields.length) pages.push(cur);\n return pages;\n}\n\nfunction resetTurnstile(): void {\n const t = (globalThis as { turnstile?: { reset: () => void } }).turnstile;\n if (t) {\n try {\n t.reset();\n } catch {\n /* widget not mounted yet */\n }\n }\n}\n\nexport function BcmsForm({\n form,\n apiBase,\n turnstileSiteKey,\n onSubmitted,\n className,\n}: BcmsFormProps): ReactElement {\n const showTurnstile = Boolean(form.turnstileEnabled && turnstileSiteKey);\n const [values, setValues] = useState<FormValues>(() => {\n const init = formInitialValues(form, readPrefill());\n if (form.honeypotField) init[form.honeypotField] = \"\";\n return init;\n });\n const [status, setStatus] = useState<Status>({ state: \"idle\" });\n const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\n\n // Steps. Until the component has mounted every page is shown, so server-rendered output (and a\n // visitor without JavaScript) gets one long form; `enhanced` then turns it into pages.\n const pages = useMemo(() => splitSteps(form.fields), [form.fields]);\n const [enhanced, setEnhanced] = useState(false);\n const [step, setStep] = useState(0);\n const pageRefs = useRef<(HTMLFieldSetElement | null)[]>([]);\n const headingRefs = useRef<(HTMLHeadingElement | null)[]>([]);\n const moveFocus = useRef(false);\n const last = pages ? pages.length - 1 : 0;\n const paged = Boolean(pages && enhanced);\n useEffect(() => setEnhanced(true), []);\n // Focus follows the visitor to the new page's heading, never on first paint.\n useEffect(() => {\n if (!moveFocus.current) return;\n moveFocus.current = false;\n headingRefs.current[step]?.focus();\n }, [step]);\n\n // The browser's own validity, for ONE page: the first control that fails reports its message.\n function pageInvalid(i: number): boolean {\n const controls = pageRefs.current[i]?.querySelectorAll<HTMLInputElement>(\"input,select,textarea\") ?? [];\n for (const c of controls) {\n if (!c.checkValidity()) {\n c.reportValidity();\n return true;\n }\n }\n return false;\n }\n function goTo(i: number): void {\n moveFocus.current = true;\n setStep(i);\n }\n function next(): void {\n if (!pageInvalid(step)) goTo(step + 1);\n }\n\n // Cloudflare auto-renders any `.cf-turnstile` element once its script is present.\n useEffect(() => {\n if (!showTurnstile || document.querySelector(`script[src=\"${TURNSTILE_SRC}\"]`)) return;\n const script = document.createElement(\"script\");\n script.src = TURNSTILE_SRC;\n script.async = true;\n script.defer = true;\n document.head.appendChild(script);\n }, [showTurnstile]);\n\n const visibleFields = useMemo(\n () => form.fields.filter((f) => f.type !== \"hidden\" && f.type !== \"step\" && shouldShowField(f, values)),\n [form.fields, values],\n );\n\n const setValue = (key: string, value: FormValue) =>\n setValues((prev) => ({ ...prev, [key]: value }));\n\n async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {\n e.preventDefault();\n // Enter inside a field before the last page moves on rather than submitting half a form.\n if (paged && step < last) return next();\n setStatus({ state: \"submitting\" });\n setFieldErrors({});\n\n const tokenEl = e.currentTarget.querySelector<HTMLInputElement>(\n '[name=\"cf-turnstile-response\"]',\n );\n const turnstileToken = tokenEl?.value || undefined;\n\n // Drop conditionally-hidden fields so a hidden required field can't block submit;\n // keep hidden-type fields and the honeypot (the API classifies bots on it).\n const data: FormValues = {};\n for (const field of form.fields) {\n if (field.type === \"step\") continue; // a divider is never an answer\n if (field.type === \"hidden\" || shouldShowField(field, values)) {\n data[field.key] = values[field.key];\n }\n }\n if (form.honeypotField) data[form.honeypotField] = values[form.honeypotField] ?? \"\";\n\n try {\n const { id } = await submitForm({ formId: form.id, data, turnstileToken, baseUrl: apiBase });\n onSubmitted?.(id);\n // A web address only: a stored `javascript:` URL would run on the site's own origin.\n if (form.redirectUrl && /^https?:/i.test(form.redirectUrl)) {\n window.location.href = form.redirectUrl;\n return;\n }\n const reset = formInitialValues(form);\n if (form.honeypotField) reset[form.honeypotField] = \"\";\n setValues(reset);\n setStep(0);\n setStatus({\n state: \"success\",\n message: form.successMessage ?? \"Thanks! Your submission was received.\",\n });\n resetTurnstile();\n } catch (err) {\n const e2 = err as FormSubmitError;\n if (e2.fieldErrors) {\n setFieldErrors(e2.fieldErrors);\n // The server found a problem on a page the visitor has left: take them back to it.\n const bad = pages?.findIndex((p) => p.fields.some((f) => e2.fieldErrors?.[f.key]));\n if (bad !== undefined && bad >= 0) goTo(bad);\n }\n setStatus({ state: \"error\", message: e2.message || \"Something went wrong. Please try again.\" });\n resetTurnstile();\n }\n }\n\n return (\n // `data-bcms-form` carries the id so the Visual Editor can find THIS form in the\n // preview frame and patch its copy live. Valued rather than bare: the runtime\n // selectors are `form[data-bcms-form]`, which a valued attribute still matches.\n <form className={className} onSubmit={handleSubmit} noValidate data-bcms-form={form.id}>\n {pages\n ? pages.map((page, i) => (\n <fieldset\n key={page.key ?? \"first\"}\n ref={(el) => {\n pageRefs.current[i] = el;\n }}\n className=\"bcms-step\"\n data-bcms-step={i + 1}\n hidden={paged && i !== step}\n aria-labelledby={`bcms-step-${form.id}-${i + 1}`}\n >\n <h3\n id={`bcms-step-${form.id}-${i + 1}`}\n className=\"bcms-step-title\"\n tabIndex={-1}\n ref={(el) => {\n headingRefs.current[i] = el;\n }}\n data-bcms-form-field={page.key ?? undefined}\n >\n <span className=\"bcms-step-count\">\n Step {i + 1} of {pages.length}\n </span>\n {page.label ? (\n <>\n {\" \"}\n <span data-bcms-form-part=\"label\">{page.label}</span>\n </>\n ) : null}\n </h3>\n {visibleFields\n .filter((f) => page.fields.includes(f))\n .map((field) => (\n <Field\n key={field.key}\n field={field}\n value={values[field.key]}\n error={fieldErrors[field.key]}\n onChange={(v) => setValue(field.key, v)}\n />\n ))}\n {paged ? (\n <div className=\"bcms-step-nav\">\n {i > 0 ? (\n <button type=\"button\" data-bcms-step-back onClick={() => goTo(i - 1)}>\n Back\n </button>\n ) : null}\n {i < last ? (\n <button type=\"button\" data-bcms-step-next onClick={next}>\n Next\n </button>\n ) : null}\n </div>\n ) : null}\n </fieldset>\n ))\n : visibleFields.map((field) => (\n <Field\n key={field.key}\n field={field}\n value={values[field.key]}\n error={fieldErrors[field.key]}\n onChange={(v) => setValue(field.key, v)}\n />\n ))}\n\n {form.honeypotField ? (\n <span aria-hidden=\"true\" style={{ position: \"absolute\", left: \"-9999px\" }}>\n <input\n type=\"text\"\n name={form.honeypotField}\n tabIndex={-1}\n autoComplete=\"off\"\n value={String(values[form.honeypotField] ?? \"\")}\n onChange={(e) => setValue(form.honeypotField as string, e.target.value)}\n />\n </span>\n ) : null}\n\n {showTurnstile ? <div className=\"cf-turnstile\" data-sitekey={turnstileSiteKey} /> : null}\n\n <button\n type=\"submit\"\n hidden={paged && step < last}\n disabled={status.state === \"submitting\"}\n data-bcms-form-part=\"submit\"\n >\n {status.state === \"submitting\" ? \"Submitting…\" : form.submitLabel ?? \"Submit\"}\n </button>\n\n {status.message ? (\n <p\n className={`bcms-form-status bcms-form-status--${status.state}`}\n role=\"status\"\n aria-live=\"polite\"\n >\n {status.message}\n </p>\n ) : null}\n </form>\n );\n}\n\ninterface FieldProps {\n field: DeliveryFormField;\n value: FormValue;\n error?: string;\n onChange: (value: FormValue) => void;\n}\n\nfunction Field({ field, value, error, onChange }: FieldProps): ReactElement {\n const required = field.required;\n const errorNode = error ? (\n <span className=\"bcms-field-error\" role=\"alert\">\n {error}\n </span>\n ) : null;\n // Every author-editable string carries a `data-bcms-form-part` so the Visual Editor can\n // repaint it live. A string the dock can edit but cannot mark shows stale on the canvas.\n const helpNode = field.helpText ? (\n <span className=\"bcms-field-help\" data-bcms-form-part=\"help\">\n {field.helpText}\n </span>\n ) : null;\n\n if (field.type === \"checkbox\" || field.type === \"consent\") {\n return (\n <label\n className=\"bcms-field bcms-field--checkbox\"\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <input\n type=\"checkbox\"\n name={field.key}\n required={required}\n checked={Boolean(value)}\n onChange={(e) => onChange(e.target.checked)}\n />{\" \"}\n <span data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </span>\n {helpNode}\n {errorNode}\n </label>\n );\n }\n\n // Pick-one and pick-many are groups of controls, not a single element, so they\n // return their own <fieldset> rather than flowing into the label+control shape\n // below. Without these two branches both fell through to `<input type=\"text\">`.\n if (field.type === \"radio\" || field.type === \"checkboxes\") {\n const multi = field.type === \"checkboxes\";\n const selected = asStringArray(value);\n return (\n <fieldset\n className={`bcms-field bcms-field--${multi ? \"checkboxes\" : \"radio\"}`}\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <legend data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </legend>\n {(field.options ?? []).map((opt) => (\n <label key={opt} className=\"bcms-option\">\n <input\n type={multi ? \"checkbox\" : \"radio\"}\n name={field.key}\n value={opt}\n // `required` on every radio in a group is the native way to demand one\n // choice. On checkboxes it would demand ALL of them, so it is omitted —\n // the API enforces non-empty instead.\n required={!multi && required}\n checked={multi ? selected.includes(opt) : value === opt}\n onChange={(e) =>\n onChange(multi ? toggleOption(value, opt, e.target.checked) : opt)\n }\n />{\" \"}\n <span data-bcms-form-part=\"option\">{opt}</span>\n </label>\n ))}\n {helpNode}\n {errorNode}\n </fieldset>\n );\n }\n\n const str = String(value ?? \"\");\n let control: ReactElement;\n if (field.type === \"textarea\") {\n control = (\n <textarea\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n } else if (field.type === \"select\") {\n control = (\n <select name={field.key} required={required} value={str} onChange={(e) => onChange(e.target.value)}>\n <option value=\"\" disabled>\n Choose…\n </option>\n {(field.options ?? []).map((opt) => (\n <option key={opt} value={opt} data-bcms-form-part=\"option\">\n {opt}\n </option>\n ))}\n </select>\n );\n } else if (field.type === \"phone\" && field.ui?.countryPicker) {\n // The fallback is a usable tel input inside the SAME wrapper, so the host's `.bcms-phone`\n // rules apply before and after the chunk lands and the swap is not a layout surprise.\n control = (\n <Suspense\n fallback={\n <span className=\"bcms-phone\">\n <input type=\"tel\" name={field.key} placeholder={field.placeholder} required={required} value={str} onChange={(e) => onChange(e.target.value)} autoComplete=\"tel\" dir=\"ltr\" />\n </span>\n }\n >\n <PhoneField\n name={field.key}\n value={str}\n onChange={onChange}\n placeholder={field.placeholder}\n required={required}\n defaultCountry={field.ui.defaultCountry}\n />\n </Suspense>\n );\n } else {\n control = (\n <input\n type={INPUT_TYPES[field.type] ?? \"text\"}\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n }\n\n return (\n <p className=\"bcms-field\" data-field={field.key} data-bcms-form-field={field.key}>\n <label data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </label>\n <br />\n {control}\n {helpNode}\n {errorNode}\n </p>\n );\n}\n"],"mappings":";;;;AAYA,SAAS,MAAM,UAAU,WAAW,SAAS,QAAQ,gBAAmD;AACxG;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AAwOS,SAIE,UAEE,KANJ;AAtOhB,IAAM,gBAAgB;AAStB,IAAM,aAAa,KAAK,MAAM,OAAO,kBAAkB,CAAC;AAGxD,IAAM,cAAkE;AAAA,E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,GAC/F;AAAA,0BAAC,YAAO,OAAM,IAAG,UAAQ,MAAC,0BAE1B;AAAA,OACE,MAAM,WAAW,CAAC,GAAG,IAAI,CAAC,QAC1B,oBAAC,YAAiB,OAAO,KAAK,uBAAoB,UAC/C,iBADU,GAEb,CACD;AAAA,OACH;AAAA,EAEJ,WAAW,MAAM,SAAS,WAAW,MAAM,IAAI,eAAe;AAG5D,cACE;AAAA,MAAC;AAAA;AAAA,QACC,UACE,oBAAC,UAAK,WAAU,cACd,8BAAC,WAAM,MAAK,OAAM,MAAM,MAAM,KAAK,aAAa,MAAM,aAAa,UAAoB,OAAO,KAAK,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK,GAAG,cAAa,OAAM,KAAI,OAAM,GAC7K;AAAA,QAGF;AAAA,UAAC;AAAA;AAAA,YACC,MAAM,MAAM;AAAA,YACZ,OAAO;AAAA,YACP;AAAA,YACA,aAAa,MAAM;AAAA,YACnB;AAAA,YACA,gBAAgB,MAAM,GAAG;AAAA;AAAA,QAC3B;AAAA;AAAA,IACF;AAAA,EAEJ,OAAO;AACL,cACE;AAAA,MAAC;AAAA;AAAA,QACC,MAAM,YAAY,MAAM,IAAI,KAAK;AAAA,QACjC,MAAM,MAAM;AAAA,QACZ,aAAa,MAAM;AAAA,QACnB;AAAA,QACA,OAAO;AAAA,QACP,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA;AAAA,IAC1C;AAAA,EAEJ;AAEA,SACE,qBAAC,OAAE,WAAU,cAAa,cAAY,MAAM,KAAK,wBAAsB,MAAM,KAC3E;AAAA,yBAAC,WAAM,uBAAoB,SACxB;AAAA,YAAM;AAAA,MACN,WAAW,OAAO;AAAA,OACrB;AAAA,IACA,oBAAC,QAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,KACH;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/form.tsx"],"sourcesContent":["\"use client\";\n\n/**\n * <BcmsForm> — render a BetterCMS form natively in React, the headless way.\n *\n * Pass a form straight from your content snapshot (`readSnapshot().forms[n]`) or\n * the delivery API. It renders real inputs (no iframe), handles conditional\n * `showIf` fields, URL-query prefill, the honeypot, an optional Turnstile widget,\n * and submits via `@bettercms-ai/sdk`'s `submitForm`. All visible markup is\n * unstyled and class-driven, so the host site owns the look.\n */\n\nimport { lazy, Suspense, useEffect, useMemo, useRef, useState, type FormEvent, type ReactElement } from \"react\";\nimport {\n submitForm,\n shouldShowField,\n formInitialValues,\n asStringArray,\n toggleOption,\n type DeliveryForm,\n type DeliveryFormField,\n type FormValue,\n type FormValues,\n type FormSubmitError,\n} from \"@bettercms-ai/sdk/read\";\n\nconst TURNSTILE_SRC = \"https://challenges.cloudflare.com/turnstile/v0/api.js\";\n\n/**\n * The platform honeypot's clipped wrapper (the forms contract's `_bcms_hp`): out of flow, so nothing\n * moves; clipped, not off-screen, so a right-to-left page cannot scroll to it; never `display:none`,\n * which some bots skip. Any value in it is a bot's. The renderer's FORM_HONEYPOT, pinned by\n * src/__tests__/content/form-script-pin.test.ts.\n */\nconst HONEYPOT_STYLE = {\n position: \"absolute\",\n width: \"1px\",\n height: \"1px\",\n overflow: \"hidden\",\n clipPath: \"inset(50%)\",\n whiteSpace: \"nowrap\",\n} as const;\n\n/**\n * The country-picker phone control, loaded only when a form actually has one.\n *\n * It carries libphonenumber's metadata (~80KB), which no form without a picker should pay\n * for. The import specifier must survive into `dist/form.js` rather than being inlined —\n * see the `external` entry in tsup.config.ts and the dist greps in the tests.\n */\nconst PhoneField = lazy(() => import(\"./phone-field.js\"));\n\n// Field type → native <input type>. Other types render their own element.\nconst INPUT_TYPES: Partial<Record<DeliveryFormField[\"type\"], string>> = {\n text: \"text\",\n email: \"email\",\n phone: \"tel\",\n url: \"url\",\n number: \"number\",\n date: \"date\",\n};\n\nexport interface BcmsFormProps {\n /** A form from your content snapshot or the delivery API. */\n form: DeliveryForm;\n /** API origin. Defaults to the SDK default (https://api.bettercms.ai). */\n apiBase?: string;\n /** Turnstile site key — needed to render the widget when `form.turnstileEnabled`. */\n turnstileSiteKey?: string;\n /** Called with the new submission id after a successful submit (before any redirect). */\n onSubmitted?: (submissionId: string) => void;\n /** Class for the <form> element; field wrappers/status use `bcms-*` classes. */\n className?: string;\n}\n\ntype Status = { state: \"idle\" | \"submitting\" | \"error\" | \"success\"; message?: string };\n\nfunction readPrefill(): Record<string, string> {\n if (typeof window === \"undefined\") return {};\n const out: Record<string, string> = {};\n new URLSearchParams(window.location.search).forEach((v, k) => {\n out[k] = v;\n });\n return out;\n}\n\ntype Page = { label: string | null; key: string | null; fields: DeliveryFormField[] };\n\n/**\n * Cut the flat field list into pages at its `step` dividers, or null when it has none. Fields\n * before the first divider are page 1; an empty page is dropped. The hosted renderer and\n * BcmsForm.astro carry the same rule: each package publishes on its own, so none of them can\n * count on a newer shared helper arriving with it.\n */\nfunction splitSteps(fields: DeliveryFormField[]): Page[] | null {\n if (!fields.some((f) => f.type === \"step\")) return null;\n const pages: Page[] = [];\n let cur: Page = { label: null, key: null, fields: [] };\n for (const f of fields) {\n if (f.type !== \"step\") {\n cur.fields.push(f);\n continue;\n }\n if (cur.fields.length) pages.push(cur);\n cur = { label: f.label, key: f.key, fields: [] };\n }\n if (cur.fields.length) pages.push(cur);\n return pages;\n}\n\nfunction resetTurnstile(): void {\n const t = (globalThis as { turnstile?: { reset: () => void } }).turnstile;\n if (t) {\n try {\n t.reset();\n } catch {\n /* widget not mounted yet */\n }\n }\n}\n\nexport function BcmsForm({\n form,\n apiBase,\n turnstileSiteKey,\n onSubmitted,\n className,\n}: BcmsFormProps): ReactElement {\n const showTurnstile = Boolean(form.turnstileEnabled && turnstileSiteKey);\n const [values, setValues] = useState<FormValues>(() => {\n const init = formInitialValues(form, readPrefill());\n if (form.honeypotField) init[form.honeypotField] = \"\";\n return init;\n });\n const [status, setStatus] = useState<Status>({ state: \"idle\" });\n const [fieldErrors, setFieldErrors] = useState<Record<string, string>>({});\n\n // Steps. Until the component has mounted every page is shown, so server-rendered output (and a\n // visitor without JavaScript) gets one long form; `enhanced` then turns it into pages.\n const pages = useMemo(() => splitSteps(form.fields), [form.fields]);\n const [enhanced, setEnhanced] = useState(false);\n const [step, setStep] = useState(0);\n const pageRefs = useRef<(HTMLFieldSetElement | null)[]>([]);\n const headingRefs = useRef<(HTMLHeadingElement | null)[]>([]);\n const moveFocus = useRef(false);\n const last = pages ? pages.length - 1 : 0;\n const paged = Boolean(pages && enhanced);\n // When the form went live: `_bcms_t` is the whole ms from here to the submit.\n const shownAt = useRef(0);\n useEffect(() => {\n setEnhanced(true);\n shownAt.current = Date.now();\n }, []);\n // Focus follows the visitor to the new page's heading, never on first paint.\n useEffect(() => {\n if (!moveFocus.current) return;\n moveFocus.current = false;\n headingRefs.current[step]?.focus();\n }, [step]);\n\n // The browser's own validity, for ONE page: the first control that fails reports its message.\n function pageInvalid(i: number): boolean {\n const controls = pageRefs.current[i]?.querySelectorAll<HTMLInputElement>(\"input,select,textarea\") ?? [];\n for (const c of controls) {\n if (!c.checkValidity()) {\n c.reportValidity();\n return true;\n }\n }\n return false;\n }\n function goTo(i: number): void {\n moveFocus.current = true;\n setStep(i);\n }\n function next(): void {\n if (!pageInvalid(step)) goTo(step + 1);\n }\n\n // Cloudflare auto-renders any `.cf-turnstile` element once its script is present.\n useEffect(() => {\n if (!showTurnstile || document.querySelector(`script[src=\"${TURNSTILE_SRC}\"]`)) return;\n const script = document.createElement(\"script\");\n script.src = TURNSTILE_SRC;\n script.async = true;\n script.defer = true;\n document.head.appendChild(script);\n }, [showTurnstile]);\n\n const visibleFields = useMemo(\n () => form.fields.filter((f) => f.type !== \"hidden\" && f.type !== \"step\" && shouldShowField(f, values)),\n [form.fields, values],\n );\n\n const setValue = (key: string, value: FormValue) =>\n setValues((prev) => ({ ...prev, [key]: value }));\n\n async function handleSubmit(e: FormEvent<HTMLFormElement>): Promise<void> {\n e.preventDefault();\n // Enter inside a field before the last page moves on rather than submitting half a form.\n if (paged && step < last) return next();\n setStatus({ state: \"submitting\" });\n setFieldErrors({});\n\n const tokenEl = e.currentTarget.querySelector<HTMLInputElement>(\n '[name=\"cf-turnstile-response\"]',\n );\n const turnstileToken = tokenEl?.value || undefined;\n\n // Drop conditionally-hidden fields so a hidden required field can't block submit;\n // keep hidden-type fields and the honeypot (the API classifies bots on it).\n const data: FormValues = {};\n for (const field of form.fields) {\n if (field.type === \"step\") continue; // a divider is never an answer\n if (field.type === \"hidden\" || shouldShowField(field, values)) {\n data[field.key] = values[field.key];\n }\n }\n if (form.honeypotField) data[form.honeypotField] = values[form.honeypotField] ?? \"\";\n // The platform's checks: the honeypot's value (a person leaves it empty) and the time taken.\n data._bcms_hp = (e.currentTarget.elements.namedItem(\"_bcms_hp\") as HTMLInputElement | null)?.value ?? \"\";\n data._bcms_t = String(Date.now() - shownAt.current);\n\n try {\n const { id } = await submitForm({ formId: form.id, data, turnstileToken, baseUrl: apiBase });\n onSubmitted?.(id);\n // A web address only: a stored `javascript:` URL would run on the site's own origin.\n if (form.redirectUrl && /^https?:/i.test(form.redirectUrl)) {\n window.location.href = form.redirectUrl;\n return;\n }\n const reset = formInitialValues(form);\n if (form.honeypotField) reset[form.honeypotField] = \"\";\n setValues(reset);\n setStep(0);\n setStatus({\n state: \"success\",\n message: form.successMessage ?? \"Thanks! Your submission was received.\",\n });\n resetTurnstile();\n } catch (err) {\n const e2 = err as FormSubmitError;\n if (e2.fieldErrors) {\n setFieldErrors(e2.fieldErrors);\n // The server found a problem on a page the visitor has left: take them back to it.\n const bad = pages?.findIndex((p) => p.fields.some((f) => e2.fieldErrors?.[f.key]));\n if (bad !== undefined && bad >= 0) goTo(bad);\n }\n setStatus({ state: \"error\", message: e2.message || \"Something went wrong. Please try again.\" });\n resetTurnstile();\n }\n }\n\n return (\n // `data-bcms-form` carries the id so the Visual Editor can find THIS form in the\n // preview frame and patch its copy live. Valued rather than bare: the runtime\n // selectors are `form[data-bcms-form]`, which a valued attribute still matches.\n <form className={className} onSubmit={handleSubmit} noValidate data-bcms-form={form.id}>\n {pages\n ? pages.map((page, i) => (\n <fieldset\n key={page.key ?? \"first\"}\n ref={(el) => {\n pageRefs.current[i] = el;\n }}\n className=\"bcms-step\"\n data-bcms-step={i + 1}\n hidden={paged && i !== step}\n aria-labelledby={`bcms-step-${form.id}-${i + 1}`}\n >\n <h3\n id={`bcms-step-${form.id}-${i + 1}`}\n className=\"bcms-step-title\"\n tabIndex={-1}\n ref={(el) => {\n headingRefs.current[i] = el;\n }}\n data-bcms-form-field={page.key ?? undefined}\n >\n <span className=\"bcms-step-count\">\n Step {i + 1} of {pages.length}\n </span>\n {page.label ? (\n <>\n {\" \"}\n <span data-bcms-form-part=\"label\">{page.label}</span>\n </>\n ) : null}\n </h3>\n {visibleFields\n .filter((f) => page.fields.includes(f))\n .map((field) => (\n <Field\n key={field.key}\n field={field}\n value={values[field.key]}\n error={fieldErrors[field.key]}\n onChange={(v) => setValue(field.key, v)}\n />\n ))}\n {paged ? (\n <div className=\"bcms-step-nav\">\n {i > 0 ? (\n <button type=\"button\" data-bcms-step-back onClick={() => goTo(i - 1)}>\n Back\n </button>\n ) : null}\n {i < last ? (\n <button type=\"button\" data-bcms-step-next onClick={next}>\n Next\n </button>\n ) : null}\n </div>\n ) : null}\n </fieldset>\n ))\n : visibleFields.map((field) => (\n <Field\n key={field.key}\n field={field}\n value={values[field.key]}\n error={fieldErrors[field.key]}\n onChange={(v) => setValue(field.key, v)}\n />\n ))}\n\n {form.honeypotField ? (\n <span aria-hidden=\"true\" style={{ position: \"absolute\", left: \"-9999px\" }}>\n <input\n type=\"text\"\n name={form.honeypotField}\n tabIndex={-1}\n autoComplete=\"off\"\n value={String(values[form.honeypotField] ?? \"\")}\n onChange={(e) => setValue(form.honeypotField as string, e.target.value)}\n />\n </span>\n ) : null}\n\n {showTurnstile ? <div className=\"cf-turnstile\" data-sitekey={turnstileSiteKey} /> : null}\n\n <div style={HONEYPOT_STYLE}>\n <input type=\"text\" name=\"_bcms_hp\" tabIndex={-1} autoComplete=\"off\" aria-hidden=\"true\" />\n </div>\n\n <button\n type=\"submit\"\n hidden={paged && step < last}\n disabled={status.state === \"submitting\"}\n data-bcms-form-part=\"submit\"\n >\n {status.state === \"submitting\" ? \"Submitting…\" : form.submitLabel ?? \"Submit\"}\n </button>\n\n {status.message ? (\n <p\n className={`bcms-form-status bcms-form-status--${status.state}`}\n role=\"status\"\n aria-live=\"polite\"\n >\n {status.message}\n </p>\n ) : null}\n </form>\n );\n}\n\ninterface FieldProps {\n field: DeliveryFormField;\n value: FormValue;\n error?: string;\n onChange: (value: FormValue) => void;\n}\n\nfunction Field({ field, value, error, onChange }: FieldProps): ReactElement {\n const required = field.required;\n const errorNode = error ? (\n <span className=\"bcms-field-error\" role=\"alert\">\n {error}\n </span>\n ) : null;\n // Every author-editable string carries a `data-bcms-form-part` so the Visual Editor can\n // repaint it live. A string the dock can edit but cannot mark shows stale on the canvas.\n const helpNode = field.helpText ? (\n <span className=\"bcms-field-help\" data-bcms-form-part=\"help\">\n {field.helpText}\n </span>\n ) : null;\n\n if (field.type === \"checkbox\" || field.type === \"consent\") {\n return (\n <label\n className=\"bcms-field bcms-field--checkbox\"\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <input\n type=\"checkbox\"\n name={field.key}\n required={required}\n checked={Boolean(value)}\n onChange={(e) => onChange(e.target.checked)}\n />{\" \"}\n <span data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </span>\n {helpNode}\n {errorNode}\n </label>\n );\n }\n\n // Pick-one and pick-many are groups of controls, not a single element, so they\n // return their own <fieldset> rather than flowing into the label+control shape\n // below. Without these two branches both fell through to `<input type=\"text\">`.\n if (field.type === \"radio\" || field.type === \"checkboxes\") {\n const multi = field.type === \"checkboxes\";\n const selected = asStringArray(value);\n return (\n <fieldset\n className={`bcms-field bcms-field--${multi ? \"checkboxes\" : \"radio\"}`}\n data-field={field.key}\n data-bcms-form-field={field.key}\n >\n <legend data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </legend>\n {(field.options ?? []).map((opt) => (\n <label key={opt} className=\"bcms-option\">\n <input\n type={multi ? \"checkbox\" : \"radio\"}\n name={field.key}\n value={opt}\n // `required` on every radio in a group is the native way to demand one\n // choice. On checkboxes it would demand ALL of them, so it is omitted —\n // the API enforces non-empty instead.\n required={!multi && required}\n checked={multi ? selected.includes(opt) : value === opt}\n onChange={(e) =>\n onChange(multi ? toggleOption(value, opt, e.target.checked) : opt)\n }\n />{\" \"}\n <span data-bcms-form-part=\"option\">{opt}</span>\n </label>\n ))}\n {helpNode}\n {errorNode}\n </fieldset>\n );\n }\n\n const str = String(value ?? \"\");\n let control: ReactElement;\n if (field.type === \"textarea\") {\n control = (\n <textarea\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n } else if (field.type === \"select\") {\n control = (\n <select name={field.key} required={required} value={str} onChange={(e) => onChange(e.target.value)}>\n <option value=\"\" disabled>\n Choose…\n </option>\n {(field.options ?? []).map((opt) => (\n <option key={opt} value={opt} data-bcms-form-part=\"option\">\n {opt}\n </option>\n ))}\n </select>\n );\n } else if (field.type === \"phone\" && field.ui?.countryPicker) {\n // The fallback is a usable tel input inside the SAME wrapper, so the host's `.bcms-phone`\n // rules apply before and after the chunk lands and the swap is not a layout surprise.\n control = (\n <Suspense\n fallback={\n <span className=\"bcms-phone\">\n <input type=\"tel\" name={field.key} placeholder={field.placeholder} required={required} value={str} onChange={(e) => onChange(e.target.value)} autoComplete=\"tel\" dir=\"ltr\" />\n </span>\n }\n >\n <PhoneField\n name={field.key}\n value={str}\n onChange={onChange}\n placeholder={field.placeholder}\n required={required}\n defaultCountry={field.ui.defaultCountry}\n />\n </Suspense>\n );\n } else {\n control = (\n <input\n type={INPUT_TYPES[field.type] ?? \"text\"}\n name={field.key}\n placeholder={field.placeholder}\n required={required}\n value={str}\n onChange={(e) => onChange(e.target.value)}\n />\n );\n }\n\n return (\n <p className=\"bcms-field\" data-field={field.key} data-bcms-form-field={field.key}>\n <label data-bcms-form-part=\"label\">\n {field.label}\n {required ? \" *\" : \"\"}\n </label>\n <br />\n {control}\n {helpNode}\n {errorNode}\n </p>\n );\n}\n"],"mappings":";;;;AAYA,SAAS,MAAM,UAAU,WAAW,SAAS,QAAQ,gBAAmD;AACxG;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAMK;AA+PS,SAIE,UAEE,KANJ;AA7PhB,IAAM,gBAAgB;AAQtB,IAAM,iBAAiB;AAAA,EACrB,UAAU;AAAA,EACV,OAAO;AAAA,EACP,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,UAAU;AAAA,EACV,YAAY;AACd;AASA,IAAM,aAAa,KAAK,MAAM,OAAO,kBAAkB,CAAC;AAGxD,IAAM,cAAkE;AAAA,EACtE,MAAM;AAAA,EACN,OAAO;AAAA,EACP,OAAO;AAAA,EACP,KAAK;AAAA,EACL,QAAQ;AAAA,EACR,MAAM;AACR;AAiBA,SAAS,cAAsC;AAC7C,MAAI,OAAO,WAAW,YAAa,QAAO,CAAC;AAC3C,QAAM,MAA8B,CAAC;AACrC,MAAI,gBAAgB,OAAO,SAAS,MAAM,EAAE,QAAQ,CAAC,GAAG,MAAM;AAC5D,QAAI,CAAC,IAAI;AAAA,EACX,CAAC;AACD,SAAO;AACT;AAUA,SAAS,WAAW,QAA4C;AAC9D,MAAI,CAAC,OAAO,KAAK,CAAC,MAAM,EAAE,SAAS,MAAM,EAAG,QAAO;AACnD,QAAM,QAAgB,CAAC;AACvB,MAAI,MAAY,EAAE,OAAO,MAAM,KAAK,MAAM,QAAQ,CAAC,EAAE;AACrD,aAAW,KAAK,QAAQ;AACtB,QAAI,EAAE,SAAS,QAAQ;AACrB,UAAI,OAAO,KAAK,CAAC;AACjB;AAAA,IACF;AACA,QAAI,IAAI,OAAO,OAAQ,OAAM,KAAK,GAAG;AACrC,UAAM,EAAE,OAAO,EAAE,OAAO,KA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KAAK,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK,GAAG,cAAa,OAAM,KAAI,OAAM,GAC7K;AAAA,QAGF;AAAA,UAAC;AAAA;AAAA,YACC,MAAM,MAAM;AAAA,YACZ,OAAO;AAAA,YACP;AAAA,YACA,aAAa,MAAM;AAAA,YACnB;AAAA,YACA,gBAAgB,MAAM,GAAG;AAAA;AAAA,QAC3B;AAAA;AAAA,IACF;AAAA,EAEJ,OAAO;AACL,cACE;AAAA,MAAC;AAAA;AAAA,QACC,MAAM,YAAY,MAAM,IAAI,KAAK;AAAA,QACjC,MAAM,MAAM;AAAA,QACZ,aAAa,MAAM;AAAA,QACnB;AAAA,QACA,OAAO;AAAA,QACP,UAAU,CAAC,MAAM,SAAS,EAAE,OAAO,KAAK;AAAA;AAAA,IAC1C;AAAA,EAEJ;AAEA,SACE,qBAAC,OAAE,WAAU,cAAa,cAAY,MAAM,KAAK,wBAAsB,MAAM,KAC3E;AAAA,yBAAC,WAAM,uBAAoB,SACxB;AAAA,YAAM;AAAA,MACN,WAAW,OAAO;AAAA,OACrB;AAAA,IACA,oBAAC,QAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,KACH;AAEJ;","names":[]}
package/dist/index.d.ts CHANGED
@@ -1,11 +1,12 @@
1
1
  import { PageMetaJson, ContentBlock, DeliveredLayout, FieldStyles, SiteSeoDefaults, BlockStyle, FieldStyle, DeliveryComponent } from '@bettercms-ai/types';
2
2
  export { DeliveredLayout, LinkValue, PageMetaJson, RESPONSIVE_CSS, SiteSeoDefaults, linkHref } from '@bettercms-ai/types';
3
3
  import { Metadata } from 'next';
4
- import { SeoInput, SeoLocation, DeliveryForm } from '@bettercms-ai/sdk';
5
- export { ResolvedSeo, SeoInput, resolveSeo } from '@bettercms-ai/sdk';
4
+ import { SeoInput, SeoLocation } from '@bettercms-ai/sdk/seo';
5
+ export { ResolvedSeo, SeoInput, resolveSeo } from '@bettercms-ai/sdk/seo';
6
6
  import { CSSProperties, ReactElement, ReactNode, ElementType, ImgHTMLAttributes } from 'react';
7
7
  import { ImageSource, ImageFormat, ImageFit } from '@bettercms-ai/image-url';
8
8
  export { ImageCrop, ImageFit, ImageFocal, ImageFormat, ImageSource, ImageUrlBuilder, ImageValueUrlOptions, imageUrl, default as imageUrlBuilder, imageValueObjectPosition, imageValueUrl } from '@bettercms-ai/image-url';
9
+ import { DeliveryForm } from '@bettercms-ai/sdk';
9
10
  import { DeliveryForm as DeliveryForm$1 } from '@bettercms-ai/sdk/read';
10
11
  import * as react_jsx_runtime from 'react/jsx-runtime';
11
12
  import { BcmsChangeEvent } from '@bettercms-ai/sdk/live';
@@ -106,17 +107,6 @@ interface EntryList<TFields> {
106
107
  hasPreviousPage: boolean;
107
108
  }
108
109
 
109
- /**
110
- * createBetterCMS — the Next.js delivery client.
111
- *
112
- * Reads run through the standard `fetch`, which the Next.js App Router patches to
113
- * participate in the data cache. We pass `next: { revalidate, tags }` so content is
114
- * cached/ISR'd and can be invalidated on publish via `revalidateTag()`.
115
- *
116
- * The raw Delivery API response is normalized into `BetterCMSEntry<TFields>` so the
117
- * return types match what @bettercms-ai/codegen generates.
118
- */
119
-
120
110
  /** A published page with its block_json — feed `blocks` to `<BcmsBlocks>`.
121
111
  * The SEO fields (FLO-302) feed `buildMetadata` for the route's `generateMetadata`. */
122
112
  interface BetterCMSPage {
@@ -591,6 +581,18 @@ declare function readPages(path?: string): SnapshotPage[];
591
581
  /** Find a single published page by `slug` from the Action snapshot. */
592
582
  declare function getPage(slug: string, path?: string): SnapshotPage | undefined;
593
583
 
584
+ type PageSnapshot = Record<string, unknown> & {
585
+ slug?: string;
586
+ };
587
+ interface BcmsPageOptions {
588
+ /** Override what `NEXT_PUBLIC_BCMS_*` / `BCMS_*` / `bcms-content.json` say. */
589
+ apiUrl?: string;
590
+ workspace?: string;
591
+ projectId?: string;
592
+ }
593
+ /** The page `slug`'s values (see the module doc for the order). Never throws; `snapshot` is the floor. */
594
+ declare function bcmsPage(slug: string, snapshot?: PageSnapshot, opts?: BcmsPageOptions): Promise<PageSnapshot>;
595
+
594
596
  /**
595
597
  * Build-time reader for the reusable components the deploy Action injects into the
596
598
  * content snapshot (`bcms-content.json` → `components`). Mirrors `forms-read.ts`.
@@ -684,7 +686,7 @@ interface SectionsData {
684
686
  /** The page's published blocks. Null when there is no snapshot or the page is not in it. */
685
687
  blocks: ContentBlock[] | null;
686
688
  components: DeliveryComponent[];
687
- forms: DeliveryForm[];
689
+ forms: DeliveryForm$1[];
688
690
  }
689
691
  /** Which of two pages that share a slug is read. */
690
692
  interface SectionsRead {
@@ -868,6 +870,22 @@ declare function defineBetterCMSLive(config: BetterCMSLiveConfig): {
868
870
  liveSrc: string;
869
871
  };
870
872
 
873
+ /**
874
+ * createRevalidateRoute — App Router POST handler for the backend's revalidation webhook: every
875
+ * tag and every page path the publish changed is revalidated. This is the production live path
876
+ * (publish → backend webhook → revalidate the ISR cache).
877
+ *
878
+ * import { createRevalidateRoute } from "@bettercms-ai/next";
879
+ * export const { POST } = createRevalidateRoute();
880
+ *
881
+ * The `X-BetterCMS-Signature` HMAC-SHA256 header is verified against the raw body with `secret`,
882
+ * else `BCMS_REVALIDATE_SECRET` (the one name, matching the project's revalidation secret).
883
+ *
884
+ * The same route answers a deploy target in "revalidate" mode (a site hosted elsewhere): that call
885
+ * signs with `X-BCMS-Signature` and names the changed `paths` and `tags` at the top level, and
886
+ * neither means everything the site caches. Read as nothing, it answered 200 with nothing refreshed, and the
887
+ * platform took the publish as delivered.
888
+ */
871
889
  interface RevalidateRouteConfig {
872
890
  /** Shared secret matching the project's revalidation webhook secret. Defaults to `BCMS_REVALIDATE_SECRET`. */
873
891
  secret?: string;
@@ -887,4 +905,4 @@ interface VisualEditingProps {
887
905
  studioUrl?: string;
888
906
  }
889
907
 
890
- export { type BcmsBlocksProps, BcmsButton, type BcmsButtonProps, BcmsDraftMarker, BcmsEmbedScripts, BcmsField, type BcmsFieldProps, type BcmsFormProps, BcmsImage, type BcmsImageProps, type BcmsLiveProps, type BcmsSectionProps, type BcmsSectionsProps, type BetterCMSConfig, type BetterCMSEntry, BetterCMSError, type BetterCMSLiveConfig, type BetterCMSNext, type BetterCMSPage, type ContentSnapshot, type ContentSource, DEFAULT_SNAPSHOT_FILE, type DraftModeRouteConfig, type EntryFieldAttrs, type EntryList, type EntryRef, type EntryTransform, type FieldAttrs, type GetEntryOptions, type ListEntriesOptions, type LlmsModel, type LlmsModelField, type LlmsTxtOptions, type LlmsTxtRouteConfig, PREVIEW_TOKEN_COOKIE, type ReadOptions, type RevalidateRouteConfig, SNAPSHOT_VERSION, type SectionColumnAttrs, type SectionRootAttrs, type SectionRootBlock, type SectionRootProps, type SectionsData, type SectionsRead, type SnapshotForms, type SnapshotPage, type VisualEditingProps, buildMetadata, buildSnapshot, createBetterCMS, createDisableDraftRoute, createDraftModeRoute, createRevalidateRoute, defineBetterCMSLive, entryAttrs, entryField, fetchModels, fieldAttrs, fieldStyleOf, generateLlmsTxt, getBranchPreview, getComponent, getContent, getForm, getPage, getPreviewBranch, getPreviewToken, isDraftEnabled, llmsTxtRoute, parseSnapshot, readComponents, readForms, readPages, readSnapshot, sectionColumnAttrs, sectionRootAttrs, sectionsFor, sectionsServerSideProps, sectionsStaticProps, serializeSnapshot, writeSnapshot };
908
+ export { type BcmsBlocksProps, BcmsButton, type BcmsButtonProps, BcmsDraftMarker, BcmsEmbedScripts, BcmsField, type BcmsFieldProps, type BcmsFormProps, BcmsImage, type BcmsImageProps, type BcmsLiveProps, type BcmsPageOptions, type BcmsSectionProps, type BcmsSectionsProps, type BetterCMSConfig, type BetterCMSEntry, BetterCMSError, type BetterCMSLiveConfig, type BetterCMSNext, type BetterCMSPage, type ContentSnapshot, type ContentSource, DEFAULT_SNAPSHOT_FILE, type DraftModeRouteConfig, type EntryFieldAttrs, type EntryList, type EntryRef, type EntryTransform, type FieldAttrs, type GetEntryOptions, type ListEntriesOptions, type LlmsModel, type LlmsModelField, type LlmsTxtOptions, type LlmsTxtRouteConfig, PREVIEW_TOKEN_COOKIE, type PageSnapshot, type ReadOptions, type RevalidateRouteConfig, SNAPSHOT_VERSION, type SectionColumnAttrs, type SectionRootAttrs, type SectionRootBlock, type SectionRootProps, type SectionsData, type SectionsRead, type SnapshotForms, type SnapshotPage, type VisualEditingProps, bcmsPage, buildMetadata, buildSnapshot, createBetterCMS, createDisableDraftRoute, createDraftModeRoute, createRevalidateRoute, defineBetterCMSLive, entryAttrs, entryField, fetchModels, fieldAttrs, fieldStyleOf, generateLlmsTxt, getBranchPreview, getComponent, getContent, getForm, getPage, getPreviewBranch, getPreviewToken, isDraftEnabled, llmsTxtRoute, parseSnapshot, readComponents, readForms, readPages, readSnapshot, sectionColumnAttrs, sectionRootAttrs, sectionsFor, sectionsServerSideProps, sectionsStaticProps, serializeSnapshot, writeSnapshot };
package/dist/index.js CHANGED
@@ -1,6 +1,25 @@
1
+ // src/node-builtins.ts
2
+ function builtin(id) {
3
+ const proc = globalThis.process;
4
+ if (typeof proc?.getBuiltinModule !== "function") {
5
+ throw new Error(`@bettercms-ai/next: ${id} is read on the server only, through process.getBuiltinModule (Node 20.16+ or 22.3+).`);
6
+ }
7
+ return proc.getBuiltinModule(id);
8
+ }
9
+ var nodeFs = () => builtin("node:fs");
10
+ var nodePath = () => builtin("node:path");
11
+ var readText = (path) => nodeFs().readFileSync(nodePath().resolve(path), "utf8");
12
+ function readTextOrNull(path) {
13
+ const fs = nodeFs();
14
+ const file = nodePath().resolve(path);
15
+ try {
16
+ return fs.readFileSync(file, "utf8");
17
+ } catch {
18
+ return null;
19
+ }
20
+ }
21
+
1
22
  // src/client.ts
2
- import { readFileSync } from "fs";
3
- import { resolve } from "path";
4
23
  import { resolveBcmsConfig } from "@bettercms-ai/sdk/config";
5
24
  import { BRANCH_SIGNATURE_HEADER } from "@bettercms-ai/sdk/draft";
6
25
 
@@ -37,20 +56,23 @@ function mapEntry(raw) {
37
56
  updatedAt: raw.updatedAt ?? null
38
57
  };
39
58
  }
40
- function configFromSite(config) {
59
+ function siteConfig(options = {}) {
41
60
  const env = typeof process !== "undefined" ? process.env : {};
42
- const { config: site, missing } = resolveBcmsConfig({
43
- options: { workspace: config.workspace, projectId: config.projectId },
61
+ return resolveBcmsConfig({
62
+ options,
44
63
  env,
45
64
  prefixes: ["NEXT_PUBLIC_", ""],
46
65
  snapshot: () => {
47
66
  try {
48
- return JSON.parse(readFileSync(resolve(env.BCMS_CONTENT_FILE || "bcms-content.json"), "utf8"));
67
+ return JSON.parse(readText(env.BCMS_CONTENT_FILE || "bcms-content.json"));
49
68
  } catch {
50
69
  return {};
51
70
  }
52
71
  }
53
72
  });
73
+ }
74
+ function configFromSite(config) {
75
+ const { config: site, missing } = siteConfig({ workspace: config.workspace, projectId: config.projectId });
54
76
  if (missing.includes("workspace")) {
55
77
  throw new Error(
56
78
  "[@bettercms-ai/next] No workspace: pass createBetterCMS({ workspace }), set NEXT_PUBLIC_BCMS_WORKSPACE, or run `bettercms pull-content` before the build so bcms-content.json is present."
@@ -221,7 +243,7 @@ function createBetterCMS(options = {}) {
221
243
  }
222
244
 
223
245
  // src/metadata.ts
224
- import { resolveSeo } from "@bettercms-ai/sdk";
246
+ import { resolveSeo } from "@bettercms-ai/sdk/seo";
225
247
  function withSiteUrlFallback(page, location) {
226
248
  const siteUrl = location.siteUrl || (typeof process !== "undefined" ? process.env.BETTERCMS_SITE_URL : void 0);
227
249
  const slugPath2 = page.slug ? page.slug === "home" ? "/" : `/${page.slug.replace(/^\/+/, "")}` : void 0;
@@ -312,11 +334,9 @@ function entryField(entry, path, opts) {
312
334
  }
313
335
 
314
336
  // src/index.ts
315
- import { resolveSeo as resolveSeo2 } from "@bettercms-ai/sdk";
337
+ import { resolveSeo as resolveSeo2 } from "@bettercms-ai/sdk/seo";
316
338
 
317
339
  // src/snapshot.ts
318
- import { readFileSync as readFileSync2, writeFileSync, mkdirSync } from "fs";
319
- import { dirname, resolve as resolve2 } from "path";
320
340
  var SNAPSHOT_VERSION = 1;
321
341
  var DEFAULT_SNAPSHOT_FILE = "bcms-content.json";
322
342
  function serializeSnapshot(snapshot) {
@@ -362,20 +382,20 @@ function isPlatformSnapshot(parsed) {
362
382
  return typeof snap?.$schema === "string" && snap.$schema.startsWith("bcms-content/") && typeof snap.collections === "object" && snap.collections !== null;
363
383
  }
364
384
  function writeSnapshot(path, snapshot) {
365
- const out = resolve2(process.cwd(), path);
385
+ const out = nodePath().resolve(path);
366
386
  try {
367
- if (isPlatformSnapshot(JSON.parse(readFileSync2(out, "utf8")))) return false;
387
+ if (isPlatformSnapshot(JSON.parse(readText(out)))) return false;
368
388
  } catch {
369
389
  }
370
- mkdirSync(dirname(out), { recursive: true });
371
- writeFileSync(out, serializeSnapshot(snapshot), "utf8");
390
+ const fs = nodeFs();
391
+ fs.mkdirSync(nodePath().dirname(out), { recursive: true });
392
+ fs.writeFileSync(out, serializeSnapshot(snapshot), "utf8");
372
393
  return true;
373
394
  }
374
395
  function readSnapshot(path) {
375
- const out = resolve2(process.cwd(), path);
376
396
  let json;
377
397
  try {
378
- json = readFileSync2(out, "utf8");
398
+ json = readText(path);
379
399
  } catch (err) {
380
400
  if (err?.code === "ENOENT") return null;
381
401
  throw err;
@@ -428,7 +448,7 @@ function getContent(config, opts = {}) {
428
448
  listEntries: (model) => live.listEntries(model, { revalidate: false })
429
449
  };
430
450
  }
431
- const resolved = resolve2(process.cwd(), path);
451
+ const resolved = nodePath().resolve(path);
432
452
  function load() {
433
453
  const cached = snapshotCache.get(resolved);
434
454
  if (cached) return cached;
@@ -633,15 +653,9 @@ import {
633
653
  } from "@bettercms-ai/image-url";
634
654
 
635
655
  // src/forms-read.ts
636
- import { readFileSync as readFileSync3 } from "fs";
637
- import { resolve as resolve3 } from "path";
638
656
  function readForms(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
639
- let raw;
640
- try {
641
- raw = readFileSync3(resolve3(process.cwd(), path), "utf8");
642
- } catch {
643
- return { forms: [], turnstileSiteKey: null };
644
- }
657
+ const raw = readTextOrNull(path);
658
+ if (raw === null) return { forms: [], turnstileSiteKey: null };
645
659
  const snap = JSON.parse(raw);
646
660
  return { forms: snap.forms ?? [], turnstileSiteKey: snap.turnstileSiteKey ?? null };
647
661
  }
@@ -650,15 +664,9 @@ function getForm(idOrName, path) {
650
664
  }
651
665
 
652
666
  // src/pages-read.ts
653
- import { readFileSync as readFileSync4 } from "fs";
654
- import { resolve as resolve4 } from "path";
655
667
  function readPages(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
656
- let raw;
657
- try {
658
- raw = readFileSync4(resolve4(process.cwd(), path), "utf8");
659
- } catch {
660
- return [];
661
- }
668
+ const raw = readTextOrNull(path);
669
+ if (raw === null) return [];
662
670
  const snap = JSON.parse(raw);
663
671
  return snap.pages ?? [];
664
672
  }
@@ -666,16 +674,84 @@ function getPage(slug, path) {
666
674
  return readPages(path).find((p) => p.slug === slug);
667
675
  }
668
676
 
677
+ // src/page-content.ts
678
+ import { readPublishedContent } from "@bettercms-ai/sdk/read";
679
+ var isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
680
+ var valuesOf = (row) => {
681
+ const { $html: _authored, ...values } = isRecord(row.data) ? row.data : {};
682
+ return { ...values, slug: row.slug };
683
+ };
684
+ var pageTags = (workspace, slug) => [
685
+ `bcms:${workspace}:all`,
686
+ `bcms:${workspace}:entry:${slug}`,
687
+ `bcms:${workspace}:page:${slug}`
688
+ ];
689
+ function pageFromContent(content, slug, stub = {}) {
690
+ const collections = isRecord(content) && isRecord(content.collections) ? content.collections : {};
691
+ const rows = Object.values(collections).flatMap((r) => Array.isArray(r) ? r : []).filter((r) => isRecord(r) && typeof r.slug === "string");
692
+ const html = (row) => isRecord(row.$html) ? { $html: row.$html } : {};
693
+ const entries = {};
694
+ for (const row of rows) {
695
+ if (row.slug in entries || isRecord(row._meta) && row._meta.page === true) continue;
696
+ entries[row.slug] = isRecord(row.data) ? { ...valuesOf(row), ...html(row) } : row;
697
+ }
698
+ const own = rows.find((r) => r.slug === slug);
699
+ const withHtml = rows.find((r) => r.slug === slug && isRecord(r.$html));
700
+ const base = own ? isRecord(own.data) ? { ...valuesOf(own), ...withHtml ? html(withHtml) : {} } : own : null;
701
+ const values = base ? "entries" in base ? base : { ...base, entries } : Object.keys(entries).length ? { slug, entries } : null;
702
+ const listed = isRecord(content) && Array.isArray(content.pages) ? content.pages : [];
703
+ const page = listed.find((p) => isRecord(p) && p.slug === slug);
704
+ let out = values;
705
+ if (page && isRecord(page.fieldStyles)) out = { ...out ?? { slug }, fieldStyles: page.fieldStyles };
706
+ if (page && "blocks" in stub && Array.isArray(page.blocks)) out = { ...out ?? { slug }, blocks: page.blocks };
707
+ return out;
708
+ }
709
+ function overlay(row, snapshot) {
710
+ const { entries, fieldStyles, blocks } = snapshot;
711
+ return { ...valuesOf(row), ...entries ? { entries } : {}, ...fieldStyles ? { fieldStyles } : {}, ...blocks ? { blocks } : {} };
712
+ }
713
+ async function readRow(url, init, draft) {
714
+ const res = await fetch(url, { ...init, headers: { Accept: "application/json" } });
715
+ if (!res.ok) return null;
716
+ const body = await res.json();
717
+ const row = draft ? body.data : body;
718
+ return isRecord(row) && isRecord(row.data) ? row : null;
719
+ }
720
+ var fellBack = /* @__PURE__ */ new Set();
721
+ function sayFellBack(slug, snapshot) {
722
+ if (typeof process === "undefined" || process.env.NODE_ENV !== "production" || fellBack.has(slug)) return;
723
+ fellBack.add(slug);
724
+ const stub = Object.entries(snapshot).every(([key, v]) => key === "slug" || key === "blocks" && Array.isArray(v) && v.length === 0);
725
+ console.warn(
726
+ stub ? `[bcms] CONTENT_STUB ${slug}: the build has no published content for this page; it renders the source's copy` : `[bcms] CONTENT_SNAPSHOT ${slug}: no live or published content could be read; it renders the snapshot it was built with`
727
+ );
728
+ }
729
+ async function bcmsPage(slug, snapshot = {}, opts = {}) {
730
+ const { config } = siteConfig(opts);
731
+ if (config.apiUrl && config.workspace) {
732
+ try {
733
+ const token = await isDraftEnabled() ? await getPreviewToken() : null;
734
+ const project = config.projectId ? `?projectId=${encodeURIComponent(config.projectId)}` : "";
735
+ const row = token ? await readRow(`${config.apiUrl}/api/v1/preview/${encodeURIComponent(slug)}?token=${encodeURIComponent(token)}`, { cache: "no-store" }, true) : await readRow(
736
+ `${config.apiUrl}/api/v1/delivery/${encodeURIComponent(config.workspace)}/content-entries/${encodeURIComponent(slug)}${project}`,
737
+ { next: { revalidate: false, tags: pageTags(config.workspace, slug) } },
738
+ false
739
+ );
740
+ if (row) return overlay(row, snapshot);
741
+ } catch (err) {
742
+ if (isRecord(err) && "digest" in err) throw err;
743
+ }
744
+ }
745
+ const published = pageFromContent(readPublishedContent(), slug, snapshot);
746
+ if (published) return published;
747
+ sayFellBack(slug, snapshot);
748
+ return snapshot;
749
+ }
750
+
669
751
  // src/components-read.ts
670
- import { readFileSync as readFileSync5 } from "fs";
671
- import { resolve as resolve5 } from "path";
672
752
  function readComponents(path = process.env.BCMS_CONTENT_FILE || "bcms-content.json") {
673
- let raw;
674
- try {
675
- raw = readFileSync5(resolve5(process.cwd(), path), "utf8");
676
- } catch {
677
- return [];
678
- }
753
+ const raw = readTextOrNull(path);
754
+ if (raw === null) return [];
679
755
  const snap = JSON.parse(raw);
680
756
  return snap.components ?? [];
681
757
  }
@@ -686,22 +762,43 @@ function getComponent(idOrSlug, path) {
686
762
  }
687
763
 
688
764
  // src/sections-read.ts
689
- import { readPublishedContent } from "@bettercms-ai/sdk";
765
+ import { readPublishedContent as readPublishedContent2 } from "@bettercms-ai/sdk/read";
690
766
  function pageRow(pages, page, read) {
691
767
  const rows = (Array.isArray(pages) ? pages : []).filter((p) => p?.slug === page);
692
768
  const template = rows.find((row) => row.template === true);
693
769
  return read?.template ? template : rows.find((row) => row.template !== true) ?? rows[0];
694
770
  }
771
+ function idsUnder(value, key, into = /* @__PURE__ */ new Set()) {
772
+ if (Array.isArray(value)) for (const item of value) idsUnder(item, key, into);
773
+ else if (value && typeof value === "object") {
774
+ for (const [k, v] of Object.entries(value)) {
775
+ if (k === key && typeof v === "string") into.add(v);
776
+ else idsUnder(v, key, into);
777
+ }
778
+ }
779
+ return into;
780
+ }
781
+ function referencedComponents(blocks, components) {
782
+ const byId = new Map(components.map((c) => [c.id, c]));
783
+ const reached = /* @__PURE__ */ new Set();
784
+ const queue = [...idsUnder(blocks, "componentId")];
785
+ for (let id = queue.pop(); id !== void 0; id = queue.pop()) {
786
+ const def = byId.get(id);
787
+ if (!def || reached.has(id)) continue;
788
+ reached.add(id);
789
+ queue.push(...idsUnder(def, "componentId"));
790
+ }
791
+ return components.filter((c) => reached.has(c.id));
792
+ }
793
+ var listOf = (value) => Array.isArray(value) ? value : [];
695
794
  function sectionsFor(page, read) {
696
- const snapshot = readPublishedContent();
795
+ const snapshot = readPublishedContent2();
697
796
  const row = pageRow(snapshot?.pages, page, read);
698
- const blocks = row?.blocks ?? row?.blockJson;
699
- return {
700
- page,
701
- blocks: Array.isArray(blocks) ? blocks : null,
702
- components: Array.isArray(snapshot?.components) ? snapshot.components : [],
703
- forms: Array.isArray(snapshot?.forms) ? snapshot.forms : []
704
- };
797
+ const listed = row?.blocks ?? row?.blockJson;
798
+ const blocks = Array.isArray(listed) ? listed : null;
799
+ const components = referencedComponents(blocks ?? [], listOf(snapshot?.components));
800
+ const formIds = idsUnder([blocks, components], "formId");
801
+ return { page, blocks, components, forms: listOf(snapshot?.forms).filter((f) => formIds.has(f.id)) };
705
802
  }
706
803
  function sectionsStaticProps(page, own, read) {
707
804
  return async (context) => {
@@ -813,11 +910,13 @@ function defineBetterCMSLive(config) {
813
910
  }
814
911
 
815
912
  // src/revalidate-route.ts
816
- import { createHmac, timingSafeEqual } from "crypto";
817
- function safeEqual(a, b) {
818
- const ab = Buffer.from(a);
819
- const bb = Buffer.from(b);
820
- return ab.length === bb.length && timingSafeEqual(ab, bb);
913
+ async function signatureValid(secret, body, header) {
914
+ const hex = /^sha256=([0-9a-f]{64})$/.exec(header)?.[1];
915
+ if (!hex) return false;
916
+ const utf8 = new TextEncoder();
917
+ const key = await crypto.subtle.importKey("raw", utf8.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
918
+ const signature = Uint8Array.from(hex.match(/../g), (byte) => parseInt(byte, 16));
919
+ return crypto.subtle.verify("HMAC", key, signature, utf8.encode(body));
821
920
  }
822
921
  function slugPath(slug) {
823
922
  if (slug.startsWith("//") || /[\s?#\\]/.test(slug)) return null;
@@ -829,9 +928,8 @@ function createRevalidateRoute(config = {}) {
829
928
  const body = await request.text();
830
929
  const secret = config.secret ?? process.env.BCMS_REVALIDATE_SECRET;
831
930
  if (secret) {
832
- const provided = request.headers.get("x-bettercms-signature") ?? "";
833
- const expected = `sha256=${createHmac("sha256", secret).update(body).digest("hex")}`;
834
- if (!safeEqual(provided, expected)) {
931
+ const header = request.headers.get("x-bettercms-signature") ?? request.headers.get("x-bcms-signature") ?? "";
932
+ if (!await signatureValid(secret, body, header)) {
835
933
  return new Response("Invalid signature", { status: 401 });
836
934
  }
837
935
  }
@@ -842,13 +940,16 @@ function createRevalidateRoute(config = {}) {
842
940
  return new Response("Invalid JSON", { status: 400 });
843
941
  }
844
942
  const strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
845
- const tags = strings(payload.data?.tags);
846
- const paths = [...new Set(strings(payload.data?.slugs).map(slugPath).filter((p) => p !== null))];
943
+ const tags = [.../* @__PURE__ */ new Set([...strings(payload.data?.tags), ...strings(payload.tags)])];
944
+ const changed = [...strings(payload.data?.slugs), ...strings(payload.paths)];
945
+ const paths = [...new Set(changed.map(slugPath).filter((p) => p !== null))];
946
+ const everything = payload.event === "revalidate" && changed.length === 0 && tags.length === 0;
847
947
  const { revalidateTag, revalidatePath } = await import("next/cache");
848
948
  const tag = revalidateTag;
849
949
  for (const t of tags) tag(t, { expire: 0 });
850
950
  for (const p of paths) revalidatePath(p);
851
- return Response.json({ revalidated: true, tags, paths });
951
+ if (everything) revalidatePath("/", "layout");
952
+ return Response.json({ revalidated: true, tags, paths: everything ? ["/"] : paths });
852
953
  }
853
954
  return { POST };
854
955
  }
@@ -863,6 +964,7 @@ export {
863
964
  PREVIEW_TOKEN_COOKIE,
864
965
  RESPONSIVE_CSS,
865
966
  SNAPSHOT_VERSION,
967
+ bcmsPage,
866
968
  buildMetadata,
867
969
  buildSnapshot,
868
970
  createBetterCMS,