@instantdb/resumable-stream 0.22.167 → 0.22.168

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.167 build /home/runner/work/instant/instant/client/packages/resumable-stream
2
+ > @instantdb/resumable-stream@0.22.168 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.167 build:tshy
8
+ > @instantdb/resumable-stream@0.22.168 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.167 build:standalone
14
+ > @instantdb/resumable-stream@0.22.168 build:standalone
15
15
  > vite build
16
16
 
17
17
  vite v5.4.14 building for production...
@@ -19,17 +19,17 @@ transforming...
19
19
  ✓ 75 modules transformed.
20
20
  rendering chunks...
21
21
  computing gzip size...
22
- dist/standalone/index.umd.cjs 66.92 kB │ gzip: 21.06 kB
23
- dist/standalone/index.js 106.30 kB │ gzip: 27.81 kB
24
- ✓ built in 1.16s
22
+ dist/standalone/index.umd.cjs 67.23 kB │ gzip: 21.11 kB
23
+ dist/standalone/index.js 107.11 kB │ gzip: 28.01 kB
24
+ ✓ built in 1.18s
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.167 check-exports
28
+ > @instantdb/resumable-stream@0.22.168 check-exports
29
29
  > attw --pack .
30
30
 
31
31
 
32
- @instantdb/resumable-stream v0.22.167
32
+ @instantdb/resumable-stream v0.22.168
33
33
 
34
34
  Build tools:
35
35
  - @arethetypeswrong/cli@^0.17.4
@@ -1,19 +1,19 @@
1
1
  var _n = Object.defineProperty;
