# Extension API

Extensions declare their metadata and modules with `defineExtension()` and run `azot build` to generate `manifest.json` before Azot loads them.

## Concepts

An **extension** is one installable package: `package.json`, a generated `manifest.json` and an entry module.

A **module** is one capability, created with a `define*` helper and declared as a key of `defineExtension()`. The key is the module ID. An extension can ship any mix of modules:

| Kind               | Helper                    | Purpose                                                           |
| ------------------ | ------------------------- | ----------------------------------------------------------------- |
| `provider`         | `defineProvider()`        | Finds media on a site (URL, search, browse) and resolves playback |
| `packet-transform` | `definePacketTransform()` | Rewrites encoded packet payloads, such as bitstream fixes         |
| `processor`        | `defineProcessor()`       | Converts one track file, such as `ass` to `srt`                   |
| `muxer`            | `defineMuxer()`           | Writes track files into one container                             |
| `service`          | `defineService()`         | A factory consumed through imported service constructors          |
| `action`           | `defineAction()`          | An operation the user runs on demand                              |
| `listener`         | `defineListener()`        | Reacts to download outcomes, such as sending a notification       |

Packet transforms, processors and muxers are described in [Processing](https://azot.mov/docs/extensions/processing.md).

## Quick start

```ts
import { defineExtension, defineProvider } from "azot";

export default defineExtension({
  title: "Example",
  example: defineProvider({
    shortName: "EX",
    matches: ["https://*.example.com/watch/*"],
    async list({ url }) {
      const html = await (await fetch(url)).text();
      const mediaUrl = html.match(/https:\/\/cdn\.example\.com\/[^"]+\.m3u8/)?.[0];
      if (!mediaUrl) return [];
      return [{ kind: "video", title: "Example video", pageUrl: url, source: { url: mediaUrl } }];
    },
  }),
});
```

Package name and version come from `package.json`, and so does the description unless `defineExtension()` sets one. The package name is the extension's identity.

## `defineExtension()`

The entry module default-exports `defineExtension()`.

| Field         | Description                                                          |
| ------------- | -------------------------------------------------------------------- |
| `title`       | Display name. Defaults to the package name.                          |
| `description` | What the extension does. Defaults to the `package.json` description. |
| `icon`        | Path relative to the package root, or an HTTPS URL.                  |
| `settings`    | Result of [`defineSettings()`](#settings).                           |
| `permissions` | Access to the user's system. See [Permissions](#permissions).        |

`title` and `description` take a plain string or [translations](#localization).

Every other key is a module: its ID mapped to a `define*` result. Declare at least one. Module IDs are stored in user configuration, so keep them stable.

Package name, version and the extensions yours builds on come from `package.json`. See [Services and dependencies](#services-and-dependencies).

## Permissions

Extensions run with the Azot API plus `node:buffer`, `node:crypto` and `node:path`. Anything that touches the user's system needs a permission. Azot lists them before the extension is installed, and asks again when an update adds one:

| Permission    | Unlocks                                                                                 |
| ------------- | --------------------------------------------------------------------------------------- |
| `files:read`  | Reading functions of `node:fs` and `node:fs/promises`, and `open` with read-only flags. |
| `files:write` | Writing functions of `node:fs` and `node:fs/promises`, and `open` with write flags.     |
| `processes`   | `node:child_process`.                                                                   |

Copying a file needs both file permissions; with both, `node:fs` is unrestricted. Processes start with `windowsHide: true` unless the options say otherwise, so console programs open no window on Windows. Requiring a module without its permission fails `azot build`. Declare only what the extension uses.

```ts
export default defineExtension({
  permissions: ["files:read"],
  // modules
});
```

Permissions describe what an extension does. They are not a sandbox: install extensions only from sources you trust.

## Packing

`azot build` bundles the entry, then writes `manifest.json` next to `package.json`. `azot dev` regenerates it after every rebuild, and `azot manifest [entry]` regenerates it without a release build, which is handy with [developer mode](https://azot.mov/docs/extensions/build-extension.md#step-3-load-the-extension). Never write or edit `manifest.json` by hand, and ship it with every release: Azot and the catalog read only `manifest.json` to list extensions, match URLs and render settings, without running extension code.

```json
{
  "title": "Example",
  "modules": {
    "example": {
      "kind": "provider",
      "shortName": "EX",
      "matches": ["https://*.example.com/watch/*"]
    }
  }
}
```

## Compatibility

An extension declares the Azot versions it supports in `engines.azot` of its `package.json`. It is the only version that decides compatibility: the extension API has no version of its own and changes with Azot.

```json
{
  "engines": { "azot": ">=5.0.0" }
}
```

`azot build` writes the oldest Azot the installed `azot` package supports when the field is missing. Raise it when the extension uses something added in a later Azot. Azot refuses an extension whose range is missing or reaches back past its last breaking change, and asks its author for an update.

## Providers

A provider finds media and resolves it for download. It needs at least one discovery method:

| Method                                       | Called for                                                  |
| -------------------------------------------- | ----------------------------------------------------------- |
| `list({ url, options, cursor?, limit? })`    | A URL matched by `matches`                                  |
| `search({ query, cursor?, limit? })`         | A text search. Returns entries and collections              |
| `browse({ collectionId?, cursor?, limit? })` | The provider catalog. Omit `collectionId` for the root      |
| `resolve({ entry, options })`                | Optional. Playback for one entry, right before it downloads |

Provider metadata:

- `shortName` - service tag for output naming templates, such as `NF` or `ATVP`.
- `matches` - URL patterns handled by `list()`. `*.example.com` includes the domain and its subdomains; an omitted path means `/*`. Omit for search or browse only providers.
- `availability` - countries where the site is known to work, `{ within: [...] }` or `{ outside: [...] }`.

### Entries

| Field                                           | Description                                                      |
| ----------------------------------------------- | ---------------------------------------------------------------- |
| `title`                                         | Required, non-empty.                                             |
| `id`                                            | Stable provider ID. Optional.                                    |
| `kind`                                          | `movie`, `episode`, `video`, `audio` or `subtitle`.              |
| `pageUrl`, `artworkUrl`                         | Web page and artwork URLs. Artwork becomes the cover.            |
| `description`, `author`, `year`                 | Catalog metadata.                                                |
| `seasonNumber`, `episodeNumber`, `episodeTitle` | Episode metadata.                                                |
| `source`                                        | `{ url, format?, headers?, expiresAt? }` for a direct media URL. |
| `data`                                          | Serializeable provider data passed back to `resolve()`.          |

```ts
defineProvider<{ videoId: string }>({
  list: ({ url }) => [{ id: url, title: "Video", data: { videoId: new URL(url).pathname } }],
  async resolve({ entry }) {
    const playback = await fetchPlayback(entry.data.videoId);
    return { source: { url: playback.manifestUrl } };
  },
});
```

### `resolve()` and `entry.source`

When a provider implements `resolve()`, Azot calls it right before each entry downloads and ignores `entry.source`. Without `resolve()`, Azot downloads `entry.source`, and fails with `MEDIA_UNAVAILABLE` when the source is absent or its `expiresAt` (Unix epoch milliseconds) has passed. An expired source asks the user to analyze the URL again.

Use `entry.source` for stable direct links. Use `resolve()` for anything that expires, for example episodes of a long season queued for later.

`resolve()` returns a resource valid for one download. It has exactly one of `source` or `input`:

| Field                             | Description                                                                                 |
| --------------------------------- | ------------------------------------------------------------------------------------------- |
| `source`                          | `{ url, format?, headers?, expiresAt? }`.                                                   |
| `input`                           | A custom `Input` from `azot`, for separate tracks or custom sources.                        |
| `metadata`                        | Catalog fields that refresh the entry, such as a fresh title. Applied before output naming. |
| `tags`, `chapters`, `attachments` | Output metadata for the muxer. See [Processing](https://azot.mov/docs/extensions/processing.md#output-metadata).                |
| `dispose()`                       | Awaited once after success, failure or cancellation.                                        |

```ts
import { HLS_FORMATS, Input, UrlSource } from "azot";

const resource = {
  input: new Input({
    formats: HLS_FORMATS,
    source: new UrlSource(manifestUrl, { requestInit: { headers: { referer: pageUrl } } }),
  }),
};
```

When a service serves one video as several manifests or files, for example one per codec or quality, return all of them as one input with `Input.merge()`. Azot lists their tracks together, so the user picks across them, and drops the tracks they share. Return every variant whatever `options` say: Azot applies the user's preferences. Merge only manifests or only files.

```ts
const resource = {
  input: Input.merge(
    [avcManifestUrl, hevcManifestUrl].map((url) => new Input({ source: new UrlSource(url) })),
  ),
};
```

`options` holds the user's download preferences relevant to providers: `videoQuality`, `videoCodecs`, `videoRange`, `videoBitrate`, `videoDimension`, `audioCodecs`, `audioChannels`, `audioBitrate`, `subtitleLanguages`, `languages`, `skipVideo`, `skipAudio`, `skipSubtitles` and `episodes`.

## Authentication

Declare sign-in on one provider with `auth`.

```ts
import { defineProvider, prompt } from "azot";

defineProvider({
  matches: ["https://example.com/*"],
  list: ({ url }) => listEntries(url),
  auth: {
    methods: ["interactive", "token", "cookies"],
    async getState() {
      const response = await fetch("https://example.com/api/me");
      if (response.status === 401) return { authenticated: false };
      if (!response.ok) throw new Error("Could not verify the session");
      const me = await response.json();
      return { authenticated: true, user: me.name };
    },
    async login(request) {
      if (request.method === "token") return saveToken(request.token);
      if (request.method === "cookies") return; // Imported into cookieStore; getState() verifies them.
      const { email, password } = await prompt("Sign in to Example", {
        form: { email: { type: "text" }, password: { type: "password" } },
      });
      await signIn(email, password);
    },
    async logout() {
      localStorage.removeItem("token");
      await cookieStore.delete();
    },
  },
});
```

- `methods` is optional and defaults to `["interactive"]`: the desktop sign-in button and the CLI without credential flags both call `login({ method: "interactive" })`. List methods only to also accept credentials from the CLI, as above. Keep `interactive` in the list to support the desktop button.
- `login()` receives only the listed methods, and its request type narrows to them: above, `request.method` is `interactive`, `token` or `cookies`. Azot refuses the others. The list is written to the manifest.
- A login succeeds only when `getState()` returns `authenticated: true` afterwards. `login()` resolving proves nothing.
- `getState()` returns `{ authenticated: false }` for a signed-out user and throws for transport failures, which are not a signed-out state.
- `auth` without `login()` may implement only `getState()` and `logout()`, to show account state without sign-in.

CLI credential flags:

```sh
azot login example --username=user --password=pass --otp=123456
azot login example --token=TOKEN
azot login example --cookie-file=cookies.txt
azot login example --cookie-header="session=abc" --cookie-url=https://example.com
```

For sign-in through a website, use the [Browser API](https://azot.mov/docs/extensions/browser.md#interactive-login).

## Settings

`defineSettings()` declares persistent settings shared by all modules of the extension. Pass the result to `defineExtension({ settings })` so packing writes the schema, and read values from it inside modules.

```ts
import { defineExtension, defineMuxer, defineSettings } from "azot";

const settings = defineSettings({
  executable: { type: "string", title: "FFmpeg executable", default: "ffmpeg" },
  preset: { type: "string", enum: ["fast", "slow"], default: "fast" },
  apiKey: { type: "string", title: "API key", required: true },
  threads: { type: "number", min: 1, max: 64 },
});

export default defineExtension({
  settings,
  ffmpeg: defineMuxer({
    containers: ["mkv"],
    async mux(request) {
      const { executable, preset } = settings; // Read once per operation.
      await runFfmpeg(executable, preset, request);
    },
  }),
});
```

| Type          | Fields                                                         |
| ------------- | -------------------------------------------------------------- |
| `string`      | `title`, `description`, `default`, `enum`, `required`          |
| `number`      | `title`, `description`, `default`, `min`, `max`, `required`    |
| `boolean`     | `title`, `description`, `default` (`false` when omitted)       |
| `file`        | `title`, `description`, `formats`, `required`                  |
| `folder`      | `title`, `description`, `required`                             |
| `output-file` | `title`, `description`, `suggestedName`, `formats`, `required` |

`enum` lists the values a dropdown offers, and the setting stores the chosen value. A plain string shows as written. To show a label instead, give an option with a `value` and a `title`; the title can be translated or reworded without changing what is saved:

```ts
const settings = defineSettings({
  source: {
    type: "string",
    enum: [
      { value: "remote", title: messages.remote },
      { value: "credentials", title: messages.credentials },
    ],
    default: "remote",
  },
});
```

`file`, `folder` and `output-file` open the system picker, and their values are absolute paths. An `output-file` is a file to write, so it may not exist yet; the save dialog starts with `suggestedName`. `formats` limits the picker and the accepted values, such as `["srt", "vtt"]`.

Every field takes `visibleWhen`, which shows it only while fields declared before it have the listed values. A hidden field has no value and is never required, so its type includes `undefined`:

```ts
const settings = defineSettings({
  mode: { type: "string", enum: ["keep", "export"], default: "keep" },
  target: {
    type: "output-file",
    suggestedName: "subtitles.srt",
    formats: ["srt"],
    required: true,
    visibleWhen: { mode: "export" }, // Or one of several: { mode: ["export", "copy"] }.
  },
});
```

## Localization

Azot shows extension text in the language of the app. Translations live in code, next to the text they translate.

`defineMessages()` takes one catalog per language, keyed by [BCP 47 tags](https://www.w3.org/International/articles/language-tags/) such as `en`, `ru` or `pt-BR`. English is required and names every message. Other languages may leave messages out, which then show in English:

```ts
// messages.ts
import { defineMessages } from "azot";

export const messages = defineMessages({
  en: {
    title: "Channel One",
    description: "Shows, news and the live broadcast",
    live: "Live",
    signIn: "Open {url} and enter the code {code}",
  },
  ru: {
    title: "Первый канал",
    description: "Передачи, новости и прямой эфир",
    live: "Прямой эфир",
    signIn: "Откройте {url} и введите код {code}",
  },
});
```

Pass messages as they are to metadata: extension and module `title` and `description`, labels of [settings](#settings) and action `args` with their `enum` titles, and action `confirmation`. Packing writes every translation into `manifest.json`, and Azot picks one without running the extension, so a change of language applies at once.

```ts
import { confirm, defineExtension, defineProvider, t } from "azot";
import { messages } from "./messages.ts";

export default defineExtension({
  title: messages.title,
  description: messages.description,
  channel: defineProvider({
    async list({ url }) {
      const code = await requestCode();
      if (!(await confirm(t(messages.signIn, { url: "https://example.com/tv", code })))) return [];
      return [{ kind: "video", title: t(messages.live), pageUrl: url, source: await getStream() }];
    },
  }),
});
```

Text produced while the extension runs goes through `t()`: dialogs, error messages, collection titles. Call it when the text is shown, never at module top level: packing has no language and refuses it, and the text would not follow a change of language anyway.

- `{name}` is a placeholder that `t()` fills from its parameters. TypeScript requires every placeholder the English text names, and every translation must use the same ones.
- Azot picks the language of the app (`navigator.language`): the same tag, then the tag without its region (`pt-BR` → `pt`), then another region of the language, else English.
- `t()` also takes inline translations, such as `t({ en: "Movies", ru: "Фильмы" })`, and any metadata field takes them directly.
- Translators can work on JSON files: `import ru from "./locales/ru.json"` and pass `ru` to `defineMessages()`. Parameters of JSON messages are not type-checked.

In tests, `setLocale()` from `azot/vitest` switches the language until the next test; tests run in English otherwise:

```ts
import { invoke, setLocale } from "azot/vitest";

test("titles collections in Russian", async () => {
  setLocale("ru");
  expect(await invoke(() => extension.channel.browse({}))).toContainEqual({
    kind: "collection",
    collection: { id: "movies", title: "Фильмы" },
  });
});
```

## Services and dependencies

An extension exposes a service factory. Consumers import a typed constructor from its package and create independent instances with `new`. Service identity and compatibility come from the extension package name and semver version.

```ts
// @example/azot-catalog/src/index.ts
import { defineExtension, defineService } from "azot";

export default defineExtension({
  Catalog: defineService({
    create(scope) {
      let sessionId = "";
      scope.onDispose(() => closeSession(sessionId));
      return {
        configure(id: string) {
          sessionId = id;
        },
        lookup(id: string) {
          return fetchItem(sessionId, id);
        },
      };
    },
  }),
});
```

`create()` may return a plain object or a class instance. Allocate instance state inside the factory. Module-level state is shared. The factory may initialize asynchronously; it runs once on the handle's first method call.

Public service methods must be required. `azot build` rejects optional or nullable callables and methods named `then`.

`azot build` emits constructor declarations inferred from your source next to the bundle, such as `dist/index.client.d.cts` for a `src/index.ts` entry. Point the package's `types` at that file, or the `types` condition of the root export when you use `exports`, and publish it with `dist/index.d.cts`. `azot build` never edits `package.json`; it stops and lists the fields to change when they do not publish the declarations. Service module names become named exports, so use JavaScript identifiers such as `Catalog`. Build service packages before publishing them. A standalone `export default defineService({ create() { /* ... */ } })` publishes a constructor named `Service`.

```json
{
  "name": "@example/azot-catalog",
  "version": "1.2.0",
  "main": "./dist/index.cjs",
  "types": "./dist/index.client.d.cts",
  "files": ["dist", "manifest.json"]
}
```

Declare the extensions yours builds on in `peerDependencies`, because Azot provides them instead of your bundle. The range is the version requirement. Install the same package as a development dependency for its declarations, from npm or from a tarball or Git URL such as a GitHub or GitLab release asset. Azot keeps peer dependencies external to the consumer bundle and supplies their constructor exports in the consumer's VM, even when an optional service extension is absent. Importing a constructor never imports the provider implementation.

```json
{
  "devDependencies": {
    "@example/azot-catalog": "https://github.com/example/azot-catalog/releases/download/v1.2.0/azot-catalog-1.2.0.tgz"
  },
  "peerDependencies": {
    "@example/azot-catalog": "^1.2.0"
  }
}
```

```ts
import { defineExtension, defineProvider } from "azot";
import { Catalog } from "@example/azot-catalog";

export default defineExtension({
  site: defineProvider({
    async search({ query }) {
      await using catalog = new Catalog();
      await catalog.configure("session-a");
      const item = await catalog.lookup(query);
      return [{ kind: "entry", entry: { id: query, title: item.title } }];
    },
  }),
});
```

Construction is synchronous. Every method call returns a promise, including methods implemented synchronously. Await calls that depend on preceding state changes. Methods run in the provider's context with its settings, storage, and dependency bindings, while inheriting the current operation's cancellation. Cancellation stops that call's wait; it does not cancel instance initialization or other calls. Public handles expose methods, not implementation fields.

`await using` disposes an instance when the scope ends. You can also call `await catalog[Symbol.asyncDispose]()` explicitly. Otherwise the host disposes it when either the consumer or provider unloads. Register cleanup with `scope.onDispose()`; it runs in the provider's context with bounded cancellation. Handles cannot be reused after disposal.

Every peer dependency other than `azot` must be an Azot extension with a semver range, which covers its public API; `azot build` rejects anything else. A missing or incompatible required dependency makes all operations of the consumer fail until installed. Mark it optional in `peerDependenciesMeta` to allow unrelated operations to continue; the constructor still imports, but method calls report `SERVICE_UNAVAILABLE` or `SERVICE_INCOMPATIBLE`.

```json
{
  "peerDependenciesMeta": {
    "@example/azot-catalog": { "optional": true }
  }
}
```

Calling a service of another extension requires Azot Pro, unless that extension is built into Azot. Extensions with services install on every plan, and an extension always uses its own services. On Free, calls to a service of an extension that is not built in reject with `EXTENSION_SERVICES_NOT_ALLOWED`.

## Actions

Actions are operations the user runs on demand.

```ts
import { defineAction } from "azot";

defineAction({
  title: "Export subtitles",
  selection: { kind: "files", accepts: { mediaKind: "subtitle" }, count: { max: 10 } },
  args: {
    format: { type: "string", enum: ["srt", "vtt"], default: "srt" },
    folder: { type: "folder", title: "Save to", required: true },
  },
  confirmation: "Export subtitles of the selected files?",
  async run({ args, selection, invocationId, onProgress }) {
    for (const [index, file] of selection.entries()) {
      await exportSubtitles(file.path, args.folder, args.format, invocationId);
      onProgress?.({ completed: index + 1, total: selection.length, unit: "items" });
    }
    return { message: `Exported ${selection.length} file(s)` };
  },
});
```

`selection` says what the action runs on, and context menus offer it only where it fits. Omit it for actions run from the extension page.

| Field     | Meaning                                                                                                                       |
| --------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `kind`    | `entries` for one discovered entry, `files` for files downloads delivered.                                                    |
| `accepts` | `files` only. A file pattern (`mediaKind`, `formats`); files that do not match are left out of the selection.                 |
| `count`   | `files` only. `{ min?, max? }`, inclusive. The action is offered when the number of accepted files fits; `min` defaults to 1. |

The request carries `onProgress`, reported like [processing progress](https://azot.mov/docs/extensions/processing.md), and `invocationId`. Retrying a failed run passes the same `invocationId` again, so an action with side effects outside Azot, such as an upload, can use it as an idempotency key.

## Listeners

Listeners react to download outcomes: chat notifications, media library refreshes, cloud uploads, marking an episode as watched. Implement a handler for each event you need; its parameter is typed for that event.

```ts
import { defineListener } from "azot";

defineListener({
  async onDownloadCompleted(event) {
    await sendMessage(`Downloaded ${event.entry.title}`, {
      idempotencyKey: event.deliveryId,
      attachments: event.files.map((file) => file.path),
    });
  },
  async onDownloadFailed(event) {
    await sendMessage(`Failed to download ${event.entry.title}: ${event.error.message}`, {
      idempotencyKey: event.deliveryId,
    });
  },
});
```

## Errors

Throw `ExtensionError` for failures Azot can act on. A plain `Error` is always accepted, but unclassified failures never trigger automatic sign-in recovery or retries.

```ts
import { ExtensionError } from "azot";

throw new ExtensionError({
  code: "RATE_LIMITED",
  message: "Try again later",
  retryAfterMs: 10_000,
});
```

| Code                    | Meaning                                                                            |
| ----------------------- | ---------------------------------------------------------------------------------- |
| `AUTH_REQUIRED`         | The user must sign in.                                                             |
| `REGION_BLOCKED`        | Not available in the user's region.                                                |
| `SUBSCRIPTION_REQUIRED` | The account lacks the required subscription.                                       |
| `UNSUPPORTED_INPUT`     | The module cannot handle this input. From a muxer, triggers the built-in fallback. |
| `MEDIA_UNAVAILABLE`     | The media was removed, is not released yet, or has no source.                      |
| `RATE_LIMITED`          | Too many requests. Set `retryAfterMs` when known.                                  |
| `SERVICE_UNAVAILABLE`   | No implementation of a service is available.                                       |
| `SERVICE_INCOMPATIBLE`  | The installed extension package does not satisfy the `peerDependencies` range.     |
| `OUTPUT_INVALID`        | A processor or muxer output failed validation.                                     |
| `INTERACTION_REQUIRED`  | The operation needs user input that is not allowed here.                           |

`details` accepts JSON data and `cause` any value.

When `list()` throws `AUTH_REQUIRED` for a link the user submitted, Azot asks them to sign in with the provider's `auth.login()` and lists once more. Throw it only when signing in would fix the failure; a signed-in user without access gets `SUBSCRIPTION_REQUIRED`.

See also: [Globals](https://azot.mov/docs/extensions/globals.md), [Feedback](https://azot.mov/docs/extensions/feedback.md), [Browser API](https://azot.mov/docs/extensions/browser.md), [Helpers](https://azot.mov/docs/extensions/helpers.md).
