@instantdb/resumable-stream 0.22.163 → 0.22.164-branch-extra-fields.23220124983.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,17 +1,17 @@
1
1
 
2
- > @instantdb/resumable-stream@0.22.163 build /home/runner/work/instant/instant/client/packages/resumable-stream
2
+ > @instantdb/resumable-stream@0.22.164-branch-extra-fields.23220124983.1 build /home/runner/work/instant/instant/client/packages/resumable-stream
3
3
  > rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports
4
4
 
5
5
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
6
6
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
7
7
 
8
- > @instantdb/resumable-stream@0.22.163 build:tshy
8
+ > @instantdb/resumable-stream@0.22.164-branch-extra-fields.23220124983.1 build:tshy
9
9
  > tshy
10
10
 
11
11
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
12
12
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
13
13
 
14
- > @instantdb/resumable-stream@0.22.163 build:standalone
14
+ > @instantdb/resumable-stream@0.22.164-branch-extra-fields.23220124983.1 build:standalone
15
15
  > vite build
16
16
 
17
17
  vite v5.4.14 building for production...
@@ -19,17 +19,17 @@ transforming...
19
19
  ✓ 73 modules transformed.
20
20
  rendering chunks...
21
21
  computing gzip size...
22
- dist/standalone/index.umd.cjs 66.85 kB │ gzip: 21.04 kB
23
- dist/standalone/index.js 106.21 kB │ gzip: 27.79 kB
24
- ✓ built in 1.12s
22
+ dist/standalone/index.umd.cjs 67.04 kB │ gzip: 21.12 kB
23
+ dist/standalone/index.js 106.47 kB │ gzip: 27.88 kB
24
+ ✓ built in 1.14s
25
25
  npm warn Unknown env config "verify-deps-before-run". This will stop working in the next major version of npm.
26
26
  npm warn Unknown user config "always-auth". This will stop working in the next major version of npm.
27
27
 
28
- > @instantdb/resumable-stream@0.22.163 check-exports
28
+ > @instantdb/resumable-stream@0.22.164-branch-extra-fields.23220124983.1 check-exports
29
29
  > attw --pack .
30
30
 
31
31
 
32
- @instantdb/resumable-stream v0.22.163
32
+ @instantdb/resumable-stream v0.22.164-branch-extra-fields.23220124983.1
33
33
 
34
34
  Build tools:
35
35
  - @arethetypeswrong/cli@^0.17.4
@@ -2,12 +2,12 @@ var _n = Object.defineProperty;
2
2
  var Mt = (e) => {
3
3
  throw TypeError(e);
4
4
  };
