@instantdb/resumable-stream 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3402 @@
1
+ var En = Object.defineProperty;
2
+ var Pt = (e) => {
3
+ throw TypeError(e);
4
+ };
5
+ var _n = (e, t, n) => t in e ? En(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
6
+ var d = (e, t, n) => _n(e, typeof t != "symbol" ? t + "" : t, n), st = (e, t, n) => t.has(e) || Pt("Cannot " + n);
7
+ var b = (e, t, n) => (st(e, t, "read from private field"), n ? n.call(e) : t.get(e)), G = (e, t, n) => t.has(e) ? Pt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), oe = (e, t, n, i) => (st(e, t, "write to private field"), i ? i.call(e, n) : t.set(e, n), n), H = (e, t, n) => (st(e, t, "access private method"), n);
8
+ const Cn = /^(?:[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 Te(e) {
10
+ return typeof e == "string" && Cn.test(e);
11
+ }
12
+ const M = [];
13
+ for (let e = 0; e < 256; ++e)
14
+ M.push((e + 256).toString(16).slice(1));
15
+ function xn(e, t = 0) {
16
+ return (M[e[t + 0]] + M[e[t + 1]] + M[e[t + 2]] + M[e[t + 3]] + "-" + M[e[t + 4]] + M[e[t + 5]] + "-" + M[e[t + 6]] + M[e[t + 7]] + "-" + M[e[t + 8]] + M[e[t + 9]] + "-" + M[e[t + 10]] + M[e[t + 11]] + M[e[t + 12]] + M[e[t + 13]] + M[e[t + 14]] + M[e[t + 15]]).toLowerCase();
17
+ }
18
+ let rt;
19
+ const Tn = new Uint8Array(16);
20
+ function Rn() {
21
+ if (!rt) {
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
+ rt = crypto.getRandomValues.bind(crypto);
25
+ }
26
+ return rt(Tn);
27
+ }
28
+ const An = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), jt = { randomUUID: An };
29
+ function Pn(e, t, n) {
30
+ var s;
31
+ if (jt.randomUUID && !e)
32
+ return jt.randomUUID();
33
+ e = e || {};
34
+ const i = e.random ?? ((s = e.rng) == null ? void 0 : s.call(e)) ?? Rn();
35
+ if (i.length < 16)
36
+ throw new Error("Random bytes length must be >= 16");
37
+ return i[6] = i[6] & 15 | 64, i[8] = i[8] & 63 | 128, xn(i);
38
+ }
39
+ const T = {
40
+ Remove: "remove",
41
+ Replace: "replace",
42
+ Add: "add"
43
+ }, Xt = Symbol.for("__MUTATIVE_PROXY_DRAFT__"), Je = Symbol.iterator, Z = {
44
+ mutable: "mutable",
45
+ immutable: "immutable"
46
+ }, _t = {};
47
+ function Ne(e, t) {
48
+ return e instanceof Map ? e.has(t) : Object.prototype.hasOwnProperty.call(e, t);
49
+ }
50
+ function Mt(e, t) {
51
+ if (t in e) {
52
+ let n = Reflect.getPrototypeOf(e);
53
+ for (; n; ) {
54
+ const i = Reflect.getOwnPropertyDescriptor(n, t);
55
+ if (i)
56
+ return i;
57
+ n = Reflect.getPrototypeOf(n);
58
+ }
59
+ }
60
+ }
61
+ function Yt(e) {
62
+ return Object.getPrototypeOf(e) === Set.prototype;
63
+ }
64
+ function Zt(e) {
65
+ return Object.getPrototypeOf(e) === Map.prototype;
66
+ }
67
+ function Q(e) {
68
+ var t;
69
+ return (t = e.copy) !== null && t !== void 0 ? t : e.original;
70
+ }
71
+ function lt(e) {
72
+ return !!k(e);
73
+ }
74
+ function k(e) {
75
+ return typeof e != "object" ? null : e == null ? void 0 : e[Xt];
76
+ }
77
+ function Ct(e) {
78
+ var t;
79
+ const n = k(e);
80
+ return n ? (t = n.copy) !== null && t !== void 0 ? t : n.original : e;
81
+ }
82
+ function Ie(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, Z)) === Z.immutable || typeof n == "function");
87
+ }
88
+ function en(e, t = []) {
89
+ if (Object.hasOwnProperty.call(e, "key")) {
90
+ const n = e.parent.copy, i = k(he(n, e.key));
91
+ if (i !== null && (i == null ? void 0 : i.original) !== e.original)
92
+ return null;
93
+ const s = e.parent.type === 3, r = s ? Array.from(e.parent.setMap.keys()).indexOf(e.key) : e.key;
94
+ if (!(s && n.size > r || Ne(n, r)))
95
+ return null;
96
+ t.push(r);
97
+ }
98
+ if (e.parent)
99
+ return en(e.parent, t);
100
+ t.reverse();
101
+ try {
102
+ jn(e.copy, t);
103
+ } catch {
104
+ return null;
105
+ }
106
+ return t;
107
+ }
108
+ function ze(e) {
109
+ return Array.isArray(e) ? 1 : e instanceof Map ? 2 : e instanceof Set ? 3 : 0;
110
+ }
111
+ function he(e, t) {
112
+ return ze(e) === 2 ? e.get(t) : e[t];
113
+ }
114
+ function xt(e, t, n) {
115
+ ze(e) === 2 ? e.set(t, n) : e[t] = n;
116
+ }
117
+ function ot(e, t) {
118
+ const n = k(e);
119
+ return (n ? Q(n) : e)[t];
120
+ }
121
+ function we(e, t) {
122
+ return e === t ? e !== 0 || 1 / e === 1 / t : e !== e && t !== t;
123
+ }
124
+ function be(e, t) {
125
+ return t ? e : [""].concat(e).map((n) => {
126
+ const i = `${n}`;
127
+ return i.indexOf("/") === -1 && i.indexOf("~") === -1 ? i : i.replace(/~/g, "~0").replace(/\//g, "~1");
128
+ }).join("/");
129
+ }
130
+ function jn(e, t) {
131
+ for (let n = 0; n < t.length - 1; n += 1) {
132
+ const i = t[n];
133
+ if (e = he(ze(e) === 3 ? Array.from(e) : e, i), typeof e != "object")
134
+ throw new Error(`Cannot resolve patch at '${t.join("/")}'.`);
135
+ }
136
+ return e;
137
+ }
138
+ function Mn(e) {
139
+ const t = Object.create(Object.getPrototypeOf(e));
140
+ return Reflect.ownKeys(e).forEach((n) => {
141
+ let i = Reflect.getOwnPropertyDescriptor(e, n);
142
+ if (i.enumerable && i.configurable && i.writable) {
143
+ t[n] = e[n];
144
+ return;
145
+ }
146
+ i.writable || (i.writable = !0, i.configurable = !0), (i.get || i.set) && (i = {
147
+ configurable: !0,
148
+ writable: !0,
149
+ enumerable: i.enumerable,
150
+ value: e[n]
151
+ }), Reflect.defineProperty(t, n, i);
152
+ }), t;
153
+ }
154
+ const Un = Object.prototype.propertyIsEnumerable;
155
+ function Dn(e, t) {
156
+ let n;
157
+ if (Array.isArray(e))
158
+ return Array.prototype.concat.call(e);
159
+ if (e instanceof Set) {
160
+ if (!Yt(e)) {
161
+ const i = Object.getPrototypeOf(e).constructor;
162
+ return new i(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 (!Zt(e)) {
167
+ const i = Object.getPrototypeOf(e).constructor;
168
+ return new i(e);
169
+ }
170
+ return new Map(e);
171
+ } else if (t != null && t.mark && (n = t.mark(e, Z), n !== void 0) && n !== Z.mutable) {
172
+ if (n === Z.immutable)
173
+ return Mn(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 i = {};
182
+ return Object.keys(e).forEach((s) => {
183
+ i[s] = e[s];
184
+ }), Object.getOwnPropertySymbols(e).forEach((s) => {
185
+ Un.call(e, s) && (i[s] = e[s]);
186
+ }), i;
187
+ } else
188
+ throw new Error("Please check mark() to ensure that it is a stable marker draftable function.");
189
+ }
190
+ function W(e) {
191
+ e.copy || (e.copy = Dn(e.original, e.options));
192
+ }
193
+ function Me(e) {
194
+ if (!Ie(e))
195
+ return Ct(e);
196
+ if (Array.isArray(e))
197
+ return e.map(Me);
198
+ if (e instanceof Map) {
199
+ const n = Array.from(e.entries()).map(([i, s]) => [
200
+ i,
201
+ Me(s)
202
+ ]);
203
+ if (!Zt(e)) {
204
+ const i = Object.getPrototypeOf(e).constructor;
205
+ return new i(n);
206
+ }
207
+ return new Map(n);
208
+ }
209
+ if (e instanceof Set) {
210
+ const n = Array.from(e).map(Me);
211
+ if (!Yt(e)) {
212
+ const i = Object.getPrototypeOf(e).constructor;
213
+ return new i(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] = Me(e[n]);
220
+ return t;
221
+ }
222
+ function Qe(e) {
223
+ return lt(e) ? Me(e) : e;
224
+ }
225
+ function te(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 && te(e.parent));
228
+ }
229
+ function Nn(e, t) {
230
+ const n = ze(e);
231
+ if (n === 0)
232
+ Reflect.ownKeys(e).forEach((i) => {
233
+ t(i, e[i], e);
234
+ });
235
+ else if (n === 1) {
236
+ let i = 0;
237
+ for (const s of e)
238
+ t(i, s, e), i += 1;
239
+ } else
240
+ e.forEach((i, s) => t(s, i, e));
241
+ }
242
+ function tn(e, t, n) {
243
+ if (lt(e) || !Ie(e, n) || t.has(e) || Object.isFrozen(e))
244
+ return;
245
+ const i = e instanceof Set, s = i ? /* @__PURE__ */ new Map() : void 0;
246
+ if (t.add(e), Nn(e, (r, o) => {
247
+ var a;
248
+ if (lt(o)) {
249
+ const u = k(o);
250
+ W(u);
251
+ const c = !((a = u.assignedMap) === null || a === void 0) && a.size || u.operated ? u.copy : u.original;
252
+ xt(i ? s : e, r, c);
253
+ } else
254
+ tn(o, t, n);
255
+ }), s) {
256
+ const r = e, o = Array.from(r);
257
+ r.clear(), o.forEach((a) => {
258
+ r.add(s.has(a) ? s.get(a) : a);
259
+ });
260
+ }
261
+ }
262
+ function Ln(e, t) {
263
+ const n = e.type === 3 ? e.setMap : e.copy;
264
+ e.finalities.revoke.length > 1 && e.assignedMap.get(t) && n && tn(he(n, t), e.finalities.handledSet, e.options);
265
+ }
266
+ function dt(e) {
267
+ e.type === 3 && e.copy && (e.copy.clear(), e.setMap.forEach((t) => {
268
+ e.copy.add(Ct(t));
269
+ }));
270
+ }
271
+ function ht(e, t, n, i) {
272
+ if (e.operated && e.assignedMap && e.assignedMap.size > 0 && !e.finalized) {
273
+ if (n && i) {
274
+ const r = en(e);
275
+ r && t(e, r, n, i);
276
+ }
277
+ e.finalized = !0;
278
+ }
279
+ }
280
+ function Tt(e, t, n, i) {
281
+ const s = k(n);
282
+ s && (s.callbacks || (s.callbacks = []), s.callbacks.push((r, o) => {
283
+ var a;
284
+ const u = e.type === 3 ? e.setMap : e.copy;
285
+ if (we(he(u, t), n)) {
286
+ let c = s.original;
287
+ s.copy && (c = s.copy), dt(e), ht(e, i, r, o), e.options.enableAutoFreeze && (e.options.updatedValues = (a = e.options.updatedValues) !== null && a !== void 0 ? a : /* @__PURE__ */ new WeakMap(), e.options.updatedValues.set(c, s.original)), xt(u, t, c);
288
+ }
289
+ }), e.options.enableAutoFreeze && s.finalities !== e.finalities && (e.options.enableAutoFreeze = !1)), Ie(n, e.options) && e.finalities.draft.push(() => {
290
+ const r = e.type === 3 ? e.setMap : e.copy;
291
+ we(he(r, t), n) && Ln(e, t);
292
+ });
293
+ }
294
+ function Wn(e, t, n, i, s) {
295
+ let { original: r, assignedMap: o, options: a } = e, u = e.copy;
296
+ u.length < r.length && ([r, u] = [u, r], [n, i] = [i, n]);
297
+ for (let c = 0; c < r.length; c += 1)
298
+ if (o.get(c.toString()) && u[c] !== r[c]) {
299
+ const l = t.concat([c]), f = be(l, s);
300
+ n.push({
301
+ op: T.Replace,
302
+ path: f,
303
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
304
+ value: Qe(u[c])
305
+ }), i.push({
306
+ op: T.Replace,
307
+ path: f,
308
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
309
+ value: Qe(r[c])
310
+ });
311
+ }
312
+ for (let c = r.length; c < u.length; c += 1) {
313
+ const l = t.concat([c]), f = be(l, s);
314
+ n.push({
315
+ op: T.Add,
316
+ path: f,
317
+ // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
318
+ value: Qe(u[c])
319
+ });
320
+ }
321
+ if (r.length < u.length) {
322
+ const { arrayLengthAssignment: c = !0 } = a.enablePatches;
323
+ if (c) {
324
+ const l = t.concat(["length"]), f = be(l, s);
325
+ i.push({
326
+ op: T.Replace,
327
+ path: f,
328
+ value: r.length
329
+ });
330
+ } else
331
+ for (let l = u.length; r.length < l; l -= 1) {
332
+ const f = t.concat([l - 1]), m = be(f, s);
333
+ i.push({
334
+ op: T.Remove,
335
+ path: m
336
+ });
337
+ }
338
+ }
339
+ }
340
+ function Fn({ original: e, copy: t, assignedMap: n }, i, s, r, o) {
341
+ n.forEach((a, u) => {
342
+ const c = he(e, u), l = Qe(he(t, u)), f = a ? Ne(e, u) ? T.Replace : T.Add : T.Remove;
343
+ if (we(c, l) && f === T.Replace)
344
+ return;
345
+ const m = i.concat(u), p = be(m, o);
346
+ s.push(f === T.Remove ? { op: f, path: p } : { op: f, path: p, value: l }), r.push(f === T.Add ? { op: T.Remove, path: p } : f === T.Remove ? { op: T.Add, path: p, value: c } : { op: T.Replace, path: p, value: c });
347
+ });
348
+ }
349
+ function zn({ original: e, copy: t }, n, i, s, r) {
350
+ let o = 0;
351
+ e.forEach((a) => {
352
+ if (!t.has(a)) {
353
+ const u = n.concat([o]), c = be(u, r);
354
+ i.push({
355
+ op: T.Remove,
356
+ path: c,
357
+ value: a
358
+ }), s.unshift({
359
+ op: T.Add,
360
+ path: c,
361
+ value: a
362
+ });
363
+ }
364
+ o += 1;
365
+ }), o = 0, t.forEach((a) => {
366
+ if (!e.has(a)) {
367
+ const u = n.concat([o]), c = be(u, r);
368
+ i.push({
369
+ op: T.Add,
370
+ path: c,
371
+ value: a
372
+ }), s.unshift({
373
+ op: T.Remove,
374
+ path: c,
375
+ value: a
376
+ });
377
+ }
378
+ o += 1;
379
+ });
380
+ }
381
+ function Fe(e, t, n, i) {
382
+ const { pathAsArray: s = !0 } = e.options.enablePatches;
383
+ switch (e.type) {
384
+ case 0:
385
+ case 2:
386
+ return Fn(e, t, n, i, s);
387
+ case 1:
388
+ return Wn(e, t, n, i, s);
389
+ case 3:
390
+ return zn(e, t, n, i, s);
391
+ }
392
+ }
393
+ const qe = (e, t, n = !1) => {
394
+ if (typeof e == "object" && e !== null && (!Ie(e, t) || n))
395
+ throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.");
396
+ }, pt = {
397
+ get size() {
398
+ return Q(k(this)).size;
399
+ },
400
+ has(e) {
401
+ return Q(k(this)).has(e);
402
+ },
403
+ set(e, t) {
404
+ const n = k(this), i = Q(n);
405
+ return (!i.has(e) || !we(i.get(e), t)) && (W(n), te(n), n.assignedMap.set(e, !0), n.copy.set(e, t), Tt(n, e, t, Fe)), this;
406
+ },
407
+ delete(e) {
408
+ if (!this.has(e))
409
+ return !1;
410
+ const t = k(this);
411
+ return W(t), te(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 = k(this);
415
+ if (this.size) {
416
+ W(e), te(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 = k(this);
424
+ Q(n).forEach((i, s) => {
425
+ e.call(t, this.get(s), s, this);
426
+ });
427
+ },
428
+ get(e) {
429
+ var t, n;
430
+ const i = k(this), s = Q(i).get(e), r = ((n = (t = i.options).mark) === null || n === void 0 ? void 0 : n.call(t, s, Z)) === Z.mutable;
431
+ if (i.options.strict && qe(s, i.options, r), r || i.finalized || !Ie(s, i.options) || s !== i.original.get(e))
432
+ return s;
433
+ const o = _t.createDraft({
434
+ original: s,
435
+ parentDraft: i,
436
+ key: e,
437
+ finalities: i.finalities,
438
+ options: i.options
439
+ });
440
+ return W(i), i.copy.set(e, o), o;
441
+ },
442
+ keys() {
443
+ return Q(k(this)).keys();
444
+ },
445
+ values() {
446
+ const e = this.keys();
447
+ return {
448
+ [Je]: () => 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
+ [Je]: () => 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
+ [Je]() {
475
+ return this.entries();
476
+ }
477
+ }, Vn = Reflect.ownKeys(pt), Ut = (e, t, { isValuesIterator: n }) => () => {
478
+ var i, s;
479
+ const r = t.next();
480
+ if (r.done)
481
+ return r;
482
+ const o = r.value;
483
+ let a = e.setMap.get(o);
484
+ const u = k(a), c = ((s = (i = e.options).mark) === null || s === void 0 ? void 0 : s.call(i, a, Z)) === Z.mutable;
485
+ if (e.options.strict && qe(o, e.options, c), !c && !u && Ie(o, e.options) && !e.finalized && e.original.has(o)) {
486
+ const l = _t.createDraft({
487
+ original: o,
488
+ parentDraft: e,
489
+ key: o,
490
+ finalities: e.finalities,
491
+ options: e.options
492
+ });
493
+ e.setMap.set(o, l), a = l;
494
+ } else u && (a = u.proxy);
495
+ return {
496
+ done: !1,
497
+ value: n ? a : [a, a]
498
+ };
499
+ }, Ke = {
500
+ get size() {
501
+ return k(this).setMap.size;
502
+ },
503
+ has(e) {
504
+ const t = k(this);
505
+ if (t.setMap.has(e))
506
+ return !0;
507
+ W(t);
508
+ const n = k(e);
509
+ return !!(n && t.setMap.has(n.original));
510
+ },
511
+ add(e) {
512
+ const t = k(this);
513
+ return this.has(e) || (W(t), te(t), t.assignedMap.set(e, !0), t.setMap.set(e, e), Tt(t, e, e, Fe)), this;
514
+ },
515
+ delete(e) {
516
+ if (!this.has(e))
517
+ return !1;
518
+ const t = k(this);
519
+ W(t), te(t);
520
+ const n = k(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 = k(this);
527
+ W(e), te(e);
528
+ for (const t of e.original)
529
+ e.assignedMap.set(t, !1);
530
+ e.setMap.clear();
531
+ },
532
+ values() {
533
+ const e = k(this);
534
+ W(e);
535
+ const t = e.setMap.keys();
536
+ return {
537
+ [Symbol.iterator]: () => this.values(),
538
+ next: Ut(e, t, { isValuesIterator: !0 })
539
+ };
540
+ },
541
+ entries() {
542
+ const e = k(this);
543
+ W(e);
544
+ const t = e.setMap.keys();
545
+ return {
546
+ [Symbol.iterator]: () => this.entries(),
547
+ next: Ut(e, t, {
548
+ isValuesIterator: !1
549
+ })
550
+ };
551
+ },
552
+ keys() {
553
+ return this.values();
554
+ },
555
+ [Je]() {
556
+ return this.values();
557
+ },
558
+ forEach(e, t) {
559
+ const n = this.values();
560
+ let i = n.next();
561
+ for (; !i.done; )
562
+ e.call(t, i.value, i.value, this), i = n.next();
563
+ }
564
+ };
565
+ Set.prototype.difference && Object.assign(Ke, {
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 Jn = Reflect.ownKeys(Ke), nn = /* @__PURE__ */ new WeakSet(), sn = {
589
+ get(e, t, n) {
590
+ var i, s;
591
+ const r = (i = e.copy) === null || i === void 0 ? void 0 : i[t];
592
+ if (r && nn.has(r))
593
+ return r;
594
+ if (t === Xt)
595
+ return e;
596
+ let o;
597
+ if (e.options.mark) {
598
+ const c = 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(c, Z), o === Z.mutable)
600
+ return e.options.strict && qe(c, e.options, !0), c;
601
+ }
602
+ const a = Q(e);
603
+ if (a instanceof Map && Vn.includes(t)) {
604
+ if (t === "size")
605
+ return Object.getOwnPropertyDescriptor(pt, "size").get.call(e.proxy);
606
+ const c = pt[t];
607
+ if (c)
608
+ return c.bind(e.proxy);
609
+ }
610
+ if (a instanceof Set && Jn.includes(t)) {
611
+ if (t === "size")
612
+ return Object.getOwnPropertyDescriptor(Ke, "size").get.call(e.proxy);
613
+ const c = Ke[t];
614
+ if (c)
615
+ return c.bind(e.proxy);
616
+ }
617
+ if (!Ne(a, t)) {
618
+ const c = Mt(a, t);
619
+ return c ? "value" in c ? c.value : (
620
+ // !case: support for getter
621
+ (s = c.get) === null || s === void 0 ? void 0 : s.call(e.proxy)
622
+ ) : void 0;
623
+ }
624
+ const u = a[t];
625
+ if (e.options.strict && qe(u, e.options), e.finalized || !Ie(u, e.options))
626
+ return u;
627
+ if (u === ot(e.original, t)) {
628
+ if (W(e), e.copy[t] = rn({
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 c = k(e.copy[t]);
636
+ return W(c), te(c), c.copy;
637
+ }
638
+ return e.copy[t];
639
+ }
640
+ return u;
641
+ },
642
+ set(e, t, n) {
643
+ var i;
644
+ if (e.type === 3 || e.type === 2)
645
+ throw new Error("Map/Set draft does not support any property assignment.");
646
+ let s;
647
+ if (e.type === 1 && t !== "length" && !(Number.isInteger(s = Number(t)) && s >= 0 && (t === 0 || s === 0 || String(s) === String(t))))
648
+ throw new Error("Only supports setting array indices and the 'length' property.");
649
+ const r = Mt(Q(e), t);
650
+ if (r != null && r.set)
651
+ return r.set.call(e.proxy, n), !0;
652
+ const o = ot(Q(e), t), a = k(o);
653
+ return a && we(a.original, n) ? (e.copy[t] = n, e.assignedMap = (i = e.assignedMap) !== null && i !== void 0 ? i : /* @__PURE__ */ new Map(), e.assignedMap.set(t, !1), !0) : (we(n, o) && (n !== void 0 || Ne(e.original, t)) || (W(e), te(e), Ne(e.original, t) && we(n, e.original[t]) ? e.assignedMap.delete(t) : e.assignedMap.set(t, !0), e.copy[t] = n, Tt(e, t, n, Fe)), !0);
654
+ },
655
+ has(e, t) {
656
+ return t in Q(e);
657
+ },
658
+ ownKeys(e) {
659
+ return Reflect.ownKeys(Q(e));
660
+ },
661
+ getOwnPropertyDescriptor(e, t) {
662
+ const n = Q(e), i = Reflect.getOwnPropertyDescriptor(n, t);
663
+ return i && {
664
+ writable: !0,
665
+ configurable: e.type !== 1 || t !== "length",
666
+ enumerable: i.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) : (ot(e.original, t) !== void 0 || t in e.original ? (W(e), te(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 rn(e) {
685
+ const { original: t, parentDraft: n, key: i, finalities: s, options: r } = e, o = ze(t), a = {
686
+ type: o,
687
+ finalized: !1,
688
+ parent: n,
689
+ original: t,
690
+ copy: null,
691
+ proxy: null,
692
+ finalities: s,
693
+ options: r,
694
+ // Mapping of draft Set items to their corresponding draft values.
695
+ setMap: o === 3 ? new Map(t.entries()) : void 0
696
+ };
697
+ (i || "key" in e) && (a.key = i);
698
+ const { proxy: u, revoke: c } = Proxy.revocable(o === 1 ? Object.assign([], a) : a, sn);
699
+ if (s.revoke.push(c), nn.add(u), a.proxy = u, n) {
700
+ const l = n;
701
+ l.finalities.draft.push((f, m) => {
702
+ var p, I;
703
+ const g = k(u);
704
+ let h = l.type === 3 ? l.setMap : l.copy;
705
+ const $ = he(h, i), w = k($);
706
+ if (w) {
707
+ let O = w.original;
708
+ w.operated && (O = Ct($)), dt(w), ht(w, Fe, f, m), l.options.enableAutoFreeze && (l.options.updatedValues = (p = l.options.updatedValues) !== null && p !== void 0 ? p : /* @__PURE__ */ new WeakMap(), l.options.updatedValues.set(O, w.original)), xt(h, i, O);
709
+ }
710
+ (I = g.callbacks) === null || I === void 0 || I.forEach((O) => {
711
+ O(f, m);
712
+ });
713
+ });
714
+ } else {
715
+ const l = k(u);
716
+ l.finalities.draft.push((f, m) => {
717
+ dt(l), ht(l, Fe, f, m);
718
+ });
719
+ }
720
+ return u;
721
+ }
722
+ _t.createDraft = rn;
723
+ Object.prototype.constructor.toString();
724
+ function Ee() {
725
+ return Pn();
726
+ }
727
+ function Qn(e, t) {
728
+ return e.localeCompare(t);
729
+ }
730
+ function Gn() {
731
+ let e = Qn;
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
+ Gn();
740
+ function Hn() {
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 Bn = Hn();
755
+ function Ge(e, t, n) {
756
+ const i = {
757
+ __etype: e,
758
+ __ops: n
759
+ };
760
+ return new Proxy(i, {
761
+ get: (s, r) => {
762
+ if (r === "__ops")
763
+ return n;
764
+ if (r === "__etype")
765
+ return e;
766
+ if (Bn.has(r))
767
+ return (o, a) => Ge(e, t, [
768
+ ...n,
769
+ a ? [r, e, t, o, a] : [r, e, t, o]
770
+ ]);
771
+ }
772
+ });
773
+ }
774
+ function qn(e, t) {
775
+ return `lookup__${e}__${JSON.stringify(t)}`;
776
+ }
777
+ function on(e) {
778
+ return e.startsWith("lookup__");
779
+ }
780
+ function Dt(e) {
781
+ const [t, n, ...i] = e.split("__");
782
+ return [n, JSON.parse(i.join("__"))];
783
+ }
784
+ function Kn(e) {
785
+ return new Proxy({
786
+ __etype: e
787
+ }, {
788
+ get(t, n) {
789
+ if (n === "lookup")
790
+ return (s, r) => Ge(e, Dt(qn(s, r)), []);
791
+ if (n === "__etype")
792
+ return e;
793
+ const i = n;
794
+ return on(i) ? Ge(e, Dt(i), []) : Ge(e, i, []);
795
+ }
796
+ });
797
+ }
798
+ function an() {
799
+ return new Proxy({}, {
800
+ get(e, t) {
801
+ return Kn(t);
802
+ }
803
+ });
804
+ }
805
+ an();
806
+ function Xn(e) {
807
+ return e.__ops;
808
+ }
809
+ class B extends Error {
810
+ constructor(n, i) {
811
+ super(n);
812
+ d(this, "hint");
813
+ this.hint = i;
814
+ const s = new.target.prototype;
815
+ Object.setPrototypeOf && Object.setPrototypeOf(this, s), Error.captureStackTrace && Error.captureStackTrace(this, B), this.name = "InstantError";
816
+ }
817
+ get [Symbol.toStringTag]() {
818
+ return "InstantError";
819
+ }
820
+ }
821
+ class Se extends B {
822
+ constructor(n) {
823
+ var r;
824
+ const i = ((r = n.body) == null ? void 0 : r.message) || `API Error (${n.status})`;
825
+ super(i, n.body.hint);
826
+ d(this, "body");
827
+ d(this, "status");
828
+ const s = new.target.prototype;
829
+ Object.setPrototypeOf && Object.setPrototypeOf(this, s), Error.captureStackTrace && Error.captureStackTrace(this, Se), this.name = "InstantAPIError", this.status = n.status, this.body = n.body;
830
+ }
831
+ get [Symbol.toStringTag]() {
832
+ return "InstantAPIError";
833
+ }
834
+ }
835
+ typeof window < "u" && typeof window.localStorage < "u" && (window.localStorage.getItem("devBackend"), window.localStorage.getItem("__instantLogging"), window.localStorage.getItem("__devtoolLocalDash"));
836
+ const Re = "v0.22.145";
837
+ class ce {
838
+ constructor(t, n, i, s = { indexed: !1, unique: !1 }) {
839
+ d(this, "valueType");
840
+ d(this, "required");
841
+ d(this, "isIndexed");
842
+ d(this, "config");
843
+ d(this, "metadata", {});
844
+ this.valueType = t, this.required = n, this.isIndexed = i, this.config = s;
845
+ }
846
+ /**
847
+ * @deprecated Only use this temporarily for attributes that you want
848
+ * to treat as required in frontend code but can’t yet mark as required
849
+ * and enforced for backend
850
+ */
851
+ clientRequired() {
852
+ return new ce(this.valueType, !1, this.isIndexed, this.config);
853
+ }
854
+ optional() {
855
+ return new ce(this.valueType, !1, this.isIndexed, this.config);
856
+ }
857
+ unique() {
858
+ return new ce(this.valueType, this.required, this.isIndexed, {
859
+ ...this.config,
860
+ unique: !0
861
+ });
862
+ }
863
+ indexed() {
864
+ return new ce(this.valueType, this.required, !0, {
865
+ ...this.config,
866
+ indexed: !0
867
+ });
868
+ }
869
+ }
870
+ class E extends Error {
871
+ constructor(t, n) {
872
+ const i = n ? `At path '${n}': ${t}` : t;
873
+ super(i), this.name = "QueryValidationError";
874
+ }
875
+ }
876
+ const Nt = [
877
+ "where",
878
+ "order",
879
+ "limit",
880
+ "last",
881
+ "first",
882
+ "offset",
883
+ "after",
884
+ "before",
885
+ "fields",
886
+ "aggregate"
887
+ ], Yn = (e) => e.valueType || "unknown", cn = (e, t, n = !1) => {
888
+ if (n || e == null)
889
+ return !0;
890
+ switch (t) {
891
+ case "string":
892
+ return typeof e == "string";
893
+ case "number":
894
+ return typeof e == "number" && !isNaN(e);
895
+ case "boolean":
896
+ return typeof e == "boolean";
897
+ case "date":
898
+ return e instanceof Date || typeof e == "string" || typeof e == "number";
899
+ default:
900
+ return !0;
901
+ }
902
+ }, Zn = (e, t, n, i, s, r, o) => {
903
+ const a = r.valueType === "json", u = (c, l, f) => {
904
+ if (!cn(f, l, a))
905
+ throw new E(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${l}, but received: ${typeof f}`, o);
906
+ };
907
+ switch (e) {
908
+ case "in":
909
+ case "$in":
910
+ if (!Array.isArray(t))
911
+ throw new E(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`, o);
912
+ for (const c of t)
913
+ u(e, n, c);
914
+ break;
915
+ case "$not":
916
+ case "$ne":
917
+ case "$gt":
918
+ case "$lt":
919
+ case "$gte":
920
+ case "$lte":
921
+ u(e, n, t);
922
+ break;
923
+ case "$like":
924
+ case "$ilike":
925
+ if (u(e, "string", t), e === "$ilike" && !r.isIndexed)
926
+ throw new E(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`, o);
927
+ break;
928
+ case "$isNull":
929
+ u(e, "boolean", t);
930
+ break;
931
+ default:
932
+ throw new E(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`, o);
933
+ }
934
+ }, _e = (e, t, n, i, s) => {
935
+ const r = Yn(n), o = n.valueType === "json";
936
+ if (typeof e == "object" && e !== null && !Array.isArray(e)) {
937
+ if (o)
938
+ return;
939
+ const u = e;
940
+ for (const [c, l] of Object.entries(u))
941
+ Zn(c, l, r, t, i, n, `${s}.${c}`);
942
+ } else if (!cn(e, r, o))
943
+ throw new E(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`, s);
944
+ }, ei = (e, t, n, i, s) => {
945
+ const r = e.split(".");
946
+ if (r.length < 2)
947
+ throw new E(`Invalid dot notation path '${e}'. Must contain at least one dot.`, s);
948
+ let o = n;
949
+ for (let l = 0; l < r.length - 1; l++) {
950
+ const f = r[l], m = i.entities[o];
951
+ if (!m)
952
+ throw new E(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`, s);
953
+ const p = m.links[f];
954
+ if (!p) {
955
+ const I = Object.keys(m.links);
956
+ throw new E(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length > 0 ? I.join(", ") : "none"}`, s);
957
+ }
958
+ o = p.entityName;
959
+ }
960
+ const a = r[r.length - 1], u = i.entities[o];
961
+ if (!u)
962
+ throw new E(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`, s);
963
+ if (a === "id") {
964
+ if (typeof t == "string" && !Te(t))
965
+ throw new E(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`, s);
966
+ _e(t, e, new ce("string", !1, !0), n, s);
967
+ return;
968
+ }
969
+ const c = u.attrs[a];
970
+ if (Object.keys(u.links).includes(a)) {
971
+ if (typeof t == "string" && !Te(t))
972
+ throw new E(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`, s);
973
+ _e(t, e, new ce("string", !1, !0), n, s);
974
+ return;
975
+ }
976
+ if (!c) {
977
+ const l = Object.keys(u.attrs);
978
+ throw new E(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${l.length > 0 ? l.join(", ") + ", id" : "id"}`, s);
979
+ }
980
+ _e(t, e, c, n, s);
981
+ }, un = (e, t, n, i) => {
982
+ for (const [s, r] of Object.entries(e)) {
983
+ if (s === "or" || s === "and") {
984
+ if (Array.isArray(r))
985
+ for (const c of r)
986
+ typeof c == "object" && c !== null && un(c, t, n, `${i}.${s}[${c}]`);
987
+ continue;
988
+ }
989
+ if (s === "id") {
990
+ _e(r, "id", new ce("string", !1, !0), t, `${i}.id`);
991
+ continue;
992
+ }
993
+ if (s.includes(".")) {
994
+ ei(s, r, t, n, `${i}.${s}`);
995
+ continue;
996
+ }
997
+ const o = n.entities[t];
998
+ if (!o)
999
+ continue;
1000
+ const a = o.attrs[s], u = o.links[s];
1001
+ if (!a && !u) {
1002
+ const c = Object.keys(o.attrs), l = Object.keys(o.links);
1003
+ throw new E(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length > 0 ? c.join(", ") : "none"}. Available links: ${l.length > 0 ? l.join(", ") : "none"}`, `${i}.${s}`);
1004
+ }
1005
+ if (a)
1006
+ _e(r, s, a, t, `${i}.${s}`);
1007
+ else if (u) {
1008
+ if (typeof r == "string" && !Te(r))
1009
+ throw new E(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`, `${i}.${s}`);
1010
+ const c = new ce("string", !1, !0);
1011
+ _e(r, s, c, t, `${i}.${s}`);
1012
+ }
1013
+ }
1014
+ }, ti = (e, t, n, i, s = 0) => {
1015
+ for (const o of Object.keys(e))
1016
+ if (!Nt.includes(o))
1017
+ throw new E(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Nt.join(", ")}. Found: ${o}`, i);
1018
+ const r = [
1019
+ // 'limit', // only supported client side
1020
+ "offset",
1021
+ "before",
1022
+ "after",
1023
+ "first",
1024
+ "last"
1025
+ ];
1026
+ for (const o of r)
1027
+ if (e[o] !== void 0 && s > 0)
1028
+ throw new E(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`, i);
1029
+ if (e.where && n) {
1030
+ if (typeof e.where != "object" || e.where === null)
1031
+ throw new E(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`, i ? `${i}.where` : void 0);
1032
+ un(e.where, t, n, i ? `${i}.where` : "where");
1033
+ }
1034
+ }, fn = (e, t, n, i, s = 0) => {
1035
+ var r;
1036
+ if (!e || typeof e != "object")
1037
+ throw new E(`Query part for entity '${t}' must be an object, but received: ${typeof e}`, i);
1038
+ for (const o of Object.keys(e))
1039
+ if (o !== "$") {
1040
+ if (n && !(o in n.entities[t].links)) {
1041
+ const u = Object.keys(n.entities[t].links);
1042
+ throw new E(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length > 0 ? u.join(", ") : "none"}`, `${i}.${o}`);
1043
+ }
1044
+ const a = e[o];
1045
+ if (typeof a == "object" && a !== null) {
1046
+ const u = (r = n == null ? void 0 : n.entities[t].links[o]) == null ? void 0 : r.entityName;
1047
+ u && fn(a, u, n, `${i}.${o}`, s + 1);
1048
+ }
1049
+ } else {
1050
+ const a = e[o];
1051
+ if (typeof a != "object" || a === null)
1052
+ throw new E(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`, `${i}.$`);
1053
+ ti(a, t, n, `${i}.$`, s);
1054
+ }
1055
+ }, Lt = (e, t) => {
1056
+ if (typeof e != "object" || e === null)
1057
+ throw new E(`Query must be an object, but received: ${typeof e}${e === null ? " (null)" : ""}`);
1058
+ if (Array.isArray(e))
1059
+ throw new E(`Query must be an object, but received: ${typeof e}`);
1060
+ const n = e;
1061
+ for (const i of Object.keys(n)) {
1062
+ if (Array.isArray(e[i]))
1063
+ throw new E(`Query keys must be strings, but found key of type: ${typeof i}`, i);
1064
+ if (typeof i != "string")
1065
+ throw new E(`Query keys must be strings, but found key of type: ${typeof i}`, i);
1066
+ if (i !== "$$ruleParams") {
1067
+ if (t && !t.entities[i]) {
1068
+ const s = Object.keys(t.entities);
1069
+ throw new E(`Entity '${i}' does not exist in schema. Available entities: ${s.length > 0 ? s.join(", ") : "none"}`, i);
1070
+ }
1071
+ fn(n[i], i, t, i, 0);
1072
+ }
1073
+ }
1074
+ }, Wt = (e) => typeof e != "string" ? !1 : on(e) ? !0 : Te(e);
1075
+ class q extends Error {
1076
+ constructor(t) {
1077
+ super(t), this.name = "TransactionValidationError";
1078
+ }
1079
+ }
1080
+ const ln = (e) => e.length > 0 ? e.join(", ") : "none", ni = (e, t) => new q(`Entity '${e}' does not exist in schema. Available entities: ${ln(t)}`), at = {
1081
+ string: (e) => typeof e == "string",
1082
+ number: (e) => typeof e == "number" && !isNaN(e),
1083
+ boolean: (e) => typeof e == "boolean",
1084
+ date: (e) => e instanceof Date || typeof e == "string" || typeof e == "number",
1085
+ json: () => !0
1086
+ }, ii = (e, t) => {
1087
+ var n;
1088
+ return e == null ? !0 : ((n = at[t.valueType]) == null ? void 0 : n.call(at, e)) ?? !1;
1089
+ }, dn = (e, t) => {
1090
+ const n = t.entities[e];
1091
+ if (!n)
1092
+ throw ni(e, Object.keys(t.entities));
1093
+ return n;
1094
+ }, ct = (e, t, n) => {
1095
+ const i = dn(e, n);
1096
+ if (typeof t != "object" || t === null)
1097
+ throw new q(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);
1098
+ for (const [s, r] of Object.entries(t)) {
1099
+ if (s === "id")
1100
+ continue;
1101
+ const o = i.attrs[s];
1102
+ if (o && !ii(r, o))
1103
+ throw new q(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`);
1104
+ }
1105
+ }, Ft = (e, t, n) => {
1106
+ const i = dn(e, n);
1107
+ if (typeof t != "object" || t === null)
1108
+ throw new q(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);
1109
+ for (const [s, r] of Object.entries(t)) {
1110
+ if (!i.links[s]) {
1111
+ const a = Object.keys(i.links);
1112
+ throw new q(`Link '${s}' does not exist on entity '${e}'. Available links: ${ln(a)}`);
1113
+ }
1114
+ if (r != null) {
1115
+ if (Array.isArray(r)) {
1116
+ for (const a of r)
1117
+ if (!Wt(a))
1118
+ throw new q(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`);
1119
+ } else if (!Wt(r))
1120
+ throw new q(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`);
1121
+ }
1122
+ }
1123
+ }, si = {
1124
+ create: ct,
1125
+ update: ct,
1126
+ merge: ct,
1127
+ link: Ft,
1128
+ unlink: Ft,
1129
+ delete: () => {
1130
+ }
1131
+ }, ri = (e, t) => {
1132
+ if (!t)
1133
+ return;
1134
+ const [n, i, s, r] = e;
1135
+ if (!Array.isArray(s) && !Te(s))
1136
+ throw new q(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);
1137
+ if (typeof i != "string")
1138
+ throw new q(`Entity name must be a string, but received: ${typeof i}`);
1139
+ const o = si[n];
1140
+ o && r !== void 0 && o(i, r, t);
1141
+ }, oi = (e, t) => {
1142
+ const n = Array.isArray(e) ? e : [e];
1143
+ for (const i of n) {
1144
+ if (!i || typeof i != "object")
1145
+ throw new q(`Transaction chunk must be an object, but received: ${typeof i}`);
1146
+ if (!Array.isArray(i.__ops))
1147
+ throw new q(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);
1148
+ for (const s of i.__ops) {
1149
+ if (!Array.isArray(s))
1150
+ throw new q(`Transaction operation must be an array, but received: ${typeof s}`);
1151
+ ri(s, t);
1152
+ }
1153
+ }
1154
+ };
1155
+ let ai = 0;
1156
+ class ci {
1157
+ constructor(t, n, i) {
1158
+ d(this, "type", "sse");
1159
+ d(this, "initParams", null);
1160
+ d(this, "sendQueue", []);
1161
+ d(this, "sendPromise");
1162
+ d(this, "closeFired", !1);
1163
+ d(this, "sseInitTimeout");
1164
+ d(this, "ES");
1165
+ d(this, "messageUrl");
1166
+ d(this, "conn");
1167
+ d(this, "url");
1168
+ d(this, "id");
1169
+ d(this, "onopen");
1170
+ d(this, "onmessage");
1171
+ d(this, "onclose");
1172
+ d(this, "onerror");
1173
+ this.id = `${this.type}_${ai++}`, this.url = n, this.messageUrl = i || this.url, this.ES = t, this.conn = new t(n), this.sseInitTimeout = setTimeout(() => {
1174
+ this.initParams || this.handleError();
1175
+ }, 1e4), this.conn.onmessage = (s) => {
1176
+ const r = JSON.parse(s.data);
1177
+ if (Array.isArray(r))
1178
+ for (const o of r)
1179
+ this.handleMessage(o);
1180
+ else
1181
+ this.handleMessage(r);
1182
+ }, this.conn.onerror = (s) => {
1183
+ this.handleError();
1184
+ };
1185
+ }
1186
+ handleMessage(t) {
1187
+ if (t.op === "sse-init") {
1188
+ this.initParams = {
1189
+ machineId: t["machine-id"],
1190
+ sessionId: t["session-id"],
1191
+ sseToken: t["sse-token"]
1192
+ }, this.onopen && this.onopen({ target: this }), clearTimeout(this.sseInitTimeout);
1193
+ return;
1194
+ }
1195
+ this.onmessage && this.onmessage({
1196
+ target: this,
1197
+ message: t
1198
+ });
1199
+ }
1200
+ // Runs the onerror and closes the connection
1201
+ handleError() {
1202
+ try {
1203
+ this.onerror && this.onerror({ target: this });
1204
+ } finally {
1205
+ this.handleClose();
1206
+ }
1207
+ }
1208
+ handleClose() {
1209
+ this.conn.close(), this.onclose && !this.closeFired && (this.closeFired = !0, this.onclose({ target: this }));
1210
+ }
1211
+ async postMessages(t) {
1212
+ var n, i, s;
1213
+ try {
1214
+ (await fetch(this.messageUrl, {
1215
+ method: "POST",
1216
+ headers: { "Content-Type": "application/json" },
1217
+ body: JSON.stringify({
1218
+ machine_id: (n = this.initParams) == null ? void 0 : n.machineId,
1219
+ session_id: (i = this.initParams) == null ? void 0 : i.sessionId,
1220
+ sse_token: (s = this.initParams) == null ? void 0 : s.sseToken,
1221
+ messages: t
1222
+ })
1223
+ })).ok || this.handleError();
1224
+ } catch {
1225
+ this.handleError();
1226
+ }
1227
+ }
1228
+ async flushQueue() {
1229
+ if (this.sendPromise || !this.sendQueue.length)
1230
+ return;
1231
+ const t = this.sendQueue;
1232
+ this.sendQueue = [];
1233
+ const n = this.postMessages(t);
1234
+ this.sendPromise = n, n.then(() => {
1235
+ this.sendPromise = null, this.flushQueue();
1236
+ });
1237
+ }
1238
+ send(t) {
1239
+ if (!this.isOpen() || !this.initParams)
1240
+ 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.");
1241
+ this.sendQueue.push(t), this.flushQueue();
1242
+ }
1243
+ isOpen() {
1244
+ return this.conn.readyState === this.ES.OPEN && this.initParams !== null;
1245
+ }
1246
+ isConnecting() {
1247
+ return this.conn.readyState === this.ES.CONNECTING || this.conn.readyState === this.ES.OPEN && this.initParams === null;
1248
+ }
1249
+ close() {
1250
+ this.handleClose();
1251
+ }
1252
+ }
1253
+ var zt;
1254
+ (function(e) {
1255
+ e.InitialSyncBatch = "InitialSyncBatch", e.InitialSyncComplete = "InitialSyncComplete", e.LoadFromStorage = "LoadFromStorage", e.SyncTransaction = "SyncTransaction", e.Error = "Error";
1256
+ })(zt || (zt = {}));
1257
+ function ui({ WStream: e, opts: t, startStream: n, appendStream: i, registerStream: s }) {
1258
+ const r = t.clientId;
1259
+ let o = null, a = null;
1260
+ const u = Ee();
1261
+ let c = !1, l = !1;
1262
+ const f = [], m = [], p = [];
1263
+ let I = !1, g = 0, h = 0;
1264
+ const $ = [], w = new TextEncoder();
1265
+ function O() {
1266
+ l = !0;
1267
+ for (const y of f)
1268
+ y();
1269
+ }
1270
+ function ne(y) {
1271
+ return f.push(y), () => {
1272
+ const v = f.indexOf(y);
1273
+ v !== -1 && f.splice(v, 1);
1274
+ };
1275
+ }
1276
+ function P(y) {
1277
+ return p.push(y), () => {
1278
+ const v = p.indexOf(y);
1279
+ v !== -1 && p.splice(v, 1);
1280
+ };
1281
+ }
1282
+ t.waitUntil && t.waitUntil(new Promise((y) => {
1283
+ p.push(y);
1284
+ }));
1285
+ function j() {
1286
+ for (const y of p)
1287
+ try {
1288
+ y();
1289
+ } catch {
1290
+ }
1291
+ }
1292
+ function K(y) {
1293
+ return m.push(y), () => {
1294
+ const v = m.indexOf(y);
1295
+ v !== -1 && m.splice(v, 1);
1296
+ };
1297
+ }
1298
+ function ie(y) {
1299
+ o = y;
1300
+ for (const v of m)
1301
+ v(o);
1302
+ }
1303
+ function V() {
1304
+ I = !0;
1305
+ }
1306
+ function Ae(y) {
1307
+ let v = g, D = 0, F = 0;
1308
+ for (const { byteLen: X } of $) {
1309
+ const re = v + X;
1310
+ if (re > y)
1311
+ break;
1312
+ v = re, D++, F += X;
1313
+ }
1314
+ D > 0 && (g += F, h -= F, $.splice(0, D));
1315
+ }
1316
+ function pe(y, v) {
1317
+ O(), y.error(v), j();
1318
+ }
1319
+ async function me() {
1320
+ const y = await n({
1321
+ clientId: r,
1322
+ reconnectToken: u,
1323
+ ruleParams: t.ruleParams
1324
+ });
1325
+ switch (y.type) {
1326
+ case "ok": {
1327
+ const { streamId: v, offset: D } = y;
1328
+ o = v, Ae(D), $.length && i({
1329
+ streamId: v,
1330
+ chunks: $.map((F) => F.chunk),
1331
+ offset: g
1332
+ }), I = !1;
1333
+ break;
1334
+ }
1335
+ case "disconnect": {
1336
+ V();
1337
+ break;
1338
+ }
1339
+ case "error": {
1340
+ a && pe(a, y.error);
1341
+ break;
1342
+ }
1343
+ }
1344
+ }
1345
+ function se() {
1346
+ V(), me();
1347
+ }
1348
+ function J({ offset: y, done: v }) {
1349
+ Ae(y), v && (c = !0, j());
1350
+ }
1351
+ function Pe(y) {
1352
+ return c ? (pe(y, new B("Stream has been closed.")), null) : o || (pe(y, new B("Stream has not been initialized.")), null);
1353
+ }
1354
+ async function $n(y) {
1355
+ a = y;
1356
+ let v = !0, D = 0;
1357
+ for (; v; ) {
1358
+ let F = Date.now() + Math.min(15e3, 500 * (D - 1));
1359
+ v = !1;
1360
+ const X = await n({
1361
+ clientId: t.clientId,
1362
+ reconnectToken: u,
1363
+ ruleParams: t.ruleParams
1364
+ });
1365
+ switch (X.type) {
1366
+ case "ok": {
1367
+ const { streamId: re, offset: it } = X;
1368
+ if (it !== 0) {
1369
+ const je = new B("Write stream is corrupted");
1370
+ pe(y, je);
1371
+ return;
1372
+ }
1373
+ ie(re), s(re, {
1374
+ onDisconnect: V,
1375
+ onFlush: J,
1376
+ onConnectionReconnect: me,
1377
+ onAppendFailed: se
1378
+ }), I = !1;
1379
+ return;
1380
+ }
1381
+ case "disconnect": {
1382
+ v = !0, V(), D++, await new Promise((re) => {
1383
+ setTimeout(re, Math.max(0, F - Date.now()));
1384
+ });
1385
+ break;
1386
+ }
1387
+ case "error": {
1388
+ pe(y, X.error);
1389
+ return;
1390
+ }
1391
+ }
1392
+ }
1393
+ }
1394
+ class kn extends e {
1395
+ constructor(v, D) {
1396
+ super(v, D);
1397
+ }
1398
+ async streamId() {
1399
+ return o || new Promise((v, D) => {
1400
+ const F = [], X = () => {
1401
+ for (const je of F)
1402
+ je();
1403
+ }, re = (je) => {
1404
+ v(je), X();
1405
+ }, it = () => {
1406
+ D(new B("Stream is closed.")), X();
1407
+ };
1408
+ F.push(K(re)), F.push(ne(it));
1409
+ });
1410
+ }
1411
+ }
1412
+ return {
1413
+ stream: new kn({
1414
+ // TODO(dww): accept a storage so that write streams can survive across
1415
+ // browser restarts
1416
+ async start(y) {
1417
+ try {
1418
+ await $n(y);
1419
+ } catch (v) {
1420
+ pe(y, v);
1421
+ }
1422
+ },
1423
+ write(y, v) {
1424
+ const D = Pe(v);
1425
+ if (D) {
1426
+ const F = w.encode(y).length;
1427
+ $.push({ chunk: y, byteLen: F });
1428
+ const X = g + h;
1429
+ h += F, I || i({ streamId: D, chunks: [y], offset: X });
1430
+ }
1431
+ },
1432
+ close() {
1433
+ o ? i({
1434
+ streamId: o,
1435
+ chunks: [],
1436
+ offset: g + h,
1437
+ isDone: !0
1438
+ }) : j(), O();
1439
+ },
1440
+ abort(y) {
1441
+ o ? i({
1442
+ streamId: o,
1443
+ chunks: [],
1444
+ offset: g + h,
1445
+ isDone: !0,
1446
+ abortReason: y
1447
+ }) : j(), O();
1448
+ }
1449
+ }),
1450
+ addCompleteCb: P,
1451
+ closed() {
1452
+ return l;
1453
+ }
1454
+ };
1455
+ }
1456
+ class fi {
1457
+ constructor() {
1458
+ d(this, "items", []);
1459
+ d(this, "resolvers", []);
1460
+ d(this, "isClosed", !1);
1461
+ }
1462
+ push(t) {
1463
+ if (this.isClosed)
1464
+ return;
1465
+ const n = this.resolvers.shift();
1466
+ n ? n({ value: t, done: !1 }) : this.items.push(t);
1467
+ }
1468
+ close() {
1469
+ for (this.isClosed = !0; this.resolvers.length > 0; )
1470
+ this.resolvers.shift()({ value: void 0, done: !0 });
1471
+ }
1472
+ async *[Symbol.asyncIterator]() {
1473
+ for (; ; )
1474
+ if (this.items.length > 0)
1475
+ yield this.items.shift();
1476
+ else {
1477
+ if (this.isClosed)
1478
+ return;
1479
+ {
1480
+ const { value: t, done: n } = await new Promise((i) => {
1481
+ this.resolvers.push(i);
1482
+ });
1483
+ if (n || !t)
1484
+ return;
1485
+ yield t;
1486
+ }
1487
+ }
1488
+ }
1489
+ }
1490
+ function li({ RStream: e, opts: t, startStream: n, cancelStream: i }) {
1491
+ let s = t.byteOffset || 0, r = !1;
1492
+ const o = new TextDecoder("utf-8"), a = new TextEncoder();
1493
+ let u, c = !1;
1494
+ const l = [];
1495
+ function f() {
1496
+ c = !0;
1497
+ for (const w of l)
1498
+ w();
1499
+ }
1500
+ function m(w) {
1501
+ return l.push(w), () => {
1502
+ const O = l.indexOf(w);
1503
+ O !== -1 && l.splice(O, 1);
1504
+ };
1505
+ }
1506
+ function p(w, O) {
1507
+ w.error(O), f();
1508
+ }
1509
+ let I = 0;
1510
+ async function g(w, O) {
1511
+ u = Ee();
1512
+ const ne = { ...w || {}, eventId: u };
1513
+ for await (const P of n(ne)) {
1514
+ if (r)
1515
+ return;
1516
+ if (P.type === "reconnect")
1517
+ return { retry: !0 };
1518
+ if (P.type === "error") {
1519
+ p(O, P.error);
1520
+ return;
1521
+ }
1522
+ if (P.offset > s) {
1523
+ p(O, new B("Stream is corrupted.")), r = !0;
1524
+ return;
1525
+ }
1526
+ let j = s - P.offset;
1527
+ if (P.files && P.files.length) {
1528
+ const K = new AbortController();
1529
+ let ie = fetch(P.files[0].url, {
1530
+ signal: K.signal
1531
+ });
1532
+ for (let V = 0; V < P.files.length; V++) {
1533
+ const Ae = P.files[V + 1], me = await ie;
1534
+ if (Ae && (ie = fetch(Ae.url, { signal: K.signal })), !me.ok) {
1535
+ if (I++, I > 10) {
1536
+ p(O, new B("Unable to process stream."));
1537
+ return;
1538
+ }
1539
+ return { retry: !0 };
1540
+ }
1541
+ if (me.body)
1542
+ for await (const se of me.body) {
1543
+ if (r) {
1544
+ K.abort();
1545
+ return;
1546
+ }
1547
+ let J = se;
1548
+ if (j > 0 && (J = se.subarray(j), j -= se.length - J.length), !J.length)
1549
+ continue;
1550
+ s += J.length;
1551
+ const Pe = o.decode(J);
1552
+ O.enqueue(Pe);
1553
+ }
1554
+ else {
1555
+ const se = await me.arrayBuffer();
1556
+ let J = se;
1557
+ if (r) {
1558
+ K.abort();
1559
+ return;
1560
+ }
1561
+ if (j > 0 && (J = new Uint8Array(se).subarray(j), j -= se.byteLength - J.length), !J.byteLength)
1562
+ continue;
1563
+ s += J.byteLength;
1564
+ const Pe = o.decode(J);
1565
+ O.enqueue(Pe);
1566
+ }
1567
+ }
1568
+ }
1569
+ if (I = 0, P.content) {
1570
+ let K = P.content, ie = a.encode(P.content);
1571
+ if (j > 0) {
1572
+ const V = ie.subarray(j);
1573
+ if (j -= ie.length - V.length, !V.length)
1574
+ continue;
1575
+ ie = V, K = o.decode(V);
1576
+ }
1577
+ s += ie.length, O.enqueue(K);
1578
+ }
1579
+ }
1580
+ }
1581
+ async function h(w) {
1582
+ let O = !0, ne = 0;
1583
+ for (; O; ) {
1584
+ O = !1;
1585
+ let P = Date.now() + Math.min(15e3, 500 * (ne - 1));
1586
+ const j = await g({ ...t, offset: s }, w);
1587
+ j != null && j.retry && (O = !0, ne++, P < Date.now() - 3e5 && (ne = 0), await new Promise((K) => {
1588
+ setTimeout(K, Math.max(0, P - Date.now()));
1589
+ }));
1590
+ }
1591
+ !r && !c && (w.close(), f());
1592
+ }
1593
+ return {
1594
+ stream: new e({
1595
+ start(w) {
1596
+ h(w);
1597
+ },
1598
+ cancel(w) {
1599
+ r = !0, u && i({ eventId: u }), f();
1600
+ }
1601
+ }),
1602
+ addCloseCb: m,
1603
+ closed() {
1604
+ return c;
1605
+ }
1606
+ };
1607
+ }
1608
+ class di {
1609
+ constructor({ WStream: t, RStream: n, trySend: i, log: s }) {
1610
+ d(this, "trySend");
1611
+ d(this, "WStream");
1612
+ d(this, "RStream");
1613
+ d(this, "writeStreams", {});
1614
+ d(this, "startWriteStreamCbs", {});
1615
+ d(this, "readStreamIterators", {});
1616
+ d(this, "log");
1617
+ d(this, "activeStreams", /* @__PURE__ */ new Set());
1618
+ this.WStream = t, this.RStream = n, this.trySend = i, this.log = s;
1619
+ }
1620
+ createWriteStream(t) {
1621
+ const { stream: n, addCompleteCb: i } = ui({
1622
+ WStream: this.WStream,
1623
+ startStream: this.startWriteStream.bind(this),
1624
+ appendStream: this.appendStream.bind(this),
1625
+ registerStream: this.registerWriteStream.bind(this),
1626
+ opts: t
1627
+ });
1628
+ return this.activeStreams.add(n), i(() => {
1629
+ this.activeStreams.delete(n);
1630
+ }), n;
1631
+ }
1632
+ createReadStream(t) {
1633
+ const { stream: n, addCloseCb: i } = li({
1634
+ RStream: this.RStream,
1635
+ opts: t,
1636
+ startStream: this.startReadStream.bind(this),
1637
+ cancelStream: this.cancelReadStream.bind(this)
1638
+ });
1639
+ return this.activeStreams.add(n), i(() => {
1640
+ this.activeStreams.delete(n);
1641
+ }), n;
1642
+ }
1643
+ startWriteStream(t) {
1644
+ const n = Ee();
1645
+ let i = null;
1646
+ const s = new Promise((o) => {
1647
+ i = o;
1648
+ });
1649
+ this.startWriteStreamCbs[n] = i;
1650
+ const r = {
1651
+ op: "start-stream",
1652
+ "client-id": t.clientId,
1653
+ "reconnect-token": t.reconnectToken
1654
+ };
1655
+ return t.ruleParams && (r["rule-params"] = t.ruleParams), this.trySend(n, r), s;
1656
+ }
1657
+ registerWriteStream(t, n) {
1658
+ this.writeStreams[t] = n;
1659
+ }
1660
+ appendStream({ streamId: t, chunks: n, isDone: i, offset: s, abortReason: r }) {
1661
+ const o = {
1662
+ op: "append-stream",
1663
+ "stream-id": t,
1664
+ chunks: n,
1665
+ offset: s,
1666
+ done: !!i
1667
+ };
1668
+ r && (o["abort-reason"] = r), this.trySend(Ee(), o);
1669
+ }
1670
+ onAppendFailed(t) {
1671
+ const n = this.writeStreams[t["stream-id"]];
1672
+ n && n.onAppendFailed();
1673
+ }
1674
+ onStartStreamOk(t) {
1675
+ const n = this.startWriteStreamCbs[t["client-event-id"]];
1676
+ if (!n) {
1677
+ this.log.info("No stream for start-stream-ok", t);
1678
+ return;
1679
+ }
1680
+ n({ type: "ok", streamId: t["stream-id"], offset: t.offset }), delete this.startWriteStreamCbs[t["client-event-id"]];
1681
+ }
1682
+ onStreamFlushed(t) {
1683
+ const n = t["stream-id"], i = this.writeStreams[n];
1684
+ if (!i) {
1685
+ this.log.info("No stream cbs for stream-flushed", t);
1686
+ return;
1687
+ }
1688
+ i.onFlush({ offset: t.offset, done: t.done }), t.done && delete this.writeStreams[n];
1689
+ }
1690
+ startReadStream({ eventId: t, clientId: n, streamId: i, offset: s, ruleParams: r }) {
1691
+ const o = { op: "subscribe-stream" };
1692
+ if (!i && !n)
1693
+ throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");
1694
+ i && (o["stream-id"] = i), n && (o["client-id"] = n), s && (o.offset = s), r && (o["rule-params"] = r);
1695
+ const a = new fi();
1696
+ return this.readStreamIterators[t] = a, this.trySend(t, o), a;
1697
+ }
1698
+ cancelReadStream({ eventId: t }) {
1699
+ const n = {
1700
+ op: "unsubscribe-stream",
1701
+ "subscribe-event-id": t
1702
+ };
1703
+ this.trySend(Ee(), n), delete this.readStreamIterators[t];
1704
+ }
1705
+ onStreamAppend(t) {
1706
+ var s;
1707
+ const n = t["client-event-id"], i = this.readStreamIterators[n];
1708
+ if (!i) {
1709
+ this.log.info("No iterator for read stream", t);
1710
+ return;
1711
+ }
1712
+ if (t.error) {
1713
+ t.retry ? i.push({ type: "reconnect" }) : i.push({
1714
+ type: "error",
1715
+ error: new B(t.error)
1716
+ }), i.close(), delete this.readStreamIterators[n];
1717
+ return;
1718
+ }
1719
+ ((s = t.files) != null && s.length || t.content) && i.push({
1720
+ type: "append",
1721
+ offset: t.offset,
1722
+ files: t.files,
1723
+ content: t.content
1724
+ }), t.done && (i.close(), delete this.readStreamIterators[n]);
1725
+ }
1726
+ onConnectionStatusChange(t) {
1727
+ for (const n of Object.values(this.startWriteStreamCbs))
1728
+ n({ type: "disconnect" });
1729
+ if (this.startWriteStreamCbs = {}, t !== hi.AUTHENTICATED)
1730
+ for (const { onDisconnect: n } of Object.values(this.writeStreams))
1731
+ n();
1732
+ else {
1733
+ for (const { onConnectionReconnect: n } of Object.values(this.writeStreams))
1734
+ n();
1735
+ for (const n of Object.values(this.readStreamIterators))
1736
+ n.push({ type: "reconnect" }), n.close();
1737
+ this.readStreamIterators = {};
1738
+ }
1739
+ }
1740
+ onRecieveError(t) {
1741
+ const n = t["original-event"];
1742
+ switch (n.op) {
1743
+ case "append-stream": {
1744
+ const i = n["stream-id"], s = this.writeStreams[i];
1745
+ s == null || s.onAppendFailed();
1746
+ break;
1747
+ }
1748
+ case "start-stream": {
1749
+ const i = t["client-event-id"], s = this.startWriteStreamCbs[i];
1750
+ s && (s({
1751
+ type: "error",
1752
+ error: new B(t.message || "Unknown error", t.hint)
1753
+ }), delete this.startWriteStreamCbs[i]);
1754
+ break;
1755
+ }
1756
+ case "subscribe-stream": {
1757
+ const i = t["client-event-id"], s = this.readStreamIterators[i];
1758
+ s && (s.push({
1759
+ type: "error",
1760
+ error: new B(t.message || "Unknown error", t.hint)
1761
+ }), s.close(), delete this.readStreamIterators[i]);
1762
+ break;
1763
+ }
1764
+ }
1765
+ }
1766
+ hasActiveStreams() {
1767
+ return this.activeStreams.size > 0;
1768
+ }
1769
+ }
1770
+ const hi = {
1771
+ AUTHENTICATED: "authenticated"
1772
+ };
1773
+ function pi() {
1774
+ return globalThis.__instantDbSchemaHashStore = globalThis.__instantDbSchemaHashStore ?? /* @__PURE__ */ new WeakMap(), globalThis.__instantDbSchemaHashStore;
1775
+ }
1776
+ function mi() {
1777
+ return globalThis.__instantDbStore = globalThis.__instantDbStore ?? {}, globalThis.__instantDbStore;
1778
+ }
1779
+ mi();
1780
+ pi();
1781
+ class Vt extends Error {
1782
+ constructor(t, n) {
1783
+ super(t), this.name = "ParseError", this.type = n.type, this.field = n.field, this.value = n.value, this.line = n.line;
1784
+ }
1785
+ }
1786
+ function ut(e) {
1787
+ }
1788
+ function yi(e) {
1789
+ if (typeof e == "function")
1790
+ throw new TypeError(
1791
+ "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
1792
+ );
1793
+ const { onEvent: t = ut, onError: n = ut, onRetry: i = ut, onComment: s } = e;
1794
+ let r = "", o = !0, a, u = "", c = "";
1795
+ function l(g) {
1796
+ const h = o ? g.replace(/^\xEF\xBB\xBF/, "") : g, [$, w] = bi(`${r}${h}`);
1797
+ for (const O of $)
1798
+ f(O);
1799
+ r = w, o = !1;
1800
+ }
1801
+ function f(g) {
1802
+ if (g === "") {
1803
+ p();
1804
+ return;
1805
+ }
1806
+ if (g.startsWith(":")) {
1807
+ s && s(g.slice(g.startsWith(": ") ? 2 : 1));
1808
+ return;
1809
+ }
1810
+ const h = g.indexOf(":");
1811
+ if (h !== -1) {
1812
+ const $ = g.slice(0, h), w = g[h + 1] === " " ? 2 : 1, O = g.slice(h + w);
1813
+ m($, O, g);
1814
+ return;
1815
+ }
1816
+ m(g, "", g);
1817
+ }
1818
+ function m(g, h, $) {
1819
+ switch (g) {
1820
+ case "event":
1821
+ c = h;
1822
+ break;
1823
+ case "data":
1824
+ u = `${u}${h}
1825
+ `;
1826
+ break;
1827
+ case "id":
1828
+ a = h.includes("\0") ? void 0 : h;
1829
+ break;
1830
+ case "retry":
1831
+ /^\d+$/.test(h) ? i(parseInt(h, 10)) : n(
1832
+ new Vt(`Invalid \`retry\` value: "${h}"`, {
1833
+ type: "invalid-retry",
1834
+ value: h,
1835
+ line: $
1836
+ })
1837
+ );
1838
+ break;
1839
+ default:
1840
+ n(
1841
+ new Vt(
1842
+ `Unknown field "${g.length > 20 ? `${g.slice(0, 20)}…` : g}"`,
1843
+ { type: "unknown-field", field: g, value: h, line: $ }
1844
+ )
1845
+ );
1846
+ break;
1847
+ }
1848
+ }
1849
+ function p() {
1850
+ u.length > 0 && t({
1851
+ id: a,
1852
+ event: c || void 0,
1853
+ // If the data buffer's last character is a U+000A LINE FEED (LF) character,
1854
+ // then remove the last character from the data buffer.
1855
+ data: u.endsWith(`
1856
+ `) ? u.slice(0, -1) : u
1857
+ }), a = void 0, u = "", c = "";
1858
+ }
1859
+ function I(g = {}) {
1860
+ r && g.consume && f(r), o = !0, a = void 0, u = "", c = "", r = "";
1861
+ }
1862
+ return { feed: l, reset: I };
1863
+ }
1864
+ function bi(e) {
1865
+ const t = [];
1866
+ let n = "", i = 0;
1867
+ for (; i < e.length; ) {
1868
+ const s = e.indexOf("\r", i), r = e.indexOf(`
1869
+ `, i);
1870
+ let o = -1;
1871
+ if (s !== -1 && r !== -1 ? o = Math.min(s, r) : s !== -1 ? o = s : r !== -1 && (o = r), o === -1) {
1872
+ n = e.slice(i);
1873
+ break;
1874
+ } else {
1875
+ const a = e.slice(i, o);
1876
+ t.push(a), i = o + 1, e[i - 1] === "\r" && e[i] === `
1877
+ ` && i++;
1878
+ }
1879
+ }
1880
+ return [t, n];
1881
+ }
1882
+ class Jt extends Event {
1883
+ /**
1884
+ * Constructs a new `ErrorEvent` instance. This is typically not called directly,
1885
+ * but rather emitted by the `EventSource` object when an error occurs.
1886
+ *
1887
+ * @param type - The type of the event (should be "error")
1888
+ * @param errorEventInitDict - Optional properties to include in the error event
1889
+ */
1890
+ constructor(t, n) {
1891
+ var i, s;
1892
+ super(t), this.code = (i = n == null ? void 0 : n.code) != null ? i : void 0, this.message = (s = n == null ? void 0 : n.message) != null ? s : void 0;
1893
+ }
1894
+ /**
1895
+ * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1896
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1897
+ * we explicitly include the properties in the `inspect` method.
1898
+ *
1899
+ * This is automatically called by Node.js when you `console.log` an instance of this class.
1900
+ *
1901
+ * @param _depth - The current depth
1902
+ * @param options - The options passed to `util.inspect`
1903
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1904
+ * @returns A string representation of the error
1905
+ */
1906
+ [Symbol.for("nodejs.util.inspect.custom")](t, n, i) {
1907
+ return i(Qt(this), n);
1908
+ }
1909
+ /**
1910
+ * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
1911
+ * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
1912
+ * we explicitly include the properties in the `inspect` method.
1913
+ *
1914
+ * This is automatically called by Deno when you `console.log` an instance of this class.
1915
+ *
1916
+ * @param inspect - The inspect function to use (prevents having to import it from `util`)
1917
+ * @param options - The options passed to `Deno.inspect`
1918
+ * @returns A string representation of the error
1919
+ */
1920
+ [Symbol.for("Deno.customInspect")](t, n) {
1921
+ return t(Qt(this), n);
1922
+ }
1923
+ }
1924
+ function gi(e) {
1925
+ const t = globalThis.DOMException;
1926
+ return typeof t == "function" ? new t(e, "SyntaxError") : new SyntaxError(e);
1927
+ }
1928
+ function mt(e) {
1929
+ return e instanceof Error ? "errors" in e && Array.isArray(e.errors) ? e.errors.map(mt).join(", ") : "cause" in e && e.cause instanceof Error ? `${e}: ${mt(e.cause)}` : e.message : `${e}`;
1930
+ }
1931
+ function Qt(e) {
1932
+ return {
1933
+ type: e.type,
1934
+ message: e.message,
1935
+ code: e.code,
1936
+ defaultPrevented: e.defaultPrevented,
1937
+ cancelable: e.cancelable,
1938
+ timeStamp: e.timeStamp
1939
+ };
1940
+ }
1941
+ var hn = (e) => {
1942
+ throw TypeError(e);
1943
+ }, Rt = (e, t, n) => t.has(e) || hn("Cannot " + n), S = (e, t, n) => (Rt(e, t, "read from private field"), n ? n.call(e) : t.get(e)), x = (e, t, n) => t.has(e) ? hn("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), _ = (e, t, n, i) => (Rt(e, t, "write to private field"), t.set(e, n), n), ae = (e, t, n) => (Rt(e, t, "access private method"), n), z, ye, ve, He, Xe, Le, ke, We, de, Oe, Ce, $e, Ue, Y, yt, bt, gt, Gt, wt, St, De, It, vt;
1944
+ class ee extends EventTarget {
1945
+ constructor(t, n) {
1946
+ var i, s;
1947
+ super(), x(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, x(this, z), x(this, ye), x(this, ve), x(this, He), x(this, Xe), x(this, Le), x(this, ke), x(this, We, null), x(this, de), x(this, Oe), x(this, Ce, null), x(this, $e, null), x(this, Ue, null), x(this, bt, async (r) => {
1948
+ var o;
1949
+ S(this, Oe).reset();
1950
+ const { body: a, redirected: u, status: c, headers: l } = r;
1951
+ if (c === 204) {
1952
+ ae(this, Y, De).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
1953
+ return;
1954
+ }
1955
+ if (u ? _(this, ve, new URL(r.url)) : _(this, ve, void 0), c !== 200) {
1956
+ ae(this, Y, De).call(this, `Non-200 status code (${c})`, c);
1957
+ return;
1958
+ }
1959
+ if (!(l.get("content-type") || "").startsWith("text/event-stream")) {
1960
+ ae(this, Y, De).call(this, 'Invalid content type, expected "text/event-stream"', c);
1961
+ return;
1962
+ }
1963
+ if (S(this, z) === this.CLOSED)
1964
+ return;
1965
+ _(this, z, this.OPEN);
1966
+ const f = new Event("open");
1967
+ if ((o = S(this, Ue)) == null || o.call(this, f), this.dispatchEvent(f), typeof a != "object" || !a || !("getReader" in a)) {
1968
+ ae(this, Y, De).call(this, "Invalid response body, expected a web ReadableStream", c), this.close();
1969
+ return;
1970
+ }
1971
+ const m = new TextDecoder(), p = a.getReader();
1972
+ let I = !0;
1973
+ do {
1974
+ const { done: g, value: h } = await p.read();
1975
+ h && S(this, Oe).feed(m.decode(h, { stream: !g })), g && (I = !1, S(this, Oe).reset(), ae(this, Y, It).call(this));
1976
+ } while (I);
1977
+ }), x(this, gt, (r) => {
1978
+ _(this, de, void 0), !(r.name === "AbortError" || r.type === "aborted") && ae(this, Y, It).call(this, mt(r));
1979
+ }), x(this, wt, (r) => {
1980
+ typeof r.id == "string" && _(this, We, r.id);
1981
+ const o = new MessageEvent(r.event || "message", {
1982
+ data: r.data,
1983
+ origin: S(this, ve) ? S(this, ve).origin : S(this, ye).origin,
1984
+ lastEventId: r.id || ""
1985
+ });
1986
+ S(this, $e) && (!r.event || r.event === "message") && S(this, $e).call(this, o), this.dispatchEvent(o);
1987
+ }), x(this, St, (r) => {
1988
+ _(this, Le, r);
1989
+ }), x(this, vt, () => {
1990
+ _(this, ke, void 0), S(this, z) === this.CONNECTING && ae(this, Y, yt).call(this);
1991
+ });
1992
+ try {
1993
+ if (t instanceof URL)
1994
+ _(this, ye, t);
1995
+ else if (typeof t == "string")
1996
+ _(this, ye, new URL(t, wi()));
1997
+ else
1998
+ throw new Error("Invalid URL");
1999
+ } catch {
2000
+ throw gi("An invalid or illegal string was specified");
2001
+ }
2002
+ _(this, Oe, yi({
2003
+ onEvent: S(this, wt),
2004
+ onRetry: S(this, St)
2005
+ })), _(this, z, this.CONNECTING), _(this, Le, 3e3), _(this, Xe, (i = n == null ? void 0 : n.fetch) != null ? i : globalThis.fetch), _(this, He, (s = n == null ? void 0 : n.withCredentials) != null ? s : !1), ae(this, Y, yt).call(this);
2006
+ }
2007
+ /**
2008
+ * Returns the state of this EventSource object's connection. It can have the values described below.
2009
+ *
2010
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
2011
+ *
2012
+ * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
2013
+ * defined in the TypeScript `dom` library.
2014
+ *
2015
+ * @public
2016
+ */
2017
+ get readyState() {
2018
+ return S(this, z);
2019
+ }
2020
+ /**
2021
+ * Returns the URL providing the event stream.
2022
+ *
2023
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
2024
+ *
2025
+ * @public
2026
+ */
2027
+ get url() {
2028
+ return S(this, ye).href;
2029
+ }
2030
+ /**
2031
+ * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
2032
+ *
2033
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
2034
+ */
2035
+ get withCredentials() {
2036
+ return S(this, He);
2037
+ }
2038
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
2039
+ get onerror() {
2040
+ return S(this, Ce);
2041
+ }
2042
+ set onerror(t) {
2043
+ _(this, Ce, t);
2044
+ }
2045
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
2046
+ get onmessage() {
2047
+ return S(this, $e);
2048
+ }
2049
+ set onmessage(t) {
2050
+ _(this, $e, t);
2051
+ }
2052
+ /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
2053
+ get onopen() {
2054
+ return S(this, Ue);
2055
+ }
2056
+ set onopen(t) {
2057
+ _(this, Ue, t);
2058
+ }
2059
+ addEventListener(t, n, i) {
2060
+ const s = n;
2061
+ super.addEventListener(t, s, i);
2062
+ }
2063
+ removeEventListener(t, n, i) {
2064
+ const s = n;
2065
+ super.removeEventListener(t, s, i);
2066
+ }
2067
+ /**
2068
+ * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
2069
+ *
2070
+ * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
2071
+ *
2072
+ * @public
2073
+ */
2074
+ close() {
2075
+ S(this, ke) && clearTimeout(S(this, ke)), S(this, z) !== this.CLOSED && (S(this, de) && S(this, de).abort(), _(this, z, this.CLOSED), _(this, de, void 0));
2076
+ }
2077
+ }
2078
+ z = /* @__PURE__ */ new WeakMap(), ye = /* @__PURE__ */ new WeakMap(), ve = /* @__PURE__ */ new WeakMap(), He = /* @__PURE__ */ new WeakMap(), Xe = /* @__PURE__ */ new WeakMap(), Le = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), We = /* @__PURE__ */ new WeakMap(), de = /* @__PURE__ */ new WeakMap(), Oe = /* @__PURE__ */ new WeakMap(), Ce = /* @__PURE__ */ new WeakMap(), $e = /* @__PURE__ */ new WeakMap(), Ue = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakSet(), /**
2079
+ * Connect to the given URL and start receiving events
2080
+ *
2081
+ * @internal
2082
+ */
2083
+ yt = function() {
2084
+ _(this, z, this.CONNECTING), _(this, de, new AbortController()), S(this, Xe)(S(this, ye), ae(this, Y, Gt).call(this)).then(S(this, bt)).catch(S(this, gt));
2085
+ }, bt = /* @__PURE__ */ new WeakMap(), gt = /* @__PURE__ */ new WeakMap(), /**
2086
+ * Get request options for the `fetch()` request
2087
+ *
2088
+ * @returns The request options
2089
+ * @internal
2090
+ */
2091
+ Gt = function() {
2092
+ var e;
2093
+ const t = {
2094
+ // [spec] Let `corsAttributeState` be `Anonymous`…
2095
+ // [spec] …will have their mode set to "cors"…
2096
+ mode: "cors",
2097
+ redirect: "follow",
2098
+ headers: { Accept: "text/event-stream", ...S(this, We) ? { "Last-Event-ID": S(this, We) } : void 0 },
2099
+ cache: "no-store",
2100
+ signal: (e = S(this, de)) == null ? void 0 : e.signal
2101
+ };
2102
+ return "window" in globalThis && (t.credentials = this.withCredentials ? "include" : "same-origin"), t;
2103
+ }, wt = /* @__PURE__ */ new WeakMap(), St = /* @__PURE__ */ new WeakMap(), /**
2104
+ * Handles the process referred to in the EventSource specification as "failing a connection".
2105
+ *
2106
+ * @param error - The error causing the connection to fail
2107
+ * @param code - The HTTP status code, if available
2108
+ * @internal
2109
+ */
2110
+ De = function(e, t) {
2111
+ var n;
2112
+ S(this, z) !== this.CLOSED && _(this, z, this.CLOSED);
2113
+ const i = new Jt("error", { code: t, message: e });
2114
+ (n = S(this, Ce)) == null || n.call(this, i), this.dispatchEvent(i);
2115
+ }, /**
2116
+ * Schedules a reconnection attempt against the EventSource endpoint.
2117
+ *
2118
+ * @param message - The error causing the connection to fail
2119
+ * @param code - The HTTP status code, if available
2120
+ * @internal
2121
+ */
2122
+ It = function(e, t) {
2123
+ var n;
2124
+ if (S(this, z) === this.CLOSED)
2125
+ return;
2126
+ _(this, z, this.CONNECTING);
2127
+ const i = new Jt("error", { code: t, message: e });
2128
+ (n = S(this, Ce)) == null || n.call(this, i), this.dispatchEvent(i), _(this, ke, setTimeout(S(this, vt), S(this, Le)));
2129
+ }, vt = /* @__PURE__ */ new WeakMap(), /**
2130
+ * ReadyState representing an EventSource currently trying to connect
2131
+ *
2132
+ * @public
2133
+ */
2134
+ ee.CONNECTING = 0, /**
2135
+ * ReadyState representing an EventSource connection that is open (eg connected)
2136
+ *
2137
+ * @public
2138
+ */
2139
+ ee.OPEN = 1, /**
2140
+ * ReadyState representing an EventSource connection that is closed (eg disconnected)
2141
+ *
2142
+ * @public
2143
+ */
2144
+ ee.CLOSED = 2;
2145
+ function wi() {
2146
+ const e = "document" in globalThis ? globalThis.document : void 0;
2147
+ return e && typeof e == "object" && "baseURI" in e && typeof e.baseURI == "string" ? e.baseURI : void 0;
2148
+ }
2149
+ function Si(e, t, n, i) {
2150
+ let s = null, r = !1;
2151
+ const o = [], a = (f) => {
2152
+ o.push(f), o.length > 100 && o.shift(), s && (s(), s = null);
2153
+ };
2154
+ e(a);
2155
+ const u = () => (n(a), Promise.resolve({ done: !0, value: void 0 }));
2156
+ return t(() => {
2157
+ r = !0, s && s(), u();
2158
+ }), {
2159
+ next: async () => {
2160
+ for (; ; ) {
2161
+ if (i() === "closed" || r)
2162
+ return u();
2163
+ const f = o.shift();
2164
+ if (f)
2165
+ return { value: f, done: !1 };
2166
+ await new Promise((p) => {
2167
+ s = p;
2168
+ });
2169
+ }
2170
+ },
2171
+ return: u,
2172
+ throw(f) {
2173
+ return n(a), Promise.reject(f);
2174
+ },
2175
+ [Symbol.asyncIterator]() {
2176
+ return this;
2177
+ }
2178
+ };
2179
+ }
2180
+ function fe(e) {
2181
+ switch (e.readyState) {
2182
+ case e.CLOSED:
2183
+ return "closed";
2184
+ case e.CONNECTING:
2185
+ return "connecting";
2186
+ case e.OPEN:
2187
+ return "open";
2188
+ default:
2189
+ return "connecting";
2190
+ }
2191
+ }
2192
+ function Ii(e) {
2193
+ let t = null;
2194
+ return {
2195
+ ...e,
2196
+ text() {
2197
+ return t || (t = e.text()), t;
2198
+ },
2199
+ json() {
2200
+ return t || (t = e.text()), t.then((n) => JSON.parse(n));
2201
+ }
2202
+ };
2203
+ }
2204
+ function Ht(e) {
2205
+ if (!e)
2206
+ return;
2207
+ const t = {};
2208
+ for (const [n, i] of Object.entries(e))
2209
+ t[n] = {
2210
+ startCursor: i["start-cursor"],
2211
+ endCursor: i["end-cursor"],
2212
+ hasNextPage: i["has-next-page?"],
2213
+ hasPreviousPage: i["has-previous-page?"]
2214
+ };
2215
+ return t;
2216
+ }
2217
+ function vi(e, t, n) {
2218
+ let i, s = !1;
2219
+ const r = Ee(), o = new ee(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`, {
2220
+ fetch(h, $) {
2221
+ return i = null, fetch(h, {
2222
+ ...$,
2223
+ method: "POST",
2224
+ headers: n.headers,
2225
+ body: JSON.stringify({
2226
+ query: e,
2227
+ "inference?": n.inference,
2228
+ versions: {
2229
+ "@instantdb/admin": Re,
2230
+ "@instantdb/core": Re
2231
+ }
2232
+ })
2233
+ }).then((w) => (w.ok || (i = Ii(w)), w));
2234
+ }
2235
+ }), a = [], u = [], c = (h) => {
2236
+ a.push(h);
2237
+ }, l = (h) => {
2238
+ a.splice(a.indexOf(h), 1);
2239
+ }, f = (h) => {
2240
+ u.push(h);
2241
+ };
2242
+ t && c(t);
2243
+ let m = null;
2244
+ function p(h) {
2245
+ if (!s)
2246
+ for (const $ of a)
2247
+ try {
2248
+ $(h);
2249
+ } catch (w) {
2250
+ console.error("Error in subscribeQuery callback", w);
2251
+ }
2252
+ }
2253
+ function I(h) {
2254
+ var $, w;
2255
+ switch (h.op) {
2256
+ case "sse-init": {
2257
+ const O = h["machine-id"], ne = h["session-id"];
2258
+ m = { machineId: O, sessionId: ne };
2259
+ break;
2260
+ }
2261
+ case "add-query-ok": {
2262
+ p({
2263
+ type: "ok",
2264
+ data: h.result,
2265
+ pageInfo: Ht(($ = h["result-meta"]) == null ? void 0 : $["page-info"]),
2266
+ sessionInfo: m
2267
+ });
2268
+ break;
2269
+ }
2270
+ case "refresh-ok": {
2271
+ h.computations.length && p({
2272
+ type: "ok",
2273
+ data: h.computations[0]["instaql-result"],
2274
+ pageInfo: Ht((w = h.computations[0]["result-meta"]) == null ? void 0 : w["page-info"]),
2275
+ sessionInfo: m
2276
+ });
2277
+ break;
2278
+ }
2279
+ case "error": {
2280
+ p({
2281
+ type: "error",
2282
+ error: new Se({ body: h, status: h.status }),
2283
+ get readyState() {
2284
+ return fe(o);
2285
+ },
2286
+ get isClosed() {
2287
+ return fe(o) === "closed";
2288
+ },
2289
+ sessionInfo: m
2290
+ });
2291
+ break;
2292
+ }
2293
+ }
2294
+ }
2295
+ return o.onerror = (h) => {
2296
+ if (i)
2297
+ i.text().then(($) => {
2298
+ let w = { type: void 0, message: $ };
2299
+ try {
2300
+ w = JSON.parse($);
2301
+ } catch {
2302
+ }
2303
+ p({
2304
+ type: "error",
2305
+ error: new Se({
2306
+ status: i.status,
2307
+ body: w
2308
+ }),
2309
+ get readyState() {
2310
+ return fe(o);
2311
+ },
2312
+ get isClosed() {
2313
+ return fe(o) === "closed";
2314
+ },
2315
+ sessionInfo: m
2316
+ });
2317
+ });
2318
+ else {
2319
+ const $ = () => {
2320
+ p({
2321
+ type: "error",
2322
+ error: new Se({
2323
+ status: h.code || 500,
2324
+ body: {
2325
+ type: void 0,
2326
+ message: h.message || "Unknown error in subscribe query."
2327
+ }
2328
+ }),
2329
+ get readyState() {
2330
+ return fe(o);
2331
+ },
2332
+ get isClosed() {
2333
+ return fe(o) === "closed";
2334
+ },
2335
+ sessionInfo: m
2336
+ });
2337
+ };
2338
+ if (o.readyState === ee.CLOSED) {
2339
+ $();
2340
+ return;
2341
+ }
2342
+ setTimeout(() => {
2343
+ o.readyState !== ee.OPEN && $();
2344
+ }, 5e3);
2345
+ }
2346
+ }, o.onmessage = (h) => {
2347
+ I(JSON.parse(h.data));
2348
+ }, {
2349
+ close: () => {
2350
+ s = !0;
2351
+ for (const h of u)
2352
+ try {
2353
+ h();
2354
+ } catch ($) {
2355
+ console.error("Error in onClose callback", $);
2356
+ }
2357
+ o.close();
2358
+ },
2359
+ [Symbol.iterator]: () => {
2360
+ throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.");
2361
+ },
2362
+ get sessionInfo() {
2363
+ return m;
2364
+ },
2365
+ get readyState() {
2366
+ return fe(o);
2367
+ },
2368
+ get isClosed() {
2369
+ return fe(o) === "closed";
2370
+ },
2371
+ [Symbol.asyncIterator]: Si.bind(this, c, f, l, () => 1)
2372
+ };
2373
+ }
2374
+ var ue = {};
2375
+ Object.defineProperty(ue, "__esModule", { value: !0 });
2376
+ var Oi = ue.parseCookie = yn;
2377
+ ue.parse = yn;
2378
+ ue.stringifyCookie = xi;
2379
+ ue.stringifySetCookie = nt;
2380
+ ue.serialize = nt;
2381
+ ue.parseSetCookie = Ti;
2382
+ ue.stringifySetCookie = nt;
2383
+ ue.serialize = nt;
2384
+ const pn = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/, mn = /^[\u0021-\u003A\u003C-\u007E]*$/, $i = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i, ki = /^[\u0020-\u003A\u003D-\u007E]*$/, Ei = /^-?\d+$/, _i = Object.prototype.toString, Ci = /* @__PURE__ */ (() => {
2385
+ const e = function() {
2386
+ };
2387
+ return e.prototype = /* @__PURE__ */ Object.create(null), e;
2388
+ })();
2389
+ function yn(e, t) {
2390
+ const n = new Ci(), i = e.length;
2391
+ if (i < 2)
2392
+ return n;
2393
+ const s = (t == null ? void 0 : t.decode) || bn;
2394
+ let r = 0;
2395
+ do {
2396
+ const o = $t(e, r, i);
2397
+ if (o === -1)
2398
+ break;
2399
+ const a = Ot(e, r, i);
2400
+ if (o > a) {
2401
+ r = e.lastIndexOf(";", o - 1) + 1;
2402
+ continue;
2403
+ }
2404
+ const u = le(e, r, o);
2405
+ n[u] === void 0 && (n[u] = s(le(e, o + 1, a))), r = a + 1;
2406
+ } while (r < i);
2407
+ return n;
2408
+ }
2409
+ function xi(e, t) {
2410
+ const n = (t == null ? void 0 : t.encode) || encodeURIComponent, i = [];
2411
+ for (const s of Object.keys(e)) {
2412
+ const r = e[s];
2413
+ if (r === void 0)
2414
+ continue;
2415
+ if (!pn.test(s))
2416
+ throw new TypeError(`cookie name is invalid: ${s}`);
2417
+ const o = n(r);
2418
+ if (!mn.test(o))
2419
+ throw new TypeError(`cookie val is invalid: ${r}`);
2420
+ i.push(`${s}=${o}`);
2421
+ }
2422
+ return i.join("; ");
2423
+ }
2424
+ function nt(e, t, n) {
2425
+ const i = typeof e == "object" ? e : { ...n, name: e, value: String(t) }, s = typeof t == "object" ? t : n, r = (s == null ? void 0 : s.encode) || encodeURIComponent;
2426
+ if (!pn.test(i.name))
2427
+ throw new TypeError(`argument name is invalid: ${i.name}`);
2428
+ const o = i.value ? r(i.value) : "";
2429
+ if (!mn.test(o))
2430
+ throw new TypeError(`argument val is invalid: ${i.value}`);
2431
+ let a = i.name + "=" + o;
2432
+ if (i.maxAge !== void 0) {
2433
+ if (!Number.isInteger(i.maxAge))
2434
+ throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);
2435
+ a += "; Max-Age=" + i.maxAge;
2436
+ }
2437
+ if (i.domain) {
2438
+ if (!$i.test(i.domain))
2439
+ throw new TypeError(`option domain is invalid: ${i.domain}`);
2440
+ a += "; Domain=" + i.domain;
2441
+ }
2442
+ if (i.path) {
2443
+ if (!ki.test(i.path))
2444
+ throw new TypeError(`option path is invalid: ${i.path}`);
2445
+ a += "; Path=" + i.path;
2446
+ }
2447
+ if (i.expires) {
2448
+ if (!Ri(i.expires) || !Number.isFinite(i.expires.valueOf()))
2449
+ throw new TypeError(`option expires is invalid: ${i.expires}`);
2450
+ a += "; Expires=" + i.expires.toUTCString();
2451
+ }
2452
+ if (i.httpOnly && (a += "; HttpOnly"), i.secure && (a += "; Secure"), i.partitioned && (a += "; Partitioned"), i.priority)
2453
+ switch (typeof i.priority == "string" ? i.priority.toLowerCase() : void 0) {
2454
+ case "low":
2455
+ a += "; Priority=Low";
2456
+ break;
2457
+ case "medium":
2458
+ a += "; Priority=Medium";
2459
+ break;
2460
+ case "high":
2461
+ a += "; Priority=High";
2462
+ break;
2463
+ default:
2464
+ throw new TypeError(`option priority is invalid: ${i.priority}`);
2465
+ }
2466
+ if (i.sameSite)
2467
+ switch (typeof i.sameSite == "string" ? i.sameSite.toLowerCase() : i.sameSite) {
2468
+ case !0:
2469
+ case "strict":
2470
+ a += "; SameSite=Strict";
2471
+ break;
2472
+ case "lax":
2473
+ a += "; SameSite=Lax";
2474
+ break;
2475
+ case "none":
2476
+ a += "; SameSite=None";
2477
+ break;
2478
+ default:
2479
+ throw new TypeError(`option sameSite is invalid: ${i.sameSite}`);
2480
+ }
2481
+ return a;
2482
+ }
2483
+ function Ti(e, t) {
2484
+ const n = (t == null ? void 0 : t.decode) || bn, i = e.length, s = Ot(e, 0, i), r = $t(e, 0, s), o = r === -1 ? { name: "", value: n(le(e, 0, s)) } : {
2485
+ name: le(e, 0, r),
2486
+ value: n(le(e, r + 1, s))
2487
+ };
2488
+ let a = s + 1;
2489
+ for (; a < i; ) {
2490
+ const u = Ot(e, a, i), c = $t(e, a, u), l = c === -1 ? le(e, a, u) : le(e, a, c), f = c === -1 ? void 0 : le(e, c + 1, u);
2491
+ switch (l.toLowerCase()) {
2492
+ case "httponly":
2493
+ o.httpOnly = !0;
2494
+ break;
2495
+ case "secure":
2496
+ o.secure = !0;
2497
+ break;
2498
+ case "partitioned":
2499
+ o.partitioned = !0;
2500
+ break;
2501
+ case "domain":
2502
+ o.domain = f;
2503
+ break;
2504
+ case "path":
2505
+ o.path = f;
2506
+ break;
2507
+ case "max-age":
2508
+ f && Ei.test(f) && (o.maxAge = Number(f));
2509
+ break;
2510
+ case "expires":
2511
+ if (!f)
2512
+ break;
2513
+ const m = new Date(f);
2514
+ Number.isFinite(m.valueOf()) && (o.expires = m);
2515
+ break;
2516
+ case "priority":
2517
+ if (!f)
2518
+ break;
2519
+ const p = f.toLowerCase();
2520
+ (p === "low" || p === "medium" || p === "high") && (o.priority = p);
2521
+ break;
2522
+ case "samesite":
2523
+ if (!f)
2524
+ break;
2525
+ const I = f.toLowerCase();
2526
+ (I === "lax" || I === "strict" || I === "none") && (o.sameSite = I);
2527
+ break;
2528
+ }
2529
+ a = u + 1;
2530
+ }
2531
+ return o;
2532
+ }
2533
+ function Ot(e, t, n) {
2534
+ const i = e.indexOf(";", t);
2535
+ return i === -1 ? n : i;
2536
+ }
2537
+ function $t(e, t, n) {
2538
+ const i = e.indexOf("=", t);
2539
+ return i < n ? i : -1;
2540
+ }
2541
+ function le(e, t, n) {
2542
+ let i = t, s = n;
2543
+ do {
2544
+ const r = e.charCodeAt(i);
2545
+ if (r !== 32 && r !== 9)
2546
+ break;
2547
+ } while (++i < s);
2548
+ for (; s > i; ) {
2549
+ const r = e.charCodeAt(s - 1);
2550
+ if (r !== 32 && r !== 9)
2551
+ break;
2552
+ s--;
2553
+ }
2554
+ return e.slice(i, s);
2555
+ }
2556
+ function bn(e) {
2557
+ if (e.indexOf("%") === -1)
2558
+ return e;
2559
+ try {
2560
+ return decodeURIComponent(e);
2561
+ } catch {
2562
+ return e;
2563
+ }
2564
+ }
2565
+ function Ri(e) {
2566
+ return _i.call(e) === "[object Date]";
2567
+ }
2568
+ function Ai(e) {
2569
+ return { ...{
2570
+ apiURI: "https://api.instantdb.com"
2571
+ }, ...e };
2572
+ }
2573
+ function Pi(e, t) {
2574
+ 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;
2575
+ }
2576
+ function ji(e, t) {
2577
+ if (!(t && ("token" in t || "guest" in t)) && !e.adminToken)
2578
+ 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`.");
2579
+ }
2580
+ function C(e, t) {
2581
+ ji(e, t);
2582
+ const { adminToken: n, appId: i } = e, s = {
2583
+ "content-type": "application/json",
2584
+ "app-id": i
2585
+ };
2586
+ return n && (s.authorization = `Bearer ${n}`), t ? Pi(s, t) : s;
2587
+ }
2588
+ function Mi() {
2589
+ return (
2590
+ // NextJS 13 onwards added a `__nextPatched` property to the fetch function
2591
+ fetch.__nextPatched && // NextJS 15 onwards _also_ added a global `next-patch` symbol.
2592
+ !globalThis[Symbol.for("next-patch")]
2593
+ );
2594
+ }
2595
+ function Ui() {
2596
+ return Mi() ? { cache: "no-store" } : {};
2597
+ }
2598
+ async function Di(e, t) {
2599
+ const n = await t.text();
2600
+ try {
2601
+ const i = JSON.parse(n);
2602
+ return e(new Se({ status: t.status, body: i }));
2603
+ } catch {
2604
+ return e(new Se({
2605
+ status: t.status,
2606
+ body: { type: void 0, message: n }
2607
+ }));
2608
+ }
2609
+ }
2610
+ async function R(e, t) {
2611
+ const n = Ui(), i = {
2612
+ ...(t == null ? void 0 : t.headers) || {},
2613
+ "Instant-Admin-Version": Re,
2614
+ "Instant-Core-Version": Re
2615
+ }, s = await fetch(e, { ...n, ...t, headers: i });
2616
+ if (s.status === 200) {
2617
+ const r = await s.json();
2618
+ return Promise.resolve(r);
2619
+ }
2620
+ return Di((r) => Promise.reject(r), s);
2621
+ }
2622
+ function Ni(e) {
2623
+ var t, n, gn;
2624
+ return t = class {
2625
+ constructor(r) {
2626
+ G(this, n);
2627
+ d(this, "source");
2628
+ d(this, "url");
2629
+ this.url = r, this.source = H(this, n, gn).call(this, r);
2630
+ }
2631
+ get onopen() {
2632
+ return this.source.onopen;
2633
+ }
2634
+ set onopen(r) {
2635
+ this.source.onopen = r;
2636
+ }
2637
+ get onmessage() {
2638
+ return this.source.onmessage;
2639
+ }
2640
+ set onmessage(r) {
2641
+ this.source.onmessage = r;
2642
+ }
2643
+ get onerror() {
2644
+ return this.source.onerror;
2645
+ }
2646
+ set onerror(r) {
2647
+ this.source.onerror = r;
2648
+ }
2649
+ get readyState() {
2650
+ return this.source.readyState;
2651
+ }
2652
+ close() {
2653
+ this.source.close();
2654
+ }
2655
+ }, n = new WeakSet(), gn = function(r) {
2656
+ return new ee(r, {
2657
+ fetch(a, u) {
2658
+ return fetch(a, {
2659
+ ...u,
2660
+ method: "POST",
2661
+ headers: e.headers,
2662
+ body: JSON.stringify({
2663
+ "inference?": e.inference,
2664
+ versions: {
2665
+ "@instantdb/admin": Re,
2666
+ "@instantdb/core": Re
2667
+ }
2668
+ })
2669
+ });
2670
+ }
2671
+ });
2672
+ }, d(t, "OPEN", ee.OPEN), d(t, "CONNECTING", ee.CONNECTING), d(t, "CLOSED", ee.CLOSED), t;
2673
+ }
2674
+ function Li(e) {
2675
+ var n, i;
2676
+ (!e.appId || !Te(e.appId)) && console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: " + JSON.stringify(e.appId));
2677
+ const t = {
2678
+ ...e,
2679
+ appId: (n = e.appId) == null ? void 0 : n.trim(),
2680
+ adminToken: (i = e.adminToken) == null ? void 0 : i.trim(),
2681
+ useDateObjects: e.useDateObjects ?? !1
2682
+ };
2683
+ return new kt(t);
2684
+ }
2685
+ function Bt(e) {
2686
+ return (Array.isArray(e) ? e : [e]).flatMap(Xn);
2687
+ }
2688
+ class Wi {
2689
+ constructor(t) {
2690
+ d(this, "config");
2691
+ this.config = t;
2692
+ }
2693
+ async getPresence(t, n) {
2694
+ return (await R(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`, {
2695
+ method: "GET",
2696
+ headers: C(this.config)
2697
+ })).sessions || {};
2698
+ }
2699
+ }
2700
+ class Fi {
2701
+ constructor(t) {
2702
+ d(this, "config");
2703
+ /**
2704
+ * Generates a magic code for the user with the given email.
2705
+ * This is useful if you want to use your own email provider
2706
+ * to send magic codes.
2707
+ *
2708
+ * @example
2709
+ * // Generate a magic code
2710
+ * const { code } = await db.auth.generateMagicCode({ email })
2711
+ * // Send the magic code to the user with your own email provider
2712
+ * await customEmailProvider.sendMagicCode(email, code)
2713
+ *
2714
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
2715
+ */
2716
+ d(this, "generateMagicCode", async (t) => R(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
2717
+ method: "POST",
2718
+ headers: C(this.config),
2719
+ body: JSON.stringify({ email: t })
2720
+ }));
2721
+ /**
2722
+ * Sends a magic code to the user with the given email.
2723
+ * This uses Instant's built-in email provider.
2724
+ *
2725
+ * @example
2726
+ * // Send an email to user with magic code
2727
+ * await db.auth.sendMagicCode({ email })
2728
+ *
2729
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
2730
+ */
2731
+ d(this, "sendMagicCode", async (t) => R(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
2732
+ method: "POST",
2733
+ headers: C(this.config),
2734
+ body: JSON.stringify({ email: t })
2735
+ }));
2736
+ /**
2737
+ * Verifies a magic code for the user with the given email.
2738
+ *
2739
+ * @example
2740
+ * const user = await db.auth.verifyMagicCode({ email, code })
2741
+ * console.log("Verified user:", user)
2742
+ *
2743
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
2744
+ */
2745
+ d(this, "verifyMagicCode", async (t, n) => {
2746
+ const { user: i } = await R(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2747
+ method: "POST",
2748
+ headers: C(this.config),
2749
+ body: JSON.stringify({ email: t, code: n })
2750
+ });
2751
+ return i;
2752
+ });
2753
+ /**
2754
+ * Verifies a given token and returns the associated user.
2755
+ *
2756
+ * This is often useful for writing custom endpoints, where you need
2757
+ * to authenticate users.
2758
+ *
2759
+ * @example
2760
+ * app.post('/custom_endpoint', async (req, res) => {
2761
+ * const user = await db.auth.verifyToken(req.headers['token'])
2762
+ * if (!user) {
2763
+ * return res.status(401).send('Uh oh, you are not authenticated')
2764
+ * }
2765
+ * // ...
2766
+ * })
2767
+ * @see https://instantdb.com/docs/backend#custom-endpoints
2768
+ */
2769
+ d(this, "verifyToken", async (t) => (await R(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
2770
+ method: "POST",
2771
+ headers: { "content-type": "application/json" },
2772
+ body: JSON.stringify({
2773
+ "app-id": this.config.appId,
2774
+ "refresh-token": t
2775
+ })
2776
+ })).user);
2777
+ /**
2778
+ * Retrieves an app user by id, email, or refresh token.
2779
+ *
2780
+ * @example
2781
+ * try {
2782
+ * const user = await db.auth.getUser({ email })
2783
+ * console.log("Found user:", user)
2784
+ * } catch (err) {
2785
+ * console.error("Failed to retrieve user:", err.message);
2786
+ * }
2787
+ *
2788
+ * @see https://instantdb.com/docs/backend#retrieve-a-user
2789
+ */
2790
+ d(this, "getUser", async (t) => {
2791
+ const n = Object.entries(t).map(([s, r]) => `${s}=${encodeURIComponent(r)}`).join("&");
2792
+ return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2793
+ method: "GET",
2794
+ headers: C(this.config)
2795
+ })).user;
2796
+ });
2797
+ /**
2798
+ * Deletes an app user by id, email, or refresh token.
2799
+ *
2800
+ * NB: This _only_ deletes the user; it does not delete all user data.
2801
+ * You will need to handle this manually.
2802
+ *
2803
+ * @example
2804
+ * try {
2805
+ * const deletedUser = await db.auth.deleteUser({ email })
2806
+ * console.log("Deleted user:", deletedUser)
2807
+ * } catch (err) {
2808
+ * console.error("Failed to delete user:", err.message);
2809
+ * }
2810
+ *
2811
+ * @see https://instantdb.com/docs/backend#delete-a-user
2812
+ */
2813
+ d(this, "deleteUser", async (t) => {
2814
+ const n = Object.entries(t).map(([s, r]) => `${s}=${r}`);
2815
+ return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2816
+ method: "DELETE",
2817
+ headers: C(this.config)
2818
+ })).deleted;
2819
+ });
2820
+ /**
2821
+ * Get instant user from Request
2822
+ *
2823
+ * Reads cookies and gets a validated user
2824
+ * @param req The request containing a cookie synced with createInstantRouteHandler
2825
+ * @param opts Allow disabling validation of refresh token
2826
+ */
2827
+ d(this, "getUserFromRequest", async (t, n) => {
2828
+ const i = t.headers.get("cookie") || "", s = Oi(i), r = "instant_user_" + this.config.appId;
2829
+ if (!s[r])
2830
+ return null;
2831
+ const o = s[r], a = JSON.parse(o);
2832
+ return a != null && a.refresh_token ? n != null && n.disableValidation ? a : await this.verifyToken(a.refresh_token) : null;
2833
+ });
2834
+ this.config = t, this.createToken = this.createToken.bind(this);
2835
+ }
2836
+ async createToken(t) {
2837
+ const n = typeof t == "string" ? { email: t } : t;
2838
+ return (await R(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
2839
+ method: "POST",
2840
+ headers: C(this.config),
2841
+ body: JSON.stringify(n)
2842
+ })).user.refresh_token;
2843
+ }
2844
+ async signOut(t) {
2845
+ const n = typeof t == "string" ? { email: t } : t, i = this.config;
2846
+ await R(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
2847
+ method: "POST",
2848
+ headers: C(i),
2849
+ body: JSON.stringify(n)
2850
+ });
2851
+ }
2852
+ }
2853
+ const qt = (e) => e && typeof e == "object" && typeof e.pipe == "function" && typeof e.read == "function", zi = (e) => e && typeof e.getReader == "function";
2854
+ class Kt {
2855
+ constructor(t, n) {
2856
+ d(this, "config");
2857
+ d(this, "impersonationOpts");
2858
+ /**
2859
+ * Uploads file at the provided path. Accepts a Buffer or a Readable stream.
2860
+ *
2861
+ * @see https://instantdb.com/docs/storage
2862
+ * @example
2863
+ * const buffer = fs.readFileSync('demo.png');
2864
+ * const isSuccess = await db.storage.uploadFile('photos/demo.png', buffer);
2865
+ */
2866
+ d(this, "uploadFile", async (t, n, i = {}) => {
2867
+ const s = {
2868
+ ...C(this.config, this.impersonationOpts),
2869
+ path: t
2870
+ };
2871
+ i.contentDisposition && (s["content-disposition"] = i.contentDisposition), delete s["content-type"], i.contentType && (s["content-type"] = i.contentType);
2872
+ let r;
2873
+ if (qt(n) && (r = "half"), qt(n) || zi(n)) {
2874
+ if (!i.fileSize)
2875
+ throw new Error("fileSize is required in metadata when uploading streams");
2876
+ s["content-length"] = i.fileSize.toString();
2877
+ }
2878
+ let o = {
2879
+ method: "PUT",
2880
+ headers: s,
2881
+ body: n,
2882
+ ...r && { duplex: r }
2883
+ };
2884
+ return R(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`, o);
2885
+ });
2886
+ /**
2887
+ * Deletes a file by its path name (e.g. "photos/demo.png").
2888
+ *
2889
+ * @deprecated Use `db.transact` to delete files instead:
2890
+ * @example
2891
+ * // Delete by id
2892
+ * await db.transact(db.tx.$files[fileId].delete());
2893
+ *
2894
+ * // Delete by path
2895
+ * await db.transact(db.tx.$files[lookup('path', 'photos/demo.png')].delete());
2896
+ *
2897
+ * @see https://instantdb.com/docs/storage
2898
+ */
2899
+ d(this, "delete", async (t) => R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2900
+ method: "DELETE",
2901
+ headers: C(this.config, this.impersonationOpts)
2902
+ }));
2903
+ /**
2904
+ * Deletes multiple files by their path names.
2905
+ *
2906
+ * @deprecated Use `db.transact` to delete files instead:
2907
+ * @example
2908
+ * // Delete multiple files by path
2909
+ * const paths = ['images/1.png', 'images/2.png', 'images/3.png'];
2910
+ * await db.transact(paths.map(p => db.tx.$files[lookup('path', p)].delete()));
2911
+ *
2912
+ * @see https://instantdb.com/docs/storage
2913
+ */
2914
+ d(this, "deleteMany", async (t) => R(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
2915
+ method: "POST",
2916
+ headers: C(this.config, this.impersonationOpts),
2917
+ body: JSON.stringify({ filenames: t })
2918
+ }));
2919
+ /**
2920
+ * @deprecated. This method will be removed in the future. Use `uploadFile`
2921
+ * instead
2922
+ */
2923
+ d(this, "upload", async (t, n, i = {}) => {
2924
+ const { data: s } = await R(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
2925
+ method: "POST",
2926
+ headers: C(this.config),
2927
+ body: JSON.stringify({
2928
+ app_id: this.config.appId,
2929
+ filename: t
2930
+ })
2931
+ }), r = {}, o = i.contentType;
2932
+ o && (r["Content-Type"] = o);
2933
+ const { ok: a } = await fetch(s, {
2934
+ method: "PUT",
2935
+ body: n,
2936
+ headers: r
2937
+ });
2938
+ return a;
2939
+ });
2940
+ /**
2941
+ * @deprecated. This method will be removed in the future. Use `query` instead
2942
+ * @example
2943
+ * const files = await db.query({ $files: {}})
2944
+ */
2945
+ d(this, "list", async () => {
2946
+ const { data: t } = await R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
2947
+ method: "GET",
2948
+ headers: C(this.config)
2949
+ });
2950
+ return t;
2951
+ });
2952
+ /**
2953
+ * @deprecated. getDownloadUrl will be removed in the future.
2954
+ * Use `query` instead to query and fetch for valid urls
2955
+ *
2956
+ * db.useQuery({
2957
+ * $files: {
2958
+ * $: {
2959
+ * where: {
2960
+ * path: "moop.png"
2961
+ * }
2962
+ * }
2963
+ * }
2964
+ * })
2965
+ */
2966
+ d(this, "getDownloadUrl", async (t) => {
2967
+ const { data: n } = await R(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2968
+ method: "GET",
2969
+ headers: C(this.config)
2970
+ });
2971
+ return n;
2972
+ });
2973
+ this.config = t, this.impersonationOpts = n;
2974
+ }
2975
+ }
2976
+ var xe;
2977
+ class Vi {
2978
+ constructor(t) {
2979
+ G(this, xe);
2980
+ /**
2981
+ * Creates a new ReadableStream for the given clientId.
2982
+ *
2983
+ * @example
2984
+ * const stream = db.streams.createReadStream({clientId: clientId})
2985
+ * for await (const chunk of stream) {
2986
+ * console.log(chunk);
2987
+ * }
2988
+ */
2989
+ d(this, "createReadStream", (t) => b(this, xe).call(this).createReadStream(t));
2990
+ /**
2991
+ * Creates a new WritableStream for the given clientId.
2992
+ *
2993
+ * @example
2994
+ * const writeStream = db.streams.createWriteStream({clientId: clientId})
2995
+ * const writer = writeStream.getWriter();
2996
+ * writer.write('Hello world');
2997
+ * writer.close();
2998
+ */
2999
+ d(this, "createWriteStream", (t) => b(this, xe).call(this).createWriteStream(t));
3000
+ oe(this, xe, t);
3001
+ }
3002
+ }
3003
+ xe = new WeakMap();
3004
+ function Ji(e) {
3005
+ return {
3006
+ info: e ? (...t) => console.info(...t) : () => {
3007
+ },
3008
+ debug: e ? (...t) => console.debug(...t) : () => {
3009
+ },
3010
+ error: e ? (...t) => console.error(...t) : () => {
3011
+ }
3012
+ };
3013
+ }
3014
+ var U, ge, N, L, A, wn, Be, Sn, In, vn, Ye, Ze, et, Et, On, tt;
3015
+ const At = class At {
3016
+ constructor(t) {
3017
+ G(this, A);
3018
+ d(this, "config");
3019
+ d(this, "auth");
3020
+ d(this, "storage");
3021
+ d(this, "streams");
3022
+ d(this, "rooms");
3023
+ d(this, "impersonationOpts");
3024
+ G(this, U, null);
3025
+ G(this, ge, 0);
3026
+ G(this, N, null);
3027
+ G(this, L);
3028
+ d(this, "tx", an());
3029
+ /**
3030
+ * Sometimes you want to scope queries to a specific user.
3031
+ *
3032
+ * You can provide a user's auth token, email, or impersonate a guest.
3033
+ *
3034
+ * @see https://instantdb.com/docs/backend#impersonating-users
3035
+ * @example
3036
+ * await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} })
3037
+ */
3038
+ d(this, "asUser", (t) => {
3039
+ const n = new At({
3040
+ ...this.config
3041
+ });
3042
+ return n.impersonationOpts = t, n.storage = new Kt(this.config, t), n;
3043
+ });
3044
+ /**
3045
+ * Use this to query your data!
3046
+ *
3047
+ * @see https://instantdb.com/docs/instaql
3048
+ *
3049
+ * @example
3050
+ * // fetch all goals
3051
+ * await db.query({ goals: {} })
3052
+ *
3053
+ * // goals where the title is "Get Fit"
3054
+ * await db.query({ goals: { $: { where: { title: "Get Fit" } } } })
3055
+ *
3056
+ * // all goals, _alongside_ their todos
3057
+ * await db.query({ goals: { todos: {} } })
3058
+ */
3059
+ d(this, "query", (t, n = {}) => {
3060
+ t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t }), this.config.disableValidation || Lt(t, this.config.schema);
3061
+ const i = n.fetchOpts || {}, s = i.headers || {};
3062
+ return R(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
3063
+ ...i,
3064
+ method: "POST",
3065
+ headers: {
3066
+ ...s,
3067
+ ...C(this.config, this.impersonationOpts)
3068
+ },
3069
+ body: JSON.stringify({
3070
+ query: t,
3071
+ "inference?": !!this.config.schema
3072
+ })
3073
+ });
3074
+ });
3075
+ /**
3076
+ * Use this to write data! You can create, update, delete, and link objects
3077
+ *
3078
+ * @see https://instantdb.com/docs/instaml
3079
+ *
3080
+ * @example
3081
+ * // Create a new object in the `goals` namespace
3082
+ * const goalId = id();
3083
+ * db.transact(db.tx.goals[goalId].update({title: "Get fit"}))
3084
+ *
3085
+ * // Update the title
3086
+ * db.transact(db.tx.goals[goalId].update({title: "Get super fit"}))
3087
+ *
3088
+ * // Delete it
3089
+ * db.transact(db.tx.goals[goalId].delete())
3090
+ *
3091
+ * // Or create an association:
3092
+ * todoId = id();
3093
+ * db.transact([
3094
+ * db.tx.todos[todoId].update({ title: 'Go on a run' }),
3095
+ * db.tx.goals[goalId].link({todos: todoId}),
3096
+ * ])
3097
+ */
3098
+ d(this, "transact", (t) => (this.config.disableValidation || oi(t, this.config.schema), R(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
3099
+ method: "POST",
3100
+ headers: C(this.config, this.impersonationOpts),
3101
+ body: JSON.stringify({
3102
+ steps: Bt(t),
3103
+ "throw-on-missing-attrs?": !!this.config.schema
3104
+ })
3105
+ })));
3106
+ /**
3107
+ * Like `query`, but returns debugging information
3108
+ * for permissions checks along with the result.
3109
+ * Useful for inspecting the values returned by the permissions checks.
3110
+ * Note, this will return debug information for *all* entities
3111
+ * that match the query's `where` clauses.
3112
+ *
3113
+ * Requires a user/guest context to be set with `asUser`,
3114
+ * since permissions checks are user-specific.
3115
+ *
3116
+ * Accepts an optional configuration object with a `rules` key.
3117
+ * The provided rules will override the rules in the database for the query.
3118
+ *
3119
+ * @see https://instantdb.com/docs/instaql
3120
+ *
3121
+ * @example
3122
+ * await db.asUser({ guest: true }).debugQuery(
3123
+ * { goals: {} },
3124
+ * { rules: { goals: { allow: { read: "auth.id != null" } } }
3125
+ * )
3126
+ */
3127
+ d(this, "debugQuery", async (t, n) => {
3128
+ t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t });
3129
+ const i = { query: t, "rules-override": n == null ? void 0 : n.rules };
3130
+ n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin);
3131
+ const s = await R(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
3132
+ method: "POST",
3133
+ headers: C(this.config, this.impersonationOpts),
3134
+ body: JSON.stringify(i)
3135
+ });
3136
+ return {
3137
+ result: s.result,
3138
+ checkResults: s["check-results"]
3139
+ };
3140
+ });
3141
+ /**
3142
+ * Like `transact`, but does not write to the database.
3143
+ * Returns debugging information for permissions checks.
3144
+ * Useful for inspecting the values returned by the permissions checks.
3145
+ *
3146
+ * Requires a user/guest context to be set with `asUser`,
3147
+ * since permissions checks are user-specific.
3148
+ *
3149
+ * Accepts an optional configuration object with a `rules` key.
3150
+ * The provided rules will override the rules in the database for the duration of the transaction.
3151
+ *
3152
+ * @example
3153
+ * const goalId = id();
3154
+ * db.asUser({ guest: true }).debugTransact(
3155
+ * [db.tx.goals[goalId].update({title: "Get fit"})],
3156
+ * { rules: { goals: { allow: { update: "auth.id != null" } } }
3157
+ * )
3158
+ */
3159
+ d(this, "debugTransact", (t, n) => {
3160
+ const i = {
3161
+ steps: Bt(t),
3162
+ "rules-override": n == null ? void 0 : n.rules,
3163
+ // @ts-expect-error because we're using a private API (for now)
3164
+ "dangerously-commit-tx": n == null ? void 0 : n.__dangerouslyCommit
3165
+ };
3166
+ return n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin), R(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
3167
+ method: "POST",
3168
+ headers: C(this.config, this.impersonationOpts),
3169
+ body: JSON.stringify(i)
3170
+ });
3171
+ });
3172
+ G(this, Ye, (t) => {
3173
+ var n;
3174
+ if (t.target !== b(this, U)) {
3175
+ b(this, L).info("[socket][open]", t.target.id, "skip; this is no longer the current transport");
3176
+ return;
3177
+ }
3178
+ b(this, L).info("[socket][open]", t.target.id), oe(this, ge, 0), (n = b(this, N)) == null || n.onConnectionStatusChange("authenticated");
3179
+ });
3180
+ G(this, Ze, (t) => {
3181
+ var n;
3182
+ if (t.target !== b(this, U)) {
3183
+ b(this, L).info("[socket][close]", t.target.id, "skip; this is no longer the current transport");
3184
+ return;
3185
+ }
3186
+ b(this, L).info("[socket][close]", t.target.id), (n = b(this, N)) == null || n.onConnectionStatusChange("closed"), b(this, U) && (oe(this, U, null), H(this, A, Et).call(this) || (setTimeout(() => H(this, A, Be).call(this), b(this, ge)), oe(this, ge, Math.min(15e3, Math.max(b(this, ge), 500) * 2))));
3187
+ });
3188
+ G(this, et, (t) => {
3189
+ var n;
3190
+ if (t.target !== b(this, U)) {
3191
+ b(this, L).info("[socket][error]", t.target.id, "skip; this is no longer the current transport");
3192
+ return;
3193
+ }
3194
+ b(this, L).info("[socket][error]", t.target.id), (n = b(this, N)) == null || n.onConnectionStatusChange("closed");
3195
+ });
3196
+ G(this, tt, (t) => {
3197
+ var i, s, r, o, a, u;
3198
+ if (t.target !== b(this, U)) {
3199
+ b(this, L).info("[socket][message]", t.target.id, "skip; this is no longer the current transport");
3200
+ return;
3201
+ }
3202
+ const n = t.message;
3203
+ switch (b(this, L).info("[receive]", n), n.op) {
3204
+ case "start-stream-ok": {
3205
+ (i = b(this, N)) == null || i.onStartStreamOk(n);
3206
+ break;
3207
+ }
3208
+ case "stream-flushed": {
3209
+ (s = b(this, N)) == null || s.onStreamFlushed(n);
3210
+ break;
3211
+ }
3212
+ case "append-failed": {
3213
+ (r = b(this, N)) == null || r.onAppendFailed(n);
3214
+ break;
3215
+ }
3216
+ case "stream-append": {
3217
+ (o = b(this, N)) == null || o.onStreamAppend(n);
3218
+ break;
3219
+ }
3220
+ case "error": {
3221
+ switch ((a = n["original-event"]) == null ? void 0 : a.op) {
3222
+ case "start-stream":
3223
+ case "append-stream":
3224
+ case "subscribe-stream":
3225
+ case "unsubscribe-stream": {
3226
+ (u = b(this, N)) == null || u.onRecieveError(n);
3227
+ break;
3228
+ }
3229
+ }
3230
+ break;
3231
+ }
3232
+ }
3233
+ H(this, A, On).call(this);
3234
+ });
3235
+ this.config = Ai(t), this.auth = new Fi(this.config), this.storage = new Kt(this.config, this.impersonationOpts), this.streams = new Vi(H(this, A, vn).bind(this)), this.rooms = new Wi(this.config), oe(this, L, Ji(!!this.config.verbose));
3236
+ }
3237
+ /**
3238
+ * Use this to to get a live view of your data!
3239
+ *
3240
+ * @see https://www.instantdb.com/docs/backend
3241
+ *
3242
+ * @example
3243
+ * // create a subscription to a query
3244
+ * const query = { goals: { $: { where: { title: "Get Fit" } } } }
3245
+ * const sub = db.subscribeQuery(query);
3246
+ *
3247
+ * // iterate through the results with an async iterator
3248
+ * for await (const payload of sub) {
3249
+ * if (payload.error) {
3250
+ * console.log(payload.error);
3251
+ * // Stop the subscription
3252
+ * sub.close();
3253
+ * } else {
3254
+ * console.log(payload.data);
3255
+ * }
3256
+ * }
3257
+ *
3258
+ * // Stop the subscription
3259
+ * sub.close();
3260
+ *
3261
+ * // Create a subscription with a callback
3262
+ * const sub = db.subscribeQuery(query, (payload) => {
3263
+ * if (payload.error) {
3264
+ * console.log(payload.error);
3265
+ * // Stop the subscription
3266
+ * sub.close();
3267
+ * } else {
3268
+ * console.log(payload.data);
3269
+ * }
3270
+ * });
3271
+ */
3272
+ subscribeQuery(t, n, i = {}) {
3273
+ t && i && "ruleParams" in i && (t = { $$ruleParams: i.ruleParams, ...t }), this.config.disableValidation || Lt(t, this.config.schema);
3274
+ const o = {
3275
+ ...(i.fetchOpts || {}).headers || {},
3276
+ ...C(this.config, this.impersonationOpts)
3277
+ }, a = !!this.config.schema;
3278
+ return vi(t, n, {
3279
+ headers: o,
3280
+ inference: a,
3281
+ apiURI: this.config.apiURI
3282
+ });
3283
+ }
3284
+ };
3285
+ U = new WeakMap(), ge = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A = new WeakSet(), wn = function() {
3286
+ b(this, U) && b(this, U).close();
3287
+ const t = {
3288
+ ...C(this.config, this.impersonationOpts)
3289
+ }, n = !!this.config.schema, i = Ni({ headers: t, inference: n }), s = new ci(i, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
3290
+ return s.onopen = b(this, Ye), s.onmessage = b(this, tt), s.onclose = b(this, Ze), s.onerror = b(this, et), oe(this, U, s), s;
3291
+ }, Be = function() {
3292
+ return b(this, U) || H(this, A, wn).call(this);
3293
+ }, Sn = function(t, n) {
3294
+ const i = H(this, A, Be).call(this);
3295
+ b(this, L).info("[send]", t, n, {
3296
+ isOpen: i.isOpen()
3297
+ }), i.isOpen() && i.send({ "client-event-id": t, ...n });
3298
+ }, In = function() {
3299
+ H(this, A, Be).call(this);
3300
+ const t = new di({
3301
+ WStream: this.config.WritableStream || WritableStream,
3302
+ RStream: this.config.ReadableStream || ReadableStream,
3303
+ trySend: (n, i) => {
3304
+ H(this, A, Sn).call(this, n, i);
3305
+ },
3306
+ log: b(this, L)
3307
+ });
3308
+ return oe(this, N, t), t;
3309
+ }, vn = function() {
3310
+ return b(this, N) || H(this, A, In).call(this);
3311
+ }, Ye = new WeakMap(), Ze = new WeakMap(), et = new WeakMap(), Et = function() {
3312
+ return !b(this, N) || !b(this, N).hasActiveStreams();
3313
+ }, On = function() {
3314
+ if (b(this, U) && H(this, A, Et).call(this)) {
3315
+ const t = b(this, U);
3316
+ b(this, L).info("cleaning up unused socket", t.id), oe(this, U, null), t.close();
3317
+ }
3318
+ }, tt = new WeakMap();
3319
+ let kt = At;
3320
+ var ft = {};
3321
+ function Ve(e) {
3322
+ let t = e;
3323
+ return new TransformStream({
3324
+ transform(n, i) {
3325
+ if (!t) {
3326
+ i.enqueue(n);
3327
+ return;
3328
+ }
3329
+ if (t > n.length) {
3330
+ t += n.length;
3331
+ return;
3332
+ }
3333
+ const s = n.slice(t);
3334
+ t = 0, i.enqueue(s);
3335
+ }
3336
+ });
3337
+ }
3338
+ function Bi(e) {
3339
+ const t = e.appId || ft.INSTANT_APP_ID;
3340
+ if (!t)
3341
+ throw new Error(
3342
+ "Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable."
3343
+ );
3344
+ const n = e.adminToken || ft.INSTANT_APP_ADMIN_TOKEN;
3345
+ if (!t)
3346
+ throw new Error(
3347
+ "Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable."
3348
+ );
3349
+ const i = e.apiURI || ft.INSTANT_API_URI, s = Li({
3350
+ appId: t,
3351
+ adminToken: n,
3352
+ apiURI: i
3353
+ });
3354
+ async function r(c, l, f) {
3355
+ const m = s.streams.createWriteStream({
3356
+ clientId: c,
3357
+ waitUntil: e.waitUntil ?? void 0
3358
+ });
3359
+ try {
3360
+ const p = await m.streamId();
3361
+ l().pipeTo(m);
3362
+ const g = s.streams.createReadStream({ streamId: p });
3363
+ return f ? g.pipeThrough(
3364
+ Ve(f)
3365
+ ) : g;
3366
+ } catch {
3367
+ const I = s.streams.createReadStream({ clientId: c });
3368
+ return f ? I.pipeThrough(
3369
+ Ve(f)
3370
+ ) : I;
3371
+ }
3372
+ }
3373
+ async function o(c, l) {
3374
+ const f = s.streams.createReadStream({ clientId: c });
3375
+ return l ? f.pipeThrough(Ve(l)) : f;
3376
+ }
3377
+ async function a(c, l, f) {
3378
+ const m = l(), p = s.streams.createWriteStream({
3379
+ clientId: c,
3380
+ waitUntil: e.waitUntil ?? void 0
3381
+ });
3382
+ await p.streamId(), m.pipeTo(p);
3383
+ const I = s.streams.createReadStream({ clientId: c });
3384
+ return f ? I.pipeThrough(Ve(f)) : I;
3385
+ }
3386
+ async function u(c) {
3387
+ var m;
3388
+ const l = await s.query({
3389
+ $streams: { $: { where: { clientId: c } } }
3390
+ }), f = (m = l == null ? void 0 : l.$streams) == null ? void 0 : m[0];
3391
+ return f != null && f.done ? "DONE" : f ? !0 : null;
3392
+ }
3393
+ return {
3394
+ resumableStream: r,
3395
+ resumeExistingStream: o,
3396
+ createNewResumableStream: a,
3397
+ hasExistingStream: u
3398
+ };
3399
+ }
3400
+ export {
3401
+ Bi as createResumableStreamContext
3402
+ };