Skip to Content

Plugin guide

Everything that touches the outside world is a plugin. This page shows how to write one, in TypeScript or as a program in any language.

The kinds

KindDoesFirst-party plugins
sourceCollects the changes of a releasegit, github, gitlab, gitea, linear, jira, shortcut, sentry, posthog (feature usage)
modelTalks to an AI providerai-sdk (every API provider), claude-code, codex
rendererMakes imagessatori (templates); screenshots are an optional one
targetSends a bundle somewheregithub-release, gitlab-release, gitea-release, pull-request, webhook, folder, zip, buffer, mixpost, postiz, publer, typefully, app-store, play, ghost, wordpress, devto, hashnode, resend, mailchimp, loops
imagePaints a picture behind an image's words, from a promptopenai; optional, named by outputs.images.backdrop
videoMakes a short clip from still frames, on this machineffmpeg (plugins/video-ffmpeg, needs ffmpeg installed); optional, on with outputs.video.enabled

justshipped plugins lists the ones your CLI has. A config entry under sources or targets picks a plugin by name:

  • a first-party id (plugin: folder),
  • plugin: exec, a program of yours in any language (below),
  • any other name, taken as an npm package installed in your project (below).

Sources and targets are the kinds you can add from the config today. Image and video plugins are first-party only for now: outputs.images.backdrop.plugin and outputs.video.plugin name one by id, and the exec protocol does not carry them yet.

The SDK interfaces

@justshipped/sdk holds the interfaces and the Zod schemas. They are in packages/sdk/src/plugin.ts; the essentials:

interface PluginBase<S extends z.ZodType> {
  id: string;
  kind: "source" | "model" | "renderer" | "target" | "image" | "video";
  version: string;
  /** The studio draws a settings form from this schema's JSON Schema. */
  settings: S;
}

interface Ctx {
  logger: Logger; // debug, info, warn, error
  /** The fetch to use for every request, so tests can inject a recording one. It retries a 429 (any method) or a 503 (GET, HEAD, PUT, DELETE, OPTIONS only) up to three times, honoring `Retry-After` (waits over a minute are not made: the response comes back), and a network error for GET, HEAD, PUT, DELETE and OPTIONS. A streamed body is never sent twice. */
  fetch: typeof fetch;
  /** Reads an env var by name. Values must never be logged or written to a bundle. */
  env(name: string): string | undefined;
  cwd: string;
  signal: AbortSignal;
}

interface SourcePlugin<S> extends PluginBase<S> {
  kind: "source";
  collect(ctx: Ctx, range: { from: string | null; to: string }, settings: z.infer<S>): Promise<CollectedChange[]>;
  // Optional, for an analytics tool: aggregate counts for the events `rules.features` names,
  // over ISO 8601 date-times. Counts only: never a person, a property or a session.
  usage?(
    ctx: Ctx,
    query: { events: readonly string[]; from: string; to: string },
    settings: z.infer<S>,
  ): Promise<{ event: string; events: number; users: number }[]>;
}

interface ModelPlugin<S> extends PluginBase<S> {
  kind: "model";
  complete<T>(
    ctx: Ctx,
    req: { model: string; system: string; prompt: string; schema?: z.ZodType<T> },
    settings: z.infer<S>,
  ): Promise<{ text?: string; object?: T; usage: { input: number; output: number } }>;
}

interface RendererPlugin<S> extends PluginBase<S> {
  kind: "renderer";
  render(
    ctx: Ctx,
    // `backdrop`: a PNG data URL to draw behind the content, read by the core from the bundle.
    job: { template: string; fields: Record<string, string>; width: number; height: number; backdrop?: string },
    settings: z.infer<S>,
  ): Promise<{ files: { path: string; bytes: Uint8Array }[] }>;
}

interface ImagePlugin<S> extends PluginBase<S> {
  kind: "image";
  // The prompt never holds collected text. Ask for the nearest size the provider supports;
  // the template crops the picture to fill. Rebuild a provider error as plain text with no key.
  generate(
    ctx: Ctx,
    req: { prompt: string; width: number; height: number },
    settings: z.infer<S>,
  ): Promise<{
    png: Uint8Array;
    width: number;
    height: number;
    model: string;
    usage: { images: number; input?: number; output?: number };
  }>;
}

