# NuuStudio add-on contract (API version 1)

Everything here is exported by `@nuustudio/sdk` (types in `src/types.ts`). The EmDash adapter is `@nuustudio/sdk/emdash`.

## Package layout

```
src/addon.ts    defineAddon({...})                    shared with the builder: no secrets, no CMS imports
src/server.ts   { dataProviders, viewer }             server only
src/index.ts    emdashAddon(addon, { package, server, plugin })   the EmDash plugin entry
src/admin.ts    registerAddon(addon[, { client }]); export const pages = {...}
package.json    "main": "./dist/index.mjs", exports "./admin": "./src/admin.ts", build with tsdown
```

## defineAddon(addon)

| Field | Type | Notes |
| --- | --- | --- |
| `id` | `string` | lowercase-hyphen; also the EmDash plugin id |
| `label`, `version?`, `description?` | `string` | shown in Settings → Add-ons |
| `modules?` | `AddonModule[]` or `(kit) => AddonModule[]` | use the function form to use the kit |
| `settings?` | `{ description?, fields: AddonSettingField[] }` | form in Settings → Add-ons |
| `ruleTypes?` | `AddonRuleType[]` | display conditions, answered on the server from the viewer |
| `dynamicSources?` | `AddonDynamicSource[]` | Dynamic Content entries, from the viewer |
| `pageAccess?` | `AddonPageAccess` | options in Page Settings → Who can see this page |
| `layouts?` | `AddonLayout[]` or `(kit) => AddonLayout[]` | starter layouts in the builder's Library |
| `adminPages?` | `{ path, label, icon }[]` | links in NuuStudio's sidebar to the plugin's admin pages |
| `privateCookies?` | `string[]` | requests with these cookies are never shared-cached |

## AddonModule

| Field | Notes |
| --- | --- |
| `name` | `<id>` or `<id>-…` |
| `label`, `icon`, `description?` | `icon`: builder icon name (`calendar`, `users`, `sparkles`…) or inline SVG body for a 24×24 viewBox |
| `category` | `basic`, `media`, `interactive`, `forms`, `dynamic`, `social`, `fullwidth`, or your own id with `categoryLabel` |
| `groups` | `{ id, label, tab: "content" \| "design" \| "advanced", open?, fields }[]` |
| `defaults` | settings of a new instance |
| `design?` | shared group targets: `{ heading: " .x", text: " .y", button: " .z", noBackground?: true, text?: false }` |
| `inlineEdit?` | `{ key, selector, rich? }[]`: text edited on the canvas |
| `render(s, ctx)` | HTML string; server and canvas |
| `css?(s, sel, out, ctx)` | `out.add(selector, { prop: value }, state?)`, `out.raw(css)`; `sel` is the module root |
| `baseCss?` | emitted once per page that uses the module |
| `runtime?` | JS function body, `el` + `Dash`, ES2018 |
| `requires?` | shared chunks, e.g. `["forms"]` for form styles |
| `data?(s)` | `{ provider, args? }`: loads `addonData(ctx)` before render (args must be JSON) |
| `ai?.hint` | tells NuuStudio's AI Builder / MCP clients when to use it |
| `hidden?` | kept for old pages, not offered any more |

**Field types:** `text`, `textarea`, `richtext`, `code`, `url`, `number`, `range` (`min`, `max`, `step`, `units`), `select` / `buttons` (`options: { value, label, icon? }[]`), `toggle`, `color`, `image`, `gallery`, `video`, `icon`, `font`, `align`, `spacing`, `corners`, `date`, `repeater` (`fields`, `itemTitleKey`, `itemLabel`, `itemDefaults`, `modal: { title, subtitle?, button? }`). Common: `key`, `label`, `default`, `description`, `placeholder`, `responsive` (tablet / phone values), `hover`, `show: (settings) => boolean`.

**Render context:** `ctx.editor` (in the builder), `ctx.node.id`, `ctx.data.page.url`. Helpers: `esc(v)`, `safeUrl(v)`, `addonData(ctx)`, `addonViewer(ctx, addonId)`.

## Settings fields

`{ key, label, type: "text" | "textarea" | "secret" | "toggle" | "select" | "number" | "url", description?, placeholder?, options?, default? }`. Saved as the plugin's EmDash settings (secrets encrypted). Read them server-side from `ctx.settings` in data providers / the viewer, or `ctx.settings.get(key)` in your own routes.

## Server part (`NuuAddonServer`)

```ts
const server: NuuAddonServer = {
  dataProviders: {
    // args from the module's data(); ctx: { settings, editor, entry? }
    upcoming: async (args, { settings, editor, entry }) => ({ … }),
  },
  // Once per request before NuuStudio renders; return null for nobody. Never return secrets.
  viewer: async ({ request, locals }) => ({ … }) ,
};
```
Providers time out after 8 s and a failure only leaves `addonData(ctx)` undefined. Viewers time out after 3 s.

## Viewer-based features

