# AnimStream Widget SDK

Erstelle Flow-Alerts und Live-Widgets als UTF-8-JSON-Datei widget.json. Version 1 bietet die Layouts card, strip und plain. Version 2 zeichnet frei gestaltete Widgets mit Canvas 2D oder WebGL 2. Der Request darf bis zu 256 KiB groß sein.

## Quickstart

1. Wähle den passenden Modus und kopiere ein gültiges Beispiel von unten.
2. Speichere es als widget.json und passe Inhalt, Layout und Farben an.
3. Prüfe die Datei mit dem JSON Schema und sende sie an die Vorschau-API.

4. Lade die fertige widget.json im [Widget-Bereich des Vendor Studios](https://animstream.com/de/vendor/widgets) hoch. Reiche sie zur Widget-Prüfung ein und verfolge den Status unter „Einreichungen“.

- `alert` — Spielt kurz ab, wenn ein Flow auslöst. Wähle im Flow-Assistenten einen Trigger und das Widget aus deinen Store-Inhalten.

- `live` — Bleibt als Szenenquelle sichtbar. Studio liefert die aktuellen Sitzungswerte für einen Zähler oder Fortschrittsbalken.

## Startprompt für KI-Assistenten

```text
Lies https://animstream.com/de/developers/widgets/index.md. Baue eine gültige widget.json für diese Idee: [deine Idee]. Wähle zwischen einer v1-Vorlage und einem frei gestalteten Canvas-Widget (v2). Nutze ein passendes Beispiel. Prüfe die Datei gegen das Schema und teste sie mit der Vorschau-API. Zeige mir die Datei und die Testergebnisse.
```

[Agent kit](https://animstream.com/widget-sdk/animstream-widget-agent-kit.zip)

## Preview API · POST /api/widget-sdk/preview

Der Body enthält das Manifest selbst. HTTP 200 liefert HTML mit Beispieldaten und Wasserzeichen. HTTP 400 bedeutet ungültiges JSON, 413 ein zu großes Paket und 422 einen Schemafehler mit Feldpfad und Meldung.

```sh
curl --fail-with-body -sS \
  -H 'Content-Type: application/json' \
  --data-binary @widget.json \
  https://animstream.com/api/widget-sdk/preview -o preview.html
```

## Flow alert · widget.json

```json
{
  "version": 1,
  "mode": "alert",
  "title": "Gift Spotlight",
  "description": "A compact thank-you card for a TikTok LIVE gift.",
  "headline": "Thank you, {user}!",
  "detail": "{gift} × {count}",
  "durationSeconds": 5,
  "events": ["GIFT"],
  "shareInCommunity": true,
  "appearance": {
    "layout": "card",
    "accent": "#D4FF4F",
    "foreground": "#F5F6FA",
    "background": "#191C25"
  }
}
```

## Live widget · widget.json

```json
{
  "version": 1,
  "mode": "live",
  "title": "After Hours Like Goal",
  "description": "A like counter with a cyan progress bar for night streams.",
  "headline": "Like goal",
  "detail": "Tap the screen to join in.",
  "metric": "likes",
  "goal": 10000,
  "showProgress": true,
  "shareInCommunity": true,
  "appearance": {
    "layout": "strip",
    "accent": "#4DF2DC",
    "foreground": "#E8FFFB",
    "background": "#162734"
  }
}
```

## Widget SDK v2 — Canvas widgets

Use v2 for bespoke effects such as fireworks, character animations, flowing
backgrounds, visualizers, custom scoreboards, or a completely custom UI. The
render function can draw any layout and visuals with Canvas 2D or WebGL 2.
Use v1 for the ready-made card, strip and plain layouts.

## Manifest

Set `version: 2` and put a single JavaScript function expression in `program`.
Keep the source as a separate JavaScript file while building. Serialize it as a
JSON string when writing `widget.json`. TypeScript authors should compile to
JavaScript first. See [canvas-runtime.d.ts](https://animstream.com/widget-sdk/agent-kit/canvas-runtime.d.ts)
for the render context and [widget.schema.json](https://animstream.com/widget-sdk/agent-kit/widget.schema.json)
for the accepted manifest fields.

```js
function render({ctx, width, height, time, event}) {
  ctx.clearRect(0, 0, width, height);
  ctx.fillStyle = "#91f2ff";
  ctx.beginPath();
  ctx.arc(width / 2, height / 2, 20 + Math.sin(time * 4) * 8, 0, Math.PI * 2);
  ctx.fill();
  ctx.fillText(event.user || "Hello", 12, 22);
}
```

| Field | Meaning |
| --- | --- |
| `mode: "alert"` | Plays when a Studio Flow triggers. `durationSeconds` is 1–30. Studio manages queueing and completion. |
| `mode: "live"` | Runs as a persistent source. Use `counters` to draw session totals. `metric`, `goal` and `showProgress` provide the same defaults as v1. The program owns what gets drawn. |
| `renderer` | Optional `"2d"` (default) or `"webgl2"`. In WebGL set the viewport on resize and clear buffers before each draw. |
| `fps` | Optional 12–60 frames per second, default 30. Keep each call fast enough for the frame interval. |
| `images` | Optional map of names to `{ mime, data }`. Use PNG, JPEG or WebP with raw base64. Each decoded image must fit within 2048 × 2048. Draw them through `images[name]`. |
| `program` | One synchronous function expression, up to 32,768 characters. No DOM or Node APIs. |
| Total request | At most 256 KiB, including manifest and embedded images. |

## Frame input

- `ctx`, `canvas`, `width`, `height` give you the rendering context, an OffscreenCanvas and its current pixel dimensions. The surface can resize while running and is capped at 1920 pixels on either axis.
- `time` and `delta` are seconds. `progress` is 0–1 for an alert and `null` for a persistent source. Studio may seek directly to a time for a still preview. Use time-based math and a seeded random function for effects that can seek.
- `event` contains `user`, `gift`, `count`, `coins` and `level` strings for Flow alerts. Fields may be empty. Convert numeric strings defensively.
- `counters` holds the available session numbers keyed by `gifts`, `coins`, `likes`, `follows`, `shares`, `comments`, `joins` and `subscribes`.
- `params` contains editable `headline`, `detail` and optional `goal`. For live widgets, `metric` and `showProgress` are also provided.
- `state` is an initially empty object retained between render calls for the same playback. It resets on replay or seek. `images` contains decoded assets. No DOM, external network access, account credentials or arbitrary Studio APIs are available to the program.

The render worker runs separately from the document. Return synchronously and
draw into the supplied context. Use a transparent background if the scene
should show through. Use a Flow audio action when an effect needs sound.

## Fireworks example

[Download fireworks.json](https://animstream.com/widget-sdk/agent-kit/examples/fireworks.json)
or read the [editable JavaScript](https://animstream.com/widget-sdk/agent-kit/examples/fireworks.js).
This example uses timed bursts, gravity, fading trails, additive glow and the
viewer's name. The number of sparks responds to the event count. It covers
portrait and landscape surfaces using relative coordinates.

Preview this file in the Widget SDK playground. Render it at multiple sizes,
check a full alert cycle and run it in the Flow Wizard with a test trigger.
For a live widget, change the test counters and verify that the displayed
values update without restarting playback. Follow the same Vendor Studio review
flow as v1.

## Fireworks · render function

[fireworks.json](https://animstream.com/widget-sdk/agent-kit/examples/fireworks.json)

```js
function render({ ctx, width, height, time, event }) {
  const unit = Math.min(width, height);
  const palette = ["#a7ff66", "#55edff", "#fbb754", "#ff78d6", "#ae95ff"];
  const bursts = [
    { x: .38, y: .46, at: .65, hue: 0 },
    { x: .68, y: .32, at: 1.1, hue: 2 },
    { x: .54, y: .61, at: 1.65, hue: 3 },
  ];
  const strength = Math.min(140, 72 + 6 * Math.max(0, Number(event.count) || 0));
  const random = (index) => {
    const value = Math.sin(index * 127.1 + 311.7) * 43758.5453123;
    return value - Math.floor(value);
  };
  ctx.clearRect(0, 0, width, height);
  ctx.save();
  ctx.globalCompositeOperation = "lighter";

  for (const [index, burst] of bursts.entries()) {
    const age = time - burst.at;
    const x = burst.x * width;
    const y = burst.y * height;
    if (age < 0 && age > -.55) {
      const launch = 1 + age / .55;
      const rocketY = height + (y - height) * launch;
      ctx.strokeStyle = palette[burst.hue];
      ctx.lineWidth = Math.max(1, unit * .007);
      ctx.beginPath();
      ctx.moveTo(x, rocketY);
      ctx.lineTo(x - unit * .025, rocketY + unit * .1);
      ctx.stroke();
    }
    if (age < 0 || age > 2.25) continue;

    const spread = .45 * (1 - Math.exp(-age * 1.65)) * unit;
    const fade = Math.max(0, 1 - age / 2.25);
    const glow = ctx.createRadialGradient(x, y, 0, x, y, Math.max(1, unit * .21 + spread * .35));
    glow.addColorStop(0, palette[burst.hue] + "78");
    glow.addColorStop(1, palette[burst.hue] + "00");
    ctx.globalAlpha = fade * fade;
    ctx.fillStyle = glow;
    ctx.fillRect(0, 0, width, height);

    for (let i = 0; i < strength; i++) {
      const seed = index * 173 + i;
      const angle = i / strength * Math.PI * 2 + random(seed) * .27;
      const velocity = .28 + .72 * random(seed + .5);
      const radius = spread * velocity;
      const gravity = age * age * unit * .043;
      const px = x + Math.cos(angle) * radius;
      const py = y + Math.sin(angle) * radius + gravity;
      const trail = unit * (.009 + .021 * velocity) * fade;
      const flicker = .52 + .48 * Math.sin(seed * 1.3 + time * (8 + velocity * 15)) ** 2;
      const colour = palette[(burst.hue + (i % 15 === 0 ? 2 : i % 4 === 0 ? 1 : 0)) % palette.length];
      ctx.globalAlpha = fade * flicker;
      ctx.strokeStyle = colour;
      ctx.lineWidth = Math.max(1, unit * (.003 + .007 * random(seed + 1)));
      ctx.lineCap = "round";
      ctx.beginPath();
      ctx.moveTo(px - Math.cos(angle) * trail, py - Math.sin(angle) * trail);
      ctx.lineTo(px, py);
      ctx.stroke();

      if (i % 11 === 0) {
        ctx.fillStyle = "#ffffff";
        ctx.beginPath();
        ctx.arc(px, py, Math.max(1, unit * .005), 0, Math.PI * 2);
        ctx.fill();
      }
    }
  }

  ctx.globalCompositeOperation = "source-over";
  ctx.globalAlpha = Math.min(1, Math.max(0, (time - .48) * 3), Math.max(0, (4 - time) * 2));
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.font = "700 " + Math.max(14, unit * .11) + "px system-ui";
  ctx.shadowColor = "#180930";
  ctx.shadowBlur = unit * .05;
  ctx.fillStyle = "#fff";
  const name = (event.user || "Fireworks").slice(0, 28);
  ctx.fillText(name, width / 2, height * .83, width * .88);
  ctx.restore();
}
```

## JSON Schema

[widget.schema.json](https://animstream.com/widget-sdk/agent-kit/widget.schema.json)

```json
{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "oneOf": [
    {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "title": {
              "type": "string",
              "minLength": 2,
              "maxLength": 80
            },
            "description": {
              "type": "string",
              "minLength": 12,
              "maxLength": 1000
            },
            "headline": {
              "type": "string",
              "minLength": 1,
              "maxLength": 100
            },
            "detail": {
              "type": "string",
              "maxLength": 160
            },
            "shareInCommunity": {
              "type": "boolean"
            },
            "version": {
              "type": "number",
              "const": 1
            },
            "appearance": {
              "type": "object",
              "properties": {
                "layout": {
                  "type": "string",
                  "enum": [
                    "card",
                    "strip",
                    "plain"
                  ]
                },
                "accent": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                },
                "foreground": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                },
                "background": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                }
              },
              "required": [
                "layout",
                "accent",
                "foreground",
                "background"
              ],
              "additionalProperties": false
            },
            "mode": {
              "type": "string",
              "const": "alert"
            },
            "durationSeconds": {
              "type": "integer",
              "minimum": 1,
              "maximum": 30
            },
            "events": {
              "minItems": 1,
              "maxItems": 8,
              "type": "array",
              "items": {
                "type": "string",
                "enum": [
                  "GIFT",
                  "LIKE",
                  "FOLLOW",
                  "SHARE",
                  "COMMENT",
                  "JOIN",
                  "SUBSCRIBE",
                  "LEVEL_UP"
                ]
              },
              "uniqueItems": true
            }
          },
          "required": [
            "title",
            "description",
            "headline",
            "detail",
            "version",
            "appearance",
            "mode",
            "durationSeconds"
          ],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "title": {
              "type": "string",
              "minLength": 2,
              "maxLength": 80
            },
            "description": {
              "type": "string",
              "minLength": 12,
              "maxLength": 1000
            },
            "headline": {
              "type": "string",
              "minLength": 1,
              "maxLength": 100
            },
            "detail": {
              "type": "string",
              "maxLength": 160
            },
            "shareInCommunity": {
              "type": "boolean"
            },
            "version": {
              "type": "number",
              "const": 1
            },
            "appearance": {
              "type": "object",
              "properties": {
                "layout": {
                  "type": "string",
                  "enum": [
                    "card",
                    "strip",
                    "plain"
                  ]
                },
                "accent": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                },
                "foreground": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                },
                "background": {
                  "type": "string",
                  "pattern": "^#[0-9A-Fa-f]{6}$"
                }
              },
              "required": [
                "layout",
                "accent",
                "foreground",
                "background"
              ],
              "additionalProperties": false
            },
            "mode": {
              "type": "string",
              "const": "live"
            },
            "metric": {
              "type": "string",
              "enum": [
                "gifts",
                "coins",
                "likes",
                "follows",
                "shares",
                "comments",
                "joins",
                "subscribes"
              ]
            },
            "goal": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000000000
            },
            "showProgress": {
              "type": "boolean"
            }
          },
          "required": [
            "title",
            "description",
            "headline",
            "detail",
            "version",
            "appearance",
            "mode",
            "metric",
            "goal",
            "showProgress"
          ],
          "additionalProperties": false
        }
      ]
    },
    {
      "oneOf": [
        {
          "type": "object",
          "properties": {
            "title": {
              "type": "string",
              "minLength": 2,
              "maxLength": 80
            },
            "description": {
              "type": "string",
              "minLength": 12,
              "maxLength": 1000
            },
            "headline": {
              "type": "string",
              "minLength": 1,
              "maxLength": 100
            },
            "detail": {
              "type": "string",
              "maxLength": 160
            },
            "shareInCommunity": {
              "type": "boolean"
            },
            "version": {
              "type": "number",
              "const": 2
            },
            "program": {
              "type": "string",
              "minLength": 1,
              "maxLength": 32768
            },
            "renderer": {
              "type": "string",
              "enum": [
                "2d",
                "webgl2"
              ]
            },
            "fps": {
              "type": "integer",
              "minimum": 12,
              "maximum": 60
            },
            "images": {
              "type": "object",
              "propertyNames": {
                "type": "string",
                "pattern": "^[a-z][a-z0-9_-]{0,31}$"
              },
              "additionalProperties": {
                "type": "object",
                "properties": {
                  "mime": {
                    "type": "string",
                    "enum": [
                      "image/png",
                      "image/jpeg",
                      "image/webp"
                    ]
                  },
                  "data": {
                    "type": "string",
                    "minLength": 4,
                    "maxLength": 196608,
                    "pattern": "^[A-Za-z0-9+/]+={0,2}$"
                  }
                },
                "required": [
                  "mime",
                  "data"
                ],
                "additionalProperties": false
              }
            },
            "mode": {
              "type": "string",
              "const": "alert"
            },
            "durationSeconds": {
              "type": "integer",
              "minimum": 1,
              "maximum": 30
            },
            "events": {
              "minItems": 1,
              "maxItems": 8,
              "type": "array",
              "items": {
                "type": "string",
                "enum": [
                  "GIFT",
                  "LIKE",
                  "FOLLOW",
                  "SHARE",
                  "COMMENT",
                  "JOIN",
                  "SUBSCRIBE",
                  "LEVEL_UP"
                ]
              },
              "uniqueItems": true
            }
          },
          "required": [
            "title",
            "description",
            "headline",
            "detail",
            "version",
            "program",
            "mode",
            "durationSeconds"
          ],
          "additionalProperties": false
        },
        {
          "type": "object",
          "properties": {
            "title": {
              "type": "string",
              "minLength": 2,
              "maxLength": 80
            },
            "description": {
              "type": "string",
              "minLength": 12,
              "maxLength": 1000
            },
            "headline": {
              "type": "string",
              "minLength": 1,
              "maxLength": 100
            },
            "detail": {
              "type": "string",
              "maxLength": 160
            },
            "shareInCommunity": {
              "type": "boolean"
            },
            "version": {
              "type": "number",
              "const": 2
            },
            "program": {
              "type": "string",
              "minLength": 1,
              "maxLength": 32768
            },
            "renderer": {
              "type": "string",
              "enum": [
                "2d",
                "webgl2"
              ]
            },
            "fps": {
              "type": "integer",
              "minimum": 12,
              "maximum": 60
            },
            "images": {
              "type": "object",
              "propertyNames": {
                "type": "string",
                "pattern": "^[a-z][a-z0-9_-]{0,31}$"
              },
              "additionalProperties": {
                "type": "object",
                "properties": {
                  "mime": {
                    "type": "string",
                    "enum": [
                      "image/png",
                      "image/jpeg",
                      "image/webp"
                    ]
                  },
                  "data": {
                    "type": "string",
                    "minLength": 4,
                    "maxLength": 196608,
                    "pattern": "^[A-Za-z0-9+/]+={0,2}$"
                  }
                },
                "required": [
                  "mime",
                  "data"
                ],
                "additionalProperties": false
              }
            },
            "mode": {
              "type": "string",
              "const": "live"
            },
            "metric": {
              "type": "string",
              "enum": [
                "gifts",
                "coins",
                "likes",
                "follows",
                "shares",
                "comments",
                "joins",
                "subscribes"
              ]
            },
            "goal": {
              "type": "integer",
              "minimum": 1,
              "maximum": 1000000000
            },
            "showProgress": {
              "type": "boolean"
            }
          },
          "required": [
            "title",
            "description",
            "headline",
            "detail",
            "version",
            "program",
            "mode",
            "metric",
            "goal",
            "showProgress"
          ],
          "additionalProperties": false
        }
      ]
    }
  ],
  "title": "AnimStream Widget Package"
}
```

---

## AnimStream Widget SDK

A widget package is a UTF-8 JSON file named `widget.json`. The schema defines the
accepted keys and bounds. Requests are up to 256 KiB. Hosted previews and Studio use
the same rendering code. Version 1 uses built-in layouts, text, colours and
Studio event data. Version 1 is declarative. For original motion graphics, see [Canvas SDK v2](https://animstream.com/widget-sdk/agent-kit/CANVAS.md). Its render function runs in an isolated worker with local graphics and Studio event data.

## Alert

Set `mode: "alert"` with a 1–30 second duration. In the Flow Wizard, choose a
trigger, such as a specific gift, and your widget from the Store assets that you
own. Assign it to an animation surface and preview the flow. Studio handles the
queue, trigger matching and playback. The widget reports completion at its
configured duration. When used in a flow the event is available as
`{user}`, `{gift}`, `{count}`, `{coins}` and `{level}` in headline and detail.
Treat absent values as optional.

Both declarative and Canvas alerts can declare which Studio events reviewers
should try. For example, add `"events": ["GIFT", "FOLLOW"]` to an alert package.
Supported codes are `GIFT`, `LIKE`, `FOLLOW`, `SHARE`, `COMMENT`, `JOIN`,
`SUBSCRIBE` and `LEVEL_UP`. List each intended event once. The review simulator
offers a test button for each one. This list is optional. Streamers choose the
actual trigger in their Studio Flow. The available event fields stay the same.

## Live

Set `mode: "live"` and choose one session metric from the schema. Place it as a
source in Studio. The metric follows the active session counters. The source
settings support custom text and goal. The goal affects the optional progress
bar. The same package can be reused across scenes.

## Preview

Post the manifest JSON to `/api/widget-sdk/preview` for a watermarked test
document. The docs at animstream.com/developers/widgets provide a file picker
and an editor. Flow previews use synthetic gifts and live previews show a
sample counter. For production, Studio supplies session and flow values.

## Publishing

Open [Vendor Studio → Widgets](https://animstream.com/vendor/widgets) and load
your `widget.json`. Test the preview, choose the price in EUR and submit the
package for widget review. Check [Submissions](https://animstream.com/vendor/widgets#submissions)
for its status and any reviewer feedback. Set zero for a free listing. Connect your payout account for Store listings. AnimStream's marketplace
collects 15% of vendor sales. Set
`shareInCommunity: true` to include the approved listing in the Studio
Community widget catalog. A paid listing keeps its Store entitlement when
featured in the Community.

[HTML](https://animstream.com/de/developers/widgets) · [AnimStream Docs Index](https://animstream.com/llms.txt)

