Samples

Four small add-ons, each runnable and tested in the repository. The first three serve the same two public-domain LibriVox recordings with one catalog, meta and streams; pick the one closest to your stack and replace the data with your own source.

SampleNeedsSource
Hono on WorkersNode 20+, @lelap/sdk, Hono, Wranglerservices/template
Plain NodeNode 20+, nothing to installexamples/node-addon
PythonPython 3.9+, nothing to installexamples/python-addon
Hard-coded catalogsNode 20+, @lelap/sdk, Wranglerexamples/seasonal-catalogs

Hono on Workers

The template: @lelap/sdk does the routing, CORS, caching headers and checks every answer against the protocol, so the code is the manifest and three handlers. It runs on Cloudflare Workers, and the same addon.fetch runs on Deno, Bun and Node. The SDK guide explains each piece; src/books.ts holds the data.

services/template/src/addon.ts
import { createAddon, type Manifest, type MetaPreview } from '@lelap/sdk';

import { BOOKS } from './books';

export const manifest: Manifest = {
  // Use a reverse-DNS ID of a domain you control.
  id: 'org.example.template',
  version: '1.0.0',
  protocol: 1,
  name: 'Template',
  description: 'A starting point for your own Lelap add-on.',
  types: ['audiobook'],
  resources: ['catalog', 'meta', 'stream'],
  idPrefixes: ['template:'],
  catalogs: [{ type: 'audiobook', id: 'books', name: 'Template books' }],
};

const preview = ({ id, type, name, author, cover, durationMs }: MetaPreview): MetaPreview => ({
  id,
  type,
  name,
  ...(author ? { author } : {}),
  ...(cover ? { cover } : {}),
  ...(durationMs ? { durationMs } : {}),
});

export const addon = createAddon({
  manifest,
  catalog: () => ({ metas: BOOKS.map((book) => preview(book.meta)), cacheMaxAge: 3600 }),
  meta: ({ id }) => {
    const book = BOOKS.find((b) => b.meta.id === id);
    return book ? { meta: book.meta, cacheMaxAge: 86400 } : null;
  },
  stream: ({ id }) => ({
    streams: BOOKS.filter((b) => b.meta.id === id).map((b) => b.stream),
    cacheMaxAge: 86400,
  }),
});
services/template/src/index.ts
import { Hono } from 'hono';

import { addon } from './addon';

// Hono leaves room for your own routes, such as a `/configure` page.
const app = new Hono();
// People open the base URL in a browser; the manifest is what they came for.
app.get('/', (c) => c.redirect('/manifest.json'));
app.all('*', (c) => addon.fetch(c.req.raw));

export default app;
Terminal
cd services/template
pnpm dev             # http://localhost:8787/manifest.json
pnpm test

In the repository the template uses the SDK from the workspace. Copy the folder out to start your own add-on, then install the SDK from npm:

Terminal
npm pkg delete dependencies.@lelap/sdk
npm install @lelap/sdk

Plain Node

The protocol by hand with node:http: no framework, no SDK, no dependencies. route() turns a path into a status and a JSON body, and the server adds the headers. Read it to see everything an add-on has to get right; it is also the shape to follow in any other language.

examples/node-addon/addon.mjs
// A Lelap add-on with nothing but Node's standard library: one catalog, meta and streams.
import { createServer } from 'node:http';

export const manifest = {
  // Use a reverse-DNS ID of a domain you control.
  id: 'org.example.node',
  version: '1.0.0',
  protocol: 1,
  name: 'Node example',
  description: 'Two public-domain LibriVox recordings, served without a framework.',
  types: ['audiobook'],
  resources: ['catalog', 'meta', 'stream'],
  idPrefixes: ['example:'],
  catalogs: [{ type: 'audiobook', id: 'classics', name: 'Classics', extra: [{ name: 'skip' }] }],
};

// Replace these with your own source. Only serve audio you are allowed to share.
const archive = (item, file) => `https://archive.org/download/${item}/${file}`;

