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): mark a page published once its Framer item is live on the site (#1331) (#1579)

Cihane56261b131d0
diff --git a/server/src/lib/cms/framer-status.js b/server/src/lib/cms/framer-status.js
new file mode 100644
index 000000000..ef45bf4aa
--- /dev/null
+++ b/server/src/lib/cms/framer-status.js
@@ -0,0 +1,237 @@
+import supabaseAdmin from '../../config/supabase.js';
+import { isSubscriptionActive } from '../../config/plans.js';
+import { logger } from '../logger.js';
+import { credentialsConfigured } from '../catalog/credentials.js';
+import { liveAddress, markDeliveryPublished } from '../content-published.js';
+import { readCmsCredentials } from './credentials.js';
+import { FramerError, readPublished } from './framer.js';
+
+/**
+ * Pages sent to Framer, published there since (Send to CMS #1331, phase 2;
+ * 00295): nothing calls back when a Framer site is published, so Ansvisor
+ * reads the items its sends made, in one connection to the project. An item
+ * goes live with the site's publish once it isn't a draft, so a send is
+ * marked published at the item's page (the site's address, the collection's
+ * detail page path with the item's slug) when the item isn't a draft and the
+ * site was published after the send and after the item's last change (an
+ * item taken out of draft since the publish isn't on the site yet). An item
+ * published before (a live page sent again) waits for the site's next
+ * publish; an item deleted in Framer
+ * closes its send. Read when the Library opens (a brand's newest sends,
+ * throttled by its route) and once a day for all, as WordPress's are
+ * (wordpress-status.js).
+ */
+
+/** Items the Library's check reads: the newest sends. The daily sweep reads the rest. */
+export const ITEMS_ON_DEMAND = 10;
+/** Items the daily sweep reads a brand. */
+export const ITEMS_DAILY = 100;
+/** Sends older than this aren't read again: a draft left that long stays one. */
+const LOOK_BACK_MS = 60 * 24 * 60 * 60 * 1000;
+/** Connections the daily sweep reads, shuffled so a deadline doesn't leave the same brands out. */
+const SWEEP_CONNECTIONS = 1000;
+const SWEEP_DEADLINE_MS = 10 * 60 * 1000;
+
+const none = { checked: 0, published: [] };
+
+/** The key was refused while reading: Settings asks for a new one (as the send read it). */
+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 }, '[framer-status] refusal not kept');
+}
+
+/** A send whose item is gone from the collection: closed. The page's next send makes a new item. */
+async function closeRemoved(send) {
+ const { error } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .update({ status: 'failed', error: 'Removed in Framer' })
+ .eq('id', send.id)
+ .eq('status', 'sent');
+ if (error) {
+ logger.warn({ err: error, deliveryId: send.id }, '[framer-status] removal not kept');
+ }
+}
+
+const logged = (err) => ({ name: err?.name, code: err?.code });
+
+/**
+ * An item's page on the site: the detail page's path with the item's slug
+ * for ":slug", as a published address is kept (liveAddress: at most 2048
+ * characters) and https. Else why it has none: 'path' (no ":slug", or
+ * another parameter), 'slug' (the item has none) or 'address'.
+ *
+ * @returns {{ url: string } | { problem: 'path'|'slug'|'address' }}
+ */
+function pageAddress(siteUrl, detailPath, slug) {
+ const params = detailPath.match(/:[A-Za-z_][A-Za-z0-9_]*/g) ?? [];
+ if (params.length !== 1 || params[0] !== ':slug') return { problem: 'path' };
+ if (typeof slug !== 'string' || !slug.trim()) return { problem: 'slug' };
+ const path = detailPath.replace(':slug', encodeURIComponent(slug));
+ const url = liveAddress(`${siteUrl}${path.startsWith('/') ? '' : '/'}${path}`);
+ return url?.startsWith('https://') ? { url } : { problem: 'address' };
+}
+
+/** Why a page has no address, as logged. */
+const UNPLACED = {
+ path: '[framer-status] detail page path has no :slug, or another parameter',
+ slug: '[framer-status] item has no slug',
+ address: '[framer-status] page address not https, or too long',
+};
+
+/**
+ * Reads the brand's pages sent to Framer and not yet seen live (each page's
+ * latest such send to the connected collection, newest first, up to
+ * `limit`), and marks the published ones published. A key refused marks the
+ * connection; any other failure to read the project is logged and leaves
+ * the sends for the next check. `connect` replaces framer-api's in tests.
+ *
+ * @returns {Promise<{ checked: number, published: { draftId: string|null, url: string }[] }>}
+ */
+export async function checkFramerPublished(brandId, { limit = ITEMS_ON_DEMAND, connect } = {}) {
+ if (!credentialsConfigured()) return none;
+ const { data: connection, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .select('id, brand_id, status, site_id, collection_id, updated_at')
+ .eq('brand_id', brandId)
+ .eq('provider', 'framer')
+ .maybeSingle();
+ if (error) throw new Error(error.message);
+ if (
+ !connection ||
+ connection.status !== 'connected' ||
+ !connection.site_id ||
+ !connection.collection_id
+ ) {
+ return none;
+ }
+
+ // The connected collection's sends only: an item in one picked before isn't read.
+ const { data: rows, error: rowsError } = await supabaseAdmin
+ .from('content_draft_deliveries')
+ .select('id, draft_id, status, published_url, external_id, target_collection, sent_at')
+ .eq('brand_id', brandId)
+ .eq('target', 'framer')
+ .eq('target_collection', connection.collection_id)
+ .eq('status', 'sent')
+ .not('external_id', 'is', null)
+ .gte('sent_at', new Date(Date.now() - LOOK_BACK_MS).toISOString())
+ .order('sent_at', { ascending: false })
+ .limit(limit * 4);
+ if (rowsError) throw new Error(rowsError.message);
+ // A page's latest send: an earlier one made the same item, updated since, or one replaced.
+ const seen = new Set();
+ const sends = [];
+ for (const row of rows ?? []) {
+ const key = row.draft_id ?? row.id;
+ if (seen.has(key)) continue;
+ seen.add(key);
+ sends.push(row);
+ if (sends.length === limit) break;
+ }
+ if (!sends.length) return none;
+
+ const credentials = await readCmsCredentials(connection.id);
+ if (!credentials?.apiKey) {
+ await markRefused(connection);
+ return none;
+ }
+ let read;
+ try {
+ read = await readPublished(
+ connection.site_id,
+ credentials.apiKey,
+ connection.collection_id,
+ sends.map((send) => send.external_id),
+ { connect },
+ );
+ } catch (err) {
+ if (err instanceof FramerError && err.code === 'auth_failed') {
+ await markRefused(connection);
+ return none;
+ }
+ // Framer busy or down, the collection gone: the sends wait for the next check.
+ logger.warn({ err: logged(err), brandId }, '[framer-status] project not read');
+ return none;
+ }
+
+ const { siteUrl, deployedAt, detailPath } = read;
+ const published = [];
+ let checked = 0;
+ let unplaced = false;
+ for (const send of sends) {
+ checked++;
+ const item = read.items.get(send.external_id);
+ if (!item) {
+ await closeRemoved(send);
+ continue;
+ }
+ // Live with a publish since the send: a live item sent again waits for the site's next one.
+ const sentAt = Date.parse(send.sent_at ?? '');
+ if (item.draft || !siteUrl || !detailPath || deployedAt === null || !(deployedAt > sentAt)) {
+ continue;
+ }
+ // And since the item's last change: one taken out of draft after the publish isn't live yet.
+ // Framer may not give the time; the send's then decides alone.
+ if (item.updatedAt !== null && item.updatedAt !== undefined) {
+ if (!(deployedAt >= Date.parse(item.updatedAt))) continue;
+ }
+ const { url, problem } = pageAddress(siteUrl, detailPath, item.slug);
+ if (!url) {
+ // The path is every page's: logged once a check. An item's own, by its send.
+ if (problem === 'path') {
+ if (!unplaced) logger.warn({ brandId }, UNPLACED.path);
+ unplaced = true;
+ } else {
+ logger.warn({ brandId, deliveryId: send.id }, UNPLACED[problem]);
+ }
+ continue;
+ }
+ await markDeliveryPublished(send, url);
+ published.push({ draftId: send.draft_id, url });
+ }
+ return { checked, published };
+}
+
+/**
+ * The daily check, for brands with Framer connected to a collection (on an
+ * active subscription), in a shuffled order so the deadline leaves out
+ * different brands each day; one brand's failure is logged and the next
+ * goes on.
+ */
+export async function sweepFramerPublished() {
+ if (!credentialsConfigured()) return { brands: 0, published: 0 };
+ const started = Date.now();
+ const { data, error } = await supabaseAdmin
+ .from('brand_cms_connections')
+ .select('brand_id, brands!inner(organizations!inner(subscription_status))')
+ .eq('provider', 'framer')
+ .eq('status', 'connected')
+ .not('collection_id', 'is', null)
+ .limit(SWEEP_CONNECTIONS);
+ if (error) throw new Error(`brand_cms_connections read: ${error.message}`);
+ const due = (data ?? []).filter((row) =>
+ isSubscriptionActive(row.brands?.organizations?.subscription_status),
+ );
+ for (let i = due.length - 1; i > 0; i--) {
+ const j = Math.floor(Math.random() * (i + 1));
+ [due[i], due[j]] = [due[j], due[i]];
+ }
+ let brands = 0;
+ let published = 0;
+ for (const row of due) {
+ if (Date.now() - started > SWEEP_DEADLINE_MS) break;
+ try {
+ const result = await checkFramerPublished(row.brand_id, { limit: ITEMS_DAILY });
+ brands++;
+ published += result.published.length;
+ } catch (err) {
+ logger.error({ err: logged(err), brandId: row.brand_id }, '[framer-status] check failed');
+ }
+ }
+ return { brands, published };
+}
diff --git a/server/src/lib/cms/framer-status.test.js b/server/src/lib/cms/framer-status.test.js
new file mode 100644
index 000000000..97e414a32
--- /dev/null
+++ b/server/src/lib/cms/framer-status.test.js
@@ -0,0 +1,461 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * Pages sent to Framer, published there since (Send to CMS #1331, phase 2;
+ * 00295): read from the items the sends made, in one connection, and marked
+ * published at the item's page once the site was published after the send.
+ */
+
+const db = { connection: null, sends: [], brands: [], queries: [], updates: [] };
+vi.mock('../../config/supabase.js', () => ({
+ default: {
+ from: (table) => {
+ const q = { table, filters: [] };
+ const result = () => {
+ if (q.update) {
+ db.updates.push({ table, update: q.update, filters: q.filters });
+ return { data: null, error: null };
+ }
+ db.queries.push(q);
+ if (table === 'brand_cms_connections') {
+ return { data: q.single ? db.connection : db.brands, error: null };
+ }
+ return { data: db.sends, error: null };
+ };
+ const chain = {
+ select: () => chain,
+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),
+ not: (col, op, value) => (q.filters.push(['not', col, op, value]), chain),
+ gte: (col, value) => (q.filters.push(['gte', col, value]), chain),
+ order: () => chain,
+ limit: (n) => ((q.limit = n), chain),
+ update: (row) => ((q.update = row), chain),
+ maybeSingle: async () => ((q.single = true), result()),
+ then: (resolve) => resolve(result()),
+ };
+ return chain;
+ },
+ },
+}));
+const configured = vi.hoisted(() => ({ on: true }));
+vi.mock('../catalog/credentials.js', () => ({ credentialsConfigured: () => configured.on }));
+let credentials;
+vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));
+const markDeliveryPublished = vi.fn();
+vi.mock('../content-published.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ markDeliveryPublished: (...args) => markDeliveryPublished(...args),
+}));
+const readPublished = vi.fn();
+vi.mock('./framer.js', async (importOriginal) => ({
+ ...(await importOriginal()),
+ readPublished: (...args) => readPublished(...args),
+}));
+const logged = { warn: [], error: [] };
+vi.mock('../logger.js', () => ({
+ logger: {
+ warn: (...args) => logged.warn.push(JSON.stringify(args)),
+ error: (...args) => logged.error.push(JSON.stringify(args)),
+ },
+}));
+
+const { checkFramerPublished, sweepFramerPublished } = await import('./framer-status.js');
+const { FramerError } = await import('./framer.js');
+
+const PROJECT = 'AbCdEfGhIj0123456789';
+const KEY = 'fr_key_0123456789abcdefSECRET';
+const SITE = 'https://www.acme.example';
+const SENT_AT = '2026-10-24T10:00:00Z';
+const AFTER = Date.parse('2026-10-24T12:00:00Z');
+const BEFORE = Date.parse('2026-10-24T09:00:00Z');
+
+const send = (id, draftId, over = {}) => ({
+ id,
+ draft_id: draftId,
+ status: 'sent',
+ published_url: null,
+ external_id: `item-${id}`,
+ target_collection: 'cBlog',
+ sent_at: SENT_AT,
+ ...over,
+});
+/** The project as readPublished reads it: the items by id, as framer.js maps them. */
+const project = (items, over = {}) => ({
+ siteUrl: SITE,
+ deployedAt: AFTER,
+ detailPath: '/blog/:slug',
+ items: new Map(Object.entries(items)),
+ ...over,
+});
+
+beforeEach(() => {
+ configured.on = true;
+ credentials = { apiKey: KEY };
+ db.connection = {
+ id: 'cn1',
+ brand_id: 'b1',
+ status: 'connected',
+ site_id: PROJECT,
+ collection_id: 'cBlog',
+ updated_at: '2026-10-27T09:00:00Z',
+ };
+ db.sends = [];
+ db.brands = [];
+ db.queries = [];
+ db.updates = [];
+ logged.warn.length = 0;
+ logged.error.length = 0;
+ markDeliveryPublished.mockReset().mockResolvedValue(undefined);
+ readPublished.mockReset();
+});
+
+const deliveryQuery = () => db.queries.find((q) => q.table === 'content_draft_deliveries');
+
+describe('checkFramerPublished', () => {
+ it('marks an item live since the site’s publish published at its page, and leaves a draft', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2')];
+ readPublished.mockResolvedValue(
+ project({
+ 'item-d1': { slug: 'cold-brew', draft: false },
+ 'item-d2': { slug: 'espresso', draft: true },
+ }),
+ );
+ const connect = vi.fn();
+ expect(await checkFramerPublished('b1', { connect })).toEqual({
+ checked: 2,
+ published: [{ draftId: 'dr1', url: `${SITE}/blog/cold-brew` }],
+ });
+ expect(markDeliveryPublished).toHaveBeenCalledTimes(1);
+ expect(markDeliveryPublished).toHaveBeenCalledWith(db.sends[0], `${SITE}/blog/cold-brew`);
+ // One read for every send, with the connection's project, key and collection.
+ expect(readPublished).toHaveBeenCalledTimes(1);
+ expect(readPublished).toHaveBeenCalledWith(PROJECT, KEY, 'cBlog', ['item-d1', 'item-d2'], {
+ connect,
+ });
+ // The connected collection's sends only, sent and not seen live, with their item.
+ expect(deliveryQuery().filters).toEqual([
+ ['eq', 'brand_id', 'b1'],
+ ['eq', 'target', 'framer'],
+ ['eq', 'target_collection', 'cBlog'],
+ ['eq', 'status', 'sent'],
+ ['not', 'external_id', 'is', null],
+ ['gte', 'sent_at', expect.any(String)],
+ ]);
+ expect(db.updates).toEqual([]);
+ });
+
+ it('puts the slug in the page’s address as a path segment', async () => {
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockResolvedValue(
+ project({ 'item-d1': { slug: 'café au lait', draft: false } }, { detailPath: 'posts/:slug' }),
+ );
+ expect((await checkFramerPublished('b1')).published).toEqual([
+ { draftId: 'dr1', url: `${SITE}/posts/caf%C3%A9%20au%20lait` },
+ ]);
+ });
+
+ it('closes a send whose item was deleted in Framer', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2')];
+ readPublished.mockResolvedValue(project({ 'item-d2': { slug: 'espresso', draft: true } }));
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 2, published: [] });
+ expect(db.updates).toEqual([
+ {
+ table: 'content_draft_deliveries',
+ update: { status: 'failed', error: 'Removed in Framer' },
+ filters: [
+ ['eq', 'id', 'd1'],
+ ['eq', 'status', 'sent'],
+ ],
+ },
+ ]);
+ });
+
+ it('waits for the site’s next publish when it was last published before the send', async () => {
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockResolvedValue(
+ project({ 'item-d1': { slug: 'cold-brew', draft: false } }, { deployedAt: BEFORE }),
+ );
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 1, published: [] });
+ // Published the very moment of the send: still not after it.
+ readPublished.mockResolvedValue(
+ project(
+ { 'item-d1': { slug: 'cold-brew', draft: false } },
+ { deployedAt: Date.parse(SENT_AT) },
+ ),
+ );
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 1, published: [] });
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ expect(db.updates).toEqual([]);
+ });
+
+ it('waits for the site’s next publish when the item was taken out of draft after the last one', async () => {
+ db.sends = [send('d1', 'dr1')];
+ const live = (updatedAt) =>
+ project({ 'item-d1': { slug: 'cold-brew', draft: false, updatedAt } });
+ // Sent at 10:00, the site published at 12:00, the item taken out of draft at 13:00.
+ readPublished.mockResolvedValue(live('2026-10-24T13:00:00.000Z'));
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 1, published: [] });
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ // Taken out of draft at 11:00, or the very moment of the publish: on the site.
+ for (const updatedAt of ['2026-10-24T11:00:00.000Z', new Date(AFTER).toISOString()]) {
+ readPublished.mockResolvedValue(live(updatedAt));
+ expect((await checkFramerPublished('b1')).published, updatedAt).toEqual([
+ { draftId: 'dr1', url: `${SITE}/blog/cold-brew` },
+ ]);
+ }
+ expect(markDeliveryPublished).toHaveBeenCalledTimes(2);
+ });
+
+ it('goes by the send’s time alone when Framer gives no time for the item’s last change', async () => {
+ db.sends = [send('d1', 'dr1')];
+ const items = { 'item-d1': { slug: 'cold-brew', draft: false, updatedAt: null } };
+ readPublished.mockResolvedValue(project(items));
+ expect((await checkFramerPublished('b1')).published).toEqual([
+ { draftId: 'dr1', url: `${SITE}/blog/cold-brew` },
+ ]);
+ readPublished.mockResolvedValue(project(items, { deployedAt: BEFORE }));
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 1, published: [] });
+ expect(markDeliveryPublished).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits while the collection has no detail page, or the site was never published', async () => {
+ db.sends = [send('d1', 'dr1')];
+ const items = { 'item-d1': { slug: 'cold-brew', draft: false } };
+ for (const over of [
+ { detailPath: null },
+ { siteUrl: null, deployedAt: null },
+ { deployedAt: null },
+ ]) {
+ readPublished.mockResolvedValue(project(items, over));
+ expect(await checkFramerPublished('b1'), JSON.stringify(over)).toEqual({
+ checked: 1,
+ published: [],
+ });
+ }
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ expect(db.updates).toEqual([]);
+ });
+
+ it('marks nothing when the detail page’s path has no :slug, or another parameter, and logs it', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2')];
+ const items = {
+ 'item-d1': { slug: 'cold-brew', draft: false },
+ 'item-d2': { slug: 'espresso', draft: false },
+ };
+ for (const detailPath of ['/blog/:id', '/blog', '/:category/:slug', '/blog/:slugged']) {
+ logged.warn.length = 0;
+ readPublished.mockResolvedValue(project(items, { detailPath }));
+ expect(await checkFramerPublished('b1'), detailPath).toEqual({ checked: 2, published: [] });
+ // Once a check, not once a page.
+ expect(logged.warn).toHaveLength(1);
+ expect(logged.warn[0]).toContain('detail page path has no :slug');
+ }
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ });
+
+ it('logs an item with no slug apart from the path, and goes on to the next page', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2'), send('d3', 'dr3')];
+ readPublished.mockResolvedValue(
+ project({
+ 'item-d1': { slug: '', draft: false },
+ 'item-d2': { slug: ' ', draft: false },
+ 'item-d3': { slug: 'cold-brew', draft: false },
+ }),
+ );
+ expect(await checkFramerPublished('b1')).toEqual({
+ checked: 3,
+ published: [{ draftId: 'dr3', url: `${SITE}/blog/cold-brew` }],
+ });
+ // Each by its send, not as the path's.
+ expect(logged.warn).toHaveLength(2);
+ expect(logged.warn[0]).toContain('item has no slug');
+ expect(logged.warn[0]).toContain('"deliveryId":"d1"');
+ expect(logged.warn[1]).toContain('"deliveryId":"d2"');
+ expect(logged.warn.join('\n')).not.toContain('detail page path');
+ });
+
+ it('marks no page whose address is too long to keep, and goes on to the next', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2')];
+ readPublished.mockResolvedValue(
+ project({
+ 'item-d1': { slug: 'a'.repeat(2100), draft: false },
+ 'item-d2': { slug: 'cold-brew', draft: false },
+ }),
+ );
+ expect(await checkFramerPublished('b1')).toEqual({
+ checked: 2,
+ published: [{ draftId: 'dr2', url: `${SITE}/blog/cold-brew` }],
+ });
+ expect(markDeliveryPublished).toHaveBeenCalledTimes(1);
+ expect(logged.warn).toHaveLength(1);
+ expect(logged.warn[0]).toContain('page address not https, or too long');
+ expect(logged.warn[0]).toContain('"deliveryId":"d1"');
+ });
+
+ it('marks no page on a site address that isn’t https', async () => {
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockResolvedValue(
+ project(
+ { 'item-d1': { slug: 'cold-brew', draft: false } },
+ { siteUrl: 'http://www.acme.example' },
+ ),
+ );
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 1, published: [] });
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ expect(logged.warn[0]).toContain('page address not https');
+ });
+
+ it('stops at a page that can’t be marked, as WordPress’s check does, for the caller to log', async () => {
+ db.sends = [send('d1', 'dr1'), send('d2', 'dr2'), send('d3', 'dr3')];
+ readPublished.mockResolvedValue(
+ project({
+ 'item-d1': { slug: 'cold-brew', draft: false },
+ 'item-d2': { slug: 'espresso', draft: false },
+ 'item-d3': { slug: 'latte', draft: false },
+ }),
+ );
+ markDeliveryPublished
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(new Error('db down'));
+ await expect(checkFramerPublished('b1')).rejects.toThrow('db down');
+ // The first page is marked; the third waits for the next check (its send is still 'sent').
+ expect(markDeliveryPublished).toHaveBeenCalledTimes(2);
+ expect(markDeliveryPublished.mock.calls.map(([delivery]) => delivery.id)).toEqual(['d1', 'd2']);
+ });
+
+ it('reads each page’s latest send only, and only as many pages as asked', async () => {
+ db.sends = [
+ send('d2', 'dr1'),
+ send('d1', 'dr1', { sent_at: '2026-10-20T10:00:00Z' }),
+ send('d3', 'dr3'),
+ send('d4', null),
+ ];
+ readPublished.mockResolvedValue(project({}));
+ await checkFramerPublished('b1');
+ expect(readPublished.mock.calls[0][3]).toEqual(['item-d2', 'item-d3', 'item-d4']);
+ expect(deliveryQuery().limit).toBe(40);
+ readPublished.mockClear();
+ db.queries = [];
+ await checkFramerPublished('b1', { limit: 2 });
+ expect(readPublished.mock.calls[0][3]).toEqual(['item-d2', 'item-d3']);
+ expect(deliveryQuery().limit).toBe(8);
+ });
+
+ it('reads the sends of the last 60 days only', async () => {
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockResolvedValue(project({}));
+ const before = Date.now();
+ await checkFramerPublished('b1');
+ const after = Date.now();
+ const since = Date.parse(deliveryQuery().filters.find((f) => f[0] === 'gte')[2]);
+ const sixtyDays = 60 * 24 * 60 * 60 * 1000;
+ expect(since).toBeGreaterThanOrEqual(before - sixtyDays);
+ expect(since).toBeLessThanOrEqual(after - sixtyDays);
+ });
+
+ it('marks the connection refused, as it was read, when Framer refuses the key', async () => {
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockRejectedValue(new FramerError('auth_failed', 'refused'));
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ expect(db.updates).toEqual([
+ {
+ table: 'brand_cms_connections',
+ update: { status: 'auth_failed', updated_at: expect.any(String) },
+ filters: [
+ ['eq', 'id', 'cn1'],
+ ['eq', 'provider', 'framer'],
+ ['eq', 'updated_at', '2026-10-27T09:00:00Z'],
+ ],
+ },
+ ]);
+ expect(markDeliveryPublished).not.toHaveBeenCalled();
+ });
+
+ it('leaves the sends for the next check when Framer can’t be read, logging no message', async () => {
+ db.sends = [send('d1', 'dr1')];
+ for (const err of [
+ new FramerError('busy', `Framer is busy for ${KEY}`),
+ new FramerError('not_found', 'The collection pages go to is gone'),
+ new TypeError(`x of ${KEY}`),
+ ]) {
+ readPublished.mockRejectedValueOnce(err);
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ }
+ expect(db.updates).toEqual([]);
+ expect(logged.warn).toHaveLength(3);
+ expect(logged.warn.join('\n')).not.toContain(KEY);
+ expect(logged.warn[0]).toContain('"code":"busy"');
+ });
+
+ it('asks to connect again when the kept key can’t be read', async () => {
+ db.sends = [send('d1', 'dr1')];
+ credentials = null;
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ credentials = { username: 'not-a-framer-key' };
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ expect(readPublished).not.toHaveBeenCalled();
+ expect(db.updates.map((u) => [u.table, u.update.status])).toEqual([
+ ['brand_cms_connections', 'auth_failed'],
+ ['brand_cms_connections', 'auth_failed'],
+ ]);
+ });
+
+ it('reads nothing without the server’s key, a connection, a connected one with a collection, or sends', async () => {
+ db.sends = [send('d1', 'dr1')];
+ configured.on = false;
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ configured.on = true;
+ for (const connection of [
+ null,
+ { ...db.connection, status: 'auth_failed' },
+ { ...db.connection, collection_id: null },
+ ]) {
+ db.connection = connection;
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ }
+ expect(deliveryQuery()).toBeUndefined();
+ db.connection = { ...db.connection, collection_id: 'cBlog' };
+ db.sends = [];
+ expect(await checkFramerPublished('b1')).toEqual({ checked: 0, published: [] });
+ expect(readPublished).not.toHaveBeenCalled();
+ expect(db.updates).toEqual([]);
+ });
+});
+
+describe('sweepFramerPublished', () => {
+ it('reads the brands of active subscriptions, going on past one that fails', async () => {
+ db.brands = [
+ { brand_id: 'b1', brands: { organizations: { subscription_status: 'active' } } },
+ { brand_id: 'b2', brands: { organizations: { subscription_status: 'canceled' } } },
+ { brand_id: 'b3', brands: { organizations: { subscription_status: 'trialing' } } },
+ ];
+ db.sends = [send('d1', 'dr1')];
+ readPublished.mockResolvedValue(project({ 'item-d1': { slug: 'cold-brew', draft: false } }));
+ markDeliveryPublished.mockRejectedValueOnce(new Error('down'));
+ // On the cloud, where subscriptions count.
+ vi.stubEnv('IS_CLOUD', 'true');
+ expect(await sweepFramerPublished()).toEqual({ brands: 1, published: 1 });
+ vi.unstubAllEnvs();
+ // The brand that failed (the order is shuffled daily) is logged; the other went on.
+ expect(logged.error).toHaveLength(1);
+ expect(logged.error[0]).toMatch(/"brandId":"b[13]"/);
+ expect(readPublished).toHaveBeenCalledTimes(2);
+ // The connections read: Framer's, connected, with a collection pages go to.
+ expect(db.queries[0]).toMatchObject({
+ table: 'brand_cms_connections',
+ filters: [
+ ['eq', 'provider', 'framer'],
+ ['eq', 'status', 'connected'],
+ ['not', 'collection_id', 'is', null],
+ ],
+ });
+ // The daily sweep reads more of a brand's pages than the Library does.
+ expect(db.queries.find((q) => q.table === 'content_draft_deliveries').limit).toBe(400);
+ });
+
+ it('does nothing on a server that can’t keep a key', async () => {
+ configured.on = false;
+ expect(await sweepFramerPublished()).toEqual({ brands: 0, published: 0 });
+ expect(db.queries).toEqual([]);
+ });
+});
diff --git a/server/src/lib/cms/framer.js b/server/src/lib/cms/framer.js
index 149e047bd..463804aa4 100644
--- a/server/src/lib/cms/framer.js
+++ b/server/src/lib/cms/framer.js
@@ -13,6 +13,8 @@ import {
*
* Each use opens a WebSocket to Framer (wss://api.framer.com) and closes it
* once done (withProject): one left open keeps the process from exiting.
+ * Pages published since a send are read the same way (readPublished,
+ * framer-status.js).
*
* The key is never put in a message, a log or an answer. Our answers and
* logs carry our own words, never Framer's messages; framer-api's own
@@ -403,6 +405,92 @@ export async function writeItem(
);
}
+/** A publish time further ahead than this is a unit read wrong: nothing is marked on it. */
+const AHEAD_MS = 10 * 60 * 1000;
+
+/**
+ * When the site was last published, in ms, or null. The unit of
+ * `deploymentTime` is undocumented by Framer: framer-api (5.1.0) types it as
+ * a plain number, so this is a guess. One too small to be ms since 1970
+ * (before 1973) is read as seconds; a time read as more than ten minutes
+ * ahead is none, so a wrong guess marks nothing published.
+ */
+function deployedAtOf(production) {
+ const time = production?.deploymentTime;
+ if (typeof time !== 'number' || !Number.isFinite(time) || time <= 0) return null;
+ const ms = time < 1e11 ? time * 1000 : time;
+ return ms > Date.now() + AHEAD_MS ? null : ms;
+}
+
+/**
+ * The path of the collection's detail page ("/blog/:slug"), a draft page
+ * left out (it isn't published); of more than one, the shortest.
+ */
+function detailPathOf(pages, collectionId) {
+ let best = null;
+ for (const page of pages ?? []) {
+ const path = typeof page?.path === 'string' ? page.path.trim() : '';
+ if (page?.collectionId !== collectionId || page.draft || !path) continue;
+ if (best === null || path.length < best.length) best = path;
+ }
+ return best;
+}
+
+/**
+ * What tells whether the items pages were sent as are live (framer-status.js),
+ * read in one connection: the site's published address and when it was last
+ * published (production; none while the site isn't), the path of the
+ * collection's detail page, and the asked-for items' slugs, draft state and
+ * last change. An item gone from the collection isn't in the map.
+ *
+ * @param {string} project the connection's project (site_id)
+ * @param {string[]} itemIds
+ * @returns {Promise<{ siteUrl: string|null, deployedAt: number|null, detailPath: string|null,
+ * items: Map<string, { slug: string, draft: boolean, updatedAt: string|null }> }>}
+ * deployedAt: in ms; updatedAt: the item's ISO time, when Framer gives it
+ */
+export async function readPublished(project, apiKey, collectionId, itemIds, 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, publish, pages] = await Promise.all([
+ collection.getItems(),
+ framer.getPublishInfo(),
+ framer.getNodesWithType('WebPageNode'),
+ ]);
+ const wanted = new Set(itemIds);
+ const production = publish?.production ?? null;
+ return {
+ siteUrl: siteUrlOf(production),
+ deployedAt: deployedAtOf(production),
+ detailPath: detailPathOf(pages, collectionId),
+ // A draft state Framer doesn't give is read as a draft: nothing is marked live on a guess.
+ items: new Map(
+ items
+ .filter((item) => wanted.has(item.id))
+ .map((item) => [
+ item.id,
+ {
+ slug: item.slug,
+ draft: item.draft !== false,
+ updatedAt: typeof item.updatedAt === 'string' ? item.updatedAt : null,
+ },
+ ]),
+ ),
+ };
+ },
+ 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 ca9d0bc2f..f54b18fb0 100644
--- a/server/src/lib/cms/framer.test.js
+++ b/server/src/lib/cms/framer.test.js
@@ -7,6 +7,7 @@ import {
collectionOf,
listCollections,
projectRef,
+ readPublished,
withProject,
writeItem,
} from './framer.js';
@@ -661,3 +662,129 @@ describe('writeItem', () => {
});
});
});
+
+describe('readPublished', () => {
+ /** A project with items, its site's publish and its web pages, as framer-api reads them. */
+ function publishedProject({
+ items = [
+ { id: 'i1', slug: 'cold-brew', draft: false, updatedAt: '2026-10-24T11:00:00.000Z' },
+ { id: 'i2', slug: 'espresso', draft: true },
+ { id: 'i3', slug: 'not-asked', draft: false },
+ ],
+ production = { url: 'https://www.acme.example/', deploymentTime: 1_761_600_000_000 },
+ pages = [
+ { path: '/', collectionId: null, draft: false },
+ { path: '/b/:slug', collectionId: 'cBlog', draft: true },
+ { path: '/archive/blog/:slug', collectionId: 'cBlog', draft: false },
+ { path: '/blog/:slug', collectionId: 'cBlog', draft: false },
+ { path: '/n/:slug', collectionId: 'cNews', draft: false },
+ ],
+ } = {}) {
+ const blog = {
+ ...collection('cBlog', 'Blog', 'user'),
+ getItems: vi.fn(async () => items.map((item) => ({ ...item }))),
+ };
+ const project = fakeProject({ production });
+ project.framer.getCollections = vi.fn(async () => [
+ blog,
+ collection('cSynced', 'Synced', 'anotherPlugin'),
+ ]);
+ project.framer.getNodesWithType = vi.fn(async () => pages);
+ return { ...project, blog };
+ }
+ const read = (connect, collectionId = 'cBlog', ids = ['i1', 'i2', 'gone']) =>
+ readPublished(PROJECT, KEY, collectionId, ids, { connect });
+
+ it('reads the site’s address and publish, the detail page, and the asked-for items', async () => {
+ const { framer, connect } = publishedProject();
+ const result = await read(connect);
+ expect(result).toEqual({
+ siteUrl: 'https://www.acme.example',
+ deployedAt: 1_761_600_000_000,
+ // The shortest of the collection's pages that aren't drafts.
+ detailPath: '/blog/:slug',
+ items: new Map([
+ ['i1', { slug: 'cold-brew', draft: false, updatedAt: '2026-10-24T11:00:00.000Z' }],
+ // An item without its last change's time has none.
+ ['i2', { slug: 'espresso', draft: true, updatedAt: null }],
+ ]),
+ });
+ // An item gone from the collection isn't in the map.
+ expect(result.items.has('gone')).toBe(false);
+ expect(connect).toHaveBeenCalledWith(PROJECT, KEY);
+ expect(framer.getNodesWithType).toHaveBeenCalledWith('WebPageNode');
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+
+ it('finds no detail page when the collection’s only one is a draft, or it has none', async () => {
+ const drafted = publishedProject({
+ pages: [{ path: '/blog/:slug', collectionId: 'cBlog', draft: true }],
+ });
+ expect((await read(drafted.connect)).detailPath).toBeNull();
+ const without = publishedProject({
+ pages: [
+ { path: '/', collectionId: null, draft: false },
+ { path: null, collectionId: 'cBlog', draft: false },
+ ],
+ });
+ expect((await read(without.connect)).detailPath).toBeNull();
+ });
+
+ it('has no address or publish time for a site never published', async () => {
+ const { connect } = publishedProject({ production: null });
+ expect(await read(connect)).toMatchObject({ siteUrl: null, deployedAt: null });
+ });
+
+ it('reads a publish time given in seconds as ms', async () => {
+ const { connect } = publishedProject({
+ production: { url: 'https://acme.framer.website', deploymentTime: 1_761_600_000 },
+ });
+ expect((await read(connect)).deployedAt).toBe(1_761_600_000_000);
+ });
+
+ it('has no publish time it can’t read, or one ahead of now (a unit guessed wrong)', async () => {
+ const at = async (deploymentTime) =>
+ (
+ await read(
+ publishedProject({ production: { url: 'https://acme.framer.website', deploymentTime } })
+ .connect,
+ )
+ ).deployedAt;
+ for (const time of [0, -1, Number.NaN, Infinity, '1761600000000', null, undefined]) {
+ expect(await at(time), String(time)).toBeNull();
+ }
+ // In microseconds, or more than ten minutes ahead: none.
+ expect(await at(1_761_600_000_000_000)).toBeNull();
+ expect(await at(Date.now() + 11 * 60 * 1000)).toBeNull();
+ // A few minutes ahead (a clock a little off) is kept.
+ const soon = Date.now() + 5 * 60 * 1000;
+ expect(await at(soon)).toBe(soon);
+ });
+
+ it('reads an item whose draft state Framer doesn’t give as a draft', async () => {
+ const { connect } = publishedProject({ items: [{ id: 'i1', slug: 'cold-brew' }] });
+ expect((await read(connect)).items.get('i1')).toEqual({
+ slug: 'cold-brew',
+ draft: true,
+ updatedAt: null,
+ });
+ });
+
+ it('finds no collection gone from the project, or a plugin’s, and closes the connection', async () => {
+ for (const collectionId of ['cGone', 'cSynced']) {
+ const { framer, connect } = publishedProject();
+ await expect(read(connect, collectionId)).rejects.toMatchObject({ code: 'not_found' });
+ expect(framer.getNodesWithType).not.toHaveBeenCalled();
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ }
+ });
+
+ it('closes the connection when a read fails, in our words', async () => {
+ const { framer, connect } = publishedProject();
+ framer.getPublishInfo.mockRejectedValue(new FramerAPIError(`No ${KEY}`, 'UNAUTHORIZED'));
+ const err = await read(connect).catch((e) => e);
+ expect(err).toMatchObject({ code: 'auth_failed' });
+ expect(err.message).not.toContain(KEY);
+ expect(framer.disconnect).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/server/src/routes/content-drafts-send.test.js b/server/src/routes/content-drafts-send.test.js
index 402a49c1d..d2b57076e 100644
--- a/server/src/routes/content-drafts-send.test.js
+++ b/server/src/routes/content-drafts-send.test.js
@@ -33,6 +33,10 @@ const checkWordPressPublished = vi.fn();
vi.mock('../lib/cms/wordpress-status.js', () => ({
checkWordPressPublished: (...args) => checkWordPressPublished(...args),
}));
+const checkFramerPublished = vi.fn();
+vi.mock('../lib/cms/framer-status.js', () => ({
+ checkFramerPublished: (...args) => checkFramerPublished(...args),
+}));
vi.mock('../lib/content-delivery.js', async (importOriginal) => ({
...(await importOriginal()),
sendContentPages: (...args) => sendContentPages(...args),
@@ -229,3 +233,50 @@ describe('POST /api/content-drafts/wordpress-status (00294)', () => {
expect(await failed.json()).toEqual({ error: 'WordPress could not be read', code: 'failed' });
});
});
+
+describe('POST /api/content-drafts/framer-status (00295)', () => {
+ const check = (body) =>
+ fetch(`${baseUrl}/framer-status`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+
+ it('reads the brand’s Framer items for any member, a brand at most every two minutes', async () => {
+ role = 'member';
+ const brand = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
+ checkFramerPublished.mockReset().mockResolvedValue({
+ checked: 1,
+ published: [{ draftId: DRAFT, url: 'https://www.acme.example/blog/cold-brew' }],
+ });
+ expect(await (await check({ brandId: brand })).json()).toEqual({
+ checked: 1,
+ published: [{ draftId: DRAFT, url: 'https://www.acme.example/blog/cold-brew' }],
+ });
+ expect(assertBrandAccess).toHaveBeenCalledWith(brand, 'u1');
+ expect(checkFramerPublished).toHaveBeenCalledWith(brand);
+ expect(await (await check({ brandId: brand })).json()).toEqual({
+ checked: 0,
+ published: [],
+ recent: true,
+ });
+ expect(checkFramerPublished).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses another workspace’s brand and a malformed one, and names a failure', async () => {
+ checkFramerPublished.mockReset();
+ assertBrandAccess.mockRejectedValueOnce(
+ Object.assign(new Error('nope'), { status: 403, code: 'not_in_workspace' }),
+ );
+ const other = await check({ brandId: 'bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb' });
+ expect(other.status).toBe(403);
+ expect(await other.json()).toMatchObject({ code: 'not_in_workspace' });
+ expect(checkFramerPublished).not.toHaveBeenCalled();
+ expect((await check({ brandId: 'x' })).status).toBe(400);
+ expect((await check({})).status).toBe(400);
+ checkFramerPublished.mockReset().mockRejectedValue(new Error('down'));
+ const failed = await check({ brandId: 'cccccccc-cccc-cccc-cccc-cccccccccccc' });
+ expect(failed.status).toBe(502);
+ expect(await failed.json()).toEqual({ error: 'Framer could not be read', code: 'failed' });
+ });
+});
diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.js
index 270d21f96..9c1a6ee0e 100644
--- a/server/src/routes/content-drafts.js
+++ b/server/src/routes/content-drafts.js
@@ -7,6 +7,7 @@ import { qualityPhase } from '../lib/content-quality.js';
import { briefRules, rebuildDraftBrief, rebuildSources } from '../lib/content-brief.js';
import { NoShoppingPath, buildShoppingPath } from '../lib/shopping-path.js';
import { DeliveryError, sendContentPages, sendInput } from '../lib/content-delivery.js';
+import { checkFramerPublished } from '../lib/cms/framer-status.js';
import { checkWebflowPublished } from '../lib/cms/webflow-status.js';
import { checkWordPressPublished } from '../lib/cms/wordpress-status.js';
import { liveAddress, publishDraft } from '../lib/content-published.js';
@@ -203,6 +204,41 @@ router.post('/wordpress-status', cmsLimiter, async (req, res) => {
}
});
+/** A brand's Framer items read at most this often on demand (the daily sweep reads them too). */
+const framerChecked = new Map();
+
+/**
+ * POST /api/content-drafts/framer-status
+ * Body: { brandId }. Pages the brand sent to Framer, published there since,
+ * marked published at the item's page (cms/framer-status.js). As
+ * /webflow-status: any member, a brand at most every two minutes.
+ */
+router.post('/framer-status', cmsLimiter, async (req, res) => {
+ const parsed = webflowStatusBody.safeParse(req.body ?? {});
+ if (!parsed.success) return res.status(400).json({ error: 'Invalid request', code: 'invalid' });
+ const { brandId } = parsed.data;
+ try {
+ await assertBrandAccess(brandId, req.user.id);
+ const last = framerChecked.get(brandId) ?? 0;
+ if (Date.now() - last < WEBFLOW_STATUS_EVERY_MS) {
+ return res.json({ checked: 0, published: [], recent: true });
+ }
+ framerChecked.set(brandId, Date.now());
+ return res.json(await checkFramerPublished(brandId));
+ } catch (err) {
+ if (ERROR_CODES[err?.status]) {
+ return res
+ .status(err.status)
+ .json({ error: err.message, code: err.code ?? ERROR_CODES[err.status] });
+ }
+ req.log.error(
+ { err: { name: err?.name, code: err?.code } },
+ 'content draft framer status error',
+ );
+ return res.status(502).json({ error: 'Framer could not be read', code: 'failed' });
+ }
+});
+
const rebuildBody = z.object({
// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).
brandId: z.guid(),
diff --git a/server/src/server.js b/server/src/server.js
index d0f2fa759..9fc21092e 100644
--- a/server/src/server.js
+++ b/server/src/server.js
@@ -34,6 +34,7 @@ import { sweepBrandFacts } from './lib/brand-facts-sweep.js';
import { purgeRemovedCatalogProducts } from './lib/catalog/purge.js';
import { sweepCatalogSources } from './lib/catalog/sources.js';
import { sweepShoppingCardMatches } from './lib/catalog/card-match.js';
+import { sweepFramerPublished } from './lib/cms/framer-status.js';
import { sweepWebflowPublished } from './lib/cms/webflow-status.js';
import { sweepWordPressPublished } from './lib/cms/wordpress-status.js';
import { generateBriefForOpportunity } from './routes/content.js';
@@ -353,6 +354,10 @@ async function runDailyTracking() {
sweepWordPressPublished().catch((err) => {
logger.error({ err: { name: err?.name } }, '[wordpress-status] daily sweep failed');
});
+ // And to Framer (00295), once a day too.
+ sweepFramerPublished().catch((err) => {
+ logger.error({ err: { name: err?.name } }, '[framer-status] daily sweep failed');
+ });
// Google Analytics sync (#704) — same contract as the Search Console sync
// above: independent, never blocks or fails the tracking run, no-ops when