@lelap/sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +110 -2
- package/dist/addon.d.ts +44 -0
- package/dist/addon.js +103 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/paths.d.ts +22 -0
- package/dist/paths.js +63 -0
- package/dist/protocol.d.ts +338 -0
- package/dist/protocol.js +160 -0
- package/dist/protocol.schema.json +571 -0
- package/package.json +50 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lelap contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,111 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lelap/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Types, zod schemas and a request handler for [Lelap](https://github.com/lelap-app/lelap) add-ons.
|
|
4
|
+
An add-on is a stateless HTTP service that answers with JSON: catalogs, metadata and audio sources
|
|
5
|
+
for the Lelap player. The SDK speaks protocol v1, so your code is a manifest and a handler for each
|
|
6
|
+
resource.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @lelap/sdk
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
It is ESM only and needs a runtime with the Fetch API (`Request` and `Response`): Cloudflare
|
|
13
|
+
Workers, Deno, Bun, or Node 20 and later.
|
|
14
|
+
|
|
15
|
+
## Example
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { createAddon, type Manifest } from '@lelap/sdk';
|
|
19
|
+
|
|
20
|
+
const manifest: Manifest = {
|
|
21
|
+
id: 'com.example.readings',
|
|
22
|
+
version: '1.0.0',
|
|
23
|
+
protocol: 1,
|
|
24
|
+
name: 'Example Readings',
|
|
25
|
+
description: 'Public-domain books read by volunteers.',
|
|
26
|
+
types: ['audiobook'],
|
|
27
|
+
resources: ['catalog'],
|
|
28
|
+
catalogs: [{ type: 'audiobook', id: 'new', name: 'New releases' }],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export const addon = createAddon({
|
|
32
|
+
manifest,
|
|
33
|
+
catalog: () => ({ metas: [], cacheMaxAge: 3600 }),
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Cloudflare Workers and Bun: export default { fetch: addon.fetch };
|
|
37
|
+
// Deno: Deno.serve(addon.fetch);
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`createAddon` routes `/manifest.json`, `/catalog/…`, `/meta/…` and `/stream/…`, adds CORS and
|
|
41
|
+
caching headers, answers `OPTIONS`, and checks every answer against the protocol's schemas. Throw
|
|
42
|
+
`AddonError(status, message)` for a JSON error; return `null` from `meta` for a 404.
|
|
43
|
+
|
|
44
|
+
## What's inside
|
|
45
|
+
|
|
46
|
+
- **Schemas and types** for every protocol object: `Manifest`, `MetaPreview`, `Meta`, `Stream`,
|
|
47
|
+
`CatalogResponse`, `MetaResponse`, `StreamResponse` and their parts. Each is a zod schema and a
|
|
48
|
+
TypeScript type of the same name.
|
|
49
|
+
- **`createAddon(handlers, options)`** turns handlers into `fetch(request)`. `options.basePath`
|
|
50
|
+
mounts several add-ons under one host.
|
|
51
|
+
- **Paths:** `catalogPath`, `metaPath`, `streamPath`, `parseRoute`, `encodeExtra`, `parseExtra`.
|
|
52
|
+
- **Helpers:** `supports`, `prefixesFor`, `hasParts`, `CORS_HEADERS`, `PROTOCOL_VERSION`.
|
|
53
|
+
- **JSON Schema** of every response, for other languages: `@lelap/sdk/protocol.schema.json`.
|
|
54
|
+
|
|
55
|
+
The SDK guide, the protocol reference and samples in plain Node and Python are in the
|
|
56
|
+
[developer docs](https://github.com/lelap-app/lelap/tree/main/apps/site/src/pages/docs). The
|
|
57
|
+
smallest complete add-on is [`services/template`](https://github.com/lelap-app/lelap/tree/main/services/template).
|
|
58
|
+
|
|
59
|
+
## License
|
|
60
|
+
|
|
61
|
+
MIT, so you can use it in an add-on under any license. The Lelap app itself is AGPL-3.0.
|
|
62
|
+
|
|
63
|
+
## Developing in the monorepo
|
|
64
|
+
|
|
65
|
+
Workspace packages (`services/*`, `packages/core`, `apps/*`, `examples/*`) import the TypeScript
|
|
66
|
+
source through `"exports": "./src/index.ts"`, so they need no build. The published package points
|
|
67
|
+
at `dist/` instead: `publishConfig` overrides `exports` and `types`, and `pnpm pack` applies it.
|
|
68
|
+
|
|
69
|
+
| Task | Command |
|
|
70
|
+
| ---------------------- | ---------------------------------- |
|
|
71
|
+
| Build ESM, types, JSON | `pnpm --filter @lelap/sdk build` |
|
|
72
|
+
| Type-check | `pnpm --filter @lelap/sdk check` |
|
|
73
|
+
| Test | `pnpm --filter @lelap/sdk test` |
|
|
74
|
+
| Files that would ship | `npm pack --dry-run` (in this dir) |
|
|
75
|
+
| The tarball npm gets | `pnpm pack` (in this dir) |
|
|
76
|
+
|
|
77
|
+
Relative imports in `src/` have no extension, which the workspace's bundlers expect;
|
|
78
|
+
`scripts/esm-paths.mjs` adds `.js` in `dist/` for Node's ESM loader.
|
|
79
|
+
|
|
80
|
+
## Releasing
|
|
81
|
+
|
|
82
|
+
Versions and the changelog come from [Changesets](https://github.com/changesets/changesets). Only
|
|
83
|
+
this package is published; the rest of the workspace is private and Changesets skips it.
|
|
84
|
+
|
|
85
|
+
1. In the pull request with the change, add a changeset and commit the file it writes:
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
pnpm changeset
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Pick `@lelap/sdk`, the bump (patch for fixes, minor for additions, major for breaking changes
|
|
92
|
+
to the API or the protocol) and a sentence for the changelog.
|
|
93
|
+
|
|
94
|
+
2. When you want to release, on a branch from `main`:
|
|
95
|
+
|
|
96
|
+
```sh
|
|
97
|
+
pnpm changeset version
|
|
98
|
+
pnpm install
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
This bumps `version` in `package.json`, writes `CHANGELOG.md` and deletes the used changesets.
|
|
102
|
+
Open a pull request with the result.
|
|
103
|
+
|
|
104
|
+
3. Merging it to `main` starts the `SDK` workflow (`.github/workflows/sdk.yml`). It builds and
|
|
105
|
+
tests the package, sees that npm doesn't have the version yet and waits in the `npm`
|
|
106
|
+
environment for a reviewer. Once approved, it packs the tarball with `pnpm pack` and runs
|
|
107
|
+
`npm publish --provenance`, so npm shows where and how the package was built. Versions with a
|
|
108
|
+
prerelease part (`0.3.0-beta.1`) go to the `next` tag.
|
|
109
|
+
|
|
110
|
+
Don't run `npm publish` in this folder: it would publish `exports` pointing at `src/`. The
|
|
111
|
+
`prepublishOnly` script stops it.
|
package/dist/addon.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { type Extra } from './paths.js';
|
|
2
|
+
import { type CatalogResponse, type ContentType, type Manifest, type MetaResponse, type StreamResponse } from './protocol.js';
|
|
3
|
+
type Awaitable<T> = T | Promise<T>;
|
|
4
|
+
export type CatalogArgs = {
|
|
5
|
+
type: ContentType;
|
|
6
|
+
id: string;
|
|
7
|
+
extra: Extra;
|
|
8
|
+
request: Request;
|
|
9
|
+
};
|
|
10
|
+
export type ItemArgs = {
|
|
11
|
+
type: ContentType;
|
|
12
|
+
id: string;
|
|
13
|
+
request: Request;
|
|
14
|
+
};
|
|
15
|
+
export type AddonHandlers = {
|
|
16
|
+
manifest: Manifest;
|
|
17
|
+
catalog?: (args: CatalogArgs) => Awaitable<CatalogResponse>;
|
|
18
|
+
/** Return `null` when the ID is unknown; the response is then a 404. */
|
|
19
|
+
meta?: (args: ItemArgs) => Awaitable<MetaResponse | null>;
|
|
20
|
+
stream?: (args: ItemArgs) => Awaitable<StreamResponse>;
|
|
21
|
+
};
|
|
22
|
+
export type AddonOptions = {
|
|
23
|
+
/** Path the add-on is mounted under, such as `/librivox`. Defaults to the root. */
|
|
24
|
+
basePath?: string;
|
|
25
|
+
/** Check handler output against the protocol schemas (slower; on by default). */
|
|
26
|
+
validate?: boolean;
|
|
27
|
+
/** Called with errors thrown by handlers, before the 500 response. */
|
|
28
|
+
onError?: (error: unknown, request: Request) => void;
|
|
29
|
+
};
|
|
30
|
+
export type Addon = {
|
|
31
|
+
manifest: Manifest;
|
|
32
|
+
fetch: (request: Request) => Promise<Response>;
|
|
33
|
+
};
|
|
34
|
+
export declare const CORS_HEADERS: Record<string, string>;
|
|
35
|
+
export declare class AddonError extends Error {
|
|
36
|
+
readonly status: number;
|
|
37
|
+
constructor(status: number, message: string);
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Turns handlers into a `fetch(request)` function that Cloudflare Workers, Deno, Bun and Node
|
|
41
|
+
* (through an adapter such as `@hono/node-server`) can serve.
|
|
42
|
+
*/
|
|
43
|
+
export declare function createAddon(handlers: AddonHandlers, options?: AddonOptions): Addon;
|
|
44
|
+
export {};
|
package/dist/addon.js
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { parseRoute } from './paths.js';
|
|
2
|
+
import { CatalogResponse as CatalogResponseSchema, Manifest as ManifestSchema, MetaResponse as MetaResponseSchema, StreamResponse as StreamResponseSchema, } from './protocol.js';
|
|
3
|
+
export const CORS_HEADERS = {
|
|
4
|
+
'Access-Control-Allow-Origin': '*',
|
|
5
|
+
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
|
6
|
+
'Access-Control-Allow-Headers': '*',
|
|
7
|
+
};
|
|
8
|
+
export class AddonError extends Error {
|
|
9
|
+
status;
|
|
10
|
+
constructor(status, message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.status = status;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function json(body, status = 200, maxAge) {
|
|
16
|
+
const headers = {
|
|
17
|
+
...CORS_HEADERS,
|
|
18
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
19
|
+
};
|
|
20
|
+
if (status === 200 && maxAge !== undefined)
|
|
21
|
+
headers['Cache-Control'] = `public, max-age=${maxAge}`;
|
|
22
|
+
return new Response(JSON.stringify(body), { status, headers });
|
|
23
|
+
}
|
|
24
|
+
function checked(schema, value, validate) {
|
|
25
|
+
if (!validate)
|
|
26
|
+
return value;
|
|
27
|
+
const result = schema.safeParse(value);
|
|
28
|
+
if (!result.success)
|
|
29
|
+
throw new Error(`Handler output does not match the protocol: ${result.error.message}`);
|
|
30
|
+
return result.data;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Turns handlers into a `fetch(request)` function that Cloudflare Workers, Deno, Bun and Node
|
|
34
|
+
* (through an adapter such as `@hono/node-server`) can serve.
|
|
35
|
+
*/
|
|
36
|
+
export function createAddon(handlers, options = {}) {
|
|
37
|
+
const manifest = ManifestSchema.parse(handlers.manifest);
|
|
38
|
+
const base = (options.basePath ?? '').replace(/\/+$/, '');
|
|
39
|
+
const validate = options.validate ?? true;
|
|
40
|
+
const typesFor = (resource) => {
|
|
41
|
+
const definition = manifest.resources.find((r) => (typeof r === 'string' ? r : r.name) === resource);
|
|
42
|
+
if (!definition)
|
|
43
|
+
return [];
|
|
44
|
+
return typeof definition === 'string' ? manifest.types : (definition.types ?? manifest.types);
|
|
45
|
+
};
|
|
46
|
+
const handle = async (request) => {
|
|
47
|
+
if (request.method === 'OPTIONS')
|
|
48
|
+
return new Response(null, { status: 204, headers: CORS_HEADERS });
|
|
49
|
+
if (request.method !== 'GET' && request.method !== 'HEAD')
|
|
50
|
+
return json({ error: 'Method not allowed' }, 405);
|
|
51
|
+
const { pathname } = new URL(request.url);
|
|
52
|
+
if (base && pathname !== base && !pathname.startsWith(`${base}/`))
|
|
53
|
+
return json({ error: 'Not found' }, 404);
|
|
54
|
+
const route = parseRoute(pathname.slice(base.length));
|
|
55
|
+
if (!route)
|
|
56
|
+
return json({ error: 'Not found' }, 404);
|
|
57
|
+
if (route.resource === 'manifest')
|
|
58
|
+
return json(manifest, 200, 3600);
|
|
59
|
+
if (!typesFor(route.resource).includes(route.type))
|
|
60
|
+
return json({ error: 'Not found' }, 404);
|
|
61
|
+
switch (route.resource) {
|
|
62
|
+
case 'catalog': {
|
|
63
|
+
if (!handlers.catalog)
|
|
64
|
+
break;
|
|
65
|
+
const known = manifest.catalogs.some((c) => c.type === route.type && c.id === route.id);
|
|
66
|
+
if (!known)
|
|
67
|
+
return json({ error: 'Unknown catalog' }, 404);
|
|
68
|
+
const body = checked(CatalogResponseSchema, await handlers.catalog({ ...route, request }), validate);
|
|
69
|
+
return json(body, 200, body.cacheMaxAge);
|
|
70
|
+
}
|
|
71
|
+
case 'meta': {
|
|
72
|
+
if (!handlers.meta)
|
|
73
|
+
break;
|
|
74
|
+
const result = await handlers.meta({ ...route, request });
|
|
75
|
+
if (!result)
|
|
76
|
+
return json({ error: 'Not found' }, 404);
|
|
77
|
+
const body = checked(MetaResponseSchema, result, validate);
|
|
78
|
+
return json(body, 200, body.cacheMaxAge);
|
|
79
|
+
}
|
|
80
|
+
case 'stream': {
|
|
81
|
+
if (!handlers.stream)
|
|
82
|
+
break;
|
|
83
|
+
const body = checked(StreamResponseSchema, await handlers.stream({ ...route, request }), validate);
|
|
84
|
+
return json(body, 200, body.cacheMaxAge);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return json({ error: 'Not found' }, 404);
|
|
88
|
+
};
|
|
89
|
+
return {
|
|
90
|
+
manifest,
|
|
91
|
+
fetch: async (request) => {
|
|
92
|
+
try {
|
|
93
|
+
return await handle(request);
|
|
94
|
+
}
|
|
95
|
+
catch (error) {
|
|
96
|
+
if (error instanceof AddonError)
|
|
97
|
+
return json({ error: error.message }, error.status);
|
|
98
|
+
options.onError?.(error, request);
|
|
99
|
+
return json({ error: 'The add-on failed to answer' }, 500);
|
|
100
|
+
}
|
|
101
|
+
},
|
|
102
|
+
};
|
|
103
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/paths.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type ContentType } from './protocol.js';
|
|
2
|
+
export type Extra = Record<string, string>;
|
|
3
|
+
/** `search=dune&skip=20`; keys sorted so equal extras give equal URLs (and cache hits). */
|
|
4
|
+
export declare function encodeExtra(extra: Extra): string;
|
|
5
|
+
export declare function parseExtra(encoded: string): Extra;
|
|
6
|
+
export declare function catalogPath(type: ContentType, id: string, extra?: Extra): string;
|
|
7
|
+
export declare function metaPath(type: ContentType, id: string): string;
|
|
8
|
+
export declare function streamPath(type: ContentType, id: string): string;
|
|
9
|
+
export type Route = {
|
|
10
|
+
resource: 'manifest';
|
|
11
|
+
} | {
|
|
12
|
+
resource: 'catalog';
|
|
13
|
+
type: ContentType;
|
|
14
|
+
id: string;
|
|
15
|
+
extra: Extra;
|
|
16
|
+
} | {
|
|
17
|
+
resource: 'meta' | 'stream';
|
|
18
|
+
type: ContentType;
|
|
19
|
+
id: string;
|
|
20
|
+
};
|
|
21
|
+
/** Parses a path relative to the add-on's base, such as `catalog/audiobook/new.json`. */
|
|
22
|
+
export declare function parseRoute(path: string): Route | null;
|
package/dist/paths.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { CONTENT_TYPES } from './protocol.js';
|
|
2
|
+
/** `search=dune&skip=20`; keys sorted so equal extras give equal URLs (and cache hits). */
|
|
3
|
+
export function encodeExtra(extra) {
|
|
4
|
+
return Object.keys(extra)
|
|
5
|
+
.filter((key) => extra[key] !== '')
|
|
6
|
+
.sort()
|
|
7
|
+
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(extra[key] ?? '')}`)
|
|
8
|
+
.join('&');
|
|
9
|
+
}
|
|
10
|
+
const decode = (value) => {
|
|
11
|
+
try {
|
|
12
|
+
return decodeURIComponent(value);
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
// Query-string style: `+` is a space in extras, not in IDs.
|
|
19
|
+
const decodeExtra = (value) => decode(value.replace(/\+/g, ' '));
|
|
20
|
+
export function parseExtra(encoded) {
|
|
21
|
+
const extra = {};
|
|
22
|
+
for (const pair of encoded.split('&')) {
|
|
23
|
+
if (!pair)
|
|
24
|
+
continue;
|
|
25
|
+
const at = pair.indexOf('=');
|
|
26
|
+
extra[decodeExtra(at < 0 ? pair : pair.slice(0, at))] =
|
|
27
|
+
at < 0 ? '' : decodeExtra(pair.slice(at + 1));
|
|
28
|
+
}
|
|
29
|
+
return extra;
|
|
30
|
+
}
|
|
31
|
+
const enc = encodeURIComponent;
|
|
32
|
+
export function catalogPath(type, id, extra = {}) {
|
|
33
|
+
const encoded = encodeExtra(extra);
|
|
34
|
+
return encoded ? `catalog/${type}/${enc(id)}/${encoded}.json` : `catalog/${type}/${enc(id)}.json`;
|
|
35
|
+
}
|
|
36
|
+
export function metaPath(type, id) {
|
|
37
|
+
return `meta/${type}/${enc(id)}.json`;
|
|
38
|
+
}
|
|
39
|
+
export function streamPath(type, id) {
|
|
40
|
+
return `stream/${type}/${enc(id)}.json`;
|
|
41
|
+
}
|
|
42
|
+
const isType = (value) => CONTENT_TYPES.includes(value);
|
|
43
|
+
/** Parses a path relative to the add-on's base, such as `catalog/audiobook/new.json`. */
|
|
44
|
+
export function parseRoute(path) {
|
|
45
|
+
const clean = path.replace(/^\/+/, '');
|
|
46
|
+
if (clean === 'manifest.json')
|
|
47
|
+
return { resource: 'manifest' };
|
|
48
|
+
if (!clean.endsWith('.json'))
|
|
49
|
+
return null;
|
|
50
|
+
// Extras stay encoded until parseExtra, so `&` and `=` inside values survive.
|
|
51
|
+
const [resource, rawType, rawId, extra, ...rest] = clean.slice(0, -'.json'.length).split('/');
|
|
52
|
+
if (rest.length > 0 || !rawType || !rawId)
|
|
53
|
+
return null;
|
|
54
|
+
const type = decode(rawType);
|
|
55
|
+
const id = decode(rawId);
|
|
56
|
+
if (!isType(type))
|
|
57
|
+
return null;
|
|
58
|
+
if (resource === 'catalog')
|
|
59
|
+
return { resource, type, id, extra: parseExtra(extra ?? '') };
|
|
60
|
+
if ((resource === 'meta' || resource === 'stream') && extra === undefined)
|
|
61
|
+
return { resource, type, id };
|
|
62
|
+
return null;
|
|
63
|
+
}
|