2
- var Mt = (e) => {
2
+ var jt = (e) => {
3
3
  throw TypeError(e);
4
4
  };
5
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);
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);
6
+ var l = (e, t, n) => Cn(e, typeof t != "symbol" ? t + "" : t, n), ot = (e, t, n) => t.has(e) || jt("Cannot " + n);
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) ? jt("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
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;
9
9
  function Pe(e) {
10
10
  return typeof e == "string" && xn.test(e);
11
11
  }
12
- const j = [];
12
+ const M = [];
13
13
  for (let e = 0; e < 256; ++e)
14
- j.push((e + 256).toString(16).slice(1));
14
+ M.push((e + 256).toString(16).slice(1));
15
15
  function Tn(e, t = 0) {
16
- return (j[e[t + 0]] + j[e[t + 1]] + j[e[t + 2]] + j[e[t + 3]] + "-" + j[e[t + 4]] + j[e[t + 5]] + "-" + j[e[t + 6]] + j[e[t + 7]] + "-" + j[e[t + 8]] + j[e[t + 9]] + "-" + j[e[t + 10]] + j[e[t + 11]] + j[e[t + 12]] + j[e[t + 13]] + j[e[t + 14]] + j[e[t + 15]]).toLowerCase();
16
+ return (M[e[t + 0]] + M[e[t + 1]] + M[e[t + 2]] + M[e[t + 3]] + "-" + M[e[t + 4]] + M[e[t + 5]] + "-" + M[e[t + 6]] + M[e[t + 7]] + "-" + M[e[t + 8]] + M[e[t + 9]] + "-" + M[e[t + 10]] + M[e[t + 11]] + M[e[t + 12]] + M[e[t + 13]] + M[e[t + 14]] + M[e[t + 15]]).toLowerCase();
17
17
  }
18
18
  let at;
19
19
  const Rn = new Uint8Array(16);
@@ -26,7 +26,7 @@ function An() {
26
26
  return at(Rn);
27
27
  }
28
28
  const Pn = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Ut = { randomUUID: Pn };
29
- function jn(e, t, n) {
29
+ function Mn(e, t, n) {
30
30
  var s;
31
31
  if (Ut.randomUUID && !e)
32
32
  return Ut.randomUUID();
@@ -36,7 +36,7 @@ function jn(e, t, n) {
36
36
  throw new Error("Random bytes length must be >= 16");
37
37
  return i[6] = i[6] & 15 | 64, i[8] = i[8] & 63 | 128, Tn(i);
38
38
  }
39
- const T = {
39
+ const R = {
40
40
  Remove: "remove",
41
41
  Replace: "replace",
42
42
  Add: "add"
@@ -99,7 +99,7 @@ function nn(e, t = []) {
99
99
  return nn(e.parent, t);
100
100
  t.reverse();
101
101
  try {
102
- Mn(e.copy, t);
102
+ jn(e.copy, t);
103
103
  } catch {
104
104
  return null;
105
105
  }
@@ -127,7 +127,7 @@ function Se(e, t) {
127
127
  return i.indexOf("/") === -1 && i.indexOf("~") === -1 ? i : i.replace(/~/g, "~0").replace(/\//g, "~1");
128
128
  }).join("/");
129
129
  }
130
- function Mn(e, t) {
130
+ function jn(e, t) {
131
131
  for (let n = 0; n < t.length - 1; n += 1) {
132
132
  const i = t[n];
133
133
  if (e = pe(ze(e) === 3 ? Array.from(e) : e, i), typeof e != "object")
@@ -190,15 +190,15 @@ function Nn(e, t) {
190
190
  function W(e) {
191
191
  e.copy || (e.copy = Nn(e.original, e.options));
192
192
  }
193
- function Me(e) {
193
+ function je(e) {
194
194
  if (!$e(e))
195
195
  return Tt(e);
196
196
  if (Array.isArray(e))
197
- return e.map(Me);
197
+ return e.map(je);
198
198
  if (e instanceof Map) {
199
199
  const n = Array.from(e.entries()).map(([i, s]) => [
200
200
  i,
201
- Me(s)
201
+ je(s)
202
202
  ]);
203
203
  if (!tn(e)) {
204
204
  const i = Object.getPrototypeOf(e).constructor;
@@ -207,7 +207,7 @@ function Me(e) {
207
207
  return new Map(n);
208
208
  }
209
209
  if (e instanceof Set) {
210
- const n = Array.from(e).map(Me);
210
+ const n = Array.from(e).map(je);
211
211
  if (!en(e)) {
212
212
  const i = Object.getPrototypeOf(e).constructor;
213
213
  return new i(n);
@@ -216,11 +216,11 @@ function Me(e) {
216
216
  }
217
217
  const t = Object.create(Object.getPrototypeOf(e));
218
218
  for (const n in e)
219
- t[n] = Me(e[n]);
219
+ t[n] = je(e[n]);
220
220
  return t;
221
221
  }
222
222
  function Qe(e) {
223
- return ht(e) ? Me(e) : e;
223
+ return ht(e) ? je(e) : e;
224
224
  }
225
225
  function ne(e) {
226
226
  var t;
@@ -298,12 +298,12 @@ function Fn(e, t, n, i, s) {
298
298
  if (o.get(c.toString()) && u[c] !== r[c]) {
299
299
  const d = t.concat([c]), f = Se(d, s);
300
300
  n.push({
301
- op: T.Replace,
301
+ op: R.Replace,
302
302
  path: f,
303
303
  // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
304
304
  value: Qe(u[c])
305
305
  }), i.push({
306
- op: T.Replace,
306
+ op: R.Replace,
307
307
  path: f,
308
308
  // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
309
309
  value: Qe(r[c])
@@ -312,7 +312,7 @@ function Fn(e, t, n, i, s) {
312
312
  for (let c = r.length; c < u.length; c += 1) {
313
313
  const d = t.concat([c]), f = Se(d, s);
314
314
  n.push({
315
- op: T.Add,
315
+ op: R.Add,
316
316
  path: f,
317
317
  // If it is a draft, it needs to be deep cloned, and it may also be non-draft.
318
318
  value: Qe(u[c])
@@ -323,7 +323,7 @@ function Fn(e, t, n, i, s) {
323
323
  if (c) {
324
324
  const d = t.concat(["length"]), f = Se(d, s);
325
325
  i.push({
326
- op: T.Replace,
326
+ op: R.Replace,
327
327
  path: f,
328
328
  value: r.length
329
329
  });
@@ -331,7 +331,7 @@ function Fn(e, t, n, i, s) {
331
331
  for (let d = u.length; r.length < d; d -= 1) {
332
332
  const f = t.concat([d - 1]), m = Se(f, s);
333
333
  i.push({
334
- op: T.Remove,
334
+ op: R.Remove,
335
335
  path: m
336
336
  });
337
337
  }
@@ -339,11 +339,11 @@ function Fn(e, t, n, i, s) {
339
339
  }
340
340
  function zn({ original: e, copy: t, assignedMap: n }, i, s, r, o) {
341
341
  n.forEach((a, u) => {
342
- const c = pe(e, u), d = Qe(pe(t, u)), f = a ? Ne(e, u) ? T.Replace : T.Add : T.Remove;
343
- if (ve(c, d) && f === T.Replace)
342
+ const c = pe(e, u), d = Qe(pe(t, u)), f = a ? Ne(e, u) ? R.Replace : R.Add : R.Remove;
343
+ if (ve(c, d) && f === R.Replace)
344
344
  return;
345
345
  const m = i.concat(u), y = Se(m, o);
346
- s.push(f === T.Remove ? { op: f, path: y } : { op: f, path: y, value: d }), r.push(f === T.Add ? { op: T.Remove, path: y } : f === T.Remove ? { op: T.Add, path: y, value: c } : { op: T.Replace, path: y, value: c });
346
+ s.push(f === R.Remove ? { op: f, path: y } : { op: f, path: y, value: d }), r.push(f === R.Add ? { op: R.Remove, path: y } : f === R.Remove ? { op: R.Add, path: y, value: c } : { op: R.Replace, path: y, value: c });
347
347
  });
348
348
  }
349
349
  function Vn({ original: e, copy: t }, n, i, s, r) {
@@ -352,11 +352,11 @@ function Vn({ original: e, copy: t }, n, i, s, r) {
352
352
  if (!t.has(a)) {
353
353
  const u = n.concat([o]), c = Se(u, r);
354
354
  i.push({
355
- op: T.Remove,
355
+ op: R.Remove,
356
356
  path: c,
357
357
  value: a
358
358
  }), s.unshift({
359
- op: T.Add,
359
+ op: R.Add,
360
360
  path: c,
361
361
  value: a
362
362
  });
@@ -366,11 +366,11 @@ function Vn({ original: e, copy: t }, n, i, s, r) {
366
366
  if (!e.has(a)) {
367
367
  const u = n.concat([o]), c = Se(u, r);
368
368
  i.push({
369
- op: T.Add,
369
+ op: R.Add,
370
370
  path: c,
371
371
  value: a
372
372
  }), s.unshift({
373
- op: T.Remove,
373
+ op: R.Remove,
374
374
  path: c,
375
375
  value: a
376
376
  });
@@ -722,7 +722,7 @@ function an(e) {
722
722
  xt.createDraft = an;
723
723
  Object.prototype.constructor.toString();
724
724
  function xe() {
725
- return jn();
725
+ return Mn();
726
726
  }
727
727
  function Gn(e, t) {
728
728
  return e.localeCompare(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.167";
837
+ const Me = "v0.22.168";
838
838
  class ue {
839
839
  constructor(t, n, i, s = { indexed: !1, unique: !1 }) {
840
840
  l(this, "valueType");
@@ -1953,11 +1953,11 @@ function Ht(e) {
1953
1953
  }
1954
1954
  var mn = (e) => {
1955
1955
  throw TypeError(e);
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)), 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)), T = (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;
1957
1957
  class te extends EventTarget {
1958
1958
  constructor(t, n) {
1959
1959
  var i, s;
1960
- 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(), T(this, Y), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, T(this, V), T(this, we), T(this, ke), T(this, He), T(this, Xe), T(this, Le), T(this, Ce), T(this, We, null), T(this, he), T(this, Ee), T(this, Re, null), T(this, _e, null), T(this, Ue, null), T(this, wt, async (r) => {
1961
1961
  var o;
1962
1962
  S(this, Ee).reset();
1963
1963
  const { body: a, redirected: u, status: c, headers: d } = r;
@@ -1987,9 +1987,9 @@ class te extends EventTarget {
1987
1987
  const { done: w, value: h } = await y.read();
1988
1988
  h && S(this, Ee).feed(m.decode(h, { stream: !w })), w && (I = !1, S(this, Ee).reset(), ce(this, Y, Ot).call(this));
1989
1989
  } while (I);
1990
- }), x(this, St, (r) => {
1990
+ }), T(this, St, (r) => {
1991
1991
  _(this, he, void 0), !(r.name === "AbortError" || r.type === "aborted") && ce(this, Y, Ot).call(this, bt(r));
1992
- }), x(this, It, (r) => {
1992
+ }), T(this, It, (r) => {
1993
1993
  typeof r.id == "string" && _(this, We, r.id);
1994
1994
  const o = new MessageEvent(r.event || "message", {
1995
1995
  data: r.data,
@@ -1997,9 +1997,9 @@ class te extends EventTarget {
1997
1997
  lastEventId: r.id || ""
1998
1998
  });
1999
1999
  S(this, _e) && (!r.event || r.event === "message") && S(this, _e).call(this, o), this.dispatchEvent(o);
2000
- }), x(this, vt, (r) => {
2000
+ }), T(this, vt, (r) => {
2001
2001
  _(this, Le, r);
2002
- }), x(this, $t, () => {
2002
+ }), T(this, $t, () => {
2003
2003
  _(this, Ce, void 0), S(this, V) === this.CONNECTING && ce(this, Y, gt).call(this);
2004
2004
  });
2005
2005
  try {
@@ -2239,8 +2239,8 @@ function Oi(e, t, n) {
2239
2239
  query: e,
2240
2240
  "inference?": n.inference,
2241
2241
  versions: {
2242
- "@instantdb/admin": je,
2243
- "@instantdb/core": je
2242
+ "@instantdb/admin": Me,
2243
+ "@instantdb/core": Me
2244
2244
  }
2245
2245
  })
2246
2246
  }).then((b) => (b.ok || (i = vi(b)), b));
@@ -2583,20 +2583,20 @@ function Pi(e) {
2583
2583
  apiURI: "https://api.instantdb.com"
2584
2584
  }, ...e };
2585
2585
  }
2586
- function ji(e, t) {
2586
+ function Mi(e, t) {
2587
2587
  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;
2588
2588
  }
2589
- function Mi(e, t) {
2589
+ function ji(e, t) {
2590
2590
  if (!(t && ("token" in t || "guest" in t)) && !e.adminToken)
2591
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`.");
2592
2592
  }
2593
2593
  function C(e, t) {
2594
- Mi(e, t);
2594
+ ji(e, t);
2595
2595
  const { adminToken: n, appId: i } = e, s = {
2596
2596
  "content-type": "application/json",
2597
2597
  "app-id": i
2598
2598
  };
2599
- return n && (s.authorization = `Bearer ${n}`), t ? ji(s, t) : s;
2599
+ return n && (s.authorization = `Bearer ${n}`), t ? Mi(s, t) : s;
2600
2600
  }
2601
2601
  function Ui() {
2602
2602
  return (
@@ -2620,11 +2620,11 @@ async function Ni(e, t) {
2620
2620
  }));
2621
2621
  }
2622
2622
  }
2623
- async function R(e, t) {
2623
+ async function x(e, t) {
2624
2624
  const n = Di(), i = {
2625
2625
  ...(t == null ? void 0 : t.headers) || {},
2626
- "Instant-Admin-Version": je,
2627
- "Instant-Core-Version": je
2626
+ "Instant-Admin-Version": Me,
2627
+ "Instant-Core-Version": Me
2628
2628
  }, s = await fetch(e, { ...n, ...t, headers: i });
2629
2629
  if (s.status === 200) {
2630
2630
  const r = await s.json();
@@ -2675,8 +2675,8 @@ function Li(e) {
2675
2675
  body: JSON.stringify({
2676
2676
  "inference?": e.inference,
2677
2677
  versions: {
2678
- "@instantdb/admin": je,
2679
- "@instantdb/core": je
2678
+ "@instantdb/admin": Me,
2679
+ "@instantdb/core": Me
2680
2680
  }
2681
2681
  })
2682
2682
  });
@@ -2704,7 +2704,7 @@ class Fi {
2704
2704
  this.config = t;
2705
2705
  }
2706
2706
  async getPresence(t, n) {
2707
- return (await R(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`, {
2707
+ return (await x(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`, {
2708
2708
  method: "GET",
2709
2709
  headers: C(this.config)
2710
2710
  })).sessions || {};
@@ -2726,7 +2726,7 @@ class zi {
2726
2726
  *
2727
2727
  * @see https://instantdb.com/docs/backend#custom-magic-codes
2728
2728
  */
2729
- l(this, "generateMagicCode", async (t) => R(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
2729
+ l(this, "generateMagicCode", async (t) => x(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`, {
2730
2730
  method: "POST",
2731
2731
  headers: C(this.config),
2732
2732
  body: JSON.stringify({ email: t })
@@ -2741,28 +2741,51 @@ class zi {
2741
2741
  *
2742
2742
  * @see https://instantdb.com/docs/backend#custom-magic-codes
2743
2743
  */
2744
- l(this, "sendMagicCode", async (t) => R(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
2744
+ l(this, "sendMagicCode", async (t) => x(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`, {
2745
2745
  method: "POST",
2746
2746
  headers: C(this.config),
2747
2747
  body: JSON.stringify({ email: t })
2748
2748
  }));
2749
2749
  /**
2750
- * Verifies a magic code for the user with the given email.
2751
- *
2752
- * @example
2753
- * const user = await db.auth.verifyMagicCode({ email, code })
2754
- * console.log("Verified user:", user)
2750
+ * @deprecated Use {@link checkMagicCode} instead to get the `created` field
2751
+ * and support `extraFields`.
2755
2752
  *
2756
2753
  * @see https://instantdb.com/docs/backend#custom-magic-codes
2757
2754
  */
2758
2755
  l(this, "verifyMagicCode", async (t, n) => {
2759
- const { user: i } = await R(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2756
+ const { user: i } = await x(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2760
2757
  method: "POST",
2761
2758
  headers: C(this.config),
2762
2759
  body: JSON.stringify({ email: t, code: n })
2763
2760
  });
2764
2761
  return i;
2765
2762
  });
2763
+ /**
2764
+ * Verifies a magic code and returns the user along with whether
2765
+ * the user was newly created. Supports `extraFields` to set custom
2766
+ * `$users` properties at signup.
2767
+ *
2768
+ * @example
2769
+ * const { user, created } = await db.auth.checkMagicCode(
2770
+ * email,
2771
+ * code,
2772
+ * { extraFields: { nickname: 'ari' } },
2773
+ * );
2774
+ *
2775
+ * @see https://instantdb.com/docs/backend#custom-magic-codes
2776
+ */
2777
+ l(this, "checkMagicCode", async (t, n, i) => {
2778
+ const s = await x(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`, {
2779
+ method: "POST",
2780
+ headers: C(this.config),
2781
+ body: JSON.stringify({
2782
+ email: t,
2783
+ code: n,
2784
+ ...i != null && i.extraFields ? { "extra-fields": i.extraFields } : {}
2785
+ })
2786
+ });
2787
+ return { user: s.user, created: s.created };
2788
+ });
2766
2789
  /**
2767
2790
  * Verifies a given token and returns the associated user.
2768
2791
  *
@@ -2779,7 +2802,7 @@ class zi {
2779
2802
  * })
2780
2803
  * @see https://instantdb.com/docs/backend#custom-endpoints
2781
2804
  */
2782
- l(this, "verifyToken", async (t) => (await R(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
2805
+ l(this, "verifyToken", async (t) => (await x(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`, {
2783
2806
  method: "POST",
2784
2807
  headers: { "content-type": "application/json" },
2785
2808
  body: JSON.stringify({
@@ -2802,7 +2825,7 @@ class zi {
2802
2825
  */
2803
2826
  l(this, "getUser", async (t) => {
2804
2827
  const n = Object.entries(t).map(([s, r]) => `${s}=${encodeURIComponent(r)}`).join("&");
2805
- return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2828
+ return (await x(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2806
2829
  method: "GET",
2807
2830
  headers: C(this.config)
2808
2831
  })).user;
@@ -2825,7 +2848,7 @@ class zi {
2825
2848
  */
2826
2849
  l(this, "deleteUser", async (t) => {
2827
2850
  const n = Object.entries(t).map(([s, r]) => `${s}=${r}`);
2828
- return (await R(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2851
+ return (await x(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`, {
2829
2852
  method: "DELETE",
2830
2853
  headers: C(this.config)
2831
2854
  })).deleted;
@@ -2848,7 +2871,7 @@ class zi {
2848
2871
  }
2849
2872
  async createToken(t) {
2850
2873
  const n = typeof t == "string" ? { email: t } : t;
2851
- return (await R(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
2874
+ return (await x(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`, {
2852
2875
  method: "POST",
2853
2876
  headers: C(this.config),
2854
2877
  body: JSON.stringify(n)
@@ -2856,7 +2879,7 @@ class zi {
2856
2879
  }
2857
2880
  async signOut(t) {
2858
2881
  const n = typeof t == "string" ? { email: t } : t, i = this.config;
2859
- await R(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
2882
+ await x(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`, {
2860
2883
  method: "POST",
2861
2884
  headers: C(i),
2862
2885
  body: JSON.stringify(n)
@@ -2894,7 +2917,7 @@ class Yt {
2894
2917
  body: n,
2895
2918
  ...r && { duplex: r }
2896
2919
  };
2897
- return R(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`, o);
2920
+ return x(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`, o);
2898
2921
  });
2899
2922
  /**
2900
2923
  * Deletes a file by its path name (e.g. "photos/demo.png").
@@ -2909,7 +2932,7 @@ class Yt {
2909
2932
  *
2910
2933
  * @see https://instantdb.com/docs/storage
2911
2934
  */
2912
- l(this, "delete", async (t) => R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2935
+ l(this, "delete", async (t) => x(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2913
2936
  method: "DELETE",
2914
2937
  headers: C(this.config, this.impersonationOpts)
2915
2938
  }));
@@ -2924,7 +2947,7 @@ class Yt {
2924
2947
  *
2925
2948
  * @see https://instantdb.com/docs/storage
2926
2949
  */
2927
- l(this, "deleteMany", async (t) => R(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
2950
+ l(this, "deleteMany", async (t) => x(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`, {
2928
2951
  method: "POST",
2929
2952
  headers: C(this.config, this.impersonationOpts),
2930
2953
  body: JSON.stringify({ filenames: t })
@@ -2934,7 +2957,7 @@ class Yt {
2934
2957
  * instead
2935
2958
  */
2936
2959
  l(this, "upload", async (t, n, i = {}) => {
2937
- const { data: s } = await R(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
2960
+ const { data: s } = await x(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`, {
2938
2961
  method: "POST",
2939
2962
  headers: C(this.config),
2940
2963
  body: JSON.stringify({
@@ -2956,7 +2979,7 @@ class Yt {
2956
2979
  * const files = await db.query({ $files: {}})
2957
2980
  */
2958
2981
  l(this, "list", async () => {
2959
- const { data: t } = await R(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
2982
+ const { data: t } = await x(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`, {
2960
2983
  method: "GET",
2961
2984
  headers: C(this.config)
2962
2985
  });
@@ -2977,7 +3000,7 @@ class Yt {
2977
3000
  * })
2978
3001
  */
2979
3002
  l(this, "getDownloadUrl", async (t) => {
2980
- const { data: n } = await R(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
3003
+ const { data: n } = await x(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`, {
2981
3004
  method: "GET",
2982
3005
  headers: C(this.config)
2983
3006
  });
@@ -3024,8 +3047,8 @@ function Qi(e) {
3024
3047
  }
3025
3048
  };
3026
3049
  }
3027
- var M, Ie, N, L, A, In, Be, vn, On, $n, Ye, Ze, et, Ct, kn, tt;
3028
- const jt = class jt {
3050
+ var j, Ie, N, L, A, In, Be, vn, On, $n, Ye, Ze, et, Ct, kn, tt;
3051
+ const Mt = class Mt {
3029
3052
  constructor(t) {
3030
3053
  Q(this, A);
3031
3054
  l(this, "config");
@@ -3034,7 +3057,7 @@ const jt = class jt {
3034
3057
  l(this, "streams");
3035
3058
  l(this, "rooms");
3036
3059
  l(this, "impersonationOpts");
3037
- Q(this, M, null);
3060
+ Q(this, j, null);
3038
3061
  Q(this, Ie, 0);
3039
3062
  Q(this, N, null);
3040
3063
  Q(this, L);
@@ -3049,7 +3072,7 @@ const jt = class jt {
3049
3072
  * await db.asUser({email: "stopa@instantdb.com"}).query({ goals: {} })
3050
3073
  */
3051
3074
  l(this, "asUser", (t) => {
3052
- const n = new jt({
3075
+ const n = new Mt({
3053
3076
  ...this.config
3054
3077
  });
3055
3078
  return n.impersonationOpts = t, n.storage = new Yt(this.config, t), n;
@@ -3072,7 +3095,7 @@ const jt = class jt {
3072
3095
  l(this, "query", (t, n = {}) => {
3073
3096
  t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t }), this.config.disableValidation || Ft(t, this.config.schema);
3074
3097
  const i = n.fetchOpts || {}, s = i.headers || {};
3075
- return R(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
3098
+ return x(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`, {
3076
3099
  ...i,
3077
3100
  method: "POST",
3078
3101
  headers: {
@@ -3108,7 +3131,7 @@ const jt = class jt {
3108
3131
  * db.tx.goals[goalId].link({todos: todoId}),
3109
3132
  * ])
3110
3133
  */
3111
- l(this, "transact", (t) => (this.config.disableValidation || ai(t, this.config.schema), R(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
3134
+ l(this, "transact", (t) => (this.config.disableValidation || ai(t, this.config.schema), x(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`, {
3112
3135
  method: "POST",
3113
3136
  headers: C(this.config, this.impersonationOpts),
3114
3137
  body: JSON.stringify({
@@ -3141,7 +3164,7 @@ const jt = class jt {
3141
3164
  t && n && "ruleParams" in n && (t = { $$ruleParams: n.ruleParams, ...t });
3142
3165
  const i = { query: t, "rules-override": n == null ? void 0 : n.rules };
3143
3166
  n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin);
3144
- const s = await R(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
3167
+ const s = await x(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`, {
3145
3168
  method: "POST",
3146
3169
  headers: C(this.config, this.impersonationOpts),
3147
3170
  body: JSON.stringify(i)
@@ -3176,7 +3199,7 @@ const jt = class jt {
3176
3199
  // @ts-expect-error because we're using a private API (for now)
3177
3200
  "dangerously-commit-tx": n == null ? void 0 : n.__dangerouslyCommit
3178
3201
  };
3179
- 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}`, {
3202
+ return n != null && n.ip && (i["ip-override"] = n.ip), n != null && n.origin && (i["origin-override"] = n.origin), x(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`, {
3180
3203
  method: "POST",
3181
3204
  headers: C(this.config, this.impersonationOpts),
3182
3205
  body: JSON.stringify(i)
@@ -3184,7 +3207,7 @@ const jt = class jt {
3184
3207
  });
3185
3208
  Q(this, Ye, (t) => {
3186
3209
  var n;
3187
- if (t.target !== g(this, M)) {
3210
+ if (t.target !== g(this, j)) {
3188
3211
  g(this, L).info("[socket][open]", t.target.id, "skip; this is no longer the current transport");
3189
3212
  return;
3190
3213
  }
@@ -3192,15 +3215,15 @@ const jt = class jt {
3192
3215
  });
3193
3216
  Q(this, Ze, (t) => {
3194
3217
  var n;
3195
- if (t.target !== g(this, M)) {
3218
+ if (t.target !== g(this, j)) {
3196
3219
  g(this, L).info("[socket][close]", t.target.id, "skip; this is no longer the current transport");
3197
3220
  return;
3198
3221
  }
3199
- 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))));
3222
+ g(this, L).info("[socket][close]", t.target.id), (n = g(this, N)) == null || n.onConnectionStatusChange("closed"), g(this, j) && (ae(this, j, 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))));
3200
3223
  });
3201
3224
  Q(this, et, (t) => {
3202
3225
  var n;
3203
- if (t.target !== g(this, M)) {
3226
+ if (t.target !== g(this, j)) {
3204
3227
  g(this, L).info("[socket][error]", t.target.id, "skip; this is no longer the current transport");
3205
3228
  return;
3206
3229
  }
@@ -3208,7 +3231,7 @@ const jt = class jt {
3208
3231
  });
3209
3232
  Q(this, tt, (t) => {
3210
3233
  var i, s, r, o, a, u;
3211
- if (t.target !== g(this, M)) {
3234
+ if (t.target !== g(this, j)) {
3212
3235
  g(this, L).info("[socket][message]", t.target.id, "skip; this is no longer the current transport");
3213
3236
  return;
3214
3237
  }
@@ -3295,14 +3318,14 @@ const jt = class jt {
3295
3318
  });
3296
3319
  }
3297
3320
  };
3298
- M = new WeakMap(), Ie = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A = new WeakSet(), In = function() {
3299
- g(this, M) && g(this, M).close();
3321
+ j = new WeakMap(), Ie = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A = new WeakSet(), In = function() {
3322
+ g(this, j) && g(this, j).close();
3300
3323
  const t = {
3301
3324
  ...C(this.config, this.impersonationOpts)
3302
3325
  }, 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}`);
3303
- 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;
3326
+ return s.onopen = g(this, Ye), s.onmessage = g(this, tt), s.onclose = g(this, Ze), s.onerror = g(this, et), ae(this, j, s), s;
3304
3327
  }, Be = function() {
3305
- return g(this, M) || G(this, A, In).call(this);
3328
+ return g(this, j) || G(this, A, In).call(this);
3306
3329
  }, vn = function(t, n) {
3307
3330
  const i = G(this, A, Be).call(this);
3308
3331
  g(this, L).info("[send]", t, n, {
@@ -3324,12 +3347,12 @@ M = new WeakMap(), Ie = new WeakMap(), N = new WeakMap(), L = new WeakMap(), A =
3324
3347
  }, Ye = new WeakMap(), Ze = new WeakMap(), et = new WeakMap(), Ct = function() {
3325
3348
  return !g(this, N) || !g(this, N).hasActiveStreams();
3326
3349
  }, kn = function() {
3327
- if (g(this, M) && G(this, A, Ct).call(this)) {
3328
- const t = g(this, M);
3329
- g(this, L).info("cleaning up unused socket", t.id), ae(this, M, null), t.close();
3350
+ if (g(this, j) && G(this, A, Ct).call(this)) {
3351
+ const t = g(this, j);
3352
+ g(this, L).info("cleaning up unused socket", t.id), ae(this, j, null), t.close();
3330
3353
  }
3331
3354
  }, tt = new WeakMap();
3332
- let _t = jt;
3355
+ let _t = Mt;
3333
3356
  var dt = {};
3334
3357
  function Ve(e) {
3335
3358
  let t = e;
@@ -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.167";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","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 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","beforeInclusive","after","afterInclusive","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=($,_,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,P)=>(Mt($,_,"write to private field"),P?P.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 P=[];for(let e=0;e<256;++e)P.push((e+256).toString(16).slice(1));function Cn(e,t=0){return(P[e[t+0]]+P[e[t+1]]+P[e[t+2]]+P[e[t+3]]+"-"+P[e[t+4]]+P[e[t+5]]+"-"+P[e[t+6]]+P[e[t+7]]+"-"+P[e[t+8]]+P[e[t+9]]+"-"+P[e[t+10]]+P[e[t+11]]+P[e[t+12]]+P[e[t+13]]+P[e[t+14]]+P[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 j={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{Pn(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 Pn(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 An(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 An(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:j.Replace,path:f,value:Ge(u[c])}),i.push({op:j.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:j.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:j.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:j.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)?j.Replace:j.Add:j.Remove;if(we(c,d)&&f===j.Replace)return;const m=i.concat(u),y=Se(m,o);s.push(f===j.Remove?{op:f,path:y}:{op:f,path:y,value:d}),r.push(f===j.Add?{op:j.Remove,path:y}:f===j.Remove?{op:j.Add,path:y,value:c}:{op:j.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:j.Remove,path:c,value:a}),s.unshift({op:j.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:j.Add,path:c,value:a}),s.unshift({op:j.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.168";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","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 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","beforeInclusive","after","afterInclusive","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 Pt(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,Pt(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}){Pt(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 At(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 At(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 At=o.decode(Ee);k.enqueue(At)}}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}
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)),M=(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,Pe,ze,me,Ae,je,Me,Ve,Z,St,It,vt,dn,Ot,$t,Je,kt,Et;class se extends EventTarget{constructor(t,n){var i,s;super(),M(this,Z),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,M(this,J),M(this,ve),M(this,Re),M(this,Ke),M(this,Xe),M(this,Fe),M(this,Pe),M(this,ze,null),M(this,me),M(this,Ae),M(this,je,null),M(this,Me,null),M(this,Ve,null),M(this,It,async r=>{var o;S(this,Ae).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,Ae).feed(m.decode(h,{stream:!w})),w&&(I=!1,S(this,Ae).reset(),ae(this,Z,kt).call(this))}while(I)}),M(this,vt,r=>{T(this,me,void 0),!(r.name==="AbortError"||r.type==="aborted")&&ae(this,Z,kt).call(this,gt(r))}),M(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)}),M(this,$t,r=>{T(this,Fe,r)}),M(this,Et,()=>{T(this,Pe,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,Ae,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,Pe)&&clearTimeout(S(this,Pe)),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,Pe=new WeakMap,ze=new WeakMap,me=new WeakMap,Ae=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,Pe,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 Pi(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 R(e,t){Pi(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 Ai(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function ji(){return Ai()?{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 A(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 A(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:R(this.config)})).sessions||{}}}class Li{constructor(t){l(this,"config");l(this,"generateMagicCode",async t=>A(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config),body:JSON.stringify({email:t})}));l(this,"sendMagicCode",async t=>A(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config),body:JSON.stringify({email:t})}));l(this,"verifyMagicCode",async(t,n)=>{const{user:i}=await A(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config),body:JSON.stringify({email:t,code:n})});return i});l(this,"checkMagicCode",async(t,n,i)=>{const s=await A(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config),body:JSON.stringify({email:t,code:n,...i!=null&&i.extraFields?{"extra-fields":i.extraFields}:{}})});return{user:s.user,created:s.created}});l(this,"verifyToken",async t=>(await A(`${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 A(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:R(this.config)})).user});l(this,"deleteUser",async t=>{const n=Object.entries(t).map(([s,r])=>`${s}=${r}`);return(await A(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:R(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 A(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,i=this.config;await A(`${i.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:R(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={...R(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 A(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});l(this,"delete",async t=>A(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:R(this.config,this.impersonationOpts)}));l(this,"deleteMany",async t=>A(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:R(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));l(this,"upload",async(t,n,i={})=>{const{data:s}=await A(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:R(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 A(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:R(this.config)});return t});l(this,"getDownloadUrl",async t=>{const{data:n}=await A(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:R(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 A(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...i,method:"POST",headers:{...s,...R(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),A(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:R(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 A(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:R(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),A(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:R(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||{},...R(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={...R(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"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instantdb/resumable-stream",
3
- "version": "0.22.167",
3
+ "version": "0.22.168",
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.167"
53
+ "@instantdb/admin": "0.22.168"
54
54
  },
55
55
  "scripts": {
56
56
  "test": "vitest",