@zveltio/sdk 3.0.0-beta.90 → 3.0.0-beta.91

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.
Files changed (44) hide show
  1. package/README.md +1 -1
  2. package/dist/client.d.ts +75 -5
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +78 -15
  5. package/dist/extension/index.d.ts +6 -2
  6. package/dist/extension/index.d.ts.map +1 -1
  7. package/dist/extension/index.js +1 -0
  8. package/dist/extension/reserved-paths.d.ts +10 -0
  9. package/dist/extension/reserved-paths.d.ts.map +1 -0
  10. package/dist/extension/reserved-paths.js +23 -0
  11. package/dist/index.d.ts +1 -1
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/local-store.d.ts +1 -1
  14. package/dist/local-store.d.ts.map +1 -1
  15. package/dist/local-store.js +5 -3
  16. package/dist/offline/index.d.ts +5 -4
  17. package/dist/offline/index.d.ts.map +1 -1
  18. package/dist/offline/index.js +5 -4
  19. package/dist/sync-manager.d.ts +8 -0
  20. package/dist/sync-manager.d.ts.map +1 -1
  21. package/dist/sync-manager.js +14 -1
  22. package/dist/tests/client.test.js +103 -0
  23. package/dist/tests/offline-provider-crdt.test.js +4 -2
  24. package/dist/tests/realtime.test.js +2 -91
  25. package/dist/tests/reserved-paths.test.d.ts +2 -0
  26. package/dist/tests/reserved-paths.test.d.ts.map +1 -0
  27. package/dist/tests/reserved-paths.test.js +21 -0
  28. package/dist/tests/sync-manager.test.js +58 -0
  29. package/dist/tests/validate-manifest-actions.test.js +6 -0
  30. package/dist/validate/index.d.ts.map +1 -1
  31. package/dist/validate/index.js +8 -3
  32. package/package.json +3 -3
  33. package/dist/client/Auth.d.ts +0 -19
  34. package/dist/client/Auth.d.ts.map +0 -1
  35. package/dist/client/Auth.js +0 -48
  36. package/dist/client/QueryBuilder.d.ts +0 -17
  37. package/dist/client/QueryBuilder.d.ts.map +0 -1
  38. package/dist/client/QueryBuilder.js +0 -89
  39. package/dist/client/RealtimeClient.d.ts +0 -40
  40. package/dist/client/RealtimeClient.d.ts.map +0 -1
  41. package/dist/client/RealtimeClient.js +0 -148
  42. package/dist/client/ZveltioClient.d.ts +0 -20
  43. package/dist/client/ZveltioClient.d.ts.map +0 -1
  44. package/dist/client/ZveltioClient.js +0 -89
