Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Marketing backend: brand kits, products, Marketing Studio, Click to Ad, Ad Multiplier and Ads Studio

Claude7ce4f4003be5
diff --git a/src/app/api/ads/batches/route.ts b/src/app/api/ads/batches/route.ts
new file mode 100644
index 00000000..66cc78ae
--- /dev/null
+++ b/src/app/api/ads/batches/route.ts
@@ -0,0 +1,16 @@
+import { after } from "next/server";
+import { BatchBody, createBatch } from "@/server/ads";
+import { failure, readBody } from "@/server/marketing";
+
+/** "Create N ads": creatives land in the grid at once; copy and pictures follow in the background. */
+export async function POST(request: Request) {
+ const body = await readBody(request, BatchBody, "Pick products and how many ads to make");
+ if (body instanceof Response) return body;
+ try {
+ const { batchId, creatives, run } = createBatch(body);
+ after(() => run);
+ return Response.json({ batchId, creatives }, { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/ads/creatives/[id]/retry/route.ts b/src/app/api/ads/creatives/[id]/retry/route.ts
new file mode 100644
index 00000000..a130ce06
--- /dev/null
+++ b/src/app/api/ads/creatives/[id]/retry/route.ts
@@ -0,0 +1,12 @@
+import { retryCreative } from "@/server/ads";
+import { failure } from "@/server/marketing";
+
+/** Make a failed ad again (this spends credits again). */
+export async function POST(_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]/retry">) {
+ const { id } = await ctx.params;
+ try {
+ return Response.json(await retryCreative(id), { status: 201 });
+ } catch (e) {
+ return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);
+ }
+}
diff --git a/src/app/api/ads/creatives/[id]/route.ts b/src/app/api/ads/creatives/[id]/route.ts
new file mode 100644
index 00000000..d2baef11
--- /dev/null
+++ b/src/app/api/ads/creatives/[id]/route.ts
@@ -0,0 +1,17 @@
+import { CreativePatch, deleteCreative, updateCreative } from "@/server/ads";
+import { readBody } from "@/server/marketing";
+
+/** Edit an ad's words or layout (the picture stays). */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, CreativePatch, "Check the ad's text");
+ if (body instanceof Response) return body;
+ const c = updateCreative(id, body);
+ return c ? Response.json(c) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Remove an ad from the grid (its picture stays in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/ads/creatives/[id]">) {
+ const { id } = await ctx.params;
+ return deleteCreative(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/ads/creatives/[id]/save/route.ts b/src/app/api/ads/creatives/[id]/save/route.ts
new file mode 100644
index 00000000..11de5945
--- /dev/null
+++ b/src/app/api/ads/creatives/[id]/save/route.ts
@@ -0,0 +1,17 @@
+import { z } from "zod";
+import { saveComposite } from "@/server/ads";
+import { failure, readBody } from "@/server/marketing";
+
+const Body = z.object({ url: z.string().startsWith("/api/files/"), ratio: z.enum(["1:1", "4:5", "9:16"]) });
+
+/** Record a creative composited in the browser (an uploaded PNG) in the Library. */
+export async function POST(request: Request, ctx: RouteContext<"/api/ads/creatives/[id]/save">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, Body, "Upload the image first");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(saveComposite(id, body), { status: 201 });
+ } catch (e) {
+ return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);
+ }
+}
diff --git a/src/app/api/ads/creatives/route.ts b/src/app/api/ads/creatives/route.ts
new file mode 100644
index 00000000..684aca37
--- /dev/null
+++ b/src/app/api/ads/creatives/route.ts
@@ -0,0 +1,11 @@
+import { connection } from "next/server";
+import { listCreatives } from "@/server/ads";
+
+/** A brand's ads (`?brand=<id>`, optionally `&batch=` or `&product=`), newest run first. */
+export async function GET(request: Request) {
+ await connection();
+ const q = new URL(request.url).searchParams;
+ const brandId = q.get("brand");
+ if (!brandId) return Response.json({ error: "Pick a brand" }, { status: 400 });
+ return Response.json({ items: listCreatives({ brandId, batchId: q.get("batch") ?? undefined, productId: q.get("product") ?? undefined }) });
+}
diff --git a/src/app/api/ads/estimate/route.ts b/src/app/api/ads/estimate/route.ts
new file mode 100644
index 00000000..ae2d9285
--- /dev/null
+++ b/src/app/api/ads/estimate/route.ts
@@ -0,0 +1,13 @@
+import { BatchBody, estimateBatch } from "@/server/ads";
+import { readBody } from "@/server/marketing";
+
+/** The total before the run: ads × price per ad (+ the copy), and which model renders them. */
+export async function POST(request: Request) {
+ const body = await readBody(request, BatchBody, "Pick products and how many ads to make");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(estimateBatch(body));
+ } catch (e) {
+ return Response.json({ costUsd: null, total: 0, perAd: null, demo: false, blocker: (e as Error).message });
+ }
+}
diff --git a/src/app/api/ads/multiplier/estimate/route.ts b/src/app/api/ads/multiplier/estimate/route.ts
new file mode 100644
index 00000000..2610f6ed
--- /dev/null
+++ b/src/app/api/ads/multiplier/estimate/route.ts
@@ -0,0 +1,11 @@
+import { estimateMultiplier, MultiplierBody, readBody } from "@/server/marketing";
+
+export async function POST(request: Request) {
+ const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(estimateMultiplier(body));
+ } catch (e) {
+ return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
+ }
+}
diff --git a/src/app/api/ads/multiplier/route.ts b/src/app/api/ads/multiplier/route.ts
new file mode 100644
index 00000000..a84e96eb
--- /dev/null
+++ b/src/app/api/ads/multiplier/route.ts
@@ -0,0 +1,12 @@
+import { failure, MultiplierBody, readBody, runMultiplier } from "@/server/marketing";
+
+/** Ad Multiplier: new versions of a reference ad (the whole ad from a prompt, or a new hook / CTA around it). */
+export async function POST(request: Request) {
+ const body = await readBody(request, MultiplierBody, "Add a reference video to recreate");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json({ runs: runMultiplier(body) }, { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/brands/[id]/chat/confirm/route.ts b/src/app/api/brands/[id]/chat/confirm/route.ts
new file mode 100644
index 00000000..7360292b
--- /dev/null
+++ b/src/app/api/brands/[id]/chat/confirm/route.ts
@@ -0,0 +1,20 @@
+import { after } from "next/server";
+import { z } from "zod";
+import { confirmProposal } from "@/server/ads";
+import { failure, readBody } from "@/server/marketing";
+
+const Body = z.object({ messageId: z.string().min(1).max(20), engine: z.enum(["cloud", "open"]), route: z.enum(["fuobe", "higgsfield"]).optional() });
+
+/** The user said yes to a chat proposal: the ads start rendering. */
+export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]/chat/confirm">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, Body);
+ if (body instanceof Response) return body;
+ try {
+ const r = confirmProposal(id, body.messageId, body.engine, body.route);
+ after(() => r.run);
+ return Response.json({ batchId: r.batchId, messages: r.chat }, { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/brands/[id]/chat/route.ts b/src/app/api/brands/[id]/chat/route.ts
new file mode 100644
index 00000000..8b55583b
--- /dev/null
+++ b/src/app/api/brands/[id]/chat/route.ts
@@ -0,0 +1,32 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { chat, clearChat, getChat } from "@/server/ads";
+import { getBrand } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+const Body = z.object({ text: z.string().trim().min(1).max(2000) });
+
+/** The brand chat ("what ads should we make for {brand}?"). */
+export async function GET(_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {
+ await connection();
+ const { id } = await ctx.params;
+ return getBrand(id) ? Response.json({ messages: getChat(id) }) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Send a message; the reply may carry a proposal (products × count + direction) to confirm. */
+export async function POST(request: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, Body, "Write a message");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json({ messages: await chat(id, body.text) });
+ } catch (e) {
+ return failure(e);
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]/chat">) {
+ const { id } = await ctx.params;
+ clearChat(id);
+ return new Response(null, { status: 204 });
+}
diff --git a/src/app/api/brands/[id]/research/route.ts b/src/app/api/brands/[id]/research/route.ts
new file mode 100644
index 00000000..07b0883d
--- /dev/null
+++ b/src/app/api/brands/[id]/research/route.ts
@@ -0,0 +1,22 @@
+import { after } from "next/server";
+import { cancelResearch, retryResearch } from "@/server/brand";
+import { failure } from "@/server/marketing";
+
+/** Run the website research again (Retry research). */
+export async function POST(_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) {
+ const { id } = await ctx.params;
+ try {
+ const { brand, run } = retryResearch(id);
+ after(() => run);
+ return Response.json(brand, { status: 202 });
+ } catch (e) {
+ return (e as Error).message === "Not found" ? Response.json({ error: "Not found" }, { status: 404 }) : failure(e);
+ }
+}
+
+/** Cancel generation: stops the research; the kit keeps what it had. */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]/research">) {
+ const { id } = await ctx.params;
+ const brand = cancelResearch(id);
+ return brand ? Response.json(brand) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/brands/[id]/route.ts b/src/app/api/brands/[id]/route.ts
new file mode 100644
index 00000000..1442f796
--- /dev/null
+++ b/src/app/api/brands/[id]/route.ts
@@ -0,0 +1,53 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { deleteBrand, getBrand, listProducts, updateBrand } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+const list = (max: number, len: number) => z.array(z.string().max(len)).max(max);
+
+const Patch = z.object({
+ name: z.string().max(80).optional(),
+ website: z.string().max(300).optional(),
+ logo: z.string().max(400).optional(),
+ tagline: z.string().max(200).optional(),
+ overview: z.string().max(2000).optional(),
+ colors: list(12, 32).optional(),
+ fonts: z.object({ heading: z.string().max(80).optional(), body: z.string().max(80).optional() }).optional(),
+ values: list(12, 120).optional(),
+ aesthetics: list(12, 120).optional(),
+ tone: list(12, 60).optional(),
+ audience: z.string().max(400).optional(),
+ sellingPoints: list(10, 200).optional(),
+ competitors: list(12, 80).optional(),
+ socials: z.array(z.object({ network: z.string().max(30), url: z.string().max(400) })).max(16).optional(),
+ language: z.string().max(40).optional(),
+ images: list(16, 400).optional(),
+ details: list(16, 400).optional(),
+});
+
+/** One brand kit with its products. */
+export async function GET(_req: Request, ctx: RouteContext<"/api/brands/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const brand = getBrand(id);
+ return brand ? Response.json({ brand, products: listProducts(id) }) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Edits from the review form. */
+export async function PATCH(request: Request, ctx: RouteContext<"/api/brands/[id]">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, Patch);
+ if (body instanceof Response) return body;
+ try {
+ const brand = updateBrand(id, body);
+ return brand ? Response.json(brand) : Response.json({ error: "Not found" }, { status: 404 });
+ } catch (e) {
+ return failure(e);
+ }
+}
+
+/** The kit and its products leave the shelf; ads already made stay in the Library. */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/brands/[id]">) {
+ const { id } = await ctx.params;
+ return deleteBrand(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/brands/route.ts b/src/app/api/brands/route.ts
new file mode 100644
index 00000000..553a65e7
--- /dev/null
+++ b/src/app/api/brands/route.ts
@@ -0,0 +1,39 @@
+import { after, connection } from "next/server";
+import { z } from "zod";
+import { createBrandFromWebsite, createManualBrand, listBrands } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+const Body = z.union([
+ z.object({ website: z.string().trim().min(1).max(300) }),
+ z.object({
+ description: z.string().trim().max(2000),
+ name: z.string().trim().max(80).optional(),
+ images: z.array(z.string().startsWith("/api/files/")).max(8).optional(),
+ colors: z.array(z.string().regex(/^#[0-9a-fA-F]{6}$/)).max(8).optional(),
+ }),
+]);
+
+/** Brand kits, newest activity first (with product and ad counts). */
+export async function GET() {
+ await connection();
+ return Response.json({ items: listBrands() });
+}
+
+/**
+ * New brand kit: `{website}` starts the research (poll GET /api/brands/:id while status is
+ * "researching"); `{description, images?}` builds one by hand ("Describe your business").
+ */
+export async function POST(request: Request) {
+ const body = await readBody(request, Body, "Add a website, or describe your business");
+ if (body instanceof Response) return body;
+ try {
+ if ("website" in body) {
+ const { brand, run } = createBrandFromWebsite(body.website);
+ after(() => run);
+ return Response.json(brand, { status: 201 });
+ }
+ return Response.json(await createManualBrand(body), { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/marketing/click-to-ad/estimate/route.ts b/src/app/api/marketing/click-to-ad/estimate/route.ts
new file mode 100644
index 00000000..f62da1b4
--- /dev/null
+++ b/src/app/api/marketing/click-to-ad/estimate/route.ts
@@ -0,0 +1,11 @@
+import { ClickToAdBody, estimateClickToAd, readBody } from "@/server/marketing";
+
+export async function POST(request: Request) {
+ const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(estimateClickToAd(body));
+ } catch (e) {
+ return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
+ }
+}
diff --git a/src/app/api/marketing/click-to-ad/route.ts b/src/app/api/marketing/click-to-ad/route.ts
new file mode 100644
index 00000000..59106e0d
--- /dev/null
+++ b/src/app/api/marketing/click-to-ad/route.ts
@@ -0,0 +1,12 @@
+import { ClickToAdBody, failure, readBody, runClickToAd } from "@/server/marketing";
+
+/** Click to Ad: a 9:16 voiced ad with captions from a product kit and a style. */
+export async function POST(request: Request) {
+ const body = await readBody(request, ClickToAdBody, "Select a product or enter a product URL");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(await runClickToAd(body), { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/marketing/estimate/route.ts b/src/app/api/marketing/estimate/route.ts
new file mode 100644
index 00000000..eb50509b
--- /dev/null
+++ b/src/app/api/marketing/estimate/route.ts
@@ -0,0 +1,12 @@
+import { estimateMarketing, MarketingBody, readBody } from "@/server/marketing";
+
+/** Price and check a Marketing Studio run before it starts; what's missing comes back as `blocker`. */
+export async function POST(request: Request) {
+ const body = await readBody(request, MarketingBody);
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(estimateMarketing(body));
+ } catch (e) {
+ return Response.json({ costUsd: null, demo: false, steps: [], notes: [], runs: 0, blocker: (e as Error).message });
+ }
+}
diff --git a/src/app/api/marketing/runs/[id]/route.ts b/src/app/api/marketing/runs/[id]/route.ts
new file mode 100644
index 00000000..bac88f6b
--- /dev/null
+++ b/src/app/api/marketing/runs/[id]/route.ts
@@ -0,0 +1,15 @@
+import { connection } from "next/server";
+import { deleteRun, getRun } from "@/server/marketing";
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const run = getRun(id);
+ return run ? Response.json(run) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+/** Forget a run (its results stay in the Library). */
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/marketing/runs/[id]">) {
+ const { id } = await ctx.params;
+ return deleteRun(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/marketing/runs/route.ts b/src/app/api/marketing/runs/route.ts
new file mode 100644
index 00000000..22f5d092
--- /dev/null
+++ b/src/app/api/marketing/runs/route.ts
@@ -0,0 +1,25 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { failure, listRuns, MarketingBody, readBody, runMarketing } from "@/server/marketing";
+
+const Feature = z.enum(["marketing", "click-to-ad", "ad-multiplier"]);
+
+/** Runs of one flow (`?feature=marketing|click-to-ad|ad-multiplier`), newest first, with every step's generation. */
+export async function GET(request: Request) {
+ await connection();
+ const q = new URL(request.url).searchParams;
+ const feature = Feature.safeParse(q.get("feature") ?? "marketing");
+ if (!feature.success) return Response.json({ error: "Unknown feature" }, { status: 400 });
+ return Response.json({ items: listRuns(feature.data, Number(q.get("limit")) || 30) });
+}
+
+/** Marketing Studio: make a template (or a free prompt) with a product, avatar, hook and brand kit. */
+export async function POST(request: Request) {
+ const body = await readBody(request, MarketingBody);
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(await runMarketing(body), { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/marketing/script/route.ts b/src/app/api/marketing/script/route.ts
new file mode 100644
index 00000000..031195ef
--- /dev/null
+++ b/src/app/api/marketing/script/route.ts
@@ -0,0 +1,21 @@
+import { z } from "zod";
+import { clickToAdScript, failure, readBody } from "@/server/marketing";
+
+const Body = z.object({
+ engine: z.enum(["cloud", "open"]),
+ productId: z.string().min(1).max(40),
+ styleId: z.string().max(40),
+ presenter: z.boolean().optional(),
+ instructions: z.string().max(600).optional(),
+});
+
+/** Write a Click to Ad voiceover script to review (Auto, or with custom instructions). */
+export async function POST(request: Request) {
+ const body = await readBody(request, Body, "Pick a product and a style");
+ if (body instanceof Response) return body;
+ try {
+ return Response.json(await clickToAdScript(body));
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/products/[id]/route.ts b/src/app/api/products/[id]/route.ts
new file mode 100644
index 00000000..a6764d03
--- /dev/null
+++ b/src/app/api/products/[id]/route.ts
@@ -0,0 +1,27 @@
+import { connection } from "next/server";
+import { deleteProduct, getProduct, ProductFields, updateProduct } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+export async function GET(_req: Request, ctx: RouteContext<"/api/products/[id]">) {
+ await connection();
+ const { id } = await ctx.params;
+ const p = getProduct(id);
+ return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });
+}
+
+export async function PATCH(request: Request, ctx: RouteContext<"/api/products/[id]">) {
+ const { id } = await ctx.params;
+ const body = await readBody(request, ProductFields.partial(), "Check the product");
+ if (body instanceof Response) return body;
+ try {
+ const p = updateProduct(id, body);
+ return p ? Response.json(p) : Response.json({ error: "Not found" }, { status: 404 });
+ } catch (e) {
+ return failure(e);
+ }
+}
+
+export async function DELETE(_req: Request, ctx: RouteContext<"/api/products/[id]">) {
+ const { id } = await ctx.params;
+ return deleteProduct(id) ? new Response(null, { status: 204 }) : Response.json({ error: "Not found" }, { status: 404 });
+}
diff --git a/src/app/api/products/read/route.ts b/src/app/api/products/read/route.ts
new file mode 100644
index 00000000..daceff9f
--- /dev/null
+++ b/src/app/api/products/read/route.ts
@@ -0,0 +1,24 @@
+import { z } from "zod";
+import { readProductLink } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+const Body = z.object({
+ url: z.string().trim().min(1).max(600),
+ brandId: z.string().max(40).nullish(),
+ /** How many products to add from a collection page. */
+ limit: z.number().int().min(1).max(10).optional(),
+ /** Also read the page's logo, colours and fonts (Click to Ad's product kit). */
+ withBrand: z.boolean().optional(),
+});
+
+/** Add product(s) from a link: names, descriptions, prices and pictures read from the page. */
+export async function POST(request: Request) {
+ const body = await readBody(request, Body, "Use a valid product link.");
+ if (body instanceof Response) return body;
+ try {
+ const r = await readProductLink(body);
+ return Response.json(r, { status: r.products.length ? 201 : 200 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/app/api/products/route.ts b/src/app/api/products/route.ts
new file mode 100644
index 00000000..b21c518e
--- /dev/null
+++ b/src/app/api/products/route.ts
@@ -0,0 +1,23 @@
+import { connection } from "next/server";
+import { z } from "zod";
+import { createProduct, listProducts, ProductFields } from "@/server/brand";
+import { failure, readBody } from "@/server/marketing";
+
+/** Products: all, a brand's (`?brand=<id>`) or the unassigned ones (`?brand=none`). */
+export async function GET(request: Request) {
+ await connection();
+ const brand = new URL(request.url).searchParams.get("brand");
+ return Response.json({ items: listProducts(brand === null ? undefined : brand === "none" ? null : brand) });
+}
+
+/** Add a product by hand. A name the brand already has answers 409 unless `force` is set ("Create anyway"). */
+export async function POST(request: Request) {
+ const body = await readBody(request, ProductFields.extend({ force: z.boolean().optional() }), "Check the product");
+ if (body instanceof Response) return body;
+ const { force, ...input } = body;
+ try {
+ return Response.json(createProduct({ ...input, price: input.price ?? null }, { force }), { status: 201 });
+ } catch (e) {
+ return failure(e);
+ }
+}
diff --git a/src/components/ads/layout.ts b/src/components/ads/layout.ts
new file mode 100644
index 00000000..db589b4d
--- /dev/null
+++ b/src/components/ads/layout.ts
@@ -0,0 +1,368 @@
+import type { AdRatio } from "@/lib/catalog/marketing";
+
+/**
+ * Ad compositing math (pure, tested): where the visual, scrim/panel, logo, headline, body copy and
+ * CTA go in each format, how text wraps and shrinks to fit, and the brand theme. The browser draws
+ * the plan on a canvas (render.ts) for the grid, the editor and PNG exports, so every surface shows
+ * the same creative.
+ */
+
+export const AD_SIZE: Record<AdRatio, { w: number; h: number }> = {
+ "1:1": { w: 1080, h: 1080 },
+ "4:5": { w: 1080, h: 1350 },
+ "9:16": { w: 1080, h: 1920 },
+};
+
+export type AdLayout = "overlay" | "panel" | "band" | "frame";
+
+export const AD_LAYOUTS: { id: AdLayout; name: string; hint: string }[] = [
+ { id: "overlay", name: "Overlay", hint: "Full-bleed picture, text over a soft shade" },
+ { id: "panel", name: "Panel", hint: "Picture on top, a colour panel for the words" },
+ { id: "band", name: "Band", hint: "A bold brand-colour band with the headline" },
+ { id: "frame", name: "Frame", hint: "Editorial: the picture framed on paper" },
+];
+
+/** A sensible layout per format when the creative hasn't picked one. */
+export const defaultLayout = (ratio: AdRatio, seed = 0): AdLayout => (ratio === "9:16" ? (seed % 3 === 2 ? "frame" : "panel") : (["overlay", "overlay", "band", "frame"] as AdLayout[])[seed % 4]);
+
+/** Width of `text` set in `font` (a CSS font string), in px. The canvas provides it in the browser. */
+export type Measure = (text: string, font: string) => number;
+
+export interface AdTheme {
+ accent: string;
+ onAccent: string;
+ ink: string;
+ paper: string;
+ heading: string;
+ body: string;
+}
+
+export interface AdContent {
+ headline: string;
+ body?: string;
+ cta?: string;
+ /** Shown when there's no logo. */
+ brand?: string;
+}
+
+export interface TextBox {
+ lines: string[];
+ x: number;
+ /** Top of the first line. */
+ y: number;
+ size: number;
+ lineHeight: number;
+ font: string;
+ color: string;
+ align: "left" | "center";
+ width: number;
+}
+
+export interface Rect {
+ x: number;
+ y: number;
+ w: number;
+ h: number;
+}
+
+export interface AdPlan {
+ w: number;
+ h: number;
+ bg: string;
+ /** Where the visual goes and the part of it that's shown (cover crop). */
+ image: (Rect & { sx: number; sy: number; sw: number; sh: number; radius: number }) | null;
+ scrim?: Rect & { from: string; to: string };
+ panel?: Rect & { color: string };
+ logo?: Rect;
+ brand?: TextBox;
+ headline: TextBox;
+ body?: TextBox;
+ cta?: Rect & { radius: number; color: string; text: TextBox };
+}
+
+// ---------------------------------------------------------------------------
+// Colour
+
+function rgb(hex: string): [number, number, number] {
+ const h = hex.replace("#", "");
+ const full = h.length === 3 ? [...h].map((c) => c + c).join("") : h.padEnd(6, "0");
+ return [0, 2, 4].map((i) => parseInt(full.slice(i, i + 2), 16)) as [number, number, number];
+}
+
+/** WCAG relative luminance. */
+export function luminance(hex: string): number {
+ const [r, g, b] = rgb(hex).map((v) => {
+ const c = v / 255;
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
+ });
+ return 0.2126 * r + 0.7152 * g + 0.0722 * b;
+}
+
+export function contrast(a: string, b: string): number {
+ const [x, y] = [luminance(a), luminance(b)].sort((p, q) => q - p);
+ return (x + 0.05) / (y + 0.05);
+}
+
+/** White or near-black text, whichever reads better on `bg`. */
+export const readableOn = (bg: string) => (contrast(bg, "#ffffff") >= contrast(bg, "#141414") ? "#ffffff" : "#141414");
+
+function saturation(hex: string): number {
+ const [r, g, b] = rgb(hex).map((v) => v / 255);
+ const max = Math.max(r, g, b);
+ const min = Math.min(r, g, b);
+ const l = (max + min) / 2;
+ return max === min ? 0 : (max - min) / (1 - Math.abs(2 * l - 1));
+}
+
+const SERIF = /serif|playfair|garamond|didot|bodoni|cormorant|lora|baskerville|fraunces|merriweather|libre caslon|dm serif|crimson|georgia|times/i;
+export const fallbackFor = (family: string) => (SERIF.test(family) && !/sans/i.test(family) ? "Georgia, serif" : "system-ui, sans-serif");
+
+/** The ad theme from a brand kit: its most colourful colour as the accent, its darkest/lightest as ink/paper. */
+export function themeFrom(kit: { colors?: string[]; fonts?: { heading?: string; body?: string } } | null | undefined): AdTheme {
+ const colors = (kit?.colors ?? []).filter((c) => /^#[0-9a-f]{6}$/i.test(c));
+ const accent = colors.find((c) => saturation(c) > 0.3 && luminance(c) > 0.03 && luminance(c) < 0.8) ?? colors[0] ?? "#5d4bdb";
+ const dark = [...colors].sort((a, b) => luminance(a) - luminance(b))[0];
+ const light = [...colors].sort((a, b) => luminance(b) - luminance(a))[0];
+ return {
+ accent,
+ onAccent: readableOn(accent),
+ ink: dark && luminance(dark) < 0.06 ? dark : "#141414",
+ paper: light && luminance(light) > 0.8 ? light : "#ffffff",
+ heading: kit?.fonts?.heading || "Inter",
+ body: kit?.fonts?.body || kit?.fonts?.heading || "Inter",
+ };
+}
+
+export const fontString = (family: string, size: number, weight = 400) => `${weight} ${Math.round(size)}px "${family.replace(/"/g, "")}", ${fallbackFor(family)}`;
+
+// ---------------------------------------------------------------------------
+// Geometry
+
+/** The part of an image that fills a box without distortion, centred on `focus` (0–1). */
+export function coverCrop(iw: number, ih: number, bw: number, bh: number, focus = { x: 0.5, y: 0.45 }) {
+ const scale = Math.max(bw / iw, bh / ih);
+ const sw = Math.min(iw, bw / scale);
+ const sh = Math.min(ih, bh / scale);
+ const clamp = (v: number, max: number) => Math.max(0, Math.min(max, v));
+ return { sx: clamp(focus.x * iw - sw / 2, iw - sw), sy: clamp(focus.y * ih - sh / 2, ih - sh), sw, sh };
+}
+
+/** A box that fits `w×h` inside `box` keeping its shape, aligned left/top (or centred). */
+export function containIn(w: number, h: number, box: Rect, align: "left" | "center" = "left"): Rect {
+ const s = Math.min(box.w / w, box.h / h);
+ const fw = w * s;
+ const fh = h * s;
+ return { x: align === "center" ? box.x + (box.w - fw) / 2 : box.x, y: box.y + (box.h - fh) / 2, w: fw, h: fh };
+}
+
+/** Greedy word wrap; a word longer than the line is broken by characters. */
+export function wrapText(text: string, width: number, font: string, measure: Measure): string[] {
+ const words = text.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
+ const lines: string[] = [];
+ let line = "";
+ for (const word of words) {
+ const tryLine = line ? `${line} ${word}` : word;
+ if (measure(tryLine, font) <= width) {
+ line = tryLine;
+ continue;
+ }
+ if (line) lines.push(line);
+ if (measure(word, font) <= width) {
+ line = word;
+ continue;
+ }
+ // Break an over-long word.
+ let piece = "";
+ for (const ch of word) {
+ if (measure(piece + ch, font) > width && piece) {
+ lines.push(piece);
+ piece = ch;
+ } else piece += ch;
+ }
+ line = piece;
+ }
+ if (line) lines.push(line);
+ return lines;
+}
+
+/**
+ * The largest size (from max down to min, in 6% steps) at which `text` fits in `maxLines` lines of
+ * `width`. At the smallest size the last line ends with "…" if the text still doesn't fit.
+ */
+export function fitText(text: string, width: number, maxLines: number, family: string, weight: number, max: number, min: number, measure: Measure): { size: number; lines: string[] } {
+ let size = max;
+ for (;;) {
+ const font = fontString(family, size, weight);
+ const lines = wrapText(text, width, font, measure);
+ if (lines.length <= maxLines) return { size, lines };
+ if (size <= min) {
+ const kept = lines.slice(0, maxLines);
+ let last = kept[maxLines - 1];
+ while (last && measure(`${last}…`, font) > width) last = last.slice(0, -1).trimEnd();
+ kept[maxLines - 1] = `${last}…`;
+ return { size, lines: kept };
+ }
+ size = Math.max(min, size * 0.94);
+ }
+}
+
+const textBox = (t: { size: number; lines: string[] }, x: number, y: number, family: string, weight: number, color: string, align: "left" | "center", width: number, lh = 1.12): TextBox => ({
+ lines: t.lines,
+ x,
+ y,
+ size: t.size,
+ lineHeight: t.size * lh,
+ font: fontString(family, t.size, weight),
+ color,
+ align,
+ width,
+});
+
+const heightOf = (b: TextBox | undefined) => (b ? b.lines.length * b.lineHeight : 0);
+
+// ---------------------------------------------------------------------------
+// The plan
+
+export interface PlanInput {
+ ratio: AdRatio;
+ layout: AdLayout;
+ content: AdContent;
+ theme: AdTheme;
+ /** The visual's pixel size (null: no visual yet). */
+ image: { w: number; h: number } | null;
+ logo?: { w: number; h: number } | null;
+ measure: Measure;
+}
+
+/** Lay out one creative. Every box stays inside the canvas; text shrinks before it overflows. */
+export function planAd(p: PlanInput): AdPlan {
+ const { w: W, h: H } = AD_SIZE[p.ratio];
+ const m = Math.round(W * 0.07);
+ const tall = p.ratio === "9:16";
+ const t = p.theme;
+ const inner = W - 2 * m;
+
+ // Copy blocks are measured first, then stacked from the bottom of their region.
+ const headlineMax = W * (tall ? 0.1 : 0.088);
+ const fitHeadline = (width: number, lines: number, max = headlineMax) => fitText(p.content.headline || " ", width, lines, t.heading, 800, max, W * 0.042, p.measure);
+ const fitBody = (width: number) => (p.content.body?.trim() ? fitText(p.content.body, width, tall ? 4 : 3, t.body, 400, W * 0.034, W * 0.026, p.measure) : null);
+ const ctaBox = (x: number, bottom: number, color: string, onColor: string, align: "left" | "center"): AdPlan["cta"] => {
+ if (!p.content.cta?.trim()) return undefined;
+ const size = W * 0.032;
+ const label = fitText(p.content.cta.trim(), inner - size * 2.4, 1, t.body, 700, size, W * 0.024, p.measure);
+ const tw = p.measure(label.lines[0], fontString(t.body, label.size, 700));
+ const bw = Math.min(inner, tw + label.size * 2.4);
+ const bh = label.size * 2.3;
+ const bx = align === "center" ? (W - bw) / 2 : x;
+ return {
+ x: bx,
+ y: bottom - bh,
+ w: bw,
+ h: bh,
+ radius: bh / 2,
+ color,
+ text: textBox(label, bx + bw / 2, bottom - bh + (bh - label.size * 1.12) / 2, t.body, 700, onColor, "center", bw),
+ };
+ };
+ const logoRect = (x: number, y: number, maxW: number, maxH: number, align: "left" | "center" = "left"): Rect | undefined =>
+ p.logo ? containIn(p.logo.w, p.logo.h, { x, y, w: maxW, h: maxH }, align) : undefined;
+ const brandText = (x: number, y: number, color: string, align: "left" | "center"): TextBox | undefined =>
+ !p.logo && p.content.brand?.trim() ? textBox(fitText(p.content.brand.trim().toUpperCase(), inner * 0.6, 1, t.body, 700, W * 0.03, W * 0.022, p.measure), x, y, t.body, 700, color, align, inner * 0.6, 1.1) : undefined;
+ const image = (r: Rect, radius = 0): AdPlan["image"] => (p.image ? { ...r, ...coverCrop(p.image.w, p.image.h, r.w, r.h), radius } : null);
+
+ if (p.layout === "panel" || p.layout === "frame") {
+ const framed = p.layout === "frame";
+ // Frame: the picture on the brand's paper; panel: the words on a brand-colour panel.
+ const bg = framed ? t.paper : t.accent;
+ const ink = framed ? (readableOn(bg) === "#ffffff" ? "#ffffff" : t.ink) : t.onAccent;
+ const imgH = Math.round(H * (tall ? 0.56 : p.ratio === "4:5" ? 0.58 : 0.54));
+ const imgRect = framed ? { x: m, y: m * 1.9, w: W - 2 * m, h: imgH - m * 1.4 } : { x: 0, y: 0, w: W, h: imgH };
+ const top = imgRect.y + imgRect.h + m * 0.8;
+ const bottom = H - m;
+ const cta = framed ? ctaBox(m, bottom, t.accent, t.onAccent, "left") : ctaBox(m, bottom, t.paper, readableOn(t.paper) === "#ffffff" ? "#ffffff" : t.ink, "left");
+ const body = fitBody(inner);
+ const gap = m * 0.4;
+ let head = fitHeadline(inner, tall ? 3 : 2);
+ const room = (cta ? bottom - cta.h - gap : bottom) - top - (body ? body.lines.length * body.size * 1.32 + gap : 0);
+ while (head.lines.length * head.size * 1.08 > room && head.size > W * 0.042) head = fitHeadline(inner, tall ? 3 : 2, head.size * 0.92);
+ const headline = textBox(head, m, top, t.heading, 800, ink, "left", inner, 1.08);
+ const bodyBox = body ? textBox(body, m, top + heightOf(headline) + gap, t.body, 400, ink, "left", inner, 1.32) : undefined;
+ return {
+ w: W,
+ h: H,
+ bg,
+ image: image(imgRect, framed ? W * 0.025 : 0),
+ panel: framed ? undefined : { x: 0, y: imgH, w: W, h: H - imgH, color: bg },
+ logo: framed ? logoRect(m, m * 0.55, W * 0.32, m * 0.95) : logoRect(m, m * 0.7, W * 0.3, H * 0.055),
+ brand: framed ? brandText(m, m * 0.75, ink, "left") : undefined,
+ headline,
+ body: bodyBox,
+ cta,
+ };
+ }
+
+ if (p.layout === "band") {
+ const bandH = Math.round(H * (tall ? 0.24 : 0.27));
+ const head = fitHeadline(inner, 2, W * 0.08);
+ const headline = textBox(head, W / 2, (bandH - head.lines.length * head.size * 1.08) / 2 + m * 0.25, t.heading, 800, t.onAccent, "center", inner, 1.08);
+ const bottom = H - m;
+ const cta = ctaBox(m, bottom, t.paper, readableOn(t.paper) === "#ffffff" ? "#ffffff" : t.ink, "center");
+ const body = fitBody(inner);
+ const bodyBox = body ? textBox(body, W / 2, (cta ? cta.y : bottom) - m * 0.45 - body.lines.length * body.size * 1.32, t.body, 600, "#ffffff", "center", inner, 1.32) : undefined;
+ return {
+ w: W,
+ h: H,
+ bg: t.accent,
+ image: image({ x: 0, y: bandH, w: W, h: H - bandH }),
+ panel: { x: 0, y: 0, w: W, h: bandH, color: t.accent },
+ scrim: bodyBox || cta ? { x: 0, y: H * 0.62, w: W, h: H * 0.38, from: "rgba(0,0,0,0)", to: "rgba(0,0,0,0.62)" } : undefined,
+ logo: logoRect(W / 2 - W * 0.13, bandH - m * 0.2 - Math.min(m * 0.5, bandH * 0.18), W * 0.26, Math.min(m * 0.5, bandH * 0.18), "center"),
+ headline,
+ body: bodyBox,
+ cta,
+ };
+ }
+
+ // Overlay: the visual fills the canvas; the words sit on a shade at the bottom.
+ const bottom = H - m;
+ const cta = ctaBox(m, bottom, t.accent, t.onAccent, "left");
+ const body = fitBody(inner);
+ const gap = m * 0.38;
+ const head = fitHeadline(inner, 3);
+ const bodyTop = (cta ? cta.y - gap : bottom) - (body ? body.lines.length * body.size * 1.32 : 0);
+ const bodyBox = body ? textBox(body, m, bodyTop, t.body, 500, "rgba(255,255,255,0.9)", "left", inner, 1.32) : undefined;
+ const headTop = (bodyBox ? bodyTop - gap : cta ? cta.y - gap : bottom) - head.lines.length * head.size * 1.06;
+ const headline = textBox(head, m, Math.max(H * 0.3, headTop), t.heading, 800, "#ffffff", "left", inner, 1.06);
+ return {
+ w: W,
+ h: H,
+ bg: t.ink,
+ image: image({ x: 0, y: 0, w: W, h: H }),
+ scrim: { x: 0, y: Math.min(headline.y - m * 1.2, H * 0.45), w: W, h: H - Math.min(headline.y - m * 1.2, H * 0.45), from: "rgba(0,0,0,0)", to: "rgba(0,0,0,0.74)" },
+ logo: logoRect(m, m * 0.8, W * 0.3, H * 0.06),
+ brand: brandText(m, m * 0.8, "#ffffff", "left"),
+ headline,
+ body: bodyBox,
+ cta,
+ };
+}
+
+/** Every drawn box of a plan (tests check they stay inside the canvas). */
+export function planRects(plan: AdPlan): Rect[] {
+ const tb = (b?: TextBox): Rect | null =>
+ b ? { x: b.align === "center" ? b.x - b.width / 2 : b.x, y: b.y, w: b.width, h: b.lines.length * b.lineHeight } : null;
+ return [plan.image, plan.panel, plan.scrim, plan.logo, tb(plan.brand), tb(plan.headline), tb(plan.body), plan.cta].filter((r): r is Rect => !!r);
+}
+
+/** File name for an exported creative: "acme-serum-4x5-3.png". */
+export function exportName(brand: string, product: string | undefined, ratio: AdRatio, n: number): string {
+ const slug = (s: string) =>
+ s
+ .toLowerCase()
+ .normalize("NFKD")
+ .replace(/[^\w\s-]/g, "")
+ .trim()
+ .replace(/[\s_]+/g, "-")
+ .slice(0, 40);
+ return `${[slug(brand), product && slug(product)].filter(Boolean).join("-") || "ad"}-${ratio.replace(":", "x")}-${n}.png`;
+}
diff --git a/src/lib/catalog/marketing.ts b/src/lib/catalog/marketing.ts
new file mode 100644
index 00000000..cabd402e
--- /dev/null
+++ b/src/lib/catalog/marketing.ts
@@ -0,0 +1,871 @@
+import type { Engine, Generation } from "./types";
+
+/**
+ * Marketing Studio, Ads Studio, Ad Multiplier and Click to Ad: the shared catalog (formats,
+ * Fuobe's own templates, UGC hooks and settings, Click-to-Ad styles, ad angles) and the pure
+ * planning helpers the client (live blockers, prices) and the server (pipelines) both use.
+ *
+ * Structure follows docs/research/higgsfield-marketing-agents.md §1–§4 (categories → formats →
+ * capabilities). Template names, prompts and previews are Fuobe's own; no Higgsfield covers.
+ */
+
+// ---------------------------------------------------------------------------
+// Brand kits and products (shared by every marketing flow)
+
+export interface BrandFonts {
+ /** Google Fonts family names (or any installed family), e.g. "Playfair Display". */
+ heading?: string;
+ body?: string;
+}
+
+export interface BrandSocial {
+ network: string;
+ url: string;
+}
+
+export interface BrandKitFields {
+ name: string;
+ website?: string;
+ /** /api/files/… URL. */
+ logo?: string;
+ tagline?: string;
+ overview?: string;
+ /** Hex colours, the main one first. */
+ colors: string[];
+ fonts: BrandFonts;
+ values: string[];
+ aesthetics: string[];
+ tone: string[];
+ audience?: string;
+ sellingPoints: string[];
+ competitors: string[];
+ socials: BrandSocial[];
+ language?: string;
+ /** /api/files/… URLs. */
+ images: string[];
+ /** Free-form "Detail" entries. */
+ details: string[];
+}
+
+export type BrandStatus = "researching" | "ready" | "failed" | "canceled";
+
+export interface BrandProgress {
+ /** Index into RESEARCH_LABELS. */
+ index: number;
+ total: number;
+ label: string;
+ startedAt: number;
+}
+
+export interface BrandKit extends BrandKitFields {
+ id: string;
+ status: BrandStatus;
+ progress?: BrandProgress | null;
+ /** What the research couldn't do ("We couldn't read the site…"), shown on the review step. */
+ note?: string | null;
+ error?: string | null;
+ source: "website" | "manual";
+ productCount?: number;
+ /** Ads made for this brand (Ads Studio shelf). */
+ adCount?: number;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface Product {
+ id: string;
+ brandId: string | null;
+ name: string;
+ description?: string;
+ price?: number | null;
+ currency?: string | null;
+ audience?: string;
+ sellingPoints: string[];
+ url?: string;
+ /** /api/files/… URLs, the hero first. */
+ images: string[];
+ createdAt: number;
+ updatedAt: number;
+}
+
+export const MAX_SELLING_POINTS = 5;
+export const MAX_PRODUCT_IMAGES = 8;
+
+/** Ads Studio's rotating research labels (Higgsfield's 14, in their order). */
+export const RESEARCH_LABELS = [
+ "Reading your website",
+ "Determining the name of your brand",
+ "Distilling your primary colours",
+ "Tuning in to your tone of voice",
+ "Decoding your aesthetics",
+ "Stalking your competitors",
+ "Sharpening your selling points",
+ "Profiling your audience",
+ "Scrolling through your socials",
+ "Unearthing your values",
+ "Gathering brand details",
+ "Preparing your brand images",
+ "Building your brand kit",
+ "Finding your products",
+] as const;
+
+/** Labels the client cycles through while the server sits in the LLM stage (it can take a while). */
+export const LLM_STAGE = { from: 3, to: 10 } as const;
+
+/**
+ * The label to show: the server's own step, except during the writing stage, where the labels
+ * from LLM_STAGE rotate every `every` ms so a slow LLM still reads as progress.
+ */
+export function researchLabel(p: Pick<BrandProgress, "index" | "startedAt"> | null | undefined, now: number, every = 2200): { index: number; label: string } {
+ if (!p) return { index: 0, label: RESEARCH_LABELS[0] };
+ if (p.index < LLM_STAGE.from || p.index > LLM_STAGE.to) return { index: p.index, label: RESEARCH_LABELS[Math.min(p.index, RESEARCH_LABELS.length - 1)] };
+ const span = LLM_STAGE.to - p.index + 1;
+ const i = p.index + (Math.floor(Math.max(0, now - p.startedAt) / every) % span);
+ return { index: i, label: RESEARCH_LABELS[i] };
+}
+
+/** Click to Ad's product-kit labels. */
+export const KIT_LABELS = ["Connecting to website", "Extracting product images", "Finding brand colors", "Locating logo", "Processing details", "Finalizing product kit"] as const;
+
+/** "Describe your business" examples for a manual brand kit (Fuobe's own). */
+export const BRAND_EXAMPLES: { label: string; text: string }[] = [
+ { label: "Food & Beverage", text: "Ember & Oat — small-batch granola and nut butters, roasted in Portland and sold online and at farmers' markets to busy people who still read labels." },
+ { label: "Home & Lifestyle", text: "Hollow Pine — hand-poured soy candles and linen sprays that smell like a cabin weekend, for renters who want a cozy home on a budget." },
+ { label: "Fashion", text: "Studio Marlow — relaxed tailoring in deadstock fabrics, made in limited runs for women who want one great blazer instead of five okay ones." },
+ { label: "Beauty & Skincare", text: "Dew Theory — fragrance-free barrier creams for sensitive and reactive skin, developed with dermatologists and sold direct online." },
+ { label: "Digital Services", text: "Northbound — a two-person studio that designs and builds fast marketing sites for seed-stage SaaS teams in four weeks." },
+];
+
+/** Brand kit languages (as Higgsfield lists them). */
+export const BRAND_LANGUAGES = [
+ "Arabic", "Chinese", "Czech", "Danish", "Dutch", "English", "Finnish", "French", "German", "Greek", "Hebrew", "Hindi", "Hungarian", "Indonesian",
+ "Italian", "Japanese", "Kazakh", "Korean", "Norwegian", "Polish", "Portuguese", "Romanian", "Russian", "Spanish", "Swedish", "Thai", "Turkish",
+ "Ukrainian", "Vietnamese",
+];
+
+export const SOCIAL_NETWORKS = ["Instagram", "TikTok", "YouTube", "Facebook", "LinkedIn", "Pinterest", "X", "Threads", "Snapchat", "Telegram", "Discord"];
+
+export function emptyKit(name = ""): BrandKitFields {
+ return { name, colors: [], fonts: {}, values: [], aesthetics: [], tone: [], sellingPoints: [], competitors: [], socials: [], images: [], details: [] };
+}
+
+const HEX = /^#[0-9a-f]{6}$/i;
+export const isHex = (s: string) => HEX.test(s);
+
+/** One sentence about the brand for image prompts (name, look, palette), kept short. */
+export function brandLine(kit: Pick<BrandKitFields, "name" | "tagline" | "aesthetics" | "colors" | "tone"> | null | undefined): string {
+ if (!kit?.name) return "";
+ const look = kit.aesthetics.slice(0, 3).join(", ");
+ const colors = kit.colors.filter(isHex).slice(0, 4);
+ return [
+ `Brand: ${kit.name}${kit.tagline ? ` (“${kit.tagline}”)` : ""}`,
+ look && `look and feel: ${look}`,
+ colors.length && `brand colours ${colors.join(", ")}`,
+ ]
+ .filter(Boolean)
+ .join("; ");
+}
+
+// ---------------------------------------------------------------------------
+// Marketing Studio: categories → formats → capabilities
+
+export type MarketingCategory = "product-shot" | "motion" | "ugc" | "tiktok" | "ads" | "posters" | "marketplace";
+
+export const CATEGORIES: { id: MarketingCategory | "all"; label: string }[] = [
+ { id: "all", label: "All" },
+ { id: "product-shot", label: "Product shot" },
+ { id: "motion", label: "Motion" },
+ { id: "ugc", label: "UGC" },
+ { id: "tiktok", label: "TikTok" },
+ { id: "ads", label: "Ads" },
+ { id: "posters", label: "Posters" },
+ { id: "marketplace", label: "Marketplace" },
+];
+
+export type FormatId =
+ | "product-standalone"
+ | "product-with-model"
+ | "motion-2d"
+ | "motion-hyper"
+ | "motion-mixed"
+ | "motion-saas"
+ | "ugc-talking"
+ | "tiktok"
+ | "ads"
+ | "poster"
+ | "marketplace";
+
+export type Need = "required" | "optional" | "none";
+export type Pipeline = "image" | "motion" | "ugc";
+
+export interface FormatDef {
+ id: FormatId;
+ category: MarketingCategory;
+ name: string;
+ kind: "image" | "video";
+ /** The chip on template cards. */
+ cardLabel: string;
+ product: Need;
+ avatar: Need;
+ /** At least one of these must be given. */
+ oneOf?: ("product" | "avatar" | "prompt" | "website")[];
+ hookAndSetting?: boolean;
+ durations?: { min: number; max: number; default: number };
+ aspectRatios: string[];
+ defaultAspect: string;
+ /** Most results per run. */
+ batch: number;
+ brandKit: boolean;
+ /** Exact on-image text (headline, CTA): in the prompt on cloud models, drawn on top for open ones. */
+ text?: boolean;
+ pipeline: Pipeline;
+ promptPlaceholder: string;
+}
+
+const VIDEO_RATIOS = ["9:16", "1:1", "3:4", "4:3", "16:9", "21:9"];
+const SHOT_RATIOS = ["1:1", "3:2", "2:3", "4:3", "3:4", "4:5", "5:4", "9:16", "16:9", "21:9"];
+
+export const FORMATS: Record<FormatId, FormatDef> = {
+ "product-standalone": {
+ id: "product-standalone", category: "product-shot", name: "Standalone", kind: "image", cardLabel: "Product shot",
+ product: "required", avatar: "none", aspectRatios: SHOT_RATIOS, defaultAspect: "3:4", batch: 4, brandKit: true, pipeline: "image",
+ promptPlaceholder: "Describe your edit, e.g. “add a few coffee beans around it”",
+ },
+ "product-with-model": {
+ id: "product-with-model", category: "product-shot", name: "With model", kind: "image", cardLabel: "Product shot",
+ product: "optional", avatar: "optional", oneOf: ["product", "avatar"], aspectRatios: ["1:1", "3:2", "2:3", "4:3", "3:4", "9:16", "16:9"], defaultAspect: "3:4",
+ batch: 4, brandKit: false, pipeline: "image", promptPlaceholder: "What should look different? e.g. “she's laughing, wind in her hair”",
+ },
+ "motion-2d": {
+ id: "motion-2d", category: "motion", name: "2D product motion", kind: "video", cardLabel: "Product motion",
+ product: "required", avatar: "none", durations: { min: 5, max: 15, default: 5 }, aspectRatios: VIDEO_RATIOS, defaultAspect: "9:16", batch: 4,
+ brandKit: true, pipeline: "motion", promptPlaceholder: "What do you want to change? e.g. “use our mint green”",
+ },
+ "motion-hyper": {
+ id: "motion-hyper", category: "motion", name: "Hypermotion", kind: "video", cardLabel: "Product motion",
+ product: "required", avatar: "none", durations: { min: 5, max: 15, default: 10 }, aspectRatios: VIDEO_RATIOS, defaultAspect: "9:16", batch: 4,
+ brandKit: true, pipeline: "motion", promptPlaceholder: "Describe the scene you imagine…",
+ },
+ "motion-mixed": {
+ id: "motion-mixed", category: "motion", name: "Mixed media", kind: "video", cardLabel: "Product motion",
+ product: "required", avatar: "none", durations: { min: 5, max: 15, default: 10 }, aspectRatios: VIDEO_RATIOS, defaultAspect: "9:16", batch: 4,
+ brandKit: true, pipeline: "motion", promptPlaceholder: "Describe the scene you imagine…",
+ },
+ "motion-saas": {
+ id: "motion-saas", category: "motion", name: "SaaS", kind: "video", cardLabel: "Product motion",
+ product: "optional", avatar: "none", oneOf: ["prompt", "product", "website"], durations: { min: 5, max: 15, default: 5 }, aspectRatios: VIDEO_RATIOS,
+ defaultAspect: "16:9", batch: 4, brandKit: true, pipeline: "motion", promptPlaceholder: "What does your app do? e.g. “invoices that chase themselves”",
+ },
+ "ugc-talking": {
+ id: "ugc-talking", category: "ugc", name: "Talking head", kind: "video", cardLabel: "UGC video",
+ product: "optional", avatar: "optional", hookAndSetting: true, durations: { min: 10, max: 30, default: 15 }, aspectRatios: ["9:16", "1:1", "3:4", "16:9"],
+ defaultAspect: "9:16", batch: 2, brandKit: true, pipeline: "ugc", promptPlaceholder: "What should they say? e.g. “it saved my 7 a.m. meetings”",
+ },
+ tiktok: {
+ id: "tiktok", category: "tiktok", name: "TikTok", kind: "video", cardLabel: "TikTok",
+ product: "optional", avatar: "optional", hookAndSetting: true, durations: { min: 8, max: 15, default: 12 }, aspectRatios: ["9:16"], defaultAspect: "9:16",
+ batch: 2, brandKit: true, pipeline: "ugc", promptPlaceholder: "The angle, e.g. “a hack nobody tells you about”",
+ },
+ ads: {
+ id: "ads", category: "ads", name: "Ads", kind: "image", cardLabel: "Ads",
+ product: "required", avatar: "optional", aspectRatios: ["1:1", "4:5", "9:16", "3:4", "4:3", "16:9"], defaultAspect: "4:5", batch: 4, brandKit: true, text: true,
+ pipeline: "image", promptPlaceholder: "Notes for the ad, e.g. “winter sale, 20% off”",
+ },
+ poster: {
+ id: "poster", category: "posters", name: "Poster", kind: "image", cardLabel: "Poster",
+ product: "optional", avatar: "none", oneOf: ["prompt", "product"], aspectRatios: ["3:4", "2:3", "4:5", "1:1", "9:16"], defaultAspect: "3:4", batch: 4, brandKit: true,
+ text: true, pipeline: "image", promptPlaceholder: "Describe the poster you want to create.",
+ },
+ marketplace: {
+ id: "marketplace", category: "marketplace", name: "Marketplace", kind: "image", cardLabel: "Marketplace",
+ product: "required", avatar: "optional", aspectRatios: ["1:1", "3:4", "4:5", "2:3", "4:3", "16:9"], defaultAspect: "1:1", batch: 4, brandKit: true, text: true,
+ pipeline: "image", promptPlaceholder: "Key facts to call out, e.g. “500 ml · BPA-free · dishwasher safe”",
+ },
+};
+
+export const MAX_PROMPT = 5000;
+
+// ---------------------------------------------------------------------------
+// Templates (Fuobe's own set; procedural previews)
+
+/** What the procedural card draws. */
+export type PreviewScene =
+ | "pedestal" | "flatlay" | "splash" | "float" | "ice" | "shadow" | "blocks" | "nature" | "studio" | "water" | "shelf" | "noir" | "picnic" | "citrus"
+ | "model" | "orbit" | "kinetic" | "collage" | "cards" | "selfie" | "split" | "headline" | "type" | "listing" | "badge" | "burst" | "stars";
+
+export interface TemplateLook {
+ scene: PreviewScene;
+ hue: number;
+ /** Second hue for gradients and props. */
+ hue2?: number;
+ /** Dark backdrop. */
+ dark?: boolean;
+}
+
+export interface MarketingTemplate {
+ id: string;
+ name: string;
+ format: FormatId;
+ /** The scene or motion, written as an image/video prompt. */
+ prompt: string;
+ aspect?: string;
+ duration?: number;
+ look: TemplateLook;
+ /** A built-in UGC hook. */
+ hook?: string;
+ setting?: string;
+ /** Default on-image headline ("{product}" and "{brand}" fill in). */
+ headline?: string;
+ cta?: string;
+}
+
+const t = (id: string, name: string, format: FormatId, look: TemplateLook, prompt: string, extra: Partial<MarketingTemplate> = {}): MarketingTemplate => ({
+ id,
+ name,
+ format,
+ look,
+ prompt,
+ ...extra,
+});
+
+export const TEMPLATES: MarketingTemplate[] = [
+ // Product shot · standalone
+ t("ps-sunlit-plinth", "Sunlit Plinth", "product-standalone", { scene: "pedestal", hue: 55, hue2: 35 }, "The product stands on a travertine plinth against a warm plaster wall; low morning sun rakes across from the left and throws a long, crisp shadow; quiet, premium, lots of negative space"),
+ t("ps-ice-bath", "Ice Bath", "product-standalone", { scene: "ice", hue: 220, hue2: 200 }, "The product is half buried in crushed ice with frost and cold droplets on its surface, cool blue rim light, shallow depth of field, refreshing and crisp"),
+ t("ps-citrus-burst", "Citrus Burst", "product-standalone", { scene: "citrus", hue: 85, hue2: 55 }, "The product surrounded by halved lemons, oranges and grapefruit on a saturated yellow backdrop, hard on-camera flash, bold summer energy"),
+ t("ps-floating-trio", "Floating Trio", "product-standalone", { scene: "float", hue: 300, hue2: 260 }, "Three copies of the product float at different angles in a soft pastel void, each with its own gentle shadow below, playful and weightless"),
+ t("ps-linen-flatlay", "Linen Flat Lay", "product-standalone", { scene: "flatlay", hue: 40, hue2: 25 }, "Overhead flat lay of the product on wrinkled oatmeal linen with dried flowers, a ceramic dish and a sprig of eucalyptus, soft diffused daylight"),
+ t("ps-splash-crown", "Splash Crown", "product-standalone", { scene: "splash", hue: 210, hue2: 190, dark: true }, "A crown of clear liquid splashes up around the product, frozen at 1/8000 s, droplets glinting against a deep backdrop, high-speed studio flash"),
+ t("ps-palm-shadow", "Palm Shadow", "product-standalone", { scene: "shadow", hue: 45, hue2: 140 }, "The product sits on a sunlit ledge while palm-leaf shadows fall across it and the warm wall behind, holiday afternoon light"),
+ t("ps-color-block", "Color Block", "product-standalone", { scene: "blocks", hue: 15, hue2: 200 }, "The product balanced on stacked geometric blocks in two bold complementary colours, clean studio light, graphic and modern"),
+ t("ps-moss-stone", "Moss & Stone", "product-standalone", { scene: "nature", hue: 135, hue2: 100 }, "The product nestled on moss and smooth river stones, soft forest light filtering through mist, earthy and natural"),
+ t("ps-studio-white", "Studio White", "product-standalone", { scene: "studio", hue: 250, hue2: 250 }, "Clean e-commerce packshot on a seamless white sweep, large soft boxes, a subtle floor reflection, true-to-life colour"),
+ t("ps-golden-ripple", "Golden Ripple", "product-standalone", { scene: "water", hue: 50, hue2: 25 }, "The product stands in a shallow pool of still water with soft ripples and a mirror reflection, golden-hour backlight"),
+ t("ps-bathroom-shelf", "Bathroom Shelf", "product-standalone", { scene: "shelf", hue: 175, hue2: 200 }, "The product on a tiled bathroom shelf next to everyday items, soft window light, real and lived-in, slightly from below"),
+ t("ps-midnight-gloss", "Midnight Gloss", "product-standalone", { scene: "noir", hue: 270, hue2: 300, dark: true }, "The product on glossy black acrylic with a sharp rim light and a long reflection, deep shadows, luxurious and moody"),
+ t("ps-gingham-picnic", "Gingham Picnic", "product-standalone", { scene: "picnic", hue: 355, hue2: 120 }, "The product on a red gingham picnic blanket with fresh strawberries and a glass bottle, bright sunny park light, cheerful"),
+
+ // Product shot · with model
+ t("pm-mirror-selfie", "Mirror Selfie", "product-with-model", { scene: "selfie", hue: 20, hue2: 340 }, "A mirror selfie: the person holds their phone in one hand and shows the product in the other, bedroom mirror, natural morning light, candid"),
+ t("pm-golden-closeup", "Golden Close-up", "product-with-model", { scene: "model", hue: 45, hue2: 20 }, "Close-up portrait, the person holds the product near their face and smiles softly, golden-hour sun, warm skin tones, shallow depth of field"),
+ t("pm-street-style", "Street Style", "product-with-model", { scene: "model", hue: 210, hue2: 30 }, "Full-body street-style shot of the person walking across a city crosswalk with the product clearly visible, editorial fashion photography"),
+ t("pm-editorial-lounge", "Editorial Lounge", "product-with-model", { scene: "model", hue: 330, hue2: 280 }, "The person lounges on a velvet vintage sofa with the product, magazine editorial lighting, rich colours, confident pose"),
+ t("pm-morning-routine", "Morning Routine", "product-with-model", { scene: "model", hue: 190, hue2: 160 }, "The person uses the product at a bright bathroom sink during their morning routine, fresh and relaxed, soft window light"),
+ t("pm-courtside", "Courtside", "product-with-model", { scene: "model", hue: 140, hue2: 30 }, "The person in sporty clothes on a clay tennis court holds the product, harsh midday sun, athletic and upbeat"),
+ t("pm-kitchen-candid", "Kitchen Candid", "product-with-model", { scene: "model", hue: 30, hue2: 90 }, "Candid shot of the person leaning on a kitchen counter with the product, mug and fruit in the background, natural daylight"),
+ t("pm-studio-smile", "Studio Smile", "product-with-model", { scene: "model", hue: 260, hue2: 220 }, "Clean studio portrait, the person holds the product toward the camera and smiles, solid colour backdrop, soft beauty lighting"),
+
+ // Motion · 2D
+ t("m2-sticker-pop", "Sticker Pop", "motion-2d", { scene: "collage", hue: 330, hue2: 60 }, "Flat 2D animation: the product pops in as a die-cut sticker, bouncy squash and stretch, doodled stars and sparkles burst around it on a flat colour background", { duration: 5 }),
+ t("m2-paper-parade", "Paper Parade", "motion-2d", { scene: "collage", hue: 30, hue2: 200 }, "Paper cut-out animation: layered paper shapes slide in like a theatre set and the product rises from behind them, gentle stop-motion jitter", { duration: 5 }),
+ t("m2-line-reveal", "Line-Art Reveal", "motion-2d", { scene: "kinetic", hue: 160, hue2: 160 }, "A single continuous line draws the outline of the product, then the real product fills in inside it, clean minimal background", { duration: 5 }),
+ t("m2-comic-panels", "Comic Panels", "motion-2d", { scene: "split", hue: 50, hue2: 0 }, "Pop-art comic panels flip one after another, each showing the product from a new angle with halftone dots and bold outlines", { duration: 5 }),
+ t("m2-retro-starburst", "Retro Starburst", "motion-2d", { scene: "burst", hue: 25, hue2: 330 }, "A rotating retro starburst background in warm colours while the product spins slowly in the centre, groovy 70s motion graphics", { duration: 5 }),
+ t("m2-grid-shuffle", "Grid Shuffle", "motion-2d", { scene: "cards", hue: 200, hue2: 280 }, "A Swiss-style grid of colour tiles shuffles and slides; one tile opens to reveal the product, crisp geometric transitions", { duration: 5 }),
+
+ // Motion · hypermotion
+ t("mh-orbit-hero", "Orbit Hero", "motion-hyper", { scene: "orbit", hue: 230, hue2: 200, dark: true }, "Pure CGI commercial: the camera orbits the product on a dark stage as a sweeping light reveals its edges, then settles on a hero angle"),
+ t("mh-liquid-wrap", "Liquid Wrap", "motion-hyper", { scene: "splash", hue: 30, hue2: 10 }, "Ribbons of glossy liquid swirl around the product and wrap it, then fall away to reveal it spotless, macro slow motion"),
+ t("mh-exploded-view", "Exploded View", "motion-hyper", { scene: "float", hue: 190, hue2: 220, dark: true }, "The product splits into an exploded view with its parts floating apart, then snaps back together, technical and precise"),
+ t("mh-ingredient-rain", "Ingredient Rain", "motion-hyper", { scene: "citrus", hue: 95, hue2: 40 }, "The product's ingredients rain down from above in slow motion and bounce around it, bright studio light, fresh and vivid"),
+ t("mh-spotlight-spin", "Spotlight Spin", "motion-hyper", { scene: "noir", hue: 280, hue2: 320, dark: true }, "A single spotlight snaps on and the product rotates on a turntable, dust motes in the beam, dramatic theatre mood"),
+ t("mh-drop-bounce", "Drop & Bounce", "motion-hyper", { scene: "blocks", hue: 350, hue2: 50 }, "The product drops into frame, bounces once on a coloured floor with a satisfying squash, and lands on its hero angle"),
+ t("mh-slow-splash", "Slow Splash", "motion-hyper", { scene: "water", hue: 200, hue2: 180 }, "The product plunges into clear water in extreme slow motion, bubbles trail upward and light caustics dance across it"),
+ t("mh-neon-sweep", "Neon Sweep", "motion-hyper", { scene: "kinetic", hue: 300, hue2: 180, dark: true }, "Neon light bars sweep across the product in sync with a beat, reflections streak over its surface, night-club energy"),
+
+ // Motion · mixed media
+ t("mm-scrapbook-flip", "Scrapbook Flip", "motion-mixed", { scene: "collage", hue: 40, hue2: 340 }, "Mixed-media scrapbook: torn paper, tape and doodles animate around a real photo of the product as pages flip"),
+ t("mm-riso-loop", "Riso Loop", "motion-mixed", { scene: "type", hue: 350, hue2: 210 }, "Risograph-print look with grain and slight misregistration; the product cycles through two-colour duotone frames"),
+ t("mm-y2k-desktop", "Y2K Desktop", "motion-mixed", { scene: "cards", hue: 190, hue2: 300 }, "A Y2K computer desktop: pop-up windows, chrome icons and a cursor open a window that shows the product"),
+ t("mm-clay-diorama", "Clay Diorama", "motion-mixed", { scene: "pedestal", hue: 20, hue2: 140 }, "Claymation diorama: tiny clay props and a little set animate in stop motion around the real product"),
+ t("mm-halftone-collage", "Halftone Collage", "motion-mixed", { scene: "split", hue: 0, hue2: 50 }, "Halftone street-poster collage: cut-out shapes and the product slide in with punchy, rhythmic cuts"),
+
+ // Motion · SaaS
+ t("ms-feature-cards", "Feature Cards", "motion-saas", { scene: "cards", hue: 250, hue2: 200 }, "Clean SaaS motion design: rounded feature cards fly in and stack, each one highlighting a benefit, soft gradients and smooth easing", { duration: 5 }),
+ t("ms-kinetic-headline", "Kinetic Headline", "motion-saas", { scene: "kinetic", hue: 210, hue2: 260 }, "Kinetic typography: the product's promise types itself out word by word with confident motion, then resolves to the logo", { duration: 5 }),
+ t("ms-device-float", "Device Float", "motion-saas", { scene: "float", hue: 220, hue2: 170 }, "A laptop and a phone float in a soft gradient space showing the app's interface, the camera drifts slowly between them", { duration: 5 }),
+ t("ms-dashboard-zoom", "Dashboard Zoom", "motion-saas", { scene: "cards", hue: 160, hue2: 220, dark: true }, "The camera pushes into a sleek dark dashboard; charts animate up and a key number counts to its value", { duration: 5 }),
+ t("ms-logo-sting", "Logo Sting", "motion-saas", { scene: "burst", hue: 270, hue2: 210 }, "A short logo sting: geometric shapes converge and click together into the brand mark with a light flare", { duration: 5 }),
+
+ // UGC · talking head
+ t("ugc-honest-review", "Honest Review", "ugc-talking", { scene: "selfie", hue: 25, hue2: 200 }, "A relaxed, honest review straight to the phone camera: what they liked, one small catch and why they'd still buy it again", { setting: "bedroom" }),
+ t("ugc-unboxing-home", "Unboxing at Home", "ugc-talking", { scene: "selfie", hue: 35, hue2: 15 }, "They open the package at the kitchen table, pull the product out and react to it for the first time", { setting: "kitchen" }),
+ t("ugc-morning-routine", "Morning Routine", "ugc-talking", { scene: "selfie", hue: 190, hue2: 50 }, "A get-ready-with-me morning routine where the product is the step they never skip", { setting: "bathroom" }),
+ t("ugc-before-after", "Before & After", "ugc-talking", { scene: "split", hue: 140, hue2: 20 }, "They describe the problem they had before, show the product, and talk through the difference it made", { setting: "office" }),
+ t("ugc-quick-tutorial", "Quick Tutorial", "ugc-talking", { scene: "selfie", hue: 205, hue2: 160 }, "A 3-step how-to: they talk and demonstrate how they use the product at the same time", { setting: "kitchen" }),
+ t("ugc-try-on", "Try-On Haul", "ugc-talking", { scene: "selfie", hue: 320, hue2: 280 }, "A try-on haul: they show the product on, turn around for the camera and say how it fits and feels", { setting: "bedroom" }),
+ t("ugc-delivery-day", "Delivery Day", "ugc-talking", { scene: "selfie", hue: 30, hue2: 210 }, "Doorstep delivery: they pick up the parcel, open it right there and share their first impression", { setting: "street" }),
+ t("ugc-wing-review", "Sky-High Review", "ugc-talking", { scene: "selfie", hue: 205, hue2: 220 }, "A completely calm product review in an absurd place, played straight for laughs", { setting: "airplane-wing", hook: "product-hit" }),
+
+ // TikTok
+ t("tt-gadget-saved", "This Saved My Week", "tiktok", { scene: "selfie", hue: 160, hue2: 45 }, "Creator-led recommendation: “this little thing saved my week” — the problem, the product, the payoff", { setting: "office" }),
+ t("tt-secret-hack", "Secret Hack", "tiktok", { scene: "selfie", hue: 280, hue2: 50 }, "They lean in to share a clever hack with the product that most people don't know about", { setting: "kitchen" }),
+ t("tt-pov-camera", "POV Camera", "tiktok", { scene: "selfie", hue: 15, hue2: 190 }, "First-person POV: we see their hands use the product in an everyday moment while they narrate", { setting: "in-car" }),
+ t("tt-mess-to-fresh", "Mess to Fresh", "tiktok", { scene: "split", hue: 100, hue2: 190 }, "A messy situation turns fresh and tidy thanks to the product, with a satisfying reveal", { setting: "bathroom" }),
+ t("tt-couple-test", "Couple Test", "tiktok", { scene: "selfie", hue: 345, hue2: 30 }, "A couple at home tries the product together and banters about it", { setting: "bedroom" }),
+ t("tt-direct-camera", "Direct to Camera", "tiktok", { scene: "selfie", hue: 230, hue2: 15 }, "Fast, punchy talking-to-camera with jump cuts: three reasons to get the product", { setting: "street" }),
+
+ // Ads
+ t("ad-hero-headline", "Hero Headline", "ads", { scene: "headline", hue: 15, hue2: 35 }, "A bold hero ad: the product large in the centre on a rich colour field, dramatic light, space at the top for a big headline", { headline: "Meet {product}", cta: "Shop now" }),
+ t("ad-problem-solution", "Problem → Solution", "ads", { scene: "split", hue: 0, hue2: 140 }, "Split composition: the left side shows the everyday problem in muted tones, the right side shows the product solving it in bright colour", { headline: "Before: hassle. After: {product}.", cta: "Try it" }),
+ t("ad-before-after", "Before / After", "ads", { scene: "split", hue: 200, hue2: 45 }, "Clean before-and-after diptych with a thin divider, the product shown on the after side, honest natural light", { headline: "See the difference", cta: "Learn more" }),
+ t("ad-five-stars", "Five Stars", "ads", { scene: "stars", hue: 45, hue2: 25 }, "Social-proof ad: the product on a soft backdrop with room for a short customer quote and a five-star row", { headline: "“My new favourite.”", cta: "Read reviews" }),
+ t("ad-compare-switch", "Compare & Switch", "ads", { scene: "split", hue: 220, hue2: 140 }, "Side-by-side comparison: a generic alternative in grey on one side, the product glowing on the other", { headline: "Why people switch", cta: "Switch today" }),
+ t("ad-benefit-ladder", "Benefit Ladder", "ads", { scene: "listing", hue: 160, hue2: 200 }, "The product on the right with three short benefit callouts stacked on the left, tidy and clear", { headline: "3 reasons to love {product}", cta: "Shop now" }),
+ t("ad-ingredient-halo", "Ingredient Halo", "ads", { scene: "citrus", hue: 110, hue2: 60 }, "The product in the centre ringed by its key ingredients or materials arranged in a neat halo", { headline: "Only what matters", cta: "See inside" }),
+ t("ad-offer-burst", "Offer Burst", "ads", { scene: "burst", hue: 350, hue2: 45 }, "Promotional ad: the product with a bright starburst badge for the offer, energetic colour", { headline: "20% off this week", cta: "Get the deal" }),
+ t("ad-big-number", "Big Number", "ads", { scene: "type", hue: 260, hue2: 200 }, "A huge stat set in type behind the product, minimal layout, confident and modern", { headline: "10,000+ happy customers", cta: "Join them" }),
+ t("ad-dark-premium", "Dark Premium", "ads", { scene: "noir", hue: 40, hue2: 270, dark: true }, "Luxurious dark ad: the product lit like jewellery on black, thin gold accents, elegant serif headline", { headline: "{product}. Quietly exceptional.", cta: "Discover" }),
+
+ // Posters
+ t("po-swiss-grid", "Swiss Grid", "poster", { scene: "type", hue: 5, hue2: 0 }, "International Typographic Style poster: strict grid, oversized grotesk type, one bold accent colour, the product or subject cropped tight", { headline: "{brand}" }),
+ t("po-riso-bloom", "Riso Bloom", "poster", { scene: "collage", hue: 330, hue2: 190 }, "Two-colour risograph poster with grain, overprint and blooming botanical shapes", { headline: "In bloom" }),
+ t("po-giant-type", "Giant Type", "poster", { scene: "type", hue: 60, hue2: 250 }, "Poster where one giant word fills the frame edge to edge and the subject peeks through the letters", { headline: "NOW" }),
+ t("po-retro-sunburst", "Retro Sunburst", "poster", { scene: "burst", hue: 30, hue2: 10 }, "1970s travel-poster sunburst with layered warm stripes and rounded retro type", { headline: "Good days ahead" }),
+ t("po-brutalist-stack", "Brutalist Stack", "poster", { scene: "type", hue: 0, hue2: 0, dark: true }, "Neo-brutalist poster: stacked heavy type, hard black borders, raw layout, one acid accent colour", { headline: "{brand}" }),
+ t("po-botanical-gallery", "Botanical Gallery", "poster", { scene: "nature", hue: 120, hue2: 40 }, "Museum exhibition poster: a botanical illustration plate, cream paper, elegant serif headline and small caption", { headline: "{product}" }),
+ t("po-chrome-y2k", "Chrome Y2K", "poster", { scene: "kinetic", hue: 200, hue2: 300 }, "Y2K poster with liquid chrome lettering, lens flares and an iridescent gradient", { headline: "{brand}" }),
+ t("po-zine-riot", "Zine Riot", "poster", { scene: "collage", hue: 50, hue2: 350 }, "Photocopied punk zine poster: ransom-note letters, staples, tape and xerox grain", { headline: "Make some noise" }),
+
+ // Marketplace
+ t("mk-clean-listing", "Clean Listing", "marketplace", { scene: "listing", hue: 210, hue2: 210 }, "Marketplace main image: the product centred on pure white, fills 85% of the frame, soft shadow, true colour", { headline: "{product}" }),
+ t("mk-feature-callouts", "Feature Callouts", "marketplace", { scene: "listing", hue: 200, hue2: 160 }, "Listing infographic: the product with thin leader lines pointing to three key features, clean sans-serif labels", { headline: "{product}" }),
+ t("mk-dimensions", "Dimensions Card", "marketplace", { scene: "studio", hue: 220, hue2: 220 }, "Product dimensions image: the product on light grey with neat measurement lines for height and width", { headline: "Size guide" }),
+ t("mk-whats-inside", "What's in the Box", "marketplace", { scene: "flatlay", hue: 35, hue2: 210 }, "Knolling layout of everything in the box laid out at right angles around the product on a light surface", { headline: "What's in the box" }),
+ t("mk-lifestyle-badge", "Lifestyle + Badge", "marketplace", { scene: "badge", hue: 140, hue2: 45 }, "The product in a bright lifestyle setting with a round quality badge in one corner", { headline: "Best seller" }),
+ t("mk-dark-premium", "Dark Premium Listing", "marketplace", { scene: "noir", hue: 30, hue2: 45, dark: true }, "Premium listing image: the product on charcoal with warm gold rim light and a slim feature strip", { headline: "{product}" }),
+];
+
+export const TEMPLATE_INDEX = new Map(TEMPLATES.map((x) => [x.id, x]));
+
+export function templatesFor(category: MarketingCategory | "all", media: "all" | "image" | "video"): MarketingTemplate[] {
+ return TEMPLATES.filter((x) => {
+ const f = FORMATS[x.format];
+ return (category === "all" || f.category === category) && (media === "all" || f.kind === media);
+ });
+}
+
+/** "All": one template of each category in turn, so the first row shows the range. */
+export function interleaved(list: MarketingTemplate[]): MarketingTemplate[] {
+ const by = new Map<MarketingCategory, MarketingTemplate[]>();
+ for (const x of list) {
+ const c = FORMATS[x.format].category;
+ by.set(c, [...(by.get(c) ?? []), x]);
+ }
+ const queues = [...by.values()];
+ const out: MarketingTemplate[] = [];
+ for (let i = 0; out.length < list.length; i++) for (const q of queues) if (q[i]) out.push(q[i]);
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// UGC hooks and settings (the mechanics are Higgsfield's; the prompts are Fuobe's own words)
+
+export interface UgcHook {
+ id: string;
+ name: string;
+ type: "stunt" | "subtle";
+ prompt: string;
+}
+
+export const UGC_HOOKS: UgcHook[] = [
+ { id: "product-hit", name: "Product Hit", type: "stunt", prompt: "Something flies into frame and bonks the creator; a beat of surprise, then they laugh it off and pivot straight to the product." },
+ { id: "spicy", name: "Spicy", type: "subtle", prompt: "Opens on an extreme close-up of the collarbone, tilts slowly up to a flawless face, pulls back to selfie framing and holds a silent beat before the pitch." },
+ { id: "interview", name: "Interview", type: "subtle", prompt: "A street interviewer asks a stranger an odd follow-up question; confusion builds until the stranger spots the product and starts a casual review." },
+ { id: "random-mic", name: "Random Object Mic", type: "stunt", prompt: "Mid-vlog, an absurd object drops into the creator's hand from above and they use it as a microphone to deliver a dead-serious review." },
+ { id: "product-crash", name: "Product Crash", type: "subtle", prompt: "The product tumbles from above and the scene glitches into chaos, then snaps back clean and calm as the creator begins reviewing it." },
+ { id: "blizzard", name: "Blizzard", type: "stunt", prompt: "A cozy room is hit by an impossible indoor blizzard; everything is covered in snow except the product, which keeps working perfectly." },
+ { id: "camera-bump", name: "Camera Bump", type: "subtle", prompt: "The camera bumps the creator's forehead by accident; they flinch, laugh, recover and naturally reveal the product while explaining it." },
+ { id: "product-dodge", name: "Product Dodge", type: "stunt", prompt: "The product flies at the creator's face; they duck just in time, then pop back up already holding it and start the review as if nothing happened." },
+ { id: "epic-fail", name: "Epic Fail", type: "subtle", prompt: "The creator attempts a backflip, lands badly, and without missing a beat pulls out the product and starts an unbothered review." },
+];
+
+export interface UgcSetting {
+ id: string;
+ name: string;
+ type: "realistic" | "unrealistic";
+ prompt: string;
+}
+
+export const UGC_SETTINGS: UgcSetting[] = [
+ { id: "bedroom", name: "Bedroom", type: "realistic", prompt: "sitting up in bed against pillows, soft window light, rumpled sheets, a relaxed morning feel" },
+ { id: "nature", name: "Nature", type: "realistic", prompt: "outdoors on a trail, in a park or at the beach depending on the product, natural light, open sky" },
+ { id: "gym", name: "Gym", type: "realistic", prompt: "on a gym bench after a workout, bright overhead lights, equipment behind, freshly-finished energy" },
+ { id: "bathroom", name: "Bathroom", type: "realistic", prompt: "front-camera selfie in a bathroom, vanity lights, tiles behind, getting-ready energy" },
+ { id: "kitchen", name: "Kitchen", type: "realistic", prompt: "leaning on a kitchen counter in daylight, a mug and fruit in the background, casual midday vibe" },
+ { id: "in-car", name: "In Car", type: "realistic", prompt: "selfie from the driver's or passenger seat of a parked car, window light on the face, between errands" },
+ { id: "street", name: "Street", type: "realistic", prompt: "walking down a city sidewalk, handheld selfie, storefronts and traffic behind, talking while moving" },
+ { id: "office", name: "Office", type: "realistic", prompt: "at a desk with a laptop open and coffee nearby, soft overhead light, a quick mention between tasks" },
+ { id: "airplane-wing", name: "Airplane Wing", type: "unrealistic", prompt: "sitting on the wing of a plane in flight above the clouds, wind whipping, completely unbothered" },
+ { id: "rooftop", name: "Rooftop Edge", type: "unrealistic", prompt: "perched on the edge of a skyscraper rooftop at golden hour, the whole city below, totally relaxed" },
+ { id: "volcano", name: "Volcano Rim", type: "unrealistic", prompt: "sitting on the rim of an active volcano, lava bubbling below and smoke drifting past, zero reaction" },
+ { id: "tiny", name: "Tiny Reviewer", type: "unrealistic", prompt: "shrunk to 15 cm tall and leaning on a giant version of the product, a normal selfie review at an impossible scale" },
+ { id: "car-roof", name: "Car Roof", type: "unrealistic", prompt: "sitting on the roof of a moving car on a desert highway at golden hour, swaying calmly as a truck passes" },
+ { id: "train", name: "Train Surf", type: "unrealistic", prompt: "hanging out of the door of a moving train filming a selfie, wind pressing against them as the live demo" },
+];
+
+export const hookById = (id?: string | null) => UGC_HOOKS.find((h) => h.id === id);
+export const settingById = (id?: string | null) => UGC_SETTINGS.find((s) => s.id === id);
+
+// ---------------------------------------------------------------------------
+// Click to Ad styles (the 10 preset names; Fuobe's own direction for each)
+
+export interface AdStyle {
+ id: string;
+ name: string;
+ description: string;
+ /** A presenter talks to camera (else product-only shots). */
+ presenter: boolean;
+ /** How the shots look. */
+ visual: string;
+ /** How the script sounds. */
+ voice: string;
+ hue: number;
+ dark?: boolean;
+}
+
+export const AD_STYLES: AdStyle[] = [
+ { id: "simple-ugc", name: "Simple UGC", description: "A creator shows it on their phone camera", presenter: true, visual: "authentic phone-camera UGC look, natural light, handheld", voice: "casual, first person, like telling a friend", hue: 25 },
+ { id: "clean-minimal", name: "Clean Minimal", description: "Calm studio shots, lots of white space", presenter: false, visual: "minimal studio shots on a soft seamless backdrop, slow controlled camera moves", voice: "calm, confident, few words", hue: 210 },
+ { id: "unboxing", name: "Unboxing", description: "Hands open the box and reveal it", presenter: false, visual: "close-up hands unboxing the product on a clean desk, satisfying reveal", voice: "excited first impressions", hue: 35 },
+ { id: "customer-reviews", name: "Customer Reviews", description: "A happy customer tells why they love it", presenter: true, visual: "testimonial selfie video at home, warm natural light", voice: "a genuine customer review with one specific detail", hue: 45 },
+ { id: "viral-chaos", name: "Viral Chaos", description: "Fast cuts, bold motion, high energy", presenter: false, visual: "fast whip pans, punchy zooms and bold colour, maximum energy", voice: "fast, punchy, meme-aware", hue: 330 },
+ { id: "luxury", name: "Luxury", description: "Dark, glossy, premium lighting", presenter: false, visual: "luxurious dark set, glossy reflections, slow elegant camera moves, gold accents", voice: "unhurried, refined, aspirational", hue: 45, dark: true },
+ { id: "product-story", name: "Product Story", description: "Where it comes from and why it matters", presenter: false, visual: "cinematic product story: materials, making-of details and the finished product", voice: "storytelling, warm narrator", hue: 20 },
+ { id: "cozy-morning", name: "Cozy Morning", description: "A slow, warm morning ritual", presenter: false, visual: "soft morning light, steam, blankets, the product in a slow morning ritual", voice: "gentle and warm", hue: 35 },
+ { id: "red-carpet", name: "Red Carpet", description: "Flash bulbs, glamour, star treatment", presenter: true, visual: "red-carpet glamour with camera flashes and a confident presenter", voice: "glamorous, playful hype", hue: 0, dark: true },
+ { id: "elegant-minimal", name: "Elegant Minimal", description: "Soft neutrals and graceful motion", presenter: false, visual: "soft neutral palette, linen and stone textures, graceful slow motion", voice: "soft-spoken and elegant", hue: 30 },
+];
+
+export const styleById = (id?: string | null) => AD_STYLES.find((s) => s.id === id);
+
+/** Click to Ad makes a 9:16 ad of at most 12 seconds. */
+export const CLICK_TO_AD = { aspect: "9:16", maxSeconds: 12, shots: 3 } as const;
+
+// ---------------------------------------------------------------------------
+// Ads Studio
+
+export const MAX_ADS_PER_PRODUCT = 20;
+export const MAX_PRODUCTS_PER_RUN = 10;
+export const AD_RATIOS = ["1:1", "4:5", "9:16"] as const;
+export type AdRatio = (typeof AD_RATIOS)[number];
+
+export interface AdAngle {
+ id: string;
+ name: string;
+ /** What the copy leads with. */
+ copy: string;
+ /** What the picture shows. */
+ visual: string;
+}
+
+export const AD_ANGLES: AdAngle[] = [
+ { id: "benefit", name: "Key benefit", copy: "lead with the single biggest benefit", visual: "the product as a confident hero shot" },
+ { id: "pain-point", name: "Pain point", copy: "name a frustration the buyer has and show the product as the fix", visual: "the product in the moment it solves an everyday problem" },
+ { id: "real-life", name: "Real-life use", copy: "show how it fits into an ordinary day", visual: "the product being used in a real, lived-in setting" },
+ { id: "offer", name: "Offer", copy: "lead with the price, a deal or free shipping", visual: "the product on a bold colour field with room for an offer badge" },
+ { id: "material", name: "Ingredients & materials", copy: "tell the story of what it's made of", visual: "the product surrounded by its ingredients or raw materials" },
+ { id: "how-to", name: "How it works", copy: "explain in one line how it's used", visual: "hands using the product, close up" },
+ { id: "lifestyle", name: "Lifestyle moment", copy: "sell the feeling of the moment it belongs to", visual: "an aspirational lifestyle scene featuring the product" },
+ { id: "social-proof", name: "Social proof", copy: "quote a happy customer or a number of buyers", visual: "the product in soft light with space for a quote" },
+ { id: "comparison", name: "Comparison", copy: "contrast it with the usual alternative", visual: "the product standing out next to a dull generic alternative" },
+];
+
+export interface AdConcept {
+ angle: string;
+ headline: string;
+ body: string;
+ cta: string;
+ /** The picture to render (no text in it). */
+ visual: string;
+}
+
+export type CreativeStatus = "writing" | "queued" | "rendering" | "ready" | "failed" | "canceled";
+
+export interface AdCreative extends AdConcept {
+ id: string;
+ batchId: string;
+ brandId: string;
+ productId: string | null;
+ position: number;
+ status: CreativeStatus;
+ /** Human words for the status ("Creative is on its way"). */
+ message?: string | null;
+ error?: string | null;
+ generationId?: string | null;
+ /** The rendered visual (or the whole ad on the Higgsfield route). */
+ image?: string | null;
+ /** The visual already holds the text (Higgsfield Ads Studio): don't draw over it. */
+ baked?: boolean;
+ layout?: string | null;
+ engine: Engine;
+ modelId: string;
+ costUsd?: number | null;
+ createdAt: number;
+}
+
+export function creativeStatusText(s: CreativeStatus, error?: string | null): string {
+ switch (s) {
+ case "writing":
+ return "Writing the copy…";
+ case "queued":
+ return "In queue";
+ case "rendering":
+ return "Creative is on its way";
+ case "ready":
+ return "Ready";
+ case "canceled":
+ return "Canceled before it was made";
+ default:
+ return error ? `Creative generation failed — ${error}` : "Creative generation failed";
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Ad Multiplier
+
+export const MULTIPLIER = { minSeconds: 4, maxSeconds: 30, maxImages: 20, maxChars: 4000, defaultPrompt: "Recreate this ad.", qualities: ["480p", "720p", "1080p"] as const } as const;
+
+export interface MultiplierParts {
+ mode: "prompt" | "sections";
+ prompt?: string;
+ hook?: string | null;
+ cta?: string | null;
+}
+
+/** The text sent for a run: the prompt, or "HOOK: …\n\nCTA: …" in sections mode. */
+export function multiplierText(p: MultiplierParts): string {
+ if (p.mode === "prompt") return (p.prompt ?? "").trim() || MULTIPLIER.defaultPrompt;
+ return [p.hook != null && `HOOK: ${p.hook.trim() || "Write a new opening hook."}`, p.cta != null && `CTA: ${p.cta.trim() || "Write a new call to action."}`].filter(Boolean).join("\n\n");
+}
+
+/** Images named in the prompt (@image_3 → 3), in order of first mention. */
+export function mentionedImages(prompt: string): number[] {
+ const out: number[] = [];
+ for (const m of prompt.matchAll(/@image_(\d{1,2})\b/g)) {
+ const n = Number(m[1]);
+ if (n >= 1 && !out.includes(n)) out.push(n);
+ }
+ return out;
+}
+
+/**
+ * The images a model gets, and the prompt rewritten for it: the mentioned images first (then the
+ * rest) up to the model's limit, renumbered; Kling reads "@Image1", the others "image 1".
+ */
+export function mentionsFor(prompt: string, images: string[], modelId: string, max: number): { prompt: string; images: string[]; dropped: number } {
+ const order = [...mentionedImages(prompt).filter((n) => n <= images.length), ...images.map((_, i) => i + 1)].filter((n, i, a) => a.indexOf(n) === i);
+ const used = order.slice(0, Math.max(0, max));
+ const kling = modelId.startsWith("kling");
+ const text = prompt.replace(/@image_(\d{1,2})\b/g, (all, d: string) => {
+ const at = used.indexOf(Number(d));
+ if (at < 0) return "the reference";
+ return kling ? `@Image${at + 1}` : `image ${at + 1}`;
+ });
+ return { prompt: text, images: used.map((n) => images[n - 1]), dropped: images.length - used.length };
+}
+
+// ---------------------------------------------------------------------------
+// Scripts and captions
+
+/** Speaking rate used to size scripts and time estimated captions (ElevenLabs/Chatterbox ≈ 2.4–2.8 w/s). */
+export const WORDS_PER_SECOND = 2.5;
+
+export const wordBudget = (seconds: number) => Math.max(6, Math.round(seconds * WORDS_PER_SECOND));
+
+/** Trim a script to its word budget at a sentence end when possible. */
+export function fitScript(script: string, seconds: number): string {
+ const max = wordBudget(seconds);
+ const words = script.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
+ if (words.length <= max) return words.join(" ");
+ const cut = words.slice(0, max).join(" ");
+ const end = Math.max(cut.lastIndexOf(". "), cut.lastIndexOf("! "), cut.lastIndexOf("? "));
+ return end > cut.length * 0.5 ? cut.slice(0, end + 1) : `${cut.replace(/[,;:\s]+$/, "")}.`;
+}
+
+export interface Cue {
+ start: number;
+ end: number;
+ text: string;
+}
+
+/**
+ * Captions timed from the script at the speaking rate (the open caption burn-in needs timed lines;
+ * the cloud captioner transcribes the clip itself). Short TikTok-style chunks of ≤ `words` words.
+ */
+export function estimateCues(script: string, words = 4, rate = WORDS_PER_SECOND, offset = 0): Cue[] {
+ const tokens = script.replace(/\s+/g, " ").trim().split(" ").filter(Boolean);
+ const cues: Cue[] = [];
+ let t = offset;
+ for (let i = 0; i < tokens.length; ) {
+ let n = Math.min(words, tokens.length - i);
+ // End a chunk at punctuation so captions follow the phrasing.
+ for (let k = 0; k < n; k++)
+ if (/[.!?,;:]$/.test(tokens[i + k])) {
+ n = k + 1;
+ break;
+ }
+ const chunk = tokens.slice(i, i + n);
+ const pause = /[.!?]$/.test(chunk[chunk.length - 1]) ? 0.25 : 0;
+ const dur = chunk.length / rate + pause;
+ cues.push({ start: round2(t), end: round2(t + dur), text: chunk.join(" ") });
+ t += dur;
+ i += n;
+ }
+ return cues;
+}
+
+/** "0.00-1.60: text" lines, the format the open caption burn-in reads from its prompt. */
+export const cueLines = (cues: Cue[]) => cues.map((c) => `${c.start.toFixed(2)}-${c.end.toFixed(2)}: ${c.text}`).join("\n");
+
+const round2 = (n: number) => Math.round(n * 100) / 100;
+
+// ---------------------------------------------------------------------------
+// Durations and models
+
+/** The allowed duration closest to the wanted one (ties go to the shorter, cheaper clip). */
+export function snapDuration(want: number, allowed: number[] | undefined): number {
+ if (!allowed?.length) return want;
+ return [...allowed].sort((a, b) => Math.abs(a - want) - Math.abs(b - want) || a - b)[0];
+}
+
+/**
+ * Split a clip into shots a model can make (open models top out at a few seconds): equal shots of
+ * at most `longest`, each snapped to an allowed length. Sums to roughly `seconds`.
+ */
+export function shotPlan(seconds: number, allowed: number[] | undefined): number[] {
+ const longest = Math.max(...(allowed?.length ? allowed : [seconds]));
+ const n = Math.max(1, Math.ceil(seconds / longest - 0.01));
+ return Array.from({ length: n }, () => snapDuration(seconds / n, allowed));
+}
+
+export interface ModelChoice {
+ id: string;
+ /** Why it's the pick ("exact text", "Higgsfield's own"). */
+ note?: string;
+}
+
+/** The models a Marketing Studio format can use on an engine, the default first. */
+export function formatModels(format: FormatDef, engine: Engine, has: { product: boolean; avatar: boolean; higgsfield: boolean }): ModelChoice[] {
+ if (engine === "open") {
+ switch (format.pipeline) {
+ case "motion":
+ return [{ id: "oss-wan22-14b-fast", note: "Wan 2.2 14B, shot by shot" }];
+ case "ugc":
+ return [{ id: "oss-infinitetalk", note: "InfiniteTalk presenter" }];
+ default:
+ if (format.id === "poster" && !has.product) return [{ id: "oss-qwen-image", note: "Qwen-Image; your text is set on top" }];
+ return [{ id: "oss-qwen-edit", note: format.text ? "Qwen-Image-Edit; your text is set on top" : "Qwen-Image-Edit with your references" }];
+ }
+ }
+ const hf: ModelChoice[] = has.higgsfield ? [{ id: "marketing-studio-image", note: "Higgsfield's own" }] : [];
+ switch (format.id) {
+ case "product-standalone":
+ return [{ id: "bria-product-shot", note: "Keeps the product pixel-exact" }, { id: "nano-banana-pro" }, ...hf, { id: "gpt-image-2-5" }, { id: "product-photography", note: "One-tap studio shot" }];
+ case "product-with-model":
+ return [{ id: "nano-banana-pro", note: "Product + person references" }, ...hf, { id: "gpt-image-2-5" }];
+ case "ads":
+ case "marketplace":
+ return [{ id: "gpt-image-2-5", note: "Exact text" }, { id: "nano-banana-pro" }, { id: "ideogram-4-5" }, ...hf];
+ case "poster":
+ return has.product
+ ? [{ id: "gpt-image-2-5", note: "Exact text" }, { id: "nano-banana-pro" }, { id: "ideogram-4-5" }]
+ : [{ id: "ideogram-3", note: "Exact text in your brand colours" }, { id: "ideogram-4-5" }, { id: "recraft-4-1" }, { id: "gpt-image-2-5" }];
+ case "ugc-talking":
+ case "tiktok":
+ return [{ id: "omnihuman-2", note: "Full-body presenter" }, { id: "kling-avatar" }];
+ default:
+ return [{ id: "seedance-2-5", note: "Higgsfield's default video model" }, { id: "kling-o3" }, { id: "gemini-omni-flash" }];
+ }
+}
+
+/** Ads Studio's visual model per engine (the copy and layout are Fuobe's; the picture has no text). */
+export function adVisualModel(engine: Engine, hasProductImage: boolean): string {
+ if (engine === "open") return hasProductImage ? "oss-qwen-edit" : "oss-qwen-image";
+ return "nano-banana-pro";
+}
+
+/** Cloud talking-presenter / voice / caption models for UGC pipelines. */
+export const UGC_MODELS = {
+ cloud: { voice: "elevenlabs-v4", still: "nano-banana-pro", talk: "omnihuman-2", clip: "seedance-2-5", captions: "auto-subtitle", join: "join-clips", mux: "merge-audio-video", trim: "trim-video", frame: "extract-frame" },
+ open: { voice: "oss-chatterbox", still: "oss-qwen-edit", talk: "oss-infinitetalk", clip: "oss-wan22-14b-fast", captions: "oss-captions-burnin", join: "oss-join-clips", mux: "oss-mux", trim: "oss-trim", frame: "oss-extract-frame" },
+} as const;
+
+/** The models the Ad Multiplier can recreate with, per engine (the first that's usable is the default). */
+export const MULTIPLIER_MODELS: Record<Engine, ModelChoice[]> = {
+ cloud: [
+ { id: "seedance-2-5", note: "Seedance 2.5 edit — what Higgsfield runs (needs a Higgsfield key)" },
+ { id: "kling-o3", note: "Kling O3 edit, up to 4 @images" },
+ { id: "gemini-omni-flash", note: "Gemini Omni Flash edit, prompt only" },
+ ],
+ open: [{ id: "oss-wan22-animate", note: "Wan Animate: your @image_1 takes over the performance" }],
+};
+
+/** Ad Multiplier quality → the resolution sent; open models top out at 720p. */
+export const multiplierResolution = (q: string, engine: Engine) => (engine === "open" && q === "1080p" ? "720p" : q);
+
+// ---------------------------------------------------------------------------
+// Runs (Marketing Studio, Click to Ad, Ad Multiplier): a batch of chained generations and what made it
+
+export type RunFeature = "marketing" | "click-to-ad" | "ad-multiplier";
+
+export interface RunOverlay {
+ headline?: string;
+ body?: string;
+ cta?: string;
+}
+
+export interface MarketingRunMeta {
+ format?: FormatId;
+ templateId?: string;
+ productId?: string | null;
+ brandId?: string | null;
+ styleId?: string;
+ /** Open-engine text formats: the exact words the browser sets over the picture. */
+ overlay?: RunOverlay | null;
+ script?: string;
+ mode?: "prompt" | "sections";
+ notes?: string[];
+}
+
+export interface MarketingRun {
+ id: string;
+ feature: RunFeature;
+ batchId: string;
+ engine: Engine;
+ title: string;
+ /** The results (the last step of a pipeline, or every output request). */
+ finalIds: string[];
+ meta: MarketingRunMeta;
+ createdAt: number;
+ /** Every step, oldest first. */
+ generations: Generation[];
+}
+
+export interface PlannedStep {
+ key: string;
+ label: string;
+ modelId: string;
+ modelName: string;
+ costUsd: number | null;
+}
+
+export interface RunEstimate {
+ costUsd: number | null;
+ demo: boolean;
+ steps: PlannedStep[];
+ notes: string[];
+ /** Why it can't run yet (shown on the Generate button). */
+ blocker?: string;
+ runs: number;
+}
+
+/** The state of a whole run: its results', else the first step that failed on its own, else running. */
+export function runStatus(r: Pick<MarketingRun, "generations" | "finalIds">): { state: "done" | "failed" | "running" | "canceled"; step?: string; error?: string } {
+ const finals = r.generations.filter((g) => r.finalIds.includes(g.id));
+ if (finals.length && finals.every((g) => g.status === "succeeded")) return { state: "done" };
+ const failed = r.generations.find((g) => g.status === "failed" && !/earlier step/i.test(g.error ?? ""));
+ if (failed) return { state: "failed", step: failed.request.step?.label, error: failed.error ?? undefined };
+ if (!finals.length || finals.every((g) => g.status === "canceled" || g.status === "failed")) return { state: finals.some((g) => g.status === "failed") ? "failed" : "canceled" };
+ return { state: "running" };
+}
diff --git a/src/lib/catalog/models.ts b/src/lib/catalog/models.ts
index aec13b0f..5b302915 100644
--- a/src/lib/catalog/models.ts
+++ b/src/lib/catalog/models.ts
@@ -1125,6 +1125,19 @@ const local: ModelDef[] = [
options: {},
hidden: true,
},
+ // Ads Studio: a creative composited over its visual (headline, copy, CTA, logo in the brand fonts), saved from the browser.
+ {
+ id: "local-ad-compose",
+ name: "Ad compositor",
+ vendor: "Fuobe",
+ family: "local",
+ engine: "open",
+ kind: "image",
+ tagline: "Headline, copy, CTA and logo set over the visual in your brand fonts, in your browser",
+ routes: [{ op: "edit", provider: "local", endpoint: "canvas" }],
+ options: {},
+ hidden: true,
+ },
];
export const MODELS: ModelDef[] = [...cloud, ...open, ...local];
diff --git a/src/server/ads.ts b/src/server/ads.ts
new file mode 100644
index 00000000..f425fad2
--- /dev/null
+++ b/src/server/ads.ts
@@ -0,0 +1,643 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import {
+ AD_ANGLES,
+ AD_RATIOS,
+ brandLine,
+ MAX_ADS_PER_PRODUCT,
+ MAX_PRODUCTS_PER_RUN,
+ adVisualModel,
+ type AdConcept,
+ type AdCreative,
+ type BrandKit,
+ type CreativeStatus,
+ type Product,
+} from "@/lib/catalog/marketing";
+import type { Engine, Generation, GenerationRequest, OutputFile } from "@/lib/catalog/types";
+import { getModel } from "@/lib/catalog";
+import { getBrand, getProduct, listProducts, parseJsonObject } from "./brand";
+import { db } from "./db";
+import { llmText } from "./enhance";
+import { createGenerations, getGeneration, previewGeneration, recordLocalGeneration } from "./generations";
+import { provider } from "./providers";
+import { engineMode } from "./settings";
+
+/**
+ * Ads Studio: brand → products → "How many ads?" → a grid that fills as ads render.
+ * Each ad = a selling angle with headline, body copy and CTA (LLM, or rules offline) + one visual
+ * from an image model (product photo as reference, no text in it). The finished creative is
+ * composited in the browser (canvas) in 1:1, 4:5 and 9:16 with the brand's logo, colours and fonts.
+ * With a Higgsfield key, Higgsfield's own Ads Studio can render whole ads in one call instead.
+ */
+
+export const BatchBody = z.object({
+ brandId: z.string().min(1).max(40),
+ engine: z.enum(["cloud", "open"]),
+ route: z.enum(["fuobe", "higgsfield"]).optional(),
+ items: z
+ .array(z.object({ productId: z.string().min(1).max(40), count: z.number().int().min(1).max(MAX_ADS_PER_PRODUCT) }))
+ .min(1)
+ .max(MAX_PRODUCTS_PER_RUN),
+ /** What the user asked for in the chat ("holiday setting for our winter sale"). */
+ direction: z.string().max(1000).optional(),
+ /** Higgsfield renders one format per ad. */
+ ratio: z.enum(AD_RATIOS).optional(),
+});
+export type BatchInput = z.infer<typeof BatchBody>;
+
+export class AdsError extends Error {}
+
+const higgsfieldReady = () => provider("higgsfield").isConfigured();
+
+/** The route a batch takes: Higgsfield's one-shot Ads Studio when asked for (or by default with a key), else Fuobe's. */
+export function batchRoute(input: Pick<BatchInput, "engine" | "route">): "fuobe" | "higgsfield" {
+ if (input.engine === "open") return "fuobe";
+ if (input.route) return input.route === "higgsfield" && higgsfieldReady() ? "higgsfield" : "fuobe";
+ return higgsfieldReady() ? "higgsfield" : "fuobe";
+}
+
+// ---------------------------------------------------------------------------
+// Copy
+
+const COPY_SYSTEM = `You are a senior performance-marketing copywriter writing static social ads (Instagram, TikTok, Meta).
+Answer with ONE JSON object and nothing else:
+{"ads": [{"angle": string (one of the angle ids given), "headline": string (at most 7 words), "body": string (at most 20 words), "cta": string (1–3 words), "visual": string (one sentence describing the photo to shoot; it must contain no text, words or logos)}]}
+Write exactly the number of ads asked for. Vary the angles, headlines and pictures; never repeat a headline. Use the brand's tone and language. No hashtags, no emojis, no quotation marks in headlines.`;
+
+const ctaFor: Record<string, string[]> = {
+ benefit: ["Shop now", "Discover more"],
+ "pain-point": ["Fix it today", "Try it"],
+ "real-life": ["See how", "Shop now"],
+ offer: ["Get the deal", "Claim offer"],
+ material: ["See inside", "Learn more"],
+ "how-to": ["Watch how", "Try it"],
+ lifestyle: ["Discover", "Shop the look"],
+ "social-proof": ["Read reviews", "Join them"],
+ comparison: ["Switch today", "Compare now"],
+};
+
+const short = (s: string, words: number) => {
+ const w = s.replace(/\s+/g, " ").trim().replace(/[.!\s]+$/, "").split(" ");
+ return w.length <= words ? w.join(" ") : `${w.slice(0, words).join(" ")}`;
+};
+
+/** Ad concepts from facts alone (no LLM): one angle after another, headlines from selling points. */
+export function heuristicConcepts(brand: Pick<BrandKit, "name" | "tagline" | "aesthetics" | "sellingPoints">, product: Pick<Product, "name" | "description" | "sellingPoints" | "price" | "currency">, count: number, direction?: string, offset = 0): AdConcept[] {
+ const points = [...product.sellingPoints, ...brand.sellingPoints].filter(Boolean);
+ const name = product.name;
+ const price = product.price != null ? `${product.currency && product.currency.length <= 3 ? `${product.currency} ` : "$"}${product.price}` : null;
+ const look = brand.aesthetics.slice(0, 2).join(", ");
+ const dir = direction?.trim();
+ const headlines: Record<string, (i: number) => string> = {
+ benefit: (i) => short(points[i % Math.max(1, points.length)] ?? `Meet ${name}`, 7),
+ "pain-point": () => `The fix you've been waiting for`,
+ "real-life": () => `Made for your every day`,
+ offer: () => (price ? `${name}, just ${price}` : `Treat yourself today`),
+ material: () => `Only the good stuff inside`,
+ "how-to": () => `Seconds to use. Days to love.`,
+ lifestyle: () => short(brand.tagline || `Your new favourite moment`, 7),
+ "social-proof": () => `Loved by thousands`,
+ comparison: () => `Why people switch to ${short(name, 3)}`,
+ };
+ return Array.from({ length: count }, (_, k) => {
+ const i = k + offset;
+ const a = AD_ANGLES[i % AD_ANGLES.length];
+ const body = points.length ? `${points[(i + 1) % points.length].replace(/[.\s]+$/, "")}.` : (product.description?.split(/(?<=[.!?])\s/)[0] ?? `${name} by ${brand.name}.`);
+ return {
+ angle: a.id,
+ headline: headlines[a.id](i),
+ body: short(body, 20) + (body.trim().endsWith(".") ? "" : "."),
+ cta: ctaFor[a.id][Math.floor(i / AD_ANGLES.length) % 2],
+ visual: [`${a.visual}: ${name}`, look && `${look} look`, dir].filter(Boolean).join(", "),
+ };
+ });
+}
+
+/** Validate an LLM's concepts; missing or broken ones are filled by the rules. */
+export function conceptsFrom(text: string | null, fallback: AdConcept[]): AdConcept[] {
+ const j = parseJsonObject(text);
+ const raw = Array.isArray(j?.ads) ? (j!.ads as Record<string, unknown>[]) : [];
+ const ids = new Set(AD_ANGLES.map((a) => a.id));
+ const s = (v: unknown, max: number) => (typeof v === "string" ? v.replace(/\s+/g, " ").replace(/^["“]|["”]$/g, "").trim().slice(0, max) : "");
+ return fallback.map((f, i) => {
+ const r = raw[i];
+ if (!r || typeof r !== "object") return f;
+ const headline = s(r.headline, 90);
+ const visual = s(r.visual, 400);
+ if (!headline || !visual) return f;
+ return { angle: ids.has(s(r.angle, 30)) ? s(r.angle, 30) : f.angle, headline, body: s(r.body, 220) || f.body, cta: s(r.cta, 30) || f.cta, visual };
+ });
+}
+
+export async function writeConcepts(brand: BrandKit, product: Product, count: number, direction?: string, offset = 0): Promise<AdConcept[]> {
+ const fallback = heuristicConcepts(brand, product, count, direction, offset);
+ const user = [
+ `Write ${count} ad concepts.`,
+ `Brand: ${brand.name}${brand.tagline ? ` — ${brand.tagline}` : ""}`,
+ brand.overview && `About the brand: ${brand.overview}`,
+ brand.tone.length && `Tone of voice: ${brand.tone.join(", ")}`,
+ brand.aesthetics.length && `Look and feel: ${brand.aesthetics.join(", ")}`,
+ brand.audience && `Audience: ${brand.audience}`,
+ `Product: ${product.name}${product.price != null ? ` (${product.price}${product.currency ? ` ${product.currency}` : ""})` : ""}`,
+ product.description && `Product description: ${product.description.slice(0, 700)}`,
+ product.sellingPoints.length && `Selling points: ${product.sellingPoints.join("; ")}`,
+ product.audience && `Product audience: ${product.audience}`,
+ `Angles (ids): ${AD_ANGLES.map((a) => `${a.id} = ${a.copy}`).join("; ")}`,
+ direction && `The client asked for: ${direction}`,
+ `Language: ${brand.language ?? "English"}`,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ return conceptsFrom(await llmText(COPY_SYSTEM, user), fallback);
+}
+
+// ---------------------------------------------------------------------------
+// Visual requests
+
+const NO_TEXT = "No text, letters, words, logos or watermarks anywhere in the picture; leave calm space for a headline";
+
+export function visualRequest(c: Pick<AdConcept, "visual" | "headline">, product: Product | null, brand: BrandKit, engine: Engine): GenerationRequest {
+ const hero = product?.images[0];
+ const modelId = adVisualModel(engine, !!hero);
+ const model = getModel(modelId);
+ const aspect = model?.options.aspectRatios?.includes("4:5") ? "4:5" : model?.options.aspectRatios?.includes("3:4") ? "3:4" : undefined;
+ return {
+ feature: "ads",
+ modelId,
+ op: hero ? "edit" : "t2i",
+ prompt: [
+ `Advertising photograph: ${c.visual.replace(/[.\s]+$/, "")}`,
+ hero && "Keep the product exactly as in the reference photo: shape, label, logo, text and colours",
+ brandLine(brand),
+ NO_TEXT,
+ ]
+ .filter(Boolean)
+ .join(". ")
+ .concat("."),
+ inputs: hero ? { images: [hero] } : undefined,
+ params: { aspectRatio: aspect, numOutputs: 1 },
+ title: c.headline,
+ batchTitle: `${brand.name} · ads`,
+ };
+}
+
+export function higgsfieldRequest(product: Product | null, brand: BrandKit, ratio: string, direction?: string, n = 0): GenerationRequest {
+ const angle = AD_ANGLES[n % AD_ANGLES.length];
+ return {
+ feature: "ads",
+ modelId: "ads-studio",
+ op: product?.images.length ? "edit" : "t2i",
+ prompt: [
+ `A static social ad for ${product?.name ?? brand.name} by ${brand.name}`,
+ `Angle: ${angle.name} — ${angle.copy}`,
+ product?.description && `Product: ${product.description.slice(0, 600)}`,
+ product?.sellingPoints.length && `Selling points: ${product.sellingPoints.join("; ")}`,
+ (product?.audience || brand.audience) && `Audience: ${product?.audience || brand.audience}`,
+ brand.tone.length && `Tone: ${brand.tone.join(", ")}`,
+ brandLine(brand),
+ direction && `Direction: ${direction}`,
+ "Include a short headline and a call to action",
+ ]
+ .filter(Boolean)
+ .join(". ")
+ .slice(0, 7900),
+ inputs: product?.images.length ? { images: product.images.slice(0, 10) } : undefined,
+ params: { aspectRatio: ratio, numOutputs: 1 },
+ title: `${product?.name ?? brand.name} ad`,
+ batchTitle: `${brand.name} · ads`,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Batches
+
+interface CreativeRow {
+ id: string;
+ batch_id: string;
+ brand_id: string;
+ product_id: string | null;
+ position: number;
+ status: CreativeStatus;
+ angle: string | null;
+ headline: string | null;
+ body: string | null;
+ cta: string | null;
+ visual: string | null;
+ generation_id: string | null;
+ layout: string | null;
+ meta_json: string | null;
+ error: string | null;
+ created_at: number;
+ updated_at: number;
+}
+
+interface CreativeMeta {
+ engine: Engine;
+ modelId: string;
+ route: "fuobe" | "higgsfield";
+ direction?: string;
+ ratio?: string;
+ /** Composited PNGs saved to the Library, by ratio. */
+ saved?: Record<string, string>;
+}
+
+declare global {
+ var __fuobeAdRuns: Set<string> | undefined;
+}
+const running = () => (globalThis.__fuobeAdRuns ??= new Set<string>());
+
+export interface BatchEstimate {
+ route: "fuobe" | "higgsfield";
+ modelId: string;
+ modelName: string;
+ total: number;
+ costUsd: number | null;
+ perAd: number | null;
+ demo: boolean;
+ copyBy: "llm" | "rules";
+}
+
+/** "Create N ads" with its price, before anything runs (the stepper shows it first). */
+export function estimateBatch(input: BatchInput): BatchEstimate {
+ const brand = getBrand(input.brandId);
+ if (!brand) throw new AdsError("That brand no longer exists");
+ const route = batchRoute(input);
+ const total = input.items.reduce((n, i) => n + i.count, 0);
+ const product = getProduct(input.items[0].productId);
+ const req = route === "higgsfield" ? higgsfieldRequest(product, brand, input.ratio ?? "4:5") : visualRequest({ visual: "the product", headline: "Ad" }, product, brand, input.engine);
+ const p = previewGeneration(req);
+ let copy = 0;
+ if (route === "fuobe") {
+ try {
+ copy = previewGeneration({ feature: "ads", modelId: input.engine === "open" ? "oss-text-llm" : "text-llm", op: "write", prompt: "copy" }).costUsd ?? 0;
+ } catch {
+ copy = 0;
+ }
+ }
+ const perAd = p.costUsd;
+ return {
+ route,
+ modelId: p.model.id,
+ modelName: p.model.name,
+ total,
+ perAd,
+ costUsd: perAd === null ? null : Math.round((perAd * total + copy * input.items.length) * 1000) / 1000,
+ demo: p.demo,
+ copyBy: copy > 0 || p.demo ? "llm" : "rules",
+ };
+}
+
+/** Start a batch: creatives appear at once ("writing"), copy and visuals follow in the background. */
+export function createBatch(input: BatchInput): { batchId: string; creatives: AdCreative[]; run: Promise<void> } {
+ const mode = engineMode();
+ if (mode !== "both" && mode !== input.engine) throw new AdsError(mode === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
+ const brand = getBrand(input.brandId);
+ if (!brand) throw new AdsError("That brand no longer exists");
+ if (brand.status === "researching") throw new AdsError("The brand research is still running");
+ const products = input.items.map((i) => {
+ const p = getProduct(i.productId);
+ if (!p) throw new AdsError("This product is no longer available. Choose another one.");
+ return { product: p, count: i.count };
+ });
+ const est = estimateBatch(input); // validates the model, engine mode and price now
+ const route = est.route;
+ const batchId = nanoid(10);
+ const now = Date.now();
+ db().prepare("INSERT INTO ad_batches (id, brand_id, engine, route, model_id, direction, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(batchId, brand.id, input.engine, route, est.modelId, input.direction ?? null, now);
+ const meta: CreativeMeta = { engine: input.engine, modelId: est.modelId, route, direction: input.direction, ratio: input.ratio };
+ const insert = db().prepare(
+ "INSERT INTO ad_creatives (id, batch_id, brand_id, product_id, position, status, generation_id, meta_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, NULL, ?, ?, ?)",
+ );
+ const ids: { id: string; product: Product; index: number }[] = [];
+ db().transaction(() => {
+ let pos = 0;
+ for (const { product, count } of products) {
+ for (let k = 0; k < count; k++) {
+ const id = nanoid(10);
+ insert.run(id, batchId, brand.id, product.id, pos++, route === "fuobe" ? "writing" : "queued", JSON.stringify(meta), now + pos, now + pos);
+ ids.push({ id, product, index: k });
+ }
+ }
+ })();
+ running().add(batchId);
+ const run = fillBatch(batchId, brand, ids, input, route).finally(() => running().delete(batchId));
+ return { batchId, creatives: listCreatives({ brandId: brand.id, batchId }), run };
+}
+
+async function fillBatch(batchId: string, brand: BrandKit, ids: { id: string; product: Product; index: number }[], input: BatchInput, route: "fuobe" | "higgsfield"): Promise<void> {
+ const setGen = (id: string, g: Generation) => db().prepare("UPDATE ad_creatives SET generation_id = ?, status = 'queued', updated_at = ? WHERE id = ?").run(g.id, Date.now(), id);
+ const fail = (id: string, error: string) => db().prepare("UPDATE ad_creatives SET status = 'failed', error = ?, updated_at = ? WHERE id = ?").run(error, Date.now(), id);
+ if (route === "higgsfield") {
+ for (const c of ids) {
+ try {
+ setGen(c.id, createGenerations(higgsfieldRequest(c.product, brand, input.ratio ?? "4:5", input.direction, c.index), { batchId })[0]);
+ } catch (e) {
+ fail(c.id, (e as Error).message);
+ }
+ }
+ return;
+ }
+ // Copy per product (one LLM call each), then one visual per ad.
+ const byProduct = new Map<string, typeof ids>();
+ for (const c of ids) byProduct.set(c.product.id, [...(byProduct.get(c.product.id) ?? []), c]);
+ for (const list of byProduct.values()) {
+ const product = list[0].product;
+ let concepts: AdConcept[];
+ try {
+ concepts = await writeConcepts(brand, product, list.length, input.direction);
+ } catch {
+ concepts = heuristicConcepts(brand, product, list.length, input.direction);
+ }
+ list.forEach((c, i) => {
+ const k = concepts[i];
+ // A creative deleted meanwhile gets no visual.
+ const ok = db()
+ .prepare("UPDATE ad_creatives SET angle = ?, headline = ?, body = ?, cta = ?, visual = ?, status = 'queued', updated_at = ? WHERE id = ? AND status = 'writing'")
+ .run(k.angle, k.headline, k.body, k.cta, k.visual, Date.now(), c.id).changes;
+ if (!ok) return;
+ try {
+ setGen(c.id, createGenerations(visualRequest(k, product, brand, input.engine), { batchId })[0]);
+ } catch (e) {
+ fail(c.id, (e as Error).message);
+ }
+ });
+ }
+}
+
+const parseMeta = (s: string | null): CreativeMeta => {
+ try {
+ return s ? (JSON.parse(s) as CreativeMeta) : { engine: "cloud", modelId: "", route: "fuobe" };
+ } catch {
+ return { engine: "cloud", modelId: "", route: "fuobe" };
+ }
+};
+
+function statusFrom(r: CreativeRow, g: Generation | null): { status: CreativeStatus; error: string | null; image: string | null; costUsd: number | null } {
+ if (!r.generation_id || r.status === "failed" || r.status === "writing") {
+ return { status: r.status, error: r.error, image: null, costUsd: null };
+ }
+ if (!g) return { status: "failed", error: "Its picture was deleted", image: null, costUsd: null };
+ const out = g.outputs.find((o: OutputFile) => o.kind === "image");
+ const map: Record<Generation["status"], CreativeStatus> = { queued: "queued", running: "rendering", succeeded: "ready", failed: "failed", canceled: "canceled" };
+ return { status: g.status === "succeeded" && !out ? "failed" : map[g.status], error: g.error ?? null, image: out?.url ?? null, costUsd: g.costUsd ?? null };
+}
+
+function toCreative(r: CreativeRow): AdCreative {
+ const meta = parseMeta(r.meta_json);
+ const g = r.generation_id ? getGeneration(r.generation_id, { includeDeleted: true }) : null;
+ const s = statusFrom(r, g);
+ return {
+ id: r.id,
+ batchId: r.batch_id,
+ brandId: r.brand_id,
+ productId: r.product_id,
+ position: r.position,
+ angle: r.angle ?? "",
+ headline: r.headline ?? "",
+ body: r.body ?? "",
+ cta: r.cta ?? "",
+ visual: r.visual ?? "",
+ status: s.status,
+ error: s.error,
+ generationId: r.generation_id,
+ image: s.image,
+ baked: meta.route === "higgsfield",
+ layout: r.layout,
+ engine: meta.engine,
+ modelId: meta.modelId,
+ costUsd: s.costUsd,
+ createdAt: r.created_at,
+ };
+}
+
+/** Creatives whose copy step died with the server: settled as "Not made — the run ended early". */
+function settle(rows: CreativeRow[]): CreativeRow[] {
+ const now = Date.now();
+ return rows.map((r) => {
+ if (r.status !== "writing" || running().has(r.batch_id) || now - r.updated_at < 20_000) return r;
+ const error = "Not made — the run ended early";
+ db().prepare("UPDATE ad_creatives SET status = 'failed', error = ?, updated_at = ? WHERE id = ? AND status = 'writing'").run(error, now, r.id);
+ return { ...r, status: "failed" as const, error };
+ });
+}
+
+export function listCreatives(o: { brandId: string; batchId?: string; productId?: string; limit?: number }): AdCreative[] {
+ const where = ["brand_id = ?"];
+ const args: unknown[] = [o.brandId];
+ if (o.batchId) {
+ where.push("batch_id = ?");
+ args.push(o.batchId);
+ }
+ if (o.productId) {
+ where.push("product_id = ?");
+ args.push(o.productId);
+ }
+ const rows = db()
+ .prepare(`SELECT * FROM ad_creatives WHERE ${where.join(" AND ")} ORDER BY created_at DESC, position ASC LIMIT ?`)
+ .all(...args, Math.min(1000, o.limit ?? 400)) as CreativeRow[];
+ return settle(rows).map(toCreative);
+}
+
+function getCreativeRow(id: string): CreativeRow | undefined {
+ return db().prepare("SELECT * FROM ad_creatives WHERE id = ?").get(id) as CreativeRow | undefined;
+}
+
+export function getCreative(id: string): AdCreative | null {
+ const r = getCreativeRow(id);
+ return r ? toCreative(settle([r])[0]) : null;
+}
+
+export const CreativePatch = z.object({
+ headline: z.string().max(140).optional(),
+ body: z.string().max(400).optional(),
+ cta: z.string().max(40).optional(),
+ layout: z.enum(["overlay", "panel", "band", "frame"]).nullable().optional(),
+});
+
+export function updateCreative(id: string, patch: z.infer<typeof CreativePatch>): AdCreative | null {
+ const r = getCreativeRow(id);
+ if (!r) return null;
+ db()
+ .prepare("UPDATE ad_creatives SET headline = ?, body = ?, cta = ?, layout = ?, updated_at = ? WHERE id = ?")
+ .run(patch.headline ?? r.headline, patch.body ?? r.body, patch.cta ?? r.cta, patch.layout === undefined ? r.layout : patch.layout, Date.now(), id);
+ return getCreative(id);
+}
+
+export function deleteCreative(id: string): boolean {
+ return db().prepare("DELETE FROM ad_creatives WHERE id = ?").run(id).changes > 0;
+}
+
+/** Make a failed or canceled ad again: new copy if it never got any, then a new visual. */
+export async function retryCreative(id: string): Promise<AdCreative> {
+ const r = getCreativeRow(id);
+ if (!r) throw new AdsError("Not found");
+ const brand = getBrand(r.brand_id);
+ if (!brand) throw new AdsError("That brand no longer exists");
+ const product = r.product_id ? getProduct(r.product_id) : null;
+ const meta = parseMeta(r.meta_json);
+ const mode = engineMode();
+ if (mode !== "both" && mode !== meta.engine) throw new AdsError(`This ad was made on the ${meta.engine === "open" ? "open-source" : "cloud"} engine, which Settings has turned off`);
+ let g: Generation;
+ if (meta.route === "higgsfield") {
+ g = createGenerations(higgsfieldRequest(product, brand, meta.ratio ?? "4:5", meta.direction, r.position), { batchId: r.batch_id })[0];
+ } else {
+ let concept: AdConcept = { angle: r.angle ?? "", headline: r.headline ?? "", body: r.body ?? "", cta: r.cta ?? "", visual: r.visual ?? "" };
+ if (!concept.headline || !concept.visual) concept = (await writeConcepts(brand, product ?? fakeProduct(brand), 1, meta.direction, r.position))[0];
+ g = createGenerations(visualRequest(concept, product, brand, meta.engine), { batchId: r.batch_id })[0];
+ db().prepare("UPDATE ad_creatives SET angle = ?, headline = ?, body = ?, cta = ?, visual = ? WHERE id = ?").run(concept.angle, concept.headline, concept.body, concept.cta, concept.visual, id);
+ }
+ db().prepare("UPDATE ad_creatives SET generation_id = ?, status = 'queued', error = NULL, updated_at = ? WHERE id = ?").run(g.id, Date.now(), id);
+ return getCreative(id)!;
+}
+
+const fakeProduct = (brand: BrandKit): Product => ({ id: "", brandId: brand.id, name: brand.name, description: brand.overview, sellingPoints: brand.sellingPoints, images: [], createdAt: 0, updatedAt: 0 });
+
+/** A composited creative (PNG uploaded by the browser) recorded in the Library. */
+export function saveComposite(id: string, input: { url: string; ratio: string }): { generation: Generation; creative: AdCreative } {
+ const r = getCreativeRow(id);
+ if (!r) throw new AdsError("Not found");
+ const c = toCreative(r);
+ const generation = recordLocalGeneration({
+ feature: "ads",
+ modelId: "local-ad-compose",
+ op: "edit",
+ prompt: [c.headline, c.body, c.cta].filter(Boolean).join(" · ") || "Ad",
+ inputs: c.image ? { images: [c.image] } : {},
+ params: { aspectRatio: input.ratio },
+ output: { url: input.url, kind: "image", contentType: "image/png" },
+ });
+ const meta = parseMeta(r.meta_json);
+ meta.saved = { ...meta.saved, [input.ratio]: generation.id };
+ db().prepare("UPDATE ad_creatives SET meta_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(meta), Date.now(), id);
+ return { generation, creative: getCreative(id)! };
+}
+
+// ---------------------------------------------------------------------------
+// Brand chat: "{name}, what ads should we make for {brand}?" — answers, and proposes runs to confirm
+
+export interface ChatMessage {
+ id: string;
+ role: "user" | "assistant";
+ text: string;
+ at: number;
+ /** A run the assistant suggests; the user confirms it (it spends money). */
+ proposal?: { items: { productId: string; count: number }[]; direction?: string } | null;
+ /** The batch a confirmed proposal started. */
+ batchId?: string;
+}
+
+const CHAT_SYSTEM = `You are the creative strategist for a brand inside an ad studio. You can make static image ads for its products.
+Answer with ONE JSON object and nothing else:
+{"reply": string (1–3 friendly sentences), "make": null or {"products": string[] (exact product names from the list; empty = all of them), "count": number (ads per product, 1–20), "direction": string (the creative direction in one sentence: theme, setting, offer, audience, language…)}}
+Set "make" whenever the user asks for ads, variations, versions or changes to ads; otherwise answer the question and set "make" to null.`;
+
+const mentionRe = (name: string) => new RegExp(`@${name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&").replace(/\s+/g, "[\\s_]+")}`, "i");
+
+/** Products named in a message with @ ("@Night Serum" or "@Night_Serum"), longest names first. */
+export function mentionedProducts(text: string, products: Pick<Product, "id" | "name">[]): string[] {
+ return [...products].sort((a, b) => b.name.length - a.name.length).filter((p) => mentionRe(p.name).test(text)).map((p) => p.id);
+}
+
+/** What to make from a message with no LLM: counts ("4 ads"), @mentions, and the rest as direction. */
+export function offlineProposal(text: string, products: Pick<Product, "id" | "name">[]): { count: number; productIds: string[]; direction: string } | null {
+ if (!/\b(ads?|make|create|generate|variations?|versions?|more|another|locali[sz]e|change)\b/i.test(text)) return null;
+ const count = Math.min(MAX_ADS_PER_PRODUCT, Math.max(1, parseInt(/(\d{1,2})\s*(?:new\s+)?(?:ads?|variations?|versions?|creatives?)/i.exec(text)?.[1] ?? "4", 10)));
+ let direction = text;
+ const ids = mentionedProducts(text, products);
+ for (const p of products) direction = direction.replace(mentionRe(p.name), p.name);
+ direction = direction.replace(/\b(please|can you|could you|make|create|generate|write)\b/gi, " ").replace(/\b\d{1,2}\s*(new\s+)?(ads?|variations?|versions?|creatives?)\b/gi, " ").replace(/\s+/g, " ").trim();
+ return { count, productIds: ids, direction };
+}
+
+interface BrandChatRow {
+ chat_json: string;
+}
+
+export function getChat(brandId: string): ChatMessage[] {
+ const r = db().prepare("SELECT chat_json FROM brand_kits WHERE id = ?").get(brandId) as BrandChatRow | undefined;
+ try {
+ return r ? (JSON.parse(r.chat_json) as ChatMessage[]) : [];
+ } catch {
+ return [];
+ }
+}
+
+function saveChat(brandId: string, chat: ChatMessage[]) {
+ db().prepare("UPDATE brand_kits SET chat_json = ? WHERE id = ?").run(JSON.stringify(chat.slice(-60)), brandId);
+}
+
+export function clearChat(brandId: string) {
+ saveChat(brandId, []);
+}
+
+export async function chat(brandId: string, text: string): Promise<ChatMessage[]> {
+ const brand = getBrand(brandId);
+ if (!brand) throw new AdsError("That brand no longer exists");
+ const products = listProducts(brandId);
+ const history = getChat(brandId);
+ const userMsg: ChatMessage = { id: nanoid(8), role: "user", text: text.trim().slice(0, 2000), at: Date.now() };
+ const context = [
+ `Brand: ${brand.name}${brand.tagline ? ` — ${brand.tagline}` : ""}`,
+ brand.overview && `About: ${brand.overview}`,
+ brand.tone.length && `Tone: ${brand.tone.join(", ")}`,
+ `Products: ${products.map((p) => p.name).join("; ") || "none yet"}`,
+ history.length && `Conversation so far:\n${history.slice(-8).map((m) => `${m.role}: ${m.text}`).join("\n")}`,
+ `User: ${userMsg.text}`,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ const j = parseJsonObject(await llmText(CHAT_SYSTEM, context));
+ let reply: ChatMessage;
+ if (j && typeof j.reply === "string") {
+ const make = j.make && typeof j.make === "object" ? (j.make as Record<string, unknown>) : null;
+ const names = Array.isArray(make?.products) ? (make!.products as unknown[]).filter((x): x is string => typeof x === "string") : [];
+ let ids = products.filter((p) => names.some((n) => n.toLowerCase() === p.name.toLowerCase())).map((p) => p.id);
+ if (!ids.length) ids = mentionedProducts(userMsg.text, products);
+ if (!ids.length) ids = products.slice(0, MAX_PRODUCTS_PER_RUN).map((p) => p.id);
+ const count = Math.min(MAX_ADS_PER_PRODUCT, Math.max(1, Math.round(Number(make?.count) || 4)));
+ reply = {
+ id: nanoid(8),
+ role: "assistant",
+ text: j.reply.slice(0, 1200),
+ at: Date.now(),
+ proposal: make && ids.length ? { items: ids.map((productId) => ({ productId, count })), direction: typeof make.direction === "string" ? make.direction.slice(0, 600) : userMsg.text } : null,
+ };
+ } else {
+ const p = offlineProposal(userMsg.text, products);
+ const ids = p?.productIds.length ? p.productIds : products.slice(0, MAX_PRODUCTS_PER_RUN).map((x) => x.id);
+ reply =
+ p && ids.length
+ ? {
+ id: nanoid(8),
+ role: "assistant",
+ text: `Here's the plan: ${p.count} ad${p.count === 1 ? "" : "s"} for ${ids.map((id) => products.find((x) => x.id === id)?.name).join(", ")}${p.direction ? `, ${p.direction.charAt(0).toLowerCase()}${p.direction.slice(1)}` : ""}. Create them?`,
+ at: Date.now(),
+ proposal: { items: ids.map((productId) => ({ productId, count: p.count })), direction: p.direction || undefined },
+ }
+ : {
+ id: nanoid(8),
+ role: "assistant",
+ text: products.length
+ ? `I can make ads for you — try “Make 4 ads for @${products[0].name} with a holiday theme”. Connect Claude or Ollama in Settings and I can talk through ideas too.`
+ : "Add a product first, then ask me for ads — e.g. “Make 4 ads with a summer theme”.",
+ at: Date.now(),
+ proposal: null,
+ };
+ }
+ const next = [...history, userMsg, reply];
+ saveChat(brandId, next);
+ return next;
+}
+
+/** The user said yes to a proposal: run it and remember the batch on the message. */
+export function confirmProposal(brandId: string, messageId: string, engine: Engine, route?: "fuobe" | "higgsfield"): { batchId: string; run: Promise<void>; chat: ChatMessage[] } {
+ const history = getChat(brandId);
+ const msg = history.find((m) => m.id === messageId);
+ if (!msg?.proposal) throw new AdsError("That suggestion is no longer available");
+ if (msg.batchId) throw new AdsError("Those ads are already on their way");
+ const r = createBatch({ brandId, engine, route, items: msg.proposal.items, direction: msg.proposal.direction });
+ const next = history.map((m) => (m.id === messageId ? { ...m, batchId: r.batchId } : m));
+ saveChat(brandId, next);
+ return { batchId: r.batchId, run: r.run, chat: next };
+}
diff --git a/src/server/brand.ts b/src/server/brand.ts
new file mode 100644
index 00000000..51da1e62
--- /dev/null
+++ b/src/server/brand.ts
@@ -0,0 +1,1351 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import {
+ BRAND_LANGUAGES,
+ emptyKit,
+ isHex,
+ MAX_PRODUCT_IMAGES,
+ MAX_SELLING_POINTS,
+ RESEARCH_LABELS,
+ type BrandKit,
+ type BrandKitFields,
+ type BrandProgress,
+ type BrandSocial,
+ type BrandStatus,
+ type Product,
+} from "@/lib/catalog/marketing";
+import { db } from "./db";
+import { llmText } from "./enhance";
+import { fetchRemote } from "./remote-fetch";
+import { saveFile } from "./storage";
+
+/**
+ * Brand kits and products, shared by Marketing Studio, Ads Studio and Click to Ad.
+ *
+ * Brand research: the site's HTML through the SSRF-safe fetch (remote-fetch.ts), then plain code
+ * reads what's machine-readable (OpenGraph, JSON-LD Organization/Product, Shopify /products.json,
+ * CSS colour variables, font families, logo, hero images) and an LLM (llmText: Claude, else Ollama)
+ * writes the soft fields (tagline, overview, tone, values, audience…). With no LLM, rule-based
+ * heuristics fill them, so a kit always comes back. Progress uses Higgsfield's 14 labels.
+ */
+
+// ---------------------------------------------------------------------------
+// HTML helpers (regex-based: no DOM on the server, and pages are untrusted input)
+
+const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", "#39": "'", hellip: "…", mdash: "—", ndash: "–", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“" };
+
+export function decodeEntities(s: string): string {
+ return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+\d*|#39);/gi, (all, e: string) => {
+ if (e[0] === "#") {
+ const n = e[1].toLowerCase() === "x" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
+ return Number.isFinite(n) && n > 0 && n < 0x110000 ? String.fromCodePoint(n) : all;
+ }
+ return ENTITIES[e.toLowerCase()] ?? all;
+ });
+}
+
+/** Attributes of one start tag (`<a href="x" class='y' hidden>` → {href, class, hidden}). */
+export function attrs(tag: string): Record<string, string> {
+ const out: Record<string, string> = {};
+ const body = tag.replace(/^<[\w:-]+/, "").replace(/\/?>$/, "");
+ for (const m of body.matchAll(/([^\s=/>"']+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+)))?/g)) {
+ out[m[1].toLowerCase()] = decodeEntities(m[2] ?? m[3] ?? m[4] ?? "");
+ }
+ return out;
+}
+
+function tags(html: string, name: string): Record<string, string>[] {
+ return [...html.matchAll(new RegExp(`<${name}\\b[^>]*>`, "gi"))].map((m) => attrs(m[0]));
+}
+
+const strip = (html: string) =>
+ decodeEntities(
+ html
+ .replace(/<(script|style|noscript|svg|template|iframe)\b[\s\S]*?<\/\1>/gi, " ")
+ .replace(/<!--[\s\S]*?-->/g, " ")
+ .replace(/<br\s*\/?>/gi, "\n")
+ .replace(/<\/(p|div|li|h[1-6]|section|article|tr)>/gi, "\n")
+ .replace(/<[^>]+>/g, " "),
+ )
+ .replace(/[ \t\f\v\r]+/g, " ")
+ .replace(/\s*\n\s*/g, "\n")
+ .replace(/\n{2,}/g, "\n")
+ .trim();
+
+const clean = (s: string | undefined | null, max = 400) => (s ? decodeEntities(s).replace(/\s+/g, " ").trim().slice(0, max) : "");
+
+function resolve(href: string | undefined, base: string): string | null {
+ if (!href || href.startsWith("data:") || href.startsWith("javascript:") || href.startsWith("#")) return null;
+ try {
+ const u = new URL(href.trim(), base);
+ return u.protocol === "http:" || u.protocol === "https:" ? u.toString() : null;
+ } catch {
+ return null;
+ }
+}
+
+function meta(html: string, ...keys: string[]): string {
+ const all = tags(html, "meta");
+ for (const k of keys) {
+ const hit = all.find((a) => (a.property ?? a.name ?? a.itemprop ?? "").toLowerCase() === k.toLowerCase() && a.content);
+ if (hit) return clean(hit.content, 1000);
+ }
+ return "";
+}
+
+function metaAll(html: string, key: string): string[] {
+ return tags(html, "meta")
+ .filter((a) => (a.property ?? a.name ?? "").toLowerCase() === key && a.content)
+ .map((a) => a.content.trim());
+}
+
+// ---------------------------------------------------------------------------
+// JSON-LD
+
+type Json = Record<string, unknown>;
+
+export function jsonLd(html: string): Json[] {
+ const out: Json[] = [];
+ const walk = (v: unknown) => {
+ if (Array.isArray(v)) v.forEach(walk);
+ else if (v && typeof v === "object") {
+ const o = v as Json;
+ out.push(o);
+ if (Array.isArray(o["@graph"])) walk(o["@graph"]);
+ if (o.itemListElement) walk(o.itemListElement);
+ if (o.item && typeof o.item === "object") walk(o.item);
+ }
+ };
+ for (const m of html.matchAll(/<script\b[^>]*type\s*=\s*["']?application\/ld\+json["']?[^>]*>([\s\S]*?)<\/script>/gi)) {
+ try {
+ walk(JSON.parse(m[1].trim()));
+ } catch {
+ // Malformed blocks are common; skip them.
+ }
+ }
+ return out;
+}
+
+const typeOf = (o: Json): string[] => (Array.isArray(o["@type"]) ? (o["@type"] as string[]) : [String(o["@type"] ?? "")]).map((t) => t.toLowerCase());
+const str = (v: unknown): string => (typeof v === "string" ? v : v && typeof v === "object" && typeof (v as Json).name === "string" ? ((v as Json).name as string) : "");
+
+function urlsOf(v: unknown): string[] {
+ if (!v) return [];
+ if (typeof v === "string") return [v];
+ if (Array.isArray(v)) return v.flatMap(urlsOf);
+ if (typeof v === "object") {
+ const o = v as Json;
+ return urlsOf(o.url ?? o.contentUrl ?? o["@id"]);
+ }
+ return [];
+}
+
+// ---------------------------------------------------------------------------
+// Colours
+
+interface Rgb {
+ r: number;
+ g: number;
+ b: number;
+}
+
+const toHex = ({ r, g, b }: Rgb) => `#${[r, g, b].map((n) => Math.max(0, Math.min(255, Math.round(n))).toString(16).padStart(2, "0")).join("")}`;
+
+function hexToRgb(hex: string): Rgb {
+ const h = hex.replace("#", "");
+ return { r: parseInt(h.slice(0, 2), 16), g: parseInt(h.slice(2, 4), 16), b: parseInt(h.slice(4, 6), 16) };
+}
+
+function hslToRgb(h: number, s: number, l: number): Rgb {
+ const k = (n: number) => (n + h / 30) % 12;
+ const a = s * Math.min(l, 1 - l);
+ const f = (n: number) => l - a * Math.max(-1, Math.min(k(n) - 3, Math.min(9 - k(n), 1)));
+ return { r: f(0) * 255, g: f(8) * 255, b: f(4) * 255 };
+}
+
+/** A CSS colour literal as #rrggbb (null for transparent/unknown/very translucent). */
+export function normalizeColor(raw: string): string | null {
+ const s = raw.trim().toLowerCase();
+ let m = /^#([0-9a-f]{3,8})$/.exec(s);
+ if (m) {
+ let h = m[1];
+ if (h.length === 3 || h.length === 4) h = [...h].map((c) => c + c).join("");
+ if (h.length === 8 && parseInt(h.slice(6, 8), 16) < 128) return null;
+ return h.length >= 6 ? `#${h.slice(0, 6)}` : null;
+ }
+ m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)(?:[\s,/]+([\d.]+%?))?\s*\)$/.exec(s);
+ if (m) {
+ const alpha = m[4] ? (m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4])) : 1;
+ if (alpha < 0.5) return null;
+ return toHex({ r: +m[1], g: +m[2], b: +m[3] });
+ }
+ m = /^hsla?\(\s*([\d.]+)(?:deg)?[\s,]+([\d.]+)%[\s,]+([\d.]+)%(?:[\s,/]+([\d.]+%?))?\s*\)$/.exec(s);
+ if (m) {
+ const alpha = m[4] ? (m[4].endsWith("%") ? parseFloat(m[4]) / 100 : parseFloat(m[4])) : 1;
+ if (alpha < 0.5) return null;
+ return toHex(hslToRgb(+m[1], +m[2] / 100, +m[3] / 100));
+ }
+ return null;
+}
+
+/** Hue-agnostic facts about a colour: lightness and saturation in 0–1. */
+export function colorStats(hex: string): { l: number; s: number } {
+ const { r, g, b } = hexToRgb(hex);
+ const max = Math.max(r, g, b) / 255;
+ const min = Math.min(r, g, b) / 255;
+ const l = (max + min) / 2;
+ const s = max === min ? 0 : (max - min) / (1 - Math.abs(2 * l - 1));
+ return { l, s };
+}
+
+const distance = (a: string, b: string) => {
+ const x = hexToRgb(a);
+ const y = hexToRgb(b);
+ return Math.sqrt(2 * (x.r - y.r) ** 2 + 4 * (x.g - y.g) ** 2 + 3 * (x.b - y.b) ** 2);
+};
+
+const BRANDY = /primary|brand|accent|main|secondary|highlight|button|btn|cta|link|theme/;
+const COLOR_LITERAL = /#[0-9a-fA-F]{3,8}\b|rgba?\([^)]*\)|hsla?\([^)]*\)/g;
+
+/**
+ * The brand palette from CSS and the theme colour: named custom properties (--brand, --primary…)
+ * count most, then how often a colour is used. Returns up to `max` distinct colours, the main
+ * (most brand-like chromatic) one first, plus a dark and a light neutral when the site uses them.
+ */
+export function extractColors(css: string[], themeColor?: string | null, max = 6): string[] {
+ const score = new Map<string, number>();
+ const add = (hex: string | null, n: number) => hex && score.set(hex, (score.get(hex) ?? 0) + n);
+ if (themeColor) add(normalizeColor(themeColor), 12);
+ for (const sheet of css) {
+ for (const m of sheet.matchAll(/--([\w-]+)\s*:\s*([^;}{]+)/g)) {
+ const name = m[1].toLowerCase();
+ if (/shadow|overlay|backdrop|scrim|border|disabled|muted|placeholder/.test(name)) continue;
+ for (const c of m[2].match(COLOR_LITERAL) ?? []) add(normalizeColor(c), BRANDY.test(name) ? 6 : 1.5);
+ }
+ for (const m of sheet.matchAll(/(?:^|[;{\s])(color|background(?:-color)?|fill|border-color)\s*:\s*([^;}{]+)/g)) {
+ for (const c of m[2].match(COLOR_LITERAL) ?? []) add(normalizeColor(c), m[1].startsWith("background") ? 0.6 : 0.4);
+ }
+ }
+ const ranked = [...score.entries()].sort((a, b) => b[1] - a[1]).map(([hex]) => hex);
+ const chromatic = ranked.filter((h) => {
+ const { l, s } = colorStats(h);
+ return s >= 0.25 && l > 0.12 && l < 0.88;
+ });
+ const out: string[] = [];
+ const push = (h: string | undefined) => h && out.length < max && !out.some((o) => distance(o, h) < 70) && out.push(h);
+ chromatic.slice(0, 4).forEach(push);
+ push(ranked.find((h) => colorStats(h).l < 0.18));
+ push(ranked.find((h) => colorStats(h).l > 0.92));
+ ranked.forEach(push);
+ return out;
+}
+
+// ---------------------------------------------------------------------------
+// Fonts
+
+const GENERIC_FONTS = new Set([
+ "serif", "sans-serif", "monospace", "cursive", "fantasy", "system-ui", "ui-sans-serif", "ui-serif", "ui-monospace", "ui-rounded", "inherit", "initial", "unset",
+ "-apple-system", "blinkmacsystemfont", "segoe ui", "helvetica neue", "helvetica", "arial", "apple color emoji", "segoe ui emoji", "segoe ui symbol", "noto color emoji",
+ "emoji", "math", "fangsong", "sans", "revert", "var", "times new roman", "times", "courier new", "courier", "georgia", "verdana", "tahoma",
+]);
+
+const firstFamily = (stack: string): string | null => {
+ for (const part of stack.split(",")) {
+ const name = part.trim().replace(/^["']|["']$/g, "").trim();
+ if (!name || name.startsWith("var(") || name.startsWith("--") || GENERIC_FONTS.has(name.toLowerCase())) continue;
+ if (!/^[\p{L}\p{N} _.-]{2,40}$/u.test(name)) continue;
+ return name;
+ }
+ return null;
+};
+
+/** Google Fonts families named in links or @imports ("Playfair Display", "Inter"). */
+export function googleFonts(text: string): string[] {
+ const out: string[] = [];
+ for (const m of text.matchAll(/fonts\.googleapis\.com\/css2?\?([^"')\s>]+)/g)) {
+ for (const fam of decodeEntities(m[1]).split("&").filter((p) => p.startsWith("family="))) {
+ for (const one of decodeURIComponent(fam.slice(7).replace(/\+/g, " ")).split("|")) {
+ const name = one.split(":")[0].trim();
+ if (name && !out.includes(name)) out.push(name);
+ }
+ }
+ }
+ return out;
+}
+
+/** Heading and body families: Google Fonts links, CSS variables (--font-heading), then h1–h3 and body rules. */
+export function extractFonts(html: string, css: string[]): { heading?: string; body?: string; all: string[] } {
+ const google = googleFonts(html + "\n" + css.join("\n"));
+ const count = new Map<string, number>();
+ let heading: string | undefined;
+ let body: string | undefined;
+ const all = css.join("\n") + "\n" + [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]).join("\n");
+ for (const m of all.matchAll(/--([\w-]*font[\w-]*)\s*:\s*([^;}{]+)/gi)) {
+ const fam = firstFamily(m[2]);
+ if (!fam) continue;
+ if (!heading && /head|display|title|serif-display|h1/.test(m[1].toLowerCase())) heading = fam;
+ else if (!body && /body|text|base|sans|primary|default/.test(m[1].toLowerCase())) body = fam;
+ }
+ for (const m of all.matchAll(/([^{}]+)\{([^{}]*)\}/g)) {
+ const fm = /font-family\s*:\s*([^;}]+)/i.exec(m[2]);
+ if (!fm) continue;
+ const fam = firstFamily(fm[1]);
+ if (!fam) continue;
+ count.set(fam, (count.get(fam) ?? 0) + 1);
+ const sel = m[1].toLowerCase();
+ if (!heading && /(^|[\s,])h[1-3]\b|heading|headline|display|title/.test(sel)) heading = fam;
+ if (!body && /(^|[\s,])(body|html|:root)\b/.test(sel)) body = fam;
+ }
+ for (const m of all.matchAll(/@font-face\s*\{[^}]*font-family\s*:\s*([^;}]+)/gi)) {
+ const fam = firstFamily(m[1]);
+ if (fam) count.set(fam, (count.get(fam) ?? 0) + 0.5);
+ }
+ const ranked = [...new Set([...google, ...[...count.entries()].sort((a, b) => b[1] - a[1]).map(([f]) => f)])];
+ heading ??= google[0] ?? ranked[0];
+ body ??= ranked.find((f) => f !== heading) ?? heading;
+ return { heading, body, all: ranked.slice(0, 8) };
+}
+
+// ---------------------------------------------------------------------------
+// Products
+
+export interface ProductDraft {
+ name: string;
+ description?: string;
+ price?: number | null;
+ currency?: string | null;
+ url?: string;
+ /** Remote image URLs (downloaded on save). */
+ images: string[];
+ brand?: string;
+ sellingPoints?: string[];
+ audience?: string;
+}
+
+const priceOf = (v: unknown): number | null => {
+ const n = typeof v === "number" ? v : typeof v === "string" ? parseFloat(v.replace(/[^\d.,]/g, "").replace(/,(\d{2})$/, ".$1").replace(/,/g, "")) : NaN;
+ return Number.isFinite(n) && n >= 0 ? Math.round(n * 100) / 100 : null;
+};
+
+function offerOf(v: unknown): { price: number | null; currency: string | null } {
+ const o = (Array.isArray(v) ? v[0] : v) as Json | undefined;
+ if (!o || typeof o !== "object") return { price: null, currency: null };
+ return { price: priceOf(o.price ?? o.lowPrice ?? (o.priceSpecification as Json | undefined)?.price), currency: str(o.priceCurrency) || null };
+}
+
+const stripHtml = (s: string, max = 600) => clean(strip(s), max);
+
+/** Products in JSON-LD (Product, ProductGroup, and Products inside an ItemList). */
+export function jsonLdProducts(blocks: Json[], base: string): ProductDraft[] {
+ const out: ProductDraft[] = [];
+ for (const o of blocks) {
+ const types = typeOf(o);
+ if (!types.some((t) => t === "product" || t === "productgroup")) continue;
+ const name = clean(str(o.name), 140);
+ if (!name || out.some((p) => p.name === name)) continue;
+ const { price, currency } = offerOf(o.offers);
+ out.push({
+ name,
+ description: stripHtml(str(o.description)),
+ price,
+ currency,
+ url: resolve(str(o.url) || undefined, base) ?? undefined,
+ images: urlsOf(o.image)
+ .map((u) => resolve(u, base))
+ .filter((u): u is string => !!u)
+ .slice(0, MAX_PRODUCT_IMAGES),
+ brand: clean(str(o.brand), 80) || undefined,
+ });
+ }
+ return out;
+}
+
+interface ShopifyProduct {
+ title?: string;
+ body_html?: string;
+ handle?: string;
+ vendor?: string;
+ variants?: { price?: string | number }[];
+ images?: { src?: string }[];
+}
+
+/** Shopify's public /products.json (a store's catalogue) or /products/<handle>.json (one product). */
+export function shopifyProducts(json: unknown, origin: string): ProductDraft[] {
+ const j = json as { products?: ShopifyProduct[]; product?: ShopifyProduct };
+ const list = j?.products ?? (j?.product ? [j.product] : []);
+ return list
+ .filter((p) => p?.title)
+ .map((p) => ({
+ name: clean(p.title, 140),
+ description: stripHtml(p.body_html ?? ""),
+ price: priceOf(p.variants?.[0]?.price),
+ currency: null,
+ url: p.handle ? `${origin.replace(/\/+$/, "")}/products/${p.handle}` : undefined,
+ images: (p.images ?? [])
+ .map((i) => resolve(i.src, origin))
+ .filter((u): u is string => !!u)
+ .slice(0, MAX_PRODUCT_IMAGES),
+ brand: p.vendor ? clean(p.vendor, 80) : undefined,
+ }));
+}
+
+const isShopify = (html: string) => /cdn\.shopify\.com|Shopify\.shop|shopify-section/i.test(html);
+
+// ---------------------------------------------------------------------------
+// The whole page
+
+export interface SiteFacts {
+ url: string;
+ host: string;
+ name: string;
+ title: string;
+ description: string;
+ themeColor: string | null;
+ lang: string | null;
+ /** Candidate logo URLs, best first (an inline SVG logo comes as `svg`). */
+ logos: string[];
+ svgLogo: string | null;
+ images: string[];
+ headings: string[];
+ text: string;
+ socials: BrandSocial[];
+ stylesheets: string[];
+ inlineCss: string[];
+ products: ProductDraft[];
+ shopify: boolean;
+ organization: { name?: string; description?: string; logo?: string; sameAs: string[] } | null;
+}
+
+const SOCIAL_HOSTS: [RegExp, string][] = [
+ [/(^|\.)instagram\.com$/, "Instagram"],
+ [/(^|\.)tiktok\.com$/, "TikTok"],
+ [/(^|\.)(youtube\.com|youtu\.be)$/, "YouTube"],
+ [/(^|\.)facebook\.com$/, "Facebook"],
+ [/(^|\.)linkedin\.com$/, "LinkedIn"],
+ [/(^|\.)pinterest\.[a-z.]+$/, "Pinterest"],
+ [/(^|\.)(x\.com|twitter\.com)$/, "X"],
+ [/(^|\.)threads\.(net|com)$/, "Threads"],
+ [/(^|\.)snapchat\.com$/, "Snapchat"],
+ [/(^|\.)(t\.me|telegram\.me)$/, "Telegram"],
+ [/(^|\.)(discord\.gg|discord\.com)$/, "Discord"],
+];
+
+export function socialOf(url: string): BrandSocial | null {
+ try {
+ const u = new URL(url);
+ const hit = SOCIAL_HOSTS.find(([re]) => re.test(u.hostname.toLowerCase()));
+ if (!hit || u.pathname.length < 2 || /\/(share|sharer|intent|dialog|plugins|embed)/.test(u.pathname)) return null;
+ return { network: hit[1], url: `${u.origin}${u.pathname}`.replace(/\/+$/, "") };
+ } catch {
+ return null;
+ }
+}
+
+const SKIP_IMAGE = /sprite|pixel|tracking|spacer|blank\.|1x1|favicon|\/icons?\/|placeholder|loader|spinner|badge|payment|flag/i;
+
+/** Everything machine-readable on a page. */
+export function parseSite(html: string, url: string): SiteFacts {
+ const u = new URL(url);
+ const host = u.hostname.replace(/^www\./, "");
+ const ld = jsonLd(html);
+ const orgRaw = ld.find((o) => typeOf(o).some((t) => ["organization", "corporation", "brand", "localbusiness", "store", "onlinestore"].includes(t)));
+ const site = ld.find((o) => typeOf(o).includes("website"));
+ const organization = orgRaw
+ ? {
+ name: clean(str(orgRaw.name), 80) || undefined,
+ description: clean(str(orgRaw.description), 600) || undefined,
+ logo: urlsOf(orgRaw.logo).map((x) => resolve(x, url)).find(Boolean) ?? undefined,
+ sameAs: urlsOf(orgRaw.sameAs),
+ }
+ : null;
+ const title = clean(/<title\b[^>]*>([\s\S]*?)<\/title>/i.exec(html)?.[1], 200);
+ const ogSite = meta(html, "og:site_name", "application-name", "apple-mobile-web-app-title");
+ const titleParts = title.split(/\s+[|–—·:-]\s+/).map((s) => s.trim()).filter(Boolean);
+ const name = organization?.name || ogSite || clean(str(site?.name), 80) || shortestBrandPart(titleParts, host) || hostName(host);
+ const description = meta(html, "description", "og:description", "twitter:description") || organization?.description || "";
+
+ const links = tags(html, "link");
+ const icons = links
+ .filter((l) => /(^|\s)(apple-touch-icon|icon|shortcut icon|mask-icon)(\s|$)/i.test(l.rel ?? ""))
+ .map((l) => ({ href: resolve(l.href, url), size: parseInt((l.sizes ?? "").split("x")[0], 10) || (/apple/i.test(l.rel) ? 180 : 32) }))
+ .filter((l): l is { href: string; size: number } => !!l.href)
+ .sort((a, b) => b.size - a.size);
+ const imgs = tags(html, "img");
+ const logoImgs = imgs
+ .filter((a) => /logo/i.test(`${a.class ?? ""} ${a.id ?? ""} ${a.alt ?? ""} ${a.src ?? ""}`))
+ .map((a) => resolve(a.src ?? a["data-src"], url))
+ .filter((x): x is string => !!x);
+ const logos = [...new Set([organization?.logo, ...logoImgs, ...icons.filter((i) => i.size >= 96).map((i) => i.href), ...icons.map((i) => i.href)].filter((x): x is string => !!x))];
+ // An inline <svg> logo: the first svg after an element whose class or id names a logo.
+ let svgLogo: string | null = null;
+ const at = html.search(/(class|id|aria-label)\s*=\s*["'][^"']*logo[^"']*["']/i);
+ if (at >= 0) {
+ const tail = html.slice(at, at + 40_000);
+ const m = /<svg\b[\s\S]*?<\/svg>/i.exec(tail);
+ if (m && m.index < 2000 && m[0].length < 30_000) svgLogo = m[0].includes("xmlns") ? m[0] : m[0].replace(/<svg\b/i, '<svg xmlns="http://www.w3.org/2000/svg"');
+ }
+
+ const images = [
+ ...metaAll(html, "og:image"),
+ ...metaAll(html, "og:image:secure_url"),
+ ...metaAll(html, "twitter:image"),
+ ...imgs
+ .filter((a) => {
+ const w = parseInt(a.width ?? "", 10);
+ const h = parseInt(a.height ?? "", 10);
+ return !(w && w < 240) && !(h && h < 240) && !/logo/i.test(`${a.class ?? ""} ${a.alt ?? ""}`);
+ })
+ .map((a) => a.src ?? a["data-src"] ?? (a.srcset ?? a["data-srcset"] ?? "").split(",").pop()?.trim().split(" ")[0]),
+ ]
+ .map((x) => resolve(x, url))
+ .filter((x): x is string => !!x && !SKIP_IMAGE.test(x) && !/\.svg(\?|$)/i.test(x));
+
+ const socials: BrandSocial[] = [];
+ for (const href of [...tags(html, "a").map((a) => a.href), ...(organization?.sameAs ?? [])]) {
+ const s = href && socialOf(resolve(href, url) ?? "");
+ if (s && !socials.some((x) => x.network === s.network)) socials.push(s);
+ }
+
+ const text = strip(html);
+ return {
+ url,
+ host,
+ name,
+ title,
+ description,
+ themeColor: meta(html, "theme-color", "msapplication-TileColor") || null,
+ lang: (/<html\b[^>]*\blang\s*=\s*["']?([a-zA-Z-]+)/i.exec(html)?.[1] ?? null)?.toLowerCase() ?? null,
+ logos,
+ svgLogo,
+ images: [...new Set(images)].slice(0, 16),
+ headings: [...html.matchAll(/<h([1-3])\b[^>]*>([\s\S]*?)<\/h\1>/gi)].map((m) => clean(strip(m[2]), 140)).filter(Boolean).slice(0, 20),
+ text: text.slice(0, 20_000),
+ socials,
+ stylesheets: links
+ .filter((l) => /stylesheet/i.test(l.rel ?? "") && l.href)
+ .map((l) => resolve(l.href, url))
+ .filter((x): x is string => !!x && !/fonts\.googleapis\.com/.test(x)),
+ inlineCss: [...html.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((m) => m[1]),
+ products: jsonLdProducts(ld, url),
+ shopify: isShopify(html),
+ organization,
+ };
+}
+
+function hostName(host: string): string {
+ const label = host.split(".").filter((p) => !/^(www|shop|store|m)$/.test(p))[0] ?? host;
+ return label.charAt(0).toUpperCase() + label.slice(1);
+}
+
+/** "Acme Coffee | Specialty beans roasted weekly" → the part that looks like a name (short, or matching the domain). */
+function shortestBrandPart(parts: string[], host: string): string {
+ if (!parts.length) return "";
+ const label = host.split(".")[0].replace(/[^a-z0-9]/g, "");
+ const matching = parts.find((p) => p.toLowerCase().replace(/[^a-z0-9]/g, "").includes(label) || label.includes(p.toLowerCase().replace(/[^a-z0-9]/g, "")));
+ if (matching && matching.length <= 40) return matching;
+ const short = [...parts].sort((a, b) => a.length - b.length)[0];
+ return short.length <= 30 ? short : "";
+}
+
+// ---------------------------------------------------------------------------
+// Product pages (Add product from link, Click to Ad)
+
+/** Products on one page: JSON-LD, Shopify's product JSON is fetched separately; else OpenGraph and the page itself. */
+export function productsFromPage(html: string, url: string): ProductDraft[] {
+ const facts = parseSite(html, url);
+ if (facts.products.length) return facts.products.map((p) => ({ ...p, url: p.url ?? url, images: p.images.length ? p.images : facts.images.slice(0, 5) }));
+ const h1 = /<h1\b[^>]*>([\s\S]*?)<\/h1>/i.exec(html)?.[1];
+ const name = meta(html, "og:title", "twitter:title") || (h1 ? clean(strip(h1), 140) : "") || facts.title;
+ if (!name) return [];
+ return [
+ {
+ name: clean(name, 140),
+ description: facts.description,
+ price: priceOf(meta(html, "product:price:amount", "og:price:amount")),
+ currency: meta(html, "product:price:currency", "og:price:currency") || null,
+ url,
+ images: facts.images.slice(0, 5),
+ },
+ ];
+}
+
+// ---------------------------------------------------------------------------
+// Brand fields: LLM, with an offline fallback
+
+export interface SoftFields {
+ name?: string;
+ tagline?: string;
+ overview?: string;
+ values?: string[];
+ aesthetics?: string[];
+ tone?: string[];
+ audience?: string;
+ sellingPoints?: string[];
+ competitors?: string[];
+ language?: string;
+ colors?: string[];
+ fonts?: { heading?: string; body?: string };
+ products?: { name: string; audience?: string; sellingPoints?: string[] }[];
+}
+
+/** The first JSON object in a model's answer (tolerates code fences and chatter around it). */
+export function parseJsonObject(text: string | null | undefined): Json | null {
+ if (!text) return null;
+ const body = text.replace(/```(?:json)?/gi, "");
+ const start = body.indexOf("{");
+ const end = body.lastIndexOf("}");
+ if (start < 0 || end <= start) return null;
+ try {
+ const v = JSON.parse(body.slice(start, end + 1));
+ return v && typeof v === "object" && !Array.isArray(v) ? (v as Json) : null;
+ } catch {
+ return null;
+ }
+}
+
+const list = (v: unknown, max: number, len = 80): string[] =>
+ (Array.isArray(v) ? v : typeof v === "string" ? v.split(/[,;\n]/) : [])
+ .map((x) => clean(typeof x === "string" ? x : str(x), len))
+ .filter((x, i, a) => x && a.indexOf(x) === i)
+ .slice(0, max);
+
+/** Validate an LLM's brand answer into soft fields (drops anything malformed). */
+export function softFieldsFrom(j: Json | null): SoftFields {
+ if (!j) return {};
+ const fonts = (j.fonts && typeof j.fonts === "object" ? j.fonts : {}) as Json;
+ return {
+ name: clean(str(j.name), 80) || undefined,
+ tagline: clean(str(j.tagline), 140) || undefined,
+ overview: clean(str(j.overview ?? j.description), 900) || undefined,
+ values: list(j.values, 6),
+ aesthetics: list(j.aesthetics, 6),
+ tone: list(j.tone, 6, 40),
+ audience: clean(str(j.audience), 300) || undefined,
+ sellingPoints: list(j.sellingPoints ?? j.selling_points, MAX_SELLING_POINTS, 120),
+ competitors: list(j.competitors, 5, 60),
+ language: matchLanguage(str(j.language)),
+ colors: list(j.colors, 6, 7)
+ .map((c) => normalizeColor(c))
+ .filter((c): c is string => !!c),
+ fonts: { heading: firstFamily(str(fonts.heading)) ?? undefined, body: firstFamily(str(fonts.body)) ?? undefined },
+ products: Array.isArray(j.products)
+ ? (j.products as Json[])
+ .filter((p) => p && typeof p === "object" && str(p.name))
+ .map((p) => ({ name: clean(str(p.name), 140), audience: clean(str(p.audience), 300) || undefined, sellingPoints: list(p.sellingPoints ?? p.selling_points, MAX_SELLING_POINTS, 120) }))
+ : undefined,
+ };
+}
+
+const LANG_CODES: Record<string, string> = {
+ ar: "Arabic", zh: "Chinese", cs: "Czech", da: "Danish", nl: "Dutch", en: "English", fi: "Finnish", fr: "French", de: "German", el: "Greek", he: "Hebrew", iw: "Hebrew",
+ hi: "Hindi", hu: "Hungarian", id: "Indonesian", it: "Italian", ja: "Japanese", kk: "Kazakh", ko: "Korean", no: "Norwegian", nb: "Norwegian", pl: "Polish",
+ pt: "Portuguese", ro: "Romanian", ru: "Russian", es: "Spanish", sv: "Swedish", th: "Thai", tr: "Turkish", uk: "Ukrainian", vi: "Vietnamese",
+};
+
+/** "en-GB" / "english" / "English" → "English" (one of BRAND_LANGUAGES), else undefined. */
+export function matchLanguage(v: string | null | undefined): string | undefined {
+ if (!v) return undefined;
+ const s = v.trim().toLowerCase();
+ const byCode = LANG_CODES[s.split(/[-_]/)[0]];
+ if (byCode) return byCode;
+ return BRAND_LANGUAGES.find((l) => l.toLowerCase() === s);
+}
+
+const KEYWORDS: { re: RegExp; tone?: string; value?: string; aesthetic?: string }[] = [
+ { re: /luxur|premium|exclusive|finest|crafted/i, tone: "Refined", aesthetic: "Premium, polished finish" },
+ { re: /fun|play|joy|happy|colou?rful/i, tone: "Playful", aesthetic: "Bright and colourful" },
+ { re: /sustainab|eco|recycl|planet|carbon|organic/i, value: "Sustainability", tone: "Conscious" },
+ { re: /handmade|hand-made|small[- ]batch|artisan|craft/i, value: "Craftsmanship", aesthetic: "Handmade, tactile textures" },
+ { re: /scien|clinical|dermatolog|research|lab-tested|proven/i, tone: "Expert", value: "Evidence-based" },
+ { re: /communit|together|family/i, value: "Community", tone: "Warm" },
+ { re: /innovat|smart|ai\b|technolog|future/i, value: "Innovation", tone: "Forward-looking" },
+ { re: /natural|plant|botanical|clean ingredient/i, value: "Natural ingredients", aesthetic: "Natural light and textures" },
+ { re: /afford|accessib|everyone|inclusive/i, value: "Accessibility", tone: "Inclusive" },
+ { re: /quality|durable|built to last|lifetime/i, value: "Quality", tone: "Confident" },
+ { re: /minimal|simple|essential|clean/i, aesthetic: "Minimal, lots of white space", tone: "Calm" },
+];
+
+const SELLING = /(free (?:shipping|delivery|returns)(?: (?:over|on orders over|worldwide|on) [^\s,.;]+)?|\d+[- ]day (?:money[- ]back )?(?:returns?|trial|guarantee)|money[- ]back guarantee|lifetime warranty|\d+[- ]year warranty|vegan|cruelty[- ]free|certified organic|made in [A-Z][a-z]+|handmade|dermatologist[- ]tested|gluten[- ]free|plastic[- ]free|carbon[- ]neutral)/gi;
+
+/** Rule-based soft fields for installs with no LLM (and as the base the LLM's answer overrides). */
+export function heuristicFields(f: Pick<SiteFacts, "name" | "title" | "description" | "text" | "lang" | "headings">, colors: string[], fonts: { heading?: string }): SoftFields {
+ const blob = `${f.title}\n${f.description}\n${f.headings.join("\n")}\n${f.text.slice(0, 8000)}`;
+ const hits = KEYWORDS.filter((k) => k.re.test(blob));
+ const firstSentence = (f.description.split(/(?<=[.!?])\s/)[0] ?? "").trim();
+ const tagline = firstSentence && firstSentence.length <= 90 ? firstSentence.replace(/[.\s]+$/, "") : f.headings.find((h) => h.length >= 8 && h.length <= 70);
+ const lights = colors.map((c) => colorStats(c));
+ const aesthetics = [
+ ...hits.flatMap((h) => (h.aesthetic ? [h.aesthetic] : [])),
+ lights.some((c) => c.l < 0.2) && lights.filter((c) => c.l < 0.2).length >= lights.length / 2 ? "Dark, moody palette" : "",
+ lights.some((c) => c.s > 0.6) ? "Saturated accent colours" : "Muted, soft colours",
+ fonts.heading && /serif|playfair|garamond|didot|bodoni|cormorant|lora|libre baskerville|dm serif|fraunces/i.test(fonts.heading) ? "Classic serif typography" : "Clean sans-serif typography",
+ ].filter(Boolean);
+ return {
+ name: f.name,
+ tagline: tagline || undefined,
+ overview: f.description || undefined,
+ values: [...new Set(hits.flatMap((h) => (h.value ? [h.value] : [])))].slice(0, 5),
+ aesthetics: [...new Set(aesthetics)].slice(0, 5),
+ tone: [...new Set([...hits.flatMap((h) => (h.tone ? [h.tone] : [])), "Friendly", "Clear"])].slice(0, 4),
+ sellingPoints: [...new Set([...blob.matchAll(SELLING)].map((m) => m[0].replace(/\s+/g, " ").trim().replace(/^./, (c) => c.toUpperCase())))].slice(0, MAX_SELLING_POINTS),
+ competitors: [],
+ language: matchLanguage(f.lang) ?? "English",
+ };
+}
+
+/**
+ * The kit from what code read (name, logo, colours, fonts, images, socials) and the soft fields:
+ * the LLM's answer wins over the heuristics field by field; empty answers never erase a fact.
+ */
+export function mergeKit(base: BrandKitFields, facts: Partial<BrandKitFields>, heuristic: SoftFields, llm: SoftFields): BrandKitFields {
+ const pick = <T,>(...v: (T | undefined | null | "")[]) => v.find((x) => x !== undefined && x !== null && x !== "" && !(Array.isArray(x) && !x.length)) as T | undefined;
+ return {
+ ...base,
+ name: pick(llm.name, facts.name, heuristic.name, base.name) ?? "",
+ website: pick(facts.website, base.website),
+ logo: pick(facts.logo, base.logo),
+ tagline: pick(llm.tagline, heuristic.tagline, base.tagline),
+ overview: pick(llm.overview, heuristic.overview, base.overview),
+ colors: pick(facts.colors, llm.colors, base.colors) ?? [],
+ fonts: { heading: pick(facts.fonts?.heading, llm.fonts?.heading, base.fonts.heading), body: pick(facts.fonts?.body, llm.fonts?.body, base.fonts.body) },
+ values: pick(llm.values, heuristic.values, base.values) ?? [],
+ aesthetics: pick(llm.aesthetics, heuristic.aesthetics, base.aesthetics) ?? [],
+ tone: pick(llm.tone, heuristic.tone, base.tone) ?? [],
+ audience: pick(llm.audience, heuristic.audience, base.audience),
+ sellingPoints: (pick(llm.sellingPoints, heuristic.sellingPoints, base.sellingPoints) ?? []).slice(0, MAX_SELLING_POINTS),
+ competitors: pick(llm.competitors, heuristic.competitors, base.competitors) ?? [],
+ socials: pick(facts.socials, base.socials) ?? [],
+ language: pick(llm.language, heuristic.language, base.language),
+ images: pick(facts.images, base.images) ?? [],
+ details: base.details,
+ };
+}
+
+const BRAND_SYSTEM = `You are a brand strategist. You read a company's website and write its brand kit for an ad team.
+Answer with ONE JSON object and nothing else:
+{"name": string, "tagline": string (at most 12 words), "overview": string (2–3 sentences: what it sells, who it's for, what makes it different), "values": string[] (3–5), "aesthetics": string[] (3–5 short look-and-feel phrases, e.g. "Muted earth tones"), "tone": string[] (3–5 single words), "audience": string (one sentence), "sellingPoints": string[] (3–5 short reasons to buy), "competitors": string[] (2–4 brand names), "language": string (the site's language in English, e.g. "German"), "products": [{"name": string, "audience": string, "sellingPoints": string[] (up to 5)}] (only for the products listed, same names)}
+Use what the site says or clearly implies. Leave a field empty ("" or []) rather than invent facts.`;
+
+function brandPrompt(f: SiteFacts | null, url: string, products: ProductDraft[]): string {
+ if (!f) return `Website: ${url}\nThe site couldn't be read. Use what is publicly known about this brand; leave fields empty if you don't know it.`;
+ return [
+ `Website: ${f.url}`,
+ `Title: ${f.title}`,
+ f.description && `Description: ${f.description}`,
+ f.headings.length && `Headings: ${f.headings.slice(0, 12).join(" · ")}`,
+ products.length && `Products: ${products.slice(0, 10).map((p) => `${p.name}${p.price != null ? ` (${p.price}${p.currency ? ` ${p.currency}` : ""})` : ""}: ${(p.description ?? "").slice(0, 200)}`).join("\n")}`,
+ `Page text:\n${f.text.slice(0, 5000)}`,
+ ]
+ .filter(Boolean)
+ .join("\n");
+}
+
+const MANUAL_SYSTEM = `You are a brand designer. From a short description of a business, create its brand kit.
+Answer with ONE JSON object and nothing else:
+{"name": string, "tagline": string (at most 12 words), "overview": string (2–3 sentences), "values": string[] (3–5), "aesthetics": string[] (3–5 short look-and-feel phrases), "tone": string[] (3–5 single words), "audience": string (one sentence), "sellingPoints": string[] (3–5), "competitors": string[] (0–3), "language": string, "colors": string[] (4–5 hex colours, the main brand colour first, including one dark and one light neutral), "fonts": {"heading": string, "body": string} (Google Fonts family names that suit the brand)}`;
+
+// Palettes and fonts for a manual kit when no LLM answers, by what the business sounds like.
+const MANUAL_LOOKS: { re: RegExp; colors: string[]; fonts: { heading: string; body: string }; aesthetics: string[]; tone: string[] }[] = [
+ { re: /coffee|roast|bakery|granola|food|kitchen|tea|chocolate|snack/i, colors: ["#8a4b2a", "#d9a066", "#2b1d14", "#f6efe6"], fonts: { heading: "Fraunces", body: "Inter" }, aesthetics: ["Warm earth tones", "Natural textures", "Daylight photography"], tone: ["Warm", "Honest", "Inviting"] },
+ { re: /skin|beauty|serum|cream|cosmetic|spa|wellness/i, colors: ["#d98c8c", "#f3d5c9", "#3b2a2f", "#fbf6f3"], fonts: { heading: "Cormorant Garamond", body: "DM Sans" }, aesthetics: ["Soft blush tones", "Clean minimal layouts", "Dewy close-ups"], tone: ["Gentle", "Expert", "Reassuring"] },
+ { re: /fashion|wear|apparel|tailor|clothing|capsule|boutique/i, colors: ["#1f1f1f", "#c8b8a6", "#7a6a58", "#f7f4ef"], fonts: { heading: "Playfair Display", body: "Inter" }, aesthetics: ["Editorial photography", "Neutral palette", "Generous white space"], tone: ["Confident", "Considered", "Elegant"] },
+ { re: /home|linen|candle|interior|decor|furniture|bedding/i, colors: ["#6b7f6a", "#d8cbb5", "#2f3a33", "#f5f1ea"], fonts: { heading: "DM Serif Display", body: "Nunito Sans" }, aesthetics: ["Cozy interiors", "Muted sage and sand", "Soft natural light"], tone: ["Calm", "Cozy", "Thoughtful"] },
+ { re: /software|saas|studio|agency|digital|app|platform|develop|design/i, colors: ["#4f46e5", "#22d3ee", "#0f172a", "#f8fafc"], fonts: { heading: "Space Grotesk", body: "Inter" }, aesthetics: ["Crisp UI screenshots", "Bold gradients", "Geometric shapes"], tone: ["Clear", "Smart", "Direct"] },
+ { re: /sport|fitness|gym|run|outdoor|bike|athlet/i, colors: ["#ff5a1f", "#111827", "#facc15", "#f3f4f6"], fonts: { heading: "Oswald", body: "Inter" }, aesthetics: ["High-contrast action shots", "Bold type", "Energetic angles"], tone: ["Energetic", "Bold", "Motivating"] },
+];
+
+/** A kit from a description when no LLM answers: name before the dash, a look by category. */
+export function heuristicManualKit(description: string): SoftFields {
+ const d = description.trim();
+ const name = clean(d.split(/\s+[—–-]\s+|[,:.]/)[0], 60);
+ const look = MANUAL_LOOKS.find((l) => l.re.test(d)) ?? { colors: ["#5d4bdb", "#f59e0b", "#1c1917", "#fafaf9"], fonts: { heading: "Fraunces", body: "Inter" }, aesthetics: ["Clean layouts", "Bold accent colour", "Natural light"], tone: ["Friendly", "Clear", "Confident"] };
+ const rest = d.replace(/^[^—–-]*[—–-]\s*/, "");
+ return {
+ name: name && name.split(" ").length <= 5 ? name : name.split(" ").slice(0, 3).join(" "),
+ tagline: clean(rest.split(/[.,;]/)[0], 90) || undefined,
+ overview: d,
+ values: heuristicFields({ name: "", title: "", description: d, text: d, lang: null, headings: [] }, [], {}).values,
+ aesthetics: look.aesthetics,
+ tone: look.tone,
+ sellingPoints: [],
+ competitors: [],
+ language: "English",
+ colors: look.colors,
+ fonts: look.fonts,
+ };
+}
+
+// ---------------------------------------------------------------------------
+// Storage
+
+interface BrandRow {
+ id: string;
+ name: string;
+ website: string | null;
+ status: BrandStatus;
+ progress_json: string | null;
+ kit_json: string;
+ chat_json: string;
+ created_at: number;
+ updated_at: number;
+ product_count?: number;
+ ad_count?: number;
+}
+
+interface StoredKit extends BrandKitFields {
+ source?: "website" | "manual";
+ note?: string | null;
+ error?: string | null;
+}
+
+interface ProductRow {
+ id: string;
+ brand_id: string | null;
+ name: string;
+ description: string | null;
+ price: number | null;
+ currency: string | null;
+ audience: string | null;
+ selling_points_json: string;
+ url: string | null;
+ images_json: string;
+ created_at: number;
+ updated_at: number;
+}
+
+const parse = <T,>(s: string | null | undefined, fallback: T): T => {
+ try {
+ return s ? (JSON.parse(s) as T) : fallback;
+ } catch {
+ return fallback;
+ }
+};
+
+function toBrand(r: BrandRow): BrandKit {
+ const kit = { ...emptyKit(r.name), ...parse<Partial<StoredKit>>(r.kit_json, {}) };
+ return {
+ ...kit,
+ fonts: kit.fonts ?? {},
+ id: r.id,
+ name: r.name,
+ website: r.website ?? kit.website,
+ status: r.status,
+ progress: parse<BrandProgress | null>(r.progress_json, null),
+ note: kit.note ?? null,
+ error: kit.error ?? null,
+ source: kit.source ?? (r.website ? "website" : "manual"),
+ productCount: r.product_count,
+ adCount: r.ad_count,
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+}
+
+export function toProduct(r: ProductRow): Product {
+ return {
+ id: r.id,
+ brandId: r.brand_id,
+ name: r.name,
+ description: r.description ?? undefined,
+ price: r.price,
+ currency: r.currency,
+ audience: r.audience ?? undefined,
+ sellingPoints: parse<string[]>(r.selling_points_json, []),
+ url: r.url ?? undefined,
+ images: parse<string[]>(r.images_json, []),
+ createdAt: r.created_at,
+ updatedAt: r.updated_at,
+ };
+}
+
+declare global {
+ var __fuobeBrandRuns: Map<string, AbortController> | undefined;
+}
+const runs = () => (globalThis.__fuobeBrandRuns ??= new Map<string, AbortController>());
+
+/** Research that died with the server (or a crashed run): settle it so the UI offers Retry. */
+function settleStale(r: BrandRow): BrandRow {
+ if (r.status !== "researching" || runs().has(r.id) || Date.now() - r.updated_at < 15_000) return r;
+ const kit = parse<StoredKit>(r.kit_json, emptyKit(r.name));
+ const error = `Research incomplete — something stopped the research of ${r.name}. Retry runs it again.`;
+ const now = Date.now();
+ db().prepare("UPDATE brand_kits SET status = 'failed', progress_json = NULL, kit_json = ?, updated_at = ? WHERE id = ? AND status = 'researching'").run(JSON.stringify({ ...kit, error }), now, r.id);
+ return { ...r, status: "failed", progress_json: null, kit_json: JSON.stringify({ ...kit, error }), updated_at: now };
+}
+
+const BRAND_SELECT = `SELECT b.*, (SELECT COUNT(*) FROM products p WHERE p.brand_id = b.id) AS product_count,
+ (SELECT COUNT(*) FROM ad_creatives c WHERE c.brand_id = b.id) AS ad_count FROM brand_kits b`;
+
+export function listBrands(): BrandKit[] {
+ return (db().prepare(`${BRAND_SELECT} ORDER BY b.updated_at DESC`).all() as BrandRow[]).map(settleStale).map(toBrand);
+}
+
+export function getBrand(id: string): BrandKit | null {
+ const r = db().prepare(`${BRAND_SELECT} WHERE b.id = ?`).get(id) as BrandRow | undefined;
+ return r ? toBrand(settleStale(r)) : null;
+}
+
+function writeKit(id: string, kit: StoredKit, status?: BrandStatus) {
+ const now = Date.now();
+ const name = kit.name.trim() || "Untitled brand";
+ if (status) db().prepare("UPDATE brand_kits SET name = ?, website = ?, kit_json = ?, status = ?, progress_json = NULL, updated_at = ? WHERE id = ?").run(name, kit.website ?? null, JSON.stringify(kit), status, now, id);
+ else db().prepare("UPDATE brand_kits SET name = ?, website = ?, kit_json = ?, updated_at = ? WHERE id = ?").run(name, kit.website ?? null, JSON.stringify(kit), now, id);
+}
+
+function storedKit(id: string): StoredKit | null {
+ const r = db().prepare("SELECT name, kit_json FROM brand_kits WHERE id = ?").get(id) as { name: string; kit_json: string } | undefined;
+ return r ? { ...emptyKit(r.name), ...parse<StoredKit>(r.kit_json, emptyKit(r.name)) } : null;
+}
+
+/** Normalise a website the user typed ("acme.com" → "https://acme.com/"); null when it isn't one. */
+export function normalizeWebsite(input: string): string | null {
+ const s = input.trim();
+ if (!s || /\s/.test(s)) return null;
+ try {
+ const u = new URL(/^https?:\/\//i.test(s) ? s : `https://${s}`);
+ if (!/^https?:$/.test(u.protocol) || !u.hostname.includes(".") || u.hostname.endsWith(".")) return null;
+ return u.toString();
+ } catch {
+ return null;
+ }
+}
+
+/** Start a brand from a website: the row exists at once, the research runs in the background. */
+export function createBrandFromWebsite(website: string): { brand: BrandKit; run: Promise<void> } {
+ const url = normalizeWebsite(website);
+ if (!url) throw new Error("Enter a valid website URL");
+ const id = nanoid(10);
+ const now = Date.now();
+ const name = hostName(new URL(url).hostname.replace(/^www\./, ""));
+ const kit: StoredKit = { ...emptyKit(name), website: url, source: "website" };
+ db()
+ .prepare("INSERT INTO brand_kits (id, name, website, status, progress_json, kit_json, chat_json, created_at, updated_at) VALUES (?, ?, ?, 'researching', ?, ?, '[]', ?, ?)")
+ .run(id, name, url, JSON.stringify(progressAt(0)), JSON.stringify(kit), now, now);
+ return { brand: getBrand(id)!, run: startResearch(id) };
+}
+
+/** Run the research again (after a failure, a cancel, or to refresh). */
+export function retryResearch(id: string): { brand: BrandKit; run: Promise<void> } {
+ const b = getBrand(id);
+ if (!b) throw new Error("Not found");
+ if (!b.website) throw new Error("This brand has no website to research");
+ if (runs().has(id)) return { brand: b, run: Promise.resolve() };
+ const kit = storedKit(id)!;
+ db().prepare("UPDATE brand_kits SET status = 'researching', progress_json = ?, kit_json = ?, updated_at = ? WHERE id = ?").run(JSON.stringify(progressAt(0)), JSON.stringify({ ...kit, error: null, note: null }), Date.now(), id);
+ return { brand: getBrand(id)!, run: startResearch(id) };
+}
+
+export function cancelResearch(id: string): BrandKit | null {
+ runs().get(id)?.abort();
+ runs().delete(id);
+ db().prepare("UPDATE brand_kits SET status = 'canceled', progress_json = NULL, updated_at = ? WHERE id = ? AND status = 'researching'").run(Date.now(), id);
+ return getBrand(id);
+}
+
+const progressAt = (index: number): BrandProgress => ({ index, total: RESEARCH_LABELS.length, label: RESEARCH_LABELS[index], startedAt: Date.now() });
+
+function startResearch(id: string): Promise<void> {
+ const ac = new AbortController();
+ runs().set(id, ac);
+ return research(id, ac.signal)
+ .catch((e) => {
+ if (ac.signal.aborted) return;
+ const kit = storedKit(id);
+ if (kit) writeKit(id, { ...kit, error: `Research incomplete — ${(e as Error).message}. Retry runs it again.` }, "failed");
+ })
+ .finally(() => {
+ if (runs().get(id) === ac) runs().delete(id);
+ });
+}
+
+async function pool<T, R>(items: T[], n: number, fn: (x: T, i: number) => Promise<R>): Promise<R[]> {
+ const out: R[] = new Array(items.length);
+ let next = 0;
+ await Promise.all(
+ Array.from({ length: Math.min(n, items.length) }, async () => {
+ while (next < items.length) {
+ const i = next++;
+ out[i] = await fn(items[i], i);
+ }
+ }),
+ );
+ return out;
+}
+
+const IMAGE_MAGIC: [number[], string][] = [
+ [[0xff, 0xd8, 0xff], "image/jpeg"],
+ [[0x89, 0x50, 0x4e, 0x47], "image/png"],
+ [[0x47, 0x49, 0x46, 0x38], "image/gif"],
+ [[0x52, 0x49, 0x46, 0x46], "image/webp"],
+];
+
+/** Fetch a remote image (SSRF-safe) into the library's uploads; null when it isn't a usable picture. */
+export async function saveRemoteImage(url: string, opts: { allowSvg?: boolean; minBytes?: number } = {}): Promise<string | null> {
+ try {
+ const res = await fetchRemote(url, { maxBytes: 15 * 1024 * 1024, timeoutMs: 20_000 });
+ const sniff = IMAGE_MAGIC.find(([sig]) => sig.every((b, i) => res.data[i] === b))?.[1];
+ const isSvg = /svg/.test(res.contentType ?? "") || res.data.subarray(0, 300).toString("utf8").includes("<svg");
+ const type = sniff ?? (isSvg && opts.allowSvg ? "image/svg+xml" : null);
+ if (!type || res.data.length < (opts.minBytes ?? 3000)) return null;
+ const name = decodeURIComponent(new URL(res.url).pathname.split("/").pop() || "image").slice(0, 80);
+ return saveFile({ data: res.data, contentType: type, name, source: "upload" }).url;
+ } catch {
+ return null;
+ }
+}
+
+async function fetchText(url: string, maxBytes: number, timeoutMs: number): Promise<{ text: string; url: string; type: string | null } | null> {
+ try {
+ const r = await fetchRemote(url, { maxBytes, timeoutMs });
+ return { text: r.data.toString("utf8"), url: r.url, type: r.contentType };
+ } catch {
+ return null;
+ }
+}
+
+async function research(id: string, signal: AbortSignal): Promise<void> {
+ const brand = getBrand(id);
+ if (!brand?.website) throw new Error("No website");
+ const step = (index: number) => {
+ if (signal.aborted) throw new Error("canceled");
+ db().prepare("UPDATE brand_kits SET progress_json = ?, updated_at = ? WHERE id = ? AND status = 'researching'").run(JSON.stringify(progressAt(index)), Date.now(), id);
+ };
+ const url = brand.website;
+ const host = new URL(url).hostname.replace(/^www\./, "");
+
+ step(0);
+ let note: string | null = null;
+ const page = await fetchText(url, 6 * 1024 * 1024, 25_000);
+ const html = page && /html|xml|text/i.test(page.type ?? "text/html") ? page.text : "";
+ if (!page) note = "We couldn't read the site, so this kit comes from what is known publicly. Check it, or retry the research.";
+
+ step(1);
+ const facts = html ? parseSite(html, page!.url) : null;
+ if (facts && facts.text.length < 40 && !facts.description && !facts.title) note = `${host} returned an empty page. Fill in the brand kit manually.`;
+ else if (facts && !facts.description && facts.text.length < 200) note = `${host} showed no brand text. Fill in the brand kit manually.`;
+
+ step(2);
+ const sheets = facts
+ ? (await pool(facts.stylesheets.slice(0, 4), 3, (s) => fetchText(s, 2 * 1024 * 1024, 10_000))).filter((x): x is NonNullable<typeof x> => !!x).map((x) => x.text)
+ : [];
+ const css = [...(facts?.inlineCss ?? []), ...sheets];
+ const colors = facts ? extractColors(css, facts.themeColor) : [];
+ const fonts = facts ? extractFonts(html, css) : { all: [] };
+
+ step(3);
+ let products: ProductDraft[] = facts?.products ?? [];
+ if (facts?.shopify) {
+ const shop = await fetchText(`${new URL(facts.url).origin}/products.json?limit=12`, 4 * 1024 * 1024, 15_000);
+ const found = shop ? shopifyProducts(parseJsonSafe(shop.text), new URL(facts.url).origin) : [];
+ if (found.length) products = found;
+ }
+ const heuristic = facts ? heuristicFields(facts, colors, fonts) : { name: brand.name, language: "English" };
+ const llm = softFieldsFrom(parseJsonObject(await llmText(BRAND_SYSTEM, brandPrompt(facts, url, products))));
+ if (signal.aborted) return;
+
+ step(11);
+ const logoUrl = facts?.svgLogo
+ ? saveFile({ data: Buffer.from(facts.svgLogo), contentType: "image/svg+xml", name: `${host}-logo.svg`, source: "upload" }).url
+ : await firstSaved(facts?.logos ?? [], { allowSvg: true, minBytes: 300 });
+ const images = (await pool(facts?.images.slice(0, 10) ?? [], 4, (u) => saveRemoteImage(u, { minBytes: 8000 }))).filter((x): x is string => !!x).slice(0, 6);
+
+ step(12);
+ const kit = storedKit(id)!;
+ const merged = mergeKit(
+ kit,
+ { name: facts?.name, website: url, logo: logoUrl ?? undefined, colors: colors.length ? colors : llm.colors, fonts, socials: facts?.socials, images },
+ heuristic,
+ llm,
+ );
+ writeKit(id, { ...merged, source: "website", note, error: null });
+
+ step(13);
+ const existing = listProducts(id);
+ for (const p of products.slice(0, 12)) {
+ if (signal.aborted) return;
+ if (existing.some((e) => (p.url && e.url === p.url) || e.name.toLowerCase() === p.name.toLowerCase())) continue;
+ const soft = llm.products?.find((x) => x.name.toLowerCase() === p.name.toLowerCase());
+ const pics = (await pool(p.images.slice(0, 4), 4, (u) => saveRemoteImage(u))).filter((x): x is string => !!x);
+ insertProduct({ ...p, audience: soft?.audience, sellingPoints: soft?.sellingPoints?.length ? soft.sellingPoints : sellingPointsFrom(p.description) }, id, pics);
+ }
+ if (signal.aborted) return;
+ db().prepare("UPDATE brand_kits SET status = 'ready', progress_json = NULL, updated_at = ? WHERE id = ? AND status = 'researching'").run(Date.now(), id);
+}
+
+function parseJsonSafe(s: string): unknown {
+ try {
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
+}
+
+async function firstSaved(urls: string[], opts: { allowSvg?: boolean; minBytes?: number }): Promise<string | null> {
+ for (const u of urls.slice(0, 4)) {
+ const saved = await saveRemoteImage(u, opts);
+ if (saved) return saved;
+ }
+ return null;
+}
+
+/** Short benefit-like sentences from a product description (a stand-in when no LLM writes them). */
+export function sellingPointsFrom(description: string | undefined): string[] {
+ if (!description) return [];
+ return description
+ .split(/(?<=[.!?])\s+|\n|•|·/)
+ .map((s) => s.trim().replace(/[.\s]+$/, ""))
+ .filter((s) => s.length >= 12 && s.length <= 90 && !/cookie|privacy|©|shipping policy/i.test(s))
+ .slice(0, 3);
+}
+
+/** A manual kit from a description ("Describe your business") and optional product photos. */
+export async function createManualBrand(input: { description: string; name?: string; images?: string[]; colors?: string[] }): Promise<BrandKit> {
+ const description = input.description.trim();
+ if (!description && !input.images?.length) throw new Error("Add a description or upload images");
+ const llm = description ? softFieldsFrom(parseJsonObject(await llmText(MANUAL_SYSTEM, `Business: ${description}`))) : {};
+ const heur = heuristicManualKit(description || input.name || "My brand");
+ const colors = (input.colors ?? []).filter(isHex);
+ const kit: StoredKit = {
+ ...mergeKit(emptyKit(input.name ?? ""), { name: input.name, colors: colors.length ? colors : undefined, images: input.images }, heur, llm),
+ colors: colors.length ? colors : llm.colors?.length ? llm.colors : (heur.colors ?? []),
+ fonts: { heading: llm.fonts?.heading ?? heur.fonts?.heading, body: llm.fonts?.body ?? heur.fonts?.body },
+ source: "manual",
+ };
+ const id = nanoid(10);
+ const now = Date.now();
+ db()
+ .prepare("INSERT INTO brand_kits (id, name, website, status, progress_json, kit_json, chat_json, created_at, updated_at) VALUES (?, ?, NULL, 'ready', NULL, ?, '[]', ?, ?)")
+ .run(id, kit.name.trim() || "My brand", JSON.stringify(kit), now, now);
+ return getBrand(id)!;
+}
+
+/** Edits from the review form: only known fields, cleaned and capped. */
+export function updateBrand(id: string, patch: Partial<BrandKitFields>): BrandKit | null {
+ const kit = storedKit(id);
+ if (!kit) return null;
+ const next: StoredKit = { ...kit };
+ if (patch.name !== undefined) next.name = clean(patch.name, 80);
+ if (patch.website !== undefined) next.website = patch.website ? (normalizeWebsite(patch.website) ?? kit.website) : undefined;
+ if (patch.logo !== undefined) next.logo = patch.logo && patch.logo.startsWith("/api/files/") ? patch.logo : undefined;
+ if (patch.tagline !== undefined) next.tagline = clean(patch.tagline, 140);
+ if (patch.overview !== undefined) next.overview = clean(patch.overview, 1200);
+ if (patch.audience !== undefined) next.audience = clean(patch.audience, 300);
+ if (patch.language !== undefined) next.language = matchLanguage(patch.language) ?? kit.language;
+ if (patch.colors) next.colors = patch.colors.map((c) => normalizeColor(c)).filter((c): c is string => !!c).slice(0, 8);
+ if (patch.fonts) next.fonts = { heading: clean(patch.fonts.heading, 60) || undefined, body: clean(patch.fonts.body, 60) || undefined };
+ if (patch.values) next.values = list(patch.values, 8);
+ if (patch.aesthetics) next.aesthetics = list(patch.aesthetics, 8);
+ if (patch.tone) next.tone = list(patch.tone, 8, 40);
+ if (patch.sellingPoints) next.sellingPoints = list(patch.sellingPoints, MAX_SELLING_POINTS, 120);
+ if (patch.competitors) next.competitors = list(patch.competitors, 8, 60);
+ if (patch.details) next.details = list(patch.details, 12, 300);
+ if (patch.images) next.images = patch.images.filter((u) => u.startsWith("/api/files/")).slice(0, 12);
+ if (patch.socials) next.socials = patch.socials.map((s) => socialOf(s.url) ?? (s.network && s.url ? { network: clean(s.network, 20), url: clean(s.url, 300) } : null)).filter((s): s is BrandSocial => !!s).slice(0, 11);
+ writeKit(id, next);
+ return getBrand(id);
+}
+
+/** "“{name}” leaves the shelf with its kit and its products. Ads already made with it stay" (in the Library). */
+export function deleteBrand(id: string): boolean {
+ runs().get(id)?.abort();
+ runs().delete(id);
+ const r = db().transaction(() => {
+ db().prepare("DELETE FROM products WHERE brand_id = ?").run(id);
+ db().prepare("DELETE FROM ad_creatives WHERE brand_id = ?").run(id);
+ db().prepare("DELETE FROM ad_batches WHERE brand_id = ?").run(id);
+ return db().prepare("DELETE FROM brand_kits WHERE id = ?").run(id);
+ })();
+ return r.changes > 0;
+}
+
+// ---------------------------------------------------------------------------
+// Products
+
+export function listProducts(brandId?: string | null): Product[] {
+ const rows =
+ brandId === undefined
+ ? db().prepare("SELECT * FROM products ORDER BY created_at DESC").all()
+ : brandId === null
+ ? db().prepare("SELECT * FROM products WHERE brand_id IS NULL ORDER BY created_at DESC").all()
+ : db().prepare("SELECT * FROM products WHERE brand_id = ? ORDER BY created_at ASC").all(brandId);
+ return (rows as ProductRow[]).map(toProduct);
+}
+
+export function getProduct(id: string): Product | null {
+ const r = db().prepare("SELECT * FROM products WHERE id = ?").get(id) as ProductRow | undefined;
+ return r ? toProduct(r) : null;
+}
+
+export interface ProductInput {
+ name: string;
+ brandId?: string | null;
+ description?: string;
+ price?: number | null;
+ currency?: string | null;
+ audience?: string;
+ sellingPoints?: string[];
+ url?: string;
+ images?: string[];
+}
+
+function insertProduct(p: Omit<ProductDraft, "images"> & { sellingPoints?: string[]; audience?: string }, brandId: string | null, images: string[]): Product {
+ const id = nanoid(10);
+ const now = Date.now();
+ db()
+ .prepare(
+ "INSERT INTO products (id, brand_id, name, description, price, currency, audience, selling_points_json, url, images_json, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
+ )
+ .run(
+ id,
+ brandId,
+ clean(p.name, 140) || "Untitled product",
+ clean(p.description, 2000) || null,
+ p.price ?? null,
+ p.currency ? clean(p.currency, 8) : null,
+ clean(p.audience, 300) || null,
+ JSON.stringify(list(p.sellingPoints ?? [], MAX_SELLING_POINTS, 120)),
+ p.url ?? null,
+ JSON.stringify(images.slice(0, MAX_PRODUCT_IMAGES)),
+ now,
+ now,
+ );
+ return getProduct(id)!;
+}
+
+/** A product from the form ("Product name" is required; up to five selling points). */
+export const ProductFields = z.object({
+ name: z.string().trim().min(1, "Give the product a name").max(140),
+ brandId: z.string().max(40).nullish(),
+ description: z.string().max(4000).optional(),
+ price: z.number().nullish(),
+ currency: z.string().max(8).nullish(),
+ audience: z.string().max(400).optional(),
+ sellingPoints: z.array(z.string().max(200)).max(5, "Add up to five selling points.").optional(),
+ url: z.string().max(600).optional(),
+ images: z.array(z.string().startsWith("/api/files/")).max(8).optional(),
+});
+
+export class DuplicateProductError extends Error {
+ override name = "DuplicateProductError";
+}
+
+export function createProduct(input: ProductInput, opts: { force?: boolean } = {}): Product {
+ const name = clean(input.name, 140);
+ if (!name) throw new Error("Give the product a name");
+ if (input.price != null && input.price < 0) throw new Error("Price cannot be negative.");
+ if (input.url && !normalizeWebsite(input.url)) throw new Error("Use a valid product link.");
+ if (input.brandId && !getBrand(input.brandId)) throw new Error("That brand no longer exists");
+ if (!opts.force && input.brandId && listProducts(input.brandId).some((p) => p.name.toLowerCase() === name.toLowerCase())) {
+ throw new DuplicateProductError(`«${name}» is already among this brand's products.`);
+ }
+ return insertProduct({ ...input, name, url: input.url ? (normalizeWebsite(input.url) ?? undefined) : undefined }, input.brandId ?? null, (input.images ?? []).filter((u) => u.startsWith("/api/files/")));
+}
+
+export function updateProduct(id: string, patch: Partial<ProductInput>): Product | null {
+ const p = getProduct(id);
+ if (!p) return null;
+ if (patch.price != null && patch.price < 0) throw new Error("Price cannot be negative.");
+ if (patch.url && !normalizeWebsite(patch.url)) throw new Error("Use a valid product link.");
+ if (patch.brandId && !getBrand(patch.brandId)) throw new Error("That brand no longer exists");
+ const next = {
+ brand_id: patch.brandId !== undefined ? patch.brandId : p.brandId,
+ name: patch.name !== undefined ? clean(patch.name, 140) || p.name : p.name,
+ description: patch.description !== undefined ? clean(patch.description, 2000) || null : (p.description ?? null),
+ price: patch.price !== undefined ? patch.price : (p.price ?? null),
+ currency: patch.currency !== undefined ? (patch.currency ? clean(patch.currency, 8) : null) : (p.currency ?? null),
+ audience: patch.audience !== undefined ? clean(patch.audience, 300) || null : (p.audience ?? null),
+ selling_points_json: JSON.stringify(patch.sellingPoints ? list(patch.sellingPoints, MAX_SELLING_POINTS, 120) : p.sellingPoints),
+ url: patch.url !== undefined ? (patch.url ? normalizeWebsite(patch.url) : null) : (p.url ?? null),
+ images_json: JSON.stringify(patch.images ? patch.images.filter((u) => u.startsWith("/api/files/")).slice(0, MAX_PRODUCT_IMAGES) : p.images),
+ };
+ db()
+ .prepare("UPDATE products SET brand_id = @brand_id, name = @name, description = @description, price = @price, currency = @currency, audience = @audience, selling_points_json = @selling_points_json, url = @url, images_json = @images_json, updated_at = @now WHERE id = @id")
+ .run({ ...next, now: Date.now(), id });
+ return getProduct(id);
+}
+
+export function deleteProduct(id: string): boolean {
+ return db().prepare("DELETE FROM products WHERE id = ?").run(id).changes > 0;
+}
+
+declare global {
+ var __fuobeLinkReads: Set<string> | undefined;
+}
+const reading = () => (globalThis.__fuobeLinkReads ??= new Set<string>());
+
+export interface LinkRead {
+ products: Product[];
+ /** How many the page listed (a collection page lists many; only the first `limit` are added). */
+ found: number;
+ /** Already among the brand's products (nothing new added). */
+ duplicate?: Product;
+ /** Brand bits the page carries: Click to Ad's product kit shows the logo and colours. */
+ brand: { name?: string; logo?: string; colors: string[]; fonts: { heading?: string; body?: string } };
+ message?: string;
+}
+
+/**
+ * Add products from a link ("Add product from link", Click to Ad): Shopify's product JSON when the
+ * store is Shopify, else JSON-LD / OpenGraph on the page. Images are downloaded into the library.
+ */
+export async function readProductLink(input: { url: string; brandId?: string | null; limit?: number; withBrand?: boolean }): Promise<LinkRead> {
+ const url = normalizeWebsite(input.url);
+ if (!url) throw new Error("Use a valid product link.");
+ if (reading().has(url)) throw new Error("That link is already being read.");
+ const brandId = input.brandId ?? null;
+ if (brandId) {
+ const dup = listProducts(brandId).find((p) => p.url === url);
+ if (dup) return { products: [], found: 1, duplicate: dup, brand: { colors: [], fonts: {} }, message: `«${dup.name}» is already among this brand's products.` };
+ }
+ reading().add(url);
+ try {
+ const page = await fetchText(url, 6 * 1024 * 1024, 25_000);
+ if (!page) throw new Error(`${new URL(url).hostname} couldn't be read`);
+ let drafts = productsFromPage(page.text, page.url);
+ if (isShopify(page.text) && /\/products\//.test(new URL(page.url).pathname)) {
+ const j = await fetchText(`${page.url.split(/[?#]/)[0].replace(/\/+$/, "")}.json`, 3 * 1024 * 1024, 12_000);
+ const shop = j ? shopifyProducts(parseJsonSafe(j.text), new URL(page.url).origin) : [];
+ if (shop.length) drafts = shop.map((p) => ({ ...p, url: page.url }));
+ }
+ if (!drafts.length) throw new Error("Paste the product's link — a description alone is not enough.");
+ const limit = Math.max(1, input.limit ?? 1);
+ const facts = input.withBrand ? parseSite(page.text, page.url) : null;
+ const llm = softFieldsFrom(
+ parseJsonObject(
+ await llmText(
+ `You write short product facts for ads. Answer with ONE JSON object: {"products":[{"name": string, "audience": string (one sentence), "sellingPoints": string[] (3–5 short reasons to buy)}]} for the products given, same names. Use only what the text says or clearly implies.`,
+ drafts
+ .slice(0, limit)
+ .map((p) => `${p.name}: ${(p.description ?? "").slice(0, 800)}`)
+ .join("\n"),
+ ),
+ ),
+ );
+ const products: Product[] = [];
+ for (const d of drafts.slice(0, limit)) {
+ const soft = llm.products?.find((x) => x.name.toLowerCase() === d.name.toLowerCase());
+ const pics = (await pool(d.images.slice(0, 5), 4, (u) => saveRemoteImage(u))).filter((x): x is string => !!x);
+ products.push(insertProduct({ ...d, audience: soft?.audience, sellingPoints: soft?.sellingPoints?.length ? soft.sellingPoints : sellingPointsFrom(d.description) }, brandId, pics));
+ }
+ let brand: LinkRead["brand"] = { colors: [], fonts: {} };
+ if (facts) {
+ const sheets = (await pool(facts.stylesheets.slice(0, 3), 3, (s) => fetchText(s, 2 * 1024 * 1024, 10_000))).filter((x): x is NonNullable<typeof x> => !!x).map((x) => x.text);
+ const css = [...facts.inlineCss, ...sheets];
+ const logo = facts.svgLogo
+ ? saveFile({ data: Buffer.from(facts.svgLogo), contentType: "image/svg+xml", name: `${facts.host}-logo.svg`, source: "upload" }).url
+ : await firstSaved(facts.logos, { allowSvg: true, minBytes: 300 });
+ const f = extractFonts(page.text, css);
+ brand = { name: facts.organization?.name ?? facts.name, logo: logo ?? undefined, colors: extractColors(css, facts.themeColor), fonts: { heading: f.heading, body: f.body } };
+ }
+ const found = drafts.length;
+ return {
+ products,
+ found,
+ brand,
+ message: found > products.length ? `Found ${found} products on that page and added the first ${products.length}. Paste a product's own link to add another.` : undefined,
+ };
+ } finally {
+ reading().delete(url);
+ }
+}
diff --git a/src/server/db.ts b/src/server/db.ts
index 73575c8d..b70d47ff 100644
--- a/src/server/db.ts
+++ b/src/server/db.ts
@@ -175,6 +175,78 @@ const MIGRATIONS: string[] = [
edited_at INTEGER
);
CREATE INDEX IF NOT EXISTS canvases_updated ON canvases(updated_at DESC);`,
+ // Marketing: brand kits (researched or manual), products (shared by every marketing flow), Ads Studio runs and their
+ // creatives, and Marketing Studio / Click to Ad / Ad Multiplier runs (a batch of chained generations plus what made it).
+ `CREATE TABLE IF NOT EXISTS brand_kits (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ website TEXT,
+ status TEXT NOT NULL DEFAULT 'ready',
+ progress_json TEXT,
+ kit_json TEXT NOT NULL DEFAULT '{}',
+ chat_json TEXT NOT NULL DEFAULT '[]',
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS brand_kits_updated ON brand_kits(updated_at DESC);
+ CREATE TABLE IF NOT EXISTS products (
+ id TEXT PRIMARY KEY,
+ brand_id TEXT,
+ name TEXT NOT NULL,
+ description TEXT,
+ price REAL,
+ currency TEXT,
+ audience TEXT,
+ selling_points_json TEXT NOT NULL DEFAULT '[]',
+ url TEXT,
+ images_json TEXT NOT NULL DEFAULT '[]',
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS products_brand ON products(brand_id, created_at);
+ CREATE TABLE IF NOT EXISTS ad_batches (
+ id TEXT PRIMARY KEY,
+ brand_id TEXT NOT NULL,
+ engine TEXT NOT NULL,
+ route TEXT NOT NULL,
+ model_id TEXT NOT NULL,
+ direction TEXT,
+ created_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS ad_batches_brand ON ad_batches(brand_id, created_at DESC);
+ CREATE TABLE IF NOT EXISTS ad_creatives (
+ id TEXT PRIMARY KEY,
+ batch_id TEXT NOT NULL,
+ brand_id TEXT NOT NULL,
+ product_id TEXT,
+ position INTEGER NOT NULL DEFAULT 0,
+ status TEXT NOT NULL,
+ angle TEXT,
+ headline TEXT,
+ body TEXT,
+ cta TEXT,
+ visual TEXT,
+ generation_id TEXT,
+ layout TEXT,
+ meta_json TEXT,
+ error TEXT,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS ad_creatives_brand ON ad_creatives(brand_id, created_at DESC);
+ CREATE INDEX IF NOT EXISTS ad_creatives_batch ON ad_creatives(batch_id);
+ CREATE INDEX IF NOT EXISTS ad_creatives_generation ON ad_creatives(generation_id);
+ CREATE TABLE IF NOT EXISTS marketing_runs (
+ id TEXT PRIMARY KEY,
+ feature TEXT NOT NULL,
+ batch_id TEXT NOT NULL,
+ final_ids_json TEXT NOT NULL DEFAULT '[]',
+ engine TEXT NOT NULL,
+ title TEXT NOT NULL,
+ meta_json TEXT NOT NULL DEFAULT '{}',
+ created_at INTEGER NOT NULL
+ );
+ CREATE INDEX IF NOT EXISTS marketing_runs_feature ON marketing_runs(feature, created_at DESC);`,
];
declare global {
diff --git a/src/server/generations.ts b/src/server/generations.ts
index e5034312..b2ebeee1 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -208,6 +208,10 @@ const ASSET_REFS: { table: string; cols: string[]; except?: string }[] = [
{ table: "cinema_projects", cols: ["cover_url", "palettes_json", "director_json", "chat_json", "brief_body"] },
{ table: "cinema_items", cols: ["meta_json"], except: "generation_id" },
{ table: "canvases", cols: ["graph_json"] },
+ { table: "brand_kits", cols: ["kit_json", "chat_json"] },
+ { table: "products", cols: ["images_json"] },
+ { table: "ad_creatives", cols: ["meta_json"] },
+ { table: "marketing_runs", cols: ["meta_json"] },
];
/** Whether anything still refers to this stored file (see ASSET_REFS). */
diff --git a/src/server/marketing.ts b/src/server/marketing.ts
new file mode 100644
index 00000000..2d695db1
--- /dev/null
+++ b/src/server/marketing.ts
@@ -0,0 +1,963 @@
+import "server-only";
+import { nanoid } from "nanoid";
+import { z } from "zod";
+import { getModel, supportsOp } from "@/lib/catalog";
+import {
+ AD_STYLES,
+ brandLine,
+ CLICK_TO_AD,
+ cueLines,
+ estimateCues,
+ fitScript,
+ FORMATS,
+ formatModels,
+ hookById,
+ MAX_PROMPT,
+ mentionsFor,
+ MULTIPLIER,
+ MULTIPLIER_MODELS,
+ multiplierResolution,
+ multiplierText,
+ settingById,
+ shotPlan,
+ snapDuration,
+ styleById,
+ TEMPLATE_INDEX,
+ UGC_MODELS,
+ wordBudget,
+ type BrandKit,
+ type FormatDef,
+ type FormatId,
+ type MarketingRun,
+ type MarketingRunMeta,
+ type MarketingTemplate,
+ type PlannedStep,
+ type Product,
+ type RunEstimate,
+ type RunFeature,
+} from "@/lib/catalog/marketing";
+import { routesFor } from "@/lib/catalog/plan";
+import type { ChainSlot, Engine, GenerationRequest, ModelDef, Operation } from "@/lib/catalog/types";
+import { getBrand, getProduct } from "./brand";
+import { createPipeline, type PipelineStep } from "./chains";
+import { db } from "./db";
+import { llmText } from "./enhance";
+import { createGenerations, listGenerations, previewChained } from "./generations";
+import { provider } from "./providers";
+import { engineMode } from "./settings";
+
+/**
+ * Marketing Studio (templates → product shots, posters, ads, product motion, UGC presenters),
+ * Click to Ad (product link → 9:16 voiced ad) and Ad Multiplier (a reference ad → new versions).
+ * Every run is one batch of generations — single requests, or chained steps through createPipeline —
+ * recorded in marketing_runs with what made it (template, product, script, the text the browser sets
+ * over open-engine posters). Both engines; demo mode runs every step on the mock provider.
+ */
+
+const FILE = z.string().startsWith("/api/files/");
+
+// ---------------------------------------------------------------------------
+// Inputs
+
+export const MarketingBody = z.object({
+ engine: z.enum(["cloud", "open"]),
+ format: z.enum(["product-standalone", "product-with-model", "motion-2d", "motion-hyper", "motion-mixed", "motion-saas", "ugc-talking", "tiktok", "ads", "poster", "marketplace"]),
+ templateId: z.string().max(80).optional(),
+ modelId: z.string().max(80).optional(),
+ productId: z.string().max(40).optional(),
+ /** Product pictures (uploaded, or the product's own; the first is the hero). */
+ productImages: z.array(FILE).max(6).optional(),
+ avatar: FILE.optional(),
+ reference: FILE.optional(),
+ brandId: z.string().max(40).optional(),
+ hookId: z.string().max(40).nullish(),
+ settingId: z.string().max(40).nullish(),
+ prompt: z.string().max(MAX_PROMPT).optional(),
+ headline: z.string().max(140).optional(),
+ cta: z.string().max(40).optional(),
+ aspectRatio: z.string().max(8).optional(),
+ duration: z.number().min(3).max(30).optional(),
+ batch: z.number().int().min(1).max(4).optional(),
+ voice: z.string().max(80).optional(),
+ voiceSample: FILE.optional(),
+ script: z.string().max(2000).optional(),
+ website: z.string().max(300).optional(),
+});
+export type MarketingInput = z.infer<typeof MarketingBody>;
+
+export const ClickToAdBody = z.object({
+ engine: z.enum(["cloud", "open"]),
+ productId: z.string().max(40),
+ styleId: z.string().max(40),
+ /** Pictures to use (3 by default; drag to reorder in the kit). */
+ images: z.array(FILE).max(5).optional(),
+ presenter: z.boolean().optional(),
+ script: z.string().max(1200).optional(),
+ /** Custom-script instructions ("highlight free shipping"). */
+ instructions: z.string().max(600).optional(),
+ quality: z.enum(["480p", "720p"]).optional(),
+ voice: z.string().max(80).optional(),
+ voiceSample: FILE.optional(),
+ avatar: FILE.optional(),
+});
+export type ClickToAdInput = z.infer<typeof ClickToAdBody>;
+
+export const MultiplierBody = z.object({
+ engine: z.enum(["cloud", "open"]),
+ video: FILE,
+ /** The clip's length (read in the browser), for the 4–30 s rule and the price. */
+ duration: z.number().min(0.5).max(600),
+ start: z.number().min(0).optional(),
+ end: z.number().min(0).optional(),
+ images: z.array(FILE).max(MULTIPLIER.maxImages).optional(),
+ mode: z.enum(["prompt", "sections"]),
+ prompt: z.string().max(MULTIPLIER.maxChars).optional(),
+ hook: z.string().max(MULTIPLIER.maxChars).nullish(),
+ cta: z.string().max(MULTIPLIER.maxChars).nullish(),
+ quality: z.enum(MULTIPLIER.qualities),
+ modelId: z.string().max(80).optional(),
+ /** Frames grabbed in the browser at the in and out points (hook / CTA mode). */
+ firstFrame: FILE.optional(),
+ lastFrame: FILE.optional(),
+ versions: z.number().int().min(1).max(4).optional(),
+});
+export type MultiplierInput = z.infer<typeof MultiplierBody>;
+
+// ---------------------------------------------------------------------------
+// Plans: steps with labels, before anything is created
+
+interface Step {
+ key: string;
+ label: string;
+ request: GenerationRequest;
+ after?: string[];
+ chain?: ChainSlot[];
+}
+
+export interface RunPlan {
+ feature: RunFeature;
+ engine: Engine;
+ title: string;
+ steps: Step[];
+ /** Keys of the result steps. */
+ finals: string[];
+ meta: MarketingRunMeta;
+ notes: string[];
+}
+
+export class PlanError extends Error {}
+
+const need = (model: string): ModelDef => {
+ const m = getModel(model);
+ if (!m) throw new PlanError(`Unknown model ${model}`);
+ return m;
+};
+
+/** The model's own aspect ratio closest to the wanted one ("auto" when it takes it, else by shape). */
+export function nearestAspect(want: string | undefined, allowed: string[] | undefined): string | undefined {
+ if (!want || !allowed?.length || allowed.includes(want)) return want;
+ const ratio = (s: string) => {
+ const [a, b] = s.split(":").map(Number);
+ return a && b ? a / b : NaN;
+ };
+ const r = ratio(want);
+ if (!Number.isFinite(r)) return allowed[0];
+ return [...allowed].filter((a) => Number.isFinite(ratio(a))).sort((a, b) => Math.abs(Math.log(ratio(a) / r)) - Math.abs(Math.log(ratio(b) / r)))[0];
+}
+
+const isSvg = (u?: string) => !!u && /\.svg(\?|$)/i.test(u);
+const sentence = (s?: string) => (s ? s.trim().replace(/[.\s]+$/, "") : "");
+const join = (...parts: (string | false | 0 | undefined | null)[]) =>
+ parts
+ .map((p) => (p ? sentence(p) : ""))
+ .filter(Boolean)
+ .join(". ") + ".";
+
+const fill = (s: string, product?: Product | null, brand?: BrandKit | null) =>
+ s.replace(/\{product\}/g, product?.name ?? "it").replace(/\{brand\}/g, brand?.name ?? product?.name ?? "").trim();
+
+function productLine(p?: Product | null): string {
+ if (!p) return "";
+ const pts = p.sellingPoints.slice(0, 2).join("; ");
+ return `The product is ${p.name}${p.description ? ` — ${p.description.slice(0, 160)}` : ""}${pts ? ` (${pts})` : ""}`;
+}
+
+const KEEP_PRODUCT = "Keep the product exactly as in the reference photo: its shape, proportions, label, logo, text and colours";
+
+/** The exact headline/CTA in a prompt (cloud models render text), or room left for the browser to set it (open). */
+function textLine(f: FormatDef, open: boolean, headline?: string, cta?: string, brand?: BrandKit | null): string {
+ if (!f.text) return "";
+ if (open) return "Leave clean, uncluttered space at the top third for a headline; no text, letters, words or logos anywhere in the image";
+ const font = brand?.fonts.heading ? `set in a ${brand.fonts.heading}-style typeface` : "in bold, clean typography";
+ return [headline && `The headline reads exactly “${headline}” ${font}`, cta && `a button that says exactly “${cta}”`, "spell every word exactly as written, no other text"].filter(Boolean).join(", ");
+}
+
+export interface PlanContext {
+ product?: Product | null;
+ brand?: BrandKit | null;
+ higgsfield: boolean;
+ /** The words the presenter says (UGC). */
+ script?: string;
+}
+
+/** Marketing Studio: one run of a template (images) or a pipeline (motion over several shots, UGC). */
+export function planMarketing(input: MarketingInput, ctx: PlanContext): RunPlan {
+ const f = FORMATS[input.format as FormatId];
+ const tpl: MarketingTemplate | undefined = input.templateId ? TEMPLATE_INDEX.get(input.templateId) : undefined;
+ if (input.templateId && !tpl) throw new PlanError("This preset is no longer available.");
+ if (tpl && tpl.format !== f.id) throw new PlanError("That template belongs to another format");
+ const open = input.engine === "open";
+ const product = ctx.product ?? null;
+ const brand = f.brandKit ? (ctx.brand ?? null) : null;
+ const productImages = input.productImages?.length ? input.productImages : (product?.images ?? []);
+ const hasProduct = productImages.length > 0;
+ const prompt = input.prompt?.trim() ?? "";
+ // Required inputs, in Higgsfield's words.
+ if (f.product === "required" && !hasProduct) throw new PlanError(product ? `${product.name} has no images` : "Attach a product to generate");
+ if (f.oneOf?.length) {
+ const has = { product: hasProduct, avatar: !!input.avatar, prompt: !!prompt, website: !!(input.website?.trim() || brand?.website) };
+ if (!f.oneOf.some((k) => has[k])) {
+ throw new PlanError(f.id === "product-with-model" ? "Attach reference or product" : f.id === "poster" ? "Add a prompt or a product" : "Add a prompt, a product or a website");
+ }
+ }
+ const choices = formatModels(f, input.engine, { product: hasProduct, avatar: !!input.avatar, higgsfield: ctx.higgsfield });
+ const name = tpl?.name ?? f.name;
+ const title = [name, product?.name ?? brand?.name].filter(Boolean).join(" · ");
+ const meta: MarketingRunMeta = { format: f.id, templateId: tpl?.id, productId: product?.id ?? null, brandId: brand?.id ?? null };
+ const notes: string[] = [];
+ const brandText = brandLine(brand);
+ const feature = "marketing";
+
+ if (f.pipeline === "image") {
+ const modelId = input.modelId && choices.some((c) => c.id === input.modelId) ? input.modelId : choices[0].id;
+ const model = need(modelId);
+ const refs = [
+ ...(f.product !== "none" ? productImages.slice(0, 1) : []),
+ ...(input.avatar && f.avatar !== "none" ? [input.avatar] : []),
+ ...(input.reference ? [input.reference] : []),
+ // The logo as a reference lets cloud models draw it; open results get it set on top in the browser.
+ ...(!open && f.text && brand?.logo && !isSvg(brand.logo) ? [brand.logo] : []),
+ ];
+ const max = model.options.maxImages ?? (supportsOp(model, "edit") ? 1 : 0);
+ let images = refs.slice(0, Math.max(0, max));
+ if (images.length < refs.length) notes.push(`${model.name} takes ${max} reference image${max === 1 ? "" : "s"}; the rest are left out`);
+ let op: Operation = images.length && supportsOp(model, "edit") ? "edit" : "t2i";
+ if (op === "t2i" && !supportsOp(model, "t2i")) {
+ if (!images.length) throw new PlanError(`${model.name} needs a product photo`);
+ op = "edit";
+ }
+ if (op === "t2i") images = [];
+ const headline = input.headline?.trim() || (tpl?.headline ? fill(tpl.headline, product, brand) : "");
+ const cta = input.cta?.trim() || (tpl?.cta ? fill(tpl.cta, product, brand) : "");
+ const person = input.avatar ? "the person from the reference photo (same face, hair, skin tone and build)" : "a natural-looking model who suits the product";
+ const scene = tpl ? fill(tpl.prompt, product, brand) : "";
+ const text = join(
+ f.id === "product-with-model"
+ ? `Photograph of ${person} with the product`
+ : f.id === "poster"
+ ? "A designed poster"
+ : f.id === "marketplace"
+ ? "A marketplace listing image for an online store"
+ : f.id === "ads"
+ ? "A finished social media ad"
+ : "Commercial product photograph",
+ scene,
+ productLine(product),
+ hasProduct && op === "edit" && KEEP_PRODUCT,
+ input.reference && "Use the last reference photo for the setting and light",
+ prompt,
+ textLine(f, open, headline, cta, brand),
+ brandText,
+ );
+ // bria-product-shot and Product Photography take the scene alone.
+ const scenePrompt = modelId === "bria-product-shot" ? join(scene || "A clean studio scene", prompt, brand?.aesthetics.slice(0, 2).join(", ")) : text;
+ const palette = !open && brand?.colors.length && routesFor(model, op).some((r) => r.map?.palette) ? brand.colors.slice(0, 5) : undefined;
+ const aspect = nearestAspect(input.aspectRatio ?? tpl?.aspect ?? f.defaultAspect, model.options.aspectRatios);
+ const batch = Math.min(input.batch ?? 1, f.batch);
+ meta.overlay = open && f.text && (headline || cta) ? { headline: headline || undefined, cta: cta || undefined } : null;
+ if (open && f.text) notes.push("Your headline is set over the picture in your brand fonts, so the words come out exact");
+ return {
+ feature,
+ engine: input.engine,
+ title,
+ steps: [
+ {
+ key: "image",
+ label: name,
+ request: {
+ feature,
+ modelId,
+ op,
+ prompt: model.options.promptless ? undefined : scenePrompt.slice(0, MAX_PROMPT),
+ inputs: images.length ? { images } : undefined,
+ params: { aspectRatio: aspect, numOutputs: batch, ...(palette && { palette }) },
+ title,
+ batchTitle: title,
+ },
+ },
+ ],
+ finals: ["image"],
+ meta,
+ notes,
+ };
+ }
+
+ if (f.pipeline === "motion") {
+ const modelId = input.modelId && choices.some((c) => c.id === input.modelId) ? input.modelId : choices[0].id;
+ const model = need(modelId);
+ const want = input.duration ?? tpl?.duration ?? f.durations!.default;
+ const aspect = nearestAspect(input.aspectRatio ?? f.defaultAspect, model.options.aspectRatios);
+ const refs = [...productImages.slice(0, 1), ...(input.reference ? [input.reference] : [])];
+ const motionText = (extra?: string) =>
+ join(tpl ? fill(tpl.prompt, product, brand) : "A polished product commercial", extra, productLine(product), hasProduct && "The product stays exactly as in the first frame: same shape, label and colours", prompt, brandText, !hasProduct && input.website && `For the product at ${input.website}`);
+ const base = { feature, modelId, params: { aspectRatio: aspect } as GenerationRequest["params"] };
+ // Open models make a few seconds per clip: longer motion is several shots from the product photo, joined.
+ const shots = open ? shotPlan(want, model.options.durations) : [snapDuration(want, model.options.durations)];
+ if (!open && shots[0] !== want) notes.push(`${model.name} makes ${shots[0]} s clips — the closest to ${want} s`);
+ const op: Operation = refs.length > 1 && supportsOp(model, "ref2v") ? "ref2v" : refs.length ? "i2v" : "t2v";
+ if (op === "t2v" && !supportsOp(model, "t2v")) throw new PlanError("Attach a product to generate");
+ const VARIATIONS = ["Wide establishing shot that introduces the product", "Slow push-in to a close-up of the product's details", "Graceful orbit around the product that ends on its hero angle", "Macro detail pass over the texture and label"];
+ const steps: Step[] = shots.map((d, i) => ({
+ key: `shot${i + 1}`,
+ label: shots.length > 1 ? `Shot ${i + 1} of ${shots.length}` : name,
+ request: {
+ ...base,
+ feature: shots.length > 1 ? `${feature}-step` : feature,
+ op,
+ prompt: motionText(shots.length > 1 ? VARIATIONS[i % VARIATIONS.length] : undefined).slice(0, MAX_PROMPT),
+ inputs: op === "t2v" ? undefined : { images: op === "ref2v" ? refs : refs.slice(0, 1) },
+ params: { ...base.params, duration: d, ...(model.options.audio && { generateAudio: true }) },
+ title,
+ },
+ }));
+ if (shots.length > 1) {
+ const joiner = UGC_MODELS[input.engine].join;
+ steps.push({
+ key: "film",
+ label: `${name} · ${shots.length} shots`,
+ request: { feature, modelId: joiner, op: "concat", prompt: title, params: { aspectRatio: nearestAspect(aspect, need(joiner).options.aspectRatios) }, chain: shots.map(() => ({ slot: "videos" as const })), title, batchTitle: title },
+ after: shots.map((_, i) => `shot${i + 1}`),
+ });
+ notes.push(`${model.name} makes up to ${Math.max(...(model.options.durations ?? [5]))} s per clip: ${shots.length} shots from your product photo, joined`);
+ }
+ return { feature, engine: input.engine, title, steps, finals: [steps[steps.length - 1].key], meta, notes };
+ }
+
+ // UGC / TikTok: voice → presenter still → talking clip → captions (+ hook clip, product close-up) → join.
+ return planPresenter({
+ feature,
+ engine: input.engine,
+ title,
+ meta,
+ script: ctx.script ?? "",
+ product,
+ productImages,
+ brand,
+ avatar: input.avatar,
+ reference: input.reference,
+ aspect: input.aspectRatio ?? f.defaultAspect,
+ hook: f.hookAndSetting ? hookById(input.hookId === undefined ? tpl?.hook : input.hookId) : undefined,
+ setting: f.hookAndSetting ? settingById(input.settingId === undefined ? tpl?.setting : input.settingId) : undefined,
+ look: tpl ? fill(tpl.prompt, product, brand) : undefined,
+ voice: input.voice,
+ voiceSample: input.voiceSample,
+ talkModel: !open && input.modelId && choices.some((c) => c.id === input.modelId) ? input.modelId : undefined,
+ broll: hasProduct,
+ notes,
+ });
+}
+
+interface PresenterPlan {
+ feature: RunFeature;
+ engine: Engine;
+ title: string;
+ meta: MarketingRunMeta;
+ script: string;
+ product: Product | null;
+ productImages: string[];
+ brand: BrandKit | null;
+ avatar?: string;
+ reference?: string;
+ aspect: string;
+ hook?: ReturnType<typeof hookById>;
+ setting?: ReturnType<typeof settingById>;
+ look?: string;
+ voice?: string;
+ voiceSample?: string;
+ talkModel?: string;
+ /** A product close-up after the presenter. */
+ broll: boolean;
+ /** Seconds of product close-up (Click to Ad keeps the ad ≤ 12 s). */
+ brollSeconds?: number;
+ quality?: string;
+ notes: string[];
+}
+
+/** A talking presenter with the product: the shared UGC chain (Marketing Studio UGC/TikTok, Click to Ad). */
+function planPresenter(p: PresenterPlan): RunPlan {
+ const open = p.engine === "open";
+ const M = UGC_MODELS[p.engine];
+ const step = `${p.feature}-step`;
+ if (!p.script.trim()) throw new PlanError("Write the script first");
+ if (open && !p.voiceSample) throw new PlanError("Add a voice sample — open-source voices are cloned from a short recording");
+ const seconds = p.script.split(/\s+/).filter(Boolean).length / 2.5;
+ const talkId = p.talkModel ?? (open ? (seconds > 6.5 ? "oss-infinitetalk-long" : M.talk) : M.talk);
+ const talk = need(talkId);
+ const stillModel = need(M.still);
+ const clip = need(M.clip);
+ const aspect = nearestAspect(p.aspect, talk.options.aspectRatios) ?? p.aspect;
+ const refs = [...(p.avatar ? [p.avatar] : []), ...p.productImages.slice(0, 1), ...(p.reference ? [p.reference] : [])].slice(0, stillModel.options.maxImages ?? 3);
+ const person = p.avatar ? "the person from the first reference photo (same face, hair and skin tone)" : "a friendly, relatable creator in their twenties";
+ const holding = p.productImages.length ? `holding the product from the ${p.avatar ? "second reference photo" : "reference photo"} up near their face` : "talking to the camera";
+ const where = p.setting?.prompt ?? "at home in natural light";
+ const steps: Step[] = [
+ {
+ key: "voice",
+ label: "Voiceover",
+ request: {
+ feature: step,
+ modelId: M.voice,
+ op: "tts",
+ prompt: p.script,
+ inputs: open ? { voiceAudio: p.voiceSample } : undefined,
+ params: !open && p.voice ? { voice: p.voice } : undefined,
+ },
+ },
+ {
+ key: "still",
+ label: "Presenter",
+ request: {
+ feature: step,
+ modelId: refs.length ? M.still : open ? "oss-qwen-image" : M.still,
+ op: refs.length ? "edit" : "t2i",
+ prompt: join(
+ `A vertical smartphone selfie video frame of ${person} ${holding}, ${where}`,
+ p.look,
+ p.productImages.length && KEEP_PRODUCT,
+ "Authentic UGC look, natural light, eye contact with the camera, mouth relaxed and closed, ready to speak",
+ p.brand && brandLine(p.brand),
+ ),
+ inputs: refs.length ? { images: refs } : undefined,
+ params: { aspectRatio: nearestAspect(aspect, (refs.length ? stillModel : need(open ? "oss-qwen-image" : M.still)).options.aspectRatios) ?? aspect, numOutputs: 1 },
+ },
+ },
+ {
+ key: "talk",
+ label: "Talking",
+ request: { feature: step, modelId: talkId, op: "avatar", prompt: "Natural talking presenter, small hand gestures, looks into the camera", params: { aspectRatio: aspect, ...(p.quality && { resolution: p.quality }) } },
+ after: ["still", "voice"],
+ chain: [{ slot: "images" }, { slot: "audio" }],
+ },
+ {
+ key: "captions",
+ label: "Captions",
+ request: open
+ ? { feature: step, modelId: M.captions, op: "captions", prompt: cueLines(estimateCues(p.script)) }
+ : { feature: step, modelId: M.captions, op: "captions", params: languageCode(p.brand?.language) ? { sourceLanguage: languageCode(p.brand?.language) } : undefined },
+ after: ["talk"],
+ chain: [{ slot: "video" }],
+ },
+ ];
+ const clipLen = (want: number) => snapDuration(want, clip.options.durations);
+ const clips: string[] = [];
+ if (p.hook) {
+ steps.push({
+ key: "hook",
+ label: `Hook · ${p.hook.name}`,
+ request: {
+ feature: step,
+ modelId: M.clip,
+ op: "i2v",
+ prompt: join(p.hook.prompt, "Same person, outfit and setting as the frame", "Vertical handheld phone footage, energetic UGC style"),
+ params: { aspectRatio: nearestAspect(aspect, clip.options.aspectRatios), duration: clipLen(4), ...(clip.options.audio && { generateAudio: true }), ...(p.quality && { resolution: p.quality }) },
+ chain: [{ slot: "images", position: "first" }],
+ },
+ after: ["still"],
+ });
+ clips.push("hook");
+ }
+ clips.push("captions");
+ if (p.broll && p.productImages.length) {
+ steps.push({
+ key: "broll",
+ label: "Product close-up",
+ request: {
+ feature: step,
+ modelId: M.clip,
+ op: "i2v",
+ prompt: join("Handheld close-up of the product turning slowly in soft natural light, shallow depth of field", KEEP_PRODUCT),
+ inputs: { images: p.productImages.slice(0, 1) },
+ params: { aspectRatio: nearestAspect(aspect, clip.options.aspectRatios), duration: clipLen(p.brollSeconds ?? 4), ...(clip.options.audio && { generateAudio: false }), ...(p.quality && { resolution: p.quality }) },
+ },
+ });
+ clips.push("broll");
+ }
+ if (clips.length > 1) {
+ steps.push({
+ key: "film",
+ label: "Final video",
+ request: { feature: p.feature, modelId: M.join, op: "concat", prompt: p.title, params: { aspectRatio: nearestAspect(aspect, need(M.join).options.aspectRatios) }, chain: clips.map(() => ({ slot: "videos" as const })), title: p.title, batchTitle: p.title },
+ after: clips,
+ });
+ } else {
+ const c = steps.find((s) => s.key === "captions")!;
+ c.request = { ...c.request, feature: p.feature, title: p.title, batchTitle: p.title };
+ }
+ if (open) p.notes.push("Open captions are timed from the script at a natural speaking pace");
+ if (open && clips.length > 1) p.notes.push("The open-source join keeps the picture; the hook and close-up play without the voiceover");
+ p.meta.script = p.script;
+ return { feature: p.feature, engine: p.engine, title: p.title, steps, finals: [steps[steps.length - 1].key === "film" ? "film" : "captions"], meta: p.meta, notes: p.notes };
+}
+
+// ---------------------------------------------------------------------------
+// Scripts
+
+const SCRIPT_SYSTEM = `You write short spoken scripts for vertical video ads (TikTok, Reels, Shorts).
+Write ONLY the words the presenter says out loud: no stage directions, no scene notes, no emojis, no hashtags, no quotation marks, no labels.
+Sound like a real person talking to a friend, open with a hook in the first line, end with a short call to action.`;
+
+export interface ScriptInput {
+ product?: Product | null;
+ brand?: BrandKit | null;
+ seconds: number;
+ hook?: string;
+ angle?: string;
+ style?: string;
+ instructions?: string;
+ language?: string;
+}
+
+/** A natural script from facts alone, for installs with no LLM. */
+export function heuristicScript(s: ScriptInput): string {
+ const name = s.product?.name ?? s.brand?.name ?? "this";
+ const points = [...(s.product?.sellingPoints ?? []), ...(s.brand?.sellingPoints ?? [])].map(sentence).filter(Boolean);
+ const opener = s.hook ? `Okay, that was not how I planned to start this, but I have to tell you about ${name}.` : `I didn't expect ${name} to become part of my every day, but here we are.`;
+ const body = points.length ? points.slice(0, 2).map((p, i) => (i === 0 ? `First, ${p.charAt(0).toLowerCase()}${p.slice(1)}.` : `And ${p.charAt(0).toLowerCase()}${p.slice(1)}.`)).join(" ") : `It just works, it looks great, and it makes my day a little easier.`;
+ const extra = s.instructions ? `${sentence(s.instructions)}.` : "";
+ const close = s.brand?.website ? `Go check out ${s.brand.name} — link's in my bio.` : `Honestly? Go try it for yourself.`;
+ return fitScript([opener, body, extra, close].filter(Boolean).join(" "), s.seconds);
+}
+
+/** The words the presenter says: the LLM when one is set up, else the heuristic. Always within the word budget. */
+export async function writeScript(s: ScriptInput): Promise<{ script: string; by: "llm" | "rules" }> {
+ const words = wordBudget(s.seconds);
+ const user = [
+ `Length: about ${words} words (${Math.round(s.seconds)} seconds spoken).`,
+ s.product && `Product: ${s.product.name}${s.product.description ? ` — ${s.product.description.slice(0, 500)}` : ""}`,
+ s.product?.sellingPoints.length && `Selling points: ${s.product.sellingPoints.join("; ")}`,
+ s.product?.audience && `Audience: ${s.product.audience}`,
+ s.brand && `Brand: ${s.brand.name}${s.brand.tagline ? ` — ${s.brand.tagline}` : ""}. Tone: ${s.brand.tone.join(", ") || "friendly"}.`,
+ s.angle && `Format: ${s.angle}`,
+ s.hook && `Opening hook (what happens on screen): ${s.hook}`,
+ s.style && `Delivery: ${s.style}`,
+ s.instructions && `Instructions: ${s.instructions}`,
+ `Language: ${s.language ?? s.brand?.language ?? "English"}`,
+ ]
+ .filter(Boolean)
+ .join("\n");
+ const out = await llmText(SCRIPT_SYSTEM, user);
+ const cleaned = out
+ ?.replace(/^\s*(script|presenter|voiceover|narrator)\s*:\s*/i, "")
+ .replace(/\[[^\]]*\]|\([^)]*\)/g, "")
+ .replace(/["“”]/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+ return cleaned && cleaned.split(" ").length >= 5 ? { script: fitScript(cleaned, s.seconds), by: "llm" } : { script: heuristicScript(s), by: "rules" };
+}
+
+// ---------------------------------------------------------------------------
+// Click to Ad: product link → product kit → style → 9:16 voiced ad (≤ 12 s)
+
+/** Seconds of voice that fit the ad: the presenter talks, then a product close-up ends it. */
+export function clickToAdSeconds(engine: Engine, presenter: boolean): { voice: number; broll: number } {
+ if (presenter) return { voice: 8, broll: 4 };
+ const clip = need(UGC_MODELS[engine].clip);
+ const shots = engine === "open" ? shotPlan(9, clip.options.durations) : [4, 4, 4];
+ return { voice: Math.max(4, Math.min(CLICK_TO_AD.maxSeconds, shots.reduce((a, b) => a + b, 0)) - 0.6), broll: 0 };
+}
+
+export function planClickToAd(input: ClickToAdInput, ctx: { product: Product; brand?: BrandKit | null; script: string }): RunPlan {
+ const style = styleById(input.styleId);
+ if (!style) throw new PlanError("Pick a style");
+ const images = input.images?.length ? input.images : ctx.product.images;
+ if (!images.length) throw new PlanError(`${ctx.product.name} has no images`);
+ const presenter = input.presenter ?? style.presenter;
+ const open = input.engine === "open";
+ const title = `${style.name} · ${ctx.product.name}`;
+ const meta: MarketingRunMeta = { productId: ctx.product.id, brandId: ctx.brand?.id ?? null, styleId: style.id, script: ctx.script };
+ const notes: string[] = [];
+ const quality = input.quality ?? "480p";
+ if (presenter) {
+ return planPresenter({
+ feature: "click-to-ad",
+ engine: input.engine,
+ title,
+ meta,
+ script: ctx.script,
+ product: ctx.product,
+ productImages: images,
+ brand: ctx.brand ?? null,
+ avatar: input.avatar,
+ aspect: CLICK_TO_AD.aspect,
+ look: style.visual,
+ voice: input.voice,
+ voiceSample: input.voiceSample,
+ broll: true,
+ brollSeconds: clickToAdSeconds(input.engine, true).broll,
+ quality,
+ notes,
+ });
+ }
+ // Product only: three shots from the kit's pictures, joined, the voiceover laid under, then captions.
+ if (!ctx.script.trim()) throw new PlanError("Write the script first");
+ if (open && !input.voiceSample) throw new PlanError("Add a voice sample — open-source voices are cloned from a short recording");
+ const M = UGC_MODELS[input.engine];
+ const clip = need(M.clip);
+ const lens = open ? shotPlan(9, clip.options.durations) : [4, 4, 4];
+ const angles = ["Hero shot, the camera glides in", "Close-up on the details as light sweeps across", "The product in use, ending on a clean final frame"];
+ const step = "click-to-ad-step";
+ const steps: Step[] = [
+ { key: "voice", label: "Voiceover", request: { feature: step, modelId: M.voice, op: "tts", prompt: ctx.script, inputs: open ? { voiceAudio: input.voiceSample } : undefined, params: !open && input.voice ? { voice: input.voice } : undefined } },
+ ...lens.map(
+ (d, i): Step => ({
+ key: `shot${i + 1}`,
+ label: `Shot ${i + 1} of ${lens.length}`,
+ request: {
+ feature: step,
+ modelId: M.clip,
+ op: "i2v",
+ prompt: join(angles[i % angles.length], style.visual, `Vertical 9:16 ad for ${ctx.product.name}`, KEEP_PRODUCT, ctx.brand && brandLine(ctx.brand)),
+ inputs: { images: [images[i % images.length]] },
+ params: { aspectRatio: nearestAspect(CLICK_TO_AD.aspect, clip.options.aspectRatios), duration: d, resolution: quality, ...(clip.options.audio && { generateAudio: false }) },
+ },
+ }),
+ ),
+ {
+ key: "film",
+ label: "Joining the shots",
+ request: { feature: step, modelId: M.join, op: "concat", prompt: title, params: { aspectRatio: nearestAspect(CLICK_TO_AD.aspect, need(M.join).options.aspectRatios) }, chain: lens.map(() => ({ slot: "videos" as const })) },
+ after: lens.map((_, i) => `shot${i + 1}`),
+ },
+ { key: "mux", label: "Adding the voiceover", request: { feature: step, modelId: M.mux, op: "mux" }, after: ["film", "voice"], chain: [{ slot: "video" }, { slot: "audio" }] },
+ {
+ key: "captions",
+ label: "Captions",
+ request: open
+ ? { feature: "click-to-ad", modelId: M.captions, op: "captions", prompt: cueLines(estimateCues(ctx.script)), title, batchTitle: title }
+ : { feature: "click-to-ad", modelId: M.captions, op: "captions", title, batchTitle: title },
+ after: ["mux"],
+ chain: [{ slot: "video" }],
+ },
+ ];
+ if (open) notes.push("Open captions are timed from the script at a natural speaking pace");
+ return { feature: "click-to-ad", engine: input.engine, title, steps, finals: ["captions"], meta, notes };
+}
+
+// ---------------------------------------------------------------------------
+// Ad Multiplier: a reference ad (4–30 s) → new versions (whole ad, or a new hook / CTA around it)
+
+export function multiplierModel(input: Pick<MultiplierInput, "engine" | "modelId">, higgsfield: boolean): ModelDef {
+ const choices = MULTIPLIER_MODELS[input.engine];
+ const fallback = input.engine === "cloud" && !higgsfield ? "kling-o3" : choices[0].id;
+ const id = input.modelId && choices.some((c) => c.id === input.modelId) ? input.modelId : fallback;
+ return need(id);
+}
+
+export function planMultiplier(input: MultiplierInput, ctx: { higgsfield: boolean; extractFrame?: boolean }): RunPlan {
+ const open = input.engine === "open";
+ const start = Math.max(0, input.start ?? 0);
+ const end = Math.min(input.duration, input.end ?? input.duration);
+ const length = end - start;
+ if (length < MULTIPLIER.minSeconds - 0.05 || length > MULTIPLIER.maxSeconds + 0.05) throw new PlanError("Video duration: 4-30 seconds");
+ const trimmed = start > 0.05 || end < input.duration - 0.05;
+ const images = input.images ?? [];
+ const text = multiplierText({ mode: input.mode, prompt: input.prompt, hook: input.hook, cta: input.cta });
+ if (input.mode === "sections" && input.hook == null && input.cta == null) throw new PlanError("Turn on Change hook or Change CTA");
+ const M = UGC_MODELS[input.engine];
+ const step = "ad-multiplier-step";
+ const meta: MarketingRunMeta = { mode: input.mode };
+ const notes: string[] = [];
+ const steps: Step[] = [];
+ const resolution = multiplierResolution(input.quality, input.engine);
+ if (trimmed) {
+ steps.push({ key: "clip", label: "Trimming the reference", request: { feature: step, modelId: M.trim, op: "trim", inputs: { video: input.video }, params: { startTime: round(start), endTime: round(end) } } });
+ }
+ const source = (slot: "video"): { inputs?: GenerationRequest["inputs"]; after?: string[]; chain?: ChainSlot[] } =>
+ trimmed ? { after: ["clip"], chain: [{ slot }] } : { inputs: { video: input.video } };
+
+ if (input.mode === "prompt") {
+ const model = multiplierModel(input, ctx.higgsfield);
+ const title = `Recreated ad · ${model.name}`;
+ if (open) {
+ // Wan Animate: the first image takes over the reference's performance; the original sound is laid back on.
+ const lead = mentionsFor(text, images, model.id, 1);
+ if (!lead.images.length) throw new PlanError("Add an image of who (or what) should star in the new version");
+ const src = source("video");
+ steps.push({
+ key: "edit",
+ label: "Recreating",
+ request: {
+ feature: trimmed ? "ad-multiplier" : step,
+ modelId: model.id,
+ op: "motion-transfer",
+ prompt: lead.prompt,
+ inputs: { ...src.inputs, images: lead.images },
+ chain: src.chain,
+ ...(trimmed && { title, batchTitle: title }),
+ },
+ after: src.after,
+ });
+ if (!trimmed) {
+ steps.push({ key: "sound", label: "Original sound", request: { feature: "ad-multiplier", modelId: M.mux, op: "mux", inputs: { audio: input.video }, title, batchTitle: title }, after: ["edit"], chain: [{ slot: "video" }] });
+ } else {
+ notes.push("Wan Animate makes the picture only; use the whole clip to keep its original sound");
+ }
+ if (images.length > 1) notes.push("Wan Animate uses one image (the first you mention)");
+ } else {
+ const max = model.options.maxImages ?? 0;
+ const m = mentionsFor(text, images, model.id, model.routes.some((r) => r.op === "v2v" && r.map?.images) ? max : 0);
+ if (m.dropped && images.length) notes.push(max ? `${model.name} takes ${max} images — the first ${max} you mention are used` : `${model.name} edits from the prompt alone; pick Kling O3 to use your images`);
+ const src = source("video");
+ steps.push({
+ key: "edit",
+ label: "Recreating",
+ request: {
+ feature: "ad-multiplier",
+ modelId: model.id,
+ op: "v2v",
+ prompt: m.prompt,
+ inputs: { ...src.inputs, ...(m.images.length && { images: m.images }) },
+ params: { resolution, ...(model.id === "kling-o3" && { extra: { keep_audio: true } }) },
+ chain: src.chain,
+ title,
+ batchTitle: title,
+ },
+ after: src.after,
+ });
+ if (model.id === "seedance-2-5" && !ctx.higgsfield) notes.push("Seedance 2.5 edit runs on Higgsfield — connect a Higgsfield key in Settings");
+ }
+ return { feature: "ad-multiplier", engine: input.engine, title, steps, finals: [steps[steps.length - 1].key], meta, notes };
+ }
+
+ // Hook / CTA: a new clip from the first (or last) frame, joined around the original.
+ const clipModel = need(M.clip);
+ const title = [input.hook != null && "New hook", input.cta != null && "New CTA"].filter(Boolean).join(" + ");
+ const frameModel = getModel(M.frame);
+ const canExtract = !!frameModel && (ctx.extractFrame ?? true);
+ const clipParams = { duration: snapDuration(4, clipModel.options.durations), ...(clipModel.options.audio && { generateAudio: true }), resolution: nearestRes(resolution, clipModel) };
+ const order: string[] = [];
+ if (input.hook != null) {
+ const start = input.firstFrame ?? images[0];
+ if (!start) throw new PlanError("Couldn't read the clip's first frame here — add an image to start the hook from");
+ if (!input.firstFrame) notes.push("The hook starts from your first image (the clip's first frame couldn't be read in this browser)");
+ steps.push({
+ key: "hook",
+ label: "New hook",
+ request: { feature: step, modelId: M.clip, op: "i2v", prompt: join(`Opening hook of the ad: the person on screen says “${(input.hook ?? "").trim() || "Wait — you need to see this"}”`, "Same people, place, light and style as this frame", "Punchy, scroll-stopping first seconds"), inputs: { images: [start] }, params: clipParams },
+ });
+ order.push("hook");
+ }
+ order.push(trimmed ? "clip" : "original");
+ if (input.cta != null) {
+ const ctaPrompt = join(`Closing call to action: the person on screen says “${(input.cta ?? "").trim() || "Try it today"}”`, "Same people, place, light and style as this frame", "End on a confident, clean final frame");
+ if (input.lastFrame) {
+ steps.push({ key: "cta", label: "New CTA", request: { feature: step, modelId: M.clip, op: "i2v", prompt: ctaPrompt, inputs: { images: [input.lastFrame] }, params: clipParams } });
+ } else if (canExtract) {
+ const src = source("video");
+ steps.push({ key: "last", label: "Last frame", request: { feature: step, modelId: M.frame, op: "frame", inputs: src.inputs, chain: src.chain }, after: src.after });
+ steps.push({ key: "cta", label: "New CTA", request: { feature: step, modelId: M.clip, op: "i2v", prompt: ctaPrompt, params: clipParams, chain: [{ slot: "images", position: "first" }] }, after: ["last"] });
+ } else {
+ const fallbackImg = images[0];
+ if (!fallbackImg) throw new PlanError("Couldn't read the clip's last frame here — add an image to end on");
+ steps.push({ key: "cta", label: "New CTA", request: { feature: step, modelId: M.clip, op: "i2v", prompt: ctaPrompt, inputs: { images: [fallbackImg] }, params: clipParams } });
+ notes.push("The CTA starts from your first image (the clip's last frame couldn't be read in this browser)");
+ }
+ order.push("cta");
+ }
+ const joiner = need(M.join);
+ const stepKeys = order.filter((k) => k !== "original");
+ // The original goes in as an input; its place among the chained clips follows from position first/last.
+ const chain: ChainSlot[] = stepKeys.map((k) => ({ slot: "videos" as const, position: order.indexOf(k) < order.indexOf("original") ? ("first" as const) : ("last" as const) }));
+ steps.push({
+ key: "film",
+ label: "Final video",
+ request: { feature: "ad-multiplier", modelId: joiner.id, op: "concat", prompt: title, inputs: trimmed ? undefined : { videos: [input.video] }, chain, title, batchTitle: title },
+ after: stepKeys,
+ });
+ if (open) notes.push("The open-source join keeps the picture; the joined ad plays without sound");
+ return { feature: "ad-multiplier", engine: input.engine, title, steps, finals: ["film"], meta, notes };
+}
+
+const round = (n: number) => Math.round(n * 100) / 100;
+
+const ISO: Record<string, string> = {
+ English: "en", Spanish: "es", French: "fr", German: "de", Italian: "it", Portuguese: "pt", Dutch: "nl", Polish: "pl", Russian: "ru", Turkish: "tr", Japanese: "ja",
+ Korean: "ko", Chinese: "zh", Arabic: "ar", Hindi: "hi", Swedish: "sv", Danish: "da", Norwegian: "no", Finnish: "fi", Greek: "el", Czech: "cs", Hungarian: "hu",
+ Romanian: "ro", Ukrainian: "uk", Vietnamese: "vi", Thai: "th", Indonesian: "id", Hebrew: "he", Kazakh: "kk",
+};
+/** The spoken language for the cloud captioner (ISO code); English needs none. */
+const languageCode = (name?: string) => (name && name !== "English" ? ISO[name] : undefined);
+const nearestRes = (want: string, m: ModelDef) => (m.options.resolutions?.includes(want) ? want : (m.options.resolutions?.filter((r) => parseInt(r) <= parseInt(want)).pop() ?? m.options.resolutions?.[0] ?? want));
+
+// ---------------------------------------------------------------------------
+// Estimates and launching
+
+/** Price and validate every step with placeholders for what earlier steps make (nothing is created). */
+export function estimatePlan(plan: RunPlan, runs = 1): RunEstimate {
+ let total: number | null = 0;
+ let demo = false;
+ const steps: PlannedStep[] = [];
+ for (const s of plan.steps) {
+ const p = previewChained({ ...s.request, ...(s.chain && { chain: s.chain }) }, s.after?.length ?? 0);
+ demo ||= p.demo;
+ steps.push({ key: s.key, label: s.label, modelId: p.model.id, modelName: p.model.name, costUsd: p.costUsd });
+ total = total === null || p.costUsd === null ? null : total + p.costUsd;
+ }
+ return { costUsd: total === null ? null : Math.round(total * runs * 1000) / 1000, demo, steps, notes: plan.notes, runs };
+}
+
+interface RunRow {
+ id: string;
+ feature: RunFeature;
+ batch_id: string;
+ final_ids_json: string;
+ engine: Engine;
+ title: string;
+ meta_json: string;
+ created_at: number;
+}
+
+/** Create the run's generations (one request, or a pipeline) and record the run. */
+export function launch(plan: RunPlan): MarketingRun {
+ const engine = engineMode();
+ if (engine !== "both" && engine !== plan.engine) throw new PlanError(engine === "open" ? "This install is set to open source only (Settings → Engine mode)" : "This install is set to paid cloud APIs only (Settings → Engine mode)");
+ const batchId = nanoid(10);
+ let byKey: Record<string, { id: string }[]>;
+ if (plan.steps.length === 1 && !plan.steps[0].after?.length) {
+ const s = plan.steps[0];
+ byKey = { [s.key]: createGenerations(s.request, { batchId }) };
+ } else {
+ const n = plan.steps.length;
+ const steps: PipelineStep[] = plan.steps.map((s, i) => ({ key: s.key, request: { ...s.request, step: { label: s.label, index: i, of: n } }, after: s.after, chain: s.chain }));
+ const made = createPipeline(steps, { batchId });
+ byKey = Object.fromEntries(Object.entries(made.byKey).map(([k, g]) => [k, [g]]));
+ }
+ const finalIds = plan.finals.flatMap((k) => byKey[k]?.map((g) => g.id) ?? []);
+ const row: RunRow = { id: nanoid(10), feature: plan.feature, batch_id: batchId, final_ids_json: JSON.stringify(finalIds), engine: plan.engine, title: plan.title, meta_json: JSON.stringify({ ...plan.meta, notes: plan.notes }), created_at: Date.now() };
+ db().prepare("INSERT INTO marketing_runs (id, feature, batch_id, final_ids_json, engine, title, meta_json, created_at) VALUES (@id, @feature, @batch_id, @final_ids_json, @engine, @title, @meta_json, @created_at)").run(row);
+ return toRun(row);
+}
+
+function toRun(r: RunRow): MarketingRun {
+ const generations = listGenerations({ batchId: r.batch_id, limit: 200 }).sort((a, b) => a.createdAt - b.createdAt || (a.request.step?.index ?? 0) - (b.request.step?.index ?? 0));
+ return { id: r.id, feature: r.feature, batchId: r.batch_id, engine: r.engine, title: r.title, finalIds: JSON.parse(r.final_ids_json) as string[], meta: JSON.parse(r.meta_json) as MarketingRunMeta, createdAt: r.created_at, generations };
+}
+
+/** Runs of one flow, newest first; a run whose generations were all trashed or deleted drops out. */
+export function listRuns(feature: RunFeature, limit = 30): MarketingRun[] {
+ const rows = db().prepare("SELECT * FROM marketing_runs WHERE feature = ? ORDER BY created_at DESC LIMIT ?").all(feature, Math.min(100, Math.max(1, limit))) as RunRow[];
+ return rows.map(toRun).filter((r) => r.generations.length > 0);
+}
+
+export function getRun(id: string): MarketingRun | null {
+ const r = db().prepare("SELECT * FROM marketing_runs WHERE id = ?").get(id) as RunRow | undefined;
+ return r ? toRun(r) : null;
+}
+
+/** Forget a run (its generations stay in the Library). */
+export function deleteRun(id: string): boolean {
+ return db().prepare("DELETE FROM marketing_runs WHERE id = ?").run(id).changes > 0;
+}
+
+const higgsfieldReady = () => provider("higgsfield").isConfigured();
+
+function context(input: { productId?: string; brandId?: string }) {
+ const product = input.productId ? getProduct(input.productId) : null;
+ if (input.productId && !product) throw new PlanError("This product is no longer available. Choose another one.");
+ const brand = input.brandId ? getBrand(input.brandId) : product?.brandId ? getBrand(product.brandId) : null;
+ return { product, brand, higgsfield: higgsfieldReady() };
+}
+
+const presenterSeconds = (input: MarketingInput) => input.duration ?? FORMATS[input.format].durations?.default ?? 15;
+
+/** Marketing Studio: price a run (a stand-in script of the right length for UGC; no LLM call). */
+export function estimateMarketing(input: MarketingInput): RunEstimate {
+ const ctx = context(input);
+ const f = FORMATS[input.format];
+ const script = f.pipeline === "ugc" ? input.script?.trim() || Array(wordBudget(presenterSeconds(input))).fill("word").join(" ") : undefined;
+ const runs = f.pipeline === "image" ? 1 : Math.min(input.batch ?? 1, f.batch);
+ return estimatePlan(planMarketing(input, { ...ctx, script }), runs);
+}
+
+export async function runMarketing(input: MarketingInput): Promise<{ runs: MarketingRun[]; script?: string }> {
+ const ctx = context(input);
+ const f = FORMATS[input.format];
+ const tpl = input.templateId ? TEMPLATE_INDEX.get(input.templateId) : undefined;
+ let script: string | undefined;
+ if (f.pipeline === "ugc") {
+ const hook = hookById(input.hookId === undefined ? tpl?.hook : input.hookId);
+ script = input.script?.trim()
+ ? fitScript(input.script, presenterSeconds(input))
+ : (await writeScript({ product: ctx.product, brand: ctx.brand, seconds: presenterSeconds(input), hook: hook?.prompt, angle: tpl?.prompt, instructions: input.prompt })).script;
+ }
+ const plan = planMarketing(input, { ...ctx, script });
+ const runs = f.pipeline === "image" ? 1 : Math.min(input.batch ?? 1, f.batch);
+ // Check the whole plan (prices, models, engine mode, demo/real) before creating anything.
+ estimatePlan(plan);
+ return { runs: Array.from({ length: runs }, () => launch(plan)), script };
+}
+
+export function estimateClickToAd(input: ClickToAdInput): RunEstimate {
+ const ctx = context({ productId: input.productId });
+ const presenter = input.presenter ?? styleById(input.styleId)?.presenter ?? false;
+ const script = input.script?.trim() || Array(wordBudget(clickToAdSeconds(input.engine, presenter).voice)).fill("word").join(" ");
+ return estimatePlan(planClickToAd(input, { product: ctx.product!, brand: ctx.brand, script }));
+}
+
+export async function clickToAdScript(input: Pick<ClickToAdInput, "engine" | "productId" | "styleId" | "presenter" | "instructions">): Promise<{ script: string; by: "llm" | "rules"; seconds: number }> {
+ const ctx = context({ productId: input.productId });
+ const style = styleById(input.styleId) ?? AD_STYLES[0];
+ const seconds = clickToAdSeconds(input.engine, input.presenter ?? style.presenter).voice;
+ const r = await writeScript({ product: ctx.product, brand: ctx.brand, seconds, style: `${style.name}: ${style.voice}`, instructions: input.instructions });
+ return { ...r, seconds };
+}
+
+export async function runClickToAd(input: ClickToAdInput): Promise<{ run: MarketingRun; script: string }> {
+ const ctx = context({ productId: input.productId });
+ if (!ctx.product) throw new PlanError("Select a product or enter a product URL");
+ const presenter = input.presenter ?? styleById(input.styleId)?.presenter ?? false;
+ const seconds = clickToAdSeconds(input.engine, presenter).voice;
+ const script = input.script?.trim() ? fitScript(input.script, seconds) : (await clickToAdScript(input)).script;
+ const plan = planClickToAd(input, { product: ctx.product, brand: ctx.brand, script });
+ estimatePlan(plan);
+ return { run: launch(plan), script };
+}
+
+export function estimateMultiplier(input: MultiplierInput): RunEstimate {
+ const plan = planMultiplier(input, { higgsfield: higgsfieldReady() });
+ return estimatePlan(plan, input.versions ?? 1);
+}
+
+export function runMultiplier(input: MultiplierInput): MarketingRun[] {
+ const plan = planMultiplier(input, { higgsfield: higgsfieldReady() });
+ estimatePlan(plan);
+ return Array.from({ length: input.versions ?? 1 }, () => launch(plan));
+}
+
+// ---------------------------------------------------------------------------
+// Route helpers (src/app/api/{brands,products,ads,marketing}/**)
+
+/** Parse a JSON body; a 400 Response with a readable message when it doesn't fit. */
+export async function readBody<S extends z.ZodType>(request: Request, schema: S, message = "Check the form and try again"): Promise<z.infer<S> | Response> {
+ const parsed = schema.safeParse(await request.json().catch(() => null));
+ if (parsed.success) return parsed.data;
+ const first = parsed.error.issues[0];
+ return Response.json({ error: first ? `${message} (${first.path.join(".") || "body"}: ${first.message})` : message }, { status: 400 });
+}
+
+/** A thrown error as a JSON response: 409 for duplicates, 422 for everything the user can fix. */
+export function failure(e: unknown): Response {
+ const err = e as Error;
+ const status = err?.name === "DuplicateProductError" || err?.constructor?.name === "DuplicateProductError" ? 409 : 422;
+ return Response.json({ error: err?.message || "Something went wrong" }, { status });
+}
diff --git a/tests/fixtures/marketing/base.css b/tests/fixtures/marketing/base.css
new file mode 100644
index 00000000..f0e3eded
--- /dev/null
+++ b/tests/fixtures/marketing/base.css
@@ -0,0 +1,11 @@
+:root{--color-foreground:#1c1917;--color-background:#ffffff;--color-accent:#0f766e;--color-border:#e7e5e4;--font-body-family:"Inter",sans-serif}
+body{font-family:"Inter",-apple-system,BlinkMacSystemFont,sans-serif;color:#1c1917;background:#fff}
+h2,.heading{font-family:Fraunces,Georgia,serif}
+.button{background-color:#c2410c;color:#fff}
+.button--secondary{background:#0f766e;color:#fff}
+.price{color:#c2410c}
+.price--sale{color:#c2410c}
+.muted{color:#78716c}
+.overlay{background:rgba(0,0,0,.4)}
+.chip{background:hsl(174, 84%, 25%)}
+@font-face{font-family:"Ember Display";src:url(/fonts/ember.woff2)}
diff --git a/tests/fixtures/marketing/og-only.html b/tests/fixtures/marketing/og-only.html
new file mode 100644
index 00000000..4e9fe610
--- /dev/null
+++ b/tests/fixtures/marketing/og-only.html
@@ -0,0 +1,7 @@
+<html><head>
+<meta property="og:title" content="Trail Bottle 750 ml">
+<meta property="og:description" content="Insulated steel bottle that keeps water cold for 24 hours.">
+<meta property="og:image" content="https://bottles.example/trail.jpg">
+<meta property="product:price:amount" content="29,90">
+<meta property="product:price:currency" content="EUR">
+</head><body><h1>Trail Bottle</h1></body></html>
diff --git a/tests/fixtures/marketing/product-page.html b/tests/fixtures/marketing/product-page.html
new file mode 100644
index 00000000..ea716d7c
--- /dev/null
+++ b/tests/fixtures/marketing/product-page.html
@@ -0,0 +1,15 @@
+<!doctype html>
+<html lang="de">
+<head>
+ <title>Dew Theory Barrier Cream – 50 ml</title>
+ <meta property="og:type" content="product">
+ <meta property="og:title" content="Barrier Cream">
+ <meta property="og:image" content="https://dewtheory.example/img/cream-front.jpg">
+ <meta property="og:image" content="https://dewtheory.example/img/cream-side.jpg">
+ <script type="application/ld+json">
+ [{"@context":"https://schema.org","@type":"BreadcrumbList","itemListElement":[]},
+ {"@context":"https://schema.org","@type":["Product"],"name":"Barrier Cream","description":"A fragrance-free cream that calms reactive skin. Dermatologist-tested.","image":["https://dewtheory.example/img/cream-front.jpg",{"url":"https://dewtheory.example/img/cream-back.jpg"}],"brand":{"@type":"Brand","name":"Dew Theory"},"offers":{"@type":"Offer","price":"34.00","priceCurrency":"EUR"},"url":"/products/barrier-cream"}]
+ </script>
+</head>
+<body><h1>Barrier Cream</h1><p>Calms reactive skin in seven days.</p></body>
+</html>
diff --git a/tests/fixtures/marketing/products.json b/tests/fixtures/marketing/products.json
new file mode 100644
index 00000000..6b122562
--- /dev/null
+++ b/tests/fixtures/marketing/products.json
@@ -0,0 +1,19 @@
+{
+ "products": [
+ {
+ "title": "Maple Pecan Granola",
+ "handle": "maple-pecan-granola",
+ "vendor": "Ember & Oat",
+ "body_html": "<p>Crunchy clusters of organic oats, Oregon pecans and dark maple syrup.</p><ul><li>Vegan and gluten-free</li><li>Only 6 grams of sugar per serving</li></ul>",
+ "variants": [{ "price": "12.50" }],
+ "images": [{ "src": "/cdn/shop/products/maple-pecan.jpg" }, { "src": "https://cdn.example-shop.com/maple-pecan-2.jpg" }]
+ },
+ {
+ "title": "Cocoa Hazelnut Butter",
+ "handle": "cocoa-hazelnut-butter",
+ "body_html": "Stone-ground hazelnuts with raw cocoa. No palm oil.",
+ "variants": [{ "price": 9 }],
+ "images": []
+ }
+ ]
+}
diff --git a/tests/fixtures/marketing/shop-home.html b/tests/fixtures/marketing/shop-home.html
new file mode 100644
index 00000000..4a0bfdce
--- /dev/null
+++ b/tests/fixtures/marketing/shop-home.html
@@ -0,0 +1,50 @@
+<!doctype html>
+<html lang="en-GB">
+<head>
+ <meta charset="utf-8">
+ <title>Ember &amp; Oat | Small-batch granola roasted in Portland</title>
+ <meta name="description" content="Small-batch granola and nut butters, slow-roasted in Portland. Free shipping over $40 and a 30-day money-back guarantee.">
+ <meta property="og:site_name" content="Ember &amp; Oat">
+ <meta property="og:image" content="/cdn/shop/files/hero-granola.jpg?v=12">
+ <meta name="twitter:image" content="https://cdn.example-shop.com/hero-bowl.jpg">
+ <meta name="theme-color" content="#C2410C">
+ <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
+ <link rel="icon" href="/favicon-32.png" sizes="32x32">
+ <link rel="stylesheet" href="/cdn/shop/t/4/assets/base.css">
+ <link href="https://fonts.googleapis.com/css2?family=Fraunces:wght@600;800&amp;family=Inter:wght@400;600&amp;display=swap" rel="stylesheet">
+ <script src="https://cdn.shopify.com/s/files/1/shop.js"></script>
+ <style>
+ :root { --color-brand: #c2410c; --color-cream: #fdf6ec; --font-heading: "Fraunces", serif; --font-body: "Inter", sans-serif; --shadow-color: rgba(0,0,0,.2); }
+ h1, .h1 { font-family: var(--font-heading); }
+ </style>
+ <script type="application/ld+json">
+ {"@context":"https://schema.org","@type":"Organization","name":"Ember & Oat","logo":"https://emberandoat.example/logo.png","sameAs":["https://www.instagram.com/emberandoat","https://www.tiktok.com/@emberandoat"],"description":"Granola that tastes like a slow Sunday."}
+ </script>
+</head>
+<body class="template-index">
+ <header class="site-header">
+ <a href="/" class="header__logo" aria-label="Ember and Oat home">
+ <svg viewBox="0 0 120 40" width="120" height="40"><rect width="120" height="40" fill="#c2410c"/><text x="10" y="26" fill="#fff">EMBER</text></svg>
+ </a>
+ <nav><a href="/collections/all">Shop</a><a href="/pages/about">About</a></nav>
+ </header>
+ <main>
+ <section class="hero">
+ <h1>Granola that tastes like a slow Sunday</h1>
+ <p>Roasted in small batches with organic oats, maple and sea salt. Vegan, gluten-free and made in Portland.</p>
+ <img src="/cdn/shop/files/hero-granola.jpg?v=12" alt="A bowl of granola" width="1600" height="900">
+ <img src="/cdn/shop/files/tracking-pixel.gif" width="1" height="1" alt="">
+ <img class="badge" src="/cdn/shop/files/payment-icons.png" alt="">
+ </section>
+ <section>
+ <h2>Our bestsellers</h2>
+ <img data-src="/cdn/shop/products/maple-pecan.jpg" alt="Maple Pecan Granola" width="800" height="800">
+ </section>
+ </main>
+ <footer>
+ <a href="https://www.instagram.com/emberandoat/">Instagram</a>
+ <a href="https://www.facebook.com/sharer/sharer.php?u=x">Share</a>
+ <a href="https://www.youtube.com/@emberandoat">YouTube</a>
+ </footer>
+</body>
+</html>
diff --git a/tests/marketing-api.test.ts b/tests/marketing-api.test.ts
new file mode 100644
index 00000000..d78a7ee7
--- /dev/null
+++ b/tests/marketing-api.test.ts
@@ -0,0 +1,448 @@
+import fs from "node:fs";
+import http from "node:http";
+import type { AddressInfo } from "node:net";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fuobe-marketing-"));
+process.env.FUOBE_DATA_DIR = dir;
+process.env.COMFYUI_URL = "http://127.0.0.1:9";
+process.env.OLLAMA_URL = "http://127.0.0.1:9";
+// The fixture site runs on 127.0.0.1 (no outside network in tests).
+process.env.FUOBE_ALLOW_PRIVATE_URLS = "1";
+
+// Route handlers call connection() and after(); outside a request, run the work directly.
+vi.mock("next/server", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("next/server")>()),
+ connection: async () => {},
+ after: (task: unknown) => void Promise.resolve(typeof task === "function" ? (task as () => unknown)() : task).catch(() => {}),
+}));
+
+const { setSetting } = await import("@/server/settings");
+const gens = await import("@/server/generations");
+const brand = await import("@/server/brand");
+const mk = await import("@/server/marketing");
+const ads = await import("@/server/ads");
+const brandsRoute = await import("@/app/api/brands/route");
+const brandRoute = await import("@/app/api/brands/[id]/route");
+const researchRoute = await import("@/app/api/brands/[id]/research/route");
+const chatRoute = await import("@/app/api/brands/[id]/chat/route");
+const confirmRoute = await import("@/app/api/brands/[id]/chat/confirm/route");
+const productsRoute = await import("@/app/api/products/route");
+const productRoute = await import("@/app/api/products/[id]/route");
+const readRoute = await import("@/app/api/products/read/route");
+const runsRoute = await import("@/app/api/marketing/runs/route");
+const estimateRoute = await import("@/app/api/marketing/estimate/route");
+const multiplierEstimate = await import("@/app/api/ads/multiplier/estimate/route");
+const adsEstimate = await import("@/app/api/ads/estimate/route");
+const creativesRoute = await import("@/app/api/ads/creatives/route");
+const creativeRoute = await import("@/app/api/ads/creatives/[id]/route");
+const saveRoute = await import("@/app/api/ads/creatives/[id]/save/route");
+const { saveFile } = await import("@/server/storage");
+const { getModel } = await import("@/lib/catalog");
+
+const json = (method: string, body?: unknown, url = "http://x/api") =>
+ new Request(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body) });
+const params = <T extends Record<string, string>>(p: T) => ({ params: Promise.resolve(p) });
+
+async function settle(id: string, ms = 60_000) {
+ const until = Date.now() + ms;
+ for (;;) {
+ const g = gens.getGeneration(id)!;
+ if (["succeeded", "failed", "canceled"].includes(g.status)) return g;
+ if (Date.now() > until) throw new Error(`timed out: ${g.status} ${g.message}`);
+ await new Promise((r) => setTimeout(r, 300));
+ }
+}
+
+// ---------------------------------------------------------------------------
+// A fixture website on 127.0.0.1
+
+const fx = (name: string) => fs.readFileSync(path.join(__dirname, "fixtures/marketing", name), "utf8");
+const PNG = Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), Buffer.alloc(12_000, 7)]);
+let origin = "";
+const local = (s: string) => s.replace(/https:\/\/(emberandoat\.example|cdn\.example-shop\.com|dewtheory\.example)/g, origin);
+const COLLECTION = () =>
+ `<html><head><script type="application/ld+json">{"@type":"ItemList","itemListElement":[${["Night Serum", "Day Cream", "Lip Balm"]
+ .map((n, i) => `{"@type":"ListItem","item":{"@type":"Product","name":"${n}","image":"${origin}/img/p${i}.png","offers":{"price":"${10 + i}","priceCurrency":"USD"}}}`)
+ .join(",")}]}</script></head><body></body></html>`;
+const server = http.createServer((req, res) => {
+ const u = new URL(req.url ?? "/", origin);
+ const send = (body: string | Buffer, type: string) => {
+ res.writeHead(200, { "Content-Type": type });
+ res.end(body);
+ };
+ if (u.pathname === "/") return send(local(fx("shop-home.html")), "text/html");
+ if (u.pathname.endsWith("base.css")) return send(fx("base.css"), "text/css");
+ if (u.pathname === "/products.json") return send(local(fx("products.json")), "application/json");
+ if (u.pathname === "/products/barrier-cream") return send(local(fx("product-page.html")), "text/html");
+ if (u.pathname === "/products/maple-pecan-granola") return send(`<html><head><script src="https://cdn.shopify.com/x.js"></script><title>Maple</title></head><body><h1>Maple</h1></body></html>`, "text/html");
+ if (u.pathname === "/products/maple-pecan-granola.json") return send(JSON.stringify({ product: JSON.parse(local(fx("products.json"))).products[0] }), "application/json");
+ if (u.pathname === "/collections/skin") return send(COLLECTION(), "text/html");
+ if (/\.(png|jpe?g|gif)$/.test(u.pathname)) return send(PNG, "image/png");
+ res.writeHead(404);
+ res.end();
+});
+
+beforeAll(async () => {
+ setSetting("demoMode", "auto");
+ setSetting("enhanceProvider", "none");
+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));
+ origin = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+afterAll(() => {
+ server.close();
+ fs.rmSync(dir, { recursive: true, force: true });
+});
+
+const upload = (name = "product.png") => saveFile({ data: PNG, contentType: "image/png", name, source: "upload" }).url;
+
+// ---------------------------------------------------------------------------
+
+describe("brand kits", () => {
+ let brandId = "";
+
+ it("researches a website: name, colours, fonts, inline SVG logo, images, socials and Shopify products", async () => {
+ const { brand: b, run } = brand.createBrandFromWebsite(`${origin}/`);
+ expect(b.status).toBe("researching");
+ expect(b.progress?.label).toBe("Reading your website");
+ await run;
+ const done = brand.getBrand(b.id)!;
+ brandId = done.id;
+ expect(done.status).toBe("ready");
+ expect(done.progress).toBeNull();
+ expect(done.name).toBe("Ember & Oat");
+ expect(done.colors[0]).toBe("#c2410c");
+ expect(done.fonts).toEqual({ heading: "Fraunces", body: "Inter" });
+ expect(done.logo).toMatch(/^\/api\/files\/uploads\/.+\.svg$/);
+ expect(done.images.length).toBeGreaterThan(0);
+ expect(done.socials.map((s) => s.network)).toContain("Instagram");
+ expect(done.tagline).toMatch(/^Small-batch granola/);
+ expect(done.sellingPoints).toContain("Vegan");
+ expect(done.language).toBe("English");
+ const products = brand.listProducts(done.id);
+ expect(products.map((p) => p.name)).toEqual(["Maple Pecan Granola", "Cocoa Hazelnut Butter"]);
+ expect(products[0].price).toBe(12.5);
+ expect(products[0].images).toHaveLength(2);
+ expect(products[0].images[0]).toMatch(/^\/api\/files\/uploads\//);
+ expect(products[0].sellingPoints.length).toBeGreaterThan(0);
+ });
+
+ it("re-runs the research without duplicating products; a site that can't be read still gives a kit to fill in", async () => {
+ const res = await researchRoute.POST(json("POST"), params({ id: brandId }));
+ expect(res.status).toBe(202);
+ await new Promise((r) => setTimeout(r, 50));
+ for (let i = 0; i < 100 && brand.getBrand(brandId)!.status === "researching"; i++) await new Promise((r) => setTimeout(r, 100));
+ expect(brand.getBrand(brandId)!.status).toBe("ready");
+ expect(brand.listProducts(brandId)).toHaveLength(2);
+
+ const { brand: dead, run } = brand.createBrandFromWebsite(`http://127.0.0.1:9/`);
+ await run;
+ const d = brand.getBrand(dead.id)!;
+ expect(d.status).toBe("ready");
+ expect(d.note).toMatch(/couldn't read the site/);
+ expect(d.name).toBe("127");
+ brand.deleteBrand(dead.id);
+ });
+
+ it("lists, edits (cleaning values) and cancels through the routes", async () => {
+ const list = await (await brandsRoute.GET()).json();
+ expect(list.items[0]).toMatchObject({ id: brandId, productCount: 2 });
+ const res = await brandRoute.PATCH(json("PATCH", { tagline: " Slow Sunday granola ", colors: ["#ABCDEF", "nope", "rgb(1,2,3)"], tone: ["Warm", "Warm", ""], language: "de" }), params({ id: brandId }));
+ const b = await res.json();
+ expect(b.tagline).toBe("Slow Sunday granola");
+ expect(b.colors).toEqual(["#abcdef", "#010203"]);
+ expect(b.tone).toEqual(["Warm"]);
+ expect(b.language).toBe("German");
+ const view = await (await brandRoute.GET(json("GET"), params({ id: brandId }))).json();
+ expect(view.products).toHaveLength(2);
+ expect((await researchRoute.DELETE(json("DELETE"), params({ id: "missing" }))).status).toBe(404);
+ expect((await brandsRoute.POST(json("POST", { website: "not a site" }))).status).toBe(422);
+ });
+
+ it("builds a kit by hand from a description (offline: name and look from the words)", async () => {
+ const res = await brandsRoute.POST(json("POST", { description: "Hollow Pine — hand-poured soy candles that smell like a cabin weekend.", colors: ["#6b7f6a"] }));
+ expect(res.status).toBe(201);
+ const b = await res.json();
+ expect(b).toMatchObject({ name: "Hollow Pine", status: "ready", source: "manual", colors: ["#6b7f6a"] });
+ expect(b.fonts.heading).toBe("DM Serif Display");
+ expect((await brandsRoute.POST(json("POST", { description: "" }))).status).toBe(422);
+ });
+
+ it("adds products by hand and from links (JSON-LD, Shopify product JSON, collection pages), with duplicate checks", async () => {
+ const created = await productsRoute.POST(json("POST", { name: "Gift Box", brandId, price: 30, sellingPoints: ["Three flavours"], images: [upload()] }));
+ expect(created.status).toBe(201);
+ const dup = await productsRoute.POST(json("POST", { name: "gift box", brandId }));
+ expect(dup.status).toBe(409);
+ expect((await dup.json()).error).toBe("«gift box» is already among this brand's products.");
+ expect((await productsRoute.POST(json("POST", { name: "gift box", brandId, force: true }))).status).toBe(201);
+ expect((await productsRoute.POST(json("POST", { name: "Bad", price: -1 }))).status).toBe(422);
+ const tooMany = await productsRoute.POST(json("POST", { name: "X", sellingPoints: ["1", "2", "3", "4", "5", "6"] }));
+ expect(tooMany.status).toBe(400);
+ expect((await tooMany.json()).error).toMatch(/Add up to five selling points/);
+
+ const read = await (await readRoute.POST(json("POST", { url: `${origin}/products/barrier-cream`, brandId }))).json();
+ expect(read.products[0]).toMatchObject({ name: "Barrier Cream", price: 34, currency: "EUR", brandId });
+ expect(read.products[0].images).toHaveLength(2);
+ const again = await (await readRoute.POST(json("POST", { url: `${origin}/products/barrier-cream`, brandId }))).json();
+ expect(again.duplicate.name).toBe("Barrier Cream");
+
+ const shop = await (await readRoute.POST(json("POST", { url: `${origin}/products/maple-pecan-granola`, withBrand: true }))).json();
+ expect(shop.products[0]).toMatchObject({ name: "Maple Pecan Granola", price: 12.5, brandId: null });
+
+ const coll = await (await readRoute.POST(json("POST", { url: `${origin}/collections/skin`, limit: 2 }))).json();
+ expect(coll.products.map((p: { name: string }) => p.name)).toEqual(["Night Serum", "Day Cream"]);
+ expect(coll.message).toBe("Found 3 products on that page and added the first 2. Paste a product's own link to add another.");
+
+ const p = read.products[0];
+ const patched = await (await productRoute.PATCH(json("PATCH", { audience: "Sensitive skin", url: "dewtheory.example/cream" }), params({ id: p.id }))).json();
+ expect(patched).toMatchObject({ audience: "Sensitive skin", url: "https://dewtheory.example/cream" });
+ const unassigned = await (await productsRoute.GET(json("GET", undefined, "http://x/api/products?brand=none"))).json();
+ expect(unassigned.items.map((x: { name: string }) => x.name)).toEqual(expect.arrayContaining(["Maple Pecan Granola", "Night Serum"]));
+ expect((await productRoute.DELETE(json("DELETE"), params({ id: p.id }))).status).toBe(204);
+ });
+
+ it("plans Marketing Studio runs per format and engine", () => {
+ const b = brand.getBrand(brandId)!;
+ const product = brand.listProducts(brandId)[0];
+ const ctx = { product, brand: b, higgsfield: false };
+ const cloudAd = mk.planMarketing({ engine: "cloud", format: "ads", templateId: "ad-hero-headline" }, ctx);
+ const r = cloudAd.steps[0].request;
+ expect(r).toMatchObject({ modelId: "gpt-image-2-5", op: "edit", feature: "marketing", params: { aspectRatio: "4:5", numOutputs: 1 } });
+ expect(r.prompt).toContain("“Meet Maple Pecan Granola”");
+ expect(r.prompt).toContain("“Shop now”");
+ expect(r.inputs?.images).toEqual([product.images[0]]); // the SVG logo isn't sent to the model
+ expect(cloudAd.meta.overlay).toBeNull();
+
+ const openAd = mk.planMarketing({ engine: "open", format: "ads", templateId: "ad-hero-headline", headline: "Crunch, sorted" }, ctx);
+ expect(openAd.steps[0].request).toMatchObject({ modelId: "oss-qwen-edit", op: "edit" });
+ expect(openAd.steps[0].request.prompt).toMatch(/no text, letters/);
+ expect(openAd.meta.overlay).toEqual({ headline: "Crunch, sorted", cta: "Shop now" });
+
+ const poster = mk.planMarketing({ engine: "cloud", format: "poster", templateId: "po-swiss-grid", prompt: "Autumn launch" }, { ...ctx, product: null });
+ expect(poster.steps[0].request).toMatchObject({ modelId: "ideogram-3", op: "t2i", params: { palette: b.colors.slice(0, 5) } });
+ expect(mk.planMarketing({ engine: "open", format: "poster", prompt: "Autumn" }, { ...ctx, product: null }).steps[0].request).toMatchObject({ modelId: "oss-qwen-image", op: "t2i" });
+
+ const shot = mk.planMarketing({ engine: "cloud", format: "product-standalone", templateId: "ps-ice-bath" }, ctx);
+ expect(shot.steps[0].request.modelId).toBe("bria-product-shot");
+ expect(shot.steps[0].request.prompt).toMatch(/^The product is half buried in crushed ice/);
+ expect(() => mk.planMarketing({ engine: "cloud", format: "product-standalone" }, { ...ctx, product: null })).toThrow("Attach a product to generate");
+ expect(() => mk.planMarketing({ engine: "cloud", format: "product-with-model" }, { ...ctx, product: null })).toThrow("Attach reference or product");
+ expect(() => mk.planMarketing({ engine: "cloud", format: "ads", templateId: "po-swiss-grid" }, ctx)).toThrow(/another format/);
+
+ // Open motion longer than a clip: shots from the product photo, then a join.
+ const motion = mk.planMarketing({ engine: "open", format: "motion-hyper", templateId: "mh-orbit-hero", duration: 15 }, ctx);
+ expect(motion.steps.map((s) => s.key)).toEqual(["shot1", "shot2", "shot3", "film"]);
+ expect(motion.steps[0].request).toMatchObject({ modelId: "oss-wan22-14b-fast", op: "i2v", params: { duration: 5, aspectRatio: "9:16" }, feature: "marketing-step" });
+ expect(motion.steps[3]).toMatchObject({ after: ["shot1", "shot2", "shot3"], request: { modelId: "oss-join-clips", op: "concat", feature: "marketing" } });
+ const cloudMotion = mk.planMarketing({ engine: "cloud", format: "motion-hyper", duration: 15 }, ctx);
+ expect(cloudMotion.steps).toHaveLength(1);
+ expect(cloudMotion.steps[0].request).toMatchObject({ modelId: "seedance-2-5", op: "i2v", params: { duration: 12 } });
+ expect(cloudMotion.notes[0]).toMatch(/12 s clips/);
+ });
+
+ it("plans the UGC presenter chain on both engines", () => {
+ const b = brand.getBrand(brandId)!;
+ const product = brand.listProducts(brandId)[0];
+ const script = "Okay so I have to tell you about this granola. It is crunchy, not too sweet, and I eat it every single morning now. Try it.";
+ const cloud = mk.planMarketing({ engine: "cloud", format: "ugc-talking", hookId: "product-hit", settingId: "kitchen" }, { product, brand: b, higgsfield: false, script });
+ expect(cloud.steps.map((s) => s.key)).toEqual(["voice", "still", "talk", "captions", "hook", "broll", "film"]);
+ const step = (k: string) => cloud.steps.find((s) => s.key === k)!;
+ expect(step("voice").request).toMatchObject({ modelId: "elevenlabs-v4", op: "tts", prompt: script });
+ expect(step("still").request.prompt).toContain("leaning on a kitchen counter");
+ expect(step("talk")).toMatchObject({ after: ["still", "voice"], chain: [{ slot: "images" }, { slot: "audio" }], request: { modelId: "omnihuman-2", op: "avatar" } });
+ expect(step("captions").request.modelId).toBe("auto-subtitle");
+ expect(step("hook")).toMatchObject({ after: ["still"], request: { op: "i2v", modelId: "seedance-2-5" } });
+ expect(step("film")).toMatchObject({ after: ["hook", "captions", "broll"], request: { modelId: "join-clips", feature: "marketing" } });
+ expect(cloud.finals).toEqual(["film"]);
+ expect(cloud.meta.script).toBe(script);
+
+ expect(() => mk.planMarketing({ engine: "open", format: "ugc-talking" }, { product, brand: b, higgsfield: false, script })).toThrow(/voice sample/);
+ const open = mk.planMarketing({ engine: "open", format: "tiktok", hookId: null, voiceSample: upload("voice.png") }, { product, brand: b, higgsfield: false, script });
+ expect(open.steps.map((s) => s.key)).toEqual(["voice", "still", "talk", "captions", "broll", "film"]);
+ expect(open.steps[0].request).toMatchObject({ modelId: "oss-chatterbox", inputs: { voiceAudio: expect.stringMatching(/^\/api\/files\//) } });
+ expect(open.steps[2].request.modelId).toBe("oss-infinitetalk-long");
+ expect(open.steps[3].request.prompt).toMatch(/^0\.00-\d+\.\d\d: Okay so I/);
+ });
+
+ it("runs a template in demo mode and lists the run with its generations", async () => {
+ const product = brand.listProducts(brandId)[0];
+ const est = await (await estimateRoute.POST(json("POST", { engine: "cloud", format: "ads", templateId: "ad-offer-burst", productId: product.id, brandId, batch: 2 }))).json();
+ expect(est).toMatchObject({ demo: true, runs: 1, steps: [{ key: "image", modelId: "gpt-image-2-5" }] });
+ const blocked = await (await estimateRoute.POST(json("POST", { engine: "cloud", format: "ads" }))).json();
+ expect(blocked.blocker).toBe("Attach a product to generate");
+
+ const res = await runsRoute.POST(json("POST", { engine: "cloud", format: "ads", templateId: "ad-offer-burst", productId: product.id, brandId, batch: 2 }));
+ expect(res.status).toBe(201);
+ const { runs } = await res.json();
+ expect(runs).toHaveLength(1);
+ const g = await settle(runs[0].finalIds[0]);
+ expect(g.status).toBe("succeeded");
+ expect(g.outputs).toHaveLength(2);
+ expect(g.request.title).toBe("Offer Burst · Maple Pecan Granola");
+ const list = await (await runsRoute.GET(json("GET", undefined, "http://x/api/marketing/runs?feature=marketing"))).json();
+ expect(list.items[0]).toMatchObject({ id: runs[0].id, title: "Offer Burst · Maple Pecan Granola", meta: { templateId: "ad-offer-burst", format: "ads" } });
+ expect(list.items[0].generations[0].status).toBe("succeeded");
+ });
+
+ it("runs a whole UGC pipeline on the demo provider (open engine: voice clone → presenter → captions → join)", async () => {
+ const product = brand.listProducts(brandId)[0];
+ const { runs, script } = await mk.runMarketing({ engine: "open", format: "ugc-talking", templateId: "ugc-honest-review", productId: product.id, brandId, voiceSample: upload("v.png"), duration: 10 });
+ expect(script?.split(" ").length).toBeLessThanOrEqual(25);
+ const run = runs[0];
+ expect(run.generations).toHaveLength(6);
+ const film = await settle(run.finalIds[0], 120_000);
+ expect(film.status).toBe("succeeded");
+ expect(film.op).toBe("concat");
+ expect(mk.getRun(run.id)!.generations.every((x) => x.status === "succeeded")).toBe(true);
+ }, 150_000);
+});
+
+describe("Click to Ad", () => {
+ it("plans product-only and presenter ads, ≤ 12 s, on both engines", () => {
+ const product = { ...brand.listProducts()[0] };
+ const script = "Three reasons I keep this in my bag. It is light, it is tough, and it looks great.";
+ const cloud = mk.planClickToAd({ engine: "cloud", productId: product.id, styleId: "clean-minimal" }, { product, script });
+ expect(cloud.steps.map((s) => s.key)).toEqual(["voice", "shot1", "shot2", "shot3", "film", "mux", "captions"]);
+ expect(cloud.steps.slice(1, 4).reduce((n, s) => n + (s.request.params?.duration ?? 0), 0)).toBe(12);
+ expect(cloud.steps[1].request).toMatchObject({ modelId: "seedance-2-5", params: { aspectRatio: "9:16", resolution: "480p", generateAudio: false } });
+ expect(cloud.steps.find((s) => s.key === "mux")).toMatchObject({ after: ["film", "voice"], chain: [{ slot: "video" }, { slot: "audio" }], request: { modelId: "merge-audio-video" } });
+ expect(() => mk.planClickToAd({ engine: "open", productId: product.id, styleId: "luxury" }, { product, script })).toThrow(/voice sample/);
+ const open = mk.planClickToAd({ engine: "open", productId: product.id, styleId: "luxury", voiceSample: upload("s.png") }, { product, script });
+ expect(open.steps.filter((s) => s.key.startsWith("shot")).map((s) => s.request.params?.duration)).toEqual([5, 5]);
+ expect(open.steps.at(-1)!.request).toMatchObject({ modelId: "oss-captions-burnin", feature: "click-to-ad" });
+ const presenter = mk.planClickToAd({ engine: "cloud", productId: product.id, styleId: "simple-ugc" }, { product, script });
+ expect(presenter.steps.map((s) => s.key)).toEqual(["voice", "still", "talk", "captions", "broll", "film"]);
+ expect(mk.clickToAdSeconds("cloud", true)).toEqual({ voice: 8, broll: 4 });
+ });
+
+ it("writes a script offline within the word budget", async () => {
+ const product = brand.listProducts()[0];
+ const s = await mk.clickToAdScript({ engine: "cloud", productId: product.id, styleId: "simple-ugc" });
+ expect(s.by).toBe("rules");
+ expect(s.script.split(" ").length).toBeLessThanOrEqual(20);
+ expect(s.script).toContain(product.name);
+ });
+});
+
+describe("Ad Multiplier", () => {
+ const video = () => saveFile({ data: PNG, contentType: "video/mp4", name: "ad.mp4", source: "upload" }).url;
+
+ it("recreates the whole ad: Kling with renumbered @images (keeps audio), Wan Animate + original sound on open", () => {
+ const imgs = [upload("a.png"), upload("b.png")];
+ const cloud = mk.planMultiplier({ engine: "cloud", video: video(), duration: 12, images: imgs, mode: "prompt", prompt: "Swap the bottle for @image_2", quality: "1080p" }, { higgsfield: false });
+ expect(cloud.steps).toHaveLength(1);
+ expect(cloud.steps[0].request).toMatchObject({ modelId: "kling-o3", op: "v2v", prompt: "Swap the bottle for @Image1", inputs: { images: [imgs[1], imgs[0]] }, params: { extra: { keep_audio: true } } });
+ const open = mk.planMultiplier({ engine: "open", video: video(), duration: 12, images: imgs, mode: "prompt", prompt: "", quality: "1080p" }, { higgsfield: false });
+ expect(open.steps.map((s) => [s.key, s.request.modelId])).toEqual([["edit", "oss-wan22-animate"], ["sound", "oss-mux"]]);
+ expect(() => mk.planMultiplier({ engine: "open", video: video(), duration: 12, mode: "prompt", quality: "720p" }, { higgsfield: false })).toThrow(/Add an image/);
+ });
+
+ it("adds a hook and a CTA around the original (trimmed first), from the frames the browser grabbed", () => {
+ const v = video();
+ const plain = mk.planMultiplier({ engine: "cloud", video: v, duration: 20, mode: "sections", hook: "Wait for it", cta: "Shop today", quality: "720p", firstFrame: upload("f.png"), lastFrame: upload("l.png") }, { higgsfield: false });
+ expect(plain.steps.map((s) => s.key)).toEqual(["hook", "cta", "film"]);
+ const film = plain.steps.at(-1)!;
+ expect(film.request.inputs).toEqual({ videos: [v] });
+ expect(film.request.chain).toEqual([{ slot: "videos", position: "first" }, { slot: "videos", position: "last" }]);
+ expect(plain.steps[0].request.prompt).toContain("“Wait for it”");
+
+ const trimmed = mk.planMultiplier({ engine: "cloud", video: v, duration: 40, start: 5, end: 20, mode: "sections", cta: "Shop today", hook: null, quality: "720p" }, { higgsfield: false });
+ expect(trimmed.steps.map((s) => s.key)).toEqual(["clip", "last", "cta", "film"]);
+ expect(trimmed.steps[0].request).toMatchObject({ modelId: "trim-video", params: { startTime: 5, endTime: 20 } });
+ expect(trimmed.steps.at(-1)).toMatchObject({ after: ["clip", "cta"], request: { inputs: undefined } });
+ expect(() => mk.planMultiplier({ engine: "cloud", video: v, duration: 3, mode: "prompt", quality: "720p" }, { higgsfield: false })).toThrow("Video duration: 4-30 seconds");
+ });
+
+ it("prices a version per second and says what blocks it", async () => {
+ const est = await (await multiplierEstimate.POST(json("POST", { engine: "cloud", video: video(), duration: 10, mode: "prompt", quality: "720p", versions: 2 }))).json();
+ expect(est).toMatchObject({ runs: 2, demo: true, steps: [{ modelId: "kling-o3" }] });
+ const bad = await (await multiplierEstimate.POST(json("POST", { engine: "cloud", video: video(), duration: 45, mode: "prompt", quality: "720p" }))).json();
+ expect(bad.blocker).toBe("Video duration: 4-30 seconds");
+ });
+});
+
+describe("Ads Studio", () => {
+ let brandId = "";
+ let products: { id: string; name: string }[] = [];
+
+ beforeAll(async () => {
+ const b = await brand.createManualBrand({ description: "Dew Theory — fragrance-free barrier creams for sensitive skin." });
+ brandId = b.id;
+ products = [
+ brand.createProduct({ name: "Barrier Cream", brandId, sellingPoints: ["Calms redness overnight", "Fragrance-free"], price: 34, currency: "EUR", images: [upload()] }),
+ brand.createProduct({ name: "Night Serum", brandId, sellingPoints: ["Repairs while you sleep"], images: [upload()] }),
+ ];
+ });
+
+ it("writes varied ad copy offline, one angle after another", () => {
+ const b = brand.getBrand(brandId)!;
+ const p = brand.getProduct(products[0].id)!;
+ const c = ads.heuristicConcepts(b, p, 6, "winter sale");
+ expect(c.map((x) => x.angle)).toEqual(["benefit", "pain-point", "real-life", "offer", "material", "how-to"]);
+ expect(c[0].headline).toBe("Calms redness overnight");
+ expect(c[3].headline).toBe("Barrier Cream, just EUR 34");
+ expect(c.every((x) => x.visual.includes("winter sale"))).toBe(true);
+ expect(new Set(c.map((x) => x.headline)).size).toBe(6);
+ // A partial LLM answer is completed by the rules.
+ const merged = ads.conceptsFrom('{"ads":[{"angle":"offer","headline":"Calm skin, 20% off","body":"This week only.","cta":"Get it","visual":"Cream on a frosted window sill"}]}', c.slice(0, 2));
+ expect(merged[0]).toEqual({ angle: "offer", headline: "Calm skin, 20% off", body: "This week only.", cta: "Get it", visual: "Cream on a frosted window sill" });
+ expect(merged[1]).toEqual(c[1]);
+ });
+
+ it("prices a run first, then fills the grid as ads render (copy, then one picture per ad)", async () => {
+ const items = [
+ { productId: products[0].id, count: 3 },
+ { productId: products[1].id, count: 2 },
+ ];
+ const est = await (await adsEstimate.POST(json("POST", { brandId, engine: "open", items }))).json();
+ expect(est).toMatchObject({ route: "fuobe", modelId: "oss-qwen-edit", total: 5, demo: true });
+ const { batchId, creatives, run } = ads.createBatch({ brandId, engine: "open", items });
+ expect(creatives).toHaveLength(5);
+ expect(creatives.every((c) => c.status === "writing")).toBe(true);
+ await run;
+ const written = ads.listCreatives({ brandId, batchId });
+ expect(written.every((c) => c.headline && c.generationId)).toBe(true);
+ const g = await settle(written[0].generationId!);
+ expect(g.request).toMatchObject({ feature: "ads", modelId: "oss-qwen-edit", op: "edit" });
+ expect(g.request.prompt).toMatch(/No text, letters/);
+ for (const c of written) await settle(c.generationId!);
+ const ready = await (await creativesRoute.GET(json("GET", undefined, `http://x/api/ads/creatives?brand=${brandId}&batch=${batchId}`))).json();
+ expect(ready.items.every((c: { status: string; image: string }) => c.status === "ready" && c.image.startsWith("/api/files/"))).toBe(true);
+
+ const first = ready.items[0];
+ const edited = await (await creativeRoute.PATCH(json("PATCH", { headline: "Calm, finally", layout: "band" }), params({ id: first.id }))).json();
+ expect(edited).toMatchObject({ headline: "Calm, finally", layout: "band" });
+ const png = saveFile({ data: PNG, contentType: "image/png", name: "ad.png", source: "upload" }).url;
+ const saved = await (await saveRoute.POST(json("POST", { url: png, ratio: "4:5" }), params({ id: first.id }))).json();
+ expect(saved.generation).toMatchObject({ modelId: "local-ad-compose", feature: "ads", status: "succeeded", provider: "local" });
+ expect(getModel("local-ad-compose")?.routes[0].provider).toBe("local");
+ const retried = await ads.retryCreative(first.id);
+ expect(retried.generationId).not.toBe(first.generationId);
+ expect((await creativeRoute.DELETE(json("DELETE"), params({ id: first.id }))).status).toBe(204);
+ }, 120_000);
+
+ it("chats offline: a request becomes a proposal to confirm, which starts a batch", async () => {
+ const res = await chatRoute.POST(json("POST", { text: "Make 3 ads for @Night Serum with a holiday theme" }), params({ id: brandId }));
+ const { messages } = await res.json();
+ const reply = messages.at(-1);
+ expect(reply.proposal).toEqual({ items: [{ productId: products[1].id, count: 3 }], direction: "for Night Serum with a holiday theme" });
+ const question = await (await chatRoute.POST(json("POST", { text: "What's our tone?" }), params({ id: brandId }))).json();
+ expect(question.messages.at(-1).proposal).toBeNull();
+ const ok = await confirmRoute.POST(json("POST", { messageId: reply.id, engine: "cloud" }), params({ id: brandId }));
+ expect(ok.status).toBe(201);
+ const { batchId } = await ok.json();
+ expect(ads.listCreatives({ brandId, batchId })).toHaveLength(3);
+ expect((await confirmRoute.POST(json("POST", { messageId: reply.id, engine: "cloud" }), params({ id: brandId }))).status).toBe(422);
+ expect(ads.offlineProposal("hello there", [])).toBeNull();
+ expect(ads.mentionedProducts("try @night_serum and @Barrier Cream", products)).toEqual([products[0].id, products[1].id]);
+ });
+
+ it("deleting a brand takes its kit, products and ads off the shelf", async () => {
+ expect((await brandRoute.DELETE(json("DELETE"), params({ id: brandId }))).status).toBe(204);
+ expect(brand.getBrand(brandId)).toBeNull();
+ expect(brand.listProducts(brandId)).toHaveLength(0);
+ expect(ads.listCreatives({ brandId })).toHaveLength(0);
+ });
+});
diff --git a/tests/marketing-catalog.test.ts b/tests/marketing-catalog.test.ts
new file mode 100644
index 00000000..4b3bed07
--- /dev/null
+++ b/tests/marketing-catalog.test.ts
@@ -0,0 +1,223 @@
+import { describe, expect, it } from "vitest";
+import { getModel, supportsOp } from "@/lib/catalog";
+import {
+ AD_STYLES,
+ CATEGORIES,
+ cueLines,
+ estimateCues,
+ fitScript,
+ FORMATS,
+ formatModels,
+ interleaved,
+ mentionedImages,
+ mentionsFor,
+ MULTIPLIER_MODELS,
+ multiplierText,
+ researchLabel,
+ RESEARCH_LABELS,
+ runStatus,
+ shotPlan,
+ snapDuration,
+ TEMPLATES,
+ templatesFor,
+ UGC_HOOKS,
+ UGC_MODELS,
+ UGC_SETTINGS,
+ wordBudget,
+ type FormatId,
+} from "@/lib/catalog/marketing";
+import type { Generation } from "@/lib/catalog/types";
+import { AD_LAYOUTS, AD_SIZE, contrast, coverCrop, exportName, fitText, planAd, planRects, readableOn, themeFrom, wrapText, type Measure } from "@/components/ads/layout";
+
+describe("marketing catalog", () => {
+ it("ships Fuobe's own templates for every category, with unique ids and valid formats", () => {
+ expect(new Set(TEMPLATES.map((t) => t.id)).size).toBe(TEMPLATES.length);
+ expect(TEMPLATES.length).toBeGreaterThanOrEqual(80);
+ for (const c of CATEGORIES.filter((c) => c.id !== "all")) expect(templatesFor(c.id as never, "all").length, c.label).toBeGreaterThanOrEqual(5);
+ for (const t of TEMPLATES) {
+ expect(FORMATS[t.format], t.id).toBeDefined();
+ expect(t.prompt.length, t.id).toBeGreaterThan(40);
+ if (t.hook) expect(UGC_HOOKS.some((h) => h.id === t.hook)).toBe(true);
+ if (t.setting) expect(UGC_SETTINGS.some((s) => s.id === t.setting)).toBe(true);
+ }
+ expect(templatesFor("all", "video").every((t) => FORMATS[t.format].kind === "video")).toBe(true);
+ });
+
+ it("interleaves categories so the first row of All shows the range", () => {
+ const first = interleaved(templatesFor("all", "all")).slice(0, 7);
+ expect(new Set(first.map((t) => FORMATS[t.format].category)).size).toBe(7);
+ });
+
+ it("has the 9 hooks, 14 settings, 10 Click-to-Ad styles and 14 research labels", () => {
+ expect(UGC_HOOKS).toHaveLength(9);
+ expect(UGC_SETTINGS).toHaveLength(14);
+ expect(AD_STYLES).toHaveLength(10);
+ expect(RESEARCH_LABELS).toHaveLength(14);
+ expect(new Set(UGC_SETTINGS.map((s) => s.id)).size).toBe(14);
+ });
+
+ it("routes every format to models that exist and do the job, on both engines", () => {
+ for (const id of Object.keys(FORMATS) as FormatId[]) {
+ for (const engine of ["cloud", "open"] as const) {
+ for (const has of [{ product: true, avatar: false, higgsfield: true }, { product: false, avatar: true, higgsfield: false }]) {
+ const list = formatModels(FORMATS[id], engine, has);
+ expect(list.length, `${id}/${engine}`).toBeGreaterThan(0);
+ for (const c of list) {
+ const m = getModel(c.id);
+ expect(m, c.id).toBeDefined();
+ expect(m!.engine).toBe(engine);
+ }
+ }
+ }
+ }
+ for (const engine of ["cloud", "open"] as const) {
+ const M = UGC_MODELS[engine];
+ expect(supportsOp(getModel(M.voice)!, "tts")).toBe(true);
+ expect(supportsOp(getModel(M.talk)!, "avatar")).toBe(true);
+ expect(supportsOp(getModel(M.clip)!, "i2v")).toBe(true);
+ expect(supportsOp(getModel(M.captions)!, "captions")).toBe(true);
+ expect(supportsOp(getModel(M.join)!, "concat")).toBe(true);
+ expect(supportsOp(getModel(M.mux)!, "mux")).toBe(true);
+ expect(supportsOp(getModel(M.trim)!, "trim")).toBe(true);
+ for (const c of MULTIPLIER_MODELS[engine]) expect(getModel(c.id)!.routes.some((r) => r.op === (engine === "open" ? "motion-transfer" : "v2v")), c.id).toBe(true);
+ }
+ });
+
+ it("rotates the research labels through the writing stage while the LLM works", () => {
+ const at = { index: 3, startedAt: 0 };
+ expect(researchLabel(at, 0).label).toBe("Tuning in to your tone of voice");
+ expect(researchLabel(at, 2200).label).toBe("Decoding your aesthetics");
+ expect(researchLabel(at, 2200 * 8).label).toBe("Tuning in to your tone of voice");
+ expect(researchLabel({ index: 12, startedAt: 0 }, 99999).label).toBe("Building your brand kit");
+ expect(researchLabel(null, 0).index).toBe(0);
+ });
+});
+
+describe("Ad Multiplier text and @image mentions", () => {
+ it("sends the prompt, or HOOK/CTA sections (both when both are on)", () => {
+ expect(multiplierText({ mode: "prompt", prompt: "" })).toBe("Recreate this ad.");
+ expect(multiplierText({ mode: "sections", hook: "What if?", cta: null })).toBe("HOOK: What if?");
+ expect(multiplierText({ mode: "sections", hook: "What if?", cta: "Try free" })).toBe("HOOK: What if?\n\nCTA: Try free");
+ expect(multiplierText({ mode: "sections", hook: "", cta: "" })).toBe("HOOK: Write a new opening hook.\n\nCTA: Write a new call to action.");
+ });
+
+ it("puts mentioned images first, renumbers them for the model and caps at its limit", () => {
+ const imgs = ["a.png", "b.png", "c.png", "d.png", "e.png", "f.png"];
+ expect(mentionedImages("swap @image_3 for @image_1, keep @image_3")).toEqual([3, 1]);
+ const k = mentionsFor("Put @image_5 in her hand and dress her like @image_2", imgs, "kling-o3", 4);
+ expect(k.images).toEqual(["e.png", "b.png", "a.png", "c.png"]);
+ expect(k.prompt).toBe("Put @Image1 in her hand and dress her like @Image2");
+ expect(k.dropped).toBe(2);
+ const s = mentionsFor("Use @image_2", imgs.slice(0, 2), "seedance-2-5", 4);
+ expect(s).toEqual({ prompt: "Use image 1", images: ["b.png", "a.png"], dropped: 0 });
+ // Past the limit, or a model with no image input: the mention becomes plain words.
+ expect(mentionsFor("Use @image_2", ["a.png", "b.png"], "gemini-omni-flash", 0)).toEqual({ prompt: "Use the reference", images: [], dropped: 2 });
+ });
+});
+
+describe("scripts, captions and durations", () => {
+ it("sizes scripts at a natural speaking pace and trims at a sentence end", () => {
+ expect(wordBudget(12)).toBe(30);
+ const long = "This is the first sentence of the script. ".repeat(10);
+ const cut = fitScript(long, 6);
+ expect(cut.split(" ").length).toBeLessThanOrEqual(15);
+ expect(cut.endsWith(".")).toBe(true);
+ expect(fitScript("Short and sweet.", 10)).toBe("Short and sweet.");
+ });
+
+ it("times captions from the script in short chunks that follow punctuation", () => {
+ const cues = estimateCues("Okay, I need to tell you about this. It changed my mornings!", 4);
+ expect(cues[0]).toEqual({ start: 0, end: 0.4, text: "Okay," });
+ expect(cues.map((c) => c.text)).toEqual(["Okay,", "I need to tell", "you about this.", "It changed my mornings!"]);
+ for (let i = 1; i < cues.length; i++) expect(cues[i].start).toBeCloseTo(cues[i - 1].end, 5);
+ expect(cueLines(cues).split("\n")[1]).toBe("0.40-2.00: I need to tell");
+ });
+
+ it("snaps durations to what a model makes and splits long open clips into shots", () => {
+ expect(snapDuration(15, [4, 5, 6, 8, 10, 12, 30])).toBe(12);
+ expect(snapDuration(9, [8, 10])).toBe(8);
+ expect(snapDuration(7, undefined)).toBe(7);
+ expect(shotPlan(15, [3, 5])).toEqual([5, 5, 5]);
+ expect(shotPlan(10, [3, 5])).toEqual([5, 5]);
+ expect(shotPlan(5, [3, 5])).toEqual([5]);
+ expect(shotPlan(9, [3, 5])).toEqual([5, 5]);
+ });
+
+ it("sums a run up from its steps", () => {
+ const g = (id: string, status: Generation["status"], error?: string, label?: string) => ({ id, status, error, request: { step: label ? { label, index: 0, of: 1 } : undefined } }) as unknown as Generation;
+ expect(runStatus({ finalIds: ["f"], generations: [g("a", "succeeded"), g("f", "succeeded")] }).state).toBe("done");
+ expect(runStatus({ finalIds: ["f"], generations: [g("a", "running"), g("f", "queued")] }).state).toBe("running");
+ const failed = runStatus({ finalIds: ["f"], generations: [g("a", "failed", "No credits", "Voiceover"), g("f", "failed", "An earlier step didn't finish")] });
+ expect(failed).toEqual({ state: "failed", step: "Voiceover", error: "No credits" });
+ });
+});
+
+// A predictable measure: every character is 0.55 em wide.
+const measure: Measure = (text, font) => text.length * parseFloat(/(\d+(?:\.\d+)?)px/.exec(font)![1]) * 0.55;
+
+describe("ad compositing layout", () => {
+ const theme = themeFrom({ colors: ["#fdf6ec", "#1c1917", "#c2410c"], fonts: { heading: "Fraunces", body: "Inter" } });
+
+ it("takes the most colourful brand colour as the accent with readable text on it", () => {
+ expect(theme.accent).toBe("#c2410c");
+ expect(theme.onAccent).toBe("#ffffff");
+ expect(theme.ink).toBe("#1c1917");
+ expect(theme.paper).toBe("#fdf6ec");
+ expect(themeFrom(null).accent).toBe("#5d4bdb");
+ expect(readableOn("#ffe14d")).toBe("#141414");
+ expect(contrast("#ffffff", "#000000")).toBeCloseTo(21, 0);
+ });
+
+ it("crops the visual to cover its box without distortion", () => {
+ expect(coverCrop(1000, 1000, 1080, 1920)).toEqual({ sx: 218.75, sy: 0, sw: 562.5, sh: 1000 });
+ const c = coverCrop(1600, 900, 1080, 1350, { x: 0.5, y: 0.5 });
+ expect(c.sw / c.sh).toBeCloseTo(1080 / 1350, 5);
+ expect(c.sx).toBeGreaterThanOrEqual(0);
+ expect(c.sx + c.sw).toBeLessThanOrEqual(1600);
+ });
+
+ it("wraps text and breaks over-long words", () => {
+ const font = "800 40px Inter";
+ expect(wrapText("Meet the new granola everyone talks about", 450, font, measure)).toEqual(["Meet the new granola", "everyone talks about"]);
+ expect(wrapText("Supercalifragilistic", 200, font, measure)).toEqual(["Supercali", "fragilist", "ic"]);
+ });
+
+ it("shrinks a long headline before it overflows, and ends with … at the smallest size", () => {
+ const short = fitText("Hello", 900, 2, "Inter", 800, 100, 40, measure);
+ expect(short.size).toBe(100);
+ const long = fitText("A very long headline that keeps going and going well past two lines of type", 900, 2, "Inter", 800, 100, 40, measure);
+ expect(long.size).toBeLessThan(100);
+ expect(long.lines.length).toBeLessThanOrEqual(2);
+ const huge = fitText("word ".repeat(80), 900, 2, "Inter", 800, 100, 40, measure);
+ expect(huge.size).toBe(40);
+ expect(huge.lines[1].endsWith("…")).toBe(true);
+ });
+
+ it("keeps every box inside the canvas for each format and layout", () => {
+ const content = { headline: "Granola that tastes like a slow Sunday morning", body: "Organic oats, maple and sea salt, roasted in small batches in Portland.", cta: "Shop now", brand: "Ember & Oat" };
+ for (const ratio of ["1:1", "4:5", "9:16"] as const) {
+ for (const layout of AD_LAYOUTS.map((l) => l.id)) {
+ for (const logo of [null, { w: 400, h: 120 }]) {
+ const plan = planAd({ ratio, layout, content, theme, image: { w: 1024, h: 1280 }, logo, measure });
+ const { w, h } = AD_SIZE[ratio];
+ expect(plan.w).toBe(w);
+ for (const r of planRects(plan)) {
+ expect(r.x, `${ratio} ${layout}`).toBeGreaterThanOrEqual(-0.5);
+ expect(r.y, `${ratio} ${layout}`).toBeGreaterThanOrEqual(-0.5);
+ expect(r.x + r.w, `${ratio} ${layout}`).toBeLessThanOrEqual(w + 0.5);
+ expect(r.y + r.h, `${ratio} ${layout}`).toBeLessThanOrEqual(h + 0.5);
+ }
+ // The headline never runs into the CTA.
+ if (plan.cta && layout !== "band") expect(plan.headline.y + plan.headline.lines.length * plan.headline.lineHeight).toBeLessThanOrEqual(plan.cta.y + 0.5);
+ expect(plan.headline.lines.join(" ")).toBe(content.headline);
+ if (logo) expect(plan.brand).toBeUndefined();
+ }
+ }
+ }
+ });
+
+ it("names exported files after the brand, product, format and number", () => {
+ expect(exportName("Ember & Oat", "Maple Pecan Granola", "4:5", 3)).toBe("ember-oat-maple-pecan-granola-4x5-3.png");
+ expect(exportName("", undefined, "9:16", 1)).toBe("ad-9x16-1.png");
+ });
+});
diff --git a/tests/marketing-scrape.test.ts b/tests/marketing-scrape.test.ts
new file mode 100644
index 00000000..a2d4d06d
--- /dev/null
+++ b/tests/marketing-scrape.test.ts
@@ -0,0 +1,215 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+import {
+ colorStats,
+ extractColors,
+ extractFonts,
+ googleFonts,
+ heuristicFields,
+ heuristicManualKit,
+ jsonLd,
+ jsonLdProducts,
+ matchLanguage,
+ mergeKit,
+ normalizeColor,
+ normalizeWebsite,
+ parseJsonObject,
+ parseSite,
+ productsFromPage,
+ sellingPointsFrom,
+ shopifyProducts,
+ socialOf,
+ softFieldsFrom,
+} from "@/server/brand";
+import { emptyKit } from "@/lib/catalog/marketing";
+
+const fixture = (name: string) => fs.readFileSync(path.join(__dirname, "fixtures/marketing", name), "utf8");
+const HOME = fixture("shop-home.html");
+const CSS = fixture("base.css");
+const URL_ = "https://emberandoat.example/";
+
+describe("brand research: reading a site (saved fixtures, no network)", () => {
+ const facts = parseSite(HOME, URL_);
+
+ it("reads the name, description, language and theme colour", () => {
+ expect(facts.name).toBe("Ember & Oat");
+ expect(facts.description).toMatch(/^Small-batch granola/);
+ expect(facts.lang).toBe("en-gb");
+ expect(facts.themeColor).toBe("#C2410C");
+ expect(facts.shopify).toBe(true);
+ expect(facts.organization?.description).toBe("Granola that tastes like a slow Sunday.");
+ });
+
+ it("finds the logo: JSON-LD first, then icons; an inline SVG logo is kept whole", () => {
+ expect(facts.logos[0]).toBe("https://emberandoat.example/logo.png");
+ expect(facts.logos).toContain("https://emberandoat.example/apple-touch-icon.png");
+ expect(facts.svgLogo).toMatch(/^<svg xmlns="http:\/\/www\.w3\.org\/2000\/svg"/);
+ expect(facts.svgLogo).toContain("</svg>");
+ });
+
+ it("collects hero images and skips pixels, payment badges and duplicates", () => {
+ expect(facts.images).toContain("https://emberandoat.example/cdn/shop/files/hero-granola.jpg?v=12");
+ expect(facts.images).toContain("https://cdn.example-shop.com/hero-bowl.jpg");
+ expect(facts.images).toContain("https://emberandoat.example/cdn/shop/products/maple-pecan.jpg");
+ expect(facts.images.some((u) => /tracking-pixel|payment/.test(u))).toBe(false);
+ expect(new Set(facts.images).size).toBe(facts.images.length);
+ });
+
+ it("finds socials from links and sameAs, once per network, never share links", () => {
+ expect(facts.socials.map((s) => s.network).sort()).toEqual(["Instagram", "TikTok", "YouTube"]);
+ expect(facts.socials.find((s) => s.network === "Instagram")?.url).toBe("https://www.instagram.com/emberandoat");
+ expect(socialOf("https://www.facebook.com/sharer/sharer.php?u=x")).toBeNull();
+ expect(socialOf("https://x.com/acme")).toEqual({ network: "X", url: "https://x.com/acme" });
+ });
+
+ it("lists stylesheets (not Google Fonts) and keeps inline CSS, headings and text", () => {
+ expect(facts.stylesheets).toEqual(["https://emberandoat.example/cdn/shop/t/4/assets/base.css"]);
+ expect(facts.inlineCss.join("")).toContain("--color-brand");
+ expect(facts.headings[0]).toBe("Granola that tastes like a slow Sunday");
+ expect(facts.text).toContain("Roasted in small batches");
+ expect(facts.text).not.toContain("<svg");
+ });
+
+ it("ranks brand colours: named brand variables and the theme colour first, a dark and a light neutral kept", () => {
+ const colors = extractColors([...facts.inlineCss, CSS], facts.themeColor);
+ expect(colors[0]).toBe("#c2410c");
+ expect(colors).toContain("#0f766e");
+ expect(colors.some((c) => colorStats(c).l < 0.18)).toBe(true);
+ expect(colors.some((c) => colorStats(c).l > 0.92)).toBe(true);
+ // Translucent overlays and shadows aren't brand colours.
+ expect(colors).not.toContain("#000000");
+ expect(colors.length).toBeLessThanOrEqual(6);
+ });
+
+ it("normalises CSS colour literals", () => {
+ expect(normalizeColor("#ABC")).toBe("#aabbcc");
+ expect(normalizeColor("rgb(194, 65, 12)")).toBe("#c2410c");
+ expect(normalizeColor("hsl(174, 84%, 25%)")).toBe("#0a756b");
+ expect(normalizeColor("rgba(0,0,0,.4)")).toBeNull();
+ expect(normalizeColor("#00000033")).toBeNull();
+ expect(normalizeColor("transparent")).toBeNull();
+ });
+
+ it("reads fonts from Google Fonts links, CSS variables and heading/body rules", () => {
+ expect(googleFonts(HOME)).toEqual(["Fraunces", "Inter"]);
+ const f = extractFonts(HOME, [CSS]);
+ expect(f.heading).toBe("Fraunces");
+ expect(f.body).toBe("Inter");
+ expect(f.all).toContain("Ember Display");
+ // System stacks are skipped.
+ expect(extractFonts("", ["body{font-family:-apple-system,Segoe UI,Helvetica,sans-serif}"]).body).toBeUndefined();
+ });
+});
+
+describe("products", () => {
+ it("reads Shopify's products.json with prices, links and absolute image URLs", () => {
+ const ps = shopifyProducts(JSON.parse(fixture("products.json")), "https://emberandoat.example");
+ expect(ps).toHaveLength(2);
+ expect(ps[0]).toMatchObject({
+ name: "Maple Pecan Granola",
+ price: 12.5,
+ url: "https://emberandoat.example/products/maple-pecan-granola",
+ images: ["https://emberandoat.example/cdn/shop/products/maple-pecan.jpg", "https://cdn.example-shop.com/maple-pecan-2.jpg"],
+ brand: "Ember & Oat",
+ });
+ expect(ps[0].description).toBe("Crunchy clusters of organic oats, Oregon pecans and dark maple syrup. Vegan and gluten-free Only 6 grams of sugar per serving");
+ expect(ps[1].price).toBe(9);
+ // A single product's JSON (/products/<handle>.json) has the same shape under "product".
+ expect(shopifyProducts({ product: { title: "One", images: [] } }, "https://x.example")[0].name).toBe("One");
+ });
+
+ it("reads a JSON-LD Product (array of blocks, typed list, offers, brand, mixed image forms)", () => {
+ const html = fixture("product-page.html");
+ const ps = jsonLdProducts(jsonLd(html), "https://dewtheory.example/products/barrier-cream");
+ expect(ps).toEqual([
+ {
+ name: "Barrier Cream",
+ description: "A fragrance-free cream that calms reactive skin. Dermatologist-tested.",
+ price: 34,
+ currency: "EUR",
+ url: "https://dewtheory.example/products/barrier-cream",
+ images: ["https://dewtheory.example/img/cream-front.jpg", "https://dewtheory.example/img/cream-back.jpg"],
+ brand: "Dew Theory",
+ },
+ ]);
+ expect(productsFromPage(html, "https://dewtheory.example/products/barrier-cream")[0].name).toBe("Barrier Cream");
+ });
+
+ it("falls back to OpenGraph product tags (European decimal price)", () => {
+ const [p] = productsFromPage(fixture("og-only.html"), "https://bottles.example/trail");
+ expect(p).toMatchObject({ name: "Trail Bottle 750 ml", price: 29.9, currency: "EUR", url: "https://bottles.example/trail", images: ["https://bottles.example/trail.jpg"] });
+ expect(p.description).toMatch(/24 hours/);
+ });
+
+ it("pulls short selling points out of a description", () => {
+ expect(sellingPointsFrom("Keeps drinks cold for 24 hours. Leak-proof lid! Made from recycled steel. Read our privacy policy.")).toEqual([
+ "Keeps drinks cold for 24 hours",
+ "Leak-proof lid!",
+ "Made from recycled steel",
+ ]);
+ });
+});
+
+describe("brand fields: LLM answers, offline heuristics and the merge", () => {
+ it("parses an LLM answer wrapped in chatter and code fences, dropping malformed fields", () => {
+ const j = parseJsonObject('Sure! ```json\n{"name":"Ember & Oat","tone":["Warm","Honest",""],"colors":["#c2410c","nope"],"language":"en","sellingPoints":"Free shipping; Vegan","products":[{"name":"Maple Pecan Granola","sellingPoints":["Crunchy"]},{"oops":1}]}\n``` hope that helps');
+ const s = softFieldsFrom(j);
+ expect(s.name).toBe("Ember & Oat");
+ expect(s.tone).toEqual(["Warm", "Honest"]);
+ expect(s.colors).toEqual(["#c2410c"]);
+ expect(s.language).toBe("English");
+ expect(s.sellingPoints).toEqual(["Free shipping", "Vegan"]);
+ expect(s.products).toEqual([{ name: "Maple Pecan Granola", audience: undefined, sellingPoints: ["Crunchy"] }]);
+ expect(parseJsonObject("no json here")).toBeNull();
+ expect(softFieldsFrom(null)).toEqual({});
+ });
+
+ it("builds soft fields offline from the page text", () => {
+ const facts = parseSite(HOME, URL_);
+ const h = heuristicFields(facts, ["#c2410c", "#1c1917", "#ffffff"], { heading: "Fraunces" });
+ expect(h.tagline).toBe("Small-batch granola and nut butters, slow-roasted in Portland");
+ expect(h.values).toEqual(expect.arrayContaining(["Sustainability", "Craftsmanship"]));
+ expect(h.sellingPoints).toEqual(expect.arrayContaining(["Free shipping over $40", "30-day money-back guarantee", "Vegan"]));
+ expect(h.aesthetics).toContain("Classic serif typography");
+ expect(h.language).toBe("English");
+ });
+
+ it("merges: the LLM wins field by field, code-read facts win for logo/colours/fonts, empty answers never erase", () => {
+ const base = { ...emptyKit("Emberandoat"), details: ["Ships from Oregon"] };
+ const merged = mergeKit(
+ base,
+ { name: "Ember & Oat", website: URL_, logo: "/api/files/uploads/x/logo.svg", colors: ["#c2410c", "#0f766e"], fonts: { heading: "Fraunces", body: "Inter" }, socials: [], images: ["/api/files/uploads/x/a.jpg"] },
+ { tagline: "From the rules", tone: ["Friendly"], values: ["Quality"], language: "English" },
+ { name: "", tagline: "Granola for slow Sundays", tone: [], values: ["Craft", "Community"], colors: ["#000000"], fonts: { heading: "Lobster" } },
+ );
+ expect(merged.name).toBe("Ember & Oat");
+ expect(merged.tagline).toBe("Granola for slow Sundays");
+ expect(merged.tone).toEqual(["Friendly"]);
+ expect(merged.values).toEqual(["Craft", "Community"]);
+ expect(merged.colors).toEqual(["#c2410c", "#0f766e"]);
+ expect(merged.fonts).toEqual({ heading: "Fraunces", body: "Inter" });
+ expect(merged.logo).toBe("/api/files/uploads/x/logo.svg");
+ expect(merged.details).toEqual(["Ships from Oregon"]);
+ });
+
+ it("makes a manual kit from a description with no LLM (name, look by category)", () => {
+ const k = heuristicManualKit("Dew Theory — fragrance-free barrier creams for sensitive skin, sold direct online.");
+ expect(k.name).toBe("Dew Theory");
+ expect(k.overview).toMatch(/^Dew Theory/);
+ expect(k.colors).toHaveLength(4);
+ expect(k.fonts?.heading).toBe("Cormorant Garamond");
+ expect(k.tone).toContain("Gentle");
+ });
+
+ it("matches languages and websites", () => {
+ expect(matchLanguage("de-DE")).toBe("German");
+ expect(matchLanguage("Japanese")).toBe("Japanese");
+ expect(matchLanguage("klingon")).toBeUndefined();
+ expect(normalizeWebsite("acme.com")).toBe("https://acme.com/");
+ expect(normalizeWebsite("http://shop.acme.co.uk/path")).toBe("http://shop.acme.co.uk/path");
+ expect(normalizeWebsite("not a site")).toBeNull();
+ expect(normalizeWebsite("localhost")).toBeNull();
+ expect(normalizeWebsite("ftp://acme.com")).toBeNull();
+ });
+});