# JavaScript plugins

> A JavaScript plugin is Site Code packaged as a plugin — the manifest, code scopes, settings, migrations, dependencies, packing the .zip and testing

Source: https://anasaki.live/docs/en/developers/js-plugins

A JavaScript plugin (`&#34;runtime&#34;: &#34;js&#34;`) uses the same API as [Site Code](/docs/en/developers/site-code) but runs as a **separate unit**: it has its own tables, settings, cookies, hooks and routes, and can only use the permissions the administrator approved. The official plugins are written this way (the sources are in `plugins-official/` of the repository).

## Package layout

```text
my-plugin/
├── manifest.json          (required — at the zip root)
├── README.md              (shown in the store — write Thai + English)
├── code/
│   ├── main.ts            (the entry file)
│   ├── lib.ts
│   └── index.d.ts         (optional: types for plugins that import it)
├── migrations/
│   └── 001_create_tables.ts
├── assets/                (publicly served css / js / images / fonts)
└── screenshots/           (images for the store page)
```

Files in `code/` and `migrations/` may be `.ts .js .mjs .json .md`, at most 200 files, 512 KB each, 2 MB in total; the whole package at most 30 MB.

## manifest.json

```json
{
  &#34;id&#34;: &#34;event-booking&#34;,
  &#34;name&#34;: &#34;Event booking&#34;,
  &#34;version&#34;: &#34;1.0.0&#34;,
  &#34;description&#34;: &#34;จองที่นั่งอีเวนต์ / Event seat booking&#34;,
  &#34;author&#34;: &#34;Your name&#34;,
  &#34;icon&#34;: &#34;🎟&#34;,
  &#34;category&#34;: &#34;content&#34;,
  &#34;license&#34;: &#34;MIT&#34;,
  &#34;minCore&#34;: &#34;2.0.4&#34;,
  &#34;runtime&#34;: &#34;js&#34;,
  &#34;permissions&#34;: [&#34;code&#34;, &#34;settings&#34;],
  &#34;settings&#34;: [
    { &#34;key&#34;: &#34;notifyEmail&#34;, &#34;type&#34;: &#34;text&#34;, &#34;label&#34;: { &#34;th&#34;: &#34;อีเมลแจ้งเตือน&#34;, &#34;en&#34;: &#34;Notification email&#34; } }
  ],
  &#34;code&#34;: {
    &#34;entry&#34;: &#34;code/main.ts&#34;,
    &#34;scopes&#34;: [&#34;db&#34;, &#34;routes&#34;, &#34;mail&#34;, &#34;admin-pages&#34;],
    &#34;routes&#34;: [&#34;/booking&#34;],
    &#34;exports&#34;: [&#34;seatsLeft&#34;],
    &#34;hooks&#34;: { &#34;events&#34;: [&#34;event-booking.booked&#34;] }
  },
  &#34;requires&#34;: { &#34;thai&#34;: &#34;^1.0.0&#34; }
}
```

| Field | Notes |
| --- | --- |
| `id` | `^[a-z0-9][a-z0-9-]{2,39}$`, unique — the namespace for everything |
| `version` | semver — every update must be higher |
| `minCore` | The lowest Anasaki Studio version it installs on |
| `permissions` | Must include `code` and the permission of every feature used (`settings`, `bodyEnd`, `webhooks`…) |
| `code.entry` | Required; a `.ts` / `.js` / `.mjs` file in `code/` |
| `code.scopes` | Code permissions — calling an API outside them throws |
| `code.routes` | Public path prefixes `site.route` / `site.page` may use (needs the `routes` scope) — a-z 0-9 `_` `-`, and since CMS 2.2.2 dots too, e.g. `/feed.xml` |
| `code.hosts` | Domains `http.fetch` may call (needs the `http` scope) |
| `code.library` / `code.exports` | A module other plugins can import / functions called with `plugins.call` |
| `code.hooks` | Names of its own filters / events, starting with `.` |
| `requires` / `optionalRequires` | Plugins it needs / works with when present (`^1.2.0`, `~1.2`, `1.x`, `>=1.0.0 <2`) |
| `capabilities` | Plugin permissions administrators can tick per role (since 2.0.6) — see [Plugin capabilities](/docs/en/developers/plugin-capabilities) |

## Code scopes

`db` · `content` · `content-write` · `content-fields` · `post-types` (since 2.0.5) · `mail` · `http` · `webhooks` · `visitor` · `routes` · `jobs` · `admin-pages` · `filters-core` · `middleware` · `head-scripts` — what each one means is in [Plugin permissions](/docs/en/store/plugin-permissions). Ask only for what you use: administrators see every one before installing, and asking for more in a later version switches the plugin off until it is approved again.

