Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(cms): send pages to a brand's Framer collection as draft items (#1331) (#1576)

Cihan6f2e619df8c1
diff --git a/server/src/lib/cms/framer-delivery.js b/server/src/lib/cms/framer-delivery.js
new file mode 100644
index 000000000..9b6e0b0d1
--- /dev/null
+++ b/server/src/lib/cms/framer-delivery.js
@@ -0,0 +1,109 @@
+import supabaseAdmin from '../../config/supabase.js';
+import { logger } from '../logger.js';
+import { readCmsCredentials } from './credentials.js';
+import { FramerError, writeItem } from './framer.js';
+import { framerFieldData, framerSlug, toFramerHtml } from './framer-items.js';
+
+/**
+ * Send to CMS to Framer (#1331, phase 2; 00295): a page goes to the brand's
+ * Framer collection as a draft item, or updates the item its last Framer
+ * send made in that collection, its draft state as it is. Nothing is
+ * published: Framer's own publish puts the site, its items with it, live.
+ * content-delivery.js reserves, writes and batches the deliveries as it
+ * does for the webhook.
+ */
+
+/**
+ * The item the page's last Framer send made in this collection, if any,
+ * whatever became of that send: an item since deleted in Framer is looked
+ * for and not found, and a new one is made (writeItem).
+ */
+async function lastItem(draftId, collectionId, deliveryId) {
+ const { data, error } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .select('external_id')
+ .eq('draft_id', draftId)
+ .eq('target', 'framer')
+ .eq('target_collection', collectionId)
+ .not('external_id', 'is', null)
+ .neq('id', deliveryId)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ return data?.external_id ?? null;
+}
+
+/**
+ * The key the send was refused with: Settings asks for a new one. Only the
+ * connection as the send read it: one connected again meanwhile keeps its
+ * new key.
+ */
+async function markRefused(connection) {
+ const { error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })
+ .eq('id', connection.id)
+ .eq('provider', 'framer')
+ .eq('updated_at', connection.updated_at);
+ if (error) logger.warn({ err: error }, '[content-delivery] framer refusal not kept');
+}
+
+/**
+ * Sends one page to the brand's Framer collection. What went wrong is said
+ * in our words. `connect` replaces framer-api's in tests.
+ *
+ * @param {{ delivery: { id: string }, page: object, html: string, jsonLd?: object[],
+ * connection: { id: string, site_id: string, collection_id: string, field_map: object,
+ * updated_at: string }, connect?: Function }} input
+ * @returns {Promise<{ taken: boolean, failure?: string, refused?: boolean, externalId?: string,
+ * collectionId?: string, updated?: boolean, live?: boolean, changed?: { images: number } }>}
+ * live: the item updated isn't a draft in Framer, so the page goes live with the site's
+ * next publish
+ */
+export async function sendToFramer({ delivery, page, html, jsonLd, connection, connect }) {
+ const collectionId = connection.collection_id;
+ const { html: body, changed } = toFramerHtml(html);
+ const slug = framerSlug(page);
+ const fieldData = framerFieldData({ page, body, jsonLd }, connection.field_map ?? {});
+ try {
+ const credentials = await readCmsCredentials(connection.id);
+ if (!credentials?.apiKey) {
+ await markRefused(connection);
+ return {
+ taken: false,
+ failure: 'The Framer API key can’t be read. Connect Framer again.',
+ refused: true,
+ };
+ }
+ const before = await lastItem(page.draftId, collectionId, delivery.id);
+ const written = await writeItem(
+ connection.site_id,
+ credentials.apiKey,
+ collectionId,
+ { before, slug, fieldData, titleField: connection.field_map?.title ?? null },
+ { connect },
+ );
+ return {
+ taken: true,
+ externalId: written.id,
+ collectionId,
+ updated: written.updated,
+ live: written.live,
+ changed,
+ };
+ } catch (err) {
+ if (err instanceof FramerError) {
+ if (err.code === 'auth_failed') {
+ await markRefused(connection);
+ return { taken: false, failure: err.message, refused: true };
+ }
+ return { taken: false, failure: err.message };
+ }
+ logger.warn(
+ { err: { name: err?.name }, deliveryId: delivery.id },
+ '[content-delivery] framer send failed',
+ );
+ return { taken: false, failure: 'Framer could not be reached' };
+ }
+}
diff --git a/server/src/lib/cms/framer-delivery.test.js b/server/src/lib/cms/framer-delivery.test.js
new file mode 100644
index 000000000..bd1e630f3
--- /dev/null
+++ b/server/src/lib/cms/framer-delivery.test.js
@@ -0,0 +1,205 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Send to CMS to Framer (#1331, phase 2; 00295): a page goes to the brand's
+ * collection as a draft item, or updates the item its last send made there.
+ */
+
+let previous;
+const queries = [];
+const updates = [];
+vi.mock('../../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const q = { table, filters: [] };
+ const chain = {
+ select: () => chain,
+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),
+ neq: (col, value) => (q.filters.push(['neq', col, value]), chain),
+ not: (col, op, value) => (q.filters.push(['not', col, op, value]), chain),
+ order: () => chain,
+ limit: () => chain,
+ update: (row) => (updates.push({ table, row, filters: q.filters }), chain),
+ maybeSingle: async () => {
+ queries.push(q);
+ return { data: previous ? { external_id: previous } : null, error: null };
+ },
+ then: (resolve) => resolve({ data: null, error: null }),
+ };
+ return chain;
+ },
+ },
+}));
+const logged = [];
+vi.mock('../logger.js', () => ({
+ logger: { warn: (...args) => logged.push(JSON.stringify(args)) },
+}));
+let credentials;
+vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));
+const framer = { writeItem: vi.fn() };
+vi.mock('./framer.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ writeItem: (...args) => framer.writeItem(...args),
+}));
+
+const { sendToFramer } = await import('./framer-delivery.js');
+const actual = await vi.importActual('./framer.js');
+const { FramerError } = actual;
+
+const PROJECT = 'AbCdEfGhIj0123456789';
+const KEY = 'fr_key_0123456789abcdefSECRET';
+const connection = {
+ id: 'cn1',
+ brand_id: 'b1',
+ site_id: PROJECT,
+ collection_id: 'cBlog',
+ field_map: { title: 'fTitle', body: 'fBody', metaDescription: 'fDesc' },
+ updated_at: '2026-10-27T09:00:00Z',
+};
+const DELIVERY = 'd2345678-0000-0000-0000-000000000000';
+const send = (over = {}, extra = {}) =>
+ sendToFramer({
+ delivery: { id: DELIVERY },
+ page: {
+ draftId: 'dr1',
+ title: 'Cold brew at home',
+ slug: 'cold-brew-at-home',
+ metaTitle: '',
+ metaDescription: 'How to make it.',
+ ...over,
+ },
+ html: '<h2>Why</h2><p>Smooth.</p><table><tr><td>a</td></tr></table><img src="https://x.example/a.png"><script type="application/ld+json">{"@type":"Article"}</script>',
+ jsonLd: [{ '@type': 'Article' }],
+ connection,
+ ...extra,
+ });
+const FIELD_DATA = {
+ fTitle: { type: 'string', value: 'Cold brew at home' },
+ fBody: {
+ type: 'formattedText',
+ value: '<h2>Why</h2><p>Smooth.</p><table><tbody><tr><td>a</td></tr></tbody></table>',
+ contentType: 'html',
+ },
+ fDesc: { type: 'string', value: 'How to make it.' },
+};
+const refusal = {
+ table: 'brand_cms_connections',
+ row: { status: 'auth_failed', updated_at: expect.any(String) },
+ filters: [
+ ['eq', 'id', 'cn1'],
+ ['eq', 'provider', 'framer'],
+ ['eq', 'updated_at', '2026-10-27T09:00:00Z'],
+ ],
+};
+
+beforeEach(() => {
+ previous = null;
+ credentials = { apiKey: KEY };
+ queries.length = 0;
+ updates.length = 0;
+ logged.length = 0;
+ framer.writeItem.mockReset().mockResolvedValue({ id: 'item-new', updated: false, live: false });
+});
+
+describe('sendToFramer', () => {
+ it('makes a draft item of a page sent for the first time', async () => {
+ expect(await send()).toEqual({
+ taken: true,
+ externalId: 'item-new',
+ collectionId: 'cBlog',
+ updated: false,
+ live: false,
+ changed: { images: 1 },
+ });
+ expect(framer.writeItem).toHaveBeenCalledWith(
+ PROJECT,
+ KEY,
+ 'cBlog',
+ { before: null, slug: 'cold-brew-at-home', fieldData: FIELD_DATA, titleField: 'fTitle' },
+ { connect: undefined },
+ );
+ // The page's last item is looked for in this collection, from any send that made one.
+ expect(queries[0].filters).toEqual([
+ ['eq', 'draft_id', 'dr1'],
+ ['eq', 'target', 'framer'],
+ ['eq', 'target_collection', 'cBlog'],
+ ['not', 'external_id', 'is', null],
+ ['neq', 'id', DELIVERY],
+ ]);
+ expect(updates).toEqual([]);
+ });
+
+ it('updates the item the page’s last send made, and says whether it is live', async () => {
+ previous = 'item-old';
+ framer.writeItem.mockResolvedValueOnce({ id: 'item-old', updated: true, live: true });
+ expect(await send()).toMatchObject({
+ taken: true,
+ externalId: 'item-old',
+ updated: true,
+ live: true,
+ });
+ expect(framer.writeItem.mock.calls[0][3].before).toBe('item-old');
+ });
+
+ it('asks to connect again when the key can’t be read, sending nothing', async () => {
+ credentials = null;
+ expect(await send()).toEqual({
+ taken: false,
+ failure: 'The Framer API key can’t be read. Connect Framer again.',
+ refused: true,
+ });
+ expect(framer.writeItem).not.toHaveBeenCalled();
+ expect(updates).toEqual([refusal]);
+ });
+
+ it('marks the key refused when Framer refuses it, and says what went wrong in its own words', async () => {
+ framer.writeItem.mockRejectedValueOnce(
+ new FramerError('auth_failed', 'Framer refused the API key.'),
+ );
+ expect(await send()).toEqual({
+ taken: false,
+ failure: 'Framer refused the API key.',
+ refused: true,
+ });
+ expect(updates).toEqual([refusal]);
+
+ framer.writeItem.mockRejectedValueOnce(
+ new FramerError('slug_taken', 'Another item in Blog has the slug "cold-brew-at-home".'),
+ );
+ expect(await send()).toEqual({
+ taken: false,
+ failure: 'Another item in Blog has the slug "cold-brew-at-home".',
+ });
+ expect(updates).toHaveLength(1);
+ });
+
+ it('says Framer couldn’t be reached on anything else, logging its name only', async () => {
+ framer.writeItem.mockRejectedValueOnce(new Error(`socket hang up with ${KEY}`));
+ expect(await send()).toEqual({ taken: false, failure: 'Framer could not be reached' });
+ expect(logged.join('')).not.toContain(KEY);
+ expect(updates).toEqual([]);
+ });
+
+ it('writes the item through one connection to the project', async () => {
+ framer.writeItem.mockImplementationOnce(actual.writeItem);
+ const addItems = vi.fn(async () => {});
+ const getItems = vi
+ .fn()
+ .mockResolvedValueOnce([])
+ .mockResolvedValueOnce([{ id: 'item-9', slug: 'cold-brew-at-home', draft: true }]);
+ const project = {
+ disconnect: vi.fn(async () => {}),
+ getCollections: vi.fn(async () => [
+ { id: 'cBlog', name: 'Blog', managedBy: 'user', getItems, addItems },
+ ]),
+ };
+ const connect = vi.fn(async () => project);
+ expect(await send({}, { connect })).toMatchObject({ taken: true, externalId: 'item-9' });
+ expect(connect).toHaveBeenCalledTimes(1);
+ expect(connect).toHaveBeenCalledWith(PROJECT, KEY);
+ expect(addItems).toHaveBeenCalledWith([
+ { slug: 'cold-brew-at-home', draft: true, fieldData: FIELD_DATA },
+ ]);
+ expect(project.disconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/lib/cms/framer-items.js b/server/src/lib/cms/framer-items.js
new file mode 100644
index 000000000..4ef1968b8
--- /dev/null
+++ b/server/src/lib/cms/framer-items.js
@@ -0,0 +1,204 @@
+import * as cheerio from 'cheerio';
+import {
+ NAME_CHARS,
+ cellHtml,
+ dropMedia,
+ dropUnkept,
+ imagesIn,
+ jsonLdText,
+ openingWords,
+ ownRows,
+ productsAsList,
+ settleRichText,
+ squash,
+ tableAsList,
+ webflowSlug,
+} from './webflow-items.js';
+
+/**
+ * A page as a Framer CMS item (Send to CMS #1331, phase 2; 00295): its body
+ * as Framer's formatted text keeps it, a slug Framer takes, and the item's
+ * fields by the brand's field map (brand_cms_connections.field_map: part →
+ * field id). The steps it shares with Webflow's rich text come from
+ * webflow-items.js.
+ */
+
+/**
+ * What Framer's formatted text is sent with; other elements give way to
+ * their content. Framer doesn't list what it keeps: these are the ones a
+ * page needs, tables and code among them.
+ */
+const KEEP = new Set([
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'p',
+ 'blockquote',
+ 'ul',
+ 'ol',
+ 'li',
+ 'a',
+ 'strong',
+ 'b',
+ 'em',
+ 'i',
+ 'sup',
+ 'sub',
+ 'br',
+ 'code',
+ 'pre',
+ 'table',
+ 'thead',
+ 'tbody',
+ 'tr',
+ 'th',
+ 'td',
+]);
+/** The blocks that stand at the top on their own: anything else there goes in a paragraph. */
+const BLOCKS = new Set([
+ 'h2',
+ 'h3',
+ 'h4',
+ 'h5',
+ 'h6',
+ 'p',
+ 'blockquote',
+ 'ul',
+ 'ol',
+ 'pre',
+ 'table',
+]);
+
+/** What a table cell keeps of its attributes: how many columns and rows it spans. */
+const SPANS = new Set(['colspan', 'rowspan']);
+const CELL_ATTRS = { th: SPANS, td: SPANS };
+
+/** A cell's spans, each a whole number from 1 to 1000; any other value goes. */
+function spansOf($, cell) {
+ return [...SPANS]
+ .map((name) => {
+ const value = String($(cell).attr(name) ?? '').trim();
+ const count = /^\d{1,4}$/.test(value) ? Number(value) : 0;
+ return count >= 1 && count <= 1000 ? ` ${name}="${count}"` : '';
+ })
+ .join('');
+}
+
+/**
+ * A table as Framer's formatted text keeps it: its own rows, a first row of
+ * header cells only as its head, each cell one line of words, links and
+ * emphasis (cellHtml) with its spans. Its caption goes before it as a
+ * paragraph; a table with no words goes.
+ */
+function framerTable($, table) {
+ const caption = $(table).children('caption').first();
+ const note = caption.length ? cellHtml($, caption[0]) : '';
+ const rows = ownRows($, table)
+ .map((row) =>
+ $(row)
+ .children('th, td')
+ .toArray()
+ .map((cell) => ({
+ head: cell.tagName.toLowerCase() === 'th',
+ spans: spansOf($, cell),
+ html: cellHtml($, cell),
+ })),
+ )
+ .filter((cells) => cells.some((cell) => cell.html));
+ const before = note ? `<p>${note}</p>` : '';
+ if (!rows.length) {
+ $(table).replaceWith(before);
+ return;
+ }
+ const head = rows[0].every((cell) => cell.head) ? rows.shift() : null;
+ const row = (cells) =>
+ `<tr>${cells.map(({ head: th, spans, html }) => (th ? `<th${spans}>${html}</th>` : `<td${spans}>${html}</td>`)).join('')}</tr>`;
+ $(table).replaceWith(
+ `${before}<table>${head ? `<thead>${row(head)}</thead>` : ''}${
+ rows.length ? `<tbody>${rows.map(row).join('')}</tbody>` : ''
+ }</table>`,
+ );
+}
+
+/**
+ * A page's publishable HTML as Framer's formatted text keeps it:
+ * - tables stay, a cell's colspan and rowspan with them (a table in a
+ * cell first reads as a line of it, as Webflow's lists read it);
+ * - a product card or grid becomes a list, a product an item ("Name
+ * $189.00"), as for Webflow: formatted text has no grid;
+ * - images and media are left out until workspace files (CHAT-06, #1331),
+ * a figure of one with its caption; scripts (the JSON-LD has its own
+ * field), embeds, forms and rules go too;
+ * - the page's title has its own field, so a heading 1 left in the body
+ * reads as a heading 2; code blocks stay;
+ * - a definition list and a caption are paragraphs, words outside a block
+ * and an item outside a list too;
+ * - any other element gives way to its content, and attributes go but a
+ * link's address and target.
+ * Returns the HTML, and how many images it left out (the send's note).
+ */
+export function toFramerHtml(html) {
+ const $ = cheerio.load(String(html ?? ''), null, false);
+ const changed = { images: imagesIn($) };
+ dropUnkept($);
+ // Inner tables first: a cell holding one reads it as a line.
+ for (const table of $('table').toArray().reverse()) {
+ if ($(table).parents('table').length) tableAsList($, table);
+ else framerTable($, table);
+ }
+ productsAsList($);
+ dropMedia($);
+ $('h1').each((_, el) => {
+ el.tagName = 'h2';
+ });
+ $('pre').each((_, el) => {
+ if (!$(el).text().trim()) $(el).remove();
+ });
+ $('dt, dd, figcaption').each((_, el) => {
+ $(el).replaceWith(`<p>${$(el).html() ?? ''}</p>`);
+ });
+ settleRichText($, { keep: KEEP, blocks: BLOCKS, attrs: CELL_ATTRS });
+ return { html: $.html().trim(), changed };
+}
+
+/**
+ * The item's slug: lowercase letters, digits and '-' (Webflow's, its '_' a
+ * '-'), from the page's slug, else its title, else the draft's own, the
+ * same every send (a slug in another script has nothing left).
+ */
+export function framerSlug(page) {
+ const slug = (value) => webflowSlug(String(value ?? '').replace(/_/g, '-'));
+ return slug(page.slug) ?? slug(page.title) ?? `page-${page.draftId}`;
+}
+
+/**
+ * The item's fields, each part of the page in the field the brand's map
+ * gives it, as Framer takes them: the title, meta title and description and
+ * JSON-LD as text, the body as HTML. The meta title falls back to the
+ * title, the meta description to the page's opening words. JSON-LD goes
+ * as its JSON, empty when the page has none, so an item sent again loses
+ * what the page no longer says. A part the map leaves out isn't sent.
+ *
+ * @param {{ page: { title: string, metaTitle?: string, metaDescription?: string },
+ * body: string, jsonLd?: object[] }} input
+ * @param {Record<string, string>} fieldMap part → field id
+ */
+export function framerFieldData({ page, body, jsonLd }, fieldMap) {
+ const text = (value) => ({ type: 'string', value });
+ const data = {};
+ if (fieldMap.title) data[fieldMap.title] = text(squash(page.title).slice(0, NAME_CHARS));
+ if (fieldMap.body) {
+ data[fieldMap.body] = { type: 'formattedText', value: body, contentType: 'html' };
+ }
+ if (fieldMap.metaTitle) {
+ data[fieldMap.metaTitle] = text(squash(page.metaTitle || page.title).slice(0, NAME_CHARS));
+ }
+ if (fieldMap.metaDescription) {
+ data[fieldMap.metaDescription] = text(squash(page.metaDescription ?? '') || openingWords(body));
+ }
+ // Empty when the page has none: a JSON-LD dropped from the page is cleared in Framer too.
+ if (fieldMap.jsonLd) data[fieldMap.jsonLd] = text(jsonLd?.length ? jsonLdText(jsonLd) : '');
+ return data;
+}
diff --git a/server/src/lib/cms/framer-items.test.js b/server/src/lib/cms/framer-items.test.js
new file mode 100644
index 000000000..733d4f567
--- /dev/null
+++ b/server/src/lib/cms/framer-items.test.js
@@ -0,0 +1,176 @@
+import { readFileSync } from 'node:fs';
+import { describe, expect, it } from 'vitest';
+import { framerFieldData, framerSlug, toFramerHtml } from './framer-items.js';
+
+/** A page as a Framer CMS item (Send to CMS #1331, phase 2; 00295). */
+
+describe('toFramerHtml', () => {
+ it('keeps what Framer’s formatted text is sent with, a link’s address and target only', () => {
+ const { html, changed } = toFramerHtml(
+ '<h2 id="x" class="big">Why</h2><p style="color:red">Cold <strong>brew</strong> is <a href="https://acme.example/brew" target="_blank" rel="noopener" class="l">smooth</a>.</p><ul><li>One</li></ul><blockquote><p>Said so.</p></blockquote>',
+ );
+ expect(html).toBe(
+ '<h2>Why</h2><p>Cold <strong>brew</strong> is <a href="https://acme.example/brew" target="_blank">smooth</a>.</p><ul><li>One</li></ul><blockquote><p>Said so.</p></blockquote>',
+ );
+ expect(changed).toEqual({ images: 0 });
+ });
+
+ it('keeps a table, its header row as its head, each cell a line of words, links and emphasis', () => {
+ expect(
+ toFramerHtml(
+ '<table class="t"><caption>Prices <em>2026</em></caption><thead><tr><th>Plan</th><th>Price</th></tr></thead><tbody><tr><td><p>Starter</p><p>for <a href="https://acme.example/s" class="x">one</a></p></td><td style="x">$49</td></tr><tr><td>Growth</td><td></td></tr><tr><td></td><td></td></tr></tbody></table>',
+ ).html,
+ ).toBe(
+ '<p>Prices <em>2026</em></p><table><thead><tr><th>Plan</th><th>Price</th></tr></thead><tbody><tr><td>Starter for <a href="https://acme.example/s">one</a></td><td>$49</td></tr><tr><td>Growth</td><td></td></tr></tbody></table>',
+ );
+ // No header row: all of it is its body.
+ expect(
+ toFramerHtml('<table>\n<tr><td>a &lt;b&gt;</td><td>c<br>d</td></tr>\n</table>').html,
+ ).toBe('<table><tbody><tr><td>a &lt;b&gt;</td><td>c d</td></tr></tbody></table>');
+ });
+
+ it('keeps a cell’s colspan and rowspan when they are whole numbers from 1 to 1000', () => {
+ expect(
+ toFramerHtml(
+ '<table><tr><th colspan="2" class="x" style="y">Plans</th></tr><tr><td rowspan=" 3 " data-x="1">Starter</td><td colspan="0">a</td></tr><tr><td colspan="1001" rowspan="two">b</td><td colspan="1000">c</td></tr></table>',
+ ).html,
+ ).toBe(
+ '<table><thead><tr><th colspan="2">Plans</th></tr></thead><tbody><tr><td rowspan="3">Starter</td><td>a</td></tr><tr><td>b</td><td colspan="1000">c</td></tr></tbody></table>',
+ );
+ });
+
+ it('keeps a first row of mixed header and data cells in the body, its header cells as they are', () => {
+ expect(
+ toFramerHtml(
+ '<table><tr><th>Plan</th><td>Note</td></tr><tr><th>Starter</th><td>$49</td></tr></table>',
+ ).html,
+ ).toBe(
+ '<table><tbody><tr><th>Plan</th><td>Note</td></tr><tr><th>Starter</th><td>$49</td></tr></tbody></table>',
+ );
+ });
+
+ it('reads a table in a cell as a line of it, and keeps a table a figure wraps', () => {
+ expect(
+ toFramerHtml(
+ '<table><tr><td>Plan<table><tr><td>x</td><td>y</td></tr></table></td><td>z</td></tr></table>',
+ ).html,
+ ).toBe('<table><tbody><tr><td>Plan x · y</td><td>z</td></tr></tbody></table>');
+ expect(
+ toFramerHtml(
+ '<figure class="wp-block-table"><table><tr><td>a</td><td>b</td></tr></table><figcaption>Prices</figcaption></figure>',
+ ).html,
+ ).toBe('<table><tbody><tr><td>a</td><td>b</td></tr></tbody></table><p>Prices</p>');
+ });
+
+ it('leaves images, media, scripts, styles, forms and embeds out, and counts the images', () => {
+ const { html, changed } = toFramerHtml(
+ '<p>Intro</p><figure><img src="https://acme.example/a.png" alt="A"><figcaption>A</figcaption></figure><p><img src="https://acme.example/b.png"></p><script type="application/ld+json">{"@type":"Article"}</script><style>p{}</style><form><input></form><iframe src="https://x.example"></iframe><video src="v.mp4"></video><p>End</p>',
+ );
+ expect(html).toBe('<p>Intro</p><p>End</p>');
+ expect(changed.images).toBe(3);
+ // A table of nothing but an image goes with it.
+ expect(toFramerHtml('<table><tr><td><img src="a.png"></td></tr></table><p>x</p>')).toEqual({
+ html: '<p>x</p>',
+ changed: { images: 1 },
+ });
+ });
+
+ it('reads a heading 1 as a heading 2, keeps code, and unwraps the rest', () => {
+ expect(
+ toFramerHtml(
+ '<div><h1>Title again</h1><section><p><span>Hi</span> <mark>there</mark> <code class="c">npm</code></p></section><pre class="p"><code class="language-sh">npm i &lt;x&gt;\n --save</code></pre><pre> </pre><dl><dt>Term</dt><dd>Meaning</dd></dl></div>Loose <strong>words</strong><menu><li>Orphan</li></menu>',
+ ).html,
+ ).toBe(
+ '<h2>Title again</h2><p>Hi there <code>npm</code></p><pre><code>npm i &lt;x&gt;\n --save</code></pre><p>Term</p><p>Meaning</p><p>Loose <strong>words</strong></p><p>Orphan</p>',
+ );
+ });
+
+ it('reads a product grid as a list, a product a line: its name linked, its price after it', () => {
+ // The editor's and the agent's grid (web/src/lib/content/product-block.ts, shopping-blocks.js).
+ const grid = JSON.parse(
+ readFileSync(
+ new URL('../../../../web/src/lib/content/__fixtures__/product-block.json', import.meta.url),
+ 'utf8',
+ ),
+ ).html;
+ const { html, changed } = toFramerHtml(
+ `<p>Our picks:</p><!-- html-block -->\n${grid}\n<!-- /html-block --><p>More below.</p>`,
+ );
+ expect(html).toBe(
+ '<p>Our picks:</p><ul><li><a href="https://shop.example/products/p1?variant=2">Summit "GTX" Boot</a> $189.00</li><li><a href="https://shop.example/products/p2">Trail Mid</a></li></ul><p>More below.</p>',
+ );
+ expect(changed.images).toBe(1);
+ });
+});
+
+describe('framerSlug', () => {
+ it('makes a slug of lowercase letters, digits and dashes, from the slug, else the title, else the draft', () => {
+ expect(framerSlug({ slug: 'Soğuk_demleme.Kahve', title: 'x', draftId: 'd1' })).toBe(
+ 'soguk-demleme-kahve',
+ );
+ expect(framerSlug({ slug: '…', title: 'Café crème', draftId: 'd1' })).toBe('cafe-creme');
+ expect(framerSlug({ slug: 'привет-мир', title: '日本語', draftId: 'dr1' })).toBe('page-dr1');
+ });
+});
+
+describe('framerFieldData', () => {
+ const page = { title: ' Cold brew at home ', metaTitle: '', metaDescription: '' };
+ const body = `<p>${'Cold brew is coffee steeped in cold water for 12 to 18 hours. '.repeat(4)}</p>`;
+ const map = {
+ title: 'fTitle',
+ body: 'fBody',
+ metaTitle: 'fSeoTitle',
+ metaDescription: 'fSeoDesc',
+ jsonLd: 'fSchema',
+ };
+
+ it('puts each part in its field as Framer takes it, falling back where a page has none', () => {
+ const data = framerFieldData(
+ { page, body, jsonLd: [{ '@type': 'Article', headline: '</script>' }] },
+ map,
+ );
+ expect(data.fTitle).toEqual({ type: 'string', value: 'Cold brew at home' });
+ expect(data.fBody).toEqual({ type: 'formattedText', value: body, contentType: 'html' });
+ expect(data.fSeoTitle).toEqual({ type: 'string', value: 'Cold brew at home' });
+ // The opening words, cut at a word.
+ expect(data.fSeoDesc.type).toBe('string');
+ expect(data.fSeoDesc.value).toMatch(/^Cold brew is coffee steeped .{60,}…$/);
+ expect(data.fSeoDesc.value.length).toBeLessThanOrEqual(160);
+ expect(data.fSchema).toEqual({
+ type: 'string',
+ value: '{"@type":"Article","headline":"\\u003c/script>"}',
+ });
+ expect(
+ framerFieldData({ page: { ...page, title: 'T'.repeat(300) }, body }, map).fTitle.value,
+ ).toHaveLength(256);
+ });
+
+ it('sends the page’s own meta, an empty JSON-LD it hasn’t (clearing an old one), and nothing for a part the map leaves out', () => {
+ expect(
+ framerFieldData(
+ {
+ page: { ...page, metaTitle: 'Cold brew, simply', metaDescription: 'How to make it.' },
+ body: '<p>x</p>',
+ jsonLd: [],
+ },
+ map,
+ ),
+ ).toEqual({
+ fTitle: { type: 'string', value: 'Cold brew at home' },
+ fBody: { type: 'formattedText', value: '<p>x</p>', contentType: 'html' },
+ fSeoTitle: { type: 'string', value: 'Cold brew, simply' },
+ fSeoDesc: { type: 'string', value: 'How to make it.' },
+ fSchema: { type: 'string', value: '' },
+ });
+ expect(
+ framerFieldData(
+ { page, body: '<p>x</p>', jsonLd: [{ '@type': 'Article' }, { '@type': 'FAQPage' }] },
+ { title: 'fTitle', body: 'fBody', jsonLd: 'fSchema' },
+ ),
+ ).toEqual({
+ fTitle: { type: 'string', value: 'Cold brew at home' },
+ fBody: { type: 'formattedText', value: '<p>x</p>', contentType: 'html' },
+ fSchema: { type: 'string', value: '[{"@type":"Article"},{"@type":"FAQPage"}]' },
+ });
+ });
+});
diff --git a/server/src/lib/cms/framer.js b/server/src/lib/cms/framer.js
index bd5809bb7..149e047bd 100644
--- a/server/src/lib/cms/framer.js
+++ b/server/src/lib/cms/framer.js
@@ -21,8 +21,10 @@ import {
export class FramerError extends Error {
/**
- * @param {'invalid'|'auth_failed'|'no_access'|'not_found'|'busy'|'unreachable'|'failed'} code
- * 'auth_failed': Framer refused the key (the person connects again)
+ * @param {'invalid'|'auth_failed'|'no_access'|'not_found'|'busy'|'unreachable'|'slug_taken'|
+ * 'failed'} code
+ * 'auth_failed': Framer refused the key (the person connects again); 'slug_taken': another
+ * item has the page's slug (a send's, never a route's)
* @param {string} message
*/
constructor(code, message) {
@@ -311,6 +313,96 @@ export async function collectionOf(project, apiKey, collectionId, opts) {
);
}
+/** The collection's items once more: a read changes nothing, so a failed one is tried again, once. */
+async function itemsAgain(collection) {
+ try {
+ return await collection.getItems();
+ } catch {
+ return collection.getItems();
+ }
+}
+
+/**
+ * Whether the item holding the page's slug is one a send of this page made
+ * and couldn't keep the id of (the connection dropped, or Framer's list
+ * didn't answer, after the item was added): still a draft, with the very
+ * title this send writes in the title field. Taking it over is safe: the
+ * slug and title are this page's, and a draft isn't on the site, so writing
+ * to it changes nothing anyone sees (a draft made by hand with this slug
+ * and title would be taken too, and written with this page). Any other
+ * item keeps its slug.
+ */
+function halfSent(item, fieldData, titleField) {
+ const title = titleField ? fieldData[titleField]?.value : undefined;
+ return (
+ item.draft === true &&
+ typeof title === 'string' &&
+ item.fieldData?.[titleField]?.value === title
+ );
+}
+
+/**
+ * Writes a page's item in one connection (framer-delivery.js): the item
+ * the page's last send made (`before`) is updated while it's in the
+ * collection, its draft state as it is; else a draft its half-done send
+ * left (halfSent) is; else a new draft item is made. A slug another item
+ * has is refused before anything is written.
+ *
+ * Framer doesn't say which item it made: it is the one new item with the
+ * slug, among those the first read didn't have.
+ *
+ * @param {string} project the connection's project (site_id)
+ * @param {{ before: string|null, slug: string, fieldData: object, titleField?: string|null }}
+ * item titleField: the field the page's title goes to (field_map.title)
+ * @returns {Promise<{ id: string, updated: boolean, live: boolean }>} live: the item
+ * updated isn't a draft, so the page goes live with the site's next publish
+ */
+export async function writeItem(
+ project,
+ apiKey,
+ collectionId,
+ { before, slug, fieldData, titleField = null },
+ opts,
+) {
+ return withProject(
+ project,
+ apiKey,
+ async (framer) => {
+ const collection = usersOwn(await framer.getCollections()).find((c) => c.id === collectionId);
+ if (!collection) {
+ throw new FramerError(
+ 'not_found',
+ 'The collection pages go to is gone from the project: pick another in Settings › Integrations.',
+ );
+ }
+ const items = await collection.getItems();
+ const current = before ? (items.find((item) => item.id === before) ?? null) : null;
+ const holder = items.find((item) => item.slug === slug && item.id !== current?.id) ?? null;
+ if (holder && (current || !halfSent(holder, fieldData, titleField))) {
+ throw new FramerError(
+ 'slug_taken',
+ `Another item in ${collection.name} has the slug "${slug}": change the page’s slug, or that item’s.`,
+ );
+ }
+ const own = current ?? holder;
+ if (own) {
+ // No draft: the item stays a draft, or live, as it is.
+ await collection.addItems([{ id: own.id, slug, fieldData }]);
+ return { id: own.id, updated: true, live: !own.draft };
+ }
+ const known = new Set(items.map((item) => item.id));
+ await collection.addItems([{ slug, draft: true, fieldData }]);
+ const made = (await itemsAgain(collection)).filter(
+ (item) => !known.has(item.id) && item.slug === slug,
+ );
+ if (made.length !== 1)
+ throw new FramerError('failed', 'Framer didn’t say which item it made.');
+ return { id: made[0].id, updated: false, live: false };
+ },
+ opts,
+ );
+}
+
/** The parts of a page a field map places, and the Framer field types each may go to. */
const PART_TYPES = {
title: ['string'],
diff --git a/server/src/lib/cms/framer.test.js b/server/src/lib/cms/framer.test.js
index 4f75c0b45..ca9d0bc2f 100644
--- a/server/src/lib/cms/framer.test.js
+++ b/server/src/lib/cms/framer.test.js
@@ -8,6 +8,7 @@ import {
listCollections,
projectRef,
withProject,
+ writeItem,
} from './framer.js';
/**
@@ -478,3 +479,185 @@ describe('checkFieldMap', () => {
);
});
});
+
+describe('writeItem', () => {
+ /** A user's collection of items as framer-api reads them; addItems keeps what it's given. */
+ function itemsProject(items = []) {
+ const store = items.map((item) => ({ ...item }));
+ let made = 0;
+ const blog = {
+ ...collection('cBlog', 'Blog', 'user'),
+ getItems: vi.fn(async () => store.map((item) => ({ ...item }))),
+ addItems: vi.fn(async (input) => {
+ for (const item of input) {
+ if (item.id)
+ Object.assign(
+ store.find((s) => s.id === item.id),
+ item,
+ );
+ else store.push({ id: `new-${++made}`, draft: false, ...item });
+ }
+ }),
+ };
+ const project = fakeProject();
+ project.framer.getCollections = vi.fn(async () => [
+ blog,
+ collection('cSynced', 'Synced', 'anotherPlugin'),
+ ]);
+ return { ...project, blog, store };
+ }
+ const fieldData = { fTitle: { type: 'string', value: 'Cold brew' } };
+ const write = (
+ connect,
+ before,
+ { slug = 'cold-brew', collectionId = 'cBlog', titleField = 'fTitle' } = {},
+ ) => writeItem(PROJECT, KEY, collectionId, { before, slug, fieldData, titleField }, { connect });
+ /** An item as Framer reads it, its title in the title field. */
+ const item = (id, slug, draft, title = 'Cold brew') => ({
+ id,
+ slug,
+ draft,
+ fieldData: { fTitle: { type: 'string', value: title, valueByLocale: {} } },
+ });
+
+ it('makes a page sent for the first time a draft item, found by its slug', async () => {
+ const { framer, connect, blog } = itemsProject([{ id: 'i7', slug: 'other', draft: false }]);
+ expect(await write(connect, null)).toEqual({ id: 'new-1', updated: false, live: false });
+ expect(connect).toHaveBeenCalledWith(PROJECT, KEY);
+ expect(blog.addItems).toHaveBeenCalledWith([{ slug: 'cold-brew', draft: true, fieldData }]);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('updates the item the page’s last send made, its draft state as it is', async () => {
+ const { connect, blog } = itemsProject([{ id: 'i1', slug: 'cold-brew-old', draft: false }]);
+ expect(await write(connect, 'i1')).toEqual({ id: 'i1', updated: true, live: true });
+ expect(blog.addItems).toHaveBeenCalledWith([{ id: 'i1', slug: 'cold-brew', fieldData }]);
+ expect(blog.addItems.mock.calls[0][0][0]).not.toHaveProperty('draft');
+ const draft = itemsProject([{ id: 'i1', slug: 'cold-brew', draft: true }]);
+ expect(await write(draft.connect, 'i1')).toEqual({ id: 'i1', updated: true, live: false });
+ });
+
+ it('makes a new draft item when the last one was deleted in Framer', async () => {
+ const { connect, blog } = itemsProject([]);
+ expect(await write(connect, 'gone')).toEqual({ id: 'new-1', updated: false, live: false });
+ expect(blog.addItems).toHaveBeenCalledWith([{ slug: 'cold-brew', draft: true, fieldData }]);
+ });
+
+ it('refuses a slug another item has, writing nothing', async () => {
+ const message =
+ 'Another item in Blog has the slug "cold-brew": change the page’s slug, or that item’s.';
+ const updating = itemsProject([
+ { id: 'i1', slug: 'cold-brew-old', draft: true },
+ { id: 'i2', slug: 'cold-brew', draft: false },
+ ]);
+ await expect(write(updating.connect, 'i1')).rejects.toMatchObject({
+ code: 'slug_taken',
+ message,
+ });
+ expect(updating.blog.addItems).not.toHaveBeenCalled();
+ const making = itemsProject([{ id: 'i9', slug: 'cold-brew', draft: false }]);
+ await expect(write(making.connect, null)).rejects.toMatchObject({
+ code: 'slug_taken',
+ message,
+ });
+ expect(making.blog.addItems).not.toHaveBeenCalled();
+ expect(making.framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails when Framer’s items don’t show the one it made', async () => {
+ const { connect, blog } = itemsProject([]);
+ blog.addItems.mockResolvedValueOnce(undefined);
+ await expect(write(connect, null)).rejects.toMatchObject({
+ code: 'failed',
+ message: 'Framer didn’t say which item it made.',
+ });
+ });
+
+ it('finds no collection gone from the project, or a plugin’s', async () => {
+ for (const collectionId of ['cGone', 'cSynced']) {
+ const { framer, connect } = itemsProject([]);
+ await expect(write(connect, null, { collectionId })).rejects.toMatchObject({
+ code: 'not_found',
+ message:
+ 'The collection pages go to is gone from the project: pick another in Settings › Integrations.',
+ });
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it('reads the items again once when the read after adding fails, and finds the item', async () => {
+ const { connect, blog } = itemsProject([]);
+ const read = blog.getItems.getMockImplementation();
+ blog.getItems
+ .mockImplementationOnce(read)
+ .mockRejectedValueOnce(new FramerPluginError('read failed'));
+ expect(await write(connect, null)).toEqual({ id: 'new-1', updated: false, live: false });
+ expect(blog.getItems).toHaveBeenCalledTimes(3);
+ expect(blog.addItems).toHaveBeenCalledTimes(1);
+ });
+
+ it('fails when the items can’t be read after adding, twice, adding nothing more', async () => {
+ const { connect, blog, framer } = itemsProject([]);
+ const read = blog.getItems.getMockImplementation();
+ blog.getItems
+ .mockImplementationOnce(read)
+ .mockRejectedValueOnce(new FramerPluginError('read failed'))
+ .mockRejectedValueOnce(new FramerPluginError('read failed'));
+ await expect(write(connect, null)).rejects.toMatchObject({ code: 'failed' });
+ expect(blog.getItems).toHaveBeenCalledTimes(3);
+ expect(blog.addItems).toHaveBeenCalledTimes(1);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('takes over the draft a half-done send of the page left: its slug and title', async () => {
+ for (const before of [null, 'gone']) {
+ const { connect, blog } = itemsProject([item('i5', 'cold-brew', true)]);
+ expect(await write(connect, before)).toEqual({ id: 'i5', updated: true, live: false });
+ expect(blog.addItems).toHaveBeenCalledWith([{ id: 'i5', slug: 'cold-brew', fieldData }]);
+ }
+ });
+
+ it('leaves an item of the slug alone when it isn’t a draft, its title differs, or no title is mapped', async () => {
+ for (const [items, titleField] of [
+ [[item('i5', 'cold-brew', false)], 'fTitle'],
+ [[item('i5', 'cold-brew', true, 'Iced coffee')], 'fTitle'],
+ [[item('i5', 'cold-brew', true)], null],
+ ]) {
+ const { connect, blog } = itemsProject(items);
+ await expect(write(connect, null, { titleField })).rejects.toMatchObject({
+ code: 'slug_taken',
+ });
+ expect(blog.addItems).not.toHaveBeenCalled();
+ }
+ // Updating its own item, the page doesn't take over another of its new slug.
+ const { connect, blog } = itemsProject([
+ item('i1', 'cold-brew-old', true),
+ item('i5', 'cold-brew', true),
+ ]);
+ await expect(write(connect, 'i1')).rejects.toMatchObject({ code: 'slug_taken' });
+ expect(blog.addItems).not.toHaveBeenCalled();
+ });
+
+ it('reads the item it made among the new ones only, and fails on two of its slug', async () => {
+ const { connect, blog, store } = itemsProject([item('i1', 'other', false)]);
+ blog.addItems.mockImplementationOnce(async ([added]) => {
+ // Another send, or a person, added an item of the same slug meanwhile.
+ store.push({ id: 'theirs', draft: true, ...added }, { id: 'ours', draft: true, ...added });
+ });
+ await expect(write(connect, null)).rejects.toMatchObject({
+ code: 'failed',
+ message: 'Framer didn’t say which item it made.',
+ });
+ // An item the first read had, given the slug meanwhile, isn't taken for the new one.
+ const renamed = itemsProject([item('i1', 'other', false)]);
+ renamed.blog.addItems.mockImplementationOnce(async ([added]) => {
+ renamed.store[0].slug = 'cold-brew';
+ renamed.store.push({ id: 'ours', draft: true, ...added });
+ });
+ expect(await write(renamed.connect, null)).toEqual({
+ id: 'ours',
+ updated: false,
+ live: false,
+ });
+ });
+});
diff --git a/server/src/lib/cms/webflow-items.js b/server/src/lib/cms/webflow-items.js
index 58e914d7d..34685c333 100644
--- a/server/src/lib/cms/webflow-items.js
+++ b/server/src/lib/cms/webflow-items.js
@@ -4,7 +4,8 @@ import { foldLetters } from '../letters.js';
/**
* A page as a Webflow CMS item (Send to CMS #1331, phase 2): its rich text
* as Webflow keeps it, a slug Webflow takes, and the item's fields by the
- * brand's field map (brand_cms_connections.field_map, 00283).
+ * brand's field map (brand_cms_connections.field_map, 00283). The steps a
+ * rich text field shares are exported for Framer's (framer-items.js).
*/
/** What Webflow's rich text keeps; other elements give way to their content. */
@@ -40,17 +41,21 @@ const DROP =
/** The meta description's fallback: the page's opening words, as long as a search result shows. */
const OPENING_CHARS = 160;
/** Webflow's longest name and plain text it's sent here. */
-const NAME_CHARS = 256;
+export const NAME_CHARS = 256;
const escape = (value) =>
String(value).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
-const squash = (value) => String(value).replace(/\s+/g, ' ').trim();
+export const squash = (value) => String(value).replace(/\s+/g, ' ').trim();
-/** Attributes go but a link's address and target. */
-function bare($, el) {
+/**
+ * Attributes go but a link's address and target, and those `attrs` keeps
+ * by tag (tag → names; Framer's table cells keep their spans).
+ */
+function bare($, el, attrs = {}) {
const tag = el.tagName?.toLowerCase();
for (const name of Object.keys(el.attribs ?? {})) {
if (tag === 'a' && (name === 'href' || name === 'target')) continue;
+ if (attrs[tag]?.has(name)) continue;
$(el).removeAttr(name);
}
}
@@ -59,7 +64,7 @@ function bare($, el) {
* A table cell as one line: its paragraphs, items and lines a space apart,
* its links and emphasis kept.
*/
-function cellHtml($, cell) {
+export function cellHtml($, cell) {
const $cell = $(cell).clone();
$cell.find('br').replaceWith(' ');
$cell
@@ -74,74 +79,64 @@ function cellHtml($, cell) {
}
/** A table's own rows, not those of a table inside one of its cells. */
-const ownRows = ($, table) =>
+export const ownRows = ($, table) =>
$(table)
.find('tr')
.toArray()
.filter((row) => $(row).closest('table')[0] === table);
-/**
- * A page's publishable HTML as Webflow's rich text keeps it:
- * - a table becomes a list, a row an item ("Header: cell · …"), a table in
- * a cell first: rich text has no tables (#1331);
- * - a product card or grid becomes a list, a product an item ("Name $189.00");
- * - images and media are left out until workspace files (CHAT-06, #1331),
- * a figure of one with its caption; scripts (the JSON-LD has its own
- * field), embeds, forms and rules go too;
- * - the page's title is the item's name, so a heading 1 left in the body
- * reads as a heading 2;
- * - a code block, a definition list, a caption and words outside a block
- * are paragraphs, an item outside a list too;
- * - any other element gives way to its content, and attributes go but a
- * link's address and target.
- * Returns the HTML, and how many tables and images it changed (the send's note).
- */
-export function toWebflowRichText(html) {
- const $ = cheerio.load(String(html ?? ''), null, false);
- const changed = {
- tables: $('table').filter((_, t) => !$(t).parents('table').length).length,
- images:
- $('img, video, svg').length + $('picture').filter((_, p) => !$(p).find('img').length).length,
- };
+/** The images (and video, SVG) a page loses: a picture once, by its image or its own. */
+export const imagesIn = ($) =>
+ $('img, video, svg').length + $('picture').filter((_, p) => !$(p).find('img').length).length;
+
+/** Scripts, styles, forms and rules go with what they hold, and comments go. */
+export function dropUnkept($) {
$(DROP).remove();
$('*')
.contents()
.add($.root().contents())
.filter((_, node) => node.type === 'comment')
.remove();
+}
- // Inner tables first: a cell holding one reads it as its list.
- for (const table of $('table').toArray().reverse()) {
- const rows = ownRows($, table);
- const own = (row) =>
- $(row)
- .children('th, td')
- .toArray()
- .map((cell) => cellHtml($, cell));
- const head =
- rows.length && $(rows[0]).children('th').length
- ? $(rows[0])
- .children('th, td')
- .toArray()
- .map((cell) => squash($(cell).text()))
- : null;
- const items = (head ? rows.slice(1) : rows)
- .map((row) =>
- own(row)
- .map((value, i) =>
- value && head?.[i] ? `<strong>${escape(head[i])}</strong>: ${value}` : value,
- )
- .filter(Boolean)
- .join(' · '),
- )
- .filter(Boolean);
- $(table).replaceWith(
- items.length ? `<ul>${items.map((item) => `<li>${item}</li>`).join('')}</ul>` : '',
- );
- }
+/**
+ * A table as a list, a row an item ("Header: cell · …"), its header naming
+ * each cell; an empty table goes.
+ */
+export function tableAsList($, table) {
+ const rows = ownRows($, table);
+ const own = (row) =>
+ $(row)
+ .children('th, td')
+ .toArray()
+ .map((cell) => cellHtml($, cell));
+ const head =
+ rows.length && $(rows[0]).children('th').length
+ ? $(rows[0])
+ .children('th, td')
+ .toArray()
+ .map((cell) => squash($(cell).text()))
+ : null;
+ const items = (head ? rows.slice(1) : rows)
+ .map((row) =>
+ own(row)
+ .map((value, i) =>
+ value && head?.[i] ? `<strong>${escape(head[i])}</strong>: ${value}` : value,
+ )
+ .filter(Boolean)
+ .join(' · '),
+ )
+ .filter(Boolean);
+ $(table).replaceWith(
+ items.length ? `<ul>${items.map((item) => `<li>${item}</li>`).join('')}</ul>` : '',
+ );
+}
- // A product card or grid (the editor's product-block.ts, shopping-blocks.js)
- // as a list: a product an item, its name linked, its price after it.
+/**
+ * A product card or grid (the editor's product-block.ts, shopping-blocks.js)
+ * as a list: a product an item, its name linked, its price after it.
+ */
+export function productsAsList($) {
$('.ansvisor-products').each((_, grid) => {
const items = $(grid)
.find('a.ansvisor-product')
@@ -156,32 +151,34 @@ export function toWebflowRichText(html) {
});
$(grid).replaceWith(items.length ? $('<ul></ul>').append(items) : '');
});
+}
- // A figure of media goes with its caption; a figure of words (a table's) keeps them.
+/** Media goes; a figure of media with its caption, a figure of words (a table's) keeps them. */
+export function dropMedia($) {
$('figure').each((_, figure) => {
if ($(figure).find(MEDIA).length) $(figure).remove();
});
$(MEDIA).remove();
- $('h1').each((_, el) => {
- el.tagName = 'h2';
- });
- $('pre').each((_, el) => {
- $(el).replaceWith(`<p>${escape($(el).text().trim())}</p>`);
- });
- $('dt, dd, figcaption, caption').each((_, el) => {
- $(el).replaceWith(`<p>${$(el).html() ?? ''}</p>`);
- });
+}
- // Inside out, so an element's children are settled before it gives way.
+/**
+ * The last steps of a rich text field: elements it doesn't keep give way to
+ * their content (inside out, so an element's children are settled before
+ * it), attributes go but a link's address and target (and `attrs`, as
+ * bare() reads it), an item outside a list is a paragraph, words and inline
+ * elements at the top go in paragraphs a run at a time (`blocks`: what
+ * stands at the top on its own), and the paragraphs, items and lists a
+ * removal left empty go.
+ */
+export function settleRichText($, { keep, blocks, attrs = {} }) {
for (const el of $('*').toArray().reverse()) {
- if (KEEP.has(el.tagName?.toLowerCase())) bare($, el);
+ if (keep.has(el.tagName?.toLowerCase())) bare($, el, attrs);
else $(el).replaceWith($(el).contents());
}
$('li').each((_, el) => {
if (!$(el).parent().is('ul, ol')) el.tagName = 'p';
});
- // Words and inline elements at the top go in paragraphs, a run at a time.
let run = [];
const wrap = () => {
if (run.some((node) => squash($(node).text()))) $(run).wrapAll('<p></p>');
@@ -189,18 +186,56 @@ export function toWebflowRichText(html) {
run = [];
};
for (const node of $.root().contents().toArray()) {
- if (node.type === 'tag' && BLOCKS.has(node.tagName.toLowerCase())) wrap();
+ if (node.type === 'tag' && blocks.has(node.tagName.toLowerCase())) wrap();
else if (node.type === 'tag' || node.type === 'text') run.push(node);
}
wrap();
- // The paragraphs, items and lists a removal left empty.
$('p, li, h2, h3, h4, h5, h6, blockquote').each((_, el) => {
if (!squash($(el).text()) && !$(el).find('br').length) $(el).remove();
});
$('ul, ol').each((_, el) => {
if (!$(el).children('li').length) $(el).remove();
});
+}
+
+/**
+ * A page's publishable HTML as Webflow's rich text keeps it:
+ * - a table becomes a list, a row an item ("Header: cell · …"), a table in
+ * a cell first: rich text has no tables (#1331);
+ * - a product card or grid becomes a list, a product an item ("Name $189.00");
+ * - images and media are left out until workspace files (CHAT-06, #1331),
+ * a figure of one with its caption; scripts (the JSON-LD has its own
+ * field), embeds, forms and rules go too;
+ * - the page's title is the item's name, so a heading 1 left in the body
+ * reads as a heading 2;
+ * - a code block, a definition list, a caption and words outside a block
+ * are paragraphs, an item outside a list too;
+ * - any other element gives way to its content, and attributes go but a
+ * link's address and target.
+ * Returns the HTML, and how many tables and images it changed (the send's note).
+ */
+export function toWebflowRichText(html) {
+ const $ = cheerio.load(String(html ?? ''), null, false);
+ const changed = {
+ tables: $('table').filter((_, t) => !$(t).parents('table').length).length,
+ images: imagesIn($),
+ };
+ dropUnkept($);
+ // Inner tables first: a cell holding one reads it as its list.
+ for (const table of $('table').toArray().reverse()) tableAsList($, table);
+ productsAsList($);
+ dropMedia($);
+ $('h1').each((_, el) => {
+ el.tagName = 'h2';
+ });
+ $('pre').each((_, el) => {
+ $(el).replaceWith(`<p>${escape($(el).text().trim())}</p>`);
+ });
+ $('dt, dd, figcaption, caption').each((_, el) => {
+ $(el).replaceWith(`<p>${$(el).html() ?? ''}</p>`);
+ });
+ settleRichText($, { keep: KEEP, blocks: BLOCKS });
return { html: $.html().trim(), changed };
}
@@ -220,7 +255,7 @@ export function webflowSlug(value) {
}
/** The page's opening words, cut at a word: its meta description when it has none. */
-function openingWords(html) {
+export function openingWords(html) {
const text = squash(
cheerio
.load(String(html ?? ''), null, false)
@@ -251,12 +286,16 @@ export function fieldDataFor({ page, slug, body, jsonLd, sentAt }, fieldMap) {
if (fieldMap.metaDescription) {
data[fieldMap.metaDescription] = squash(page.metaDescription) || openingWords(body);
}
- if (fieldMap.jsonLd) {
- // Every "<" escaped: nothing in it can end or open a tag in the embed's script.
- data[fieldMap.jsonLd] = jsonLd?.length
- ? JSON.stringify(jsonLd.length === 1 ? jsonLd[0] : jsonLd).replace(/</g, '\\u003c')
- : '';
- }
+ if (fieldMap.jsonLd) data[fieldMap.jsonLd] = jsonLd?.length ? jsonLdText(jsonLd) : '';
if (fieldMap.date && sentAt) data[fieldMap.date] = sentAt.toISOString();
return data;
}
+
+/**
+ * A page's JSON-LD as one field's text: one block as itself, several as a
+ * list. Every "<" escaped: nothing in it can end or open a tag in the
+ * embed's script.
+ */
+export function jsonLdText(jsonLd) {
+ return JSON.stringify(jsonLd.length === 1 ? jsonLd[0] : jsonLd).replace(/</g, '\\u003c');
+}
diff --git a/server/src/lib/content-delivery.js b/server/src/lib/content-delivery.js
index 6611c7973..147eab4f4 100644
--- a/server/src/lib/content-delivery.js
+++ b/server/src/lib/content-delivery.js
@@ -10,6 +10,7 @@ import { isWebflowConfigured } from './composio.js';
import { credentialsConfigured } from './catalog/credentials.js';
import { sendToWebflow } from './cms/webflow-delivery.js';
import { sendToWordPress } from './cms/wordpress-delivery.js';
+import { sendToFramer } from './cms/framer-delivery.js';
/**
* Send to CMS, phase 1 (#1331): an admin or manager sends Content Editor
@@ -27,8 +28,9 @@ import { sendToWordPress } from './cms/wordpress-delivery.js';
* the workspace's next send (reserve_content_deliveries).
*
* Phase 2: a page can go to the brand's Webflow collection instead (00283,
- * cms/webflow-delivery.js), as a draft item, or to its WordPress site
- * (00294, cms/wordpress-delivery.js), as a draft post, under the same cap,
+ * cms/webflow-delivery.js), as a draft item, to its WordPress site (00294,
+ * cms/wordpress-delivery.js), as a draft post, or to its Framer collection
+ * (00295, cms/framer-delivery.js), as a draft item, under the same cap,
* batches and delivery rows; a delivery says where it went (`target`).
*/
@@ -63,8 +65,11 @@ export const deliveryPage = z.object({
.default(null),
});
-/** Where pages go: the brand's webhook (phase 1), its Webflow collection or its WordPress site (phase 2). */
-const DELIVERY_TARGETS = ['webhook', 'webflow', 'wordpress'];
+/**
+ * Where pages go: the brand's webhook (phase 1), its Webflow collection, its
+ * WordPress site or its Framer collection (phase 2).
+ */
+const DELIVERY_TARGETS = ['webhook', 'webflow', 'wordpress', 'framer'];
export const sendInput = z.object({
// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).
@@ -78,7 +83,8 @@ export class DeliveryError extends Error {
/**
* @param {'no_webhook'|'webhook_not_subscribed'|'webflow_not_configured'|'no_webflow'|
* 'webflow_refused'|'webflow_not_ready'|'wordpress_not_configured'|'no_wordpress'|
- * 'wordpress_refused'|'in_progress'|'not_found'|'daily_limit'} code
+ * 'wordpress_refused'|'framer_not_configured'|'no_framer'|'framer_refused'|
+ * 'framer_not_ready'|'in_progress'|'not_found'|'daily_limit'} code
*/
constructor(code, message, status) {
super(message);
@@ -293,10 +299,46 @@ async function wordpressFor(brandId) {
return data;
}
+/**
+ * The brand's Framer connection (00295), its key kept by the API, ready to
+ * take pages: a collection with its title and body fields.
+ */
+async function framerFor(brandId) {
+ if (!credentialsConfigured()) {
+ throw new DeliveryError('framer_not_configured', 'Framer is not set up on this server.', 503);
+ }
+ const { data, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .select('id, brand_id, status, site_id, collection_id, field_map, updated_at')
+ .eq('brand_id', brandId)
+ .eq('provider', 'framer')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (!data) {
+ throw new DeliveryError('no_framer', 'Connect Framer in Settings › Integrations.', 409);
+ }
+ if (data.status === 'auth_failed') {
+ throw new DeliveryError(
+ 'framer_refused',
+ 'Framer refused the API key. Connect it again in Settings › Integrations.',
+ 409,
+ );
+ }
+ if (!data.collection_id || !data.field_map?.title || !data.field_map?.body) {
+ throw new DeliveryError(
+ 'framer_not_ready',
+ 'Pick the Framer collection and its fields in Settings › Integrations.',
+ 409,
+ );
+ }
+ return data;
+}
+
/** A CMS a page goes to itself, not through the webhook: its connection, and how a page is sent. */
const NATIVE = {
webflow: { label: 'Webflow', connect: webflowFor, send: sendToWebflow },
wordpress: { label: 'WordPress', connect: wordpressFor, send: sendToWordPress },
+ framer: { label: 'Framer', connect: framerFor, send: sendToFramer },
};
async function brandFor(brandId) {
@@ -369,10 +411,10 @@ async function sendToWebhooks({ delivery, page, brand, html, jsonLd, configs })
/**
* Sends one queued delivery, to the brand's webhooks or its CMS (a Webflow
- * collection, a WordPress site), and writes how it went: sent, or failed
- * with the reason. A Webflow item's or WordPress post's id, and its
- * collection or site, are kept on the delivery, so the page's next send
- * updates it. A webhook's callback can land before the
+ * or Framer collection, a WordPress site), and writes how it went: sent, or
+ * failed with the reason. A Webflow or Framer item's or WordPress post's id,
+ * and its collection or site, are kept on the delivery, so the page's next
+ * send updates it. A webhook's callback can land before the
* webhook answers (an automation that publishes, or fails, first): then the
* delivery keeps what the callback said, and that is what comes back.
*/
@@ -392,7 +434,8 @@ async function deliver({ delivery, page, brand, configs, native }) {
: {}),
};
// How the CMS took it, for the one page's answer (and the batch); not kept.
- // live: WordPress had the page's post live, so a new draft was made.
+ // live: WordPress had the page's post live, so a new draft was made;
+ // Framer's item updated isn't a draft, so it goes live with the site's next publish.
const how = native
? sent.taken
? { updated: sent.updated, changed: sent.changed, live: sent.live }
@@ -505,8 +548,8 @@ async function myRuleSets(orgId, siteType, drafts) {
/**
* Sends pages of one brand: checks they are the brand's (not archived), that
- * a webhook takes the event (or the brand's Webflow collection is ready, or
- * its WordPress site connected, for those targets), reserves them against the day's cap (those past
+ * a webhook takes the event (or the brand's Webflow or Framer collection is
+ * ready, or its WordPress site connected, for those targets), reserves them against the day's cap (those past
* it don't go), keeps each page's slug and meta on its draft, then sends
* them. One page is sent before this returns; more go on in the background,
* so a CMS isn't sent 25 posts at once.
@@ -554,7 +597,7 @@ export async function sendContentPages({
},
);
if (reserveError) {
- // 00284, 00294: a page already on its way to the CMS isn't sent there again meanwhile.
+ // 00284, 00294, 00295: a page already on its way to the CMS isn't sent there again meanwhile.
if (/delivery_in_progress/.test(reserveError.message ?? '')) {
throw new DeliveryError(
'in_progress',
diff --git a/server/src/lib/content-delivery.test.js b/server/src/lib/content-delivery.test.js
index e2ffb0c37..e85b17065 100644
--- a/server/src/lib/content-delivery.test.js
+++ b/server/src/lib/content-delivery.test.js
@@ -16,9 +16,12 @@ const db = {
// The brand's Webflow connection (00283), and whether this server has Webflow set up.
webflow: null,
webflowConfigured: true,
- // Its WordPress connection (00294), and whether this server can keep its sign-in.
+ // Its WordPress connection (00294), and whether this server can keep its sign-in
+ // (Framer's key too: one CONNECTOR_CREDENTIALS_KEY).
wordpress: null,
wordpressConfigured: true,
+ // Its Framer connection (00295).
+ framer: null,
queued: [],
updates: [],
rpc: [],
@@ -53,7 +56,8 @@ function from(table) {
if (table === 'webhook_configs') return { data: db.configs, error: null };
if (table === 'brand_cms_connections') {
const provider = q.filters.find(([op, col]) => op === 'eq' && col === 'provider')?.[2];
- return { data: provider === 'wordpress' ? db.wordpress : db.webflow, error: null };
+ const connection = { wordpress: db.wordpress, framer: db.framer }[provider];
+ return { data: connection === undefined ? db.webflow : connection, error: null };
}
if (table === 'brands') {
db.brandReads += 1;
@@ -105,6 +109,10 @@ const sendToWordPress = vi.fn();
vi.mock('./cms/wordpress-delivery.js', () => ({
sendToWordPress: (...args) => sendToWordPress(...args),
}));
+const sendToFramer = vi.fn();
+vi.mock('./cms/framer-delivery.js', () => ({
+ sendToFramer: (...args) => sendToFramer(...args),
+}));
const { DAILY_DELIVERIES, DeliveryError, PAUSE_MS, cleanPublishHtml, sendContentPages, signBody } =
await import('./content-delivery.js');
@@ -158,10 +166,12 @@ beforeEach(() => {
db.webflowConfigured = true;
db.wordpress = null;
db.wordpressConfigured = true;
+ db.framer = null;
db.rpcError = null;
postJson.mockReset().mockResolvedValue({ status: 200, answer: '{"ok":true}' });
sendToWebflow.mockReset();
sendToWordPress.mockReset();
+ sendToFramer.mockReset();
});
afterEach(() => {
@@ -719,3 +729,142 @@ describe('sendContentPages to WordPress (phase 2, 00294)', () => {
expect(closed).toHaveLength(2);
});
});
+
+describe('sendContentPages to Framer (phase 2, 00295)', () => {
+ const connection = {
+ id: 'cn1',
+ brand_id: 'b1',
+ status: 'connected',
+ site_id: 'AbCdEfGhIj0123456789',
+ collection_id: 'cBlog',
+ field_map: { title: 'fTitle', body: 'fBody' },
+ updated_at: '2026-10-27T09:00:00Z',
+ };
+ const toFramer = (pages = [page()]) =>
+ sendContentPages({ orgId: 'o1', brandId: 'b1', userId: 'u1', pages, target: 'framer' });
+
+ it('sends a page to the brand’s collection, not its webhooks, and keeps the item on the delivery', async () => {
+ db.framer = connection;
+ sendToFramer.mockResolvedValue({
+ taken: true,
+ externalId: 'item-1',
+ collectionId: 'cBlog',
+ updated: true,
+ live: true,
+ changed: { images: 2 },
+ });
+ const sent = await toFramer();
+ expect(db.rpc[0].args.p_target).toBe('framer');
+ expect(postJson).not.toHaveBeenCalled();
+ expect(sendToWebflow).not.toHaveBeenCalled();
+ expect(sendToWordPress).not.toHaveBeenCalled();
+ expect(sendToFramer).toHaveBeenCalledWith(
+ expect.objectContaining({
+ connection,
+ html: '<h2>Why</h2><p>Because.</p>',
+ jsonLd: [],
+ page: expect.objectContaining({ draftId: page().draftId, slug: 'best-aeo-tools' }),
+ }),
+ );
+ const write = db.updates.find((u) => u.table === 'content_draft_deliveries');
+ expect(write.update).toMatchObject({
+ status: 'sent',
+ error: null,
+ external_id: 'item-1',
+ target_collection: 'cBlog',
+ });
+ // How Framer took it goes in the answer, as Webflow's and WordPress's do.
+ expect(sent.deliveries[0]).toMatchObject({
+ status: 'sent',
+ updated: true,
+ live: true,
+ changed: { images: 2 },
+ });
+ });
+
+ it('writes a page Framer didn’t take as failed, with the reason', async () => {
+ db.framer = connection;
+ sendToFramer.mockResolvedValue({
+ taken: false,
+ failure: 'Another item in Blog has the slug "best-aeo-tools".',
+ });
+ const sent = await toFramer();
+ const write = db.updates.find((u) => u.table === 'content_draft_deliveries');
+ expect(write.update).toMatchObject({
+ status: 'failed',
+ error: 'Another item in Blog has the slug "best-aeo-tools".',
+ });
+ expect(write.update).not.toHaveProperty('external_id');
+ expect(sent.deliveries[0]).toMatchObject({ refused: false });
+ });
+
+ it('refuses before reserving when Framer isn’t set up, connected or ready to take pages', async () => {
+ db.wordpressConfigured = false;
+ await expect(toFramer()).rejects.toMatchObject({
+ code: 'framer_not_configured',
+ status: 503,
+ message: 'Framer is not set up on this server.',
+ });
+ db.wordpressConfigured = true;
+ await expect(toFramer()).rejects.toMatchObject({
+ code: 'no_framer',
+ status: 409,
+ message: 'Connect Framer in Settings › Integrations.',
+ });
+ db.framer = { ...connection, status: 'auth_failed' };
+ await expect(toFramer()).rejects.toMatchObject({ code: 'framer_refused', status: 409 });
+ for (const ready of [
+ { collection_id: null },
+ { field_map: { body: 'fBody' } },
+ { field_map: { title: 'fTitle' } },
+ ]) {
+ db.framer = { ...connection, ...ready };
+ await expect(toFramer()).rejects.toMatchObject({
+ code: 'framer_not_ready',
+ status: 409,
+ message: 'Pick the Framer collection and its fields in Settings › Integrations.',
+ });
+ }
+ // A WordPress connection isn't a Framer one.
+ db.framer = null;
+ db.wordpress = {
+ id: 'cn2',
+ brand_id: 'b1',
+ status: 'connected',
+ site_url: 'https://x.example',
+ };
+ await expect(toFramer()).rejects.toMatchObject({ code: 'no_framer' });
+ expect(db.rpc).toEqual([]);
+ expect(sendToFramer).not.toHaveBeenCalled();
+ });
+
+ it('refuses a page already on its way to Framer, naming it', async () => {
+ db.framer = connection;
+ db.rpcError = { message: 'delivery_in_progress' };
+ await expect(toFramer()).rejects.toMatchObject({
+ code: 'in_progress',
+ message: 'A page is already being sent to Framer. Wait for it, then send again.',
+ });
+ });
+
+ it('stops a batch once Framer refuses the key, closing the rest with the reason', async () => {
+ vi.useFakeTimers();
+ db.framer = connection;
+ const second = page({ draftId: 'c0ffee00-0000-4000-8000-000000000002', slug: 'second' });
+ db.drafts = [draft(page().draftId), draft(second.draftId)];
+ db.queued = [row(page().draftId), row(second.draftId)];
+ sendToFramer.mockResolvedValue({
+ taken: false,
+ failure: 'Framer refused the API key.',
+ refused: true,
+ });
+ await toFramer([page(), second]);
+ await vi.runAllTimersAsync();
+ expect(sendToFramer).toHaveBeenCalledTimes(1);
+ const closed = db.updates.filter(
+ (u) =>
+ u.table === 'content_draft_deliveries' && u.update.error === 'Framer refused the API key.',
+ );
+ expect(closed).toHaveLength(2);
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index c9d044f3b..270d21f96 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -23,7 +23,7 @@ import { PlanLimitError } from '../lib/plan-guard.js';
* (CE-018); Hand off has it fix the page's open Quality checks (CE-051);
* Start's Agent has the Content Agent do the page (CE-015);
* Stop ends the agent's run under way, changing nothing (v1.1 CE-027); and
- * Send to CMS sends pages to the brand's webhook, its Webflow collection or its WordPress site (#1331).
+ * Send to CMS sends pages to the brand's webhook, its Webflow or Framer collection or its WordPress site (#1331).
*/
const router = Router();
@@ -49,7 +49,7 @@ async function assertSender(userId) {
/**
* POST /api/content-drafts/send
- * Body: { brandId, target?: 'webhook' | 'webflow' | 'wordpress', pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }
+ * Body: { brandId, target?: 'webhook' | 'webflow' | 'wordpress' | 'framer', pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }
* One page is sent before this answers: { deliveries: [{ id, status, http_status, error }] };
* more (up to 25) go on in the background: { batchId, deliveries: queued, skipped }.
*/