# Designing a campaign type on SubtleAds

You're helping someone decide what an app can sell sponsors — possibly
before they've registered. A campaign type is one JSON document:
`name`, `description`, `pricing`, `delivery`, `slots[]`, `assets[]`,
`fields[]`, `groups[]`, `groupLayout`, `validationRules[]`. It validates against `campaignTypeSpec`
(`packages/schema/src/campaign-type.ts` in the platform repo) — everything
downstream (booking form, quote, rejection messages) is generated from it,
so getting the shape right here is the whole job. There is no separate
"basics" object — `name`/`description` are flat, top-level fields.

## Decision procedure

1. **List the places an ad can appear → `slots`.** Each slot has a `key`,
   `label`, and usually points at exactly one asset via `assetKey`. Several
   slots may share one asset. Leave `assetKey` out entirely for a
   **text-only slot** — a placement the app draws from the campaign's fields
   (sponsor name, brand colour, blurb, CTA label) with no uploaded file
   involved at all. It sells, serves and bills exactly like any other slot;
   the sponsor is simply never asked for a creative for it. Prefer that over
   declaring an asset the app doesn't actually render: the booking form asks
   for every declared asset, so a placeholder image gets collected from the
   sponsor and then silently never drawn. An optional `role` (`intro`,
   `ambient`, `mark`, `outro`, `interstitial`) is a platform-wide
   vocabulary, skippable. A
   slot can also optionally set `previewSurface` — a screenshot of the real
   place with the ad's footprint pinned onto it, so a sponsor sees their
   creative composited in before booking. That's set up separately, once the
   app is registered (below) — nothing to include in this JSON beyond the key.

2. **For each asset, declare the shape you want — never what you'll accept.**
   `aspect` (e.g. `"16:9"`), `targetWidth`/`maxDurationSec`, `formats`,
   `maxSizeMB`. The ingest pipeline conforms whatever master the sponsor
   uploads to exactly that shape; it only rejects when no safe transform
   exists (source under `minSourceWidth`, or a `contain` crop needing >3x
   stretch) — never for "wrong size."

3. **Pick exactly one pricing model:**
   - `flat` / `cpd` — guaranteed, date-bound placement, sold regardless of
     traffic. `cpd` for variable-length flights.
   - `cpm` — the standard usage unit, billed per confirmed impression,
     shown to sponsors as "$X CPM."
   - `cpc` — billed per click through the ad's `clickUrl` (a player's
     first click on a sponsor in a session); appearances are free. Only if a
     click is a real, instrumented action. Per-click campaigns compete for
     impressions by how far behind their spend is, like any metered campaign,
     so set the rate where the clicks you expect pay for the impressions they
     take.
   - `cps` — one price per genuine session the ad was shown in, immune to
     multi-slot inflation by construction (five slots filled in one session
     still bills once).
   - `sov` — a guaranteed *share* of decisions, NOT a consumption unit.
     Cannot pair with `exclusive_per_slot` delivery (rule below).
   - `METERED_MODELS` (`cpm`/`cpc`/`cps`) draw down a budget until it's
     spent. `RESERVED_MODELS` (`flat`/`cpd`/`sov`) buy a fixed window
     regardless of volume.
   - Any model can price by country: `geoMultipliers`, e.g.
     `{ "US": 1.5, "IN": 0.2 }` (`"default"` for the rest, 1 if left out).
     A metered model charges each event at the rate for its player's
     country, whichever countries the sponsor picked; a reserved model is
     paid up front at the highest rate among the countries the booking
     reaches. Don't make a type per market just to price it differently.

