@aurabase/realtime 0.4.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/dist/index.js ADDED
@@ -0,0 +1,1225 @@
1
+ import { fetchWithAuth } from '@aurabase/core';
2
+
3
+ // src/RealtimeService.ts
4
+
5
+ // src/columnFilter.ts
6
+ var VALID_OPS = /* @__PURE__ */ new Set([
7
+ "eq",
8
+ "neq",
9
+ "lt",
10
+ "lte",
11
+ "gt",
12
+ "gte",
13
+ "in",
14
+ "like",
15
+ "ilike",
16
+ "is",
17
+ "match",
18
+ "imatch",
19
+ "isdistinct"
20
+ ]);
21
+ var MAX_REGEX_PATTERN_LEN = 512;
22
+ var MAX_IN_VALUES = 100;
23
+ function parseColumnFilter(filterStr) {
24
+ const eqIdx = filterStr.indexOf("=");
25
+ if (eqIdx === -1) return null;
26
+ const column = filterStr.slice(0, eqIdx);
27
+ if (!column) return null;
28
+ let rest = filterStr.slice(eqIdx + 1);
29
+ let negated = false;
30
+ if (rest.startsWith("not.")) {
31
+ negated = true;
32
+ rest = rest.slice(4);
33
+ }
34
+ const dotIdx = rest.indexOf(".");
35
+ if (dotIdx === -1) return null;
36
+ const opStr = rest.slice(0, dotIdx);
37
+ let value = rest.slice(dotIdx + 1);
38
+ if (!VALID_OPS.has(opStr)) return null;
39
+ const op = opStr;
40
+ if (op === "in") {
41
+ const stripped = value.replace(/^\(+/, "").replace(/\)+$/, "");
42
+ if (stripped.split(",").length > MAX_IN_VALUES) return null;
43
+ value = stripped;
44
+ } else if (op === "is") {
45
+ if (value !== "null" && value !== "true" && value !== "false") return null;
46
+ } else if (op === "match" || op === "imatch") {
47
+ if (value.length > MAX_REGEX_PATTERN_LEN) return null;
48
+ try {
49
+ new RegExp(value, op === "imatch" ? "i" : void 0);
50
+ } catch {
51
+ return null;
52
+ }
53
+ }
54
+ return { column, op, value, negated };
55
+ }
56
+ function splitTopLevel(s) {
57
+ const parts = [];
58
+ let depth = 0;
59
+ let start = 0;
60
+ for (let i = 0; i < s.length; i++) {
61
+ const c = s[i];
62
+ if (c === "(") depth += 1;
63
+ else if (c === ")") depth = Math.max(0, depth - 1);
64
+ else if (c === "," && depth === 0) {
65
+ parts.push(s.slice(start, i));
66
+ start = i + 1;
67
+ }
68
+ }
69
+ parts.push(s.slice(start));
70
+ return parts;
71
+ }
72
+ function parseFilterSet(s) {
73
+ const parts = splitTopLevel(s);
74
+ const out = [];
75
+ for (const part of parts) {
76
+ const cf = parseColumnFilter(part.trim());
77
+ if (!cf) return null;
78
+ out.push(cf);
79
+ }
80
+ return out;
81
+ }
82
+ function jsonValueToString(field) {
83
+ if (typeof field === "string") return field;
84
+ if (typeof field === "number" || typeof field === "boolean") return String(field);
85
+ if (field === null) return "null";
86
+ try {
87
+ return JSON.stringify(field) ?? "";
88
+ } catch {
89
+ return "";
90
+ }
91
+ }
92
+ function parseStrictNumber(s) {
93
+ if (s.trim() === "") return null;
94
+ const n = Number(s);
95
+ return Number.isFinite(n) ? n : null;
96
+ }
97
+ function compareNumeric(a, b, cmp) {
98
+ const an = parseStrictNumber(a);
99
+ const bn = parseStrictNumber(b);
100
+ if (an === null || bn === null) return false;
101
+ return cmp(an, bn);
102
+ }
103
+ function likeToRegExp(pattern, caseInsensitive) {
104
+ let re = "^";
105
+ for (const ch of pattern) {
106
+ if (ch === "%") re += ".*";
107
+ else if (ch === "_") re += ".";
108
+ else re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
109
+ }
110
+ re += "$";
111
+ try {
112
+ return new RegExp(re, caseInsensitive ? "i" : void 0);
113
+ } catch {
114
+ return null;
115
+ }
116
+ }
117
+ function matchesRaw(cf, record) {
118
+ if (cf.op === "is") {
119
+ const field2 = record[cf.column];
120
+ switch (cf.value) {
121
+ case "null":
122
+ return field2 === void 0 || field2 === null;
123
+ case "true":
124
+ return field2 === true;
125
+ case "false":
126
+ return field2 === false;
127
+ default:
128
+ return false;
129
+ }
130
+ }
131
+ if (cf.op === "isdistinct") {
132
+ const field2 = record[cf.column];
133
+ const fieldIsNull = field2 === void 0 || field2 === null;
134
+ if (fieldIsNull) return true;
135
+ return jsonValueToString(field2) !== cf.value;
136
+ }
137
+ if (!(cf.column in record) || record[cf.column] === void 0) return null;
138
+ const field = record[cf.column];
139
+ const fieldStr = jsonValueToString(field);
140
+ switch (cf.op) {
141
+ case "eq":
142
+ return fieldStr === cf.value;
143
+ case "neq":
144
+ return fieldStr !== cf.value;
145
+ case "lt":
146
+ return compareNumeric(fieldStr, cf.value, (a, b) => a < b);
147
+ case "lte":
148
+ return compareNumeric(fieldStr, cf.value, (a, b) => a <= b);
149
+ case "gt":
150
+ return compareNumeric(fieldStr, cf.value, (a, b) => a > b);
151
+ case "gte":
152
+ return compareNumeric(fieldStr, cf.value, (a, b) => a >= b);
153
+ case "in":
154
+ return cf.value.split(",").map((v) => v.trim()).some((v) => v === fieldStr);
155
+ case "like": {
156
+ const re = likeToRegExp(cf.value, false);
157
+ return re ? re.test(fieldStr) : null;
158
+ }
159
+ case "ilike": {
160
+ const re = likeToRegExp(cf.value, true);
161
+ return re ? re.test(fieldStr) : null;
162
+ }
163
+ case "match": {
164
+ try {
165
+ return new RegExp(cf.value).test(fieldStr);
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+ case "imatch": {
171
+ try {
172
+ return new RegExp(cf.value, "i").test(fieldStr);
173
+ } catch {
174
+ return null;
175
+ }
176
+ }
177
+ default:
178
+ return null;
179
+ }
180
+ }
181
+ function matchesSingle(cf, record) {
182
+ const raw = matchesRaw(cf, record);
183
+ if (raw === null) return false;
184
+ return cf.negated ? !raw : raw;
185
+ }
186
+ function matchesColumnFilter(filter, record) {
187
+ const set = parseFilterSet(filter);
188
+ if (!set) return false;
189
+ return set.every((cf) => matchesSingle(cf, record));
190
+ }
191
+
192
+ // src/AuraChannel.ts
193
+ var DEFAULT_SUBSCRIBE_TIMEOUT_MS = 1e4;
194
+ var AuraChannel = class {
195
+ name;
196
+ _projectId;
197
+ _listeners = [];
198
+ _subscribed = false;
199
+ _sendFn = null;
200
+ _subscribeCallback = null;
201
+ _presenceState = {};
202
+ _isPrivate = false;
203
+ _broadcastAck = false;
204
+ _broadcastSelf = false;
205
+ _presenceKey = "";
206
+ /** ID de subscription retourné par le serveur (utilisé pour le filtre RLS allowed_sub_ids) */
207
+ _subscriptionId = null;
208
+ /** Compteur pour générer des ref_id uniques par connexion */
209
+ _refCounter = 0;
210
+ /** Dernier event ID recu — utilise pour since_id au reconnect */
211
+ _lastEventId = null;
212
+ /** Pending ACK callbacks : ref_id → resolve */
213
+ _pendingAcks = /* @__PURE__ */ new Map();
214
+ /**
215
+ * Timer d'attente de la confirmation `subscribed`. Armé à l'ENVOI effectif du
216
+ * message subscribe (parité phoenix : `Push#startTimeout` ne démarre qu'au
217
+ * `send()`), désarmé dès qu'une réponse — `subscribed` ou `error` — arrive.
218
+ */
219
+ _subscribeTimer = null;
220
+ /** Délai avant `TIMED_OUT`, surchargeable par `subscribe(cb, timeout)`. */
221
+ _subscribeTimeoutMs = DEFAULT_SUBSCRIBE_TIMEOUT_MS;
222
+ /** `CLOSED` n'est émis qu'une fois par cycle de vie du canal (unsubscribe idempotent). */
223
+ _closedEmitted = false;
224
+ constructor(name, projectId, options) {
225
+ this.name = name;
226
+ this._projectId = projectId;
227
+ this._isPrivate = options?.private ?? false;
228
+ this._broadcastAck = options?.broadcast?.ack ?? false;
229
+ this._broadcastSelf = options?.broadcast?.self ?? false;
230
+ this._presenceKey = options?.config?.presence?.key ?? "";
231
+ }
232
+ /** Génère un ref_id unique pour la corrélation request/response. */
233
+ _nextRef() {
234
+ return `${this.fullName}:r${++this._refCounter}`;
235
+ }
236
+ /** Full channel name with project prefix (for server protocol) */
237
+ get fullName() {
238
+ return `${this._projectId}:${this.name}`;
239
+ }
240
+ on(type, filter, callback) {
241
+ this._listeners.push({ type, filter, callback });
242
+ return this;
243
+ }
244
+ // ─── Subscribe ──────────────────────────────────────────────────────────
245
+ /**
246
+ * Subscribe to the channel. Sends the Subscribe message to the server
247
+ * with the full config (postgres_changes, broadcast, presence).
248
+ *
249
+ * Le callback reçoit les mêmes statuts que `@supabase/realtime-js` :
250
+ * - `SUBSCRIBED` — le serveur a confirmé l'abonnement ;
251
+ * - `CHANNEL_ERROR` — refus serveur (RLS, rate limit…), échec de handshake ou
252
+ * coupure inattendue de la connexion ;
253
+ * - `TIMED_OUT` — aucune réponse du serveur dans `timeoutMs` après l'envoi ;
254
+ * - `CLOSED` — le canal a été fermé volontairement (`unsubscribe()`,
255
+ * `removeChannel()`, `removeAllChannels()`, `disconnect()`).
256
+ *
257
+ * @param callback Callback de statut (optionnel).
258
+ * @param timeoutMs Délai avant `TIMED_OUT` (défaut 10 s, comme Supabase).
259
+ */
260
+ subscribe(callback, timeoutMs) {
261
+ this._subscribeCallback = callback ?? null;
262
+ this._subscribed = true;
263
+ this._closedEmitted = false;
264
+ if (typeof timeoutMs === "number" && timeoutMs > 0) {
265
+ this._subscribeTimeoutMs = timeoutMs;
266
+ }
267
+ if (this._sendFn) {
268
+ this._doSubscribe();
269
+ }
270
+ return this;
271
+ }
272
+ /** Called by RealtimeService once the WS connection is ready. */
273
+ _bindSend(sendFn) {
274
+ this._sendFn = sendFn;
275
+ }
276
+ /** Send the subscribe message to the server. */
277
+ _doSubscribe() {
278
+ if (!this._sendFn) return;
279
+ const pgFilters = this._listeners.filter((l) => l.type === "postgres_changes").map((l) => l.filter);
280
+ const msg = {
281
+ type: "subscribe",
282
+ channel: this.fullName,
283
+ ref_id: this._nextRef(),
284
+ since_id: this._lastEventId ?? void 0,
285
+ config: {
286
+ postgres_changes: pgFilters,
287
+ broadcast: {
288
+ self_broadcast: this._broadcastSelf,
289
+ // ← depuis les options du channel
290
+ ack: this._broadcastAck
291
+ // ← depuis les options du channel
292
+ },
293
+ presence: { key: this._presenceKey },
294
+ // ← depuis les options du channel
295
+ private: this._isPrivate
296
+ }
297
+ };
298
+ this._sendFn(JSON.stringify(msg));
299
+ this._armSubscribeTimeout();
300
+ }
301
+ /** (Re)arme le compte à rebours d'attente de la confirmation `subscribed`. */
302
+ _armSubscribeTimeout() {
303
+ this._clearSubscribeTimeout();
304
+ if (!this._subscribeCallback) return;
305
+ this._subscribeTimer = setTimeout(() => {
306
+ this._subscribeTimer = null;
307
+ this._subscribeCallback?.("TIMED_OUT");
308
+ }, this._subscribeTimeoutMs);
309
+ }
310
+ _clearSubscribeTimeout() {
311
+ if (this._subscribeTimer) {
312
+ clearTimeout(this._subscribeTimer);
313
+ this._subscribeTimer = null;
314
+ }
315
+ }
316
+ /**
317
+ * Signale une erreur de transport (échec de handshake, coupure inattendue,
318
+ * connexion morte) — appelé par `RealtimeService`.
319
+ *
320
+ * Émet `CHANNEL_ERROR`, comme `@supabase/realtime-js` : chez Supabase, la
321
+ * fermeture du socket déclenche `Socket#triggerChanError` (phoenix
322
+ * `socket.js:550`), qui produit `CHANNEL_ERROR` et **jamais** `CLOSED` —
323
+ * `CLOSED` reste réservé à la fermeture volontaire du canal.
324
+ */
325
+ _signalError(err) {
326
+ this._clearSubscribeTimeout();
327
+ if (!this._subscribed) return;
328
+ this._subscribeCallback?.("CHANNEL_ERROR", err);
329
+ }
330
+ /** Unsubscribe from the channel. */
331
+ unsubscribe() {
332
+ if (this._sendFn) {
333
+ this._sendFn(JSON.stringify({ type: "unsubscribe", channel: this.fullName }));
334
+ }
335
+ this._clearSubscribeTimeout();
336
+ this._subscribed = false;
337
+ this._listeners.length = 0;
338
+ this._presenceState = {};
339
+ if (!this._closedEmitted) {
340
+ this._closedEmitted = true;
341
+ this._subscribeCallback?.("CLOSED");
342
+ }
343
+ }
344
+ // ─── Broadcast ──────────────────────────────────────────────────────────
345
+ /**
346
+ * Send a broadcast message to the channel.
347
+ * If broadcast.ack=true, returns a Promise that resolves when the server ACKs.
348
+ *
349
+ * @example
350
+ * ```ts
351
+ * // Without ACK (fire & forget)
352
+ * channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100, y: 200 } })
353
+ *
354
+ * // With ACK (wait for server confirmation)
355
+ * await channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100 } })
356
+ * ```
357
+ */
358
+ send(message) {
359
+ return new Promise((resolve) => {
360
+ if (!this._sendFn) {
361
+ resolve("error");
362
+ return;
363
+ }
364
+ const ref_id = message.ref_id ?? this._nextRef();
365
+ if (this._broadcastAck) {
366
+ const timer = setTimeout(() => {
367
+ this._pendingAcks.delete(ref_id);
368
+ resolve("timeout");
369
+ }, 5e3);
370
+ this._pendingAcks.set(ref_id, () => {
371
+ clearTimeout(timer);
372
+ resolve("ok");
373
+ });
374
+ } else {
375
+ resolve("ok");
376
+ }
377
+ this._sendFn(
378
+ JSON.stringify({
379
+ type: "broadcast",
380
+ channel: this.fullName,
381
+ ref_id,
382
+ payload: { event: message.event, ...message.payload }
383
+ })
384
+ );
385
+ });
386
+ }
387
+ // ─── Presence ───────────────────────────────────────────────────────────
388
+ /**
389
+ * Track presence state for this client.
390
+ * Returns a Promise that resolves with 'ok' once tracked (compatible Supabase).
391
+ *
392
+ * @example
393
+ * ```ts
394
+ * await channel.track({ user: 'user-1', online_at: new Date().toISOString() })
395
+ * ```
396
+ */
397
+ async track(state) {
398
+ if (!this._sendFn) return "error";
399
+ this._sendFn(
400
+ JSON.stringify({
401
+ type: "presence_update",
402
+ channel: this.fullName,
403
+ meta: state
404
+ })
405
+ );
406
+ return "ok";
407
+ }
408
+ /** Stop tracking presence. */
409
+ async untrack() {
410
+ return this.track({});
411
+ }
412
+ /** Get the current presence state for this channel. */
413
+ presenceState() {
414
+ return { ...this._presenceState };
415
+ }
416
+ // ─── Internal: dispatch server messages ──────────────────────────────────
417
+ /** Called by RealtimeService when a server message arrives for this channel. */
418
+ _onMessage(msg) {
419
+ switch (msg.type) {
420
+ case "subscribed": {
421
+ const subMsg = msg;
422
+ if (subMsg.subscription_id) this._subscriptionId = subMsg.subscription_id;
423
+ this._clearSubscribeTimeout();
424
+ this._subscribeCallback?.("SUBSCRIBED");
425
+ break;
426
+ }
427
+ case "event": {
428
+ const evtMsg = msg;
429
+ if (evtMsg.id) {
430
+ const event = {
431
+ id: evtMsg.id,
432
+ event: evtMsg.event,
433
+ topic: evtMsg.topic,
434
+ payload: evtMsg.payload,
435
+ timestamp: evtMsg.timestamp,
436
+ allowed_sub_ids: evtMsg.allowed_sub_ids
437
+ };
438
+ this._dispatchEvent(event);
439
+ }
440
+ break;
441
+ }
442
+ case "presence_state": {
443
+ const presMsg = msg;
444
+ if (presMsg.presences) {
445
+ this._presenceState = {};
446
+ for (const p of presMsg.presences) {
447
+ const key = p.user_id || p.client_id;
448
+ if (!this._presenceState[key]) this._presenceState[key] = [];
449
+ this._presenceState[key].push(p);
450
+ }
451
+ for (const l of this._listeners) {
452
+ if (l.type === "presence" && l.filter.event === "sync") {
453
+ l.callback(this._presenceState);
454
+ }
455
+ }
456
+ }
457
+ break;
458
+ }
459
+ case "error": {
460
+ const errMsg = msg;
461
+ this._clearSubscribeTimeout();
462
+ this._subscribeCallback?.("CHANNEL_ERROR", new Error(errMsg.message ?? "Unknown error"));
463
+ break;
464
+ }
465
+ case "token_refreshed":
466
+ break;
467
+ case "broadcast_ack": {
468
+ const ackMsg = msg;
469
+ const refId = ackMsg.ref_id ?? ackMsg.message_id;
470
+ if (refId) {
471
+ const resolve = this._pendingAcks.get(refId);
472
+ if (resolve) {
473
+ this._pendingAcks.delete(refId);
474
+ resolve();
475
+ }
476
+ }
477
+ break;
478
+ }
479
+ }
480
+ }
481
+ /** Dispatch a RealtimeEvent to matching listeners. */
482
+ _dispatchEvent(event) {
483
+ if (!event) return;
484
+ if (event.id) this._lastEventId = event.id;
485
+ const allowed = event.allowed_sub_ids;
486
+ if (allowed && this._subscriptionId && !allowed.includes(this._subscriptionId)) {
487
+ return;
488
+ }
489
+ const eventType = event.event;
490
+ if (eventType === "presence") {
491
+ const payload = event.payload;
492
+ const action = payload.action;
493
+ const key = payload.user_id || payload.client_id;
494
+ if (action === "join") {
495
+ if (!this._presenceState[key]) this._presenceState[key] = [];
496
+ if (!this._presenceState[key].some((p) => p.client_id === payload.client_id)) {
497
+ const presenceInfo = {
498
+ client_id: payload.client_id,
499
+ user_id: payload.user_id ?? void 0,
500
+ metadata: payload.metadata ?? payload.meta ?? {},
501
+ joined_at: (/* @__PURE__ */ new Date()).toISOString(),
502
+ last_seen: (/* @__PURE__ */ new Date()).toISOString()
503
+ };
504
+ this._presenceState[key].push(presenceInfo);
505
+ }
506
+ } else if (action === "leave") {
507
+ const arr = this._presenceState[key];
508
+ if (arr) {
509
+ const idx = arr.findIndex((p) => p.client_id === payload.client_id);
510
+ if (idx >= 0) arr.splice(idx, 1);
511
+ if (arr.length === 0) delete this._presenceState[key];
512
+ }
513
+ } else if (action === "update") {
514
+ const arr = this._presenceState[key];
515
+ if (arr) {
516
+ const idx = arr.findIndex((p) => p.client_id === payload.client_id);
517
+ if (idx >= 0) {
518
+ arr[idx].metadata = payload.metadata ?? payload.meta ?? {};
519
+ arr[idx].last_seen = (/* @__PURE__ */ new Date()).toISOString();
520
+ } else {
521
+ const presenceInfo = {
522
+ client_id: payload.client_id,
523
+ user_id: payload.user_id ?? void 0,
524
+ metadata: payload.metadata ?? payload.meta ?? {},
525
+ joined_at: (/* @__PURE__ */ new Date()).toISOString(),
526
+ last_seen: (/* @__PURE__ */ new Date()).toISOString()
527
+ };
528
+ this._presenceState[key].push(presenceInfo);
529
+ }
530
+ } else {
531
+ this._presenceState[key] = [{
532
+ client_id: payload.client_id,
533
+ user_id: payload.user_id ?? void 0,
534
+ metadata: payload.metadata ?? payload.meta ?? {},
535
+ joined_at: (/* @__PURE__ */ new Date()).toISOString(),
536
+ last_seen: (/* @__PURE__ */ new Date()).toISOString()
537
+ }];
538
+ }
539
+ }
540
+ }
541
+ for (const listener of this._listeners) {
542
+ if (listener.type === "postgres_changes") {
543
+ const filter = listener.filter;
544
+ if (eventType === "insert" || eventType === "update" || eventType === "delete") {
545
+ const filterEvent = filter.event.toLowerCase();
546
+ if (filterEvent === "*" || filterEvent === eventType) {
547
+ const payload = event.payload;
548
+ if (filter.schema && payload.schema !== filter.schema) continue;
549
+ if (filter.table && payload.table !== filter.table) continue;
550
+ if (filter.filter) {
551
+ const target = eventType === "delete" ? payload.old_record : payload.record;
552
+ if (target && typeof target === "object") {
553
+ if (!matchesColumnFilter(filter.filter, target)) {
554
+ continue;
555
+ }
556
+ }
557
+ }
558
+ listener.callback(event);
559
+ }
560
+ }
561
+ } else if (listener.type === "broadcast") {
562
+ if (eventType === "broadcast") {
563
+ const filter = listener.filter;
564
+ const payload = event.payload;
565
+ if (!filter.event || payload.event === filter.event) {
566
+ listener.callback(event);
567
+ }
568
+ }
569
+ } else if (listener.type === "presence") {
570
+ if (eventType === "presence") {
571
+ const filter = listener.filter;
572
+ const payload = event.payload;
573
+ const action = payload.action;
574
+ if (filter.event === "join" && action === "join") {
575
+ listener.callback({
576
+ key: payload.user_id || payload.client_id,
577
+ newPresences: [payload]
578
+ });
579
+ } else if (filter.event === "leave" && action === "leave") {
580
+ listener.callback({
581
+ key: payload.user_id || payload.client_id,
582
+ leftPresences: [payload]
583
+ });
584
+ } else if (filter.event === "sync") {
585
+ listener.callback(this.presenceState());
586
+ }
587
+ }
588
+ }
589
+ }
590
+ }
591
+ /** Whether this channel has been subscribed. */
592
+ get isSubscribed() {
593
+ return this._subscribed;
594
+ }
595
+ /** Get listeners (for re-subscribe after reconnect). */
596
+ _getListeners() {
597
+ return this._listeners;
598
+ }
599
+ };
600
+
601
+ // src/HeartbeatManager.ts
602
+ var HeartbeatManager = class {
603
+ _worker = null;
604
+ _workerUrl = null;
605
+ _interval = null;
606
+ _sendFn = null;
607
+ start(sendPing, intervalMs = 25e3) {
608
+ this.stop();
609
+ this._sendFn = sendPing;
610
+ if (typeof Worker !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
611
+ try {
612
+ const code = `let i=null;onmessage=(e)=>{if(e.data.type==='start'){if(i)clearInterval(i);i=setInterval(()=>postMessage('ping'),e.data.interval||25000);}else if(e.data.type==='stop'){if(i){clearInterval(i);i=null;}}};`;
613
+ const blob = new Blob([code], { type: "application/javascript" });
614
+ this._workerUrl = URL.createObjectURL(blob);
615
+ this._worker = new Worker(this._workerUrl);
616
+ this._worker.onmessage = () => {
617
+ this._sendFn?.();
618
+ };
619
+ this._worker.postMessage({ type: "start", interval: intervalMs });
620
+ return;
621
+ } catch {
622
+ this._worker = null;
623
+ if (this._workerUrl) {
624
+ try {
625
+ URL.revokeObjectURL(this._workerUrl);
626
+ } catch {
627
+ }
628
+ this._workerUrl = null;
629
+ }
630
+ }
631
+ }
632
+ this._interval = setInterval(() => {
633
+ this._sendFn?.();
634
+ }, intervalMs);
635
+ }
636
+ stop() {
637
+ if (this._worker) {
638
+ try {
639
+ this._worker.postMessage({ type: "stop" });
640
+ this._worker.terminate();
641
+ } catch {
642
+ }
643
+ this._worker = null;
644
+ }
645
+ if (this._workerUrl) {
646
+ try {
647
+ URL.revokeObjectURL(this._workerUrl);
648
+ } catch {
649
+ }
650
+ this._workerUrl = null;
651
+ }
652
+ if (this._interval) {
653
+ clearInterval(this._interval);
654
+ this._interval = null;
655
+ }
656
+ this._sendFn = null;
657
+ }
658
+ get isActive() {
659
+ return this._worker !== null || this._interval !== null;
660
+ }
661
+ };
662
+
663
+ // src/jwt.ts
664
+ function base64UrlToBase64(segment) {
665
+ let out = segment.replace(/-/g, "+").replace(/_/g, "/");
666
+ while (out.length % 4 !== 0) out += "=";
667
+ return out;
668
+ }
669
+ function decodeJwtPayload(token) {
670
+ try {
671
+ const parts = token.split(".");
672
+ if (parts.length !== 3) return null;
673
+ const raw = parts[1];
674
+ if (!raw) return null;
675
+ const json = atob(base64UrlToBase64(raw));
676
+ const parsed = JSON.parse(json);
677
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
678
+ return parsed;
679
+ } catch {
680
+ return null;
681
+ }
682
+ }
683
+ function getTokenExpiryMs(token) {
684
+ const payload = decodeJwtPayload(token);
685
+ if (!payload) return null;
686
+ const exp = payload.exp;
687
+ if (typeof exp !== "number" || !Number.isFinite(exp)) return null;
688
+ return exp * 1e3;
689
+ }
690
+
691
+ // src/errors.ts
692
+ var RealtimeConnectionError = class _RealtimeConnectionError extends Error {
693
+ /** Phase du cycle de vie où l'échec s'est produit. */
694
+ phase;
695
+ /** Code de fermeture WebSocket (RFC 6455 §7.4), si le runtime l'a fourni. */
696
+ code;
697
+ /** Raison de fermeture fournie par le serveur, si présente (souvent vide). */
698
+ reason;
699
+ constructor(phase, message, options) {
700
+ super(message, options?.cause !== void 0 ? { cause: options.cause } : void 0);
701
+ this.name = "RealtimeConnectionError";
702
+ this.phase = phase;
703
+ this.code = options?.code;
704
+ this.reason = options?.reason;
705
+ Object.setPrototypeOf(this, _RealtimeConnectionError.prototype);
706
+ }
707
+ };
708
+
709
+ // src/RealtimeService.ts
710
+ var HEARTBEAT_INTERVAL_MS = 25e3;
711
+ var MAX_TIMEOUT_MS = 2147483647;
712
+ var RealtimeService = class _RealtimeService {
713
+ client;
714
+ _ws = null;
715
+ _channels = /* @__PURE__ */ new Map();
716
+ _state = "disconnected";
717
+ _stateListeners = /* @__PURE__ */ new Set();
718
+ // ─── Reconnection state ──────────────────────────────────────────────
719
+ _autoReconnect = true;
720
+ _reconnectAttempts = 0;
721
+ _maxReconnectAttempts = Infinity;
722
+ _reconnectTimer = null;
723
+ _intentionalClose = false;
724
+ _heartbeat = new HeartbeatManager();
725
+ _tokenRefreshTimer = null;
726
+ /** Dernier access_token propagé au serveur — évite les pushs redondants (propagation différentielle). */
727
+ _lastSentToken = null;
728
+ /** Listeners d'erreurs de transport (handshake refusé, coupure, connexion morte). */
729
+ _errorListeners = /* @__PURE__ */ new Set();
730
+ /**
731
+ * `true` entre l'envoi d'un ping et la réception du message serveur suivant.
732
+ * S'il est encore `true` au tick de heartbeat suivant, aucun octet applicatif
733
+ * n'est revenu en 25 s alors que le serveur en pousse au moins un toutes les
734
+ * 30 s et répond au ping : la connexion est morte (TCP à demi-fermé).
735
+ */
736
+ _awaitingPong = false;
737
+ /** Backoff delays in ms: 1s, 2s, 4s, 8s, 16s, 30s (cap) */
738
+ static BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
739
+ constructor(client) {
740
+ this.client = client;
741
+ }
742
+ /** Current connection state. */
743
+ get connectionState() {
744
+ return this._state;
745
+ }
746
+ /** Listen for connection state changes. */
747
+ onStateChange(callback) {
748
+ this._stateListeners.add(callback);
749
+ return () => this._stateListeners.delete(callback);
750
+ }
751
+ _setState(state) {
752
+ this._state = state;
753
+ for (const cb of this._stateListeners) {
754
+ try {
755
+ cb(state);
756
+ } catch {
757
+ }
758
+ }
759
+ }
760
+ /**
761
+ * Écoute les erreurs de transport de la connexion realtime.
762
+ *
763
+ * Complète `onStateChange` (qui ne dit que « ça a bougé ») en fournissant la
764
+ * CAUSE : handshake refusé (typiquement un 401 sur le token/apikey), coupure
765
+ * inattendue, ou connexion morte détectée par le heartbeat. Sans ce canal,
766
+ * un refus d'authentification était totalement silencieux — la boucle de
767
+ * reconnexion tournait indéfiniment sans que l'appelant puisse le savoir.
768
+ *
769
+ * @returns Une fonction de désabonnement.
770
+ *
771
+ * @example
772
+ * ```ts
773
+ * aura.realtime.onError((err) => {
774
+ * if (err.phase === 'handshake') {
775
+ * // token expiré / apikey invalide → renouveler la session
776
+ * }
777
+ * })
778
+ * ```
779
+ */
780
+ onError(callback) {
781
+ this._errorListeners.add(callback);
782
+ return () => this._errorListeners.delete(callback);
783
+ }
784
+ /**
785
+ * Diffuse une erreur de transport : aux listeners `onError`, puis à tous les
786
+ * canaux sous forme de `CHANNEL_ERROR` (mécanisme officiel Supabase — chez
787
+ * phoenix, `Socket#triggerChanError` fait exactement cela).
788
+ *
789
+ * Chaque callback est isolé : un listener qui jette ne doit jamais interrompre
790
+ * la diffusion ni la boucle de reconnexion.
791
+ */
792
+ _emitError(err) {
793
+ const listeners = Array.from(this._errorListeners);
794
+ const channels = Array.from(this._channels.values());
795
+ for (const cb of listeners) {
796
+ try {
797
+ cb(err);
798
+ } catch {
799
+ }
800
+ }
801
+ for (const ch of channels) {
802
+ try {
803
+ ch._signalError(err);
804
+ } catch {
805
+ }
806
+ }
807
+ }
808
+ // ─── WebSocket URL ──────────────────────────────────────────────────────
809
+ get _wsUrl() {
810
+ const base = this.client.baseUrl.replace(/^http/, "ws");
811
+ return `${base}/v1/realtime/ws`;
812
+ }
813
+ // ─── Connection management ──────────────────────────────────────────────
814
+ /** Ensure the WebSocket connection is open. */
815
+ connect() {
816
+ if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
817
+ return;
818
+ }
819
+ this._intentionalClose = false;
820
+ this._setState("connecting");
821
+ const token = this.client.authStore.token;
822
+ const params = new URLSearchParams();
823
+ if (token) params.set("token", token);
824
+ if (this.client.apiKey) params.set("apikey", this.client.apiKey);
825
+ const url = `${this._wsUrl}?${params.toString()}`;
826
+ const ws = new WebSocket(url);
827
+ this._ws = ws;
828
+ let opened = false;
829
+ ws.onopen = () => {
830
+ if (ws !== this._ws) {
831
+ try {
832
+ ws.close();
833
+ } catch {
834
+ }
835
+ return;
836
+ }
837
+ opened = true;
838
+ this._reconnectAttempts = 0;
839
+ this._setState("connected");
840
+ this._awaitingPong = false;
841
+ this._heartbeat.start(() => this._heartbeatTick(ws), HEARTBEAT_INTERVAL_MS);
842
+ this._scheduleTokenRefresh();
843
+ for (const channel of this._channels.values()) {
844
+ channel._bindSend((data) => this._send(data));
845
+ if (channel.isSubscribed) {
846
+ channel._doSubscribe();
847
+ }
848
+ }
849
+ };
850
+ ws.onmessage = (evt) => {
851
+ if (ws !== this._ws) return;
852
+ this._awaitingPong = false;
853
+ try {
854
+ const raw = typeof evt.data === "string" ? evt.data : "";
855
+ const msg = JSON.parse(raw);
856
+ this._dispatch(msg);
857
+ } catch (e) {
858
+ if (typeof console !== "undefined") {
859
+ console.warn("[aura-realtime] Failed to parse WS message:", evt.data, e);
860
+ }
861
+ }
862
+ };
863
+ ws.onclose = (evt) => {
864
+ if (ws !== this._ws) return;
865
+ const intentional = this._intentionalClose;
866
+ this._detachSocket();
867
+ if (!intentional) {
868
+ this._emitError(
869
+ opened ? new RealtimeConnectionError(
870
+ "connection",
871
+ "Realtime : connexion WebSocket ferm\xE9e de fa\xE7on inattendue.",
872
+ { code: evt?.code, reason: evt?.reason }
873
+ ) : new RealtimeConnectionError(
874
+ "handshake",
875
+ "Realtime : \xE9chec du handshake WebSocket (ferm\xE9 avant ouverture). Causes possibles, par ordre de fr\xE9quence : authentification refus\xE9e (HTTP 401/403 \u2014 token JWT absent, expir\xE9 ou invalide, apikey rejet\xE9e), quota de connexions atteint (HTTP 429), ou serveur injoignable / en red\xE9marrage / bloqu\xE9 par un proxy ou TLS. La sp\xE9cification WebSocket n'expose pas le statut HTTP du handshake au client : le SDK ne peut pas trancher entre ces causes.",
876
+ { code: evt?.code ?? 1006, reason: evt?.reason }
877
+ )
878
+ );
879
+ }
880
+ if (intentional || this._intentionalClose) {
881
+ this._setState("disconnected");
882
+ this._intentionalClose = false;
883
+ } else if (this._autoReconnect) {
884
+ this._scheduleReconnect();
885
+ } else {
886
+ this._setState("disconnected");
887
+ }
888
+ };
889
+ ws.onerror = (evt) => {
890
+ if (ws !== this._ws) return;
891
+ if (typeof console !== "undefined") {
892
+ console.warn("[aura-realtime] WebSocket error", evt);
893
+ }
894
+ };
895
+ }
896
+ /**
897
+ * Détache le socket courant et remet à zéro tout ce qui lui était attaché.
898
+ * Partagé par `onclose` et par la détection de connexion morte (qui ne peut PAS
899
+ * compter sur un `onclose` : une socket à demi-fermée n'en émet parfois jamais).
900
+ */
901
+ _detachSocket() {
902
+ this._ws = null;
903
+ this._lastSentToken = null;
904
+ this._awaitingPong = false;
905
+ this._heartbeat.stop();
906
+ }
907
+ /**
908
+ * Un tick de heartbeat : vérifie la liveness du lien puis émet un ping.
909
+ *
910
+ * Règle (calquée sur `Socket#sendHeartbeat`/`heartbeatTimeout` de phoenix, que
911
+ * `@supabase/realtime-js` réutilise) : si le ping du tick précédent n'a été suivi
912
+ * d'AUCUN message serveur, la connexion est morte. Le contrat serveur rend cette
913
+ * règle sûre — `aura-realtime` répond au ping immédiatement ET pousse un pong
914
+ * spontané toutes les 30 s : 25 s de silence total ne peuvent pas être normaux.
915
+ */
916
+ _heartbeatTick(ws) {
917
+ if (ws !== this._ws) return;
918
+ if (ws.readyState !== WebSocket.OPEN) {
919
+ this._handleDeadConnection(
920
+ "Realtime : la connexion WebSocket n\u2019est plus ouverte mais aucun \xE9v\xE9nement de fermeture n\u2019est arriv\xE9 (socket fig\xE9). Reconnexion."
921
+ );
922
+ return;
923
+ }
924
+ if (this._awaitingPong) {
925
+ this._handleDeadConnection(
926
+ `Realtime : connexion inactive \u2014 aucune r\xE9ponse du serveur dans les ${HEARTBEAT_INTERVAL_MS} ms suivant un ping (connexion probablement morte). Reconnexion.`
927
+ );
928
+ return;
929
+ }
930
+ this._awaitingPong = true;
931
+ this._send(JSON.stringify({ type: "ping" }));
932
+ }
933
+ /**
934
+ * Connexion « zombie » : ouverte du point de vue du système, muette en pratique.
935
+ *
936
+ * On ne peut pas se contenter d'appeler `close()` et d'attendre le `onclose` :
937
+ * sur un TCP à demi-fermé, la frame Close part dans le vide et l'événement peut
938
+ * n'arriver que bien plus tard (voire jamais). On détache donc le socket
939
+ * IMMÉDIATEMENT — la garde `ws !== this._ws` neutralisera son `onclose` tardif —
940
+ * puis on relance le cycle de reconnexion nous-mêmes.
941
+ */
942
+ _handleDeadConnection(message) {
943
+ const dead = this._ws;
944
+ this._detachSocket();
945
+ if (dead) {
946
+ try {
947
+ dead.close();
948
+ } catch {
949
+ }
950
+ }
951
+ this._emitError(new RealtimeConnectionError("liveness", message));
952
+ if (this._autoReconnect && !this._intentionalClose) {
953
+ this._scheduleReconnect();
954
+ } else {
955
+ this._intentionalClose = false;
956
+ this._setState("disconnected");
957
+ }
958
+ }
959
+ /** Send raw data through the WebSocket. */
960
+ _send(data) {
961
+ if (this._ws && this._ws.readyState === WebSocket.OPEN) {
962
+ this._ws.send(data);
963
+ }
964
+ }
965
+ /** Refresh the JWT token on an existing connection (no disconnect). */
966
+ refreshToken(token) {
967
+ if (token === this._lastSentToken) {
968
+ this._scheduleTokenRefresh();
969
+ return;
970
+ }
971
+ this._lastSentToken = token;
972
+ this._send(JSON.stringify({ type: "access_token", token }));
973
+ this._scheduleTokenRefresh();
974
+ }
975
+ /**
976
+ * Définit/rafraîchit explicitement le token utilisé pour l'autorisation des
977
+ * canaux privés et broadcast (parité `@supabase/realtime-js` `setAuth`).
978
+ *
979
+ * - Avec `token` : utilise ce token. Sinon, reprend `client.authStore.token`.
980
+ * - Propage via le pipeline existant `refreshToken` (push
981
+ * `{ type:'access_token', token }` sur une connexion ouverte, dédupliqué via
982
+ * `_lastSentToken`). N'ouvre ni ne ferme aucune connexion WS.
983
+ * - Hors-ligne : `connect()` lit `client.authStore.token` au moment de l'open,
984
+ * donc `setAuth()` doit être appelé avec un token présent dans le store (ou
985
+ * après authentification) pour prendre effet sur une future connexion.
986
+ *
987
+ * À appeler AVANT de s'abonner à un canal privé (`channel(name,{private:true})`).
988
+ *
989
+ * @example
990
+ * ```ts
991
+ * aura.realtime.setAuth(session.access_token)
992
+ * const ch = aura.realtime.channel('secret', { private: true }).subscribe()
993
+ * ```
994
+ */
995
+ setAuth(token) {
996
+ const resolved = token ?? this.client.authStore.token;
997
+ if (resolved == null) return;
998
+ this.refreshToken(resolved);
999
+ }
1000
+ /**
1001
+ * Envoie un broadcast par HTTP (REST), sans connexion WebSocket ouverte
1002
+ * (parité `@supabase/realtime-js`). Utile côté serveur/edge.
1003
+ *
1004
+ * POST `/v1/realtime/{projectId}/broadcast` avec le contrat du handler backend
1005
+ * (`broadcast.rs`) : `{ channel, payload }`, `channel` préfixé par le projet,
1006
+ * `event` replié dans `payload` (aligné sur le broadcast WS).
1007
+ *
1008
+ * @param channel Nom du canal (préfixé projet automatiquement si absent).
1009
+ * @param event Nom de l'événement broadcast.
1010
+ * @param payload Données de l'événement.
1011
+ * @returns `AuraResponse<null>` — `error` non nul en cas de 4xx/rate-limit.
1012
+ *
1013
+ * @example
1014
+ * ```ts
1015
+ * await aura.realtime.httpBroadcast('room-1', 'cursor', { x: 10, y: 20 })
1016
+ * ```
1017
+ */
1018
+ httpBroadcast(channel, event, payload = {}) {
1019
+ const prefix = `${this.client.projectId}:`;
1020
+ const fullChannel = channel.startsWith(prefix) ? channel : `${prefix}${channel}`;
1021
+ const body = {
1022
+ channel: fullChannel,
1023
+ payload: { event, ...payload }
1024
+ };
1025
+ return fetchWithAuth(
1026
+ `${this.client.baseUrl}/v1/realtime/${this.client.projectId}/broadcast`,
1027
+ { method: "POST", body },
1028
+ this.client
1029
+ );
1030
+ }
1031
+ /**
1032
+ * Schedule proactive token refresh at 80% of the JWT TTL.
1033
+ * Prevents token expiration during an active WebSocket session.
1034
+ */
1035
+ _scheduleTokenRefresh() {
1036
+ if (this._tokenRefreshTimer) {
1037
+ clearTimeout(this._tokenRefreshTimer);
1038
+ this._tokenRefreshTimer = null;
1039
+ }
1040
+ const token = this.client.authStore.token;
1041
+ if (!token) return;
1042
+ const exp = getTokenExpiryMs(token);
1043
+ if (exp === null) return;
1044
+ const ttl = exp - Date.now();
1045
+ if (ttl <= 0) return;
1046
+ const refreshIn = ttl * 0.8;
1047
+ if (refreshIn > MAX_TIMEOUT_MS) {
1048
+ this._tokenRefreshTimer = setTimeout(() => {
1049
+ this._tokenRefreshTimer = null;
1050
+ this._scheduleTokenRefresh();
1051
+ }, MAX_TIMEOUT_MS);
1052
+ return;
1053
+ }
1054
+ this._tokenRefreshTimer = setTimeout(async () => {
1055
+ this._tokenRefreshTimer = null;
1056
+ try {
1057
+ const res = await this.client.auth.refreshSession();
1058
+ if (res.data) {
1059
+ this.refreshToken(res.data.access_token);
1060
+ }
1061
+ } catch {
1062
+ }
1063
+ }, refreshIn);
1064
+ }
1065
+ /** Schedule a reconnection attempt with exponential backoff + jitter. */
1066
+ _scheduleReconnect() {
1067
+ if (this._reconnectTimer) {
1068
+ clearTimeout(this._reconnectTimer);
1069
+ this._reconnectTimer = null;
1070
+ }
1071
+ if (this._reconnectAttempts >= this._maxReconnectAttempts) {
1072
+ this._setState("disconnected");
1073
+ return;
1074
+ }
1075
+ this._reconnectAttempts++;
1076
+ this._setState("reconnecting");
1077
+ const idx = Math.min(this._reconnectAttempts - 1, _RealtimeService.BACKOFF_MS.length - 1);
1078
+ const baseDelay = _RealtimeService.BACKOFF_MS[idx];
1079
+ const jitter = Math.random() * baseDelay * 0.25;
1080
+ const delay = baseDelay + jitter;
1081
+ this._reconnectTimer = setTimeout(() => {
1082
+ this._reconnectTimer = null;
1083
+ this.connect();
1084
+ }, delay);
1085
+ }
1086
+ /** Enable/disable auto-reconnect (enabled by default). */
1087
+ setAutoReconnect(enabled, maxAttempts) {
1088
+ this._autoReconnect = enabled;
1089
+ if (maxAttempts !== void 0) this._maxReconnectAttempts = maxAttempts;
1090
+ }
1091
+ /** Disconnect the WebSocket and clean up all channels. */
1092
+ disconnect() {
1093
+ this._intentionalClose = true;
1094
+ this._heartbeat.stop();
1095
+ if (this._tokenRefreshTimer) {
1096
+ clearTimeout(this._tokenRefreshTimer);
1097
+ this._tokenRefreshTimer = null;
1098
+ }
1099
+ if (this._reconnectTimer) {
1100
+ clearTimeout(this._reconnectTimer);
1101
+ this._reconnectTimer = null;
1102
+ }
1103
+ this._reconnectAttempts = 0;
1104
+ this._awaitingPong = false;
1105
+ for (const channel of this._channels.values()) {
1106
+ channel.unsubscribe();
1107
+ }
1108
+ this._channels.clear();
1109
+ if (this._ws) {
1110
+ this._ws.close();
1111
+ this._ws = null;
1112
+ }
1113
+ this._setState("disconnected");
1114
+ this._lastSentToken = null;
1115
+ }
1116
+ // ─── Channel factory ────────────────────────────────────────────────────
1117
+ /**
1118
+ * Create or retrieve a channel by name.
1119
+ * Returns an `AuraChannel` with chainable `.on()` / `.subscribe()` API.
1120
+ *
1121
+ * @example
1122
+ * ```ts
1123
+ * const channel = aura.realtime.channel('room-1')
1124
+ * ```
1125
+ */
1126
+ channel(name, options) {
1127
+ const existing = this._channels.get(name);
1128
+ if (existing) return existing;
1129
+ const ch = new AuraChannel(name, this.client.projectId, options);
1130
+ this._channels.set(name, ch);
1131
+ this.connect();
1132
+ if (this._ws && this._ws.readyState === WebSocket.OPEN) {
1133
+ ch._bindSend((data) => this._send(data));
1134
+ }
1135
+ return ch;
1136
+ }
1137
+ /** Remove a channel. */
1138
+ removeChannel(name) {
1139
+ const ch = this._channels.get(name);
1140
+ if (ch) {
1141
+ ch.unsubscribe();
1142
+ this._channels.delete(name);
1143
+ }
1144
+ }
1145
+ /** List active channels. */
1146
+ getChannels() {
1147
+ return Array.from(this._channels.values());
1148
+ }
1149
+ /** Remove all channels and subscriptions. */
1150
+ removeAllChannels() {
1151
+ for (const ch of this._channels.values()) {
1152
+ ch.unsubscribe();
1153
+ }
1154
+ this._channels.clear();
1155
+ }
1156
+ // ─── Message dispatch ───────────────────────────────────────────────────
1157
+ /** Route incoming server messages to the correct channel. */
1158
+ _dispatch(msg) {
1159
+ const channelFull = "channel" in msg ? msg.channel : "topic" in msg ? msg.topic : void 0;
1160
+ if (channelFull) {
1161
+ const prefix = `${this.client.projectId}:`;
1162
+ const name = channelFull.startsWith(prefix) ? channelFull.slice(prefix.length) : channelFull;
1163
+ const ch = this._channels.get(name);
1164
+ if (ch) {
1165
+ ch._onMessage(msg);
1166
+ return;
1167
+ }
1168
+ for (const [, channel] of this._channels) {
1169
+ if (channel.fullName === channelFull || channelFull.startsWith(channel.fullName + ":")) {
1170
+ channel._onMessage(msg);
1171
+ return;
1172
+ }
1173
+ }
1174
+ }
1175
+ if (msg.type === "token_refreshed") {
1176
+ return;
1177
+ }
1178
+ if (msg.type === "pong") {
1179
+ return;
1180
+ }
1181
+ if (msg.type === "broadcast_ack") {
1182
+ const ack = msg;
1183
+ const refId = ack.ref_id ?? ack.message_id;
1184
+ if (refId) {
1185
+ const marker = refId.lastIndexOf(":r");
1186
+ if (marker > 0) {
1187
+ const fullName = refId.slice(0, marker);
1188
+ for (const ch of this._channels.values()) {
1189
+ if (ch.fullName === fullName) {
1190
+ ch._onMessage(msg);
1191
+ return;
1192
+ }
1193
+ }
1194
+ }
1195
+ }
1196
+ for (const ch of this._channels.values()) {
1197
+ ch._onMessage(msg);
1198
+ }
1199
+ return;
1200
+ }
1201
+ if (msg.type === "error") {
1202
+ for (const ch of this._channels.values()) {
1203
+ ch._onMessage(msg);
1204
+ }
1205
+ }
1206
+ }
1207
+ // ─── Backward compatibility ─────────────────────────────────────────────
1208
+ /**
1209
+ * Simple callback-based subscription (legacy API).
1210
+ * Prefer using `.channel().on().subscribe()` instead.
1211
+ *
1212
+ * @deprecated Use `channel().on().subscribe()` instead.
1213
+ */
1214
+ on(channelName, callback) {
1215
+ this.connect();
1216
+ const ch = this.channel(channelName);
1217
+ ch.on("postgres_changes", { event: "*" }, callback);
1218
+ ch.subscribe();
1219
+ return {
1220
+ unsubscribe: () => this.removeChannel(channelName)
1221
+ };
1222
+ }
1223
+ };
1224
+
1225
+ export { AuraChannel, DEFAULT_SUBSCRIBE_TIMEOUT_MS, HEARTBEAT_INTERVAL_MS, HeartbeatManager, RealtimeConnectionError, RealtimeService };