lazypock 0.18.0 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/realtime.ts CHANGED
@@ -1,11 +1,12 @@
1
- // ── Phoenix Channel WebSocket Client ──────────────────
1
+ // ── SSE Realtime Client ───────────────────────────────
2
2
  //
3
- // Implements the Phoenix Channels protocol over WebSocket
4
- // to subscribe to collection realtime updates.
3
+ // Subscribes to this server's Server-Sent Events endpoint at `/api/realtime`.
5
4
  //
6
- // Protocol: Phoenix V1 JSON Serializer (object-based messages).
7
- // Sends messages as JSON objects with {topic, event, payload, ref, join_ref}.
8
- // Receives messages as JSON objects with {topic, event, payload, ref}.
5
+ // One connection carries every topic the client is subscribed to: the server takes
6
+ // a comma-separated `subscribe` query parameter and cannot change it on a live
7
+ // connection, so changing the subscription set reconnects. The stream is read with
8
+ // `fetch` rather than `EventSource` so the bearer token and the `X-Connection-Id`
9
+ // header can be sent — `EventSource` supports neither.
9
10
 
10
11
  interface RealtimeEvent {
11
12
  event: string;
@@ -16,171 +17,160 @@ interface RealtimeEvent {
16
17
  interface SubEntry {
17
18
  topic: string;
18
19
  callback: (e: RealtimeEvent) => void;
19
- /** Optional payload forwarded with the channel join (e.g. expand). */
20
+ /** Accepted for API compatibility; SSE has no join payload. */
20
21
  joinPayload?: Record<string, unknown>;
21
22
  }
22
23
 
23
24
  export type RealtimeConnectOpts = {
24
- /** WebSocket URL (e.g. ws://localhost:4000/socket/websocket) */
25
+ /** SSE endpoint URL, e.g. `http://localhost:4000/api/realtime`. */
25
26
  url: string;
26
- /** Auth token to pass as query param */
27
+ /** Auth token to send as a bearer. */
27
28
  token?: string;
28
29
  };
29
30
 
30
31
  /**
31
32
  * Provides the current auth token at connect/reconnect time.
32
- * Wired by {@link LazypockClient} from its `authStore` so the socket is
33
+ * Wired by {@link LazypockClient} from its `authStore` so the stream is
33
34
  * always authenticated with the latest token (PocketBase parity).
34
35
  */
35
36
  export type RealtimeTokenProvider = () => string | undefined;
36
37
 
37
38
  /**
38
- * Derive a WebSocket URL from an HTTP base URL.
39
- * http://localhost:4000/api → ws://localhost:4000/socket/websocket
39
+ * Derive the SSE endpoint from an HTTP base URL.
40
+ * `http://localhost:4000/api` → `http://localhost:4000/api/realtime`
41
+ */
42
+ export function sseUrlFromBaseUrl(baseUrl: string): string {
43
+ return `${baseUrl.replace(/\/+$/, "")}/realtime`;
44
+ }
45
+
46
+ /**
47
+ * @deprecated Realtime is SSE, not WebSocket. Use {@link sseUrlFromBaseUrl}.
48
+ * Kept so an existing import keeps compiling.
40
49
  */
41
50
  export function wsUrlFromBaseUrl(baseUrl: string): string {
42
- try {
43
- const url = new URL(baseUrl);
44
- const protocol = url.protocol === "https:" ? "wss:" : "ws:";
45
- return `${protocol}//${url.host}/socket/websocket`;
46
- } catch {
47
- return `${baseUrl.replace(/^http/, "ws").replace(/\/api$/, "")}/socket/websocket`;
48
- }
51
+ return sseUrlFromBaseUrl(baseUrl);
49
52
  }
50
53
 
51
54
  /**
52
- * Phoenix Channel client for real-time collection subscriptions.
55
+ * Translate an SDK topic to the server's `subscribe` specifier.
53
56
  *
54
- * Connects via WebSocket and subscribes to collection topics.
55
- * Includes automatic reconnection with exponential backoff.
57
+ * The SDK keeps PocketBase's topic names (`collection:posts`, `collections`); the
58
+ * server takes a collection name, an optional `/recordId`, and the registry topic.
59
+ */
60
+ function serverTopic(topic: string): string | null {
61
+ if (topic === "collections") return "collections";
62
+ if (!topic.startsWith("collection:")) return null;
63
+ const rest = topic.slice("collection:".length);
64
+ const [name, recordId] = rest.split(":");
65
+ if (!name) return null;
66
+ return recordId ? `${name}/${recordId}` : name;
67
+ }
68
+
69
+ /** The data of one server realtime event. */
70
+ interface RealtimeFrame {
71
+ collection?: string;
72
+ action?: string;
73
+ id?: string;
74
+ record?: Record<string, unknown>;
75
+ }
76
+
77
+ /**
78
+ * SSE client for real-time collection subscriptions.
56
79
  *
57
- * @example
58
- * ```ts
59
- * const rt = new RealtimeService();
60
- * rt.connect({ url: wsUrlFromBaseUrl('http://localhost:4000/api') });
61
- * rt.subscribe('collection:posts', (e) => console.log(e));
62
- * ```
80
+ * Connects to `/api/realtime`, subscribes to the collection topics the SDK uses,
81
+ * and reconnects with exponential backoff. Live row-level security is applied by the
82
+ * server: an event is only sent for a record the subscriber may read.
63
83
  */
64
84
  export class RealtimeService {
65
- private ws: WebSocket | null = null;
66
- private refCounter = 0;
85
+ private controller: AbortController | null = null;
86
+ private open = false;
87
+ private closed = false;
67
88
  private subscriptions = new Map<string, SubEntry[]>();
68
89
  private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
90
+ private resubscribeTimer: ReturnType<typeof setTimeout> | null = null;
69
91
  private reconnectAttempt = 0;
70
92
  private maxReconnectDelay = 5000;
71
93
 
72
- // Callbacks for connection state
94
+ // Callbacks for connection state.
73
95
  onReconnect?: () => void;
74
96
  onDisconnect?: () => void;
75
- onError?: (err: Event) => void;
97
+ onError?: (err: unknown) => void;
76
98
 
77
- private url: string = "";
99
+ private url = "";
78
100
  private token: string | undefined;
79
101
  private tokenProvider: RealtimeTokenProvider | null = null;
80
102
 
81
103
  // Per-client connection id (browser tab / device). Sent as the
82
- // `connectionId` socket query param so the server can exclude the
83
- // *originating* connection from its own realtime broadcasts, while the
84
- // same user's other tabs/devices still receive them.
104
+ // `X-Connection-Id` header so the server can exclude the *originating*
105
+ // connection from its own broadcasts, while the same user's other
106
+ // tabs/devices still receive them.
85
107
  private connectionId: string | undefined;
86
108
 
87
- /** Whether the WebSocket is currently open. */
109
+ /** Whether the stream is currently open. */
88
110
  get isOpen(): boolean {
89
- return this.ws?.readyState === WebSocket.OPEN;
111
+ return this.open;
90
112
  }
91
113
 
92
- /**
93
- * The most recently used WebSocket URL (set on {@link connect}).
94
- * Useful for SDK convenience methods that auto-connect before subscribing.
95
- */
114
+ /** The most recently used SSE URL (set on {@link connect}/{@link setUrl}). */
96
115
  get lastUrl(): string {
97
116
  return this.url;
98
117
  }
99
118
 
100
- /** The auth token configured for this connection (set on connect). */
119
+ /** The auth token configured for this connection. */
101
120
  get lastToken(): string | undefined {
102
121
  return this.token;
103
122
  }
104
123
 
105
- /**
106
- * Set the per-client connection id (browser tab / device). The SDK
107
- * appends it as the `connectionId` socket query param at connect time
108
- * (unless the URL already carries one), matching the `X-Connection-Id`
109
- * header the HTTP client sends — together they let the server exclude
110
- * the originating connection from its own realtime broadcasts.
111
- */
124
+ /** Set the per-client connection id (browser tab / device). */
112
125
  setConnectionId(id: string): void {
113
126
  this.connectionId = id;
114
127
  }
115
128
 
116
- /**
117
- * Set the socket URL. Useful before subscribing so the SDK can
118
- * auto-connect on the first {@link subscribe}.
119
- */
129
+ /** Set the stream URL. Useful before subscribing so the SDK auto-connects. */
120
130
  setUrl(url: string): void {
121
131
  this.url = url;
122
132
  }
123
133
 
124
- /**
125
- * Register a token provider consulted at every (re)connect.
126
- * When set, it takes precedence over the token passed to {@link connect}.
127
- */
134
+ /** Register a token provider consulted at every (re)connect. */
128
135
  setTokenProvider(provider: RealtimeTokenProvider): void {
129
136
  this.tokenProvider = provider;
130
137
  }
131
138
 
132
139
  /**
133
- * Reconnect the socket immediately with the current token.
134
- * Called by the SDK when auth changes (login/logout/token refresh) so
135
- * private-channel joins are authorized with the new credentials. No-op
136
- * when the socket has never been opened and nothing is subscribed.
140
+ * Reconnect immediately with the current token, so auth changes
141
+ * (login/logout/refresh) re-authorize private subscriptions.
137
142
  */
138
143
  refresh(): void {
139
- if (typeof WebSocket === "undefined") return;
140
- if (!this.ws && this.subscriptions.size === 0) return;
141
- this.clearReconnectTimer();
142
- const ws = this.ws;
143
- this.ws = null;
144
- if (ws) {
145
- // Suppress the auto-reconnect path for this intentional close.
146
- ws.onclose = null;
147
- ws.close();
148
- }
144
+ if (this.closed) return;
145
+ if (!this.open && this.subscriptions.size === 0) return;
149
146
  this.reconnectAttempt = 0;
150
147
  this.doConnect();
151
148
  }
152
149
 
153
- /*
154
- * Ensure the socket is connected, then subscribe.
155
- * Used by collection-level convenience wrappers so a connection is opened
156
- * automatically on the first subscribe (matching PocketBase behaviour —
157
- * works for anonymous/public collections too).
158
- */
150
+ /** Ensure a connection is open, then subscribe. */
159
151
  ensureConnected(): void {
160
- if (this.isOpen || !this.url) return;
161
- if (typeof WebSocket === "undefined") return;
152
+ if (this.open || this.controller || !this.url) return;
153
+ if (this.serverTopics().length === 0) return;
162
154
  this.doConnect();
163
155
  }
164
156
 
165
157
  connect(opts: RealtimeConnectOpts): void {
166
158
  this.url = opts.url;
167
159
  this.token = opts.token;
160
+ this.closed = false;
168
161
  this.reconnectAttempt = 0;
169
162
  this.doConnect();
170
163
  }
171
164
 
172
165
  disconnect(): void {
166
+ this.closed = true;
173
167
  this.clearReconnectTimer();
174
- this.ws?.close();
175
- this.ws = null;
168
+ this.closeStream();
176
169
  }
177
170
 
178
171
  /**
179
- * Subscribe to a topic (e.g. "collection:posts" or "custom:chat-room").
180
- * The backend Channel authorizes via listRule on join.
181
- *
182
- * @param joinPayload Optional payload forwarded with the channel join
183
- * (available to the server's join callback / hooks, e.g. `expand`).
172
+ * Subscribe to a topic (`collection:posts`, `collection:posts:ID`, or the
173
+ * registry topic `collections`).
184
174
  */
185
175
  subscribe(
186
176
  topic: string,
@@ -190,189 +180,186 @@ export class RealtimeService {
190
180
  const subs = this.subscriptions.get(topic) || [];
191
181
  subs.push({ topic, callback, joinPayload });
192
182
  this.subscriptions.set(topic, subs);
193
-
194
- if (this.ws?.readyState === WebSocket.OPEN) {
195
- this.joinTopic(topic, joinPayload);
196
- }
183
+ this.resubscribe();
197
184
  }
198
185
 
199
- /**
200
- * Remove all subscriptions for topics under `prefix` (the topic itself or
201
- * any topic starting with `prefix + ":"`). Used by collection-level
202
- * `unsubscribe()` to drop every subscription of a collection.
203
- */
186
+ /** Remove every subscription under `prefix` (the topic or `prefix:...`). */
204
187
  unsubscribeByPrefix(prefix: string): void {
188
+ let changed = false;
205
189
  for (const topic of [...this.subscriptions.keys()]) {
206
190
  if (topic === prefix || topic.startsWith(prefix + ":")) {
207
191
  this.subscriptions.delete(topic);
192
+ changed = true;
208
193
  }
209
194
  }
195
+ if (changed) this.resubscribe();
210
196
  }
211
197
 
212
- /**
213
- * Unsubscribe a specific callback from a topic.
214
- */
198
+ /** Remove a specific callback from a topic, or the whole topic. */
215
199
  unsubscribe(topic: string, callback?: (e: RealtimeEvent) => void): void {
216
200
  if (!callback) {
217
- this.subscriptions.delete(topic);
201
+ if (this.subscriptions.delete(topic)) this.resubscribe();
218
202
  return;
219
203
  }
220
- const subs = this.subscriptions
221
- .get(topic)
222
- ?.filter((s) => s.callback !== callback);
204
+ const subs = this.subscriptions.get(topic)?.filter((s) => s.callback !== callback);
223
205
  if (subs && subs.length > 0) {
224
206
  this.subscriptions.set(topic, subs);
225
- } else {
226
- this.subscriptions.delete(topic);
207
+ return;
227
208
  }
209
+ this.subscriptions.delete(topic);
210
+ this.resubscribe();
228
211
  }
229
212
 
230
- private resubscribeAll(): void {
231
- const seen = new Set<string>();
232
- for (const entries of this.subscriptions.values()) {
233
- for (const entry of entries) {
234
- if (seen.has(entry.topic)) continue;
235
- seen.add(entry.topic);
236
- if (this.ws?.readyState === WebSocket.OPEN) {
237
- this.joinTopic(entry.topic, entry.joinPayload);
238
- }
239
- }
240
- }
241
- }
213
+ // ── Internals ────────────────────────────────────
242
214
 
243
- private doConnect(): void {
244
- if (typeof WebSocket === "undefined") {
245
- console.warn(
246
- "[lazypock] WebSocket not available — realtime subscriptions disabled",
247
- );
248
- return;
215
+ /** The distinct server topics the current subscriptions need. */
216
+ private serverTopics(): string[] {
217
+ const topics = new Set<string>();
218
+ for (const topic of this.subscriptions.keys()) {
219
+ const server = serverTopic(topic);
220
+ if (server) topics.add(server);
249
221
  }
222
+ return [...topics];
223
+ }
250
224
 
251
- let url = this.url;
252
- const token = this.tokenProvider ? this.tokenProvider() : this.token;
253
- if (token) {
254
- url +=
255
- (url.includes("?") ? "&" : "?") +
256
- "token=" +
257
- encodeURIComponent(token);
258
- }
259
- // Advertise the connection id on the socket (unless the caller
260
- // already provided one via the URL, e.g. a custom client wrapper).
261
- if (this.connectionId && !url.includes("connectionId=")) {
262
- url +=
263
- (url.includes("?") ? "&" : "?") +
264
- "connectionId=" +
265
- encodeURIComponent(this.connectionId);
266
- }
225
+ /**
226
+ * The subscription set is part of the connection URL, so a change needs a new
227
+ * connection. Coalesced, because mounting a page subscribes to several
228
+ * collections in one tick.
229
+ */
230
+ private resubscribe(): void {
231
+ if (this.resubscribeTimer) clearTimeout(this.resubscribeTimer);
232
+ this.resubscribeTimer = setTimeout(() => {
233
+ this.resubscribeTimer = null;
234
+ if (this.controller) {
235
+ this.doConnect();
236
+ } else {
237
+ this.ensureConnected();
238
+ }
239
+ }, 0);
240
+ }
267
241
 
268
- this.ws = new WebSocket(url);
242
+ private doConnect(): void {
243
+ if (this.closed) return;
244
+ const topics = this.serverTopics();
245
+ if (topics.length === 0 || !this.url) return;
269
246
 
270
- this.ws.onopen = () => {
271
- this.reconnectAttempt = 0;
272
- this.resubscribeAll();
273
- this.startHeartbeat();
274
- };
247
+ // Drop any in-flight attempt: its `finally` sees a nulled controller and
248
+ // does not schedule a reconnect of its own.
249
+ this.closeStream();
275
250
 
276
- this.ws.onmessage = (msg: MessageEvent) => {
277
- this.handleMessage(msg.data);
278
- };
251
+ const params = new URLSearchParams();
252
+ params.set("subscribe", topics.join(","));
253
+ const url = this.url + (this.url.includes("?") ? "&" : "?") + params.toString();
279
254
 
280
- this.ws.onclose = () => {
281
- this.stopHeartbeat();
282
- this.onDisconnect?.();
283
- this.scheduleReconnect();
284
- };
255
+ const token = this.tokenProvider ? this.tokenProvider() : this.token;
256
+ const headers: Record<string, string> = { Accept: "text/event-stream" };
257
+ if (token) headers.Authorization = `Bearer ${token}`;
258
+ if (this.connectionId) headers["X-Connection-Id"] = this.connectionId;
285
259
 
286
- this.ws.onerror = (err: Event) => {
287
- this.onError?.(err);
288
- };
260
+ const controller = new AbortController();
261
+ this.controller = controller;
262
+ void this.read(url, headers, controller);
289
263
  }
290
264
 
291
- private handleMessage(data: string): void {
292
- let parsed: Record<string, unknown>;
265
+ private async read(
266
+ url: string,
267
+ headers: Record<string, string>,
268
+ controller: AbortController,
269
+ ): Promise<void> {
293
270
  try {
294
- parsed = JSON.parse(data) as Record<string, unknown>;
295
- } catch {
296
- return;
297
- }
298
- if (typeof parsed !== "object" || !parsed.topic || !parsed.event) return;
299
-
300
- const topic = parsed.topic as string;
301
- const event = parsed.event as string;
302
- const payload = (parsed.payload as Record<string, unknown>) || {};
303
-
304
- // Handle phx_reply (join/heartbeat responses)
305
- if (event === "phx_reply") return;
271
+ const response = await fetch(url, { headers, signal: controller.signal });
272
+ if (!response.ok || !response.body) {
273
+ throw new Error(`realtime connection failed (${response.status})`);
274
+ }
275
+ this.open = true;
276
+ this.reconnectAttempt = 0;
277
+ this.onReconnect?.();
306
278
 
307
- // Relay incoming events to all subscribers of this topic
308
- const subs = this.subscriptions.get(topic);
309
- if (subs) {
310
- const e: RealtimeEvent = {
311
- event,
312
- topic,
313
- payload: payload as Record<string, unknown>,
314
- };
315
- for (const s of subs) {
316
- try {
317
- s.callback(e);
318
- } catch {
319
- // swallow callback errors
279
+ const reader = response.body.getReader();
280
+ const decoder = new TextDecoder();
281
+ let buffer = "";
282
+ for (;;) {
283
+ const { done, value } = await reader.read();
284
+ if (done) break;
285
+ buffer = (buffer + decoder.decode(value, { stream: true })).replace(
286
+ /\r\n/g,
287
+ "\n",
288
+ );
289
+ let index: number;
290
+ while ((index = buffer.indexOf("\n\n")) >= 0) {
291
+ this.handleFrame(buffer.slice(0, index));
292
+ buffer = buffer.slice(index + 2);
320
293
  }
321
294
  }
295
+ throw new Error("realtime stream ended");
296
+ } catch (err) {
297
+ if (controller.signal.aborted) return;
298
+ this.onError?.(err);
299
+ } finally {
300
+ if (this.controller === controller) {
301
+ this.open = false;
302
+ this.controller = null;
303
+ this.onDisconnect?.();
304
+ this.scheduleReconnect();
305
+ }
322
306
  }
323
307
  }
324
308
 
325
- private joinTopic(
326
- topic: string,
327
- joinPayload?: Record<string, unknown>,
328
- ): void {
329
- const ref = this.nextRef();
330
- // Phoenix V1 JSON Serializer expects a JSON object, not an array
331
- const msg = JSON.stringify({
332
- topic: topic,
333
- event: "phx_join",
334
- payload: joinPayload ?? {},
335
- ref: ref,
336
- });
337
- this.ws?.send(msg);
338
- }
309
+ private handleFrame(frame: string): void {
310
+ const dataLines: string[] = [];
311
+ for (const line of frame.split("\n")) {
312
+ if (line.startsWith("data:")) {
313
+ dataLines.push(line.slice(5).replace(/^ /, ""));
314
+ }
315
+ }
316
+ if (dataLines.length === 0) return;
339
317
 
340
- private nextRef(): string {
341
- this.refCounter++;
342
- return this.refCounter.toString();
318
+ let data: RealtimeFrame;
319
+ try {
320
+ data = JSON.parse(dataLines.join("\n")) as RealtimeFrame;
321
+ } catch {
322
+ return;
323
+ }
324
+ this.dispatch(data);
343
325
  }
344
326
 
345
- // ── Heartbeat ──
346
-
347
- private heartbeatInterval: ReturnType<typeof setInterval> | null = null;
348
-
349
- private startHeartbeat(): void {
350
- this.stopHeartbeat();
351
- this.heartbeatInterval = setInterval(() => {
352
- if (this.ws?.readyState === WebSocket.OPEN) {
353
- const ref = this.nextRef();
354
- // Phoenix V1 JSON Serializer expects a JSON object
355
- const msg = JSON.stringify({
356
- topic: "phoenix",
357
- event: "heartbeat",
358
- payload: {},
359
- ref: ref,
360
- });
361
- this.ws.send(msg);
362
- }
363
- }, 30_000);
327
+ private dispatch(data: RealtimeFrame): void {
328
+ const action = typeof data.action === "string" ? data.action : "update";
329
+ if (data.collection === "collections") {
330
+ this.emit("collections", action, (data.record ?? {}) as Record<string, unknown>);
331
+ return;
332
+ }
333
+ if (!data.collection) return;
334
+ const payload: Record<string, unknown> = { record: data.record ?? {}, action };
335
+ this.emit(`collection:${data.collection}`, action, payload);
336
+ if (data.id) {
337
+ this.emit(`collection:${data.collection}:${data.id}`, action, payload);
338
+ }
364
339
  }
365
340
 
366
- private stopHeartbeat(): void {
367
- if (this.heartbeatInterval) {
368
- clearInterval(this.heartbeatInterval);
369
- this.heartbeatInterval = null;
341
+ private emit(topic: string, event: string, payload: Record<string, unknown>): void {
342
+ const subs = this.subscriptions.get(topic);
343
+ if (!subs) return;
344
+ const e: RealtimeEvent = { event, topic, payload };
345
+ for (const s of subs) {
346
+ try {
347
+ s.callback(e);
348
+ } catch {
349
+ // swallow callback errors
350
+ }
370
351
  }
371
352
  }
372
353
 
373
- // ── Reconnect ──
354
+ private closeStream(): void {
355
+ const controller = this.controller;
356
+ this.controller = null;
357
+ this.open = false;
358
+ controller?.abort();
359
+ }
374
360
 
375
361
  private scheduleReconnect(): void {
362
+ if (this.closed) return;
376
363
  this.clearReconnectTimer();
377
364
  const delay = Math.min(
378
365
  1000 * 2 ** this.reconnectAttempt,
@@ -381,7 +368,6 @@ export class RealtimeService {
381
368
  this.reconnectAttempt++;
382
369
  this.reconnectTimer = setTimeout(() => {
383
370
  this.reconnectTimer = null;
384
- this.onReconnect?.();
385
371
  this.doConnect();
386
372
  }, delay);
387
373
  }