4. **Pick exclusivity.** `delivery.exclusivity` defaults to `"shared"`.
   Set `"exclusive_per_slot"` only when "one sponsor owns this slot" is a
   real product fact, not a pricing tactic. Two combinations are schema-
   enforced, not advisory — do not propose either:
   - `exclusive_per_slot` + a non-null `delivery.defaultShareOfVoicePct`
     together (rejected: can't mean "you alone" and "you get 50%" at once).
   - `sov` pricing with anything but `shared` delivery (rejected: a
     guaranteed share requires something to share).
   - If proposing `exclusive_per_slot`, also set `maxConsecutiveRenewals`
     (default 2) and `bookingHorizonDays` (default 90) — the guardrails
     that keep "exclusive sponsorship" from becoming permanent lockout.

5. **Other fields ride separately.** Anything besides a file is a
   `fields[]` entry: `boolean`, `select`, `text`, `link`, `number`,
   `date`, `color`. A `color` field's optional `contrastFloors` is
   checked at submission, before moderation or payment. An `optional`
   colour the sponsor leaves alone arrives as no value at all (the booking
   form shows it crossed out), so the app's own default or derivation
   applies — never a fallback hex.

6. **More than a handful of fields? Group them.** Declare `groups[]`
   (`key`, `label`, optional `help`) and give each field a `group`
   naming one. Uploads can join groups too: set `group` on an `assets[]`
   entry, and it's shown in that group after the group's fields (an
   ungrouped upload stays in the form's own uploads section). Membership
   lives on the field or upload, so moving one is changing its `group`;
   order inside a group is the order of `fields[]`, then of `assets[]`,
   and the order of groups is the order of `groups[]`. A group may set `parent` to
   sit inside another — one level deep only, the parent must be top-level.
   `groupLayout` is `"sections"` (default, stacked) or `"tabs"`; it
   applies to top-level groups, and nested ones are always sections inside
   their parent. Ungrouped fields are shown first. A field or upload naming
   a group that doesn't exist, a duplicate group key, or nesting two levels
   deep is rejected. Groups only arrange the form: values, validation and what the
   SDK receives are unchanged.
   ```json
   "groups": [
     { "key": "brand", "label": "Brand" },
     { "key": "table", "label": "Table" },
     { "key": "chat", "label": "Chat", "help": "Lines other players see at the table." },
     { "key": "chat_line_1", "label": "Line 1", "parent": "chat" }
   ],
   "groupLayout": "tabs",
   "fields": [
     { "key": "brand_name", "type": "text", "label": "Brand name", "maxLength": 24, "group": "brand" },
     { "key": "chat_line_1", "type": "text", "label": "Chat line 1", "maxLength": 30, "group": "chat_line_1" }
   ],
   "assets": [
     { "key": "card_back", "kind": "image", "label": "Card back", "aspect": "5:7", "group": "table" }
   ]
   ```

## Worked examples — paste-ready, adapt them, don't invent new field names

### 3D game-world billboard
Real, live example — see `packages/db/src/seed.ts` (DrivingTest's
"3D Billboard") and `apps/demo-drivingtest/src/main.ts` for the SDK wiring
that renders it.
```json
{
  "name": "3D Billboard",
  "pricing": { "model": "cpm", "rateMinor": 400, "currency": "usd", "minBudgetMinor": 10000 },
  "delivery": {
    "exclusivity": "shared",
    "dedupeWindowSec": 30,
    "frequencyCap": { "count": 4, "perHours": 24 }
  },
  "assets": [
    { "key": "billboard_texture", "kind": "image", "label": "Billboard artwork", "aspect": "16:9", "targetWidth": 1024, "minSourceWidth": 1024 }
  ],
  "slots": [
    { "key": "billboard_highway", "label": "Highway billboard", "assetKey": "billboard_texture", "role": "ambient" },
    { "key": "billboard_roundabout", "label": "Roundabout billboard", "assetKey": "billboard_texture", "role": "ambient" }
  ]
}
```

### Mobile app banner + interstitial
Two campaign types, not one — they're priced differently because they cost
different amounts of attention.
```json
{
  "name": "Bottom banner",
  "pricing": { "model": "cpm", "rateMinor": 200, "currency": "usd", "minBudgetMinor": 5000 },
  "delivery": { "exclusivity": "shared", "frequencyCap": { "count": 6, "perHours": 24 } },
  "assets": [{ "key": "banner_image", "kind": "image", "label": "Banner", "aspect": "6:1", "cropStrategy": "smart" }],
  "slots": [{ "key": "bottom_banner", "label": "Bottom banner", "assetKey": "banner_image", "role": "ambient" }]
}
```
```json
{
  "name": "Interstitial",
  "pricing": { "model": "cpm", "rateMinor": 1500, "currency": "usd", "minBudgetMinor": 15000 },
  "delivery": { "exclusivity": "shared", "frequencyCap": { "count": 2, "perHours": 24 } },
  "assets": [{ "key": "interstitial_image", "kind": "image", "label": "Interstitial", "aspect": "9:16", "cropStrategy": "smart" }],
  "slots": [{ "key": "between_screens", "label": "Between screens", "assetKey": "interstitial_image", "role": "interstitial" }]
}
```

### Text-only sponsor panel — no creative at all
A billable placement the app composes itself, for a surface with no image
element in it. `assets` is omitted entirely and no slot names one. Its
preview surface (set up after registering) uses text layers bound to these
fields, so sponsors see their own copy in place. Don't bake placeholder copy
into the screenshot.
```json
{
  "name": "Round sponsor",
  "pricing": { "model": "cps", "rateMinor": 300, "currency": "usd", "minBudgetMinor": 5000 },
  "delivery": { "exclusivity": "shared" },
  "fields": [
    { "key": "brand_name", "type": "text", "label": "Sponsor name", "maxLength": 40 },
    { "key": "brand_color", "type": "color", "label": "Brand colour" },
    { "key": "blurb", "type": "text", "label": "One-line pitch", "maxLength": 90 },
    { "key": "cta_label", "type": "text", "label": "Button label", "maxLength": 24 }
  ],
  "slots": [
    { "key": "round_start", "label": "Round start panel", "role": "intro" },
    { "key": "round_end", "label": "Round end panel", "role": "outro" }
  ]
}
```
Those four field keys are the platform's reserved ones, so they arrive at the
app in the decision response's `brand` object rather than having to be read
out of the free-form `fields` bag. Text stays sharp at every density and
there is nothing to half-load while a round is starting, which is usually the
real reason a panel is composed rather than uploaded.

### Newsletter / content sponsorship
```json
{
  "name": "Newsletter sponsor",
  "pricing": { "model": "flat", "amountMinor": 20000, "unit": "flight", "currency": "usd", "minFlightDays": 7, "maxFlightDays": 30 },
  "delivery": { "exclusivity": "exclusive_per_slot", "maxConsecutiveRenewals": 2, "bookingHorizonDays": 90 },
  "assets": [{ "key": "sponsor_logo", "kind": "image", "label": "Logo", "aspect": "3:1", "cropStrategy": "contain" }],
  "fields": [
    { "key": "sponsor_link", "type": "link", "label": "Sponsor link" },
    { "key": "pitch", "type": "text", "label": "One-line pitch", "maxLength": 140 }
  ],
  "slots": [{ "key": "issue_sponsor", "label": "Issue sponsor", "assetKey": "sponsor_logo", "role": "mark" }]
}
```
Not `cpm` — there's no reliable per-open confirm signal for an email.

### Podcast / audio pre-roll
```json
{
  "name": "Episode sponsor",
  "pricing": { "model": "cpd", "rateMinor": 5000, "currency": "usd", "minFlightDays": 1, "maxFlightDays": 30 },
  "delivery": { "exclusivity": "shared" },
  "assets": [{ "key": "preroll_audio", "kind": "audio", "label": "Pre-roll audio", "maxDurationSec": 30, "loudnessLufs": -16 }],
  "slots": [
    { "key": "preroll", "label": "Pre-roll", "assetKey": "preroll_audio", "role": "intro" },
    { "key": "midroll", "label": "Mid-roll", "assetKey": "preroll_audio", "role": "interstitial" }
  ]
}
```
`cps` is the harder-but-more-honest option if playback-continued-past-the-spot
is genuinely instrumented; `flat`/`cpd` per episode is the honest default
otherwise — a play count isn't a confirmed listen.

## Turning this into a real campaign type

Once the app is registered, the fastest path is pasting the whole JSON
document in one shot — there's no need to walk the guided tabs field by
field, and this is the intended way to hand someone a finished proposal:

1. Sign in as that app's own team and go to `/app/types/new`.
2. Click "Whole document as JSON" in the left sidebar (or go straight to
   `/app/types/new?tab=json`).
3. Paste the JSON into the textarea, replacing what's there.
4. Click "Apply to all sections" — each top-level key is checked against
   its own section's schema and merged into a draft. You don't have to
   supply every field: anything omitted falls back to the schema's own
   default (`delivery.exclusivity` defaults to `"shared"`,
   `dedupeWindowSec` to `30`, and so on) — a minimal document is a
   valid document. Don't pad a proposal with defaulted values just to
   look complete.
5. Click "Create campaign type" at the top of the page. This is the one
   moment the *whole* document is re-validated together, including the
   cross-field rules below — if something's wrong it names the exact
   field and reason, and nothing is created until it's clean.

Verified end to end: a document with only `name`, `pricing`, a partial
`delivery`, one `asset`, and its `slots` — no `fields`, no
`validationRules` — creates successfully.

## Rules the schema enforces — do not propose a spec that violates these

- No two fields, assets, or slots may share a `key`.
- Every slot's `assetKey`, where it has one, must reference a declared
  asset. A slot with no `assetKey` is a text-only placement — legal, and
  the way to say this one is drawn from fields alone.
- An image asset with `powerOfTwo: true` must derive power-of-two
  dimensions at its `aspect`/`targetWidth`, or drop the flag.
- The two exclusivity/`sov` conflicts in step 4 above.

## Once the app is registered

Fetch `/app/docs/agent.md` from inside that app's own console. Each app has
its own portal origin, so that file does not live on the host you fetched
*this* one from: take the host you fetched this file from and prefix the app's
slug as a subdomain — e.g. an app with slug `drivingtest` on
`https://subtleads.example` serves it at
`https://drivingtest.subtleads.example/app/docs/agent.md` — unless the app has
attached its own custom domain, in which case use that. Fetch it with any of
that app's API keys (`Authorization: Bearer sk_...`, minted at `/app/setup`),
or from a browser signed in as a member of the app's team.

That file has the real tenant slug; both base URLs spelled out absolutely (the
serving endpoint for `/v1/*`, and that app's own portal origin for every
`/api/*` and `/app/*` path, so nothing has to be guessed); this app's
*actual* existing campaign types (so you can tell whether a request is a new
type or an edit to one that already exists, before proposing a new document to
paste); the SDK-wiring protocol this file doesn't cover; and — if you're
vision-capable and already have a screenshot in hand — a stable
`/api/surfaces` endpoint for pinning `previewSurface`s directly, corner
coordinates and all. That last part is reproduced in full below, with
`<your-app>` standing in for the app's portal address.

## Preview surfaces — showing a sponsor their creative in situ

A slot can optionally set `previewSurface` to the key of a "surface": a
screenshot of a real place in the app with the ad's footprint pinned
onto it, so a sponsor sees their own creative composited in before they pay.
Surfaces are tenant-level, not versioned with the campaign type — several
types can point at the same surface, and re-shooting a stale screenshot
doesn't bump anything.

If you already have a screenshot and can see where the ad should sit in it
(vision-capable), you can create or update one directly:

```
POST https://<your-app>.subtleads.example/api/surfaces       — create/update (multipart/form-data)
GET  https://<your-app>.subtleads.example/api/surfaces       — list this app's surfaces
GET  https://<your-app>.subtleads.example/api/surfaces/<key> — read one, including its current layers
```

On the portal base URL above (`https://<your-app>.subtleads.example`), not the serving endpoint.
Authenticated either of two ways:

- A signed-in session cookie for a member of the app's own team —
  whoever gave you this file runs the request through their own
  already-authenticated browser/session, or hands you a copy of that cookie.
  The cookie path only works against `https://<your-app>.subtleads.example` itself: this app's
  identity comes from the host on that path, so the same request sent to any
  other portal host acts as a different app or none at all. A key (below)
  carries its own identity and works from anywhere.
- An `Authorization: Bearer sk_...` API key scoped to `surfaces` (or
  `types`, for the endpoint above), minted from `/app/setup` by someone on
  the app's team. This is the one meant for an unattended script or
  agent that has no browser session of its own — ask for one rather than
  asking for a live cookie. Shown once at creation; if it's been lost, that
  key is revoked and a new one made, not recovered.

**POST fields** (multipart/form-data, matching the browser editor exactly):
- `key` — lowercase, snake_case, starts with a letter (e.g.
  `highway_hoarding`). Immutable once created.
- `existingKey` — set this instead of relying on `key` when updating one
  that already exists; omit for a new surface.
- `label` — 1-120 characters. Required for a new surface; on an update,
  omit it to keep the saved one. `description` (optional, up to 500) works
  the same way, and sending it empty clears it.
- `screenshot` — the image file. Required for a new surface; omit on an
  update to keep the existing one. PNG/JPEG/WebP, 320px+ on each side — it
  gets re-encoded and downscaled to at most 2560px, so there's nothing to
  gain from sending it larger. Mind the request size limit below.
- `sampleValues` (optional) — a JSON object (as a string field) of
  stand-ins for placeholders your app fills into sponsor copy at runtime,
  e.g. `{"name": "Sandy"}` if the app puts the player's name where a sponsor
  wrote `{name}`. Text layers show the sample in the preview; a token with
  no sample shows as written. Keys are letters, digits and underscores
  (starting with a letter, up to 32), values up to 60 characters, at most 20.
  Omit it on an update to keep the saved ones.
- `layers` — a JSON array (as a string field), one entry per layer in
  paint order, **bottom to top**. Up to 12. Every layer has an `id` (1-64
  characters, unique in the surface, and how an update recognises it) and a
  `label` (1-120). Four kinds:
  - `{ "id", "label", "kind": "creative", "assetKey", "fit": "fill"|"contain", "transform", "style" }`
    — the booked ad itself. `assetKey` (required, 1-64) names one of the
    campaign type's declared assets; resolved at render time, so a surface
    knows nothing about which campaign type will use it — an unknown key just
    renders unfilled. `fit`: `fill` (default) stretches to the corners,
    `contain` letterboxes inside them at the artwork's own aspect.
  - `{ "id", "label", "kind": "color", "fieldKey", "fallback": "#808080", "transform", "style" }`
    — a flat fill bound to a campaign-type colour field (e.g. the felt on a
    table). `fieldKey` is optional; `fallback` (`#rrggbb`, default
    `#808080`) paints before a value exists, or always when nothing is bound.
    Several colour layers can bind one field, so one pick recolours them all.
  - `{ "id", "label", "kind": "image", "image", "fit", "transform", "style" }`
    — a static image you author once (a vignette, a HUD element), `fit` as
    for a creative layer. PNG/JPEG/WebP in, stored as PNG so transparency
    survives; downscaled to at most 2560px, 320px+ on each side. A new one
    needs a real file too, in a field named `layer_file_<id>` matching this
    layer's `id`. On an update, one whose `id` is already saved keeps its
    image when you send no file (see "Updating one" below).
  - `{ "id", "label", "kind": "text", ...settings below, "transform", "style" }`
    — the sponsor's own words. This is how a text-only slot gets a preview:
    don't bake placeholder copy ("Your text here") into the screenshot;
    leave that spot clean and put a text layer on it. One field per layer,
    so a name, a pitch and a button are three layers. Every setting but
    `transform` is optional:
    - `fieldKey` — the campaign-type text field the copy comes from, usually
      `brand_name`, `blurb` or `cta_label`. Leave it out for a fixed label
      that always shows `fallbackText`.
    - `fallbackText` — 1-200 characters, default `"Sponsor copy"`. Shown
      until the sponsor types, and whenever `fieldKey` is unset or names a
      field the campaign type doesn't declare.
    - `font` — `sans` (default), `rounded`, `serif` or `mono`: system
      stand-ins for the app's real typeface, so line breaks come out close
      rather than exact. There's no way to load your own font.
    - `fontSizePct` — 1-40, default 6: a percentage of the **screenshot's**
      shorter side, not the box's, so resizing the box never rescales the text.
    - `fontWeight` — `regular`, `medium`, `semibold` (default), `bold`.
    - `align` — `left`, `center` (default), `right`.
    - `verticalAlign` — `top`, `center` (default), `bottom`: where the
      copy sits in its box. A one-line message laid out from the top in the
      app wants `top`, or it sits half a line low.
    - `lineHeight` — 0.8-2, default 1.2, a multiple of the font size.
    - `letterSpacingEm` — -0.1 to 0.5, default 0.
    - `textTransform` — `none` (default) or `uppercase`.
    - `maxLines` — 1-4, default 2. Copy that runs longer is cut off with an
      ellipsis rather than shrunk.
    - `color` — `#rrggbb`, default `#ffffff`.
    - `colorFieldKey` — a colour field the text colour comes from instead,
      with `colorMode`: `match` (default) paints the text in that colour;
      `contrast` picks black or white, whichever reads better on it. Use
      `"colorFieldKey": "brand_color", "colorMode": "contrast"` for copy on a
      band a colour layer fills from `brand_color`, so it stays readable on
      a light brand colour. Until the sponsor picks, it contrasts with that
      colour layer's `fallback`; with neither, it uses `color`.
    Pin it with a rectangular `warp` quad over the spot the app draws the
    copy; square corners keep it flat. `fixed` sets it across the whole
    screenshot.
  - `transform` is `{ "mode": "fixed" }` for scenery with no footprint of
    its own, or `{ "mode": "warp", "corners": [[x,y],[x,y],[x,y],[x,y]] }`
    for the ad's actual pinned footprint — **4 corners in order top-left,
    top-right, bottom-right, bottom-left, each an `[x, y]` pair normalized
    to the screenshot: (0,0) is the top-left pixel, (1,1) the bottom-right.**
    A corner may go slightly negative or past 1 (up to ±0.5) for something
    that runs off-frame, but the four corners must stay convex and cover a
    non-trivial area — a self-intersecting or collinear quad is rejected.
  - `style` (every layer, all optional): `opacity` 0-1 (default 1),
    `blendMode` `normal|multiply|screen|overlay|soft-light|hard-light|luminosity`
    (default `normal`), `brightness` and `saturation` 0-2 (default 1),
    `cornerRadiusPct` 0-50 of the shorter side (default 0).

Response is the saved surface as JSON, including `previewUrl`.

**Errors.** A `400` names what's wrong and where, e.g. `layer 3 ("Button")
maxLines: Number must be less than or equal to 4`. A setting no layer of
that kind has is refused rather than dropped, with the nearest real one if
there is one (`Nothing was saved: layer 2 ("Splash line") has no setting
"fontsize" — did you mean "fontSizePct"?`), so a typo can't save silently.
A `500` means we failed, not you: its `message` says which step broke
(storing an image, or saving the surface), that nothing was saved, and why
(`detail`, e.g. the storage service's answer), with a `ref` to quote. A
storage write that fails for a passing reason is retried a few times before
it gets that far, so one `500` is worth a retry and several in a row are
worth reporting.

**Request size.** The whole request has to stay under **4.5 MB** — the
hosting platform refuses anything larger with a `413` before it reaches
us, whatever the file limits above say. Large images are the usual cause:
send an image layer as WebP with transparency rather than PNG (it's stored
as PNG either way, at a fraction of the upload size), cap it at 2560px since
nothing larger is kept, and send one image per request — create or update
the surface with the screenshot, then add each image layer in its own
update.

**Updating one.** Each part you send replaces the saved one, and each part
you leave out entirely keeps it. Start from what's saved:

1. `GET https://<your-app>.subtleads.example/api/surfaces/<key>` returns
   `{ key, label, description, screenshot, layers, sampleValues, previewUrl }`,
   with every setting filled in, defaults included.
2. POST with `existingKey` set to that key, and only what's changing:
   - `layers`, if sent, is the **whole** stack, edited. A layer you leave
     out of it is deleted, so send the unchanged ones back exactly as the GET
     returned them (`id`, `transform` and `style` included) alongside
     your additions. Leave `layers` out altogether to keep them all — to
     re-shoot just the screenshot, say.
   - `label`, `description` and `sampleValues` — leave out to keep;
     send `description` empty to clear it.
   - An `image` layer keeps its saved image as long as its `id` is
     unchanged and you send no `layer_file_<id>`. You don't need the
     original file to keep it.
   - `screenshot` — leave it out to keep the current one, or send a new
     file to re-shoot it. Corners are fractions of the screenshot, so a
     recapture at the same framing keeps every pin in place.

**Example — giving a text-only slot its preview.** A game-over panel whose
screenshot has placeholder copy baked into it ("Your splash line", "Your
Button Text") shows every sponsor that copy instead of their own. Re-shoot
the screenshot with the placeholder gone, then add one text layer per field
over the spot the app draws it, on top of the layers already there:

```json
[
  { "id": "splash_line", "label": "Splash line", "kind": "text", "fieldKey": "blurb",
    "fallbackText": "Your splash line", "fontSizePct": 4.5, "maxLines": 2,
    "transform": { "mode": "warp", "corners": [[0.32, 0.40], [0.68, 0.40], [0.68, 0.62], [0.32, 0.62]] } },
  { "id": "button_label", "label": "Button label", "kind": "text", "fieldKey": "cta_label",
    "fallbackText": "Your Button Text", "fontSizePct": 3.5, "fontWeight": "bold", "maxLines": 1,
    "color": "#0d3b2a",
    "transform": { "mode": "warp", "corners": [[0.40, 0.80], [0.60, 0.80], [0.60, 0.90], [0.40, 0.90]] } }
]
```

The corners here are illustrative; take them from where the copy sits in
your screenshot. The old placeholder wording makes a good `fallbackText`,
since it's what shows until a sponsor types. Bind only fields the campaign
types using this surface declare as text fields (check `GET /api/types`);
anything else just shows the fallback. Size each box for the longest copy
the field allows (its `maxLength`): the preview cuts anything that doesn't
fit to an ellipsis, which tells a sponsor their copy runs long when it may
in fact fit in the app.

**There is no automated visual check.** This platform has no server-side
renderer for a surface — the composited view is a live browser effect, not
an image file — so nothing here can confirm a quad actually lines up with
the billboard/card/banner in the screenshot. After creating or updating one,
open its `previewUrl` (`/app/surfaces/<key>`) and have a person confirm it
looks right before pointing a real slot's `previewSurface` at it.

## Live preview — the app itself, in the booking form

A preview surface is a screenshot. A live preview is the app's own page,
framed in the booking form and fed the sponsor's draft as they edit, so they
see their brand in the real scene before they pay. The same page appears,
with the submitted values, on the team's review queue and the sponsor's
campaign page, and in the catalogue drawing its own sample brand. Wherever
the page doesn't answer, the preview surfaces are shown instead, so keep them.

### What the app builds

1. **A page on your own domain**, e.g. `https://preview.example.com/subtleads`,
   that draws the scene from the messages below. Not on the portal's own site:
   pages there share the portal's sign-in, so Setup refuses them.
2. **Its token**, served as the whole of
   `https://<that domain>/.well-known/subtleads-preview`. The token is on Setup's
   Live preview card; saving the page's address, or "Check again", fetches it
   (https on 443, no redirects, 5 seconds, 1 KB).
3. **A frame-ancestors policy** naming the portal, so no one else can frame
   the page: `Content-Security-Policy: frame-ancestors https://<your-app>.subtleads.example` (and any
   custom portal domain; the card lists them).
4. **The agreement** on the card: preview data is used only to draw the
   preview, the page uploads and stores nothing it receives, and passes
   nothing on. Sponsors are told their unsubmitted files reach the page.

While building it, register a **development page** on the card too
(`http://localhost:<port>/…`, no token needed). It's framed instead of the
live page for the app's own team only, so you can try it before deploying.

### The frame

`sandbox="allow-scripts allow-same-origin"`, `allow=""`,
`referrerpolicy="no-referrer"`: no forms, popups, dialogs or top navigation.
Laid out at phone (390×844) or desktop
(1440×900), as the sponsor picks, and scaled to fit.

### Messages

Every message has `type` and `v`. Post to the portal's origin, never `"*"`,
and accept only messages whose `event.origin` is the portal's.

- **page → editor, on load:** `{ type: "subtleads.preview.ready", v: 1, accepts: [1] }`
  — the versions you speak. No `ready` within
  5 seconds of the frame loading, or no
  version in common, and the editor shows the preview surfaces.
- **editor → page:** `{ type: "subtleads.preview.state", v: 1, seq, campaignTypeId, typeVersion, sample?, fields, creatives, focus? }`
  — after every `ready`, then on each edit, at most one per
  150 ms, always the whole state. Draw nothing older than
  the last `seq` you drew.
  - `fields`: the type's declared fields only, typed as stored. An optional
    field left empty is absent; a yes/no is always `true` or `false`; a
    multi-select is an array. Never budget, dates, targeting, price or contact
    details.
  - `creatives[assetKey]`: `{ file: Blob, contentType, width, height }` for a
    file the sponsor has picked but not submitted — draw it with
    `URL.createObjectURL(file)` — or `{ url, contentType, width, height }`
    for stored creative. An asset that allows several files is an array, in
    the sponsor's order. Files arrive as picked, up to 32 MB; the asset's size
    and shape are checked at submit, so answer an oversized one with a check
    rather than drawing nothing.
  - `focus`: `{ field }` or `{ asset }`, the control the sponsor is editing —
    show where it appears.
  - `sample: true` (the catalogue): `fields` and `creatives` are empty;
    draw your own sample brand.
- **page → editor:** `{ type: "subtleads.preview.checks", v: 1, seq, checks: [{ field?, asset?, level: "warning" | "info", message }] }`
  — advisory notes about state `seq`, shown under the field or upload they
  name (or under the frame) as plain text, never blocking submit. Up to
  20 of 200 characters. Answer each
  state with its checks; `[]` clears them. Rules that must hold belong in the
  campaign type, where the server enforces them.
- **page → editor:** `{ type: "subtleads.preview.resize", v: 1, height }` —
  for a page that knows its height, between 200 and
  4000 px.

Treat every value as untrusted: text as text, never HTML; images only
through object URLs or the given URL.