interface VideoPlugin<S> extends PluginBase<S> {
  kind: "video";
  // Frames are PNG bytes in order. Nothing in the request is collected or model text. A tool
  // the machine lacks is an error that says how to install it: the run warns and goes on.
  compose(
    ctx: Ctx,
    req: {
      frames: { png: Uint8Array; durationMs: number; motion: "none" | "zoom" }[];
      width: number;
      height: number;
      fps: number;
      transition?: "crossfade" | "cut";
      background?: string; // #rrggbb behind a frame that does not fill the clip
    },
    settings: z.infer<S>,
  ): Promise<{ mp4: Uint8Array; durationMs: number }>;
}

interface TargetPlugin<S> extends PluginBase<S> {
  kind: "target";
  capabilities: { drafts: boolean; approval: boolean; media: "upload" | "url" | "none"; channels: string[] };
  plan(ctx: Ctx, bundle: { dir: string }, settings: z.infer<S>): Promise<{ summary: string; actions: string[] }>;
  publish(
    ctx: Ctx,
    bundle: { dir: string },
    settings: z.infer<S>,
  ): Promise<{ links: { label: string; url: string }[]; ids: Record<string, string> }>;
  /** Optional, for a scheduler: how the posts it made did. Read-only. */
  metrics?(
    ctx: Ctx,
    request: { posts: { channel: string; postId: string }[] },
    settings: z.infer<S>,
  ): Promise<
    {
      channel: string;
      postId: string;
      url?: string;
      at?: string;
      impressions?: number;
      likes?: number;
      reposts?: number;
      replies?: number;
      clicks?: number;
    }[]
  >;
}

defineSourcePlugin, defineModelPlugin, defineRendererPlugin, defineTargetPlugin, defineImagePlugin and defineVideoPlugin are identity helpers that type every callback's settings from your schema.