const BOOKS = [
  {
    meta: {
      id: 'example:raven',
      type: 'audiobook',
      name: 'The Raven',
      author: 'Edgar Allan Poe',
      cover: 'https://archive.org/services/img/raven',
      year: 1845,
      durationMs: 570_000,
      description: 'A grieving narrator is visited at midnight by a talking raven.',
      language: 'en',
    },
    streams: [
      {
        sourceKey: 'example:raven:64kb',
        name: 'Node example',
        title: 'LibriVox recording',
        url: archive('raven', 'raven_poe_64kb.mp3'),
        durationMs: 570_000,
        mime: 'audio/mpeg',
        downloadable: true,
      },
    ],
  },
  {
    meta: {
      id: 'example:christmas-carol',
      type: 'audiobook',
      name: 'A Christmas Carol',
      author: 'Charles Dickens',
      cover: 'https://archive.org/services/img/A_Christmas_Carol',
      year: 1843,
      durationMs: 11_669_000,
      description: 'Ebenezer Scrooge is visited by three spirits on Christmas Eve.',
      language: 'en',
    },
    streams: [
      {
        sourceKey: 'example:christmas-carol:64kb',
        name: 'Node example',
        title: 'LibriVox recording',
        mime: 'audio/mpeg',
        downloadable: true,
        parts: [
          [
            'Preface and Stave 1',
            'A_Christmas_Carol_Preface_and_Stave_1_Dickens_64kb.mp3',
            2_680_000,
          ],
          ['Stave 2', 'A_Christmas_Carol_Stave_2_Dickens_64kb.mp3', 2_660_000],
          ['Stave 3', 'A_Christmas_Carol_Stave_3_Dickens_64kb.mp3', 2_674_000],
          ['Stave 4', 'A_Christmas_Carol_Stave_4_Dickens_64kb.mp3', 2_529_000],
          ['Stave 5', 'A_Christmas_Carol_Stave_5_Dickens_64kb.mp3', 1_126_000],
        ].map(([title, file, durationMs]) => ({
          title,
          url: archive('A_Christmas_Carol', file),
          durationMs,
        })),
      },
    ],
  },
];

const PAGE = 50;
const DAY = 86_400;

const preview = ({ id, type, name, author, cover, year }) => ({
  id,
  type,
  name,
  author,
  cover,
  year,
});

/** Answers one request: `{ status, body, maxAge? }`. Pure, so tests need no server. */
export function route(pathname) {
  if (pathname === '/manifest.json') return { status: 200, body: manifest, maxAge: 3600 };
  // /{resource}/{type}/{id}.json or /catalog/{type}/{id}/{extra}.json, IDs percent-encoded.
  const match = /^\/(catalog|meta|stream)\/([^/]+)\/([^/]+?)(?:\/([^/]*))?\.json$/.exec(pathname);
  if (!match) return notFound();
  const [, resource, type, rawId, rawExtra] = match;
  let id;
  try {
    id = decodeURIComponent(rawId);
  } catch {
    return notFound();
  }
  if (type !== 'audiobook') return notFound();

  if (resource === 'catalog') {
    if (id !== 'classics') return notFound('Unknown catalog');
    // Extras are a query string in a path segment, so URLSearchParams decodes them (`+` too).
    const skip = Number(new URLSearchParams(rawExtra ?? '').get('skip') ?? 0);
    if (!Number.isInteger(skip) || skip < 0)
      return { status: 400, body: { error: 'skip must be a whole number' } };
    const metas = BOOKS.slice(skip, skip + PAGE).map((book) => preview(book.meta));
    return { status: 200, body: { metas, cacheMaxAge: 6 * 3600 }, maxAge: 6 * 3600 };
  }
  if (rawExtra !== undefined) return notFound();

  const book = BOOKS.find((b) => b.meta.id === id);
  if (resource === 'meta') {
    if (!book) return notFound();
    return { status: 200, body: { meta: book.meta, cacheMaxAge: DAY }, maxAge: DAY };
  }
  // No streams is an empty list, not an error.
  return { status: 200, body: { streams: book?.streams ?? [], cacheMaxAge: DAY }, maxAge: DAY };
}

const notFound = (error = 'Not found') => ({ status: 404, body: { error } });