5
- var Cn = (e, t, n) => t in e ? _n(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
6
- var l = (e, t, n) => Cn(e, typeof t != "symbol" ? t + "" : t, n), ot = (e, t, n) => t.has(e) || Mt("Cannot " + n);
5
+ var xn = (e, t, n) => t in e ? _n(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
6
+ var l = (e, t, n) => xn(e, typeof t != "symbol" ? t + "" : t, n), ot = (e, t, n) => t.has(e) || Mt("Cannot " + n);
7
7
  var g = (e, t, n) => (ot(e, t, "read from private field"), n ? n.call(e) : t.get(e)), Q = (e, t, n) => t.has(e) ? Mt("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), ae = (e, t, n, i) => (ot(e, t, "write to private field"), i ? i.call(e, n) : t.set(e, n), n), G = (e, t, n) => (ot(e, t, "access private method"), n);
8
- const xn = /^(?:[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;
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
9
  function Pe(e) {
10
- return typeof e == "string" && xn.test(e);
10
+ return typeof e == "string" && Cn.test(e);
11
11
  }
12
12
  const j = [];
13
13
  for (let e = 0; e < 256; ++e)
@@ -43,7 +43,7 @@ const T = {
43
43
  }, Zt = Symbol.for("__MUTATIVE_PROXY_DRAFT__"), Je = Symbol.iterator, Z = {
44
44
  mutable: "mutable",
45
45
  immutable: "immutable"
46
- }, xt = {};
46
+ }, Ct = {};
47
47
  function Ne(e, t) {
48
48
  return e instanceof Map ? e.has(t) : Object.prototype.hasOwnProperty.call(e, t);
49
49
  }
@@ -430,7 +430,7 @@ const qe = (e, t, n = !1) => {
430
430
  const i = k(this), s = J(i).get(e), r = ((n = (t = i.options).mark) === null || n === void 0 ? void 0 : n.call(t, s, Z)) === Z.mutable;
431
431
  if (i.options.strict && qe(s, i.options, r), r || i.finalized || !$e(s, i.options) || s !== i.original.get(e))
432
432
  return s;
433
- const o = xt.createDraft({
433
+ const o = Ct.createDraft({
434
434
  original: s,
435
435
  parentDraft: i,
436
436
  key: e,
@@ -483,7 +483,7 @@ const qe = (e, t, n = !1) => {
483
483
  let a = e.setMap.get(o);
484
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
485
  if (e.options.strict && qe(o, e.options, c), !c && !u && $e(o, e.options) && !e.finalized && e.original.has(o)) {
486
- const d = xt.createDraft({
486
+ const d = Ct.createDraft({
487
487
  original: o,
488
488
  parentDraft: e,
489
489
  key: o,
@@ -719,9 +719,9 @@ function an(e) {
719
719
  }
720
720
  return u;
721
721
  }
722
- xt.createDraft = an;
722
+ Ct.createDraft = an;
723
723
  Object.prototype.constructor.toString();
724
- function xe() {
724
+ function Ce() {
725
725
  return jn();
726
726
  }
727
727
  function Gn(e, t) {
@@ -834,7 +834,7 @@ class Oe extends H {
834
834
  }
835
835
  }
836
836
  typeof window < "u" && typeof window.localStorage < "u" && (window.localStorage.getItem("devBackend"), window.localStorage.getItem("__instantLogging"), window.localStorage.getItem("__devtoolLocalDash"));
837
- const je = "v0.22.163";
837
+ const je = "v0.22.164-branch-extra-fields.23220124983.1";
838
838
  class ue {
839
839
  constructor(t, n, i, s = { indexed: !1, unique: !1 }) {
840
840
  l(this, "valueType");
@@ -882,7 +882,9 @@ const Wt = [
882
882
  "first",
883
883
  "offset",
884
884
  "after",
885
+ "afterInclusive",
885
886
  "before",
887
+ "beforeInclusive",
886
888
  "fields",
887
889
  "aggregate"
888
890
  ], Zn = (e) => e.valueType || "unknown", fn = (e, t, n = !1) => {
@@ -1020,7 +1022,9 @@ const Wt = [
1020
1022
  // 'limit', // only supported client side
1021
1023
  "offset",
1022
1024
  "before",
1025
+ "beforeInclusive",
1023
1026
  "after",
1027
+ "afterInclusive",
1024
1028
  "first",
1025
1029
  "last"
1026
1030
  ];
@@ -1258,7 +1262,7 @@ var Jt;
1258
1262
  function fi({ WStream: e, opts: t, startStream: n, appendStream: i, registerStream: s }) {
1259
1263
  const r = t.clientId;
1260
1264
  let o = null, a = null, u = null;
1261
- const c = xe();
1265
+ const c = Ce();
1262
1266
  let d = !1, f = !1;
1263
1267
  const m = [], y = [], I = [];
1264
1268
  let w = !1, h = 0, O = 0;
@@ -1509,7 +1513,7 @@ function di({ RStream: e, opts: t, startStream: n, cancelStream: i }) {
1509
1513
  }
1510
1514
  let I = 0;
1511
1515
  async function w(b, $) {
1512
- u = xe();
1516
+ u = Ce();
1513
1517
  const q = { ...b || {}, eventId: u };
1514
1518
  for await (const P of n(q)) {
1515
1519
  if (r)
@@ -1650,7 +1654,7 @@ class hi {
1650
1654
  }), n;
1651
1655
  }
1652
1656
  startWriteStream(t) {
1653
- const n = xe();
1657
+ const n = Ce();
1654
1658
  let i = null;
1655
1659
  const s = new Promise((o) => {
1656
1660
  i = o;
@@ -1674,7 +1678,7 @@ class hi {
1674
1678
  offset: s,
1675
1679
  done: !!i
1676
1680
  };
1677
- r && (o["abort-reason"] = r), this.trySend(xe(), o);
1681
+ r && (o["abort-reason"] = r), this.trySend(Ce(), o);
1678
1682
  }
1679
1683
  onAppendFailed(t) {
1680
1684
  const n = this.writeStreams[t["stream-id"]];
@@ -1709,7 +1713,7 @@ class hi {
1709
1713
  op: "unsubscribe-stream",
1710
1714
  "subscribe-event-id": t
1711
1715
  };
1712
- this.trySend(xe(), n), delete this.readStreamIterators[t];
1716
+ this.trySend(Ce(), n), delete this.readStreamIterators[t];
1713
1717
  }
1714
1718
  onStreamAppend(t) {
1715
1719
  var s;
@@ -1949,11 +1953,11 @@ function Ht(e) {
1949
1953
  }
1950
1954
  var mn = (e) => {
1951
1955
  throw TypeError(e);
1952
- }, Pt = (e, t, n) => t.has(e) || mn("Cannot " + n), S = (e, t, n) => (Pt(e, t, "read from private field"), n ? n.call(e) : t.get(e)), x = (e, t, n) => t.has(e) ? mn("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), _ = (e, t, n, i) => (Pt(e, t, "write to private field"), t.set(e, n), n), ce = (e, t, n) => (Pt(e, t, "access private method"), n), V, we, ke, He, Xe, Le, Ce, We, he, Ee, Re, _e, Ue, Y, gt, wt, St, Bt, It, vt, De, Ot, $t;
1956
+ }, Pt = (e, t, n) => t.has(e) || mn("Cannot " + n), S = (e, t, n) => (Pt(e, t, "read from private field"), n ? n.call(e) : t.get(e)), C = (e, t, n) => t.has(e) ? mn("Cannot add the same private member more than once") : t instanceof WeakSet ? t.add(e) : t.set(e, n), _ = (e, t, n, i) => (Pt(e, t, "write to private field"), t.set(e, n), n), ce = (e, t, n) => (Pt(e, t, "access private method"), n), V, we, ke, He, Xe, Le, xe, We, he, Ee, Re, _e, Ue, Y, gt, wt, St, Bt, It, vt, De, Ot, $t;
1953
1957
  class te extends EventTarget {
1954
1958
  constructor(t, n) {
1955
1959
  var i, s;
1956
- super(), x(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, x(this, V), x(this, we), x(this, ke), x(this, He), x(this, Xe), x(this, Le), x(this, Ce), x(this, We, null), x(this, he), x(this, Ee), x(this, Re, null), x(this, _e, null), x(this, Ue, null), x(this, wt, async (r) => {
1960
+ super(), C(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, C(this, V), C(this, we), C(this, ke), C(this, He), C(this, Xe), C(this, Le), C(this, xe), C(this, We, null), C(this, he), C(this, Ee), C(this, Re, null), C(this, _e, null), C(this, Ue, null), C(this, wt, async (r) => {
1957
1961
  var o;
1958
1962
  S(this, Ee).reset();
1959
1963
  const { body: a, redirected: u, status: c, headers: d } = r;
@@ -1983,9 +1987,9 @@ class te extends EventTarget {
1983
1987
  const { done: w, value: h } = await y.read();
1984
1988
  h && S(this, Ee).feed(m.decode(h, { stream: !w })), w && (I = !1, S(this, Ee).reset(), ce(this, Y, Ot).call(this));
1985
1989
  } while (I);
1986
- }), x(this, St, (r) => {
1990
+ }), C(this, St, (r) => {
1987
1991
  _(this, he, void 0), !(r.name === "AbortError" || r.type === "aborted") && ce(this, Y, Ot).call(this, bt(r));
1988
- }), x(this, It, (r) => {
1992
+ }), C(this, It, (r) => {
1989
1993
  typeof r.id == "string" && _(this, We, r.id);
1990
1994
  const o = new MessageEvent(r.event || "message", {
1991
1995
  data: r.data,
@@ -1993,10 +1997,10 @@ class te extends EventTarget {
1993
1997
  lastEventId: r.id || ""
1994
1998
  });
1995
1999
  S(this, _e) && (!r.event || r.event === "message") && S(this, _e).call(this, o), this.dispatchEvent(o);
1996
- }), x(this, vt, (r) => {
2000
+ }), C(this, vt, (r) => {
1997
2001
  _(this, Le, r);
1998
- }), x(this, $t, () => {
1999
- _(this, Ce, void 0), S(this, V) === this.CONNECTING && ce(this, Y, gt).call(this);
2002
+ }), C(this, $t, () => {
2003
+ _(this, xe, void 0), S(this, V) === this.CONNECTING && ce(this, Y, gt).call(this);
2000
2004
  });
2001
2005
  try {
2002
2006
  if (t instanceof URL)
@@ -2081,10 +2085,10 @@ class te extends EventTarget {
2081
2085
  * @public
2082
2086
  */
2083
2087
  close() {
2084
- S(this, Ce) && clearTimeout(S(this, Ce)), S(this, V) !== this.CLOSED && (S(this, he) && S(this, he).abort(), _(this, V, this.CLOSED), _(this, he, void 0));
2088
+ S(this, xe) && clearTimeout(S(this, xe)), S(this, V) !== this.CLOSED && (S(this, he) && S(this, he).abort(), _(this, V, this.CLOSED), _(this, he, void 0));
2085
2089
  }
2086
2090
  }
2087
- V = /* @__PURE__ */ new WeakMap(), we = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), He = /* @__PURE__ */ new WeakMap(), Xe = /* @__PURE__ */ new WeakMap(), Le = /* @__PURE__ */ new WeakMap(), Ce = /* @__PURE__ */ new WeakMap(), We = /* @__PURE__ */ new WeakMap(), he = /* @__PURE__ */ new WeakMap(), Ee = /* @__PURE__ */ new WeakMap(), Re = /* @__PURE__ */ new WeakMap(), _e = /* @__PURE__ */ new WeakMap(), Ue = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakSet(), /**
2091
+ V = /* @__PURE__ */ new WeakMap(), we = /* @__PURE__ */ new WeakMap(), ke = /* @__PURE__ */ new WeakMap(), He = /* @__PURE__ */ new WeakMap(), Xe = /* @__PURE__ */ new WeakMap(), Le = /* @__PURE__ */ new WeakMap(), xe = /* @__PURE__ */ new WeakMap(), We = /* @__PURE__ */ new WeakMap(), he = /* @__PURE__ */ new WeakMap(), Ee = /* @__PURE__ */ new WeakMap(), Re = /* @__PURE__ */ new WeakMap(), _e = /* @__PURE__ */ new WeakMap(), Ue = /* @__PURE__ */ new WeakMap(), Y = /* @__PURE__ */ new WeakSet(), /**
2088
2092
  * Connect to the given URL and start receiving events
2089
2093
  *
2090
2094
  * @internal
@@ -2134,7 +2138,7 @@ Ot = function(e, t) {
2134
2138
  return;
2135
2139
  _(this, V, this.CONNECTING);
2136
2140
  const i = new Gt("error", { code: t, message: e });
2137
- (n = S(this, Re)) == null || n.call(this, i), this.dispatchEvent(i), _(this, Ce, setTimeout(S(this, $t), S(this, Le)));
2141
+ (n = S(this, Re)) == null || n.call(this, i), this.dispatchEvent(i), _(this, xe, setTimeout(S(this, $t), S(this, Le)));
2138
2142
  }, $t = /* @__PURE__ */ new WeakMap(), /**
2139
2143
  * ReadyState representing an EventSource currently trying to connect
2140
2144
  *
@@ -2225,7 +2229,7 @@ function qt(e) {
2225
2229
  }
2226
2230
  function Oi(e, t, n) {
2227
2231
  let i, s = !1;
2228
- const r = xe(), o = new te(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`, {
2232
+ const r = Ce(), o = new te(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`, {
2229
2233
  fetch(h, O) {
2230
2234
  return i = null, fetch(h, {
2231
2235
  ...O,
@@ -2390,13 +2394,13 @@ fe.serialize = nt;
2390
2394
  fe.parseSetCookie = Ri;
2391
2395
  fe.stringifySetCookie = nt;
2392
2396
  fe.serialize = nt;
2393
- const yn = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/, bn = /^[\u0021-\u003A\u003C-\u007E]*$/, ki = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i, Ei = /^[\u0020-\u003A\u003D-\u007E]*$/, _i = /^-?\d+$/, Ci = Object.prototype.toString, xi = /* @__PURE__ */ (() => {
2397
+ const yn = /^[\u0021-\u003A\u003C\u003E-\u007E]+$/, bn = /^[\u0021-\u003A\u003C-\u007E]*$/, ki = /^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i, Ei = /^[\u0020-\u003A\u003D-\u007E]*$/, _i = /^-?\d+$/, xi = Object.prototype.toString, Ci = /* @__PURE__ */ (() => {
2394
2398
  const e = function() {
2395
2399
  };
2396
2400
  return e.prototype = /* @__PURE__ */ Object.create(null), e;
2397
2401
  })();
2398
2402
  function gn(e, t) {
2399
- const n = new xi(), i = e.length;
2403
+ const n = new Ci(), i = e.length;
2400
2404
  if (i < 2)
2401
2405
  return n;
2402
2406
  const s = (t == null ? void 0 : t.decode) || wn;
@@ -2572,7 +2576,7 @@ function wn(e) {
2572
2576
  }
2573
2577
  }
2574
2578
  function Ai(e) {
2575
- return Ci.call(e) === "[object Date]";
2579
+ return xi.call(e) === "[object Date]";
2576
2580
  }
2577
2581
  function Pi(e) {
2578
2582
  return { ...{
@@ -2586,7 +2590,7 @@ function Mi(e, t) {
2586
2590
  if (!(t && ("token" in t || "guest" in t)) && !e.adminToken)
2587
2591
  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`.");
2588
2592
  }
2589
- function C(e, t) {
2593
+ function x(e, t) {
2590
2594
  Mi(e, t);
2591
2595
  const { adminToken: n, appId: i } = e, s = {
2592
2596
  "content-type": "application/json",
@@ -2702,7 +2706,7 @@ class Fi {
2702
2706
  async getPresence(t, n) {
2703
2707
  return (await R(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`, {
2704
2708
  method: "GET",
2705
- headers: C(this.config)
2709
+ headers: x(this.config)
2706
2710
  })).sessions || {};
2707
2711
  }
2708
2712
  }
@@ -2724,7 +2728,7 @@ class zi {
2724
2728
  */
2725
2729
  l(this, "generateMagicCode", async (t) => R(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
2726
2730
  method: "POST",
2727
- headers: C(this.config),
2731
+ headers: x(this.config),
2728
2732
  body: JSON.stringify({ email: t })
2729
2733
  }));
2730
2734
  /**
@@ -2739,7 +2743,7 @@ class zi {
2739
2743
  */
2740
2744
  l(this, "sendMagicCode", async (t) => R(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
2741
2745
  method: "POST",
2742
- headers: C(this.config),
2746
+ headers: x(this.config),
2743
2747
  body: JSON.stringify({ email: t })
2744
2748
  }));
2745
2749
  /**
@@ -2751,13 +2755,17 @@ class zi {
2751
2755
  *
2752
2756
  * @see https://instantdb.com/docs/backend#custom-magic-codes
2753
2757
  */
2754
- l(this, "verifyMagicCode", async (t, n) => {
2755
- const { user: i } = await R(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2758
+ l(this, "verifyMagicCode", async (t, n, i) => {
2759
+ const s = await R(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2756
2760
  method: "POST",
2757
- headers: C(this.config),
2758
- body: JSON.stringify({ email: t, code: n })
2761
+ headers: x(this.config),
2762
+ body: JSON.stringify({
2763
+ email: t,
2764
+ code: n,
2765
+ ...i != null && i.extraFields ? { "extra-fields": i.extraFields } : {}
2766
+ })
2759
2767
  });
2760
- return i;
2768
+ return { ...s.user, created: s.created };
2761
2769
  });
2762
2770
  /**
2763
2771
  * Verifies a given token and returns the associated user.
@@ -2800,7 +2808,7 @@ class zi {
2800
2808
  const n = Object.entries(t).map(([s, r]) => `${s}=${encodeURIComponent(r)}`).join("&");
2801
2809
  return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2802
2810
  method: "GET",
2803
- headers: C(this.config)
2811
+ headers: x(this.config)
2804
2812
  })).user;
2805
2813
  });
2806
2814
  /**
@@ -2823,7 +2831,7 @@ class zi {
2823
2831
  const n = Object.entries(t).map(([s, r]) => `${s}=${r}`);
2824
2832
  return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2825
2833
  method: "DELETE",
2826
- headers: C(this.config)
2834
+ headers: x(this.config)
2827
2835
  })).deleted;
2828
2836
  });
2829
2837
  /**
@@ -2846,7 +2854,7 @@ class zi {
2846
2854
  const n = typeof t == "string" ? { email: t } : t;
2847
2855
  return (await R(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
2848
2856
  method: "POST",
2849
- headers: C(this.config),
2857
+ headers: x(this.config),
2850
2858
  body: JSON.stringify(n)
2851
2859
  })).user.refresh_token;
2852
2860
  }
@@ -2854,7 +2862,7 @@ class zi {
2854
2862
  const n = typeof t == "string" ? { email: t } : t, i = this.config;
2855
2863
  await R(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
2856
2864
  method: "POST",
2857
- headers: C(i),
2865
+ headers: x(i),
2858
2866
  body: JSON.stringify(n)
2859
2867
  });
2860
2868
  }
@@ -2874,7 +2882,7 @@ class Yt {
2874
2882
  */
2875
2883
  l(this, "uploadFile", async (t, n, i = {}) => {
2876
2884
  const s = {
2877
- ...C(this.config, this.impersonationOpts),
2885
+ ...x(this.config, this.impersonationOpts),
2878
2886
  path: t
2879
2887
  };
2880
2888
  i.contentDisposition && (s["content-disposition"] = i.contentDisposition), delete s["content-type"], i.contentType && (s["content-type"] = i.contentType);
@@ -2907,7 +2915,7 @@ class Yt {
2907
2915
  */
2908
2916
  l(this, "delete", async (t) => R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2909
2917
  method: "DELETE",
2910
- headers: C(this.config, this.impersonationOpts)
2918
+ headers: x(this.config, this.impersonationOpts)
2911
2919
  }));
2912
2920
  /**
2913
2921
  * Deletes multiple files by their path names.
@@ -2922,7 +2930,7 @@ class Yt {
2922
2930
  */
2923
2931
  l(this, "deleteMany", async (t) => R(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
2924
2932
  method: "POST",
2925
- headers: C(this.config, this.impersonationOpts),
2933
+ headers: x(this.config, this.impersonationOpts),
2926
2934
  body: JSON.stringify({ filenames: t })
2927
2935
  }));
2928
2936
  /**
@@ -2932,7 +2940,7 @@ class Yt {
2932
2940
  l(this, "upload", async (t, n, i = {}) => {
2933
2941
  const { data: s } = await R(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
2934
2942
  method: "POST",
2935
- headers: C(this.config),
2943
+ headers: x(this.config),
2936
2944
  body: JSON.stringify({
2937
2945
  app_id: this.config.appId,
2938
2946
  filename: t
@@ -2954,7 +2962,7 @@ class Yt {
2954
2962
  l(this, "list", async () => {
2955
2963
  const { data: t } = await R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
2956
2964
  method: "GET",
2957
- headers: C(this.config)
2965
+ headers: x(this.config)
2958
2966
  });
2959
2967
  return t;
2960
2968
  });
@@ -2975,7 +2983,7 @@ class Yt {
2975
2983
  l(this, "getDownloadUrl", async (t) => {
2976
2984
  const { data: n } = await R(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2977
2985
  method: "GET",
2978
- headers: C(this.config)
2986
+ headers: x(this.config)
2979
2987
  });
2980
2988
  return n;
2981
2989
  });
@@ -3020,7 +3028,7 @@ function Qi(e) {
3020
3028
  }
3021
3029
  };
3022
3030
  }
3023
- var M, Ie, N, L, A, In, Be, vn, On, $n, Ye, Ze, et, Ct, kn, tt;
3031
+ var M, Ie, N, L, A, In, Be, vn, On, $n, Ye, Ze, et, xt, kn, tt;
3024
3032
  const jt = class jt {
3025
3033
  constructor(t) {
3026
3034
  Q(this, A);
@@ -3073,7 +3081,7 @@ const jt = class jt {
3073
3081
  method: "POST",
3074
3082
  headers: {
3075
3083
  ...s,
3076
- ...C(this.config, this.impersonationOpts)
3084
+ ...x(this.config, this.impersonationOpts)
3077
3085
  },
3078
3086
  body: JSON.stringify({
3079
3087
  query: t,
@@ -3106,7 +3114,7 @@ const jt = class jt {
3106
3114
  */
3107
3115
  l(this, "transact", (t) => (this.config.disableValidation || ai(t, this.config.schema), R(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
3108
3116
  method: "POST",
3109
- headers: C(this.config, this.impersonationOpts),
3117
+ headers: x(this.config, this.impersonationOpts),
3110
3118
  body: JSON.stringify({
3111
3119
  steps: Kt(t),
3112
3120
  "throw-on-missing-attrs?": !!this.config.schema
@@ -3139,7 +3147,7 @@ const jt = class jt {
3139
3147
  n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin);
3140
3148
  const s = await R(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
3141
3149
  method: "POST",
3142
- headers: C(this.config, this.impersonationOpts),
3150
+ headers: x(this.config, this.impersonationOpts),
3143
3151
  body: JSON.stringify(i)
3144
3152
  });
3145
3153
  return {
@@ -3174,7 +3182,7 @@ const jt = class jt {
3174
3182
  };
3175
3183
  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}`, {
3176
3184
  method: "POST",
3177
- headers: C(this.config, this.impersonationOpts),
3185
+ headers: x(this.config, this.impersonationOpts),
3178
3186
  body: JSON.stringify(i)
3179
3187
  });
3180
3188
  });
@@ -3192,7 +3200,7 @@ const jt = class jt {
3192
3200
  g(this, L).info("[socket][close]", t.target.id, "skip; this is no longer the current transport");
3193
3201
  return;
3194
3202
  }
3195
- g(this, L).info("[socket][close]", t.target.id), (n = g(this, N)) == null || n.onConnectionStatusChange("closed"), g(this, M) && (ae(this, M, null), G(this, A, Ct).call(this) || (setTimeout(() => G(this, A, Be).call(this), g(this, Ie)), ae(this, Ie, Math.min(15e3, Math.max(g(this, Ie), 500) * 2))));
3203
+ g(this, L).info("[socket][close]", t.target.id), (n = g(this, N)) == null || n.onConnectionStatusChange("closed"), g(this, M) && (ae(this, M, null), G(this, A, xt).call(this) || (setTimeout(() => G(this, A, Be).call(this), g(this, Ie)), ae(this, Ie, Math.min(15e3, Math.max(g(this, Ie), 500) * 2))));
3196
3204
  });
3197
3205
  Q(this, et, (t) => {
3198
3206
  var n;
@@ -3282,7 +3290,7 @@ const jt = class jt {
3282
3290
  t && i && "ruleParams" in i && (t = { $$ruleParams: i.ruleParams, ...t }), this.config.disableValidation || Ft(t, this.config.schema);
3283
3291
  const o = {
3284
3292
  ...(i.fetchOpts || {}).headers || {},
3285
- ...C(this.config, this.impersonationOpts)
3293
+ ...x(this.config, this.impersonationOpts)
3286
3294
  }, a = !!this.config.schema;
3287
3295
  return Oi(t, n, {
3288
3296
  headers: o,
@@ -3294,7 +3302,7 @@ const jt = class jt {
3294
3302
  M = new WeakMap(), Ie = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A = new WeakSet(), In = function() {
3295
3303
  g(this, M) && g(this, M).close();
3296
3304
  const t = {
3297
- ...C(this.config, this.impersonationOpts)
3305
+ ...x(this.config, this.impersonationOpts)
3298
3306
  }, n = !!this.config.schema, i = Li({ headers: t, inference: n }), s = new ui(i, `${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`, `${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);
3299
3307
  return s.onopen = g(this, Ye), s.onmessage = g(this, tt), s.onclose = g(this, Ze), s.onerror = g(this, et), ae(this, M, s), s;
3300
3308
  }, Be = function() {
@@ -3317,10 +3325,10 @@ M = new WeakMap(), Ie = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A =
3317
3325
  return ae(this, N, t), t;
3318
3326
  }, $n = function() {
3319
3327
  return g(this, N) || G(this, A, On).call(this);
3320
- }, Ye = new WeakMap(), Ze = new WeakMap(), et = new WeakMap(), Ct = function() {
3328
+ }, Ye = new WeakMap(), Ze = new WeakMap(), et = new WeakMap(), xt = function() {
3321
3329
  return !g(this, N) || !g(this, N).hasActiveStreams();
3322
3330
  }, kn = function() {
3323
- if (g(this, M) && G(this, A, Ct).call(this)) {
3331
+ if (g(this, M) && G(this, A, xt).call(this)) {
3324
3332
  const t = g(this, M);
3325
3333
  g(this, L).info("cleaning up unused socket", t.id), ae(this, M, null), t.close();
3326
3334
  }
@@ -1,5 +1,5 @@
1
- (function($,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):($=typeof globalThis<"u"?globalThis:$||self,_($.instant={}))})(this,function($){"use strict";var Qi=Object.defineProperty;var In=$=>{throw TypeError($)};var Gi=($,_,x)=>_ in $?Qi($,_,{enumerable:!0,configurable:!0,writable:!0,value:x}):$[_]=x;var l=($,_,x)=>Gi($,typeof _!="symbol"?_+"":_,x),Mt=($,_,x)=>_.has($)||In("Cannot "+x);var g=($,_,x)=>(Mt($,_,"read from private field"),x?x.call($):_.get($)),K=($,_,x)=>_.has($)?In("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add($):_.set($,x),he=($,_,x,R)=>(Mt($,_,"write to private field"),R?R.call($,x):_.set($,x),x),X=($,_,x)=>(Mt($,_,"access private method"),x);var Ue,N,Oe,W,F,U,On,st,$n,kn,En,et,tt,nt,Ut,_n,it;const _=/^(?:[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;function x(e){return typeof e=="string"&&_.test(e)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function Cn(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}let rt;const xn=new Uint8Array(16);function Tn(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(xn)}const Dt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Rn(e,t,n){var s;if(Dt.randomUUID&&!e)return Dt.randomUUID();e=e||{};const i=e.random??((s=e.rng)==null?void 0:s.call(e))??Tn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,Cn(i)}const P={Remove:"remove",Replace:"replace",Add:"add"},Nt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ot={};function De(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Lt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Wt(e){return Object.getPrototypeOf(e)===Set.prototype}function Ft(e){return Object.getPrototypeOf(e)===Map.prototype}function H(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function at(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[Nt]}function ct(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ge(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,Y))===Y.immutable||typeof n=="function")}function zt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=E(pe(n,e.key));if(i!==null&&(i==null?void 0:i.original)!==e.original)return null;const s=e.parent.type===3,r=s?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(s&&n.size>r||De(n,r)))return null;t.push(r)}if(e.parent)return zt(e.parent,t);t.reverse();try{An(e.copy,t)}catch{return null}return t}function Ne(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function pe(e,t){return Ne(e)===2?e.get(t):e[t]}function ut(e,t,n){Ne(e)===2?e.set(t,n):e[t]=n}function ft(e,t){const n=E(e);return(n?H(n):e)[t]}function we(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Se(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function An(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=pe(Ne(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Pn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const jn=Object.prototype.propertyIsEnumerable;function Mn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return Pn(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const i={};return Object.keys(e).forEach(s=>{i[s]=e[s]}),Object.getOwnPropertySymbols(e).forEach(s=>{jn.call(e,s)&&(i[s]=e[s])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function L(e){e.copy||(e.copy=Mn(e.original,e.options))}function Le(e){if(!ge(e))return ct(e);if(Array.isArray(e))return e.map(Le);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,s])=>[i,Le(s)]);if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Le);if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Le(e[n]);return t}function Ge(e){return at(e)?Le(e):e}function ie(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ie(e.parent))}function Un(e,t){const n=Ne(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const s of e)t(i,s,e),i+=1}else e.forEach((i,s)=>t(s,i,e))}function Vt(e,t,n){if(at(e)||!ge(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,s=i?new Map:void 0;if(t.add(e),Un(e,(r,o)=>{var a;if(at(o)){const u=E(o);L(u);const c=!((a=u.assignedMap)===null||a===void 0)&&a.size||u.operated?u.copy:u.original;ut(i?s:e,r,c)}else Vt(o,t,n)}),s){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(s.has(a)?s.get(a):a)})}}function Dn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Vt(pe(n,t),e.finalities.handledSet,e.options)}function lt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(ct(t))}))}function dt(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const r=zt(e);r&&t(e,r,n,i)}e.finalized=!0}}function ht(e,t,n,i){const s=E(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((r,o)=>{var a;const u=e.type===3?e.setMap:e.copy;if(we(pe(u,t),n)){let c=s.original;s.copy&&(c=s.copy),lt(e),dt(e,i,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(c,s.original)),ut(u,t,c)}}),e.options.enableAutoFreeze&&s.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ge(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;we(pe(r,t),n)&&Dn(e,t)})}function Nn(e,t,n,i,s){let{original:r,assignedMap:o,options:a}=e,u=e.copy;u.length<r.length&&([r,u]=[u,r],[n,i]=[i,n]);for(let c=0;c<r.length;c+=1)if(o.get(c.toString())&&u[c]!==r[c]){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Replace,path:f,value:Ge(u[c])}),i.push({op:P.Replace,path:f,value:Ge(r[c])})}for(let c=r.length;c<u.length;c+=1){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Add,path:f,value:Ge(u[c])})}if(r.length<u.length){const{arrayLengthAssignment:c=!0}=a.enablePatches;if(c){const d=t.concat(["length"]),f=Se(d,s);i.push({op:P.Replace,path:f,value:r.length})}else for(let d=u.length;r.length<d;d-=1){const f=t.concat([d-1]),m=Se(f,s);i.push({op:P.Remove,path:m})}}}function Ln({original:e,copy:t,assignedMap:n},i,s,r,o){n.forEach((a,u)=>{const c=pe(e,u),d=Ge(pe(t,u)),f=a?De(e,u)?P.Replace:P.Add:P.Remove;if(we(c,d)&&f===P.Replace)return;const m=i.concat(u),y=Se(m,o);s.push(f===P.Remove?{op:f,path:y}:{op:f,path:y,value:d}),r.push(f===P.Add?{op:P.Remove,path:y}:f===P.Remove?{op:P.Add,path:y,value:c}:{op:P.Replace,path:y,value:c})})}function Wn({original:e,copy:t},n,i,s,r){let o=0;e.forEach(a=>{if(!t.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Remove,path:c,value:a}),s.unshift({op:P.Add,path:c,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Add,path:c,value:a}),s.unshift({op:P.Remove,path:c,value:a})}o+=1})}function We(e,t,n,i){const{pathAsArray:s=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Ln(e,t,n,i,s);case 1:return Nn(e,t,n,i,s);case 3:return Wn(e,t,n,i,s)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ge(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},pt={get size(){return H(E(this)).size},has(e){return H(E(this)).has(e)},set(e,t){const n=E(this),i=H(n);return(!i.has(e)||!we(i.get(e),t))&&(L(n),ie(n),n.assignedMap.set(e,!0),n.copy.set(e,t),ht(n,e,t,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return L(t),ie(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){L(e),ie(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);H(n).forEach((i,s)=>{e.call(t,this.get(s),s,this)})},get(e){var t,n;const i=E(this),s=H(i).get(e),r=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,s,Y))===Y.mutable;if(i.options.strict&&He(s,i.options,r),r||i.finalized||!ge(s,i.options)||s!==i.original.get(e))return s;const o=ot.createDraft({original:s,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return L(i),i.copy.set(e,o),o},keys(){return H(E(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Qe](){return this.entries()}},Fn=Reflect.ownKeys(pt),Jt=(e,t,{isValuesIterator:n})=>()=>{var i,s;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const u=E(a),c=((s=(i=e.options).mark)===null||s===void 0?void 0:s.call(i,a,Y))===Y.mutable;if(e.options.strict&&He(o,e.options,c),!c&&!u&&ge(o,e.options)&&!e.finalized&&e.original.has(o)){const d=ot.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,d),a=d}else u&&(a=u.proxy);return{done:!1,value:n?a:[a,a]}},Be={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;L(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(L(t),ie(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),ht(t,e,e,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);L(t),ie(t);const n=E(e);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))},clear(){if(!this.size)return;const e=E(this);L(e),ie(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Jt(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Jt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Be,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const zn=Reflect.ownKeys(Be),Qt=new WeakSet,Gt={get(e,t,n){var i,s;const r=(i=e.copy)===null||i===void 0?void 0:i[t];if(r&&Qt.has(r))return r;if(t===Nt)return e;let o;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(c,Y),o===Y.mutable)return e.options.strict&&He(c,e.options,!0),c}const a=H(e);if(a instanceof Map&&Fn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(pt,"size").get.call(e.proxy);const c=pt[t];if(c)return c.bind(e.proxy)}if(a instanceof Set&&zn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const c=Be[t];if(c)return c.bind(e.proxy)}if(!De(a,t)){const c=Lt(a,t);return c?"value"in c?c.value:(s=c.get)===null||s===void 0?void 0:s.call(e.proxy):void 0}const u=a[t];if(e.options.strict&&He(u,e.options),e.finalized||!ge(u,e.options))return u;if(u===ft(e.original,t)){if(L(e),e.copy[t]=Ht({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return L(c),ie(c),c.copy}return e.copy[t]}return u},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(e.type===1&&t!=="length"&&!(Number.isInteger(s=Number(t))&&s>=0&&(t===0||s===0||String(s)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Lt(H(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ft(H(e),t),a=E(o);return a&&we(a.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(we(n,o)&&(n!==void 0||De(e.original,t))||(L(e),ie(e),De(e.original,t)&&we(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,ht(e,t,n,We)),!0)},has(e,t){return t in H(e)},ownKeys(e){return Reflect.ownKeys(H(e))},getOwnPropertyDescriptor(e,t){const n=H(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?Gt.set.call(this,e,t,void 0,e.proxy):(ft(e.original,t)!==void 0||t in e.original?(L(e),ie(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function Ht(e){const{original:t,parentDraft:n,key:i,finalities:s,options:r}=e,o=Ne(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:s,options:r,setMap:o===3?new Map(t.entries()):void 0};(i||"key"in e)&&(a.key=i);const{proxy:u,revoke:c}=Proxy.revocable(o===1?Object.assign([],a):a,Gt);if(s.revoke.push(c),Qt.add(u),a.proxy=u,n){const d=n;d.finalities.draft.push((f,m)=>{var y,I;const w=E(u);let h=d.type===3?d.setMap:d.copy;const O=pe(h,i),b=E(O);if(b){let k=b.original;b.operated&&(k=ct(O)),lt(b),dt(b,We,f,m),d.options.enableAutoFreeze&&(d.options.updatedValues=(y=d.options.updatedValues)!==null&&y!==void 0?y:new WeakMap,d.options.updatedValues.set(k,b.original)),ut(h,i,k)}(I=w.callbacks)===null||I===void 0||I.forEach(k=>{k(f,m)})})}else{const d=E(u);d.finalities.draft.push((f,m)=>{lt(d),dt(d,We,f,m)})}return u}ot.createDraft=Ht,Object.prototype.constructor.toString();function Ce(){return Rn()}function Vn(e,t){return e.localeCompare(t)}function Jn(){let e=Vn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Jn();function Qn(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Gn=Qn();function qe(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(s,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Gn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Hn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function Bt(e){return e.startsWith("lookup__")}function qt(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Bn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(s,r)=>qe(e,qt(Hn(s,r)),[]);if(n==="__etype")return e;const i=n;return Bt(i)?qe(e,qt(i),[]):qe(e,i,[])}})}function Kt(){return new Proxy({},{get(e,t){return Bn(t)}})}Kt();function qn(e){return e.__ops}class B extends Error{constructor(n,i,s){super(n);l(this,"hint");l(this,"traceId");this.hint=i,s&&(this.traceId=s);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class Ie extends B{constructor(n){var r;const i=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(i,n.body.hint,n.body["trace-id"]);l(this,"body");l(this,"status");const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,Ie),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const xe="v0.22.163";class oe{constructor(t,n,i,s={indexed:!1,unique:!1}){l(this,"valueType");l(this,"required");l(this,"isIndexed");l(this,"config");l(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=i,this.config=s}clientRequired(){return new oe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new oe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new oe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new oe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class C extends Error{constructor(t,n){const i=n?`At path '${n}': ${t}`:t;super(i),this.name="QueryValidationError"}}const Xt=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Kn=e=>e.valueType||"unknown",Yt=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Xn=(e,t,n,i,s,r,o)=>{const a=r.valueType==="json",u=(c,d,f)=>{if(!Yt(f,d,a))throw new C(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new C(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`,o);for(const c of t)u(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":u(e,n,t);break;case"$like":case"$ilike":if(u(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new C(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`,o);break;case"$isNull":u(e,"boolean",t);break;default:throw new C(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`,o)}},Te=(e,t,n,i,s)=>{const r=Kn(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const u=e;for(const[c,d]of Object.entries(u))Xn(c,d,r,t,i,n,`${s}.${c}`)}else if(!Yt(e,r,o))throw new C(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`,s)},Yn=(e,t,n,i,s)=>{const r=e.split(".");if(r.length<2)throw new C(`Invalid dot notation path '${e}'. Must contain at least one dot.`,s);let o=n;for(let d=0;d<r.length-1;d++){const f=r[d],m=i.entities[o];if(!m)throw new C(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,s);const y=m.links[f];if(!y){const I=Object.keys(m.links);throw new C(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length>0?I.join(", "):"none"}`,s)}o=y.entityName}const a=r[r.length-1],u=i.entities[o];if(!u)throw new C(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,s);if(a==="id"){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}const c=u.attrs[a];if(Object.keys(u.links).includes(a)){if(typeof t=="string"&&!x(t))throw new C(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}if(!c){const d=Object.keys(u.attrs);throw new C(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,s)}Te(t,e,c,n,s)},Zt=(e,t,n,i)=>{for(const[s,r]of Object.entries(e)){if(s==="or"||s==="and"){if(Array.isArray(r))for(const c of r)typeof c=="object"&&c!==null&&Zt(c,t,n,`${i}.${s}[${c}]`);continue}if(s==="id"){Te(r,"id",new oe("string",!1,!0),t,`${i}.id`);continue}if(s.includes(".")){Yn(s,r,t,n,`${i}.${s}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[s],u=o.links[s];if(!a&&!u){const c=Object.keys(o.attrs),d=Object.keys(o.links);throw new C(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${i}.${s}`)}if(a)Te(r,s,a,t,`${i}.${s}`);else if(u){if(typeof r=="string"&&!x(r))throw new C(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${i}.${s}`);const c=new oe("string",!1,!0);Te(r,s,c,t,`${i}.${s}`)}}},Zn=(e,t,n,i,s=0)=>{for(const o of Object.keys(e))if(!Xt.includes(o))throw new C(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Xt.join(", ")}. Found: ${o}`,i);const r=["offset","before","after","first","last"];for(const o of r)if(e[o]!==void 0&&s>0)throw new C(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,i);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new C(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,i?`${i}.where`:void 0);Zt(e.where,t,n,i?`${i}.where`:"where")}},en=(e,t,n,i,s=0)=>{var r;if(!e||typeof e!="object")throw new C(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,i);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const u=Object.keys(n.entities[t].links);throw new C(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length>0?u.join(", "):"none"}`,`${i}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const u=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;u&&en(a,u,n,`${i}.${o}`,s+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new C(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${i}.$`);Zn(a,t,n,`${i}.$`,s)}},tn=(e,t)=>{if(typeof e!="object"||e===null)throw new C(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new C(`Query must be an object, but received: ${typeof e}`);const n=e;for(const i of Object.keys(n)){if(Array.isArray(e[i]))throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(typeof i!="string")throw new C(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(i!=="$$ruleParams"){if(t&&!t.entities[i]){const s=Object.keys(t.entities);throw new C(`Entity '${i}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,i)}en(n[i],i,t,i,0)}}},nn=e=>typeof e!="string"?!1:Bt(e)?!0:x(e);class q extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const sn=e=>e.length>0?e.join(", "):"none",ei=(e,t)=>new q(`Entity '${e}' does not exist in schema. Available entities: ${sn(t)}`),mt={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},ti=(e,t)=>{var n;return e==null?!0:((n=mt[t.valueType])==null?void 0:n.call(mt,e))??!1},rn=(e,t)=>{const n=t.entities[e];if(!n)throw ei(e,Object.keys(t.entities));return n},yt=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(s==="id")continue;const o=i.attrs[s];if(o&&!ti(r,o))throw new q(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},on=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(!i.links[s]){const a=Object.keys(i.links);throw new q(`Link '${s}' does not exist on entity '${e}'. Available links: ${sn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!nn(a))throw new q(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!nn(r))throw new q(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},ni={create:yt,update:yt,merge:yt,link:on,unlink:on,delete:()=>{}},ii=(e,t)=>{if(!t)return;const[n,i,s,r]=e;if(!Array.isArray(s)&&!x(s))throw new q(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);if(typeof i!="string")throw new q(`Entity name must be a string, but received: ${typeof i}`);const o=ni[n];o&&r!==void 0&&o(i,r,t)},si=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const i of n){if(!i||typeof i!="object")throw new q(`Transaction chunk must be an object, but received: ${typeof i}`);if(!Array.isArray(i.__ops))throw new q(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);for(const s of i.__ops){if(!Array.isArray(s))throw new q(`Transaction operation must be an array, but received: ${typeof s}`);ii(s,t)}}};let ri=0;class oi{constructor(t,n,i){l(this,"type","sse");l(this,"initParams",null);l(this,"sendQueue",[]);l(this,"sendPromise");l(this,"closeFired",!1);l(this,"sseInitTimeout");l(this,"ES");l(this,"messageUrl");l(this,"conn");l(this,"url");l(this,"id");l(this,"onopen");l(this,"onmessage");l(this,"onclose");l(this,"onerror");this.id=`${this.type}_${ri++}`,this.url=n,this.messageUrl=i||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const r=JSON.parse(s.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=s=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}async postMessages(t){var n,i,s;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(i=this.initParams)==null?void 0:i.sessionId,sse_token:(s=this.initParams)==null?void 0:s.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(t){if(!this.isOpen()||!this.initParams)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.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var an;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(an||(an={}));function ai({WStream:e,opts:t,startStream:n,appendStream:i,registerStream:s}){const r=t.clientId;let o=null,a=null,u=null;const c=Ce();let d=!1,f=!1;const m=[],y=[],I=[];let w=!1,h=0,O=0;const b=[],k=new TextEncoder;function ee(){f=!0;for(const p of m)p(a??void 0)}function D(p){return m.push(p),f&&p(a??void 0),()=>{const v=m.indexOf(p);v!==-1&&m.splice(v,1)}}function z(p){return I.push(p),()=>{const v=I.indexOf(p);v!==-1&&I.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(p=>{I.push(p)}));function Q(){for(const p of I)try{p()}catch{}}function ue(p){return y.push(p),o&&p(o),()=>{const v=y.indexOf(p);v!==-1&&y.splice(v,1)}}function re(p){o=p;for(const v of y)v(o)}function $e(){w=!0}function At(p){let v=h,V=0,G=0;for(const{byteLen:ne}of b){const de=v+ne;if(de>p)break;v=de,V++,G+=ne}V>0&&(h+=G,O-=G,b.splice(0,V))}function te(p,v){a=v,ee(),p.error(v),Q()}async function fe(){const p=await n({clientId:r,reconnectToken:c,ruleParams:t.ruleParams});switch(p.type){case"ok":{const{streamId:v,offset:V}=p;o=v,At(V),b.length&&i({streamId:v,chunks:b.map(G=>G.chunk),offset:h}),w=!1;break}case"disconnect":{$e();break}case"error":{u&&te(u,p.error);break}}}function le(){$e(),fe()}function ke({offset:p,done:v}){At(p),v&&(d=!0,Q())}function Ee(p){return d?(te(p,new B("Stream has been closed.")),null):o||(te(p,new B("Stream has not been initialized.")),null)}async function Pt(p){u=p;let v=!0,V=0;for(;v;){let G=Date.now()+Math.min(15e3,500*(V-1));v=!1;const ne=await n({clientId:t.clientId,reconnectToken:c,ruleParams:t.ruleParams});switch(ne.type){case"ok":{const{streamId:de,offset:jt}=ne;if(jt!==0){const _e=new B("Write stream is corrupted");te(p,_e);return}re(de),s(de,{onDisconnect:$e,onFlush:ke,onConnectionReconnect:fe,onAppendFailed:le}),w=!1;return}case"disconnect":{v=!0,$e(),V++,await new Promise(de=>{setTimeout(de,Math.max(0,G-Date.now()))});break}case"error":{te(p,ne.error);return}}}}class Ji extends e{constructor(v,V){super(v,V)}async streamId(){return o||new Promise((v,V)=>{const G=[],ne=()=>{for(const _e of G)_e()},de=_e=>{v(_e),ne()},jt=_e=>{V(_e||new B("Stream is closed.")),ne()};G.push(ue(de)),G.push(D(jt))})}}return{stream:new Ji({async start(p){try{await Pt(p)}catch(v){te(p,v)}},write(p,v){const V=Ee(v);if(V){const G=k.encode(p).length;b.push({chunk:p,byteLen:G});const ne=h+O;O+=G,w||i({streamId:V,chunks:[p],offset:ne})}},close(){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0}):Q(),ee()},abort(p){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0,abortReason:p}):Q(),ee()}}),addCompleteCb:z,closed(){return f}}}class ci{constructor(){l(this,"items",[]);l(this,"resolvers",[]);l(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(i=>{this.resolvers.push(i)});if(n||!t)return;yield t}}}}function ui({RStream:e,opts:t,startStream:n,cancelStream:i}){let s=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let u,c=!1;const d=[];function f(){c=!0;for(const b of d)b()}function m(b){return d.push(b),()=>{const k=d.indexOf(b);k!==-1&&d.splice(k,1)}}function y(b,k){b.error(k),f()}let I=0;async function w(b,k){u=Ce();const ee={...b||{},eventId:u};for await(const D of n(ee)){if(r)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(k,D.error);return}if(D.offset>s){y(k,new B("Stream is corrupted.")),r=!0;return}let z=s-D.offset;if(D.files&&D.files.length){const Q=new AbortController;let ue=fetch(D.files[0].url,{signal:Q.signal});for(let re=0;re<D.files.length;re++){const $e=D.files[re+1],te=await ue;if($e&&(ue=fetch($e.url,{signal:Q.signal})),!te.ok){if(I++,I>10){y(k,new B("Unable to process stream."));return}return{retry:!0}}if(te.body){const fe=te.body.getReader();try{for(;;){const{done:le,value:ke}=await fe.read();if(le)break;if(r){Q.abort();return}let Ee=ke;if(z>0&&(Ee=ke.subarray(z),z-=ke.length-Ee.length),!Ee.length)continue;s+=Ee.length;const Pt=o.decode(Ee);k.enqueue(Pt)}}finally{fe.releaseLock()}}else{const fe=await te.arrayBuffer();let le=fe;if(r){Q.abort();return}if(z>0&&(le=new Uint8Array(fe).subarray(z),z-=fe.byteLength-le.length),!le.byteLength)continue;s+=le.byteLength;const ke=o.decode(le);k.enqueue(ke)}}}if(I=0,D.content){let Q=D.content,ue=a.encode(D.content);if(z>0){const re=ue.subarray(z);if(z-=ue.length-re.length,!re.length)continue;ue=re,Q=o.decode(re)}s+=ue.length,k.enqueue(Q)}}}async function h(b){let k=!0,ee=0;for(;k;){k=!1;let D=Date.now()+Math.min(15e3,500*(ee-1));const z=await w({...t,offset:s},b);z!=null&&z.retry&&(k=!0,ee++,D<Date.now()-3e5&&(ee=0),await new Promise(Q=>{setTimeout(Q,Math.max(0,D-Date.now()))}))}!r&&!c&&(b.close(),f())}return{stream:new e({start(b){h(b)},cancel(b){r=!0,u&&i({eventId:u}),f()}}),addCloseCb:m,closed(){return c}}}class fi{constructor({WStream:t,RStream:n,trySend:i,log:s}){l(this,"trySend");l(this,"WStream");l(this,"RStream");l(this,"writeStreams",{});l(this,"startWriteStreamCbs",{});l(this,"readStreamIterators",{});l(this,"log");l(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=i,this.log=s}createWriteStream(t){const{stream:n,addCompleteCb:i}=ai({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:i}=ui({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=Ce();let i=null;const s=new Promise(o=>{i=o});this.startWriteStreamCbs[n]=i;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),s}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:i,offset:s,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:s,done:!!i};r&&(o["abort-reason"]=r),this.trySend(Ce(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],i=this.writeStreams[n];if(!i){this.log.info("No stream cbs for stream-flushed",t);return}i.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:i,offset:s,ruleParams:r}){const o={op:"subscribe-stream"};if(!i&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");i&&(o["stream-id"]=i),n&&(o["client-id"]=n),s&&(o.offset=s),r&&(o["rule-params"]=r);const a=new ci;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(Ce(),n),delete this.readStreamIterators[t]}onStreamAppend(t){var s;const n=t["client-event-id"],i=this.readStreamIterators[n];if(!i){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?i.push({type:"reconnect"}):i.push({type:"error",error:new B(t.error)}),i.close(),delete this.readStreamIterators[n];return}((s=t.files)!=null&&s.length||t.content)&&i.push({type:"append",offset:t.offset,files:t.files,content:t.content}),t.done&&(i.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==li.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const i=n["stream-id"],s=this.writeStreams[i];s==null||s.onAppendFailed();break}case"start-stream":{const i=t["client-event-id"],s=this.startWriteStreamCbs[i];s&&(s({type:"error",error:new B(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[i]);break}case"subscribe-stream":{const i=t["client-event-id"],s=this.readStreamIterators[i];s&&(s.push({type:"error",error:new B(t.message||"Unknown error",t.hint)}),s.close(),delete this.readStreamIterators[i]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const li={AUTHENTICATED:"authenticated"};function di(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function hi(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}hi(),di();class cn extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function bt(e){}function pi(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=bt,onError:n=bt,onRetry:i=bt,onComment:s}=e;let r="",o=!0,a,u="",c="";function d(w){const h=o?w.replace(/^\xEF\xBB\xBF/,""):w,[O,b]=mi(`${r}${h}`);for(const k of O)f(k);r=b,o=!1}function f(w){if(w===""){y();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const h=w.indexOf(":");if(h!==-1){const O=w.slice(0,h),b=w[h+1]===" "?2:1,k=w.slice(h+b);m(O,k,w);return}m(w,"",w)}function m(w,h,O){switch(w){case"event":c=h;break;case"data":u=`${u}${h}
1
+ (function($,_){typeof exports=="object"&&typeof module<"u"?_(exports):typeof define=="function"&&define.amd?define(["exports"],_):($=typeof globalThis<"u"?globalThis:$||self,_($.instant={}))})(this,function($){"use strict";var Qi=Object.defineProperty;var In=$=>{throw TypeError($)};var Gi=($,_,C)=>_ in $?Qi($,_,{enumerable:!0,configurable:!0,writable:!0,value:C}):$[_]=C;var l=($,_,C)=>Gi($,typeof _!="symbol"?_+"":_,C),Mt=($,_,C)=>_.has($)||In("Cannot "+C);var g=($,_,C)=>(Mt($,_,"read from private field"),C?C.call($):_.get($)),K=($,_,C)=>_.has($)?In("Cannot add the same private member more than once"):_ instanceof WeakSet?_.add($):_.set($,C),he=($,_,C,R)=>(Mt($,_,"write to private field"),R?R.call($,C):_.set($,C),C),X=($,_,C)=>(Mt($,_,"access private method"),C);var Ue,N,Oe,W,F,U,On,st,$n,kn,En,et,tt,nt,Ut,_n,it;const _=/^(?:[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;function C(e){return typeof e=="string"&&_.test(e)}const R=[];for(let e=0;e<256;++e)R.push((e+256).toString(16).slice(1));function xn(e,t=0){return(R[e[t+0]]+R[e[t+1]]+R[e[t+2]]+R[e[t+3]]+"-"+R[e[t+4]]+R[e[t+5]]+"-"+R[e[t+6]]+R[e[t+7]]+"-"+R[e[t+8]]+R[e[t+9]]+"-"+R[e[t+10]]+R[e[t+11]]+R[e[t+12]]+R[e[t+13]]+R[e[t+14]]+R[e[t+15]]).toLowerCase()}let rt;const Cn=new Uint8Array(16);function Tn(){if(!rt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");rt=crypto.getRandomValues.bind(crypto)}return rt(Cn)}const Dt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Rn(e,t,n){var s;if(Dt.randomUUID&&!e)return Dt.randomUUID();e=e||{};const i=e.random??((s=e.rng)==null?void 0:s.call(e))??Tn();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=i[6]&15|64,i[8]=i[8]&63|128,xn(i)}const P={Remove:"remove",Replace:"replace",Add:"add"},Nt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,Y={mutable:"mutable",immutable:"immutable"},ot={};function De(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Lt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const i=Reflect.getOwnPropertyDescriptor(n,t);if(i)return i;n=Reflect.getPrototypeOf(n)}}}function Wt(e){return Object.getPrototypeOf(e)===Set.prototype}function Ft(e){return Object.getPrototypeOf(e)===Map.prototype}function H(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function at(e){return!!E(e)}function E(e){return typeof e!="object"?null:e==null?void 0:e[Nt]}function ct(e){var t;const n=E(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ge(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,Y))===Y.immutable||typeof n=="function")}function zt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,i=E(pe(n,e.key));if(i!==null&&(i==null?void 0:i.original)!==e.original)return null;const s=e.parent.type===3,r=s?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(s&&n.size>r||De(n,r)))return null;t.push(r)}if(e.parent)return zt(e.parent,t);t.reverse();try{An(e.copy,t)}catch{return null}return t}function Ne(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function pe(e,t){return Ne(e)===2?e.get(t):e[t]}function ut(e,t,n){Ne(e)===2?e.set(t,n):e[t]=n}function ft(e,t){const n=E(e);return(n?H(n):e)[t]}function we(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Se(e,t){return t?e:[""].concat(e).map(n=>{const i=`${n}`;return i.indexOf("/")===-1&&i.indexOf("~")===-1?i:i.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function An(e,t){for(let n=0;n<t.length-1;n+=1){const i=t[n];if(e=pe(Ne(e)===3?Array.from(e):e,i),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Pn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let i=Reflect.getOwnPropertyDescriptor(e,n);if(i.enumerable&&i.configurable&&i.writable){t[n]=e[n];return}i.writable||(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(i={configurable:!0,writable:!0,enumerable:i.enumerable,value:e[n]}),Reflect.defineProperty(t,n,i)}),t}const jn=Object.prototype.propertyIsEnumerable;function Mn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,Y),n!==void 0)&&n!==Y.mutable){if(n===Y.immutable)return Pn(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const i={};return Object.keys(e).forEach(s=>{i[s]=e[s]}),Object.getOwnPropertySymbols(e).forEach(s=>{jn.call(e,s)&&(i[s]=e[s])}),i}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function L(e){e.copy||(e.copy=Mn(e.original,e.options))}function Le(e){if(!ge(e))return ct(e);if(Array.isArray(e))return e.map(Le);if(e instanceof Map){const n=Array.from(e.entries()).map(([i,s])=>[i,Le(s)]);if(!Ft(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Le);if(!Wt(e)){const i=Object.getPrototypeOf(e).constructor;return new i(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Le(e[n]);return t}function Ge(e){return at(e)?Le(e):e}function ie(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ie(e.parent))}function Un(e,t){const n=Ne(e);if(n===0)Reflect.ownKeys(e).forEach(i=>{t(i,e[i],e)});else if(n===1){let i=0;for(const s of e)t(i,s,e),i+=1}else e.forEach((i,s)=>t(s,i,e))}function Vt(e,t,n){if(at(e)||!ge(e,n)||t.has(e)||Object.isFrozen(e))return;const i=e instanceof Set,s=i?new Map:void 0;if(t.add(e),Un(e,(r,o)=>{var a;if(at(o)){const u=E(o);L(u);const c=!((a=u.assignedMap)===null||a===void 0)&&a.size||u.operated?u.copy:u.original;ut(i?s:e,r,c)}else Vt(o,t,n)}),s){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(s.has(a)?s.get(a):a)})}}function Dn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Vt(pe(n,t),e.finalities.handledSet,e.options)}function lt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(ct(t))}))}function dt(e,t,n,i){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&i){const r=zt(e);r&&t(e,r,n,i)}e.finalized=!0}}function ht(e,t,n,i){const s=E(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((r,o)=>{var a;const u=e.type===3?e.setMap:e.copy;if(we(pe(u,t),n)){let c=s.original;s.copy&&(c=s.copy),lt(e),dt(e,i,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(c,s.original)),ut(u,t,c)}}),e.options.enableAutoFreeze&&s.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ge(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;we(pe(r,t),n)&&Dn(e,t)})}function Nn(e,t,n,i,s){let{original:r,assignedMap:o,options:a}=e,u=e.copy;u.length<r.length&&([r,u]=[u,r],[n,i]=[i,n]);for(let c=0;c<r.length;c+=1)if(o.get(c.toString())&&u[c]!==r[c]){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Replace,path:f,value:Ge(u[c])}),i.push({op:P.Replace,path:f,value:Ge(r[c])})}for(let c=r.length;c<u.length;c+=1){const d=t.concat([c]),f=Se(d,s);n.push({op:P.Add,path:f,value:Ge(u[c])})}if(r.length<u.length){const{arrayLengthAssignment:c=!0}=a.enablePatches;if(c){const d=t.concat(["length"]),f=Se(d,s);i.push({op:P.Replace,path:f,value:r.length})}else for(let d=u.length;r.length<d;d-=1){const f=t.concat([d-1]),m=Se(f,s);i.push({op:P.Remove,path:m})}}}function Ln({original:e,copy:t,assignedMap:n},i,s,r,o){n.forEach((a,u)=>{const c=pe(e,u),d=Ge(pe(t,u)),f=a?De(e,u)?P.Replace:P.Add:P.Remove;if(we(c,d)&&f===P.Replace)return;const m=i.concat(u),y=Se(m,o);s.push(f===P.Remove?{op:f,path:y}:{op:f,path:y,value:d}),r.push(f===P.Add?{op:P.Remove,path:y}:f===P.Remove?{op:P.Add,path:y,value:c}:{op:P.Replace,path:y,value:c})})}function Wn({original:e,copy:t},n,i,s,r){let o=0;e.forEach(a=>{if(!t.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Remove,path:c,value:a}),s.unshift({op:P.Add,path:c,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const u=n.concat([o]),c=Se(u,r);i.push({op:P.Add,path:c,value:a}),s.unshift({op:P.Remove,path:c,value:a})}o+=1})}function We(e,t,n,i){const{pathAsArray:s=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Ln(e,t,n,i,s);case 1:return Nn(e,t,n,i,s);case 3:return Wn(e,t,n,i,s)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ge(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},pt={get size(){return H(E(this)).size},has(e){return H(E(this)).has(e)},set(e,t){const n=E(this),i=H(n);return(!i.has(e)||!we(i.get(e),t))&&(L(n),ie(n),n.assignedMap.set(e,!0),n.copy.set(e,t),ht(n,e,t,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);return L(t),ie(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=E(this);if(this.size){L(e),ie(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=E(this);H(n).forEach((i,s)=>{e.call(t,this.get(s),s,this)})},get(e){var t,n;const i=E(this),s=H(i).get(e),r=((n=(t=i.options).mark)===null||n===void 0?void 0:n.call(t,s,Y))===Y.mutable;if(i.options.strict&&He(s,i.options,r),r||i.finalized||!ge(s,i.options)||s!==i.original.get(e))return s;const o=ot.createDraft({original:s,parentDraft:i,key:e,finalities:i.finalities,options:i.options});return L(i),i.copy.set(e,o),o},keys(){return H(E(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Qe](){return this.entries()}},Fn=Reflect.ownKeys(pt),Jt=(e,t,{isValuesIterator:n})=>()=>{var i,s;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const u=E(a),c=((s=(i=e.options).mark)===null||s===void 0?void 0:s.call(i,a,Y))===Y.mutable;if(e.options.strict&&He(o,e.options,c),!c&&!u&&ge(o,e.options)&&!e.finalized&&e.original.has(o)){const d=ot.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,d),a=d}else u&&(a=u.proxy);return{done:!1,value:n?a:[a,a]}},Be={get size(){return E(this).setMap.size},has(e){const t=E(this);if(t.setMap.has(e))return!0;L(t);const n=E(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=E(this);return this.has(e)||(L(t),ie(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),ht(t,e,e,We)),this},delete(e){if(!this.has(e))return!1;const t=E(this);L(t),ie(t);const n=E(e);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))},clear(){if(!this.size)return;const e=E(this);L(e),ie(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Jt(e,t,{isValuesIterator:!0})}},entries(){const e=E(this);L(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Jt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let i=n.next();for(;!i.done;)e.call(t,i.value,i.value,this),i=n.next()}};Set.prototype.difference&&Object.assign(Be,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const zn=Reflect.ownKeys(Be),Qt=new WeakSet,Gt={get(e,t,n){var i,s;const r=(i=e.copy)===null||i===void 0?void 0:i[t];if(r&&Qt.has(r))return r;if(t===Nt)return e;let o;if(e.options.mark){const c=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(c,Y),o===Y.mutable)return e.options.strict&&He(c,e.options,!0),c}const a=H(e);if(a instanceof Map&&Fn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(pt,"size").get.call(e.proxy);const c=pt[t];if(c)return c.bind(e.proxy)}if(a instanceof Set&&zn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const c=Be[t];if(c)return c.bind(e.proxy)}if(!De(a,t)){const c=Lt(a,t);return c?"value"in c?c.value:(s=c.get)===null||s===void 0?void 0:s.call(e.proxy):void 0}const u=a[t];if(e.options.strict&&He(u,e.options),e.finalized||!ge(u,e.options))return u;if(u===ft(e.original,t)){if(L(e),e.copy[t]=Ht({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const c=E(e.copy[t]);return L(c),ie(c),c.copy}return e.copy[t]}return u},set(e,t,n){var i;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(e.type===1&&t!=="length"&&!(Number.isInteger(s=Number(t))&&s>=0&&(t===0||s===0||String(s)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Lt(H(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ft(H(e),t),a=E(o);return a&&we(a.original,n)?(e.copy[t]=n,e.assignedMap=(i=e.assignedMap)!==null&&i!==void 0?i:new Map,e.assignedMap.set(t,!1),!0):(we(n,o)&&(n!==void 0||De(e.original,t))||(L(e),ie(e),De(e.original,t)&&we(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,ht(e,t,n,We)),!0)},has(e,t){return t in H(e)},ownKeys(e){return Reflect.ownKeys(H(e))},getOwnPropertyDescriptor(e,t){const n=H(e),i=Reflect.getOwnPropertyDescriptor(n,t);return i&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:i.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?Gt.set.call(this,e,t,void 0,e.proxy):(ft(e.original,t)!==void 0||t in e.original?(L(e),ie(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function Ht(e){const{original:t,parentDraft:n,key:i,finalities:s,options:r}=e,o=Ne(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:s,options:r,setMap:o===3?new Map(t.entries()):void 0};(i||"key"in e)&&(a.key=i);const{proxy:u,revoke:c}=Proxy.revocable(o===1?Object.assign([],a):a,Gt);if(s.revoke.push(c),Qt.add(u),a.proxy=u,n){const d=n;d.finalities.draft.push((f,m)=>{var y,I;const w=E(u);let h=d.type===3?d.setMap:d.copy;const O=pe(h,i),b=E(O);if(b){let k=b.original;b.operated&&(k=ct(O)),lt(b),dt(b,We,f,m),d.options.enableAutoFreeze&&(d.options.updatedValues=(y=d.options.updatedValues)!==null&&y!==void 0?y:new WeakMap,d.options.updatedValues.set(k,b.original)),ut(h,i,k)}(I=w.callbacks)===null||I===void 0||I.forEach(k=>{k(f,m)})})}else{const d=E(u);d.finalities.draft.push((f,m)=>{lt(d),dt(d,We,f,m)})}return u}ot.createDraft=Ht,Object.prototype.constructor.toString();function xe(){return Rn()}function Vn(e,t){return e.localeCompare(t)}function Jn(){let e=Vn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Jn();function Qn(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Gn=Qn();function qe(e,t,n){const i={__etype:e,__ops:n};return new Proxy(i,{get:(s,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Gn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Hn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function Bt(e){return e.startsWith("lookup__")}function qt(e){const[t,n,...i]=e.split("__");return[n,JSON.parse(i.join("__"))]}function Bn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(s,r)=>qe(e,qt(Hn(s,r)),[]);if(n==="__etype")return e;const i=n;return Bt(i)?qe(e,qt(i),[]):qe(e,i,[])}})}function Kt(){return new Proxy({},{get(e,t){return Bn(t)}})}Kt();function qn(e){return e.__ops}class B extends Error{constructor(n,i,s){super(n);l(this,"hint");l(this,"traceId");this.hint=i,s&&(this.traceId=s);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class Ie extends B{constructor(n){var r;const i=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(i,n.body.hint,n.body["trace-id"]);l(this,"body");l(this,"status");const s=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,s),Error.captureStackTrace&&Error.captureStackTrace(this,Ie),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const Ce="v0.22.164-branch-extra-fields.23220124983.1";class oe{constructor(t,n,i,s={indexed:!1,unique:!1}){l(this,"valueType");l(this,"required");l(this,"isIndexed");l(this,"config");l(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=i,this.config=s}clientRequired(){return new oe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new oe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new oe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new oe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class x extends Error{constructor(t,n){const i=n?`At path '${n}': ${t}`:t;super(i),this.name="QueryValidationError"}}const Xt=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],Kn=e=>e.valueType||"unknown",Yt=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},Xn=(e,t,n,i,s,r,o)=>{const a=r.valueType==="json",u=(c,d,f)=>{if(!Yt(f,d,a))throw new x(`Invalid value for operator '${c}' on attribute '${i}' in entity '${s}'. Expected ${d}, but received: ${typeof f}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new x(`Operator '${e}' for attribute '${i}' in entity '${s}' must be an array, but received: ${typeof t}`,o);for(const c of t)u(e,n,c);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":u(e,n,t);break;case"$like":case"$ilike":if(u(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new x(`Operator '${e}' can only be used with indexed attributes, but '${i}' in entity '${s}' is not indexed`,o);break;case"$isNull":u(e,"boolean",t);break;default:throw new x(`Unknown operator '${e}' for attribute '${i}' in entity '${s}'`,o)}},Te=(e,t,n,i,s)=>{const r=Kn(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const u=e;for(const[c,d]of Object.entries(u))Xn(c,d,r,t,i,n,`${s}.${c}`)}else if(!Yt(e,r,o))throw new x(`Invalid value for attribute '${t}' in entity '${i}'. Expected ${r}, but received: ${typeof e}`,s)},Yn=(e,t,n,i,s)=>{const r=e.split(".");if(r.length<2)throw new x(`Invalid dot notation path '${e}'. Must contain at least one dot.`,s);let o=n;for(let d=0;d<r.length-1;d++){const f=r[d],m=i.entities[o];if(!m)throw new x(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,s);const y=m.links[f];if(!y){const I=Object.keys(m.links);throw new x(`Link '${f}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${I.length>0?I.join(", "):"none"}`,s)}o=y.entityName}const a=r[r.length-1],u=i.entities[o];if(!u)throw new x(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,s);if(a==="id"){if(typeof t=="string"&&!C(t))throw new x(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}const c=u.attrs[a];if(Object.keys(u.links).includes(a)){if(typeof t=="string"&&!C(t))throw new x(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,s);Te(t,e,new oe("string",!1,!0),n,s);return}if(!c){const d=Object.keys(u.attrs);throw new x(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${d.length>0?d.join(", ")+", id":"id"}`,s)}Te(t,e,c,n,s)},Zt=(e,t,n,i)=>{for(const[s,r]of Object.entries(e)){if(s==="or"||s==="and"){if(Array.isArray(r))for(const c of r)typeof c=="object"&&c!==null&&Zt(c,t,n,`${i}.${s}[${c}]`);continue}if(s==="id"){Te(r,"id",new oe("string",!1,!0),t,`${i}.id`);continue}if(s.includes(".")){Yn(s,r,t,n,`${i}.${s}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[s],u=o.links[s];if(!a&&!u){const c=Object.keys(o.attrs),d=Object.keys(o.links);throw new x(`Attribute or link '${s}' does not exist on entity '${t}'. Available attributes: ${c.length>0?c.join(", "):"none"}. Available links: ${d.length>0?d.join(", "):"none"}`,`${i}.${s}`)}if(a)Te(r,s,a,t,`${i}.${s}`);else if(u){if(typeof r=="string"&&!C(r))throw new x(`Invalid value for link '${s}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${i}.${s}`);const c=new oe("string",!1,!0);Te(r,s,c,t,`${i}.${s}`)}}},Zn=(e,t,n,i,s=0)=>{for(const o of Object.keys(e))if(!Xt.includes(o))throw new x(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Xt.join(", ")}. Found: ${o}`,i);const r=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const o of r)if(e[o]!==void 0&&s>0)throw new x(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,i);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new x(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,i?`${i}.where`:void 0);Zt(e.where,t,n,i?`${i}.where`:"where")}},en=(e,t,n,i,s=0)=>{var r;if(!e||typeof e!="object")throw new x(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,i);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const u=Object.keys(n.entities[t].links);throw new x(`Link '${o}' does not exist on entity '${t}'. Available links: ${u.length>0?u.join(", "):"none"}`,`${i}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const u=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;u&&en(a,u,n,`${i}.${o}`,s+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new x(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${i}.$`);Zn(a,t,n,`${i}.$`,s)}},tn=(e,t)=>{if(typeof e!="object"||e===null)throw new x(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new x(`Query must be an object, but received: ${typeof e}`);const n=e;for(const i of Object.keys(n)){if(Array.isArray(e[i]))throw new x(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(typeof i!="string")throw new x(`Query keys must be strings, but found key of type: ${typeof i}`,i);if(i!=="$$ruleParams"){if(t&&!t.entities[i]){const s=Object.keys(t.entities);throw new x(`Entity '${i}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,i)}en(n[i],i,t,i,0)}}},nn=e=>typeof e!="string"?!1:Bt(e)?!0:C(e);class q extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const sn=e=>e.length>0?e.join(", "):"none",ei=(e,t)=>new q(`Entity '${e}' does not exist in schema. Available entities: ${sn(t)}`),mt={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},ti=(e,t)=>{var n;return e==null?!0:((n=mt[t.valueType])==null?void 0:n.call(mt,e))??!1},rn=(e,t)=>{const n=t.entities[e];if(!n)throw ei(e,Object.keys(t.entities));return n},yt=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(s==="id")continue;const o=i.attrs[s];if(o&&!ti(r,o))throw new q(`Invalid value for attribute '${s}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},on=(e,t,n)=>{const i=rn(e,n);if(typeof t!="object"||t===null)throw new q(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[s,r]of Object.entries(t)){if(!i.links[s]){const a=Object.keys(i.links);throw new q(`Link '${s}' does not exist on entity '${e}'. Available links: ${sn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!nn(a))throw new q(`Invalid entity ID in link '${s}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!nn(r))throw new q(`Invalid UUID in link '${s}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},ni={create:yt,update:yt,merge:yt,link:on,unlink:on,delete:()=>{}},ii=(e,t)=>{if(!t)return;const[n,i,s,r]=e;if(!Array.isArray(s)&&!C(s))throw new q(`Invalid id for entity '${i}'. Expected a UUID, but received: ${s}`);if(typeof i!="string")throw new q(`Entity name must be a string, but received: ${typeof i}`);const o=ni[n];o&&r!==void 0&&o(i,r,t)},si=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const i of n){if(!i||typeof i!="object")throw new q(`Transaction chunk must be an object, but received: ${typeof i}`);if(!Array.isArray(i.__ops))throw new q(`Transaction chunk must have __ops array, but received: ${typeof i.__ops}`);for(const s of i.__ops){if(!Array.isArray(s))throw new q(`Transaction operation must be an array, but received: ${typeof s}`);ii(s,t)}}};let ri=0;class oi{constructor(t,n,i){l(this,"type","sse");l(this,"initParams",null);l(this,"sendQueue",[]);l(this,"sendPromise");l(this,"closeFired",!1);l(this,"sseInitTimeout");l(this,"ES");l(this,"messageUrl");l(this,"conn");l(this,"url");l(this,"id");l(this,"onopen");l(this,"onmessage");l(this,"onclose");l(this,"onerror");this.id=`${this.type}_${ri++}`,this.url=n,this.messageUrl=i||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=s=>{const r=JSON.parse(s.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=s=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}async postMessages(t){var n,i,s;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(i=this.initParams)==null?void 0:i.sessionId,sse_token:(s=this.initParams)==null?void 0:s.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(t){if(!this.isOpen()||!this.initParams)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.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var an;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(an||(an={}));function ai({WStream:e,opts:t,startStream:n,appendStream:i,registerStream:s}){const r=t.clientId;let o=null,a=null,u=null;const c=xe();let d=!1,f=!1;const m=[],y=[],I=[];let w=!1,h=0,O=0;const b=[],k=new TextEncoder;function ee(){f=!0;for(const p of m)p(a??void 0)}function D(p){return m.push(p),f&&p(a??void 0),()=>{const v=m.indexOf(p);v!==-1&&m.splice(v,1)}}function z(p){return I.push(p),()=>{const v=I.indexOf(p);v!==-1&&I.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(p=>{I.push(p)}));function Q(){for(const p of I)try{p()}catch{}}function ue(p){return y.push(p),o&&p(o),()=>{const v=y.indexOf(p);v!==-1&&y.splice(v,1)}}function re(p){o=p;for(const v of y)v(o)}function $e(){w=!0}function At(p){let v=h,V=0,G=0;for(const{byteLen:ne}of b){const de=v+ne;if(de>p)break;v=de,V++,G+=ne}V>0&&(h+=G,O-=G,b.splice(0,V))}function te(p,v){a=v,ee(),p.error(v),Q()}async function fe(){const p=await n({clientId:r,reconnectToken:c,ruleParams:t.ruleParams});switch(p.type){case"ok":{const{streamId:v,offset:V}=p;o=v,At(V),b.length&&i({streamId:v,chunks:b.map(G=>G.chunk),offset:h}),w=!1;break}case"disconnect":{$e();break}case"error":{u&&te(u,p.error);break}}}function le(){$e(),fe()}function ke({offset:p,done:v}){At(p),v&&(d=!0,Q())}function Ee(p){return d?(te(p,new B("Stream has been closed.")),null):o||(te(p,new B("Stream has not been initialized.")),null)}async function Pt(p){u=p;let v=!0,V=0;for(;v;){let G=Date.now()+Math.min(15e3,500*(V-1));v=!1;const ne=await n({clientId:t.clientId,reconnectToken:c,ruleParams:t.ruleParams});switch(ne.type){case"ok":{const{streamId:de,offset:jt}=ne;if(jt!==0){const _e=new B("Write stream is corrupted");te(p,_e);return}re(de),s(de,{onDisconnect:$e,onFlush:ke,onConnectionReconnect:fe,onAppendFailed:le}),w=!1;return}case"disconnect":{v=!0,$e(),V++,await new Promise(de=>{setTimeout(de,Math.max(0,G-Date.now()))});break}case"error":{te(p,ne.error);return}}}}class Ji extends e{constructor(v,V){super(v,V)}async streamId(){return o||new Promise((v,V)=>{const G=[],ne=()=>{for(const _e of G)_e()},de=_e=>{v(_e),ne()},jt=_e=>{V(_e||new B("Stream is closed.")),ne()};G.push(ue(de)),G.push(D(jt))})}}return{stream:new Ji({async start(p){try{await Pt(p)}catch(v){te(p,v)}},write(p,v){const V=Ee(v);if(V){const G=k.encode(p).length;b.push({chunk:p,byteLen:G});const ne=h+O;O+=G,w||i({streamId:V,chunks:[p],offset:ne})}},close(){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0}):Q(),ee()},abort(p){o?i({streamId:o,chunks:[],offset:h+O,isDone:!0,abortReason:p}):Q(),ee()}}),addCompleteCb:z,closed(){return f}}}class ci{constructor(){l(this,"items",[]);l(this,"resolvers",[]);l(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(i=>{this.resolvers.push(i)});if(n||!t)return;yield t}}}}function ui({RStream:e,opts:t,startStream:n,cancelStream:i}){let s=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let u,c=!1;const d=[];function f(){c=!0;for(const b of d)b()}function m(b){return d.push(b),()=>{const k=d.indexOf(b);k!==-1&&d.splice(k,1)}}function y(b,k){b.error(k),f()}let I=0;async function w(b,k){u=xe();const ee={...b||{},eventId:u};for await(const D of n(ee)){if(r)return;if(D.type==="reconnect")return{retry:!0};if(D.type==="error"){y(k,D.error);return}if(D.offset>s){y(k,new B("Stream is corrupted.")),r=!0;return}let z=s-D.offset;if(D.files&&D.files.length){const Q=new AbortController;let ue=fetch(D.files[0].url,{signal:Q.signal});for(let re=0;re<D.files.length;re++){const $e=D.files[re+1],te=await ue;if($e&&(ue=fetch($e.url,{signal:Q.signal})),!te.ok){if(I++,I>10){y(k,new B("Unable to process stream."));return}return{retry:!0}}if(te.body){const fe=te.body.getReader();try{for(;;){const{done:le,value:ke}=await fe.read();if(le)break;if(r){Q.abort();return}let Ee=ke;if(z>0&&(Ee=ke.subarray(z),z-=ke.length-Ee.length),!Ee.length)continue;s+=Ee.length;const Pt=o.decode(Ee);k.enqueue(Pt)}}finally{fe.releaseLock()}}else{const fe=await te.arrayBuffer();let le=fe;if(r){Q.abort();return}if(z>0&&(le=new Uint8Array(fe).subarray(z),z-=fe.byteLength-le.length),!le.byteLength)continue;s+=le.byteLength;const ke=o.decode(le);k.enqueue(ke)}}}if(I=0,D.content){let Q=D.content,ue=a.encode(D.content);if(z>0){const re=ue.subarray(z);if(z-=ue.length-re.length,!re.length)continue;ue=re,Q=o.decode(re)}s+=ue.length,k.enqueue(Q)}}}async function h(b){let k=!0,ee=0;for(;k;){k=!1;let D=Date.now()+Math.min(15e3,500*(ee-1));const z=await w({...t,offset:s},b);z!=null&&z.retry&&(k=!0,ee++,D<Date.now()-3e5&&(ee=0),await new Promise(Q=>{setTimeout(Q,Math.max(0,D-Date.now()))}))}!r&&!c&&(b.close(),f())}return{stream:new e({start(b){h(b)},cancel(b){r=!0,u&&i({eventId:u}),f()}}),addCloseCb:m,closed(){return c}}}class fi{constructor({WStream:t,RStream:n,trySend:i,log:s}){l(this,"trySend");l(this,"WStream");l(this,"RStream");l(this,"writeStreams",{});l(this,"startWriteStreamCbs",{});l(this,"readStreamIterators",{});l(this,"log");l(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=i,this.log=s}createWriteStream(t){const{stream:n,addCompleteCb:i}=ai({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:i}=ui({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),i(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=xe();let i=null;const s=new Promise(o=>{i=o});this.startWriteStreamCbs[n]=i;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),s}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:i,offset:s,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:s,done:!!i};r&&(o["abort-reason"]=r),this.trySend(xe(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],i=this.writeStreams[n];if(!i){this.log.info("No stream cbs for stream-flushed",t);return}i.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:i,offset:s,ruleParams:r}){const o={op:"subscribe-stream"};if(!i&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");i&&(o["stream-id"]=i),n&&(o["client-id"]=n),s&&(o.offset=s),r&&(o["rule-params"]=r);const a=new ci;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(xe(),n),delete this.readStreamIterators[t]}onStreamAppend(t){var s;const n=t["client-event-id"],i=this.readStreamIterators[n];if(!i){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?i.push({type:"reconnect"}):i.push({type:"error",error:new B(t.error)}),i.close(),delete this.readStreamIterators[n];return}((s=t.files)!=null&&s.length||t.content)&&i.push({type:"append",offset:t.offset,files:t.files,content:t.content}),t.done&&(i.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==li.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const i=n["stream-id"],s=this.writeStreams[i];s==null||s.onAppendFailed();break}case"start-stream":{const i=t["client-event-id"],s=this.startWriteStreamCbs[i];s&&(s({type:"error",error:new B(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[i]);break}case"subscribe-stream":{const i=t["client-event-id"],s=this.readStreamIterators[i];s&&(s.push({type:"error",error:new B(t.message||"Unknown error",t.hint)}),s.close(),delete this.readStreamIterators[i]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const li={AUTHENTICATED:"authenticated"};function di(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function hi(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}hi(),di();class cn extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function bt(e){}function pi(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=bt,onError:n=bt,onRetry:i=bt,onComment:s}=e;let r="",o=!0,a,u="",c="";function d(w){const h=o?w.replace(/^\xEF\xBB\xBF/,""):w,[O,b]=mi(`${r}${h}`);for(const k of O)f(k);r=b,o=!1}function f(w){if(w===""){y();return}if(w.startsWith(":")){s&&s(w.slice(w.startsWith(": ")?2:1));return}const h=w.indexOf(":");if(h!==-1){const O=w.slice(0,h),b=w[h+1]===" "?2:1,k=w.slice(h+b);m(O,k,w);return}m(w,"",w)}function m(w,h,O){switch(w){case"event":c=h;break;case"data":u=`${u}${h}
2
2
  `;break;case"id":a=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?i(parseInt(h,10)):n(new cn(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:O}));break;default:n(new cn(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:h,line:O}));break}}function y(){u.length>0&&t({id:a,event:c||void 0,data:u.endsWith(`
3
3
  `)?u.slice(0,-1):u}),a=void 0,u="",c=""}function I(w={}){r&&w.consume&&f(r),o=!0,a=void 0,u="",c="",r=""}return{feed:d,reset:I}}function mi(e){const t=[];let n="",i=0;for(;i<e.length;){const s=e.indexOf("\r",i),r=e.indexOf(`
4
4
  `,i);let o=-1;if(s!==-1&&r!==-1?o=Math.min(s,r):s!==-1?o=s:r!==-1&&(o=r),o===-1){n=e.slice(i);break}else{const a=e.slice(i,o);t.push(a),i=o+1,e[i-1]==="\r"&&e[i]===`
5
- `&&i++}}return[t,n]}class un extends Event{constructor(t,n){var i,s;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}[Symbol.for("nodejs.util.inspect.custom")](t,n,i){return i(fn(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(fn(this),n)}}function yi(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function gt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(gt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${gt(e.cause)}`:e.message:`${e}`}function fn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ln=e=>{throw TypeError(e)},wt=(e,t,n)=>t.has(e)||ln("Cannot "+n),S=(e,t,n)=>(wt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?ln("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,i)=>(wt(e,t,"write to private field"),t.set(e,n),n),ae=(e,t,n)=>(wt(e,t,"access private method"),n),J,ve,Re,Ke,Xe,Fe,Ae,ze,me,Pe,je,Me,Ve,Z,St,It,vt,dn,Ot,$t,Je,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),j(this,Z),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,J),j(this,ve),j(this,Re),j(this,Ke),j(this,Xe),j(this,Fe),j(this,Ae),j(this,ze,null),j(this,me),j(this,Pe),j(this,je,null),j(this,Me,null),j(this,Ve,null),j(this,It,async r=>{var o;S(this,Pe).reset();const{body:a,redirected:u,status:c,headers:d}=r;if(c===204){ae(this,Z,Je).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Re,new URL(r.url)):T(this,Re,void 0),c!==200){ae(this,Z,Je).call(this,`Non-200 status code (${c})`,c);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ae(this,Z,Je).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(S(this,J)===this.CLOSED)return;T(this,J,this.OPEN);const f=new Event("open");if((o=S(this,Ve))==null||o.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){ae(this,Z,Je).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const m=new TextDecoder,y=a.getReader();let I=!0;do{const{done:w,value:h}=await y.read();h&&S(this,Pe).feed(m.decode(h,{stream:!w})),w&&(I=!1,S(this,Pe).reset(),ae(this,Z,kt).call(this))}while(I)}),j(this,vt,r=>{T(this,me,void 0),!(r.name==="AbortError"||r.type==="aborted")&&ae(this,Z,kt).call(this,gt(r))}),j(this,Ot,r=>{typeof r.id=="string"&&T(this,ze,r.id);const o=new MessageEvent(r.event||"message",{data:r.data,origin:S(this,Re)?S(this,Re).origin:S(this,ve).origin,lastEventId:r.id||""});S(this,Me)&&(!r.event||r.event==="message")&&S(this,Me).call(this,o),this.dispatchEvent(o)}),j(this,$t,r=>{T(this,Fe,r)}),j(this,Et,()=>{T(this,Ae,void 0),S(this,J)===this.CONNECTING&&ae(this,Z,St).call(this)});try{if(t instanceof URL)T(this,ve,t);else if(typeof t=="string")T(this,ve,new URL(t,bi()));else throw new Error("Invalid URL")}catch{throw yi("An invalid or illegal string was specified")}T(this,Pe,pi({onEvent:S(this,Ot),onRetry:S(this,$t)})),T(this,J,this.CONNECTING),T(this,Fe,3e3),T(this,Xe,(i=n==null?void 0:n.fetch)!=null?i:globalThis.fetch),T(this,Ke,(s=n==null?void 0:n.withCredentials)!=null?s:!1),ae(this,Z,St).call(this)}get readyState(){return S(this,J)}get url(){return S(this,ve).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,je)}set onerror(t){T(this,je,t)}get onmessage(){return S(this,Me)}set onmessage(t){T(this,Me,t)}get onopen(){return S(this,Ve)}set onopen(t){T(this,Ve,t)}addEventListener(t,n,i){const s=n;super.addEventListener(t,s,i)}removeEventListener(t,n,i){const s=n;super.removeEventListener(t,s,i)}close(){S(this,Ae)&&clearTimeout(S(this,Ae)),S(this,J)!==this.CLOSED&&(S(this,me)&&S(this,me).abort(),T(this,J,this.CLOSED),T(this,me,void 0))}}J=new WeakMap,ve=new WeakMap,Re=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Fe=new WeakMap,Ae=new WeakMap,ze=new WeakMap,me=new WeakMap,Pe=new WeakMap,je=new WeakMap,Me=new WeakMap,Ve=new WeakMap,Z=new WeakSet,St=function(){T(this,J,this.CONNECTING),T(this,me,new AbortController),S(this,Xe)(S(this,ve),ae(this,Z,dn).call(this)).then(S(this,It)).catch(S(this,vt))},It=new WeakMap,vt=new WeakMap,dn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,ze)?{"Last-Event-ID":S(this,ze)}:void 0},cache:"no-store",signal:(e=S(this,me))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ot=new WeakMap,$t=new WeakMap,Je=function(e,t){var n;S(this,J)!==this.CLOSED&&T(this,J,this.CLOSED);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i)},kt=function(e,t){var n;if(S(this,J)===this.CLOSED)return;T(this,J,this.CONNECTING);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i),T(this,Ae,setTimeout(S(this,Et),S(this,Fe)))},Et=new WeakMap,se.CONNECTING=0,se.OPEN=1,se.CLOSED=2;function bi(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function gi(e,t,n,i){let s=null,r=!1;const o=[],a=f=>{o.push(f),o.length>100&&o.shift(),s&&(s(),s=null)};e(a);const u=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,s&&s(),u()}),{next:async()=>{for(;;){if(i()==="closed"||r)return u();const f=o.shift();if(f)return{value:f,done:!1};await new Promise(y=>{s=y})}},return:u,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function ye(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function wi(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function hn(e){if(!e)return;const t={};for(const[n,i]of Object.entries(e))t[n]={startCursor:i["start-cursor"],endCursor:i["end-cursor"],hasNextPage:i["has-next-page?"],hasPreviousPage:i["has-previous-page?"]};return t}function Si(e,t,n){let i,s=!1;const r=Ce(),o=new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{fetch(h,O){return i=null,fetch(h,{...O,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})}).then(b=>(b.ok||(i=wi(b)),b))}}),a=[],u=[],c=h=>{a.push(h)},d=h=>{a.splice(a.indexOf(h),1)},f=h=>{u.push(h)};t&&c(t);let m=null;function y(h){if(!s)for(const O of a)try{O(h)}catch(b){console.error("Error in subscribeQuery callback",b)}}function I(h){var O,b;switch(h.op){case"sse-init":{const k=h["machine-id"],ee=h["session-id"];m={machineId:k,sessionId:ee};break}case"add-query-ok":{y({type:"ok",data:h.result,pageInfo:hn((O=h["result-meta"])==null?void 0:O["page-info"]),sessionInfo:m});break}case"refresh-ok":{h.computations.length&&y({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:hn((b=h.computations[0]["result-meta"])==null?void 0:b["page-info"]),sessionInfo:m});break}case"error":{y({type:"error",error:new Ie({body:h,status:h.status}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m});break}}}return o.onerror=h=>{if(i)i.text().then(O=>{let b={type:void 0,message:O};try{b=JSON.parse(O)}catch{}y({type:"error",error:new Ie({status:i.status,body:b}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})});else{const O=()=>{y({type:"error",error:new Ie({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})};if(o.readyState===se.CLOSED){O();return}setTimeout(()=>{o.readyState!==se.OPEN&&O()},5e3)}},o.onmessage=h=>{I(JSON.parse(h.data))},{close:()=>{s=!0;for(const h of u)try{h()}catch(O){console.error("Error in onClose callback",O)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return m},get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},[Symbol.asyncIterator]:gi.bind(this,c,f,d,()=>1)}}var ce={};Object.defineProperty(ce,"__esModule",{value:!0});var Ii=ce.parseCookie=yn;ce.parse=yn,ce.stringifyCookie=_i,ce.stringifySetCookie=Ye,ce.serialize=Ye,ce.parseSetCookie=Ci,ce.stringifySetCookie=Ye,ce.serialize=Ye;const pn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mn=/^[\u0021-\u003A\u003C-\u007E]*$/,vi=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Oi=/^[\u0020-\u003A\u003D-\u007E]*$/,$i=/^-?\d+$/,ki=Object.prototype.toString,Ei=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function yn(e,t){const n=new Ei,i=e.length;if(i<2)return n;const s=(t==null?void 0:t.decode)||bn;let r=0;do{const o=Ct(e,r,i);if(o===-1)break;const a=_t(e,r,i);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const u=be(e,r,o);n[u]===void 0&&(n[u]=s(be(e,o+1,a))),r=a+1}while(r<i);return n}function _i(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,i=[];for(const s of Object.keys(e)){const r=e[s];if(r===void 0)continue;if(!pn.test(s))throw new TypeError(`cookie name is invalid: ${s}`);const o=n(r);if(!mn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);i.push(`${s}=${o}`)}return i.join("; ")}function Ye(e,t,n){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;if(!pn.test(i.name))throw new TypeError(`argument name is invalid: ${i.name}`);const o=i.value?r(i.value):"";if(!mn.test(o))throw new TypeError(`argument val is invalid: ${i.value}`);let a=i.name+"="+o;if(i.maxAge!==void 0){if(!Number.isInteger(i.maxAge))throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);a+="; Max-Age="+i.maxAge}if(i.domain){if(!vi.test(i.domain))throw new TypeError(`option domain is invalid: ${i.domain}`);a+="; Domain="+i.domain}if(i.path){if(!Oi.test(i.path))throw new TypeError(`option path is invalid: ${i.path}`);a+="; Path="+i.path}if(i.expires){if(!xi(i.expires)||!Number.isFinite(i.expires.valueOf()))throw new TypeError(`option expires is invalid: ${i.expires}`);a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.partitioned&&(a+="; Partitioned"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${i.sameSite}`)}return a}function Ci(e,t){const n=(t==null?void 0:t.decode)||bn,i=e.length,s=_t(e,0,i),r=Ct(e,0,s),o=r===-1?{name:"",value:n(be(e,0,s))}:{name:be(e,0,r),value:n(be(e,r+1,s))};let a=s+1;for(;a<i;){const u=_t(e,a,i),c=Ct(e,a,u),d=c===-1?be(e,a,u):be(e,a,c),f=c===-1?void 0:be(e,c+1,u);switch(d.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=f;break;case"path":o.path=f;break;case"max-age":f&&$i.test(f)&&(o.maxAge=Number(f));break;case"expires":if(!f)break;const m=new Date(f);Number.isFinite(m.valueOf())&&(o.expires=m);break;case"priority":if(!f)break;const y=f.toLowerCase();(y==="low"||y==="medium"||y==="high")&&(o.priority=y);break;case"samesite":if(!f)break;const I=f.toLowerCase();(I==="lax"||I==="strict"||I==="none")&&(o.sameSite=I);break}a=u+1}return o}function _t(e,t,n){const i=e.indexOf(";",t);return i===-1?n:i}function Ct(e,t,n){const i=e.indexOf("=",t);return i<n?i:-1}function be(e,t,n){let i=t,s=n;do{const r=e.charCodeAt(i);if(r!==32&&r!==9)break}while(++i<s);for(;s>i;){const r=e.charCodeAt(s-1);if(r!==32&&r!==9)break;s--}return e.slice(i,s)}function bn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function xi(e){return ki.call(e)==="[object Date]"}function Ti(e){return{...{apiURI:"https://api.instantdb.com"},...e}}function Ri(e,t){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}function Ai(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)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`.")}function A(e,t){Ai(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?Ri(s,t):s}function Pi(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function ji(){return Pi()?{cache:"no-store"}:{}}async function Mi(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new Ie({status:t.status,body:i}))}catch{return e(new Ie({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=ji(),i={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":xe,"Instant-Core-Version":xe},s=await fetch(e,{...n,...t,headers:i});if(s.status===200){const r=await s.json();return Promise.resolve(r)}return Mi(r=>Promise.reject(r),s)}function Ui(e){var t,n,vn;return t=class{constructor(r){K(this,n);l(this,"source");l(this,"url");this.url=r,this.source=X(this,n,vn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,vn=function(r){return new se(r,{fetch(a,u){return fetch(a,{...u,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":xe,"@instantdb/core":xe}})})}})},l(t,"OPEN",se.OPEN),l(t,"CONNECTING",se.CONNECTING),l(t,"CLOSED",se.CLOSED),t}function Di(e){var n,i;(!e.appId||!x(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(i=e.adminToken)==null?void 0:i.trim(),useDateObjects:e.useDateObjects??!1};return new xt(t)}function gn(e){return(Array.isArray(e)?e:[e]).flatMap(qn)}class Ni{constructor(t){l(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Li{constructor(t){l(this,"config");l(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"verifyMagicCode",async(t,n)=>{const{user:i}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n})});return i});l(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);l(this,"getUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${encodeURIComponent(r)}`).join("&");return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});l(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});l(this,"getUserFromRequest",async(t,n)=>{const i=t.headers.get("cookie")||"",s=Ii(i),r="instant_user_"+this.config.appId;if(!s[r])return null;const o=s[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await M(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(i),body:JSON.stringify(n)})}}const wn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Wi=e=>e&&typeof e.getReader=="function";class Sn{constructor(t,n){l(this,"config");l(this,"impersonationOpts");l(this,"uploadFile",async(t,n,i={})=>{const s={...A(this.config,this.impersonationOpts),path:t};i.contentDisposition&&(s["content-disposition"]=i.contentDisposition),delete s["content-type"],i.contentType&&(s["content-type"]=i.contentType);let r;if(wn(n)&&(r="half"),wn(n)||Wi(n)){if(!i.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=i.fileSize.toString()}let o={method:"PUT",headers:s,body:n,...r&&{duplex:r}};return M(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});l(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));l(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));l(this,"upload",async(t,n,i={})=>{const{data:s}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=i.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(s,{method:"PUT",body:n,headers:r});return a});l(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});l(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Fi{constructor(t){K(this,Ue);l(this,"createReadStream",t=>g(this,Ue).call(this).createReadStream(t));l(this,"createWriteStream",t=>g(this,Ue).call(this).createWriteStream(t));he(this,Ue,t)}}Ue=new WeakMap;function zi(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Rt=class Rt{constructor(t){K(this,U);l(this,"config");l(this,"auth");l(this,"storage");l(this,"streams");l(this,"rooms");l(this,"impersonationOpts");K(this,N,null);K(this,Oe,0);K(this,W,null);K(this,F);l(this,"tx",Kt());l(this,"asUser",t=>{const n=new Rt({...this.config});return n.impersonationOpts=t,n.storage=new Sn(this.config,t),n});l(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const i=n.fetchOpts||{},s=i.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});l(this,"transact",t=>(this.config.disableValidation||si(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:gn(t),"throw-on-missing-attrs?":!!this.config.schema})})));l(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const i={query:t,"rules-override":n==null?void 0:n.rules};n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin);const s=await M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)});return{result:s.result,checkResults:s["check-results"]}});l(this,"debugTransact",(t,n)=>{const i={steps:gn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)})});K(this,et,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][open]",t.target.id),he(this,Oe,0),(n=g(this,W))==null||n.onConnectionStatusChange("authenticated")});K(this,tt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][close]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed"),g(this,N)&&(he(this,N,null),X(this,U,Ut).call(this)||(setTimeout(()=>X(this,U,st).call(this),g(this,Oe)),he(this,Oe,Math.min(15e3,Math.max(g(this,Oe),500)*2))))});K(this,nt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][error]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed")});K(this,it,t=>{var i,s,r,o,a,u;if(t.target!==g(this,N)){g(this,F).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(g(this,F).info("[receive]",n),n.op){case"start-stream-ok":{(i=g(this,W))==null||i.onStartStreamOk(n);break}case"stream-flushed":{(s=g(this,W))==null||s.onStreamFlushed(n);break}case"append-failed":{(r=g(this,W))==null||r.onAppendFailed(n);break}case"stream-append":{(o=g(this,W))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(u=g(this,W))==null||u.onRecieveError(n);break}}break}}X(this,U,_n).call(this)});this.config=Ti(t),this.auth=new Li(this.config),this.storage=new Sn(this.config,this.impersonationOpts),this.streams=new Fi(X(this,U,En).bind(this)),this.rooms=new Ni(this.config),he(this,F,zi(!!this.config.verbose))}subscribeQuery(t,n,i={}){t&&i&&"ruleParams"in i&&(t={$$ruleParams:i.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const o={...(i.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return Si(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};N=new WeakMap,Oe=new WeakMap,W=new WeakMap,F=new WeakMap,U=new WeakSet,On=function(){g(this,N)&&g(this,N).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,i=Ui({headers:t,inference:n}),s=new oi(i,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return s.onopen=g(this,et),s.onmessage=g(this,it),s.onclose=g(this,tt),s.onerror=g(this,nt),he(this,N,s),s},st=function(){return g(this,N)||X(this,U,On).call(this)},$n=function(t,n){const i=X(this,U,st).call(this);g(this,F).info("[send]",t,n,{isOpen:i.isOpen()}),i.isOpen()&&i.send({"client-event-id":t,...n})},kn=function(){X(this,U,st).call(this);const t=new fi({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,i)=>{X(this,U,$n).call(this,n,i)},log:g(this,F)});return he(this,W,t),t},En=function(){return g(this,W)||X(this,U,kn).call(this)},et=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ut=function(){return!g(this,W)||!g(this,W).hasActiveStreams()},_n=function(){if(g(this,N)&&X(this,U,Ut).call(this)){const t=g(this,N);g(this,F).info("cleaning up unused socket",t.id),he(this,N,null),t.close()}},it=new WeakMap;let xt=Rt;var Tt={};function Ze(e){let t=e;return new TransformStream({transform(n,i){if(!t){i.enqueue(n);return}if(t>n.length){t-=n.length;return}const s=n.slice(t);t=0,i.enqueue(s)}})}function Vi(e){const t=e.appId||Tt.INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.");const n=e.adminToken||Tt.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const i=e.apiURI||Tt.INSTANT_API_URI,s=Di({appId:t,adminToken:n,apiURI:i});async function r(c,d,f){const m=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});try{const y=await m.streamId();d().pipeTo(m);const w=s.streams.createReadStream({streamId:y});return f?w.pipeThrough(Ze(f)):w}catch{const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}}async function o(c,d){const f=s.streams.createReadStream({clientId:c});return d?f.pipeThrough(Ze(d)):f}async function a(c,d,f){const m=d(),y=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});await y.streamId(),m.pipeTo(y);const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}async function u(c){var m;const d=await s.query({$streams:{$:{where:{clientId:c}}}}),f=(m=d==null?void 0:d.$streams)==null?void 0:m[0];return f!=null&&f.done?"DONE":f?!0:null}return{resumableStream:r,resumeExistingStream:o,createNewResumableStream:a,hasExistingStream:u}}$.createResumableStreamContext=Vi,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
5
+ `&&i++}}return[t,n]}class un extends Event{constructor(t,n){var i,s;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}[Symbol.for("nodejs.util.inspect.custom")](t,n,i){return i(fn(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(fn(this),n)}}function yi(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function gt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(gt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${gt(e.cause)}`:e.message:`${e}`}function fn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var ln=e=>{throw TypeError(e)},wt=(e,t,n)=>t.has(e)||ln("Cannot "+n),S=(e,t,n)=>(wt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?ln("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,i)=>(wt(e,t,"write to private field"),t.set(e,n),n),ae=(e,t,n)=>(wt(e,t,"access private method"),n),J,ve,Re,Ke,Xe,Fe,Ae,ze,me,Pe,je,Me,Ve,Z,St,It,vt,dn,Ot,$t,Je,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),j(this,Z),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,J),j(this,ve),j(this,Re),j(this,Ke),j(this,Xe),j(this,Fe),j(this,Ae),j(this,ze,null),j(this,me),j(this,Pe),j(this,je,null),j(this,Me,null),j(this,Ve,null),j(this,It,async r=>{var o;S(this,Pe).reset();const{body:a,redirected:u,status:c,headers:d}=r;if(c===204){ae(this,Z,Je).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Re,new URL(r.url)):T(this,Re,void 0),c!==200){ae(this,Z,Je).call(this,`Non-200 status code (${c})`,c);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ae(this,Z,Je).call(this,'Invalid content type, expected "text/event-stream"',c);return}if(S(this,J)===this.CLOSED)return;T(this,J,this.OPEN);const f=new Event("open");if((o=S(this,Ve))==null||o.call(this,f),this.dispatchEvent(f),typeof a!="object"||!a||!("getReader"in a)){ae(this,Z,Je).call(this,"Invalid response body, expected a web ReadableStream",c),this.close();return}const m=new TextDecoder,y=a.getReader();let I=!0;do{const{done:w,value:h}=await y.read();h&&S(this,Pe).feed(m.decode(h,{stream:!w})),w&&(I=!1,S(this,Pe).reset(),ae(this,Z,kt).call(this))}while(I)}),j(this,vt,r=>{T(this,me,void 0),!(r.name==="AbortError"||r.type==="aborted")&&ae(this,Z,kt).call(this,gt(r))}),j(this,Ot,r=>{typeof r.id=="string"&&T(this,ze,r.id);const o=new MessageEvent(r.event||"message",{data:r.data,origin:S(this,Re)?S(this,Re).origin:S(this,ve).origin,lastEventId:r.id||""});S(this,Me)&&(!r.event||r.event==="message")&&S(this,Me).call(this,o),this.dispatchEvent(o)}),j(this,$t,r=>{T(this,Fe,r)}),j(this,Et,()=>{T(this,Ae,void 0),S(this,J)===this.CONNECTING&&ae(this,Z,St).call(this)});try{if(t instanceof URL)T(this,ve,t);else if(typeof t=="string")T(this,ve,new URL(t,bi()));else throw new Error("Invalid URL")}catch{throw yi("An invalid or illegal string was specified")}T(this,Pe,pi({onEvent:S(this,Ot),onRetry:S(this,$t)})),T(this,J,this.CONNECTING),T(this,Fe,3e3),T(this,Xe,(i=n==null?void 0:n.fetch)!=null?i:globalThis.fetch),T(this,Ke,(s=n==null?void 0:n.withCredentials)!=null?s:!1),ae(this,Z,St).call(this)}get readyState(){return S(this,J)}get url(){return S(this,ve).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,je)}set onerror(t){T(this,je,t)}get onmessage(){return S(this,Me)}set onmessage(t){T(this,Me,t)}get onopen(){return S(this,Ve)}set onopen(t){T(this,Ve,t)}addEventListener(t,n,i){const s=n;super.addEventListener(t,s,i)}removeEventListener(t,n,i){const s=n;super.removeEventListener(t,s,i)}close(){S(this,Ae)&&clearTimeout(S(this,Ae)),S(this,J)!==this.CLOSED&&(S(this,me)&&S(this,me).abort(),T(this,J,this.CLOSED),T(this,me,void 0))}}J=new WeakMap,ve=new WeakMap,Re=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Fe=new WeakMap,Ae=new WeakMap,ze=new WeakMap,me=new WeakMap,Pe=new WeakMap,je=new WeakMap,Me=new WeakMap,Ve=new WeakMap,Z=new WeakSet,St=function(){T(this,J,this.CONNECTING),T(this,me,new AbortController),S(this,Xe)(S(this,ve),ae(this,Z,dn).call(this)).then(S(this,It)).catch(S(this,vt))},It=new WeakMap,vt=new WeakMap,dn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,ze)?{"Last-Event-ID":S(this,ze)}:void 0},cache:"no-store",signal:(e=S(this,me))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ot=new WeakMap,$t=new WeakMap,Je=function(e,t){var n;S(this,J)!==this.CLOSED&&T(this,J,this.CLOSED);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i)},kt=function(e,t){var n;if(S(this,J)===this.CLOSED)return;T(this,J,this.CONNECTING);const i=new un("error",{code:t,message:e});(n=S(this,je))==null||n.call(this,i),this.dispatchEvent(i),T(this,Ae,setTimeout(S(this,Et),S(this,Fe)))},Et=new WeakMap,se.CONNECTING=0,se.OPEN=1,se.CLOSED=2;function bi(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}function gi(e,t,n,i){let s=null,r=!1;const o=[],a=f=>{o.push(f),o.length>100&&o.shift(),s&&(s(),s=null)};e(a);const u=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,s&&s(),u()}),{next:async()=>{for(;;){if(i()==="closed"||r)return u();const f=o.shift();if(f)return{value:f,done:!1};await new Promise(y=>{s=y})}},return:u,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function ye(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function wi(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function hn(e){if(!e)return;const t={};for(const[n,i]of Object.entries(e))t[n]={startCursor:i["start-cursor"],endCursor:i["end-cursor"],hasNextPage:i["has-next-page?"],hasPreviousPage:i["has-previous-page?"]};return t}function Si(e,t,n){let i,s=!1;const r=xe(),o=new se(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{fetch(h,O){return i=null,fetch(h,{...O,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":Ce,"@instantdb/core":Ce}})}).then(b=>(b.ok||(i=wi(b)),b))}}),a=[],u=[],c=h=>{a.push(h)},d=h=>{a.splice(a.indexOf(h),1)},f=h=>{u.push(h)};t&&c(t);let m=null;function y(h){if(!s)for(const O of a)try{O(h)}catch(b){console.error("Error in subscribeQuery callback",b)}}function I(h){var O,b;switch(h.op){case"sse-init":{const k=h["machine-id"],ee=h["session-id"];m={machineId:k,sessionId:ee};break}case"add-query-ok":{y({type:"ok",data:h.result,pageInfo:hn((O=h["result-meta"])==null?void 0:O["page-info"]),sessionInfo:m});break}case"refresh-ok":{h.computations.length&&y({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:hn((b=h.computations[0]["result-meta"])==null?void 0:b["page-info"]),sessionInfo:m});break}case"error":{y({type:"error",error:new Ie({body:h,status:h.status}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m});break}}}return o.onerror=h=>{if(i)i.text().then(O=>{let b={type:void 0,message:O};try{b=JSON.parse(O)}catch{}y({type:"error",error:new Ie({status:i.status,body:b}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})});else{const O=()=>{y({type:"error",error:new Ie({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:m})};if(o.readyState===se.CLOSED){O();return}setTimeout(()=>{o.readyState!==se.OPEN&&O()},5e3)}},o.onmessage=h=>{I(JSON.parse(h.data))},{close:()=>{s=!0;for(const h of u)try{h()}catch(O){console.error("Error in onClose callback",O)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return m},get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},[Symbol.asyncIterator]:gi.bind(this,c,f,d,()=>1)}}var ce={};Object.defineProperty(ce,"__esModule",{value:!0});var Ii=ce.parseCookie=yn;ce.parse=yn,ce.stringifyCookie=_i,ce.stringifySetCookie=Ye,ce.serialize=Ye,ce.parseSetCookie=xi,ce.stringifySetCookie=Ye,ce.serialize=Ye;const pn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,mn=/^[\u0021-\u003A\u003C-\u007E]*$/,vi=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,Oi=/^[\u0020-\u003A\u003D-\u007E]*$/,$i=/^-?\d+$/,ki=Object.prototype.toString,Ei=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function yn(e,t){const n=new Ei,i=e.length;if(i<2)return n;const s=(t==null?void 0:t.decode)||bn;let r=0;do{const o=xt(e,r,i);if(o===-1)break;const a=_t(e,r,i);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const u=be(e,r,o);n[u]===void 0&&(n[u]=s(be(e,o+1,a))),r=a+1}while(r<i);return n}function _i(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,i=[];for(const s of Object.keys(e)){const r=e[s];if(r===void 0)continue;if(!pn.test(s))throw new TypeError(`cookie name is invalid: ${s}`);const o=n(r);if(!mn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);i.push(`${s}=${o}`)}return i.join("; ")}function Ye(e,t,n){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;if(!pn.test(i.name))throw new TypeError(`argument name is invalid: ${i.name}`);const o=i.value?r(i.value):"";if(!mn.test(o))throw new TypeError(`argument val is invalid: ${i.value}`);let a=i.name+"="+o;if(i.maxAge!==void 0){if(!Number.isInteger(i.maxAge))throw new TypeError(`option maxAge is invalid: ${i.maxAge}`);a+="; Max-Age="+i.maxAge}if(i.domain){if(!vi.test(i.domain))throw new TypeError(`option domain is invalid: ${i.domain}`);a+="; Domain="+i.domain}if(i.path){if(!Oi.test(i.path))throw new TypeError(`option path is invalid: ${i.path}`);a+="; Path="+i.path}if(i.expires){if(!Ci(i.expires)||!Number.isFinite(i.expires.valueOf()))throw new TypeError(`option expires is invalid: ${i.expires}`);a+="; Expires="+i.expires.toUTCString()}if(i.httpOnly&&(a+="; HttpOnly"),i.secure&&(a+="; Secure"),i.partitioned&&(a+="; Partitioned"),i.priority)switch(typeof i.priority=="string"?i.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${i.priority}`)}if(i.sameSite)switch(typeof i.sameSite=="string"?i.sameSite.toLowerCase():i.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${i.sameSite}`)}return a}function xi(e,t){const n=(t==null?void 0:t.decode)||bn,i=e.length,s=_t(e,0,i),r=xt(e,0,s),o=r===-1?{name:"",value:n(be(e,0,s))}:{name:be(e,0,r),value:n(be(e,r+1,s))};let a=s+1;for(;a<i;){const u=_t(e,a,i),c=xt(e,a,u),d=c===-1?be(e,a,u):be(e,a,c),f=c===-1?void 0:be(e,c+1,u);switch(d.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=f;break;case"path":o.path=f;break;case"max-age":f&&$i.test(f)&&(o.maxAge=Number(f));break;case"expires":if(!f)break;const m=new Date(f);Number.isFinite(m.valueOf())&&(o.expires=m);break;case"priority":if(!f)break;const y=f.toLowerCase();(y==="low"||y==="medium"||y==="high")&&(o.priority=y);break;case"samesite":if(!f)break;const I=f.toLowerCase();(I==="lax"||I==="strict"||I==="none")&&(o.sameSite=I);break}a=u+1}return o}function _t(e,t,n){const i=e.indexOf(";",t);return i===-1?n:i}function xt(e,t,n){const i=e.indexOf("=",t);return i<n?i:-1}function be(e,t,n){let i=t,s=n;do{const r=e.charCodeAt(i);if(r!==32&&r!==9)break}while(++i<s);for(;s>i;){const r=e.charCodeAt(s-1);if(r!==32&&r!==9)break;s--}return e.slice(i,s)}function bn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function Ci(e){return ki.call(e)==="[object Date]"}function Ti(e){return{...{apiURI:"https://api.instantdb.com"},...e}}function Ri(e,t){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}function Ai(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)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`.")}function A(e,t){Ai(e,t);const{adminToken:n,appId:i}=e,s={"content-type":"application/json","app-id":i};return n&&(s.authorization=`Bearer ${n}`),t?Ri(s,t):s}function Pi(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function ji(){return Pi()?{cache:"no-store"}:{}}async function Mi(e,t){const n=await t.text();try{const i=JSON.parse(n);return e(new Ie({status:t.status,body:i}))}catch{return e(new Ie({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=ji(),i={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":Ce,"Instant-Core-Version":Ce},s=await fetch(e,{...n,...t,headers:i});if(s.status===200){const r=await s.json();return Promise.resolve(r)}return Mi(r=>Promise.reject(r),s)}function Ui(e){var t,n,vn;return t=class{constructor(r){K(this,n);l(this,"source");l(this,"url");this.url=r,this.source=X(this,n,vn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,vn=function(r){return new se(r,{fetch(a,u){return fetch(a,{...u,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":Ce,"@instantdb/core":Ce}})})}})},l(t,"OPEN",se.OPEN),l(t,"CONNECTING",se.CONNECTING),l(t,"CLOSED",se.CLOSED),t}function Di(e){var n,i;(!e.appId||!C(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(i=e.adminToken)==null?void 0:i.trim(),useDateObjects:e.useDateObjects??!1};return new Ct(t)}function gn(e){return(Array.isArray(e)?e:[e]).flatMap(qn)}class Ni{constructor(t){l(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Li{constructor(t){l(this,"config");l(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));l(this,"verifyMagicCode",async(t,n,i)=>{const s=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n,...i!=null&&i.extraFields?{"extra-fields":i.extraFields}:{}})});return{...s.user,created:s.created}});l(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);l(this,"getUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${encodeURIComponent(r)}`).join("&");return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});l(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});l(this,"getUserFromRequest",async(t,n)=>{const i=t.headers.get("cookie")||"",s=Ii(i),r="instant_user_"+this.config.appId;if(!s[r])return null;const o=s[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await M(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(i),body:JSON.stringify(n)})}}const wn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Wi=e=>e&&typeof e.getReader=="function";class Sn{constructor(t,n){l(this,"config");l(this,"impersonationOpts");l(this,"uploadFile",async(t,n,i={})=>{const s={...A(this.config,this.impersonationOpts),path:t};i.contentDisposition&&(s["content-disposition"]=i.contentDisposition),delete s["content-type"],i.contentType&&(s["content-type"]=i.contentType);let r;if(wn(n)&&(r="half"),wn(n)||Wi(n)){if(!i.fileSize)throw new Error("fileSize is required in metadata when uploading streams");s["content-length"]=i.fileSize.toString()}let o={method:"PUT",headers:s,body:n,...r&&{duplex:r}};return M(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});l(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));l(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));l(this,"upload",async(t,n,i={})=>{const{data:s}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=i.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(s,{method:"PUT",body:n,headers:r});return a});l(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});l(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Fi{constructor(t){K(this,Ue);l(this,"createReadStream",t=>g(this,Ue).call(this).createReadStream(t));l(this,"createWriteStream",t=>g(this,Ue).call(this).createWriteStream(t));he(this,Ue,t)}}Ue=new WeakMap;function zi(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Rt=class Rt{constructor(t){K(this,U);l(this,"config");l(this,"auth");l(this,"storage");l(this,"streams");l(this,"rooms");l(this,"impersonationOpts");K(this,N,null);K(this,Oe,0);K(this,W,null);K(this,F);l(this,"tx",Kt());l(this,"asUser",t=>{const n=new Rt({...this.config});return n.impersonationOpts=t,n.storage=new Sn(this.config,t),n});l(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const i=n.fetchOpts||{},s=i.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});l(this,"transact",t=>(this.config.disableValidation||si(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:gn(t),"throw-on-missing-attrs?":!!this.config.schema})})));l(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const i={query:t,"rules-override":n==null?void 0:n.rules};n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin);const s=await M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)});return{result:s.result,checkResults:s["check-results"]}});l(this,"debugTransact",(t,n)=>{const i={steps:gn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(i["ip-override"]=n.ip),n!=null&&n.origin&&(i["origin-override"]=n.origin),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(i)})});K(this,et,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][open]",t.target.id),he(this,Oe,0),(n=g(this,W))==null||n.onConnectionStatusChange("authenticated")});K(this,tt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][close]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed"),g(this,N)&&(he(this,N,null),X(this,U,Ut).call(this)||(setTimeout(()=>X(this,U,st).call(this),g(this,Oe)),he(this,Oe,Math.min(15e3,Math.max(g(this,Oe),500)*2))))});K(this,nt,t=>{var n;if(t.target!==g(this,N)){g(this,F).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}g(this,F).info("[socket][error]",t.target.id),(n=g(this,W))==null||n.onConnectionStatusChange("closed")});K(this,it,t=>{var i,s,r,o,a,u;if(t.target!==g(this,N)){g(this,F).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(g(this,F).info("[receive]",n),n.op){case"start-stream-ok":{(i=g(this,W))==null||i.onStartStreamOk(n);break}case"stream-flushed":{(s=g(this,W))==null||s.onStreamFlushed(n);break}case"append-failed":{(r=g(this,W))==null||r.onAppendFailed(n);break}case"stream-append":{(o=g(this,W))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(u=g(this,W))==null||u.onRecieveError(n);break}}break}}X(this,U,_n).call(this)});this.config=Ti(t),this.auth=new Li(this.config),this.storage=new Sn(this.config,this.impersonationOpts),this.streams=new Fi(X(this,U,En).bind(this)),this.rooms=new Ni(this.config),he(this,F,zi(!!this.config.verbose))}subscribeQuery(t,n,i={}){t&&i&&"ruleParams"in i&&(t={$$ruleParams:i.ruleParams,...t}),this.config.disableValidation||tn(t,this.config.schema);const o={...(i.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return Si(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};N=new WeakMap,Oe=new WeakMap,W=new WeakMap,F=new WeakMap,U=new WeakSet,On=function(){g(this,N)&&g(this,N).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,i=Ui({headers:t,inference:n}),s=new oi(i,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return s.onopen=g(this,et),s.onmessage=g(this,it),s.onclose=g(this,tt),s.onerror=g(this,nt),he(this,N,s),s},st=function(){return g(this,N)||X(this,U,On).call(this)},$n=function(t,n){const i=X(this,U,st).call(this);g(this,F).info("[send]",t,n,{isOpen:i.isOpen()}),i.isOpen()&&i.send({"client-event-id":t,...n})},kn=function(){X(this,U,st).call(this);const t=new fi({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,i)=>{X(this,U,$n).call(this,n,i)},log:g(this,F)});return he(this,W,t),t},En=function(){return g(this,W)||X(this,U,kn).call(this)},et=new WeakMap,tt=new WeakMap,nt=new WeakMap,Ut=function(){return!g(this,W)||!g(this,W).hasActiveStreams()},_n=function(){if(g(this,N)&&X(this,U,Ut).call(this)){const t=g(this,N);g(this,F).info("cleaning up unused socket",t.id),he(this,N,null),t.close()}},it=new WeakMap;let Ct=Rt;var Tt={};function Ze(e){let t=e;return new TransformStream({transform(n,i){if(!t){i.enqueue(n);return}if(t>n.length){t-=n.length;return}const s=n.slice(t);t=0,i.enqueue(s)}})}function Vi(e){const t=e.appId||Tt.INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ID environment variable.");const n=e.adminToken||Tt.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const i=e.apiURI||Tt.INSTANT_API_URI,s=Di({appId:t,adminToken:n,apiURI:i});async function r(c,d,f){const m=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});try{const y=await m.streamId();d().pipeTo(m);const w=s.streams.createReadStream({streamId:y});return f?w.pipeThrough(Ze(f)):w}catch{const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}}async function o(c,d){const f=s.streams.createReadStream({clientId:c});return d?f.pipeThrough(Ze(d)):f}async function a(c,d,f){const m=d(),y=s.streams.createWriteStream({clientId:c,waitUntil:e.waitUntil??void 0});await y.streamId(),m.pipeTo(y);const I=s.streams.createReadStream({clientId:c});return f?I.pipeThrough(Ze(f)):I}async function u(c){var m;const d=await s.query({$streams:{$:{where:{clientId:c}}}}),f=(m=d==null?void 0:d.$streams)==null?void 0:m[0];return f!=null&&f.done?"DONE":f?!0:null}return{resumableStream:r,resumeExistingStream:o,createNewResumableStream:a,hasExistingStream:u}}$.createResumableStreamContext=Vi,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instantdb/resumable-stream",
3
- "version": "0.22.163",
3
+ "version": "0.22.164-branch-extra-fields.23220124983.1",
4
4
  "description": "Instant's drop-in replacement for Vercel's resumable-stream package.",
5
5
  "homepage": "https://github.com/instantdb/instant/tree/main/client/packages/resumable-stream",
6
6
  "repository": {
@@ -50,7 +50,7 @@
50
50
  "vitest": "^1.6.0"
51
51
  },
52
52
  "dependencies": {
53
- "@instantdb/admin": "0.22.163"
53
+ "@instantdb/admin": "0.22.164-branch-extra-fields.23220124983.1"
54
54
  },
55
55
  "scripts": {
56
56
  "test": "vitest",