@sidekickdb/resumable-stream 0.0.0 → 2.0.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.
@@ -0,0 +1,4323 @@
1
+ var Wn = Object.defineProperty;
2
+ var qt = (e) => {
3
+ throw TypeError(e);
4
+ };
5
+ var Kn = (e, t, n) => t in e ? Wn(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
6
+ var d = (e, t, n) => Kn(e, typeof t != "symbol" ? t + "" : t, n), wt = (e, t, n) => t.has(e) || qt("Cannot " + n);
7
+ var f = (e, t, n) => (wt(e, t, "read from private field"), n ? n.call(e) : t.get(e)), k = (e, t, n) => t.has(e) ? qt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), S = (e, t, n, s) => (wt(e, t, "write to private field"), s ? s.call(e, n) : t.set(e, n), n), O = (e, t, n) => (wt(e, t, "access private method"), n);
8
+ const Vn = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
9
+ function Fe(e) {
10
+ return typeof e == "string" && Vn.test(e);
11
+ }
12
+ const L = [];
13
+ for (let e = 0; e < 256; ++e)
14
+ L.push((e + 256).toString(16).slice(1));
15
+ function Jn(e, t = 0) {
16
+ return (L[e[t + 0]] + L[e[t + 1]] + L[e[t + 2]] + L[e[t + 3]] + "-" + L[e[t + 4]] + L[e[t + 5]] + "-" + L[e[t + 6]] + L[e[t + 7]] + "-" + L[e[t + 8]] + L[e[t + 9]] + "-" + L[e[t + 10]] + L[e[t + 11]] + L[e[t + 12]] + L[e[t + 13]] + L[e[t + 14]] + L[e[t + 15]]).toLowerCase();
17
+ }
18
+ let St;
19
+ const Hn = new Uint8Array(16);
20
+ function qn() {
21
+ if (!St) {
22
+ if (typeof crypto > "u" || !crypto.getRandomValues)
23
+ throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");
24
+ St = crypto.getRandomValues.bind(crypto);
25
+ }
26
+ return St(Hn);
27
+ }
28
+ const Bn = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Bt = { randomUUID: Bn };
29
+ function Qn(e, t, n) {
30
+ var r;
31
+ if (Bt.randomUUID && !e)
32
+ return Bt.randomUUID();
33
+ e = e || {};
34
+ const s = e.random ?? ((r = e.rng) == null ? void 0 : r.call(e)) ?? qn();
35
+ if (s.length < 16)
36
+ throw new Error("Random bytes length must be >= 16");
37
+ return s[6] = s[6] & 15 | 64, s[8] = s[8] & 63 | 128, Jn(s);
38
+ }
39
+ const M = {
40
+ Remove: "remove",
41
+ Replace: "replace",
42
+ Add: "add"
43
+ }, pn = Symbol.for("__MUTATIVE_PROXY_DRAFT__"), tt = Symbol.iterator, re = {
44
+ mutable: "mutable",
45
+ immutable: "immutable"
46
+ }, Nt = {};
47
+ function Ke(e, t) {
48
+ return e instanceof Map ? e.has(t) : Object.prototype.hasOwnProperty.call(e, t);
49
+ }
50
+ function Qt(e, t) {
51
+ if (t in e) {
52
+ let n = Reflect.getPrototypeOf(e);
53
+ for (; n; ) {
54
+ const s = Reflect.getOwnPropertyDescriptor(n, t);
55
+ if (s)
56
+ return s;
57
+ n = Reflect.getPrototypeOf(n);
58
+ }
59
+ }
60
+ }
61
+ function yn(e) {
62
+ return Object.getPrototypeOf(e) === Set.prototype;
63
+ }
64
+ function mn(e) {
65
+ return Object.getPrototypeOf(e) === Map.prototype;
66
+ }
67
+ function X(e) {
68
+ var t;
69
+ return (t = e.copy) !== null && t !== void 0 ? t : e.original;
70
+ }
71
+ function Et(e) {
72
+ return !!E(e);
73
+ }
74
+ function E(e) {
75
+ return typeof e != "object" ? null : e == null ? void 0 : e[pn];
76
+ }
77
+ function Lt(e) {
78
+ var t;
79
+ const n = E(e);
80
+ return n ? (t = n.copy) !== null && t !== void 0 ? t : n.original : e;
81
+ }
82
+ function Te(e, t) {
83
+ if (!e || typeof e != "object")
84
+ return !1;
85
+ let n;
86
+ return Object.getPrototypeOf(e) === Object.prototype || Array.isArray(e) || e instanceof Map || e instanceof Set || !!(t != null && t.mark) && ((n = t.mark(e, re)) === re.immutable || typeof n == "function");
87
+ }
88
+ function bn(e, t = []) {
89
+ if (Object.hasOwnProperty.call(e, "key")) {
90
+ const n = e.parent.copy, s = E(me(n, e.key));
91
+ if (s !== null && (s == null ? void 0 : s.original) !== e.original)
92
+ return null;
93
+ const r = e.parent.type === 3, i = r ? Array.from(e.parent.setMap.keys()).indexOf(e.key) : e.key;
94
+ if (!(r && n.size > i || Ke(n, i)))
95
+ return null;
96
+ t.push(i);
97
+ }
98
+ if (e.parent)
99
+ return bn(e.parent, t);
100
+ t.reverse();
101
+ try {
102
+ Gn(e.copy, t);
103
+ } catch {
104
+ return null;
105
+ }
106
+ return t;
107
+ }
108
+ function Xe(e) {
109
+ return Array.isArray(e) ? 1 : e instanceof Map ? 2 : e instanceof Set ? 3 : 0;
110
+ }
111
+ function me(e, t) {
112
+ return Xe(e) === 2 ? e.get(t) : e[t];
113
+ }
114
+ function Ft(e, t, n) {
115
+ Xe(e) === 2 ? e.set(t, n) : e[t] = n;
116
+ }
117
+ function It(e, t) {
118
+ const n = E(e);
119
+ return (n ? X(n) : e)[t];
120
+ }
121
+ function Ce(e, t) {
122
+ return e === t ? e !== 0 || 1 / e === 1 / t : e !== e && t !== t;
123
+ }
124
+ function we(e, t) {
125
+ return t ? e : [""].concat(e).map((n) => {
126
+ const s = `${n}`;
127
+ return s.indexOf("/") === -1 && s.indexOf("~") === -1 ? s : s.replace(/~/g, "~0").replace(/\//g, "~1");
128
+ }).join("/");
129
+ }
130
+ function Gn(e, t) {
131
+ for (let n = 0; n < t.length - 1; n += 1) {
132
+ const s = t[n];
133
+ if (e = me(Xe(e) === 3 ? Array.from(e) : e, s), typeof e != "object")
134
+ throw new Error(`Cannot resolve patch at '${t.join("/")}'.`);
135
+ }
136
+ return e;
137
+ }
138
+ function Xn(e) {
139
+ const t = Object.create(Object.getPrototypeOf(e));
140
+ return Reflect.ownKeys(e).forEach((n) => {
141
+ let s = Reflect.getOwnPropertyDescriptor(e, n);
142
+ if (s.enumerable && s.configurable && s.writable) {
143
+ t[n] = e[n];
144
+ return;
145
+ }
146
+ s.writable || (s.writable = !0, s.configurable = !0), (s.get || s.set) && (s = {
147
+ configurable: !0,
148
+ writable: !0,
149
+ enumerable: s.enumerable,
150
+ value: e[n]
151
+ }), Reflect.defineProperty(t, n, s);
152
+ }), t;
153
+ }
154
+ const Yn = Object.prototype.propertyIsEnumerable;
155
+ function Zn(e, t) {
156
+ let n;
157
+ if (Array.isArray(e))
158
+ return Array.prototype.concat.call(e);
159
+ if (e instanceof Set) {
160
+ if (!yn(e)) {
161
+ const s = Object.getPrototypeOf(e).constructor;
162
+ return new s(e.values());
163
+ }
164
+ return Set.prototype.difference ? Set.prototype.difference.call(e, /* @__PURE__ */ new Set()) : new Set(e.values());
165
+ } else if (e instanceof Map) {
166
+ if (!mn(e)) {
167
+ const s = Object.getPrototypeOf(e).constructor;
168
+ return new s(e);
169
+ }
170
+ return new Map(e);
171
+ } else if (t != null && t.mark && (n = t.mark(e, re), n !== void 0) && n !== re.mutable) {
172
+ if (n === re.immutable)
173
+ return Xn(e);
174
+ if (typeof n == "function") {
175
+ if (t.enablePatches || t.enableAutoFreeze)
176
+ throw new Error("You can't use mark and patches or auto freeze together.");
177
+ return n();
178
+ }
179
+ throw new Error(`Unsupported mark result: ${n}`);
180
+ } else if (typeof e == "object" && Object.getPrototypeOf(e) === Object.prototype) {
181
+ const s = {};
182
+ return Object.keys(e).forEach((r) => {
183
+ s[r] = e[r];
184
+ }), Object.getOwnPropertySymbols(e).forEach((r) => {
185
+ Yn.call(e, r) && (s[r] = e[r]);
186
+ }), s;
187
+ } else
188
+ throw new Error("Please check mark() to ensure that it is a stable marker draftable function.");
189
+ }
190
+ function q(e) {
191
+ e.copy || (e.copy = Zn(e.original, e.options));
192
+ }
193
+ function ze(e) {
194
+ if (!Te(e))
195
+ return Lt(e);
196
+ if (Array.isArray(e))
197
+ return e.map(ze);
198
+ if (e instanceof Map) {
199
+ const n = Array.from(e.entries()).map(([s, r]) => [
200
+ s,
201
+ ze(r)
202
+ ]);
203
+ if (!mn(e)) {
204
+ const s = Object.getPrototypeOf(e).constructor;
205
+ return new s(n);
206
+ }
207
+ return new Map(n);
208
+ }
209
+ if (e instanceof Set) {
210
+ const n = Array.from(e).map(ze);
211
+ if (!yn(e)) {
212
+ const s = Object.getPrototypeOf(e).constructor;
213
+ return new s(n);
214
+ }
215
+ return new Set(n);
216
+ }
217
+ const t = Object.create(Object.getPrototypeOf(e));
218
+ for (const n in e)
219
+ t[n] = ze(e[n]);
220
+ return t;
221
+ }
222
+ function nt(e) {
223
+ return Et(e) ? ze(e) : e;
224
+ }
225
+ function ie(e) {
226
+ var t;
227
+ e.assignedMap = (t = e.assignedMap) !== null && t !== void 0 ? t : /* @__PURE__ */ new Map(), e.operated || (e.operated = !0, e.parent && ie(e.parent));
228
+ }
229
+ function es(e, t) {
230
+ const n = Xe(e);
231
+ if (n === 0)
232
+ Reflect.ownKeys(e).forEach((s) => {
233
+ t(s, e[s], e);
234
+ });
235
+ else if (n === 1) {
236
+ let s = 0;
237
+ for (const r of e)
238
+ t(s, r, e), s += 1;
239
+ } else
240
+ e.forEach((s, r) => t(r, s, e));
241
+ }
242
+ function gn(e, t, n) {
243
+ if (Et(e) || !Te(e, n) || t.has(e) || Object.isFrozen(e))
244
+ return;
245
+ const s = e instanceof Set, r = s ? /* @__PURE__ */ new Map() : void 0;
246
+ if (t.add(e), es(e, (i, o) => {
247
+ var a;
248
+ if (Et(o)) {
249
+ const c = E(o);
250
+ q(c);
251
+ const u = !((a = c.assignedMap) === null || a === void 0) && a.size || c.operated ? c.copy : c.original;
252
+ Ft(s ? r : e, i, u);
253
+ } else
254
+ gn(o, t, n);
255
+ }), r) {
256
+ const i = e, o = Array.from(i);
257
+ i.clear(), o.forEach((a) => {
258
+ i.add(r.has(a) ? r.get(a) : a);
259
+ });
260
+ }
261
+ }
262
+ function ts(e, t) {
263
+ const n = e.type === 3 ? e.setMap : e.copy;
264
+ e.finalities.revoke.length > 1 && e.assignedMap.get(t) && n && gn(me(n, t), e.finalities.handledSet, e.options);
265
+ }
266
+ function Ct(e) {
267
+ e.type === 3 && e.copy && (e.copy.clear(), e.setMap.forEach((t) => {
268
+ e.copy.add(Lt(t));
269
+ }));
270
+ }
271
+ function xt(e, t, n, s) {
272
+ if (e.operated && e.assignedMap && e.assignedMap.size > 0 && !e.finalized) {
273
+ if (n && s) {
274
+ const i = bn(e);
275
+ i && t(e, i, n, s);
276
+ }
277
+ e.finalized = !0;
278
+ }
279
+ }
280
+ function zt(e, t, n, s) {
281
+ const r = E(n);
282
+ r && (r.callbacks || (r.callbacks = []), r.callbacks.push((i, o) => {
283
+ var a;
284
+ const c = e.type === 3 ? e.setMap : e.copy;
285
+ if (Ce(me(c, t), n)) {
286
+ let u = r.original;
287
+ r.copy && (u = r.copy), Ct(e), xt(e, s, i, o), e.options.enableAutoFreeze && (e.options.updatedValues = (a = e.options.updatedValues) !== null && a !== void 0 ? a : /* @__PURE__ */ new WeakMap(), e.options.updatedValues.set(u, r.original)), Ft(c, t, u);
288
+ }
289
+ }), e.options.enableAutoFreeze && r.finalities !== e.finalities && (e.options.enableAutoFreeze = !1)), Te(n, e.options) && e.finalities.draft.push(() => {
290
+ const i = e.type === 3 ? e.setMap : e.copy;
291
+ Ce(me(i, t), n) && ts(e, t);
292
+ });
293
+ }
294
+ function ns(e, t, n, s, r) {
295
+ let { original: i, assignedMap: o, options: a } = e, c = e.copy;
296
+ c.length < i.length && ([i, c] = [c, i], [n, s] = [s, n]);
297
+ for (let u = 0; u < i.length; u += 1)
298
+ if (o.get(u.toString()) && c[u] !== i[u]) {
299
+ const h = t.concat([u]), l = we(h, r);
300
+ n.push({
301
+ op: M.Replace,
302
+ path: l,
303
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
304
+ value: nt(c[u])
305
+ }), s.push({
306
+ op: M.Replace,
307
+ path: l,
308
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
309
+ value: nt(i[u])
310
+ });
311
+ }
312
+ for (let u = i.length; u < c.length; u += 1) {
313
+ const h = t.concat([u]), l = we(h, r);
314
+ n.push({
315
+ op: M.Add,
316
+ path: l,
317
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
318
+ value: nt(c[u])
319
+ });
320
+ }
321
+ if (i.length < c.length) {
322
+ const { arrayLengthAssignment: u = !0 } = a.enablePatches;
323
+ if (u) {
324
+ const h = t.concat(["length"]), l = we(h, r);
325
+ s.push({
326
+ op: M.Replace,
327
+ path: l,
328
+ value: i.length
329
+ });
330
+ } else
331
+ for (let h = c.length; i.length < h; h -= 1) {
332
+ const l = t.concat([h - 1]), y = we(l, r);
333
+ s.push({
334
+ op: M.Remove,
335
+ path: y
336
+ });
337
+ }
338
+ }
339
+ }
340
+ function ss({ original: e, copy: t, assignedMap: n }, s, r, i, o) {
341
+ n.forEach((a, c) => {
342
+ const u = me(e, c), h = nt(me(t, c)), l = a ? Ke(e, c) ? M.Replace : M.Add : M.Remove;
343
+ if (Ce(u, h) && l === M.Replace)
344
+ return;
345
+ const y = s.concat(c), m = we(y, o);
346
+ r.push(l === M.Remove ? { op: l, path: m } : { op: l, path: m, value: h }), i.push(l === M.Add ? { op: M.Remove, path: m } : l === M.Remove ? { op: M.Add, path: m, value: u } : { op: M.Replace, path: m, value: u });
347
+ });
348
+ }
349
+ function rs({ original: e, copy: t }, n, s, r, i) {
350
+ let o = 0;
351
+ e.forEach((a) => {
352
+ if (!t.has(a)) {
353
+ const c = n.concat([o]), u = we(c, i);
354
+ s.push({
355
+ op: M.Remove,
356
+ path: u,
357
+ value: a
358
+ }), r.unshift({
359
+ op: M.Add,
360
+ path: u,
361
+ value: a
362
+ });
363
+ }
364
+ o += 1;
365
+ }), o = 0, t.forEach((a) => {
366
+ if (!e.has(a)) {
367
+ const c = n.concat([o]), u = we(c, i);
368
+ s.push({
369
+ op: M.Add,
370
+ path: u,
371
+ value: a
372
+ }), r.unshift({
373
+ op: M.Remove,
374
+ path: u,
375
+ value: a
376
+ });
377
+ }
378
+ o += 1;
379
+ });
380
+ }
381
+ function Ve(e, t, n, s) {
382
+ const { pathAsArray: r = !0 } = e.options.enablePatches;
383
+ switch (e.type) {
384
+ case 0:
385
+ case 2:
386
+ return ss(e, t, n, s, r);
387
+ case 1:
388
+ return ns(e, t, n, s, r);
389
+ case 3:
390
+ return rs(e, t, n, s, r);
391
+ }
392
+ }
393
+ const it = (e, t, n = !1) => {
394
+ if (typeof e == "object" && e !== null && (!Te(e, t) || n))
395
+ throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.");
396
+ }, Tt = {
397
+ get size() {
398
+ return X(E(this)).size;
399
+ },
400
+ has(e) {
401
+ return X(E(this)).has(e);
402
+ },
403
+ set(e, t) {
404
+ const n = E(this), s = X(n);
405
+ return (!s.has(e) || !Ce(s.get(e), t)) && (q(n), ie(n), n.assignedMap.set(e, !0), n.copy.set(e, t), zt(n, e, t, Ve)), this;
406
+ },
407
+ delete(e) {
408
+ if (!this.has(e))
409
+ return !1;
410
+ const t = E(this);
411
+ return q(t), ie(t), t.original.has(e) ? t.assignedMap.set(e, !1) : t.assignedMap.delete(e), t.copy.delete(e), !0;
412
+ },
413
+ clear() {
414
+ const e = E(this);
415
+ if (this.size) {
416
+ q(e), ie(e), e.assignedMap = /* @__PURE__ */ new Map();
417
+ for (const [t] of e.original)
418
+ e.assignedMap.set(t, !1);
419
+ e.copy.clear();
420
+ }
421
+ },
422
+ forEach(e, t) {
423
+ const n = E(this);
424
+ X(n).forEach((s, r) => {
425
+ e.call(t, this.get(r), r, this);
426
+ });
427
+ },
428
+ get(e) {
429
+ var t, n;
430
+ const s = E(this), r = X(s).get(e), i = ((n = (t = s.options).mark) === null || n === void 0 ? void 0 : n.call(t, r, re)) === re.mutable;
431
+ if (s.options.strict && it(r, s.options, i), i || s.finalized || !Te(r, s.options) || r !== s.original.get(e))
432
+ return r;
433
+ const o = Nt.createDraft({
434
+ original: r,
435
+ parentDraft: s,
436
+ key: e,
437
+ finalities: s.finalities,
438
+ options: s.options
439
+ });
440
+ return q(s), s.copy.set(e, o), o;
441
+ },
442
+ keys() {
443
+ return X(E(this)).keys();
444
+ },
445
+ values() {
446
+ const e = this.keys();
447
+ return {
448
+ [tt]: () => this.values(),
449
+ next: () => {
450
+ const t = e.next();
451
+ return t.done ? t : {
452
+ done: !1,
453
+ value: this.get(t.value)
454
+ };
455
+ }
456
+ };
457
+ },
458
+ entries() {
459
+ const e = this.keys();
460
+ return {
461
+ [tt]: () => this.entries(),
462
+ next: () => {
463
+ const t = e.next();
464
+ if (t.done)
465
+ return t;
466
+ const n = this.get(t.value);
467
+ return {
468
+ done: !1,
469
+ value: [t.value, n]
470
+ };
471
+ }
472
+ };
473
+ },
474
+ [tt]() {
475
+ return this.entries();
476
+ }
477
+ }, is = Reflect.ownKeys(Tt), Gt = (e, t, { isValuesIterator: n }) => () => {
478
+ var s, r;
479
+ const i = t.next();
480
+ if (i.done)
481
+ return i;
482
+ const o = i.value;
483
+ let a = e.setMap.get(o);
484
+ const c = E(a), u = ((r = (s = e.options).mark) === null || r === void 0 ? void 0 : r.call(s, a, re)) === re.mutable;
485
+ if (e.options.strict && it(o, e.options, u), !u && !c && Te(o, e.options) && !e.finalized && e.original.has(o)) {
486
+ const h = Nt.createDraft({
487
+ original: o,
488
+ parentDraft: e,
489
+ key: o,
490
+ finalities: e.finalities,
491
+ options: e.options
492
+ });
493
+ e.setMap.set(o, h), a = h;
494
+ } else c && (a = c.proxy);
495
+ return {
496
+ done: !1,
497
+ value: n ? a : [a, a]
498
+ };
499
+ }, ot = {
500
+ get size() {
501
+ return E(this).setMap.size;
502
+ },
503
+ has(e) {
504
+ const t = E(this);
505
+ if (t.setMap.has(e))
506
+ return !0;
507
+ q(t);
508
+ const n = E(e);
509
+ return !!(n && t.setMap.has(n.original));
510
+ },
511
+ add(e) {
512
+ const t = E(this);
513
+ return this.has(e) || (q(t), ie(t), t.assignedMap.set(e, !0), t.setMap.set(e, e), zt(t, e, e, Ve)), this;
514
+ },
515
+ delete(e) {
516
+ if (!this.has(e))
517
+ return !1;
518
+ const t = E(this);
519
+ q(t), ie(t);
520
+ const n = E(e);
521
+ return n && t.setMap.has(n.original) ? (t.assignedMap.set(n.original, !1), t.setMap.delete(n.original)) : (!n && t.setMap.has(e) ? t.assignedMap.set(e, !1) : t.assignedMap.delete(e), t.setMap.delete(e));
522
+ },
523
+ clear() {
524
+ if (!this.size)
525
+ return;
526
+ const e = E(this);
527
+ q(e), ie(e);
528
+ for (const t of e.original)
529
+ e.assignedMap.set(t, !1);
530
+ e.setMap.clear();
531
+ },
532
+ values() {
533
+ const e = E(this);
534
+ q(e);
535
+ const t = e.setMap.keys();
536
+ return {
537
+ [Symbol.iterator]: () => this.values(),
538
+ next: Gt(e, t, { isValuesIterator: !0 })
539
+ };
540
+ },
541
+ entries() {
542
+ const e = E(this);
543
+ q(e);
544
+ const t = e.setMap.keys();
545
+ return {
546
+ [Symbol.iterator]: () => this.entries(),
547
+ next: Gt(e, t, {
548
+ isValuesIterator: !1
549
+ })
550
+ };
551
+ },
552
+ keys() {
553
+ return this.values();
554
+ },
555
+ [tt]() {
556
+ return this.values();
557
+ },
558
+ forEach(e, t) {
559
+ const n = this.values();
560
+ let s = n.next();
561
+ for (; !s.done; )
562
+ e.call(t, s.value, s.value, this), s = n.next();
563
+ }
564
+ };
565
+ Set.prototype.difference && Object.assign(ot, {
566
+ intersection(e) {
567
+ return Set.prototype.intersection.call(new Set(this.values()), e);
568
+ },
569
+ union(e) {
570
+ return Set.prototype.union.call(new Set(this.values()), e);
571
+ },
572
+ difference(e) {
573
+ return Set.prototype.difference.call(new Set(this.values()), e);
574
+ },
575
+ symmetricDifference(e) {
576
+ return Set.prototype.symmetricDifference.call(new Set(this.values()), e);
577
+ },
578
+ isSubsetOf(e) {
579
+ return Set.prototype.isSubsetOf.call(new Set(this.values()), e);
580
+ },
581
+ isSupersetOf(e) {
582
+ return Set.prototype.isSupersetOf.call(new Set(this.values()), e);
583
+ },
584
+ isDisjointFrom(e) {
585
+ return Set.prototype.isDisjointFrom.call(new Set(this.values()), e);
586
+ }
587
+ });
588
+ const os = Reflect.ownKeys(ot), wn = /* @__PURE__ */ new WeakSet(), Sn = {
589
+ get(e, t, n) {
590
+ var s, r;
591
+ const i = (s = e.copy) === null || s === void 0 ? void 0 : s[t];
592
+ if (i && wn.has(i))
593
+ return i;
594
+ if (t === pn)
595
+ return e;
596
+ let o;
597
+ if (e.options.mark) {
598
+ const u = t === "size" && (e.original instanceof Map || e.original instanceof Set) ? Reflect.get(e.original, t) : Reflect.get(e.original, t, n);
599
+ if (o = e.options.mark(u, re), o === re.mutable)
600
+ return e.options.strict && it(u, e.options, !0), u;
601
+ }
602
+ const a = X(e);
603
+ if (a instanceof Map && is.includes(t)) {
604
+ if (t === "size")
605
+ return Object.getOwnPropertyDescriptor(Tt, "size").get.call(e.proxy);
606
+ const u = Tt[t];
607
+ if (u)
608
+ return u.bind(e.proxy);
609
+ }
610
+ if (a instanceof Set && os.includes(t)) {
611
+ if (t === "size")
612
+ return Object.getOwnPropertyDescriptor(ot, "size").get.call(e.proxy);
613
+ const u = ot[t];
614
+ if (u)
615
+ return u.bind(e.proxy);
616
+ }
617
+ if (!Ke(a, t)) {
618
+ const u = Qt(a, t);
619
+ return u ? "value" in u ? u.value : (
620
+ // !case: support for getter
621
+ (r = u.get) === null || r === void 0 ? void 0 : r.call(e.proxy)
622
+ ) : void 0;
623
+ }
624
+ const c = a[t];
625
+ if (e.options.strict && it(c, e.options), e.finalized || !Te(c, e.options))
626
+ return c;
627
+ if (c === It(e.original, t)) {
628
+ if (q(e), e.copy[t] = In({
629
+ original: e.original[t],
630
+ parentDraft: e,
631
+ key: e.type === 1 ? Number(t) : t,
632
+ finalities: e.finalities,
633
+ options: e.options
634
+ }), typeof o == "function") {
635
+ const u = E(e.copy[t]);
636
+ return q(u), ie(u), u.copy;
637
+ }
638
+ return e.copy[t];
639
+ }
640
+ return c;
641
+ },
642
+ set(e, t, n) {
643
+ var s;
644
+ if (e.type === 3 || e.type === 2)
645
+ throw new Error("Map/Set draft does not support any property assignment.");
646
+ let r;
647
+ if (e.type === 1 && t !== "length" && !(Number.isInteger(r = Number(t)) && r >= 0 && (t === 0 || r === 0 || String(r) === String(t))))
648
+ throw new Error("Only supports setting array indices and the 'length' property.");
649
+ const i = Qt(X(e), t);
650
+ if (i != null && i.set)
651
+ return i.set.call(e.proxy, n), !0;
652
+ const o = It(X(e), t), a = E(o);
653
+ return a && Ce(a.original, n) ? (e.copy[t] = n, e.assignedMap = (s = e.assignedMap) !== null && s !== void 0 ? s : /* @__PURE__ */ new Map(), e.assignedMap.set(t, !1), !0) : (Ce(n, o) && (n !== void 0 || Ke(e.original, t)) || (q(e), ie(e), Ke(e.original, t) && Ce(n, e.original[t]) ? e.assignedMap.delete(t) : e.assignedMap.set(t, !0), e.copy[t] = n, zt(e, t, n, Ve)), !0);
654
+ },
655
+ has(e, t) {
656
+ return t in X(e);
657
+ },
658
+ ownKeys(e) {
659
+ return Reflect.ownKeys(X(e));
660
+ },
661
+ getOwnPropertyDescriptor(e, t) {
662
+ const n = X(e), s = Reflect.getOwnPropertyDescriptor(n, t);
663
+ return s && {
664
+ writable: !0,
665
+ configurable: e.type !== 1 || t !== "length",
666
+ enumerable: s.enumerable,
667
+ value: n[t]
668
+ };
669
+ },
670
+ getPrototypeOf(e) {
671
+ return Reflect.getPrototypeOf(e.original);
672
+ },
673
+ setPrototypeOf() {
674
+ throw new Error("Cannot call 'setPrototypeOf()' on drafts");
675
+ },
676
+ defineProperty() {
677
+ throw new Error("Cannot call 'defineProperty()' on drafts");
678
+ },
679
+ deleteProperty(e, t) {
680
+ var n;
681
+ return e.type === 1 ? Sn.set.call(this, e, t, void 0, e.proxy) : (It(e.original, t) !== void 0 || t in e.original ? (q(e), ie(e), e.assignedMap.set(t, !1)) : (e.assignedMap = (n = e.assignedMap) !== null && n !== void 0 ? n : /* @__PURE__ */ new Map(), e.assignedMap.delete(t)), e.copy && delete e.copy[t], !0);
682
+ }
683
+ };
684
+ function In(e) {
685
+ const { original: t, parentDraft: n, key: s, finalities: r, options: i } = e, o = Xe(t), a = {
686
+ type: o,
687
+ finalized: !1,
688
+ parent: n,
689
+ original: t,
690
+ copy: null,
691
+ proxy: null,
692
+ finalities: r,
693
+ options: i,
694
+ // Mapping of draft Set items to their corresponding draft values.
695
+ setMap: o === 3 ? new Map(t.entries()) : void 0
696
+ };
697
+ (s || "key" in e) && (a.key = s);
698
+ const { proxy: c, revoke: u } = Proxy.revocable(o === 1 ? Object.assign([], a) : a, Sn);
699
+ if (r.revoke.push(u), wn.add(c), a.proxy = c, n) {
700
+ const h = n;
701
+ h.finalities.draft.push((l, y) => {
702
+ var m, g;
703
+ const w = E(c);
704
+ let p = h.type === 3 ? h.setMap : h.copy;
705
+ const $ = me(p, s), v = E($);
706
+ if (v) {
707
+ let F = v.original;
708
+ v.operated && (F = Lt($)), Ct(v), xt(v, Ve, l, y), h.options.enableAutoFreeze && (h.options.updatedValues = (m = h.options.updatedValues) !== null && m !== void 0 ? m : /* @__PURE__ */ new WeakMap(), h.options.updatedValues.set(F, v.original)), Ft(p, s, F);
709
+ }
710
+ (g = w.callbacks) === null || g === void 0 || g.forEach((F) => {
711
+ F(l, y);
712
+ });
713
+ });
714
+ } else {
715
+ const h = E(c);
716
+ h.finalities.draft.push((l, y) => {
717
+ Ct(h), xt(h, Ve, l, y);
718
+ });
719
+ }
720
+ return c;
721
+ }
722
+ Nt.createDraft = In;
723
+ Object.prototype.constructor.toString();
724
+ function Ae() {
725
+ return Qn();
726
+ }
727
+ function as(e, t) {
728
+ return e.localeCompare(t);
729
+ }
730
+ function cs() {
731
+ let e = as;
732
+ if (typeof Intl == "object" && Intl.hasOwnProperty("Collator"))
733
+ try {
734
+ e = Intl.Collator("en-US").compare;
735
+ } catch {
736
+ }
737
+ return e;
738
+ }
739
+ cs();
740
+ function us() {
741
+ const t = {
742
+ __etype: 1,
743
+ __ops: 1,
744
+ create: 1,
745
+ update: 1,
746
+ link: 1,
747
+ unlink: 1,
748
+ delete: 1,
749
+ merge: 1,
750
+ ruleParams: 1
751
+ };
752
+ return new Set(Object.keys(t));
753
+ }
754
+ const fs = us();
755
+ function st(e, t, n) {
756
+ const s = {
757
+ __etype: e,
758
+ __ops: n
759
+ };
760
+ return new Proxy(s, {
761
+ get: (r, i) => {
762
+ if (i === "__ops")
763
+ return n;
764
+ if (i === "__etype")
765
+ return e;
766
+ if (fs.has(i))
767
+ return (o, a) => st(e, t, [
768
+ ...n,
769
+ a ? [i, e, t, o, a] : [i, e, t, o]
770
+ ]);
771
+ }
772
+ });
773
+ }
774
+ function ds(e, t) {
775
+ return `lookup__${e}__${JSON.stringify(t)}`;
776
+ }
777
+ function kn(e) {
778
+ return e.startsWith("lookup__");
779
+ }
780
+ function Xt(e) {
781
+ const [t, n, ...s] = e.split("__");
782
+ return [n, JSON.parse(s.join("__"))];
783
+ }
784
+ function ls(e) {
785
+ return new Proxy({
786
+ __etype: e
787
+ }, {
788
+ get(t, n) {
789
+ if (n === "lookup")
790
+ return (r, i) => st(e, Xt(ds(r, i)), []);
791
+ if (n === "__etype")
792
+ return e;
793
+ const s = n;
794
+ return kn(s) ? st(e, Xt(s), []) : st(e, s, []);
795
+ }
796
+ });
797
+ }
798
+ function $n() {
799
+ return new Proxy({}, {
800
+ get(e, t) {
801
+ return ls(t);
802
+ }
803
+ });
804
+ }
805
+ $n();
806
+ function hs(e) {
807
+ return e.__ops;
808
+ }
809
+ class x extends Error {
810
+ constructor(n, s, r) {
811
+ super(n);
812
+ d(this, "hint");
813
+ d(this, "traceId");
814
+ this.hint = s, r && (this.traceId = r);
815
+ const i = new.target.prototype;
816
+ Object.setPrototypeOf && Object.setPrototypeOf(this, i), Error.captureStackTrace && Error.captureStackTrace(this, x), this.name = "InstantError";
817
+ }
818
+ get [Symbol.toStringTag]() {
819
+ return "InstantError";
820
+ }
821
+ }
822
+ class ue extends x {
823
+ constructor(n) {
824
+ var i, o;
825
+ const s = ((i = n.body) == null ? void 0 : i.message) || `API Error (${n.status})`;
826
+ super(s, n.body.hint, ((o = n.body) == null ? void 0 : o.traceId) || n.body["trace-id"]);
827
+ d(this, "body");
828
+ d(this, "status");
829
+ const r = new.target.prototype;
830
+ Object.setPrototypeOf && Object.setPrototypeOf(this, r), Error.captureStackTrace && Error.captureStackTrace(this, ue), this.name = "InstantAPIError", this.status = n.status, this.body = n.body;
831
+ }
832
+ get [Symbol.toStringTag]() {
833
+ return "InstantAPIError";
834
+ }
835
+ }
836
+ typeof window < "u" && typeof window.localStorage < "u" && (window.localStorage.getItem("devBackend"), window.localStorage.getItem("__instantLogging"), window.localStorage.getItem("__devtoolLocalDash"));
837
+ const xe = "v2.0.1";
838
+ class ce {
839
+ constructor(t, n, s, r = { indexed: !1, unique: !1 }) {
840
+ d(this, "valueType");
841
+ d(this, "required");
842
+ d(this, "isIndexed");
843
+ d(this, "config");
844
+ d(this, "metadata", {});
845
+ this.valueType = t, this.required = n, this.isIndexed = s, this.config = r;
846
+ }
847
+ /**
848
+ * @deprecated Only use this temporarily for attributes that you want
849
+ * to treat as required in frontend code but can’t yet mark as required
850
+ * and enforced for backend
851
+ */
852
+ clientRequired() {
853
+ return new ce(this.valueType, !1, this.isIndexed, this.config);
854
+ }
855
+ optional() {
856
+ return new ce(this.valueType, !1, this.isIndexed, this.config);
857
+ }
858
+ unique() {
859
+ return new ce(this.valueType, this.required, this.isIndexed, {
860
+ ...this.config,
861
+ unique: !0
862
+ });
863
+ }
864
+ indexed() {
865
+ return new ce(this.valueType, this.required, !0, {
866
+ ...this.config,
867
+ indexed: !0
868
+ });
869
+ }
870
+ }
871
+ class _ extends Error {
872
+ constructor(t, n) {
873
+ const s = n ? `At path '${n}': ${t}` : t;
874
+ super(s), this.name = "QueryValidationError";
875
+ }
876
+ }
877
+ const Yt = [
878
+ "where",
879
+ "order",
880
+ "limit",
881
+ "last",
882
+ "first",
883
+ "offset",
884
+ "after",
885
+ "afterInclusive",
886
+ "before",
887
+ "beforeInclusive",
888
+ "fields",
889
+ "aggregate"
890
+ ], ps = (e) => e.valueType || "unknown", vn = (e, t, n = !1) => {
891
+ if (n || e == null)
892
+ return !0;
893
+ switch (t) {
894
+ case "string":
895
+ return typeof e == "string";
896
+ case "number":
897
+ return typeof e == "number" && !isNaN(e);
898
+ case "boolean":
899
+ return typeof e == "boolean";
900
+ case "date":
901
+ return e instanceof Date || typeof e == "string" || typeof e == "number";
902
+ default:
903
+ return !0;
904
+ }
905
+ }, ys = (e, t, n, s, r, i, o) => {
906
+ const a = i.valueType === "json", c = (u, h, l) => {
907
+ if (!vn(l, h, a))
908
+ throw new _(`Invalid value for operator '${u}' on attribute '${s}' in entity '${r}'. Expected ${h}, but received: ${typeof l}`, o);
909
+ };
910
+ switch (e) {
911
+ case "in":
912
+ case "$in":
913
+ if (!Array.isArray(t))
914
+ throw new _(`Operator '${e}' for attribute '${s}' in entity '${r}' must be an array, but received: ${typeof t}`, o);
915
+ for (const u of t)
916
+ c(e, n, u);
917
+ break;
918
+ case "$not":
919
+ case "$ne":
920
+ case "$gt":
921
+ case "$lt":
922
+ case "$gte":
923
+ case "$lte":
924
+ c(e, n, t);
925
+ break;
926
+ case "$like":
927
+ case "$ilike":
928
+ if (c(e, "string", t), e === "$ilike" && !i.isIndexed)
929
+ throw new _(`Operator '${e}' can only be used with indexed attributes, but '${s}' in entity '${r}' is not indexed`, o);
930
+ break;
931
+ case "$isNull":
932
+ c(e, "boolean", t);
933
+ break;
934
+ default:
935
+ throw new _(`Unknown operator '${e}' for attribute '${s}' in entity '${r}'`, o);
936
+ }
937
+ }, Pe = (e, t, n, s, r) => {
938
+ const i = ps(n), o = n.valueType === "json";
939
+ if (typeof e == "object" && e !== null && !Array.isArray(e)) {
940
+ if (o)
941
+ return;
942
+ const c = e;
943
+ for (const [u, h] of Object.entries(c))
944
+ ys(u, h, i, t, s, n, `${r}.${u}`);
945
+ } else if (!vn(e, i, o))
946
+ throw new _(`Invalid value for attribute '${t}' in entity '${s}'. Expected ${i}, but received: ${typeof e}`, r);
947
+ }, ms = (e, t, n, s, r) => {
948
+ const i = e.split(".");
949
+ if (i.length < 2)
950
+ throw new _(`Invalid dot notation path '${e}'. Must contain at least one dot.`, r);
951
+ let o = n;
952
+ for (let h = 0; h < i.length - 1; h++) {
953
+ const l = i[h], y = s.entities[o];
954
+ if (!y)
955
+ throw new _(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`, r);
956
+ const m = y.links[l];
957
+ if (!m) {
958
+ const g = Object.keys(y.links);
959
+ throw new _(`Link '${l}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${g.length > 0 ? g.join(", ") : "none"}`, r);
960
+ }
961
+ o = m.entityName;
962
+ }
963
+ const a = i[i.length - 1], c = s.entities[o];
964
+ if (!c)
965
+ throw new _(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`, r);
966
+ if (a === "id") {
967
+ if (typeof t == "string" && !Fe(t))
968
+ throw new _(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`, r);
969
+ Pe(t, e, new ce("string", !1, !0), n, r);
970
+ return;
971
+ }
972
+ const u = c.attrs[a];
973
+ if (Object.keys(c.links).includes(a)) {
974
+ if (typeof t == "string" && !Fe(t))
975
+ throw new _(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`, r);
976
+ Pe(t, e, new ce("string", !1, !0), n, r);
977
+ return;
978
+ }
979
+ if (!u) {
980
+ const h = Object.keys(c.attrs);
981
+ throw new _(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${h.length > 0 ? h.join(", ") + ", id" : "id"}`, r);
982
+ }
983
+ Pe(t, e, u, n, r);
984
+ }, On = (e, t, n, s) => {
985
+ for (const [r, i] of Object.entries(e)) {
986
+ if (r === "or" || r === "and") {
987
+ if (Array.isArray(i))
988
+ for (const u of i)
989
+ typeof u == "object" && u !== null && On(u, t, n, `${s}.${r}[${u}]`);
990
+ continue;
991
+ }
992
+ if (r === "id") {
993
+ Pe(i, "id", new ce("string", !1, !0), t, `${s}.id`);
994
+ continue;
995
+ }
996
+ if (r.includes(".")) {
997
+ ms(r, i, t, n, `${s}.${r}`);
998
+ continue;
999
+ }
1000
+ const o = n.entities[t];
1001
+ if (!o)
1002
+ continue;
1003
+ const a = o.attrs[r], c = o.links[r];
1004
+ if (!a && !c) {
1005
+ const u = Object.keys(o.attrs), h = Object.keys(o.links);
1006
+ throw new _(`Attribute or link '${r}' does not exist on entity '${t}'. Available attributes: ${u.length > 0 ? u.join(", ") : "none"}. Available links: ${h.length > 0 ? h.join(", ") : "none"}`, `${s}.${r}`);
1007
+ }
1008
+ if (a)
1009
+ Pe(i, r, a, t, `${s}.${r}`);
1010
+ else if (c) {
1011
+ if (typeof i == "string" && !Fe(i))
1012
+ throw new _(`Invalid value for link '${r}' in entity '${t}'. Expected a UUID, but received: ${i}`, `${s}.${r}`);
1013
+ const u = new ce("string", !1, !0);
1014
+ Pe(i, r, u, t, `${s}.${r}`);
1015
+ }
1016
+ }
1017
+ }, bs = (e, t, n, s, r = 0) => {
1018
+ for (const o of Object.keys(e))
1019
+ if (!Yt.includes(o))
1020
+ throw new _(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Yt.join(", ")}. Found: ${o}`, s);
1021
+ const i = [
1022
+ // 'limit', // only supported client side
1023
+ "offset",
1024
+ "before",
1025
+ "beforeInclusive",
1026
+ "after",
1027
+ "afterInclusive",
1028
+ "first",
1029
+ "last"
1030
+ ];
1031
+ for (const o of i)
1032
+ if (e[o] !== void 0 && r > 0)
1033
+ throw new _(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`, s);
1034
+ if (e.where && n) {
1035
+ if (typeof e.where != "object" || e.where === null)
1036
+ throw new _(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`, s ? `${s}.where` : void 0);
1037
+ On(e.where, t, n, s ? `${s}.where` : "where");
1038
+ }
1039
+ }, En = (e, t, n, s, r = 0) => {
1040
+ var i;
1041
+ if (!e || typeof e != "object")
1042
+ throw new _(`Query part for entity '${t}' must be an object, but received: ${typeof e}`, s);
1043
+ for (const o of Object.keys(e))
1044
+ if (o !== "$") {
1045
+ if (n && !(o in n.entities[t].links)) {
1046
+ const c = Object.keys(n.entities[t].links);
1047
+ throw new _(`Link '${o}' does not exist on entity '${t}'. Available links: ${c.length > 0 ? c.join(", ") : "none"}`, `${s}.${o}`);
1048
+ }
1049
+ const a = e[o];
1050
+ if (typeof a == "object" && a !== null) {
1051
+ const c = (i = n == null ? void 0 : n.entities[t].links[o]) == null ? void 0 : i.entityName;
1052
+ c && En(a, c, n, `${s}.${o}`, r + 1);
1053
+ }
1054
+ } else {
1055
+ const a = e[o];
1056
+ if (typeof a != "object" || a === null)
1057
+ throw new _(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`, `${s}.$`);
1058
+ bs(a, t, n, `${s}.$`, r);
1059
+ }
1060
+ }, Zt = (e, t) => {
1061
+ if (typeof e != "object" || e === null)
1062
+ throw new _(`Query must be an object, but received: ${typeof e}${e === null ? " (null)" : ""}`);
1063
+ if (Array.isArray(e))
1064
+ throw new _(`Query must be an object, but received: ${typeof e}`);
1065
+ const n = e;
1066
+ for (const s of Object.keys(n)) {
1067
+ if (Array.isArray(e[s]))
1068
+ throw new _(`Query keys must be strings, but found key of type: ${typeof s}`, s);
1069
+ if (typeof s != "string")
1070
+ throw new _(`Query keys must be strings, but found key of type: ${typeof s}`, s);
1071
+ if (s !== "$$ruleParams") {
1072
+ if (t && !t.entities[s]) {
1073
+ const r = Object.keys(t.entities);
1074
+ throw new _(`Entity '${s}' does not exist in schema. Available entities: ${r.length > 0 ? r.join(", ") : "none"}`, s);
1075
+ }
1076
+ En(n[s], s, t, s, 0);
1077
+ }
1078
+ }
1079
+ }, en = (e) => typeof e != "string" ? !1 : kn(e) ? !0 : Fe(e);
1080
+ class Z extends Error {
1081
+ constructor(t) {
1082
+ super(t), this.name = "TransactionValidationError";
1083
+ }
1084
+ }
1085
+ const Cn = (e) => e.length > 0 ? e.join(", ") : "none", gs = (e, t) => new Z(`Entity '${e}' does not exist in schema. Available entities: ${Cn(t)}`), kt = {
1086
+ string: (e) => typeof e == "string",
1087
+ number: (e) => typeof e == "number" && !isNaN(e),
1088
+ boolean: (e) => typeof e == "boolean",
1089
+ date: (e) => e instanceof Date || typeof e == "string" || typeof e == "number",
1090
+ json: () => !0
1091
+ }, ws = (e, t) => {
1092
+ var n;
1093
+ return e == null ? !0 : ((n = kt[t.valueType]) == null ? void 0 : n.call(kt, e)) ?? !1;
1094
+ }, xn = (e, t) => {
1095
+ const n = t.entities[e];
1096
+ if (!n)
1097
+ throw gs(e, Object.keys(t.entities));
1098
+ return n;
1099
+ }, $t = (e, t, n) => {
1100
+ const s = xn(e, n);
1101
+ if (typeof t != "object" || t === null)
1102
+ throw new Z(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);
1103
+ for (const [r, i] of Object.entries(t)) {
1104
+ if (r === "id")
1105
+ continue;
1106
+ const o = s.attrs[r];
1107
+ if (o && !ws(i, o))
1108
+ throw new Z(`Invalid value for attribute '${r}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof i}`);
1109
+ }
1110
+ }, tn = (e, t, n) => {
1111
+ const s = xn(e, n);
1112
+ if (typeof t != "object" || t === null)
1113
+ throw new Z(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);
1114
+ for (const [r, i] of Object.entries(t)) {
1115
+ if (!s.links[r]) {
1116
+ const a = Object.keys(s.links);
1117
+ throw new Z(`Link '${r}' does not exist on entity '${e}'. Available links: ${Cn(a)}`);
1118
+ }
1119
+ if (i != null) {
1120
+ if (Array.isArray(i)) {
1121
+ for (const a of i)
1122
+ if (!en(a))
1123
+ throw new Z(`Invalid entity ID in link '${r}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`);
1124
+ } else if (!en(i))
1125
+ throw new Z(`Invalid UUID in link '${r}' for entity '${e}'. Expected a UUID, but received: ${i}`);
1126
+ }
1127
+ }
1128
+ }, Ss = {
1129
+ create: $t,
1130
+ update: $t,
1131
+ merge: $t,
1132
+ link: tn,
1133
+ unlink: tn,
1134
+ delete: () => {
1135
+ }
1136
+ }, Is = (e, t) => {
1137
+ if (!t)
1138
+ return;
1139
+ const [n, s, r, i] = e;
1140
+ if (!Array.isArray(r) && !Fe(r))
1141
+ throw new Z(`Invalid id for entity '${s}'. Expected a UUID, but received: ${r}`);
1142
+ if (typeof s != "string")
1143
+ throw new Z(`Entity name must be a string, but received: ${typeof s}`);
1144
+ const o = Ss[n];
1145
+ o && i !== void 0 && o(s, i, t);
1146
+ }, ks = (e, t) => {
1147
+ const n = Array.isArray(e) ? e : [e];
1148
+ for (const s of n) {
1149
+ if (!s || typeof s != "object")
1150
+ throw new Z(`Transaction chunk must be an object, but received: ${typeof s}`);
1151
+ if (!Array.isArray(s.__ops))
1152
+ throw new Z(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);
1153
+ for (const r of s.__ops) {
1154
+ if (!Array.isArray(r))
1155
+ throw new Z(`Transaction operation must be an array, but received: ${typeof r}`);
1156
+ Is(r, t);
1157
+ }
1158
+ }
1159
+ };
1160
+ let $s = 0;
1161
+ class vs {
1162
+ constructor(t, n, s) {
1163
+ d(this, "type", "sse");
1164
+ d(this, "initParams", null);
1165
+ d(this, "sendQueue", []);
1166
+ d(this, "sendPromise");
1167
+ d(this, "closeFired", !1);
1168
+ d(this, "sseInitTimeout");
1169
+ d(this, "ES");
1170
+ d(this, "messageUrl");
1171
+ d(this, "conn");
1172
+ d(this, "url");
1173
+ d(this, "id");
1174
+ d(this, "onopen");
1175
+ d(this, "onmessage");
1176
+ d(this, "onclose");
1177
+ d(this, "onerror");
1178
+ this.id = `${this.type}_${$s++}`, this.url = n, this.messageUrl = s || this.url, this.ES = t, this.conn = new t(n), this.sseInitTimeout = setTimeout(() => {
1179
+ this.initParams || this.handleError();
1180
+ }, 1e4), this.conn.onmessage = (r) => {
1181
+ const i = JSON.parse(r.data);
1182
+ if (Array.isArray(i))
1183
+ for (const o of i)
1184
+ this.handleMessage(o);
1185
+ else
1186
+ this.handleMessage(i);
1187
+ }, this.conn.onerror = (r) => {
1188
+ this.handleError();
1189
+ };
1190
+ }
1191
+ handleMessage(t) {
1192
+ if (t.op === "sse-init") {
1193
+ this.initParams = {
1194
+ machineId: t["machine-id"],
1195
+ sessionId: t["session-id"],
1196
+ sseToken: t["sse-token"]
1197
+ }, this.onopen && this.onopen({ target: this }), clearTimeout(this.sseInitTimeout);
1198
+ return;
1199
+ }
1200
+ this.onmessage && this.onmessage({
1201
+ target: this,
1202
+ message: t
1203
+ });
1204
+ }
1205
+ // Runs the onerror and closes the connection
1206
+ handleError() {
1207
+ try {
1208
+ this.onerror && this.onerror({ target: this });
1209
+ } finally {
1210
+ this.handleClose();
1211
+ }
1212
+ }
1213
+ handleClose() {
1214
+ this.conn.close(), this.onclose && !this.closeFired && (this.closeFired = !0, this.onclose({ target: this }));
1215
+ }
1216
+ async postMessages(t) {
1217
+ var n, s, r;
1218
+ try {
1219
+ (await fetch(this.messageUrl, {
1220
+ method: "POST",
1221
+ headers: { "Content-Type": "application/json" },
1222
+ body: JSON.stringify({
1223
+ machine_id: (n = this.initParams) == null ? void 0 : n.machineId,
1224
+ session_id: (s = this.initParams) == null ? void 0 : s.sessionId,
1225
+ sse_token: (r = this.initParams) == null ? void 0 : r.sseToken,
1226
+ messages: t
1227
+ })
1228
+ })).ok || this.handleError();
1229
+ } catch {
1230
+ this.handleError();
1231
+ }
1232
+ }
1233
+ async flushQueue() {
1234
+ if (this.sendPromise || !this.sendQueue.length)
1235
+ return;
1236
+ const t = this.sendQueue;
1237
+ this.sendQueue = [];
1238
+ const n = this.postMessages(t);
1239
+ this.sendPromise = n, n.then(() => {
1240
+ this.sendPromise = null, this.flushQueue();
1241
+ });
1242
+ }
1243
+ send(t) {
1244
+ if (!this.isOpen() || !this.initParams)
1245
+ throw this.isConnecting() ? new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state.") : this.conn.readyState === this.ES.CLOSED ? new Error("EventSource is already in CLOSING or CLOSED state.") : new Error("EventSource is in invalid state.");
1246
+ this.sendQueue.push(t), this.flushQueue();
1247
+ }
1248
+ isOpen() {
1249
+ return this.conn.readyState === this.ES.OPEN && this.initParams !== null;
1250
+ }
1251
+ isConnecting() {
1252
+ return this.conn.readyState === this.ES.CONNECTING || this.conn.readyState === this.ES.OPEN && this.initParams === null;
1253
+ }
1254
+ close() {
1255
+ this.handleClose();
1256
+ }
1257
+ }
1258
+ var nn;
1259
+ (function(e) {
1260
+ e.InitialSyncBatch = "InitialSyncBatch", e.InitialSyncComplete = "InitialSyncComplete", e.LoadFromStorage = "LoadFromStorage", e.SyncTransaction = "SyncTransaction", e.Error = "Error";
1261
+ })(nn || (nn = {}));
1262
+ function Os({ WStream: e, opts: t, startStream: n, appendStream: s, registerStream: r }) {
1263
+ const i = t.clientId;
1264
+ let o = null, a = null, c = null;
1265
+ const u = Ae();
1266
+ let h = !1, l = !1;
1267
+ const y = [], m = [], g = [];
1268
+ let w = !1, p = 0, $ = 0;
1269
+ const v = [], F = new TextEncoder();
1270
+ function be() {
1271
+ l = !0;
1272
+ for (const b of y)
1273
+ b(a ?? void 0);
1274
+ }
1275
+ function bt(b) {
1276
+ return y.push(b), l && b(a ?? void 0), () => {
1277
+ const I = y.indexOf(b);
1278
+ I !== -1 && y.splice(I, 1);
1279
+ };
1280
+ }
1281
+ function Jt(b) {
1282
+ return g.push(b), () => {
1283
+ const I = g.indexOf(b);
1284
+ I !== -1 && g.splice(I, 1);
1285
+ };
1286
+ }
1287
+ t.waitUntil && t.waitUntil(new Promise((b) => {
1288
+ g.push(b);
1289
+ }));
1290
+ function R() {
1291
+ for (const b of g)
1292
+ try {
1293
+ b();
1294
+ } catch {
1295
+ }
1296
+ }
1297
+ function C(b) {
1298
+ return m.push(b), o && b(o), () => {
1299
+ const I = m.indexOf(b);
1300
+ I !== -1 && m.splice(I, 1);
1301
+ };
1302
+ }
1303
+ function ee(b) {
1304
+ o = b;
1305
+ for (const I of m)
1306
+ I(o);
1307
+ }
1308
+ function T() {
1309
+ w = !0;
1310
+ }
1311
+ function U(b) {
1312
+ let I = p, N = 0, Q = 0;
1313
+ for (const { byteLen: te } of v) {
1314
+ const oe = I + te;
1315
+ if (oe > b)
1316
+ break;
1317
+ I = oe, N++, Q += te;
1318
+ }
1319
+ N > 0 && (p += Q, $ -= Q, v.splice(0, N));
1320
+ }
1321
+ function j(b, I) {
1322
+ a = I, be(), b.error(I), R();
1323
+ }
1324
+ async function Y() {
1325
+ const b = await n({
1326
+ clientId: i,
1327
+ reconnectToken: u,
1328
+ ruleParams: t.ruleParams
1329
+ });
1330
+ switch (b.type) {
1331
+ case "ok": {
1332
+ const { streamId: I, offset: N } = b;
1333
+ o = I, U(N), v.length && s({
1334
+ streamId: I,
1335
+ chunks: v.map((Q) => Q.chunk),
1336
+ offset: p
1337
+ }), w = !1;
1338
+ break;
1339
+ }
1340
+ case "disconnect": {
1341
+ T();
1342
+ break;
1343
+ }
1344
+ case "error": {
1345
+ c && j(c, b.error);
1346
+ break;
1347
+ }
1348
+ }
1349
+ }
1350
+ function z() {
1351
+ T(), Y();
1352
+ }
1353
+ function Ye({ offset: b, done: I }) {
1354
+ U(b), I && (h = !0, R());
1355
+ }
1356
+ function Ht(b) {
1357
+ return h ? (j(b, new x("Stream has been closed.")), null) : o || (j(b, new x("Stream has not been initialized.")), null);
1358
+ }
1359
+ async function _e(b) {
1360
+ c = b;
1361
+ let I = !0, N = 0;
1362
+ for (; I; ) {
1363
+ let Q = Date.now() + Math.min(15e3, 500 * (N - 1));
1364
+ I = !1;
1365
+ const te = await n({
1366
+ clientId: t.clientId,
1367
+ reconnectToken: u,
1368
+ ruleParams: t.ruleParams
1369
+ });
1370
+ switch (te.type) {
1371
+ case "ok": {
1372
+ const { streamId: oe, offset: gt } = te;
1373
+ if (gt !== 0) {
1374
+ const ge = new x("Write stream is corrupted");
1375
+ j(b, ge);
1376
+ return;
1377
+ }
1378
+ ee(oe), r(oe, {
1379
+ onDisconnect: T,
1380
+ onFlush: Ye,
1381
+ onConnectionReconnect: Y,
1382
+ onAppendFailed: z
1383
+ }), w = !1;
1384
+ return;
1385
+ }
1386
+ case "disconnect": {
1387
+ I = !0, T(), N++, await new Promise((oe) => {
1388
+ setTimeout(oe, Math.max(0, Q - Date.now()));
1389
+ });
1390
+ break;
1391
+ }
1392
+ case "error": {
1393
+ j(b, te.error);
1394
+ return;
1395
+ }
1396
+ }
1397
+ }
1398
+ }
1399
+ class de extends e {
1400
+ constructor(I, N) {
1401
+ super(I, N);
1402
+ }
1403
+ async streamId() {
1404
+ return o || new Promise((I, N) => {
1405
+ const Q = [], te = () => {
1406
+ for (const ge of Q)
1407
+ ge();
1408
+ }, oe = (ge) => {
1409
+ I(ge), te();
1410
+ }, gt = (ge) => {
1411
+ N(ge || new x("Stream is closed.")), te();
1412
+ };
1413
+ Q.push(C(oe)), Q.push(bt(gt));
1414
+ });
1415
+ }
1416
+ }
1417
+ return {
1418
+ stream: new de({
1419
+ // TODO(dww): accept a storage so that write streams can survive across
1420
+ // browser restarts
1421
+ async start(b) {
1422
+ try {
1423
+ await _e(b);
1424
+ } catch (I) {
1425
+ j(b, I);
1426
+ }
1427
+ },
1428
+ write(b, I) {
1429
+ const N = Ht(I);
1430
+ if (N) {
1431
+ const Q = F.encode(b).length;
1432
+ v.push({ chunk: b, byteLen: Q });
1433
+ const te = p + $;
1434
+ $ += Q, w || s({ streamId: N, chunks: [b], offset: te });
1435
+ }
1436
+ },
1437
+ close() {
1438
+ o ? s({
1439
+ streamId: o,
1440
+ chunks: [],
1441
+ offset: p + $,
1442
+ isDone: !0
1443
+ }) : R(), be();
1444
+ },
1445
+ abort(b) {
1446
+ o ? s({
1447
+ streamId: o,
1448
+ chunks: [],
1449
+ offset: p + $,
1450
+ isDone: !0,
1451
+ abortReason: b
1452
+ }) : R(), be();
1453
+ }
1454
+ }),
1455
+ addCompleteCb: Jt,
1456
+ closed() {
1457
+ return l;
1458
+ }
1459
+ };
1460
+ }
1461
+ class Es {
1462
+ constructor() {
1463
+ d(this, "items", []);
1464
+ d(this, "resolvers", []);
1465
+ d(this, "isClosed", !1);
1466
+ }
1467
+ push(t) {
1468
+ if (this.isClosed)
1469
+ return;
1470
+ const n = this.resolvers.shift();
1471
+ n ? n({ value: t, done: !1 }) : this.items.push(t);
1472
+ }
1473
+ close() {
1474
+ for (this.isClosed = !0; this.resolvers.length > 0; )
1475
+ this.resolvers.shift()({ value: void 0, done: !0 });
1476
+ }
1477
+ async *[Symbol.asyncIterator]() {
1478
+ for (; ; )
1479
+ if (this.items.length > 0)
1480
+ yield this.items.shift();
1481
+ else {
1482
+ if (this.isClosed)
1483
+ return;
1484
+ {
1485
+ const { value: t, done: n } = await new Promise((s) => {
1486
+ this.resolvers.push(s);
1487
+ });
1488
+ if (n || !t)
1489
+ return;
1490
+ yield t;
1491
+ }
1492
+ }
1493
+ }
1494
+ }
1495
+ function Cs({ RStream: e, opts: t, startStream: n, cancelStream: s }) {
1496
+ let r = t.byteOffset || 0, i = !1;
1497
+ const o = new TextDecoder("utf-8"), a = new TextEncoder();
1498
+ let c, u = !1;
1499
+ const h = [], l = [];
1500
+ let y = null, m = null;
1501
+ function g(R) {
1502
+ u = !0;
1503
+ for (const C of h)
1504
+ C(R);
1505
+ }
1506
+ function w(R) {
1507
+ return h.push(R), () => {
1508
+ const C = h.indexOf(R);
1509
+ C !== -1 && h.splice(C, 1);
1510
+ };
1511
+ }
1512
+ function p(R) {
1513
+ return l.push(R), y && R(y), () => {
1514
+ const C = l.indexOf(R);
1515
+ C !== -1 && l.splice(C, 1);
1516
+ };
1517
+ }
1518
+ function $(R, C) {
1519
+ m = C, R.error(C), g(C);
1520
+ }
1521
+ let v = 0;
1522
+ async function F(R, C) {
1523
+ c = Ae();
1524
+ const ee = { ...R || {}, eventId: c };
1525
+ for await (const T of n(ee)) {
1526
+ if (i)
1527
+ return;
1528
+ if (T.type === "reconnect")
1529
+ return { retry: !0 };
1530
+ if (T.type === "error") {
1531
+ $(C, T.error);
1532
+ return;
1533
+ }
1534
+ if (T.offset > r) {
1535
+ $(C, new x("Stream is corrupted.")), i = !0;
1536
+ return;
1537
+ }
1538
+ y = T.streamId;
1539
+ for (const j of l)
1540
+ j(y);
1541
+ let U = r - T.offset;
1542
+ if (T.files && T.files.length) {
1543
+ const j = new AbortController();
1544
+ let Y = fetch(T.files[0].url, {
1545
+ signal: j.signal
1546
+ });
1547
+ for (let z = 0; z < T.files.length; z++) {
1548
+ const Ye = T.files[z + 1], _e = await Y;
1549
+ if (Ye && (Y = fetch(Ye.url, { signal: j.signal })), !_e.ok) {
1550
+ if (v++, v > 10) {
1551
+ $(C, new x("Unable to process stream."));
1552
+ return;
1553
+ }
1554
+ return { retry: !0 };
1555
+ }
1556
+ if (_e.body) {
1557
+ const de = _e.body.getReader();
1558
+ try {
1559
+ for (; ; ) {
1560
+ const { done: le, value: b } = await de.read();
1561
+ if (le)
1562
+ break;
1563
+ if (i) {
1564
+ j.abort();
1565
+ return;
1566
+ }
1567
+ let I = b;
1568
+ if (U > 0 && (I = b.subarray(U), U -= b.length - I.length), !I.length)
1569
+ continue;
1570
+ r += I.length;
1571
+ const N = o.decode(I);
1572
+ C.enqueue(N);
1573
+ }
1574
+ } finally {
1575
+ de.releaseLock();
1576
+ }
1577
+ } else {
1578
+ const de = await _e.arrayBuffer();
1579
+ let le = de;
1580
+ if (i) {
1581
+ j.abort();
1582
+ return;
1583
+ }
1584
+ if (U > 0 && (le = new Uint8Array(de).subarray(U), U -= de.byteLength - le.length), !le.byteLength)
1585
+ continue;
1586
+ r += le.byteLength;
1587
+ const b = o.decode(le);
1588
+ C.enqueue(b);
1589
+ }
1590
+ }
1591
+ }
1592
+ if (v = 0, T.content) {
1593
+ let j = T.content, Y = a.encode(T.content);
1594
+ if (U > 0) {
1595
+ const z = Y.subarray(U);
1596
+ if (U -= Y.length - z.length, !z.length)
1597
+ continue;
1598
+ Y = z, j = o.decode(z);
1599
+ }
1600
+ r += Y.length, C.enqueue(j);
1601
+ }
1602
+ }
1603
+ }
1604
+ async function be(R) {
1605
+ let C = !0, ee = 0;
1606
+ for (; C; ) {
1607
+ C = !1;
1608
+ let T = Date.now() + Math.min(15e3, 500 * (ee - 1));
1609
+ const U = await F({ ...t, offset: r }, R);
1610
+ U != null && U.retry && (C = !0, ee++, T < Date.now() - 3e5 && (ee = 0), await new Promise((j) => {
1611
+ setTimeout(j, Math.max(0, T - Date.now()));
1612
+ }));
1613
+ }
1614
+ !i && !u && (R.close(), g());
1615
+ }
1616
+ class bt extends e {
1617
+ constructor(C, ee) {
1618
+ super(C, ee);
1619
+ }
1620
+ async streamId() {
1621
+ if (y)
1622
+ return y;
1623
+ if (m)
1624
+ throw m;
1625
+ return new Promise((C, ee) => {
1626
+ const T = [], U = () => {
1627
+ for (const z of T)
1628
+ z();
1629
+ }, j = (z) => {
1630
+ C(z), U();
1631
+ }, Y = (z) => {
1632
+ ee(z || new x("Stream is closed.")), U();
1633
+ };
1634
+ T.push(p(j)), T.push(w(Y));
1635
+ });
1636
+ }
1637
+ }
1638
+ return {
1639
+ stream: new bt({
1640
+ start(R) {
1641
+ be(R);
1642
+ },
1643
+ cancel(R) {
1644
+ i = !0, c && s({ eventId: c }), g();
1645
+ }
1646
+ }),
1647
+ addCloseCb: w,
1648
+ closed() {
1649
+ return u;
1650
+ }
1651
+ };
1652
+ }
1653
+ class xs {
1654
+ constructor({ WStream: t, RStream: n, trySend: s, log: r }) {
1655
+ d(this, "trySend");
1656
+ d(this, "WStream");
1657
+ d(this, "RStream");
1658
+ d(this, "writeStreams", {});
1659
+ d(this, "startWriteStreamCbs", {});
1660
+ d(this, "readStreamIterators", {});
1661
+ d(this, "log");
1662
+ d(this, "activeStreams", /* @__PURE__ */ new Set());
1663
+ this.WStream = t, this.RStream = n, this.trySend = s, this.log = r;
1664
+ }
1665
+ createWriteStream(t) {
1666
+ const { stream: n, addCompleteCb: s } = Os({
1667
+ WStream: this.WStream,
1668
+ startStream: this.startWriteStream.bind(this),
1669
+ appendStream: this.appendStream.bind(this),
1670
+ registerStream: this.registerWriteStream.bind(this),
1671
+ opts: t
1672
+ });
1673
+ return this.activeStreams.add(n), s(() => {
1674
+ this.activeStreams.delete(n);
1675
+ }), n;
1676
+ }
1677
+ createReadStream(t) {
1678
+ const { stream: n, addCloseCb: s } = Cs({
1679
+ RStream: this.RStream,
1680
+ opts: t,
1681
+ startStream: this.startReadStream.bind(this),
1682
+ cancelStream: this.cancelReadStream.bind(this)
1683
+ });
1684
+ return this.activeStreams.add(n), s(() => {
1685
+ this.activeStreams.delete(n);
1686
+ }), n;
1687
+ }
1688
+ startWriteStream(t) {
1689
+ const n = Ae();
1690
+ let s = null;
1691
+ const r = new Promise((o) => {
1692
+ s = o;
1693
+ });
1694
+ this.startWriteStreamCbs[n] = s;
1695
+ const i = {
1696
+ op: "start-stream",
1697
+ "client-id": t.clientId,
1698
+ "reconnect-token": t.reconnectToken
1699
+ };
1700
+ return t.ruleParams && (i["rule-params"] = t.ruleParams), this.trySend(n, i), r;
1701
+ }
1702
+ registerWriteStream(t, n) {
1703
+ this.writeStreams[t] = n;
1704
+ }
1705
+ appendStream({ streamId: t, chunks: n, isDone: s, offset: r, abortReason: i }) {
1706
+ const o = {
1707
+ op: "append-stream",
1708
+ "stream-id": t,
1709
+ chunks: n,
1710
+ offset: r,
1711
+ done: !!s
1712
+ };
1713
+ i && (o["abort-reason"] = i), this.trySend(Ae(), o);
1714
+ }
1715
+ onAppendFailed(t) {
1716
+ const n = this.writeStreams[t["stream-id"]];
1717
+ n && n.onAppendFailed();
1718
+ }
1719
+ onStartStreamOk(t) {
1720
+ const n = this.startWriteStreamCbs[t["client-event-id"]];
1721
+ if (!n) {
1722
+ this.log.info("No stream for start-stream-ok", t);
1723
+ return;
1724
+ }
1725
+ n({ type: "ok", streamId: t["stream-id"], offset: t.offset }), delete this.startWriteStreamCbs[t["client-event-id"]];
1726
+ }
1727
+ onStreamFlushed(t) {
1728
+ const n = t["stream-id"], s = this.writeStreams[n];
1729
+ if (!s) {
1730
+ this.log.info("No stream cbs for stream-flushed", t);
1731
+ return;
1732
+ }
1733
+ s.onFlush({ offset: t.offset, done: t.done }), t.done && delete this.writeStreams[n];
1734
+ }
1735
+ startReadStream({ eventId: t, clientId: n, streamId: s, offset: r, ruleParams: i }) {
1736
+ const o = { op: "subscribe-stream" };
1737
+ if (!s && !n)
1738
+ throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");
1739
+ s && (o["stream-id"] = s), n && (o["client-id"] = n), r && (o.offset = r), i && (o["rule-params"] = i);
1740
+ const a = new Es();
1741
+ return this.readStreamIterators[t] = a, this.trySend(t, o), a;
1742
+ }
1743
+ cancelReadStream({ eventId: t }) {
1744
+ const n = {
1745
+ op: "unsubscribe-stream",
1746
+ "subscribe-event-id": t
1747
+ };
1748
+ this.trySend(Ae(), n), delete this.readStreamIterators[t];
1749
+ }
1750
+ onStreamAppend(t) {
1751
+ const n = t["client-event-id"], s = this.readStreamIterators[n];
1752
+ if (!s) {
1753
+ this.log.info("No iterator for read stream", t);
1754
+ return;
1755
+ }
1756
+ if (t.error) {
1757
+ t.retry ? s.push({ type: "reconnect" }) : s.push({
1758
+ type: "error",
1759
+ error: new x(t.error)
1760
+ }), s.close(), delete this.readStreamIterators[n];
1761
+ return;
1762
+ }
1763
+ s.push({
1764
+ type: "append",
1765
+ offset: t.offset,
1766
+ files: t.files,
1767
+ content: t.content,
1768
+ streamId: t["stream-id"]
1769
+ }), t.done && (s.close(), delete this.readStreamIterators[n]);
1770
+ }
1771
+ onConnectionStatusChange(t) {
1772
+ for (const n of Object.values(this.startWriteStreamCbs))
1773
+ n({ type: "disconnect" });
1774
+ if (this.startWriteStreamCbs = {}, t !== Ts.AUTHENTICATED)
1775
+ for (const { onDisconnect: n } of Object.values(this.writeStreams))
1776
+ n();
1777
+ else {
1778
+ for (const { onConnectionReconnect: n } of Object.values(this.writeStreams))
1779
+ n();
1780
+ for (const n of Object.values(this.readStreamIterators))
1781
+ n.push({ type: "reconnect" }), n.close();
1782
+ this.readStreamIterators = {};
1783
+ }
1784
+ }
1785
+ onRecieveError(t) {
1786
+ const n = t["original-event"];
1787
+ switch (n.op) {
1788
+ case "append-stream": {
1789
+ const s = n["stream-id"], r = this.writeStreams[s];
1790
+ r == null || r.onAppendFailed();
1791
+ break;
1792
+ }
1793
+ case "start-stream": {
1794
+ const s = t["client-event-id"], r = this.startWriteStreamCbs[s];
1795
+ r && (r({
1796
+ type: "error",
1797
+ error: new x(t.message || "Unknown error", t.hint)
1798
+ }), delete this.startWriteStreamCbs[s]);
1799
+ break;
1800
+ }
1801
+ case "subscribe-stream": {
1802
+ const s = t["client-event-id"], r = this.readStreamIterators[s];
1803
+ r && (r.push({
1804
+ type: "error",
1805
+ error: new x(t.message || "Unknown error", t.hint)
1806
+ }), r.close(), delete this.readStreamIterators[s]);
1807
+ break;
1808
+ }
1809
+ }
1810
+ }
1811
+ hasActiveStreams() {
1812
+ return this.activeStreams.size > 0;
1813
+ }
1814
+ }
1815
+ const Ts = {
1816
+ AUTHENTICATED: "authenticated"
1817
+ };
1818
+ class _s extends x {
1819
+ constructor(t) {
1820
+ super(t), this.name = "MissingApiURIError";
1821
+ }
1822
+ get [Symbol.toStringTag]() {
1823
+ return "MissingApiURIError";
1824
+ }
1825
+ }
1826
+ function Rs({ target: e, option: t = "apiURI", envVar: n }) {
1827
+ return `No SidekickDB server URL configured. ${n ? `Pass \`${t}\` to ${e} or set the ${n} environment variable` : `Pass \`${t}\` to ${e}`}, for example ${t}: 'https://sidekick.example.com'. SidekickDB has no default server.`;
1828
+ }
1829
+ function Wt(e, t) {
1830
+ if (typeof e == "string" && e.trim() !== "")
1831
+ return e;
1832
+ throw new _s(Rs(t));
1833
+ }
1834
+ function As() {
1835
+ return globalThis.__instantDbSchemaHashStore = globalThis.__instantDbSchemaHashStore ?? /* @__PURE__ */ new WeakMap(), globalThis.__instantDbSchemaHashStore;
1836
+ }
1837
+ function Ps() {
1838
+ return globalThis.__instantDbStore = globalThis.__instantDbStore ?? {}, globalThis.__instantDbStore;
1839
+ }
1840
+ Ps();
1841
+ As();
1842
+ class sn extends Event {
1843
+ /**
1844
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
1845
+ * but rather emitted by the `EventSource` object when an error occurs.
1846
+ *
1847
+ * @param type - The type of the event (should be "error")
1848
+ * @param errorEventInitDict - Optional properties to include in the error event
1849
+ */
1850
+ constructor(n, s) {
1851
+ super(n);
1852
+ /**
1853
+ * HTTP status code, if this was triggered by an HTTP error
1854
+ * Note: this is not part of the spec, but is included for better error handling.
1855
+ *
1856
+ * @public
1857
+ */
1858
+ d(this, "code");
1859
+ /**
1860
+ * Optional message attached to the error.
1861
+ * Note: this is not part of the spec, but is included for better error handling.
1862
+ *
1863
+ * @public
1864
+ */
1865
+ d(this, "message");
1866
+ this.code = (s == null ? void 0 : s.code) ?? void 0, this.message = (s == null ? void 0 : s.message) ?? void 0;
1867
+ }
1868
+ /**
1869
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1870
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1871
+ * we explicitly include the properties in the `inspect` method.
1872
+ *
1873
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
1874
+ *
1875
+ * @param _depth - The current depth
1876
+ * @param options - The options passed to `util.inspect`
1877
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1878
+ * @returns A string representation of the error
1879
+ */
1880
+ [Symbol.for("nodejs.util.inspect.custom")](n, s, r) {
1881
+ return r(rn(this), s);
1882
+ }
1883
+ /**
1884
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1885
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1886
+ * we explicitly include the properties in the `inspect` method.
1887
+ *
1888
+ * This is automatically called by Deno when you `console.log` an instance of this class.
1889
+ *
1890
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1891
+ * @param options - The options passed to `Deno.inspect`
1892
+ * @returns A string representation of the error
1893
+ */
1894
+ [Symbol.for("Deno.customInspect")](n, s) {
1895
+ return n(rn(this), s);
1896
+ }
1897
+ }
1898
+ function js(e) {
1899
+ const t = globalThis.DOMException;
1900
+ return typeof t == "function" ? new t(e, "SyntaxError") : new SyntaxError(e);
1901
+ }
1902
+ function _t(e) {
1903
+ return e instanceof Error ? "errors" in e && Array.isArray(e.errors) ? e.errors.map(_t).join(", ") : "cause" in e && e.cause instanceof Error ? `${e}: ${_t(e.cause)}` : e.message : `${e}`;
1904
+ }
1905
+ function rn(e) {
1906
+ return {
1907
+ type: e.type,
1908
+ message: e.message,
1909
+ code: e.code,
1910
+ defaultPrevented: e.defaultPrevented,
1911
+ cancelable: e.cancelable,
1912
+ timeStamp: e.timeStamp
1913
+ };
1914
+ }
1915
+ class on extends Error {
1916
+ constructor(t, n) {
1917
+ super(t), this.name = "ParseError", this.type = n.type, this.field = n.field, this.value = n.value, this.line = n.line;
1918
+ }
1919
+ }
1920
+ function vt(e) {
1921
+ }
1922
+ function Us(e) {
1923
+ if (typeof e == "function")
1924
+ throw new TypeError(
1925
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
1926
+ );
1927
+ const { onEvent: t = vt, onError: n = vt, onRetry: s = vt, onComment: r } = e;
1928
+ let i = "", o = !0, a, c = "", u = "";
1929
+ function h(w) {
1930
+ const p = o ? w.replace(/^\xEF\xBB\xBF/, "") : w, [$, v] = Ms(`${i}${p}`);
1931
+ for (const F of $)
1932
+ l(F);
1933
+ i = v, o = !1;
1934
+ }
1935
+ function l(w) {
1936
+ if (w === "") {
1937
+ m();
1938
+ return;
1939
+ }
1940
+ if (w.startsWith(":")) {
1941
+ r && r(w.slice(w.startsWith(": ") ? 2 : 1));
1942
+ return;
1943
+ }
1944
+ const p = w.indexOf(":");
1945
+ if (p !== -1) {
1946
+ const $ = w.slice(0, p), v = w[p + 1] === " " ? 2 : 1, F = w.slice(p + v);
1947
+ y($, F, w);
1948
+ return;
1949
+ }
1950
+ y(w, "", w);
1951
+ }
1952
+ function y(w, p, $) {
1953
+ switch (w) {
1954
+ case "event":
1955
+ u = p;
1956
+ break;
1957
+ case "data":
1958
+ c = `${c}${p}
1959
+ `;
1960
+ break;
1961
+ case "id":
1962
+ a = p.includes("\0") ? void 0 : p;
1963
+ break;
1964
+ case "retry":
1965
+ /^\d+$/.test(p) ? s(parseInt(p, 10)) : n(
1966
+ new on(`Invalid \`retry\` value: "${p}"`, {
1967
+ type: "invalid-retry",
1968
+ value: p,
1969
+ line: $
1970
+ })
1971
+ );
1972
+ break;
1973
+ default:
1974
+ n(
1975
+ new on(
1976
+ `Unknown field "${w.length > 20 ? `${w.slice(0, 20)}…` : w}"`,
1977
+ { type: "unknown-field", field: w, value: p, line: $ }
1978
+ )
1979
+ );
1980
+ break;
1981
+ }
1982
+ }
1983
+ function m() {
1984
+ c.length > 0 && t({
1985
+ id: a,
1986
+ event: u || void 0,
1987
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
1988
+ // then remove the last character from the data buffer.
1989
+ data: c.endsWith(`
1990
+ `) ? c.slice(0, -1) : c
1991
+ }), a = void 0, c = "", u = "";
1992
+ }
1993
+ function g(w = {}) {
1994
+ i && w.consume && l(i), o = !0, a = void 0, c = "", u = "", i = "";
1995
+ }
1996
+ return { feed: h, reset: g };
1997
+ }
1998
+ function Ms(e) {
1999
+ const t = [];
2000
+ let n = "", s = 0;
2001
+ for (; s < e.length; ) {
2002
+ const r = e.indexOf("\r", s), i = e.indexOf(`
2003
+ `, s);
2004
+ let o = -1;
2005
+ if (r !== -1 && i !== -1 ? o = Math.min(r, i) : r !== -1 ? r === e.length - 1 ? o = -1 : o = r : i !== -1 && (o = i), o === -1) {
2006
+ n = e.slice(s);
2007
+ break;
2008
+ } else {
2009
+ const a = e.slice(s, o);
2010
+ t.push(a), s = o + 1, e[s - 1] === "\r" && e[s] === `
2011
+ ` && s++;
2012
+ }
2013
+ }
2014
+ return [t, n];
2015
+ }
2016
+ var K, ye, Se, Je, He, qe, je, Ie, Ue, ae, ke, $e, ve, Me, B, Rt, at, ct, Tn, ut, ft, We, At, dt;
2017
+ class se extends EventTarget {
2018
+ constructor(n, s) {
2019
+ super();
2020
+ k(this, B);
2021
+ /**
2022
+ * ReadyState representing an EventSource currently trying to connect
2023
+ *
2024
+ * @public
2025
+ */
2026
+ d(this, "CONNECTING", 0);
2027
+ /**
2028
+ * ReadyState representing an EventSource connection that is open (eg connected)
2029
+ *
2030
+ * @public
2031
+ */
2032
+ d(this, "OPEN", 1);
2033
+ /**
2034
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
2035
+ *
2036
+ * @public
2037
+ */
2038
+ d(this, "CLOSED", 2);
2039
+ // PRIVATES FOLLOW
2040
+ /**
2041
+ * Current connection state
2042
+ *
2043
+ * @internal
2044
+ */
2045
+ k(this, K);
2046
+ /**
2047
+ * Original URL used to connect.
2048
+ *
2049
+ * Note that this will stay the same even after a redirect.
2050
+ *
2051
+ * @internal
2052
+ */
2053
+ k(this, ye);
2054
+ /**
2055
+ * The destination URL after a redirect. Is reset on reconnection.
2056
+ *
2057
+ * @internal
2058
+ */
2059
+ k(this, Se);
2060
+ /**
2061
+ * Whether to include credentials in the request
2062
+ *
2063
+ * @internal
2064
+ */
2065
+ k(this, Je);
2066
+ /**
2067
+ * The fetch implementation to use
2068
+ *
2069
+ * @internal
2070
+ */
2071
+ k(this, He);
2072
+ /**
2073
+ * The MessageEvent constructor to use
2074
+ *
2075
+ * @internal
2076
+ */
2077
+ k(this, qe);
2078
+ /**
2079
+ * The reconnection time in milliseconds
2080
+ *
2081
+ * @internal
2082
+ */
2083
+ k(this, je);
2084
+ /**
2085
+ * Reference to an ongoing reconnect attempt, if any
2086
+ *
2087
+ * @internal
2088
+ */
2089
+ k(this, Ie);
2090
+ /**
2091
+ * The last event ID seen by the EventSource, which will be sent as `Last-Event-ID` in the
2092
+ * request headers on a reconnection attempt.
2093
+ *
2094
+ * @internal
2095
+ */
2096
+ k(this, Ue, null);
2097
+ /**
2098
+ * The AbortController instance used to abort the fetch request
2099
+ *
2100
+ * @internal
2101
+ */
2102
+ k(this, ae);
2103
+ /**
2104
+ * Instance of an EventSource parser (`eventsource-parser` npm module)
2105
+ *
2106
+ * @internal
2107
+ */
2108
+ k(this, ke);
2109
+ /**
2110
+ * Holds the current error handler, attached through `onerror` property directly.
2111
+ * Note that `addEventListener('error', …)` will not be stored here.
2112
+ *
2113
+ * @internal
2114
+ */
2115
+ k(this, $e, null);
2116
+ /**
2117
+ * Holds the current message handler, attached through `onmessage` property directly.
2118
+ * Note that `addEventListener('message', …)` will not be stored here.
2119
+ *
2120
+ * @internal
2121
+ */
2122
+ k(this, ve, null);
2123
+ /**
2124
+ * Holds the current open handler, attached through `onopen` property directly.
2125
+ * Note that `addEventListener('open', …)` will not be stored here.
2126
+ *
2127
+ * @internal
2128
+ */
2129
+ k(this, Me, null);
2130
+ /**
2131
+ * Handles the fetch response
2132
+ *
2133
+ * @param response - The Fetch(ish) response
2134
+ * @internal
2135
+ */
2136
+ k(this, at, async (n) => {
2137
+ var y;
2138
+ f(this, ke).reset();
2139
+ const { body: s, redirected: r, status: i, headers: o } = n;
2140
+ if (i === 204) {
2141
+ O(this, B, We).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
2142
+ return;
2143
+ }
2144
+ if (r ? S(this, Se, new URL(n.url)) : S(this, Se, void 0), i !== 200) {
2145
+ O(this, B, We).call(this, `Non-200 status code (${i})`, i);
2146
+ return;
2147
+ }
2148
+ if (!(o.get("content-type") || "").startsWith("text/event-stream")) {
2149
+ O(this, B, We).call(this, 'Invalid content type, expected "text/event-stream"', i);
2150
+ return;
2151
+ }
2152
+ if (f(this, K) === this.CLOSED)
2153
+ return;
2154
+ S(this, K, this.OPEN);
2155
+ const c = new Event("open");
2156
+ if ((y = f(this, Me)) == null || y.call(this, c), this.dispatchEvent(c), typeof s != "object" || !s || !("getReader" in s)) {
2157
+ O(this, B, We).call(this, "Invalid response body, expected a web ReadableStream", i), this.close();
2158
+ return;
2159
+ }
2160
+ const u = new TextDecoder(), h = s.getReader();
2161
+ let l = !0;
2162
+ do {
2163
+ const { done: m, value: g } = await h.read();
2164
+ g && f(this, ke).feed(u.decode(g, { stream: !m })), m && (l = !1, f(this, ke).reset(), O(this, B, At).call(this));
2165
+ } while (l);
2166
+ });
2167
+ /**
2168
+ * Handles rejected requests for the EventSource endpoint
2169
+ *
2170
+ * @param err - The error from `fetch()`
2171
+ * @internal
2172
+ */
2173
+ k(this, ct, (n) => {
2174
+ S(this, ae, void 0), !(n.name === "AbortError" || n.type === "aborted") && O(this, B, At).call(this, _t(n));
2175
+ });
2176
+ /**
2177
+ * Called by EventSourceParser instance when an event has successfully been parsed
2178
+ * and is ready to be processed.
2179
+ *
2180
+ * @param event - The parsed event
2181
+ * @internal
2182
+ */
2183
+ k(this, ut, (n) => {
2184
+ typeof n.id == "string" && S(this, Ue, n.id);
2185
+ const s = new (f(this, qe))(n.event || "message", {
2186
+ data: n.data,
2187
+ origin: f(this, Se) ? f(this, Se).origin : f(this, ye).origin,
2188
+ lastEventId: n.id || ""
2189
+ });
2190
+ f(this, ve) && (!n.event || n.event === "message") && f(this, ve).call(this, s), this.dispatchEvent(s);
2191
+ });
2192
+ /**
2193
+ * Called by EventSourceParser instance when a new reconnection interval is received
2194
+ * from the EventSource endpoint.
2195
+ *
2196
+ * @param value - The new reconnection interval in milliseconds
2197
+ * @internal
2198
+ */
2199
+ k(this, ft, (n) => {
2200
+ S(this, je, n);
2201
+ });
2202
+ /**
2203
+ * Reconnects to the EventSource endpoint after a disconnect/failure
2204
+ *
2205
+ * @internal
2206
+ */
2207
+ k(this, dt, () => {
2208
+ S(this, Ie, void 0), f(this, K) === this.CONNECTING && O(this, B, Rt).call(this);
2209
+ });
2210
+ try {
2211
+ if (n instanceof URL)
2212
+ S(this, ye, n);
2213
+ else if (typeof n == "string")
2214
+ S(this, ye, new URL(n, Ds()));
2215
+ else
2216
+ throw new Error("Invalid URL");
2217
+ } catch {
2218
+ throw js("An invalid or illegal string was specified");
2219
+ }
2220
+ S(this, ke, Us({
2221
+ onEvent: f(this, ut),
2222
+ onRetry: f(this, ft)
2223
+ })), S(this, K, this.CONNECTING), S(this, je, 3e3), S(this, He, (s == null ? void 0 : s.fetch) ?? globalThis.fetch), S(this, qe, (s == null ? void 0 : s.messageEvent) ?? globalThis.MessageEvent), S(this, Je, (s == null ? void 0 : s.withCredentials) ?? !1), O(this, B, Rt).call(this);
2224
+ }
2225
+ /**
2226
+ * Returns the state of this EventSource object's connection. It can have the values described below.
2227
+ *
2228
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
2229
+ *
2230
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
2231
+ * defined in the TypeScript `dom` library.
2232
+ *
2233
+ * @public
2234
+ */
2235
+ get readyState() {
2236
+ return f(this, K);
2237
+ }
2238
+ /**
2239
+ * Returns the URL providing the event stream.
2240
+ *
2241
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
2242
+ *
2243
+ * @public
2244
+ */
2245
+ get url() {
2246
+ return f(this, ye).href;
2247
+ }
2248
+ /**
2249
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
2250
+ *
2251
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
2252
+ */
2253
+ get withCredentials() {
2254
+ return f(this, Je);
2255
+ }
2256
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
2257
+ get onerror() {
2258
+ return f(this, $e);
2259
+ }
2260
+ set onerror(n) {
2261
+ S(this, $e, n);
2262
+ }
2263
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
2264
+ get onmessage() {
2265
+ return f(this, ve);
2266
+ }
2267
+ set onmessage(n) {
2268
+ S(this, ve, n);
2269
+ }
2270
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
2271
+ get onopen() {
2272
+ return f(this, Me);
2273
+ }
2274
+ set onopen(n) {
2275
+ S(this, Me, n);
2276
+ }
2277
+ addEventListener(n, s, r) {
2278
+ const i = s;
2279
+ super.addEventListener(n, i, r);
2280
+ }
2281
+ removeEventListener(n, s, r) {
2282
+ const i = s;
2283
+ super.removeEventListener(n, i, r);
2284
+ }
2285
+ /**
2286
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
2287
+ *
2288
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
2289
+ *
2290
+ * @public
2291
+ */
2292
+ close() {
2293
+ f(this, Ie) && clearTimeout(f(this, Ie)), f(this, K) !== this.CLOSED && (f(this, ae) && f(this, ae).abort(), S(this, K, this.CLOSED), S(this, ae, void 0));
2294
+ }
2295
+ }
2296
+ K = new WeakMap(), ye = new WeakMap(), Se = new WeakMap(), Je = new WeakMap(), He = new WeakMap(), qe = new WeakMap(), je = new WeakMap(), Ie = new WeakMap(), Ue = new WeakMap(), ae = new WeakMap(), ke = new WeakMap(), $e = new WeakMap(), ve = new WeakMap(), Me = new WeakMap(), B = new WeakSet(), /**
2297
+ * Connect to the given URL and start receiving events
2298
+ *
2299
+ * @internal
2300
+ */
2301
+ Rt = function() {
2302
+ S(this, K, this.CONNECTING), S(this, ae, new AbortController()), f(this, He)(f(this, ye), O(this, B, Tn).call(this)).then(f(this, at)).catch(f(this, ct));
2303
+ }, at = new WeakMap(), ct = new WeakMap(), /**
2304
+ * Get request options for the `fetch()` request
2305
+ *
2306
+ * @returns The request options
2307
+ * @internal
2308
+ */
2309
+ Tn = function() {
2310
+ var r;
2311
+ const s = {
2312
+ // [spec] Let `corsAttributeState` be `Anonymous`…
2313
+ // [spec] …will have their mode set to "cors"…
2314
+ mode: "cors",
2315
+ redirect: "follow",
2316
+ headers: { Accept: "text/event-stream", ...f(this, Ue) ? { "Last-Event-ID": f(this, Ue) } : void 0 },
2317
+ cache: "no-store",
2318
+ signal: (r = f(this, ae)) == null ? void 0 : r.signal
2319
+ };
2320
+ return "window" in globalThis && (s.credentials = this.withCredentials ? "include" : "same-origin"), s;
2321
+ }, ut = new WeakMap(), ft = new WeakMap(), /**
2322
+ * Handles the process referred to in the EventSource specification as "failing a connection".
2323
+ *
2324
+ * @param error - The error causing the connection to fail
2325
+ * @param code - The HTTP status code, if available
2326
+ * @internal
2327
+ */
2328
+ We = function(n, s) {
2329
+ var i;
2330
+ f(this, K) !== this.CLOSED && S(this, K, this.CLOSED);
2331
+ const r = new sn("error", { code: s, message: n });
2332
+ (i = f(this, $e)) == null || i.call(this, r), this.dispatchEvent(r);
2333
+ }, /**
2334
+ * Schedules a reconnection attempt against the EventSource endpoint.
2335
+ *
2336
+ * @param message - The error causing the connection to fail
2337
+ * @param code - The HTTP status code, if available
2338
+ * @internal
2339
+ */
2340
+ At = function(n, s) {
2341
+ var i;
2342
+ if (f(this, K) === this.CLOSED)
2343
+ return;
2344
+ S(this, K, this.CONNECTING);
2345
+ const r = new sn("error", { code: s, message: n });
2346
+ (i = f(this, $e)) == null || i.call(this, r), this.dispatchEvent(r), S(this, Ie, setTimeout(f(this, dt), f(this, je)));
2347
+ }, dt = new WeakMap(), /**
2348
+ * ReadyState representing an EventSource currently trying to connect
2349
+ *
2350
+ * @public
2351
+ */
2352
+ d(se, "CONNECTING", 0), /**
2353
+ * ReadyState representing an EventSource connection that is open (eg connected)
2354
+ *
2355
+ * @public
2356
+ */
2357
+ d(se, "OPEN", 1), /**
2358
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
2359
+ *
2360
+ * @public
2361
+ */
2362
+ d(se, "CLOSED", 2);
2363
+ Object.defineProperty(se, Symbol.for("eventsource.supports-fetch-override"), {
2364
+ value: !0,
2365
+ writable: !1,
2366
+ configurable: !1,
2367
+ enumerable: !1
2368
+ });
2369
+ function Ds() {
2370
+ const e = "document" in globalThis ? globalThis.document : void 0;
2371
+ return e && typeof e == "object" && "baseURI" in e && typeof e.baseURI == "string" ? e.baseURI : void 0;
2372
+ }
2373
+ class _n extends Event {
2374
+ constructor(n, s) {
2375
+ super(n);
2376
+ d(this, "data");
2377
+ d(this, "origin");
2378
+ d(this, "lastEventId");
2379
+ d(this, "source");
2380
+ d(this, "ports");
2381
+ this.data = (s == null ? void 0 : s.data) ?? null, this.origin = (s == null ? void 0 : s.origin) ?? "", this.lastEventId = (s == null ? void 0 : s.lastEventId) ?? "", this.source = (s == null ? void 0 : s.source) ?? null, this.ports = (s == null ? void 0 : s.ports) ?? [];
2382
+ }
2383
+ /** @deprecated */
2384
+ initMessageEvent(n, s, r, i, o, a, c, u) {
2385
+ }
2386
+ }
2387
+ function Ns(e, t, n, s) {
2388
+ let r = null, i = !1;
2389
+ const o = [], a = (l) => {
2390
+ o.push(l), o.length > 100 && o.shift(), r && (r(), r = null);
2391
+ };
2392
+ e(a);
2393
+ const c = () => (n(a), Promise.resolve({ done: !0, value: void 0 }));
2394
+ return t(() => {
2395
+ i = !0, r && r(), c();
2396
+ }), {
2397
+ next: async () => {
2398
+ for (; ; ) {
2399
+ if (s() === "closed" || i)
2400
+ return c();
2401
+ const l = o.shift();
2402
+ if (l)
2403
+ return { value: l, done: !1 };
2404
+ await new Promise((m) => {
2405
+ r = m;
2406
+ });
2407
+ }
2408
+ },
2409
+ return: c,
2410
+ throw(l) {
2411
+ return n(a), Promise.reject(l);
2412
+ },
2413
+ [Symbol.asyncIterator]() {
2414
+ return this;
2415
+ }
2416
+ };
2417
+ }
2418
+ function he(e) {
2419
+ switch (e.readyState) {
2420
+ case e.CLOSED:
2421
+ return "closed";
2422
+ case e.CONNECTING:
2423
+ return "connecting";
2424
+ case e.OPEN:
2425
+ return "open";
2426
+ default:
2427
+ return "connecting";
2428
+ }
2429
+ }
2430
+ function Ls(e) {
2431
+ let t = null;
2432
+ return {
2433
+ ...e,
2434
+ text() {
2435
+ return t || (t = e.text()), t;
2436
+ },
2437
+ json() {
2438
+ return t || (t = e.text()), t.then((n) => JSON.parse(n));
2439
+ }
2440
+ };
2441
+ }
2442
+ function an(e) {
2443
+ if (!e)
2444
+ return;
2445
+ const t = {};
2446
+ for (const [n, s] of Object.entries(e))
2447
+ t[n] = {
2448
+ startCursor: s["start-cursor"],
2449
+ endCursor: s["end-cursor"],
2450
+ hasNextPage: s["has-next-page?"],
2451
+ hasPreviousPage: s["has-previous-page?"]
2452
+ };
2453
+ return t;
2454
+ }
2455
+ function Fs(e, t, n) {
2456
+ let s, r = !1;
2457
+ const i = Ae(), o = new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${i}`, {
2458
+ messageEvent: _n,
2459
+ fetch(p, $) {
2460
+ return s = null, fetch(p, {
2461
+ ...$,
2462
+ method: "POST",
2463
+ headers: n.headers,
2464
+ body: JSON.stringify({
2465
+ query: e,
2466
+ "inference?": n.inference,
2467
+ versions: {
2468
+ "@instantdb/admin": xe,
2469
+ "@instantdb/core": xe
2470
+ }
2471
+ })
2472
+ }).then((v) => (v.ok || (s = Ls(v)), v));
2473
+ }
2474
+ }), a = [], c = [], u = (p) => {
2475
+ a.push(p);
2476
+ }, h = (p) => {
2477
+ a.splice(a.indexOf(p), 1);
2478
+ }, l = (p) => {
2479
+ c.push(p);
2480
+ };
2481
+ t && u(t);
2482
+ let y = null;
2483
+ function m(p) {
2484
+ if (!r)
2485
+ for (const $ of a)
2486
+ try {
2487
+ $(p);
2488
+ } catch (v) {
2489
+ console.error("Error in subscribeQuery callback", v);
2490
+ }
2491
+ }
2492
+ function g(p) {
2493
+ var $, v;
2494
+ switch (p.op) {
2495
+ case "sse-init": {
2496
+ const F = p["machine-id"], be = p["session-id"];
2497
+ y = { machineId: F, sessionId: be };
2498
+ break;
2499
+ }
2500
+ case "add-query-ok": {
2501
+ m({
2502
+ type: "ok",
2503
+ data: p.result,
2504
+ pageInfo: an(($ = p["result-meta"]) == null ? void 0 : $["page-info"]),
2505
+ sessionInfo: y
2506
+ });
2507
+ break;
2508
+ }
2509
+ case "refresh-ok": {
2510
+ p.computations.length && m({
2511
+ type: "ok",
2512
+ data: p.computations[0]["instaql-result"],
2513
+ pageInfo: an((v = p.computations[0]["result-meta"]) == null ? void 0 : v["page-info"]),
2514
+ sessionInfo: y
2515
+ });
2516
+ break;
2517
+ }
2518
+ case "error": {
2519
+ m({
2520
+ type: "error",
2521
+ error: new ue({ body: p, status: p.status }),
2522
+ get readyState() {
2523
+ return he(o);
2524
+ },
2525
+ get isClosed() {
2526
+ return he(o) === "closed";
2527
+ },
2528
+ sessionInfo: y
2529
+ });
2530
+ break;
2531
+ }
2532
+ }
2533
+ }
2534
+ return o.onerror = (p) => {
2535
+ if (s)
2536
+ s.text().then(($) => {
2537
+ let v = { type: void 0, message: $ };
2538
+ try {
2539
+ v = JSON.parse($);
2540
+ } catch {
2541
+ }
2542
+ m({
2543
+ type: "error",
2544
+ error: new ue({
2545
+ status: s.status,
2546
+ body: v
2547
+ }),
2548
+ get readyState() {
2549
+ return he(o);
2550
+ },
2551
+ get isClosed() {
2552
+ return he(o) === "closed";
2553
+ },
2554
+ sessionInfo: y
2555
+ });
2556
+ });
2557
+ else {
2558
+ const $ = () => {
2559
+ m({
2560
+ type: "error",
2561
+ error: new ue({
2562
+ status: p.code || 500,
2563
+ body: {
2564
+ type: void 0,
2565
+ message: p.message || "Unknown error in subscribe query."
2566
+ }
2567
+ }),
2568
+ get readyState() {
2569
+ return he(o);
2570
+ },
2571
+ get isClosed() {
2572
+ return he(o) === "closed";
2573
+ },
2574
+ sessionInfo: y
2575
+ });
2576
+ };
2577
+ if (o.readyState === se.CLOSED) {
2578
+ $();
2579
+ return;
2580
+ }
2581
+ setTimeout(() => {
2582
+ o.readyState !== se.OPEN && $();
2583
+ }, 5e3);
2584
+ }
2585
+ }, o.onmessage = (p) => {
2586
+ g(JSON.parse(p.data));
2587
+ }, {
2588
+ close: () => {
2589
+ r = !0;
2590
+ for (const p of c)
2591
+ try {
2592
+ p();
2593
+ } catch ($) {
2594
+ console.error("Error in onClose callback", $);
2595
+ }
2596
+ o.close();
2597
+ },
2598
+ [Symbol.iterator]: () => {
2599
+ throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.");
2600
+ },
2601
+ get sessionInfo() {
2602
+ return y;
2603
+ },
2604
+ get readyState() {
2605
+ return he(o);
2606
+ },
2607
+ get isClosed() {
2608
+ return he(o) === "closed";
2609
+ },
2610
+ [Symbol.asyncIterator]: Ns.bind(this, u, l, h, () => 1)
2611
+ };
2612
+ }
2613
+ var fe = {};
2614
+ Object.defineProperty(fe, "__esModule", { value: !0 });
2615
+ var zs = fe.parseCookie = Pn;
2616
+ fe.parse = Pn;
2617
+ fe.stringifyCookie = qs;
2618
+ fe.stringifySetCookie = mt;
2619
+ fe.serialize = mt;
2620
+ fe.parseSetCookie = Bs;
2621
+ fe.stringifySetCookie = mt;
2622
+ fe.serialize = mt;
2623
+ const Rn = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/, An = /^[\u0021-\u003A\u003C-\u007E]*$/, Ws = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i, Ks = /^[\u0020-\u003A\u003D-\u007E]*$/, Vs = /^-?\d+$/, Js = Object.prototype.toString, Hs = /* @__PURE__ */ (() => {
2624
+ const e = function() {
2625
+ };
2626
+ return e.prototype = /* @__PURE__ */ Object.create(null), e;
2627
+ })();
2628
+ function Pn(e, t) {
2629
+ const n = new Hs(), s = e.length;
2630
+ if (s < 2)
2631
+ return n;
2632
+ const r = (t == null ? void 0 : t.decode) || jn;
2633
+ let i = 0;
2634
+ do {
2635
+ const o = jt(e, i, s);
2636
+ if (o === -1)
2637
+ break;
2638
+ const a = Pt(e, i, s);
2639
+ if (o > a) {
2640
+ i = e.lastIndexOf(";", o - 1) + 1;
2641
+ continue;
2642
+ }
2643
+ const c = pe(e, i, o);
2644
+ n[c] === void 0 && (n[c] = r(pe(e, o + 1, a))), i = a + 1;
2645
+ } while (i < s);
2646
+ return n;
2647
+ }
2648
+ function qs(e, t) {
2649
+ const n = (t == null ? void 0 : t.encode) || encodeURIComponent, s = [];
2650
+ for (const r of Object.keys(e)) {
2651
+ const i = e[r];
2652
+ if (i === void 0)
2653
+ continue;
2654
+ if (!Rn.test(r))
2655
+ throw new TypeError(`cookie name is invalid: ${r}`);
2656
+ const o = n(i);
2657
+ if (!An.test(o))
2658
+ throw new TypeError(`cookie val is invalid: ${i}`);
2659
+ s.push(`${r}=${o}`);
2660
+ }
2661
+ return s.join("; ");
2662
+ }
2663
+ function mt(e, t, n) {
2664
+ const s = typeof e == "object" ? e : { ...n, name: e, value: String(t) }, r = typeof t == "object" ? t : n, i = (r == null ? void 0 : r.encode) || encodeURIComponent;
2665
+ if (!Rn.test(s.name))
2666
+ throw new TypeError(`argument name is invalid: ${s.name}`);
2667
+ const o = s.value ? i(s.value) : "";
2668
+ if (!An.test(o))
2669
+ throw new TypeError(`argument val is invalid: ${s.value}`);
2670
+ let a = s.name + "=" + o;
2671
+ if (s.maxAge !== void 0) {
2672
+ if (!Number.isInteger(s.maxAge))
2673
+ throw new TypeError(`option maxAge is invalid: ${s.maxAge}`);
2674
+ a += "; Max-Age=" + s.maxAge;
2675
+ }
2676
+ if (s.domain) {
2677
+ if (!Ws.test(s.domain))
2678
+ throw new TypeError(`option domain is invalid: ${s.domain}`);
2679
+ a += "; Domain=" + s.domain;
2680
+ }
2681
+ if (s.path) {
2682
+ if (!Ks.test(s.path))
2683
+ throw new TypeError(`option path is invalid: ${s.path}`);
2684
+ a += "; Path=" + s.path;
2685
+ }
2686
+ if (s.expires) {
2687
+ if (!Qs(s.expires) || !Number.isFinite(s.expires.valueOf()))
2688
+ throw new TypeError(`option expires is invalid: ${s.expires}`);
2689
+ a += "; Expires=" + s.expires.toUTCString();
2690
+ }
2691
+ if (s.httpOnly && (a += "; HttpOnly"), s.secure && (a += "; Secure"), s.partitioned && (a += "; Partitioned"), s.priority)
2692
+ switch (typeof s.priority == "string" ? s.priority.toLowerCase() : void 0) {
2693
+ case "low":
2694
+ a += "; Priority=Low";
2695
+ break;
2696
+ case "medium":
2697
+ a += "; Priority=Medium";
2698
+ break;
2699
+ case "high":
2700
+ a += "; Priority=High";
2701
+ break;
2702
+ default:
2703
+ throw new TypeError(`option priority is invalid: ${s.priority}`);
2704
+ }
2705
+ if (s.sameSite)
2706
+ switch (typeof s.sameSite == "string" ? s.sameSite.toLowerCase() : s.sameSite) {
2707
+ case !0:
2708
+ case "strict":
2709
+ a += "; SameSite=Strict";
2710
+ break;
2711
+ case "lax":
2712
+ a += "; SameSite=Lax";
2713
+ break;
2714
+ case "none":
2715
+ a += "; SameSite=None";
2716
+ break;
2717
+ default:
2718
+ throw new TypeError(`option sameSite is invalid: ${s.sameSite}`);
2719
+ }
2720
+ return a;
2721
+ }
2722
+ function Bs(e, t) {
2723
+ const n = (t == null ? void 0 : t.decode) || jn, s = e.length, r = Pt(e, 0, s), i = jt(e, 0, r), o = i === -1 ? { name: "", value: n(pe(e, 0, r)) } : {
2724
+ name: pe(e, 0, i),
2725
+ value: n(pe(e, i + 1, r))
2726
+ };
2727
+ let a = r + 1;
2728
+ for (; a < s; ) {
2729
+ const c = Pt(e, a, s), u = jt(e, a, c), h = u === -1 ? pe(e, a, c) : pe(e, a, u), l = u === -1 ? void 0 : pe(e, u + 1, c);
2730
+ switch (h.toLowerCase()) {
2731
+ case "httponly":
2732
+ o.httpOnly = !0;
2733
+ break;
2734
+ case "secure":
2735
+ o.secure = !0;
2736
+ break;
2737
+ case "partitioned":
2738
+ o.partitioned = !0;
2739
+ break;
2740
+ case "domain":
2741
+ o.domain = l;
2742
+ break;
2743
+ case "path":
2744
+ o.path = l;
2745
+ break;
2746
+ case "max-age":
2747
+ l && Vs.test(l) && (o.maxAge = Number(l));
2748
+ break;
2749
+ case "expires":
2750
+ if (!l)
2751
+ break;
2752
+ const y = new Date(l);
2753
+ Number.isFinite(y.valueOf()) && (o.expires = y);
2754
+ break;
2755
+ case "priority":
2756
+ if (!l)
2757
+ break;
2758
+ const m = l.toLowerCase();
2759
+ (m === "low" || m === "medium" || m === "high") && (o.priority = m);
2760
+ break;
2761
+ case "samesite":
2762
+ if (!l)
2763
+ break;
2764
+ const g = l.toLowerCase();
2765
+ (g === "lax" || g === "strict" || g === "none") && (o.sameSite = g);
2766
+ break;
2767
+ }
2768
+ a = c + 1;
2769
+ }
2770
+ return o;
2771
+ }
2772
+ function Pt(e, t, n) {
2773
+ const s = e.indexOf(";", t);
2774
+ return s === -1 ? n : s;
2775
+ }
2776
+ function jt(e, t, n) {
2777
+ const s = e.indexOf("=", t);
2778
+ return s < n ? s : -1;
2779
+ }
2780
+ function pe(e, t, n) {
2781
+ let s = t, r = n;
2782
+ do {
2783
+ const i = e.charCodeAt(s);
2784
+ if (i !== 32 && i !== 9)
2785
+ break;
2786
+ } while (++s < r);
2787
+ for (; r > s; ) {
2788
+ const i = e.charCodeAt(r - 1);
2789
+ if (i !== 32 && i !== 9)
2790
+ break;
2791
+ r--;
2792
+ }
2793
+ return e.slice(s, r);
2794
+ }
2795
+ function jn(e) {
2796
+ if (e.indexOf("%") === -1)
2797
+ return e;
2798
+ try {
2799
+ return decodeURIComponent(e);
2800
+ } catch {
2801
+ return e;
2802
+ }
2803
+ }
2804
+ function Qs(e) {
2805
+ return Js.call(e) === "[object Date]";
2806
+ }
2807
+ const Gs = {
2808
+ "https://api.instantdb.com": {
2809
+ keys: [
2810
+ {
2811
+ kty: "OKP",
2812
+ crv: "Ed25519",
2813
+ alg: "EdDSA",
2814
+ use: "sig",
2815
+ kid: "1034696293",
2816
+ x: "N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o"
2817
+ }
2818
+ ]
2819
+ },
2820
+ "http://localhost:8888": {
2821
+ keys: [
2822
+ {
2823
+ kty: "OKP",
2824
+ crv: "Ed25519",
2825
+ alg: "EdDSA",
2826
+ use: "sig",
2827
+ kid: "503090235",
2828
+ x: "qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow"
2829
+ }
2830
+ ]
2831
+ }
2832
+ };
2833
+ function Xs(e) {
2834
+ if (e.kty === "OKP" && e.crv === "Ed25519")
2835
+ return { name: "Ed25519" };
2836
+ if (e.kty === "EC")
2837
+ return { name: "ECDSA", namedCurve: e.crv };
2838
+ if (e.kty === "RSA")
2839
+ return {
2840
+ name: "RSASSA-PKCS1-v1_5",
2841
+ hash: {
2842
+ RS256: "SHA-256",
2843
+ RS384: "SHA-384",
2844
+ RS512: "SHA-512"
2845
+ }[e.alg] || "SHA-256"
2846
+ };
2847
+ throw new Error(`Unsupported JWK configuration: kty=${e.kty}, crv=${e.crv}`);
2848
+ }
2849
+ async function Ys(e) {
2850
+ const t = Xs(e), n = await crypto.subtle.importKey("jwk", e, t, !1, ["verify"]);
2851
+ return { alg: t, key: n };
2852
+ }
2853
+ function Zs(e, t, n, s) {
2854
+ return crypto.subtle.verify(e, t, n, s);
2855
+ }
2856
+ function er(e) {
2857
+ const t = new Uint8Array(Math.ceil(e.length / 2));
2858
+ for (let n = 0; n < t.length; n++)
2859
+ t[n] = parseInt(e.substring(n * 2, n * 2 + 2), 16);
2860
+ return t;
2861
+ }
2862
+ function tr(e) {
2863
+ let t, n, s;
2864
+ for (const i of e.split(",")) {
2865
+ const [o, a] = i.split("=");
2866
+ switch (o) {
2867
+ case "t": {
2868
+ t = a;
2869
+ break;
2870
+ }
2871
+ case "kid": {
2872
+ n = a;
2873
+ break;
2874
+ }
2875
+ case "v1": {
2876
+ s = a;
2877
+ break;
2878
+ }
2879
+ }
2880
+ }
2881
+ const r = [];
2882
+ if (t || r.push("t"), n || r.push("kid"), s || r.push("v1"), r.length || !t || !n || !s)
2883
+ throw new x("Invalid Instant-Signature header.", {
2884
+ header: e,
2885
+ missingKeys: r
2886
+ });
2887
+ return { t, kid: n, v1: s };
2888
+ }
2889
+ function nr(e, t, n) {
2890
+ if (Math.floor(e.getTime() / 1e3) - parseInt(t, 10) > n)
2891
+ throw new x("Webhook signature is too old", {
2892
+ tolerance: n,
2893
+ receivedAt: e,
2894
+ t
2895
+ });
2896
+ }
2897
+ const cn = {}, sr = 300;
2898
+ async function rr(e, t) {
2899
+ const n = await t.text();
2900
+ try {
2901
+ const s = JSON.parse(n);
2902
+ return e(new ue({ status: t.status, body: s }));
2903
+ } catch {
2904
+ return e(new ue({
2905
+ status: t.status,
2906
+ body: { type: void 0, message: n }
2907
+ }));
2908
+ }
2909
+ }
2910
+ const ir = async (e, t) => {
2911
+ const n = {
2912
+ ...(t == null ? void 0 : t.headers) || {},
2913
+ "Instant-Core-Version": xe
2914
+ }, s = await fetch(e, { ...t, headers: n });
2915
+ return s.status === 200 ? s.json() : rr((r) => Promise.reject(r), s);
2916
+ };
2917
+ function Un(e) {
2918
+ return e ? new Date(e) : null;
2919
+ }
2920
+ function Re(e) {
2921
+ return {
2922
+ id: e.id,
2923
+ sink: e.sink,
2924
+ namespaces: e.namespaces ?? [],
2925
+ actions: e.actions,
2926
+ status: e.status,
2927
+ disabledReason: e.disabled_reason ?? null,
2928
+ createdAt: new Date(e.created_at),
2929
+ updatedAt: new Date(e.updated_at)
2930
+ };
2931
+ }
2932
+ function or(e) {
2933
+ return {
2934
+ attemptAt: Un(e["attempt-at"]),
2935
+ durationMs: e["duration-ms"] ?? null,
2936
+ success: e["success?"] ?? null,
2937
+ statusCode: e["status-code"] ?? null,
2938
+ responseText: e["response-text"] ?? null,
2939
+ errorType: e["error-type"] ?? null,
2940
+ errorMessage: e["error-message"] ?? null
2941
+ };
2942
+ }
2943
+ function Ot(e) {
2944
+ return {
2945
+ isn: e.isn,
2946
+ status: e.status,
2947
+ attempts: e.attempts ? e.attempts.map(or) : null,
2948
+ nextAttemptAfter: Un(e.next_attempt_after),
2949
+ createdAt: new Date(e.created_at),
2950
+ updatedAt: new Date(e.updated_at)
2951
+ };
2952
+ }
2953
+ var V, Be, De, Ne, Qe, G, ne;
2954
+ class ar {
2955
+ constructor(t) {
2956
+ k(this, G);
2957
+ k(this, V);
2958
+ k(this, Be);
2959
+ k(this, De);
2960
+ k(this, Ne);
2961
+ k(this, Qe);
2962
+ S(this, V, t.appId), S(this, Be, t.apiURI), S(this, De, t.token), S(this, Ne, t.withAuth), S(this, Qe, t.jsonFetch);
2963
+ }
2964
+ /**
2965
+ * Returns every webhook configured on the app, newest first. Includes both
2966
+ * active and disabled webhooks.
2967
+ */
2968
+ async list() {
2969
+ return ((await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks`)).webhooks || []).map(Re);
2970
+ }
2971
+ /**
2972
+ * Creates a new webhook. The webhook is created in the `active` state and
2973
+ * starts receiving matching events immediately.
2974
+ *
2975
+ * The server rejects the request if `url` is not an HTTPS URL pointing at a
2976
+ * public host, if `namespaces` doesn't reference any entity in the app's
2977
+ * schema, if `actions` is empty, or if the app has hit its webhook limit.
2978
+ *
2979
+ * An app may have at most **100 active webhooks** at a time; {@link delete}
2980
+ * a webhook to free up a slot before creating another.
2981
+ *
2982
+ * @example
2983
+ * const webhook = await db.webhooks.manager.create({
2984
+ * url: 'https://example.com/instant',
2985
+ * namespaces: ['posts', 'comments'],
2986
+ * actions: ['create', 'update'],
2987
+ * });
2988
+ */
2989
+ async create(t) {
2990
+ const n = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks`, {
2991
+ method: "POST",
2992
+ body: t
2993
+ });
2994
+ return Re(n.webhook);
2995
+ }
2996
+ /**
2997
+ * Updates a webhook's `url`, `namespaces`, and/or `actions`. Pass only the
2998
+ * fields you want to change; omitted fields keep their current value.
2999
+ *
3000
+ * Does not affect the webhook's status — use {@link enable} or
3001
+ * {@link disable} for that.
3002
+ */
3003
+ async update(t, n) {
3004
+ const s = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}`, { method: "POST", body: n });
3005
+ return Re(s.webhook);
3006
+ }
3007
+ /**
3008
+ * Deletes a webhook. No further events will be queued for it. Returns the
3009
+ * webhook as it looked just before deletion.
3010
+ */
3011
+ async delete(t) {
3012
+ const n = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}`, { method: "DELETE" });
3013
+ return Re(n.webhook);
3014
+ }
3015
+ /**
3016
+ * Re-enables a disabled webhook. Clears `disabledReason` and resumes
3017
+ * delivery for new events. Has no effect if the webhook is already active.
3018
+ *
3019
+ * Events that occurred while the webhook was disabled are not retroactively
3020
+ * delivered.
3021
+ */
3022
+ async enable(t) {
3023
+ const n = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}/enable`, { method: "POST", body: {} });
3024
+ return Re(n.webhook);
3025
+ }
3026
+ /**
3027
+ * Disables a webhook. No new events will be queued until it is re-enabled
3028
+ * via {@link enable}. In-flight events already being processed will still
3029
+ * complete.
3030
+ *
3031
+ * @param opts.reason Optional human-readable note stored on the webhook
3032
+ * and surfaced in the dashboard.
3033
+ */
3034
+ async disable(t, n) {
3035
+ const s = n != null && n.reason ? { reason: n.reason } : {}, r = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}/disable`, { method: "POST", body: s });
3036
+ return Re(r.webhook);
3037
+ }
3038
+ /**
3039
+ * Returns a page of events for a webhook, newest first.
3040
+ *
3041
+ * Events are retained for ~60 days. To paginate, pass the previous page's
3042
+ * `pageInfo.endCursor` as `opts.after`; stop when `pageInfo.hasNextPage`
3043
+ * is `false`.
3044
+ */
3045
+ async listEvents(t, n) {
3046
+ var i, o, a;
3047
+ const s = n != null && n.after ? `?after=${encodeURIComponent(n.after)}` : "", r = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}/events${s}`);
3048
+ return {
3049
+ events: (r.events || []).map(Ot),
3050
+ pageInfo: {
3051
+ startCursor: ((i = r.pageInfo) == null ? void 0 : i.startCursor) ?? null,
3052
+ endCursor: ((o = r.pageInfo) == null ? void 0 : o.endCursor) ?? null,
3053
+ hasNextPage: !!((a = r.pageInfo) != null && a.hasNextPage)
3054
+ }
3055
+ };
3056
+ }
3057
+ /**
3058
+ * Fetches a single webhook event by its `isn`.
3059
+ */
3060
+ async getEvent(t, n) {
3061
+ const s = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}/events/${n}`);
3062
+ return Ot(s.event);
3063
+ }
3064
+ /** Returns the full payload for an event. */
3065
+ async getPayload(t, n) {
3066
+ return O(this, G, ne).call(this, `/webhooks/payload/${f(this, V)}/${t}/${n}`);
3067
+ }
3068
+ /**
3069
+ * Re-queues an event for delivery, regardless of its current status. Use
3070
+ * this to retry a `failed` event or force a redelivery of a `success` one.
3071
+ *
3072
+ * The server rate-limits resends; if the event was queued or resent very
3073
+ * recently the call will fail with a validation error asking you to try
3074
+ * again in about a minute.
3075
+ */
3076
+ async resendEvent(t, n) {
3077
+ const s = await O(this, G, ne).call(this, `/dash/apps/${f(this, V)}/webhooks/${t}/events/${n}`, { method: "POST", body: {} });
3078
+ return Ot(s.event);
3079
+ }
3080
+ }
3081
+ V = new WeakMap(), Be = new WeakMap(), De = new WeakMap(), Ne = new WeakMap(), Qe = new WeakMap(), G = new WeakSet(), ne = function(t, n) {
3082
+ if (!f(this, V))
3083
+ throw new x("appId is required to manage webhooks. Pass it to the Webhooks constructor.");
3084
+ const s = (r) => {
3085
+ const i = {
3086
+ method: n == null ? void 0 : n.method,
3087
+ headers: {
3088
+ authorization: `Bearer ${r}`,
3089
+ "content-type": "application/json"
3090
+ }
3091
+ };
3092
+ return (n == null ? void 0 : n.body) !== void 0 && (i.body = JSON.stringify(n.body)), f(this, Qe).call(this, `${f(this, Be)}${t}`, i);
3093
+ };
3094
+ if (f(this, Ne))
3095
+ return f(this, Ne).call(this, s);
3096
+ if (!f(this, De))
3097
+ throw new x("A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.");
3098
+ return s(f(this, De));
3099
+ };
3100
+ var Ge, Oe;
3101
+ const Kt = class Kt {
3102
+ constructor(t, n) {
3103
+ /** App this instance is bound to. */
3104
+ d(this, "appId");
3105
+ /** Schema used to type webhook payloads and handler records. */
3106
+ d(this, "schema");
3107
+ k(this, Ge);
3108
+ /** Base URL for the Instant API. */
3109
+ d(this, "apiURI");
3110
+ k(this, Oe);
3111
+ /** Manage webhook subscriptions and inspect delivery events. */
3112
+ d(this, "manager");
3113
+ this.appId = t.appId, this.schema = t.schema, S(this, Ge, t.adminToken || t.token), this.apiURI = Wt(t.apiURI, { target: "new Webhooks()" }), S(this, Oe, n || ir), this.manager = new ar({
3114
+ appId: this.appId,
3115
+ apiURI: this.apiURI,
3116
+ token: f(this, Ge),
3117
+ withAuth: t.withAuth,
3118
+ jsonFetch: f(this, Oe)
3119
+ });
3120
+ }
3121
+ /**
3122
+ * Schema-bound helpers for building typed handler maps.
3123
+ *
3124
+ * - `typedHandlers(namespace, action, handler)` builds a single typed entry.
3125
+ * Pass `'$default'` for `namespace` to register a catch-all handler.
3126
+ * - `combineHandlers(...entries)` merges entries into a
3127
+ * {@link WebhookHandlers} object suitable for {@link processPayload} and
3128
+ * {@link processRequest}.
3129
+ *
3130
+ * If you already have a {@link Webhooks} instance, prefer the instance
3131
+ * form (`db.webhooks.helpers()`) — it infers `Schema` automatically.
3132
+ *
3133
+ * @example
3134
+ * const { typedHandlers, combineHandlers } = Webhooks.helpers<typeof schema>();
3135
+ * const handlers = combineHandlers(
3136
+ * typedHandlers('posts', 'create', (record) => { ... }),
3137
+ * typedHandlers('comments', '$default', (record) => { ... }),
3138
+ * typedHandlers('$default', (record) => { ... }),
3139
+ * );
3140
+ */
3141
+ static helpers() {
3142
+ function t(...s) {
3143
+ if (s.length === 2)
3144
+ return { $default: s[1] };
3145
+ const [r, i, o] = s;
3146
+ return { [r]: { [i]: o } };
3147
+ }
3148
+ function n(...s) {
3149
+ const r = {};
3150
+ for (const i of s)
3151
+ for (const o of Object.keys(i))
3152
+ o === "$default" ? r.$default = i.$default : r[o] = { ...r[o], ...i[o] };
3153
+ return r;
3154
+ }
3155
+ return {
3156
+ typedHandlers: t,
3157
+ combineHandlers: n
3158
+ };
3159
+ }
3160
+ /**
3161
+ * Instance form of {@link Webhooks.helpers} that infers `Schema` from this
3162
+ * instance — no `<typeof schema>` type argument required.
3163
+ *
3164
+ * @example
3165
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3166
+ */
3167
+ helpers() {
3168
+ return Kt.helpers();
3169
+ }
3170
+ /** Fetches Instant's JWK set for verifying webhook signatures. */
3171
+ async fetchJwks() {
3172
+ return await f(this, Oe).call(this, `${this.apiURI}/.well-known/webhooks/jwks.json`);
3173
+ }
3174
+ /**
3175
+ * Resolves a `kid` to an imported {@link CryptoKey}, hitting a
3176
+ * process-wide cache on repeat calls. Falls back to {@link fetchJwks} if
3177
+ * the key isn't already known.
3178
+ */
3179
+ async keyOfKid(t) {
3180
+ var o, a, c;
3181
+ const n = `${this.apiURI}:${t}`, s = cn[n];
3182
+ if (s)
3183
+ return s;
3184
+ const r = ((o = Gs[this.apiURI]) == null ? void 0 : o.keys.find((u) => u.kid === t)) || ((c = (a = await this.fetchJwks()) == null ? void 0 : a.keys) == null ? void 0 : c.find((u) => u.kid === t));
3185
+ if (!r)
3186
+ throw new x("Could not find matching signing key", { kid: t });
3187
+ const i = await Ys(r);
3188
+ return cn[n] = i, i;
3189
+ }
3190
+ /**
3191
+ * Verifies an `Instant-Signature` header against a body and returns the
3192
+ * parsed {@link WebhookBody} (containing the `payloadUrl` and a JWT
3193
+ * `token` for fetching the records).
3194
+ *
3195
+ * Throws if the signature doesn't validate, the signature is older than
3196
+ * `opts.tolerance` (default 300 seconds), or the body doesn't decode to
3197
+ * the expected shape.
3198
+ *
3199
+ * @param body Either the raw body string, or a function returning it.
3200
+ * Use a function to defer reading the body until after the
3201
+ * header has been parsed.
3202
+ */
3203
+ async validate(t, n, s) {
3204
+ const r = (s == null ? void 0 : s.receivedAt) || /* @__PURE__ */ new Date(), { t: i, kid: o, v1: a } = tr(t), c = (s == null ? void 0 : s.tolerance) ?? sr;
3205
+ nr(r, i, c);
3206
+ const { alg: u, key: h } = await this.keyOfKid(o), l = typeof n == "function" ? await n() : n, y = new TextEncoder().encode(`${i}.${l}`);
3207
+ if (!await Zs(u, h, er(a), y))
3208
+ throw new x("Instant Signature did not validate", {
3209
+ header: t
3210
+ });
3211
+ const g = JSON.parse(l);
3212
+ if (typeof g != "object" || typeof g.payloadUrl != "string" || typeof g.token != "string")
3213
+ throw new x("Invalid webhook body, expected an object with payloadUrl and token fields", { body: g });
3214
+ return g;
3215
+ }
3216
+ /**
3217
+ * Pulls the `Instant-Signature` header and body from a `Request` and
3218
+ * delegates to {@link validate}. Throws if the header is missing.
3219
+ */
3220
+ async validateRequest(t, n) {
3221
+ const s = t.headers.get("instant-signature");
3222
+ if (!s)
3223
+ throw new x("Request is missing Instant-Signature header");
3224
+ return this.validate(s, () => t.text(), n);
3225
+ }
3226
+ /**
3227
+ * Fetches the records and `idempotencyKey` for a validated
3228
+ * {@link WebhookBody}, authenticating with the JWT `token` it carries.
3229
+ */
3230
+ fetchPayloads({ payloadUrl: t, token: n }) {
3231
+ return f(this, Oe).call(this, t, {
3232
+ headers: { Authorization: `Bearer ${n}`, accept: "application/json" }
3233
+ });
3234
+ }
3235
+ /**
3236
+ * Dispatches each record in `payload` to its matching handler in
3237
+ * `handlers`. Resolution order per record: exact `namespace` + `action` →
3238
+ * `namespace`'s `$default` → top-level `$default`. Records with no matching
3239
+ * handler are skipped.
3240
+ *
3241
+ * Handlers run concurrently. If any handler rejects, the call rejects so
3242
+ * the caller (e.g. {@link processRequest}) can return a non-2xx response
3243
+ * and let Instant retry the event.
3244
+ */
3245
+ async processPayload(t, n) {
3246
+ var r, i;
3247
+ const s = [];
3248
+ for (const o of n.data) {
3249
+ const { namespace: a, action: c } = o, u = ((r = t == null ? void 0 : t[a]) == null ? void 0 : r[c]) || ((i = t == null ? void 0 : t[a]) == null ? void 0 : i.$default) || (t == null ? void 0 : t.$default);
3250
+ u && s.push(u(o));
3251
+ }
3252
+ await Promise.all(s);
3253
+ }
3254
+ /**
3255
+ * The one-liner for handling webhooks. Hand it your handlers and the
3256
+ * incoming `Request` — it verifies the signature, fetches the records, and
3257
+ * dispatches each one to your code.
3258
+ *
3259
+ * Async handlers are executed in parallel, the return promise will resolve once
3260
+ * all handlers complete and will reject if any of the handlers fails.
3261
+ *
3262
+ * @example
3263
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3264
+ *
3265
+ * const handlers = combineHandlers(
3266
+ * typedHandlers('posts', 'create', async (record) => {
3267
+ * await sendNewPostEmail(record.after);
3268
+ * }),
3269
+ * typedHandlers('$default', (record) => {
3270
+ * console.log('webhook event', record);
3271
+ * }),
3272
+ * );
3273
+ *
3274
+ * export async function POST(req: Request) {
3275
+ * await db.webhooks.processRequest(handlers, req);
3276
+ * return new Response('ok');
3277
+ * }
3278
+ */
3279
+ async processRequest(t, n, s) {
3280
+ const r = await this.validateRequest(n, s), i = await this.fetchPayloads(r);
3281
+ await this.processPayload(t, i);
3282
+ }
3283
+ /**
3284
+ * Adapter for frameworks that hand you a Node-style `http.IncomingMessage`
3285
+ * (Next.js Pages Router, Express, Koa, etc.) instead of a Web `Request`.
3286
+ * Wraps the request in a Web `Request` and delegates to
3287
+ * {@link processRequest}. You still send the HTTP response yourself.
3288
+ *
3289
+ * The raw body is required for signature verification. The adapter picks
3290
+ * it up from one of:
3291
+ *
3292
+ * - `req.body` if it's a `Buffer` or `Uint8Array` (set by middleware like
3293
+ * `express.raw({ type: 'application/json' })`)
3294
+ * - `req.body` if it's a string (set by middleware like `express.text()`)
3295
+ * - otherwise the unconsumed request stream
3296
+ *
3297
+ * Don't use a JSON body parser on this route — `express.json()` and
3298
+ * `bodyParser: true` in Next.js both parse the body into an object,
3299
+ * destroying the raw bytes the signature was computed over.
3300
+ *
3301
+ * @example
3302
+ * // Next.js Pages Router (`pages/api/webhooks.ts`)
3303
+ * import type { NextApiRequest, NextApiResponse } from 'next';
3304
+ *
3305
+ * export const config = { api: { bodyParser: false } };
3306
+ *
3307
+ * const { typedHandlers, combineHandlers } = db.webhooks.helpers();
3308
+ *
3309
+ * const handlers = combineHandlers(
3310
+ * typedHandlers('posts', 'create', async (record) => {
3311
+ * await sendNewPostEmail(record.after);
3312
+ * }),
3313
+ * typedHandlers('$default', (record) => {
3314
+ * console.log('unhandled record', record);
3315
+ * }),
3316
+ * );
3317
+ *
3318
+ * export default async function handler(
3319
+ * req: NextApiRequest,
3320
+ * res: NextApiResponse,
3321
+ * ) {
3322
+ * try {
3323
+ * await db.webhooks.processNodeRequest(handlers, req);
3324
+ * res.status(200).end();
3325
+ * } catch (e) {
3326
+ * res.status(400).json({ error: String(e) });
3327
+ * }
3328
+ * }
3329
+ *
3330
+ * @example
3331
+ * // Express — skip the JSON body parser on the webhook route and use
3332
+ * // `express.raw()` so `req.body` arrives as a Buffer.
3333
+ * import express from 'express';
3334
+ *
3335
+ * const app = express();
3336
+ *
3337
+ * app.use((req, res, next) => {
3338
+ * if (req.originalUrl === '/webhooks/instant') return next();
3339
+ * express.json()(req, res, next);
3340
+ * });
3341
+ *
3342
+ * app.post(
3343
+ * '/webhooks/instant',
3344
+ * express.raw({ type: 'application/json' }),
3345
+ * async (req, res) => {
3346
+ * try {
3347
+ * await db.webhooks.processNodeRequest(handlers, req);
3348
+ * res.status(200).end();
3349
+ * } catch (e) {
3350
+ * res.status(400).json({ error: String(e) });
3351
+ * }
3352
+ * },
3353
+ * );
3354
+ *
3355
+ * @example
3356
+ * // Koa — `ctx.req` is the raw IncomingMessage. If `koa-bodyparser` (or
3357
+ * // similar) runs on this route it consumes the stream, so either skip it
3358
+ * // here or pull the raw body yourself and shim it onto the request:
3359
+ * import Koa from 'koa';
3360
+ * import Router from '@koa/router';
3361
+ * import rawBody from 'raw-body';
3362
+ *
3363
+ * const router = new Router();
3364
+ *
3365
+ * router.post('/webhooks/instant', async (ctx) => {
3366
+ * try {
3367
+ * await db.webhooks.processNodeRequest(handlers, ctx.req, {
3368
+ * body: rawBody(ctx.req), // adapter awaits the Promise
3369
+ * });
3370
+ * ctx.status = 200;
3371
+ * } catch (e) {
3372
+ * ctx.status = 400;
3373
+ * ctx.body = { error: String(e) };
3374
+ * }
3375
+ * });
3376
+ *
3377
+ * @example
3378
+ * // NestJS (Express adapter). With `rawBody: true` on the factory, Nest
3379
+ * // populates `req.rawBody` itself — just pass `req`.
3380
+ * import { Controller, Post, Req, HttpCode } from '@nestjs/common';
3381
+ * import type { Request } from 'express';
3382
+ *
3383
+ * @Controller('webhooks')
3384
+ * export class WebhooksController {
3385
+ * @Post('instant')
3386
+ * @HttpCode(200)
3387
+ * async handle(@Req() req: Request) {
3388
+ * await db.webhooks.processNodeRequest(handlers, req);
3389
+ * }
3390
+ * }
3391
+ *
3392
+ * // (Pair with `NestFactory.create(AppModule, { rawBody: true })` in main.ts.)
3393
+ */
3394
+ async processNodeRequest(t, n, s) {
3395
+ let r, i = !1, o = (s == null ? void 0 : s.body) ?? n.rawBody ?? n.body;
3396
+ if (o != null && typeof o.then == "function" && (o = await o), typeof o == "string")
3397
+ r = o;
3398
+ else if (o instanceof Uint8Array)
3399
+ r = new TextDecoder("utf-8").decode(o);
3400
+ else if (o != null && typeof o == "object")
3401
+ try {
3402
+ r = JSON.stringify(o), i = !0;
3403
+ } catch {
3404
+ throw new x("Webhook request body has already been parsed and could not be re-serialized. Configure this route to receive the raw request body instead of parsed JSON.");
3405
+ }
3406
+ else if (n[Symbol.asyncIterator]) {
3407
+ const l = new TextEncoder(), y = [];
3408
+ for await (const p of n)
3409
+ y.push(typeof p == "string" ? l.encode(p) : p);
3410
+ let m = 0;
3411
+ for (const p of y)
3412
+ m += p.byteLength;
3413
+ const g = new Uint8Array(m);
3414
+ let w = 0;
3415
+ for (const p of y)
3416
+ g.set(p, w), w += p.byteLength;
3417
+ r = new TextDecoder("utf-8").decode(g);
3418
+ } else
3419
+ throw new x("Could not read the webhook request body. Pass a Node IncomingMessage with an unconsumed stream, or set `req.body` to the raw bytes (Buffer/Uint8Array) or string.");
3420
+ const a = typeof n.headers.host == "string" ? n.headers.host : "localhost", c = new URL(n.url ?? "/", `https://${a}`), u = new Headers();
3421
+ for (const [l, y] of Object.entries(n.headers))
3422
+ typeof y == "string" ? u.set(l, y) : Array.isArray(y) && u.set(l, y.join(", "));
3423
+ const h = new Request(c, {
3424
+ method: n.method ?? "POST",
3425
+ headers: u,
3426
+ body: r
3427
+ });
3428
+ try {
3429
+ await this.processRequest(t, h, s);
3430
+ } catch (l) {
3431
+ throw i && l instanceof x && l.message === "Instant Signature did not validate" ? new x("Webhook signature did not validate. The request body was re-serialized from a parsed JSON object, which can produce different bytes than the server signed. Configure this route to receive the raw request body instead of parsed JSON.", { hint: l.hint }) : l;
3432
+ }
3433
+ }
3434
+ };
3435
+ Ge = new WeakMap(), Oe = new WeakMap();
3436
+ let Ut = Kt;
3437
+ const cr = { target: "init() in @sidekickdb/admin" };
3438
+ function ur(e) {
3439
+ return {
3440
+ ...e,
3441
+ apiURI: Wt(e.apiURI, cr)
3442
+ };
3443
+ }
3444
+ function fr(e, t) {
3445
+ return "email" in t ? e["as-email"] = t.email : "token" in t ? e["as-token"] = t.token : "guest" in t && (e["as-guest"] = "true"), e;
3446
+ }
3447
+ function dr(e, t) {
3448
+ if (!(t && ("token" in t || "guest" in t)) && !e.adminToken)
3449
+ throw t && "email" in t ? new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`.") : new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.");
3450
+ }
3451
+ function P(e, t) {
3452
+ dr(e, t);
3453
+ const { adminToken: n, appId: s } = e, r = {
3454
+ "content-type": "application/json",
3455
+ "app-id": s
3456
+ };
3457
+ return n && (r.authorization = `Bearer ${n}`), t ? fr(r, t) : r;
3458
+ }
3459
+ function lr() {
3460
+ return (
3461
+ // NextJS 13 onwards added a `__nextPatched` property to the fetch function
3462
+ fetch.__nextPatched && // NextJS 15 onwards _also_ added a global `next-patch` symbol.
3463
+ !globalThis[Symbol.for("next-patch")]
3464
+ );
3465
+ }
3466
+ function hr() {
3467
+ return lr() ? { cache: "no-store" } : {};
3468
+ }
3469
+ async function pr(e, t) {
3470
+ const n = await t.text();
3471
+ try {
3472
+ const s = JSON.parse(n);
3473
+ return e(new ue({ status: t.status, body: s }));
3474
+ } catch {
3475
+ return e(new ue({
3476
+ status: t.status,
3477
+ body: { type: void 0, message: n }
3478
+ }));
3479
+ }
3480
+ }
3481
+ async function A(e, t) {
3482
+ const n = hr(), s = {
3483
+ ...(t == null ? void 0 : t.headers) || {},
3484
+ "Instant-Admin-Version": xe,
3485
+ "Instant-Core-Version": xe
3486
+ }, r = await fetch(e, { ...n, ...t, headers: s });
3487
+ if (r.status === 200) {
3488
+ const i = await r.json();
3489
+ return Promise.resolve(i);
3490
+ }
3491
+ return pr((i) => Promise.reject(i), r);
3492
+ }
3493
+ function yr(e) {
3494
+ var t, n, Mn;
3495
+ return t = class {
3496
+ constructor(i) {
3497
+ k(this, n);
3498
+ d(this, "source");
3499
+ d(this, "url");
3500
+ this.url = i, this.source = O(this, n, Mn).call(this, i);
3501
+ }
3502
+ get onopen() {
3503
+ return this.source.onopen;
3504
+ }
3505
+ set onopen(i) {
3506
+ this.source.onopen = i;
3507
+ }
3508
+ get onmessage() {
3509
+ return this.source.onmessage;
3510
+ }
3511
+ set onmessage(i) {
3512
+ this.source.onmessage = i;
3513
+ }
3514
+ get onerror() {
3515
+ return this.source.onerror;
3516
+ }
3517
+ set onerror(i) {
3518
+ this.source.onerror = i;
3519
+ }
3520
+ get readyState() {
3521
+ return this.source.readyState;
3522
+ }
3523
+ close() {
3524
+ this.source.close();
3525
+ }
3526
+ }, n = new WeakSet(), Mn = function(i) {
3527
+ return new se(i, {
3528
+ messageEvent: _n,
3529
+ fetch(a, c) {
3530
+ return fetch(a, {
3531
+ ...c,
3532
+ method: "POST",
3533
+ headers: e.headers,
3534
+ body: JSON.stringify({
3535
+ "inference?": e.inference,
3536
+ versions: {
3537
+ "@instantdb/admin": xe,
3538
+ "@instantdb/core": xe
3539
+ }
3540
+ })
3541
+ });
3542
+ }
3543
+ });
3544
+ }, d(t, "OPEN", se.OPEN), d(t, "CONNECTING", se.CONNECTING), d(t, "CLOSED", se.CLOSED), t;
3545
+ }
3546
+ function mr(e) {
3547
+ var n, s;
3548
+ (!e.appId || !Fe(e.appId)) && console.warn("warning: SidekickDB Admin DB must be initialized with a valid appId. Received: " + JSON.stringify(e.appId));
3549
+ const t = {
3550
+ ...e,
3551
+ appId: (n = e.appId) == null ? void 0 : n.trim(),
3552
+ adminToken: (s = e.adminToken) == null ? void 0 : s.trim(),
3553
+ useDateObjects: e.useDateObjects ?? !1
3554
+ };
3555
+ return new Mt(t);
3556
+ }
3557
+ function un(e) {
3558
+ return (Array.isArray(e) ? e : [e]).flatMap(hs);
3559
+ }
3560
+ class br {
3561
+ constructor(t) {
3562
+ d(this, "config");
3563
+ this.config = t;
3564
+ }
3565
+ async getPresence(t, n) {
3566
+ return (await A(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`, {
3567
+ method: "GET",
3568
+ headers: P(this.config)
3569
+ })).sessions || {};
3570
+ }
3571
+ }
3572
+ class gr {
3573
+ constructor(t) {
3574
+ d(this, "config");
3575
+ /**
3576
+ * Generates a magic code for the user with the given email.
3577
+ * This is useful if you want to use your own email provider
3578
+ * to send magic codes.
3579
+ *
3580
+ * @example
3581
+ * // Generate a magic code
3582
+ * const { code } = await db.auth.generateMagicCode({ email })
3583
+ * // Send the magic code to the user with your own email provider
3584
+ * await customEmailProvider.sendMagicCode(email, code)
3585
+ *
3586
+ * @see https://sidekickdb.co/docs/backend#custom-magic-codes
3587
+ */
3588
+ d(this, "generateMagicCode", async (t) => A(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
3589
+ method: "POST",
3590
+ headers: P(this.config),
3591
+ body: JSON.stringify({ email: t })
3592
+ }));
3593
+ /**
3594
+ * Sends a magic code to the user with the given email.
3595
+ * This uses Instant's built-in email provider.
3596
+ *
3597
+ * @example
3598
+ * // Send an email to user with magic code
3599
+ * await db.auth.sendMagicCode({ email })
3600
+ *
3601
+ * @see https://sidekickdb.co/docs/backend#custom-magic-codes
3602
+ */
3603
+ d(this, "sendMagicCode", async (t) => A(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
3604
+ method: "POST",
3605
+ headers: P(this.config),
3606
+ body: JSON.stringify({ email: t })
3607
+ }));
3608
+ /**
3609
+ * @deprecated Use {@link checkMagicCode} instead to get the `created` field
3610
+ * and support `extraFields`.
3611
+ *
3612
+ * @see https://sidekickdb.co/docs/backend#custom-magic-codes
3613
+ */
3614
+ d(this, "verifyMagicCode", async (t, n) => {
3615
+ const { user: s } = await A(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
3616
+ method: "POST",
3617
+ headers: P(this.config),
3618
+ body: JSON.stringify({ email: t, code: n })
3619
+ });
3620
+ return s;
3621
+ });
3622
+ /**
3623
+ * Verifies a magic code and returns the user along with whether
3624
+ * the user was newly created. Supports `extraFields` to set custom
3625
+ * `$users` properties at signup.
3626
+ *
3627
+ * @example
3628
+ * const { user, created } = await db.auth.checkMagicCode(
3629
+ * email,
3630
+ * code,
3631
+ * { extraFields: { nickname: 'ari' } },
3632
+ * );
3633
+ *
3634
+ * @see https://sidekickdb.co/docs/backend#custom-magic-codes
3635
+ */
3636
+ d(this, "checkMagicCode", async (t, n, s) => {
3637
+ const r = await A(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
3638
+ method: "POST",
3639
+ headers: P(this.config),
3640
+ body: JSON.stringify({
3641
+ email: t,
3642
+ code: n,
3643
+ ...s != null && s.extraFields ? { "extra-fields": s.extraFields } : {}
3644
+ })
3645
+ });
3646
+ return { user: r.user, created: r.created };
3647
+ });
3648
+ /**
3649
+ * Verifies a given token and returns the associated user.
3650
+ *
3651
+ * This is often useful for writing custom endpoints, where you need
3652
+ * to authenticate users.
3653
+ *
3654
+ * @example
3655
+ * app.post('/custom_endpoint', async (req, res) => {
3656
+ * const user = await db.auth.verifyToken(req.headers['token'])
3657
+ * if (!user) {
3658
+ * return res.status(401).send('Uh oh, you are not authenticated')
3659
+ * }
3660
+ * // ...
3661
+ * })
3662
+ * @see https://sidekickdb.co/docs/backend#custom-endpoints
3663
+ */
3664
+ d(this, "verifyToken", async (t) => (await A(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
3665
+ method: "POST",
3666
+ headers: { "content-type": "application/json" },
3667
+ body: JSON.stringify({
3668
+ "app-id": this.config.appId,
3669
+ "refresh-token": t
3670
+ })
3671
+ })).user);
3672
+ /**
3673
+ * Retrieves an app user by id, email, or refresh token.
3674
+ * Resolves to `null` when no user matches; throws on malformed
3675
+ * input or auth errors.
3676
+ *
3677
+ * @example
3678
+ * const user = await db.auth.getUser({ email });
3679
+ * if (!user) {
3680
+ * console.log("No user found");
3681
+ * return;
3682
+ * }
3683
+ * console.log("Found user:", user);
3684
+ *
3685
+ * @see https://sidekickdb.co/docs/backend#retrieve-a-user
3686
+ */
3687
+ d(this, "getUser", async (t) => {
3688
+ const n = new URLSearchParams(Object.entries(t)).toString();
3689
+ return (await A(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
3690
+ method: "GET",
3691
+ headers: P(this.config)
3692
+ })).user;
3693
+ });
3694
+ /**
3695
+ * Deletes an app user by id, email, or refresh token.
3696
+ * Resolves to `null` when no user matches; throws on malformed
3697
+ * input or auth errors.
3698
+ *
3699
+ * NB: This _only_ deletes the user; it does not delete all user data.
3700
+ * You will need to handle this manually.
3701
+ *
3702
+ * @example
3703
+ * const deletedUser = await db.auth.deleteUser({ email });
3704
+ * if (!deletedUser) {
3705
+ * console.log("No user found to delete");
3706
+ * return;
3707
+ * }
3708
+ * console.log("Deleted user:", deletedUser);
3709
+ *
3710
+ * @see https://sidekickdb.co/docs/backend#delete-a-user
3711
+ */
3712
+ d(this, "deleteUser", async (t) => {
3713
+ const n = new URLSearchParams(Object.entries(t)).toString();
3714
+ return (await A(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
3715
+ method: "DELETE",
3716
+ headers: P(this.config)
3717
+ })).deleted;
3718
+ });
3719
+ /**
3720
+ * Get instant user from Request
3721
+ *
3722
+ * Reads cookies and gets a validated user
3723
+ * @param req The request containing a cookie synced with createInstantRouteHandler
3724
+ * @param opts Allow disabling validation of refresh token
3725
+ */
3726
+ d(this, "getUserFromRequest", async (t, n) => {
3727
+ const s = t.headers.get("cookie") || "", r = zs(s), i = "instant_user_" + this.config.appId;
3728
+ if (!r[i])
3729
+ return null;
3730
+ const o = r[i], a = JSON.parse(o);
3731
+ return a != null && a.refresh_token ? n != null && n.disableValidation ? a : await this.verifyToken(a.refresh_token) : null;
3732
+ });
3733
+ this.config = t, this.createToken = this.createToken.bind(this);
3734
+ }
3735
+ async createToken(t) {
3736
+ const n = typeof t == "string" ? { email: t } : t;
3737
+ return (await A(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
3738
+ method: "POST",
3739
+ headers: P(this.config),
3740
+ body: JSON.stringify(n)
3741
+ })).user.refresh_token;
3742
+ }
3743
+ async signOut(t) {
3744
+ const n = typeof t == "string" ? { email: t } : t, s = this.config;
3745
+ await A(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
3746
+ method: "POST",
3747
+ headers: P(s),
3748
+ body: JSON.stringify(n)
3749
+ });
3750
+ }
3751
+ }
3752
+ const fn = (e) => e && typeof e == "object" && typeof e.pipe == "function" && typeof e.read == "function", wr = (e) => e && typeof e.getReader == "function";
3753
+ function dn(e) {
3754
+ return /^[\x20-\x7e\xa0-\xff]*$/.test(e);
3755
+ }
3756
+ class ln {
3757
+ constructor(t, n) {
3758
+ d(this, "config");
3759
+ d(this, "impersonationOpts");
3760
+ /**
3761
+ * Uploads file at the provided path. Accepts a Buffer or a Readable stream.
3762
+ *
3763
+ * @see https://sidekickdb.co/docs/storage
3764
+ * @example
3765
+ * const buffer = fs.readFileSync('demo.png');
3766
+ * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
3767
+ */
3768
+ d(this, "uploadFile", async (t, n, s = {}) => {
3769
+ const r = {
3770
+ ...P(this.config, this.impersonationOpts)
3771
+ };
3772
+ dn(t) && (r.path = t), s.contentDisposition && dn(s.contentDisposition) && (r["content-disposition"] = s.contentDisposition), delete r["content-type"], s.contentType && (r["content-type"] = s.contentType);
3773
+ let i;
3774
+ if (fn(n) && (i = "half"), fn(n) || wr(n)) {
3775
+ if (!s.fileSize)
3776
+ throw new Error("fileSize is required in metadata when uploading streams");
3777
+ r["content-length"] = s.fileSize.toString();
3778
+ }
3779
+ let o = {
3780
+ method: "PUT",
3781
+ headers: r,
3782
+ body: n,
3783
+ ...i && { duplex: i }
3784
+ }, a = `${this.config.apiURI}/admin/storage/upload?app_id=${encodeURIComponent(this.config.appId)}&path=${encodeURIComponent(t)}`;
3785
+ return s.contentDisposition && (a += `&content-disposition=${encodeURIComponent(s.contentDisposition)}`), A(a, o);
3786
+ });
3787
+ /**
3788
+ * Deletes a file by its path name (e.g. "photos/demo.png").
3789
+ *
3790
+ * @deprecated Use `db.transact` to delete files instead:
3791
+ * @example
3792
+ * // Delete by id
3793
+ * await db.transact(db.tx.$files[fileId].delete());
3794
+ *
3795
+ * // Delete by path
3796
+ * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete());
3797
+ *
3798
+ * @see https://sidekickdb.co/docs/storage
3799
+ */
3800
+ d(this, "delete", async (t) => A(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
3801
+ method: "DELETE",
3802
+ headers: P(this.config, this.impersonationOpts)
3803
+ }));
3804
+ /**
3805
+ * Deletes multiple files by their path names.
3806
+ *
3807
+ * @deprecated Use `db.transact` to delete files instead:
3808
+ * @example
3809
+ * // Delete multiple files by path
3810
+ * const paths = ['images/1.png', 'images/2.png', 'images/3.png'];
3811
+ * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete()));
3812
+ *
3813
+ * @see https://sidekickdb.co/docs/storage
3814
+ */
3815
+ d(this, "deleteMany", async (t) => A(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
3816
+ method: "POST",
3817
+ headers: P(this.config, this.impersonationOpts),
3818
+ body: JSON.stringify({ filenames: t })
3819
+ }));
3820
+ /**
3821
+ * @deprecated. This method will be removed in the future. Use `uploadFile`
3822
+ * instead
3823
+ */
3824
+ d(this, "upload", async (t, n, s = {}) => {
3825
+ const { data: r } = await A(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
3826
+ method: "POST",
3827
+ headers: P(this.config),
3828
+ body: JSON.stringify({
3829
+ app_id: this.config.appId,
3830
+ filename: t
3831
+ })
3832
+ }), i = {}, o = s.contentType;
3833
+ o && (i["Content-Type"] = o);
3834
+ const { ok: a } = await fetch(r, {
3835
+ method: "PUT",
3836
+ body: n,
3837
+ headers: i
3838
+ });
3839
+ return a;
3840
+ });
3841
+ /**
3842
+ * @deprecated. This method will be removed in the future. Use `query` instead
3843
+ * @example
3844
+ * const files = await db.query({ $files: {}})
3845
+ */
3846
+ d(this, "list", async () => {
3847
+ const { data: t } = await A(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
3848
+ method: "GET",
3849
+ headers: P(this.config)
3850
+ });
3851
+ return t;
3852
+ });
3853
+ /**
3854
+ * @deprecated. getDownloadUrl will be removed in the future.
3855
+ * Use `query` instead to query and fetch for valid urls
3856
+ *
3857
+ * db.useQuery({
3858
+ * $files: {
3859
+ * $: {
3860
+ * where: {
3861
+ * path: "moop.png"
3862
+ * }
3863
+ * }
3864
+ * }
3865
+ * })
3866
+ */
3867
+ d(this, "getDownloadUrl", async (t) => {
3868
+ const { data: n } = await A(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
3869
+ method: "GET",
3870
+ headers: P(this.config)
3871
+ });
3872
+ return n;
3873
+ });
3874
+ this.config = t, this.impersonationOpts = n;
3875
+ }
3876
+ }
3877
+ var Le;
3878
+ class Sr {
3879
+ constructor(t) {
3880
+ k(this, Le);
3881
+ /**
3882
+ * Creates a new ReadableStream for the given clientId.
3883
+ *
3884
+ * @example
3885
+ * const stream = db.streams.createReadStream({clientId: clientId})
3886
+ * for await (const chunk of stream) {
3887
+ * console.log(chunk);
3888
+ * }
3889
+ */
3890
+ d(this, "createReadStream", (t) => f(this, Le).call(this).createReadStream(t));
3891
+ /**
3892
+ * Creates a new WritableStream for the given clientId.
3893
+ *
3894
+ * @example
3895
+ * const writeStream = db.streams.createWriteStream({clientId: clientId})
3896
+ * const writer = writeStream.getWriter();
3897
+ * writer.write('Hello world');
3898
+ * writer.close();
3899
+ */
3900
+ d(this, "createWriteStream", (t) => f(this, Le).call(this).createWriteStream(t));
3901
+ S(this, Le, t);
3902
+ }
3903
+ }
3904
+ Le = new WeakMap();
3905
+ function Ir(e, t = console) {
3906
+ return {
3907
+ info: e ? (...n) => t.info(...n) : () => {
3908
+ },
3909
+ debug: e ? (...n) => t.debug(...n) : () => {
3910
+ },
3911
+ error: e ? (...n) => t.error(...n) : () => {
3912
+ }
3913
+ };
3914
+ }
3915
+ var W, Ee, J, H, D, Dn, rt, Nn, Ln, Fn, lt, ht, pt, Dt, zn, yt;
3916
+ const Vt = class Vt {
3917
+ constructor(t) {
3918
+ k(this, D);
3919
+ d(this, "config");
3920
+ d(this, "auth");
3921
+ d(this, "storage");
3922
+ d(this, "streams");
3923
+ d(this, "rooms");
3924
+ d(this, "impersonationOpts");
3925
+ d(this, "webhooks");
3926
+ k(this, W, null);
3927
+ k(this, Ee, 0);
3928
+ k(this, J, null);
3929
+ k(this, H);
3930
+ d(this, "tx", $n());
3931
+ /**
3932
+ * Sometimes you want to scope queries to a specific user.
3933
+ *
3934
+ * You can provide a user's auth token, email, or impersonate a guest.
3935
+ *
3936
+ * @see https://sidekickdb.co/docs/backend#impersonating-users
3937
+ * @example
3938
+ * await db.asUser({email: "stopa@example.com"}).query({ goals: {} })
3939
+ */
3940
+ d(this, "asUser", (t) => {
3941
+ const n = new Vt({
3942
+ ...this.config
3943
+ });
3944
+ return n.impersonationOpts = t, n.storage = new ln(this.config, t), n;
3945
+ });
3946
+ /**
3947
+ * Use this to query your data!
3948
+ *
3949
+ * @see https://sidekickdb.co/docs/instaql
3950
+ *
3951
+ * @example
3952
+ * // fetch all goals
3953
+ * await db.query({ goals: {} })
3954
+ *
3955
+ * // goals where the title is "Get Fit"
3956
+ * await db.query({ goals: { $: { where: { title: "Get Fit" } } } })
3957
+ *
3958
+ * // all goals, _alongside_ their todos
3959
+ * await db.query({ goals: { todos: {} } })
3960
+ */
3961
+ d(this, "query", (t, n = {}) => {
3962
+ t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t }), this.config.disableValidation || Zt(t, this.config.schema);
3963
+ const s = n.fetchOpts || {}, r = s.headers || {};
3964
+ return A(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
3965
+ ...s,
3966
+ method: "POST",
3967
+ headers: {
3968
+ ...r,
3969
+ ...P(this.config, this.impersonationOpts)
3970
+ },
3971
+ body: JSON.stringify({
3972
+ query: t,
3973
+ "inference?": !!this.config.schema
3974
+ })
3975
+ });
3976
+ });
3977
+ /**
3978
+ * Use this to write data! You can create, update, delete, and link objects
3979
+ *
3980
+ * @see https://sidekickdb.co/docs/instaml
3981
+ *
3982
+ * @example
3983
+ * // Create a new object in the `goals` namespace
3984
+ * const goalId = id();
3985
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
3986
+ *
3987
+ * // Update the title
3988
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
3989
+ *
3990
+ * // Delete it
3991
+ * db.transact(db.tx.goals[goalId].delete())
3992
+ *
3993
+ * // Or create an association:
3994
+ * todoId = id();
3995
+ * db.transact([
3996
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
3997
+ * db.tx.goals[goalId].link({todos: todoId}),
3998
+ * ])
3999
+ */
4000
+ d(this, "transact", (t) => (this.config.disableValidation || ks(t, this.config.schema), A(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
4001
+ method: "POST",
4002
+ headers: P(this.config, this.impersonationOpts),
4003
+ body: JSON.stringify({
4004
+ steps: un(t),
4005
+ "throw-on-missing-attrs?": !!this.config.schema
4006
+ })
4007
+ })));
4008
+ /**
4009
+ * Like `query`, but returns debugging information
4010
+ * for permissions checks along with the result.
4011
+ * Useful for inspecting the values returned by the permissions checks.
4012
+ * Note, this will return debug information for *all* entities
4013
+ * that match the query's `where` clauses.
4014
+ *
4015
+ * Requires a user/guest context to be set with `asUser`,
4016
+ * since permissions checks are user-specific.
4017
+ *
4018
+ * Accepts an optional configuration object with a `rules` key.
4019
+ * The provided rules will override the rules in the database for the query.
4020
+ *
4021
+ * @see https://sidekickdb.co/docs/instaql
4022
+ *
4023
+ * @example
4024
+ * await db.asUser({ guest: true }).debugQuery(
4025
+ * { goals: {} },
4026
+ * { rules: { goals: { allow: { read: "auth.id != null" } } }
4027
+ * )
4028
+ */
4029
+ d(this, "debugQuery", async (t, n) => {
4030
+ t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t });
4031
+ const s = {
4032
+ query: t,
4033
+ "rules-override": n == null ? void 0 : n.rules,
4034
+ "inference?": (n == null ? void 0 : n.cardinalityInference) ?? !!this.config.schema
4035
+ };
4036
+ n != null && n.ip && (s["ip-override"] = n.ip), n != null && n.origin && (s["origin-override"] = n.origin);
4037
+ const r = await A(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
4038
+ method: "POST",
4039
+ headers: P(this.config, this.impersonationOpts),
4040
+ body: JSON.stringify(s)
4041
+ });
4042
+ return {
4043
+ result: r.result,
4044
+ checkResults: r["check-results"]
4045
+ };
4046
+ });
4047
+ /**
4048
+ * Like `transact`, but does not write to the database.
4049
+ * Returns debugging information for permissions checks.
4050
+ * Useful for inspecting the values returned by the permissions checks.
4051
+ *
4052
+ * Requires a user/guest context to be set with `asUser`,
4053
+ * since permissions checks are user-specific.
4054
+ *
4055
+ * Accepts an optional configuration object with a `rules` key.
4056
+ * The provided rules will override the rules in the database for the duration of the transaction.
4057
+ *
4058
+ * @example
4059
+ * const goalId = id();
4060
+ * db.asUser({ guest: true }).debugTransact(
4061
+ * [db.tx.goals[goalId].update({title: "Get fit"})],
4062
+ * { rules: { goals: { allow: { update: "auth.id != null" } } }
4063
+ * )
4064
+ */
4065
+ d(this, "debugTransact", (t, n) => {
4066
+ const s = {
4067
+ steps: un(t),
4068
+ "rules-override": n == null ? void 0 : n.rules,
4069
+ // @ts-expect-error because we're using a private API (for now)
4070
+ "dangerously-commit-tx": n == null ? void 0 : n.__dangerouslyCommit
4071
+ };
4072
+ return n != null && n.ip && (s["ip-override"] = n.ip), n != null && n.origin && (s["origin-override"] = n.origin), A(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
4073
+ method: "POST",
4074
+ headers: P(this.config, this.impersonationOpts),
4075
+ body: JSON.stringify(s)
4076
+ });
4077
+ });
4078
+ k(this, lt, (t) => {
4079
+ var n;
4080
+ if (t.target !== f(this, W)) {
4081
+ f(this, H).info("[socket][open]", t.target.id, "skip; this is no longer the current transport");
4082
+ return;
4083
+ }
4084
+ f(this, H).info("[socket][open]", t.target.id), S(this, Ee, 0), (n = f(this, J)) == null || n.onConnectionStatusChange("authenticated");
4085
+ });
4086
+ k(this, ht, (t) => {
4087
+ var n;
4088
+ if (t.target !== f(this, W)) {
4089
+ f(this, H).info("[socket][close]", t.target.id, "skip; this is no longer the current transport");
4090
+ return;
4091
+ }
4092
+ f(this, H).info("[socket][close]", t.target.id), (n = f(this, J)) == null || n.onConnectionStatusChange("closed"), f(this, W) && (S(this, W, null), O(this, D, Dt).call(this) || (setTimeout(() => O(this, D, rt).call(this), f(this, Ee)), S(this, Ee, Math.min(15e3, Math.max(f(this, Ee), 500) * 2))));
4093
+ });
4094
+ k(this, pt, (t) => {
4095
+ var n;
4096
+ if (t.target !== f(this, W)) {
4097
+ f(this, H).info("[socket][error]", t.target.id, "skip; this is no longer the current transport");
4098
+ return;
4099
+ }
4100
+ f(this, H).info("[socket][error]", t.target.id), (n = f(this, J)) == null || n.onConnectionStatusChange("closed");
4101
+ });
4102
+ k(this, yt, (t) => {
4103
+ var s, r, i, o, a, c;
4104
+ if (t.target !== f(this, W)) {
4105
+ f(this, H).info("[socket][message]", t.target.id, "skip; this is no longer the current transport");
4106
+ return;
4107
+ }
4108
+ const n = t.message;
4109
+ switch (f(this, H).info("[receive]", n), n.op) {
4110
+ case "start-stream-ok": {
4111
+ (s = f(this, J)) == null || s.onStartStreamOk(n);
4112
+ break;
4113
+ }
4114
+ case "stream-flushed": {
4115
+ (r = f(this, J)) == null || r.onStreamFlushed(n);
4116
+ break;
4117
+ }
4118
+ case "append-failed": {
4119
+ (i = f(this, J)) == null || i.onAppendFailed(n);
4120
+ break;
4121
+ }
4122
+ case "stream-append": {
4123
+ (o = f(this, J)) == null || o.onStreamAppend(n);
4124
+ break;
4125
+ }
4126
+ case "error": {
4127
+ switch ((a = n["original-event"]) == null ? void 0 : a.op) {
4128
+ case "start-stream":
4129
+ case "append-stream":
4130
+ case "subscribe-stream":
4131
+ case "unsubscribe-stream": {
4132
+ (c = f(this, J)) == null || c.onRecieveError(n);
4133
+ break;
4134
+ }
4135
+ }
4136
+ break;
4137
+ }
4138
+ }
4139
+ O(this, D, zn).call(this);
4140
+ });
4141
+ this.config = ur(t), this.auth = new gr(this.config), this.storage = new ln(this.config, this.impersonationOpts), this.streams = new Sr(O(this, D, Fn).bind(this)), this.rooms = new br(this.config), this.webhooks = new Ut(this.config, A), S(this, H, Ir(!!this.config.verbose, this.config.logger));
4142
+ }
4143
+ /**
4144
+ * Use this to to get a live view of your data!
4145
+ *
4146
+ * @see https://sidekickdb.co/docs/backend
4147
+ *
4148
+ * @example
4149
+ * // create a subscription to a query
4150
+ * const query = { goals: { $: { where: { title: "Get Fit" } } } }
4151
+ * const sub = db.subscribeQuery(query);
4152
+ *
4153
+ * // iterate through the results with an async iterator
4154
+ * for await (const payload of sub) {
4155
+ * if (payload.error) {
4156
+ * console.log(payload.error);
4157
+ * // Stop the subscription
4158
+ * sub.close();
4159
+ * } else {
4160
+ * console.log(payload.data);
4161
+ * }
4162
+ * }
4163
+ *
4164
+ * // Stop the subscription
4165
+ * sub.close();
4166
+ *
4167
+ * // Create a subscription with a callback
4168
+ * const sub = db.subscribeQuery(query, (payload) => {
4169
+ * if (payload.error) {
4170
+ * console.log(payload.error);
4171
+ * // Stop the subscription
4172
+ * sub.close();
4173
+ * } else {
4174
+ * console.log(payload.data);
4175
+ * }
4176
+ * });
4177
+ */
4178
+ subscribeQuery(t, n, s = {}) {
4179
+ t && s && "ruleParams" in s && (t = { $$ruleParams: s.ruleParams, ...t }), this.config.disableValidation || Zt(t, this.config.schema);
4180
+ const o = {
4181
+ ...(s.fetchOpts || {}).headers || {},
4182
+ ...P(this.config, this.impersonationOpts)
4183
+ }, a = !!this.config.schema;
4184
+ return Fs(t, n, {
4185
+ headers: o,
4186
+ inference: a,
4187
+ apiURI: this.config.apiURI
4188
+ });
4189
+ }
4190
+ };
4191
+ W = new WeakMap(), Ee = new WeakMap(), J = new WeakMap(), H = new WeakMap(), D = new WeakSet(), Dn = function() {
4192
+ f(this, W) && f(this, W).close();
4193
+ const t = {
4194
+ ...P(this.config, this.impersonationOpts)
4195
+ }, n = !!this.config.schema, s = yr({ headers: t, inference: n }), r = new vs(s, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
4196
+ return r.onopen = f(this, lt), r.onmessage = f(this, yt), r.onclose = f(this, ht), r.onerror = f(this, pt), S(this, W, r), r;
4197
+ }, rt = function() {
4198
+ return f(this, W) || O(this, D, Dn).call(this);
4199
+ }, Nn = function(t, n) {
4200
+ const s = O(this, D, rt).call(this);
4201
+ f(this, H).info("[send]", t, n, {
4202
+ isOpen: s.isOpen()
4203
+ }), s.isOpen() && s.send({ "client-event-id": t, ...n });
4204
+ }, Ln = function() {
4205
+ O(this, D, rt).call(this);
4206
+ const t = new xs({
4207
+ WStream: this.config.WritableStream || WritableStream,
4208
+ RStream: this.config.ReadableStream || ReadableStream,
4209
+ trySend: (n, s) => {
4210
+ O(this, D, Nn).call(this, n, s);
4211
+ },
4212
+ log: f(this, H)
4213
+ });
4214
+ return S(this, J, t), t;
4215
+ }, Fn = function() {
4216
+ return f(this, J) || O(this, D, Ln).call(this);
4217
+ }, lt = new WeakMap(), ht = new WeakMap(), pt = new WeakMap(), Dt = function() {
4218
+ return !f(this, J) || !f(this, J).hasActiveStreams();
4219
+ }, zn = function() {
4220
+ if (f(this, W) && O(this, D, Dt).call(this)) {
4221
+ const t = f(this, W);
4222
+ f(this, H).info("cleaning up unused socket", t.id), S(this, W, null), t.close();
4223
+ }
4224
+ }, yt = new WeakMap();
4225
+ let Mt = Vt;
4226
+ var hn = {};
4227
+ function Ze(e) {
4228
+ let t = e;
4229
+ return new TransformStream({
4230
+ transform(n, s) {
4231
+ if (!t) {
4232
+ s.enqueue(n);
4233
+ return;
4234
+ }
4235
+ if (t > n.length) {
4236
+ t -= n.length;
4237
+ return;
4238
+ }
4239
+ const r = n.slice(t);
4240
+ t = 0, s.enqueue(r);
4241
+ }
4242
+ });
4243
+ }
4244
+ function et(e) {
4245
+ return [
4246
+ hn[e],
4247
+ hn[e.replace("SIDEKICK_", "INSTANT_")]
4248
+ ].find((t) => t == null ? void 0 : t.trim());
4249
+ }
4250
+ function vr(e) {
4251
+ const t = e.appId || et("SIDEKICK_APP_ID") || et("NEXT_PUBLIC_SIDEKICK_APP_ID");
4252
+ if (!t)
4253
+ throw new Error(
4254
+ "Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable."
4255
+ );
4256
+ const n = e.adminToken || et("SIDEKICK_APP_ADMIN_TOKEN");
4257
+ if (!n)
4258
+ throw new Error(
4259
+ "Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable."
4260
+ );
4261
+ const s = Wt(e.apiURI || et("SIDEKICK_API_URI"), {
4262
+ target: "createResumableStreamContext()",
4263
+ envVar: "SIDEKICK_API_URI"
4264
+ }), r = { appId: t, adminToken: n, apiURI: s };
4265
+ e.verbose && (r.verbose = e.verbose);
4266
+ const i = mr(r);
4267
+ async function o(h, l, y) {
4268
+ const m = i.streams.createWriteStream({
4269
+ clientId: h,
4270
+ waitUntil: e.waitUntil ?? void 0
4271
+ });
4272
+ try {
4273
+ const g = await m.streamId();
4274
+ l().pipeTo(m);
4275
+ const p = i.streams.createReadStream({ streamId: g });
4276
+ return y ? p.pipeThrough(
4277
+ Ze(y)
4278
+ ) : p;
4279
+ } catch {
4280
+ const w = i.streams.createReadStream({ clientId: h });
4281
+ return y ? w.pipeThrough(
4282
+ Ze(y)
4283
+ ) : w;
4284
+ }
4285
+ }
4286
+ async function a(h, l) {
4287
+ var m, g, w;
4288
+ const y = i.streams.createReadStream({ clientId: h });
4289
+ try {
4290
+ await y.streamId();
4291
+ } catch (p) {
4292
+ if (p instanceof x && ((w = (g = (m = p.hint) == null ? void 0 : m.errors) == null ? void 0 : g[0]) == null ? void 0 : w.message) === "Stream is missing.")
4293
+ return;
4294
+ throw p;
4295
+ }
4296
+ return l ? y.pipeThrough(Ze(l)) : y;
4297
+ }
4298
+ async function c(h, l, y) {
4299
+ const m = l(), g = i.streams.createWriteStream({
4300
+ clientId: h,
4301
+ waitUntil: e.waitUntil ?? void 0
4302
+ });
4303
+ await g.streamId(), m.pipeTo(g);
4304
+ const w = i.streams.createReadStream({ clientId: h });
4305
+ return y ? w.pipeThrough(Ze(y)) : w;
4306
+ }
4307
+ async function u(h) {
4308
+ var m;
4309
+ const l = await i.query({
4310
+ $streams: { $: { where: { clientId: h } } }
4311
+ }), y = (m = l == null ? void 0 : l.$streams) == null ? void 0 : m[0];
4312
+ return y != null && y.done ? "DONE" : y ? !0 : null;
4313
+ }
4314
+ return {
4315
+ resumableStream: o,
4316
+ resumeExistingStream: a,
4317
+ createNewResumableStream: c,
4318
+ hasExistingStream: u
4319
+ };
4320
+ }
4321
+ export {
4322
+ vr as createResumableStreamContext
4323
+ };