// Every response, errors included, needs CORS: the web app calls add-ons from the browser.
const CORS = {
  'Access-Control-Allow-Origin': '*',
  'Access-Control-Allow-Methods': 'GET, OPTIONS',
  'Access-Control-Allow-Headers': '*',
};

export function createAddonServer() {
  return createServer((req, res) => {
    if (req.method === 'OPTIONS') {
      res.writeHead(204, CORS).end();
      return;
    }
    const answer =
      req.method === 'GET' || req.method === 'HEAD'
        ? route(new URL(req.url ?? '/', 'http://addon').pathname)
        : { status: 405, body: { error: 'Method not allowed' } };
    const headers = { ...CORS, 'Content-Type': 'application/json; charset=utf-8' };
    if (answer.maxAge !== undefined) headers['Cache-Control'] = `public, max-age=${answer.maxAge}`;
    res.writeHead(answer.status, headers);
    res.end(req.method === 'HEAD' ? undefined : JSON.stringify(answer.body));
  });
}
examples/node-addon/server.mjs
import { createAddonServer } from './addon.mjs';

const port = Number(process.env.PORT ?? 8787);
createAddonServer().listen(port, () => {
  console.log(`Add-on running: http://localhost:${port}/manifest.json`);
});
Terminal
cd examples/node-addon
npm start            # http://localhost:8787/manifest.json
npm test             # node:test, no dependencies

Python

The same add-on with Python’s standard library: http.server for serving and urllib.parse for IDs and extras. Nothing to install. For more than a handful of listeners, keep route() and serve it from the WSGI or ASGI framework you already use.

examples/python-addon/addon.py
"""A Lelap add-on on Python's standard library: one catalog, meta and streams.

Run it with `python3 addon.py` and open http://localhost:8787/manifest.json.
"""

import json
import os
import re
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, unquote, urlsplit

MANIFEST = {
    # Use a reverse-DNS ID of a domain you control.
    "id": "org.example.python",
    "version": "1.0.0",
    "protocol": 1,
    "name": "Python example",
    "description": "Two public-domain LibriVox recordings, served by the standard library.",
    "types": ["audiobook"],
    "resources": ["catalog", "meta", "stream"],
    "idPrefixes": ["example:"],
    "catalogs": [
        {"type": "audiobook", "id": "classics", "name": "Classics", "extra": [{"name": "skip"}]}
    ],
}


def archive(item, file):
    return "https://archive.org/download/%s/%s" % (item, file)


# Replace these with your own source. Only serve audio you are allowed to share.
CAROL_PARTS = [
    ("Preface and Stave 1", "A_Christmas_Carol_Preface_and_Stave_1_Dickens_64kb.mp3", 2680000),
    ("Stave 2", "A_Christmas_Carol_Stave_2_Dickens_64kb.mp3", 2660000),
    ("Stave 3", "A_Christmas_Carol_Stave_3_Dickens_64kb.mp3", 2674000),
    ("Stave 4", "A_Christmas_Carol_Stave_4_Dickens_64kb.mp3", 2529000),
    ("Stave 5", "A_Christmas_Carol_Stave_5_Dickens_64kb.mp3", 1126000),
]

BOOKS = [
    {
        "meta": {
            "id": "example:raven",
            "type": "audiobook",
            "name": "The Raven",
            "author": "Edgar Allan Poe",
            "cover": "https://archive.org/services/img/raven",
            "year": 1845,
            "durationMs": 570000,
            "description": "A grieving narrator is visited at midnight by a talking raven.",
            "language": "en",
        },
        "streams": [
            {
                "sourceKey": "example:raven:64kb",
                "name": "Python example",
                "title": "LibriVox recording",
                "url": archive("raven", "raven_poe_64kb.mp3"),
                "durationMs": 570000,
                "mime": "audio/mpeg",
                "downloadable": True,
            }
        ],
    },
    {
        "meta": {
            "id": "example:christmas-carol",
            "type": "audiobook",
            "name": "A Christmas Carol",
            "author": "Charles Dickens",
            "cover": "https://archive.org/services/img/A_Christmas_Carol",
            "year": 1843,
            "durationMs": 11669000,
            "description": "Ebenezer Scrooge is visited by three spirits on Christmas Eve.",
            "language": "en",
        },
        "streams": [
            {
                "sourceKey": "example:christmas-carol:64kb",
                "name": "Python example",
                "title": "LibriVox recording",
                "mime": "audio/mpeg",
                "downloadable": True,
                "parts": [
                    {
                        "title": title,
                        "url": archive("A_Christmas_Carol", file),
                        "durationMs": duration,
                    }
                    for title, file, duration in CAROL_PARTS
                ],
            }
        ],
    },
]