Rules every plugin follows:

  • Web-standard APIs and node: built-ins only, so it runs on Node 22+ and on Bun.
  • Use ctx.fetch, never the global fetch: it is what tests replace, and it retries a 429 (any method) or a 503 (idempotent methods only) up to three times, waiting as long as Retry-After says (or backing off with jitter when it says nothing). A wait over a minute is not made: the 429 comes back to you, to report or to wait out yourself. A network error is retried only for GET, HEAD, PUT, DELETE and OPTIONS, and a request with a streamed body is never retried. Don't add a retry loop of your own on top for the same cases: the attempts multiply.
  • Secrets by name. A setting ending in _env holds the name of an environment variable; read the value with ctx.env(name) and never log it, return it, or write it anywhere.
  • Collected text is untrusted. Never execute it or build a command or path from it.
  • plan sends nothing that changes anything. It only says what publish would do.
  • publish is idempotent. Running it twice for the same app and version updates what the first run made. Return the ids of what you made: they are saved in published.json and merged into your settings under existing on the next run, when your settings schema has that key. When publish makes something and then fails (a draft created, its content refused), throw PartlyPublishedError from @justshipped/sdk with what it made ({ links, ids }): those ids are recorded in published.json all the same, added to the earlier ones, before the failure is reported, so the next run updates that draft instead of making another.
  • metrics only reads, and only the posts it is asked about. justshipped engagement and the studio ask it about the ids the target recorded in published.json, nothing else; an answer about another post is dropped. Send GET requests only (a GraphQL API's read query is the one exception), never a write. Return numbers only: no reply or comment text, names, followers or audience details. Leave out a post that has no numbers yet. With no key, warn once and return none; an error names the status and the env var, never a key or a response body. When it read some posts and then had to stop (a rate limit), throw PartlyReadError from @justshipped/sdk with what it read: those numbers are kept, and the posts it did not reach are asked about first on the next refresh : pass asked, the exact posts it dealt with (sent a request for, or skipped as never readable), so only those wait their turn. Posts are always asked about in turn: never asked first, then the one asked longest ago, answered or not. For a service with a tight rate limit, set metricsLimit on the plugin to the most posts one call may be asked about; the host sends no more and the rest wait for the next refresh.

A worked target in TypeScript

A target that puts Pebble's changelog on its website through an HTTP API. A target gets the bundle's folder and reads the files it needs: release.json (parse it with ReleaseBundle) and the text files beside it.

// src/index.ts
import { readFile } from "node:fs/promises";
import { join } from "node:path";
import { defineTargetPlugin, ReleaseBundle } from "@justshipped/sdk";
import { z } from "zod";

const Settings = z.object({
  /** Where the notes are posted. */
  url: z.url().default("https://pebble.example.com/api/release-notes"),
  /** The NAME of the variable holding the token, never the token. */
  token_env: z.string().default("PEBBLE_NOTES_TOKEN"),
});

async function load(dir: string) {
  const release = ReleaseBundle.parse(JSON.parse(await readFile(join(dir, "release.json"), "utf8")));
  const changelog = await readFile(join(dir, "changelog.md"), "utf8");
  return { release, changelog };
}

export default defineTargetPlugin({
  id: "pebble-notes",
  kind: "target",
  version: "1.0.0",
  capabilities: { drafts: false, approval: false, media: "none", channels: [] },
  settings: Settings,

  // Says what publish would do. Sends nothing.
  async plan(_ctx, bundle, settings) {
    const { release } = await load(bundle.dir);
    return {
      summary: `Post the ${release.app} ${release.version} changelog to ${new URL(settings.url).origin}`,
      actions: [`PUT changelog.md for ${release.version}`],
    };
  },

  async publish(ctx, bundle, settings) {
    const token = ctx.env(settings.token_env);
    if (!token) throw new Error(`${settings.token_env} is not set`);
    const { release, changelog } = await load(bundle.dir);

    // PUT by version, so a re-run replaces the same entry instead of adding one.
    const response = await ctx.fetch(`${settings.url}/${encodeURIComponent(release.version)}`, {
      method: "PUT",
      headers: { authorization: `Bearer ${token}`, "content-type": "application/json" },
      body: JSON.stringify({ app: release.app, version: release.version, markdown: changelog }),
      signal: ctx.signal,
    });
    if (!response.ok) throw new Error(`The notes endpoint answered ${response.status}`);

    const { id, url } = z.object({ id: z.string(), url: z.url() }).parse(await response.json());
    ctx.logger.info(`pebble-notes: saved ${release.version}`);
    return { links: [{ label: "Release notes", url }], ids: { note: id } };
  },
});

Things to notice:

  • The error names the variable, never its value, and never quotes the response body (it could echo the token).
  • The log line and the plan name the origin only, not a full URL that might carry a credential.
  • The service's answer is validated before it is used.
  • bundle.dir is a copy of the bundle made for the target, without the files for the owner's team under internal/; bundle.source then names the bundle's own folder. Read from dir, and never write inside either. See Versions for each audience.
  • It declares drafts: false because it is not a scheduler. Like the webhook target, it delivers a bundle a person has already reviewed, to a service you run, when that person runs publish or publishes the release. A target that posts to a social scheduler follows stricter rules.

Loading a plugin from npm

Publish the package (ESM, with the plugin as its default export or an export named plugin), install it in the project, and name it in the config:

targets:
  - plugin: justshipped-plugin-pebble-notes
    token_env: PEBBLE_NOTES_TOKEN

This works when justshipped runs on Node or Bun beside a node_modules folder (npx justshipped, or the package installed in the project). The single-file executable has no node_modules: there, use the exec protocol. The name must be a package name, not a path or URL. A plugin from npm runs with the same access as the tool itself.

The exec protocol

An exec plugin is any program. For each call the host starts it once with an argument list (never through a shell), writes one JSON request on stdin, and reads one JSON response from stdout:

{ "protocol": 1, "kind": "target", "method": "publish", "settings": { "path": "notes.md" }, "payload": { "bundle": { "dir": "/work/releases/2.0.0" } } }
{ "ok": true, "result": { "links": [], "ids": { "path": "/work/notes.md" } } }
{ "ok": false, "error": { "message": "settings.path is required", "code": "settings" } }
kindmethodpayloadresult
sourcecollect{ range: { from, to } }a list of changes
modelcomplete{ model, system, prompt, schema? }{ text?, object?, usage: { input, output } }
rendererrender{ job: { template, fields, width, height } }{ files: [{ path, base64 }] }
targetplan{ bundle: { dir } }{ summary, actions }
targetpublish{ bundle: { dir } }{ links, ids }
  • Print nothing but the response on stdout. Lines on stderr go to the Just Shipped log.
  • The program gets a minimal environment: PATH, HOME, locale and temp variables, plus the variables named by its top-level *_env settings and by the entry's env list. Nothing from the environment is put in the request.
  • It is killed when the timeout passes (120 seconds by default) or the run is cancelled.
  • The schemas are exec-request.schema.json and exec-response.schema.json in @justshipped/sdk/schemas.

examples/exec-python-target/ is a complete target in Python with the standard library only. In the config:

targets:
  - plugin: exec
    id: notes-file
    command: [python3, examples/exec-python-target/target.py]
    path: notes.md

command, id, timeout_ms, env, max_output_bytes and capabilities configure the host; every other key is handed to the program as its settings. The same entry under sources runs a source. See Targets.

Testing with a recorded fetch

Tests never touch the network and never need a real key. A plugin takes everything from ctx, so a test hands it a fetch that records each request and answers with a payload saved from the real service:

// src/index.test.ts
import { mkdtemp, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { Ctx } from "@justshipped/sdk";
import { expect, it } from "vitest";
import target from "./index";
// A release.json from one of your own runs, saved beside the test.
import release from "./fixtures/release.json" with { type: "json" };

it("puts the changelog and returns the link", async () => {
  const dir = await mkdtemp(join(tmpdir(), "pebble-notes-"));
  await writeFile(join(dir, "release.json"), JSON.stringify(release));
  await writeFile(join(dir, "changelog.md"), "## New\n\n- Streak levels\n");

  // The recorded exchange: every request is kept, and the reply is one saved from the service.
  const requests: { url: string; init: RequestInit | undefined }[] = [];
  const fetch: typeof globalThis.fetch = async (input, init) => {
    requests.push({ url: String(input), init });
    return Response.json({ id: "note-7", url: "https://pebble.example.com/notes/2.0.0" });
  };
  const ctx: Ctx = {
    fetch,
    env: (name) => (name === "PEBBLE_NOTES_TOKEN" ? "test-token" : undefined),
    logger: { debug() {}, info() {}, warn() {}, error() {} },
    cwd: dir,
    signal: new AbortController().signal,
  };

  const settings = target.settings.parse({});
  const result = await target.publish(ctx, { dir }, settings);

  expect(result.ids).toEqual({ note: "note-7" });
  expect(requests).toHaveLength(1);
  expect(requests[0]?.url).toBe("https://pebble.example.com/api/release-notes/2.0.0");
  expect(requests[0]?.init?.method).toBe("PUT");

  // plan must never send anything.
  await target.plan(ctx, { dir }, settings);
  expect(requests).toHaveLength(1);
});

Worth a test each: a missing token, a non-2xx answer, an answer of the wrong shape, and that no error message or log line holds the token. For a source, record the forge's JSON pages and assert the changes collect returns. examples/pebble/releases/2.0.0/release.json is a ready-made bundle to test a target against.

Schedulers: drafts only

A target that reaches a social scheduler, or any other service that posts to an audience on someone's behalf, may only create drafts or posts that wait for approval. This is the product's central promise: a person reviews everything before it is public.

  • Never call an endpoint that publishes, schedules or queues, and never send a field that does (a publish time, a "post now" flag, a queue slot).
  • Set capabilities.drafts (or approval) to true, and list the channels you support in capabilities.channels.
  • On a re-run, update the draft you made (its id comes back under existing). If a person has since scheduled or published it, leave it alone and warn.
  • Offer no setting that turns any of this off.

First-party schedulers are held to this by a contract test that runs each one against a recording fetch and fails on a request to another origin, a write outside the service's draft endpoints, or a body that schedules or publishes. Write the same test for yours. See Targets and Scheduler keys and ids.

Edit on GitHub

On this page