@caasx/sdk 0.0.0-stage → 0.1.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/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## @caasx/sdk@0.1.0
2
+
3
+ ### First npm release
4
+
5
+ `createClient` reads delivery content and runs likes, comments and polls, and `caasx types` writes a tenant's model as TypeScript. Community requests get the viewer's JWT from an `identity` callback backed by your app's own identity provider.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Joppa Digital
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,188 @@
1
- # Temporary Holding Version
1
+ <h1 align="center">caasX SDK</h1>
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ <p align="center">
4
+ A typed client for the caasX delivery API, and a CLI that writes your tenant's types.
5
+ </p>
6
+
7
+ <p align="center">
8
+ <a href="https://www.npmjs.com/package/@caasx/sdk"><img src="https://img.shields.io/npm/v/@caasx/sdk?style=for-the-badge&labelColor=000000" alt="npm version"></a>
9
+ <a href="https://www.npmjs.com/package/@caasx/sdk"><img src="https://img.shields.io/npm/l/@caasx/sdk?style=for-the-badge&labelColor=000000" alt="MIT License"></a>
10
+ </p>
11
+
12
+ ## ✨ What is the caasX SDK?
13
+
14
+ `@caasx/sdk` reads entries, rails, search results and playback sessions from the caasX delivery API, and runs likes, comments and polls for signed in viewers. `caasx types` turns your tenant's content model into a TypeScript interface, so `cms.get("episode", id)` comes back typed as an episode.
15
+
16
+ The package is ESM with no runtime dependencies. The client uses only `fetch`, `URL` and `AbortController`, with no Node imports. The CLI needs Node 22 or later.
17
+
18
+ ## 🚀 Getting Started
19
+
20
+ ```bash
21
+ npm install @caasx/sdk
22
+ ```
23
+
24
+ Generate your tenant's types, then hand them to the client:
25
+
26
+ ```bash
27
+ CAASX_URL=https://api.example.com CAASX_KEY="$PUBLISHABLE_KEY" \
28
+ npx caasx types --out src/caasx.gen.ts
29
+ ```
30
+
31
+ ```ts
32
+ import { createClient } from "@caasx/sdk";
33
+ import type { Model } from "./caasx.gen.js";
34
+
35
+ const cms = createClient<Model>({
36
+ url: "https://api.example.com",
37
+ key: publishableKey,
38
+ });
39
+
40
+ const page = await cms.list("episode", { limit: 20, include: ["video"] });
41
+ ```
42
+
43
+ ### Commands
44
+
45
+ | Command | What it does |
46
+ | -------------------------- | ------------------------------------------------ |
47
+ | `caasx types` | Write the tenant's model to `caasx.gen.ts`. |
48
+ | `caasx types --out <path>` | Write it to another file. |
49
+ | `caasx types --check` | Report whether the file is stale, write nothing. |
50
+ | `caasx --version` | Print the SDK version. |
51
+
52
+ `--url` and `--key` override `CAASX_URL` and `CAASX_KEY`. Keep credentials in the environment, not on the command line. Regenerate after the model changes.
53
+
54
+ ## 📖 Reading Content
55
+
56
+ ```ts
57
+ const page = await cms.list("episode", {
58
+ limit: 20,
59
+ filter: [{ field: "season", op: "eq", value: seasonId }],
60
+ sort: "id",
61
+ include: ["season.series", "video"],
62
+ cursor: nextCursor,
63
+ signal,
64
+ });
65
+
66
+ const episode = await cms.get("episode", episodeId, { include: ["video"], signal });
67
+ const rail = await cms.rail("home-hero", { signal });
68
+ const session = await cms.play(videoId, { signal });
69
+ ```
70
+
71
+ `url` is the API's HTTP(S) origin or a path prefix such as `https://example.com/api/`, never a `/v1` route. A trailing slash is fine. The client rejects a URL that holds credentials, a query string or a fragment. `key` is a publishable key: `pk_` and 43 URL-safe characters. Pass `fetch` in the options to bring your own transport. The client sends no cookies and rejects redirects instead of forwarding credentials to them.
72
+
73
+ `list` returns `{ items, next, catalog_version }`. For the next page, pass `next` back as `cursor` with the same type, sort and filters. A null cursor starts over. `get` returns the entry itself, not the API's one entry page. The client never retries a request, never follows pagination on its own and caches nothing.
74
+
75
+ Filters take `eq`, `in`, `lt`, `lte`, `gt`, `gte`, `null` and `has`. A scalar value is a string, a finite number or a boolean. `in` takes a nonempty array and repeats the query parameter once per value. `null` takes a boolean. `has` matches a terms field holding one term id and takes a single string, for example `{ field: "topics", op: "has", value: termId }`. The server checks fields, operators, sort keys and include paths against the tenant model.
76
+
77
+ Without a model type, an entry has the five `EntryEnvelope` properties and unknown tenant fields. With `Model`, a list of episodes returns `Model["episode"]` entries. At runtime the client checks the platform envelope, not your field values, and keeps unknown properties and expanded objects as they arrive. A generated reference field is a UUID string, an expanded object or null, so narrow it before use. Include paths do not change the static type.
78
+
79
+ ### Rails and Playback
80
+
81
+ A rail's `layout` is a free string, and its title, card titles and images can be null. So can image URLs and dimensions. A playback session has no catalog version. Check `session.status === "ready"` before reading its playback URLs. `expires_at` is in Unix seconds. Keep signed playback URLs out of durable caches and logs.
82
+
83
+ `session.preroll` is the ad to play before the video, or null when there is none. It has `id`, `sponsor_name`, `click_url` and a `creative`, which is a ready playback session with its own signed URLs. An API older than preroll leaves the field out, and the client reads that as null.
84
+
85
+ ### Sponsored Rail Cards
86
+
87
+ `RailItem` is `EntryRailItem | SponsoredRailItem`. Check `sponsored`, not `target.type`, to tell a sponsored card apart. Both carry the same card fields, and a sponsored card adds `sponsored.sponsor_name` and `sponsored.click_url`.
88
+
89
+ ```ts
90
+ const rail = await cms.rail("home-hero");
91
+
92
+ for (const item of rail.items) {
93
+ if (item.sponsored) {
94
+ showSponsor(item.sponsored.sponsor_name, item.sponsored.click_url);
95
+ }
96
+ }
97
+ ```
98
+
99
+ ### Search and Taxonomies
100
+
101
+ `search(q, { type, cursor, limit, include })` returns `{ items: [{ type, entry }], next, catalog_version }`. Leave out `type` to search every type. `include` expands reference paths the same way it does on `list` and `get`, for example `search(q, { include: ["cover"] })`. A cursor belongs to its `q`, `type` and `include`, and reusing it with others fails with a `CaasxError` whose code is `"cursor_mismatch"`. `limit` is an integer from 1 to 50.
102
+
103
+ `taxonomy(slug)` returns `{ items, catalog_version }`. The items are the root terms with nested `children`, both in position order.
104
+
105
+ ### Watching the Catalog
106
+
107
+ ```ts
108
+ const watcher = cms.watchCatalog({
109
+ since: cachedVersion,
110
+ intervalMs: 15000,
111
+ onChange(newVersion, previousVersion) {
112
+ invalidateTenantQueries(newVersion, previousVersion);
113
+ },
114
+ onError(error) {
115
+ reportError(error);
116
+ },
117
+ });
118
+
119
+ watcher.stop();
120
+ ```
121
+
122
+ Polling starts at once. Each finished poll schedules the next one `intervalMs` later, 15000 by default, so requests never overlap. Without `since`, the first successful poll sets the baseline and calls nothing. Every new version calls `onChange`, a reset to a lower version included. A failed request keeps the baseline, calls `onError` and polling carries on. If `onChange` throws, the baseline stays put and the next poll tries again. Callbacks are synchronous, and an exception from `onError` does not stop polling.
123
+
124
+ `stop()` is safe to call more than once. It cancels the next timer, aborts the request in flight and silences later callbacks. Start a watcher when your app comes to the foreground and stop it when it goes to the background. Other requests on the client never move its baseline. After the first poll, the watcher sends `If-None-Match` with the last ETag it accepted and treats a 304 as no change. It keeps no entry cache.
125
+
126
+ ## 💬 Community
127
+
128
+ Viewers sign in with your app's own identity provider. A platform admin registers that provider's issuer for your tenant, and caasX verifies the JWT your app already holds. There is no caasX token to mint and no server of yours to run. Pass `identity`, a function that returns the current JWT, or null when nobody is signed in:
129
+
130
+ ```ts
131
+ const cms = createClient({
132
+ url: "https://api.example.com",
133
+ key: publishableKey,
134
+ identity: ({ forceRefresh }) => auth.getToken({ forceRefresh }),
135
+ });
136
+
137
+ const profile = await cms.viewer({ signal });
138
+ const counts = await cms.interactions([episodeId], { signal });
139
+ const liked = await cms.like(episodeId, { signal });
140
+ const unliked = await cms.unlike(episodeId, { signal });
141
+ const posted = await cms.comment(episodeId, { text: "Good episode", signal });
142
+ const reply = await cms.comment(episodeId, { text: "Agreed", parent: posted.id, signal });
143
+ const comments = await cms.comments(episodeId, { cursor: nextComment, limit: 20, signal });
144
+ await cms.report(posted.id, { signal });
145
+ const poll = await cms.poll(episodeId, { signal });
146
+ const voted = await cms.vote(poll.id, optionId, { signal });
147
+ ```
148
+
149
+ The client calls `identity` before every community request and sends the token as `X-Caasx-Viewer`. Delivery reads such as `list()`, `get()`, `rail()` and `play()` never call it, and a sign in, sign out or token refresh applies to the next request with the same client.
150
+
151
+ When the API answers 401 `viewer_invalid`, the client calls `identity({ forceRefresh: true, rejectedToken })` once, with the token that failed, and retries only if it gets a different token back. A callback that throws or rejects fails the call before any request goes out. Aborting `signal` rejects the call even while the callback is still pending. The client never stores, caches or logs a token and never needs a refresh token. A token must not contain spaces or control characters.
152
+
153
+ Reads work signed out. `interactions()`, `comments()` and `poll()` return counts with `liked` false, `mine` false and `choice` null. Writes and `viewer()` need a viewer and fail with 401 `viewer_required` without one. For anonymous participation, use your provider's anonymous sign in, and caasX treats those users like any other viewer.
154
+
155
+ caasX identifies a viewer by the stable id claim your tenant registration names, `sub` by default. Some providers put a session in `sub`. Convex Auth sets it to `userId|sessionId`, which would make every new session a new viewer, so issue a claim that holds only the user id and register that one.
156
+
157
+ The publishable key needs `interactions:write`.
158
+
159
+ `viewer()` returns the viewer's `display_name` and nullable `badge`. `like()` and `unlike()` return `{ likes, liked }`. `interactions()` takes 1 to 100 nonempty ids without commas and returns `{ entries }`, keyed by entry id, each with `likes`, `liked` and `comments`.
160
+
161
+ `comment()` needs a viewer and returns the new comment. Leave out `parent` for a top level comment. `comments()` returns `{ items, next }`, and `next` goes back in as `cursor`. Its `limit` is an integer from 1 to 50. A comment has `id`, `parent`, `display_name`, `badge`, `text`, `created_at` and `mine`. `report()` resolves with no value.
162
+
163
+ `poll()` and `vote()` return the question, nullable `opens_at` and `closes_at`, `open`, the options with their vote counts, and the viewer's nullable `choice`. Every community method takes `signal` and validates the shape of the response.
164
+
165
+ ## ⚠️ Errors
166
+
167
+ `CaasxError` has `status`, `code` and `message` for HTTP failures. `code` is the server's `reason` when it sends one, otherwise its `error` message, otherwise `HTTP <status>`, which is also what a non-JSON error body gets. Errors the SDK creates redact API keys and the viewer tokens `identity` returned for that call, and never include request URLs or response bodies. Network and abort errors come straight from `fetch`, so a custom `fetch` must not put request headers in the errors it throws. `CaasxProtocolError` means a successful response held malformed JSON or a malformed platform envelope.
168
+
169
+ ### Browsers and CORS
170
+
171
+ A browser on another origin can call `rail()` and `theme()`. Their routes, `GET /v1/rails/:slug` and `GET /v1/themes/:slug`, are the only delivery routes that send CORS headers. They allow any origin, the GET, HEAD and OPTIONS methods and the `Authorization` and `If-None-Match` request headers, and expose `ETag` and `Retry-After`. No other delivery route sends CORS headers, entries, search, catalog and taxonomies included, so call those from the same origin or from a server. A 429 from any route also allows any origin and exposes `Retry-After`. CORS does not apply to native apps.
172
+
173
+ ## 🧬 Generated Types
174
+
175
+ ```bash
176
+ caasx types --out src/caasx.gen.ts
177
+ caasx types --check --out src/caasx.gen.ts
178
+ ```
179
+
180
+ The platform can add field kinds and filter operators before your installed CLI knows about them. A field of an unknown kind comes out as `unknown`, and a known field keeps its type when it gains an unknown operator. The CLI prints one warning per affected field on stderr and still succeeds. Upgrade `@caasx/sdk` for the full types.
181
+
182
+ The generated interface checks nothing at runtime. `cms.model()` returns the model document for tooling, and the client validates only its page envelope.
183
+
184
+ When `--out` names a symlink, regenerating replaces the link's target atomically and keeps the link. A broken symlink fails and leaves the link as it was.
185
+
186
+ ## 📄 License
187
+
188
+ The caasX SDK is licensed under the MIT License. The full text ships in the package as `LICENSE`.
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export declare function runCli(args: string[], env?: NodeJS.ProcessEnv): Promise<number>;
package/dist/cli.js ADDED
@@ -0,0 +1,160 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from "node:crypto";
3
+ import { realpathSync } from "node:fs";
4
+ import { lstat, mkdir, open, readFile, realpath, rename, rm } from "node:fs/promises";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { parseArgs } from "node:util";
8
+ import { createClient } from "./client.js";
9
+ import { generateTypes } from "./typegen.js";
10
+ const options = {
11
+ url: { type: "string" },
12
+ key: { type: "string" },
13
+ out: { type: "string" },
14
+ check: { type: "boolean" },
15
+ help: { type: "boolean", short: "h" },
16
+ version: { type: "boolean" },
17
+ };
18
+ const help = `Usage: caasx types [options]
19
+
20
+ --url <url> API origin or prefix (defaults to CAASX_URL)
21
+ --key <key> Publishable key (defaults to CAASX_KEY)
22
+ --out <path> Output file (defaults to caasx.gen.ts)
23
+ --check Check output without changing files
24
+ --help, -h Show help
25
+ --version Show version
26
+ `;
27
+ async function readOutput(path) {
28
+ try {
29
+ return await readFile(path);
30
+ }
31
+ catch (error) {
32
+ if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") {
33
+ return null;
34
+ }
35
+ throw error;
36
+ }
37
+ }
38
+ async function writeOutput(path, content) {
39
+ const metadata = await lstat(path).catch((error) => {
40
+ if (error !== null && typeof error === "object" && "code" in error && error.code === "ENOENT") {
41
+ return null;
42
+ }
43
+ throw error;
44
+ });
45
+ const destination = metadata?.isSymbolicLink() ? await realpath(path) : path;
46
+ await mkdir(dirname(destination), { recursive: true });
47
+ const temporary = join(dirname(destination), `.caasx-${randomUUID()}.tmp`);
48
+ const handle = await open(temporary, "wx");
49
+ try {
50
+ await handle.writeFile(content, "utf8");
51
+ await handle.close();
52
+ await rename(temporary, destination);
53
+ }
54
+ finally {
55
+ try {
56
+ await handle.close();
57
+ }
58
+ finally {
59
+ await rm(temporary, { force: true });
60
+ }
61
+ }
62
+ }
63
+ export async function runCli(args, env = process.env) {
64
+ let parsed;
65
+ try {
66
+ parsed = parseArgs({
67
+ args,
68
+ strict: true,
69
+ allowPositionals: true,
70
+ options,
71
+ });
72
+ }
73
+ catch {
74
+ process.stderr.write("Invalid arguments. Run caasx --help.\n");
75
+ return 2;
76
+ }
77
+ const { values, positionals } = parsed;
78
+ if (positionals.length > 1 || (positionals.length === 1 && positionals[0] !== "types")) {
79
+ process.stderr.write("Expected the types command. Run caasx --help.\n");
80
+ return 2;
81
+ }
82
+ if (values.help) {
83
+ process.stdout.write(help);
84
+ return 0;
85
+ }
86
+ if (values.version) {
87
+ try {
88
+ const metadata = JSON.parse(await readFile(new URL("../package.json", import.meta.url), "utf8"));
89
+ if (metadata === null ||
90
+ typeof metadata !== "object" ||
91
+ !("version" in metadata) ||
92
+ typeof metadata.version !== "string") {
93
+ throw new TypeError("Invalid package version.");
94
+ }
95
+ process.stdout.write(`${metadata.version}\n`);
96
+ return 0;
97
+ }
98
+ catch {
99
+ process.stderr.write("Unable to read the SDK version.\n");
100
+ return 1;
101
+ }
102
+ }
103
+ const url = values.url ?? env.CAASX_URL;
104
+ const key = values.key ?? env.CAASX_KEY;
105
+ const output = values.out ?? "caasx.gen.ts";
106
+ if (positionals.length !== 1 || !url || !key || !output || output.includes("\0")) {
107
+ process.stderr.write("Provide the types command, API URL and publishable key. Run caasx --help.\n");
108
+ return 2;
109
+ }
110
+ let client;
111
+ try {
112
+ client = createClient({ url, key });
113
+ }
114
+ catch {
115
+ process.stderr.write("Invalid API URL or publishable key.\n");
116
+ return 2;
117
+ }
118
+ let generated;
119
+ try {
120
+ generated = generateTypes(await client.model());
121
+ }
122
+ catch {
123
+ process.stderr.write("Unable to generate types from the API model.\n");
124
+ return 1;
125
+ }
126
+ for (const warning of generated.warnings) {
127
+ process.stderr.write(`${warning}\n`);
128
+ }
129
+ try {
130
+ const path = resolve(output);
131
+ const current = await readOutput(path);
132
+ if (current?.equals(Buffer.from(generated.source, "utf8"))) {
133
+ return 0;
134
+ }
135
+ if (values.check) {
136
+ process.stderr.write("Generated types are missing or out of date.\n");
137
+ return 1;
138
+ }
139
+ await writeOutput(path, generated.source);
140
+ return 0;
141
+ }
142
+ catch {
143
+ process.stderr.write("Unable to read or write generated types.\n");
144
+ return 1;
145
+ }
146
+ }
147
+ function isMain() {
148
+ if (!process.argv[1]) {
149
+ return false;
150
+ }
151
+ try {
152
+ return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
153
+ }
154
+ catch {
155
+ return false;
156
+ }
157
+ }
158
+ if (isMain()) {
159
+ process.exitCode = await runCli(process.argv.slice(2));
160
+ }
@@ -0,0 +1,12 @@
1
+ import type { Client, ClientOptions, DefaultSchema, EntryEnvelope } from "./types.js";
2
+ export declare class CaasxError extends Error {
3
+ readonly status: number;
4
+ readonly code: string;
5
+ constructor(status: number, code: string, message: string);
6
+ }
7
+ export declare class CaasxProtocolError extends Error {
8
+ constructor();
9
+ }
10
+ export declare function createClient<Schema extends {
11
+ [Key in keyof Schema]: EntryEnvelope;
12
+ } = DefaultSchema>(options: ClientOptions): Client<Schema>;