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(settings): connect a brand's Webflow site, collection and fields in Settings › Integrations (Send to CMS #1331, phase 2 part 3: Webflow card) (#1505)

Cihanf34bf4dfca8f
diff --git a/web/messages/en.json b/web/messages/en.json
index b5463430f..865497abf 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7632,6 +7632,73 @@
}
}
},
+ "webflow": {
+ "title": "Webflow",
+ "description": "Send to CMS puts {brand}'s pages in a Webflow collection as draft items. You publish them in Webflow.",
+ "noBrand": "Pick a brand to connect its Webflow site.",
+ "unavailable": "Couldn't read the Webflow connection right now.",
+ "notConfigured": "Webflow isn't set up on this server yet.",
+ "connected": "Connected",
+ "refused": "Token refused",
+ "site": "Site: {site}",
+ "notConnectedMember": "Not connected. Admins and managers can connect Webflow.",
+ "refusedMember": "Webflow refused the token. Pages can't go there until an admin or manager pastes a new one.",
+ "pagesGoTo": "Pages go to {collection}.",
+ "noCollection": "No collection picked yet.",
+ "tokenLabel": "Site token",
+ "tokenPlaceholder": "Paste the site token",
+ "tokenHint": "In Webflow: Site settings › Apps & integrations › API access › Generate API token, with Sites: Read and CMS: Read and write. It's kept by our connector service, never shown again.",
+ "connect": "Connect",
+ "connecting": "Connecting…",
+ "connectedToast": "Webflow connected",
+ "refusedNote": "Webflow refused the saved token. Paste a new one to send pages again.",
+ "replaceToken": "Replace token",
+ "cancel": "Cancel",
+ "disconnect": "Disconnect",
+ "disconnectTitle": "Disconnect Webflow?",
+ "disconnectDescription": "Pages stop going to Webflow, and the token is removed. Items already sent stay in Webflow.",
+ "disconnected": "Webflow disconnected",
+ "siteLabel": "Site",
+ "sitePlaceholder": "Pick a site",
+ "collectionLabel": "Collection",
+ "collectionPlaceholder": "Pick a collection",
+ "loadingCollections": "Reading the site's collections…",
+ "noCollections": "This site has no CMS collections.",
+ "collectionsUnavailable": "Couldn't read the site's collections right now.",
+ "fieldsUnavailable": "Couldn't read the collection's fields right now. Pick it again in a moment.",
+ "fieldsTitle": "Which field takes what",
+ "fieldsHint": "Each page's title and slug go to the item's Name and Slug.",
+ "parts": {
+ "body": "Page content (rich 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. In the collection template, add an Embed that puts this field inside a JSON-LD script tag.",
+ "save": "Save",
+ "saved": "Saved. Pages go to {collection}.",
+ "errors": {
+ "not_configured": "Webflow isn't set up on this server yet.",
+ "invalid": "Check what you picked and try again.",
+ "invalidToken": "That doesn't look like a Webflow site token.",
+ "forbidden": "Only admins and managers can change the Webflow connection.",
+ "not_connected": "Connect Webflow first.",
+ "auth_failed": "Webflow refused this token. Check it and try again.",
+ "missing_scopes": "The token needs Sites: Read and CMS: Read and write. Generate one with them.",
+ "no_access": "The token doesn't reach this site or collection.",
+ "no_site": "This token reaches no Webflow site.",
+ "not_found": "That site or collection is gone. Pick another.",
+ "invalid_map": "The fields don't fit the collection.",
+ "changed": "The connection changed meanwhile. Reload and try again.",
+ "session": "Your session expired. Sign in again.",
+ "workspace": "This brand isn't in your workspace.",
+ "busy": "Too many requests. Wait a few minutes.",
+ "failed": "Couldn't reach Webflow. Try again later."
+ }
+ },
"integrations_connected": "Connected",
"integrations_notConfigured": "Not configured",
"integrations_disconnect": "Disconnect",
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index 0b6b5838f..1508a878e 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -39,6 +39,7 @@ import {
} from '@/lib/actions/integrations';
import { matchProperty } from '@/lib/property-match';
import { CatalogSourcesCard } from './catalog-sources-card';
+import { WebflowCard } from './webflow-card';
import { useIntegrationConnect } from '@/hooks/use-integration-connect';
/**
@@ -79,6 +80,8 @@ export function IntegrationsSection() {
</IntegrationCard>
<CatalogSourcesCard />
+
+ <WebflowCard />
</CardContent>
</Card>
);
diff --git a/web/src/components/settings/webflow-card.test.tsx b/web/src/components/settings/webflow-card.test.tsx
new file mode 100644
index 000000000..4b108f874
--- /dev/null
+++ b/web/src/components/settings/webflow-card.test.tsx
@@ -0,0 +1,361 @@
+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 { WebflowConnection } from '@/lib/webflow-client';
+
+const client = vi.hoisted(() => ({
+ readWebflow: vi.fn(),
+ connectWebflow: vi.fn(),
+ listWebflowCollections: vi.fn(),
+ readWebflowCollection: vi.fn(),
+ saveWebflowSettings: vi.fn(),
+ disconnectWebflow: vi.fn(),
+}));
+vi.mock('@/lib/webflow-client', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/webflow-client')>()),
+ ...client,
+}));
+const role = vi.hoisted(() => ({ canManage: true }));
+vi.mock('@/hooks/use-user-role', () => ({ useUserRole: () => role }));
+vi.mock('@/stores/use-brand-store', () => ({
+ useBrandStore: () => ({ activeBrandId: 'b1', brands: [{ id: 'b1', name: 'Acme' }] }),
+}));
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+const { WebflowCard } = await import('./webflow-card');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+/** Settings › Integrations › Webflow (Send to CMS #1331, phase 2): a brand's site, collection and fields. */
+
+let container: HTMLDivElement;
+let root: Root;
+
+const CONNECTED: WebflowConnection = {
+ status: 'connected',
+ siteId: 's1',
+ siteName: 'Acme',
+ collectionId: 'c1',
+ collectionName: 'Blog Posts',
+ fieldMap: { body: 'post-body', metaDescription: 'post-summary' },
+ connectedAt: '2026-10-25T10:00:00Z',
+ updatedAt: '2026-10-25T10:00:00Z',
+};
+const FIELDS = [
+ { slug: 'name', name: 'Name', type: 'PlainText', required: true },
+ { slug: 'post-body', name: 'Post Body', type: 'RichText', required: false },
+ { slug: 'post-summary', name: 'Post Summary', type: 'PlainText', required: false },
+];
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <WebflowCard />
+ </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 select a label names. */
+const picker = (label: string) => {
+ const name = [...container.querySelectorAll('label')].find((l) => l.textContent === label);
+ return container.querySelector(`[id="${name!.htmlFor}"]`)!;
+};
+const option = (text: string) =>
+ [...document.querySelectorAll<HTMLElement>('[role="option"]')].find(
+ (o) => o.textContent === text,
+ );
+async function typeToken(value: string) {
+ const input = container.querySelector<HTMLInputElement>('input[type="password"]')!;
+ await act(async () => {
+ const setter = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!;
+ setter.call(input, value);
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await act(async () => {
+ container
+ .querySelector('form')!
+ .dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
+ });
+}
+
+beforeEach(() => {
+ role.canManage = true;
+ client.readWebflow
+ .mockReset()
+ .mockResolvedValue({ ok: true, configured: true, connection: null });
+ client.connectWebflow.mockReset().mockResolvedValue({
+ ok: true,
+ connection: { ...CONNECTED, collectionId: null, collectionName: null, fieldMap: {} },
+ sites: [],
+ });
+ client.listWebflowCollections.mockReset().mockResolvedValue({
+ ok: true,
+ sites: [{ id: 's1', name: 'Acme' }],
+ siteId: 's1',
+ collections: [{ id: 'c1', name: 'Blog Posts', slug: 'post' }],
+ });
+ client.readWebflowCollection.mockReset().mockResolvedValue({
+ ok: true,
+ id: 'c1',
+ name: 'Blog Posts',
+ fields: FIELDS,
+ suggested: { body: 'post-body' },
+ });
+ client.saveWebflowSettings.mockReset().mockResolvedValue({ ok: true, connection: CONNECTED });
+ client.disconnectWebflow.mockReset().mockResolvedValue({ ok: true, success: true });
+ toast.error.mockReset();
+ toast.success.mockReset();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+ document.body.replaceChildren();
+});
+
+describe('WebflowCard', () => {
+ it('says when this server has no Webflow set up', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: false, connection: null });
+ await render();
+ expect(container.textContent).toContain("Webflow isn't set up on this server yet.");
+ expect(container.querySelector('input')).toBeNull();
+ });
+
+ it('connects the brand’s site with a pasted token, then asks where pages go', async () => {
+ await render();
+ expect(client.readWebflow).toHaveBeenCalledWith('b1');
+ expect(container.textContent).toContain(
+ "Send to CMS puts Acme's pages in a Webflow collection",
+ );
+ await typeToken(' wf-token-123 ');
+ expect(client.connectWebflow).toHaveBeenCalledWith('b1', 'wf-token-123');
+ expect(toast.success).toHaveBeenCalledWith('Webflow connected');
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ expect(client.listWebflowCollections).toHaveBeenCalledWith('b1', 's1');
+ expect(container.textContent).toContain('Collection');
+ });
+
+ it('says why a token wasn’t taken, and keeps the form', async () => {
+ client.connectWebflow.mockResolvedValue({ ok: false, code: 'missing_scopes' });
+ await render();
+ await typeToken('wf-token');
+ expect(toast.error).toHaveBeenCalledWith(
+ 'The token needs Sites: Read and CMS: Read and write. Generate one with them.',
+ );
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('asks for a new token when Webflow refused the saved one', async () => {
+ client.readWebflow.mockResolvedValue({
+ ok: true,
+ configured: true,
+ connection: { ...CONNECTED, status: 'auth_failed' },
+ });
+ await render();
+ expect(container.textContent).toContain('Token refused');
+ expect(container.textContent).toContain('Webflow refused the saved token.');
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('reads the saved collection’s fields with its map, and saves it', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ await render();
+ expect(client.readWebflowCollection).toHaveBeenCalledWith('b1', 'c1', 's1');
+ expect(container.textContent).toContain('Which field takes what');
+ await act(async () => {
+ button('Save')!.click();
+ });
+ expect(client.saveWebflowSettings).toHaveBeenCalledWith('b1', {
+ siteId: 's1',
+ collectionId: 'c1',
+ fieldMap: { body: 'post-body', metaDescription: 'post-summary' },
+ });
+ expect(toast.success).toHaveBeenCalledWith('Saved. Pages go to Blog Posts.');
+ });
+
+ it('lists what doesn’t fit when a map is refused', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ client.saveWebflowSettings.mockResolvedValue({
+ ok: false,
+ code: 'invalid_map',
+ problems: ['The collection requires Category, which Send to CMS doesn’t fill'],
+ });
+ await render();
+ await act(async () => {
+ button('Save')!.click();
+ });
+ expect(toast.error).toHaveBeenCalledWith("The fields don't fit the collection.");
+ expect(container.textContent).toContain('The collection requires Category');
+ });
+
+ it('shows a member where pages go, without the token or the settings', async () => {
+ role.canManage = false;
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ await render();
+ expect(container.textContent).toContain('Pages go to Blog Posts.');
+ expect(container.querySelector('input')).toBeNull();
+ expect(button('Disconnect')).toBeUndefined();
+ expect(client.listWebflowCollections).not.toHaveBeenCalled();
+
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: null });
+ act(() => root.unmount());
+ root = createRoot(container);
+ await render();
+ expect(container.textContent).toContain('Admins and managers can connect Webflow.');
+ });
+
+ it('disconnects after asking', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ await render();
+ await act(async () => {
+ button('Disconnect')!.click();
+ });
+ const confirm = [...document.body.querySelectorAll('button')].filter(
+ (b) => b.textContent === 'Disconnect',
+ );
+ await act(async () => {
+ confirm[confirm.length - 1].click();
+ });
+ expect(client.disconnectWebflow).toHaveBeenCalledWith('b1');
+ expect(toast.success).toHaveBeenCalledWith('Webflow disconnected');
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('gives another collection its own suggested map, not the saved one', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ client.listWebflowCollections.mockResolvedValue({
+ ok: true,
+ sites: [{ id: 's1', name: 'Acme' }],
+ siteId: 's1',
+ collections: [
+ { id: 'c1', name: 'Blog Posts', slug: 'post' },
+ { id: 'c2', name: 'Guides', slug: 'guide' },
+ ],
+ });
+ await render();
+ client.readWebflowCollection.mockResolvedValue({
+ ok: true,
+ id: 'c2',
+ name: 'Guides',
+ fields: FIELDS,
+ suggested: { body: 'post-body' },
+ });
+ await click(picker('Collection'));
+ // Base UI picks the highlighted option: the pointer moves onto it first.
+ const guides = option('Guides')!;
+ await act(async () => {
+ guides.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));
+ });
+ await click(guides);
+ expect(client.readWebflowCollection).toHaveBeenLastCalledWith('b1', 'c2', 's1');
+ await click(button('Save'));
+ expect(client.saveWebflowSettings).toHaveBeenCalledWith('b1', {
+ siteId: 's1',
+ collectionId: 'c2',
+ fieldMap: { body: 'post-body' },
+ });
+ });
+
+ it('doesn’t save when the collection’s fields couldn’t be read', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ client.readWebflowCollection.mockResolvedValue({ ok: false, code: 'failed' });
+ await render();
+ expect(container.textContent).toContain("Couldn't read the collection's fields right now.");
+ expect(button('Save')!.disabled).toBe(true);
+ });
+
+ it('says the collections couldn’t be read, not that there are none', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ client.listWebflowCollections.mockResolvedValue({ ok: false, code: 'failed' });
+ await render();
+ expect(container.textContent).toContain("Couldn't read the site's collections right now.");
+ expect(container.textContent).not.toContain('This site has no CMS collections.');
+ });
+
+ it('reads the connection again when Webflow refuses its token, and asks for a new one', async () => {
+ client.readWebflow
+ .mockResolvedValueOnce({ ok: true, configured: true, connection: CONNECTED })
+ .mockResolvedValue({
+ ok: true,
+ configured: true,
+ connection: { ...CONNECTED, status: 'auth_failed' },
+ });
+ client.listWebflowCollections.mockResolvedValue({ ok: false, code: 'auth_failed' });
+ await render();
+ await act(async () => {});
+ expect(client.readWebflow).toHaveBeenCalledTimes(2);
+ expect(container.textContent).toContain('Webflow refused the saved token.');
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ });
+
+ it('replaces the token, or goes back to the settings', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ await render();
+ await click(button('Replace token'));
+ expect(container.querySelector('input[type="password"]')).not.toBeNull();
+ expect(button('Replace token')).toBeUndefined();
+ await click(button('Cancel'));
+ expect(container.querySelector('input[type="password"]')).toBeNull();
+ expect(container.textContent).toContain('Which field takes what');
+ });
+
+ it('saves only what the pickers show, a field deleted in Webflow since left out', async () => {
+ client.readWebflow.mockResolvedValue({
+ ok: true,
+ configured: true,
+ connection: { ...CONNECTED, fieldMap: { body: 'post-body', metaTitle: 'seo-title-gone' } },
+ });
+ await render();
+ await click(button('Save'));
+ expect(client.saveWebflowSettings).toHaveBeenCalledWith('b1', {
+ siteId: 's1',
+ collectionId: 'c1',
+ fieldMap: { body: 'post-body' },
+ });
+ });
+
+ it('names a refused map’s parts by their labels, read out', async () => {
+ client.readWebflow.mockResolvedValue({ ok: true, configured: true, connection: CONNECTED });
+ client.saveWebflowSettings.mockResolvedValue({
+ ok: false,
+ code: 'invalid_map',
+ problems: ['metaTitle: the collection has no field "x"', 'The collection requires Category'],
+ });
+ await render();
+ await click(button('Save'));
+ 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('tells a member that pages can’t go while the token is refused', async () => {
+ role.canManage = false;
+ client.readWebflow.mockResolvedValue({
+ ok: true,
+ configured: true,
+ connection: { ...CONNECTED, status: 'auth_failed' },
+ });
+ await render();
+ expect(container.textContent).toContain(
+ "Webflow refused the token. Pages can't go there until an admin or manager pastes a new one.",
+ );
+ expect(container.textContent).not.toContain('Pages go to Blog Posts.');
+ });
+});
diff --git a/web/src/components/settings/webflow-card.tsx b/web/src/components/settings/webflow-card.tsx
new file mode 100644
index 000000000..a47ef9019
--- /dev/null
+++ b/web/src/components/settings/webflow-card.tsx
@@ -0,0 +1,619 @@
+'use client';
+
+import { useEffect, useId, useRef, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { AlertTriangle, Globe, 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 {
+ Dialog,
+ DialogClose,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from '@/components/ui/dialog';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { useUserRole } from '@/hooks/use-user-role';
+import {
+ WEBFLOW_PARTS,
+ WEBFLOW_PART_TYPES,
+ type WebflowError,
+ connectWebflow,
+ disconnectWebflow,
+ listWebflowCollections,
+ readWebflow,
+ readWebflowCollection,
+ saveWebflowSettings,
+ type WebflowCollection,
+ type WebflowConnection,
+ type WebflowField,
+ type WebflowFieldMap,
+ type WebflowSite,
+} from '@/lib/webflow-client';
+import { useBrandStore } from '@/stores/use-brand-store';
+
+/** The parts of a map whose field is still one of that part's choices, each field once. */
+function fitting(map: WebflowFieldMap, fields: WebflowField[]): WebflowFieldMap {
+ const kept: WebflowFieldMap = {};
+ const used = new Set<string>();
+ for (const part of WEBFLOW_PARTS) {
+ const slug = map[part];
+ const field = fields.find((f) => f.slug === slug);
+ if (!slug || !field || field.type !== WEBFLOW_PART_TYPES[part]) continue;
+ if (slug === 'name' || slug === 'slug' || used.has(slug)) continue;
+ kept[part] = slug;
+ used.add(slug);
+ }
+ return kept;
+}
+
+/** A part the map leaves out. */
+const NOT_SENT = '__none__';
+/** Answers that mean the connection changed: it's read again. */
+const STALE: readonly WebflowError[] = ['auth_failed', 'changed', 'not_connected'];
+
+/**
+ * Send to CMS → Webflow (#1331, phase 2): the active brand's Webflow site.
+ * Admins and managers connect it with a site token, pick the collection
+ * pages go to and which of its fields takes each part of a page, replace
+ * the token and disconnect; members see where pages go.
+ */
+export function WebflowCard() {
+ const t = useTranslations('settings.webflow');
+ const { activeBrandId, brands } = useBrandStore();
+ const { canManage } = useUserRole();
+ 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: WebflowConnection | null;
+ failed: boolean;
+ } | null>(null);
+ // Replacing the token, 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 token refused or replaced meanwhile.
+ const [reads, setReads] = useState(0);
+
+ useEffect(() => {
+ if (!activeBrandId) return;
+ let cancelled = false;
+ readWebflow(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: WebflowConnection | null) =>
+ setRead((r) => (r && r.brandId === activeBrandId ? { ...r, connection: next } : r));
+
+ const disconnect = async () => {
+ if (!activeBrandId) return;
+ setDisconnecting(true);
+ const result = await disconnectWebflow(activeBrandId);
+ setDisconnecting(false);
+ if (!result.ok) {
+ toast.error(t(`errors.${result.code}`));
+ return;
+ }
+ setConnection(null);
+ toast.success(t('disconnected'));
+ };
+
+ 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">
+ <Globe 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>
+ {connection?.siteName && (
+ <p className="mt-1 text-xs text-muted-foreground">
+ {t('site', { site: connection.siteName })}
+ </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={() => setReplacingFor(activeBrandId)}>
+ {t('replaceToken')}
+ </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>
+ )}
+ <TokenForm
+ brandId={activeBrandId}
+ onCancel={replacing ? () => setReplacingFor(null) : undefined}
+ onConnected={(next) => {
+ setReplacingFor(null);
+ setConnection(next);
+ }}
+ />
+ </div>
+ ) : (
+ <WebflowMapping
+ key={activeBrandId}
+ brandId={activeBrandId}
+ connection={connection}
+ onSaved={setConnection}
+ onStale={() => setReads((n) => n + 1)}
+ />
+ )}
+ </div>
+ );
+}
+
+/** The site token, pasted once: it goes to the API and is never shown again. */
+function TokenForm({
+ brandId,
+ onConnected,
+ onCancel,
+}: {
+ brandId: string;
+ onConnected: (connection: WebflowConnection) => void;
+ onCancel?: () => void;
+}) {
+ const t = useTranslations('settings.webflow');
+ const [token, setToken] = useState('');
+ const [connecting, setConnecting] = useState(false);
+
+ const connect = async () => {
+ setConnecting(true);
+ const result = await connectWebflow(brandId, token.trim());
+ setConnecting(false);
+ if (!result.ok) {
+ toast.error(t(result.code === 'invalid' ? 'errors.invalidToken' : `errors.${result.code}`));
+ return;
+ }
+ setToken('');
+ toast.success(t('connectedToast'));
+ onConnected(result.connection);
+ };
+
+ return (
+ <form
+ className="space-y-2"
+ onSubmit={(e) => {
+ e.preventDefault();
+ if (token.trim() && !connecting) void connect();
+ }}
+ >
+ <Label htmlFor={`webflow-token-${brandId}`}>{t('tokenLabel')}</Label>
+ <div className="flex flex-wrap gap-2">
+ <Input
+ id={`webflow-token-${brandId}`}
+ aria-describedby={`webflow-token-hint-${brandId}`}
+ type="password"
+ autoComplete="off"
+ spellCheck={false}
+ value={token}
+ onChange={(e) => setToken(e.target.value)}
+ placeholder={t('tokenPlaceholder')}
+ className="min-w-0 flex-1 basis-64"
+ />
+ <Button
+ type="submit"
+ size="sm"
+ className="h-9 gap-2"
+ disabled={!token.trim() || 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" onClick={onCancel}>
+ {t('cancel')}
+ </Button>
+ )}
+ </div>
+ <p id={`webflow-token-hint-${brandId}`} className="text-xs text-muted-foreground">
+ {t('tokenHint')}
+ </p>
+ </form>
+ );
+}
+
+/** The site and collection pages go to, and which of its fields takes each part of a page. */
+function WebflowMapping({
+ brandId,
+ connection,
+ onSaved,
+ onStale,
+}: {
+ brandId: string;
+ connection: WebflowConnection;
+ onSaved: (connection: WebflowConnection) => void;
+ /** The connection changed (a token refused, replaced or removed): read it again. */
+ onStale: () => void;
+}) {
+ const t = useTranslations('settings.webflow');
+ // The saved settings, for the fields 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: WebflowError) => {
+ toast.error(t(`errors.${code}`));
+ if (STALE.includes(code)) stale.current();
+ };
+ const [siteId, setSiteId] = useState<string | null>(connection.siteId);
+ const [collectionId, setCollectionId] = useState<string | null>(connection.collectionId);
+ // What was read, by the site or collection asked: until it's the one on screen, it's loading.
+ const [siteRead, setSiteRead] = useState<{
+ siteId: string | null;
+ sites: WebflowSite[];
+ collections: WebflowCollection[];
+ failed: boolean;
+ } | null>(null);
+ const [fieldsRead, setFieldsRead] = useState<{
+ key: string;
+ fields: WebflowField[];
+ failed: boolean;
+ } | null>(null);
+ const fieldsKey = `${siteId}:${collectionId}`;
+ const sites = siteRead?.sites ?? [];
+ const sitesRead = siteRead && siteRead.siteId === siteId ? siteRead : null;
+ const collections = sitesRead ? sitesRead.collections : null;
+ const fieldsNow = fieldsRead?.key === fieldsKey ? fieldsRead : null;
+ const fields = fieldsNow?.fields ?? null;
+ const [map, setMap] = useState<WebflowFieldMap>(connection.fieldMap);
+ const [problems, setProblems] = useState<string[]>([]);
+ const [saving, setSaving] = useState(false);
+
+ // The site's collections.
+ useEffect(() => {
+ let cancelled = false;
+ listWebflowCollections(brandId, siteId).then((result) => {
+ if (cancelled) return;
+ if (!result.ok) {
+ report(result.code);
+ // The sites stay pickable; the collections say they couldn't be read.
+ setSiteRead((prev) => ({
+ siteId,
+ sites: prev?.sites ?? [],
+ collections: [],
+ failed: true,
+ }));
+ return;
+ }
+ // The site the API read (none when the token no longer reaches the
+ // one asked), or the token's one site.
+ const site =
+ result.siteId ?? (result.sites.length === 1 ? (result.sites[0]?.id ?? null) : null);
+ if (site !== siteId) setSiteId(site);
+ setSiteRead({
+ siteId: site,
+ sites: result.sites,
+ collections: site === result.siteId ? result.collections : [],
+ failed: false,
+ });
+ });
+ return () => {
+ cancelled = true;
+ };
+ // report reads the latest onStale through a ref.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [brandId, siteId, t]);
+
+ // The collection's fields: the saved map for the saved collection, else the suggested one.
+ useEffect(() => {
+ if (!collectionId) return;
+ let cancelled = false;
+ const key = `${siteId}:${collectionId}`;
+ readWebflowCollection(brandId, collectionId, siteId).then((result) => {
+ if (cancelled) return;
+ if (!result.ok) {
+ report(result.code);
+ setFieldsRead({ key, fields: [], failed: true });
+ return;
+ }
+ setFieldsRead({ key, fields: result.fields, failed: false });
+ // Only what the pickers can show: a saved part whose field was deleted
+ // or changed type in Webflow since is left out, so what's saved is what's shown.
+ setMap(
+ fitting(
+ collectionId === saved.current.collectionId ? saved.current.fieldMap : result.suggested,
+ result.fields,
+ ),
+ );
+ });
+ return () => {
+ cancelled = true;
+ };
+ // report reads the latest onStale through a ref.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [brandId, collectionId, siteId, t]);
+
+ const save = async () => {
+ if (!siteId || !collectionId) return;
+ setSaving(true);
+ setProblems([]);
+ const result = await saveWebflowSettings(brandId, { siteId, collectionId, fieldMap: map });
+ setSaving(false);
+ if (!result.ok) {
+ setProblems(result.problems ?? []);
+ report(result.code);
+ return;
+ }
+ toast.success(t('saved', { collection: result.connection.collectionName ?? '' }));
+ onSaved(result.connection);
+ };
+
+ /** The API names a part by its key ("metaTitle: …"): the person reads its label. */
+ const problemText = (problem: string) => {
+ const part = WEBFLOW_PARTS.find((p) => problem.startsWith(`${p}: `));
+ return part ? `${t(`parts.${part}`)}: ${problem.slice(part.length + 2)}` : problem;
+ };
+ const siteItems = sites.map((s) => ({ value: s.id, label: s.name }));
+ const collectionItems = (collections ?? []).map((c) => ({ value: c.id, label: c.name }));
+ const required = new Set((fields ?? []).filter((f) => f.required).map((f) => f.slug));
+
+ return (
+ <div className="space-y-4">
+ {sites.length > 1 && (
+ <Picker
+ label={t('siteLabel')}
+ items={siteItems}
+ value={siteId}
+ placeholder={t('sitePlaceholder')}
+ onChange={(value) => {
+ setSiteId(value);
+ setCollectionId(null);
+ setMap({});
+ }}
+ />
+ )}
+ {siteRead === null || (siteId !== null && collections === 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>
+ ) : !siteId || !collections ? null : sitesRead?.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={collectionId}
+ placeholder={t('collectionPlaceholder')}
+ onChange={(value) => {
+ if (value === collectionId) return;
+ setCollectionId(value);
+ // The new collection's own map comes with its fields.
+ setMap({});
+ setProblems([]);
+ }}
+ />
+ )}
+
+ {collectionId && (
+ <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>
+ {fields === null ? (
+ <Skeleton className="h-24 w-full" />
+ ) : fieldsNow?.failed ? (
+ <p className="text-sm text-muted-foreground">{t('fieldsUnavailable')}</p>
+ ) : (
+ WEBFLOW_PARTS.map((part) => {
+ // A field of the part's type that no other part takes.
+ const taken = new Set(
+ WEBFLOW_PARTS.filter((other) => other !== part).map((other) => map[other]),
+ );
+ const fits = fields.filter(
+ (f) =>
+ f.type === WEBFLOW_PART_TYPES[part] &&
+ f.slug !== 'name' &&
+ f.slug !== 'slug' &&
+ !taken.has(f.slug),
+ );
+ const items = [
+ ...(part === 'body' ? [] : [{ value: NOT_SENT, label: t('notSent') }]),
+ ...fits.map((f) => ({
+ value: f.slug,
+ label: required.has(f.slug) ? 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
+ : part === 'body'
+ ? 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;
+ })
+ }
+ />
+ );
+ })
+ )}
+ {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={save}
+ disabled={saving || !fields || fieldsNow?.failed || !fields.length || !map.body}
+ >
+ {saving && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {t('save')}
+ </Button>
+ </div>
+ )}
+ </div>
+ );
+}
+
+/** A labelled select, one row. */
+function Picker({
+ label,
+ items,
+ value,
+ placeholder,
+ onChange,
+}: {
+ label: string;
+ items: { value: string; label: string }[];
+ value: string | null;
+ placeholder: string;
+ onChange: (value: string | null) => void;
+}) {
+ const id = useId();
+ return (
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Label htmlFor={id} className="font-normal">
+ {label}
+ </Label>
+ <Select items={items} value={value} onValueChange={(v) => onChange(v ?? null)}>
+ <SelectTrigger id={id} className="h-8 w-64 max-w-full text-xs">
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent>
+ {items.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/web/src/lib/webflow-client.test.ts b/web/src/lib/webflow-client.test.ts
new file mode 100644
index 000000000..535f48c2f
--- /dev/null
+++ b/web/src/lib/webflow-client.test.ts
@@ -0,0 +1,82 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+/** Send to CMS › Webflow (#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 { connectWebflow, readWebflowCollection, saveWebflowSettings, disconnectWebflow } =
+ await import('./webflow-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/webflow';
+
+describe('webflow-client', () => {
+ it('sends the token once, in the body, with the session', async () => {
+ answer(200, { connection: { status: 'connected' }, sites: [{ id: 's1', name: 'Acme' }] });
+ expect(await connectWebflow('b1', 'wf-token')).toEqual({
+ ok: true,
+ connection: { status: 'connected' },
+ sites: [{ id: 's1', name: 'Acme' }],
+ });
+ const [url, init] = fetchMock.mock.calls[0];
+ expect(url).toBe(BASE);
+ expect(init).toMatchObject({
+ method: 'POST',
+ body: JSON.stringify({ token: 'wf-token' }),
+ headers: { 'Content-Type': 'application/json', Authorization: 'Bearer tok' },
+ });
+ });
+
+ it('asks for a collection on a named site, and saves the settings', async () => {
+ answer(200, { id: 'c1', name: 'Blog', fields: [], suggested: {} });
+ await readWebflowCollection('b1', 'c1', 's2');
+ expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}/collections/c1?siteId=s2`);
+
+ answer(200, { connection: { collectionId: 'c1' } });
+ await saveWebflowSettings('b1', {
+ siteId: 's1',
+ collectionId: 'c1',
+ fieldMap: { body: 'post-body' },
+ });
+ expect(fetchMock.mock.calls[1][1]).toMatchObject({
+ method: 'PUT',
+ body: JSON.stringify({ siteId: 's1', collectionId: 'c1', fieldMap: { body: 'post-body' } }),
+ });
+ });
+
+ it("names the API's reasons with the problems, and the general ones", async () => {
+ answer(400, {
+ code: 'invalid_map',
+ problems: ['body: Post Summary is PlainText, not RichText'],
+ });
+ expect(
+ await saveWebflowSettings('b1', { siteId: 's1', collectionId: 'c1', fieldMap: {} }),
+ ).toEqual({
+ ok: false,
+ code: 'invalid_map',
+ problems: ['body: Post Summary is PlainText, not RichText'],
+ });
+ answer(409, { code: 'auth_failed' });
+ expect(await connectWebflow('b1', 'x')).toEqual({ ok: false, code: 'auth_failed' });
+ answer(403, { code: 'not_in_workspace' });
+ expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'workspace' });
+ answer(429, { message: 'Too many requests' });
+ expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'busy' });
+ answer(500, { code: 'something_else' });
+ expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'failed' });
+ fetchMock.mockRejectedValue(new TypeError('offline'));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ expect(await disconnectWebflow('b1')).toEqual({ ok: false, code: 'failed' });
+ });
+});
diff --git a/web/src/lib/webflow-client.ts b/web/src/lib/webflow-client.ts
new file mode 100644
index 000000000..3e8368e20
--- /dev/null
+++ b/web/src/lib/webflow-client.ts
@@ -0,0 +1,178 @@
+import { BROWSER_API_BASE_URL } from '@/config/api';
+import { apiFailure } from '@/lib/api-failure';
+import { createClient } from '@/lib/supabase/client';
+
+/**
+ * A brand's Webflow connection for Send to CMS (#1331, phase 2), from the
+ * browser through the API's same-origin proxy. The site token goes from
+ * here to the API once, which hands it to Composio: never through a server
+ * action, a log or a response.
+ */
+
+/** The parts of a page a field map places. */
+export const WEBFLOW_PARTS = ['body', 'metaTitle', 'metaDescription', 'jsonLd'] as const;
+export type WebflowPart = (typeof WEBFLOW_PARTS)[number];
+export type WebflowFieldMap = Partial<Record<WebflowPart, string>>;
+/** The Webflow field types each part may go to. */
+export const WEBFLOW_PART_TYPES: Record<WebflowPart, string> = {
+ body: 'RichText',
+ metaTitle: 'PlainText',
+ metaDescription: 'PlainText',
+ jsonLd: 'PlainText',
+};
+
+export interface WebflowConnection {
+ status: 'connected' | 'auth_failed';
+ siteId: string | null;
+ siteName: string | null;
+ collectionId: string | null;
+ collectionName: string | null;
+ fieldMap: WebflowFieldMap;
+ connectedAt: string;
+ updatedAt: string;
+}
+export interface WebflowSite {
+ id: string;
+ name: string;
+}
+export interface WebflowCollection {
+ id: string;
+ name: string;
+ slug: string;
+}
+export interface WebflowField {
+ slug: string;
+ name: string;
+ type: string;
+ required: boolean;
+}
+
+export type WebflowError =
+ | 'not_configured'
+ | 'invalid'
+ | 'forbidden'
+ | 'not_connected'
+ | 'auth_failed'
+ | 'missing_scopes'
+ | 'no_access'
+ | 'no_site'
+ | 'not_found'
+ | 'invalid_map'
+ | 'changed'
+ | 'session'
+ | 'workspace'
+ | 'busy'
+ | 'failed';
+
+const KNOWN: readonly WebflowError[] = [
+ 'not_configured',
+ 'invalid',
+ 'forbidden',
+ 'not_connected',
+ 'auth_failed',
+ 'missing_scopes',
+ 'no_access',
+ 'no_site',
+ 'not_found',
+ 'invalid_map',
+ 'changed',
+];
+
+export type WebflowResult<T> =
+ | ({ ok: true } & T)
+ | { ok: false; code: WebflowError; problems?: string[] };
+
+async function call<T>(
+ brandId: string,
+ path: string,
+ init: RequestInit = {},
+): Promise<WebflowResult<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)}/webflow${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
+ : 'failed',
+ };
+ }
+ return { ok: true, ...(body as T) };
+ } catch (err) {
+ console.error('Webflow call failed:', err);
+ return { ok: false, code: 'failed' };
+ }
+}
+
+/** The brand's connection, and whether this server has Webflow set up. */
+export function readWebflow(brandId: string) {
+ return call<{ configured: boolean; connection: WebflowConnection | null }>(brandId, '');
+}
+
+/** Connects the brand's site with its token, or replaces the token. */
+export function connectWebflow(brandId: string, token: string) {
+ return call<{ connection: WebflowConnection; sites: WebflowSite[] }>(brandId, '', {
+ method: 'POST',
+ body: JSON.stringify({ token }),
+ });
+}
+
+/** The sites the token reaches, and the collections of one (the connection's unless named). */
+export function listWebflowCollections(brandId: string, siteId?: string | null) {
+ const query = siteId ? `?${new URLSearchParams({ siteId })}` : '';
+ return call<{ sites: WebflowSite[]; siteId: string | null; collections: WebflowCollection[] }>(
+ brandId,
+ `/collections${query}`,
+ );
+}
+
+/** A collection's fields, and the map they suggest. */
+export function readWebflowCollection(
+ brandId: string,
+ collectionId: string,
+ siteId?: string | null,
+) {
+ const query = siteId ? `?${new URLSearchParams({ siteId })}` : '';
+ return call<{ id: string; name: string; fields: WebflowField[]; suggested: WebflowFieldMap }>(
+ brandId,
+ `/collections/${encodeURIComponent(collectionId)}${query}`,
+ );
+}
+
+/** Where the brand's pages go: the site, the collection and the field map. */
+export function saveWebflowSettings(
+ brandId: string,
+ settings: { siteId: string; collectionId: string; fieldMap: WebflowFieldMap },
+) {
+ return call<{ connection: WebflowConnection }>(brandId, '', {
+ method: 'PUT',
+ body: JSON.stringify(settings),
+ });
+}
+
+/** Disconnects the brand's Webflow site: Composio lets go of the token. */
+export function disconnectWebflow(brandId: string) {
+ return call<{ success: boolean }>(brandId, '', { method: 'DELETE' });
+}