@facto-to/notifications 0.0.0-stage → 0.1.0-beta.1

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/core.js ADDED
@@ -0,0 +1,588 @@
1
+ const P = "sse_auth_header_required", ee = "sse_stream_lagged", U = "sse_http_error", te = "sse_session_revoked";
2
+ class W extends Error {
3
+ code;
4
+ status;
5
+ constructor(n, l, d) {
6
+ super(
7
+ l,
8
+ d?.cause !== void 0 ? { cause: d.cause } : void 0
9
+ ), this.name = "RealtimeStreamError", this.code = n, this.status = d?.status;
10
+ }
11
+ }
12
+ const J = /^\d+$/;
13
+ function V(a) {
14
+ let n = !0, l = !1, d = "", k = [], m, M, C, R;
15
+ function c() {
16
+ if (!(k.length > 0) && m === void 0) {
17
+ M = void 0, C = void 0;
18
+ return;
19
+ }
20
+ const s = {
21
+ event: m !== void 0 && m !== "" ? m : "message",
22
+ data: k.join(`
23
+ `)
24
+ };
25
+ M !== void 0 && (s.id = M), m !== void 0 && (s.explicitEvent = m), C !== void 0 && (s.retryMs = C), k = [], m = void 0, M = void 0, C = void 0, a.onFrame(s);
26
+ }
27
+ function o(t) {
28
+ if (t === "") {
29
+ c();
30
+ return;
31
+ }
32
+ if (t.startsWith(":")) {
33
+ a.onComment?.(t.slice(1));
34
+ return;
35
+ }
36
+ const r = t.indexOf(":");
37
+ let s, i;
38
+ switch (r === -1 ? (s = t, i = "") : (s = t.slice(0, r), i = t.slice(r + 1), i.startsWith(" ") && (i = i.slice(1))), s) {
39
+ case "event":
40
+ m = i;
41
+ break;
42
+ case "data":
43
+ k.push(i);
44
+ break;
45
+ case "id":
46
+ i.includes("\0") || (M = i, R = i, a.onId?.(i));
47
+ break;
48
+ case "retry":
49
+ if (J.test(i)) {
50
+ const I = Number.parseInt(i, 10);
51
+ Number.isSafeInteger(I) && (C = I, a.onRetry?.(I));
52
+ }
53
+ break;
54
+ }
55
+ }
56
+ function h(t) {
57
+ if (!t) return;
58
+ let r = t;
59
+ n && (n = !1, r.startsWith("\uFEFF") && (r = r.slice(1)));
60
+ let s = 0;
61
+ l && (l = !1, r.startsWith(`
62
+ `) && (s = 1));
63
+ for (let i = s; i < r.length; i += 1) {
64
+ const I = r.charCodeAt(i);
65
+ if (I === 10) {
66
+ const S = d + r.slice(s, i);
67
+ d = "", s = i + 1, o(S);
68
+ } else if (I === 13) {
69
+ const S = d + r.slice(s, i);
70
+ d = "", i + 1 < r.length ? r.charCodeAt(i + 1) === 10 && (i += 1) : l = !0, s = i + 1, o(S);
71
+ }
72
+ }
73
+ s < r.length && (d += r.slice(s));
74
+ }
75
+ function E() {
76
+ n = !0, l = !1, d = "", k = [], m = void 0, M = void 0, C = void 0;
77
+ }
78
+ return {
79
+ feed: h,
80
+ reset: E,
81
+ getLastEventId: () => R
82
+ };
83
+ }
84
+ function re(a) {
85
+ const n = [];
86
+ return V({
87
+ onFrame: (d) => n.push(d)
88
+ }).feed(a), n;
89
+ }
90
+ class ne {
91
+ capacity;
92
+ entries = /* @__PURE__ */ new Set();
93
+ constructor(n = 500) {
94
+ this.capacity = Number.isFinite(n) && n >= 1 ? Math.floor(n) : 500;
95
+ }
96
+ /**
97
+ * Records `key` in the LRU set.
98
+ * Returns `true` if `key` was newly added, or `false` if it was already seen.
99
+ */
100
+ remember(n) {
101
+ if (this.entries.has(n))
102
+ return this.entries.delete(n), this.entries.add(n), !1;
103
+ if (this.entries.add(n), this.entries.size > this.capacity) {
104
+ const l = this.entries.values().next().value;
105
+ l !== void 0 && this.entries.delete(l);
106
+ }
107
+ return !0;
108
+ }
109
+ has(n) {
110
+ return this.entries.has(n);
111
+ }
112
+ delete(n) {
113
+ return this.entries.delete(n);
114
+ }
115
+ clear() {
116
+ this.entries.clear();
117
+ }
118
+ get size() {
119
+ return this.entries.size;
120
+ }
121
+ }
122
+ let K = 0;
123
+ function Q() {
124
+ K += 1;
125
+ const a = String(K).padStart(8, "0"), n = Math.random().toString(36).slice(2, 10);
126
+ return `${a}-${n}`;
127
+ }
128
+ function Y(a, n) {
129
+ const l = `facto:notifications:stream:${a}`;
130
+ return n ? n(l) : typeof BroadcastChannel < "u" ? new BroadcastChannel(l) : null;
131
+ }
132
+ function X(a) {
133
+ const {
134
+ scopeKey: n,
135
+ openLeaderStream: l,
136
+ handlers: d,
137
+ broadcastChannelFactory: k
138
+ } = a, m = Math.max(10, a.electionTimeoutMs ?? 50), M = Math.max(50, a.heartbeatIntervalMs ?? 5e3), C = M * 3, R = Y(n, k);
139
+ if (!R)
140
+ return l(a.initialLastEventId, d);
141
+ const c = Q();
142
+ let o = "electing", h = null, E = "idle", t = a.initialLastEventId, r = !1, s = !1, i = null, I = null, S = null, _ = null, w = !1;
143
+ function p(f) {
144
+ E !== f && (E = f, d.onStatusChange?.(f));
145
+ }
146
+ function b() {
147
+ I !== null && (clearTimeout(I), I = null);
148
+ }
149
+ function A() {
150
+ S !== null && (clearInterval(S), S = null);
151
+ }
152
+ function F() {
153
+ _ !== null && (clearTimeout(_), _ = null);
154
+ }
155
+ function g(f) {
156
+ if (!r)
157
+ try {
158
+ R.postMessage(f);
159
+ } catch {
160
+ }
161
+ }
162
+ function T() {
163
+ F(), !(r || s || o !== "follower") && (_ = setTimeout(() => {
164
+ r || s || o !== "follower" || (h = null, O(m));
165
+ }, C));
166
+ }
167
+ function H() {
168
+ if (A(), i) {
169
+ const f = i;
170
+ i = null, f.close();
171
+ }
172
+ }
173
+ function D(f, e) {
174
+ s || (s = !0, b(), F(), e && g({ type: "stream-revoked", leaderId: c, rawData: f }), H(), p("revoked"), d.onSessionRevoked?.(f));
175
+ }
176
+ function q() {
177
+ if (r || s || o === "leader") return;
178
+ b(), F(), o = "leader", h = c, w = !1, g({
179
+ type: "leader-announce",
180
+ leaderId: c,
181
+ status: "connecting",
182
+ lastEventId: t,
183
+ revoked: !1
184
+ }), i = l(t, {
185
+ onOpen: () => {
186
+ if (r || s) return;
187
+ t = i?.getLastEventId() ?? t, g({ type: "stream-open", leaderId: c, lastEventId: t }), d.onOpen?.();
188
+ },
189
+ onFrame: (e) => {
190
+ r || s || (e.id !== void 0 && (t = e.id), g({
191
+ type: "stream-frame",
192
+ leaderId: c,
193
+ frame: e,
194
+ lastEventId: t
195
+ }), d.onFrame(e));
196
+ },
197
+ onLagged: (e, u) => {
198
+ r || s || (g({
199
+ type: "stream-lagged",
200
+ leaderId: c,
201
+ droppedCount: e,
202
+ rawData: u,
203
+ lastEventId: t
204
+ }), d.onLagged?.(e, u));
205
+ },
206
+ onResync: (e) => {
207
+ r || s || (g({
208
+ type: "stream-resync",
209
+ leaderId: c,
210
+ reason: e,
211
+ lastEventId: t
212
+ }), d.onResync?.(e));
213
+ },
214
+ onSessionRevoked: (e) => {
215
+ D(e, !0);
216
+ },
217
+ onStatusChange: (e) => {
218
+ r || s || (p(e), g({
219
+ type: "stream-status",
220
+ leaderId: c,
221
+ status: e,
222
+ lastEventId: t
223
+ }));
224
+ },
225
+ onTransportError: (e) => {
226
+ r || s || d.onTransportError?.(e);
227
+ }
228
+ }), A(), S = setInterval(() => {
229
+ if (r || s || o !== "leader") return;
230
+ t = i?.getLastEventId() ?? t, g({
231
+ type: "leader-heartbeat",
232
+ leaderId: c,
233
+ status: E,
234
+ lastEventId: t
235
+ });
236
+ }, M);
237
+ }
238
+ function j(f, e, u) {
239
+ b(), o === "leader" && H(), o = "follower", h = f, u !== void 0 && (t = u), T(), e !== "idle" && (p(e), e === "open" && !w && (w = !0, d.onOpen?.()));
240
+ }
241
+ function O(f) {
242
+ r || s || (b(), F(), o = "electing", h = null, w = !1, p("connecting"), g({ type: "leader-query", tabId: c }), I = setTimeout(() => {
243
+ I = null, !(r || s || o !== "electing") && q();
244
+ }, f));
245
+ }
246
+ function $(f) {
247
+ if (r || s) return;
248
+ const e = f.data;
249
+ if (!(!e || typeof e != "object" || typeof e.type != "string"))
250
+ switch (e.type) {
251
+ case "leader-query": {
252
+ if (e.tabId === c) return;
253
+ o === "leader" ? g({
254
+ type: "leader-announce",
255
+ leaderId: c,
256
+ status: E,
257
+ lastEventId: i?.getLastEventId() ?? t,
258
+ revoked: s
259
+ }) : o === "electing" && (c < e.tabId ? g({ type: "leader-candidate", tabId: c }) : (b(), I = setTimeout(() => {
260
+ I = null, !r && !s && o === "electing" && q();
261
+ }, m * 3)));
262
+ break;
263
+ }
264
+ case "leader-candidate": {
265
+ if (e.tabId === c) return;
266
+ o === "electing" && e.tabId < c && (b(), I = setTimeout(() => {
267
+ I = null, !r && !s && o === "electing" && q();
268
+ }, m * 3));
269
+ break;
270
+ }
271
+ case "leader-announce": {
272
+ if (e.leaderId === c) return;
273
+ if (e.revoked) {
274
+ D("session_revoked", !1);
275
+ return;
276
+ }
277
+ o === "leader" ? e.leaderId < c ? j(e.leaderId, e.status, e.lastEventId) : g({
278
+ type: "leader-announce",
279
+ leaderId: c,
280
+ status: E,
281
+ lastEventId: i?.getLastEventId() ?? t,
282
+ revoked: s
283
+ }) : j(e.leaderId, e.status, e.lastEventId);
284
+ break;
285
+ }
286
+ case "leader-heartbeat": {
287
+ if (e.leaderId === c) return;
288
+ o === "follower" && (h === null || h === e.leaderId) && (h = e.leaderId, e.lastEventId !== void 0 && (t = e.lastEventId), T(), e.status !== "idle" && p(e.status));
289
+ break;
290
+ }
291
+ case "leader-release": {
292
+ if (e.leaderId === c) return;
293
+ e.lastEventId !== void 0 && (t = e.lastEventId), o === "follower" && (h === null || h === e.leaderId) && O(m);
294
+ break;
295
+ }
296
+ case "stream-open": {
297
+ if (e.leaderId === c || o !== "follower" || h !== null && e.leaderId !== h) return;
298
+ e.lastEventId !== void 0 && (t = e.lastEventId), T(), p("open"), w = !0, d.onOpen?.();
299
+ break;
300
+ }
301
+ case "stream-status": {
302
+ if (e.leaderId === c || o !== "follower" || h !== null && e.leaderId !== h) return;
303
+ e.lastEventId !== void 0 && (t = e.lastEventId), T(), p(e.status);
304
+ break;
305
+ }
306
+ case "stream-frame": {
307
+ if (e.leaderId === c || o !== "follower" || h !== null && e.leaderId !== h) return;
308
+ e.lastEventId !== void 0 ? t = e.lastEventId : e.frame.id !== void 0 && (t = e.frame.id), T(), d.onFrame(e.frame);
309
+ break;
310
+ }
311
+ case "stream-lagged": {
312
+ if (e.leaderId === c || o !== "follower" || h !== null && e.leaderId !== h) return;
313
+ e.lastEventId !== void 0 && (t = e.lastEventId), T(), d.onLagged?.(e.droppedCount, e.rawData);
314
+ break;
315
+ }
316
+ case "stream-resync": {
317
+ if (e.leaderId === c || o !== "follower" || h !== null && e.leaderId !== h) return;
318
+ e.lastEventId !== void 0 && (t = e.lastEventId), T(), d.onResync?.(e.reason);
319
+ break;
320
+ }
321
+ case "stream-revoked": {
322
+ if (e.leaderId === c) return;
323
+ D(e.rawData, !1);
324
+ break;
325
+ }
326
+ }
327
+ }
328
+ R.onmessage = $, O(m);
329
+ function v() {
330
+ if (r) return;
331
+ const f = o === "leader", e = i?.getLastEventId() ?? t;
332
+ t = e, b(), F(), H(), f && !s && g({
333
+ type: "leader-release",
334
+ leaderId: c,
335
+ lastEventId: e
336
+ }), r = !0, R.onmessage = null;
337
+ try {
338
+ R.close();
339
+ } catch {
340
+ }
341
+ s || p("closed");
342
+ }
343
+ return {
344
+ close: v,
345
+ getStatus: () => E,
346
+ getLastEventId: () => i?.getLastEventId() ?? t
347
+ };
348
+ }
349
+ function Z(a) {
350
+ const n = a.trim();
351
+ if (!n) return null;
352
+ if (/^\d+$/.test(n)) {
353
+ const l = Number.parseInt(n, 10);
354
+ return Number.isSafeInteger(l) ? l : null;
355
+ }
356
+ try {
357
+ const l = JSON.parse(n);
358
+ if (typeof l == "number" && Number.isFinite(l) && l >= 0)
359
+ return Math.floor(l);
360
+ if (l && typeof l == "object") {
361
+ const d = l;
362
+ for (const k of ["dropped", "droppedCount", "dropped_count", "count", "lagged"]) {
363
+ const m = d[k];
364
+ if (typeof m == "number" && Number.isFinite(m) && m >= 0)
365
+ return Math.floor(m);
366
+ }
367
+ }
368
+ } catch {
369
+ return null;
370
+ }
371
+ return null;
372
+ }
373
+ function G(a, n) {
374
+ const l = a.fetch ?? globalThis.fetch, d = a.credentials ?? "include", k = a.maxReconnectAttempts ?? 1 / 0, m = Math.max(10, a.reconnectBaseDelayMs ?? 500), M = Math.max(
375
+ m,
376
+ a.reconnectMaxDelayMs ?? 3e4
377
+ ), C = a.visibilityResyncThresholdMs ?? 15e3, R = a.now ?? (() => Date.now()), c = a.random ?? (() => Math.random()), o = a.documentRef ?? (typeof document < "u" ? document : void 0);
378
+ let h = "idle", E = a.lastEventId, t = !1, r = !1, s = !1, i = !1, I = 0, S, _ = null, w = null, p = null;
379
+ function b(v) {
380
+ h !== v && (h = v, n.onStatusChange?.(v));
381
+ }
382
+ function A() {
383
+ _ !== null && (clearTimeout(_), _ = null);
384
+ }
385
+ function F() {
386
+ if (w) {
387
+ const v = w;
388
+ w = null, v.abort();
389
+ }
390
+ }
391
+ function g() {
392
+ if (!(!o || t || r)) {
393
+ if (o.visibilityState === "hidden") {
394
+ p = R();
395
+ return;
396
+ }
397
+ if (o.visibilityState === "visible" && p !== null) {
398
+ const v = R() - p;
399
+ p = null, v >= C && n.onResync?.("visibility");
400
+ }
401
+ }
402
+ }
403
+ o && (o.visibilityState === "hidden" && (p = R()), o.addEventListener("visibilitychange", g));
404
+ function T() {
405
+ o && o.removeEventListener("visibilitychange", g);
406
+ }
407
+ function H(v) {
408
+ const e = Math.min(
409
+ M,
410
+ (S ?? m) * 2 ** Math.max(0, v - 1)
411
+ ), u = 0.8 + 0.2 * Math.min(1, Math.max(0, c()));
412
+ return Math.min(
413
+ M,
414
+ Math.max(10, Math.round(e * u))
415
+ );
416
+ }
417
+ function D() {
418
+ if (t || r) return;
419
+ if (I >= k) {
420
+ t = !0, T(), b("closed");
421
+ return;
422
+ }
423
+ I += 1;
424
+ const v = H(I);
425
+ b("reconnecting"), A(), _ = setTimeout(() => {
426
+ _ = null, !t && !r && O();
427
+ }, v);
428
+ }
429
+ function q(v) {
430
+ r || (r = !0, t = !0, A(), T(), F(), b("revoked"), n.onSessionRevoked?.(v));
431
+ }
432
+ async function j() {
433
+ const v = typeof a.headers == "function" ? await a.headers() : a.headers, f = {}, e = (u, L) => {
434
+ const x = u.toLowerCase();
435
+ for (const N of Object.keys(f))
436
+ N.toLowerCase() === x && N !== u && delete f[N];
437
+ f[u] = L;
438
+ };
439
+ if (v instanceof Headers)
440
+ v.forEach((u, L) => {
441
+ e(L, u);
442
+ });
443
+ else if (Array.isArray(v))
444
+ for (const [u, L] of v)
445
+ e(u, L);
446
+ else if (v)
447
+ for (const [u, L] of Object.entries(v))
448
+ L !== void 0 && e(u, L);
449
+ return e("Accept", "text/event-stream"), e("Cache-Control", "no-cache"), E !== void 0 && E !== "" && e("Last-Event-ID", E), f;
450
+ }
451
+ async function O() {
452
+ if (t || r) return;
453
+ b(s || i ? "reconnecting" : "connecting");
454
+ let v;
455
+ try {
456
+ v = await j();
457
+ } catch (u) {
458
+ if (t || r) return;
459
+ i = !0, n.onTransportError?.(u), D();
460
+ return;
461
+ }
462
+ if (t || r) return;
463
+ if (a.requireAuthHeader && !Object.entries(v).find(
464
+ ([x]) => x.toLowerCase() === "authorization"
465
+ )?.[1]?.trim()) {
466
+ const x = new W(
467
+ P,
468
+ "Authorization header is required to open the realtime stream."
469
+ );
470
+ t = !0, A(), T(), b("closed"), n.onTransportError?.(x);
471
+ return;
472
+ }
473
+ if (typeof l != "function") {
474
+ const u = new W(
475
+ "sse_fetch_unavailable",
476
+ "Fetch implementation is not available."
477
+ );
478
+ t = !0, T(), b("closed"), n.onTransportError?.(u);
479
+ return;
480
+ }
481
+ const f = new AbortController();
482
+ w = f;
483
+ let e = null;
484
+ try {
485
+ const u = await l(a.url, {
486
+ method: "GET",
487
+ headers: v,
488
+ credentials: d,
489
+ cache: "no-store",
490
+ signal: f.signal
491
+ });
492
+ if (t || r) return;
493
+ if (!u.ok)
494
+ throw new W(
495
+ U,
496
+ `Realtime stream request failed with status ${u.status}`,
497
+ { status: u.status }
498
+ );
499
+ if (!u.body)
500
+ throw new W(
501
+ "sse_empty_body",
502
+ "Realtime stream response did not include a readable body."
503
+ );
504
+ const L = s || i;
505
+ s = !0, i = !1, b("open"), n.onOpen?.(), L && n.onResync?.("reconnect");
506
+ const x = new TextDecoder("utf-8"), N = V({
507
+ onId: (y) => {
508
+ E = y;
509
+ },
510
+ onRetry: (y) => {
511
+ S = y;
512
+ },
513
+ onComment: () => {
514
+ I = 0;
515
+ },
516
+ onFrame: (y) => {
517
+ if (!(t || r)) {
518
+ if (I = 0, y.id !== void 0 && (E = y.id), y.retryMs !== void 0 && (S = y.retryMs), y.event === "session-revoked") {
519
+ q(y.data);
520
+ return;
521
+ }
522
+ if (y.event === "lagged") {
523
+ const B = Z(y.data);
524
+ n.onLagged?.(B, y.data), n.onResync?.("lagged"), n.onFrame(y);
525
+ return;
526
+ }
527
+ n.onFrame(y);
528
+ }
529
+ }
530
+ });
531
+ for (e = u.body.getReader(); !t && !r; ) {
532
+ const { done: y, value: B } = await e.read();
533
+ if (y) {
534
+ const z = x.decode();
535
+ z && N.feed(z);
536
+ break;
537
+ }
538
+ B && B.byteLength > 0 && N.feed(x.decode(B, { stream: !0 }));
539
+ }
540
+ !t && !r && D();
541
+ } catch (u) {
542
+ if (t || r) return;
543
+ i = !0, n.onTransportError?.(u), D();
544
+ } finally {
545
+ e && e.cancel().catch(() => {
546
+ }), w === f && (w = null);
547
+ }
548
+ }
549
+ O();
550
+ function $() {
551
+ t || (t = !0, A(), T(), F(), r || b("closed"));
552
+ }
553
+ return {
554
+ close: $,
555
+ getStatus: () => h,
556
+ getLastEventId: () => E
557
+ };
558
+ }
559
+ function ae(a, n) {
560
+ return a.multiTab === !0 && a.scopeKey ? X({
561
+ scopeKey: a.scopeKey,
562
+ initialLastEventId: a.lastEventId,
563
+ broadcastChannelFactory: a.broadcastChannelFactory,
564
+ electionTimeoutMs: a.multiTabElectionTimeoutMs,
565
+ heartbeatIntervalMs: a.multiTabHeartbeatIntervalMs,
566
+ openLeaderStream: (l, d) => G(
567
+ {
568
+ ...a,
569
+ lastEventId: l ?? a.lastEventId,
570
+ multiTab: !1
571
+ },
572
+ d
573
+ ),
574
+ handlers: n
575
+ }) : G(a, n);
576
+ }
577
+ export {
578
+ ne as LruDedupeSet,
579
+ W as RealtimeStreamError,
580
+ P as SSE_AUTH_HEADER_REQUIRED,
581
+ U as SSE_HTTP_ERROR,
582
+ te as SSE_SESSION_REVOKED,
583
+ ee as SSE_STREAM_LAGGED,
584
+ X as createMultiTabCoordinator,
585
+ ae as createRealtimeStream,
586
+ V as createSseParser,
587
+ re as parseSseText
588
+ };