@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.
@@ -0,0 +1,2 @@
1
+ export { CaasxError, CaasxProtocolError, createClient } from "./client.js";
2
+ export type { Catalog, CatalogWatcher, Client, ClientOptions, CommentOptions, CommentPage, CommentsOptions, DefaultSchema, EntryComment, EntryEnvelope, EntryPoll, EntryRailItem, Filter, FilterOperator, FilterValue, GetOptions, IdentityOptions, Image, Interactions, LikeState, ListOptions, ModelDocument, ModelField, ModelFieldKind, ModelType, Page, Playback, PlaybackCaption, PlaybackSession, PollOption, PrerollDecision, Rail, RailItem, RequestOptions, Screen, SearchHit, SearchOptions, SearchPage, SponsoredRailItem, Sponsorship, Taxonomy, TaxonomyTerm, Term, Theme, TypedSearchOptions, Video, VideoStatus, Viewer, ViewerToken, WatchCatalogOptions, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export { CaasxError, CaasxProtocolError, createClient } from "./client.js";
@@ -0,0 +1,4 @@
1
+ export declare function generateTypes(document: unknown): {
2
+ source: string;
3
+ warnings: string[];
4
+ };
@@ -0,0 +1,252 @@
1
+ const kinds = [
2
+ "text",
3
+ "rich_text",
4
+ "integer",
5
+ "bigint",
6
+ "float",
7
+ "boolean",
8
+ "date",
9
+ "datetime",
10
+ "uuid",
11
+ "entry",
12
+ "entries",
13
+ "choice",
14
+ "video",
15
+ "image",
16
+ "images",
17
+ "term",
18
+ "terms",
19
+ ];
20
+ const envelope = new Map([
21
+ ["id", { kind: "uuid", required: true }],
22
+ ["external_id", { kind: "text", required: false }],
23
+ ["created_at", { kind: "datetime", required: true }],
24
+ ["updated_at", { kind: "datetime", required: false }],
25
+ ["published_at", { kind: "datetime", required: false }],
26
+ ]);
27
+ const reserved = new Set([
28
+ ...envelope.keys(),
29
+ "tenant",
30
+ "status",
31
+ "created_by",
32
+ "updated_by",
33
+ "published_by",
34
+ "row_version",
35
+ "search_document",
36
+ "ingest_hash",
37
+ "ingested_at",
38
+ "ingest_owned",
39
+ ]);
40
+ const operators = new Set(["eq", "in", "lt", "lte", "gt", "gte", "null"]);
41
+ function invalid(path) {
42
+ throw new TypeError(`Invalid model document at ${path}.`);
43
+ }
44
+ function object(value, path) {
45
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
46
+ invalid(path);
47
+ }
48
+ return value;
49
+ }
50
+ function text(value, path, nonempty = true) {
51
+ if (typeof value !== "string" || (nonempty && value.length === 0)) {
52
+ invalid(path);
53
+ }
54
+ return value;
55
+ }
56
+ function boolean(value, path) {
57
+ if (typeof value !== "boolean") {
58
+ invalid(path);
59
+ }
60
+ return value;
61
+ }
62
+ function isKind(value) {
63
+ return kinds.some((kind) => kind === value);
64
+ }
65
+ function parseField(value, path) {
66
+ const field = object(value, path);
67
+ const key = text(field.key, `${path}.key`);
68
+ const kind = text(field.kind, `${path}.kind`);
69
+ text(field.label, `${path}.label`, false);
70
+ const required = boolean(field.required, `${path}.required`);
71
+ const isEnvelope = boolean(field.envelope, `${path}.envelope`);
72
+ const deprecated = Object.hasOwn(field, "deprecated")
73
+ ? boolean(field.deprecated, `${path}.deprecated`)
74
+ : false;
75
+ const target = kind === "entry" || kind === "entries" ? text(field.target, `${path}.target`) : null;
76
+ let options = null;
77
+ if (kind === "choice" && Object.hasOwn(field, "options")) {
78
+ if (!Array.isArray(field.options) ||
79
+ !field.options.every((option) => typeof option === "string") ||
80
+ new Set(field.options).size !== field.options.length) {
81
+ invalid(`${path}.options`);
82
+ }
83
+ options = field.options;
84
+ }
85
+ if (kind !== "entry" &&
86
+ kind !== "entries" &&
87
+ field.target !== null &&
88
+ (isKind(kind) || typeof field.target !== "string" || field.target.length === 0)) {
89
+ invalid(`${path}.target`);
90
+ }
91
+ boolean(field.sortable, `${path}.sortable`);
92
+ if (!Array.isArray(field.operators)) {
93
+ invalid(`${path}.operators`);
94
+ }
95
+ const seenOperators = new Set();
96
+ for (const operator of field.operators) {
97
+ if (typeof operator !== "string" || seenOperators.has(operator)) {
98
+ invalid(`${path}.operators`);
99
+ }
100
+ seenOperators.add(operator);
101
+ }
102
+ const unrecognized = isKind(kind) ? [] : [`kind ${quote(kind)}`];
103
+ const unknownOperators = [...seenOperators].filter((operator) => !operators.has(operator));
104
+ if (unknownOperators.length > 0) {
105
+ const noun = unknownOperators.length === 1 ? "operator" : "operators";
106
+ unrecognized.push(`${noun} ${unknownOperators.map(quote).join(", ")}`);
107
+ }
108
+ if (Object.hasOwn(field, "taxonomy")) {
109
+ text(field.taxonomy, `${path}.taxonomy`);
110
+ }
111
+ if (isEnvelope) {
112
+ const expected = envelope.get(key);
113
+ if (!expected || expected.kind !== kind || expected.required !== required || deprecated) {
114
+ invalid(`${path}.envelope`);
115
+ }
116
+ }
117
+ else if (reserved.has(key)) {
118
+ invalid(`${path}.key`);
119
+ }
120
+ return {
121
+ key,
122
+ kind: isKind(kind) ? kind : "unknown",
123
+ unrecognized,
124
+ required,
125
+ envelope: isEnvelope,
126
+ target,
127
+ options,
128
+ deprecated,
129
+ };
130
+ }
131
+ function parseDocument(value) {
132
+ const document = object(value, "document");
133
+ if (!Array.isArray(document.items) ||
134
+ document.next !== null ||
135
+ !Number.isSafeInteger(document.catalog_version) ||
136
+ document.catalog_version < 0) {
137
+ invalid("document");
138
+ }
139
+ const seenTypes = new Set();
140
+ return document.items.map((value, typeIndex) => {
141
+ const path = `items[${typeIndex}]`;
142
+ const modelType = object(value, path);
143
+ const key = text(modelType.key, `${path}.key`);
144
+ text(modelType.label, `${path}.label`, false);
145
+ if (seenTypes.has(key) || !Array.isArray(modelType.fields)) {
146
+ invalid(path);
147
+ }
148
+ seenTypes.add(key);
149
+ const seenFields = new Set();
150
+ const fields = modelType.fields.map((value, fieldIndex) => {
151
+ const field = parseField(value, `${path}.fields[${fieldIndex}]`);
152
+ if (seenFields.has(field.key)) {
153
+ invalid(`${path}.fields[${fieldIndex}].key`);
154
+ }
155
+ seenFields.add(field.key);
156
+ return field;
157
+ });
158
+ return { key, fields };
159
+ });
160
+ }
161
+ function compareKeys(left, right) {
162
+ return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
163
+ }
164
+ function quote(value) {
165
+ return JSON.stringify(value)
166
+ .replace(/\u2028/g, "\\u2028")
167
+ .replace(/\u2029/g, "\\u2029");
168
+ }
169
+ function fieldType(field, typeKeys) {
170
+ switch (field.kind) {
171
+ case "entry":
172
+ case "entries": {
173
+ const target = field.target;
174
+ const expanded = target !== null && typeKeys.has(target)
175
+ ? `Model[${quote(target)}]`
176
+ : "(EntryEnvelope & Record<string, unknown>)";
177
+ return field.kind === "entries" ? `string[] | ${expanded}[]` : `string | ${expanded} | null`;
178
+ }
179
+ case "video":
180
+ return "string | Video | null";
181
+ case "image":
182
+ return "string | Image | null";
183
+ case "images":
184
+ return "(string | Image)[]";
185
+ case "term":
186
+ return "string | Term | null";
187
+ case "terms":
188
+ return "(string | Term)[]";
189
+ case "unknown":
190
+ return "unknown";
191
+ default: {
192
+ const scalar = field.kind === "integer"
193
+ ? "number"
194
+ : field.kind === "float"
195
+ ? 'number | "NaN" | "Infinity" | "-Infinity"'
196
+ : field.kind === "boolean"
197
+ ? "boolean"
198
+ : field.kind === "choice" && field.options !== null && field.options.length > 0
199
+ ? `${field.options.map(quote).join(" | ")} | (string & {})`
200
+ : "string";
201
+ return field.required && !field.deprecated ? scalar : `${scalar} | null`;
202
+ }
203
+ }
204
+ }
205
+ export function generateTypes(document) {
206
+ const model = parseDocument(document).sort(compareKeys);
207
+ const warnings = model.flatMap((modelType) => modelType.fields
208
+ .filter((field) => field.unrecognized.length > 0)
209
+ .map((field) => {
210
+ const name = quote(`${modelType.key}.${field.key}`);
211
+ const detail = field.unrecognized.join(", ");
212
+ return field.kind === "unknown"
213
+ ? `Typed ${name} as unknown: unrecognized ${detail}. Upgrade @caasx/sdk to type it.`
214
+ : `Ignored unrecognized ${detail} on ${name}. Upgrade @caasx/sdk to use it.`;
215
+ }));
216
+ const typeKeys = new Set(model.map((modelType) => modelType.key));
217
+ const imports = new Set();
218
+ const lines = [];
219
+ for (const modelType of model) {
220
+ imports.add("EntryEnvelope");
221
+ lines.push(` ${quote(modelType.key)}: EntryEnvelope & {`);
222
+ for (const field of modelType.fields.filter((field) => !field.envelope).sort(compareKeys)) {
223
+ if (field.kind === "video") {
224
+ imports.add("Video");
225
+ }
226
+ else if (field.kind === "image" || field.kind === "images") {
227
+ imports.add("Image");
228
+ }
229
+ else if (field.kind === "term" || field.kind === "terms") {
230
+ imports.add("Term");
231
+ }
232
+ if (field.kind === "rich_text") {
233
+ const description = "HTML limited to p, br, h2, h3, h4, strong, em, u, s, blockquote, ul, ol, li, pre, code, a[href] (http, https, mailto), img[src] (image pull zone) and img[alt].";
234
+ lines.push(field.deprecated
235
+ ? ` /**\n * ${description}\n * @deprecated\n */`
236
+ : ` /** ${description} */`);
237
+ }
238
+ else if (field.deprecated) {
239
+ lines.push(" /** @deprecated */");
240
+ }
241
+ lines.push(` ${quote(field.key)}${field.deprecated ? "?" : ""}: ${fieldType(field, typeKeys)};`);
242
+ }
243
+ lines.push(" };");
244
+ }
245
+ const header = imports.size > 0
246
+ ? `import type { ${[...imports].sort().join(", ")} } from "@caasx/sdk";\n\n`
247
+ : "";
248
+ return {
249
+ source: `${header}export interface Model {\n${lines.length > 0 ? `${lines.join("\n")}\n` : ""}}\n`,
250
+ warnings,
251
+ };
252
+ }
@@ -0,0 +1,285 @@
1
+ export interface EntryEnvelope {
2
+ id: string;
3
+ external_id: string | null;
4
+ created_at: string;
5
+ updated_at: string | null;
6
+ published_at: string | null;
7
+ }
8
+ export type DefaultSchema = Record<string, EntryEnvelope & Record<string, unknown>>;
9
+ export interface Page<Entry> {
10
+ items: Entry[];
11
+ next: string | null;
12
+ catalog_version: number;
13
+ }
14
+ export type FilterOperator = "eq" | "in" | "lt" | "lte" | "gt" | "gte" | "null" | "has";
15
+ export type FilterValue = string | number | boolean;
16
+ export type Filter = {
17
+ field: string;
18
+ op: "eq" | "lt" | "lte" | "gt" | "gte";
19
+ value: FilterValue;
20
+ } | {
21
+ field: string;
22
+ op: "in";
23
+ value: readonly FilterValue[];
24
+ } | {
25
+ field: string;
26
+ op: "has";
27
+ value: string;
28
+ } | {
29
+ field: string;
30
+ op: "null";
31
+ value: boolean;
32
+ };
33
+ export interface RequestOptions {
34
+ signal?: AbortSignal;
35
+ }
36
+ export interface GetOptions extends RequestOptions {
37
+ include?: readonly string[];
38
+ }
39
+ export interface ListOptions extends GetOptions {
40
+ limit?: number;
41
+ cursor?: string | null;
42
+ sort?: string;
43
+ filter?: readonly Filter[];
44
+ }
45
+ export interface SearchOptions extends RequestOptions {
46
+ include?: readonly string[];
47
+ cursor?: string | null;
48
+ limit?: number;
49
+ }
50
+ export interface TypedSearchOptions<Type extends string> extends SearchOptions {
51
+ type: Type;
52
+ }
53
+ export type SearchHit<Schema, Type extends keyof Schema> = {
54
+ [Key in Type]: {
55
+ type: Key;
56
+ entry: Schema[Key];
57
+ };
58
+ }[Type];
59
+ export interface SearchPage<Schema, Type extends keyof Schema> extends Catalog {
60
+ items: SearchHit<Schema, Type>[];
61
+ next: string | null;
62
+ }
63
+ export interface ClientOptions {
64
+ url: string;
65
+ key: string;
66
+ fetch?: typeof globalThis.fetch;
67
+ identity?: (options: IdentityOptions) => ViewerToken | Promise<ViewerToken>;
68
+ }
69
+ export type IdentityOptions = {
70
+ forceRefresh: false;
71
+ } | {
72
+ forceRefresh: true;
73
+ rejectedToken: string;
74
+ };
75
+ export type ViewerToken = string | null | undefined;
76
+ export type Viewer = {
77
+ kind: "viewer";
78
+ display_name: string;
79
+ badge: string | null;
80
+ };
81
+ export interface LikeState {
82
+ likes: number;
83
+ liked: boolean;
84
+ }
85
+ export interface Interactions {
86
+ entries: Record<string, LikeState & {
87
+ comments: number;
88
+ poll: string | null;
89
+ }>;
90
+ }
91
+ export interface EntryComment {
92
+ id: string;
93
+ parent: string | null;
94
+ display_name: string;
95
+ badge: string | null;
96
+ text: string;
97
+ created_at: string;
98
+ mine: boolean;
99
+ }
100
+ export interface CommentPage {
101
+ items: EntryComment[];
102
+ next: string | null;
103
+ }
104
+ export interface CommentsOptions extends RequestOptions {
105
+ cursor?: string | null;
106
+ limit?: number;
107
+ }
108
+ export interface CommentOptions extends RequestOptions {
109
+ text: string;
110
+ parent?: string | null;
111
+ }
112
+ export interface PollOption {
113
+ id: string;
114
+ label: string;
115
+ votes: number;
116
+ }
117
+ export interface EntryPoll {
118
+ id: string;
119
+ question: string;
120
+ opens_at: string | null;
121
+ closes_at: string | null;
122
+ open: boolean;
123
+ options: PollOption[];
124
+ choice: string | null;
125
+ }
126
+ export interface Catalog {
127
+ catalog_version: number;
128
+ }
129
+ export type VideoStatus = "reserved" | "uploading" | "processing" | "failed" | "ready";
130
+ export interface Video {
131
+ id: string;
132
+ status: VideoStatus;
133
+ duration_ms: number | null;
134
+ thumbnail_url: string | null;
135
+ }
136
+ export interface Image {
137
+ id: string;
138
+ url: string | null;
139
+ width: number | null;
140
+ height: number | null;
141
+ }
142
+ export interface Term {
143
+ id: string;
144
+ slug: string;
145
+ label: string;
146
+ parent: string | null;
147
+ }
148
+ export interface TaxonomyTerm extends Term {
149
+ children: TaxonomyTerm[];
150
+ }
151
+ export interface Taxonomy extends Catalog {
152
+ items: TaxonomyTerm[];
153
+ }
154
+ export interface EntryRailItem {
155
+ title: string | null;
156
+ subtitle: string | null;
157
+ badge: string | null;
158
+ image: Image | null;
159
+ target: {
160
+ type: string;
161
+ id: string;
162
+ };
163
+ sponsored?: undefined;
164
+ }
165
+ export interface Sponsorship {
166
+ sponsor_name: string;
167
+ click_url: string;
168
+ }
169
+ export interface SponsoredRailItem extends Omit<EntryRailItem, "sponsored"> {
170
+ sponsored: Sponsorship;
171
+ }
172
+ export type RailItem = EntryRailItem | SponsoredRailItem;
173
+ export interface Rail extends Catalog {
174
+ slug: string;
175
+ title: string | null;
176
+ layout: string;
177
+ items: RailItem[];
178
+ }
179
+ export interface Screen extends Catalog {
180
+ slug: string;
181
+ rails: Omit<Rail, "catalog_version">[];
182
+ }
183
+ export interface Theme extends Catalog {
184
+ name: string;
185
+ slug: string;
186
+ primaryColor?: string | null;
187
+ secondaryColor?: string | null;
188
+ backgroundColor?: string | null;
189
+ surfaceColor?: string | null;
190
+ textColor?: string | null;
191
+ textMutedColor?: string | null;
192
+ borderColor?: string | null;
193
+ borderRadius?: string | null;
194
+ fontFamily?: string | null;
195
+ fontSize?: string | null;
196
+ }
197
+ export interface PlaybackCaption {
198
+ srclang: string;
199
+ label: string;
200
+ url: string;
201
+ }
202
+ export interface Playback {
203
+ hls_url: string;
204
+ expires_at: number;
205
+ thumbnail_url: string | null;
206
+ captions: PlaybackCaption[];
207
+ }
208
+ type PlaybackBase = {
209
+ id: string;
210
+ duration_ms: number | null;
211
+ };
212
+ type ReadyPlayback = PlaybackBase & {
213
+ status: "ready";
214
+ playback: Playback;
215
+ };
216
+ export interface PrerollDecision {
217
+ id: string;
218
+ sponsor_name: string;
219
+ click_url: string;
220
+ creative: ReadyPlayback;
221
+ }
222
+ export type PlaybackSession = ((PlaybackBase & {
223
+ status: Exclude<VideoStatus, "ready">;
224
+ playback: null;
225
+ }) | ReadyPlayback) & {
226
+ preroll: PrerollDecision | null;
227
+ };
228
+ export type ModelFieldKind = "text" | "rich_text" | "integer" | "bigint" | "float" | "boolean" | "date" | "datetime" | "uuid" | "entry" | "entries" | "choice" | "video" | "image" | "images" | "term" | "terms";
229
+ export interface ModelField {
230
+ key: string;
231
+ label: string;
232
+ kind: ModelFieldKind;
233
+ required: boolean;
234
+ envelope: boolean;
235
+ operators: FilterOperator[];
236
+ sortable: boolean;
237
+ target: string | null;
238
+ deprecated?: boolean;
239
+ taxonomy?: string;
240
+ options?: string[];
241
+ }
242
+ export interface ModelType {
243
+ key: string;
244
+ label: string;
245
+ fields: ModelField[];
246
+ }
247
+ export interface ModelDocument extends Catalog {
248
+ items: ModelType[];
249
+ next: null;
250
+ }
251
+ export interface WatchCatalogOptions {
252
+ since?: number;
253
+ intervalMs?: number;
254
+ onChange: (newVersion: number, previousVersion: number) => void;
255
+ onError?: (error: unknown) => void;
256
+ }
257
+ export interface CatalogWatcher {
258
+ stop(): void;
259
+ }
260
+ export interface Client<Schema extends {
261
+ [Key in keyof Schema]: EntryEnvelope;
262
+ } = DefaultSchema> {
263
+ viewer(options?: RequestOptions): Promise<Viewer>;
264
+ like(entryId: string, options?: RequestOptions): Promise<LikeState>;
265
+ unlike(entryId: string, options?: RequestOptions): Promise<LikeState>;
266
+ interactions(entryIds: readonly string[], options?: RequestOptions): Promise<Interactions>;
267
+ comments(entryId: string, options?: CommentsOptions): Promise<CommentPage>;
268
+ comment(entryId: string, options: CommentOptions): Promise<EntryComment>;
269
+ report(commentId: string, options?: RequestOptions): Promise<void>;
270
+ poll(entryId: string, options?: RequestOptions): Promise<EntryPoll>;
271
+ vote(pollId: string, optionId: string, options?: RequestOptions): Promise<EntryPoll>;
272
+ list<Type extends Extract<keyof Schema, string>>(type: Type, options?: ListOptions): Promise<Page<Schema[Type]>>;
273
+ get<Type extends Extract<keyof Schema, string>>(type: Type, id: string, options?: GetOptions): Promise<Schema[Type]>;
274
+ search<Type extends Extract<keyof Schema, string>>(query: string, options: TypedSearchOptions<Type>): Promise<SearchPage<Schema, Type>>;
275
+ search(query: string, options?: SearchOptions): Promise<SearchPage<Schema, Extract<keyof Schema, string>>>;
276
+ taxonomy(slug: string, options?: RequestOptions): Promise<Taxonomy>;
277
+ rail(slug: string, options?: RequestOptions): Promise<Rail>;
278
+ screen(slug: string, options?: RequestOptions): Promise<Screen>;
279
+ theme(slug: string, options?: RequestOptions): Promise<Theme>;
280
+ play(id: string, options?: RequestOptions): Promise<PlaybackSession>;
281
+ catalog(options?: RequestOptions): Promise<Catalog>;
282
+ model(options?: RequestOptions): Promise<ModelDocument>;
283
+ watchCatalog(options: WatchCatalogOptions): CatalogWatcher;
284
+ }
285
+ export {};
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@caasx/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Fetch client, TypeScript types and type generator for the caasX delivery API.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/JoppaDigital/caasx.git",
10
+ "directory": "packages/sdk"
11
+ },
12
+ "publishConfig": {
13
+ "access": "public"
14
+ },
15
+ "main": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js",
21
+ "default": "./dist/index.js"
22
+ }
23
+ },
24
+ "bin": {
25
+ "caasx": "./dist/cli.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "README.md",
30
+ "CHANGELOG.md"
31
+ ],
32
+ "sideEffects": false,
33
+ "engines": {
34
+ "node": ">=22"
35
+ },
36
+ "devDependencies": {
37
+ "@types/node": "^22.20.4",
38
+ "typescript": "^6.0.3",
39
+ "vitest": "^4.1.5"
40
+ },
41
+ "scripts": {
42
+ "build": "pnpm run clean && tsc -p tsconfig.build.json --removeComments --declaration false && tsc -p tsconfig.build.json --emitDeclarationOnly",
43
+ "clean": "node --input-type=module -e \"import { rmSync } from 'node:fs'; rmSync('dist', { recursive: true, force: true });\"",
44
+ "test": "vitest run",
45
+ "typecheck": "tsc --noEmit"
46
+ }
6
47
  }