@zveltio/sdk 2.0.8 → 3.0.0-beta.100
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/README.md +17 -4
- package/dist/build/index.d.ts +77 -0
- package/dist/build/index.d.ts.map +1 -0
- package/dist/build/index.js +157 -0
- package/dist/client.d.ts +103 -7
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +129 -28
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +21 -3
- package/dist/crdt.d.ts.map +1 -1
- package/dist/crdt.js +11 -2
- package/dist/ddl/index.d.ts +173 -0
- package/dist/ddl/index.d.ts.map +1 -0
- package/dist/ddl/index.js +33 -0
- package/dist/errors.d.ts +58 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/extension/action-refusal.d.ts +27 -0
- package/dist/extension/action-refusal.d.ts.map +1 -0
- package/dist/extension/action-refusal.js +29 -0
- package/dist/extension/capabilities.d.ts +71 -0
- package/dist/extension/capabilities.d.ts.map +1 -0
- package/dist/extension/capabilities.js +79 -0
- package/dist/extension/dates.d.ts +7 -0
- package/dist/extension/dates.d.ts.map +1 -0
- package/dist/extension/dates.js +14 -0
- package/dist/extension/index.d.ts +1570 -10
- package/dist/extension/index.d.ts.map +1 -1
- package/dist/extension/index.js +17 -1
- package/dist/extension/jsonb.d.ts +62 -0
- package/dist/extension/jsonb.d.ts.map +1 -0
- package/dist/extension/jsonb.js +64 -0
- package/dist/extension/multipart.d.ts +58 -0
- package/dist/extension/multipart.d.ts.map +1 -0
- package/dist/extension/multipart.js +61 -0
- package/dist/extension/numeric.d.ts +94 -0
- package/dist/extension/numeric.d.ts.map +1 -0
- package/dist/extension/numeric.js +162 -0
- package/dist/extension/permission-gate.d.ts +52 -0
- package/dist/extension/permission-gate.d.ts.map +1 -0
- package/dist/extension/permission-gate.js +125 -0
- package/dist/extension/reserved-paths.d.ts +10 -0
- package/dist/extension/reserved-paths.d.ts.map +1 -0
- package/dist/extension/reserved-paths.js +23 -0
- package/dist/index.d.ts +4 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/local-store.d.ts +14 -1
- package/dist/local-store.d.ts.map +1 -1
- package/dist/local-store.js +93 -16
- package/dist/offline/index.d.ts +75 -0
- package/dist/offline/index.d.ts.map +1 -0
- package/dist/offline/index.js +251 -0
- package/dist/publish/index.d.ts +94 -0
- package/dist/publish/index.d.ts.map +1 -0
- package/dist/publish/index.js +153 -0
- package/dist/realtime.d.ts +25 -1
- package/dist/realtime.d.ts.map +1 -1
- package/dist/realtime.js +53 -5
- package/dist/rpc/index.d.ts +68 -0
- package/dist/rpc/index.d.ts.map +1 -0
- package/dist/rpc/index.js +63 -0
- package/dist/schema-codegen.d.ts +84 -0
- package/dist/schema-codegen.d.ts.map +1 -0
- package/dist/schema-codegen.js +503 -0
- package/dist/schema-watcher.d.ts +10 -2
- package/dist/schema-watcher.d.ts.map +1 -1
- package/dist/schema-watcher.js +26 -13
- package/dist/studio/index.d.ts +85 -0
- package/dist/studio/index.d.ts.map +1 -0
- package/dist/studio/index.js +183 -0
- package/dist/studio/slot-owner-registry.d.ts +13 -0
- package/dist/studio/slot-owner-registry.d.ts.map +1 -0
- package/dist/studio/slot-owner-registry.js +21 -0
- package/dist/svelte.d.ts +1 -1
- package/dist/svelte.d.ts.map +1 -1
- package/dist/svelte.js +4 -2
- package/dist/sync-manager.d.ts +49 -4
- package/dist/sync-manager.d.ts.map +1 -1
- package/dist/sync-manager.js +175 -24
- package/dist/testing/index.d.ts +121 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +305 -0
- package/dist/testing/with-test-db.d.ts +119 -0
- package/dist/testing/with-test-db.d.ts.map +1 -0
- package/dist/testing/with-test-db.js +320 -0
- package/dist/tests/action-refusal.test.d.ts +2 -0
- package/dist/tests/action-refusal.test.d.ts.map +1 -0
- package/dist/tests/action-refusal.test.js +13 -0
- package/dist/tests/client.test.d.ts +2 -0
- package/dist/tests/client.test.d.ts.map +1 -0
- package/dist/tests/client.test.js +164 -0
- package/dist/tests/crdt-orset.test.d.ts +2 -0
- package/dist/tests/crdt-orset.test.d.ts.map +1 -0
- package/dist/tests/crdt-orset.test.js +23 -0
- package/dist/tests/local-store.test.js +44 -0
- package/dist/tests/migration-parse.test.d.ts +2 -0
- package/dist/tests/migration-parse.test.d.ts.map +1 -0
- package/dist/tests/migration-parse.test.js +17 -0
- package/dist/tests/multipart.test.d.ts +2 -0
- package/dist/tests/multipart.test.d.ts.map +1 -0
- package/dist/tests/multipart.test.js +37 -0
- package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
- package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
- package/dist/tests/offline-provider-crdt.test.js +206 -0
- package/dist/tests/realtime.test.d.ts +2 -0
- package/dist/tests/realtime.test.d.ts.map +1 -0
- package/dist/tests/realtime.test.js +220 -0
- package/dist/tests/reserved-paths.test.d.ts +2 -0
- package/dist/tests/reserved-paths.test.d.ts.map +1 -0
- package/dist/tests/reserved-paths.test.js +21 -0
- package/dist/tests/sync-manager.test.d.ts +2 -0
- package/dist/tests/sync-manager.test.d.ts.map +1 -0
- package/dist/tests/sync-manager.test.js +123 -0
- package/dist/tests/today-in.test.d.ts +2 -0
- package/dist/tests/today-in.test.d.ts.map +1 -0
- package/dist/tests/today-in.test.js +14 -0
- package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
- package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-actions.test.js +82 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
- package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-dependencies.test.js +27 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
- package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
- package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
- package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
- package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
- package/dist/tests/with-test-db.test.d.ts +2 -0
- package/dist/tests/with-test-db.test.d.ts.map +1 -0
- package/dist/tests/with-test-db.test.js +57 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/utils.d.ts.map +1 -1
- package/dist/utils.js +3 -1
- package/dist/validate/index.d.ts +148 -0
- package/dist/validate/index.d.ts.map +1 -0
- package/dist/validate/index.js +887 -0
- package/dist/validate/migration-parse.d.ts +22 -0
- package/dist/validate/migration-parse.d.ts.map +1 -0
- package/dist/validate/migration-parse.js +11 -0
- package/dist/validate/shared-message-keys.d.ts +16 -0
- package/dist/validate/shared-message-keys.d.ts.map +1 -0
- package/dist/validate/shared-message-keys.js +227 -0
- package/package.json +56 -4
- package/dist/client/Auth.d.ts +0 -19
- package/dist/client/Auth.d.ts.map +0 -1
- package/dist/client/Auth.js +0 -45
- package/dist/client/QueryBuilder.d.ts +0 -17
- package/dist/client/QueryBuilder.d.ts.map +0 -1
- package/dist/client/QueryBuilder.js +0 -76
- package/dist/client/RealtimeClient.d.ts +0 -22
- package/dist/client/RealtimeClient.d.ts.map +0 -1
- package/dist/client/RealtimeClient.js +0 -96
- package/dist/client/ZveltioClient.d.ts +0 -20
- package/dist/client/ZveltioClient.d.ts.map +0 -1
- package/dist/client/ZveltioClient.js +0 -78
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Offline-sync provider abstraction.
|
|
3
|
+
*
|
|
4
|
+
* The SDK ships TWO sync strategies for the Postgres ↔ client store
|
|
5
|
+
* loop, picked at construction time:
|
|
6
|
+
*
|
|
7
|
+
* - **`crdt`** (default) — bespoke field-level Last-Write-Wins merge on
|
|
8
|
+
* top of IndexedDB via `LocalStore` + `SyncManager`. Works offline,
|
|
9
|
+
* applies on reconnect, handles conflicts. No external dependency beyond
|
|
10
|
+
* the SDK + engine. Browser only: there is no store for React Native or
|
|
11
|
+
* Node (no SQLite backend).
|
|
12
|
+
*
|
|
13
|
+
* - **`electric`** — Electric 1.x shapes, served THROUGH the engine:
|
|
14
|
+
* `GET {engineUrl}/api/electric/v1/shape?collection=…`. The engine decides
|
|
15
|
+
* the table, rows and columns from the caller's grants, tenant, row rules
|
|
16
|
+
* and column permissions, and proxies Electric's Shape protocol (initial
|
|
17
|
+
* snapshot, then long-poll `live=true`). Read-only: writes go through the
|
|
18
|
+
* data API, and Electric streams them back. Requires the engine's
|
|
19
|
+
* ELECTRIC_URL + ELECTRIC_SECRET; the client never talks to Electric.
|
|
20
|
+
*
|
|
21
|
+
* `subscribe('contacts', cb)` keeps one live shape per collection and calls
|
|
22
|
+
* `cb` with every current row after each change. `pull()` brings each of
|
|
23
|
+
* `tables` up to date once.
|
|
24
|
+
*/
|
|
25
|
+
export class ElectricNotConfigured extends Error {
|
|
26
|
+
constructor(reason) {
|
|
27
|
+
super(`Electric SQL provider is not configured: ${reason}. ` +
|
|
28
|
+
`Set provider: 'crdt' for the default sync path. See docs/engine/offline-sync.md.`);
|
|
29
|
+
this.name = 'ElectricNotConfigured';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export class ElectricUnavailable extends Error {
|
|
33
|
+
constructor(reason) {
|
|
34
|
+
super(`Electric SQL is unavailable: ${reason}. ` +
|
|
35
|
+
`The engine refused the shape, reports ELECTRIC_URL / ELECTRIC_SECRET unset, or ` +
|
|
36
|
+
`the Electric service is down. Fall back to provider: 'crdt' or check the ops checklist.`);
|
|
37
|
+
this.name = 'ElectricUnavailable';
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Build the configured offline-sync provider.
|
|
42
|
+
*
|
|
43
|
+
* For `crdt` (default): returns a thin adapter around `SyncManager`.
|
|
44
|
+
*
|
|
45
|
+
* For `electric`: syncs `tables` once before resolving. Throws
|
|
46
|
+
* `ElectricNotConfigured` when there is no `fetch`, and `ElectricUnavailable`
|
|
47
|
+
* when the engine refuses a shape (401, 403, 409 with its reason, 503).
|
|
48
|
+
*/
|
|
49
|
+
export async function createOfflineProvider(config) {
|
|
50
|
+
const kind = config.provider ?? 'crdt';
|
|
51
|
+
if (kind === 'electric') {
|
|
52
|
+
return makeElectricProvider(config);
|
|
53
|
+
}
|
|
54
|
+
return makeCrdtAdapter(config);
|
|
55
|
+
}
|
|
56
|
+
// ── CRDT adapter (today's working path) ─────────────────────────────────────
|
|
57
|
+
/**
|
|
58
|
+
* The CRDT provider, wrapping `SyncManager`.
|
|
59
|
+
*
|
|
60
|
+
* It did not wrap anything. `pull()` was an empty body, `subscribe()` returned
|
|
61
|
+
* an unsubscribe that unsubscribed from nothing, and `push()` returned `0` —
|
|
62
|
+
* which is the worst of the four, because `0` reads as "there was nothing to
|
|
63
|
+
* send" rather than "I did not look". `SyncManager` was imported and then
|
|
64
|
+
* discarded with `void SyncManager`, and the interface docs a few lines up said
|
|
65
|
+
* "Today the CRDT provider wraps SyncManager" while it did not.
|
|
66
|
+
*
|
|
67
|
+
* This is the DEFAULT provider (`config.provider ?? 'crdt'`), so an application
|
|
68
|
+
* that called `createOfflineProvider({ engineUrl })` and pushed on a timer got a
|
|
69
|
+
* clean run and an empty server, forever, with nothing in any log.
|
|
70
|
+
*
|
|
71
|
+
* The store is opened but background sync is NOT started: this interface is
|
|
72
|
+
* explicitly pull/push, and a timer firing `syncNow()` underneath would make the
|
|
73
|
+
* number `push()` returns meaningless.
|
|
74
|
+
*/
|
|
75
|
+
async function makeCrdtAdapter(config) {
|
|
76
|
+
// Lazy imports keep the bundle tree-shakeable for consumers who only want the
|
|
77
|
+
// type definitions.
|
|
78
|
+
const [{ SyncManager }, { ZveltioClient }] = await Promise.all([
|
|
79
|
+
import('../sync-manager.js'),
|
|
80
|
+
import('../client.js'),
|
|
81
|
+
]);
|
|
82
|
+
const client = new ZveltioClient({ baseUrl: config.engineUrl });
|
|
83
|
+
const sync = new SyncManager(client);
|
|
84
|
+
await sync.open();
|
|
85
|
+
const tables = config.tables ?? [];
|
|
86
|
+
return {
|
|
87
|
+
kind: 'crdt',
|
|
88
|
+
async pull() {
|
|
89
|
+
// Silence here is what the old implementation was. A provider asked to
|
|
90
|
+
// pull with nothing to pull from is a configuration mistake, and saying so
|
|
91
|
+
// costs one throw; not saying so costs an empty local database that looks
|
|
92
|
+
// like an empty server.
|
|
93
|
+
if (tables.length === 0) {
|
|
94
|
+
throw new Error('createOfflineProvider: `tables` is empty, so there is nothing to pull. ' +
|
|
95
|
+
'List the collections to replicate, e.g. { tables: ["orders", "customers"] }.');
|
|
96
|
+
}
|
|
97
|
+
await sync.pull(tables);
|
|
98
|
+
},
|
|
99
|
+
async push() {
|
|
100
|
+
// The count is the drop in pending operations across the sync. Operations
|
|
101
|
+
// that failed stay pending and are therefore not counted, which is what
|
|
102
|
+
// "the number of ops sent" has to mean if the number is to be worth
|
|
103
|
+
// anything.
|
|
104
|
+
const before = await sync.getStatus();
|
|
105
|
+
await sync.syncNow();
|
|
106
|
+
const after = await sync.getStatus();
|
|
107
|
+
return Math.max(0, before.pending - after.pending);
|
|
108
|
+
},
|
|
109
|
+
subscribe(table, cb) {
|
|
110
|
+
return sync.collection(table).subscribe((rows) => cb(rows));
|
|
111
|
+
},
|
|
112
|
+
async close() {
|
|
113
|
+
await sync.stop();
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
async function makeElectricProvider(config) {
|
|
118
|
+
const doFetch = config.fetch ?? globalThis.fetch;
|
|
119
|
+
if (typeof doFetch !== 'function') {
|
|
120
|
+
throw new ElectricNotConfigured('no fetch implementation available — pass config.fetch');
|
|
121
|
+
}
|
|
122
|
+
const shapes = new Map();
|
|
123
|
+
const subscribers = new Map();
|
|
124
|
+
const loops = new Map();
|
|
125
|
+
// The engine names collections; `zvd_contacts` is accepted for the old table spelling.
|
|
126
|
+
const nameOf = (table) => table.replace(/^zvd_/, '');
|
|
127
|
+
const notify = (name) => {
|
|
128
|
+
const rows = [...(shapes.get(name)?.rows.values() ?? [])];
|
|
129
|
+
for (const cb of subscribers.get(name) ?? [])
|
|
130
|
+
cb(rows);
|
|
131
|
+
};
|
|
132
|
+
/** One Shape-protocol request. Resolves true once the shape is up to date. */
|
|
133
|
+
async function step(name, live, signal) {
|
|
134
|
+
const st = shapes.get(name) ?? { rows: new Map(), offset: '-1' };
|
|
135
|
+
shapes.set(name, st);
|
|
136
|
+
const qs = new URLSearchParams({ collection: name, offset: st.offset });
|
|
137
|
+
if (st.handle)
|
|
138
|
+
qs.set('handle', st.handle);
|
|
139
|
+
if (live)
|
|
140
|
+
qs.set('live', 'true');
|
|
141
|
+
if (live && st.cursor)
|
|
142
|
+
qs.set('cursor', st.cursor);
|
|
143
|
+
const res = await doFetch(`${config.engineUrl}/api/electric/v1/shape?${qs}`, {
|
|
144
|
+
credentials: 'include',
|
|
145
|
+
headers: config.headers,
|
|
146
|
+
signal,
|
|
147
|
+
});
|
|
148
|
+
if (!res.ok) {
|
|
149
|
+
const body = (await res.json().catch(() => ({})));
|
|
150
|
+
if (res.status === 409 && body.code === 'electric.must_refetch') {
|
|
151
|
+
// The shape was rebuilt (a rule or grant changed): start over.
|
|
152
|
+
shapes.set(name, { rows: new Map(), offset: '-1' });
|
|
153
|
+
notify(name);
|
|
154
|
+
return false;
|
|
155
|
+
}
|
|
156
|
+
if (res.status === 403 && st.rows.size) {
|
|
157
|
+
// Read access was revoked: rows held from before must not outlive it.
|
|
158
|
+
shapes.set(name, { rows: new Map(), offset: '-1' });
|
|
159
|
+
notify(name);
|
|
160
|
+
}
|
|
161
|
+
throw new ElectricUnavailable(`engine returned ${res.status}${body.code ? ` ${body.code}` : ''}: ` +
|
|
162
|
+
(body.detail ?? body.error ?? 'no detail'));
|
|
163
|
+
}
|
|
164
|
+
const messages = (await res.json());
|
|
165
|
+
st.offset = res.headers.get('electric-offset') ?? st.offset;
|
|
166
|
+
st.handle = res.headers.get('electric-handle') ?? st.handle;
|
|
167
|
+
st.cursor = res.headers.get('electric-cursor') ?? st.cursor;
|
|
168
|
+
let changed = false;
|
|
169
|
+
let upToDate = false;
|
|
170
|
+
for (const m of messages) {
|
|
171
|
+
if (m.headers.control === 'up-to-date')
|
|
172
|
+
upToDate = true;
|
|
173
|
+
if (!m.key)
|
|
174
|
+
continue;
|
|
175
|
+
changed = true;
|
|
176
|
+
if (m.headers.operation === 'delete')
|
|
177
|
+
st.rows.delete(m.key);
|
|
178
|
+
// An update carries only the changed columns.
|
|
179
|
+
else
|
|
180
|
+
st.rows.set(m.key, { ...st.rows.get(m.key), ...m.value });
|
|
181
|
+
}
|
|
182
|
+
if (changed)
|
|
183
|
+
notify(name);
|
|
184
|
+
return upToDate;
|
|
185
|
+
}
|
|
186
|
+
async function syncOnce(name) {
|
|
187
|
+
for (let i = 0; i < 1000 && !(await step(name, false)); i++)
|
|
188
|
+
;
|
|
189
|
+
}
|
|
190
|
+
function follow(name) {
|
|
191
|
+
if (loops.has(name))
|
|
192
|
+
return;
|
|
193
|
+
const ctl = new AbortController();
|
|
194
|
+
loops.set(name, ctl);
|
|
195
|
+
void (async () => {
|
|
196
|
+
let backoff = 1_000;
|
|
197
|
+
let upToDate = false;
|
|
198
|
+
while (!ctl.signal.aborted) {
|
|
199
|
+
try {
|
|
200
|
+
upToDate = await step(name, upToDate, ctl.signal);
|
|
201
|
+
backoff = 1_000;
|
|
202
|
+
}
|
|
203
|
+
catch (err) {
|
|
204
|
+
if (ctl.signal.aborted)
|
|
205
|
+
return;
|
|
206
|
+
// A refusal (403, 409) stays a refusal until something changes; retry slowly.
|
|
207
|
+
console.warn(`[offline:electric] ${name}:`, err.message);
|
|
208
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
209
|
+
backoff = Math.min(backoff * 2, 30_000);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
})();
|
|
213
|
+
}
|
|
214
|
+
const provider = {
|
|
215
|
+
kind: 'electric',
|
|
216
|
+
async pull() {
|
|
217
|
+
// A followed collection is already kept current by its live loop.
|
|
218
|
+
for (const t of config.tables ?? [])
|
|
219
|
+
if (!loops.has(nameOf(t)))
|
|
220
|
+
await syncOnce(nameOf(t));
|
|
221
|
+
},
|
|
222
|
+
async push() {
|
|
223
|
+
throw new Error('The electric provider syncs reads only: write through the data API ' +
|
|
224
|
+
'(client.collection(name).create/update/delete); Electric streams the change back.');
|
|
225
|
+
},
|
|
226
|
+
subscribe(table, cb) {
|
|
227
|
+
const name = nameOf(table);
|
|
228
|
+
const set = subscribers.get(name) ?? new Set();
|
|
229
|
+
subscribers.set(name, set);
|
|
230
|
+
set.add(cb);
|
|
231
|
+
follow(name);
|
|
232
|
+
return () => {
|
|
233
|
+
set.delete(cb);
|
|
234
|
+
if (set.size === 0) {
|
|
235
|
+
subscribers.delete(name);
|
|
236
|
+
loops.get(name)?.abort();
|
|
237
|
+
loops.delete(name);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
},
|
|
241
|
+
async close() {
|
|
242
|
+
for (const ctl of loops.values())
|
|
243
|
+
ctl.abort();
|
|
244
|
+
loops.clear();
|
|
245
|
+
subscribers.clear();
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
// Fail at creation, as the token mint did, when the engine refuses.
|
|
249
|
+
await provider.pull();
|
|
250
|
+
return provider;
|
|
251
|
+
}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publish primitives for `zveltio extension publish` (S4-05).
|
|
3
|
+
*
|
|
4
|
+
* Pure functions: WebCrypto Ed25519 keypairs, archive hashing, signature
|
|
5
|
+
* envelope shape that matches the engine's verifier (S1-01). No filesystem,
|
|
6
|
+
* no HTTP — the CLI layers those on top.
|
|
7
|
+
*
|
|
8
|
+
* Storage format: JWK. We pick JWK over PKCS#8 because it is JSON-native
|
|
9
|
+
* (one file per key, plain `Bun.write`), works in Cloudflare Workers without
|
|
10
|
+
* conversion, and survives copy-paste through environment variables.
|
|
11
|
+
*
|
|
12
|
+
* Signature shape mirrors `ExtensionSignature` in
|
|
13
|
+
* `packages/engine/src/lib/signature-verify.ts` so the engine can verify
|
|
14
|
+
* archives produced here without translation.
|
|
15
|
+
*/
|
|
16
|
+
/** Stored keypair format. Matches WebCrypto JWK + a Zveltio-specific keyId. */
|
|
17
|
+
export interface ZveltioKeypair {
|
|
18
|
+
/** Stable identifier; default is a short random hex string. */
|
|
19
|
+
keyId: string;
|
|
20
|
+
/** Created-at, RFC 3339. Informational. */
|
|
21
|
+
createdAt: string;
|
|
22
|
+
/** Public half — safe to share. */
|
|
23
|
+
publicJwk: JsonWebKey;
|
|
24
|
+
/** Private half — keep on disk + permission 600. */
|
|
25
|
+
privateJwk: JsonWebKey;
|
|
26
|
+
}
|
|
27
|
+
/** Signature envelope written next to `<archive>.zvext` as `<archive>.zvext.sig`. */
|
|
28
|
+
export interface ExtensionSignature {
|
|
29
|
+
algorithm: 'ed25519';
|
|
30
|
+
/** Base64 of the 64-byte Ed25519 signature. */
|
|
31
|
+
signature: string;
|
|
32
|
+
/** Hex of sha256(archive bytes). */
|
|
33
|
+
bundleSha256: string;
|
|
34
|
+
/** RFC 3339, informational. */
|
|
35
|
+
signedAt: string;
|
|
36
|
+
/** Key identifier — engine looks this up in its trusted keys list. */
|
|
37
|
+
keyId: string;
|
|
38
|
+
}
|
|
39
|
+
declare function bytesToHex(bytes: ArrayBuffer | Uint8Array): string;
|
|
40
|
+
declare function bytesToBase64(bytes: Uint8Array): string;
|
|
41
|
+
declare function base64ToBytes(b64: string): Uint8Array;
|
|
42
|
+
/** Compute sha256(bytes) → lowercase hex. */
|
|
43
|
+
export declare function sha256Hex(bytes: Uint8Array): Promise<string>;
|
|
44
|
+
/**
|
|
45
|
+
* Generate a fresh Ed25519 keypair.
|
|
46
|
+
*
|
|
47
|
+
* @param keyId Optional stable identifier. If omitted, generates a short
|
|
48
|
+
* random hex string. Useful to keep human-readable
|
|
49
|
+
* ("zveltio-prod-2026") or to scope per-publisher.
|
|
50
|
+
*/
|
|
51
|
+
export declare function generateKeypair(keyId?: string): Promise<ZveltioKeypair>;
|
|
52
|
+
/** Import a private JWK back into a CryptoKey usable for signing. */
|
|
53
|
+
export declare function importPrivateKey(jwk: JsonWebKey): Promise<CryptoKey>;
|
|
54
|
+
/** Import a public JWK back into a CryptoKey usable for verification. */
|
|
55
|
+
export declare function importPublicKey(jwk: JsonWebKey): Promise<CryptoKey>;
|
|
56
|
+
/**
|
|
57
|
+
* Build the signature envelope for a given archive.
|
|
58
|
+
*
|
|
59
|
+
* Signs over the UTF-8 bytes of the lowercase hex sha256 — same shape the
|
|
60
|
+
* engine verifier (`verifySignature`) expects. Stays away from signing the
|
|
61
|
+
* raw archive directly so the signature payload is a fixed 64 bytes
|
|
62
|
+
* regardless of archive size.
|
|
63
|
+
*/
|
|
64
|
+
export declare function signBundle(archive: Uint8Array, keypair: ZveltioKeypair): Promise<ExtensionSignature>;
|
|
65
|
+
/**
|
|
66
|
+
* Verify a signature against an archive — symmetric to the engine's
|
|
67
|
+
* `verifySignature`. Returned errors are plain strings so the CLI can
|
|
68
|
+
* print them without leaking internal types.
|
|
69
|
+
*/
|
|
70
|
+
export declare function verifyBundle(archive: Uint8Array, signature: ExtensionSignature, publicJwk: JsonWebKey): Promise<{
|
|
71
|
+
ok: true;
|
|
72
|
+
} | {
|
|
73
|
+
ok: false;
|
|
74
|
+
reason: string;
|
|
75
|
+
}>;
|
|
76
|
+
/**
|
|
77
|
+
* Convenience: derive a registry-style "trusted key" entry from a public
|
|
78
|
+
* JWK so a publisher can copy-paste it into the engine's
|
|
79
|
+
* `REGISTRY_PUBLIC_KEYS_JSON` env (or hand it to the registry admin).
|
|
80
|
+
*
|
|
81
|
+
* Returns `{ keyId, publicKeyHex }` — exact shape the engine's
|
|
82
|
+
* `registry-keys.ts` parser expects.
|
|
83
|
+
*/
|
|
84
|
+
export declare function exportTrustedKeyEntry(keyId: string, publicJwk: JsonWebKey): Promise<{
|
|
85
|
+
keyId: string;
|
|
86
|
+
publicKeyHex: string;
|
|
87
|
+
}>;
|
|
88
|
+
export declare const _bytes: {
|
|
89
|
+
bytesToHex: typeof bytesToHex;
|
|
90
|
+
bytesToBase64: typeof bytesToBase64;
|
|
91
|
+
base64ToBytes: typeof base64ToBytes;
|
|
92
|
+
};
|
|
93
|
+
export {};
|
|
94
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/publish/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,+EAA+E;AAC/E,MAAM,WAAW,cAAc;IAC7B,+DAA+D;IAC/D,KAAK,EAAE,MAAM,CAAC;IACd,2CAA2C;IAC3C,SAAS,EAAE,MAAM,CAAC;IAClB,mCAAmC;IACnC,SAAS,EAAE,UAAU,CAAC;IACtB,oDAAoD;IACpD,UAAU,EAAE,UAAU,CAAC;CACxB;AAED,qFAAqF;AACrF,MAAM,WAAW,kBAAkB;IACjC,SAAS,EAAE,SAAS,CAAC;IACrB,+CAA+C;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,oCAAoC;IACpC,YAAY,EAAE,MAAM,CAAC;IACrB,+BAA+B;IAC/B,QAAQ,EAAE,MAAM,CAAC;IACjB,sEAAsE;IACtE,KAAK,EAAE,MAAM,CAAC;CACf;AAED,iBAAS,UAAU,CAAC,KAAK,EAAE,WAAW,GAAG,UAAU,GAAG,MAAM,CAK3D;AAED,iBAAS,aAAa,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAKhD;AAED,iBAAS,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAO9C;AAED,6CAA6C;AAC7C,wBAAsB,SAAS,CAAC,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAGlE;AAED;;;;;;GAMG;AACH,wBAAsB,eAAe,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAY7E;AAQD,qEAAqE;AACrE,wBAAsB,gBAAgB,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,CAE1E;AAED,yEAAyE;AACzE,wBAAsB,eAAe,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,CAAC,SAAS,CAAC,CAEzE;AAED;;;;;;;GAOG;AACH,wBAAsB,UAAU,CAC9B,OAAO,EAAE,UAAU,EACnB,OAAO,EAAE,cAAc,GACtB,OAAO,CAAC,kBAAkB,CAAC,CAa7B;AAED;;;;GAIG;AACH,wBAAsB,YAAY,CAChC,OAAO,EAAE,UAAU,EACnB,SAAS,EAAE,kBAAkB,EAC7B,SAAS,EAAE,UAAU,GACpB,OAAO,CAAC;IAAE,EAAE,EAAE,IAAI,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CA+BvD;AAED;;;;;;;GAOG;AACH,wBAAsB,qBAAqB,CACzC,KAAK,EAAE,MAAM,EACb,SAAS,EAAE,UAAU,GACpB,OAAO,CAAC;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,MAAM,CAAA;CAAE,CAAC,CASlD;AAGD,eAAO,MAAM,MAAM;;;;CAA+C,CAAC"}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Publish primitives for `zveltio extension publish` (S4-05).
|
|
3
|
+
*
|
|
4
|
+
* Pure functions: WebCrypto Ed25519 keypairs, archive hashing, signature
|
|
5
|
+
* envelope shape that matches the engine's verifier (S1-01). No filesystem,
|
|
6
|
+
* no HTTP — the CLI layers those on top.
|
|
7
|
+
*
|
|
8
|
+
* Storage format: JWK. We pick JWK over PKCS#8 because it is JSON-native
|
|
9
|
+
* (one file per key, plain `Bun.write`), works in Cloudflare Workers without
|
|
10
|
+
* conversion, and survives copy-paste through environment variables.
|
|
11
|
+
*
|
|
12
|
+
* Signature shape mirrors `ExtensionSignature` in
|
|
13
|
+
* `packages/engine/src/lib/signature-verify.ts` so the engine can verify
|
|
14
|
+
* archives produced here without translation.
|
|
15
|
+
*/
|
|
16
|
+
function bytesToHex(bytes) {
|
|
17
|
+
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
18
|
+
let out = '';
|
|
19
|
+
for (let i = 0; i < view.length; i++)
|
|
20
|
+
out += view[i].toString(16).padStart(2, '0');
|
|
21
|
+
return out;
|
|
22
|
+
}
|
|
23
|
+
function bytesToBase64(bytes) {
|
|
24
|
+
// btoa is available in Bun + browsers. Node 22+ has it too.
|
|
25
|
+
let bin = '';
|
|
26
|
+
for (let i = 0; i < bytes.length; i++)
|
|
27
|
+
bin += String.fromCharCode(bytes[i]);
|
|
28
|
+
return btoa(bin);
|
|
29
|
+
}
|
|
30
|
+
function base64ToBytes(b64) {
|
|
31
|
+
const normalized = b64.replace(/-/g, '+').replace(/_/g, '/');
|
|
32
|
+
const padded = normalized + '='.repeat((4 - (normalized.length % 4)) % 4);
|
|
33
|
+
const bin = atob(padded);
|
|
34
|
+
const out = new Uint8Array(bin.length);
|
|
35
|
+
for (let i = 0; i < bin.length; i++)
|
|
36
|
+
out[i] = bin.charCodeAt(i);
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
/** Compute sha256(bytes) → lowercase hex. */
|
|
40
|
+
export async function sha256Hex(bytes) {
|
|
41
|
+
const buf = await crypto.subtle.digest('SHA-256', bytes);
|
|
42
|
+
return bytesToHex(buf);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Generate a fresh Ed25519 keypair.
|
|
46
|
+
*
|
|
47
|
+
* @param keyId Optional stable identifier. If omitted, generates a short
|
|
48
|
+
* random hex string. Useful to keep human-readable
|
|
49
|
+
* ("zveltio-prod-2026") or to scope per-publisher.
|
|
50
|
+
*/
|
|
51
|
+
export async function generateKeypair(keyId) {
|
|
52
|
+
const pair = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']);
|
|
53
|
+
const kp = pair;
|
|
54
|
+
const publicJwk = await crypto.subtle.exportKey('jwk', kp.publicKey);
|
|
55
|
+
const privateJwk = await crypto.subtle.exportKey('jwk', kp.privateKey);
|
|
56
|
+
const finalKeyId = keyId ?? randomKeyId();
|
|
57
|
+
return {
|
|
58
|
+
keyId: finalKeyId,
|
|
59
|
+
createdAt: new Date().toISOString(),
|
|
60
|
+
publicJwk,
|
|
61
|
+
privateJwk,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function randomKeyId() {
|
|
65
|
+
const buf = new Uint8Array(6);
|
|
66
|
+
crypto.getRandomValues(buf);
|
|
67
|
+
return 'zv-' + bytesToHex(buf);
|
|
68
|
+
}
|
|
69
|
+
/** Import a private JWK back into a CryptoKey usable for signing. */
|
|
70
|
+
export async function importPrivateKey(jwk) {
|
|
71
|
+
return await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['sign']);
|
|
72
|
+
}
|
|
73
|
+
/** Import a public JWK back into a CryptoKey usable for verification. */
|
|
74
|
+
export async function importPublicKey(jwk) {
|
|
75
|
+
return await crypto.subtle.importKey('jwk', jwk, { name: 'Ed25519' }, false, ['verify']);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Build the signature envelope for a given archive.
|
|
79
|
+
*
|
|
80
|
+
* Signs over the UTF-8 bytes of the lowercase hex sha256 — same shape the
|
|
81
|
+
* engine verifier (`verifySignature`) expects. Stays away from signing the
|
|
82
|
+
* raw archive directly so the signature payload is a fixed 64 bytes
|
|
83
|
+
* regardless of archive size.
|
|
84
|
+
*/
|
|
85
|
+
export async function signBundle(archive, keypair) {
|
|
86
|
+
const bundleSha256 = await sha256Hex(archive);
|
|
87
|
+
const key = await importPrivateKey(keypair.privateJwk);
|
|
88
|
+
const dataBytes = new TextEncoder().encode(bundleSha256.toLowerCase());
|
|
89
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
90
|
+
const sigBuf = await crypto.subtle.sign({ name: 'Ed25519' }, key, dataBytes);
|
|
91
|
+
return {
|
|
92
|
+
algorithm: 'ed25519',
|
|
93
|
+
signature: bytesToBase64(new Uint8Array(sigBuf)),
|
|
94
|
+
bundleSha256,
|
|
95
|
+
signedAt: new Date().toISOString(),
|
|
96
|
+
keyId: keypair.keyId,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Verify a signature against an archive — symmetric to the engine's
|
|
101
|
+
* `verifySignature`. Returned errors are plain strings so the CLI can
|
|
102
|
+
* print them without leaking internal types.
|
|
103
|
+
*/
|
|
104
|
+
export async function verifyBundle(archive, signature, publicJwk) {
|
|
105
|
+
if (signature.algorithm !== 'ed25519') {
|
|
106
|
+
return { ok: false, reason: `unsupported algorithm "${signature.algorithm}"` };
|
|
107
|
+
}
|
|
108
|
+
const actualHash = await sha256Hex(archive);
|
|
109
|
+
if (actualHash.toLowerCase() !== signature.bundleSha256.toLowerCase()) {
|
|
110
|
+
return {
|
|
111
|
+
ok: false,
|
|
112
|
+
reason: `bundleSha256 mismatch (expected ${signature.bundleSha256}, got ${actualHash})`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
let sigBytes;
|
|
116
|
+
try {
|
|
117
|
+
sigBytes = base64ToBytes(signature.signature);
|
|
118
|
+
}
|
|
119
|
+
catch (err) {
|
|
120
|
+
return { ok: false, reason: `signature is not valid base64: ${err.message}` };
|
|
121
|
+
}
|
|
122
|
+
if (sigBytes.length !== 64) {
|
|
123
|
+
return { ok: false, reason: `signature length ${sigBytes.length} is not 64 bytes` };
|
|
124
|
+
}
|
|
125
|
+
const key = await importPublicKey(publicJwk);
|
|
126
|
+
const dataBytes = new TextEncoder().encode(signature.bundleSha256.toLowerCase());
|
|
127
|
+
const ok = await crypto.subtle.verify({ name: 'Ed25519' }, key,
|
|
128
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
129
|
+
sigBytes,
|
|
130
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
131
|
+
dataBytes);
|
|
132
|
+
return ok ? { ok: true } : { ok: false, reason: 'Ed25519 verification failed' };
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Convenience: derive a registry-style "trusted key" entry from a public
|
|
136
|
+
* JWK so a publisher can copy-paste it into the engine's
|
|
137
|
+
* `REGISTRY_PUBLIC_KEYS_JSON` env (or hand it to the registry admin).
|
|
138
|
+
*
|
|
139
|
+
* Returns `{ keyId, publicKeyHex }` — exact shape the engine's
|
|
140
|
+
* `registry-keys.ts` parser expects.
|
|
141
|
+
*/
|
|
142
|
+
export async function exportTrustedKeyEntry(keyId, publicJwk) {
|
|
143
|
+
// Re-import as `extractable: true` — the cached `importPublicKey` produces
|
|
144
|
+
// a non-extractable key for hot-path verification. Cheap (microseconds) and
|
|
145
|
+
// keeps the exporter as a one-liner for callers.
|
|
146
|
+
const key = await crypto.subtle.importKey('jwk', publicJwk, { name: 'Ed25519' }, true, [
|
|
147
|
+
'verify',
|
|
148
|
+
]);
|
|
149
|
+
const rawBuf = await crypto.subtle.exportKey('raw', key);
|
|
150
|
+
return { keyId, publicKeyHex: bytesToHex(new Uint8Array(rawBuf)) };
|
|
151
|
+
}
|
|
152
|
+
// Re-exports for the CLI to encode/decode bytes without pulling in node:buffer.
|
|
153
|
+
export const _bytes = { bytesToHex, bytesToBase64, base64ToBytes };
|
package/dist/realtime.d.ts
CHANGED
|
@@ -1,3 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine closes a socket with this code when the session or API key it
|
|
3
|
+
* opened with is no longer valid (signed out, revoked, expired, user
|
|
4
|
+
* deactivated). Reconnecting is refused with 401, so clients stop instead.
|
|
5
|
+
*/
|
|
6
|
+
export declare const WS_UNAUTHORIZED = 4001;
|
|
7
|
+
/**
|
|
8
|
+
* A WebSocket that sends `headers` with the upgrade where the runtime can (the
|
|
9
|
+
* Bun/undici `{ headers }` second argument). A browser's constructor reads that
|
|
10
|
+
* argument as subprotocols and throws on an object, so there the socket opens
|
|
11
|
+
* without them and authenticates by the session cookie.
|
|
12
|
+
*/
|
|
13
|
+
export declare function openWebSocket(url: string, headers?: Record<string, string>): WebSocket;
|
|
1
14
|
export declare class ZveltioRealtime {
|
|
2
15
|
private ws;
|
|
3
16
|
private listeners;
|
|
@@ -5,10 +18,21 @@ export declare class ZveltioRealtime {
|
|
|
5
18
|
private reconnectAttempts;
|
|
6
19
|
private maxReconnectAttempts;
|
|
7
20
|
private reconnectTimer;
|
|
8
|
-
|
|
21
|
+
private headers;
|
|
22
|
+
private unauthorizedCallbacks;
|
|
23
|
+
/**
|
|
24
|
+
* @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
|
|
25
|
+
* for a server-side client. Bun and Node (undici) accept them; a browser
|
|
26
|
+
* cannot set headers on a WebSocket and authenticates by session cookie.
|
|
27
|
+
*/
|
|
28
|
+
constructor(baseUrl: string, options?: {
|
|
29
|
+
headers?: Record<string, string>;
|
|
30
|
+
});
|
|
9
31
|
connect(): void;
|
|
10
32
|
private attemptReconnect;
|
|
11
33
|
subscribe(collection: string, callback: (data: any) => void): () => void;
|
|
34
|
+
/** Called when the engine ends the socket because its credentials were revoked. */
|
|
35
|
+
onUnauthorized(callback: () => void): () => void;
|
|
12
36
|
disconnect(): void;
|
|
13
37
|
}
|
|
14
38
|
//# sourceMappingURL=realtime.d.ts.map
|
package/dist/realtime.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"realtime.d.ts","sourceRoot":"","sources":["../src/realtime.ts"],"names":[],"mappings":"AAAA,qBAAa,eAAe;IAC1B,OAAO,CAAC,EAAE,CAA0B;
|
|
1
|
+
{"version":3,"file":"realtime.d.ts","sourceRoot":"","sources":["../src/realtime.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,eAAO,MAAM,eAAe,OAAO,CAAC;AAEpC;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,SAAS,CAStF;AAED,qBAAa,eAAe;IAC1B,OAAO,CAAC,EAAE,CAA0B;IAEpC,OAAO,CAAC,SAAS,CAAoD;IACrE,OAAO,CAAC,OAAO,CAAS;IACxB,OAAO,CAAC,iBAAiB,CAAK;IAC9B,OAAO,CAAC,oBAAoB,CAAM;IAClC,OAAO,CAAC,cAAc,CAA8C;IACpE,OAAO,CAAC,OAAO,CAAqC;IACpD,OAAO,CAAC,qBAAqB,CAAyB;IAEtD;;;;OAIG;gBACS,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAO;IAM/E,OAAO,IAAI,IAAI;IA+Cf,OAAO,CAAC,gBAAgB;IASxB,SAAS,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,IAAI,EAAE,GAAG,KAAK,IAAI,GAAG,MAAM,IAAI;IAqBxE,mFAAmF;IACnF,cAAc,CAAC,QAAQ,EAAE,MAAM,IAAI,GAAG,MAAM,IAAI;IAKhD,UAAU,IAAI,IAAI;CAQnB"}
|
package/dist/realtime.js
CHANGED
|
@@ -1,17 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The engine closes a socket with this code when the session or API key it
|
|
3
|
+
* opened with is no longer valid (signed out, revoked, expired, user
|
|
4
|
+
* deactivated). Reconnecting is refused with 401, so clients stop instead.
|
|
5
|
+
*/
|
|
6
|
+
export const WS_UNAUTHORIZED = 4001;
|
|
7
|
+
/**
|
|
8
|
+
* A WebSocket that sends `headers` with the upgrade where the runtime can (the
|
|
9
|
+
* Bun/undici `{ headers }` second argument). A browser's constructor reads that
|
|
10
|
+
* argument as subprotocols and throws on an object, so there the socket opens
|
|
11
|
+
* without them and authenticates by the session cookie.
|
|
12
|
+
*/
|
|
13
|
+
export function openWebSocket(url, headers) {
|
|
14
|
+
if (headers && Object.keys(headers).length > 0) {
|
|
15
|
+
try {
|
|
16
|
+
return new WebSocket(url, { headers });
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
// A browser: no header can be set on a WebSocket.
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
return new WebSocket(url);
|
|
23
|
+
}
|
|
1
24
|
export class ZveltioRealtime {
|
|
2
25
|
ws = null;
|
|
26
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
3
27
|
listeners = new Map();
|
|
4
28
|
baseUrl;
|
|
5
29
|
reconnectAttempts = 0;
|
|
6
30
|
maxReconnectAttempts = 10;
|
|
7
31
|
reconnectTimer = null;
|
|
8
|
-
|
|
32
|
+
headers;
|
|
33
|
+
unauthorizedCallbacks = new Set();
|
|
34
|
+
/**
|
|
35
|
+
* @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
|
|
36
|
+
* for a server-side client. Bun and Node (undici) accept them; a browser
|
|
37
|
+
* cannot set headers on a WebSocket and authenticates by session cookie.
|
|
38
|
+
*/
|
|
39
|
+
constructor(baseUrl, options = {}) {
|
|
9
40
|
// Convert http(s) to ws(s)
|
|
10
41
|
this.baseUrl = baseUrl.replace(/^http/, 'ws');
|
|
42
|
+
this.headers = options.headers;
|
|
11
43
|
}
|
|
12
44
|
connect() {
|
|
13
45
|
const wsUrl = `${this.baseUrl}/api/ws`;
|
|
14
|
-
this.ws =
|
|
46
|
+
this.ws = openWebSocket(wsUrl, this.headers);
|
|
15
47
|
this.ws.onopen = () => {
|
|
16
48
|
this.reconnectAttempts = 0;
|
|
17
49
|
// Re-subscribe to all existing collections using the server's expected protocol
|
|
@@ -30,13 +62,23 @@ export class ZveltioRealtime {
|
|
|
30
62
|
try {
|
|
31
63
|
fn(msg);
|
|
32
64
|
}
|
|
33
|
-
catch {
|
|
65
|
+
catch {
|
|
66
|
+
/* ignore callback errors */
|
|
67
|
+
}
|
|
34
68
|
});
|
|
35
69
|
}
|
|
36
70
|
}
|
|
37
|
-
catch {
|
|
71
|
+
catch {
|
|
72
|
+
/* invalid JSON — ignore */
|
|
73
|
+
}
|
|
38
74
|
};
|
|
39
|
-
this.ws.onclose = () => {
|
|
75
|
+
this.ws.onclose = (event) => {
|
|
76
|
+
if (event?.code === WS_UNAUTHORIZED) {
|
|
77
|
+
// No retry: every attempt would be refused. `connect()` again once the
|
|
78
|
+
// app holds a valid session or key.
|
|
79
|
+
this.unauthorizedCallbacks.forEach((cb) => cb());
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
40
82
|
this.attemptReconnect();
|
|
41
83
|
};
|
|
42
84
|
this.ws.onerror = () => {
|
|
@@ -51,6 +93,7 @@ export class ZveltioRealtime {
|
|
|
51
93
|
this.reconnectAttempts++;
|
|
52
94
|
this.reconnectTimer = setTimeout(() => this.connect(), delay);
|
|
53
95
|
}
|
|
96
|
+
// biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
|
|
54
97
|
subscribe(collection, callback) {
|
|
55
98
|
if (!this.listeners.has(collection))
|
|
56
99
|
this.listeners.set(collection, new Set());
|
|
@@ -70,6 +113,11 @@ export class ZveltioRealtime {
|
|
|
70
113
|
}
|
|
71
114
|
};
|
|
72
115
|
}
|
|
116
|
+
/** Called when the engine ends the socket because its credentials were revoked. */
|
|
117
|
+
onUnauthorized(callback) {
|
|
118
|
+
this.unauthorizedCallbacks.add(callback);
|
|
119
|
+
return () => this.unauthorizedCallbacks.delete(callback);
|
|
120
|
+
}
|
|
73
121
|
disconnect() {
|
|
74
122
|
if (this.reconnectTimer)
|
|
75
123
|
clearTimeout(this.reconnectTimer);
|