@@ -1,40 +0,0 @@
1
- import type { RealtimeMessage } from '../types/index.js';
2
- type EventCallback = (message: RealtimeMessage) => void;
3
- type StatusCallback = (status: 'connecting' | 'connected' | 'disconnected') => void;
4
- export declare class RealtimeClient {
5
- private ws;
6
- private baseUrl;
7
- private headers;
8
- private subscriptions;
9
- private statusCallbacks;
10
- private unauthorizedCallbacks;
11
- private reconnectDelay;
12
- private maxReconnectDelay;
13
- private reconnectAttempts;
14
- private maxReconnectAttempts;
15
- private reconnectTimer;
16
- private shouldReconnect;
17
- /** Set by a 4001 close; only an explicit `connect()` clears it. */
18
- private unauthorized;
19
- /**
20
- * @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
21
- * for a server-side client (Bun, Node). A browser cannot set headers on a
22
- * WebSocket and authenticates by session cookie.
23
- */
24
- constructor(baseUrl: string, options?: {
25
- headers?: Record<string, string>;
26
- });
27
- /** Open the socket — also after a 4001, once the app has re-authenticated. */
28
- connect(): void;
29
- private open;
30
- disconnect(): void;
31
- subscribe(collection: string, event: string | '*', callback: EventCallback): () => void;
32
- onStatusChange(callback: StatusCallback): () => void;
33
- /** Called when the engine ends the socket because its credentials were revoked. */
34
- onUnauthorized(callback: () => void): () => void;
35
- private sendSubscribe;
36
- private sendUnsubscribe;
37
- private notifyStatus;
38
- }
39
- export {};
40
- //# sourceMappingURL=RealtimeClient.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"RealtimeClient.d.ts","sourceRoot":"","sources":["../../src/client/RealtimeClient.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AAEzD,KAAK,aAAa,GAAG,CAAC,O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rl;
5
- headers;
6
- subscriptions = new Map();
7
- statusCallbacks = new Set();
8
- unauthorizedCallbacks = new Set();
9
- reconnectDelay = 1000;
10
- maxReconnectDelay = 30000;
11
- reconnectAttempts = 0;
12
- maxReconnectAttempts = 10;
13
- reconnectTimer = null;
14
- shouldReconnect = true;
15
- /** Set by a 4001 close; only an explicit `connect()` clears it. */
16
- unauthorized = false;
17
- /**
18
- * @param options.headers Sent with the upgrade — e.g. `{ 'X-API-Key': key }`
19
- * for a server-side client (Bun, Node). A browser cannot set headers on a
20
- * WebSocket and authenticates by session cookie.
21
- */
22
- constructor(baseUrl, options = {}) {
23
- this.baseUrl = baseUrl;
24
- this.headers = options.headers;
25
- }
26
- /** Open the socket — also after a 4001, once the app has re-authenticated. */
27
- connect() {
28
- this.unauthorized = false;
29
- this.shouldReconnect = true;
30
- this.reconnectAttempts = 0;
31
- this.reconnectDelay = 1000;
32
- this.open();
33
- }
34
- open() {
35
- if (this.ws?.readyState === WebSocket.OPEN || this.ws?.readyState === WebSocket.CONNECTING) {
36
- return;
37
- }
38
- const wsUrl = this.baseUrl.replace(/^http/, 'ws') + '/api/ws';
39
- const ws = openWebSocket(wsUrl, this.headers);
40
- this.ws = ws;
41
- this.notifyStatus('connecting');
42
- ws.onopen = () => {
43
- this.reconnectDelay = 1000;
44
- this.reconnectAttempts = 0;
45
- this.notifyStatus('connected');
46
- // Re-subscribe all active subscriptions
47
- for (const channel of this.subscriptions.keys()) {
48
- this.sendSubscribe(channel);
49
- }
50
- };
51
- ws.onmessage = (event) => {
52
- try {
53
- const message = JSON.parse(event.data);
54
- const key = `${message.collection}:${message.event}`;
55
- const wildcard = `${message.collection}:*`;
56
- const allWildcard = `*:*`;
57
- for (const [sub, callbacks] of this.subscriptions) {
58
- if (sub === key || sub === wildcard || sub === allWildcard) {
59
- callbacks.forEach((cb) => cb(message));
60
- }
61
- }
62
- }
63
- catch {
64
- /* ignore invalid messages */
65
- }
66
- };
67
- ws.onclose = (event) => {
68
- // A socket `disconnect()` dropped still reports; one already replaced does not.
69
- if (this.ws !== ws) {
70
- if (this.ws === null)
71
- this.notifyStatus('disconnected');
72
- return;
73
- }
74
- this.notifyStatus('disconnected');
75
- if (event?.code === WS_UNAUTHORIZED) {
76
- // Credentials revoked: every retry would be refused with 401.
77
- this.unauthorized = true;
78
- this.unauthorizedCallbacks.forEach((cb) => cb());
79
- return;
80
- }
81
- // Bounded: a refused handshake (401) is not visible to a WebSocket in any
82
- // runtime — it closes as 1002/1006 — so it must not be retried forever.
83
- if (!this.shouldReconnect || this.reconnectAttempts >= this.maxReconnectAttempts)
84
- return;
85
- this.reconnectAttempts++;
86
- this.reconnectTimer = setTimeout(() => this.open(), this.reconnectDelay);
87
- this.reconnectDelay = Math.min(this.reconnectDelay * 2, this.maxReconnectDelay);
88
- };
89
- ws.onerror = () => {
90
- ws.close();
91
- };
92
- }
93
- disconnect() {
94
- this.shouldReconnect = false;
95
- if (this.reconnectTimer)
96
- clearTimeout(this.reconnectTimer);
97
- this.reconnectTimer = null;
98
- this.ws?.close();
99
- this.ws = null;
100
- }
101
- // Subscribe to events on a collection
102
- // pattern examples: 'products:insert', 'products:*', '*:*'
103
- subscribe(collection, event, callback) {
104
- const key = `${collection}:${event}`;
105
- if (!this.subscriptions.has(key)) {
106
- this.subscriptions.set(key, new Set());
107
- }
108
- this.subscriptions.get(key).add(callback);
109
- if (this.ws?.readyState === WebSocket.OPEN) {
110
- this.sendSubscribe(key);
111
- }
112
- else if (!this.unauthorized) {
113
- this.connect();
114
- }
115
- // After a 4001 the subscription is only recorded: the next explicit
116
- // `connect()` sends it. Dialling again would only be refused.
117
- // Return unsubscribe function
118
- return () => {
119
- this.subscriptions.get(key)?.delete(callback);
120
- if (this.subscriptions.get(key)?.size === 0) {
121
- this.subscriptions.delete(key);
122
- this.sendUnsubscribe(key);
123
- }
124
- };
125
- }
126
- onStatusChange(callback) {
127
- this.statusCallbacks.add(callback);
128
- return () => this.statusCallbacks.delete(callback);
129
- }
130
- /** Called when the engine ends the socket because its credentials were revoked. */
131
- onUnauthorized(callback) {
132
- this.unauthorizedCallbacks.add(callback);
133
- return () => this.unauthorizedCallbacks.delete(callback);
134
- }
135
- sendSubscribe(channel) {
136
- if (this.ws?.readyState === WebSocket.OPEN) {
137
- this.ws.send(JSON.stringify({ type: 'subscribe', channel }));
138
- }
139
- }
140
- sendUnsubscribe(channel) {
141
- if (this.ws?.readyState === WebSocket.OPEN) {
142
- this.ws.send(JSON.stringify({ type: 'unsubscribe', channel }));
143
- }
144
- }
145
- notifyStatus(status) {
146
- this.statusCallbacks.forEach((cb) => cb(status));
147
- }
148
- }
@@ -1,20 +0,0 @@
1
- import type { ZveltioConfig, QueryOptions, QueryResponse, DeleteResponse } from '../types/index.js';
2
- import { QueryBuilder } from './QueryBuilder.js';
3
- import { Auth } from './Auth.js';
4
- import { RealtimeClient } from './RealtimeClient.js';
5
- export declare class ZveltioClient {
6
- readonly auth: Auth;
7
- readonly realtime: RealtimeClient;
8
- private config;
9
- constructor(config: ZveltioConfig);
10
- from(collection: string): QueryBuilder;
11
- list<T = any>(collection: string, options?: QueryOptions): Promise<QueryResponse<T>>;
12
- get<T = any>(collection: string, id: string): Promise<T>;
13
- create<T = any>(collection: string, data: Partial<T>): Promise<T>;
14
- update<T = any>(collection: string, id: string, data: Partial<T>): Promise<T>;
15
- replace<T = any>(collection: string, id: string, data: T): Promise<T>;
16
- delete(collection: string, id: string): Promise<DeleteResponse>;
17
- request<T>(path: string, init?: RequestInit): Promise<T>;
18
- }
19
- export declare function createClient(config: ZveltioConfig): ZveltioClient;
20
- //# sourceMappingURL=ZveltioClient.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"ZveltioClient.d.ts","sourceRoot":"","sources":["../../src/client/ZveltioClient.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,aAAa,EACb,YAAY,EACZ,aAAa,EAGb,cAAc,EACf,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,YAAY,EAAE,M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AgB,YAAY,CAAC,MAAM,EAAE,aAAa,GAAG,aAAa,CAEjE"}
@@ -1,89 +0,0 @@
1
- import { QueryBuilder } from './QueryBuilder.js';
2
- import { Auth } from './Auth.js';
3
- import { RealtimeClient } from './RealtimeClient.js';
4
- export class ZveltioClient {
5
- auth;
6
- realtime;
7
- config;
8
- constructor(config) {
9
- this.config = config;
10
- this.auth = new Auth(config);
11
- // The key the HTTP calls send, sent with the upgrade too (server-side
12
- // clients; a browser authenticates the socket by its session cookie).
13
- this.realtime = new RealtimeClient(config.baseUrl, {
14
- headers: config.apiKey ? { 'X-API-Key': config.apiKey } : undefined,
15
- });
16
- // A socket closed for revoked credentials is the same event as a 401.
17
- this.realtime.onUnauthorized(() => config.onUnauthorized?.());
18
- }
19
- // Fluent query builder
20
- from(collection) {
21
- return new QueryBuilder(collection, this.config);
22
- }
23
- // Direct CRUD methods
24
- // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
25
- async list(collection, options) {
26
- return this.from(collection).query(options);
27
- }
28
- // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
29
- async get(collection, id) {
30
- const res = await this.request(`/api/data/${collection}/${id}`);
31
- return res.record;
32
- }
33
- // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
34
- async create(collection, data) {
35
- const res = await this.request(`/api/data/${collection}`, {
36
- method: 'POST',
37
- body: JSON.stringify(data),
38
- });
39
- return res.record;
40
- }
41
- // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
42
- async update(collection, id, data) {
43
- const res = await this.request(`/api/data/${collection}/${id}`, {
44
- method: 'PATCH',
45
- body: JSON.stringify(data),
46
- });
47
- return res.record;
48
- }
49
- // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
50
- async replace(collection, id, data) {
51
- const res = await this.request(`/api/data/${collection}/${id}`, {
52
- method: 'PUT',
53
- body: JSON.stringify(data),
54
- });
55
- return res.record;
56
- }
57
- async delete(collection, id) {
58
- return this.request(`/api/data/${collection}/${id}`, {
59
- method: 'DELETE',
60
- });
61
- }
62
- // Raw request helper
63
- async request(path, init) {
64
- const headers = {
65
- 'Content-Type': 'application/json',
66
- ...init?.headers,
67
- };
68
- if (this.config.apiKey) {
69
- headers['X-API-Key'] = this.config.apiKey;
70
- }
71
- const res = await fetch(`${this.config.baseUrl}${path}`, {
72
- ...init,
73
- credentials: 'include',
74
- headers,
75
- });
76
- if (res.status === 401) {
77
- this.config.onUnauthorized?.();
78
- throw new Error('Unauthorized');
79
- }
80
- if (!res.ok) {
81
- const err = await res.json().catch(() => ({ error: res.statusText }));
82
- throw new Error(err.error || `Request failed: ${res.status}`);
83
- }
84
- return res.json();
85
- }
86
- }
87
- export function createClient(config) {
88
- return new ZveltioClient(config);
89
- }