PAGE = 50
DAY = 86400
PREVIEW_FIELDS = ("id", "type", "name", "author", "cover", "year")

# /{resource}/{type}/{id}.json or /catalog/{type}/{id}/{extra}.json, with IDs percent-encoded.
ROUTE = re.compile(r"^/(catalog|meta|stream)/([^/]+)/([^/]+?)(?:/([^/]*))?\.json$")


def not_found(error="Not found"):
    return 404, {"error": error}, None


def route(path):
    """Answers one request path with (status, body, max_age). Pure, so tests need no server."""
    if path == "/manifest.json":
        return 200, MANIFEST, 3600
    match = ROUTE.match(path)
    if not match:
        return not_found()
    resource, kind, raw_id, raw_extra = match.groups()
    # Split first, then decode: a `/` inside an ID arrives as %2F.
    item_id = unquote(raw_id)
    if kind != "audiobook":
        return not_found()

    if resource == "catalog":
        if item_id != "classics":
            return not_found("Unknown catalog")
        # Extras are a query string in a path segment; parse_qs decodes `+` as a space too.
        extra = parse_qs(raw_extra or "")
        skip = extra.get("skip", ["0"])[0]
        if not skip.isdigit():
            return 400, {"error": "skip must be a whole number"}, None
        start = int(skip)
        metas = [
            {key: book["meta"][key] for key in PREVIEW_FIELDS if key in book["meta"]}
            for book in BOOKS[start : start + PAGE]
        ]
        return 200, {"metas": metas, "cacheMaxAge": 6 * 3600}, 6 * 3600
    if raw_extra is not None:
        return not_found()

    book = next((b for b in BOOKS if b["meta"]["id"] == item_id), None)
    if resource == "meta":
        if book is None:
            return not_found()
        return 200, {"meta": book["meta"], "cacheMaxAge": DAY}, DAY
    # No streams is an empty list, not an error.
    streams = book["streams"] if book else []
    return 200, {"streams": streams, "cacheMaxAge": DAY}, DAY


# Every response, errors included, needs CORS: the web app calls add-ons from the browser.
CORS = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "GET, OPTIONS",
    "Access-Control-Allow-Headers": "*",
}


class AddonHandler(BaseHTTPRequestHandler):
    def do_OPTIONS(self):
        self.send_response(204)
        for name, value in CORS.items():
            self.send_header(name, value)
        self.end_headers()

    def do_GET(self):
        self.answer(*route(urlsplit(self.path).path), send_body=True)

    def do_HEAD(self):
        self.answer(*route(urlsplit(self.path).path), send_body=False)

    def do_POST(self):
        self.answer(405, {"error": "Method not allowed"}, None, send_body=True)

    do_PUT = do_DELETE = do_PATCH = do_POST

    def answer(self, status, body, max_age, send_body):
        data = json.dumps(body).encode("utf-8")
        self.send_response(status)
        for name, value in CORS.items():
            self.send_header(name, value)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(data)))
        if max_age is not None:
            self.send_header("Cache-Control", "public, max-age=%d" % max_age)
        self.end_headers()
        if send_body:
            self.wfile.write(data)


def create_server(port=8787, host=""):
    return ThreadingHTTPServer((host, port), AddonHandler)


if __name__ == "__main__":
    port = int(os.environ.get("PORT", "8787"))
    print("Add-on running: http://localhost:%d/manifest.json" % port)
    create_server(port).serve_forever()
Terminal
cd examples/python-addon
python3 addon.py     # http://localhost:8787/manifest.json
python3 -m unittest

Hard-coded catalogs

