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): connect a brand's Framer project from Settings › Integrations (#1331) (#1578)

Cihana717a629e5ac
diff --git a/web/messages/en.json b/web/messages/en.json
index f77f5b035..c37428bb7 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -9443,6 +9443,85 @@
"failed": "Couldn't reach WordPress. Try again later."
}
},
+ "framer": {
+ "title": "Framer",
+ "description": "Send to CMS puts {brand}'s pages in a Framer CMS collection as draft items. You publish them in Framer.",
+ "noBrand": "Pick a brand to connect its Framer project.",
+ "unavailable": "Couldn't read the Framer connection right now.",
+ "notConfigured": "Framer isn't set up on this server yet.",
+ "connected": "Connected",
+ "refused": "Key refused",
+ "project": "Project: {project}",
+ "published": "published at {url}",
+ "account": "key acts as {account}",
+ "notConnectedMember": "Not connected. Admins and managers can connect Framer.",
+ "refusedMember": "Framer refused the API key. Pages can't go there until an admin or manager connects it again.",
+ "pagesGoTo": "Pages go to {collection} as draft items.",
+ "noCollection": "No collection picked yet.",
+ "projectLabel": "Project address",
+ "projectPlaceholder": "https://framer.com/projects/…",
+ "keyLabel": "API key",
+ "keyPlaceholder": "Paste the API key",
+ "keyHint": "Paste the project's address as your browser shows it in Framer, or its id. Make the key in the project's Site Settings › General: it works as the user who makes it, so make it as a user who can edit the CMS. It's kept encrypted by our API, never shown again.",
+ "keyShort": "That's too short for a Framer API key. Paste the whole key Framer made.",
+ "connect": "Connect",
+ "connecting": "Checking the project…",
+ "connectedToast": "Framer connected",
+ "refusedNote": "Framer refused the saved API key. Make a new one in the project and connect again to send pages.",
+ "replace": "Replace key",
+ "cancel": "Cancel",
+ "disconnect": "Disconnect",
+ "disconnectTitle": "Disconnect Framer?",
+ "disconnectDescription": "Pages stop going to Framer. Items already sent stay in Framer. Framer doesn't let us revoke the API key: delete it in the project's Site Settings › General.",
+ "disconnected": "Framer disconnected",
+ "disconnectedNotRevoked": "Framer disconnected. Delete its API key in Framer too, in the project's Site Settings › General.",
+ "collectionLabel": "Collection",
+ "collectionPlaceholder": "Pick a collection",
+ "collectionBlocked": "{name} (needs fields we can't fill)",
+ "collectionIncomplete": "{name} (lacks a field pages need)",
+ "collectionGone": "The saved collection, {collection}, is no longer in the project, or a plugin manages it now. Pick another.",
+ "loadingCollections": "Reading the project's collections…",
+ "noCollections": "This project has no CMS collection pages can go to. Add one in Framer.",
+ "collectionsUnavailable": "Couldn't read the project's collections right now.",
+ "blocked": "{collection} requires {fields}, which Send to CMS can't fill. Make {count, plural, one {it} other {them}} optional in Framer, or pick another collection.",
+ "missing": {
+ "title": "{collection} has no plain text field for the page's title. Add one in Framer, or pick another collection.",
+ "body": "{collection} has no formatted text field for the page's content. Add one in Framer, or pick another collection."
+ },
+ "unmapped": "{collection} requires {fields}. Pick {count, plural, one {it} other {them}} above for the title, page content, meta title or meta description, or make {count, plural, one {it} other {them}} optional in Framer.",
+ "fieldsTitle": "Which field takes what",
+ "fieldsHint": "A page's title and content each need a field; the rest are optional.",
+ "parts": {
+ "title": "Title",
+ "body": "Page content (formatted text)",
+ "metaTitle": "Meta title",
+ "metaDescription": "Meta description",
+ "jsonLd": "JSON-LD (structured data)"
+ },
+ "notSent": "Not sent",
+ "pickField": "Pick a field",
+ "fieldRequired": "{name} (required)",
+ "jsonLdHint": "JSON-LD goes as plain JSON text. On the collection's page in Framer, put this field inside a JSON-LD script tag.",
+ "save": "Save",
+ "saved": "Saved. Pages go to {collection}.",
+ "errors": {
+ "not_configured": "Framer isn't set up on this server yet.",
+ "invalid": "Check what you picked and try again.",
+ "invalidConnect": "Check the project's address (framer.com/projects/…) or its id, and paste the whole API key made in that project.",
+ "forbidden": "Only admins and managers can change the Framer connection.",
+ "not_connected": "Connect Framer first.",
+ "auth_failed": "Framer refused this API key. Make a new one in the project's Site Settings › General and try again.",
+ "no_access": "This key's user can't edit the project's CMS. Make the key as a user who can.",
+ "not_found": "Framer couldn't find that project or collection. Check the project's address, and that the key was made in it.",
+ "invalid_map": "The fields don't fit the collection.",
+ "changed": "The connection changed meanwhile. Reload and try again.",
+ "busy": "Framer is busy, or there are too many requests. Wait a minute and try again.",
+ "unreachable": "Framer didn't answer in time. Try again.",
+ "session": "Your session expired. Sign in again.",
+ "workspace": "This brand isn't in your workspace.",
+ "failed": "Couldn't reach Framer. Try again later."
+ }
+ },
"integrations_connected": "Connected",
"integrations_notConfigured": "Not configured",
"integrations_comingSoon": "Coming soon",
diff --git a/web/src/components/settings/framer-card.test.tsx b/web/src/components/settings/framer-card.test.tsx
new file mode 100644
index 000000000..051f00c47
--- /dev/null
+++ b/web/src/components/settings/framer-card.test.tsx
@@ -0,0 +1,670 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+import type { FramerCollection, FramerConnection, FramerError } from '@/lib/framer-client';
+
+const client = vi.hoisted(() => ({
+ readFramer: vi.fn(),
+ connectFramer: vi.fn(),
+ readFramerCollections: vi.fn(),
+ saveFramerTarget: vi.fn(),
+ disconnectFramer: vi.fn(),
+}));
+vi.mock('@/lib/framer-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/framer-client')>()),
+ ...client,
+}));
+const role = vi.hoisted(() => ({ canManage: true }));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));
+const store = vi.hoisted(() => ({ activeBrandId: 'b1' }));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: () => ({
+ activeBrandId: store.activeBrandId,
+ brands: [
+ { id: 'b1', name: 'Acme' },
+ { id: 'b2', name: 'Beta' },
+ ],
+ }),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn(), warning: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+// The read-only workspace's upgrade dialog.
+const openUpgrade = vi.hoisted(() => vi.fn());
+const gate = vi.hoisted(() => ({ isLocked: false }));
+vi.mock('@/components/providers/upgrade-gate', () => ({
+ useUpgradeGate: () => ({
+ isLocked: gate.isLocked,
+ openUpgrade,
+ guard:
+ <Args extends unknown[]>(fn: (...args: Args) => unknown, options: { action?: string } = {}) =>
+ (...args: Args) =>
+ gate.isLocked ? openUpgrade(options.action) : fn(...args),
+ }),
+}));
+
+const { FramerCard } = await import('./framer-card');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Settings › Integrations › Framer (Send to CMS #1331, phase 2; 00295): a brand's project, collection and fields. */
+
+// Every reason the client names has its words: a missing one fails typecheck. A read-only
+// workspace's refusal opens the upgrade dialog instead.
+const ERROR_TEXTS: Record<Exclude<FramerError, 'subscription'>, string> = messages.settings.framer
+ .errors;
+const TEXT = messages.settings.framer;
+
+let container: HTMLDivElement;
+let root: Root;
+
+const PROJECT_ID = 'abcdefghij0123456789';
+const KEY = 'fr_live_key_0123456789';
+const CONNECTED: FramerConnection = {
+ status: 'connected',
+ projectId: PROJECT_ID,
+ projectName: 'Acme Site',
+ siteUrl: 'https://acme.framer.website',
+ account: 'Jane Doe',
+ collectionId: 'c1',
+ collectionName: 'Blog',
+ fieldMap: { title: 'f-title', body: 'f-content', metaDescription: 'f-summary' },
+ connectedAt: '2026-10-27T10:00:00Z',
+ updatedAt: '2026-10-27T10:00:00Z',
+};
+const BLOG: FramerCollection = {
+ id: 'c1',
+ name: 'Blog',
+ titleField: 'f-title',
+ fields: [
+ { id: 'f-title', name: 'Title', type: 'string', required: true },
+ { id: 'f-content', name: 'Content', type: 'formattedText', required: false },
+ { id: 'f-summary', name: 'Summary', type: 'string', required: false },
+ { id: 'f-cover', name: 'Cover', type: 'image', required: false },
+ { id: 'f-seo', name: 'SEO Title', type: 'string', required: false },
+ ],
+};
+const NEWS: FramerCollection = {
+ id: 'c2',
+ name: 'News',
+ titleField: 'n-headline',
+ fields: [
+ { id: 'n-headline', name: 'Headline', type: 'string', required: true },
+ { id: 'n-body', name: 'Body', type: 'formattedText', required: false },
+ { id: 'n-excerpt', name: 'Excerpt', type: 'string', required: false },
+ ],
+};
+const EVENTS: FramerCollection = {
+ id: 'c3',
+ name: 'Events',
+ titleField: 'e-title',
+ fields: [
+ { id: 'e-title', name: 'Title', type: 'string', required: true },
+ { id: 'e-body', name: 'Details', type: 'formattedText', required: false },
+ { id: 'e-date', name: 'Date', type: 'date', required: true },
+ ],
+};
+
+const NOTES: FramerCollection = {
+ id: 'c4',
+ name: 'Notes',
+ titleField: 'x-title',
+ fields: [
+ { id: 'x-title', name: 'Title', type: 'string', required: false },
+ { id: 'x-text', name: 'Text', type: 'string', required: false },
+ ],
+};
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <FramerCard />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+const button = (label: string, within: ParentNode = container) =>
+ [...within.querySelectorAll('button')].find((b) => b.textContent === label);
+const click = async (el: Element | undefined) => {
+ await act(async () => {
+ el!.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ (el as HTMLElement).click();
+ });
+};
+/** The input or select a label names. */
+const field = (label: string) => {
+ const name = [...container.querySelectorAll('label')].find((l) => l.textContent === label);
+ return container.querySelector<HTMLInputElement>(`[id="${name!.htmlFor}"]`)!;
+};
+async function type(label: string, value: string) {
+ const input = field(label);
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+}
+const submit = async () => {
+ await act(async () => {
+ container
+ .querySelector('form')!
+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ });
+};
+/** Opens the select a label names, and reads its own options (a closed one's stay mounted). */
+async function open(label: string) {
+ const trigger = field(label);
+ await click(trigger);
+ const list = document.getElementById(trigger.getAttribute('aria-controls')!)!;
+ return [...list.querySelectorAll<HTMLElement>('[role="option"]')];
+}
+const texts = (options: HTMLElement[]) => options.map((o) => o.textContent);
+const close = async () => {
+ await act(async () => {
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
+ });
+};
+/** Opens a select and picks one of its options. */
+async function pick(label: string, text: string) {
+ const option = (await open(label)).find((o) => o.textContent === text)!;
+ // Base UI picks the highlighted option: the pointer moves onto it first.
+ await act(async () => {
+ option.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));
+ });
+ await click(option);
+}
+/** The texts an element's aria-describedby names, in order. */
+const described = (el: Element) =>
+ el
+ .getAttribute('aria-describedby')!
+ .split(' ')
+ .map((id) => document.getElementById(id)!.textContent);
+const connectedWith = (connection: FramerConnection | null) =>
+ client.readFramer.mockResolvedValue({ ok: true, configured: true, connection });
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+ role.canManage = true;
+ store.activeBrandId = 'b1';
+ gate.isLocked = false;
+ openUpgrade.mockReset();
+ for (const fn of Object.values(client)) fn.mockReset();
+ for (const fn of Object.values(toast)) fn.mockReset();
+ connectedWith(null);
+ client.readFramerCollections.mockResolvedValue({ ok: true, collections: [BLOG, NEWS, EVENTS] });
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+});
+
+describe('FramerCard', () => {
+ it('connects the project with an API key, never keeping the key, then asks where pages go', async () => {
+ client.connectFramer.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ expect(client.readFramer).toHaveBeenCalledWith('b1');
+ expect(container.textContent).toContain(
+ "Send to CMS puts Acme's pages in a Framer CMS collection as draft items.",
+ );
+ expect(container.textContent).toContain('Site Settings › General');
+ const key = field('API key');
+ expect(key.type).toBe('password');
+ expect(key.autocomplete).toBe('new-password');
+ expect(key.getAttribute('spellcheck')).toBe('false');
+ await type('Project address', ` https://framer.com/projects/Acme--${PROJECT_ID} `);
+ await type('API key', ` ${KEY} `);
+ await submit();
+ expect(client.connectFramer).toHaveBeenCalledWith('b1', {
+ project: `https://framer.com/projects/Acme--${PROJECT_ID}`,
+ apiKey: KEY,
+ });
+ expect(toast.success).toHaveBeenCalledWith('Framer connected');
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ expect(container.textContent).toContain('Connected');
+ expect(container.textContent).toContain(
+ 'Project: Acme Site · published at https://acme.framer.website · key acts as Jane Doe',
+ );
+ expect(client.readFramerCollections).toHaveBeenCalledWith('b1');
+ expect(container.textContent).toContain('Pages go to Blog as draft items.');
+ });
+
+ it('keeps Connect off until both are filled, and stops a key too short to be one', async () => {
+ await render();
+ expect(button('Connect')!.disabled).toBe(true);
+ await type('Project address', PROJECT_ID);
+ expect(button('Connect')!.disabled).toBe(true);
+ await type('API key', 'fr_12');
+ expect(button('Connect')!.disabled).toBe(true);
+ expect(container.textContent).toContain(TEXT.keyShort);
+ // Read out with the field: the hint, and why the key won't do.
+ expect(described(field('API key'))).toEqual([TEXT.keyHint, TEXT.keyShort]);
+ expect(described(field('Project address'))).toEqual([TEXT.keyHint]);
+ expect(TEXT.keyHint).toContain('or its id');
+ await type('API key', KEY);
+ expect(button('Connect')!.disabled).toBe(false);
+ expect(container.textContent).not.toContain(TEXT.keyShort);
+ expect(described(field('API key'))).toEqual([TEXT.keyHint]);
+ await type('Project address', ' ');
+ expect(button('Connect')!.disabled).toBe(true);
+ await submit();
+ expect(client.connectFramer).not.toHaveBeenCalled();
+ });
+
+ it('says why Framer didn’t take it, in our words, and keeps what was typed', async () => {
+ client.connectFramer.mockResolvedValue({ ok: false, code: 'no_access' });
+ await render();
+ await type('Project address', PROJECT_ID);
+ await type('API key', KEY);
+ await submit();
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.no_access);
+ expect(field('Project address').value).toBe(PROJECT_ID);
+ expect(field('API key').value).toBe(KEY);
+
+ client.connectFramer.mockResolvedValue({ ok: false, code: 'invalid' });
+ await submit();
+ expect(toast.error).toHaveBeenLastCalledWith(TEXT.errors.invalidConnect);
+ });
+
+ it('reads the saved collection with its map, offers each part only fields of its type, and saves', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ expect(container.textContent).toContain('Which field takes what');
+ // Strings only, and not one another part takes (Summary is the meta description's).
+ expect(texts(await open('Title'))).toEqual(['Title (required)', 'SEO Title']);
+ await close();
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c1',
+ fieldMap: { title: 'f-title', body: 'f-content', metaDescription: 'f-summary' },
+ });
+ expect(toast.success).toHaveBeenCalledWith('Saved. Pages go to Blog.');
+ });
+
+ it('gives another collection its own suggested map, not the saved one', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ await pick('Collection', 'News');
+ expect(texts(await open('Page content (formatted text)'))).toEqual(['Body']);
+ await close();
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c2',
+ fieldMap: { title: 'n-headline', body: 'n-body', metaDescription: 'n-excerpt' },
+ });
+ });
+
+ it('gives the saved collection its saved map back, not a suggested one', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ await pick('Collection', 'News');
+ await pick('Collection', 'Blog');
+ await click(button('Save'));
+ // Blog's suggestion would add SEO Title as the meta title.
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c1',
+ fieldMap: { title: 'f-title', body: 'f-content', metaDescription: 'f-summary' },
+ });
+ });
+
+ it('marks a collection with no formatted text field, says why, and won’t save it', async () => {
+ connectedWith(CONNECTED);
+ client.readFramerCollections.mockResolvedValue({ ok: true, collections: [BLOG, NOTES] });
+ await render();
+ expect(texts(await open('Collection'))).toEqual(['Blog', 'Notes (lacks a field pages need)']);
+ await close();
+ await pick('Collection', 'Notes (lacks a field pages need)');
+ expect(container.textContent).toContain(
+ "Notes has no formatted text field for the page's content. Add one in Framer, or pick another collection.",
+ );
+ expect(button('Save')!.disabled).toBe(true);
+ });
+
+ it('takes a part out with Not sent', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ await pick('Meta description', 'Not sent');
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c1',
+ fieldMap: { title: 'f-title', body: 'f-content' },
+ });
+ });
+
+ it('says how JSON-LD goes once a field takes it', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ expect(container.textContent).not.toContain(TEXT.jsonLdHint);
+ await pick('JSON-LD (structured data)', 'SEO Title');
+ expect(container.textContent).toContain(TEXT.jsonLdHint);
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c1',
+ fieldMap: {
+ title: 'f-title',
+ body: 'f-content',
+ metaDescription: 'f-summary',
+ jsonLd: 'f-seo',
+ },
+ });
+ });
+
+ it('says the saved collection is gone, or that the project has none', async () => {
+ connectedWith({ ...CONNECTED, collectionId: 'c-gone', collectionName: 'Old posts' });
+ await render();
+ expect(container.textContent).toContain(
+ 'The saved collection, Old posts, is no longer in the project, or a plugin manages it now. Pick another.',
+ );
+ expect(container.textContent).not.toContain('Which field takes what');
+
+ client.readFramerCollections.mockResolvedValue({ ok: true, collections: [] });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain(TEXT.noCollections);
+ });
+
+ it('reads the connection again when a save finds it changed, and another project’s collections with it', async () => {
+ const other = {
+ ...CONNECTED,
+ projectId: 'zyxwvutsrq9876543210',
+ projectName: 'Other Site',
+ collectionId: null,
+ collectionName: null,
+ fieldMap: {},
+ };
+ client.readFramer
+ .mockResolvedValueOnce({ ok: true, configured: true, connection: CONNECTED })
+ .mockResolvedValue({ ok: true, configured: true, connection: other });
+ client.saveFramerTarget.mockResolvedValue({ ok: false, code: 'changed' });
+ await render();
+ expect(client.readFramerCollections).toHaveBeenCalledTimes(1);
+ await click(button('Save'));
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.changed);
+ expect(client.readFramer).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain('Project: Other Site');
+ expect(client.readFramerCollections).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain(TEXT.noCollection);
+ });
+
+ it('asks to connect again when a save finds the connection gone', async () => {
+ client.readFramer
+ .mockResolvedValueOnce({ ok: true, configured: true, connection: CONNECTED })
+ .mockResolvedValue({ ok: true, configured: true, connection: null });
+ client.saveFramerTarget.mockResolvedValue({ ok: false, code: 'not_connected' });
+ await render();
+ await click(button('Save'));
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.not_connected);
+ expect(client.readFramer).toHaveBeenCalledTimes(2);
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('marks a collection whose required fields can’t be filled, and won’t save it', async () => {
+ connectedWith(CONNECTED);
+ await render();
+ expect(texts(await open('Collection'))).toEqual([
+ 'Blog',
+ 'News',
+ "Events (needs fields we can't fill)",
+ ]);
+ await close();
+ await pick('Collection', "Events (needs fields we can't fill)");
+ expect(container.textContent).toContain(
+ "Events requires Date, which Send to CMS can't fill. Make it optional in Framer, or pick another collection.",
+ );
+ expect(button('Save')!.disabled).toBe(true);
+ });
+
+ it('asks for a part for a required field the map leaves out', async () => {
+ connectedWith({ ...CONNECTED, fieldMap: { title: 'f-title', body: 'f-content' } });
+ client.readFramerCollections.mockResolvedValue({
+ ok: true,
+ collections: [
+ {
+ ...BLOG,
+ fields: BLOG.fields.map((f) => (f.id === 'f-summary' ? { ...f, required: true } : f)),
+ },
+ ],
+ });
+ await render();
+ expect(container.textContent).toContain(
+ 'Blog requires Summary. Pick it above for the title, page content, meta title or meta description, or make it optional in Framer.',
+ );
+ expect(button('Save')!.disabled).toBe(true);
+ });
+
+ it('leaves out a saved part whose field was deleted in Framer since', async () => {
+ connectedWith({ ...CONNECTED, fieldMap: { ...CONNECTED.fieldMap, metaTitle: 'f-gone' } });
+ client.saveFramerTarget.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledWith('b1', {
+ collectionId: 'c1',
+ fieldMap: { title: 'f-title', body: 'f-content', metaDescription: 'f-summary' },
+ });
+ });
+
+ it('lists what doesn’t fit when a map is refused, by the parts’ labels', async () => {
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({
+ ok: false,
+ code: 'invalid_map',
+ problems: ['metaTitle: the collection has no field "x"', 'The collection requires Category'],
+ });
+ await render();
+ await click(button('Save'));
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.invalid_map);
+ const list = container.querySelector('ul[role="alert"]')!;
+ expect([...list.querySelectorAll('li')].map((li) => li.textContent)).toEqual([
+ 'Meta title: the collection has no field "x"',
+ 'The collection requires Category',
+ ]);
+ });
+
+ it('says the collections couldn’t be read, not that there are none', async () => {
+ connectedWith(CONNECTED);
+ client.readFramerCollections.mockResolvedValue({ ok: false, code: 'unreachable' });
+ await render();
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.unreachable);
+ expect(container.textContent).toContain(TEXT.collectionsUnavailable);
+ expect(container.textContent).not.toContain(TEXT.noCollections);
+ });
+
+ it('reads the connection again when Framer refuses its key, and asks for a new one', async () => {
+ client.readFramer
+ .mockResolvedValueOnce({ ok: true, configured: true, connection: CONNECTED })
+ .mockResolvedValue({
+ ok: true,
+ configured: true,
+ connection: { ...CONNECTED, status: 'auth_failed' },
+ });
+ client.readFramerCollections.mockResolvedValue({ ok: false, code: 'auth_failed' });
+ await render();
+ await act(async () => {});
+ expect(client.readFramer).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain(TEXT.refusedNote);
+ });
+
+ it('replaces the key for the same project, and goes back on Cancel, not while it’s checked', async () => {
+ connectedWith(CONNECTED);
+ await render();
+ expect(container.querySelector('form')).toBeNull();
+ await click(button('Replace key'));
+ expect(field('Project address').value).toBe(PROJECT_ID);
+ expect(field('API key').value).toBe('');
+ expect(button('Replace key')).toBeUndefined();
+ await click(button('Cancel'));
+ expect(container.querySelector('form')).toBeNull();
+ expect(container.textContent).toContain('Which field takes what');
+
+ await click(button('Replace key'));
+ client.connectFramer.mockReturnValueOnce(new Promise(() => {}));
+ await type('API key', KEY);
+ await submit();
+ expect(container.textContent).toContain('Checking the project…');
+ expect(button('Cancel')!.disabled).toBe(true);
+ });
+
+ it('disconnects after asking, and says to delete the key in Framer', async () => {
+ connectedWith(CONNECTED);
+ client.disconnectFramer.mockResolvedValue({ ok: true, success: true, revoked: false });
+ await render();
+ await click(button('Disconnect'));
+ const dialog = document.querySelector('[role="dialog"]')!;
+ expect(dialog.textContent).toContain(TEXT.disconnectDescription);
+ await click(button('Disconnect', dialog));
+ expect(client.disconnectFramer).toHaveBeenCalledWith('b1');
+ expect(toast.warning).toHaveBeenCalledWith(TEXT.disconnectedNotRevoked);
+ expect(TEXT.disconnectedNotRevoked).toContain('Site Settings › General');
+ expect(container.textContent).not.toContain('Connected');
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('keeps the connection when a disconnect fails', async () => {
+ connectedWith(CONNECTED);
+ client.disconnectFramer.mockResolvedValue({ ok: false, code: 'forbidden' });
+ await render();
+ await click(button('Disconnect'));
+ await click(button('Disconnect', document.querySelector('[role="dialog"]')!));
+ expect(toast.error).toHaveBeenCalledWith(ERROR_TEXTS.forbidden);
+ expect(toast.warning).not.toHaveBeenCalled();
+ expect(container.textContent).toContain('Connected');
+ expect(container.textContent).toContain('Which field takes what');
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ });
+
+ it('goes back to where pages go once a replaced key is taken', async () => {
+ connectedWith(CONNECTED);
+ client.connectFramer.mockResolvedValue({ ok: true, connection: CONNECTED });
+ await render();
+ await click(button('Replace key'));
+ await type('API key', KEY);
+ await submit();
+ expect(client.connectFramer).toHaveBeenCalledWith('b1', { project: PROJECT_ID, apiKey: KEY });
+ expect(toast.success).toHaveBeenCalledWith('Framer connected');
+ expect(container.querySelector('form')).toBeNull();
+ expect(container.textContent).toContain('Which field takes what');
+ expect(button('Replace key')).not.toBeUndefined();
+ });
+
+ it('asks for a new key after Framer refused the saved one, with the project filled in', async () => {
+ connectedWith({ ...CONNECTED, status: 'auth_failed' });
+ await render();
+ expect(container.textContent).toContain('Key refused');
+ expect(container.textContent).toContain(TEXT.refusedNote);
+ expect(field('Project address').value).toBe(PROJECT_ID);
+ expect(field('API key').value).toBe('');
+ expect(button('Replace key')).toBeUndefined();
+ expect(client.readFramerCollections).not.toHaveBeenCalled();
+ });
+
+ it('shows members where pages go, with no form or buttons', async () => {
+ role.canManage = false;
+ connectedWith(CONNECTED);
+ await render();
+ expect(container.textContent).toContain('Pages go to Blog as draft items.');
+ expect(container.querySelector('form')).toBeNull();
+ expect(container.querySelector('button')).toBeNull();
+ expect(client.readFramerCollections).not.toHaveBeenCalled();
+
+ for (const [connection, text] of [
+ [null, 'Not connected. Admins and managers can connect Framer.'],
+ [{ ...CONNECTED, status: 'auth_failed' }, TEXT.refusedMember],
+ [{ ...CONNECTED, collectionId: null, collectionName: null }, TEXT.noCollection],
+ ] as const) {
+ connectedWith(connection);
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain(text);
+ }
+ });
+
+ it('says when the server can’t keep a key, or the connection can’t be read', async () => {
+ client.readFramer.mockResolvedValue({ ok: true, configured: false, connection: null });
+ await render();
+ expect(container.textContent).toContain("Framer isn't set up on this server yet.");
+ expect(container.querySelector('input')).toBeNull();
+ act(() => root.unmount());
+ root = createRoot(container);
+ client.readFramer.mockResolvedValue({ ok: false, code: 'failed' });
+ await render();
+ expect(container.textContent).toContain("Couldn't read the Framer connection right now.");
+ });
+
+ it('shows another brand’s connection never, while its own is read', async () => {
+ connectedWith(CONNECTED);
+ await render();
+ expect(container.textContent).toContain('Acme Site');
+ client.readFramer.mockReturnValueOnce(new Promise(() => {}));
+ store.activeBrandId = 'b2';
+ await render();
+ expect(container.textContent).not.toContain('Acme Site');
+ expect(container.textContent).not.toContain('Pages go to Blog');
+ expect(client.readFramer).toHaveBeenLastCalledWith('b2');
+ });
+
+ it('opens the upgrade dialog, not an error, when a read-only workspace’s connect, save or disconnect is refused', async () => {
+ client.connectFramer.mockResolvedValue({ ok: false, code: 'subscription' });
+ await render();
+ await type('Project address', PROJECT_ID);
+ await type('API key', KEY);
+ await submit();
+ expect(client.connectFramer).toHaveBeenCalledTimes(1);
+ expect(openUpgrade).toHaveBeenCalledTimes(1);
+ expect(toast.error).not.toHaveBeenCalled();
+
+ connectedWith(CONNECTED);
+ client.saveFramerTarget.mockResolvedValue({ ok: false, code: 'subscription' });
+ client.disconnectFramer.mockResolvedValue({ ok: false, code: 'subscription' });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ await click(button('Save'));
+ expect(client.saveFramerTarget).toHaveBeenCalledTimes(1);
+ expect(openUpgrade).toHaveBeenCalledTimes(2);
+ await click(button('Disconnect'));
+ await click(button('Disconnect', document.querySelector('[role="dialog"]')!));
+ expect(client.disconnectFramer).toHaveBeenCalledTimes(1);
+ expect(openUpgrade).toHaveBeenCalledTimes(3);
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('on a read-only workspace, connects, replaces and saves nothing, and still disconnects', async () => {
+ gate.isLocked = true;
+ await render();
+ await type('Project address', PROJECT_ID);
+ await type('API key', KEY);
+ await submit();
+ expect(openUpgrade).toHaveBeenLastCalledWith('Connecting your CMS needs a plan');
+ expect(client.connectFramer).not.toHaveBeenCalled();
+
+ connectedWith(CONNECTED);
+ client.disconnectFramer.mockResolvedValue({ ok: true, success: true, revoked: false });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ await click(button('Replace key'));
+ expect(openUpgrade).toHaveBeenLastCalledWith('Connecting your CMS needs a plan');
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ await click(button('Save'));
+ expect(openUpgrade).toHaveBeenLastCalledWith('Saving the CMS settings needs a plan');
+ expect(client.saveFramerTarget).not.toHaveBeenCalled();
+ // Disconnect ends an access: it stays open.
+ await click(button('Disconnect'));
+ await click(button('Disconnect', document.querySelector('[role="dialog"]')!));
+ expect(client.disconnectFramer).toHaveBeenCalledWith('b1');
+ expect(toast.warning).toHaveBeenCalledWith(TEXT.disconnectedNotRevoked);
+ });
+});
diff --git a/web/src/components/settings/framer-card.tsx b/web/src/components/settings/framer-card.tsx
new file mode 100644
index 000000000..8823b0e69
--- /dev/null
+++ b/web/src/components/settings/framer-card.tsx
@@ -0,0 +1,639 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { useFormatter, useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { AlertTriangle, LayoutTemplate, Loader2, Unplug } from 'lucide-react';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Input } from '@/components/ui/input';
+import { Label } from '@/components/ui/label';
+import { Skeleton } from '@/components/ui/skeleton';
+import { useUpgradeGate } from '@/components/providers/upgrade-gate';
+import {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import { useUserRole } from '@/hooks/use-user-role';
+import {
+ FRAMER_NEEDED,
+ FRAMER_PARTS,
+ FRAMER_PART_TYPES,
+ connectFramer,
+ disconnectFramer,
+ fittingFramerMap,
+ missingFramerParts,
+ readFramer,
+ readFramerCollections,
+ saveFramerTarget,
+ suggestFramerMap,
+ unfillableFramerFields,
+ unmappedFramerFields,
+ type FramerCollection,
+ type FramerConnection,
+ type FramerError,
+ type FramerFieldMap,
+} from '@/lib/framer-client';
+import { useBrandStore } from '@/stores/use-brand-store';
+import { Picker } from './webflow-card';
+
+/** A part the map leaves out. */
+const NOT_SENT = '__none__';
+/** Answers that mean the connection changed: it's read again. */
+const STALE: readonly FramerError[] = ['auth_failed', 'changed', 'not_connected'];
+
+/**
+ * Send to CMS → Framer (#1331, phase 2; 00295): the active brand's Framer
+ * project. Admins and managers connect it with an API key made in the
+ * project, pick the collection pages go to and which of its fields takes
+ * each part of a page, replace the key and disconnect; members see where
+ * pages go. Framer can't revoke a key through its API: the person deletes
+ * it in the project.
+ */
+export function FramerCard() {
+ const t = useTranslations('settings.framer');
+ const { activeBrandId, brands } = useBrandStore();
+ const { canManage } = useUserRole();
+ // A read-only workspace's refusal opens the upgrade dialog, not a toast;
+ // while it is read-only, Replace key opens it at once. Disconnect stays
+ // open: it ends an access, it starts nothing.
+ const { guard, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ const brand = brands.find((b) => b.id === activeBrandId) ?? null;
+
+ // The connection as read for a brand: another brand's never shows.
+ const [read, setRead] = useState<{
+ brandId: string;
+ configured: boolean;
+ connection: FramerConnection | null;
+ failed: boolean;
+ } | null>(null);
+ // Replacing the key, for the brand it was asked for.
+ const [replacingFor, setReplacingFor] = useState<string | null>(null);
+ const replacing = replacingFor !== null && replacingFor === activeBrandId;
+ const [disconnecting, setDisconnecting] = useState(false);
+ // Bumped to read the connection again: a key refused or replaced meanwhile.
+ const [reads, setReads] = useState(0);
+
+ useEffect(() => {
+ if (!activeBrandId) return;
+ let cancelled = false;
+ readFramer(activeBrandId).then((result) => {
+ if (cancelled) return;
+ setRead(
+ result.ok
+ ? {
+ brandId: activeBrandId,
+ configured: result.configured,
+ connection: result.connection,
+ failed: false,
+ }
+ : { brandId: activeBrandId, configured: true, connection: null, failed: true },
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [activeBrandId, reads]);
+
+ const current = read?.brandId === activeBrandId ? read : null;
+ const connection = current?.connection ?? null;
+ const setConnection = (next: FramerConnection | null) =>
+ setRead((r) => (r && r.brandId === activeBrandId ? { ...r, connection: next } : r));
+ // The project, the published site and the user the key acts as, as far as Framer told them.
+ const details = connection
+ ? [
+ t('project', { project: connection.projectName ?? connection.projectId }),
+ connection.siteUrl ? t('published', { url: connection.siteUrl }) : null,
+ connection.account ? t('account', { account: connection.account }) : null,
+ ].filter(Boolean)
+ : [];
+
+ const disconnect = async () => {
+ if (!activeBrandId) return;
+ setDisconnecting(true);
+ const result = await disconnectFramer(activeBrandId);
+ setDisconnecting(false);
+ if (!result.ok) {
+ if (result.code === 'subscription') openUpgrade();
+ else toast.error(t(`errors.${result.code}`));
+ return;
+ }
+ setConnection(null);
+ setReplacingFor(null);
+ // Not revoked: the key still works until it's deleted in Framer.
+ if (result.revoked) toast.success(t('disconnected'));
+ else toast.warning(t('disconnectedNotRevoked'));
+ };
+
+ return (
+ <div className="space-y-4 rounded-lg border p-4">
+ <div className="flex items-start gap-3">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted/50">
+ <LayoutTemplate className="h-5 w-5 text-muted-foreground" />
+ </div>
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <p className="text-sm font-medium">{t('title')}</p>
+ {connection?.status === 'connected' && (
+ <Badge
+ variant="outline"
+ className="border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
+ >
+ {t('connected')}
+ </Badge>
+ )}
+ {connection?.status === 'auth_failed' && (
+ <Badge
+ variant="outline"
+ className="border-amber-500/30 bg-amber-500/10 text-amber-700 dark:text-amber-400"
+ >
+ {t('refused')}
+ </Badge>
+ )}
+ </div>
+ <p className="text-sm text-muted-foreground">
+ {brand ? t('description', { brand: brand.name }) : t('noBrand')}
+ </p>
+ {details.length > 0 && (
+ <p className="mt-1 text-xs text-muted-foreground [overflow-wrap:anywhere]">
+ {details.join(' · ')}
+ </p>
+ )}
+ {canManage && connection && (
+ <div className="mt-3 flex flex-wrap items-center gap-2">
+ {!replacing && current?.configured && connection.status === 'connected' && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={guard(() => setReplacingFor(activeBrandId), {
+ action: tActions('connectCms'),
+ })}
+ >
+ {t('replace')}
+ </Button>
+ )}
+ <Dialog>
+ <DialogTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ className="gap-2"
+ disabled={disconnecting}
+ />
+ }
+ >
+ {disconnecting ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Unplug className="h-3.5 w-3.5" />
+ )}
+ {t('disconnect')}
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>{t('disconnectTitle')}</DialogTitle>
+ <DialogDescription>{t('disconnectDescription')}</DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>{t('cancel')}</DialogClose>
+ <DialogClose render={<Button variant="destructive" onClick={disconnect} />}>
+ {t('disconnect')}
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ </div>
+ )}
+ </div>
+ </div>
+
+ {!activeBrandId ? null : !current ? (
+ <Skeleton className="h-16 w-full" />
+ ) : current.failed ? (
+ <p className="text-sm text-muted-foreground">{t('unavailable')}</p>
+ ) : !current.configured ? (
+ <p className="text-sm text-muted-foreground">{t('notConfigured')}</p>
+ ) : !canManage ? (
+ <p className="text-sm text-muted-foreground">
+ {!connection
+ ? t('notConnectedMember')
+ : connection.status === 'auth_failed'
+ ? t('refusedMember')
+ : connection.collectionName
+ ? t('pagesGoTo', { collection: connection.collectionName })
+ : t('noCollection')}
+ </p>
+ ) : !connection || connection.status === 'auth_failed' || replacing ? (
+ <div className="space-y-3">
+ {connection?.status === 'auth_failed' && (
+ <div className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300">
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>{t('refusedNote')}</span>
+ </div>
+ )}
+ <KeyForm
+ brandId={activeBrandId}
+ // Connecting again, to the project as it was: a new key for it keeps where pages go.
+ initial={connection}
+ onCancel={replacing ? () => setReplacingFor(null) : undefined}
+ onConnected={(next) => {
+ setReplacingFor(null);
+ setConnection(next);
+ }}
+ />
+ </div>
+ ) : (
+ <FramerMapping
+ // Another project's collections are read again, never kept from the last one.
+ key={`${activeBrandId}:${connection.projectId}`}
+ brandId={activeBrandId}
+ connection={connection}
+ onSaved={setConnection}
+ onStale={() => setReads((n) => n + 1)}
+ />
+ )}
+ </div>
+ );
+}
+
+/** The project and an API key made in it: the key goes to the API once, never shown again. */
+function KeyForm({
+ brandId,
+ initial,
+ onConnected,
+ onCancel,
+}: {
+ brandId: string;
+ initial: FramerConnection | null;
+ onConnected: (connection: FramerConnection) => void;
+ onCancel?: () => void;
+}) {
+ const t = useTranslations('settings.framer');
+ // Read-only (plan not active): Connect opens the upgrade dialog before anything is sent.
+ const { guard, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ // The API takes the project's id as well as its address.
+ const [project, setProject] = useState(initial?.projectId ?? '');
+ const [apiKey, setApiKey] = useState('');
+ const [connecting, setConnecting] = useState(false);
+ const id = (field: string) => `framer-${field}-${brandId}`;
+ const key = apiKey.trim();
+ // The API takes a key of 8 characters or more: a shorter one is a paste cut short.
+ const short = key !== '' && key.length < 8;
+ const ready = project.trim() !== '' && key !== '' && !short;
+
+ const connect = async () => {
+ setConnecting(true);
+ const result = await connectFramer(brandId, { project: project.trim(), apiKey: key });
+ setConnecting(false);
+ if (!result.ok) {
+ if (result.code === 'subscription') openUpgrade();
+ else
+ toast.error(
+ t(result.code === 'invalid' ? 'errors.invalidConnect' : `errors.${result.code}`),
+ );
+ return;
+ }
+ setApiKey('');
+ toast.success(t('connectedToast'));
+ onConnected(result.connection);
+ };
+ const connectProject = guard(() => void connect(), { action: tActions('connectCms') });
+
+ return (
+ <form
+ className="space-y-3"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (ready && !connecting) connectProject();
+ }}
+ >
+ <div className="space-y-1.5">
+ <Label htmlFor={id('project')}>{t('projectLabel')}</Label>
+ <Input
+ id={id('project')}
+ aria-describedby={id('hint')}
+ inputMode="url"
+ autoComplete="off"
+ spellCheck={false}
+ value={project}
+ onChange={(e) => setProject(e.target.value)}
+ placeholder={t('projectPlaceholder')}
+ />
+ </div>
+ <div className="space-y-1.5">
+ <Label htmlFor={id('key')}>{t('keyLabel')}</Label>
+ <Input
+ id={id('key')}
+ // The hint, and why Connect is off while the key is too short.
+ aria-describedby={short ? `${id('hint')} ${id('short')}` : id('hint')}
+ aria-invalid={short || undefined}
+ type="password"
+ // Not a sign-in to Ansvisor: no saved password is offered here.
+ autoComplete="new-password"
+ spellCheck={false}
+ value={apiKey}
+ onChange={(e) => setApiKey(e.target.value)}
+ placeholder={t('keyPlaceholder')}
+ />
+ </div>
+ <p id={id('hint')} className="text-xs text-muted-foreground">
+ {t('keyHint')}
+ </p>
+ {short && (
+ <p id={id('short')} className="text-xs text-amber-700 dark:text-amber-400">
+ {t('keyShort')}
+ </p>
+ )}
+ <div className="flex flex-wrap gap-2">
+ <Button type="submit" size="sm" className="h-9 gap-2" disabled={!ready || connecting}>
+ {connecting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {connecting ? t('connecting') : t('connect')}
+ </Button>
+ {onCancel && (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="h-9"
+ disabled={connecting}
+ onClick={onCancel}
+ >
+ {t('cancel')}
+ </Button>
+ )}
+ </div>
+ </form>
+ );
+}
+
+/** The collection pages go to, and which of its fields takes each part of a page. */
+function FramerMapping({
+ brandId,
+ connection,
+ onSaved,
+ onStale,
+}: {
+ brandId: string;
+ connection: FramerConnection;
+ onSaved: (connection: FramerConnection) => void;
+ /** The connection changed (a key refused, replaced or removed): read it again. */
+ onStale: () => void;
+}) {
+ const t = useTranslations('settings.framer');
+ const format = useFormatter();
+ // Read-only (plan not active): Save opens the upgrade dialog before anything is sent.
+ const { guard, openUpgrade } = useUpgradeGate();
+ const tActions = useTranslations('readOnly.actions');
+ // The saved settings, for the collections read: a save doesn't read them again.
+ const saved = useRef(connection);
+ useEffect(() => {
+ saved.current = connection;
+ }, [connection]);
+ const stale = useRef(onStale);
+ useEffect(() => {
+ stale.current = onStale;
+ }, [onStale]);
+ /** Says what went wrong, and reads the connection again when it changed. */
+ const report = (code: FramerError) => {
+ if (code === 'subscription') {
+ openUpgrade();
+ return;
+ }
+ toast.error(t(`errors.${code}`));
+ if (STALE.includes(code)) stale.current();
+ };
+ const [listed, setListed] = useState<{
+ collections: FramerCollection[];
+ failed: boolean;
+ } | null>(null);
+ const [collectionId, setCollectionId] = useState<string | null>(connection.collectionId);
+ const [map, setMap] = useState<FramerFieldMap>(connection.fieldMap);
+ const [problems, setProblems] = useState<string[]>([]);
+ const [saving, setSaving] = useState(false);
+
+ // The project's collections, each with its fields.
+ useEffect(() => {
+ let cancelled = false;
+ readFramerCollections(brandId).then((result) => {
+ if (cancelled) return;
+ if (!result.ok) {
+ report(result.code);
+ setListed({ collections: [], failed: true });
+ return;
+ }
+ setListed({ collections: result.collections, failed: false });
+ // Only what the pickers can show: a saved part whose field was deleted
+ // or changed type in Framer since is left out, so what's saved is what's shown.
+ const savedOne = result.collections.find((c) => c.id === saved.current.collectionId);
+ if (savedOne) setMap(fittingFramerMap(saved.current.fieldMap, savedOne.fields));
+ });
+ return () => {
+ cancelled = true;
+ };
+ // report reads the latest onStale through a ref.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [brandId, t]);
+
+ const collections = listed?.collections ?? [];
+ const collection = collections.find((c) => c.id === collectionId) ?? null;
+ const fields = collection?.fields ?? [];
+ const required = new Set(fields.filter((f) => f.required).map((f) => f.id));
+ // Required fields no map fills (an image, a date…), and ones this map leaves to no part.
+ const unfillable = collection ? unfillableFramerFields(collection) : [];
+ const unmapped = unmappedFramerFields(map, fields);
+ // A part every page has that the collection has no field for (no formatted text, say).
+ const missing = collection ? missingFramerParts(collection) : [];
+ const names = (list: { name: string }[]) => format.list(list.map((f) => f.name));
+ const fits =
+ !!collection &&
+ FRAMER_NEEDED.every((part) => map[part]) &&
+ !unfillable.length &&
+ !missing.length;
+
+ const save = async () => {
+ if (!collection) return;
+ setSaving(true);
+ setProblems([]);
+ const result = await saveFramerTarget(brandId, { collectionId: collection.id, fieldMap: map });
+ setSaving(false);
+ if (!result.ok) {
+ setProblems(result.problems ?? []);
+ report(result.code);
+ return;
+ }
+ toast.success(t('saved', { collection: result.connection.collectionName ?? collection.name }));
+ onSaved(result.connection);
+ };
+
+ /** The API names a part by its key ("metaTitle: …"): the person reads its label. */
+ const problemText = (problem: string) => {
+ const part = FRAMER_PARTS.find((p) => problem.startsWith(`${p}: `));
+ return part ? `${t(`parts.${part}`)}: ${problem.slice(part.length + 2)}` : problem;
+ };
+ // A collection pages can't go to is marked before it's picked.
+ const collectionItems = collections.map((c) => ({
+ value: c.id,
+ label: unfillableFramerFields(c).length
+ ? t('collectionBlocked', { name: c.name })
+ : missingFramerParts(c).length
+ ? t('collectionIncomplete', { name: c.name })
+ : c.name,
+ }));
+
+ return (
+ <div className="space-y-4">
+ <p className="text-sm text-muted-foreground">
+ {connection.collectionName
+ ? t('pagesGoTo', { collection: connection.collectionName })
+ : t('noCollection')}
+ </p>
+ {listed === null ? (
+ <p className="flex items-center gap-2 text-xs text-muted-foreground">
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ {t('loadingCollections')}
+ </p>
+ ) : listed.failed ? (
+ <p className="text-sm text-muted-foreground">{t('collectionsUnavailable')}</p>
+ ) : collections.length === 0 ? (
+ <p className="text-sm text-muted-foreground">{t('noCollections')}</p>
+ ) : (
+ <Picker
+ label={t('collectionLabel')}
+ items={collectionItems}
+ value={collection ? collection.id : null}
+ placeholder={t('collectionPlaceholder')}
+ onChange={(value) => {
+ const next = collections.find((c) => c.id === value);
+ if (!next || next.id === collectionId) return;
+ setCollectionId(next.id);
+ // The saved collection gets its saved map back; another, its own suggested one.
+ setMap(
+ next.id === saved.current.collectionId
+ ? fittingFramerMap(saved.current.fieldMap, next.fields)
+ : suggestFramerMap(next),
+ );
+ setProblems([]);
+ }}
+ />
+ )}
+ {listed && !listed.failed && collectionId && !collection && (
+ <p className="text-sm text-muted-foreground">
+ {t('collectionGone', { collection: connection.collectionName ?? collectionId })}
+ </p>
+ )}
+
+ {collection && (
+ <div className="space-y-3 rounded-md border p-3">
+ <div>
+ <p className="text-sm font-medium">{t('fieldsTitle')}</p>
+ <p className="text-xs text-muted-foreground">{t('fieldsHint')}</p>
+ </div>
+ {unfillable.length > 0 && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300"
+ >
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>
+ {t('blocked', {
+ collection: collection.name,
+ fields: names(unfillable),
+ count: unfillable.length,
+ })}
+ </span>
+ </div>
+ )}
+ {missing.length > 0 && (
+ <div
+ role="alert"
+ className="flex items-start gap-2 rounded-md border border-amber-200 bg-amber-50 p-3 text-sm text-amber-800 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300"
+ >
+ <AlertTriangle className="mt-0.5 h-4 w-4 shrink-0" />
+ <span>
+ {missing
+ .map((part) => t(`missing.${part}`, { collection: collection.name }))
+ .join(' ')}
+ </span>
+ </div>
+ )}
+ {FRAMER_PARTS.map((part) => {
+ const needed = FRAMER_NEEDED.includes(part);
+ // A field of the part's type that no other part takes.
+ const taken = new Set(
+ FRAMER_PARTS.filter((other) => other !== part).map((other) => map[other]),
+ );
+ const choices = fields.filter(
+ (f) => f.type === FRAMER_PART_TYPES[part] && !taken.has(f.id),
+ );
+ const items = [
+ ...(needed ? [] : [{ value: NOT_SENT, label: t('notSent') }]),
+ ...choices.map((f) => ({
+ value: f.id,
+ label: required.has(f.id) ? t('fieldRequired', { name: f.name }) : f.name,
+ })),
+ ];
+ const picked = map[part];
+ return (
+ <Picker
+ key={part}
+ label={t(`parts.${part}`)}
+ items={items}
+ value={
+ picked && items.some((item) => item.value === picked)
+ ? picked
+ : needed
+ ? null
+ : NOT_SENT
+ }
+ placeholder={t('pickField')}
+ onChange={(value) =>
+ setMap((m) => {
+ const next = { ...m };
+ if (!value || value === NOT_SENT) delete next[part];
+ else next[part] = value;
+ return next;
+ })
+ }
+ />
+ );
+ })}
+ {unmapped.length > 0 && (
+ <p className="text-xs text-amber-700 dark:text-amber-400">
+ {t('unmapped', {
+ collection: collection.name,
+ fields: names(unmapped),
+ count: unmapped.length,
+ })}
+ </p>
+ )}
+ {map.jsonLd && <p className="text-xs text-muted-foreground">{t('jsonLdHint')}</p>}
+ {problems.length > 0 && (
+ <ul role="alert" className="list-disc space-y-1 pl-5 text-xs text-destructive">
+ {problems.map((p) => (
+ <li key={p}>{problemText(p)}</li>
+ ))}
+ </ul>
+ )}
+ <Button
+ size="sm"
+ className="gap-2"
+ onClick={guard(save, { action: tActions('saveCmsSettings') })}
+ disabled={saving || !fits || unmapped.length > 0}
+ >
+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {t('save')}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index c971e154b..1820f11f9 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -42,6 +42,7 @@ import { MERCHANT_CENTER_LABEL } from '@/lib/catalog';
import { isCloud } from '@/config/plans';
import { CatalogSourcesCard, type CatalogSourcesRead } from './catalog-sources-card';
import { CatalogCategoryPages } from './catalog-category-pages';
+import { FramerCard } from './framer-card';
import { MerchantCenterAccounts } from './merchant-center-accounts';
import { WebflowCard } from './webflow-card';
import { WordPressCard } from './wordpress-card';
@@ -132,6 +133,8 @@ export function IntegrationsSection() {
<WebflowCard />
<WordPressCard />
+
+ <FramerCard />
</IntegrationGroup>
</CardContent>
</Card>
diff --git a/web/src/components/settings/webflow-card.tsx b/web/src/components/settings/webflow-card.tsx
index 0a9e18e84..34c1a4cc8 100644
--- a/web/src/components/settings/webflow-card.tsx
+++ b/web/src/components/settings/webflow-card.tsx
@@ -664,8 +664,8 @@ function WebflowMapping({
);
}
-/** A labelled select, one row. */
-function Picker({
+/** A labelled select, one row: the Framer card's too. */
+export function Picker({
label,
items,
value,
diff --git a/web/src/lib/framer-client.test.ts b/web/src/lib/framer-client.test.ts
new file mode 100644
index 000000000..c5b2c8341
--- /dev/null
+++ b/web/src/lib/framer-client.test.ts
@@ -0,0 +1,225 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { FramerCollection } from './framer-client';
+
+/** Send to CMS › Framer (#1331, phase 2): a brand's connection from the browser, through the API's proxy. */
+
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({
+ auth: { getSession: async () => ({ data: { session: { access_token: 'tok' } } }) },
+ }),
+}));
+
+const {
+ connectFramer,
+ disconnectFramer,
+ fittingFramerMap,
+ missingFramerParts,
+ readFramer,
+ readFramerCollections,
+ saveFramerTarget,
+ suggestFramerMap,
+ unfillableFramerFields,
+ unmappedFramerFields,
+} = await import('./framer-client');
+
+const fetchMock = vi.fn();
+beforeEach(() => {
+ fetchMock.mockReset();
+ vi.stubGlobal('fetch', fetchMock);
+});
+
+const answer = (status: number, body: unknown) =>
+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));
+const BASE = '/api/aeo/api/cms/brands/b1/framer';
+const input = {
+ project: 'https://framer.com/projects/Acme--abcdefghij0123456789',
+ apiKey: 'fr_key',
+};
+
+const BLOG: FramerCollection = {
+ id: 'c1',
+ name: 'Blog',
+ titleField: 'f-title',
+ fields: [
+ { id: 'f-seo', name: 'SEO Title', type: 'string', required: false },
+ { id: 'f-title', name: 'Title', type: 'string', required: true },
+ { id: 'f-cover', name: 'Cover', type: 'image', required: false },
+ { id: 'f-intro', name: 'Intro', type: 'formattedText', required: false },
+ { id: 'f-content', name: 'Content', type: 'formattedText', required: false },
+ { id: 'f-summary', name: 'Summary', type: 'string', required: false },
+ { id: 'f-schema', name: 'Schema markup', type: 'string', required: false },
+ ],
+};
+
+describe('framer-client', () => {
+ it('reads the connection, and whether the server can keep a key', async () => {
+ answer(200, { configured: true, connection: null });
+ expect(await readFramer('b1')).toEqual({ ok: true, configured: true, connection: null });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe(BASE);
+ expect(init.headers).toEqual({ Authorization: 'Bearer tok' });
+ });
+
+ it('sends the project and the key once, in the body, with the session', async () => {
+ answer(200, { connection: { status: 'connected' } });
+ expect(await connectFramer('b1', input)).toEqual({
+ ok: true,
+ connection: { status: 'connected' },
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe(BASE);
+ expect(init).toMatchObject({
+ method: 'POST',
+ body: JSON.stringify(input),
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer tok' },
+ });
+ });
+
+ it('reads the collections, saves where pages go, and disconnects', async () => {
+ answer(200, { collections: [BLOG] });
+ expect(await readFramerCollections('b1')).toEqual({ ok: true, collections: [BLOG] });
+ expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}/collections`);
+
+ answer(200, { connection: { collectionId: 'c1' } });
+ const target = { collectionId: 'c1', fieldMap: { title: 'f-title', body: 'f-content' } };
+ await saveFramerTarget('b1', target);
+ expect(fetchMock.mock.calls[1][0]).toBe(BASE);
+ expect(fetchMock.mock.calls[1][1]).toMatchObject({
+ method: 'PUT',
+ body: JSON.stringify(target),
+ });
+
+ answer(200, { success: true, revoked: false });
+ expect(await disconnectFramer('b1')).toEqual({ ok: true, success: true, revoked: false });
+ expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'DELETE' });
+ });
+
+ it("names the API's reasons with the problems, and the general ones", async () => {
+ answer(400, { code: 'invalid_map', problems: ['title: pick the text field', 3] });
+ expect(await saveFramerTarget('b1', { collectionId: 'c1', fieldMap: {} })).toEqual({
+ ok: false,
+ code: 'invalid_map',
+ problems: ['title: pick the text field'],
+ });
+ for (const [status, code] of [
+ [400, 'invalid'],
+ [409, 'auth_failed'],
+ [403, 'no_access'],
+ [404, 'not_found'],
+ [429, 'busy'],
+ [502, 'unreachable'],
+ [503, 'not_configured'],
+ [409, 'not_connected'],
+ [409, 'changed'],
+ [403, 'forbidden'],
+ ] as const) {
+ answer(status, { code, error: 'x' });
+ expect(await connectFramer('b1', input)).toEqual({ ok: false, code });
+ }
+ answer(401, { error: 'Unauthorized' });
+ expect(await readFramer('b1')).toEqual({ ok: false, code: 'session' });
+ answer(403, { code: 'not_in_workspace' });
+ expect(await readFramer('b1')).toEqual({ ok: false, code: 'workspace' });
+ answer(429, { message: 'Too many requests' });
+ expect(await readFramer('b1')).toEqual({ ok: false, code: 'busy' });
+ // A read-only workspace: the upgrade dialog's, not a message.
+ answer(402, { code: 'subscription_inactive', error: 'x' });
+ expect(await connectFramer('b1', input)).toEqual({ ok: false, code: 'subscription' });
+ answer(502, { code: 'failed', error: 'Something went wrong with Framer' });
+ expect(await readFramer('b1')).toEqual({ ok: false, code: 'failed' });
+ fetchMock.mockRejectedValue(new TypeError('offline'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(await readFramer('b1')).toEqual({ ok: false, code: 'failed' });
+ });
+});
+
+describe('suggestFramerMap', () => {
+ it('suggests the slug’s field for the title, and the rest by their names, one field a part', () => {
+ expect(suggestFramerMap(BLOG)).toEqual({
+ title: 'f-title',
+ body: 'f-content',
+ metaTitle: 'f-seo',
+ metaDescription: 'f-summary',
+ jsonLd: 'f-schema',
+ });
+ });
+
+ it('falls back to a field named as a title, and to the first formatted text for the body', () => {
+ expect(
+ suggestFramerMap({
+ id: 'c2',
+ name: 'Guides',
+ titleField: 'f-date',
+ fields: [
+ { id: 'f-date', name: 'Date', type: 'date', required: false },
+ { id: 'f-seo', name: 'SEO Title', type: 'string', required: false },
+ { id: 'f-name', name: 'Name', type: 'string', required: false },
+ { id: 'f-intro', name: 'Intro', type: 'formattedText', required: false },
+ ],
+ }),
+ ).toEqual({ title: 'f-name', body: 'f-intro', metaTitle: 'f-seo' });
+ expect(suggestFramerMap({ id: 'c3', name: 'Empty', titleField: null, fields: [] })).toEqual({});
+ });
+});
+
+describe('fittingFramerMap', () => {
+ it('keeps only fields that are still there, of the part’s type, each once', () => {
+ expect(
+ fittingFramerMap(
+ {
+ title: 'f-title',
+ body: 'f-cover',
+ metaTitle: 'f-gone',
+ metaDescription: 'f-title',
+ jsonLd: 'f-schema',
+ },
+ BLOG.fields,
+ ),
+ ).toEqual({ title: 'f-title', jsonLd: 'f-schema' });
+ });
+});
+
+describe('missingFramerParts', () => {
+ it('names the parts every page has that the collection has no field for', () => {
+ expect(missingFramerParts(BLOG)).toEqual([]);
+ expect(
+ missingFramerParts({
+ ...BLOG,
+ fields: BLOG.fields.filter((f) => f.type !== 'formattedText'),
+ }),
+ ).toEqual(['body']);
+ expect(missingFramerParts({ ...BLOG, fields: [] })).toEqual(['title', 'body']);
+ });
+});
+
+describe('required fields', () => {
+ const strict: FramerCollection = {
+ ...BLOG,
+ fields: BLOG.fields.map((f) =>
+ f.id === 'f-cover' || f.id === 'f-schema' ? { ...f, required: true } : f,
+ ),
+ };
+
+ it('names the ones no map fills', () => {
+ expect(unfillableFramerFields(strict).map((f) => f.name)).toEqual(['Cover']);
+ expect(unfillableFramerFields(BLOG)).toEqual([]);
+ });
+
+ it('names the ones the map leaves to no part a page always has, JSON-LD aside', () => {
+ expect(
+ unmappedFramerFields(
+ { title: 'f-title', body: 'f-content', jsonLd: 'f-schema' },
+ strict.fields,
+ ).map((f) => f.name),
+ ).toEqual(['Schema markup']);
+ expect(
+ unmappedFramerFields(
+ { title: 'f-title', body: 'f-content', metaDescription: 'f-schema' },
+ strict.fields,
+ ),
+ ).toEqual([]);
+ expect(unmappedFramerFields({ body: 'f-content' }, BLOG.fields).map((f) => f.name)).toEqual([
+ 'Title',
+ ]);
+ });
+});
diff --git a/web/src/lib/framer-client.ts b/web/src/lib/framer-client.ts
new file mode 100644
index 000000000..15569437d
--- /dev/null
+++ b/web/src/lib/framer-client.ts
@@ -0,0 +1,264 @@
+import { BROWSER_API_BASE_URL } from '@/config/api';
+import { apiFailure } from '@/lib/api-failure';
+import { createClient } from '@/lib/supabase/client';
+
+/**
+ * A brand's Framer connection for Send to CMS (#1331, phase 2; 00295), from
+ * the browser through the API's same-origin proxy. The API key goes from
+ * here to the API once, which checks it with Framer and keeps it encrypted:
+ * never through a server action, a log or a response.
+ */
+
+/** The parts of a page a field map places: a page's title and body always. */
+export const FRAMER_PARTS = ['title', 'body', 'metaTitle', 'metaDescription', 'jsonLd'] as const;
+export type FramerPart = (typeof FRAMER_PARTS)[number];
+export type FramerFieldMap = Partial<Record<FramerPart, string>>;
+/** The Framer field type each part may go to (server/src/lib/cms/framer.js). */
+export const FRAMER_PART_TYPES: Record<FramerPart, string> = {
+ title: 'string',
+ body: 'formattedText',
+ metaTitle: 'string',
+ metaDescription: 'string',
+ jsonLd: 'string',
+};
+/** The parts every map places. */
+export const FRAMER_NEEDED: readonly FramerPart[] = ['title', 'body'];
+/**
+ * The parts every page has, so a field the collection requires may take
+ * one: a page's meta title falls back to its title, its meta description to
+ * its opening words. A page may have no JSON-LD.
+ */
+const ALWAYS_FILLED: readonly FramerPart[] = ['title', 'body', 'metaTitle', 'metaDescription'];
+const FILLABLE_TYPES = new Set(ALWAYS_FILLED.map((part) => FRAMER_PART_TYPES[part]));
+
+export interface FramerConnection {
+ status: 'connected' | 'auth_failed';
+ projectId: string;
+ projectName: string | null;
+ /** The project's published address, when it has one. */
+ siteUrl: string | null;
+ /** The Framer user the key acts as. */
+ account: string | null;
+ collectionId: string | null;
+ collectionName: string | null;
+ fieldMap: FramerFieldMap;
+ connectedAt: string;
+ updatedAt: string;
+}
+export interface FramerField {
+ id: string;
+ name: string;
+ /** Framer's own type: 'string', 'formattedText', 'image', 'date'… */
+ type: string;
+ required: boolean;
+}
+export interface FramerCollection {
+ id: string;
+ name: string;
+ /** The field its items' slugs are made from: the one a page's title suits. */
+ titleField: string | null;
+ fields: FramerField[];
+}
+
+export type FramerError =
+ | 'not_configured'
+ | 'invalid'
+ | 'forbidden'
+ | 'not_connected'
+ | 'auth_failed'
+ | 'no_access'
+ | 'not_found'
+ | 'invalid_map'
+ | 'changed'
+ | 'busy'
+ | 'unreachable'
+ | 'session'
+ | 'workspace'
+ /** A read-only workspace (plan not active): the upgrade dialog, not a message. */
+ | 'subscription'
+ | 'failed';
+
+const KNOWN: readonly FramerError[] = [
+ 'not_configured',
+ 'invalid',
+ 'forbidden',
+ 'not_connected',
+ 'auth_failed',
+ 'no_access',
+ 'not_found',
+ 'invalid_map',
+ 'changed',
+ 'busy',
+ 'unreachable',
+];
+
+export type FramerResult<T> =
+ | ({ ok: true } & T)
+ | { ok: false; code: FramerError; problems?: string[] };
+
+async function call<T>(
+ brandId: string,
+ path: string,
+ init: RequestInit = {},
+): Promise<FramerResult<T>> {
+ try {
+ const {
+ data: { session },
+ } = await createClient().auth.getSession();
+ if (!session) return { ok: false, code: 'session' };
+ const res = await fetch(
+ `${BROWSER_API_BASE_URL}/api/cms/brands/${encodeURIComponent(brandId)}/framer${path}`,
+ {
+ ...init,
+ headers: {
+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),
+ ...init.headers,
+ Authorization: `Bearer ${session.access_token}`,
+ },
+ },
+ );
+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;
+ if (!res.ok) {
+ const known = KNOWN.find((c) => c === body.code);
+ const problems = Array.isArray(body.problems)
+ ? body.problems.filter((p): p is string => typeof p === 'string')
+ : undefined;
+ if (known) return { ok: false, code: known, ...(problems ? { problems } : {}) };
+ const general = apiFailure(res.status, body);
+ return {
+ ok: false,
+ code:
+ general === 'session' ||
+ general === 'workspace' ||
+ general === 'busy' ||
+ general === 'subscription'
+ ? general
+ : 'failed',
+ };
+ }
+ return { ok: true, ...(body as T) };
+ } catch (err) {
+ console.error('Framer call failed:', err);
+ return { ok: false, code: 'failed' };
+ }
+}
+
+/** The brand's connection, and whether this server can keep a Framer key. */
+export function readFramer(brandId: string) {
+ return call<{ configured: boolean; connection: FramerConnection | null }>(brandId, '');
+}
+
+/**
+ * Connects the brand's project (its address or id) with an API key made in
+ * it, or replaces the key: the API checks them with Framer first.
+ */
+export function connectFramer(brandId: string, input: { project: string; apiKey: string }) {
+ return call<{ connection: FramerConnection }>(brandId, '', {
+ method: 'POST',
+ body: JSON.stringify(input),
+ });
+}
+
+/** The project's collections pages may go to, with their fields. */
+export function readFramerCollections(brandId: string) {
+ return call<{ collections: FramerCollection[] }>(brandId, '/collections');
+}
+
+/** Where the brand's pages go: the collection, and which of its fields takes each part. */
+export function saveFramerTarget(
+ brandId: string,
+ target: { collectionId: string; fieldMap: FramerFieldMap },
+) {
+ return call<{ connection: FramerConnection }>(brandId, '', {
+ method: 'PUT',
+ body: JSON.stringify(target),
+ });
+}
+
+/** Disconnects the brand's project; `revoked` is false, as Framer can't revoke a key. */
+export function disconnectFramer(brandId: string) {
+ return call<{ success: boolean; revoked: boolean }>(brandId, '', { method: 'DELETE' });
+}
+
+/** The words a field's name is read for, by part: the first field that has them is suggested. */
+const HINTS: Record<FramerPart, RegExp[]> = {
+ // Whole names only: "SEO Title" is a meta title's.
+ title: [/^((post|page|article|blog)-)?(title|name)$/, /^(heading|headline)$/],
+ body: [/(^|-)(post-)?body($|-)/, /content/, /article/, /rich/],
+ metaTitle: [/(meta|seo)-?title/],
+ metaDescription: [/(meta|seo)-?desc/, /summary/, /excerpt/, /description/],
+ jsonLd: [/json-?ld/, /schema/, /structured/],
+};
+
+/**
+ * The field map a collection suggests, as Webflow's does (server
+ * suggestFieldMap): for each part, the first field of its type whose name
+ * reads as that part, one field a part. A page's title goes first to the
+ * field the slugs are made from; its body falls back to the first
+ * formatted text.
+ */
+export function suggestFramerMap(collection: FramerCollection): FramerFieldMap {
+ const map: FramerFieldMap = {};
+ const taken = new Set<string>();
+ const words = (f: FramerField) => f.name.trim().toLowerCase().replace(/\s+/g, '-');
+ for (const part of FRAMER_PARTS) {
+ const fits = collection.fields.filter(
+ (f) => f.type === FRAMER_PART_TYPES[part] && !taken.has(f.id),
+ );
+ let pick = part === 'title' ? fits.find((f) => f.id === collection.titleField) : undefined;
+ for (const hint of HINTS[part]) {
+ if (pick) break;
+ pick = fits.find((f) => hint.test(words(f)));
+ }
+ if (!pick && part === 'body') pick = fits[0];
+ if (pick) {
+ map[part] = pick.id;
+ taken.add(pick.id);
+ }
+ }
+ return map;
+}
+
+/** The parts of a map whose field is still one of that part's choices, each field once. */
+export function fittingFramerMap(map: FramerFieldMap, fields: FramerField[]): FramerFieldMap {
+ const kept: FramerFieldMap = {};
+ const used = new Set<string>();
+ for (const part of FRAMER_PARTS) {
+ const id = map[part];
+ const field = fields.find((f) => f.id === id);
+ if (!id || !field || field.type !== FRAMER_PART_TYPES[part] || used.has(id)) continue;
+ kept[part] = id;
+ used.add(id);
+ }
+ return kept;
+}
+
+/**
+ * The fields a collection requires that Send to CMS can't fill whatever the
+ * map: of a type no part a page always has can go to (an image, a date…).
+ * The API refuses such a collection until they're optional in Framer.
+ */
+export function unfillableFramerFields(collection: FramerCollection): FramerField[] {
+ return collection.fields.filter((f) => f.required && !FILLABLE_TYPES.has(f.type));
+}
+
+/**
+ * The parts every map places that the collection has no field for (no
+ * formatted text for a page's body, say): pages can't go to it until one is
+ * added in Framer.
+ */
+export function missingFramerParts(collection: FramerCollection): FramerPart[] {
+ return FRAMER_NEEDED.filter(
+ (part) => !collection.fields.some((f) => f.type === FRAMER_PART_TYPES[part]),
+ );
+}
+
+/**
+ * The fields a collection requires that Send to CMS could fill but the map
+ * leaves to no part a page always has: the API refuses the map until each
+ * takes one (JSON-LD doesn't count, as a page may have none).
+ */
+export function unmappedFramerFields(map: FramerFieldMap, fields: FramerField[]): FramerField[] {
+ const filled = new Set(ALWAYS_FILLED.map((part) => map[part]).filter(Boolean));
+ return fields.filter((f) => f.required && FILLABLE_TYPES.has(f.type) && !filled.has(f.id));
+}