# Write a plugin and publish it

**Goal:** create a Récit plugin package, give it one static directive, test it, draw it in a deck
with `recit build`, and publish the package on npm.

**The plugin API is experimental**, except for the
[v1 data source contract](/documentation/plugins/data-sources): it may change in a minor release
([Stability](/documentation/reference/stability#experimental)). Pin the version of `recit` your
plugin peers on.

This guide follows the reference plugin of the repository, `examples/plugin-lorem`, and the deck
that uses it, `examples/deck-plugin`. For every capability (components, film blocks, themes,
exporters, data sources, commands, AI jobs), see [Writing a plugin](/documentation/plugins/writing).

## 1. Create the package

Récit is not on npm: `create-recit`, which holds the template, and the `recit` packages come as
archives of the private channel ([Quickstart](/documentation/getting-started/quickstart)). With them
in `archives/`:

```bash
npm install -g npm@11
npm exec --package ./archives/create-recit.tgz -- create-recit recit-plugin-acme --template plugin
cd recit-plugin-acme
npm install ../archives/*.tgz
```

The `plugin` template is a copy of `examples/plugin-lorem`: one of each capability, its tests and a
build with `tsdown`. **It needs npm 11 or later** (`engines.npm`): npm 10 crashes while it installs
vitest 4.1. The package takes the name of its folder; call it `recit-plugin-<name>` or
`@scope/recit-plugin-<name>`.

The template names everything `lorem`, and this guide keeps its names so that each step matches the
files you have. Rename `lorem` to your own short name (`acme`) once the guide works: it prefixes
your directives, your diagnostics (`acme/quote-empty`) and your commands (`recit acme sync`).

## 2. Write the directive

A static directive is a function that returns [hast](https://github.com/syntax-tree/hast) at build
time: the page gets HTML and no script. Open `src/quote.ts`:

```ts title="src/quote.ts"
import type { Element, ElementContent } from "hast";
import type { PluginDirectiveRender } from "recit/plugin";
import type { LoremOptions } from "./options.js";

type Node = { type: string; value?: unknown; children?: Node[] };

/** The text of a directive's content, its Markdown marks dropped. */
const textOf = (node: Node): string =>
  typeof node.value === "string"
    ? node.value
    : (node.children ?? []).map(textOf).join("");

/**
 * `:::lorem-quote{author="…"}`: a quote and its author. Its output goes in
 * after sanitisation, so every text is a hast text node, never raw HTML.
 */
const quote: PluginDirectiveRender<{ author: string }> = (node, context) => {
  const text = textOf(node).trim();
  if (text === "")
    context.report({
      code: "lorem/quote-empty",
      severity: "warning",
      message: "a lorem-quote with no text",
      sceneIndex: context.sceneIndex,
    });
  const accent = (context.options as Partial<LoremOptions>).accent ?? "violet";
  const children: ElementContent[] = [
    {
      type: "element",
      tagName: "blockquote",
      properties: {},
      children: [{ type: "text", value: text }],
    },
    {
      type: "element",
      tagName: "figcaption",
      properties: {},
      children: [{ type: "text", value: `— ${context.attributes.author}` }],
    },
  ];
  return {
    type: "element",
    tagName: "figure",
    properties: { dataLoremAccent: accent },
    children,
  } satisfies Element;
};

export default quote;
```

- Every text is a hast text node, never raw HTML: Récit sanitises the output like its own
  directives.
- `context.report` raises a diagnostic whose code starts with the plugin's name.
- `context.options` holds the options of the plugin, as the config passes them.

## 3. Declare it

`src/index.ts` is the Node entry. It declares the directive, its `attributes` schema and its module:

```ts title="src/index.ts"
import { definePlugin } from "recit/plugin";
import * as z from "zod";
import { LoremOptionsSchema } from "./options.js";

export default definePlugin({
  name: "lorem",
  api: 1,
  version: "0.0.0",
  options: LoremOptionsSchema,
  directives: {
    // Static: rendered to HTML at build time, no JavaScript in the page
    "lorem-quote": {
      attributes: z.object({ author: z.string().min(1) }),
      render: () => import("./quote.js"),
      description: "A quote and its author, in the plugin's accent",
    },
    // … the other capabilities of the template
  },
});
```

The `attributes` schema is required: a directive never exists in Markdown only. The schema validates
`:::lorem-quote{author="…"}` in a `.md` and in its JSON twin, and gives its JSON Schema. The render
module is a lazy `import()`, loaded only by a story that uses the directive.

## 4. Test the twin round trip

`src/__tests__/unit/index.spec.ts` checks that a story using the directive survives Markdown → JSON
→ Markdown, and reads the HTML it draws:

```ts title="src/__tests__/unit/index.spec.ts"
const { html } = await expectRoundTrip(
  lorem({ accent: "teal" }),
  `# Lorem

:::lorem-quote{author="Cicero"}
Neque porro quisquam est.
:::
`,
);
expect(html[0]).toContain("<blockquote>Neque porro quisquam est.</blockquote>");
expect(html[0]).toContain("— Cicero");
```

Run the tests, then build the package:

```bash
npm test
npm run build
```

`npm test` calls no network: the AI jobs of the template run against `fakeAiProvider` of
`recit/plugin/testing`. The bible job tests of the template need `@recit/scenario`, a preview
package not published on npm, and are skipped without it, so `npm test` passes without it.
`npm run build` writes `dist/`, the only folder the package ships.

## 5. Use it in a deck

In a deck project (for example one made by
[Write and present your first deck](/documentation/guides/first-deck)), install the plugin from its
folder, then load it in `recit.config.ts`:

```bash
npm install ../recit-plugin-acme
```

```ts title="recit.config.ts"
import lorem from "recit-plugin-acme";
import { defineConfig } from "recit/config";

export default defineConfig({
  plugins: [lorem({ accent: "violet" })],
});
```

Write the directive in a scene of `slides.md`:

```md title="slides.md"
--- id=quote

# A static directive

:::lorem-quote{author="Cicero"}
Neque porro quisquam est qui dolorem ipsum.
:::
```

Preview the deck, then build it:

```bash
npx recit dev slides.md
npx recit build slides.md
```

`recit dev` loads the browser entry of the plugin; `recit build` writes the directive's HTML into
`dist/`, which any static file host can serve.

## 6. Publish it

Before the first release, edit `package.json`:

- remove `"private": true`, which the template sets so that nothing is published by mistake, and set
  `version`;
- keep the `recit-plugin` keyword: that is how people find a plugin on npm;
- keep `files` to `dist` and `README.md`: no source, no test, no fixture;
- keep the two entries of `exports` (`browser` for the client bundle, `default` for Node) and the
  peers on `recit` and `zod`;
- keep the optional peers (`@recit/motion-blocks`, `@recit/scenario`) only for the capabilities your
  plugin keeps: `@recit/scenario`, which the bible jobs load, is a preview package not published on
  npm yet.

Then publish:

```bash
npm publish --access public
```

`--access public` is needed for a scoped name only. To publish without showing your source, or to a
private registry, see [Publishing a plugin](/documentation/plugins/publishing).

## Check

- `npm test` passes, with the round trip of `:::lorem-quote`.
- In the built deck, the `quote` slide shows a figure with « Neque porro quisquam est qui dolorem
  ipsum. » and « — Cicero », and the browser console has no error.
- `npm view recit-plugin-acme keywords` lists `recit-plugin` after the release.

This guide is tested by `e2e/guide-write-plugin.spec.ts`: it compares the blocks above with
`examples/plugin-lorem` and `examples/deck-plugin`, builds the deck with the plugin and opens the
`quote` slide.