A catalog doesn’t have to come from a database or an API. This add-on serves two fixed lists from a JSON file, with no code beyond the SDK:

  • Christmas: A Christmas Carol (Charles Dickens), 'Twas the Night Before Christmas (Clement C. Moore), The Gift of the Magi (O. Henry), The Chimes (Charles Dickens), The Cricket on the Hearth (Charles Dickens), Old Christmas (Washington Irving).
  • Autumn: The Legend of Sleepy Hollow (Washington Irving), Ode to Autumn (John Keats), The Turn of the Screw (Henry James), Dracula (Bram Stoker), Frankenstein (Mary Wollstonecraft Shelley).

It only answers catalog. Every book has a librivox: ID, the archive.org identifier of a LibriVox recording, so the LibriVox add-on that Lelap ships with answers its meta and streams. Listeners get two new rows on Home, and the audio comes straight from archive.org.

examples/seasonal-catalogs/src/catalogs.json (excerpt)
{
  "catalogs": [
    {
      "id": "christmas",
      "name": "Christmas",
      "metas": [
        {
          "id": "librivox:christmascarol_librivox",
          "type": "audiobook",
          "name": "A Christmas Carol",
          "author": "Charles Dickens",
          "cover": "https://archive.org/services/img/christmascarol_librivox",
          "year": 1843,
          "description": "Ebenezer Scrooge is visited by three spirits on Christmas Eve."
        },
        …
      ]
    },
    {
      "id": "autumn",
      "name": "Autumn",
      "metas": [
        {
          "id": "librivox:sleepy_hollow_librivox",
          "type": "audiobook",
          "name": "The Legend of Sleepy Hollow",
          "author": "Washington Irving",
          "cover": "https://archive.org/services/img/sleepy_hollow_librivox",
          "year": 1820,
          "description": "A schoolmaster, a harvest party and a headless horseman on the road home."
        },
        …
      ]
    }
  ]
}
examples/seasonal-catalogs/src/addon.ts
import { CatalogResponse, createAddon, type Manifest } from '@lelap/sdk';

import data from './catalogs.json' with { type: 'json' };

// The JSON is checked against the protocol at startup, so a typo fails here and not in the app.
const catalogs = data.catalogs.map(({ id, name, metas }) => ({
  id,
  name,
  ...CatalogResponse.parse({ metas, cacheMaxAge: 86400 }),
}));

export const manifest: Manifest = {
  // Use a reverse-DNS ID of a domain you control.
  id: 'org.example.seasonal',
  version: '1.0.0',
  protocol: 1,
  name: 'Seasonal readings',
  description: 'Public-domain LibriVox recordings for Christmas and for autumn evenings.',
  types: ['audiobook'],
  // Catalogs only: the items have `librivox:` IDs, so the LibriVox add-on answers meta and streams.
  resources: ['catalog'],
  catalogs: catalogs.map(({ id, name }) => ({ type: 'audiobook', id, name })),
};

export const addon = createAddon({
  manifest,
  // createAddon only calls this for catalogs the manifest lists, so `find` always matches.
  catalog: ({ id }) => {
    const { metas, cacheMaxAge } = catalogs.find((c) => c.id === id) ?? { metas: [] };
    return { metas, cacheMaxAge };
  },
});
Terminal
cd examples/seasonal-catalogs
pnpm dev             # http://localhost:8787/manifest.json
pnpm test

A copy outside the repository installs the SDK from npm the same way as the template.

To change the lists, edit the JSON: each catalog has an id, a name and a list of MetaPreview objects. The add-on checks the file against the protocol when it starts. A recording’s ID is the last part of its archive.org address: archive.org/details/christmascarol_librivox is librivox:christmascarol_librivox. ol: IDs of Open Library works work too; the LibriVox add-on looks up recordings for them.

Catalogs of your own recordings need meta and stream as well: start from the template instead.

What every sample checks

Each sample’s tests run in CI with the rest of the repository. Between them they check:

  • the manifest, a catalog with skip paging, meta and both kinds of stream;
  • percent-encoded IDs, and 404 JSON errors for unknown routes and IDs;
  • Access-Control-Allow-Origin: * on every answer and 204 for OPTIONS;
  • that every answer passes the protocol’s schemas, Python’s included.

Before you share your own add-on, paste its manifest into the manifest checker, then add it in the app.