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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(cms): connect a brand's Wix site with its owner's API key and send pages to its Blog as draft posts (#1331) (#1721)
Cihan24aed3548c83
diff --git a/server/.env.example b/server/.env.exampleindex c364a7adf..9d80a8ba8 100644--- a/server/.env.example+++ b/server/.env.example@@ -234,11 +234,11 @@ AI_VOLUME_MULTIPLIER=0.45# COMPOSIO_GMC_AUTH_CONFIG_ID=# Store connections for the product catalog (#1263, CONNECTORS.md), and-# Send to CMS's WordPress and Framer connections (#1331): the key that+# Send to CMS's WordPress, Framer and Wix connections (#1331): the key that# encrypts a store's or a WordPress site's sign-in, and a Framer project's-# API key, 32 bytes in base64 (openssl rand -base64 32). Only this server+# or a Wix site's API key, 32 bytes in base64 (openssl rand -base64 32). Only this server# holds it; the web app never sees a sign-in. Optional: without it,-# Settings says store connections, WordPress and Framer aren't set up, and+# Settings says store connections, WordPress, Framer and Wix aren't set up, and# feeds, uploads and the webhook work as before. Changing it makes the saved# sign-ins unreadable until they're entered again.# CONNECTOR_CREDENTIALS_KEY=diff --git a/server/src/lib/cms/wix-delivery.js b/server/src/lib/cms/wix-delivery.jsnew file mode 100644index 000000000..0cb9c84b0--- /dev/null+++ b/server/src/lib/cms/wix-delivery.js@@ -0,0 +1,178 @@+import * as cheerio from 'cheerio';+import supabaseAdmin from '../../config/supabase.js';+import { logger } from '../logger.js';+import { readCmsCredentials } from './credentials.js';+import { WixError, createDraftPost, readDraftPost, toRicos, updateDraftPost } from './wix.js';++/**+ * Send to CMS to Wix (#1331, phase 2; 00372): a page goes to the brand's Wix+ * site's Blog as a draft post, or updates the post its last Wix send made on+ * that site. Unlike WordPress, Wix keeps a draft of a live post: a page whose+ * post is published updates that draft (UPDATE_PUBLICATION), and the post+ * people read stays as it was until the person publishes the changes in Wix.+ * content-delivery.js reserves, writes and batches the deliveries as it does+ * for the webhook.+ *+ * The page's title and meta description, and its JSON-LD, go as the post's+ * SEO tags; its images stay out (Wix shows only images in its Media+ * Manager), and the send counts them.+ */++/** Wix's limits on a draft post's excerpt and slug. */+const EXCERPT_MAX = 500;+const SLUG_MAX = 100;++/**+ * The post's status that means it's live: its changes go to its draft+ * version (UPDATE_PUBLICATION). A scheduled post isn't live yet, so it's+ * written as a draft is (UPDATE).+ */+const LIVE = 'PUBLISHED';++/**+ * The post the page's last Wix send made on this site, if any, whatever+ * became of that send. The site is its id (the delivery's target_collection).+ */+async function lastPost(draftId, siteId, deliveryId) {+ const { data, error } = await supabaseAdmin+ .from('content_draft_deliveries')+ .select('id, external_id')+ .eq('draft_id', draftId)+ .eq('target', 'wix')+ .eq('target_collection', siteId)+ .not('external_id', 'is', null)+ .neq('id', deliveryId)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return data?.external_id ? data : null;+}++/**+ * The key the send was refused with: Settings asks for a new one. Only the+ * connection as the send read it: one connected again meanwhile keeps its+ * new key.+ */+async function markRefused(connection) {+ const { error } = await supabaseAdmin+ .from('brand_cms_connections')+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })+ .eq('id', connection.id)+ .eq('provider', 'wix')+ .eq('updated_at', connection.updated_at);+ if (error) logger.warn({ err: error }, '[content-delivery] wix refusal not kept');+}++/** The page's HTML as Wix takes it: its JSON-LD (sent as SEO tags) and images out; how many images went. */+export function toWixHtml(html) {+ const $ = cheerio.load(html, null, false);+ $('script').remove();+ const images = $('img').length;+ $('img, picture, source').remove();+ // A figure left with only its caption, or nothing, goes too.+ $('figure').each((_, el) => {+ if (!$(el).find('*').not('figcaption').length) $(el).remove();+ });+ return { html: $.html(), images };+}++/** The post's SEO tags: its title, meta description and JSON-LD. */+export function seoTags(page, jsonLd = []) {+ const tags = [];+ const title = page.metaTitle || page.title;+ if (title) tags.push({ type: 'title', children: title, custom: false, disabled: false });+ if (page.metaDescription) {+ tags.push({+ type: 'meta',+ props: { name: 'description', content: page.metaDescription },+ custom: false,+ disabled: false,+ });+ }+ for (const block of jsonLd) {+ tags.push({+ type: 'script',+ props: { type: 'application/ld+json' },+ // Every "<" escaped: nothing in it can end or open a tag in the post's script.+ children: JSON.stringify(block).replace(/</g, '\\u003c'),+ custom: false,+ disabled: false,+ });+ }+ return tags;+}++/**+ * Sends one page to the brand's Wix site's Blog. What went wrong is said in+ * our words.+ *+ * @param {{ delivery: { id: string }, page: object, html: string, jsonLd?: object[],+ * connection: { id: string, site_id: string, account: string, updated_at: string },+ * request?: Function, base?: string }} input+ * @returns {Promise<{ taken: boolean, failure?: string, refused?: boolean, externalId?: string,+ * collectionId?: string, updated?: boolean, live?: boolean, changed?: { images: number } }>}+ */+export async function sendToWix({ delivery, page, html, jsonLd = [], connection, request, base }) {+ const siteId = connection.site_id;+ const opts = { request, base };+ try {+ const credentials = await readCmsCredentials(connection.id);+ if (!credentials?.apiKey) {+ await markRefused(connection);+ return {+ taken: false,+ failure: 'The Wix API key can’t be read. Connect Wix again.',+ refused: true,+ };+ }+ const { apiKey } = credentials;+ const { html: body, images } = toWixHtml(html);+ const post = {+ title: page.title.slice(0, 200),+ richContent: await toRicos(siteId, apiKey, body, opts),+ memberId: connection.account,+ ...(page.metaDescription ? { excerpt: page.metaDescription.slice(0, EXCERPT_MAX) } : {}),+ ...(page.slug ? { seoSlug: page.slug.slice(0, SLUG_MAX) } : {}),+ seoData: { tags: seoTags(page, jsonLd) },+ };+ const last = await lastPost(page.draftId, siteId, delivery.id);+ const current = last ? await readDraftPost(siteId, apiKey, last.external_id, opts) : null;+ let written = null;+ if (current && current.status !== 'DELETED') {+ try {+ written = await updateDraftPost(siteId, apiKey, current.id, post, {+ ...opts,+ live: current.status === LIVE,+ });+ } catch (err) {+ if (!(err instanceof WixError && err.code === 'not_found')) throw err;+ }+ }+ const updated = Boolean(written);+ written ??= await createDraftPost(siteId, apiKey, post, opts);+ return {+ taken: true,+ // Wix's answer to an update may leave out the post's id: it's the one updated, still.+ externalId: written.id ?? current?.id,+ collectionId: siteId,+ updated,+ // A live post's draft was written: nothing new was made beside it.+ live: false,+ changed: { images },+ };+ } catch (err) {+ if (err instanceof WixError) {+ if (err.code === 'auth_failed') {+ await markRefused(connection);+ return { taken: false, failure: err.message, refused: true };+ }+ return { taken: false, failure: err.message };+ }+ logger.warn(+ { err: { name: err?.name }, deliveryId: delivery.id },+ '[content-delivery] wix send failed',+ );+ return { taken: false, failure: 'Wix could not be reached' };+ }+}diff --git a/server/src/lib/cms/wix-delivery.test.js b/server/src/lib/cms/wix-delivery.test.jsnew file mode 100644index 000000000..2d9797898--- /dev/null+++ b/server/src/lib/cms/wix-delivery.test.js@@ -0,0 +1,208 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Send to CMS to Wix (#1331, phase 2; 00372): a page goes to the brand's+ * site's Blog as a draft post, updates the post its last send made there,+ * and writes a live post's draft version, never the post people read.+ */++let previous;+const queries = [];+const updates = [];+vi.mock('../../config/supabase.js', () => ({+ default: {+ from: (table) => {+ const q = { table, filters: [] };+ const chain = {+ select: () => chain,+ eq: (col, value) => (q.filters.push(['eq', col, value]), chain),+ neq: (col, value) => (q.filters.push(['neq', col, value]), chain),+ not: (col, op, value) => (q.filters.push(['not', col, op, value]), chain),+ order: () => chain,+ limit: () => chain,+ update: (row) => (updates.push({ table, row, filters: q.filters }), chain),+ maybeSingle: async () => {+ queries.push(q);+ return { data: previous ? { id: 'd0', external_id: previous } : null, error: null };+ },+ then: (resolve) => resolve({ data: null, error: null }),+ };+ return chain;+ },+ },+}));+vi.mock('../logger.js', () => ({ logger: { warn: vi.fn() } }));+let credentials;+vi.mock('./credentials.js', () => ({ readCmsCredentials: async () => credentials }));+const wix = {+ createDraftPost: vi.fn(),+ readDraftPost: vi.fn(),+ updateDraftPost: vi.fn(),+ toRicos: vi.fn(),+};+vi.mock('./wix.js', async (importOriginal) => ({+ ...(await importOriginal()),+ createDraftPost: (...args) => wix.createDraftPost(...args),+ readDraftPost: (...args) => wix.readDraftPost(...args),+ updateDraftPost: (...args) => wix.updateDraftPost(...args),+ toRicos: (...args) => wix.toRicos(...args),+}));++const { seoTags, sendToWix, toWixHtml } = await import('./wix-delivery.js');+const { WixError } = await import('./wix.js');++const SITE = '2f8a1c3e-1111-4222-8333-944455556666';+const MEMBER = 'c00e8a5c-322b-4e77-8813-002e3ea7e811';+const POST = '9124f6ef-a537-4bdd-bca3-e7306947deeb';+const connection = {+ id: 'cn1',+ site_id: SITE,+ account: MEMBER,+ updated_at: '2026-10-28T09:00:00Z',+};+const HTML =+ '<h2>Why</h2><p>Smooth.</p><figure><img src="https://acme.example/a.png" alt="A"></figure><script type="application/ld+json">{"@type":"Article"}</script>';+const send = () =>+ sendToWix({+ delivery: { id: 'd2345678-0000-0000-0000-000000000000' },+ page: {+ draftId: 'dr1',+ title: 'Cold brew at home',+ slug: 'cold-brew-at-home',+ metaTitle: '',+ metaDescription: 'How to make it.',+ },+ html: HTML,+ jsonLd: [{ '@type': 'Article' }],+ connection,+ });++beforeEach(() => {+ previous = null;+ queries.length = 0;+ updates.length = 0;+ credentials = { apiKey: 'IST.fake-key' };+ for (const fn of Object.values(wix)) fn.mockReset();+ wix.toRicos.mockResolvedValue({ nodes: [{ type: 'PARAGRAPH' }] });+ wix.createDraftPost.mockResolvedValue({ id: POST, status: 'UNPUBLISHED', url: null });+ wix.updateDraftPost.mockResolvedValue({ id: POST, status: 'UNPUBLISHED', url: null });+});++describe('toWixHtml', () => {+ it('leaves its JSON-LD and images out, and counts the images', () => {+ expect(toWixHtml(HTML)).toEqual({ html: '<h2>Why</h2><p>Smooth.</p>', images: 1 });+ });+});++describe('seoTags', () => {+ it("gives the post its title, meta description and JSON-LD as Wix's SEO tags", () => {+ expect(+ seoTags({ title: 'T', metaTitle: 'Meta T', metaDescription: 'D' }, [{ '@type': 'Article' }]),+ ).toEqual([+ { type: 'title', children: 'Meta T', custom: false, disabled: false },+ {+ type: 'meta',+ props: { name: 'description', content: 'D' },+ custom: false,+ disabled: false,+ },+ {+ type: 'script',+ props: { type: 'application/ld+json' },+ children: '{"@type":"Article"}',+ custom: false,+ disabled: false,+ },+ ]);+ });++ it('escapes every "<" in the JSON-LD, so it can’t end the script it goes in', () => {+ const [tag] = seoTags({}, [{ '@type': 'Article', headline: 'Cold brew </script><b>x' }]);+ expect(tag.children).not.toContain('<');+ expect(tag.children).toContain('\\u003c/script>\\u003cb>x');+ expect(JSON.parse(tag.children).headline).toBe('Cold brew </script><b>x');+ });+});++describe('sendToWix', () => {+ it('writes a new draft post, owned by the member the connection keeps', async () => {+ expect(await send()).toEqual({+ taken: true,+ externalId: POST,+ collectionId: SITE,+ updated: false,+ live: false,+ changed: { images: 1 },+ });+ const [, , post] = wix.createDraftPost.mock.calls[0];+ expect(post).toMatchObject({+ title: 'Cold brew at home',+ memberId: MEMBER,+ excerpt: 'How to make it.',+ seoSlug: 'cold-brew-at-home',+ richContent: { nodes: [{ type: 'PARAGRAPH' }] },+ });+ // The page's last send on this site is looked for.+ expect(queries[0].filters).toEqual(+ expect.arrayContaining([+ ['eq', 'target', 'wix'],+ ['eq', 'target_collection', SITE],+ ]),+ );+ });++ it('updates the draft its last send made, and a live post as its draft version', async () => {+ previous = POST;+ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'UNPUBLISHED', url: null });+ expect(await send()).toMatchObject({ taken: true, updated: true });+ expect(wix.updateDraftPost.mock.calls[0][4]).toMatchObject({ live: false });++ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'PUBLISHED', url: null });+ expect(await send()).toMatchObject({ taken: true, updated: true, live: false });+ expect(wix.updateDraftPost.mock.calls[1][4]).toMatchObject({ live: true });+ expect(wix.createDraftPost).not.toHaveBeenCalled();+ });++ it('keeps the post’s id when Wix’s answer to the update leaves it out', async () => {+ previous = POST;+ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'UNPUBLISHED', url: null });+ wix.updateDraftPost.mockResolvedValue({ id: null, status: null, url: null });+ // Kept on the delivery, the page's next send updates this post rather than making a second.+ expect(await send()).toMatchObject({ taken: true, updated: true, externalId: POST });+ expect(wix.createDraftPost).not.toHaveBeenCalled();+ });++ it('writes a scheduled post as a draft, not as a live post’s draft version', async () => {+ previous = POST;+ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'SCHEDULED', url: null });+ expect(await send()).toMatchObject({ taken: true, updated: true });+ expect(wix.updateDraftPost.mock.calls[0][4]).toMatchObject({ live: false });+ });++ it('writes a new post when the last one was deleted or is gone', async () => {+ previous = POST;+ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'DELETED', url: null });+ expect(await send()).toMatchObject({ taken: true, updated: false });+ wix.readDraftPost.mockResolvedValue({ id: POST, status: 'UNPUBLISHED', url: null });+ wix.updateDraftPost.mockRejectedValue(new WixError('not_found', 'gone', 404));+ expect(await send()).toMatchObject({ taken: true, updated: false });+ expect(wix.createDraftPost).toHaveBeenCalledTimes(2);+ });++ it('marks the connection refused when Wix refuses the key, or it can’t be read', async () => {+ wix.createDraftPost.mockRejectedValue(new WixError('auth_failed', 'Wix refused the API key.'));+ expect(await send()).toEqual({+ taken: false,+ failure: 'Wix refused the API key.',+ refused: true,+ });+ credentials = null;+ expect(await send()).toMatchObject({ taken: false, refused: true });+ expect(updates.map((u) => u.row.status)).toEqual(['auth_failed', 'auth_failed']);+ });++ it('says Wix couldn’t be reached for anything else', async () => {+ wix.toRicos.mockRejectedValue(new Error('socket hang up'));+ expect(await send()).toEqual({ taken: false, failure: 'Wix could not be reached' });+ });+});diff --git a/server/src/lib/cms/wix.js b/server/src/lib/cms/wix.jsnew file mode 100644index 000000000..603c6ccb8--- /dev/null+++ b/server/src/lib/cms/wix.js@@ -0,0 +1,365 @@+import * as cheerio from 'cheerio';+import { ConnectorHttpError, requestJson } from '../../connectors/http.js';++/**+ * Wix for Send to CMS (#1331, phase 2; 00372): a site's Blog through Wix's+ * REST API, with an API key the site's owner made in Wix's API Keys Manager+ * (the Wix Blog permissions), sent as `Authorization: <key>` beside+ * `wix-site-id: <site id>`.+ *+ * Every call goes through the connectors' HTTP client (connectors/http.js):+ * https only, no redirect followed, and a POST never sent twice. Pages go as+ * draft posts: nothing here publishes. A page's HTML becomes Wix's rich+ * content (Ricos) through Wix's own converter, in pieces it takes at once.+ *+ * The key is never put in a message, a log or an answer.+ */++/** Wix's REST API; tests reach a fake of it. */+export const WIX_API = 'https://www.wixapis.com';++export class WixError extends Error {+ /**+ * @param {'invalid'|'auth_failed'|'no_access'|'no_ricos_permission'|'no_blog'|'no_member'|+ * 'not_found'|'unreachable'|'failed'} code+ * 'auth_failed': the key is refused (the person connects again);+ * 'no_ricos_permission': the key may write the Blog, not use Wix's converter+ * @param {string} message+ * @param {number} [status] the HTTP status Wix answered, when it did+ */+ constructor(code, message, status) {+ super(message);+ this.name = 'WixError';+ this.code = code;+ this.status = status;+ }+}++const GUID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;++/**+ * The site's id as the person gave it: the id itself, or the address of its+ * dashboard (manage.wix.com/dashboard/<site id>/…), where Wix shows it.+ */+export function siteIdOf(input) {+ const match = String(input ?? '')+ .trim()+ .match(GUID);+ if (!match) {+ throw new WixError(+ 'invalid',+ 'That isn’t a Wix site id. Copy it from the address of the site’s dashboard.',+ );+ }+ return match[0].toLowerCase();+}++/** Wix's answer to a call that failed, in our words. */+function wixError(err) {+ if (err instanceof WixError) return err;+ if (!(err instanceof ConnectorHttpError)) return err;+ const { status } = err;+ switch (err.code) {+ case 'auth':+ return status === 403+ ? new WixError(+ 'no_access',+ 'The API key isn’t allowed to do that. Give it the Wix Blog permissions in the API Keys Manager.',+ status,+ )+ : new WixError('auth_failed', 'Wix refused the API key.', status);+ case 'timeout':+ case 'unreachable':+ case 'invalid_url':+ case 'blocked':+ return new WixError('unreachable', 'Wix couldn’t be reached.');+ case 'rate_limited':+ return new WixError('unreachable', 'Wix asked to wait. Try again later.', status);+ case 'http_error':+ if (status === 404) return new WixError('not_found', 'Wix has no such post.', status);+ return new WixError('failed', `Wix answered ${status}.`, status);+ default:+ return new WixError('failed', 'Wix didn’t answer as expected.', status);+ }+}++/**+ * One call to Wix's API for the site. `request` replaces the HTTP client and+ * `base` Wix's address in tests (connectors/testing.js).+ */+async function call(path, { siteId, apiKey, method = 'GET', query, body, request, base }) {+ try {+ const { data } = await (request ?? requestJson)(`${base ?? WIX_API}${path}`, {+ method,+ headers: { authorization: apiKey, 'wix-site-id': siteId },+ query,+ body,+ });+ return data;+ } catch (err) {+ throw wixError(err);+ }+}++/**+ * Checks a site and its key before they're kept: the key opens the site's+ * Blog, it may use Wix's converter (a page is sent through it: tried on a+ * line of text, which Wix doesn't keep), and a member can own the posts it+ * writes (Wix's Blog needs one): the owner of its newest post, else its+ * first member. The site's name when the key may read it.+ *+ * @returns {Promise<{ siteName: string|null, memberId: string }>}+ */+export async function checkSite(siteId, apiKey, { request, base } = {}) {+ const opts = { siteId, apiKey, request, base };+ let posts;+ try {+ posts = await call('/blog/v3/posts', { ...opts, query: { 'paging.limit': 1 } });+ } catch (err) {+ if (err instanceof WixError && err.code === 'not_found') {+ throw new WixError(+ 'no_blog',+ 'This site has no Wix Blog. Add the Blog to the site first.',+ err.status,+ );+ }+ throw err;+ }+ await toRicos(siteId, apiKey, '<p>x</p>', { request, base });+ let memberId = posts?.posts?.[0]?.memberId ?? null;+ if (!memberId) {+ const members = await call('/members/v1/members/query', {+ ...opts,+ method: 'POST',+ body: { query: { paging: { limit: 1 } } },+ }).catch(() => null);+ memberId = members?.members?.[0]?.id ?? null;+ }+ if (typeof memberId !== 'string' || !GUID.test(memberId)) {+ throw new WixError(+ 'no_member',+ 'Wix needs a site member to own the posts. Write one post on the Blog as the site’s owner, then connect again.',+ );+ }+ const properties = await call('/site-properties/v4/properties', opts).catch(() => null);+ const name = properties?.properties?.siteDisplayName;+ return {+ siteName: typeof name === 'string' && name.trim() ? name.trim().slice(0, 300) : null,+ memberId,+ };+}++/** The most Wix's converter is sent at once: its limit is 30,000 characters. */+export const RICOS_CHUNK = 29_000;+/** What the converter keeps of a page beside paragraphs, lists and text styles. */+const RICOS_PLUGINS = ['HEADING', 'LINK', 'TABLE', 'CODE_BLOCK', 'DIVIDER'];++const escapeText = (text) =>+ text.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');++/** Pieces joined, in order, as many as fit in `limit` characters at a time. */+function pack(pieces, limit) {+ const packed = [];+ let current = '';+ for (const piece of pieces) {+ if (current && current.length + piece.length > limit) {+ packed.push(current);+ current = '';+ }+ current += piece;+ }+ if (current) packed.push(current);+ return packed;+}++/**+ * Text, escaped, in pieces of at most `limit` characters, cut between+ * words. Only a word longer than that on its own is cut: an escaped+ * character takes up to five, so its parts are a fifth of the limit.+ */+function textPieces(text, limit) {+ const parts = [];+ for (const word of text.match(/\S+\s*|\s+/g) ?? []) {+ let rest = word;+ while (rest) {+ const part =+ escapeText(rest).length <= limit ? rest : rest.slice(0, Math.max(1, Math.floor(limit / 5)));+ parts.push(escapeText(part));+ rest = rest.slice(part.length);+ }+ }+ return pack(parts, limit);+}++/**+ * A node's HTML in pieces of at most `limit` characters, each one whole. A+ * node longer than that is split among its children, each piece in a copy+ * of its tag (a list's items in lists, a table's rows in tables, a+ * paragraph's text in paragraphs, between words). One with nothing to split+ * it by goes as its text, in paragraphs.+ */+function nodePieces($, node, limit) {+ const outer = $.html(node);+ if (outer.length <= limit) return [outer];+ if (node.type === 'text') return textPieces(node.data, limit);+ if (node.type === 'tag' && node.children?.length) {+ const empty = $.html($(node).clone().empty());+ const close = `</${node.name}>`;+ const room = limit - empty.length;+ // A tag that takes up half the room isn't worth copying.+ if (empty.endsWith(close) && room >= limit / 2) {+ const open = empty.slice(0, -close.length);+ const inner = node.children.flatMap((child) => nodePieces($, child, room));+ return pack(inner, room).map((html) => `${open}${html}${close}`);+ }+ }+ const text = $(node).text().replace(/\s+/g, ' ').trim();+ return textPieces(text, limit - '<p></p>'.length).map((piece) => `<p>${piece}</p>`);+}++/**+ * The page's top-level blocks in pieces of at most RICOS_CHUNK characters,+ * in order. A block longer than that on its own is split among its children+ * (nodePieces).+ */+export function ricosChunks(html, limit = RICOS_CHUNK) {+ const $ = cheerio.load(html, null, false);+ const blocks = [];+ for (const node of $.root().contents().toArray()) {+ if (!$.html(node).trim()) continue;+ blocks.push(...nodePieces($, node, limit));+ }+ return pack(blocks, limit);+}++/**+ * The page's HTML as Wix's rich content: its pieces converted one after+ * another, joined. A key refused there has the Blog's permissions, not the+ * converter's (Manage Ricos Document).+ */+export async function toRicos(siteId, apiKey, html, { request, base } = {}) {+ const nodes = [];+ for (const chunk of ricosChunks(html)) {+ const data = await call('/ricos/v1/ricos-document/convert/to-ricos', {+ siteId,+ apiKey,+ method: 'POST',+ body: { html: chunk, options: { plugins: RICOS_PLUGINS } },+ request,+ base,+ }).catch((err) => {+ if (err instanceof WixError && err.code === 'no_access') {+ throw new WixError(+ 'no_ricos_permission',+ 'The API key needs the Ricos permission (Manage Ricos Document) too. Add it to the key in Wix’s API Keys Manager, then try again.',+ err.status,+ );+ }+ throw err;+ });+ if (!Array.isArray(data?.document?.nodes)) {+ throw new WixError('failed', 'Wix couldn’t read the page’s text.');+ }+ nodes.push(...data.document.nodes);+ }+ return { nodes };+}++/**+ * A post's address, whole: Wix may give it without its scheme+ * (mysite.wixsite.com/mysite/post/x), so it gets https://. Null when it+ * isn't a web address.+ */+export function webAddress(url) {+ const value = typeof url === 'string' ? url.trim() : '';+ if (/^https?:\/\//i.test(value)) return value;+ if (value.startsWith('//')) return `https:${value}`;+ // A host first: example.com/…, mysite.wixsite.com/…+ if (/^[a-z0-9-]+(\.[a-z0-9-]+)+(:\d+)?([/?#]|$)/i.test(value)) return `https://${value}`;+ return null;+}++/** A draft post as Send to CMS keeps it. */+function draftOf(data) {+ const post = data?.draftPost ?? {};+ const url = webAddress(+ typeof post.url === 'string'+ ? post.url+ : post.url?.base && post.url?.path+ ? `${post.url.base.replace(/\/$/, '')}${post.url.path}`+ : null,+ );+ return {+ id: typeof post.id === 'string' ? post.id : null,+ status: typeof post.status === 'string' ? post.status : null,+ url,+ };+}++const postPath = (id) => (GUID.test(String(id)) ? String(id).match(GUID)[0] : null);++/**+ * A new draft post.+ * @param {{ title: string, richContent: object, memberId: string, excerpt?: string,+ * seoSlug?: string, seoData?: object }} post+ */+export async function createDraftPost(siteId, apiKey, post, { request, base } = {}) {+ const created = draftOf(+ await call('/blog/v3/draft-posts', {+ siteId,+ apiKey,+ method: 'POST',+ body: { draftPost: post, publish: false, fieldsets: ['URL'] },+ request,+ base,+ }),+ );+ if (!created.id) throw new WixError('failed', 'Wix didn’t say which post it made.');+ return created;+}++/** A draft post as it stands, or null when it's gone. */+export async function readDraftPost(siteId, apiKey, id, { request, base } = {}) {+ const path = postPath(id);+ if (!path) return null;+ try {+ return draftOf(+ await call(`/blog/v3/draft-posts/${path}`, {+ siteId,+ apiKey,+ query: { fieldsets: 'URL' },+ request,+ base,+ }),+ );+ } catch (err) {+ if (err instanceof WixError && err.code === 'not_found') return null;+ throw err;+ }+}++/**+ * Writes a draft post. A published one is written as its draft version+ * (UPDATE_PUBLICATION): the post people read stays as it was until the+ * person publishes the changes in Wix.+ */+export async function updateDraftPost(+ siteId,+ apiKey,+ id,+ post,+ { live = false, request, base } = {},+) {+ const path = postPath(id);+ if (!path) throw new WixError('not_found', 'Wix has no such post.');+ return draftOf(+ await call(`/blog/v3/draft-posts/${path}`, {+ siteId,+ apiKey,+ method: 'PATCH',+ body: { draftPost: { ...post, id: path }, action: live ? 'UPDATE_PUBLICATION' : 'UPDATE' },+ request,+ base,+ }),+ );+}diff --git a/server/src/lib/cms/wix.test.js b/server/src/lib/cms/wix.test.jsnew file mode 100644index 000000000..7ccb3211c--- /dev/null+++ b/server/src/lib/cms/wix.test.js@@ -0,0 +1,291 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++// The harness reaches the Supabase admin client at import time.+vi.mock('../../config/supabase.js', () => ({ default: {} }));++const { startFakeApi } = await import('../../connectors/testing.js');+const {+ RICOS_CHUNK,+ WixError,+ checkSite,+ createDraftPost,+ readDraftPost,+ ricosChunks,+ siteIdOf,+ toRicos,+ updateDraftPost,+ webAddress,+} = await import('./wix.js');++/**+ * Wix's REST API for Send to CMS (#1331, phase 2; 00372): a site checked+ * before its key is kept, a page's HTML turned into Wix's rich content, and+ * draft posts written, against a fake of the API (its answers as Wix's+ * reference shows them). Real keys are tried by the maintainer.+ */++const SITE = '2f8a1c3e-1111-4222-8333-944455556666';+const KEY = 'IST.eyJraWQiOiJQb3pIX2FDMiIsImFsZyI6IlJTMjU2In0.fake-key';+const MEMBER = 'c00e8a5c-322b-4e77-8813-002e3ea7e811';+const POST = '9124f6ef-a537-4bdd-bca3-e7306947deeb';++let api;+afterEach(() => api?.close());++const start = async (routes) => {+ api = await startFakeApi(routes);+ return { base: api.origin, request: api.request };+};++const CONVERT = 'POST /ricos/v1/ricos-document/convert/to-ricos';+const converts = () => ({ json: { document: { nodes: [{ type: 'PARAGRAPH' }] } } });++describe('siteIdOf', () => {+ it("reads the site's id, or the dashboard address it is in", () => {+ expect(siteIdOf(SITE.toUpperCase())).toBe(SITE);+ expect(siteIdOf(`https://manage.wix.com/dashboard/${SITE}/home`)).toBe(SITE);+ });++ it('refuses what has no id', () => {+ expect(() => siteIdOf('my-site.wixsite.com')).toThrow(WixError);+ });+});++describe('checkSite', () => {+ it("checks the Blog and the converter with the key, and takes its newest post's owner and the site's name", async () => {+ const opts = await start({+ 'GET /blog/v3/posts': () => ({ json: { posts: [{ id: POST, memberId: MEMBER }] } }),+ [CONVERT]: converts,+ 'GET /site-properties/v4/properties': () => ({+ json: { properties: { siteDisplayName: ' Acme Coffee ' } },+ }),+ });++ expect(await checkSite(SITE, KEY, opts)).toEqual({ siteName: 'Acme Coffee', memberId: MEMBER });+ const [first] = api.calls;+ // The key goes as Wix takes it, beside the site's id; never anywhere else.+ expect(first.headers.authorization).toBe(KEY);+ expect(first.headers['wix-site-id']).toBe(SITE);+ expect(first.query).toEqual({ 'paging.limit': '1' });+ // The converter is tried on a line of text: nothing is written to the site.+ expect(api.calls[1]).toMatchObject({+ method: 'POST',+ path: '/ricos/v1/ricos-document/convert/to-ricos',+ body: { html: '<p>x</p>' },+ });+ });++ it('takes a member when the Blog has no post yet, and goes without a name it may not read', async () => {+ const opts = await start({+ 'GET /blog/v3/posts': () => ({ json: { posts: [] } }),+ [CONVERT]: converts,+ 'POST /members/v1/members/query': () => ({ json: { members: [{ id: MEMBER }] } }),+ 'GET /site-properties/v4/properties': () => ({ status: 403, json: {} }),+ });+ expect(await checkSite(SITE, KEY, opts)).toEqual({ siteName: null, memberId: MEMBER });+ });++ it('says what stops it: a refused key, a site with no Blog, no member to own the posts', async () => {+ let opts = await start({ 'GET /blog/v3/posts': () => ({ status: 401, json: {} }) });+ await expect(checkSite(SITE, KEY, opts)).rejects.toMatchObject({ code: 'auth_failed' });+ api.close();++ opts = await start({ 'GET /blog/v3/posts': () => ({ status: 404, json: {} }) });+ await expect(checkSite(SITE, KEY, opts)).rejects.toMatchObject({ code: 'no_blog' });+ api.close();++ opts = await start({+ 'GET /blog/v3/posts': () => ({ json: { posts: [] } }),+ [CONVERT]: converts,+ 'POST /members/v1/members/query': () => ({ json: { members: [] } }),+ });+ await expect(checkSite(SITE, KEY, opts)).rejects.toMatchObject({ code: 'no_member' });+ });++ it('says the key needs the Ricos permission when the converter refuses it', async () => {+ const opts = await start({+ 'GET /blog/v3/posts': () => ({ json: { posts: [{ id: POST, memberId: MEMBER }] } }),+ [CONVERT]: () => ({ status: 403, json: { message: 'PERMISSION_DENIED' } }),+ });+ await expect(checkSite(SITE, KEY, opts)).rejects.toMatchObject({+ code: 'no_ricos_permission',+ message: expect.stringContaining('Manage Ricos Document'),+ });+ // Refused there, nothing else is asked.+ expect(api.calls.map((call) => call.path)).toEqual([+ '/blog/v3/posts',+ '/ricos/v1/ricos-document/convert/to-ricos',+ ]);+ });+});++describe('ricosChunks', () => {+ it('keeps the blocks in order, in pieces within Wix’s 30,000 characters', () => {+ expect(RICOS_CHUNK).toBeLessThan(30_000);+ const block = `<p>${'a'.repeat(12_000)}</p>`;+ const chunks = ricosChunks(`${block}${block}${block}<h2>End</h2>`);+ expect(chunks).toHaveLength(2);+ expect(chunks.every((chunk) => chunk.length <= RICOS_CHUNK)).toBe(true);+ expect(chunks[1].endsWith('<h2>End</h2>')).toBe(true);+ });++ it('splits a block longer than that among its children, in copies of its tag', () => {+ const items = Array.from({ length: 40 }, (_, i) => `<li>Item ${i}: smooth and sweet</li>`);+ const chunks = ricosChunks(`<ul class="steps">${items.join('')}</ul>`, 500);+ expect(chunks.length).toBeGreaterThan(1);+ for (const chunk of chunks) {+ expect(chunk.length).toBeLessThanOrEqual(500);+ expect(chunk).toMatch(/^<ul class="steps">(<li>Item \d+: smooth and sweet<\/li>)+<\/ul>$/);+ }+ // Every item, once, in order.+ expect(chunks.join('').match(/Item \d+/g)).toEqual(items.map((_, i) => `Item ${i}`));++ const rows = `<tr><td>${'x < y & '.repeat(300)}</td></tr>`;+ const tables = ricosChunks(`<table><tbody>${rows}</tbody></table>`, 1000);+ expect(tables.every((chunk) => chunk.length <= 1000)).toBe(true);+ expect(tables.every((chunk) => chunk.startsWith('<table><tbody><tr><td>'))).toBe(true);+ expect(tables.join('')).toContain('x < y &');+ });++ it('cuts a long paragraph between words, keeping its links', () => {+ const text = 'Cold brew steeps slowly overnight. '.repeat(60);+ const chunks = ricosChunks(+ `<p>See <a href="https://acme.example">the guide</a>. ${text}</p>`,+ 600,+ );+ expect(chunks.every((chunk) => chunk.length <= 600)).toBe(true);+ expect(chunks.every((chunk) => chunk.startsWith('<p>') && chunk.endsWith('</p>'))).toBe(true);+ expect(chunks.join('')).toContain('<a href="https://acme.example">the guide</a>');+ // The words of the paragraph's text after the link, each whole.+ const words = new Set(`. ${text}`.trim().split(/\s+/));+ for (const chunk of chunks.slice(1)) {+ for (const word of chunk+ .replace(/<[^>]+>/g, '')+ .trim()+ .split(/\s+/)) {+ expect(words.has(word)).toBe(true);+ }+ }+ });++ it('sends a block with nothing to split it by as its text, escaped, between words', () => {+ const chunks = ricosChunks(+ `<p title="${'t'.repeat(600)}">${'fish & chips '.repeat(200)}</p>`,+ 1000,+ );+ expect(chunks.length).toBeGreaterThan(1);+ expect(chunks.every((chunk) => chunk.length <= 1000)).toBe(true);+ expect(chunks.join('')).not.toContain('title=');+ for (const chunk of chunks) {+ expect(chunk).toMatch(/^<p>((fish|&|chips) ?)+<\/p>$/);+ }+ });+});++describe('toRicos', () => {+ it("joins each piece's nodes, as Wix's converter gives them", async () => {+ let n = 0;+ const opts = await start({+ 'POST /ricos/v1/ricos-document/convert/to-ricos': (req) => ({+ json: {+ document: {+ nodes: [{ type: 'PARAGRAPH', id: `n${(n += 1)}`, html: req.body.html.length }],+ },+ },+ }),+ });+ const block = `<p>${'a'.repeat(15_000)}</p>`;+ const doc = await toRicos(SITE, KEY, `${block}${block}`, opts);+ expect(doc.nodes.map((node) => node.id)).toEqual(['n1', 'n2']);+ expect(api.calls[0].body.options.plugins).toContain('HEADING');+ });+});++describe('webAddress', () => {+ it('keeps a web address, adds https:// to one without its scheme, and drops the rest', () => {+ expect(webAddress('https://acme.example/post/x')).toBe('https://acme.example/post/x');+ expect(webAddress(' acme.example/post/x ')).toBe('https://acme.example/post/x');+ expect(webAddress('//acme.example/post/x')).toBe('https://acme.example/post/x');+ expect(webAddress('/post/x')).toBeNull();+ expect(webAddress('javascript:alert(1)')).toBeNull();+ expect(webAddress(null)).toBeNull();+ });+});++describe('draft posts', () => {+ it('writes a new draft, never published', async () => {+ const opts = await start({+ 'POST /blog/v3/draft-posts': () => ({+ json: {+ draftPost: { id: POST, status: 'UNPUBLISHED', url: 'https://acme.example/post/x' },+ },+ }),+ });+ const post = { title: 'T', richContent: { nodes: [] }, memberId: MEMBER };+ expect(await createDraftPost(SITE, KEY, post, opts)).toEqual({+ id: POST,+ status: 'UNPUBLISHED',+ url: 'https://acme.example/post/x',+ });+ expect(api.calls[0].body).toEqual({ draftPost: post, publish: false, fieldsets: ['URL'] });+ });++ it("reads a draft, null once it's gone", async () => {+ const opts = await start({+ [`GET /blog/v3/draft-posts/${POST}`]: () => ({+ json: {+ draftPost: {+ id: POST,+ status: 'PUBLISHED',+ url: { base: 'https://acme.example/', path: '/post/x' },+ },+ },+ }),+ });+ expect(await readDraftPost(SITE, KEY, POST, opts)).toEqual({+ id: POST,+ status: 'PUBLISHED',+ url: 'https://acme.example/post/x',+ });+ expect(await readDraftPost(SITE, KEY, 'f0000000-0000-4000-8000-000000000000', opts)).toBeNull();+ expect(await readDraftPost(SITE, KEY, 'not-an-id', opts)).toBeNull();+ });++ it('gives an address Wix sends without its scheme https://', async () => {+ const OTHER = 'a1111111-2222-4333-8444-955555555555';+ const opts = await start({+ [`GET /blog/v3/draft-posts/${POST}`]: () => ({+ json: {+ draftPost: { id: POST, status: 'PUBLISHED', url: 'mysite.wixsite.com/mysite/post/x' },+ },+ }),+ [`GET /blog/v3/draft-posts/${OTHER}`]: () => ({+ json: {+ draftPost: {+ id: OTHER,+ status: 'PUBLISHED',+ url: { base: 'mysite.wixsite.com/mysite/', path: '/post/y' },+ },+ },+ }),+ });+ expect((await readDraftPost(SITE, KEY, POST, opts)).url).toBe(+ 'https://mysite.wixsite.com/mysite/post/x',+ );+ expect((await readDraftPost(SITE, KEY, OTHER, opts)).url).toBe(+ 'https://mysite.wixsite.com/mysite/post/y',+ );+ });++ it("writes a live post's draft version, never the post people read", async () => {+ const opts = await start({+ [`PATCH /blog/v3/draft-posts/${POST}`]: () => ({+ json: { draftPost: { id: POST, status: 'PUBLISHED' } },+ }),+ });+ await updateDraftPost(SITE, KEY, POST, { title: 'T' }, opts);+ await updateDraftPost(SITE, KEY, POST, { title: 'T' }, { ...opts, live: true });+ expect(api.calls.map((call) => call.body.action)).toEqual(['UPDATE', 'UPDATE_PUBLICATION']);+ expect(api.calls[0].body.draftPost).toEqual({ title: 'T', id: POST });+ });+});diff --git a/server/src/lib/content-delivery.js b/server/src/lib/content-delivery.jsindex 147eab4f4..f1ee340bd 100644--- a/server/src/lib/content-delivery.js+++ b/server/src/lib/content-delivery.js@@ -11,6 +11,7 @@ import { credentialsConfigured } from './catalog/credentials.js';import { sendToWebflow } from './cms/webflow-delivery.js';import { sendToWordPress } from './cms/wordpress-delivery.js';import { sendToFramer } from './cms/framer-delivery.js';+import { sendToWix } from './cms/wix-delivery.js';/*** Send to CMS, phase 1 (#1331): an admin or manager sends Content Editor@@ -29,8 +30,9 @@ import { sendToFramer } from './cms/framer-delivery.js';** Phase 2: a page can go to the brand's Webflow collection instead (00283,* cms/webflow-delivery.js), as a draft item, to its WordPress site (00294,- * cms/wordpress-delivery.js), as a draft post, or to its Framer collection- * (00295, cms/framer-delivery.js), as a draft item, under the same cap,+ * cms/wordpress-delivery.js), as a draft post, to its Framer collection+ * (00295, cms/framer-delivery.js), as a draft item, or to its Wix site's+ * Blog (00372, cms/wix-delivery.js), as a draft post, under the same cap,* batches and delivery rows; a delivery says where it went (`target`).*/@@ -67,9 +69,9 @@ export const deliveryPage = z.object({/*** Where pages go: the brand's webhook (phase 1), its Webflow collection, its- * WordPress site or its Framer collection (phase 2).+ * WordPress site, its Framer collection or its Wix site's Blog (phase 2).*/-const DELIVERY_TARGETS = ['webhook', 'webflow', 'wordpress', 'framer'];+const DELIVERY_TARGETS = ['webhook', 'webflow', 'wordpress', 'framer', 'wix'];export const sendInput = z.object({// guid, not uuid: brand ids aren't all RFC 4122 versions (seeded ones).@@ -84,7 +86,8 @@ export class DeliveryError extends Error {* @param {'no_webhook'|'webhook_not_subscribed'|'webflow_not_configured'|'no_webflow'|* 'webflow_refused'|'webflow_not_ready'|'wordpress_not_configured'|'no_wordpress'|* 'wordpress_refused'|'framer_not_configured'|'no_framer'|'framer_refused'|- * 'framer_not_ready'|'in_progress'|'not_found'|'daily_limit'} code+ * 'framer_not_ready'|'wix_not_configured'|'no_wix'|'wix_refused'|'in_progress'|+ * 'not_found'|'daily_limit'} code*/constructor(code, message, status) {super(message);@@ -334,11 +337,37 @@ async function framerFor(brandId) {return data;}+/** The brand's Wix connection, its API key kept by the API (00372). */+async function wixFor(brandId) {+ if (!credentialsConfigured()) {+ throw new DeliveryError('wix_not_configured', 'Wix is not set up on this server.', 503);+ }+ const { data, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select('id, brand_id, status, site_id, account, updated_at')+ .eq('brand_id', brandId)+ .eq('provider', 'wix')+ .maybeSingle();+ if (error) throw new Error(error.message);+ if (!data) {+ throw new DeliveryError('no_wix', 'Connect Wix in Settings › Integrations.', 409);+ }+ if (data.status === 'auth_failed') {+ throw new DeliveryError(+ 'wix_refused',+ 'Wix refused the API key. Connect it again in Settings › Integrations.',+ 409,+ );+ }+ return data;+}+/** A CMS a page goes to itself, not through the webhook: its connection, and how a page is sent. */const NATIVE = {webflow: { label: 'Webflow', connect: webflowFor, send: sendToWebflow },wordpress: { label: 'WordPress', connect: wordpressFor, send: sendToWordPress },framer: { label: 'Framer', connect: framerFor, send: sendToFramer },+ wix: { label: 'Wix', connect: wixFor, send: sendToWix },};async function brandFor(brandId) {diff --git a/server/src/lib/content-delivery.test.js b/server/src/lib/content-delivery.test.jsindex e85b17065..d8cb6a0d2 100644--- a/server/src/lib/content-delivery.test.js+++ b/server/src/lib/content-delivery.test.js@@ -17,11 +17,13 @@ const db = {webflow: null,webflowConfigured: true,// Its WordPress connection (00294), and whether this server can keep its sign-in- // (Framer's key too: one CONNECTOR_CREDENTIALS_KEY).+ // (Framer's and Wix's API keys too: one CONNECTOR_CREDENTIALS_KEY).wordpress: null,wordpressConfigured: true,// Its Framer connection (00295).framer: null,+ // Its Wix connection (00372).+ wix: null,queued: [],updates: [],rpc: [],@@ -56,7 +58,7 @@ function from(table) {if (table === 'webhook_configs') return { data: db.configs, error: null };if (table === 'brand_cms_connections') {const provider = q.filters.find(([op, col]) => op === 'eq' && col === 'provider')?.[2];- const connection = { wordpress: db.wordpress, framer: db.framer }[provider];+ const connection = { wordpress: db.wordpress, framer: db.framer, wix: db.wix }[provider];return { data: connection === undefined ? db.webflow : connection, error: null };}if (table === 'brands') {@@ -113,6 +115,8 @@ const sendToFramer = vi.fn();vi.mock('./cms/framer-delivery.js', () => ({sendToFramer: (...args) => sendToFramer(...args),}));+const sendToWix = vi.fn();+vi.mock('./cms/wix-delivery.js', () => ({ sendToWix: (...args) => sendToWix(...args) }));const { DAILY_DELIVERIES, DeliveryError, PAUSE_MS, cleanPublishHtml, sendContentPages, signBody } =await import('./content-delivery.js');@@ -167,11 +171,13 @@ beforeEach(() => {db.wordpress = null;db.wordpressConfigured = true;db.framer = null;+ db.wix = null;db.rpcError = null;postJson.mockReset().mockResolvedValue({ status: 200, answer: '{"ok":true}' });sendToWebflow.mockReset();sendToWordPress.mockReset();sendToFramer.mockReset();+ sendToWix.mockReset();});afterEach(() => {@@ -868,3 +874,98 @@ describe('sendContentPages to Framer (phase 2, 00295)', () => {expect(closed).toHaveLength(2);});});++describe('sendContentPages to Wix (phase 2, 00372)', () => {+ const connection = {+ id: 'cn1',+ brand_id: 'b1',+ status: 'connected',+ site_id: '2f8a1c3e-1111-4222-8333-944455556666',+ account: 'c00e8a5c-322b-4e77-8813-002e3ea7e811',+ updated_at: '2026-10-28T09:00:00Z',+ };+ const toWix = (pages = [page()]) =>+ sendContentPages({ orgId: 'o1', brandId: 'b1', userId: 'u1', pages, target: 'wix' });++ it('sends a page to the brand’s site, not its webhooks, and keeps the post on the delivery', async () => {+ db.wix = connection;+ sendToWix.mockResolvedValue({+ taken: true,+ externalId: '9124f6ef-a537-4bdd-bca3-e7306947deeb',+ collectionId: connection.site_id,+ updated: false,+ live: false,+ changed: { images: 0 },+ });+ const sent = await toWix();+ expect(db.rpc[0].args.p_target).toBe('wix');+ expect(postJson).not.toHaveBeenCalled();+ expect(sendToWebflow).not.toHaveBeenCalled();+ expect(sendToWordPress).not.toHaveBeenCalled();+ expect(sendToWix).toHaveBeenCalledWith(+ expect.objectContaining({+ connection,+ html: '<h2>Why</h2><p>Because.</p>',+ page: expect.objectContaining({ draftId: page().draftId, slug: 'best-aeo-tools' }),+ }),+ );+ const write = db.updates.find((u) => u.table === 'content_draft_deliveries');+ expect(write.update).toMatchObject({+ status: 'sent',+ external_id: '9124f6ef-a537-4bdd-bca3-e7306947deeb',+ target_collection: connection.site_id,+ });+ expect(sent.deliveries[0]).toMatchObject({ status: 'sent', updated: false });+ });++ it('refuses before reserving when Wix isn’t connected or set up', async () => {+ db.wordpressConfigured = false;+ await expect(toWix()).rejects.toMatchObject({ code: 'wix_not_configured', status: 503 });+ db.wordpressConfigured = true;+ await expect(toWix()).rejects.toMatchObject({ code: 'no_wix', status: 409 });+ db.wix = { ...connection, status: 'auth_failed' };+ await expect(toWix()).rejects.toMatchObject({ code: 'wix_refused', status: 409 });+ // A WordPress connection isn't a Wix one.+ db.wix = null;+ db.wordpress = {+ id: 'cn2',+ brand_id: 'b1',+ status: 'connected',+ site_url: 'https://b.example',+ };+ await expect(toWix()).rejects.toMatchObject({ code: 'no_wix' });+ expect(db.rpc).toEqual([]);+ expect(sendToWix).not.toHaveBeenCalled();+ });++ it('refuses a page already on its way to Wix, naming it', async () => {+ db.wix = connection;+ db.rpcError = { message: 'delivery_in_progress' };+ await expect(toWix()).rejects.toMatchObject({+ code: 'in_progress',+ message: 'A page is already being sent to Wix. Wait for it, then send again.',+ });+ expect(sendToWix).not.toHaveBeenCalled();+ });++ it('stops a batch once Wix refuses the API key, closing the rest with the reason', async () => {+ vi.useFakeTimers();+ db.wix = connection;+ const second = page({ draftId: 'c0ffee00-0000-4000-8000-000000000002', slug: 'second' });+ db.drafts = [draft(page().draftId), draft(second.draftId)];+ db.queued = [row(page().draftId), row(second.draftId)];+ sendToWix.mockResolvedValue({+ taken: false,+ failure: 'Wix refused the API key.',+ refused: true,+ });+ await toWix([page(), second]);+ await vi.runAllTimersAsync();+ expect(sendToWix).toHaveBeenCalledTimes(1);+ const closed = db.updates.filter(+ (u) =>+ u.table === 'content_draft_deliveries' && u.update.error === 'Wix refused the API key.',+ );+ expect(closed).toHaveLength(2);+ });+});diff --git a/server/src/middleware/demo-brand.js b/server/src/middleware/demo-brand.jsindex 144e4723b..9fa313a78 100644--- a/server/src/middleware/demo-brand.js+++ b/server/src/middleware/demo-brand.js@@ -116,13 +116,15 @@ export const DEMO_GUARDED = [guard('PUT /cms/brands/:brandId/webflow', brandIn('path')),guard('DELETE /cms/brands/:brandId/webflow', brandIn('path')),- // WordPress and Framer (cms-wordpress.js, cms-framer.js): a connection- // would reach a real site.+ // WordPress, Framer and Wix (cms-wordpress.js, cms-framer.js, cms-wix.js):+ // a connection would reach a real site.guard('POST /cms/brands/:brandId/wordpress', brandIn('path')),guard('DELETE /cms/brands/:brandId/wordpress', brandIn('path')),guard('POST /cms/brands/:brandId/framer', brandIn('path')),guard('PUT /cms/brands/:brandId/framer', brandIn('path')),guard('DELETE /cms/brands/:brandId/framer', brandIn('path')),+ guard('POST /cms/brands/:brandId/wix', brandIn('path')),+ guard('DELETE /cms/brands/:brandId/wix', brandIn('path')),// Content Editor (content-drafts.js): the draft's brand is in the body;// the draft itself is checked too.diff --git a/server/src/middleware/subscription.js b/server/src/middleware/subscription.jsindex 31c3d4a1f..679565b24 100644--- a/server/src/middleware/subscription.js+++ b/server/src/middleware/subscription.js@@ -65,6 +65,8 @@ export const COST_STOPPING = [{ method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/wordpress\/?$/ },// Disconnects a brand's Framer project (cms-framer.js): its API key is deleted.{ method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/framer\/?$/ },+ // Disconnects a brand's Wix site (cms-wix.js): its API key is deleted.+ { method: 'DELETE', path: /^\/cms\/brands\/[^/]+\/wix\/?$/ },// Removes an AI-bot log connection (bots.js): its secret stops working.{ method: 'DELETE', path: /^\/bots\/connections\/[^/]+\/[^/]+\/?$/ },// Removes a store from the catalog (catalog.js): its sign-in is revoked atdiff --git a/server/src/middleware/subscription.test.js b/server/src/middleware/subscription.test.jsindex 891966bdc..0329a8a72 100644--- a/server/src/middleware/subscription.test.js+++ b/server/src/middleware/subscription.test.js@@ -161,6 +161,7 @@ describe('requireActiveSubscription', () => {['DELETE', '/cms/brands/b1/webflow'],['DELETE', '/cms/brands/b1/wordpress'],['DELETE', '/cms/brands/b1/framer'],+ ['DELETE', '/cms/brands/b1/wix'],['DELETE', '/bots/connections/b1/c1'],// A store's sign-in is revoked at the store as it is removed.['DELETE', '/catalog/sources/9b2c1e40-0000-4000-8000-000000000003'],@@ -190,6 +191,8 @@ describe('requireActiveSubscription', () => {['POST', '/cms/brands/b1/framer'],['PUT', '/cms/brands/b1/framer'],['DELETE', '/cms/brands/b1/framer/collections'],+ ['POST', '/cms/brands/b1/wix'],+ ['DELETE', '/cms/brands/b1/wix/extra'],['POST', '/bots/connections/b1'],['DELETE', '/bots/connections/b1'],['POST', '/catalog/sources'],@@ -203,7 +206,7 @@ describe('requireActiveSubscription', () => {expect(res.status).toHaveBeenCalledWith(402);}// Both Google disconnects are one route.- expect(COST_STOPPING).toHaveLength(8);+ expect(COST_STOPPING).toHaveLength(9);});it('lets an organization off a plan delete a brand, and nothing near it', async () => {diff --git a/server/src/routes/cms-wix.js b/server/src/routes/cms-wix.jsnew file mode 100644index 000000000..0b617a0c6--- /dev/null+++ b/server/src/routes/cms-wix.js@@ -0,0 +1,162 @@+import { Router } from 'express';+import { z } from 'zod';+import supabaseAdmin from '../config/supabase.js';+import { assertBrandAccess } from '../lib/access.js';+import { credentialsConfigured } from '../lib/catalog/credentials.js';+import { saveCmsCredentials } from '../lib/cms/credentials.js';+import { WixError, checkSite, siteIdOf } from '../lib/cms/wix.js';+import { cmsLimiter } from '../middleware/rate-limiter.js';+import { assertWriter, brandOf } from './cms.js';++/**+ * A brand's Wix connection for Send to CMS (#1331, phase 2; 00372). Members+ * read a brand's connection; admins and managers connect the brand's site+ * with an API key its owner made in Wix's API Keys Manager, and disconnect:+ * GET /api/cms/brands/:brandId/wix the connection, or none+ * POST /api/cms/brands/:brandId/wix { siteId, apiKey } connect, or replace the key+ * DELETE /api/cms/brands/:brandId/wix disconnect+ * The key passes through here once: it is checked with Wix, then sealed by+ * the API (lib/cms/credentials.js). It is never stored in the clear, logged+ * or sent back. Wix can't revoke it for us: the owner deletes it in the API+ * Keys Manager.+ */++const router = Router();++const PROVIDER = 'wix';+const COLUMNS = 'id, brand_id, status, site_id, site_name, account, created_at, updated_at';++const connectInput = z.object({+ // The site's id, or its dashboard's address with it.+ siteId: z.string().trim().min(1).max(2048),+ // A Wix API key: a long token from the API Keys Manager.+ apiKey: z.string().trim().min(20).max(4096),+});++async function connectionOf(id) {+ const { data, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .select(COLUMNS)+ .eq('brand_id', id)+ .eq('provider', PROVIDER)+ .maybeSingle();+ if (error) throw new Error(error.message);+ return data;+}++/** The connection as the web shows it: never the key. */+const shape = (row) =>+ row+ ? {+ status: row.status,+ siteId: row.site_id,+ siteName: row.site_name,+ connectedAt: row.created_at,+ updatedAt: row.updated_at,+ }+ : null;++const WIX_STATUS = { invalid: 400, unreachable: 502, failed: 502 };++/** Answers a failure; logged by name only, since a message may quote what the person typed. */+function fail(req, res, err, what) {+ if (err instanceof WixError) {+ return res.status(WIX_STATUS[err.code] ?? 409).json({ error: err.message, code: err.code });+ }+ if (err?.status && err.status < 500) {+ return res.status(err.status).json({+ error: err.message,+ code: err.code ?? (err.status === 404 ? 'not_found' : 'forbidden'),+ });+ }+ req.log.error({ err: { name: err?.name } }, what);+ return res.status(500).json({ error: 'Something went wrong with Wix', code: 'failed' });+}++// The API keeps Wix's API key encrypted, under CONNECTOR_CREDENTIALS_KEY.+const notConfigured = (res) =>+ res.status(503).json({ error: 'Wix is not set up on this server.', code: 'not_configured' });++// GET — the brand's connection, for every member (Settings, the Send dialog).+router.get('/brands/:brandId/wix', async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ try {+ await assertBrandAccess(id, req.user.id);+ return res.json({+ configured: credentialsConfigured(),+ connection: shape(await connectionOf(id)),+ });+ } catch (err) {+ return fail(req, res, err, 'cms wix read error');+ }+});++// POST — connect the brand's site, or replace its key: checked with Wix first.+router.post('/brands/:brandId/wix', cmsLimiter, async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ const parsed = connectInput.safeParse(req.body ?? {});+ if (!parsed.success) {+ return res+ .status(400)+ .json({ error: 'Enter the site’s id and an API key from Wix.', code: 'invalid' });+ }+ try {+ await assertWriter(id, req.user.id);+ if (!credentialsConfigured()) return notConfigured(res);+ const siteId = siteIdOf(parsed.data.siteId);+ const { apiKey } = parsed.data;+ const { siteName, memberId } = await checkSite(siteId, apiKey);+ const { data: row, error } = await supabaseAdmin+ .from('brand_cms_connections')+ .upsert(+ {+ brand_id: id,+ provider: PROVIDER,+ site_id: siteId,+ site_name: siteName,+ account: memberId,+ status: 'connected',+ connected_by: req.user.id,+ updated_at: new Date().toISOString(),+ },+ { onConflict: 'brand_id,provider' },+ )+ .select(COLUMNS)+ .single();+ if (error) throw new Error(error.message);+ try {+ await saveCmsCredentials(row.id, { apiKey }, { setBy: req.user.id });+ } catch (err) {+ // Connected without its key, a send would use the one it replaced, on the new site.+ await supabaseAdmin+ .from('brand_cms_connections')+ .update({ status: 'auth_failed', updated_at: new Date().toISOString() })+ .eq('id', row.id);+ throw err;+ }+ return res.json({ connection: shape(row) });+ } catch (err) {+ return fail(req, res, err, 'cms wix connect error');+ }+});++// DELETE — disconnect: the row goes, its key with it. The owner deletes the key in Wix.+router.delete('/brands/:brandId/wix', cmsLimiter, async (req, res) => {+ const id = brandOf(req, res);+ if (!id) return;+ try {+ await assertWriter(id, req.user.id);+ const row = await connectionOf(id);+ if (row) {+ const { error } = await supabaseAdmin.from('brand_cms_connections').delete().eq('id', row.id);+ if (error) throw new Error(error.message);+ }+ return res.json({ success: true });+ } catch (err) {+ return fail(req, res, err, 'cms wix disconnect error');+ }+});++export default router;diff --git a/server/src/routes/cms-wix.test.js b/server/src/routes/cms-wix.test.jsnew file mode 100644index 000000000..0c069b4c8--- /dev/null+++ b/server/src/routes/cms-wix.test.js@@ -0,0 +1,241 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';++/**+ * /api/cms/brands/:brandId/wix (Send to CMS, #1331 phase 2, 00372): a+ * brand's Wix connection. Members read it; admins and managers connect a+ * site with its owner's API key, checked with Wix first, and disconnect; the+ * key is never kept in the clear, logged or sent back.+ */++const BRAND = '33333333-3333-3333-3333-333333333333';+const API_KEY = 'IST.eyJraWQiOiJQb3pIX2FDMiJ9.secret-wix-key';+const SITE = '2f8a1c3e-1111-4222-8333-944455556666';+const MEMBER = 'c00e8a5c-322b-4e77-8813-002e3ea7e811';++let role;+let rows;+let configured;+const assertBrandAccess = vi.fn();+const credentials = { save: vi.fn(), read: vi.fn() };+const wix = { checkSite: vi.fn() };++/** brand_cms_connections in memory: the queries the routes make. */+function table() {+ let filters = [];+ let write = null;+ const matches = (row) => filters.every(([col, value]) => row[col] === value);+ const run = () => {+ if (write?.kind === 'upsert') {+ const at = rows.findIndex(+ (r) => r.brand_id === write.row.brand_id && r.provider === write.row.provider,+ );+ const row = {+ id: 'cn1',+ created_at: '2026-10-27T10:00:00Z',+ ...(at >= 0 ? rows[at] : {}),+ ...write.row,+ };+ if (at >= 0) rows[at] = row;+ else rows.push(row);+ return [row];+ }+ if (write?.kind === 'update') {+ const hit = rows.filter(matches);+ for (const row of hit) Object.assign(row, write.fields);+ return hit;+ }+ if (write?.kind === 'delete') {+ const hit = rows.filter(matches);+ rows = rows.filter((r) => !matches(r));+ return hit;+ }+ return rows.filter(matches);+ };+ const answer = () => run().map((row) => ({ ...row }));+ const chain = {+ select: () => chain,+ eq: (col, value) => {+ filters.push([col, value]);+ return chain;+ },+ upsert: (row) => {+ write = { kind: 'upsert', row };+ return chain;+ },+ update: (fields) => {+ write = { kind: 'update', fields };+ return chain;+ },+ delete: () => {+ write = { kind: 'delete' };+ return chain;+ },+ maybeSingle: async () => ({ data: answer()[0] ?? null, error: null }),+ single: async () => ({ data: answer()[0] ?? null, error: null }),+ then: (resolve) => resolve({ data: answer(), error: null }),+ };+ return chain;+}++vi.mock('../config/supabase.js', () => ({+ default: {+ from: (name) => {+ if (name === 'profiles') {+ const chain = {+ select: () => chain,+ eq: () => chain,+ single: async () => ({ data: { role } }),+ };+ return chain;+ }+ return table();+ },+ },+}));+vi.mock('../lib/access.js', () => ({ assertBrandAccess: (...args) => assertBrandAccess(...args) }));+vi.mock('../lib/composio.js', () => ({+ isWebflowConfigured: () => false,+ connectWebflowToken: vi.fn(),+ deleteConnection: vi.fn(),+ forgetWebflowAccounts: vi.fn(),+}));+vi.mock('../lib/catalog/credentials.js', () => ({ credentialsConfigured: () => configured }));+vi.mock('../lib/cms/credentials.js', () => ({+ saveCmsCredentials: (...args) => credentials.save(...args),+ readCmsCredentials: (...args) => credentials.read(...args),+}));+vi.mock('../lib/cms/wix.js', async (importOriginal) => ({+ ...(await importOriginal()),+ checkSite: (...args) => wix.checkSite(...args),+}));+vi.mock('../middleware/rate-limiter.js', () => ({ cmsLimiter: (_req, _res, next) => next() }));++const { default: router } = await import('./cms-wix.js');+const { WixError } = await import('../lib/cms/wix.js');++let server;+let base;+let logged;++beforeEach(async () => {+ role = 'manager';+ rows = [];+ logged = [];+ configured = true;+ assertBrandAccess.mockReset().mockResolvedValue({ orgId: 'o1' });+ credentials.save.mockReset().mockResolvedValue(undefined);+ credentials.read.mockReset().mockResolvedValue({ apiKey: API_KEY });+ wix.checkSite.mockReset().mockResolvedValue({ siteName: 'Acme Coffee', memberId: MEMBER });+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ const log = (...args) => logged.push(JSON.stringify(args));+ req.log = { error: log, warn: log, info: log };+ next();+ });+ app.use('/api/cms', router);+ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ base = `http://127.0.0.1:${server.address().port}/api/cms/brands/${BRAND}/wix`;+});++afterEach(() => new Promise((resolve) => server.close(resolve)));++const call = (method, body) =>+ fetch(base, {+ method,+ headers: { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+const input = { siteId: `https://manage.wix.com/dashboard/${SITE}/home`, apiKey: API_KEY };+const connectedRow = (extra = {}) => ({+ id: 'cn1',+ brand_id: BRAND,+ provider: 'wix',+ status: 'connected',+ site_id: SITE,+ site_name: 'Acme Coffee',+ account: MEMBER,+ created_at: '2026-10-20T10:00:00Z',+ updated_at: '2026-10-20T10:00:00Z',+ ...extra,+});++describe('GET', () => {+ it('shows a member the connection, never its key', async () => {+ rows = [connectedRow()];+ const res = await call('GET');+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body).toEqual({+ configured: true,+ connection: {+ status: 'connected',+ siteId: SITE,+ siteName: 'Acme Coffee',+ connectedAt: '2026-10-20T10:00:00Z',+ updatedAt: '2026-10-20T10:00:00Z',+ },+ });+ expect(JSON.stringify(body)).not.toContain(API_KEY);+ });+});++describe('POST', () => {+ it('checks the site with Wix, then keeps the connection and seals its key', async () => {+ const res = await call('POST', input);+ expect(res.status).toBe(200);+ // The site's id read from its dashboard's address.+ expect(wix.checkSite).toHaveBeenCalledWith(SITE, API_KEY);+ expect(rows[0]).toMatchObject({+ provider: 'wix',+ site_id: SITE,+ site_name: 'Acme Coffee',+ account: MEMBER,+ status: 'connected',+ });+ expect(credentials.save).toHaveBeenCalledWith('cn1', { apiKey: API_KEY }, { setBy: 'u1' });+ expect(JSON.stringify(await res.json())).not.toContain(API_KEY);+ });++ it('refuses a member who is neither an admin nor a manager, and input it can’t read', async () => {+ role = 'member';+ expect((await call('POST', input)).status).toBe(403);+ role = 'manager';+ expect((await call('POST', { siteId: 'x', apiKey: 'short' })).status).toBe(400);+ expect((await call('POST', { ...input, siteId: 'no id here' })).status).toBe(400);+ expect(wix.checkSite).not.toHaveBeenCalled();+ });++ it('says what Wix answered, and keeps nothing', async () => {+ wix.checkSite.mockRejectedValue(new WixError('no_blog', 'This site has no Wix Blog.'));+ const res = await call('POST', input);+ expect(res.status).toBe(409);+ expect(await res.json()).toEqual({ error: 'This site has no Wix Blog.', code: 'no_blog' });+ expect(rows).toEqual([]);+ expect(credentials.save).not.toHaveBeenCalled();+ });++ it('marks the connection refused when its key can’t be kept, and says it isn’t set up without the key store', async () => {+ credentials.save.mockRejectedValue(new Error('brand_cms_credentials write: error'));+ expect((await call('POST', input)).status).toBe(500);+ expect(rows[0].status).toBe('auth_failed');+ expect(logged.join('')).not.toContain(API_KEY);++ configured = false;+ expect((await call('POST', input)).status).toBe(503);+ });+});++describe('DELETE', () => {+ it('disconnects, its key with it', async () => {+ rows = [connectedRow()];+ const res = await call('DELETE');+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ success: true });+ expect(rows).toEqual([]);+ });+});diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex 0bd0df24a..518daea35 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -50,7 +50,7 @@ async function assertSender(userId) {/*** POST /api/content-drafts/send- * Body: { brandId, target?: 'webhook' | 'webflow' | 'wordpress' | 'framer', pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }+ * Body: { brandId, target?: 'webhook' | 'webflow' | 'wordpress' | 'framer' | 'wix', pages: [{ draftId, title, slug, metaTitle, metaDescription, html, author, featuredImage }] }* One page is sent before this answers: { deliveries: [{ id, status, http_status, error }] };* more (up to 25) go on in the background: { batchId, deliveries: queued, skipped }.*/diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex 23a862d6d..df746dc27 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -20,6 +20,7 @@ import catalogRoutes from './catalog.js';import cmsRoutes from './cms.js';import cmsWordPressRoutes from './cms-wordpress.js';import cmsFramerRoutes from './cms-framer.js';+import cmsWixRoutes from './cms-wix.js';import demoRoutes from './demo.js';const router = Router();@@ -45,6 +46,7 @@ router.use('/catalog', catalogRoutes);router.use('/cms', cmsRoutes);router.use('/cms', cmsWordPressRoutes);router.use('/cms', cmsFramerRoutes);+router.use('/cms', cmsWixRoutes);router.use('/demo', demoRoutes);router.get('/health', (req, res) => {diff --git a/supabase/migrations/00372_cms_wix.sql b/supabase/migrations/00372_cms_wix.sqlnew file mode 100644index 000000000..7338abb9b--- /dev/null+++ b/supabase/migrations/00372_cms_wix.sql@@ -0,0 +1,130 @@+-- ============================================================================+-- 00372: Wix for Send to CMS (#1331, phase 2)+-- ============================================================================+-- After Webflow (00283, 00284), WordPress (00294) and Framer (00295), a brand+-- connects its Wix site: the site's id and an API key its owner made in Wix's+-- API Keys Manager, with the Wix Blog permissions. Pages go to the site's+-- Blog through Wix's REST API as draft posts.+--+-- * brand_cms_connections takes provider 'wix'. A Wix connection keeps the+-- site's id (`site_id`), its name (`site_name`) and the member who owns+-- the posts it writes (`account`: a Wix member id; Wix's Blog needs an+-- owner for a post).+-- * The API key is kept in brand_cms_credentials, sealed as WordPress's+-- sign-in is (00294); the table itself doesn't change.+-- * content_draft_deliveries.target takes 'wix'. `target_collection` keeps+-- the site's id the post was written to, as it keeps WordPress's site.+-- * reserve_content_deliveries: as 00295, a page already queued for the+-- same CMS (Webflow, WordPress, Framer or Wix) isn't sent there again+-- meanwhile.++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_check,+ add constraint brand_cms_connections_provider_check+ check (provider in ('webflow', 'wordpress', 'framer', 'wix'));++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_fields,+ add constraint brand_cms_connections_provider_fields check (+ case provider+ when 'webflow' then composio_account_id is not null and composio_entity_id is not null+ when 'wordpress' then site_url is not null and account is not null+ when 'framer' then site_id is not null+ when 'wix' then site_id is not null and account is not null+ else false+ end+ );++comment on column public.brand_cms_connections.site_id is+ 'Webflow: the site pages go to (00283). Framer (00295): the project''s id, as Framer connects to it. Wix (00372): the site''s id.';+comment on column public.brand_cms_connections.site_name is+ 'The site''s name (Webflow, WordPress, Wix (00372): its display name, when the API key may read it), or the Framer project''s (00295).';+comment on column public.brand_cms_connections.account is+ 'WordPress (00294): the user the connection signs in as, with an Application Password. Framer (00295): the user the API key acts as. Both kept in brand_cms_credentials. Wix (00372): the member who owns the posts it writes.';++comment on table public.brand_cms_credentials is+ 'Send to CMS (#1331, 00294, 00295, 00372): a CMS connection''s sign-in (WordPress: the user and the Application Password; Framer: the project''s API key; Wix: the site owner''s API key), encrypted by the API (AES-256-GCM, bound to the connection id). Service role only; removed with its connection.';++alter table public.content_draft_deliveries+ drop constraint if exists content_draft_deliveries_target_check,+ add constraint content_draft_deliveries_target_check+ check (target in ('webhook', 'webflow', 'wordpress', 'framer', 'wix'));++comment on column public.content_draft_deliveries.target is+ 'Where the page was sent (00284, 00294, 00295, 00372): the brand''s webhook, its Webflow collection, its WordPress site, its Framer collection or its Wix site''s Blog (00283).';+comment on column public.content_draft_deliveries.target_collection is+ 'The Webflow or Framer collection (00284, 00295), the WordPress site''s address (00294) or the Wix site''s id (00372) the page''s item or post was written to; its id is external_id.';++-- ----------------------------------------------------------------------------+-- As 00295, with Wix among the CMSs a page isn't sent to twice at once.+-- ----------------------------------------------------------------------------+create or replace function public.reserve_content_deliveries(+ p_organization_id uuid,+ p_brand_id uuid,+ p_sent_by uuid,+ p_batch_id uuid,+ p_items jsonb,+ p_limit integer,+ p_target text default 'webhook'+)+returns setof public.content_draft_deliveries+language plpgsql+security definer+set search_path = public+as $$+declare+ used integer;+ room integer;+begin+ perform pg_advisory_xact_lock(hashtext('content_deliveries:' || p_organization_id::text));++ -- sent_at stays empty: it was never sent, and its time stays its own.+ update public.content_draft_deliveries+ set status = 'failed', error = 'Not sent: interrupted'+ where organization_id = p_organization_id+ and status = 'queued'+ and created_at < now() - interval '30 minutes';++ select count(*) into used+ from public.content_draft_deliveries+ where organization_id = p_organization_id+ and created_at > now() - interval '24 hours';++ room := greatest(0, p_limit - used);+ if room = 0 or jsonb_typeof(p_items) <> 'array' then+ return;+ end if;++ -- Under the lock, so two sends of one page can't both pass: both would+ -- make an item (Webflow refuses the second on its slug) or a post.+ if p_target in ('webflow', 'wordpress', 'framer', 'wix') and exists (+ select 1+ from public.content_draft_deliveries d+ join jsonb_array_elements(p_items) as items(item)+ on d.draft_id = (item ->> 'draft_id')::uuid+ where d.organization_id = p_organization_id+ and d.target = p_target+ and d.status = 'queued'+ ) then+ raise exception 'delivery_in_progress' using errcode = 'P0001';+ end if;++ return query+ insert into public.content_draft_deliveries+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug, target)+ select p_organization_id, p_brand_id, (item ->> 'draft_id')::uuid, p_sent_by, p_batch_id,+ left(item ->> 'title', 300), nullif(left(item ->> 'slug', 200), ''),+ coalesce(p_target, 'webhook')+ from jsonb_array_elements(p_items) with ordinality as items(item, position)+ order by position+ limit room+ returning *;+end;+$$;++revoke all on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ from public, anon, authenticated;+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ to service_role;++notify pgrst, 'reload schema';diff --git a/supabase/schema.sql b/supabase/schema.sqlindex 1460dcd47..05431802b 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -43048,6 +43048,140 @@ comment on function public.catalog_suggestion_categories(uuid, integer, integer)notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00372_cms_wix.sql+-- ─────────────────────────────────────────────────────────────────────────+-- ============================================================================+-- 00372: Wix for Send to CMS (#1331, phase 2)+-- ============================================================================+-- After Webflow (00283, 00284), WordPress (00294) and Framer (00295), a brand+-- connects its Wix site: the site's id and an API key its owner made in Wix's+-- API Keys Manager, with the Wix Blog permissions. Pages go to the site's+-- Blog through Wix's REST API as draft posts.+--+-- * brand_cms_connections takes provider 'wix'. A Wix connection keeps the+-- site's id (`site_id`), its name (`site_name`) and the member who owns+-- the posts it writes (`account`: a Wix member id; Wix's Blog needs an+-- owner for a post).+-- * The API key is kept in brand_cms_credentials, sealed as WordPress's+-- sign-in is (00294); the table itself doesn't change.+-- * content_draft_deliveries.target takes 'wix'. `target_collection` keeps+-- the site's id the post was written to, as it keeps WordPress's site.+-- * reserve_content_deliveries: as 00295, a page already queued for the+-- same CMS (Webflow, WordPress, Framer or Wix) isn't sent there again+-- meanwhile.++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_check,+ add constraint brand_cms_connections_provider_check+ check (provider in ('webflow', 'wordpress', 'framer', 'wix'));++alter table public.brand_cms_connections+ drop constraint if exists brand_cms_connections_provider_fields,+ add constraint brand_cms_connections_provider_fields check (+ case provider+ when 'webflow' then composio_account_id is not null and composio_entity_id is not null+ when 'wordpress' then site_url is not null and account is not null+ when 'framer' then site_id is not null+ when 'wix' then site_id is not null and account is not null+ else false+ end+ );++comment on column public.brand_cms_connections.site_id is+ 'Webflow: the site pages go to (00283). Framer (00295): the project''s id, as Framer connects to it. Wix (00372): the site''s id.';+comment on column public.brand_cms_connections.site_name is+ 'The site''s name (Webflow, WordPress, Wix (00372): its display name, when the API key may read it), or the Framer project''s (00295).';+comment on column public.brand_cms_connections.account is+ 'WordPress (00294): the user the connection signs in as, with an Application Password. Framer (00295): the user the API key acts as. Both kept in brand_cms_credentials. Wix (00372): the member who owns the posts it writes.';++comment on table public.brand_cms_credentials is+ 'Send to CMS (#1331, 00294, 00295, 00372): a CMS connection''s sign-in (WordPress: the user and the Application Password; Framer: the project''s API key; Wix: the site owner''s API key), encrypted by the API (AES-256-GCM, bound to the connection id). Service role only; removed with its connection.';++alter table public.content_draft_deliveries+ drop constraint if exists content_draft_deliveries_target_check,+ add constraint content_draft_deliveries_target_check+ check (target in ('webhook', 'webflow', 'wordpress', 'framer', 'wix'));++comment on column public.content_draft_deliveries.target is+ 'Where the page was sent (00284, 00294, 00295, 00372): the brand''s webhook, its Webflow collection, its WordPress site, its Framer collection or its Wix site''s Blog (00283).';+comment on column public.content_draft_deliveries.target_collection is+ 'The Webflow or Framer collection (00284, 00295), the WordPress site''s address (00294) or the Wix site''s id (00372) the page''s item or post was written to; its id is external_id.';++-- ----------------------------------------------------------------------------+-- As 00295, with Wix among the CMSs a page isn't sent to twice at once.+-- ----------------------------------------------------------------------------+create or replace function public.reserve_content_deliveries(+ p_organization_id uuid,+ p_brand_id uuid,+ p_sent_by uuid,+ p_batch_id uuid,+ p_items jsonb,+ p_limit integer,+ p_target text default 'webhook'+)+returns setof public.content_draft_deliveries+language plpgsql+security definer+set search_path = public+as $$+declare+ used integer;+ room integer;+begin+ perform pg_advisory_xact_lock(hashtext('content_deliveries:' || p_organization_id::text));++ -- sent_at stays empty: it was never sent, and its time stays its own.+ update public.content_draft_deliveries+ set status = 'failed', error = 'Not sent: interrupted'+ where organization_id = p_organization_id+ and status = 'queued'+ and created_at < now() - interval '30 minutes';++ select count(*) into used+ from public.content_draft_deliveries+ where organization_id = p_organization_id+ and created_at > now() - interval '24 hours';++ room := greatest(0, p_limit - used);+ if room = 0 or jsonb_typeof(p_items) <> 'array' then+ return;+ end if;++ -- Under the lock, so two sends of one page can't both pass: both would+ -- make an item (Webflow refuses the second on its slug) or a post.+ if p_target in ('webflow', 'wordpress', 'framer', 'wix') and exists (+ select 1+ from public.content_draft_deliveries d+ join jsonb_array_elements(p_items) as items(item)+ on d.draft_id = (item ->> 'draft_id')::uuid+ where d.organization_id = p_organization_id+ and d.target = p_target+ and d.status = 'queued'+ ) then+ raise exception 'delivery_in_progress' using errcode = 'P0001';+ end if;++ return query+ insert into public.content_draft_deliveries+ (organization_id, brand_id, draft_id, sent_by, batch_id, title, slug, target)+ select p_organization_id, p_brand_id, (item ->> 'draft_id')::uuid, p_sent_by, p_batch_id,+ left(item ->> 'title', 300), nullif(left(item ->> 'slug', 200), ''),+ coalesce(p_target, 'webhook')+ from jsonb_array_elements(p_items) with ordinality as items(item, position)+ order by position+ limit room+ returning *;+end;+$$;++revoke all on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ from public, anon, authenticated;+grant execute on function public.reserve_content_deliveries(uuid, uuid, uuid, uuid, jsonb, integer, text)+ to service_role;++notify pgrst, 'reload schema';+-- ─────────────────────────────────────────────────────────────────────────-- migrations/00373_basket_positive_sentiment.sql-- ─────────────────────────────────────────────────────────────────────────