@moltcms-sdk/client 0.2.1

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 ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,107 @@
1
+ # @moltcms-sdk/client
2
+
3
+ Typed, authenticated client for the moltcms incremental-sync SSE endpoint.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install @moltcms-sdk/client
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ `openSyncStream` uses `fetch`, not the native `EventSource`, so it can send the
14
+ required Bearer API key. `onChange` may be asynchronous; changes are delivered
15
+ one at a time and the completion cursor is not emitted until each handler has
16
+ finished successfully.
17
+
18
+ ```ts
19
+ import { openSyncStream, type DeliveryItem } from "@moltcms-sdk/client";
20
+
21
+ const stream = openSyncStream<DeliveryItem>(
22
+ "https://api.example.com/tenants/tenant-id/sync",
23
+ {
24
+ onChange: async (item, seq) => {
25
+ await persistChange(item, seq);
26
+ },
27
+ onComplete: async (cursor) => {
28
+ await persistCursor(cursor);
29
+ },
30
+ onError: (message) => console.error("moltcms sync error:", message),
31
+ onTransportError: (error) => console.error("moltcms transport error:", error),
32
+ },
33
+ {
34
+ apiKey: process.env.MOLTCMS_READ_KEY!,
35
+ cursor: await loadCursor(),
36
+ },
37
+ );
38
+
39
+ ```
40
+
41
+ Call `stream.close()` only when the consumer is shutting down or the sync is no
42
+ longer needed; it aborts the active request and disables reconnects.
43
+
44
+ After an interrupted connection, the client reuses the last successfully
45
+ handled change event id as `Last-Event-ID`. On the next fresh sync, pass the
46
+ opaque cursor received by `onComplete` through the `cursor` option instead.
47
+
48
+ The default `autoClose: true` stops the stream after a `sync-complete` or
49
+ server `error` event. Set `autoClose: false` to reconnect after each completed
50
+ cycle.
51
+
52
+ ## Generated, schema-safe items
53
+
54
+ The API-key endpoint `GET /tenants/{tenant}/sync/schemas` exposes the current
55
+ schema definitions. Generate an importable type module before compiling the
56
+ consumer:
57
+
58
+ ```sh
59
+ npx moltcms-sdk-codegen \
60
+ --sync-url https://api.example.com/tenants/tenant-id/sync \
61
+ --api-key "$MOLTCMS_READ_KEY" \
62
+ --output src/moltcms-schema.ts
63
+ ```
64
+
65
+ Use the generated map with `openTypedSyncStream`:
66
+
67
+ ```ts
68
+ import { openTypedSyncStream } from "@moltcms-sdk/client";
69
+ import {
70
+ schemaVersions,
71
+ type MoltcmsSchemas,
72
+ } from "./moltcms-schema.js";
73
+
74
+ openTypedSyncStream<MoltcmsSchemas>(
75
+ "https://api.example.com/tenants/tenant-id/sync",
76
+ {
77
+ onChange: async (item) => {
78
+ if (item.type === "content" && item.content_type === "post") {
79
+ await persistPost(item.data.title);
80
+ }
81
+ },
82
+ },
83
+ {
84
+ apiKey: process.env.MOLTCMS_READ_KEY!,
85
+ schemaVersions,
86
+ },
87
+ );
88
+ ```
89
+
90
+ For every content item, the client retrieves and validates the exact
91
+ `(content_type, schema_version)` before calling `onChange`. A version absent
92
+ from the generated module fails closed; regenerate after a schema change before
93
+ accepting data written with that version. The API intentionally does not cast
94
+ old content to the latest schema.
95
+
96
+ ## Publishing
97
+
98
+ Pushing a tag named `v<package.json version>` runs the release workflow. Before
99
+ the first release, configure npm Trusted Publishing with:
100
+
101
+ - Package: `@moltcms-sdk/client`
102
+ - Organization: `smartcrabai`
103
+ - Repository: `moltcms-sdk`
104
+ - Workflow filename: `release.yml`
105
+ - Environment: leave empty
106
+
107
+ The workflow publishes with npm provenance.
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env node
2
+ import type { ContentSchema } from "./types.js";
3
+ /** Renders an importable TypeScript schema map from moltcms schema metadata. */
4
+ export declare function generateSchemaTypes(schemas: readonly ContentSchema[]): string;
@@ -0,0 +1,80 @@
1
+ #!/usr/bin/env node
2
+ import { writeFile } from "node:fs/promises";
3
+ import { pathToFileURL } from "node:url";
4
+ import { fetchSyncSchemas } from "./schema-client.js";
5
+ /** Renders an importable TypeScript schema map from moltcms schema metadata. */
6
+ export function generateSchemaTypes(schemas) {
7
+ const ordered = [...schemas].sort((left, right) => left.content_type.localeCompare(right.content_type));
8
+ const schemaBlocks = ordered.map(renderSchema).join("\n");
9
+ const versions = Object.fromEntries(ordered.map((schema) => [schema.content_type, [schema.version]]));
10
+ return `// Generated by @moltcms-sdk/client. Do not edit.\nimport type { SchemaVersionIndex } from "@moltcms-sdk/client";\n\nexport interface MoltcmsSchemas {\n${schemaBlocks}}\n\nexport const schemaVersions = ${JSON.stringify(versions, null, "\t")} as const satisfies SchemaVersionIndex<MoltcmsSchemas>;\n`;
11
+ }
12
+ function renderSchema(schema) {
13
+ const fields = schema.fields.map(renderField).join("\n");
14
+ return `\t${JSON.stringify(schema.content_type)}: {\n\t\t${schema.version}: {\n${fields}\n\t\t};\n\t};\n`;
15
+ }
16
+ function renderField(field) {
17
+ const property = JSON.stringify(field.name);
18
+ const value = renderFieldValue(field);
19
+ const definition = field.required
20
+ ? `${property}: ${value}`
21
+ : `${property}?: ${value} | null`;
22
+ return `\t\t\t${definition};`;
23
+ }
24
+ function renderFieldValue(field) {
25
+ switch (field.kind) {
26
+ case "string":
27
+ case "text":
28
+ case "datetime":
29
+ return "string";
30
+ case "number":
31
+ return "number";
32
+ case "boolean":
33
+ return "boolean";
34
+ case "image":
35
+ case "relation":
36
+ return field.multiple ? "string[]" : "string";
37
+ case "select": {
38
+ const options = field.options
39
+ .map((option) => JSON.stringify(option))
40
+ .join(" | ");
41
+ const value = options.length === 0 ? "never" : options;
42
+ return field.multiple ? `(${value})[]` : value;
43
+ }
44
+ case "richtext":
45
+ case "json":
46
+ return "unknown";
47
+ }
48
+ }
49
+ async function main() {
50
+ const args = parseArguments(process.argv.slice(2));
51
+ const schemas = await fetchSyncSchemas(args.syncUrl, { apiKey: args.apiKey });
52
+ await writeFile(args.output, generateSchemaTypes(schemas));
53
+ }
54
+ function parseArguments(args) {
55
+ const values = {};
56
+ for (let index = 0; index < args.length; index += 2) {
57
+ const option = args[index];
58
+ const value = args[index + 1];
59
+ if (option === undefined ||
60
+ value === undefined ||
61
+ !option.startsWith("--")) {
62
+ throw new TypeError("Usage: moltcms-sdk-codegen --sync-url <url> --api-key <key> --output <file>");
63
+ }
64
+ values[option.slice(2)] = value;
65
+ }
66
+ const syncUrl = values["sync-url"];
67
+ const apiKey = values["api-key"];
68
+ const output = values.output;
69
+ if (syncUrl === undefined || apiKey === undefined || output === undefined) {
70
+ throw new TypeError("Usage: moltcms-sdk-codegen --sync-url <url> --api-key <key> --output <file>");
71
+ }
72
+ return { syncUrl, apiKey, output };
73
+ }
74
+ if (process.argv[1] !== undefined &&
75
+ import.meta.url === pathToFileURL(process.argv[1]).href) {
76
+ main().catch((error) => {
77
+ console.error(error);
78
+ process.exitCode = 1;
79
+ });
80
+ }
@@ -0,0 +1,7 @@
1
+ export { openSyncStream, SyncHttpError } from "./sync-stream.js";
2
+ export type { SyncStream, SyncStreamHandlers, SyncStreamOptions, SyncFetch, } from "./sync-stream.js";
3
+ export { fetchSyncSchemas, fetchSyncSchemaVersion, schemaCollectionUrl, SyncSchemaHttpError, } from "./schema-client.js";
4
+ export type { SyncSchemaRequestOptions } from "./schema-client.js";
5
+ export { openTypedSyncStream, SyncItemValidationError, UnknownGeneratedSchemaVersionError, } from "./typed-sync-stream.js";
6
+ export type { SchemaTypeMap, SchemaVersionIndex, TypedDeliveryItem, TypedSyncStreamHandlers, TypedSyncStreamOptions, } from "./typed-sync-stream.js";
7
+ export type { ContentChange, ContentDeleted, ContentSchema, ContentType, DeliveryItem, FieldDef, FieldType, SchemaChanged, } from "./types.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { openSyncStream, SyncHttpError } from "./sync-stream.js";
2
+ export { fetchSyncSchemas, fetchSyncSchemaVersion, schemaCollectionUrl, SyncSchemaHttpError, } from "./schema-client.js";
3
+ export { openTypedSyncStream, SyncItemValidationError, UnknownGeneratedSchemaVersionError, } from "./typed-sync-stream.js";
@@ -0,0 +1,22 @@
1
+ import type { ContentSchema } from "./types.js";
2
+ import type { SyncFetch } from "./sync-stream.js";
3
+ export interface SyncSchemaRequestOptions {
4
+ /** Read-only API key sent as `Authorization: Bearer <apiKey>`. */
5
+ apiKey: string;
6
+ /** Overrides the transport, for example to instrument requests. */
7
+ fetch?: SyncFetch;
8
+ /** Cancels the schema request when aborted. */
9
+ signal?: AbortSignal;
10
+ }
11
+ /** An unsuccessful HTTP response while retrieving schema metadata. */
12
+ export declare class SyncSchemaHttpError extends Error {
13
+ readonly status: number;
14
+ readonly statusText: string;
15
+ constructor(response: Response);
16
+ }
17
+ /** Retrieves the current schema for each content type accessible to this API key. */
18
+ export declare function fetchSyncSchemas(syncUrl: string, options: SyncSchemaRequestOptions): Promise<ContentSchema[]>;
19
+ /** Retrieves the schema whose version exactly matches a sync content item. */
20
+ export declare function fetchSyncSchemaVersion(syncUrl: string, contentType: string, version: number, options: SyncSchemaRequestOptions): Promise<ContentSchema>;
21
+ /** Derives the API-key schema collection endpoint from a `/sync` endpoint URL. */
22
+ export declare function schemaCollectionUrl(syncUrl: string): URL;
@@ -0,0 +1,52 @@
1
+ /** An unsuccessful HTTP response while retrieving schema metadata. */
2
+ export class SyncSchemaHttpError extends Error {
3
+ status;
4
+ statusText;
5
+ constructor(response) {
6
+ super(`Sync schema request failed with HTTP ${response.status} ${response.statusText}`);
7
+ this.name = "SyncSchemaHttpError";
8
+ this.status = response.status;
9
+ this.statusText = response.statusText;
10
+ }
11
+ }
12
+ /** Retrieves the current schema for each content type accessible to this API key. */
13
+ export async function fetchSyncSchemas(syncUrl, options) {
14
+ return requestSchemaJson(schemaCollectionUrl(syncUrl), options);
15
+ }
16
+ /** Retrieves the schema whose version exactly matches a sync content item. */
17
+ export async function fetchSyncSchemaVersion(syncUrl, contentType, version, options) {
18
+ if (!Number.isSafeInteger(version) || version < 1) {
19
+ throw new RangeError("Schema version must be a positive safe integer");
20
+ }
21
+ const url = schemaCollectionUrl(syncUrl);
22
+ url.pathname += `/${encodeURIComponent(contentType)}/${version}`;
23
+ return requestSchemaJson(url, options);
24
+ }
25
+ /** Derives the API-key schema collection endpoint from a `/sync` endpoint URL. */
26
+ export function schemaCollectionUrl(syncUrl) {
27
+ const base = typeof location === "undefined" ? undefined : location.href;
28
+ const url = new URL(syncUrl, base);
29
+ if (!url.pathname.endsWith("/sync")) {
30
+ throw new TypeError("The sync URL must end with /sync");
31
+ }
32
+ url.pathname += "/schemas";
33
+ url.search = "";
34
+ url.hash = "";
35
+ return url;
36
+ }
37
+ async function requestSchemaJson(url, options) {
38
+ if (options.apiKey.length === 0) {
39
+ throw new TypeError("SyncSchemaRequestOptions.apiKey must not be empty");
40
+ }
41
+ const request = options.fetch ?? globalThis.fetch;
42
+ const response = await request(url, {
43
+ headers: {
44
+ accept: "application/json",
45
+ authorization: `Bearer ${options.apiKey}`,
46
+ },
47
+ signal: options.signal,
48
+ });
49
+ if (!response.ok)
50
+ throw new SyncSchemaHttpError(response);
51
+ return (await response.json());
52
+ }
@@ -0,0 +1,49 @@
1
+ import type { DeliveryItem } from "./types.js";
2
+ /** A fetch implementation used to open the sync stream. */
3
+ export type SyncFetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
4
+ export interface SyncStreamHandlers<Item> {
5
+ /** A content or schema change. `seq` is the raw SSE event id. */
6
+ onChange: (item: Item, seq: string) => void | Promise<void>;
7
+ /** The feed is fully drained; persist this opaque cursor for the next run. */
8
+ onComplete?: (cursor: string) => void | Promise<void>;
9
+ /** A server-sent `error` event. */
10
+ onError?: (message: string) => void | Promise<void>;
11
+ /** Network, HTTP-status, malformed-payload, or consumer-handler failures. */
12
+ onTransportError?: (error: unknown) => void | Promise<void>;
13
+ }
14
+ export interface SyncStreamOptions {
15
+ /** Read-only API key sent as `Authorization: Bearer <apiKey>`. */
16
+ apiKey: string;
17
+ /** Opaque cursor from the preceding `sync-complete` event. */
18
+ cursor?: string;
19
+ /** Selects the published (default) or draft feed. */
20
+ kind?: "published" | "draft";
21
+ /** Stops after `sync-complete` or server `error`; defaults to `true`. */
22
+ autoClose?: boolean;
23
+ /** Cancels the stream when aborted. */
24
+ signal?: AbortSignal;
25
+ /** Overrides the transport, for example to instrument requests. */
26
+ fetch?: SyncFetch;
27
+ }
28
+ export interface SyncStream {
29
+ /** Stops the request and prevents any reconnect. Idempotent. */
30
+ close: () => void;
31
+ /** Whether this client has been closed. */
32
+ readonly closed: boolean;
33
+ }
34
+ /** An unsuccessful HTTP response while opening the sync feed. */
35
+ export declare class SyncHttpError extends Error {
36
+ readonly status: number;
37
+ readonly statusText: string;
38
+ constructor(response: Response);
39
+ }
40
+ /**
41
+ * Opens an authenticated, reconnecting client for a moltcms `/sync` SSE feed.
42
+ *
43
+ * `fetch` is used instead of `EventSource` because the moltcms endpoint
44
+ * requires a Bearer API key, which the browser's native EventSource cannot
45
+ * attach. After an interrupted connection the client sends the most recent
46
+ * `change` event id in `Last-Event-ID`; that header takes precedence over a
47
+ * supplied cursor on the server.
48
+ */
49
+ export declare function openSyncStream<Item = DeliveryItem>(syncUrl: string, handlers: SyncStreamHandlers<Item>, options: SyncStreamOptions): SyncStream;
@@ -0,0 +1,235 @@
1
+ /** An unsuccessful HTTP response while opening the sync feed. */
2
+ export class SyncHttpError extends Error {
3
+ status;
4
+ statusText;
5
+ constructor(response) {
6
+ super(`Sync request failed with HTTP ${response.status} ${response.statusText}`);
7
+ this.name = "SyncHttpError";
8
+ this.status = response.status;
9
+ this.statusText = response.statusText;
10
+ }
11
+ }
12
+ const DEFAULT_RETRY_MILLISECONDS = 3_000;
13
+ /**
14
+ * Opens an authenticated, reconnecting client for a moltcms `/sync` SSE feed.
15
+ *
16
+ * `fetch` is used instead of `EventSource` because the moltcms endpoint
17
+ * requires a Bearer API key, which the browser's native EventSource cannot
18
+ * attach. After an interrupted connection the client sends the most recent
19
+ * `change` event id in `Last-Event-ID`; that header takes precedence over a
20
+ * supplied cursor on the server.
21
+ */
22
+ export function openSyncStream(syncUrl, handlers, options) {
23
+ if (options.apiKey.length === 0) {
24
+ throw new TypeError("SyncStreamOptions.apiKey must not be empty");
25
+ }
26
+ const base = typeof location === "undefined" ? undefined : location.href;
27
+ const url = new URL(syncUrl, base);
28
+ if (options.cursor !== undefined)
29
+ url.searchParams.set("cursor", options.cursor);
30
+ if (options.kind !== undefined)
31
+ url.searchParams.set("kind", options.kind);
32
+ const shutdown = new AbortController();
33
+ const request = options.fetch ?? globalThis.fetch;
34
+ const autoClose = options.autoClose ?? true;
35
+ let activeRequest;
36
+ let closed = false;
37
+ let lastEventId;
38
+ let retryMilliseconds = DEFAULT_RETRY_MILLISECONDS;
39
+ const close = () => {
40
+ if (closed)
41
+ return;
42
+ closed = true;
43
+ activeRequest?.abort();
44
+ shutdown.abort();
45
+ };
46
+ const stopForExternalAbort = () => close();
47
+ if (options.signal !== undefined) {
48
+ if (options.signal.aborted)
49
+ close();
50
+ else
51
+ options.signal.addEventListener("abort", stopForExternalAbort, {
52
+ once: true,
53
+ });
54
+ }
55
+ void consume();
56
+ return {
57
+ close,
58
+ get closed() {
59
+ return closed;
60
+ },
61
+ };
62
+ async function consume() {
63
+ while (!closed) {
64
+ const controller = new AbortController();
65
+ activeRequest = controller;
66
+ const abortFromShutdown = () => controller.abort();
67
+ shutdown.signal.addEventListener("abort", abortFromShutdown, {
68
+ once: true,
69
+ });
70
+ try {
71
+ const response = await request(url, {
72
+ headers: syncHeaders(options.apiKey, lastEventId),
73
+ signal: controller.signal,
74
+ });
75
+ if (!response.ok) {
76
+ close();
77
+ await handlers.onTransportError?.(new SyncHttpError(response));
78
+ return;
79
+ }
80
+ if (response.body === null) {
81
+ throw new TypeError("Sync response did not include a body");
82
+ }
83
+ await parseSse(response.body, {
84
+ onMessage: async (message) => {
85
+ if (!closed)
86
+ await handleMessage(message);
87
+ },
88
+ onRetry: (milliseconds) => {
89
+ retryMilliseconds = milliseconds;
90
+ },
91
+ });
92
+ }
93
+ catch (error) {
94
+ if (!closed)
95
+ await handlers.onTransportError?.(error);
96
+ }
97
+ finally {
98
+ shutdown.signal.removeEventListener("abort", abortFromShutdown);
99
+ if (activeRequest === controller)
100
+ activeRequest = undefined;
101
+ }
102
+ if (!closed)
103
+ await delay(retryMilliseconds, shutdown.signal);
104
+ }
105
+ }
106
+ async function handleMessage(message) {
107
+ switch (message.event) {
108
+ case "change": {
109
+ try {
110
+ const item = JSON.parse(message.data);
111
+ await handlers.onChange(item, message.id ?? "");
112
+ if (message.id !== undefined)
113
+ lastEventId = message.id;
114
+ }
115
+ catch (error) {
116
+ // A failed consumer has not durably handled this change. Do not
117
+ // accept the completion cursor or advance Last-Event-ID past it.
118
+ close();
119
+ await handlers.onTransportError?.(error);
120
+ }
121
+ break;
122
+ }
123
+ case "sync-complete": {
124
+ try {
125
+ const cursor = JSON.parse(message.data);
126
+ if (typeof cursor !== "string") {
127
+ throw new TypeError("sync-complete data must be a JSON string");
128
+ }
129
+ if (autoClose)
130
+ close();
131
+ await handlers.onComplete?.(cursor);
132
+ }
133
+ catch (error) {
134
+ close();
135
+ await handlers.onTransportError?.(error);
136
+ }
137
+ break;
138
+ }
139
+ case "error":
140
+ if (autoClose)
141
+ close();
142
+ await handlers.onError?.(message.data);
143
+ break;
144
+ default:
145
+ break;
146
+ }
147
+ }
148
+ }
149
+ function syncHeaders(apiKey, lastEventId) {
150
+ const headers = new Headers({
151
+ accept: "text/event-stream",
152
+ authorization: `Bearer ${apiKey}`,
153
+ });
154
+ if (lastEventId !== undefined && lastEventId.length > 0) {
155
+ headers.set("last-event-id", lastEventId);
156
+ }
157
+ return headers;
158
+ }
159
+ async function parseSse(body, callbacks) {
160
+ const reader = body.getReader();
161
+ const decoder = new TextDecoder();
162
+ let buffer = "";
163
+ let event = "message";
164
+ let data = [];
165
+ let id;
166
+ const dispatch = async () => {
167
+ if (data.length > 0) {
168
+ await callbacks.onMessage({ event, data: data.join("\n"), id });
169
+ }
170
+ event = "message";
171
+ data = [];
172
+ id = undefined;
173
+ };
174
+ const processLine = async (line) => {
175
+ if (line.length === 0) {
176
+ await dispatch();
177
+ return;
178
+ }
179
+ if (line.startsWith(":"))
180
+ return;
181
+ const separator = line.indexOf(":");
182
+ const field = separator === -1 ? line : line.slice(0, separator);
183
+ const valueStart = separator === -1 ? line.length : separator + 1;
184
+ const value = line.charAt(valueStart) === " "
185
+ ? line.slice(valueStart + 1)
186
+ : line.slice(valueStart);
187
+ switch (field) {
188
+ case "event":
189
+ event = value;
190
+ break;
191
+ case "data":
192
+ data.push(value);
193
+ break;
194
+ case "id":
195
+ if (!value.includes("\0"))
196
+ id = value;
197
+ break;
198
+ case "retry": {
199
+ if (/^\d+$/.test(value))
200
+ callbacks.onRetry(Number(value));
201
+ break;
202
+ }
203
+ default:
204
+ break;
205
+ }
206
+ };
207
+ try {
208
+ while (true) {
209
+ const chunk = await reader.read();
210
+ if (chunk.done)
211
+ return;
212
+ buffer += decoder.decode(chunk.value, { stream: true });
213
+ let newline = buffer.indexOf("\n");
214
+ while (newline !== -1) {
215
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
216
+ buffer = buffer.slice(newline + 1);
217
+ await processLine(line);
218
+ newline = buffer.indexOf("\n");
219
+ }
220
+ }
221
+ }
222
+ finally {
223
+ reader.releaseLock();
224
+ }
225
+ }
226
+ function delay(milliseconds, signal) {
227
+ const { promise, resolve } = Promise.withResolvers();
228
+ const timer = setTimeout(resolve, milliseconds);
229
+ const abort = () => {
230
+ clearTimeout(timer);
231
+ resolve();
232
+ };
233
+ signal.addEventListener("abort", abort, { once: true });
234
+ return promise.finally(() => signal.removeEventListener("abort", abort));
235
+ }
@@ -0,0 +1,55 @@
1
+ import { type SyncStream, type SyncStreamOptions } from "./sync-stream.js";
2
+ import type { ContentChange, ContentDeleted, SchemaChanged } from "./types.js";
3
+ /**
4
+ * A generated mapping from content-type literals to exact schema-version data
5
+ * shapes. It intentionally has no string index signature so TypeScript keeps
6
+ * each generated content type as a discriminant.
7
+ */
8
+ export type SchemaTypeMap = object;
9
+ /** Runtime counterpart of generated schema versions, coupled to `S`. */
10
+ export type SchemaVersionIndex<S extends SchemaTypeMap> = {
11
+ readonly [ContentType in keyof S & string]: readonly (keyof S[ContentType] & number)[];
12
+ };
13
+ type TypedContentChange<S extends SchemaTypeMap> = {
14
+ [C in keyof S & string]: {
15
+ [V in keyof S[C] & number]: Omit<ContentChange, "content_type" | "schema_version" | "data"> & {
16
+ content_type: C;
17
+ schema_version: V;
18
+ data: S[C][V];
19
+ };
20
+ }[keyof S[C] & number];
21
+ }[keyof S & string];
22
+ type TypedContentDeleted<S extends SchemaTypeMap> = Omit<ContentDeleted, "content_type"> & {
23
+ content_type: keyof S & string;
24
+ };
25
+ /** A sync item narrowed to the content types and schema versions generated for `S`. */
26
+ export type TypedDeliveryItem<S extends SchemaTypeMap> = TypedContentChange<S> | TypedContentDeleted<S> | SchemaChanged;
27
+ export interface TypedSyncStreamHandlers<S extends SchemaTypeMap> {
28
+ /** A validated item whose content data has the exact generated schema type. */
29
+ onChange: (item: TypedDeliveryItem<S>, seq: string) => void | Promise<void>;
30
+ onComplete?: (cursor: string) => void | Promise<void>;
31
+ onError?: (message: string) => void | Promise<void>;
32
+ onTransportError?: (error: unknown) => void | Promise<void>;
33
+ }
34
+ export interface TypedSyncStreamOptions<S extends SchemaTypeMap> extends SyncStreamOptions {
35
+ /** Versions emitted by the generated schema module. Unknown versions are rejected. */
36
+ schemaVersions: SchemaVersionIndex<S>;
37
+ }
38
+ /** A schema version was not present in the generated type module. */
39
+ export declare class UnknownGeneratedSchemaVersionError extends Error {
40
+ constructor(contentType: string, version: number);
41
+ }
42
+ /** A received content item did not conform to its exact moltcms schema version. */
43
+ export declare class SyncItemValidationError extends Error {
44
+ constructor(message: string);
45
+ }
46
+ /**
47
+ * Opens a schema-validated sync stream.
48
+ *
49
+ * This function fetches and caches the exact `(content_type, schema_version)`
50
+ * definition for each content item. The generated `schemaVersions` index is
51
+ * checked first, so an item written against a version absent from generated
52
+ * TypeScript types fails closed instead of being cast to the latest schema.
53
+ */
54
+ export declare function openTypedSyncStream<S extends SchemaTypeMap>(syncUrl: string, handlers: TypedSyncStreamHandlers<S>, options: TypedSyncStreamOptions<S>): SyncStream;
55
+ export {};
@@ -0,0 +1,146 @@
1
+ import { fetchSyncSchemaVersion, } from "./schema-client.js";
2
+ import { openSyncStream, } from "./sync-stream.js";
3
+ /** A schema version was not present in the generated type module. */
4
+ export class UnknownGeneratedSchemaVersionError extends Error {
5
+ constructor(contentType, version) {
6
+ super(`No generated schema exists for content type ${contentType} version ${version}`);
7
+ this.name = "UnknownGeneratedSchemaVersionError";
8
+ }
9
+ }
10
+ /** A received content item did not conform to its exact moltcms schema version. */
11
+ export class SyncItemValidationError extends Error {
12
+ constructor(message) {
13
+ super(message);
14
+ this.name = "SyncItemValidationError";
15
+ }
16
+ }
17
+ /**
18
+ * Opens a schema-validated sync stream.
19
+ *
20
+ * This function fetches and caches the exact `(content_type, schema_version)`
21
+ * definition for each content item. The generated `schemaVersions` index is
22
+ * checked first, so an item written against a version absent from generated
23
+ * TypeScript types fails closed instead of being cast to the latest schema.
24
+ */
25
+ export function openTypedSyncStream(syncUrl, handlers, options) {
26
+ const schemas = new Map();
27
+ const runtimeSchemaVersions = options.schemaVersions;
28
+ const schemaOptions = {
29
+ apiKey: options.apiKey,
30
+ fetch: options.fetch,
31
+ signal: options.signal,
32
+ };
33
+ return openSyncStream(syncUrl, {
34
+ onChange: async (item, seq) => {
35
+ if (item.type === "content") {
36
+ const schema = await schemaFor(item.content_type, item.schema_version);
37
+ validateContentItem(item, schema);
38
+ }
39
+ await handlers.onChange(item, seq);
40
+ },
41
+ onComplete: handlers.onComplete,
42
+ onError: handlers.onError,
43
+ onTransportError: handlers.onTransportError,
44
+ }, options);
45
+ function schemaFor(contentType, version) {
46
+ if (!runtimeSchemaVersions[contentType]?.includes(version)) {
47
+ throw new UnknownGeneratedSchemaVersionError(contentType, version);
48
+ }
49
+ const key = `${contentType}\u0000${version}`;
50
+ let schema = schemas.get(key);
51
+ if (schema === undefined) {
52
+ schema = fetchSyncSchemaVersion(syncUrl, contentType, version, schemaOptions);
53
+ schemas.set(key, schema);
54
+ }
55
+ return schema;
56
+ }
57
+ }
58
+ function validateContentItem(item, schema) {
59
+ if (schema.content_type !== item.content_type ||
60
+ schema.version !== item.schema_version) {
61
+ throw new SyncItemValidationError(`Schema response does not match ${item.content_type} version ${item.schema_version}`);
62
+ }
63
+ const fields = new Map(schema.fields.map((field) => [field.name, field]));
64
+ for (const name of Object.keys(item.data)) {
65
+ if (!fields.has(name)) {
66
+ throw new SyncItemValidationError(`Unknown field ${name} in ${item.content_type}`);
67
+ }
68
+ }
69
+ for (const field of schema.fields)
70
+ validateField(item.data[field.name], field);
71
+ }
72
+ function validateField(value, field) {
73
+ if (value === undefined || value === null) {
74
+ if (field.required) {
75
+ throw new SyncItemValidationError(`Required field ${field.name} is missing`);
76
+ }
77
+ return;
78
+ }
79
+ const invalid = () => {
80
+ throw new SyncItemValidationError(`Field ${field.name} has an invalid value`);
81
+ };
82
+ switch (field.kind) {
83
+ case "string": {
84
+ if (typeof value !== "string")
85
+ invalid();
86
+ const stringValue = value;
87
+ const maxLength = "max_len" in field ? field.max_len : undefined;
88
+ if (maxLength !== undefined &&
89
+ maxLength !== null &&
90
+ stringValue.length > maxLength) {
91
+ invalid();
92
+ }
93
+ break;
94
+ }
95
+ case "text":
96
+ case "datetime":
97
+ if (typeof value !== "string")
98
+ invalid();
99
+ break;
100
+ case "number": {
101
+ if (typeof value !== "number" || !Number.isFinite(value))
102
+ invalid();
103
+ const numberValue = value;
104
+ const minimum = "min" in field ? field.min : undefined;
105
+ const maximum = "max" in field ? field.max : undefined;
106
+ if (minimum !== undefined && minimum !== null && numberValue < minimum)
107
+ invalid();
108
+ if (maximum !== undefined && maximum !== null && numberValue > maximum)
109
+ invalid();
110
+ if (field.integer && !Number.isInteger(numberValue))
111
+ invalid();
112
+ break;
113
+ }
114
+ case "boolean":
115
+ if (typeof value !== "boolean")
116
+ invalid();
117
+ break;
118
+ case "image":
119
+ case "relation": {
120
+ const multiple = "multiple" in field && field.multiple === true;
121
+ if (multiple) {
122
+ if (!Array.isArray(value) ||
123
+ value.some((item) => typeof item !== "string")) {
124
+ invalid();
125
+ }
126
+ }
127
+ else if (typeof value !== "string") {
128
+ invalid();
129
+ }
130
+ break;
131
+ }
132
+ case "select": {
133
+ const multiple = "multiple" in field && field.multiple === true;
134
+ const options = "options" in field ? field.options : [];
135
+ const selected = multiple ? value : [value];
136
+ if (!Array.isArray(selected) ||
137
+ selected.some((option) => typeof option !== "string" || !options.includes(option))) {
138
+ invalid();
139
+ }
140
+ break;
141
+ }
142
+ case "richtext":
143
+ case "json":
144
+ break;
145
+ }
146
+ }
@@ -0,0 +1,71 @@
1
+ /** The name of a content type within a moltcms tenant. */
2
+ export type ContentType = string;
3
+ /** A field declaration in a content schema. */
4
+ export type FieldType = {
5
+ kind: "string";
6
+ max_len?: number | null;
7
+ } | {
8
+ kind: "text";
9
+ } | {
10
+ kind: "richtext";
11
+ } | {
12
+ kind: "number";
13
+ integer?: boolean;
14
+ min?: number | null;
15
+ max?: number | null;
16
+ } | {
17
+ kind: "boolean";
18
+ } | {
19
+ kind: "datetime";
20
+ } | {
21
+ kind: "image";
22
+ multiple?: boolean;
23
+ } | {
24
+ kind: "relation";
25
+ multiple?: boolean;
26
+ target: ContentType;
27
+ } | {
28
+ kind: "select";
29
+ multiple?: boolean;
30
+ options: string[];
31
+ } | {
32
+ kind: "json";
33
+ };
34
+ /** A named field in a content schema. */
35
+ export type FieldDef = FieldType & {
36
+ name: string;
37
+ required?: boolean;
38
+ };
39
+ /** A complete, immutable version of one content type's schema. */
40
+ export interface ContentSchema {
41
+ content_type: ContentType;
42
+ version: number;
43
+ fields: FieldDef[];
44
+ }
45
+ /** The current state of a content entity. */
46
+ export interface ContentChange {
47
+ type: "content";
48
+ content_type: ContentType;
49
+ id: string;
50
+ seq: number;
51
+ schema_version: number;
52
+ /** Field values are defined by the content type's schema. */
53
+ data: Record<string, unknown>;
54
+ }
55
+ /** A content entity that must be removed from a local projection. */
56
+ export interface ContentDeleted {
57
+ type: "content_deleted";
58
+ content_type: ContentType;
59
+ id: string;
60
+ seq: number;
61
+ }
62
+ /** A versioned content-schema definition. */
63
+ export interface SchemaChanged {
64
+ type: "schema_changed";
65
+ content_type: ContentType;
66
+ seq: number;
67
+ version: number;
68
+ fields: FieldDef[];
69
+ }
70
+ /** One item sent in a `change` event on the sync feed. */
71
+ export type DeliveryItem = ContentChange | ContentDeleted | SchemaChanged;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@moltcms-sdk/client",
3
+ "version": "0.2.1",
4
+ "description": "Typed, authenticated Server-Sent Events client for moltcms incremental sync.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "bin": {
10
+ "moltcms-sdk-codegen": "./dist/codegen.js"
11
+ },
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "scripts": {
22
+ "build": "tsc -p tsconfig.build.json",
23
+ "check": "tsc -p tsconfig.build.json --noEmit && tsc -p tsconfig.test.json",
24
+ "test": "bun test",
25
+ "fmt": "biome format .",
26
+ "fmt:fix": "biome format --write .",
27
+ "lint": "oxlint .",
28
+ "lint:fix": "oxlint --fix .",
29
+ "prepublishOnly": "bun run check && bun run build"
30
+ },
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "registry": "https://registry.npmjs.org"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/smartcrabai/moltcms-sdk.git"
38
+ },
39
+ "keywords": [
40
+ "moltcms",
41
+ "sse",
42
+ "sync",
43
+ "typescript"
44
+ ],
45
+ "engines": {
46
+ "node": ">=22"
47
+ },
48
+ "devDependencies": {
49
+ "@biomejs/biome": "2.5.3",
50
+ "@types/bun": "latest",
51
+ "oxlint": "1.73.0",
52
+ "typescript": "^5.9.3"
53
+ }
54
+ }