## Everything is namespaced

| Thing | In the `event-booking` plugin |
| --- | --- |
| Tables | `schema.create('seats')` → the real table `p_event_booking_seats` (the prefix is added/stripped for you) |
| Settings | `site.settings('notifyEmail')` reads Plugins → Settings first, then Site Code → Secrets & settings (for this plugin), then the manifest's `default` |
| Cookies | `response.setCookie('cart', …)` → the real name starts with `pl__` — a plugin cannot see the system's or other plugins' cookies |
| Actions / collections | `/_a/event-booking:` · `code:event-booking:` |
| Admin pages / jobs | `event-booking:` |
| Its own hooks | `site.emit('event-booking.booked', …)` |

Plugins don't get `db.query` / `schema.raw` and cannot see other units' tables.

## Plugin content types (since 2.0.5)

Plugins with the `post-types` scope (and `&#34;minCore&#34;: &#34;2.0.5&#34;`) can call `site.postType` like Site Code:

```ts
site.postType('docs_doc', {
  label: { th: 'เอกสาร', en: 'Docs' }, icon: '📘',
  slug: 'docs',          // default = the id with _ turned into - (docs-doc)
  public: false,         // the system does not route /docs and /docs/<slug> — the plugin serves the pages
  fields: {
    product: { type: 'select', options: ['studio', 'store'] },
    order: 'number',
  },
});
```

- **The type id** must be `_` and still match `^[a-z][a-z0-9_]{1,19}$` (20 characters in all) — plugin `docs` → `docs_doc` ✔, just `docs` ✘, plugin `event-booking` → `event_booking_seat` ✔. If it is too long or the plugin id starts with a digit, activation fails with a message
- **`public: false`** — the system makes no `/` archive and no `//` pages (default `true`), but post links (`post.url`, the admin's &#34;View&#34; button) are still `//`, so the plugin should handle that path itself (e.g. redirect). `slug` may match a prefix in the plugin's own `code.routes`, but must not clash with system paths, other plugins' paths or other types' slugs
- **Fields declared in the spec's `fields`** are stored under their plain names (`product`, `order`) — usable in `db.posts.list({ type: 'docs_doc', where: { 'meta.order': { gte: 1 } }, orderBy: 'meta.order' })` and returned as `post.meta.product`. A plugin's `site.fields(type, …)` still stores them as `.` (not filterable with `where`), so declare fields in the type's spec. Field specs (including select options) are fixed at registration — a settings change takes effect when the plugin reloads
- Reading/writing the type's posts with `db.posts` needs the `content` / `content-write` scope as usual. Other units (Site Code, other plugins) can read them, but only the owning plugin can write
- The type gets a menu and editor in the admin, appears in the designer's post list options and travels with site export/import — switching off or deleting the plugin keeps the posts (hidden) until it is activated again

> [!NOTE]
> The Plugin Store supports the `post-types` scope since Store 1.2.1 — plugins using it can be uploaded as usual.

## Migrations

```ts
// migrations/001_create_tables.ts
export default migration({
  up(schema) {
    schema.create('seats', (t) => {
      t.id();
      t.string('event_slug', 191).index();
      t.string('email', 191);
      t.timestamps();
    });
  },
  down(schema) { schema.drop('seats'); },
});
```

Needs the `db` scope — migrations run on activation and when an active plugin is upgraded. For changes that may lose data the administrator must tick the confirmation, and the table is backed up first.

## Packing and testing

1. Type-check while writing: copy `anasaki.d.ts` (download it from the Site Code page or with `anasaki-code types`) into the folder
2. Zip the folder (files at the zip root, or inside a single top folder)
    4 
3. On a test site: **Plugins → Upload .zip** → approve the permissions → **Activate** — if the code doesn't build, the system reports file:line and the plugin stays off
4. Read the plugin's logs under **Site Code → Logs** (or `anasaki-code logs --unit event-booking`)
5. Fix, bump `version` and upload again — settings and data stay

> [!NOTE]
> Already have working Site Code? The **Export as plugin** button on the Site Code page makes a `.zip` from the published version, with a `manifest.json` that guesses the scopes, routes, exports and requires — check and fix it before sending it to the store.

Ready: [Signing up and publishing plugins](/docs/en/store/publish-plugin) · a complete example: [Plugin example](/docs/en/developers/plugin-example) · the whole API: [Plugin API](/docs/en/developers/plugin-api)
