@aurabase/aurabase-js 0.3.1 → 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.
Files changed (86) hide show
  1. package/README.md +26 -795
  2. package/{packages/aurabase/dist/AuraClient-DAtDbfPB.d.ts → dist/AuraClient-BcFE8u1v.d.cts} +1 -1
  3. package/{packages/aurabase/dist/AuraClient-DAtDbfPB.d.cts → dist/AuraClient-BcFE8u1v.d.ts} +1 -1
  4. package/{packages/aurabase/dist → dist}/index.d.cts +1 -1
  5. package/{packages/aurabase/dist → dist}/index.d.ts +1 -1
  6. package/{packages/aurabase/dist → dist}/ssr.d.cts +1 -1
  7. package/{packages/aurabase/dist → dist}/ssr.d.ts +1 -1
  8. package/package.json +72 -82
  9. package/.changeset/config.json +0 -11
  10. package/CHANGELOG.md +0 -30
  11. package/packages/ai/LICENSE +0 -21
  12. package/packages/ai/README.md +0 -106
  13. package/packages/ai/dist/index.cjs +0 -229
  14. package/packages/ai/dist/index.d.cts +0 -139
  15. package/packages/ai/dist/index.d.ts +0 -139
  16. package/packages/ai/dist/index.js +0 -226
  17. package/packages/ai/package.json +0 -61
  18. package/packages/aurabase/LICENSE +0 -21
  19. package/packages/aurabase/README.md +0 -64
  20. package/packages/aurabase/package.json +0 -80
  21. package/packages/aurabase/vitest.e2e.config.ts +0 -9
  22. package/packages/auth/LICENSE +0 -21
  23. package/packages/auth/README.md +0 -215
  24. package/packages/auth/dist/index.cjs +0 -1175
  25. package/packages/auth/dist/index.d.cts +0 -397
  26. package/packages/auth/dist/index.d.ts +0 -397
  27. package/packages/auth/dist/index.js +0 -1170
  28. package/packages/auth/package.json +0 -61
  29. package/packages/core/LICENSE +0 -21
  30. package/packages/core/README.md +0 -132
  31. package/packages/core/dist/index.cjs +0 -695
  32. package/packages/core/dist/index.d.cts +0 -1137
  33. package/packages/core/dist/index.d.ts +0 -1137
  34. package/packages/core/dist/index.js +0 -673
  35. package/packages/core/package.json +0 -57
  36. package/packages/db/LICENSE +0 -21
  37. package/packages/db/README.md +0 -152
  38. package/packages/db/VENDORED.md +0 -93
  39. package/packages/db/dist/index.cjs +0 -544
  40. package/packages/db/dist/index.d.cts +0 -1111
  41. package/packages/db/dist/index.d.ts +0 -1111
  42. package/packages/db/dist/index.js +0 -541
  43. package/packages/db/package.json +0 -62
  44. package/packages/functions/LICENSE +0 -21
  45. package/packages/functions/README.md +0 -96
  46. package/packages/functions/dist/index.cjs +0 -173
  47. package/packages/functions/dist/index.d.cts +0 -81
  48. package/packages/functions/dist/index.d.ts +0 -81
  49. package/packages/functions/dist/index.js +0 -168
  50. package/packages/functions/package.json +0 -60
  51. package/packages/gen/LICENSE +0 -21
  52. package/packages/gen/README.md +0 -84
  53. package/packages/gen/dist/cli.cjs +0 -334
  54. package/packages/gen/dist/cli.d.cts +0 -1
  55. package/packages/gen/dist/cli.d.ts +0 -1
  56. package/packages/gen/dist/cli.js +0 -332
  57. package/packages/gen/dist/index.cjs +0 -257
  58. package/packages/gen/dist/index.d.cts +0 -12
  59. package/packages/gen/dist/index.d.ts +0 -12
  60. package/packages/gen/dist/index.js +0 -255
  61. package/packages/gen/package.json +0 -66
  62. package/packages/notifications/LICENSE +0 -21
  63. package/packages/notifications/README.md +0 -134
  64. package/packages/notifications/dist/index.cjs +0 -128
  65. package/packages/notifications/dist/index.d.cts +0 -81
  66. package/packages/notifications/dist/index.d.ts +0 -81
  67. package/packages/notifications/dist/index.js +0 -125
  68. package/packages/notifications/package.json +0 -60
  69. package/packages/realtime/LICENSE +0 -21
  70. package/packages/realtime/README.md +0 -183
  71. package/packages/realtime/dist/index.cjs +0 -977
  72. package/packages/realtime/dist/index.d.cts +0 -259
  73. package/packages/realtime/dist/index.d.ts +0 -259
  74. package/packages/realtime/dist/index.js +0 -973
  75. package/packages/realtime/package.json +0 -60
  76. package/packages/storage/LICENSE +0 -21
  77. package/packages/storage/README.md +0 -141
  78. package/packages/storage/dist/index.cjs +0 -333
  79. package/packages/storage/dist/index.d.cts +0 -185
  80. package/packages/storage/dist/index.d.ts +0 -185
  81. package/packages/storage/dist/index.js +0 -329
  82. package/packages/storage/package.json +0 -60
  83. /package/{packages/aurabase/dist → dist}/index.cjs +0 -0
  84. /package/{packages/aurabase/dist → dist}/index.js +0 -0
  85. /package/{packages/aurabase/dist → dist}/ssr.cjs +0 -0
  86. /package/{packages/aurabase/dist → dist}/ssr.js +0 -0