```ts
ruleTypes: [{
  id: "<id>-level", label: "Member level", icon: "award", section: "Visitor", word: "is",
  operators: ["any", "none"], value: "text" /* | "enum" | "number" */, options?, single?, mono?, placeholder?,
  key?: { label, placeholder },             // a name typed before the operator
  hint?,
  evaluate: (rule, viewer) => boolean | null,   // rule: { type, operator, values, key? }; null = skip
}],
dynamicSources: [{
  id: "<id>-name", label: "Member Name", group: "Member", kinds: ["text", "html"],
  needsKey?, keyLabel?, dated?,
  resolve: (viewer, { key, editor }) => string,
  sample?: "Alex Morgan" | ((key) => string),  // what the builder shows
}],
pageAccess: {
  options: [{ value: "member", label: "Active members" }, { value: "level", label: "Members at a level…", argument: { label: "Level" } }],
  check: (value, argument, viewer) => boolean,      // stored as "<id>:<value>[:<argument>]"
  noAccess?: (viewer, settings) => ({ signInModule?, joinUrl? }),
},
```
Use `kit.rules.text(operator, actualValues, ruleValues)` in `evaluate` to match text exactly like built-in rules. Pages using these are sent `private, no-cache`.

## Layouts

```ts
layouts: [{ id: "<id>-checkout-page", name, category, description,
  build: (id) => ({ version: 1, sections: [{ id: id(), type: "section", settings: {}, rows: [
    { id: id(), type: "row", layout: "4_4", settings: {}, columns: [
      { id: id(), type: "column", settings: {}, modules: [{ id: id(), type: "module", name: "<id>-x", settings: {} }] }] }] }] }) }]
```
Row layouts: `4_4`, `1_2,1_2`, `1_3,1_3,1_3`, `2_3,1_3`, `1_4,1_4,1_4,1_4`….

## The kit (`NuuKit`)

| Member | What |
| --- | --- |
| `fields.textGroup(id, label, prefix, extra?, { headingLevel? })` | text style group; target it with `design[prefix]` |
| `fields.buttonGroup(prefix?, label?)` | full button style group |
| `forms.builderFields()` | Contact Form field-builder item fields (for a `repeater`) |
| `forms.fieldHtml(field, index, nodeId, showLabels, marks?)` | one built form field as HTML |
| `forms.engineJs` | form engine (`window.DashForm`); prepend to a runtime that uses built fields |
| `html.icon(name, className?)`, `html.part(ctx, id, index?)` | inline SVG icon; click-to-edit part marks |
| `css.prop(s, key, cssProp, out, { sel, hoverSel? }, transform?)` | responsive + hover CSS from a setting |
| `css.color(value, ctx)` | color setting to CSS (global colors resolved) |
| `rules.text(op, actual, values)` | text rule matching |
| `server?.deliver({ event, formId, name, fields, email?, firstName?, lastName?, page?, targets })` | send to the site's integrations (webhook, Mailchimp, Kit…) |
| `server?.settings(addonId)` / `server?.storage(addonId, collection, indexes)` | settings / storage outside your routes |
| `ui?` | admin React components: `Page`, `AdminShell`, `AdminShellLoading`, `Group`, `Field`, `Pill`, `Result`, `Icon`, `Modal`, `Spinner`, `Toggle`, `useToast`, `useAdminCss` |

`getKit()` returns it once NuuStudio has loaded (`undefined` before). Inside `modules: (kit) => …` it's the argument.

## Browser part

```ts
// src/admin.ts
registerAddon(addon, { client: { textCheckers: [checker] } });   // checker: { id, label, check(text, { lang, context }), languages?, dictionary?, status?, onStatus?, warmUp? }
export const pages = { "/my-page": MyPage };                        // React; wrap in kit.ui.Page and kit.ui.AdminShell
```
List the page in `plugin.admin.pages` (`{ path, label, icon, group: "NuuStudio" }`) and in `adminPages` so NuuStudio's sidebar links it.

## emdashAddon(addon, options)

```ts
const plugin = emdashAddon(addon, {
  package: "@acme/nuu-thing",          // npm name; adminEntry defaults to "<package>/admin"
  server,                               // NuuAddonServer
  plugin: { capabilities, routes, storage, hooks, admin: { pages, settingsSchema }, mcp },
});
export const acmeThing = (options = {}) => plugin.descriptor(options);   // for astro.config.mjs
export const createPlugin = plugin.createPlugin;
export default createPlugin;
```
Adds routes `nuu/settings`, `nuu/settings/save` (when there are settings) and `nuu/uninstall` (deletes declared storage, settings and KV after your `plugin:uninstall` hook).

## Lifecycle

- **On / off:** the EmDash plugin state. Off: NuuStudio ignores every contribution, its routes answer 404, elements stay on pages (the site leaves them out, the builder shows a note).
- **Uninstall** (Settings → Add-ons): optionally deletes the data, turns it off, then shows the steps to remove it from `astro.config.mjs` and the package.
- **Install:** `pnpm add` + `astro.config.mjs` + restart / redeploy. Add-ons run in page rendering, so they ship with the site's code (no runtime install).