@@ -1,973 +0,0 @@
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 AuraChannel = class {
194
- name;
195
- _projectId;
196
- _listeners = [];
197
- _subscribed = false;
198
- _sendFn = null;
199
- _subscribeCallback = null;
200
- _presenceState = {};
201
- _isPrivate = false;
202
- _broadcastAck = false;
203
- _broadcastSelf = false;
204
- _presenceKey = "";
205
- /** ID de subscription retourné par le serveur (utilisé pour le filtre RLS allowed_sub_ids) */
206
- _subscriptionId = null;
207
- /** Compteur pour générer des ref_id uniques par connexion */
208
- _refCounter = 0;
209
- /** Dernier event ID recu — utilise pour since_id au reconnect */
210
- _lastEventId = null;
211
- /** Pending ACK callbacks : ref_id → resolve */
212
- _pendingAcks = /* @__PURE__ */ new Map();
213
- constructor(name, projectId, options) {
214
- this.name = name;
215
- this._projectId = projectId;
216
- this._isPrivate = options?.private ?? false;
217
- this._broadcastAck = options?.broadcast?.ack ?? false;
218
- this._broadcastSelf = options?.broadcast?.self ?? false;
219
- this._presenceKey = options?.config?.presence?.key ?? "";
220
- }
221
- /** Génère un ref_id unique pour la corrélation request/response. */
222
- _nextRef() {
223
- return `${this.fullName}:r${++this._refCounter}`;
224
- }
225
- /** Full channel name with project prefix (for server protocol) */
226
- get fullName() {
227
- return `${this._projectId}:${this.name}`;
228
- }
229
- on(type, filter, callback) {
230
- this._listeners.push({ type, filter, callback });
231
- return this;
232
- }
233
- // ─── Subscribe ──────────────────────────────────────────────────────────
234
- /**
235
- * Subscribe to the channel. Sends the Subscribe message to the server
236
- * with the full config (postgres_changes, broadcast, presence).
237
- */
238
- subscribe(callback) {
239
- this._subscribeCallback = callback ?? null;
240
- this._subscribed = true;
241
- if (this._sendFn) {
242
- this._doSubscribe();
243
- }
244
- return this;
245
- }
246
- /** Called by RealtimeService once the WS connection is ready. */
247
- _bindSend(sendFn) {
248
- this._sendFn = sendFn;
249
- }
250
- /** Send the subscribe message to the server. */
251
- _doSubscribe() {
252
- if (!this._sendFn) return;
253
- const pgFilters = this._listeners.filter((l) => l.type === "postgres_changes").map((l) => l.filter);
254
- const msg = {
255
- type: "subscribe",
256
- channel: this.fullName,
257
- ref_id: this._nextRef(),
258
- since_id: this._lastEventId ?? void 0,
259
- config: {
260
- postgres_changes: pgFilters,
261
- broadcast: {
262
- self_broadcast: this._broadcastSelf,
263
- // ← depuis les options du channel
264
- ack: this._broadcastAck
265
- // ← depuis les options du channel
266
- },
267
- presence: { key: this._presenceKey },
268
- // ← depuis les options du channel
269
- private: this._isPrivate
270
- }
271
- };
272
- this._sendFn(JSON.stringify(msg));
273
- }
274
- /** Unsubscribe from the channel. */
275
- unsubscribe() {
276
- if (this._sendFn) {
277
- this._sendFn(JSON.stringify({ type: "unsubscribe", channel: this.fullName }));
278
- }
279
- this._subscribed = false;
280
- this._listeners.length = 0;
281
- this._presenceState = {};
282
- }
283
- // ─── Broadcast ──────────────────────────────────────────────────────────
284
- /**
285
- * Send a broadcast message to the channel.
286
- * If broadcast.ack=true, returns a Promise that resolves when the server ACKs.
287
- *
288
- * @example
289
- * ```ts
290
- * // Without ACK (fire & forget)
291
- * channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100, y: 200 } })
292
- *
293
- * // With ACK (wait for server confirmation)
294
- * await channel.send({ type: 'broadcast', event: 'cursor-pos', payload: { x: 100 } })
295
- * ```
296
- */
297
- send(message) {
298
- return new Promise((resolve) => {
299
- if (!this._sendFn) {
300
- resolve("error");
301
- return;
302
- }
303
- const ref_id = message.ref_id ?? this._nextRef();
304
- if (this._broadcastAck) {
305
- const timer = setTimeout(() => {
306
- this._pendingAcks.delete(ref_id);
307
- resolve("timeout");
308
- }, 5e3);
309
- this._pendingAcks.set(ref_id, () => {
310
- clearTimeout(timer);
311
- resolve("ok");
312
- });
313
- } else {
314
- resolve("ok");
315
- }
316
- this._sendFn(
317
- JSON.stringify({
318
- type: "broadcast",
319
- channel: this.fullName,
320
- ref_id,
321
- payload: { event: message.event, ...message.payload }
322
- })
323
- );
324
- });
325
- }
326
- // ─── Presence ───────────────────────────────────────────────────────────
327
- /**
328
- * Track presence state for this client.
329
- * Returns a Promise that resolves with 'ok' once tracked (compatible Supabase).
330
- *
331
- * @example
332
- * ```ts
333
- * await channel.track({ user: 'user-1', online_at: new Date().toISOString() })
334
- * ```
335
- */
336
- async track(state) {
337
- if (!this._sendFn) return "error";
338
- this._sendFn(
339
- JSON.stringify({
340
- type: "presence_update",
341
- channel: this.fullName,
342
- meta: state
343
- })
344
- );
345
- return "ok";
346
- }
347
- /** Stop tracking presence. */
348
- async untrack() {
349
- return this.track({});
350
- }
351
- /** Get the current presence state for this channel. */
352
- presenceState() {
353
- return { ...this._presenceState };
354
- }
355
- // ─── Internal: dispatch server messages ──────────────────────────────────
356
- /** Called by RealtimeService when a server message arrives for this channel. */
357
- _onMessage(msg) {
358
- switch (msg.type) {
359
- case "subscribed": {
360
- const subMsg = msg;
361
- if (subMsg.subscription_id) this._subscriptionId = subMsg.subscription_id;
362
- this._subscribeCallback?.("SUBSCRIBED");
363
- break;
364
- }
365
- case "event": {
366
- const evtMsg = msg;
367
- if (evtMsg.id) {
368
- const event = {
369
- id: evtMsg.id,
370
- event: evtMsg.event,
371
- topic: evtMsg.topic,
372
- payload: evtMsg.payload,
373
- timestamp: evtMsg.timestamp,
374
- allowed_sub_ids: evtMsg.allowed_sub_ids
375
- };
376
- this._dispatchEvent(event);
377
- }
378
- break;
379
- }
380
- case "presence_state": {
381
- const presMsg = msg;
382
- if (presMsg.presences) {
383
- this._presenceState = {};
384
- for (const p of presMsg.presences) {
385
- const key = p.user_id || p.client_id;
386
- if (!this._presenceState[key]) this._presenceState[key] = [];
387
- this._presenceState[key].push(p);
388
- }
389
- for (const l of this._listeners) {
390
- if (l.type === "presence" && l.filter.event === "sync") {
391
- l.callback(this._presenceState);
392
- }
393
- }
394
- }
395
- break;
396
- }
397
- case "error": {
398
- const errMsg = msg;
399
- this._subscribeCallback?.("CHANNEL_ERROR", new Error(errMsg.message ?? "Unknown error"));
400
- break;
401
- }
402
- case "token_refreshed":
403
- break;
404
- case "broadcast_ack": {
405
- const ackMsg = msg;
406
- const refId = ackMsg.ref_id ?? ackMsg.message_id;
407
- if (refId) {
408
- const resolve = this._pendingAcks.get(refId);
409
- if (resolve) {
410
- this._pendingAcks.delete(refId);
411
- resolve();
412
- }
413
- }
414
- break;
415
- }
416
- }
417
- }
418
- /** Dispatch a RealtimeEvent to matching listeners. */
419
- _dispatchEvent(event) {
420
- if (!event) return;
421
- if (event.id) this._lastEventId = event.id;
422
- const allowed = event.allowed_sub_ids;
423
- if (allowed && this._subscriptionId && !allowed.includes(this._subscriptionId)) {
424
- return;
425
- }
426
- const eventType = event.event;
427
- if (eventType === "presence") {
428
- const payload = event.payload;
429
- const action = payload.action;
430
- const key = payload.user_id || payload.client_id;
431
- if (action === "join") {
432
- if (!this._presenceState[key]) this._presenceState[key] = [];
433
- if (!this._presenceState[key].some((p) => p.client_id === payload.client_id)) {
434
- const presenceInfo = {
435
- client_id: payload.client_id,
436
- user_id: payload.user_id ?? void 0,
437
- metadata: payload.metadata ?? payload.meta ?? {},
438
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
439
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
440
- };
441
- this._presenceState[key].push(presenceInfo);
442
- }
443
- } else if (action === "leave") {
444
- const arr = this._presenceState[key];
445
- if (arr) {
446
- const idx = arr.findIndex((p) => p.client_id === payload.client_id);
447
- if (idx >= 0) arr.splice(idx, 1);
448
- if (arr.length === 0) delete this._presenceState[key];
449
- }
450
- } else if (action === "update") {
451
- const arr = this._presenceState[key];
452
- if (arr) {
453
- const idx = arr.findIndex((p) => p.client_id === payload.client_id);
454
- if (idx >= 0) {
455
- arr[idx].metadata = payload.metadata ?? payload.meta ?? {};
456
- arr[idx].last_seen = (/* @__PURE__ */ new Date()).toISOString();
457
- } else {
458
- const presenceInfo = {
459
- client_id: payload.client_id,
460
- user_id: payload.user_id ?? void 0,
461
- metadata: payload.metadata ?? payload.meta ?? {},
462
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
463
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
464
- };
465
- this._presenceState[key].push(presenceInfo);
466
- }
467
- } else {
468
- this._presenceState[key] = [{
469
- client_id: payload.client_id,
470
- user_id: payload.user_id ?? void 0,
471
- metadata: payload.metadata ?? payload.meta ?? {},
472
- joined_at: (/* @__PURE__ */ new Date()).toISOString(),
473
- last_seen: (/* @__PURE__ */ new Date()).toISOString()
474
- }];
475
- }
476
- }
477
- }
478
- for (const listener of this._listeners) {
479
- if (listener.type === "postgres_changes") {
480
- const filter = listener.filter;
481
- if (eventType === "insert" || eventType === "update" || eventType === "delete") {
482
- const filterEvent = filter.event.toLowerCase();
483
- if (filterEvent === "*" || filterEvent === eventType) {
484
- const payload = event.payload;
485
- if (filter.schema && payload.schema !== filter.schema) continue;
486
- if (filter.table && payload.table !== filter.table) continue;
487
- if (filter.filter) {
488
- const target = eventType === "delete" ? payload.old_record : payload.record;
489
- if (target && typeof target === "object") {
490
- if (!matchesColumnFilter(filter.filter, target)) {
491
- continue;
492
- }
493
- }
494
- }
495
- listener.callback(event);
496
- }
497
- }
498
- } else if (listener.type === "broadcast") {
499
- if (eventType === "broadcast") {
500
- const filter = listener.filter;
501
- const payload = event.payload;
502
- if (!filter.event || payload.event === filter.event) {
503
- listener.callback(event);
504
- }
505
- }
506
- } else if (listener.type === "presence") {
507
- if (eventType === "presence") {
508
- const filter = listener.filter;
509
- const payload = event.payload;
510
- const action = payload.action;
511
- if (filter.event === "join" && action === "join") {
512
- listener.callback({
513
- key: payload.user_id || payload.client_id,
514
- newPresences: [payload]
515
- });
516
- } else if (filter.event === "leave" && action === "leave") {
517
- listener.callback({
518
- key: payload.user_id || payload.client_id,
519
- leftPresences: [payload]
520
- });
521
- } else if (filter.event === "sync") {
522
- listener.callback(this.presenceState());
523
- }
524
- }
525
- }
526
- }
527
- }
528
- /** Whether this channel has been subscribed. */
529
- get isSubscribed() {
530
- return this._subscribed;
531
- }
532
- /** Get listeners (for re-subscribe after reconnect). */
533
- _getListeners() {
534
- return this._listeners;
535
- }
536
- };
537
-
538
- // src/HeartbeatManager.ts
539
- var HeartbeatManager = class {
540
- _worker = null;
541
- _workerUrl = null;
542
- _interval = null;
543
- _sendFn = null;
544
- start(sendPing, intervalMs = 25e3) {
545
- this.stop();
546
- this._sendFn = sendPing;
547
- if (typeof Worker !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function") {
548
- try {
549
- 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;}}};`;
550
- const blob = new Blob([code], { type: "application/javascript" });
551
- this._workerUrl = URL.createObjectURL(blob);
552
- this._worker = new Worker(this._workerUrl);
553
- this._worker.onmessage = () => {
554
- this._sendFn?.();
555
- };
556
- this._worker.postMessage({ type: "start", interval: intervalMs });
557
- return;
558
- } catch {
559
- this._worker = null;
560
- if (this._workerUrl) {
561
- try {
562
- URL.revokeObjectURL(this._workerUrl);
563
- } catch {
564
- }
565
- this._workerUrl = null;
566
- }
567
- }
568
- }
569
- this._interval = setInterval(() => {
570
- this._sendFn?.();
571
- }, intervalMs);
572
- }
573
- stop() {
574
- if (this._worker) {
575
- try {
576
- this._worker.postMessage({ type: "stop" });
577
- this._worker.terminate();
578
- } catch {
579
- }
580
- this._worker = null;
581
- }
582
- if (this._workerUrl) {
583
- try {
584
- URL.revokeObjectURL(this._workerUrl);
585
- } catch {
586
- }
587
- this._workerUrl = null;
588
- }
589
- if (this._interval) {
590
- clearInterval(this._interval);
591
- this._interval = null;
592
- }
593
- this._sendFn = null;
594
- }
595
- get isActive() {
596
- return this._worker !== null || this._interval !== null;
597
- }
598
- };
599
-
600
- // src/RealtimeService.ts
601
- var RealtimeService = class _RealtimeService {
602
- client;
603
- _ws = null;
604
- _channels = /* @__PURE__ */ new Map();
605
- _state = "disconnected";
606
- _stateListeners = /* @__PURE__ */ new Set();
607
- // ─── Reconnection state ──────────────────────────────────────────────
608
- _autoReconnect = true;
609
- _reconnectAttempts = 0;
610
- _maxReconnectAttempts = Infinity;
611
- _reconnectTimer = null;
612
- _intentionalClose = false;
613
- _heartbeat = new HeartbeatManager();
614
- _tokenRefreshTimer = null;
615
- /** Dernier access_token propagé au serveur — évite les pushs redondants (propagation différentielle). */
616
- _lastSentToken = null;
617
- /** Backoff delays in ms: 1s, 2s, 4s, 8s, 16s, 30s (cap) */
618
- static BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
619
- constructor(client) {
620
- this.client = client;
621
- }
622
- /** Current connection state. */
623
- get connectionState() {
624
- return this._state;
625
- }
626
- /** Listen for connection state changes. */
627
- onStateChange(callback) {
628
- this._stateListeners.add(callback);
629
- return () => this._stateListeners.delete(callback);
630
- }
631
- _setState(state) {
632
- this._state = state;
633
- for (const cb of this._stateListeners) {
634
- try {
635
- cb(state);
636
- } catch {
637
- }
638
- }
639
- }
640
- // ─── WebSocket URL ──────────────────────────────────────────────────────
641
- get _wsUrl() {
642
- const base = this.client.baseUrl.replace(/^http/, "ws");
643
- return `${base}/v1/realtime/ws`;
644
- }
645
- // ─── Connection management ──────────────────────────────────────────────
646
- /** Ensure the WebSocket connection is open. */
647
- connect() {
648
- if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) {
649
- return;
650
- }
651
- this._intentionalClose = false;
652
- this._setState("connecting");
653
- const token = this.client.authStore.token;
654
- const params = new URLSearchParams();
655
- if (token) params.set("token", token);
656
- if (this.client.apiKey) params.set("apikey", this.client.apiKey);
657
- const url = `${this._wsUrl}?${params.toString()}`;
658
- const ws = new WebSocket(url);
659
- this._ws = ws;
660
- ws.onopen = () => {
661
- if (ws !== this._ws) {
662
- try {
663
- ws.close();
664
- } catch {
665
- }
666
- return;
667
- }
668
- this._reconnectAttempts = 0;
669
- this._setState("connected");
670
- this._heartbeat.start(() => this._send(JSON.stringify({ type: "ping" })), 25e3);
671
- this._scheduleTokenRefresh();
672
- for (const channel of this._channels.values()) {
673
- channel._bindSend((data) => this._send(data));
674
- if (channel.isSubscribed) {
675
- channel._doSubscribe();
676
- }
677
- }
678
- };
679
- ws.onmessage = (evt) => {
680
- if (ws !== this._ws) return;
681
- try {
682
- const raw = typeof evt.data === "string" ? evt.data : "";
683
- const msg = JSON.parse(raw);
684
- this._dispatch(msg);
685
- } catch (e) {
686
- if (typeof console !== "undefined") {
687
- console.warn("[aura-realtime] Failed to parse WS message:", evt.data, e);
688
- }
689
- }
690
- };
691
- ws.onclose = () => {
692
- if (ws !== this._ws) return;
693
- this._ws = null;
694
- this._lastSentToken = null;
695
- this._heartbeat.stop();
696
- if (this._intentionalClose) {
697
- this._setState("disconnected");
698
- this._intentionalClose = false;
699
- } else if (this._autoReconnect) {
700
- this._scheduleReconnect();
701
- } else {
702
- this._setState("disconnected");
703
- }
704
- };
705
- ws.onerror = (evt) => {
706
- if (ws !== this._ws) return;
707
- if (typeof console !== "undefined") {
708
- console.warn("[aura-realtime] WebSocket error", evt);
709
- }
710
- };
711
- }
712
- /** Send raw data through the WebSocket. */
713
- _send(data) {
714
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
715
- this._ws.send(data);
716
- }
717
- }
718
- /** Refresh the JWT token on an existing connection (no disconnect). */
719
- refreshToken(token) {
720
- if (token === this._lastSentToken) {
721
- this._scheduleTokenRefresh();
722
- return;
723
- }
724
- this._lastSentToken = token;
725
- this._send(JSON.stringify({ type: "access_token", token }));
726
- this._scheduleTokenRefresh();
727
- }
728
- /**
729
- * Définit/rafraîchit explicitement le token utilisé pour l'autorisation des
730
- * canaux privés et broadcast (parité `@supabase/realtime-js` `setAuth`).
731
- *
732
- * - Avec `token` : utilise ce token. Sinon, reprend `client.authStore.token`.
733
- * - Propage via le pipeline existant `refreshToken` (push
734
- * `{ type:'access_token', token }` sur une connexion ouverte, dédupliqué via
735
- * `_lastSentToken`). N'ouvre ni ne ferme aucune connexion WS.
736
- * - Hors-ligne : `connect()` lit `client.authStore.token` au moment de l'open,
737
- * donc `setAuth()` doit être appelé avec un token présent dans le store (ou
738
- * après authentification) pour prendre effet sur une future connexion.
739
- *
740
- * À appeler AVANT de s'abonner à un canal privé (`channel(name,{private:true})`).
741
- *
742
- * @example
743
- * ```ts
744
- * aura.realtime.setAuth(session.access_token)
745
- * const ch = aura.realtime.channel('secret', { private: true }).subscribe()
746
- * ```
747
- */
748
- setAuth(token) {
749
- const resolved = token ?? this.client.authStore.token;
750
- if (resolved == null) return;
751
- this.refreshToken(resolved);
752
- }
753
- /**
754
- * Envoie un broadcast par HTTP (REST), sans connexion WebSocket ouverte
755
- * (parité `@supabase/realtime-js`). Utile côté serveur/edge.
756
- *
757
- * POST `/v1/realtime/{projectId}/broadcast` avec le contrat du handler backend
758
- * (`broadcast.rs`) : `{ channel, payload }`, `channel` préfixé par le projet,
759
- * `event` replié dans `payload` (aligné sur le broadcast WS).
760
- *
761
- * @param channel Nom du canal (préfixé projet automatiquement si absent).
762
- * @param event Nom de l'événement broadcast.
763
- * @param payload Données de l'événement.
764
- * @returns `AuraResponse<null>` — `error` non nul en cas de 4xx/rate-limit.
765
- *
766
- * @example
767
- * ```ts
768
- * await aura.realtime.httpBroadcast('room-1', 'cursor', { x: 10, y: 20 })
769
- * ```
770
- */
771
- httpBroadcast(channel, event, payload = {}) {
772
- const prefix = `${this.client.projectId}:`;
773
- const fullChannel = channel.startsWith(prefix) ? channel : `${prefix}${channel}`;
774
- const body = {
775
- channel: fullChannel,
776
- payload: { event, ...payload }
777
- };
778
- return fetchWithAuth(
779
- `${this.client.baseUrl}/v1/realtime/${this.client.projectId}/broadcast`,
780
- { method: "POST", body },
781
- this.client
782
- );
783
- }
784
- /**
785
- * Schedule proactive token refresh at 80% of the JWT TTL.
786
- * Prevents token expiration during an active WebSocket session.
787
- */
788
- _scheduleTokenRefresh() {
789
- if (this._tokenRefreshTimer) {
790
- clearTimeout(this._tokenRefreshTimer);
791
- this._tokenRefreshTimer = null;
792
- }
793
- const token = this.client.authStore.token;
794
- if (!token) return;
795
- try {
796
- const payload = JSON.parse(atob(token.split(".")[1]));
797
- const exp = payload.exp * 1e3;
798
- const ttl = exp - Date.now();
799
- if (ttl <= 0) return;
800
- const refreshIn = ttl * 0.8;
801
- this._tokenRefreshTimer = setTimeout(async () => {
802
- this._tokenRefreshTimer = null;
803
- try {
804
- const res = await this.client.auth.refreshSession();
805
- if (res.data) {
806
- this.refreshToken(res.data.access_token);
807
- }
808
- } catch {
809
- }
810
- }, refreshIn);
811
- } catch {
812
- }
813
- }
814
- /** Schedule a reconnection attempt with exponential backoff + jitter. */
815
- _scheduleReconnect() {
816
- if (this._reconnectTimer) {
817
- clearTimeout(this._reconnectTimer);
818
- this._reconnectTimer = null;
819
- }
820
- if (this._reconnectAttempts >= this._maxReconnectAttempts) {
821
- this._setState("disconnected");
822
- return;
823
- }
824
- this._reconnectAttempts++;
825
- this._setState("reconnecting");
826
- const idx = Math.min(this._reconnectAttempts - 1, _RealtimeService.BACKOFF_MS.length - 1);
827
- const baseDelay = _RealtimeService.BACKOFF_MS[idx];
828
- const jitter = Math.random() * baseDelay * 0.25;
829
- const delay = baseDelay + jitter;
830
- this._reconnectTimer = setTimeout(() => {
831
- this._reconnectTimer = null;
832
- this.connect();
833
- }, delay);
834
- }
835
- /** Enable/disable auto-reconnect (enabled by default). */
836
- setAutoReconnect(enabled, maxAttempts) {
837
- this._autoReconnect = enabled;
838
- if (maxAttempts !== void 0) this._maxReconnectAttempts = maxAttempts;
839
- }
840
- /** Disconnect the WebSocket and clean up all channels. */
841
- disconnect() {
842
- this._intentionalClose = true;
843
- this._heartbeat.stop();
844
- if (this._tokenRefreshTimer) {
845
- clearTimeout(this._tokenRefreshTimer);
846
- this._tokenRefreshTimer = null;
847
- }
848
- if (this._reconnectTimer) {
849
- clearTimeout(this._reconnectTimer);
850
- this._reconnectTimer = null;
851
- }
852
- this._reconnectAttempts = 0;
853
- for (const channel of this._channels.values()) {
854
- channel.unsubscribe();
855
- }
856
- this._channels.clear();
857
- if (this._ws) {
858
- this._ws.close();
859
- this._ws = null;
860
- }
861
- this._setState("disconnected");
862
- this._lastSentToken = null;
863
- }
864
- // ─── Channel factory ────────────────────────────────────────────────────
865
- /**
866
- * Create or retrieve a channel by name.
867
- * Returns an `AuraChannel` with chainable `.on()` / `.subscribe()` API.
868
- *
869
- * @example
870
- * ```ts
871
- * const channel = aura.realtime.channel('room-1')
872
- * ```
873
- */
874
- channel(name, options) {
875
- const existing = this._channels.get(name);
876
- if (existing) return existing;
877
- const ch = new AuraChannel(name, this.client.projectId, options);
878
- this._channels.set(name, ch);
879
- this.connect();
880
- if (this._ws && this._ws.readyState === WebSocket.OPEN) {
881
- ch._bindSend((data) => this._send(data));
882
- }
883
- return ch;
884
- }
885
- /** Remove a channel. */
886
- removeChannel(name) {
887
- const ch = this._channels.get(name);
888
- if (ch) {
889
- ch.unsubscribe();
890
- this._channels.delete(name);
891
- }
892
- }
893
- /** List active channels. */
894
- getChannels() {
895
- return Array.from(this._channels.values());
896
- }
897
- /** Remove all channels and subscriptions. */
898
- removeAllChannels() {
899
- for (const ch of this._channels.values()) {
900
- ch.unsubscribe();
901
- }
902
- this._channels.clear();
903
- }
904
- // ─── Message dispatch ───────────────────────────────────────────────────
905
- /** Route incoming server messages to the correct channel. */
906
- _dispatch(msg) {
907
- const channelFull = "channel" in msg ? msg.channel : "topic" in msg ? msg.topic : void 0;
908
- if (channelFull) {
909
- const prefix = `${this.client.projectId}:`;
910
- const name = channelFull.startsWith(prefix) ? channelFull.slice(prefix.length) : channelFull;
911
- const ch = this._channels.get(name);
912
- if (ch) {
913
- ch._onMessage(msg);
914
- return;
915
- }
916
- for (const [, channel] of this._channels) {
917
- if (channel.fullName === channelFull || channelFull.startsWith(channel.fullName + ":")) {
918
- channel._onMessage(msg);
919
- return;
920
- }
921
- }
922
- }
923
- if (msg.type === "token_refreshed") {
924
- return;
925
- }
926
- if (msg.type === "pong") {
927
- return;
928
- }
929
- if (msg.type === "broadcast_ack") {
930
- const ack = msg;
931
- const refId = ack.ref_id ?? ack.message_id;
932
- if (refId) {
933
- const marker = refId.lastIndexOf(":r");
934
- if (marker > 0) {
935
- const fullName = refId.slice(0, marker);
936
- for (const ch of this._channels.values()) {
937
- if (ch.fullName === fullName) {
938
- ch._onMessage(msg);
939
- return;
940
- }
941
- }
942
- }
943
- }
944
- for (const ch of this._channels.values()) {
945
- ch._onMessage(msg);
946
- }
947
- return;
948
- }
949
- if (msg.type === "error") {
950
- for (const ch of this._channels.values()) {
951
- ch._onMessage(msg);
952
- }
953
- }
954
- }
955
- // ─── Backward compatibility ─────────────────────────────────────────────
956
- /**
957
- * Simple callback-based subscription (legacy API).
958
- * Prefer using `.channel().on().subscribe()` instead.
959
- *
960
- * @deprecated Use `channel().on().subscribe()` instead.
961
- */
962
- on(channelName, callback) {
963
- this.connect();
964
- const ch = this.channel(channelName);
965
- ch.on("postgres_changes", { event: "*" }, callback);
966
- ch.subscribe();
967
- return {
968
- unsubscribe: () => this.removeChannel(channelName)
969
- };
970
- }
971
- };
972
-
973
- export { AuraChannel, HeartbeatManager, RealtimeService };