@instantdb/core 0.22.56 → 0.22.57
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/commonjs/Reactor.d.ts +5 -0
- package/dist/commonjs/Reactor.d.ts.map +1 -1
- package/dist/commonjs/Reactor.js +43 -5
- package/dist/commonjs/Reactor.js.map +1 -1
- package/dist/commonjs/SyncTable.d.ts +140 -0
- package/dist/commonjs/SyncTable.d.ts.map +1 -0
- package/dist/commonjs/SyncTable.js +538 -0
- package/dist/commonjs/SyncTable.js.map +1 -0
- package/dist/commonjs/index.d.ts +21 -1
- package/dist/commonjs/index.d.ts.map +1 -1
- package/dist/commonjs/index.js +19 -1
- package/dist/commonjs/index.js.map +1 -1
- package/dist/commonjs/instaql.d.ts +1 -0
- package/dist/commonjs/instaql.d.ts.map +1 -1
- package/dist/commonjs/instaql.js +9 -5
- package/dist/commonjs/instaql.js.map +1 -1
- package/dist/commonjs/store.d.ts +5 -0
- package/dist/commonjs/store.d.ts.map +1 -1
- package/dist/commonjs/store.js +11 -0
- package/dist/commonjs/store.js.map +1 -1
- package/dist/commonjs/utils/PersistedObject.d.ts +11 -5
- package/dist/commonjs/utils/PersistedObject.d.ts.map +1 -1
- package/dist/commonjs/utils/PersistedObject.js +12 -2
- package/dist/commonjs/utils/PersistedObject.js.map +1 -1
- package/dist/esm/Reactor.d.ts +5 -0
- package/dist/esm/Reactor.d.ts.map +1 -1
- package/dist/esm/Reactor.js +43 -5
- package/dist/esm/Reactor.js.map +1 -1
- package/dist/esm/SyncTable.d.ts +140 -0
- package/dist/esm/SyncTable.d.ts.map +1 -0
- package/dist/esm/SyncTable.js +498 -0
- package/dist/esm/SyncTable.js.map +1 -0
- package/dist/esm/index.d.ts +21 -1
- package/dist/esm/index.d.ts.map +1 -1
- package/dist/esm/index.js +19 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/instaql.d.ts +1 -0
- package/dist/esm/instaql.d.ts.map +1 -1
- package/dist/esm/instaql.js +8 -5
- package/dist/esm/instaql.js.map +1 -1
- package/dist/esm/store.d.ts +5 -0
- package/dist/esm/store.d.ts.map +1 -1
- package/dist/esm/store.js +9 -3
- package/dist/esm/store.js.map +1 -1
- package/dist/esm/utils/PersistedObject.d.ts +11 -5
- package/dist/esm/utils/PersistedObject.d.ts.map +1 -1
- package/dist/esm/utils/PersistedObject.js +12 -2
- package/dist/esm/utils/PersistedObject.js.map +1 -1
- package/dist/standalone/index.js +1579 -1135
- package/dist/standalone/index.umd.cjs +3 -3
- package/package.json +2 -2
- package/src/Reactor.js +60 -4
- package/src/SyncTable.ts +821 -0
- package/src/index.ts +48 -0
- package/src/instaql.js +11 -5
- package/src/store.js +11 -3
- package/src/utils/PersistedObject.ts +15 -6
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
(function(O,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):(O=typeof globalThis<"u"?globalThis:O||self,E(O.instant={}))})(this,function(O){"use strict";var yo=Object.defineProperty;var bo=(O,E,M)=>E in O?yo(O,E,{enumerable:!0,configurable:!0,writable:!0,value:M}):O[E]=M;var y=(O,E,M)=>bo(O,typeof E!="symbol"?E+"":E,M);function E(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=E(t[n]);for(let s=0;s<r.length;s++)e^=r.charCodeAt(s),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const s=n[r],i=E(s);e^=parseInt(i,16),e*=16777619,e=e>>>0;const o=E(t[s]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return E(String(t))}const M={Remove:"remove",Replace:"replace",Add:"add"},Mt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qn=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),ge=Symbol.iterator,L={mutable:"mutable",immutable:"immutable"},Ue={};function de(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Ct(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function xe(t){return Object.getPrototypeOf(t)===Set.prototype}function Le(t){return Object.getPrototypeOf(t)===Map.prototype}function N(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function X(t){return!!g(t)}function g(t){return typeof t!="object"?null:t==null?void 0:t[Mt]}function Ne(t){var e;const n=g(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function V(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!(e!=null&&e.mark)&&((n=e.mark(t,L))===L.immutable||typeof n=="function")}function kt(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=g(B(n,t.key));if(r!==null&&(r==null?void 0:r.original)!==t.original)return null;const s=t.parent.type===3,i=s?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(s&&n.size>i||de(n,i)))return null;e.push(i)}if(t.parent)return kt(t.parent,e);e.reverse();try{Gn(t.copy,e)}catch{return null}return e}function ee(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function B(t,e){return ee(t)===2?t.get(e):t[e]}function he(t,e,n){ee(t)===2?t.set(e,n):t[e]=n}function Fe(t,e){const n=g(t);return(n?N(n):t)[e]}function H(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function qe(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function te(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Gn(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=B(ee(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function Bn(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const Hn=Object.prototype.propertyIsEnumerable;function vt(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!xe(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!Le(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e!=null&&e.mark&&(n=e.mark(t,L),n!==void 0)&&n!==L.mutable){if(n===L.immutable)return Bn(t);if(typeof n=="function"){if(e.enablePatches||e.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 t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(s=>{r[s]=t[s]}),Object.getOwnPropertySymbols(t).forEach(s=>{Hn.call(t,s)&&(r[s]=t[s])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function P(t){t.copy||(t.copy=vt(t.original,t.options))}function pe(t){if(!V(t))return Ne(t);if(Array.isArray(t))return t.map(pe);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,s])=>[r,pe(s)]);if(!Le(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(pe);if(!xe(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=pe(t[n]);return e}function me(t){return X(t)?pe(t):t}function K(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&K(t.parent))}function It(){throw new Error("Cannot modify frozen object")}function re(t,e,n,r,s){{n=n??new WeakMap,r=r??[],s=s??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const a=r.indexOf(o);if(o&&typeof o=="object"&&a!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${s.slice(0,a).map((c,u)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const f=r[u];return typeof c=="object"&&(f instanceof Map||f instanceof Set)?Array.from(f.keys()).indexOf(c):c}).join("/")}`);r.push(o),s.push(e)}else r.push(o)}if(Object.isFrozen(t)||X(t)){r.pop(),s.pop();return}switch(ee(t)){case 2:for(const[a,c]of t)re(a,a,n,r,s),re(c,a,n,r,s);t.set=t.clear=t.delete=It;break;case 3:for(const a of t)re(a,a,n,r,s);t.add=t.clear=t.delete=It;break;case 1:Object.freeze(t);let o=0;for(const a of t)re(a,o,n,r,s),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(a=>{const c=t[a];re(c,a,n,r,s)})}r.pop(),s.pop()}function Ve(t,e){const n=ee(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const s of t)e(r,s,t),r+=1}else t.forEach((r,s)=>e(s,r,t))}function Pt(t,e,n){if(X(t)||!V(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,s=r?new Map:void 0;if(e.add(t),Ve(t,(i,o)=>{var a;if(X(o)){const c=g(o);P(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;he(r?s:t,i,u)}else Pt(o,e,n)}),s){const i=t,o=Array.from(i);i.clear(),o.forEach(a=>{i.add(s.has(a)?s.get(a):a)})}}function Jn(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&Pt(B(n,e),t.finalities.handledSet,t.options)}function ze(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(Ne(e))}))}function We(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const i=kt(t);i&&e(t,i,n,r)}t.finalized=!0}}function Ke(t,e,n,r){const s=g(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((i,o)=>{var a;const c=t.type===3?t.setMap:t.copy;if(H(B(c,e),n)){let u=s.original;s.copy&&(u=s.copy),ze(t),We(t,r,i,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(a=t.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,t.options.updatedValues.set(u,s.original)),he(c,e,u)}}),t.options.enableAutoFreeze&&s.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),V(n,t.options)&&t.finalities.draft.push(()=>{const i=t.type===3?t.setMap:t.copy;H(B(i,e),n)&&Jn(t,e)})}function Yn(t,e,n,r,s){let{original:i,assignedMap:o,options:a}=t,c=t.copy;c.length<i.length&&([i,c]=[c,i],[n,r]=[r,n]);for(let u=0;u<i.length;u+=1)if(o.get(u.toString())&&c[u]!==i[u]){const f=e.concat([u]),l=te(f,s);n.push({op:M.Replace,path:l,value:me(c[u])}),r.push({op:M.Replace,path:l,value:me(i[u])})}for(let u=i.length;u<c.length;u+=1){const f=e.concat([u]),l=te(f,s);n.push({op:M.Add,path:l,value:me(c[u])})}if(i.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const f=e.concat(["length"]),l=te(f,s);r.push({op:M.Replace,path:l,value:i.length})}else for(let f=c.length;i.length<f;f-=1){const l=e.concat([f-1]),d=te(l,s);r.push({op:M.Remove,path:d})}}}function Zn({original:t,copy:e,assignedMap:n},r,s,i,o){n.forEach((a,c)=>{const u=B(t,c),f=me(B(e,c)),l=a?de(t,c)?M.Replace:M.Add:M.Remove;if(H(u,f)&&l===M.Replace)return;const d=r.concat(c),h=te(d,o);s.push(l===M.Remove?{op:l,path:h}:{op:l,path:h,value:f}),i.push(l===M.Add?{op:M.Remove,path:h}:l===M.Remove?{op:M.Add,path:h,value:u}:{op:M.Replace,path:h,value:u})})}function Xn({original:t,copy:e},n,r,s,i){let o=0;t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=te(c,i);r.push({op:M.Remove,path:u,value:a}),s.unshift({op:M.Add,path:u,value:a})}o+=1}),o=0,e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=te(c,i);r.push({op:M.Add,path:u,value:a}),s.unshift({op:M.Remove,path:u,value:a})}o+=1})}function ye(t,e,n,r){const{pathAsArray:s=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return Zn(t,e,n,r,s);case 1:return Yn(t,e,n,r,s);case 3:return Xn(t,e,n,r,s)}}const Se=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!V(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},Qe={get size(){return N(g(this)).size},has(t){return N(g(this)).has(t)},set(t,e){const n=g(this),r=N(n);return(!r.has(t)||!H(r.get(t),e))&&(P(n),K(n),n.assignedMap.set(t,!0),n.copy.set(t,e),Ke(n,t,e,ye)),this},delete(t){if(!this.has(t))return!1;const e=g(this);return P(e),K(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=g(this);if(this.size){P(t),K(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=g(this);N(n).forEach((r,s)=>{t.call(e,this.get(s),s,this)})},get(t){var e,n;const r=g(this),s=N(r).get(t),i=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,s,L))===L.mutable;if(r.options.strict&&Se(s,r.options,i),i||r.finalized||!V(s,r.options)||s!==r.original.get(t))return s;const o=Ue.createDraft({original:s,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return P(r),r.copy.set(t,o),o},keys(){return N(g(this)).keys()},values(){const t=this.keys();return{[ge]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[ge]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[ge](){return this.entries()}},er=Reflect.ownKeys(Qe),$t=(t,e,{isValuesIterator:n})=>()=>{var r,s;const i=e.next();if(i.done)return i;const o=i.value;let a=t.setMap.get(o);const c=g(a),u=((s=(r=t.options).mark)===null||s===void 0?void 0:s.call(r,a,L))===L.mutable;if(t.options.strict&&Se(o,t.options,u),!u&&!c&&V(o,t.options)&&!t.finalized&&t.original.has(o)){const f=Ue.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,f),a=f}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},Oe={get size(){return g(this).setMap.size},has(t){const e=g(this);if(e.setMap.has(t))return!0;P(e);const n=g(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=g(this);return this.has(t)||(P(e),K(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),Ke(e,t,t,ye)),this},delete(t){if(!this.has(t))return!1;const e=g(this);P(e),K(e);const n=g(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=g(this);P(t),K(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=g(this);P(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:$t(t,e,{isValuesIterator:!0})}},entries(){const t=g(this);P(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:$t(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[ge](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(Oe,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const tr=Reflect.ownKeys(Oe),jt=new WeakSet,Dt={get(t,e,n){var r,s;const i=(r=t.copy)===null||r===void 0?void 0:r[e];if(i&&jt.has(i))return i;if(e===Mt)return t;let o;if(t.options.mark){const u=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(u,L),o===L.mutable)return t.options.strict&&Se(u,t.options,!0),u}const a=N(t);if(a instanceof Map&&er.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Qe,"size").get.call(t.proxy);const u=Qe[e];if(u)return u.bind(t.proxy)}if(a instanceof Set&&tr.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(Oe,"size").get.call(t.proxy);const u=Oe[e];if(u)return u.bind(t.proxy)}if(!de(a,e)){const u=Ct(a,e);return u?"value"in u?u.value:(s=u.get)===null||s===void 0?void 0:s.call(t.proxy):void 0}const c=a[e];if(t.options.strict&&Se(c,t.options),t.finalized||!V(c,t.options))return c;if(c===Fe(t.original,e)){if(P(t),t.copy[e]=Ge({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const u=g(t.copy[e]);return P(u),K(u),u.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(t.type===1&&e!=="length"&&!(Number.isInteger(s=Number(e))&&s>=0&&(e===0||s===0||String(s)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const i=Ct(N(t),e);if(i!=null&&i.set)return i.set.call(t.proxy,n),!0;const o=Fe(N(t),e),a=g(o);return a&&H(a.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(H(n,o)&&(n!==void 0||de(t.original,e))||(P(t),K(t),de(t.original,e)&&H(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,Ke(t,e,n,ye)),!0)},has(t,e){return e in N(t)},ownKeys(t){return Reflect.ownKeys(N(t))},getOwnPropertyDescriptor(t,e){const n=N(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?Dt.set.call(this,t,e,void 0,t.proxy):(Fe(t.original,e)!==void 0||e in t.original?(P(t),K(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function Ge(t){const{original:e,parentDraft:n,key:r,finalities:s,options:i}=t,o=ee(e),a={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:s,options:i,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(a.key=r);const{proxy:c,revoke:u}=Proxy.revocable(o===1?Object.assign([],a):a,Dt);if(s.revoke.push(u),jt.add(c),a.proxy=c,n){const f=n;f.finalities.draft.push((l,d)=>{var h,p;const T=g(c);let w=f.type===3?f.setMap:f.copy;const b=B(w,r),m=g(b);if(m){let A=m.original;m.operated&&(A=Ne(b)),ze(m),We(m,ye,l,d),f.options.enableAutoFreeze&&(f.options.updatedValues=(h=f.options.updatedValues)!==null&&h!==void 0?h:new WeakMap,f.options.updatedValues.set(A,m.original)),he(w,r,A)}(p=T.callbacks)===null||p===void 0||p.forEach(A=>{A(l,d)})})}else{const f=g(c);f.finalities.draft.push((l,d)=>{ze(f),We(f,ye,l,d)})}return c}Ue.createDraft=Ge;function nr(t,e,n,r,s){var i;const o=g(t),a=(i=o==null?void 0:o.original)!==null&&i!==void 0?i:t,c=!!e.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const u=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&qe(o),s&&re(u,u,o==null?void 0:o.options.updatedValues),[u,n&&c?[{op:M.Replace,path:[],value:e[0]}]:n,r&&c?[{op:M.Replace,path:[],value:a}]:r]}function rr(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let s,i;e.enablePatches&&(s=[],i=[]);const a=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,L))===L.mutable||!V(t,e)?t:Ge({original:t,parentDraft:null,finalities:r,options:e});return[a,(c=[])=>{const[u,f,l]=nr(a,c,s,i,e.enableAutoFreeze);return e.enablePatches?[u,f,l]:u}]}function Be(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:s=!0}=t;Ve(n,(i,o,a)=>{const c=g(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const u=c.original;if(a instanceof Set){const f=Array.from(a);a.clear(),f.forEach(l=>a.add(i===l?u:l))}else he(a,i,u)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,Be(t))}),s&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function Rt(t){var e;const n=g(t);if(!V(t,n==null?void 0:n.options))return t;const r=ee(t);if(n&&!n.operated)return n.original;let s;function i(){s=r===2?Le(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):vt(t,n==null?void 0:n.options)}if(n){n.finalized=!0;try{i()}finally{n.finalized=!1}}else s=t;if(Ve(s,(o,a)=>{if(n&&H(B(n.original,o),a))return;const c=Rt(a);c!==a&&(s===t&&i(),he(s,o,c))}),r===3){const o=(e=n==null?void 0:n.original)!==null&&e!==void 0?e:s;return xe(o)?new Set(s):new(Object.getPrototypeOf(o)).constructor(s)}return s}function Ut(t){if(!X(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return Rt(t)}const He=(t=>function e(n,r,s){var i,o,a;if(typeof n=="function"&&typeof r!="function")return function(S,...j){return e(S,x=>n.call(this,x,...j),r)};const c=n,u=r;let f=s;if(typeof r!="function"&&(f=r),f!==void 0&&Object.prototype.toString.call(f)!=="[object Object]")throw new Error(`Invalid options: ${f}, 'options' should be an object.`);f=Object.assign(Object.assign({},t),f);const l=X(c)?Ut(c):c,d=Array.isArray(f.mark)?(S,j)=>{for(const x of f.mark){if(typeof x!="function")throw new Error(`Invalid mark: ${x}, 'mark' should be a function.`);const Y=x(S,j);if(Y)return Y}}:f.mark,h=(i=f.enablePatches)!==null&&i!==void 0?i:!1,p=(o=f.strict)!==null&&o!==void 0?o:!1,w={enableAutoFreeze:(a=f.enableAutoFreeze)!==null&&a!==void 0?a:!1,mark:d,strict:p,enablePatches:h};if(!V(l,w)&&typeof l=="object"&&l!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[b,m]=rr(l,w);if(typeof r!="function"){if(!V(l,w))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[b,m]}let A;try{A=u(b)}catch(S){throw qe(g(b)),S}const q=S=>{const j=g(b);if(!X(S)){if(S!==void 0&&!H(S,b)&&(j!=null&&j.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const Y=S==null?void 0:S[Qn];if(Y){const _=Y[0];return w.strict&&typeof S=="object"&&S!==null&&Be({rootDraft:j,value:S,useRawReturn:!0}),m([_])}if(S!==void 0)return typeof S=="object"&&S!==null&&Be({rootDraft:j,value:S}),m([S])}if(S===b||S===void 0)return m([]);const x=g(S);if(w===x.options){if(x.operated)throw new Error("Cannot return a modified child draft.");return m([Ut(S)])}return m([S])};return A instanceof Promise?A.then(q,S=>{throw qe(g(b)),S}):q(A)})();Object.prototype.constructor.toString();function xt(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&Object.keys(t).every(s=>e.hasOwnProperty(s))}function Lt(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>e.hasOwnProperty(n)&&t[n]===e[n])}function Ae(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:xt(t,e)?Object.keys(t).every(n=>Ae(t[n],e[n])):!1}function Je(t){if(!be(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function Nt(t,e){if(!be(t)||!be(e))return e;const n={...t};for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const s=be(t[r])&&be(e[r]);n[r]=s?Nt(t[r],e[r]):e[r]}return n}function be(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sr(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const o=e[i];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[i+1]=="number"?[]:{}),r=r[o]}const s=e[e.length-1];Array.isArray(r)&&typeof s=="number"?r.splice(s,0,n):r[s]=n}function Ft(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const i=e[s];(!(i in r)||typeof r[i]!="object")&&(r[i]=typeof e[s+1]=="number"?[]:{}),r=r[i]}r[e[e.length-1]]=n}function qt(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}qt(t[n],r),ir(t[n])&&delete t[n]}}function ir(t){return t&&Object.keys(t).length===0}const Vt=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,or={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function ar(t){return new Date(t)}function cr(t){return new Date(t+"Z")}const ur=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function fr(t){const e=t.match(ur);if(!e)return null;const[n,r,s,i]=e;return r<=0||s<=0||i<=0?null:r>999?new Date(Date.UTC(r,s-1,i,0,0,0,0)):new Date(Date.UTC(i,r-1,s,0,0,0,0))}function lr(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function dr(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function hr(t){return new Date(t)}function pr(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function yr(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,s,i]=n,o=`${r}${s}${i}:00`;return new Date(o)}return null}function br(t){const[e,n]=t.split(", "),[r,s,i]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,a,c,u,f]=o;return a=Number(a),c=Number(c),u=Number(u),f==="PM"&&a!==12?a+=12:f==="AM"&&a===12&&(a=0),new Date(Date.UTC(i,r-1,s,a,c,u))}function Tr(t){switch(t){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function wr(t){const e=t.match(Vt);if(!e)return null;const[n]=e,r=or[n],s=new Date(t.replace(Vt,"Z"));return new Date(s.getTime()-r*1e3)}const _r=[fr,dr,pr,br,hr,cr,yr,lr,ar,Tr,wr];function gr(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Ye(t){for(const e of _r){const n=gr(e,t);if(n)return n}return null}function mr(t){try{const e=JSON.parse(t);return typeof e=="string"?Ye(e):null}catch{return null}}function Ee(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=Ye(t)||mr(t)||Ye(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}function Sr(t){return t.cardinality==="one"}function Ze(t){return t["value-type"]==="ref"}function Xe(t){return t["value-type"]==="blob"}function se(t,e){return t[e]}function Me(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function z(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&z(t.get(n),r)}function D(t,e,n){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.set(e[0],n);return}const[r,...s]=e;let i=t.get(r);i||(i=new Map,t.set(r,i)),D(i,s,n)}function zt(t,e,n){const r=new Map,s=new Map,i=new Map;for(const o of e){let[a,c,u,f]=o;const l=se(t,c);if(!l){console.warn("no such attr",a,t);continue}l["checked-data-type"]==="date"&&n&&(u=Ee(u),o[2]=u),Ze(l)&&D(i,[u,c,a],o),D(r,[a,c,u],o),D(s,[c,a,u],o)}return{eav:r,aev:s,vae:i}}function Wt(t){const e=new Map,n=new Map,r=new Map,s=new Map;for(const i of Object.values(t)){const o=i["forward-identity"],[a,c,u]=o,f=i["reverse-identity"];if(D(r,[c,u],i),Xe(i)&&D(e,[c,u],i),i["primary?"]&&D(n,[c],i),f){const[l,d,h]=f;D(s,[d,h],i)}}return{blobAttrs:e,primaryKeys:n,forwardIdents:r,revIdents:s}}function Or(t){return{__type:t.__type,attrs:t.attrs,triples:R(t.eav,3),cardinalityInference:t.cardinalityInference,linkIndex:t.linkIndex,useDateObjects:t.useDateObjects}}function Ar(t){return tt(t.attrs,t.triples,t.cardinalityInference,t.linkIndex,t.useDateObjects)}function et(t){t.attrIndexes=Wt(t.attrs)}function tt(t,e,n,r,s){const i=zt(t,e,s);return i.useDateObjects=s,i.attrs=t,i.attrIndexes=Wt(t),i.cardinalityInference=n,i.linkIndex=r,i.__type="store",i}function Te(t,e){var s,i;let n;if(Array.isArray(e[0])){const[o,a]=e[0],c=t.aev.get(o);if(!c)return null;n=(s=R(c,2).find(f=>f[2]===a))==null?void 0:s[0]}else n=e[0];if(!n)return null;const r=e[2];if(Array.isArray(r)&&r.length===2&&t.aev.get(r[0])){const[o,a]=r,c=t.aev.get(o);if(!c)return null;const f=(i=R(c,2).find(T=>T[2]===a))==null?void 0:i[0];if(!f)return null;const[l,d,h,...p]=e;return[n,d,f,...p]}else{const[o,...a]=e;return[n,...a]}}function Er(t,e){const n=Te(t,e);if(!n)return;const[r,s,i]=n,o=se(t.attrs,s);o&&(z(t.eav,[r,s,i]),z(t.aev,[s,r,i]),Ze(o)&&z(t.vae,[i,s,r]))}let Mr=0;function Kt(t,e,n){const[r,s,i]=n;let o;const a=Me(t.ea,[r,s,i]);return a&&(o=a[3]),o||Date.now()*10+Mr++}function Cr(t,e){const n=Te(t,e);if(!n)return;let[r,s,i]=n;const o=se(t.attrs,s);if(!o)return;o["checked-data-type"]==="date"&&t.useDateObjects&&(i=Ee(i));const a=Me(t.eav,[r,s,i]),c=(a==null?void 0:a[3])??Kt(t,o,n),u=[r,s,i,c];Sr(o)?(D(t.eav,[r,s],new Map([[i,u]])),D(t.aev,[s,r],new Map([[i,u]]))):(D(t.eav,[r,s,i],u),D(t.aev,[s,r,i],u)),Ze(o)&&D(t.vae,[i,s,r],u)}function kr(t,e){var d;const n=Te(t,e);if(!n)return;const[r,s,i]=n,o=se(t.attrs,s);if(!o)return;if(!Xe(o))throw new Error("merge operation is not supported for links");const a=Me(t.eav,[r,s]);if(!a)return;const c=(d=a.values().next())==null?void 0:d.value;if(!c)return;const u=c[2],f=Nt(u,i),l=[r,s,f,Kt(t,o,c)];D(t.eav,[r,s],new Map([[f,l]]))}function nt(t,e){var c,u;const[n,r]=e,s=Te(t,[n]);if(!s)return;const[i]=s,o=t.eav.get(i);if(o){for(const f of o.keys()){const l=t.attrs[f];l&&l["on-delete-reverse"]==="cascade"&&R(o.get(f),1).forEach(([d,h,p])=>{var T;return nt(t,[p,(T=l["reverse-identity"])==null?void 0:T[1]])}),(!r||!l||((c=l["forward-identity"])==null?void 0:c[1])===r)&&(z(t.aev,[f,i]),z(t.eav,[i,f]))}o.size===0&&z(t.eav,[i])}const a=t.vae.get(i)&&R(t.vae.get(i),2);a&&a.forEach(f=>{var T,w,b;const[l,d,h]=f,p=t.attrs[d];(!r||!p||((T=p["reverse-identity"])==null?void 0:T[1])===r)&&(z(t.eav,[l,d,h]),z(t.aev,[d,l,h]),z(t.vae,[h,d,l])),p&&p["on-delete"]==="cascade"&&((w=p["reverse-identity"])==null?void 0:w[1])===r&&nt(t,[l,(b=p["forward-identity"])==null?void 0:b[1]])}),((u=t.vae.get(i))==null?void 0:u.size)===0&&z(t.vae,[i])}function Qt(t,e){const n=zt(t.attrs,e,t.useDateObjects);Object.keys(n).forEach(r=>{t[r]=n[r]})}function vr(t,[e]){t.attrs[e.id]=e,et(t)}function Gt(t){return R(t.eav,3)}function Ir(t,[e]){if(!t.attrs[e])return;const n=Gt(t).filter(([r,s])=>s!==e);delete t.attrs[e],et(t),Qt(t,n)}function Pr(t,[e]){const n=t.attrs[e.id];n&&(t.attrs[e.id]={...n,...e},et(t),Qt(t,Gt(t)))}function $r(t,e){const[n,...r]=e;switch(n){case"add-triple":Cr(t,r);break;case"deep-merge-triple":kr(t,r);break;case"retract-triple":Er(t,r);break;case"delete-entity":nt(t,r);break;case"add-attr":vr(t,r);break;case"delete-attr":Ir(t,r);break;case"update-attr":Pr(t,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function R(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())R(r,e-1,n);return n}function Ce(t,e,n){var i,o;const r=[];if(n!=null&&n.hasOwnProperty("$not")){for(const a of e.keys())n.$not!==a&&r.push(e.get(a));return r}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:a,isNull:c,reverse:u}=n.$isNull;if(u)for(const f of e.keys()){const l=t.vae.get(f),d=!l||((i=l.get(a))==null?void 0:i.get(null))||!l.get(a);(c?d:!d)&&r.push(e.get(f))}else{const f=t.aev.get(a);for(const l of e.keys()){const d=!f||((o=f.get(l))==null?void 0:o.get(null))||!f.get(l);(c?d:!d)&&r.push(e.get(l))}}return r}if(n!=null&&n.$comparator)return R(e,1).filter(n.$op);const s=n.in||n.$in||[n];for(const a of s){const c=e.get(a);c&&r.push(c)}return r}function jr(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Dr(t,[e,n,r]){var i,o;switch(jr(e,n,r)){case"e":{const a=t.eav.get(e);return R(a,2)}case"ea":{const a=(i=t.eav.get(e))==null?void 0:i.get(n);return R(a,1)}case"eav":{const a=(o=t.eav.get(e))==null?void 0:o.get(n);return a?Ce(t,a,r):[]}case"ev":{const a=t.eav.get(e);if(!a)return[];const c=[];for(const u of a.values())c.push(...Ce(t,u,r));return c}case"a":{const a=t.aev.get(n);return R(a,2)}case"av":{const a=t.aev.get(n);if(!a)return[];const c=[];for(const u of a.values())c.push(...Ce(t,u,r));return c}case"v":{const a=[];for(const c of t.eav.values())for(const u of c.values())a.push(...Ce(t,u,r));return a}default:return R(t.eav,3)}}function Rr(t,e,n){var s;const r={};for(const[i,o]of e.entries()){const a=(s=t.eav.get(n))==null?void 0:s.get(o.id),c=R(a,1);for(const u of c)r[i]=u[2]}return r}function ie(t,e,n){var r;return(r=t.attrIndexes.forwardIdents.get(e))==null?void 0:r.get(n)}function Bt(t,e,n){var r;return(r=t.attrIndexes.revIdents.get(e))==null?void 0:r.get(n)}function Ur(t,e){return t.attrIndexes.blobAttrs.get(e)}function Ht(t,e){var r;const n=t.attrIndexes.primaryKeys.get(e);return n||((r=t.attrIndexes.forwardIdents.get(e))==null?void 0:r.get("id"))}function xr(t,e){const n=Te(t,e);if(!n)return;const[r,s,i]=n;if(se(t.attrs,s))return Me(t.eav,[r,s])}function Lr(t,e){const n=e.filter(([r,s,i,o,a])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const c=a==null?void 0:a.mode;if(c!=="create"&&c!=="update")return!0;let u=!1;const f=se(t.attrs,i);if(f){const l=Ht(t,f["forward-identity"][1]);u=!!xr(t,[s,l.id,s])}return!(c==="create"&&u||c==="update"&&!u)});return He(t,r=>{n.forEach(s=>{$r(r,s)})})}function Nr(t){return typeof t=="string"&&t.startsWith("?")}function Fr(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return Yt(r,e,n)}return{...n,[t]:e}}function Jt(t,e,n){return t===e?n:null}function qr(t){switch(typeof t){case"string":return t.startsWith("?")?Fr:Jt;default:return Jt}}const Vr=["in","$in","$not","$isNull","$comparator"];function zr(t){for(const e of Vr)if(t.hasOwnProperty(e))return!0;return!1}function Yt(t,e,n){return n?typeof t=="object"?zr(t)?n:null:qr(t)(t,e,n):null}function Wr(t,e,n){return t.reduce((r,s,i)=>{const o=e[i];return Yt(s,o,r)},n)}function Kr(t,e,n){return Br(t,e,n).map(r=>Wr(e,r,n)).filter(r=>r)}function Qr(t,e,n){return e.or?e.or.patterns.flatMap(r=>rt(t,r,n)):e.and?e.and.patterns.reduce((r,s)=>rt(t,s,r),n):n.flatMap(r=>Kr(t,e,r))}function rt(t,e,n=[{}]){return e.reduce((r,s)=>Qr(t,s,r),n)}function st(t,e){return Array.isArray(e)?e.map(n=>st(t,n)):Nr(e)?t[e]:e}function Gr(t,{find:e,where:n}){return rt(t,n).map(s=>st(s,e))}function Br(t,e,n){return Dr(t,st(n,e))}const Hr=/^(?:[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 oe(t){return typeof t=="string"&&Hr.test(t)}const k=[];for(let t=0;t<256;++t)k.push((t+256).toString(16).slice(1));function Jr(t,e=0){return(k[t[e+0]]+k[t[e+1]]+k[t[e+2]]+k[t[e+3]]+"-"+k[t[e+4]]+k[t[e+5]]+"-"+k[t[e+6]]+k[t[e+7]]+"-"+k[t[e+8]]+k[t[e+9]]+"-"+k[t[e+10]]+k[t[e+11]]+k[t[e+12]]+k[t[e+13]]+k[t[e+14]]+k[t[e+15]]).toLowerCase()}let it;const Yr=new Uint8Array(16);function Zr(){if(!it){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");it=crypto.getRandomValues.bind(crypto)}return it(Yr)}const Zt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Xr(t,e,n){var s;if(Zt.randomUUID&&!t)return Zt.randomUUID();t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??Zr();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Jr(r)}function Xt(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function es(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function ts(t,e){return es(Xt(t),Xt(e))}function v(){return Xr()}function ns(t,e){return t.localeCompare(e)}function rs(){let t=ns;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const ss=rs();let is=0;function we(t){return ke(`_${t}`,is++)}function ke(t,e){return`?${t}-${e}`}class ae extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function os(t,e){const n=Ht(t,e);if(!n)throw new ae(`Could not find id attr for ${e}`);return n}function en(t,e,n,r){return[as(t,e,n,r)]}function as(t,e,n,r){return[t(n,r),os(e,n).id,t(n,r),t("time",r)]}function cs(t,e,n){return t.map(r=>r===e?n:r)}function tn(t,e,n,r,s){const i=ie(e,n,s),o=Bt(e,n,s),a=i||o;if(!a)throw new ae(`Could not find attr for ${[n,s]}`);if(a["value-type"]!=="ref")throw new Error(`Attr ${a.id} is not a ref`);const[c,u]=a["forward-identity"],[f,l]=a["reverse-identity"],d=r+1,h=i?[t(u,r),a.id,t(l,d),we("time")]:[t(u,d),a.id,t(l,r),we("time")];return[i?l:u,d,h,a,!!i]}function nn(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),s=new RegExp(`^${r}$`,t?void 0:"i");return function(o){return typeof o!="string"?!1:s.test(o)}}function us(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";if(e.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])>new Date(e.$gt)}:function(s){return s[2]>e.$gt}};if(e.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])>=new Date(e.$gte)}:function(s){return s[2]>=e.$gte}};if(e.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])<new Date(e.$lt)}:function(s){return s[2]<e.$lt}};if(e.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])<=new Date(e.$lte)}:function(s){return s[2]<=e.$lte}};if(e.hasOwnProperty("$like")){const r=nn(!0,e.$like);return{$comparator:!0,$op:function(i){return r(i[2])}}}if(e.hasOwnProperty("$ilike")){const r=nn(!1,e.$ilike);return{$comparator:!0,$op:function(i){return r(i[2])}}}return e}function fs(t,e,n,r,s,i){const o=ie(e,n,s),a=Bt(e,n,s),c=o||a;if(!c)throw new ae(`No attr for etype = ${n} label = ${s}`);if(i!=null&&i.hasOwnProperty("$isNull")){const u=ie(e,n,"id");if(!u)throw new ae(`No attr for etype = ${n} label = id`);return[t(n,r),u.id,{$isNull:{attrId:c.id,isNull:i.$isNull,reverse:!o}},we("time")]}return o?[t(n,r),c.id,us(c,i),we("time")]:[i,c.id,t(n,r),we("time")]}function ls(t,e,n,r,s){const[i,o,a]=s.reduce((c,u)=>{const[f,l,d]=c,[h,p,T]=tn(t,e,f,l,u);return[h,p,[...d,T]]},[n,r,[]]);return[i,o,a]}function ot(t,e,n,r,s,i){const o=s.slice(0,s.length-1),a=s[s.length-1],[c,u,f]=ls(t,e,n,r,o),l=fs(t,e,c,u,a,i);return f.concat([l])}function ds(t,e){return e?[e].concat(t):t}function hs([t,e]){return t==="or"&&Array.isArray(e)}function ps([t,e]){return t==="and"&&Array.isArray(e)}function ys(t,e,n){return(r,s)=>{const i=t(r,s);return e==i?i:`${i}-${n}`}}function rn(t,e,n,r,s,i){const o=t(r,s),a=i.map((c,u)=>{const f=ys(t,o,u);return on(f,n,r,s,c)});return{[e]:{patterns:a,joinSym:o}}}function bs(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function sn(t,e,n,r,s){return bs(s).map(i=>ot(t,e,n,r,i,{$isNull:!0}))}function on(t,e,n,r,s){return Object.entries(s).flatMap(([i,o])=>{if(hs([i,o]))return rn(t,"or",e,n,r,o);if(ps([i,o]))return rn(t,"and",e,n,r,o);if(i==="$entityIdStartsWith")return[];const a=i.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o={...o,$not:o.$ne},delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const c=ot(t,e,n,r,a,o),u=sn(t,e,n,r,a);return[{or:{patterns:[c,...u],joinSym:t(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&a.length>1?[{or:{patterns:sn(t,e,n,r,a),joinSym:t(n,r)}}]:ot(t,e,n,r,a,o)})}function Ts(t,e,n,r){const s=ke;return r?on(s,t,e,n,r).concat(en(s,t,e,n)):en(s,t,e,n)}function ws(t,e,n){return[t(e,n),t("time",n)]}function _s(t,e,n,r,s,i){const[o,a,c,u,f]=tn(t,e,n,r,s),l=cs(c,t(n,r),i);return[o,a,l,u,f]}function gs(t,e,{etype:n,level:r,form:s},i){const o=Object.keys(s).filter(a=>a!=="$");return o.length?Object.entries(i).map(function([c,u]){return o.map(function(d){var p,T,w;const h=!!(e.cardinalityInference&&((w=(T=(p=e.linkIndex)==null?void 0:p[n])==null?void 0:T[d])!=null&&w.isSingular));try{const[b,m,A]=_s(t,e,n,r,d,c),q=cn(e,{etype:b,level:m,form:s[d],join:A}),S=h?q[0]:q;return{[d]:S}}catch(b){if(b instanceof ae)return{[d]:h?void 0:[]};throw b}}).reduce(function(d,h){return{...d,...h}},u)}):Object.values(i)}function ms(t,e,n){return n==="string"?ss(t,e):t>e?1:-1}function ve([t,e],[n,r],s){return e===r||e==null&&r==null?ts(t,n):r==null?1:e==null?-1:ms(e,r,s)}function at(t){return t==null?t:new Date(t).getTime()}function Ss(t,e,n,r){var p;const[s,i,o,a]=t,c=n==="desc"?1:-1;if(((p=e["forward-identity"])==null?void 0:p[2])==="id")return ve(r,[s,a],null)===c;const[u,f]=r,l=e["checked-data-type"],d=l==="date"?at(f):f,h=l==="date"?at(o):o;return ve([u,d],[s,h],l)===c}function Os(t,e){const n=e[1];return t.attrs[n]}function As(t,e,n){const r=Object.keys(n)[0];return ie(t,e,r)}function Es(t,e,n,r){if(n)return Os(t,n);if(r)return As(t,e,r)}function Ms(t,e,n){var s,i;if(!Array.isArray(n.fields))return Ur(t,e);const r=new Map;for(const o of n.fields){const a=ie(t,e,o),c=(s=a==null?void 0:a["forward-identity"])==null?void 0:s[2];c&&Xe(a)&&r.set(c,a)}if(!r.has("id")){const o=ie(t,e,"id"),a=(i=o==null?void 0:o["forward-identity"])==null?void 0:i[2];a&&r.set(a,o)}return r}function Cs(t,{etype:e,pageInfo:n,dq:r,form:s}){var h,p;const i=(h=s==null?void 0:s.$)==null?void 0:h.order,o=an(s),a=ks(s);let c=Gr(t,r);const u=n==null?void 0:n["start-cursor"],f=Es(t,e,u,i);if(f&&((p=f==null?void 0:f["forward-identity"])==null?void 0:p[2])!=="id"){const T=f["checked-data-type"]==="date",w=f.id;c=c.map(([b])=>{var A,q,S,j,x;let m=(x=(j=(S=(q=(A=t.eav.get(b))==null?void 0:A.get(w))==null?void 0:q.values())==null?void 0:S.next())==null?void 0:j.value)==null?void 0:x[2];return T&&(m=at(m)),[b,m]})}c.sort(a==="asc"?function(w,b){return ve(w,b,f==null?void 0:f["checked-data-type"])}:function(w,b){return ve(b,w,f==null?void 0:f["checked-data-type"])});let l={};const d=Ms(t,e,r);for(const T of c){const[w]=T;if(l[w]||!o&&u&&f&&Ss(u,f,a,T))continue;const b=Rr(t,d,w);b&&(l[w]=b)}return l}function ks(t){var n;const e=(n=t.$)==null?void 0:n.order;return e&&e[Object.keys(e)[0]]||"asc"}function an(t){var s,i,o;const e=(s=t.$)==null?void 0:s.offset,n=(i=t.$)==null?void 0:i.before,r=(o=t.$)==null?void 0:o.after;return!e&&!n&&!r}function vs(t,{etype:e,level:n,form:r,join:s,pageInfo:i}){var l,d,h,p,T;if(!an(r)&&(!i||!i["start-cursor"]))return[];const o=ds(Ts(t,e,n,(l=r.$)==null?void 0:l.where),s),a=ws(ke,e,n),c=(d=r.$)==null?void 0:d.fields,u=Cs(t,{etype:e,pageInfo:i,form:r,dq:{where:o,find:a,fields:c}}),f=((h=r.$)==null?void 0:h.limit)||((p=r.$)==null?void 0:p.first)||((T=r.$)==null?void 0:T.last);if(f!=null){n>0&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const w=Object.entries(u);return w.length<=f?u:Object.fromEntries(w.slice(0,f))}return u}function Is(t,e){try{return vs(t,e)}catch(n){if(n instanceof ae)return{};throw n}}function cn(t,e){const n=Is(t,e);return gs(ke,t,e,n)}function Ps(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function $s({store:t,pageInfo:e,aggregate:n},r){const i={data:Object.keys(r).reduce(function(a,c){return n!=null&&n[c]||c==="$$ruleParams"||(a[c]=cn(t,{etype:c,form:r[c],level:0,pageInfo:e==null?void 0:e[c]})),a},{})};return e&&(i.pageInfo=Ps(e)),n&&(i.aggregate=n),i}function js(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const Ds=js();function ct(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(s,i)=>{if(i==="__ops")return n;if(i==="__etype")return t;if(Ds.has(i))return(o,a)=>ct(t,e,[...n,a?[i,t,e,o,a]:[i,t,e,o]])}})}function Rs(t,e){return`lookup__${t}__${JSON.stringify(e)}`}function Ie(t){return t.startsWith("lookup__")}function un(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function Us(t){return new Proxy({__etype:t},{get(e,n){if(n==="__etype")return t;const r=n;return Ie(r)?ct(t,un(r),[]):ct(t,r,[])}})}function ut(){return new Proxy({},{get(t,e){return Us(e)}})}const xs=ut();function fn(t){return t.__ops}function Ls(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,s=[];for(const o of e){const a=n[o];if(a)s.push(a);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,u]=o;s.push([n[c],u])}else s.push(o)}const[i]=e;if((i==="add-triple"||i==="retract-triple")&&r.has(e[2])){const o=s[1];s[1]=s[3],s[3]=o}return s}function I(t,e,n){return Object.values(t).find(r=>{const[s,i,o]=r["forward-identity"];return i===e&&o===n})}function ne(t,e,n){return Object.values(t).find(r=>{const s=r["reverse-identity"];if(!s)return!1;const[i,o,a]=s;return o===e&&a===n})}function Ns(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function ft(t,e,n){return n.indexOf(".")!==-1&&!I(t,e,n)}function lt(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function Fs(t,e,n){if(!ft(t,e,n))return I(t,e,n);const r=lt(n),s=I(t,e,r)||ne(t,e,r);if(s&&s["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return s}function dt(t){return typeof t=="string"&&!Ie(t)?null:typeof t=="string"&&Ie(t)?un(t):Ns(t)}function U(t,e,n){const r=dt(n);if(r===null)return n;const[s,i]=r,o=Fs(t,e,s);if(!o||!o["unique?"])throw new Error(`${s} is not a unique attribute.`);return[o.id,i]}function ln(t,e,n,r){const s=U(t,e,n);return Array.isArray(s)?[["add-triple",s,I(t,e,"id").id,s]].concat(r):r}function qs({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=I(t,e,i),u=ne(t,e,i);return a.map(f=>c?["add-triple",U(t,e,n),c.id,U(t,c["reverse-identity"][1],f)]:["add-triple",U(t,u["forward-identity"][1],f),u.id,U(t,e,n)])});return ln(t,e,n,s)}function Vs({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=I(t,e,i),u=ne(t,e,i);return a.map(f=>c?["retract-triple",U(t,e,n),c.id,U(t,c["reverse-identity"][1],f)]:["retract-triple",U(t,u["forward-identity"][1],f),u.id,U(t,e,n)])});return ln(t,e,n,s)}function zs(t,e,n){if(Array.isArray(n)){const[r,s]=n;for(const i of t||[]){const o=i==null?void 0:i.aev.get(r);if(o){for(const[a,c,u]of R(o,2))if(u===s)return!0}}}else for(const r of t||[]){const s=r==null?void 0:r.eav.get(n);if(s){for(const i of s.keys())if(r.attrs[i]["forward-identity"][1]==e)return!0}}return!1}function dn({stores:t,attrs:e},[n,r,s,i]){return(i==null?void 0:i.upsert)===!1?{mode:"update"}:(i==null?void 0:i.upsert)===!0?null:zs(t,n,r)?{mode:"update"}:null}function Ws(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Je(i),c=U(n,r,s);return[["id",c]].concat(Object.entries(a)).map(([f,l])=>{const d=I(n,r,f);return d["checked-data-type"]==="date"&&t.useDateObjects&&(l=Ee(l)),["add-triple",c,d.id,l,{mode:"create"}]})}function Ks(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Je(i),c=U(n,r,s),u=dn(t,[r,c,i,o]);return[["id",c]].concat(Object.entries(a)).map(([l,d])=>{const h=I(n,r,l);return h["checked-data-type"]==="date"&&t.useDateObjects&&(d=Ee(d)),["add-triple",c,h.id,d,...u?[u]:[]]})}function Qs({attrs:t},[e,n]){return[["delete-entity",U(t,e,n),e]]}function Gs(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Je(i),c=U(n,r,s),u=dn(t,[r,c,i,o]),f=Object.entries(a).map(([d,h])=>{const p=I(n,r,d);return["deep-merge-triple",c,p.id,h,...u?[u]:[]]});return[["add-triple",c,I(n,r,"id").id,c,...u?[u]:[]]].concat(f)}function Bs({attrs:t},[e,n,r]){return[["rule-params",U(t,e,n),e,r]]}function Hs(t){const[e,n,r,s,i]=t;if(!s)return t;const o={...s};return delete o.id,[e,n,r,o,...i?[i]:[]]}function Js(t,e){const[n,...r]=Hs(e);switch(n){case"merge":return Gs(t,r);case"create":return Ws(t,r);case"update":return Ks(t,r);case"link":return qs(t,r);case"unlink":return Vs(t,r);case"delete":return Qs(t,r);case"ruleParams":return Bs(t,r);default:throw new Error(`unsupported action ${n}`)}}function Ys(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function Zs(t,e,n){var a,c;const r=(c=(a=t.entities[e])==null?void 0:a.attrs)==null?void 0:c[n];if(n==="id")return null;if(!r)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:s,indexed:i}=r==null?void 0:r.config,o=Ys(r==null?void 0:r.valueType);return{"index?":i,"unique?":s,"checked-data-type":o}}function Pe(t,e,n,r){const s=t?Zs(t,e,n):null,i=v(),a=[v(),e,n];return{id:i,"forward-identity":a,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}function Xs(t,e,n){return Object.values(t.links).find(s=>s.forward.on===e&&s.forward.label===n||s.reverse.on===e&&s.reverse.label===n)}function ei(t,e,n){const r=Xs(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:s,reverse:i}=r;return{"forward-identity":[v(),s.on,s.label],"reverse-identity":[v(),i.on,i.label],cardinality:s.has==="one"?"one":"many","unique?":i.has==="one","on-delete":s.onDelete,"on-delete-reverse":i.onDelete}}function hn(t,e,n,r){const s=t?ei(t,e,n):null,i=v(),o=[v(),e,n],a=[v(),n,e];return{id:i,"forward-identity":o,"reverse-identity":a,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}const ti=new Set(["create","update","merge","link","unlink"]),ni=new Set(["link","unlink"]),ri=new Set(["create","update","merge"]),si=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),ht={"unique?":!0,"index?":!0},ii={...ht,cardinality:"one"};function oi(t){const e=[],[n,r,s,i]=t;if(!si.has(n))return e;const o=dt(s);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[a,c]of Object.entries(i)){const u=Array.isArray(c)?c:[c];for(const f of u){const l=dt(f);l&&e.push({etype:r,lookupPair:l,linkLabel:a})}}return e}function ai({attrs:t,schema:e},n){var u,f;const[r,s,i]=[new Set,{...t},[]];function o(l){s[l.id]=l,i.push(["add-attr",l]),r.add(l.id)}function a(l){l!=null&&l.isUnsynced&&!r.has(l.id)&&(i.push(["add-attr",l]),r.add(l.id))}function c(l,d){const h=I(s,l,d),p=ne(s,l,d);a(h),a(p),!h&&!p&&o(hn(e,l,d,ii))}for(const l of n)for(const{etype:d,lookupPair:h,linkLabel:p}of oi(l)){const T=h[0];if(p){c(d,p);const w=I(s,d,p),b=ne(s,d,p);a(w),a(b);const m=((u=w==null?void 0:w["reverse-identity"])==null?void 0:u[1])||((f=b==null?void 0:b["forward-identity"])==null?void 0:f[1])||p;if(ft(s,m,T))c(m,lt(T));else{const A=I(s,m,T);A||o(Pe(e,m,T,ht)),a(A)}}else if(ft(s,d,T))c(d,lt(T));else{const w=I(s,d,T);w||o(Pe(e,d,T,ht)),a(w)}}for(const l of n){const[d,h,p,T]=l;if(ti.has(d)){const w=I(s,h,"id");a(w),w||o(Pe(e,h,"id",{"unique?":!0}));for(const b of Object.keys(T)){const m=I(s,h,b);if(a(m),ri.has(d)&&(m||o(Pe(e,h,b,b==="id"?{"unique?":!0}:null))),ni.has(d)){const A=ne(s,h,b);!m&&!A&&o(hn(e,h,b)),a(A)}}}}return[s,i]}function ci(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>fn(c)),[s,i]=ai(t,r),o={...t,attrs:s},a=r.flatMap(c=>Js(o,c));return[...i,...a]}class pt{constructor(e){this.dbName=e,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=s=>{n(s)},r.onsuccess=s=>{const i=s.target;e(i.result)},r.onupgradeneeded=s=>{s.target.result.createObjectStore(this._storeName)}})}async getItem(e){const n=await this._dbPromise;return new Promise((r,s)=>{const a=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);a.onerror=c=>{s(c)},a.onsuccess=c=>{a.result?r(a.result):r(null)}})}async setItem(e,n){const r=await this._dbPromise;return new Promise((s,i)=>{const c=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,e);c.onerror=u=>{i(u)},c.onsuccess=u=>{s()}})}}class yt{static async getIsOnline(){return navigator.onLine}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class ce extends Error{constructor(e,n){super(e),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,ce),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class _e extends ce{constructor(e){var s;const n=((s=e.body)==null?void 0:s.message)||`API Error (${e.status})`;super(n,e.body.hint);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,_e),this.name="InstantAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"InstantAPIError"}}async function W(t,e){const n=await fetch(t,e),r=await n.json();return n.status===200?Promise.resolve(r):Promise.reject(new _e({status:n.status,body:r}))}function ui({apiURI:t,appId:e,email:n}){return W(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}async function fi({apiURI:t,appId:e,email:n,code:r,refreshToken:s}){return await W(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n,code:r,...s?{"refresh-token":s}:{}})})}async function li({apiURI:t,appId:e,refreshToken:n}){return await W(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,"refresh-token":n})})}async function di({apiURI:t,appId:e}){return await W(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e})})}async function pn({apiURI:t,appId:e,code:n,codeVerifier:r,refreshToken:s}){return await W(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,code:n,code_verifier:r,refresh_token:s})})}async function hi({apiURI:t,appId:e,nonce:n,idToken:r,clientName:s,refreshToken:i}){return await W(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,nonce:n,id_token:r,client_name:s,refresh_token:i})})}async function pi({apiURI:t,appId:e,refreshToken:n}){return await W(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,refresh_token:n})})}async function yi({apiURI:t,appId:e,path:n,file:r,refreshToken:s,contentType:i,contentDisposition:o}){const a={app_id:e,path:n,authorization:`Bearer ${s}`,"content-type":i||r.type};return o&&(a["content-disposition"]=o),await W(`${t}/storage/upload`,{method:"PUT",headers:a,body:r})}async function bi({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await W(`${t}/storage/files?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}async function Ti({apiURI:t,appId:e,fileName:n,refreshToken:r,metadata:s={}}){const{data:i}=await W(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({app_id:e,filename:n})});return i}async function wi(t,e){return(await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok}async function _i({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await W(`${t}/storage/signed-download-url?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}let bt=!1,yn=!1,bn=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(bt=!!window.localStorage.getItem("devBackend"),yn=!!window.localStorage.getItem("__instantLogging"),bn=!!window.localStorage.getItem("__devtoolLocalDash"));function Tn(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function gi(t,e,n){const r={peers:{}};if(e&&"user"in e?e.user:!0){const i=Tn(t.user??{},e==null?void 0:e.keys);r.user={...i,peerId:n}}for(const i of Object.keys(t.peers??{})){const o=(e==null?void 0:e.peers)===void 0,a=Array.isArray(e==null?void 0:e.peers)&&(e==null?void 0:e.peers.includes(i));if(o||a){const c=Tn(t.peers[i],e==null?void 0:e.keys);r.peers[i]={...c,peerId:i}}}return r}function mi(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!Lt(t.user,e.user))||!xt(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!Lt(t.peers[r],e.peers[r]))return!0;return!1}class wn{constructor(){y(this,"promise");y(this,"_resolve");y(this,"_reject");this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}function Si(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}class _n{constructor(e,n,r,s,i=u=>u,o=u=>u,a=100,c=1e3){this._subs=[],this._nextSave=null,this._persister=e,this._key=n,this._onMerge=s,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=i,this.parse=o,this._saveThrottleMs=a,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=c,this._load()}async _getFromStorage(){try{return this.parse(await this._persister.getItem(this._key))}catch(e){return console.error(`Unable to read from storage for key=${this._key}`,e),null}}async _load(){const e=await this._getFromStorage();this._isLoading=!1,this._onMerge(e,this.currentValue);for(const n of this._loadedCbs)n()}async waitForLoaded(){if(!this._isLoading)return;await new Promise(n=>{this._loadedCbs.push(n)})}isLoading(){return this._isLoading}version(){return this._version}async waitForSync(){if(!this._nextSave)return;await new Promise(n=>{this._pendingSaveCbs.push(n)})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const e of this._pendingSaveCbs)e();this._pendingSaveCbs.length=0}async flush(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())}_enqueuePersist(e){if(this._nextSave){e&&this._pendingSaveCbs.push(e);return}this._nextSave=setTimeout(()=>{Si(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(e,n){this._version++,this.currentValue=e(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue)}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}}function gn(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":s}=r,{"join-rows":i}=s;for(const o of i)for(const a of o)e.push(a);gn(n["child-nodes"],e)})}function mn(t){const e=[];return gn(t,e),e}function Sn(t){return Object.values(t.links).reduce((e,n)=>{var r,s;return e[r=n.forward.on]??(e[r]={}),e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},e[s=n.reverse.on]??(e[s]={}),e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e},{})}const Tt="v0.22.56";function Oi(t,e){return{info:t?(...n)=>console.info(...n,e()):()=>{},debug:t?(...n)=>console.debug(...n,e()):()=>{},error:t?(...n)=>console.error(...n,e()):()=>{}}}class ${constructor(e,n,r,s={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=s,this.metadata={}}clientRequired(){return new $(this.valueType,!1,this.isIndexed,this.config)}optional(){return new $(this.valueType,!1,this.isIndexed,this.config)}unique(){return new $(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new $(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class $e{constructor(e,n){this.attrs=e,this.links=n}asType(){return new $e(this.attrs,this.links)}}class je{constructor(e,n,r){this.entities=e,this.links=n,this.rooms=r}withRoomSchema(){return new je(this.entities,this.links,{})}}class C extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const On=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Ai=t=>t.valueType||"unknown",An=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},Ei=(t,e,n,r,s,i,o)=>{const a=i.valueType==="json",c=(u,f,l)=>{if(!An(l,f,a))throw new C(`Invalid value for operator '${u}' on attribute '${r}' in entity '${s}'. Expected ${f}, but received: ${typeof l}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new C(`Operator '${t}' for attribute '${r}' in entity '${s}' must be an array, but received: ${typeof e}`,o);for(const u of e)c(t,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!i.isIndexed)throw new C(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${s}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;default:throw new C(`Unknown operator '${t}' for attribute '${r}' in entity '${s}'`,o)}},ue=(t,e,n,r,s)=>{const i=Ai(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){if(o)return;const c=t;for(const[u,f]of Object.entries(c))Ei(u,f,i,e,r,n,`${s}.${u}`)}else if(!An(t,i,o))throw new C(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${i}, but received: ${typeof t}`,s)},Mi=(t,e,n,r,s)=>{const i=t.split(".");if(i.length<2)throw new C(`Invalid dot notation path '${t}'. Must contain at least one dot.`,s);let o=n;for(let f=0;f<i.length-1;f++){const l=i[f],d=r.entities[o];if(!d)throw new C(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,s);const h=d.links[l];if(!h){const p=Object.keys(d.links);throw new C(`Link '${l}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${p.length>0?p.join(", "):"none"}`,s)}o=h.entityName}const a=i[i.length-1],c=r.entities[o];if(!c)throw new C(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,s);if(a==="id"){if(typeof e=="string"&&!oe(e))throw new C(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,s);ue(e,t,new $("string",!1,!0),n,s);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof e=="string"&&!oe(e))throw new C(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${e}`,s);ue(e,t,new $("string",!1,!0),n,s);return}if(!u){const f=Object.keys(c.attrs);throw new C(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${f.length>0?f.join(", ")+", id":"id"}`,s)}ue(e,t,u,n,s)},En=(t,e,n,r)=>{for(const[s,i]of Object.entries(t)){if(s==="or"||s==="and"){if(Array.isArray(i))for(const u of i)typeof u=="object"&&u!==null&&En(u,e,n,`${r}.${s}[${u}]`);continue}if(s==="id"){ue(i,"id",new $("string",!1,!0),e,`${r}.id`);continue}if(s.includes(".")){Mi(s,i,e,n,`${r}.${s}`);continue}const o=n.entities[e];if(!o)continue;const a=o.attrs[s],c=o.links[s];if(!a&&!c){const u=Object.keys(o.attrs),f=Object.keys(o.links);throw new C(`Attribute or link '${s}' does not exist on entity '${e}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${f.length>0?f.join(", "):"none"}`,`${r}.${s}`)}if(a)ue(i,s,a,e,`${r}.${s}`);else if(c){if(typeof i=="string"&&!oe(i))throw new C(`Invalid value for link '${s}' in entity '${e}'. Expected a UUID, but received: ${i}`,`${r}.${s}`);const u=new $("string",!1,!0);ue(i,s,u,e,`${r}.${s}`)}}},Ci=(t,e,n,r,s=0)=>{for(const o of Object.keys(t))if(!On.includes(o))throw new C(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${On.join(", ")}. Found: ${o}`,r);const i=["offset","before","after","first","last"];for(const o of i)if(t[o]!==void 0&&s>0)throw new C(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new C(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);En(t.where,e,n,r?`${r}.where`:"where")}},Mn=(t,e,n,r,s=0)=>{var i;if(!t||typeof t!="object")throw new C(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const o of Object.keys(t))if(o!=="$"){if(n&&!(o in n.entities[e].links)){const c=Object.keys(n.entities[e].links);throw new C(`Link '${o}' does not exist on entity '${e}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${o}`)}const a=t[o];if(typeof a=="object"&&a!==null){const c=(i=n==null?void 0:n.entities[e].links[o])==null?void 0:i.entityName;c&&Mn(a,c,n,`${r}.${o}`,s+1)}}else{const a=t[o];if(typeof a!="object"||a===null)throw new C(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof a}`,`${r}.$`);Ci(a,e,n,`${r}.$`,s)}},wt=(t,e)=>{if(typeof t!="object"||t===null)throw new C(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new C(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new C(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new C(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const s=Object.keys(e.entities);throw new C(`Entity '${r}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,r)}Mn(n[r],r,e,r,0)}}},Cn=t=>typeof t!="string"?!1:Ie(t)?!0:oe(t);class F extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const kn=t=>t.length>0?t.join(", "):"none",ki=(t,e)=>new F(`Entity '${t}' does not exist in schema. Available entities: ${kn(e)}`),_t={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},vi=(t,e)=>{var n;return t==null?!0:((n=_t[e.valueType])==null?void 0:n.call(_t,t))??!1},vn=(t,e)=>{const n=e.entities[t];if(!n)throw ki(t,Object.keys(e.entities));return n},gt=(t,e,n)=>{const r=vn(t,n);if(typeof e!="object"||e===null)throw new F(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(s==="id")continue;const o=r.attrs[s];if(o&&!vi(i,o))throw new F(`Invalid value for attribute '${s}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof i}`)}},In=(t,e,n)=>{const r=vn(t,n);if(typeof e!="object"||e===null)throw new F(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(!r.links[s]){const a=Object.keys(r.links);throw new F(`Link '${s}' does not exist on entity '${t}'. Available links: ${kn(a)}`)}if(i!=null){if(Array.isArray(i)){for(const a of i)if(!Cn(a))throw new F(`Invalid entity ID in link '${s}' for entity '${t}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!Cn(i))throw new F(`Invalid UUID in link '${s}' for entity '${t}'. Expected a UUID, but received: ${i}`)}}},Ii={create:gt,update:gt,merge:gt,link:In,unlink:In,delete:()=>{}},Pi=(t,e)=>{if(!e)return;const[n,r,s,i]=t;if(!Array.isArray(s)&&!oe(s))throw new F(`Invalid id for entity '${r}'. Expected a UUID, but received: ${s}`);if(typeof r!="string")throw new F(`Entity name must be a string, but received: ${typeof r}`);const o=Ii[n];o&&i!==void 0&&o(r,i,e)},Pn=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new F(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new F(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const s of r.__ops){if(!Array.isArray(s))throw new F(`Transaction operation must be an array, but received: ${typeof s}`);Pi(s,e)}}};let $n=0;class jn{constructor(e){this.type="ws",this.id=`${this.type}_${$n++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(e){return this.conn.send(JSON.stringify(e))}}class $i{constructor(e,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${$n++}`,this.url=n,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const s=JSON.parse(r.data);if(s.op==="sse-init"){this.initParams={machineId:s["machine-id"],sessionId:s["session-id"],sseToken:s["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:s})},this.conn.onerror=r=>{this.handleError()}}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(e){try{(await fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:e})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const e=this.sendQueue;this.sendQueue=[];const n=this.postMessages(e);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(e){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(e),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()}}const J={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},ji=3e4,Di=3e4,Ri=200,Ui={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},mt="_instant_oauth_redirect",St="currentUser";function xi({transportType:t,appId:e,apiURI:n,wsURI:r,EventSourceImpl:s}){if(!s)return new jn(`${r}?app_id=${e}`);switch(t){case"ws":return new jn(`${r}?app_id=${e}`);case"sse":return new $i(s,`${n}/runtime/sse?app_id=${e}`);default:throw new Error("Unknown transport type "+t)}}function Li(){return typeof window<"u"||typeof chrome<"u"}const Dn={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Ni(t,e){var r;const n=typeof t=="string"?JSON.parse(t):t;for(const s in n){const i=n[s];if((r=i==null?void 0:i.result)!=null&&r.store){const o=i.result.store;i.result.store=Ar({...o,useDateObjects:e})}}return n}function Fi(t){var n;const e={};for(const r in t){const s=t[r],i={...s};(n=s.result)!=null&&n.store&&(i.result={...s.result,store:Or(s.result.store)}),e[r]=i}return e}function Rn(t){return[...t].sort((e,n)=>{const[r,s]=e,[i,o]=n,a=s.order||0,c=o.order||0;return a==c?r<i?-1:r>i?1:0:a-c})}class qi{constructor(e,n=pt,r=yt,s,i){y(this,"attrs");y(this,"_isOnline",!0);y(this,"_isShutdown",!1);y(this,"status",J.CONNECTING);y(this,"querySubs");y(this,"pendingMutations");y(this,"queryCbs",{});y(this,"queryOnceDfds",{});y(this,"authCbs",[]);y(this,"attrsCbs",[]);y(this,"mutationErrorCbs",[]);y(this,"connectionStatusCbs",[]);y(this,"config");y(this,"_persister");y(this,"mutationDeferredStore",new Map);y(this,"_reconnectTimeoutId",null);y(this,"_reconnectTimeoutMs",0);y(this,"_transport");y(this,"_transportType","ws");y(this,"_EventSource");y(this,"_wsOk",null);y(this,"_localIdPromises",{});y(this,"_errorMessage",null);y(this,"_oauthCallbackResponse",null);y(this,"_linkIndex",null);y(this,"_broadcastChannel");y(this,"_rooms",{});y(this,"_roomsPendingLeave",{});y(this,"_presence",{});y(this,"_broadcastQueue",[]);y(this,"_broadcastSubs",{});y(this,"_currentUserCached",{isLoading:!0,error:void 0,user:void 0});y(this,"_beforeUnloadCbs",[]);y(this,"_dataForQueryCache",{});y(this,"_log");y(this,"_pendingTxCleanupTimeout");y(this,"_pendingMutationCleanupThreshold");y(this,"_inFlightMutationEventIds",new Set);y(this,"_onMergeQuerySubs",(e,n)=>{const r=e||{},s={...n};Object.entries(n).forEach(([o,a])=>{var f;const c=(f=r==null?void 0:r[o])==null?void 0:f.result,u=a.result;c&&!u&&(s[o].result=c)}),Object.keys(r).filter(o=>!n[o]).sort((o,a)=>{var f,l;const c=((f=r[o])==null?void 0:f.lastAccessed)||0;return(((l=r[a])==null?void 0:l.lastAccessed)||0)-c}).slice(0,this.queryCacheLimit).forEach(o=>{s[o]=r[o]}),this.querySubs.set(o=>s),this.loadedNotifyAll()});y(this,"_onMergePendingMutations",(e,n)=>{const r=new Map([...e.entries(),...n.entries()]);this.pendingMutations.set(i=>r),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,e).forEach(([i,o])=>{!n.has(i)&&!o["tx-id"]&&this._sendMutation(i,o)})});y(this,"getPreviousResult",e=>{const n=E(e);return this.dataForQuery(n)});y(this,"notifyOne",e=>{var i;const n=this.queryCbs[e]??[],r=(i=this._dataForQueryCache[e])==null?void 0:i.data,s=this.dataForQuery(e);s&&(Ae(s,r)||n.forEach(o=>o.cb(s)))});y(this,"notifyOneQueryOnce",e=>{const n=this.queryOnceDfds[e]??[],r=this.dataForQuery(e);n.forEach(s=>{this._completeQueryOnce(s.q,e,s.dfd),s.dfd.resolve(r)})});y(this,"notifyQueryError",(e,n)=>{(this.queryCbs[e]||[]).forEach(s=>s.cb({error:n}))});y(this,"pushTx",e=>{this.config.disableValidation||Pn(e,this.config.schema);try{const n=ci({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(r=>{var s;return(s=r==null?void 0:r.result)==null?void 0:s.store}),useDateObjects:this.config.useDateObjects},e);return this.pushOps(n)}catch(n){return this.pushOps([],n)}});y(this,"pushOps",(e,n)=>{const r=v(),s=[...this.pendingMutations.currentValue.values()],i=Math.max(0,...s.map(c=>c.order||0))+1,o={op:"transact","tx-steps":e,created:Date.now(),error:n,order:i};this.pendingMutations.set(c=>(c.set(r,o),c));const a=new wn;return this.mutationDeferredStore.set(r,a),this._sendMutation(r,o),this.notifyAll(),a.promise});y(this,"_transportOnOpen",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][open]",n.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(J.OPENED),this.getCurrentUser().then(r=>{var s;this._trySend(v(),{op:"init","app-id":this.config.appId,"refresh-token":(s=r.user)==null?void 0:s.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(r=>{this._log.error("[socket][error]",n.id,r)})});y(this,"_transportOnMessage",e=>{const n=e.target,r=e.message;if(this._transport!==n){this._log.info("[socket][message]",n.id,r,"skip; this is no longer the current transport");return}!this._wsOk&&n.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(n.id,e.message)});y(this,"_transportOnError",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][error]",n.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",n.id,e)});y(this,"_scheduleReconnect",()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)});y(this,"_transportOnClose",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][close]",n.id,"skip; this is no longer the current transport");return}this._setStatus(J.CLOSED);for(const r of Object.values(this._rooms))r.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",n.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",n.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()});if(this._EventSource=i,this.config={...Ui,...e},this.queryCacheLimit=this.config.queryCacheLimit??10,this._pendingTxCleanupTimeout=this.config.pendingTxCleanupTimeout??Di,this._pendingMutationCleanupThreshold=this.config.pendingMutationCleanupThreshold??Ri,this._log=Oi(e.verbose||bt||yn,()=>this._reactorStats()),this.versions={...s||{},"@instantdb/core":Tt},this.config.schema&&(this._linkIndex=Sn(this.config.schema)),!!Li()){if(!e.appId)throw new Error("Instant must be initialized with an appId.");if(!oe(e.appId))throw new Error(`Instant must be initialized with a valid appId. \`${e.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",async o=>{var a;try{if(((a=o.data)==null?void 0:a.type)==="auth"){const c=await this.getCurrentUser();this.updateUser(c.user)}}catch(c){this._log.error("[error] handle broadcast channel",c)}})),this._initStorage(n),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(o=>{this._isOnline=o,this._startSocket(),r.listen(a=>{a!==this._isOnline&&(this._log.info("[network] online =",a),this._isOnline=a,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",J.CLOSED),this._setStatus(J.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(e){this.config={...this.config,schema:e,cardinalityInference:!!e},this._linkIndex=e?Sn(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(e){this._persister=new e(`instant_${this.config.appId}_5`),this.querySubs=new _n(this._persister,"querySubs",{},this._onMergeQuerySubs,Fi,n=>Ni(n,this.config.useDateObjects)),this.pendingMutations=new _n(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const e of this._beforeUnloadCbs)e()}_finishTransaction(e,n,r){const s=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const i=e!=="error"&&e!=="timeout";if(!s&&!i&&console.error("Mutation failed",{status:e,eventId:n,...r}),!!s)if(i)s.resolve({status:e,eventId:n});else if(r.type){const{status:o,...a}=r;s.reject(new _e({body:a,status:o}))}else s.reject(new ce(r.message,r.hint))}_setStatus(e,n){this.status=e,this._errorMessage=n,this.notifyConnectionStatusSubs(e)}_flushEnqueuedRoomData(e){var s,i;const n=(i=(s=this._presence[e])==null?void 0:s.result)==null?void 0:i.user,r=this._broadcastQueue[e];if(this._broadcastQueue[e]=[],n&&this._trySetPresence(e,n),r)for(const o of r){const{topic:a,roomType:c,data:u}=o;this._tryBroadcast(e,c,a,u)}}_handleReceive(e,n){var s,i,o,a,c,u;const r=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(Dn[n.op]||this._log.info("[receive]",e,n.op,n),n.op){case"init-ok":this._setStatus(J.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const _ of Object.keys(this._rooms)){const Q=(i=(s=this._presence[_])==null?void 0:s.result)==null?void 0:i.user;this._tryJoinRoom(_,Q)}break;case"add-query-exists":this.notifyOneQueryOnce(E(n.q));break;case"add-query-ok":const{q:f,result:l}=n,d=E(f),h=(a=(o=l==null?void 0:l[0])==null?void 0:o.data)==null?void 0:a["page-info"],p=(u=(c=l==null?void 0:l[0])==null?void 0:c.data)==null?void 0:u.aggregate,T=mn(l),w=tt(this.attrs,T,r,this._linkIndex,this.config.useDateObjects);this.querySubs.set(_=>(_[d].result={store:w,pageInfo:h,aggregate:p,processedTxId:n["processed-tx-id"]},_)),this._cleanupPendingMutationsQueries(),this.notifyOne(d),this.notifyOneQueryOnce(d),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:b,attrs:m}=n,A=n["processed-tx-id"];m&&this._setAttrs(m),this._cleanupPendingMutationsTimeout();const q=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,A);q!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>q);const S=Rn(q.entries()),j=b.map(_=>{var Vn,zn,Wn,Kn;const Q=_["instaql-query"],G=_["instaql-result"],fe=E(Q),le=mn(G),Z=tt(this.attrs,le,r,this._linkIndex,this.config.useDateObjects),Re=this._applyOptimisticUpdates(Z,S,A),ho=(zn=(Vn=G==null?void 0:G[0])==null?void 0:Vn.data)==null?void 0:zn["page-info"],po=(Kn=(Wn=G==null?void 0:G[0])==null?void 0:Wn.data)==null?void 0:Kn.aggregate;return{hash:fe,store:Re,pageInfo:ho,aggregate:po}});j.forEach(({hash:_,store:Q,pageInfo:G,aggregate:fe})=>{this.querySubs.set(le=>(le[_].result={store:Q,pageInfo:G,aggregate:fe,processedTxId:A},le))}),this._cleanupPendingMutationsQueries(),j.forEach(({hash:_})=>{this.notifyOne(_)});break;case"transact-ok":{const{"client-event-id":_,"tx-id":Q}=n;this._inFlightMutationEventIds.delete(_);const fe=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(_);if(!fe)break;this.pendingMutations.set(Z=>(Z.set(_,{...Z.get(_),"tx-id":Q,confirmed:Date.now()}),Z));const le=fe["tx-steps"].filter(([Z,...Re])=>Z==="add-attr").map(([Z,Re])=>Re).concat(Object.values(this.attrs));this._setAttrs(le),this._finishTransaction("synced",_),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const _=n["room-id"];this._trySetRoomConnected(_,!0),this._patchPresencePeers(_,n.edits),this._notifyPresenceSubs(_);break}case"refresh-presence":{const _=n["room-id"];this._trySetRoomConnected(_,!0),this._setPresencePeers(_,n.data),this._notifyPresenceSubs(_);break}case"server-broadcast":{const _=n["room-id"],Q=n.topic;this._trySetRoomConnected(_,!0),this._notifyBroadcastSubs(_,Q,n);break}case"join-room-ok":{const _=n["room-id"];if(!this._rooms[_]){this._roomsPendingLeave[_]&&(this._tryLeaveRoom(_),delete this._roomsPendingLeave[_]);break}this._trySetRoomConnected(_,!0),this._flushEnqueuedRoomData(_);break}case"leave-room-ok":{const _=n["room-id"];this._trySetRoomConnected(_,!1);break}case"join-room-error":const x=n["room-id"],Y=this._rooms[x];Y&&(Y.error=n.error),this._notifyPresenceSubs(x);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(e,n,r){const s=this.pendingMutations.currentValue.get(n);if(s&&(e!=="timeout"||!s["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const i={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(i),this._finishTransaction(e,n,r)}}_handleReceiveError(e){var a,c,u,f,l;console.log("error",e);const n=e["client-event-id"];this._inFlightMutationEventIds.delete(n);const r=this.pendingMutations.currentValue.get(n),s={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(e.hint&&(s.hint=e.hint),r){this._handleMutationError("error",n,e);return}if((a=e["original-event"])!=null&&a.hasOwnProperty("q")&&((c=e["original-event"])==null?void 0:c.op)==="add-query"){const d=(u=e["original-event"])==null?void 0:u.q,h=E(d);this.notifyQueryError(E(d),s),this.notifyQueryOnceError(d,h,n,s);return}if(((f=e["original-event"])==null?void 0:f.op)==="init"){if(e.type==="record-not-found"&&((l=e.hint)==null?void 0:l["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(J.ERRORED,s),this.notifyAll();return}const o={...e};delete o.message,delete o.hint,console.error(e.message,o),e.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
2
|
-
`,e.hint)}notifyQueryOnceError(e,n,r,s){var o;const i=(o=this.queryOnceDfds[n])==null?void 0:o.find(a=>a.eventId===r);i&&(i.dfd.reject(s),this._completeQueryOnce(e,n,i.dfd))}_setAttrs(e){this.attrs=e.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(e,n){const r=v();return this.querySubs.set(s=>(s[n]=s[n]||{q:e,result:null,eventId:r},s[n].lastAccessed=Date.now(),s)),this._trySendAuthed(r,{op:"add-query",q:e}),r}subscribeQuery(e,n,r){this.config.disableValidation||wt(e,this.config.schema),r&&"ruleParams"in r&&(e={$$ruleParams:r.ruleParams,...e});const s=E(e),i=this.getPreviousResult(e);return i&&n(i),this.queryCbs[s]=this.queryCbs[s]??[],this.queryCbs[s].push({q:e,cb:n}),this._startQuerySub(e,s),()=>{this._unsubQuery(e,s,n)}}queryOnce(e,n){this.config.disableValidation||wt(e,this.config.schema),n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=new wn;if(!this._isOnline)return r.reject(new Error("We can't run `queryOnce`, because the device is offline.")),r.promise;if(!this.querySubs)return r.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.instantdb.com/docs/backend#query")),r.promise;const s=E(e),i=this._startQuerySub(e,s);return this.queryOnceDfds[s]=this.queryOnceDfds[s]??[],this.queryOnceDfds[s].push({q:e,dfd:r,eventId:i}),setTimeout(()=>r.reject(new Error("Query timed out")),ji),r.promise}_completeQueryOnce(e,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(s=>s.dfd!==r),this._cleanupQuery(e,n))}_unsubQuery(e,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(s=>s.cb!==r),this._cleanupQuery(e,n))}_cleanupQuery(e,n){var s,i;(s=this.queryCbs[n])!=null&&s.length||(i=this.queryOnceDfds[n])!=null&&i.length||(delete this.queryCbs[n],delete this.queryOnceDfds[n],this._trySendAuthed(v(),{op:"remove-query",q:e}))}_rewriteMutations(e,n,r){if(!e)return n;const s=f=>{const[l,d,h]=f["forward-identity"];return I(e,d,h)},i=f=>{const[l,d,h]=f["forward-identity"];return ne(e,d,h)},o={attrIdMap:{},refSwapAttrIds:new Set};let a=!1;const c=(f,l)=>{const d=[];for(const h of f){const[p]=h;if(p==="add-attr"){const[w,b]=h,m=s(b);if(m&&b.id!==m.id){o.attrIdMap[b.id]=m.id,a=!0;continue}if(b["value-type"]==="ref"){const A=i(b);if(A){o.attrIdMap[b.id]=A.id,o.refSwapAttrIds.add(b.id),a=!0;continue}}}if(r&&l&&r>=l&&p==="add-attr"||p==="update-attr"||p==="delete-attr"){a=!0;continue}const T=a?Ls(o,h):h;d.push(T)}return a?d:f},u=new Map;for(const[f,l]of n.entries())u.set(f,{...l,"tx-steps":c(l["tx-steps"],l["tx-id"])});return a?u:n}_rewriteMutationsSorted(e,n){return Rn(this._rewriteMutations(e,n).entries())}optimisticAttrs(){var o;const e=[...this.pendingMutations.currentValue.values()].flatMap(a=>a["tx-steps"]),n=new Set(e.filter(([a,c])=>a==="delete-attr").map(([a,c])=>c)),r=[];for(const[a,c]of e)if(a==="add-attr")r.push(c);else if(a==="update-attr"&&c.id&&((o=this.attrs)!=null&&o[c.id])){const u={...this.attrs[c.id],...c};r.push(u)}const s=[...Object.values(this.attrs||{}),...r].filter(a=>!n.has(a.id));return Object.fromEntries(s.map(a=>[a.id,a]))}dataForQuery(e){const n=this._errorMessage;if(n)return{error:n};if(!this.querySubs||!this.pendingMutations)return;const r=this.querySubs.version(),s=this.querySubs.currentValue,i=this.pendingMutations.version(),o=this.pendingMutations.currentValue,{q:a,result:c}=s[e]||{};if(!c)return;const u=this._dataForQueryCache[e];if(u&&r===u.querySubVersion&&i===u.pendingMutationsVersion)return u.data;const{store:f,pageInfo:l,aggregate:d,processedTxId:h}=c,p=this._rewriteMutationsSorted(f.attrs,o),T=this._applyOptimisticUpdates(f,p,h),w=$s({store:T,pageInfo:l,aggregate:d},a);return this._dataForQueryCache[e]={querySubVersion:r,pendingMutationsVersion:i,data:w},w}_applyOptimisticUpdates(e,n,r){for(const[s,i]of n)(!i["tx-id"]||r&&i["tx-id"]>r)&&(e=Lr(e,i["tx-steps"]));return e}notifyAll(){Object.keys(this.queryCbs).forEach(e=>{this.notifyOne(e)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var e;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(e=this._transport)==null||e.close()}_sendMutation(e,n){if(n.error){this._handleMutationError("error",e,{message:n.error.message});return}if(this.status!==J.AUTHENTICATED){this._finishTransaction("enqueued",e);return}const r=Math.max(6e3,Math.min(this._inFlightMutationEventIds.size+1,this.pendingMutations.currentValue.size+1)*6e3);this._isOnline?(this._trySend(e,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",e,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",e)}_flushPendingMessages(){Object.keys(this.queryCbs).map(s=>this.querySubs.currentValue[s]).filter(s=>s).forEach(({eventId:s,q:i})=>{this._trySendAuthed(s,{op:"add-query",q:i})}),Object.values(this.queryOnceDfds).flat().forEach(({eventId:s,q:i})=>{this._trySendAuthed(s,{op:"add-query",q:i})}),this._rewriteMutationsSorted(this.attrs,this.pendingMutations.currentValue).forEach(([s,i])=>{i["tx-id"]||this._sendMutation(s,i)})}_cleanupPendingMutationsQueries(){let e=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(e=Math.min(e,n==null?void 0:n.processedTxId));this.pendingMutations.set(n=>{for(const[r,s]of Array.from(n.entries()))s["tx-id"]&&s["tx-id"]<=e&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){if(this.pendingMutations.currentValue.size<this._pendingMutationCleanupThreshold)return;const e=Date.now();this.pendingMutations.set(n=>{for(const[r,s]of Array.from(n.entries()))s.confirmed&&s.confirmed+this._pendingTxCleanupTimeout<e&&n.delete(r);return n})}_trySendAuthed(...e){this.status===J.AUTHENTICATED&&this._trySend(...e)}_trySend(e,n,r){if(this._transport.isOpen()){switch(Dn[n.op]||this._log.info("[send]",this._transport.id,n.op,n),n.op){case"transact":{this._inFlightMutationEventIds.add(e);break}case"init":this._inFlightMutationEventIds.clear()}this._transport.send({"client-event-id":e,...n})}}_startSocket(){if(this._wsOk=null,this._isShutdown){this._log.info("[socket][start]",this.config.appId,"Reactor has been shut down and will not start a new socket");return}if(this._transport&&this._transport.isConnecting()){this._log.info("[socket][start]",this._transport.id,"maintained as current transport, we were still in a connecting state");return}const e=this._transport;this._transport=xi({transportType:this._transportType,appId:this.config.appId,apiURI:this.config.apiURI,wsURI:this.config.websocketURI,EventSourceImpl:this._EventSource}),this._transport.onopen=this._transportOnOpen,this._transport.onmessage=this._transportOnMessage,this._transport.onclose=this._transportOnClose,this._transport.onerror=this._transportOnError,this._log.info("[socket][start]",this._transport.id),e!=null&&e.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",e.id),e.close())}async getLocalId(e){const n=`localToken_${e}`,r=await this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const s=v();return this._localIdPromises[n]=this._persister.setItem(n,s).then(()=>s),this._localIdPromises[n]}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const e=new URL(window.location.href);if(e.searchParams.get(mt)){const n=e.toString();e.searchParams.delete(mt),e.searchParams.delete("code"),e.searchParams.delete("error");const r=e.pathname+(e.searchParams.size?"?"+e.searchParams:"")+e.hash;if(history.replaceState(history.state,"",r),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let s=!1;const i=o=>{var a;s||(s=!0,navigation.removeEventListener("navigate",i),!o.userInitiated&&o.navigationType==="replace"&&((a=o.destination)==null?void 0:a.url)===n&&history.replaceState(history.state,"",r))};navigation.addEventListener("navigate",i)}}}async _oauthLoginInit(){var s,i,o,a;if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const e=new URLSearchParams(window.location.search);if(!e.get(mt))return null;const n=e.get("error");if(n)return this._replaceUrlAfterOAuth(),{error:{message:n}};const r=e.get("code");if(!r)return null;this._replaceUrlAfterOAuth();try{const c=await this._getCurrentUser(),u=(c==null?void 0:c.type)==="guest",{user:f}=await pn({apiURI:this.config.apiURI,appId:this.config.appId,code:r,refreshToken:u?c.refresh_token:void 0});return this.setCurrentUser(f),null}catch(c){return((s=c==null?void 0:c.body)==null?void 0:s.type)==="record-not-found"&&((o=(i=c==null?void 0:c.body)==null?void 0:i.hint)==null?void 0:o["record-type"])==="app-oauth-code"&&await this._hasCurrentUser()?null:{error:{message:((a=c==null?void 0:c.body)==null?void 0:a.message)||"Error logging in."}}}}async _waitForOAuthCallbackResponse(){return await this._oauthCallbackResponse}__subscribeMutationErrors(e){return this.mutationErrorCbs.push(e),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==e)}}subscribeAuth(e){this.authCbs.push(e);const n=this._currentUserCached;n.isLoading||e(this._currentUserCached);let r=!1;return this.getCurrentUser().then(s=>{r||Ae(s,n)||e(s)}),()=>{r=!0,this.authCbs=this.authCbs.filter(s=>s!==e)}}async getAuth(){const{user:e,error:n}=await this.getCurrentUser();if(n)throw new ce("Could not get current user: "+n.message);return e}subscribeConnectionStatus(e){return this.connectionStatusCbs.push(e),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==e)}}subscribeAttrs(e){return this.attrsCbs.push(e),this.attrs&&e(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==e)}}notifyAuthSubs(e){this.authCbs.forEach(n=>n(e))}notifyMutationErrorSubs(e){this.mutationErrorCbs.forEach(n=>n(e))}notifyAttrsSubs(){if(!this.attrs)return;const e=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(e))}notifyConnectionStatusSubs(e){this.connectionStatusCbs.forEach(n=>n(e))}async setCurrentUser(e){await this._persister.setItem(St,e)}getCurrentUserCached(){return this._currentUserCached}async _getCurrentUser(){const e=await this._persister.getItem(St);return typeof e=="string"?JSON.parse(e):e}async getCurrentUser(){const e=await this._waitForOAuthCallbackResponse();if(e!=null&&e.error){const s={error:e.error,user:void 0};return this._currentUserCached={isLoading:!1,...s},s}const r={user:await this._getCurrentUser(),error:void 0};return this._currentUserCached={isLoading:!1,...r},r}async _hasCurrentUser(){const e=await this._persister.getItem(St);return JSON.parse(e)!=null}async changeCurrentUser(e){var r;const{user:n}=await this.getCurrentUser();if(!Ae(n,e)){await this.setCurrentUser(e),this.updateUser(e);try{(r=this._broadcastChannel)==null||r.postMessage({type:"auth"})}catch(s){console.error("Error posting message to broadcast channel",s)}}}updateUser(e){const n={error:void 0,user:e};this._currentUserCached={isLoading:!1,...n},this._dataForQueryCache={},this.querySubs.set(r=>(Object.keys(r).forEach(s=>{delete r[s].result}),r)),this._reconnectTimeoutMs=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:e}){return ui({apiURI:this.config.apiURI,appId:this.config.appId,email:e})}async signInWithMagicCode({email:e,code:n}){var o;const r=await this.getCurrentUser(),s=((o=r==null?void 0:r.user)==null?void 0:o.type)==="guest",i=await fi({apiURI:this.config.apiURI,appId:this.config.appId,email:e,code:n,refreshToken:s?r.user.refresh_token:void 0});return await this.changeCurrentUser(i.user),i}async signInWithCustomToken(e){const n=await li({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:e});return await this.changeCurrentUser(n.user),n}async signInAsGuest(){const e=await di({apiURI:this.config.apiURI,appId:this.config.appId});return await this.changeCurrentUser(e.user),e}potentiallyInvalidateToken(e,n){var i;const r=(i=e==null?void 0:e.user)==null?void 0:i.refresh_token;if(!r)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}pi({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:r}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}async signOut(e){const n=await this.getCurrentUser();this.potentiallyInvalidateToken(n,e),await this.changeCurrentUser(null)}createAuthorizationURL({clientName:e,redirectURL:n}){const{apiURI:r,appId:s}=this.config;return`${r}/runtime/oauth/start?app_id=${s}&client_name=${e}&redirect_uri=${n}`}async exchangeCodeForToken({code:e,codeVerifier:n}){var o;const r=await this.getCurrentUser(),s=((o=r==null?void 0:r.user)==null?void 0:o.type)==="guest",i=await pn({apiURI:this.config.apiURI,appId:this.config.appId,code:e,codeVerifier:n,refreshToken:s?r.user.refresh_token:void 0});return await this.changeCurrentUser(i.user),i}issuerURI(){const{apiURI:e,appId:n}=this.config;return`${e}/runtime/${n}`}async signInWithIdToken({idToken:e,clientName:n,nonce:r}){var a;const s=await this.getCurrentUser(),i=(a=s==null?void 0:s.user)==null?void 0:a.refresh_token,o=await hi({apiURI:this.config.apiURI,appId:this.config.appId,idToken:e,clientName:n,nonce:r,refreshToken:i});return await this.changeCurrentUser(o.user),o}joinRoom(e,n){let r=!1;this._rooms[e]||(r=!0,this._rooms[e]={isConnected:!1,error:void 0}),this._presence[e]=this._presence[e]||{};const s=this._presence[e].result;return n&&!s&&(this._presence[e].result=this._presence[e].result||{},this._presence[e].result.user=n,this._notifyPresenceSubs(e)),r&&this._tryJoinRoom(e,n),()=>{this._cleanupRoom(e)}}_cleanupRoom(e){var n,r,s;if(!((r=(n=this._presence[e])==null?void 0:n.handlers)!=null&&r.length)&&!Object.keys(this._broadcastSubs[e]??{}).length){const i=(s=this._rooms[e])==null?void 0:s.isConnected;delete this._rooms[e],delete this._presence[e],delete this._broadcastSubs[e],i?this._tryLeaveRoom(e):this._roomsPendingLeave[e]=!0}}getPresence(e,n,r={}){const s=this._rooms[n],i=this._presence[n];return!s||!i||!i.result?null:{...gi(i.result,r,this._sessionId),isLoading:!s.isConnected,error:s.error}}publishPresence(e,n,r){const s=this._rooms[n],i=this._presence[n];if(!s||!i)return;i.result=i.result||{};const o={...i.result.user,...r};i.result.user=o,s.isConnected&&(this._trySetPresence(n,o),this._notifyPresenceSubs(n))}_trySetPresence(e,n){this._trySendAuthed(v(),{op:"set-presence","room-id":e,data:n})}_tryJoinRoom(e,n){this._trySendAuthed(v(),{op:"join-room","room-id":e,data:n}),delete this._roomsPendingLeave[e]}_tryLeaveRoom(e){this._trySendAuthed(v(),{op:"leave-room","room-id":e})}_trySetRoomConnected(e,n){const r=this._rooms[e];r&&(r.isConnected=n)}subscribePresence(e,n,r,s){const i=this.joinRoom(n,r.initialPresence||r.initialData),o={...r,roomId:n,cb:s,prev:null};return this._presence[n]=this._presence[n]||{},this._presence[n].handlers=this._presence[n].handlers||[],this._presence[n].handlers.push(o),this._notifyPresenceSub(n,o),()=>{var a,c;this._presence[n].handlers=((c=(a=this._presence[n])==null?void 0:a.handlers)==null?void 0:c.filter(u=>u!==o))??[],i()}}_notifyPresenceSubs(e){var n,r;(r=(n=this._presence[e])==null?void 0:n.handlers)==null||r.forEach(s=>{this._notifyPresenceSub(e,s)})}_notifyPresenceSub(e,n){const r=this.getPresence("",e,n);r&&(n.prev&&!mi(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(e,n){var o,a,c;const r=((a=(o=this._presence[e])==null?void 0:o.result)==null?void 0:a.peers)||{};let s=Object.fromEntries(Object.entries(r).map(([u,f])=>[u,{data:f}]));(c=this._presence[e])==null||c.result;const i=He(s,u=>{for(let[f,l,d]of n)switch(l){case"+":sr(u,f,d);break;case"r":Ft(u,f,d);break;case"-":qt(u,f);break}delete u[this._sessionId]});this._setPresencePeers(e,i)}_setPresencePeers(e,n){const r={...n};delete r[this._sessionId];const s=Object.fromEntries(Object.entries(r).map(([i,o])=>[i,o.data]));this._presence=He(this._presence,i=>{Ft(i,[e,"result","peers"],s)})}publishTopic({roomType:e,roomId:n,topic:r,data:s}){const i=this._rooms[n];if(i){if(!i.isConnected){this._broadcastQueue[n]=this._broadcastQueue[n]??[],this._broadcastQueue[n].push({topic:r,roomType:e,data:s});return}this._tryBroadcast(n,e,r,s)}}_tryBroadcast(e,n,r,s){this._trySendAuthed(v(),{op:"client-broadcast","room-id":e,roomType:n,topic:r,data:s})}subscribeTopic(e,n,r){const s=this.joinRoom(e);return this._broadcastSubs[e]=this._broadcastSubs[e]||{},this._broadcastSubs[e][n]=this._broadcastSubs[e][n]||[],this._broadcastSubs[e][n].push(r),this._presence[e]=this._presence[e]||{},()=>{this._broadcastSubs[e][n]=this._broadcastSubs[e][n].filter(i=>i!==r),this._broadcastSubs[e][n].length||delete this._broadcastSubs[e][n],s()}}_notifyBroadcastSubs(e,n,r){var s,i,o;(o=(i=(s=this._broadcastSubs)==null?void 0:s[e])==null?void 0:i[n])==null||o.forEach(a=>{var f,l,d,h,p,T;const c=(f=r.data)==null?void 0:f.data,u=r.data["peer-id"]===this._sessionId?(d=(l=this._presence[e])==null?void 0:l.result)==null?void 0:d.user:(T=(p=(h=this._presence[e])==null?void 0:h.result)==null?void 0:p.peers)==null?void 0:T[r.data["peer-id"]];return a(c,u)})}async uploadFile(e,n,r){var o;const s=await this.getCurrentUser(),i=(o=s==null?void 0:s.user)==null?void 0:o.refresh_token;return yi({...r,apiURI:this.config.apiURI,appId:this.config.appId,path:e,file:n,refreshToken:i})}async deleteFile(e){var i;const n=await this.getCurrentUser(),r=(i=n==null?void 0:n.user)==null?void 0:i.refresh_token;return await bi({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}async upload(e,n){var c;const r=await this.getCurrentUser(),s=(c=r==null?void 0:r.user)==null?void 0:c.refresh_token,i=e||n.name,o=await Ti({apiURI:this.config.apiURI,appId:this.config.appId,fileName:i,refreshToken:s});return await wi(o,n)}async getDownloadUrl(e){var i;const n=await this.getCurrentUser(),r=(i=n==null?void 0:n.user)==null?void 0:i.refresh_token;return await _i({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}}function Vi(t,e){return new je(Un(t,e),e,void 0)}function zi(t){return new $e(t,{})}function Wi(){return new $("string",!0,!1)}function Ki(){return new $("number",!0,!1)}function Qi(){return new $("boolean",!0,!1)}function Gi(){return new $("date",!0,!1)}function Bi(){return new $("json",!0,!1)}function Hi(){return new $("json",!0,!1)}function Un(t,e){var s,i,o,a;const n={fwd:{},rev:{}};for(const c of Object.values(e))(s=n.fwd)[i=c.forward.on]||(s[i]={}),(o=n.rev)[a=c.reverse.on]||(o[a]={}),n.fwd[c.forward.on][c.forward.label]={entityName:c.reverse.on,cardinality:c.forward.has},n.rev[c.reverse.on][c.reverse.label]={entityName:c.forward.on,cardinality:c.reverse.has};return Object.fromEntries(Object.entries(t).map(([c,u])=>[c,new $e(u.attrs,{...n.fwd[c],...n.rev[c]})]))}function Ji({entities:t,links:e,rooms:n}){const r=e??{},s=n??{};return new je(Un(t,r),r,s)}const Yi={graph:Vi,schema:Ji,entity:zi,string:Wi,number:Ki,boolean:Qi,date:Gi,json:Bi,any:Hi};let De;function Zi(t,e){De==null||De.dispose();const n=so(e),r=to(e,a),s=eo(Xi(t));function i(f){var l;f.source===s.element.contentWindow&&((l=f.data)==null?void 0:l.type)==="close"&&n.isVisible()&&a()}function o(f){const l=f.shiftKey&&f.ctrlKey&&f.key==="0",d=f.key==="Escape"||f.key==="Esc";(l||d&&n.isVisible())&&a()}function a(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(s.element)||n.element.appendChild(s.element))}function c(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",i)}function u(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",i),De={dispose:c}}return u()}function Xi(t){return`${bt||bn?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${t}`}function eo(t){const e=document.createElement("iframe");return e.src=t,e.className="instant-devtool-iframe",Object.assign(e.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:e}}function to(t,e){const n=`
|
|
1
|
+
(function(m,A){typeof exports=="object"&&typeof module<"u"?A(exports):typeof define=="function"&&define.amd?define(["exports"],A):(m=typeof globalThis<"u"?globalThis:m||self,A(m.instant={}))})(this,function(m){"use strict";var So=Object.defineProperty;var mo=(m,A,E)=>A in m?So(m,A,{enumerable:!0,configurable:!0,writable:!0,value:E}):m[A]=E;var g=(m,A,E)=>mo(m,typeof A!="symbol"?A+"":A,E);function A(t){if(typeof t=="number")return(Math.abs(t*2654435761)>>>0).toString(16);if(typeof t=="boolean")return t?"1":"0";if(t===null)return"null";if(t===void 0)return"undefined";if(typeof t=="string"){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e+=(e<<1)+(e<<4)+(e<<7)+(e<<8)+(e<<24),e=e>>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n<t.length;n++){e^=(n+1)*2654435761;const r=A(t[n]);for(let s=0;s<r.length;s++)e^=r.charCodeAt(s),e*=16777619,e=e>>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r<n.length;r++){const s=n[r],i=A(s);e^=parseInt(i,16),e*=16777619,e=e>>>0;const o=A(t[s]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return A(String(t))}const E={Remove:"remove",Replace:"replace",Add:"add"},At=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Yn=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),Te=Symbol.iterator,x={mutable:"mutable",immutable:"immutable"},$e={};function ae(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function Et(t,e){if(e in t){let n=Reflect.getPrototypeOf(t);for(;n;){const r=Reflect.getOwnPropertyDescriptor(n,e);if(r)return r;n=Reflect.getPrototypeOf(n)}}}function je(t){return Object.getPrototypeOf(t)===Set.prototype}function De(t){return Object.getPrototypeOf(t)===Map.prototype}function L(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function H(t){return!!S(t)}function S(t){return typeof t!="object"?null:t==null?void 0:t[At]}function Re(t){var e;const n=S(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function V(t,e){if(!t||typeof t!="object")return!1;let n;return Object.getPrototypeOf(t)===Object.prototype||Array.isArray(t)||t instanceof Map||t instanceof Set||!!(e!=null&&e.mark)&&((n=e.mark(t,x))===x.immutable||typeof n=="function")}function kt(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=S(K(n,t.key));if(r!==null&&(r==null?void 0:r.original)!==t.original)return null;const s=t.parent.type===3,i=s?Array.from(t.parent.setMap.keys()).indexOf(t.key):t.key;if(!(s&&n.size>i||ae(n,i)))return null;e.push(i)}if(t.parent)return kt(t.parent,e);e.reverse();try{Zn(t.copy,e)}catch{return null}return e}function J(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function K(t,e){return J(t)===2?t.get(e):t[e]}function ce(t,e,n){J(t)===2?t.set(e,n):t[e]=n}function Ue(t,e){const n=S(t);return(n?L(n):t)[e]}function Q(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function xe(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function Y(t,e){return e?t:[""].concat(t).map(n=>{const r=`${n}`;return r.indexOf("/")===-1&&r.indexOf("~")===-1?r:r.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Zn(t,e){for(let n=0;n<e.length-1;n+=1){const r=e[n];if(t=K(J(t)===3?Array.from(t):t,r),typeof t!="object")throw new Error(`Cannot resolve patch at '${e.join("/")}'.`)}return t}function Xn(t){const e=Object.create(Object.getPrototypeOf(t));return Reflect.ownKeys(t).forEach(n=>{let r=Reflect.getOwnPropertyDescriptor(t,n);if(r.enumerable&&r.configurable&&r.writable){e[n]=t[n];return}r.writable||(r.writable=!0,r.configurable=!0),(r.get||r.set)&&(r={configurable:!0,writable:!0,enumerable:r.enumerable,value:t[n]}),Reflect.defineProperty(e,n,r)}),e}const er=Object.prototype.propertyIsEnumerable;function Ct(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!je(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t.values())}return Set.prototype.difference?Set.prototype.difference.call(t,new Set):new Set(t.values())}else if(t instanceof Map){if(!De(t)){const r=Object.getPrototypeOf(t).constructor;return new r(t)}return new Map(t)}else if(e!=null&&e.mark&&(n=e.mark(t,x),n!==void 0)&&n!==x.mutable){if(n===x.immutable)return Xn(t);if(typeof n=="function"){if(e.enablePatches||e.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 t=="object"&&Object.getPrototypeOf(t)===Object.prototype){const r={};return Object.keys(t).forEach(s=>{r[s]=t[s]}),Object.getOwnPropertySymbols(t).forEach(s=>{er.call(t,s)&&(r[s]=t[s])}),r}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function $(t){t.copy||(t.copy=Ct(t.original,t.options))}function ue(t){if(!V(t))return Re(t);if(Array.isArray(t))return t.map(ue);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,s])=>[r,ue(s)]);if(!De(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Map(n)}if(t instanceof Set){const n=Array.from(t).map(ue);if(!je(t)){const r=Object.getPrototypeOf(t).constructor;return new r(n)}return new Set(n)}const e=Object.create(Object.getPrototypeOf(t));for(const n in t)e[n]=ue(t[n]);return e}function ge(t){return H(t)?ue(t):t}function W(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&W(t.parent))}function Mt(){throw new Error("Cannot modify frozen object")}function ee(t,e,n,r,s){{n=n??new WeakMap,r=r??[],s=s??[];const o=n.has(t)?n.get(t):t;if(r.length>0){const a=r.indexOf(o);if(o&&typeof o=="object"&&a!==-1)throw r[0]===o?new Error("Forbids circular reference"):new Error(`Forbids circular reference: ~/${s.slice(0,a).map((c,u)=>{if(typeof c=="symbol")return`[${c.toString()}]`;const f=r[u];return typeof c=="object"&&(f instanceof Map||f instanceof Set)?Array.from(f.keys()).indexOf(c):c}).join("/")}`);r.push(o),s.push(e)}else r.push(o)}if(Object.isFrozen(t)||H(t)){r.pop(),s.pop();return}switch(J(t)){case 2:for(const[a,c]of t)ee(a,a,n,r,s),ee(c,a,n,r,s);t.set=t.clear=t.delete=Mt;break;case 3:for(const a of t)ee(a,a,n,r,s);t.add=t.clear=t.delete=Mt;break;case 1:Object.freeze(t);let o=0;for(const a of t)ee(a,o,n,r,s),o+=1;break;default:Object.freeze(t),Object.keys(t).forEach(a=>{const c=t[a];ee(c,a,n,r,s)})}r.pop(),s.pop()}function Le(t,e){const n=J(t);if(n===0)Reflect.ownKeys(t).forEach(r=>{e(r,t[r],t)});else if(n===1){let r=0;for(const s of t)e(r,s,t),r+=1}else t.forEach((r,s)=>e(s,r,t))}function It(t,e,n){if(H(t)||!V(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,s=r?new Map:void 0;if(e.add(t),Le(t,(i,o)=>{var a;if(H(o)){const c=S(o);$(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;ce(r?s:t,i,u)}else It(o,e,n)}),s){const i=t,o=Array.from(i);i.clear(),o.forEach(a=>{i.add(s.has(a)?s.get(a):a)})}}function tr(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&It(K(n,e),t.finalities.handledSet,t.options)}function Ne(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(Re(e))}))}function Fe(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const i=kt(t);i&&e(t,i,n,r)}t.finalized=!0}}function Ve(t,e,n,r){const s=S(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((i,o)=>{var a;const c=t.type===3?t.setMap:t.copy;if(Q(K(c,e),n)){let u=s.original;s.copy&&(u=s.copy),Ne(t),Fe(t,r,i,o),t.options.enableAutoFreeze&&(t.options.updatedValues=(a=t.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,t.options.updatedValues.set(u,s.original)),ce(c,e,u)}}),t.options.enableAutoFreeze&&s.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),V(n,t.options)&&t.finalities.draft.push(()=>{const i=t.type===3?t.setMap:t.copy;Q(K(i,e),n)&&tr(t,e)})}function nr(t,e,n,r,s){let{original:i,assignedMap:o,options:a}=t,c=t.copy;c.length<i.length&&([i,c]=[c,i],[n,r]=[r,n]);for(let u=0;u<i.length;u+=1)if(o.get(u.toString())&&c[u]!==i[u]){const f=e.concat([u]),l=Y(f,s);n.push({op:E.Replace,path:l,value:ge(c[u])}),r.push({op:E.Replace,path:l,value:ge(i[u])})}for(let u=i.length;u<c.length;u+=1){const f=e.concat([u]),l=Y(f,s);n.push({op:E.Add,path:l,value:ge(c[u])})}if(i.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const f=e.concat(["length"]),l=Y(f,s);r.push({op:E.Replace,path:l,value:i.length})}else for(let f=c.length;i.length<f;f-=1){const l=e.concat([f-1]),d=Y(l,s);r.push({op:E.Remove,path:d})}}}function rr({original:t,copy:e,assignedMap:n},r,s,i,o){n.forEach((a,c)=>{const u=K(t,c),f=ge(K(e,c)),l=a?ae(t,c)?E.Replace:E.Add:E.Remove;if(Q(u,f)&&l===E.Replace)return;const d=r.concat(c),h=Y(d,o);s.push(l===E.Remove?{op:l,path:h}:{op:l,path:h,value:f}),i.push(l===E.Add?{op:E.Remove,path:h}:l===E.Remove?{op:E.Add,path:h,value:u}:{op:E.Replace,path:h,value:u})})}function sr({original:t,copy:e},n,r,s,i){let o=0;t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=Y(c,i);r.push({op:E.Remove,path:u,value:a}),s.unshift({op:E.Add,path:u,value:a})}o+=1}),o=0,e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=Y(c,i);r.push({op:E.Add,path:u,value:a}),s.unshift({op:E.Remove,path:u,value:a})}o+=1})}function fe(t,e,n,r){const{pathAsArray:s=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return rr(t,e,n,r,s);case 1:return nr(t,e,n,r,s);case 3:return sr(t,e,n,r,s)}}const we=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!V(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},qe={get size(){return L(S(this)).size},has(t){return L(S(this)).has(t)},set(t,e){const n=S(this),r=L(n);return(!r.has(t)||!Q(r.get(t),e))&&($(n),W(n),n.assignedMap.set(t,!0),n.copy.set(t,e),Ve(n,t,e,fe)),this},delete(t){if(!this.has(t))return!1;const e=S(this);return $(e),W(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=S(this);if(this.size){$(t),W(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=S(this);L(n).forEach((r,s)=>{t.call(e,this.get(s),s,this)})},get(t){var e,n;const r=S(this),s=L(r).get(t),i=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,s,x))===x.mutable;if(r.options.strict&&we(s,r.options,i),i||r.finalized||!V(s,r.options)||s!==r.original.get(t))return s;const o=$e.createDraft({original:s,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return $(r),r.copy.set(t,o),o},keys(){return L(S(this)).keys()},values(){const t=this.keys();return{[Te]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[Te]:()=>this.entries(),next:()=>{const e=t.next();if(e.done)return e;const n=this.get(e.value);return{done:!1,value:[e.value,n]}}}},[Te](){return this.entries()}},ir=Reflect.ownKeys(qe),vt=(t,e,{isValuesIterator:n})=>()=>{var r,s;const i=e.next();if(i.done)return i;const o=i.value;let a=t.setMap.get(o);const c=S(a),u=((s=(r=t.options).mark)===null||s===void 0?void 0:s.call(r,a,x))===x.mutable;if(t.options.strict&&we(o,t.options,u),!u&&!c&&V(o,t.options)&&!t.finalized&&t.original.has(o)){const f=$e.createDraft({original:o,parentDraft:t,key:o,finalities:t.finalities,options:t.options});t.setMap.set(o,f),a=f}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},_e={get size(){return S(this).setMap.size},has(t){const e=S(this);if(e.setMap.has(t))return!0;$(e);const n=S(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=S(this);return this.has(t)||($(e),W(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),Ve(e,t,t,fe)),this},delete(t){if(!this.has(t))return!1;const e=S(this);$(e),W(e);const n=S(t);return n&&e.setMap.has(n.original)?(e.assignedMap.set(n.original,!1),e.setMap.delete(n.original)):(!n&&e.setMap.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.setMap.delete(t))},clear(){if(!this.size)return;const t=S(this);$(t),W(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=S(this);$(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:vt(t,e,{isValuesIterator:!0})}},entries(){const t=S(this);$(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:vt(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[Te](){return this.values()},forEach(t,e){const n=this.values();let r=n.next();for(;!r.done;)t.call(e,r.value,r.value,this),r=n.next()}};Set.prototype.difference&&Object.assign(_e,{intersection(t){return Set.prototype.intersection.call(new Set(this.values()),t)},union(t){return Set.prototype.union.call(new Set(this.values()),t)},difference(t){return Set.prototype.difference.call(new Set(this.values()),t)},symmetricDifference(t){return Set.prototype.symmetricDifference.call(new Set(this.values()),t)},isSubsetOf(t){return Set.prototype.isSubsetOf.call(new Set(this.values()),t)},isSupersetOf(t){return Set.prototype.isSupersetOf.call(new Set(this.values()),t)},isDisjointFrom(t){return Set.prototype.isDisjointFrom.call(new Set(this.values()),t)}});const or=Reflect.ownKeys(_e),Pt=new WeakSet,$t={get(t,e,n){var r,s;const i=(r=t.copy)===null||r===void 0?void 0:r[e];if(i&&Pt.has(i))return i;if(e===At)return t;let o;if(t.options.mark){const u=e==="size"&&(t.original instanceof Map||t.original instanceof Set)?Reflect.get(t.original,e):Reflect.get(t.original,e,n);if(o=t.options.mark(u,x),o===x.mutable)return t.options.strict&&we(u,t.options,!0),u}const a=L(t);if(a instanceof Map&&ir.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(qe,"size").get.call(t.proxy);const u=qe[e];if(u)return u.bind(t.proxy)}if(a instanceof Set&&or.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(_e,"size").get.call(t.proxy);const u=_e[e];if(u)return u.bind(t.proxy)}if(!ae(a,e)){const u=Et(a,e);return u?"value"in u?u.value:(s=u.get)===null||s===void 0?void 0:s.call(t.proxy):void 0}const c=a[e];if(t.options.strict&&we(c,t.options),t.finalized||!V(c,t.options))return c;if(c===Ue(t.original,e)){if($(t),t.copy[e]=ze({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const u=S(t.copy[e]);return $(u),W(u),u.copy}return t.copy[e]}return c},set(t,e,n){var r;if(t.type===3||t.type===2)throw new Error("Map/Set draft does not support any property assignment.");let s;if(t.type===1&&e!=="length"&&!(Number.isInteger(s=Number(e))&&s>=0&&(e===0||s===0||String(s)===String(e))))throw new Error("Only supports setting array indices and the 'length' property.");const i=Et(L(t),e);if(i!=null&&i.set)return i.set.call(t.proxy,n),!0;const o=Ue(L(t),e),a=S(o);return a&&Q(a.original,n)?(t.copy[e]=n,t.assignedMap=(r=t.assignedMap)!==null&&r!==void 0?r:new Map,t.assignedMap.set(e,!1),!0):(Q(n,o)&&(n!==void 0||ae(t.original,e))||($(t),W(t),ae(t.original,e)&&Q(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,Ve(t,e,n,fe)),!0)},has(t,e){return e in L(t)},ownKeys(t){return Reflect.ownKeys(L(t))},getOwnPropertyDescriptor(t,e){const n=L(t),r=Reflect.getOwnPropertyDescriptor(n,e);return r&&{writable:!0,configurable:t.type!==1||e!=="length",enumerable:r.enumerable,value:n[e]}},getPrototypeOf(t){return Reflect.getPrototypeOf(t.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(t,e){var n;return t.type===1?$t.set.call(this,t,e,void 0,t.proxy):(Ue(t.original,e)!==void 0||e in t.original?($(t),W(t),t.assignedMap.set(e,!1)):(t.assignedMap=(n=t.assignedMap)!==null&&n!==void 0?n:new Map,t.assignedMap.delete(e)),t.copy&&delete t.copy[e],!0)}};function ze(t){const{original:e,parentDraft:n,key:r,finalities:s,options:i}=t,o=J(e),a={type:o,finalized:!1,parent:n,original:e,copy:null,proxy:null,finalities:s,options:i,setMap:o===3?new Map(e.entries()):void 0};(r||"key"in t)&&(a.key=r);const{proxy:c,revoke:u}=Proxy.revocable(o===1?Object.assign([],a):a,$t);if(s.revoke.push(u),Pt.add(c),a.proxy=c,n){const f=n;f.finalities.draft.push((l,d)=>{var h,p;const b=S(c);let T=f.type===3?f.setMap:f.copy;const y=K(T,r),w=S(y);if(w){let O=w.original;w.operated&&(O=Re(y)),Ne(w),Fe(w,fe,l,d),f.options.enableAutoFreeze&&(f.options.updatedValues=(h=f.options.updatedValues)!==null&&h!==void 0?h:new WeakMap,f.options.updatedValues.set(O,w.original)),ce(T,r,O)}(p=b.callbacks)===null||p===void 0||p.forEach(O=>{O(l,d)})})}else{const f=S(c);f.finalities.draft.push((l,d)=>{Ne(f),Fe(f,fe,l,d)})}return c}$e.createDraft=ze;function ar(t,e,n,r,s){var i;const o=S(t),a=(i=o==null?void 0:o.original)!==null&&i!==void 0?i:t,c=!!e.length;if(o!=null&&o.operated)for(;o.finalities.draft.length>0;)o.finalities.draft.pop()(n,r);const u=c?e[0]:o?o.operated?o.copy:o.original:t;return o&&xe(o),s&&ee(u,u,o==null?void 0:o.options.updatedValues),[u,n&&c?[{op:E.Replace,path:[],value:e[0]}]:n,r&&c?[{op:E.Replace,path:[],value:a}]:r]}function cr(t,e){var n;const r={draft:[],revoke:[],handledSet:new WeakSet};let s,i;e.enablePatches&&(s=[],i=[]);const a=((n=e.mark)===null||n===void 0?void 0:n.call(e,t,x))===x.mutable||!V(t,e)?t:ze({original:t,parentDraft:null,finalities:r,options:e});return[a,(c=[])=>{const[u,f,l]=ar(a,c,s,i,e.enableAutoFreeze);return e.enablePatches?[u,f,l]:u}]}function We(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:s=!0}=t;Le(n,(i,o,a)=>{const c=S(o);if(c&&e&&c.finalities===e.finalities){t.isContainDraft=!0;const u=c.original;if(a instanceof Set){const f=Array.from(a);a.clear(),f.forEach(l=>a.add(i===l?u:l))}else ce(a,i,u)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,We(t))}),s&&(t.isContainDraft||console.warn("The return value does not contain any draft, please use 'rawReturn()' to wrap the return value to improve performance."),r&&console.warn("The return value contains drafts, please don't use 'rawReturn()' to wrap the return value."))}function jt(t){var e;const n=S(t);if(!V(t,n==null?void 0:n.options))return t;const r=J(t);if(n&&!n.operated)return n.original;let s;function i(){s=r===2?De(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):Ct(t,n==null?void 0:n.options)}if(n){n.finalized=!0;try{i()}finally{n.finalized=!1}}else s=t;if(Le(s,(o,a)=>{if(n&&Q(K(n.original,o),a))return;const c=jt(a);c!==a&&(s===t&&i(),ce(s,o,c))}),r===3){const o=(e=n==null?void 0:n.original)!==null&&e!==void 0?e:s;return je(o)?new Set(s):new(Object.getPrototypeOf(o)).constructor(s)}return s}function Dt(t){if(!H(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return jt(t)}const Ke=(t=>function e(n,r,s){var i,o,a;if(typeof n=="function"&&typeof r!="function")return function(_,...I){return e(_,F=>n.call(this,F,...I),r)};const c=n,u=r;let f=s;if(typeof r!="function"&&(f=r),f!==void 0&&Object.prototype.toString.call(f)!=="[object Object]")throw new Error(`Invalid options: ${f}, 'options' should be an object.`);f=Object.assign(Object.assign({},t),f);const l=H(c)?Dt(c):c,d=Array.isArray(f.mark)?(_,I)=>{for(const F of f.mark){if(typeof F!="function")throw new Error(`Invalid mark: ${F}, 'mark' should be a function.`);const X=F(_,I);if(X)return X}}:f.mark,h=(i=f.enablePatches)!==null&&i!==void 0?i:!1,p=(o=f.strict)!==null&&o!==void 0?o:!1,T={enableAutoFreeze:(a=f.enableAutoFreeze)!==null&&a!==void 0?a:!1,mark:d,strict:p,enablePatches:h};if(!V(l,T)&&typeof l=="object"&&l!==null)throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");const[y,w]=cr(l,T);if(typeof r!="function"){if(!V(l,T))throw new Error("Invalid base state: create() only supports plain objects, arrays, Set, Map or using mark() to mark the state as immutable.");return[y,w]}let O;try{O=u(y)}catch(_){throw xe(S(y)),_}const C=_=>{const I=S(y);if(!H(_)){if(_!==void 0&&!Q(_,y)&&(I!=null&&I.operated))throw new Error("Either the value is returned as a new non-draft value, or only the draft is modified without returning any value.");const X=_==null?void 0:_[Yn];if(X){const Ot=X[0];return T.strict&&typeof _=="object"&&_!==null&&We({rootDraft:I,value:_,useRawReturn:!0}),w([Ot])}if(_!==void 0)return typeof _=="object"&&_!==null&&We({rootDraft:I,value:_}),w([_])}if(_===y||_===void 0)return w([]);const F=S(_);if(T===F.options){if(F.operated)throw new Error("Cannot return a modified child draft.");return w([Dt(_)])}return w([_])};return O instanceof Promise?O.then(C,_=>{throw xe(S(y)),_}):C(O)})();Object.prototype.constructor.toString();function Rt(t,e){const n=Object.keys(t),r=Object.keys(e);return n.length===r.length&&Object.keys(t).every(s=>e.hasOwnProperty(s))}function Ut(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>e.hasOwnProperty(n)&&t[n]===e[n])}function Se(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:Rt(t,e)?Object.keys(t).every(n=>Se(t[n],e[n])):!1}function Qe(t){if(!le(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function xt(t,e){if(!le(t)||!le(e))return e;const n={...t};for(const r of Object.keys(e)){if(e[r]===void 0)continue;if(e[r]===null){delete n[r];continue}const s=le(t[r])&&le(e[r]);n[r]=s?xt(t[r],e[r]):e[r]}return n}function le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ur(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;i<e.length-1;i++){const o=e[i];(!(o in r)||typeof r[o]!="object")&&(r[o]=typeof e[i+1]=="number"?[]:{}),r=r[o]}const s=e[e.length-1];Array.isArray(r)&&typeof s=="number"?r.splice(s,0,n):r[s]=n}function Lt(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let s=0;s<e.length-1;s++){const i=e[s];(!(i in r)||typeof r[i]!="object")&&(r[i]=typeof e[s+1]=="number"?[]:{}),r=r[i]}r[e[e.length-1]]=n}function Nt(t,e){if(!t||e.length===0)return;const[n,...r]=e;if(n in t){if(r.length===0){Array.isArray(t)?t.splice(n,1):delete t[n];return}Nt(t[n],r),fr(t[n])&&delete t[n]}}function fr(t){return t&&Object.keys(t).length===0}const Ft=/ZULU|YEKT|YEKST|YAPT|YAKT|YAKST|XJT|WGT|WGST|WFT|WETDST|WET|WDT|WAT|WAST|WAKT|WADT|VUT|VOLT|VLAT|VLAST|VET|UZT|UZST|UYT|UYST|UTC|UT|ULAT|ULAST|UCT|TVT|TRUT|TOT|TMT|TKT|TJT|TFT|TAHT|SGT|SCT|SAST|SADT|RET|PYT|PYST|PWT|PST|PONT|PMST|PMDT|PKT|PKST|PHT|PGT|PETT|PETST|PET|PDT|OMST|OMSST|NZT|NZST|NZDT|NUT|NST|NPT|NOVT|NOVST|NFT|NDT|MYT|MVT|MUT|MUST|MST|MSK|MSD|MPT|MMT|MHT|MEZ|METDST|MET|MESZ|MEST|MDT|MAWT|MART|MAGT|MAGST|LKT|LINT|LIGT|LHST|LHDT|KST|KRAT|KRAST|KOST|KGT|KGST|KDT|JST|JAYT|IST|IRT|IRKT|IRKST|IOT|IDT|ICT|HST|HKT|GYT|GMT|GILT|GFT|GET|GEST|GAMT|GALT|FNT|FNST|FKT|FKST|FJT|FJST|FET|EST|EGT|EGST|EETDST|EET|EEST|EDT|EAT|EAST|EASST|DDUT|DAVT|CXT|CST|COT|CLT|CLST|CKT|CHUT|CHAST|CHADT|CETDST|CET|CEST|CDT|CCT|CAST|CADT|BTT|BST|BRT|BRST|BRA|BOT|BORT|BNT|BDT|BDST|AZT|AZST|AZOT|AZOST|AWST|AWSST|AST|ART|ARST|ANAT|ANAST|AMT|AMST|ALMT|ALMST|AKST|AKDT|AFT|AEST|AESST|AEDT|ADT|ACWST|ACT|ACST|ACSST|ACDT$/,lr={ZULU:0,YEKT:18e3,YEKST:21600,YAPT:36e3,YAKT:32400,YAKST:32400,XJT:21600,WGT:-10800,WGST:-7200,WFT:43200,WETDST:3600,WET:0,WDT:32400,WAT:3600,WAST:25200,WAKT:43200,WADT:28800,VUT:39600,VOLT:10800,VLAT:36e3,VLAST:36e3,VET:-14400,UZT:18e3,UZST:21600,UYT:-10800,UYST:-7200,UTC:0,UT:0,ULAT:28800,ULAST:32400,UCT:0,TVT:43200,TRUT:36e3,TOT:46800,TMT:18e3,TKT:46800,TJT:18e3,TFT:18e3,TAHT:-36e3,SGT:28800,SCT:14400,SAST:7200,SADT:37800,RET:14400,PYT:-14400,PYST:-10800,PWT:32400,PST:-28800,PONT:39600,PMST:-10800,PMDT:-7200,PKT:18e3,PKST:21600,PHT:28800,PGT:36e3,PETT:43200,PETST:43200,PET:-18e3,PDT:-25200,OMST:21600,OMSST:21600,NZT:43200,NZST:43200,NZDT:46800,NUT:-39600,NST:-12600,NPT:20700,NOVT:25200,NOVST:25200,NFT:-12600,NDT:-9e3,MYT:28800,MVT:18e3,MUT:14400,MUST:18e3,MST:-25200,MSK:10800,MSD:14400,MPT:36e3,MMT:23400,MHT:43200,MEZ:3600,METDST:7200,MET:3600,MESZ:7200,MEST:7200,MDT:-21600,MAWT:18e3,MART:-34200,MAGT:39600,MAGST:39600,LKT:19800,LINT:50400,LIGT:36e3,LHST:37800,LHDT:37800,KST:32400,KRAT:25200,KRAST:25200,KOST:39600,KGT:21600,KGST:21600,KDT:36e3,JST:32400,JAYT:32400,IST:7200,IRT:12600,IRKT:28800,IRKST:28800,IOT:21600,IDT:10800,ICT:25200,HST:-36e3,HKT:28800,GYT:-14400,GMT:0,GILT:43200,GFT:-10800,GET:14400,GEST:14400,GAMT:-32400,GALT:-21600,FNT:-7200,FNST:-3600,FKT:-10800,FKST:-10800,FJT:43200,FJST:46800,FET:10800,EST:-18e3,EGT:-3600,EGST:0,EETDST:10800,EET:7200,EEST:10800,EDT:-14400,EAT:10800,EAST:-21600,EASST:-21600,DDUT:36e3,DAVT:25200,CXT:25200,CST:-21600,COT:-18e3,CLT:-14400,CLST:-10800,CKT:-36e3,CHUT:36e3,CHAST:45900,CHADT:49500,CETDST:7200,CET:3600,CEST:7200,CDT:-18e3,CCT:28800,CAST:34200,CADT:37800,BTT:21600,BST:3600,BRT:-10800,BRST:-7200,BRA:-10800,BOT:-14400,BORT:28800,BNT:28800,BDT:21600,BDST:7200,AZT:14400,AZST:14400,AZOT:-3600,AZOST:0,AWST:28800,AWSST:32400,AST:-14400,ART:-10800,ARST:-10800,ANAT:43200,ANAST:43200,AMT:-14400,AMST:14400,ALMT:21600,ALMST:25200,AKST:-32400,AKDT:-28800,AFT:16200,AEST:36e3,AESST:39600,AEDT:39600,ADT:-10800,ACWST:31500,ACT:-18e3,ACST:34200,ACSST:37800,ACDT:37800};function dr(t){return new Date(t)}function hr(t){return new Date(t+"Z")}const pr=/^(\d+)[\./-](\d+)[\./-](\d+)$/;function yr(t){const e=t.match(pr);if(!e)return null;const[n,r,s,i]=e;return r<=0||s<=0||i<=0?null:r>999?new Date(Date.UTC(r,s-1,i,0,0,0,0)):new Date(Date.UTC(i,r-1,s,0,0,0,0))}function br(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function Tr(t){const[e,n]=t.split(" ");return new Date(e+"T"+n+"Z")}function gr(t){return new Date(t)}function wr(t){const e=/^(\w{3}) (\w{3}) (\d{2}) (\d{4})$/;if(!t.match(e))throw new Error(`Unable to parse \`${t}\` as a date.`);const r=new Date(t+" UTC");return new Date(Date.UTC(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate(),0,0,0,0))}function _r(t){const e=/^(.+T.+)([+-])(\d{2})$/,n=t.match(e);if(n){const[,r,s,i]=n,o=`${r}${s}${i}:00`;return new Date(o)}return null}function Sr(t){const[e,n]=t.split(", "),[r,s,i]=e.split("/").map(Number),o=n.match(/(\d{1,2}):(\d{2}):(\d{2}) (AM|PM)/);if(!o)throw new Error(`Unable to parse time from: ${t}`);let[,a,c,u,f]=o;return a=Number(a),c=Number(c),u=Number(u),f==="PM"&&a!==12?a+=12:f==="AM"&&a===12&&(a=0),new Date(Date.UTC(i,r-1,s,a,c,u))}function mr(t){switch(t){case"epoch":return new Date(0);case"infinity":case"-infinity":case"today":case"tomorrow":case"yesterday":return null}}function Or(t){const e=t.match(Ft);if(!e)return null;const[n]=e,r=lr[n],s=new Date(t.replace(Ft,"Z"));return new Date(s.getTime()-r*1e3)}const Ar=[yr,Tr,wr,Sr,gr,hr,_r,br,dr,mr,Or];function Er(t,e){try{const n=t(e);return n instanceof Date&&!isNaN(n.getTime())?n:null}catch{return null}}function Be(t){for(const e of Ar){const n=Er(e,t);if(n)return n}return null}function kr(t){try{const e=JSON.parse(t);return typeof e=="string"?Be(e):null}catch{return null}}function de(t){if(t!==void 0){if(t===null)return null;if(t instanceof Date)return t;if(typeof t=="string"){const e=Be(t)||kr(t)||Be(t.trim());if(!e)throw new Error(`Unable to parse \`${t}\` as a date.`);return e}else if(typeof t=="number")return new Date(t);throw new Error(`Invalid date value \`${t}\`. Expected a date, number, or string, got type ${typeof t}.`)}}function Cr(t){return t.cardinality==="one"}function Ge(t){return t["value-type"]==="ref"}function He(t){return t["value-type"]==="blob"}function te(t,e){return t[e]}function ne(t,e){return e.reduce((n,r)=>n&&n.get(r),t)}function q(t,e){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.delete(e[0]);return}const[n,...r]=e;t.has(n)&&q(t.get(n),r)}function D(t,e,n){if(e.length===0)throw new Error("path must have at least one element");if(e.length===1){t.set(e[0],n);return}const[r,...s]=e;let i=t.get(r);i||(i=new Map,t.set(r,i)),D(i,s,n)}function Vt(t,e,n){const r=new Map,s=new Map,i=new Map;for(const o of e){let[a,c,u,f]=o;const l=te(t,c);if(!l){console.warn("no such attr",a,t);continue}l["checked-data-type"]==="date"&&n&&(u=de(u),o[2]=u),Ge(l)&&D(i,[u,c,a],o),D(r,[a,c,u],o),D(s,[c,a,u],o)}return{eav:r,aev:s,vae:i}}function qt(t){const e=new Map,n=new Map,r=new Map,s=new Map;for(const i of Object.values(t)){const o=i["forward-identity"],[a,c,u]=o,f=i["reverse-identity"];if(D(r,[c,u],i),He(i)&&D(e,[c,u],i),i["primary?"]&&D(n,[c],i),f){const[l,d,h]=f;D(s,[d,h],i)}}return{blobAttrs:e,primaryKeys:n,forwardIdents:r,revIdents:s}}function zt(t){return{__type:t.__type,attrs:t.attrs,triples:R(t.eav,3),cardinalityInference:t.cardinalityInference,linkIndex:t.linkIndex,useDateObjects:t.useDateObjects}}function Wt(t){return me(t.attrs,t.triples,t.cardinalityInference,t.linkIndex,t.useDateObjects)}function Mr(t,e){return ne(t.eav,[e])!==void 0}function Je(t){t.attrIndexes=qt(t.attrs)}function me(t,e,n,r,s){const i=Vt(t,e,s);return i.useDateObjects=s,i.attrs=t,i.attrIndexes=qt(t),i.cardinalityInference=n,i.linkIndex=r,i.__type="store",i}function he(t,e){var s,i;let n;if(Array.isArray(e[0])){const[o,a]=e[0],c=t.aev.get(o);if(!c)return null;n=(s=R(c,2).find(f=>f[2]===a))==null?void 0:s[0]}else n=e[0];if(!n)return null;const r=e[2];if(Array.isArray(r)&&r.length===2&&t.aev.get(r[0])){const[o,a]=r,c=t.aev.get(o);if(!c)return null;const f=(i=R(c,2).find(b=>b[2]===a))==null?void 0:i[0];if(!f)return null;const[l,d,h,...p]=e;return[n,d,f,...p]}else{const[o,...a]=e;return[n,...a]}}function Kt(t,e){const n=he(t,e);if(!n)return;const[r,s,i]=n,o=te(t.attrs,s);o&&(q(t.eav,[r,s,i]),q(t.aev,[s,r,i]),Ge(o)&&q(t.vae,[i,s,r]))}let Ir=0;function Qt(t,e,n){const[r,s,i]=n;let o;const a=ne(t.ea,[r,s,i]);return a&&(o=a[3]),o||Date.now()*10+Ir++}function Bt(t,e){const n=he(t,e);if(!n)return;let[r,s,i]=n;const o=te(t.attrs,s);if(!o)return;o["checked-data-type"]==="date"&&t.useDateObjects&&(i=de(i));const a=ne(t.eav,[r,s,i]),c=(a==null?void 0:a[3])??Qt(t,o,n),u=[r,s,i,c];Cr(o)?(D(t.eav,[r,s],new Map([[i,u]])),D(t.aev,[s,r],new Map([[i,u]]))):(D(t.eav,[r,s,i],u),D(t.aev,[s,r,i],u)),Ge(o)&&D(t.vae,[i,s,r],u)}function vr(t,e){var d;const n=he(t,e);if(!n)return;const[r,s,i]=n,o=te(t.attrs,s);if(!o)return;if(!He(o))throw new Error("merge operation is not supported for links");const a=ne(t.eav,[r,s]);if(!a)return;const c=(d=a.values().next())==null?void 0:d.value;if(!c)return;const u=c[2],f=xt(u,i),l=[r,s,f,Qt(t,o,c)];D(t.eav,[r,s],new Map([[f,l]]))}function Ye(t,e){var c,u;const[n,r]=e,s=he(t,[n]);if(!s)return;const[i]=s,o=t.eav.get(i);if(o){for(const f of o.keys()){const l=t.attrs[f];l&&l["on-delete-reverse"]==="cascade"&&R(o.get(f),1).forEach(([d,h,p])=>{var b;return Ye(t,[p,(b=l["reverse-identity"])==null?void 0:b[1]])}),(!r||!l||((c=l["forward-identity"])==null?void 0:c[1])===r)&&(q(t.aev,[f,i]),q(t.eav,[i,f]))}o.size===0&&q(t.eav,[i])}const a=t.vae.get(i)&&R(t.vae.get(i),2);a&&a.forEach(f=>{var b,T,y;const[l,d,h]=f,p=t.attrs[d];(!r||!p||((b=p["reverse-identity"])==null?void 0:b[1])===r)&&(q(t.eav,[l,d,h]),q(t.aev,[d,l,h]),q(t.vae,[h,d,l])),p&&p["on-delete"]==="cascade"&&((T=p["reverse-identity"])==null?void 0:T[1])===r&&Ye(t,[l,(y=p["forward-identity"])==null?void 0:y[1]])}),((u=t.vae.get(i))==null?void 0:u.size)===0&&q(t.vae,[i])}function Gt(t,e){const n=Vt(t.attrs,e,t.useDateObjects);Object.keys(n).forEach(r=>{t[r]=n[r]})}function Pr(t,[e]){t.attrs[e.id]=e,Je(t)}function Ht(t){return R(t.eav,3)}function $r(t,[e]){if(!t.attrs[e])return;const n=Ht(t).filter(([r,s])=>s!==e);delete t.attrs[e],Je(t),Gt(t,n)}function jr(t,[e]){const n=t.attrs[e.id];n&&(t.attrs[e.id]={...n,...e},Je(t),Gt(t,Ht(t)))}function Dr(t,e){const[n,...r]=e;switch(n){case"add-triple":Bt(t,r);break;case"deep-merge-triple":vr(t,r);break;case"retract-triple":Kt(t,r);break;case"delete-entity":Ye(t,r);break;case"add-attr":Pr(t,r);break;case"delete-attr":$r(t,r);break;case"update-attr":jr(t,r);break;case"restore-attr":break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function R(t,e,n=[]){if(!t||e===0)return n;if(e===1){for(const r of t.values())n.push(r);return n}for(const r of t.values())R(r,e-1,n);return n}function Oe(t,e,n){var i,o;const r=[];if(n!=null&&n.hasOwnProperty("$not")){for(const a of e.keys())n.$not!==a&&r.push(e.get(a));return r}if(n!=null&&n.hasOwnProperty("$isNull")){const{attrId:a,isNull:c,reverse:u}=n.$isNull;if(u)for(const f of e.keys()){const l=t.vae.get(f),d=!l||((i=l.get(a))==null?void 0:i.get(null))||!l.get(a);(c?d:!d)&&r.push(e.get(f))}else{const f=t.aev.get(a);for(const l of e.keys()){const d=!f||((o=f.get(l))==null?void 0:o.get(null))||!f.get(l);(c?d:!d)&&r.push(e.get(l))}}return r}if(n!=null&&n.$comparator)return R(e,1).filter(n.$op);const s=n.in||n.$in||[n];for(const a of s){const c=e.get(a);c&&r.push(c)}return r}function Rr(t,e,n){let r="";return t!==void 0&&(r+="e"),e!==void 0&&(r+="a"),n!==void 0&&(r+="v"),r}function Ur(t,[e,n,r]){var i,o;switch(Rr(e,n,r)){case"e":{const a=t.eav.get(e);return R(a,2)}case"ea":{const a=(i=t.eav.get(e))==null?void 0:i.get(n);return R(a,1)}case"eav":{const a=(o=t.eav.get(e))==null?void 0:o.get(n);return a?Oe(t,a,r):[]}case"ev":{const a=t.eav.get(e);if(!a)return[];const c=[];for(const u of a.values())c.push(...Oe(t,u,r));return c}case"a":{const a=t.aev.get(n);return R(a,2)}case"av":{const a=t.aev.get(n);if(!a)return[];const c=[];for(const u of a.values())c.push(...Oe(t,u,r));return c}case"v":{const a=[];for(const c of t.eav.values())for(const u of c.values())a.push(...Oe(t,u,r));return a}default:return R(t.eav,3)}}function xr(t,e,n){var s;const r={};for(const[i,o]of e.entries()){const a=(s=t.eav.get(n))==null?void 0:s.get(o.id),c=R(a,1);for(const u of c)r[i]=u[2]}return r}function G(t,e,n){var r;return(r=t.attrIndexes.forwardIdents.get(e))==null?void 0:r.get(n)}function Jt(t,e,n){var r;return(r=t.attrIndexes.revIdents.get(e))==null?void 0:r.get(n)}function Lr(t,e){return t.attrIndexes.blobAttrs.get(e)}function Yt(t,e){var r;const n=t.attrIndexes.primaryKeys.get(e);return n||((r=t.attrIndexes.forwardIdents.get(e))==null?void 0:r.get("id"))}function Nr(t,e){const n=he(t,e);if(!n)return;const[r,s,i]=n;if(te(t.attrs,s))return ne(t.eav,[r,s])}function Fr(t,e){const n=e.filter(([r,s,i,o,a])=>{if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const c=a==null?void 0:a.mode;if(c!=="create"&&c!=="update")return!0;let u=!1;const f=te(t.attrs,i);if(f){const l=Yt(t,f["forward-identity"][1]);u=!!Nr(t,[s,l.id,s])}return!(c==="create"&&u||c==="update"&&!u)});return Ke(t,r=>{n.forEach(s=>{Dr(r,s)})})}function Vr(t){return typeof t=="string"&&t.startsWith("?")}function qr(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return Xt(r,e,n)}return{...n,[t]:e}}function Zt(t,e,n){return t===e?n:null}function zr(t){switch(typeof t){case"string":return t.startsWith("?")?qr:Zt;default:return Zt}}const Wr=["in","$in","$not","$isNull","$comparator"];function Kr(t){for(const e of Wr)if(t.hasOwnProperty(e))return!0;return!1}function Xt(t,e,n){return n?typeof t=="object"?Kr(t)?n:null:zr(t)(t,e,n):null}function Qr(t,e,n){return t.reduce((r,s,i)=>{const o=e[i];return Xt(s,o,r)},n)}function Br(t,e,n){return Jr(t,e,n).map(r=>Qr(e,r,n)).filter(r=>r)}function Gr(t,e,n){return e.or?e.or.patterns.flatMap(r=>Ze(t,r,n)):e.and?e.and.patterns.reduce((r,s)=>Ze(t,s,r),n):n.flatMap(r=>Br(t,e,r))}function Ze(t,e,n=[{}]){return e.reduce((r,s)=>Gr(t,s,r),n)}function Xe(t,e){return Array.isArray(e)?e.map(n=>Xe(t,n)):Vr(e)?t[e]:e}function Hr(t,{find:e,where:n}){return Ze(t,n).map(s=>Xe(s,e))}function Jr(t,e,n){return Ur(t,Xe(n,e))}const Yr=/^(?:[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 re(t){return typeof t=="string"&&Yr.test(t)}const v=[];for(let t=0;t<256;++t)v.push((t+256).toString(16).slice(1));function Zr(t,e=0){return(v[t[e+0]]+v[t[e+1]]+v[t[e+2]]+v[t[e+3]]+"-"+v[t[e+4]]+v[t[e+5]]+"-"+v[t[e+6]]+v[t[e+7]]+"-"+v[t[e+8]]+v[t[e+9]]+"-"+v[t[e+10]]+v[t[e+11]]+v[t[e+12]]+v[t[e+13]]+v[t[e+14]]+v[t[e+15]]).toLowerCase()}let et;const Xr=new Uint8Array(16);function es(){if(!et){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");et=crypto.getRandomValues.bind(crypto)}return et(Xr)}const en={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ts(t,e,n){var s;if(en.randomUUID&&!t)return en.randomUUID();t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??es();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Zr(r)}function tn(t){const e=t.replace(/-/g,""),n=[];for(let r=0;r<e.length;r+=2)n.push(parseInt(e.substring(r,r+2),16));return n}function ns(t,e){for(let n=0;n<t.length;n++){if(t[n]<e[n])return-1;if(t[n]>e[n])return 1}return 0}function rs(t,e){return ns(tn(t),tn(e))}function M(){return ts()}function ss(t,e){return t.localeCompare(e)}function is(){let t=ss;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{t=Intl.Collator("en-US").compare}catch{}return t}const os=is();let as=0;function pe(t){return Ae(`_${t}`,as++)}function Ae(t,e){return`?${t}-${e}`}class se extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function cs(t,e){const n=Yt(t,e);if(!n)throw new se(`Could not find id attr for ${e}`);return n}function nn(t,e,n,r){return[us(t,e,n,r)]}function us(t,e,n,r){return[t(n,r),cs(e,n).id,t(n,r),t("time",r)]}function fs(t,e,n){return t.map(r=>r===e?n:r)}function rn(t,e,n,r,s){const i=G(e,n,s),o=Jt(e,n,s),a=i||o;if(!a)throw new se(`Could not find attr for ${[n,s]}`);if(a["value-type"]!=="ref")throw new Error(`Attr ${a.id} is not a ref`);const[c,u]=a["forward-identity"],[f,l]=a["reverse-identity"],d=r+1,h=i?[t(u,r),a.id,t(l,d),pe("time")]:[t(u,d),a.id,t(l,r),pe("time")];return[i?l:u,d,h,a,!!i]}function sn(t,e){if(typeof e!="string")return function(o){return!1};const r=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&").replace(/%/g,".*").replace(/_/g,"."),s=new RegExp(`^${r}$`,t?void 0:"i");return function(o){return typeof o!="string"?!1:s.test(o)}}function ls(t,e){if(typeof e!="object"||e.hasOwnProperty("$in")||e.hasOwnProperty("in"))return e;const n=t["checked-data-type"]==="date";if(e.hasOwnProperty("$gt"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])>new Date(e.$gt)}:function(s){return s[2]>e.$gt}};if(e.hasOwnProperty("$gte"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])>=new Date(e.$gte)}:function(s){return s[2]>=e.$gte}};if(e.hasOwnProperty("$lt"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])<new Date(e.$lt)}:function(s){return s[2]<e.$lt}};if(e.hasOwnProperty("$lte"))return{$comparator:!0,$op:n?function(s){return new Date(s[2])<=new Date(e.$lte)}:function(s){return s[2]<=e.$lte}};if(e.hasOwnProperty("$like")){const r=sn(!0,e.$like);return{$comparator:!0,$op:function(i){return r(i[2])}}}if(e.hasOwnProperty("$ilike")){const r=sn(!1,e.$ilike);return{$comparator:!0,$op:function(i){return r(i[2])}}}return e}function ds(t,e,n,r,s,i){const o=G(e,n,s),a=Jt(e,n,s),c=o||a;if(!c)throw new se(`No attr for etype = ${n} label = ${s}`);if(i!=null&&i.hasOwnProperty("$isNull")){const u=G(e,n,"id");if(!u)throw new se(`No attr for etype = ${n} label = id`);return[t(n,r),u.id,{$isNull:{attrId:c.id,isNull:i.$isNull,reverse:!o}},pe("time")]}return o?[t(n,r),c.id,ls(c,i),pe("time")]:[i,c.id,t(n,r),pe("time")]}function hs(t,e,n,r,s){const[i,o,a]=s.reduce((c,u)=>{const[f,l,d]=c,[h,p,b]=rn(t,e,f,l,u);return[h,p,[...d,b]]},[n,r,[]]);return[i,o,a]}function tt(t,e,n,r,s,i){const o=s.slice(0,s.length-1),a=s[s.length-1],[c,u,f]=hs(t,e,n,r,o),l=ds(t,e,c,u,a,i);return f.concat([l])}function ps(t,e){return e?[e].concat(t):t}function ys([t,e]){return t==="or"&&Array.isArray(e)}function bs([t,e]){return t==="and"&&Array.isArray(e)}function Ts(t,e,n){return(r,s)=>{const i=t(r,s);return e==i?i:`${i}-${n}`}}function on(t,e,n,r,s,i){const o=t(r,s),a=i.map((c,u)=>{const f=Ts(t,o,u);return cn(f,n,r,s,c)});return{[e]:{patterns:a,joinSym:o}}}function gs(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function an(t,e,n,r,s){return gs(s).map(i=>tt(t,e,n,r,i,{$isNull:!0}))}function cn(t,e,n,r,s){return Object.entries(s).flatMap(([i,o])=>{if(ys([i,o]))return on(t,"or",e,n,r,o);if(bs([i,o]))return on(t,"and",e,n,r,o);if(i==="$entityIdStartsWith")return[];const a=i.split(".");if(o!=null&&o.hasOwnProperty("$ne")&&(o={...o,$not:o.$ne},delete o.$ne),o!=null&&o.hasOwnProperty("$not")){const c=tt(t,e,n,r,a,o),u=an(t,e,n,r,a);return[{or:{patterns:[c,...u],joinSym:t(n,r)}}]}return o!=null&&o.hasOwnProperty("$isNull")&&o.$isNull===!0&&a.length>1?[{or:{patterns:an(t,e,n,r,a),joinSym:t(n,r)}}]:tt(t,e,n,r,a,o)})}function ws(t,e,n,r){const s=Ae;return r?cn(s,t,e,n,r).concat(nn(s,t,e,n)):nn(s,t,e,n)}function _s(t,e,n){return[t(e,n),t("time",n)]}function Ss(t,e,n,r,s,i){const[o,a,c,u,f]=rn(t,e,n,r,s),l=fs(c,t(n,r),i);return[o,a,l,u,f]}function ms(t,e,{etype:n,level:r,form:s},i){const o=Object.keys(s).filter(a=>a!=="$");return o.length?Object.entries(i).map(function([c,u]){return o.map(function(d){var p,b,T;const h=!!(e.cardinalityInference&&((T=(b=(p=e.linkIndex)==null?void 0:p[n])==null?void 0:b[d])!=null&&T.isSingular));try{const[y,w,O]=Ss(t,e,n,r,d,c),C=fn(e,{etype:y,level:w,form:s[d],join:O}),_=h?C[0]:C;return{[d]:_}}catch(y){if(y instanceof se)return{[d]:h?void 0:[]};throw y}}).reduce(function(d,h){return{...d,...h}},u)}):Object.values(i)}function Os(t,e,n){return n==="string"?os(t,e):t>e?1:-1}function ye(t,e,n,r,s){return e===r||e==null&&r==null?rs(t,n):r==null?1:e==null?-1:Os(e,r,s)}function Ee([t,e],[n,r],s){return ye(t,e,n,r,s)}function nt(t){return t==null?t:new Date(t).getTime()}function As(t,e,n,r){var p;const[s,i,o,a]=t,c=n==="desc"?1:-1;if(((p=e["forward-identity"])==null?void 0:p[2])==="id")return Ee(r,[s,a],null)===c;const[u,f]=r,l=e["checked-data-type"],d=l==="date"?nt(f):f,h=l==="date"?nt(o):o;return Ee([u,d],[s,h],l)===c}function Es(t,e){const n=e[1];return t.attrs[n]}function ks(t,e,n){const r=Object.keys(n)[0];return G(t,e,r)}function Cs(t,e,n,r){if(n)return Es(t,n);if(r)return ks(t,e,r)}function Ms(t,e,n){var s,i;if(!Array.isArray(n.fields))return Lr(t,e);const r=new Map;for(const o of n.fields){const a=G(t,e,o),c=(s=a==null?void 0:a["forward-identity"])==null?void 0:s[2];c&&He(a)&&r.set(c,a)}if(!r.has("id")){const o=G(t,e,"id"),a=(i=o==null?void 0:o["forward-identity"])==null?void 0:i[2];a&&r.set(a,o)}return r}function Is(t,{etype:e,pageInfo:n,dq:r,form:s}){var h,p;const i=(h=s==null?void 0:s.$)==null?void 0:h.order,o=un(s),a=vs(s);let c=Hr(t,r);const u=n==null?void 0:n["start-cursor"],f=Cs(t,e,u,i);if(f&&((p=f==null?void 0:f["forward-identity"])==null?void 0:p[2])!=="id"){const b=f["checked-data-type"]==="date",T=f.id;c=c.map(([y])=>{var O,C,_,I,F;let w=(F=(I=(_=(C=(O=t.eav.get(y))==null?void 0:O.get(T))==null?void 0:C.values())==null?void 0:_.next())==null?void 0:I.value)==null?void 0:F[2];return b&&(w=nt(w)),[y,w]})}c.sort(a==="asc"?function(T,y){return Ee(T,y,f==null?void 0:f["checked-data-type"])}:function(T,y){return Ee(y,T,f==null?void 0:f["checked-data-type"])});let l={};const d=Ms(t,e,r);for(const b of c){const[T]=b;if(l[T]||!o&&u&&f&&As(u,f,a,b))continue;const y=xr(t,d,T);y&&(l[T]=y)}return l}function vs(t){var n;const e=(n=t.$)==null?void 0:n.order;return e&&e[Object.keys(e)[0]]||"asc"}function un(t){var s,i,o;const e=(s=t.$)==null?void 0:s.offset,n=(i=t.$)==null?void 0:i.before,r=(o=t.$)==null?void 0:o.after;return!e&&!n&&!r}function Ps(t,{etype:e,level:n,form:r,join:s,pageInfo:i}){var l,d,h,p,b;if(!un(r)&&(!i||!i["start-cursor"]))return[];const o=ps(ws(t,e,n,(l=r.$)==null?void 0:l.where),s),a=_s(Ae,e,n),c=(d=r.$)==null?void 0:d.fields,u=Is(t,{etype:e,pageInfo:i,form:r,dq:{where:o,find:a,fields:c}}),f=((h=r.$)==null?void 0:h.limit)||((p=r.$)==null?void 0:p.first)||((b=r.$)==null?void 0:b.last);if(f!=null){n>0&&console.warn("WARNING: Limits in child queries are only run client-side. Data returned from the server will not have a limit.");const T=Object.entries(u);return T.length<=f?u:Object.fromEntries(T.slice(0,f))}return u}function $s(t,e){try{return Ps(t,e)}catch(n){if(n instanceof se)return{};throw n}}function fn(t,e){const n=$s(t,e);return ms(Ae,t,e,n)}function js(t){const e={};for(const[n,r]of Object.entries(t))e[n]={startCursor:r["start-cursor"],endCursor:r["end-cursor"],hasNextPage:r["has-next-page?"],hasPreviousPage:r["has-previous-page?"]};return e}function ln({store:t,pageInfo:e,aggregate:n},r){const i={data:Object.keys(r).reduce(function(a,c){return n!=null&&n[c]||c==="$$ruleParams"||(a[c]=fn(t,{etype:c,form:r[c],level:0,pageInfo:e==null?void 0:e[c]})),a},{})};return e&&(i.pageInfo=js(e)),n&&(i.aggregate=n),i}function Ds(){const e={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(e))}const Rs=Ds();function rt(t,e,n){const r={__etype:t,__ops:n};return new Proxy(r,{get:(s,i)=>{if(i==="__ops")return n;if(i==="__etype")return t;if(Rs.has(i))return(o,a)=>rt(t,e,[...n,a?[i,t,e,o,a]:[i,t,e,o]])}})}function Us(t,e){return`lookup__${t}__${JSON.stringify(e)}`}function ke(t){return t.startsWith("lookup__")}function dn(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function xs(t){return new Proxy({__etype:t},{get(e,n){if(n==="__etype")return t;const r=n;return ke(r)?rt(t,dn(r),[]):rt(t,r,[])}})}function st(){return new Proxy({},{get(t,e){return xs(e)}})}const Ls=st();function hn(t){return t.__ops}function Ns(t,e){const{attrIdMap:n,refSwapAttrIds:r}=t,s=[];for(const o of e){const a=n[o];if(a)s.push(a);else if(Array.isArray(o)&&o.length==2&&n[o[0]]){const[c,u]=o;s.push([n[c],u])}else s.push(o)}const[i]=e;if((i==="add-triple"||i==="retract-triple")&&r.has(e[2])){const o=s[1];s[1]=s[3],s[3]=o}return s}function P(t,e,n){return Object.values(t).find(r=>{const[s,i,o]=r["forward-identity"];return i===e&&o===n})}function Z(t,e,n){return Object.values(t).find(r=>{const s=r["reverse-identity"];if(!s)return!1;const[i,o,a]=s;return o===e&&a===n})}function Fs(t){if(Array.isArray(t))return t;const e=Object.entries(t);if(e.length!==1)throw new Error("lookup must be an object with a single unique attr and value.");return e[0]}function it(t,e,n){return n.indexOf(".")!==-1&&!P(t,e,n)}function ot(t){const[e,n,...r]=t.split(".");if(r.length>0||n!=="id")throw new Error(`${t} is not a valid lookup attribute.`);return e}function Vs(t,e,n){if(!it(t,e,n))return P(t,e,n);const r=ot(n),s=P(t,e,r)||Z(t,e,r);if(s&&s["value-type"]!=="ref")throw new Error(`${n} does not reference a valid link attribute.`);return s}function at(t){return typeof t=="string"&&!ke(t)?null:typeof t=="string"&&ke(t)?dn(t):Fs(t)}function U(t,e,n){const r=at(n);if(r===null)return n;const[s,i]=r,o=Vs(t,e,s);if(!o||!o["unique?"])throw new Error(`${s} is not a unique attribute.`);return[o.id,i]}function pn(t,e,n,r){const s=U(t,e,n);return Array.isArray(s)?[["add-triple",s,P(t,e,"id").id,s]].concat(r):r}function qs({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=P(t,e,i),u=Z(t,e,i);return a.map(f=>c?["add-triple",U(t,e,n),c.id,U(t,c["reverse-identity"][1],f)]:["add-triple",U(t,u["forward-identity"][1],f),u.id,U(t,e,n)])});return pn(t,e,n,s)}function zs({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=P(t,e,i),u=Z(t,e,i);return a.map(f=>c?["retract-triple",U(t,e,n),c.id,U(t,c["reverse-identity"][1],f)]:["retract-triple",U(t,u["forward-identity"][1],f),u.id,U(t,e,n)])});return pn(t,e,n,s)}function Ws(t,e,n){if(Array.isArray(n)){const[r,s]=n;for(const i of t||[]){const o=i==null?void 0:i.aev.get(r);if(o){for(const[a,c,u]of R(o,2))if(u===s)return!0}}}else for(const r of t||[]){const s=r==null?void 0:r.eav.get(n);if(s){for(const i of s.keys())if(r.attrs[i]["forward-identity"][1]==e)return!0}}return!1}function yn({stores:t,attrs:e},[n,r,s,i]){return(i==null?void 0:i.upsert)===!1?{mode:"update"}:(i==null?void 0:i.upsert)===!0?null:Ws(t,n,r)?{mode:"update"}:null}function Ks(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Qe(i),c=U(n,r,s);return[["id",c]].concat(Object.entries(a)).map(([f,l])=>{const d=P(n,r,f);return d["checked-data-type"]==="date"&&t.useDateObjects&&(l=de(l)),["add-triple",c,d.id,l,{mode:"create"}]})}function Qs(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Qe(i),c=U(n,r,s),u=yn(t,[r,c,i,o]);return[["id",c]].concat(Object.entries(a)).map(([l,d])=>{const h=P(n,r,l);return h["checked-data-type"]==="date"&&t.useDateObjects&&(d=de(d)),["add-triple",c,h.id,d,...u?[u]:[]]})}function Bs({attrs:t},[e,n]){return[["delete-entity",U(t,e,n),e]]}function Gs(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Qe(i),c=U(n,r,s),u=yn(t,[r,c,i,o]),f=Object.entries(a).map(([d,h])=>{const p=P(n,r,d);return["deep-merge-triple",c,p.id,h,...u?[u]:[]]});return[["add-triple",c,P(n,r,"id").id,c,...u?[u]:[]]].concat(f)}function Hs({attrs:t},[e,n,r]){return[["rule-params",U(t,e,n),e,r]]}function Js(t){const[e,n,r,s,i]=t;if(!s)return t;const o={...s};return delete o.id,[e,n,r,o,...i?[i]:[]]}function Ys(t,e){const[n,...r]=Js(e);switch(n){case"merge":return Gs(t,r);case"create":return Ks(t,r);case"update":return Qs(t,r);case"link":return qs(t,r);case"unlink":return zs(t,r);case"delete":return Bs(t,r);case"ruleParams":return Hs(t,r);default:throw new Error(`unsupported action ${n}`)}}function Zs(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function Xs(t,e,n){var a,c;const r=(c=(a=t.entities[e])==null?void 0:a.attrs)==null?void 0:c[n];if(n==="id")return null;if(!r)throw new Error(`${e}.${n} does not exist in your schema`);const{unique:s,indexed:i}=r==null?void 0:r.config,o=Zs(r==null?void 0:r.valueType);return{"index?":i,"unique?":s,"checked-data-type":o}}function Ce(t,e,n,r){const s=t?Xs(t,e,n):null,i=M(),a=[M(),e,n];return{id:i,"forward-identity":a,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}function ei(t,e,n){return Object.values(t.links).find(s=>s.forward.on===e&&s.forward.label===n||s.reverse.on===e&&s.reverse.label===n)}function ti(t,e,n){const r=ei(t,e,n);if(!r)throw new Error(`Couldn't find the link ${e}.${n} in your schema`);const{forward:s,reverse:i}=r;return{"forward-identity":[M(),s.on,s.label],"reverse-identity":[M(),i.on,i.label],cardinality:s.has==="one"?"one":"many","unique?":i.has==="one","on-delete":s.onDelete,"on-delete-reverse":i.onDelete}}function bn(t,e,n,r){const s=t?ti(t,e,n):null,i=M(),o=[M(),e,n],a=[M(),n,e];return{id:i,"forward-identity":o,"reverse-identity":a,"value-type":"ref",cardinality:"many","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}const ni=new Set(["create","update","merge","link","unlink"]),ri=new Set(["link","unlink"]),si=new Set(["create","update","merge"]),ii=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),ct={"unique?":!0,"index?":!0},oi={...ct,cardinality:"one"};function ai(t){const e=[],[n,r,s,i]=t;if(!ii.has(n))return e;const o=at(s);if(o&&e.push({etype:r,lookupPair:o}),n==="link")for(const[a,c]of Object.entries(i)){const u=Array.isArray(c)?c:[c];for(const f of u){const l=at(f);l&&e.push({etype:r,lookupPair:l,linkLabel:a})}}return e}function ci({attrs:t,schema:e},n){var u,f;const[r,s,i]=[new Set,{...t},[]];function o(l){s[l.id]=l,i.push(["add-attr",l]),r.add(l.id)}function a(l){l!=null&&l.isUnsynced&&!r.has(l.id)&&(i.push(["add-attr",l]),r.add(l.id))}function c(l,d){const h=P(s,l,d),p=Z(s,l,d);a(h),a(p),!h&&!p&&o(bn(e,l,d,oi))}for(const l of n)for(const{etype:d,lookupPair:h,linkLabel:p}of ai(l)){const b=h[0];if(p){c(d,p);const T=P(s,d,p),y=Z(s,d,p);a(T),a(y);const w=((u=T==null?void 0:T["reverse-identity"])==null?void 0:u[1])||((f=y==null?void 0:y["forward-identity"])==null?void 0:f[1])||p;if(it(s,w,b))c(w,ot(b));else{const O=P(s,w,b);O||o(Ce(e,w,b,ct)),a(O)}}else if(it(s,d,b))c(d,ot(b));else{const T=P(s,d,b);T||o(Ce(e,d,b,ct)),a(T)}}for(const l of n){const[d,h,p,b]=l;if(ni.has(d)){const T=P(s,h,"id");a(T),T||o(Ce(e,h,"id",{"unique?":!0}));for(const y of Object.keys(b)){const w=P(s,h,y);if(a(w),si.has(d)&&(w||o(Ce(e,h,y,y==="id"?{"unique?":!0}:null))),ri.has(d)){const O=Z(s,h,y);!w&&!O&&o(bn(e,h,y)),a(O)}}}}return[s,i]}function ui(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>hn(c)),[s,i]=ci(t,r),o={...t,attrs:s},a=r.flatMap(c=>Ys(o,c));return[...i,...a]}class ut{constructor(e){this.dbName=e,this._storeName="kv",this._dbPromise=this._init()}_init(){return new Promise((e,n)=>{const r=indexedDB.open(this.dbName,1);r.onerror=s=>{n(s)},r.onsuccess=s=>{const i=s.target;e(i.result)},r.onupgradeneeded=s=>{s.target.result.createObjectStore(this._storeName)}})}async getItem(e){const n=await this._dbPromise;return new Promise((r,s)=>{const a=n.transaction([this._storeName],"readonly").objectStore(this._storeName).get(e);a.onerror=c=>{s(c)},a.onsuccess=c=>{a.result?r(a.result):r(null)}})}async setItem(e,n){const r=await this._dbPromise;return new Promise((s,i)=>{const c=r.transaction([this._storeName],"readwrite").objectStore(this._storeName).put(n,e);c.onerror=u=>{i(u)},c.onsuccess=u=>{s()}})}}class ft{static async getIsOnline(){return navigator.onLine}static listen(e){const n=()=>{e(!0)},r=()=>{e(!1)};return addEventListener("online",n),addEventListener("offline",r),()=>{removeEventListener("online",n),removeEventListener("offline",r)}}}class ie extends Error{constructor(e,n){super(e),this.hint=n;const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,ie),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class be extends ie{constructor(e){var s;const n=((s=e.body)==null?void 0:s.message)||`API Error (${e.status})`;super(n,e.body.hint);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,be),this.name="InstantAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"InstantAPIError"}}async function z(t,e){const n=await fetch(t,e),r=await n.json();return n.status===200?Promise.resolve(r):Promise.reject(new be({status:n.status,body:r}))}function fi({apiURI:t,appId:e,email:n}){return z(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}async function li({apiURI:t,appId:e,email:n,code:r,refreshToken:s}){return await z(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n,code:r,...s?{"refresh-token":s}:{}})})}async function di({apiURI:t,appId:e,refreshToken:n}){return await z(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,"refresh-token":n})})}async function hi({apiURI:t,appId:e}){return await z(`${t}/runtime/auth/sign_in_guest`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e})})}async function Tn({apiURI:t,appId:e,code:n,codeVerifier:r,refreshToken:s}){return await z(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,code:n,code_verifier:r,refresh_token:s})})}async function pi({apiURI:t,appId:e,nonce:n,idToken:r,clientName:s,refreshToken:i}){return await z(`${t}/runtime/oauth/id_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,nonce:n,id_token:r,client_name:s,refresh_token:i})})}async function yi({apiURI:t,appId:e,refreshToken:n}){return await z(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,refresh_token:n})})}async function bi({apiURI:t,appId:e,path:n,file:r,refreshToken:s,contentType:i,contentDisposition:o}){const a={app_id:e,path:n,authorization:`Bearer ${s}`,"content-type":i||r.type};return o&&(a["content-disposition"]=o),await z(`${t}/storage/upload`,{method:"PUT",headers:a,body:r})}async function Ti({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await z(`${t}/storage/files?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}async function gi({apiURI:t,appId:e,fileName:n,refreshToken:r,metadata:s={}}){const{data:i}=await z(`${t}/storage/signed-upload-url`,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${r}`},body:JSON.stringify({app_id:e,filename:n})});return i}async function wi(t,e){return(await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok}async function _i({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await z(`${t}/storage/signed-download-url?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}let lt=!1,gn=!1,wn=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(lt=!!window.localStorage.getItem("devBackend"),gn=!!window.localStorage.getItem("__instantLogging"),wn=!!window.localStorage.getItem("__devtoolLocalDash"));function _n(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function Si(t,e,n){const r={peers:{}};if(e&&"user"in e?e.user:!0){const i=_n(t.user??{},e==null?void 0:e.keys);r.user={...i,peerId:n}}for(const i of Object.keys(t.peers??{})){const o=(e==null?void 0:e.peers)===void 0,a=Array.isArray(e==null?void 0:e.peers)&&(e==null?void 0:e.peers.includes(i));if(o||a){const c=_n(t.peers[i],e==null?void 0:e.keys);r.peers[i]={...c,peerId:i}}}return r}function mi(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!Ut(t.user,e.user))||!Rt(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!Ut(t.peers[r],e.peers[r]))return!0;return!1}class Sn{constructor(){g(this,"promise");g(this,"_resolve");g(this,"_reject");this.promise=new Promise((e,n)=>{this._resolve=e,this._reject=n})}resolve(e){this._resolve(e)}reject(e){this._reject(e)}}function Oi(t,e){typeof requestIdleCallback>"u"?t():requestIdleCallback(t,{timeout:e})}class dt{constructor(e,n,r,s,i=u=>u,o=u=>u,a=100,c=1e3){this._subs=[],this._nextSave=null,this._persister=e,this._key=n,this._onMerge=s,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.serialize=i,this.parse=o,this._saveThrottleMs=a,this._pendingSaveCbs=[],this._version=0,this._idleCallbackMaxWaitMs=c,this._load()}async _getFromStorage(){try{return this.parse(await this._persister.getItem(this._key))}catch(e){return console.error(`Unable to read from storage for key=${this._key}`,e),null}}async _load(){const e=await this._getFromStorage();this._isLoading=!1;const n=this._onMerge(e,this.currentValue);n&&(this.currentValue=n);for(const r of this._loadedCbs)r()}async waitForLoaded(){if(!this._isLoading)return;await new Promise(n=>{this._loadedCbs.push(n)})}isLoading(){return this._isLoading}version(){return this._version}async waitForSync(){if(!this._nextSave)return;await new Promise(n=>{this._pendingSaveCbs.push(n)})}_writeToStorage(){this._persister.setItem(this._key,this.serialize(this.currentValue));for(const e of this._pendingSaveCbs)e();this._pendingSaveCbs.length=0}async flush(){this._nextSave&&(clearTimeout(this._nextSave),this._writeToStorage())}_enqueuePersist(e){if(this._nextSave){e&&this._pendingSaveCbs.push(e);return}this._nextSave=setTimeout(()=>{Oi(()=>{this._nextSave=null,this._writeToStorage()},this._idleCallbackMaxWaitMs)},this._saveThrottleMs)}set(e,n){this._version++,this.currentValue=e(this.currentValue),this._isLoading?this._loadedCbs.push(()=>this._enqueuePersist(n)):this._enqueuePersist(n);for(const r of this._subs)r(this.currentValue);return this.currentValue}subscribe(e){return this._subs.push(e),e(this.currentValue),()=>{this._subs=this._subs.filter(n=>n!==e)}}}function mn(t,e=[]){t.forEach(n=>{const{data:r}=n,{"datalog-result":s}=r,{"join-rows":i}=s;for(const o of i)for(const a of o)e.push(a);mn(n["child-nodes"],e)})}function On(t){const e=[];return mn(t,e),e}function An(t){return Object.values(t.links).reduce((e,n)=>{var r,s;return e[r=n.forward.on]??(e[r]={}),e[n.forward.on][n.forward.label]={isForward:!0,isSingular:n.forward.has==="one",link:n},e[s=n.reverse.on]??(e[s]={}),e[n.reverse.on][n.reverse.label]={isForward:!1,isSingular:n.reverse.has==="one",link:n},e},{})}const ht="v0.22.57";function Ai(t,e){return{info:t?(...n)=>console.info(...n,e()):()=>{},debug:t?(...n)=>console.debug(...n,e()):()=>{},error:t?(...n)=>console.error(...n,e()):()=>{}}}class j{constructor(e,n,r,s={indexed:!1,unique:!1}){this.valueType=e,this.required=n,this.isIndexed=r,this.config=s,this.metadata={}}clientRequired(){return new j(this.valueType,!1,this.isIndexed,this.config)}optional(){return new j(this.valueType,!1,this.isIndexed,this.config)}unique(){return new j(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new j(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class Me{constructor(e,n){this.attrs=e,this.links=n}asType(){return new Me(this.attrs,this.links)}}class Ie{constructor(e,n,r){this.entities=e,this.links=n,this.rooms=r}withRoomSchema(){return new Ie(this.entities,this.links,{})}}class k extends Error{constructor(e,n){const r=n?`At path '${n}': ${e}`:e;super(r),this.name="QueryValidationError"}}const En=["where","order","limit","last","first","offset","after","before","fields","aggregate"],Ei=t=>t.valueType||"unknown",kn=(t,e,n=!1)=>{if(n||t==null)return!0;switch(e){case"string":return typeof t=="string";case"number":return typeof t=="number"&&!isNaN(t);case"boolean":return typeof t=="boolean";case"date":return t instanceof Date||typeof t=="string"||typeof t=="number";default:return!0}},ki=(t,e,n,r,s,i,o)=>{const a=i.valueType==="json",c=(u,f,l)=>{if(!kn(l,f,a))throw new k(`Invalid value for operator '${u}' on attribute '${r}' in entity '${s}'. Expected ${f}, but received: ${typeof l}`,o)};switch(t){case"in":case"$in":if(!Array.isArray(e))throw new k(`Operator '${t}' for attribute '${r}' in entity '${s}' must be an array, but received: ${typeof e}`,o);for(const u of e)c(t,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(t,n,e);break;case"$like":case"$ilike":if(c(t,"string",e),t==="$ilike"&&!i.isIndexed)throw new k(`Operator '${t}' can only be used with indexed attributes, but '${r}' in entity '${s}' is not indexed`,o);break;case"$isNull":c(t,"boolean",e);break;default:throw new k(`Unknown operator '${t}' for attribute '${r}' in entity '${s}'`,o)}},oe=(t,e,n,r,s)=>{const i=Ei(n),o=n.valueType==="json";if(typeof t=="object"&&t!==null&&!Array.isArray(t)){if(o)return;const c=t;for(const[u,f]of Object.entries(c))ki(u,f,i,e,r,n,`${s}.${u}`)}else if(!kn(t,i,o))throw new k(`Invalid value for attribute '${e}' in entity '${r}'. Expected ${i}, but received: ${typeof t}`,s)},Ci=(t,e,n,r,s)=>{const i=t.split(".");if(i.length<2)throw new k(`Invalid dot notation path '${t}'. Must contain at least one dot.`,s);let o=n;for(let f=0;f<i.length-1;f++){const l=i[f],d=r.entities[o];if(!d)throw new k(`Entity '${o}' does not exist in schema while traversing dot notation path '${t}'.`,s);const h=d.links[l];if(!h){const p=Object.keys(d.links);throw new k(`Link '${l}' does not exist on entity '${o}' in dot notation path '${t}'. Available links: ${p.length>0?p.join(", "):"none"}`,s)}o=h.entityName}const a=i[i.length-1],c=r.entities[o];if(!c)throw new k(`Target entity '${o}' does not exist in schema for dot notation path '${t}'.`,s);if(a==="id"){if(typeof e=="string"&&!re(e))throw new k(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${e}`,s);oe(e,t,new j("string",!1,!0),n,s);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof e=="string"&&!re(e))throw new k(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${e}`,s);oe(e,t,new j("string",!1,!0),n,s);return}if(!u){const f=Object.keys(c.attrs);throw new k(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${t}'. Available attributes: ${f.length>0?f.join(", ")+", id":"id"}`,s)}oe(e,t,u,n,s)},Cn=(t,e,n,r)=>{for(const[s,i]of Object.entries(t)){if(s==="or"||s==="and"){if(Array.isArray(i))for(const u of i)typeof u=="object"&&u!==null&&Cn(u,e,n,`${r}.${s}[${u}]`);continue}if(s==="id"){oe(i,"id",new j("string",!1,!0),e,`${r}.id`);continue}if(s.includes(".")){Ci(s,i,e,n,`${r}.${s}`);continue}const o=n.entities[e];if(!o)continue;const a=o.attrs[s],c=o.links[s];if(!a&&!c){const u=Object.keys(o.attrs),f=Object.keys(o.links);throw new k(`Attribute or link '${s}' does not exist on entity '${e}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${f.length>0?f.join(", "):"none"}`,`${r}.${s}`)}if(a)oe(i,s,a,e,`${r}.${s}`);else if(c){if(typeof i=="string"&&!re(i))throw new k(`Invalid value for link '${s}' in entity '${e}'. Expected a UUID, but received: ${i}`,`${r}.${s}`);const u=new j("string",!1,!0);oe(i,s,u,e,`${r}.${s}`)}}},Mi=(t,e,n,r,s=0)=>{for(const o of Object.keys(t))if(!En.includes(o))throw new k(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${En.join(", ")}. Found: ${o}`,r);const i=["offset","before","after","first","last"];for(const o of i)if(t[o]!==void 0&&s>0)throw new k(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,r);if(t.where&&n){if(typeof t.where!="object"||t.where===null)throw new k(`'where' clause must be an object in entity '${e}', but received: ${typeof t.where}`,r?`${r}.where`:void 0);Cn(t.where,e,n,r?`${r}.where`:"where")}},Mn=(t,e,n,r,s=0)=>{var i;if(!t||typeof t!="object")throw new k(`Query part for entity '${e}' must be an object, but received: ${typeof t}`,r);for(const o of Object.keys(t))if(o!=="$"){if(n&&!(o in n.entities[e].links)){const c=Object.keys(n.entities[e].links);throw new k(`Link '${o}' does not exist on entity '${e}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${r}.${o}`)}const a=t[o];if(typeof a=="object"&&a!==null){const c=(i=n==null?void 0:n.entities[e].links[o])==null?void 0:i.entityName;c&&Mn(a,c,n,`${r}.${o}`,s+1)}}else{const a=t[o];if(typeof a!="object"||a===null)throw new k(`Query parameter '$' must be an object in entity '${e}', but received: ${typeof a}`,`${r}.$`);Mi(a,e,n,`${r}.$`,s)}},pt=(t,e)=>{if(typeof t!="object"||t===null)throw new k(`Query must be an object, but received: ${typeof t}${t===null?" (null)":""}`);if(Array.isArray(t))throw new k(`Query must be an object, but received: ${typeof t}`);const n=t;for(const r of Object.keys(n)){if(Array.isArray(t[r]))throw new k(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(typeof r!="string")throw new k(`Query keys must be strings, but found key of type: ${typeof r}`,r);if(r!=="$$ruleParams"){if(e&&!e.entities[r]){const s=Object.keys(e.entities);throw new k(`Entity '${r}' does not exist in schema. Available entities: ${s.length>0?s.join(", "):"none"}`,r)}Mn(n[r],r,e,r,0)}}},In=t=>typeof t!="string"?!1:ke(t)?!0:re(t);class N extends Error{constructor(e){super(e),this.name="TransactionValidationError"}}const vn=t=>t.length>0?t.join(", "):"none",Ii=(t,e)=>new N(`Entity '${t}' does not exist in schema. Available entities: ${vn(e)}`),yt={string:t=>typeof t=="string",number:t=>typeof t=="number"&&!isNaN(t),boolean:t=>typeof t=="boolean",date:t=>t instanceof Date||typeof t=="string"||typeof t=="number",json:()=>!0},vi=(t,e)=>{var n;return t==null?!0:((n=yt[e.valueType])==null?void 0:n.call(yt,t))??!1},Pn=(t,e)=>{const n=e.entities[t];if(!n)throw Ii(t,Object.keys(e.entities));return n},bt=(t,e,n)=>{const r=Pn(t,n);if(typeof e!="object"||e===null)throw new N(`Arguments for data operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(s==="id")continue;const o=r.attrs[s];if(o&&!vi(i,o))throw new N(`Invalid value for attribute '${s}' in entity '${t}'. Expected ${o.valueType}, but received: ${typeof i}`)}},$n=(t,e,n)=>{const r=Pn(t,n);if(typeof e!="object"||e===null)throw new N(`Arguments for link operation on entity '${t}' must be an object, but received: ${typeof e}`);for(const[s,i]of Object.entries(e)){if(!r.links[s]){const a=Object.keys(r.links);throw new N(`Link '${s}' does not exist on entity '${t}'. Available links: ${vn(a)}`)}if(i!=null){if(Array.isArray(i)){for(const a of i)if(!In(a))throw new N(`Invalid entity ID in link '${s}' for entity '${t}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!In(i))throw new N(`Invalid UUID in link '${s}' for entity '${t}'. Expected a UUID, but received: ${i}`)}}},Pi={create:bt,update:bt,merge:bt,link:$n,unlink:$n,delete:()=>{}},$i=(t,e)=>{if(!e)return;const[n,r,s,i]=t;if(!Array.isArray(s)&&!re(s))throw new N(`Invalid id for entity '${r}'. Expected a UUID, but received: ${s}`);if(typeof r!="string")throw new N(`Entity name must be a string, but received: ${typeof r}`);const o=Pi[n];o&&i!==void 0&&o(r,i,e)},jn=(t,e)=>{const n=Array.isArray(t)?t:[t];for(const r of n){if(!r||typeof r!="object")throw new N(`Transaction chunk must be an object, but received: ${typeof r}`);if(!Array.isArray(r.__ops))throw new N(`Transaction chunk must have __ops array, but received: ${typeof r.__ops}`);for(const s of r.__ops){if(!Array.isArray(s))throw new N(`Transaction operation must be an array, but received: ${typeof s}`);$i(s,e)}}};let Dn=0;class Rn{constructor(e){this.type="ws",this.id=`${this.type}_${Dn++}`,this.conn=new WebSocket(e),this.conn.onopen=n=>{this.onopen&&this.onopen({target:this})},this.conn.onmessage=n=>{this.onmessage&&this.onmessage({target:this,message:JSON.parse(n.data.toString())})},this.conn.onclose=n=>{this.onclose&&this.onclose({target:this})},this.conn.onerror=n=>{this.onerror&&this.onerror({target:this})}}close(){this.conn.close()}isOpen(){return this.conn.readyState===WebSocket.OPEN}isConnecting(){return this.conn.readyState===WebSocket.CONNECTING}send(e){return this.conn.send(JSON.stringify(e))}}class ji{constructor(e,n){this.type="sse",this.initParams=null,this.sendQueue=[],this.closeFired=!1,this.sseInitTimeout=null,this.id=`${this.type}_${Dn++}`,this.url=n,this.ES=e,this.conn=new e(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const s=JSON.parse(r.data);if(s.op==="sse-init"){this.initParams={machineId:s["machine-id"],sessionId:s["session-id"],sseToken:s["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:s})},this.conn.onerror=r=>{this.handleError()}}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(e){try{(await fetch(this.url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:this.initParams.machineId,session_id:this.initParams.sessionId,sse_token:this.initParams.sseToken,messages:e})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const e=this.sendQueue;this.sendQueue=[];const n=this.postMessages(e);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(e){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(e),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()}}function Di(t,e){for(const n in t){const r=t[n];for(const s of r.entities||[])s.store.useDateObjects=e,s.store=Wt(s.store)}return t}function Ri(t){const e={};for(const n in t){const r=t[n];if(r.entities){const s=[];for(const i of r.entities)s.push({...i,store:zt(i.store)});e[n]={...r,entities:s}}else e[n]=r}return e}function Ui(t,e){const n={};for(const[r,s]of Object.entries(e))n[r]=s;if(t)for(const[r,s]of Object.entries(t))n[r]=s;return n}function Tt(t,e){return ln({store:e,pageInfo:null,aggregate:null},t.query).data[t.table][0]}function Un(t,e,n){var i;const r=(i=G(e,t.table,"id"))==null?void 0:i.id;if(!r)return-1;const s=ne(e.eav,[n,r,n]);return s?s[3]:-1}function xn(t,e){for(const{action:n,triple:r}of e)switch(n){case"added":Bt(t,r);break;case"removed":Kt(t,r);break}}function xi(t,e){var r,s;const n={};for(const{action:i,triple:o}of e){const[a,c,u]=o,f=(s=(r=t.attrs[c])==null?void 0:r["forward-identity"])==null?void 0:s[2];if(!f)continue;const l=n[a]??{};n[a]=l;const d=l[f]??{};switch(l[f]=d,i){case"added":d.newValue=u;break;case"removed":d.oldValue===void 0&&(d.oldValue=u);break}}return n}function ve(t,e){return{[t.table]:e.map(n=>n.entity)}}function Li(t,e){const n=t.orderFieldType;if(t.orderField==="serverCreatedAt"){e.sort(t.orderDirection==="asc"?function(i,o){return ye(i.entity.id,i.serverCreatedAt,o.entity.id,o.serverCreatedAt,n)}:function(i,o){return ye(o.entity.id,o.serverCreatedAt,i.entity.id,i.serverCreatedAt,n)});return}const r=t.orderField;e.sort(t.orderDirection==="asc"?function(i,o){return ye(i.entity.id,i.entity[r],o.entity.id,o.entity[r],n)}:function(i,o){return ye(o.entity.id,o.entity[r],i.entity.id,i.entity[r],n)})}var Ln=(t=>(t.InitialSyncBatch="InitialSyncBatch",t.InitialSyncComplete="InitialSyncComplete",t.LoadFromStorage="LoadFromStorage",t.SyncTransaction="SyncTransaction",t.Error="Error",t))(Ln||{});class Ni{constructor(e,n,r,s,i){this.callbacks={},this.idToHash={},this.trySend=e,this.config=r,this.log=s,this.createStore=i,this.subs=new dt(n,"subs",{},Ui,Ri,o=>Di(o,this.config.useDateObjects))}beforeUnload(){this.subs.flush()}subscribe(e,n){const r=A(e);return this.callbacks[r]=this.callbacks[r]||[],this.callbacks[r].push(n),this.initSubscription(e,r,n),s=>{this.unsubscribe(r,n,s==null?void 0:s.keepSubscription)}}unsubscribe(e,n,r){const s=(this.callbacks[e]||[]).filter(i=>i!==n);if(this.callbacks[e]=s,!s.length){if(delete this.callbacks[e],r)return;const i=this.subs.currentValue[e];i!=null&&i.state&&this.clearSubscriptionData(i.state.subscriptionId),this.subs.set(o=>(delete o[e],o))}}sendStart(e){this.trySend(M(),{op:"start-sync",q:e})}sendResync(e,n){this.idToHash[n.subscriptionId]=e.hash,this.trySend(n.subscriptionId,{op:"resync-table","subscription-id":n.subscriptionId,"tx-id":n.txId,token:n.token})}sendRemove(e){this.trySend(M(),{op:"remove-sync","subscription-id":e.subscriptionId})}async initSubscription(e,n,r){var f,l,d;await this.subs.waitForLoaded();const s=this.subs.currentValue[n];if(s&&s.state&&s.state.txId){this.sendResync(s,s.state),s.entities&&r&&(Object.keys(e)[0],r({type:"LoadFromStorage",data:ve(s,s.entities)}));return}const i=Object.keys(e)[0],o=((l=(f=e[i])==null?void 0:f.$)==null?void 0:l.order)||{serverCreatedAt:"asc"},[a,c]=Object.entries(o)[0],u=a==="serverCreatedAt"?"number":(d=G(this.createStore([]),i,a))==null?void 0:d["checked-data-type"];this.subs.set(h=>(h[n]={query:e,hash:n,table:i,orderDirection:c,orderField:a,orderFieldType:u,createdAt:Date.now(),updatedAt:Date.now()},h)),this.sendStart(e)}async flushPending(){await this.subs.waitForLoaded();for(const e of Object.keys(this.callbacks)){const n=this.subs.currentValue[e];n?await this.initSubscription(n.query,n.hash):this.log.error("Missing sub for hash in flushPending",e)}}onStartSyncOk(e){const n=e["subscription-id"],r=e.q,s=A(r);this.idToHash[n]=s,this.subs.set(i=>{const o=i[s];return o?(o.state={subscriptionId:n,token:e.token},i):(this.log.error("Missing sub for hash",s,"subscription-id",n,"query",r),i)})}notifyCbs(e,n){for(const r of this.callbacks[e]||[])r(n)}onSyncLoadBatch(e){const n=e["subscription-id"],r=e["join-rows"],s=this.idToHash[n];if(!s){this.log.error("Missing hash for subscription",e);return}const i=[],a=this.subs.set(c=>{const u=c[s];if(!u)return this.log.error("Missing sub for hash",s,e),c;const f=u.entities??[];u.entities=f;for(const l of r){const d=this.createStore(l),h=Tt(u,d);f.push({store:d,entity:h,serverCreatedAt:Un(u,d,h.id)}),i.push(h)}return u.updatedAt=Date.now(),c})[s];a.entities&&this.notifyCbs(s,{type:"InitialSyncBatch",data:ve(a,a.entities),batch:i})}onSyncInitFinish(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(i=>{const o=i[r];if(!o)return this.log.error("Missing sub for hash",r,e),i;const a=o.state;return a?(a.txId=e["tx-id"],o.updatedAt=Date.now(),i):(this.log.error("Sub never set init, missing result",o,e),i)});const s=this.subs.currentValue[r];s&&this.notifyCbs(r,{type:"InitialSyncComplete",data:ve(s,s.entities||[])})}onSyncUpdateTriples(e){const n=e["subscription-id"],r=this.idToHash[n];if(!r){this.log.error("Missing hash for subscription",e);return}this.subs.set(s=>{const i=s[r];if(!i)return this.log.error("Missing sub for hash",r,e),s;const o=i.state;if(!o)return this.log.error("Missing state for sub",i,e),s;for(const a of e.txes){if(o.txId>=a["tx-id"])continue;o.txId=a["tx-id"];const c=[],u={};for(const p of a.changes){const b=u[p.triple[0]]??[];u[p.triple[0]]=b,b.push(p)}const f=i.entities||[];i.entities=f;const l=[];e:for(const[p,b]of Object.entries(u))for(const[T,y]of Object.entries(f))if(Mr(y.store,p)){xn(y.store,b);const w=Tt(i,y.store),O=xi(y.store,b)[p];for(const[C,{oldValue:_,newValue:I}]of Object.entries(O||{}))_===I&&delete O[C];w?(l.push({oldEntity:y.entity,newEntity:w,changedFields:O||{}}),y.entity=w):c.push(T),delete u[p];continue e}const d=[];for(const[p,b]of Object.entries(u)){const T=this.createStore([]);xn(T,b);const y=Tt(i,T);if(!y){this.log.error("No entity found after applying change",{sub:i,changes:b,store:T});continue}f.push({store:T,entity:y,serverCreatedAt:Un(i,T,y.id)}),d.push(y)}const h=[];for(const p of c.sort().reverse())h.push(f[p].entity),f.splice(p,1);Li(i,f),this.notifyCbs(r,{type:"SyncTransaction",data:ve(i,i.entities),added:d,removed:h,updated:l}),i.updatedAt=Date.now()}return s})}clearSubscriptionData(e){const n=this.idToHash[e];if(n){delete this.idToHash[e];const r=this.subs.currentValue[n];if(r.state&&this.sendRemove(r.state),this.subs.set(s=>(delete s[n],s)),r)return r}}onStartSyncError(e){const n=A(e["original-event"].q),r={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa.",status:e.status,type:e.type,hint:e.hint},s=Object.keys(e["original-event"].q)[0];this.notifyCbs(n,{type:"Error",data:{[s]:[]},error:r})}onResyncError(e){const n=e["original-event"]["subscription-id"],r=this.clearSubscriptionData(n);r&&this.initSubscription(r.query,r.hash)}}const B={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Fi=3e4,Vi=3e4,qi=200,zi={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},gt="_instant_oauth_redirect",wt="currentUser";function Wi({transportType:t,appId:e,apiURI:n,wsURI:r,EventSourceImpl:s}){if(!s)return new Rn(`${r}?app_id=${e}`);switch(t){case"ws":return new Rn(`${r}?app_id=${e}`);case"sse":return new ji(s,`${n}/runtime/sse?app_id=${e}`);default:throw new Error("Unknown transport type "+t)}}function Ki(){return typeof window<"u"||typeof chrome<"u"}const Nn={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function Qi(t,e){var r;const n=typeof t=="string"?JSON.parse(t):t;for(const s in n){const i=n[s];if((r=i==null?void 0:i.result)!=null&&r.store){const o=i.result.store;i.result.store=Wt({...o,useDateObjects:e})}}return n}function Bi(t){var n;const e={};for(const r in t){const s=t[r],i={...s};(n=s.result)!=null&&n.store&&(i.result={...s.result,store:zt(s.result.store)}),e[r]=i}return e}function Fn(t){return[...t].sort((e,n)=>{const[r,s]=e,[i,o]=n,a=s.order||0,c=o.order||0;return a==c?r<i?-1:r>i?1:0:a-c})}class Gi{constructor(e,n=ut,r=ft,s,i){g(this,"attrs");g(this,"_isOnline",!0);g(this,"_isShutdown",!1);g(this,"status",B.CONNECTING);g(this,"querySubs");g(this,"pendingMutations");g(this,"queryCbs",{});g(this,"queryOnceDfds",{});g(this,"authCbs",[]);g(this,"attrsCbs",[]);g(this,"mutationErrorCbs",[]);g(this,"connectionStatusCbs",[]);g(this,"config");g(this,"_persister");g(this,"mutationDeferredStore",new Map);g(this,"_reconnectTimeoutId",null);g(this,"_reconnectTimeoutMs",0);g(this,"_transport");g(this,"_transportType","ws");g(this,"_EventSource");g(this,"_wsOk",null);g(this,"_localIdPromises",{});g(this,"_errorMessage",null);g(this,"_oauthCallbackResponse",null);g(this,"_linkIndex",null);g(this,"_broadcastChannel");g(this,"_rooms",{});g(this,"_roomsPendingLeave",{});g(this,"_presence",{});g(this,"_broadcastQueue",[]);g(this,"_broadcastSubs",{});g(this,"_currentUserCached",{isLoading:!0,error:void 0,user:void 0});g(this,"_beforeUnloadCbs",[]);g(this,"_dataForQueryCache",{});g(this,"_log");g(this,"_pendingTxCleanupTimeout");g(this,"_pendingMutationCleanupThreshold");g(this,"_inFlightMutationEventIds",new Set);g(this,"_onMergeQuerySubs",(e,n)=>{const r=e||{},s={...n};Object.entries(n).forEach(([o,a])=>{var f;const c=(f=r==null?void 0:r[o])==null?void 0:f.result,u=a.result;c&&!u&&(s[o].result=c)}),Object.keys(r).filter(o=>!n[o]).sort((o,a)=>{var f,l;const c=((f=r[o])==null?void 0:f.lastAccessed)||0;return(((l=r[a])==null?void 0:l.lastAccessed)||0)-c}).slice(0,this.queryCacheLimit).forEach(o=>{s[o]=r[o]}),this.querySubs.set(o=>s),this.loadedNotifyAll()});g(this,"_onMergePendingMutations",(e,n)=>{const r=new Map([...e.entries(),...n.entries()]);this.pendingMutations.set(i=>r),this.loadedNotifyAll(),this._rewriteMutationsSorted(this.attrs,e).forEach(([i,o])=>{!n.has(i)&&!o["tx-id"]&&this._sendMutation(i,o)})});g(this,"getPreviousResult",e=>{const n=A(e);return this.dataForQuery(n)});g(this,"notifyOne",e=>{var i;const n=this.queryCbs[e]??[],r=(i=this._dataForQueryCache[e])==null?void 0:i.data,s=this.dataForQuery(e);s&&(Se(s,r)||n.forEach(o=>o.cb(s)))});g(this,"notifyOneQueryOnce",e=>{const n=this.queryOnceDfds[e]??[],r=this.dataForQuery(e);n.forEach(s=>{this._completeQueryOnce(s.q,e,s.dfd),s.dfd.resolve(r)})});g(this,"notifyQueryError",(e,n)=>{(this.queryCbs[e]||[]).forEach(s=>s.cb({error:n}))});g(this,"pushTx",e=>{this.config.disableValidation||jn(e,this.config.schema);try{const n=ui({attrs:this.optimisticAttrs(),schema:this.config.schema,stores:Object.values(this.querySubs.currentValue).map(r=>{var s;return(s=r==null?void 0:r.result)==null?void 0:s.store}),useDateObjects:this.config.useDateObjects},e);return this.pushOps(n)}catch(n){return this.pushOps([],n)}});g(this,"pushOps",(e,n)=>{const r=M(),s=[...this.pendingMutations.currentValue.values()],i=Math.max(0,...s.map(c=>c.order||0))+1,o={op:"transact","tx-steps":e,created:Date.now(),error:n,order:i};this.pendingMutations.set(c=>(c.set(r,o),c));const a=new Sn;return this.mutationDeferredStore.set(r,a),this._sendMutation(r,o),this.notifyAll(),a.promise});g(this,"_transportOnOpen",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][open]",n.id,"skip; this is no longer the current transport");return}this._log.info("[socket][open]",this._transport.id),this._setStatus(B.OPENED),this.getCurrentUser().then(r=>{var s;this._trySend(M(),{op:"init","app-id":this.config.appId,"refresh-token":(s=r.user)==null?void 0:s.refresh_token,versions:this.versions,"__admin-token":this.config.__adminToken})}).catch(r=>{this._log.error("[socket][error]",n.id,r)})});g(this,"_transportOnMessage",e=>{const n=e.target,r=e.message;if(this._transport!==n){this._log.info("[socket][message]",n.id,r,"skip; this is no longer the current transport");return}!this._wsOk&&n.type==="ws"&&(this._wsOk=!0),this._transportType="ws",this._handleReceive(n.id,e.message)});g(this,"_transportOnError",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][error]",n.id,"skip; this is no longer the current transport");return}this._log.error("[socket][error]",n.id,e)});g(this,"_scheduleReconnect",()=>{!this._wsOk&&this._transportType!=="sse"&&(this._transportType="sse",this._reconnectTimeoutMs=0),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",this._transport.id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)});g(this,"_transportOnClose",e=>{const n=e.target;if(this._transport!==n){this._log.info("[socket][close]",n.id,"skip; this is no longer the current transport");return}this._setStatus(B.CLOSED);for(const r of Object.values(this._rooms))r.isConnected=!1;if(this._isShutdown){this._log.info("[socket][close]",n.id,"Reactor has been shut down and will not reconnect");return}this._log.info("[socket][close]",n.id,"schedule reconnect, ms =",this._reconnectTimeoutMs),this._scheduleReconnect()});if(this._EventSource=i,this.config={...zi,...e},this.queryCacheLimit=this.config.queryCacheLimit??10,this._pendingTxCleanupTimeout=this.config.pendingTxCleanupTimeout??Vi,this._pendingMutationCleanupThreshold=this.config.pendingMutationCleanupThreshold??qi,this._log=Ai(e.verbose||lt||gn,()=>this._reactorStats()),this.versions={...s||{},"@instantdb/core":ht},this.config.schema&&(this._linkIndex=An(this.config.schema)),!!Ki()){if(!e.appId)throw new Error("Instant must be initialized with an appId.");if(!re(e.appId))throw new Error(`Instant must be initialized with a valid appId. \`${e.appId}\` is not a valid uuid.`);typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",async o=>{var a;try{if(((a=o.data)==null?void 0:a.type)==="auth"){const c=await this.getCurrentUser();this.updateUser(c.user)}}catch(c){this._log.error("[error] handle broadcast channel",c)}})),this._initStorage(n),this._syncTable=new Ni(this._trySendAuthed.bind(this),this._persister,{useDateObjects:this.config.useDateObjects},this._log,o=>me(this.attrs,o,this.config.enableCardinalityInference,this._linkIndex,this.config.useDateObjects)),this._oauthCallbackResponse=this._oauthLoginInit(),this.getCurrentUser(),r.getIsOnline().then(o=>{this._isOnline=o,this._startSocket(),r.listen(a=>{a!==this._isOnline&&(this._log.info("[network] online =",a),this._isOnline=a,this._isOnline?this._startSocket():(this._log.info("Changing status from",this.status,"to",B.CLOSED),this._setStatus(B.CLOSED)))})}),typeof addEventListener<"u"&&(this._beforeUnload=this._beforeUnload.bind(this),addEventListener("beforeunload",this._beforeUnload))}}updateSchema(e){this.config={...this.config,schema:e,cardinalityInference:!!e},this._linkIndex=e?An(this.config.schema):null}_reactorStats(){return{inFlightMutationCount:this._inFlightMutationEventIds.size,pendingMutationCount:this.pendingMutations.currentValue.size,transportType:this._transportType}}_initStorage(e){this._persister=new e(`instant_${this.config.appId}_5`),this.querySubs=new dt(this._persister,"querySubs",{},this._onMergeQuerySubs,Bi,n=>Qi(n,this.config.useDateObjects)),this.pendingMutations=new dt(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>[...n.entries()],n=>new Map(typeof n=="string"?JSON.parse(n):n),100,100),this._beforeUnloadCbs.push(()=>{this.pendingMutations.flush(),this.querySubs.flush()})}_beforeUnload(){for(const e of this._beforeUnloadCbs)e();this._syncTable.beforeUnload()}_finishTransaction(e,n,r){const s=this.mutationDeferredStore.get(n);this.mutationDeferredStore.delete(n);const i=e!=="error"&&e!=="timeout";if(!s&&!i&&console.error("Mutation failed",{status:e,eventId:n,...r}),!!s)if(i)s.resolve({status:e,eventId:n});else if(r.type){const{status:o,...a}=r;s.reject(new be({body:a,status:o}))}else s.reject(new ie(r.message,r.hint))}_setStatus(e,n){this.status=e,this._errorMessage=n,this.notifyConnectionStatusSubs(e)}_flushEnqueuedRoomData(e){var s,i;const n=(i=(s=this._presence[e])==null?void 0:s.result)==null?void 0:i.user,r=this._broadcastQueue[e];if(this._broadcastQueue[e]=[],n&&this._trySetPresence(e,n),r)for(const o of r){const{topic:a,roomType:c,data:u}=o;this._tryBroadcast(e,c,a,u)}}_handleReceive(e,n){var s,i,o,a,c,u;const r=!!this.config.schema&&("cardinalityInference"in this.config?!!this.config.cardinalityInference:!0);switch(Nn[n.op]||this._log.info("[receive]",e,n.op,n),n.op){case"init-ok":{this._setStatus(B.AUTHENTICATED),this._reconnectTimeoutMs=0,this._setAttrs(n.attrs),this._flushPendingMessages(),this._sessionId=n["session-id"];for(const d of Object.keys(this._rooms)){const h=(i=(s=this._presence[d])==null?void 0:s.result)==null?void 0:i.user;this._tryJoinRoom(d,h)}break}case"add-query-exists":{this.notifyOneQueryOnce(A(n.q));break}case"add-query-ok":{const{q:d,result:h}=n,p=A(d),b=(a=(o=h==null?void 0:h[0])==null?void 0:o.data)==null?void 0:a["page-info"],T=(u=(c=h==null?void 0:h[0])==null?void 0:c.data)==null?void 0:u.aggregate,y=On(h),w=me(this.attrs,y,r,this._linkIndex,this.config.useDateObjects);this.querySubs.set(O=>(O[p].result={store:w,pageInfo:b,aggregate:T,processedTxId:n["processed-tx-id"]},O)),this._cleanupPendingMutationsQueries(),this.notifyOne(p),this.notifyOneQueryOnce(p),this._cleanupPendingMutationsTimeout();break}case"start-sync-ok":{this._syncTable.onStartSyncOk(n);break}case"sync-load-batch":{this._syncTable.onSyncLoadBatch(n);break}case"sync-init-finish":{this._syncTable.onSyncInitFinish(n);break}case"sync-update-triples":{this._syncTable.onSyncUpdateTriples(n);break}case"refresh-ok":{const{computations:d,attrs:h}=n,p=n["processed-tx-id"];h&&this._setAttrs(h),this._cleanupPendingMutationsTimeout();const b=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,p);b!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>b);const T=Fn(b.entries()),y=d.map(w=>{var Bn,Gn,Hn,Jn;const O=w["instaql-query"],C=w["instaql-result"],_=A(O),I=On(C),F=me(this.attrs,I,r,this._linkIndex,this.config.useDateObjects),X=this._applyOptimisticUpdates(F,T,p),Ot=(Gn=(Bn=C==null?void 0:C[0])==null?void 0:Bn.data)==null?void 0:Gn["page-info"],_o=(Jn=(Hn=C==null?void 0:C[0])==null?void 0:Hn.data)==null?void 0:Jn.aggregate;return{hash:_,store:X,pageInfo:Ot,aggregate:_o}});y.forEach(({hash:w,store:O,pageInfo:C,aggregate:_})=>{this.querySubs.set(I=>(I[w].result={store:O,pageInfo:C,aggregate:_,processedTxId:p},I))}),this._cleanupPendingMutationsQueries(),y.forEach(({hash:w})=>{this.notifyOne(w)});break}case"transact-ok":{const{"client-event-id":d,"tx-id":h}=n;this._inFlightMutationEventIds.delete(d);const b=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(d);if(!b)break;this.pendingMutations.set(y=>(y.set(d,{...y.get(d),"tx-id":h,confirmed:Date.now()}),y));const T=b["tx-steps"].filter(([y,...w])=>y==="add-attr").map(([y,w])=>w).concat(Object.values(this.attrs));this._setAttrs(T),this._finishTransaction("synced",d),this._cleanupPendingMutationsTimeout();break}case"patch-presence":{const d=n["room-id"];this._trySetRoomConnected(d,!0),this._patchPresencePeers(d,n.edits),this._notifyPresenceSubs(d);break}case"refresh-presence":{const d=n["room-id"];this._trySetRoomConnected(d,!0),this._setPresencePeers(d,n.data),this._notifyPresenceSubs(d);break}case"server-broadcast":{const d=n["room-id"],h=n.topic;this._trySetRoomConnected(d,!0),this._notifyBroadcastSubs(d,h,n);break}case"join-room-ok":{const d=n["room-id"];if(!this._rooms[d]){this._roomsPendingLeave[d]&&(this._tryLeaveRoom(d),delete this._roomsPendingLeave[d]);break}this._trySetRoomConnected(d,!0),this._flushEnqueuedRoomData(d);break}case"leave-room-ok":{const d=n["room-id"];this._trySetRoomConnected(d,!1);break}case"join-room-error":const f=n["room-id"],l=this._rooms[f];l&&(l.error=n.error),this._notifyPresenceSubs(f);break;case"error":this._handleReceiveError(n);break;default:this._log.info("Uknown op",n.op,n);break}}_handleMutationError(e,n,r){const s=this.pendingMutations.currentValue.get(n);if(s&&(e!=="timeout"||!s["tx-id"])){this.pendingMutations.set(o=>(o.delete(n),o)),this._inFlightMutationEventIds.delete(n);const i={message:r.message,hint:r.hint};this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(i),this._finishTransaction(e,n,r)}}_handleReceiveError(e){var a,c,u,f,l,d,h;console.log("error",e);const n=e["client-event-id"];this._inFlightMutationEventIds.delete(n);const r=this.pendingMutations.currentValue.get(n),s={message:e.message||"Uh-oh, something went wrong. Ping Joe & Stopa."};if(e.hint&&(s.hint=e.hint),r){this._handleMutationError("error",n,e);return}if((a=e["original-event"])!=null&&a.hasOwnProperty("q")&&((c=e["original-event"])==null?void 0:c.op)==="add-query"){const p=(u=e["original-event"])==null?void 0:u.q,b=A(p);this.notifyQueryError(A(p),s),this.notifyQueryOnceError(p,b,n,s);return}if(((f=e["original-event"])==null?void 0:f.op)==="init"){if(e.type==="record-not-found"&&((l=e.hint)==null?void 0:l["record-type"])==="app-user"){this.changeCurrentUser(null);return}this._setStatus(B.ERRORED,s),this.notifyAll();return}if(((d=e["original-event"])==null?void 0:d.op)==="resync-table"){this._syncTable.onResyncError(e);return}if(((h=e["original-event"])==null?void 0:h.op)==="start-sync"){this._syncTable.onStartSyncError(e);return}const o={...e};delete o.message,delete o.hint,console.error(e.message,o),e.hint&&console.error(`This error comes with some debugging information. Here it is:
|
|
2
|
+
`,e.hint)}notifyQueryOnceError(e,n,r,s){var o;const i=(o=this.queryOnceDfds[n])==null?void 0:o.find(a=>a.eventId===r);i&&(i.dfd.reject(s),this._completeQueryOnce(e,n,i.dfd))}_setAttrs(e){this.attrs=e.reduce((n,r)=>(n[r.id]=r,n),{}),this.notifyAttrsSubs()}_startQuerySub(e,n){const r=M();return this.querySubs.set(s=>(s[n]=s[n]||{q:e,result:null,eventId:r},s[n].lastAccessed=Date.now(),s)),this._trySendAuthed(r,{op:"add-query",q:e}),r}subscribeTable(e,n){return this._syncTable.subscribe(e,n)}subscribeQuery(e,n,r){this.config.disableValidation||pt(e,this.config.schema),r&&"ruleParams"in r&&(e={$$ruleParams:r.ruleParams,...e});const s=A(e),i=this.getPreviousResult(e);return i&&n(i),this.queryCbs[s]=this.queryCbs[s]??[],this.queryCbs[s].push({q:e,cb:n}),this._startQuerySub(e,s),()=>{this._unsubQuery(e,s,n)}}queryOnce(e,n){this.config.disableValidation||pt(e,this.config.schema),n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=new Sn;if(!this._isOnline)return r.reject(new Error("We can't run `queryOnce`, because the device is offline.")),r.promise;if(!this.querySubs)return r.reject(new Error("We can't run `queryOnce` on the backend. Use adminAPI.query instead: https://www.instantdb.com/docs/backend#query")),r.promise;const s=A(e),i=this._startQuerySub(e,s);return this.queryOnceDfds[s]=this.queryOnceDfds[s]??[],this.queryOnceDfds[s].push({q:e,dfd:r,eventId:i}),setTimeout(()=>r.reject(new Error("Query timed out")),Fi),r.promise}_completeQueryOnce(e,n,r){this.queryOnceDfds[n]&&(this.queryOnceDfds[n]=this.queryOnceDfds[n].filter(s=>s.dfd!==r),this._cleanupQuery(e,n))}_unsubQuery(e,n,r){this.queryCbs[n]&&(this.queryCbs[n]=this.queryCbs[n].filter(s=>s.cb!==r),this._cleanupQuery(e,n))}_cleanupQuery(e,n){var s,i;(s=this.queryCbs[n])!=null&&s.length||(i=this.queryOnceDfds[n])!=null&&i.length||(delete this.queryCbs[n],delete this.queryOnceDfds[n],this._trySendAuthed(M(),{op:"remove-query",q:e}))}_rewriteMutations(e,n,r){if(!e)return n;const s=f=>{const[l,d,h]=f["forward-identity"];return P(e,d,h)},i=f=>{const[l,d,h]=f["forward-identity"];return Z(e,d,h)},o={attrIdMap:{},refSwapAttrIds:new Set};let a=!1;const c=(f,l)=>{const d=[];for(const h of f){const[p]=h;if(p==="add-attr"){const[T,y]=h,w=s(y);if(w&&y.id!==w.id){o.attrIdMap[y.id]=w.id,a=!0;continue}if(y["value-type"]==="ref"){const O=i(y);if(O){o.attrIdMap[y.id]=O.id,o.refSwapAttrIds.add(y.id),a=!0;continue}}}if(r&&l&&r>=l&&p==="add-attr"||p==="update-attr"||p==="delete-attr"){a=!0;continue}const b=a?Ns(o,h):h;d.push(b)}return a?d:f},u=new Map;for(const[f,l]of n.entries())u.set(f,{...l,"tx-steps":c(l["tx-steps"],l["tx-id"])});return a?u:n}_rewriteMutationsSorted(e,n){return Fn(this._rewriteMutations(e,n).entries())}optimisticAttrs(){var o;const e=[...this.pendingMutations.currentValue.values()].flatMap(a=>a["tx-steps"]),n=new Set(e.filter(([a,c])=>a==="delete-attr").map(([a,c])=>c)),r=[];for(const[a,c]of e)if(a==="add-attr")r.push(c);else if(a==="update-attr"&&c.id&&((o=this.attrs)!=null&&o[c.id])){const u={...this.attrs[c.id],...c};r.push(u)}const s=[...Object.values(this.attrs||{}),...r].filter(a=>!n.has(a.id));return Object.fromEntries(s.map(a=>[a.id,a]))}dataForQuery(e){const n=this._errorMessage;if(n)return{error:n};if(!this.querySubs||!this.pendingMutations)return;const r=this.querySubs.version(),s=this.querySubs.currentValue,i=this.pendingMutations.version(),o=this.pendingMutations.currentValue,{q:a,result:c}=s[e]||{};if(!c)return;const u=this._dataForQueryCache[e];if(u&&r===u.querySubVersion&&i===u.pendingMutationsVersion)return u.data;const{store:f,pageInfo:l,aggregate:d,processedTxId:h}=c,p=this._rewriteMutationsSorted(f.attrs,o),b=this._applyOptimisticUpdates(f,p,h),T=ln({store:b,pageInfo:l,aggregate:d},a);return this._dataForQueryCache[e]={querySubVersion:r,pendingMutationsVersion:i,data:T},T}_applyOptimisticUpdates(e,n,r){for(const[s,i]of n)(!i["tx-id"]||r&&i["tx-id"]>r)&&(e=Fr(e,i["tx-steps"]));return e}notifyAll(){Object.keys(this.queryCbs).forEach(e=>{this.notifyOne(e)})}loadedNotifyAll(){this.pendingMutations.isLoading()||this.querySubs.isLoading()||this.notifyAll()}shutdown(){var e;this._log.info("[shutdown]",this.config.appId),this._isShutdown=!0,(e=this._transport)==null||e.close()}_sendMutation(e,n){if(n.error){this._handleMutationError("error",e,{message:n.error.message});return}if(this.status!==B.AUTHENTICATED){this._finishTransaction("enqueued",e);return}const r=Math.max(6e3,Math.min(this._inFlightMutationEventIds.size+1,this.pendingMutations.currentValue.size+1)*6e3);this._isOnline?(this._trySend(e,n),setTimeout(()=>{this._isOnline&&this._handleMutationError("timeout",e,{message:"transaction timed out"})},r)):this._finishTransaction("enqueued",e)}_flushPendingMessages(){Object.keys(this.queryCbs).map(s=>this.querySubs.currentValue[s]).filter(s=>s).forEach(({eventId:s,q:i})=>{this._trySendAuthed(s,{op:"add-query",q:i})}),Object.values(this.queryOnceDfds).flat().forEach(({eventId:s,q:i})=>{this._trySendAuthed(s,{op:"add-query",q:i})}),this._rewriteMutationsSorted(this.attrs,this.pendingMutations.currentValue).forEach(([s,i])=>{i["tx-id"]||this._sendMutation(s,i)}),this._syncTable.flushPending()}_cleanupPendingMutationsQueries(){let e=Number.MAX_SAFE_INTEGER;for(const{result:n}of Object.values(this.querySubs.currentValue))n!=null&&n.processedTxId&&(e=Math.min(e,n==null?void 0:n.processedTxId));this.pendingMutations.set(n=>{for(const[r,s]of Array.from(n.entries()))s["tx-id"]&&s["tx-id"]<=e&&n.delete(r);return n})}_cleanupPendingMutationsTimeout(){if(this.pendingMutations.currentValue.size<this._pendingMutationCleanupThreshold)return;const e=Date.now();this.pendingMutations.set(n=>{for(const[r,s]of Array.from(n.entries()))s.confirmed&&s.confirmed+this._pendingTxCleanupTimeout<e&&n.delete(r);return n})}_trySendAuthed(...e){this.status===B.AUTHENTICATED&&this._trySend(...e)}_trySend(e,n,r){if(this._transport.isOpen()){switch(Nn[n.op]||this._log.info("[send]",this._transport.id,n.op,n),n.op){case"transact":{this._inFlightMutationEventIds.add(e);break}case"init":this._inFlightMutationEventIds.clear()}this._transport.send({"client-event-id":e,...n})}}_startSocket(){if(this._wsOk=null,this._isShutdown){this._log.info("[socket][start]",this.config.appId,"Reactor has been shut down and will not start a new socket");return}if(this._transport&&this._transport.isConnecting()){this._log.info("[socket][start]",this._transport.id,"maintained as current transport, we were still in a connecting state");return}const e=this._transport;this._transport=Wi({transportType:this._transportType,appId:this.config.appId,apiURI:this.config.apiURI,wsURI:this.config.websocketURI,EventSourceImpl:this._EventSource}),this._transport.onopen=this._transportOnOpen,this._transport.onmessage=this._transportOnMessage,this._transport.onclose=this._transportOnClose,this._transport.onerror=this._transportOnError,this._log.info("[socket][start]",this._transport.id),e!=null&&e.isOpen()&&(this._log.info("[socket][start]",this._transport.id,"close previous transport id = ",e.id),e.close())}async getLocalId(e){const n=`localToken_${e}`,r=await this._persister.getItem(n);if(r)return r;if(this._localIdPromises[n])return this._localIdPromises[n];const s=M();return this._localIdPromises[n]=this._persister.setItem(n,s).then(()=>s),this._localIdPromises[n]}_replaceUrlAfterOAuth(){if(typeof URL>"u")return;const e=new URL(window.location.href);if(e.searchParams.get(gt)){const n=e.toString();e.searchParams.delete(gt),e.searchParams.delete("code"),e.searchParams.delete("error");const r=e.pathname+(e.searchParams.size?"?"+e.searchParams:"")+e.hash;if(history.replaceState(history.state,"",r),typeof navigation=="object"&&typeof navigation.addEventListener=="function"&&typeof navigation.removeEventListener=="function"){let s=!1;const i=o=>{var a;s||(s=!0,navigation.removeEventListener("navigate",i),!o.userInitiated&&o.navigationType==="replace"&&((a=o.destination)==null?void 0:a.url)===n&&history.replaceState(history.state,"",r))};navigation.addEventListener("navigate",i)}}}async _oauthLoginInit(){var s,i,o,a;if(typeof window>"u"||typeof window.location>"u"||typeof URLSearchParams>"u")return null;const e=new URLSearchParams(window.location.search);if(!e.get(gt))return null;const n=e.get("error");if(n)return this._replaceUrlAfterOAuth(),{error:{message:n}};const r=e.get("code");if(!r)return null;this._replaceUrlAfterOAuth();try{const c=await this._getCurrentUser(),u=(c==null?void 0:c.type)==="guest",{user:f}=await Tn({apiURI:this.config.apiURI,appId:this.config.appId,code:r,refreshToken:u?c.refresh_token:void 0});return this.setCurrentUser(f),null}catch(c){return((s=c==null?void 0:c.body)==null?void 0:s.type)==="record-not-found"&&((o=(i=c==null?void 0:c.body)==null?void 0:i.hint)==null?void 0:o["record-type"])==="app-oauth-code"&&await this._hasCurrentUser()?null:{error:{message:((a=c==null?void 0:c.body)==null?void 0:a.message)||"Error logging in."}}}}async _waitForOAuthCallbackResponse(){return await this._oauthCallbackResponse}__subscribeMutationErrors(e){return this.mutationErrorCbs.push(e),()=>{this.mutationErrorCbs=this.mutationErrorCbs.filter(n=>n!==e)}}subscribeAuth(e){this.authCbs.push(e);const n=this._currentUserCached;n.isLoading||e(this._currentUserCached);let r=!1;return this.getCurrentUser().then(s=>{r||Se(s,n)||e(s)}),()=>{r=!0,this.authCbs=this.authCbs.filter(s=>s!==e)}}async getAuth(){const{user:e,error:n}=await this.getCurrentUser();if(n)throw new ie("Could not get current user: "+n.message);return e}subscribeConnectionStatus(e){return this.connectionStatusCbs.push(e),()=>{this.connectionStatusCbs=this.connectionStatusCbs.filter(n=>n!==e)}}subscribeAttrs(e){return this.attrsCbs.push(e),this.attrs&&e(this.attrs),()=>{this.attrsCbs=this.attrsCbs.filter(n=>n!==e)}}notifyAuthSubs(e){this.authCbs.forEach(n=>n(e))}notifyMutationErrorSubs(e){this.mutationErrorCbs.forEach(n=>n(e))}notifyAttrsSubs(){if(!this.attrs)return;const e=this.optimisticAttrs();this.attrsCbs.forEach(n=>n(e))}notifyConnectionStatusSubs(e){this.connectionStatusCbs.forEach(n=>n(e))}async setCurrentUser(e){await this._persister.setItem(wt,e)}getCurrentUserCached(){return this._currentUserCached}async _getCurrentUser(){const e=await this._persister.getItem(wt);return typeof e=="string"?JSON.parse(e):e}async getCurrentUser(){const e=await this._waitForOAuthCallbackResponse();if(e!=null&&e.error){const s={error:e.error,user:void 0};return this._currentUserCached={isLoading:!1,...s},s}const r={user:await this._getCurrentUser(),error:void 0};return this._currentUserCached={isLoading:!1,...r},r}async _hasCurrentUser(){const e=await this._persister.getItem(wt);return JSON.parse(e)!=null}async changeCurrentUser(e){var r;const{user:n}=await this.getCurrentUser();if(!Se(n,e)){await this.setCurrentUser(e),this.updateUser(e);try{(r=this._broadcastChannel)==null||r.postMessage({type:"auth"})}catch(s){console.error("Error posting message to broadcast channel",s)}}}updateUser(e){const n={error:void 0,user:e};this._currentUserCached={isLoading:!1,...n},this._dataForQueryCache={},this.querySubs.set(r=>(Object.keys(r).forEach(s=>{delete r[s].result}),r)),this._reconnectTimeoutMs=0,this._transport.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:e}){return fi({apiURI:this.config.apiURI,appId:this.config.appId,email:e})}async signInWithMagicCode({email:e,code:n}){var o;const r=await this.getCurrentUser(),s=((o=r==null?void 0:r.user)==null?void 0:o.type)==="guest",i=await li({apiURI:this.config.apiURI,appId:this.config.appId,email:e,code:n,refreshToken:s?r.user.refresh_token:void 0});return await this.changeCurrentUser(i.user),i}async signInWithCustomToken(e){const n=await di({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:e});return await this.changeCurrentUser(n.user),n}async signInAsGuest(){const e=await hi({apiURI:this.config.apiURI,appId:this.config.appId});return await this.changeCurrentUser(e.user),e}potentiallyInvalidateToken(e,n){var i;const r=(i=e==null?void 0:e.user)==null?void 0:i.refresh_token;if(!r)return;if(n.invalidateToken===!1){this._log.info("[auth-invalidate] skipped invalidateToken");return}yi({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:r}).then(()=>{this._log.info("[auth-invalidate] completed invalidateToken")}).catch(o=>{})}async signOut(e){const n=await this.getCurrentUser();this.potentiallyInvalidateToken(n,e),await this.changeCurrentUser(null)}createAuthorizationURL({clientName:e,redirectURL:n}){const{apiURI:r,appId:s}=this.config;return`${r}/runtime/oauth/start?app_id=${s}&client_name=${e}&redirect_uri=${n}`}async exchangeCodeForToken({code:e,codeVerifier:n}){var o;const r=await this.getCurrentUser(),s=((o=r==null?void 0:r.user)==null?void 0:o.type)==="guest",i=await Tn({apiURI:this.config.apiURI,appId:this.config.appId,code:e,codeVerifier:n,refreshToken:s?r.user.refresh_token:void 0});return await this.changeCurrentUser(i.user),i}issuerURI(){const{apiURI:e,appId:n}=this.config;return`${e}/runtime/${n}`}async signInWithIdToken({idToken:e,clientName:n,nonce:r}){var a;const s=await this.getCurrentUser(),i=(a=s==null?void 0:s.user)==null?void 0:a.refresh_token,o=await pi({apiURI:this.config.apiURI,appId:this.config.appId,idToken:e,clientName:n,nonce:r,refreshToken:i});return await this.changeCurrentUser(o.user),o}joinRoom(e,n){let r=!1;this._rooms[e]||(r=!0,this._rooms[e]={isConnected:!1,error:void 0}),this._presence[e]=this._presence[e]||{};const s=this._presence[e].result;return n&&!s&&(this._presence[e].result=this._presence[e].result||{},this._presence[e].result.user=n,this._notifyPresenceSubs(e)),r&&this._tryJoinRoom(e,n),()=>{this._cleanupRoom(e)}}_cleanupRoom(e){var n,r,s;if(!((r=(n=this._presence[e])==null?void 0:n.handlers)!=null&&r.length)&&!Object.keys(this._broadcastSubs[e]??{}).length){const i=(s=this._rooms[e])==null?void 0:s.isConnected;delete this._rooms[e],delete this._presence[e],delete this._broadcastSubs[e],i?this._tryLeaveRoom(e):this._roomsPendingLeave[e]=!0}}getPresence(e,n,r={}){const s=this._rooms[n],i=this._presence[n];return!s||!i||!i.result?null:{...Si(i.result,r,this._sessionId),isLoading:!s.isConnected,error:s.error}}publishPresence(e,n,r){const s=this._rooms[n],i=this._presence[n];if(!s||!i)return;i.result=i.result||{};const o={...i.result.user,...r};i.result.user=o,s.isConnected&&(this._trySetPresence(n,o),this._notifyPresenceSubs(n))}_trySetPresence(e,n){this._trySendAuthed(M(),{op:"set-presence","room-id":e,data:n})}_tryJoinRoom(e,n){this._trySendAuthed(M(),{op:"join-room","room-id":e,data:n}),delete this._roomsPendingLeave[e]}_tryLeaveRoom(e){this._trySendAuthed(M(),{op:"leave-room","room-id":e})}_trySetRoomConnected(e,n){const r=this._rooms[e];r&&(r.isConnected=n)}subscribePresence(e,n,r,s){const i=this.joinRoom(n,r.initialPresence||r.initialData),o={...r,roomId:n,cb:s,prev:null};return this._presence[n]=this._presence[n]||{},this._presence[n].handlers=this._presence[n].handlers||[],this._presence[n].handlers.push(o),this._notifyPresenceSub(n,o),()=>{var a,c;this._presence[n].handlers=((c=(a=this._presence[n])==null?void 0:a.handlers)==null?void 0:c.filter(u=>u!==o))??[],i()}}_notifyPresenceSubs(e){var n,r;(r=(n=this._presence[e])==null?void 0:n.handlers)==null||r.forEach(s=>{this._notifyPresenceSub(e,s)})}_notifyPresenceSub(e,n){const r=this.getPresence("",e,n);r&&(n.prev&&!mi(r,n.prev)||(n.prev=r,n.cb(r)))}_patchPresencePeers(e,n){var o,a,c;const r=((a=(o=this._presence[e])==null?void 0:o.result)==null?void 0:a.peers)||{};let s=Object.fromEntries(Object.entries(r).map(([u,f])=>[u,{data:f}]));(c=this._presence[e])==null||c.result;const i=Ke(s,u=>{for(let[f,l,d]of n)switch(l){case"+":ur(u,f,d);break;case"r":Lt(u,f,d);break;case"-":Nt(u,f);break}delete u[this._sessionId]});this._setPresencePeers(e,i)}_setPresencePeers(e,n){const r={...n};delete r[this._sessionId];const s=Object.fromEntries(Object.entries(r).map(([i,o])=>[i,o.data]));this._presence=Ke(this._presence,i=>{Lt(i,[e,"result","peers"],s)})}publishTopic({roomType:e,roomId:n,topic:r,data:s}){const i=this._rooms[n];if(i){if(!i.isConnected){this._broadcastQueue[n]=this._broadcastQueue[n]??[],this._broadcastQueue[n].push({topic:r,roomType:e,data:s});return}this._tryBroadcast(n,e,r,s)}}_tryBroadcast(e,n,r,s){this._trySendAuthed(M(),{op:"client-broadcast","room-id":e,roomType:n,topic:r,data:s})}subscribeTopic(e,n,r){const s=this.joinRoom(e);return this._broadcastSubs[e]=this._broadcastSubs[e]||{},this._broadcastSubs[e][n]=this._broadcastSubs[e][n]||[],this._broadcastSubs[e][n].push(r),this._presence[e]=this._presence[e]||{},()=>{this._broadcastSubs[e][n]=this._broadcastSubs[e][n].filter(i=>i!==r),this._broadcastSubs[e][n].length||delete this._broadcastSubs[e][n],s()}}_notifyBroadcastSubs(e,n,r){var s,i,o;(o=(i=(s=this._broadcastSubs)==null?void 0:s[e])==null?void 0:i[n])==null||o.forEach(a=>{var f,l,d,h,p,b;const c=(f=r.data)==null?void 0:f.data,u=r.data["peer-id"]===this._sessionId?(d=(l=this._presence[e])==null?void 0:l.result)==null?void 0:d.user:(b=(p=(h=this._presence[e])==null?void 0:h.result)==null?void 0:p.peers)==null?void 0:b[r.data["peer-id"]];return a(c,u)})}async uploadFile(e,n,r){var o;const s=await this.getCurrentUser(),i=(o=s==null?void 0:s.user)==null?void 0:o.refresh_token;return bi({...r,apiURI:this.config.apiURI,appId:this.config.appId,path:e,file:n,refreshToken:i})}async deleteFile(e){var i;const n=await this.getCurrentUser(),r=(i=n==null?void 0:n.user)==null?void 0:i.refresh_token;return await Ti({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}async upload(e,n){var c;const r=await this.getCurrentUser(),s=(c=r==null?void 0:r.user)==null?void 0:c.refresh_token,i=e||n.name,o=await gi({apiURI:this.config.apiURI,appId:this.config.appId,fileName:i,refreshToken:s});return await wi(o,n)}async getDownloadUrl(e){var i;const n=await this.getCurrentUser(),r=(i=n==null?void 0:n.user)==null?void 0:i.refresh_token;return await _i({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}}function Hi(t,e){return new Ie(Vn(t,e),e,void 0)}function Ji(t){return new Me(t,{})}function Yi(){return new j("string",!0,!1)}function Zi(){return new j("number",!0,!1)}function Xi(){return new j("boolean",!0,!1)}function eo(){return new j("date",!0,!1)}function to(){return new j("json",!0,!1)}function no(){return new j("json",!0,!1)}function Vn(t,e){var s,i,o,a;const n={fwd:{},rev:{}};for(const c of Object.values(e))(s=n.fwd)[i=c.forward.on]||(s[i]={}),(o=n.rev)[a=c.reverse.on]||(o[a]={}),n.fwd[c.forward.on][c.forward.label]={entityName:c.reverse.on,cardinality:c.forward.has},n.rev[c.reverse.on][c.reverse.label]={entityName:c.forward.on,cardinality:c.reverse.has};return Object.fromEntries(Object.entries(t).map(([c,u])=>[c,new Me(u.attrs,{...n.fwd[c],...n.rev[c]})]))}function ro({entities:t,links:e,rooms:n}){const r=e??{},s=n??{};return new Ie(Vn(t,r),r,s)}const so={graph:Hi,schema:ro,entity:Ji,string:Yi,number:Zi,boolean:Xi,date:eo,json:to,any:no};let Pe;function io(t,e){Pe==null||Pe.dispose();const n=lo(e),r=co(e,a),s=ao(oo(t));function i(f){var l;f.source===s.element.contentWindow&&((l=f.data)==null?void 0:l.type)==="close"&&n.isVisible()&&a()}function o(f){const l=f.shiftKey&&f.ctrlKey&&f.key==="0",d=f.key==="Escape"||f.key==="Esc";(l||d&&n.isVisible())&&a()}function a(){n.isVisible()?n.element.style.display="none":(n.element.style.display="block",n.element.contains(s.element)||n.element.appendChild(s.element))}function c(){n.element.remove(),r.element.remove(),removeEventListener("keydown",o),removeEventListener("message",i)}function u(){document.body.appendChild(n.element),document.body.appendChild(r.element),addEventListener("keydown",o),addEventListener("message",i),Pe={dispose:c}}return u()}function oo(t){return`${lt||wn?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${t}`}function ao(t){const e=document.createElement("iframe");return e.src=t,e.className="instant-devtool-iframe",Object.assign(e.style,{width:"100%",height:"100%",backgroundColor:"white",border:"none"}),{element:e}}function co(t,e){const n=`
|
|
3
3
|
<svg width="32" height="32" viewBox="0 0 512 512" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
4
4
|
<rect width="512" height="512" fill="black"/>
|
|
5
5
|
<rect x="97.0973" y="91.3297" width="140" height="330" fill="white"/>
|
|
6
6
|
</svg>
|
|
7
|
-
`,r=document.createElement("button");return r.innerHTML=n,r.className="instant-devtool-toggler",Object.assign(r.style,{position:"fixed",...
|
|
7
|
+
`,r=document.createElement("button");return r.innerHTML=n,r.className="instant-devtool-toggler",Object.assign(r.style,{position:"fixed",...uo(t.position),height:"32px",width:"32px",display:"flex",alignItems:"center",justifyContent:"center",zIndex:"9010",padding:"0",margin:"0",border:"none",cursor:"pointer"}),r.addEventListener("click",e),{element:r}}function uo(t){switch(t){case"bottom-left":return{bottom:"24px",left:"24px"};case"bottom-right":return{bottom:"24px",right:"24px"};case"top-right":return{top:"24px",right:"24px"};case"top-left":return{top:"24px",left:"24px"}}}function fo(t){switch(t){case"bottom-left":return{bottom:"24px",right:"24px",left:"60px",top:"72px"};case"bottom-right":return{bottom:"24px",left:"24px",right:"60px",top:"72px"};case"top-right":return{top:"24px",left:"24px",right:"60px",bottom:"72px"};case"top-left":return{top:"24px",right:"24px",left:"60px",bottom:"72px"}}}function lo(t){const e=document.createElement("div");Object.assign(e.style,{position:"fixed",...fo(t.position),display:"block",borderRadius:"4px",border:"1px #ccc solid",boxShadow:"0px 0px 8px #00000044",backgroundColor:"#eee",zIndex:"999990"}),e.style.display="none",e.className="instant-devtool-container";function n(){return e.style.display!=="none"}return{element:e,isVisible:n}}const ho={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"};function po(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function yo(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}function _t(t){const e=t.__adminToken;return t.appId+"_"+(t.websocketURI||"default_ws_uri")+"_"+(t.apiURI||"default_api_uri")+"_"+(e||"client_only")+"_"+t.useDateObjects}const St=yo(),mt=po();class qn{constructor(e){this.db=e,this.sendMagicCode=n=>this.db.sendMagicCode(n),this.signInWithMagicCode=n=>this.db.signInWithMagicCode(n),this.signInWithToken=n=>this.db.signInWithCustomToken(n),this.signInAsGuest=()=>this.db.signInAsGuest(),this.createAuthorizationURL=n=>this.db.createAuthorizationURL(n),this.signInWithIdToken=n=>this.db.signInWithIdToken(n),this.exchangeOAuthCode=n=>this.db.exchangeCodeForToken(n),this.issuerURI=()=>this.db.issuerURI(),this.signOut=(n={invalidateToken:!0})=>this.db.signOut(n)}}class zn{constructor(e){this.db=e,this.uploadFile=(n,r,s={})=>this.db.uploadFile(n,r,s),this.delete=n=>this.db.deleteFile(n),this.upload=(n,r)=>this.db.upload(n,r),this.put=this.upload,this.getDownloadUrl=n=>this.db.getDownloadUrl(n)}}function bo(t){return JSON.parse(JSON.stringify(t))}class Wn{constructor(e){this.tx=st(),this._reactor=e,this.auth=new qn(this._reactor),this.storage=new zn(this._reactor)}transact(e){return this._reactor.pushTx(e)}getLocalId(e){return this._reactor.getLocalId(e)}subscribeQuery(e,n,r){return this._reactor.subscribeQuery(e,n,r)}subscribeAuth(e){return this._reactor.subscribeAuth(e)}getAuth(){return this._reactor.getAuth()}subscribeConnectionStatus(e){return this._reactor.subscribeConnectionStatus(e)}joinRoom(e="_defaultRoomType",n="_defaultRoomId",r){return{leaveRoom:this._reactor.joinRoom(n,r==null?void 0:r.initialPresence),subscribeTopic:(i,o)=>this._reactor.subscribeTopic(n,i,o),subscribePresence:(i,o)=>this._reactor.subscribePresence(e,n,i,o),publishTopic:(i,o)=>this._reactor.publishTopic({roomType:e,roomId:n,topic:i,data:o}),publishPresence:i=>this._reactor.publishPresence(e,n,i),getPresence:i=>this._reactor.getPresence(e,n,i)}}shutdown(){delete St[_t(this._reactor.config)],this._reactor.shutdown()}queryOnce(e,n){return this._reactor.queryOnce(e,n)}_syncTableExperimental(e,n){return this._reactor.subscribeTable(e,n)}}function Kn(t){if(!t)return"0";if(mt.get(t))return mt.get(t);const e=A(t);return mt.set(t,e),e}function To(t,e){return Kn(t._reactor.config.schema)!==Kn(e)}function Qn(t,e,n,r,s){const i=St[_t(t)];if(i)return To(i,t.schema)&&i._reactor.updateSchema(t.schema),i;const o=new Gi({...ho,...t,cardinalityInference:!!t.schema},e||ut,n||ft,{...r||{},"@instantdb/core":ht},s),a=new Wn(o);return St[_t(t)]=a,go(t.appId,t.devtool),a}function go(t,e){if(typeof window>"u"||typeof window.location>"u"||typeof document>"u"||typeof e=="boolean"&&!e)return;const n={position:"bottom-right",allowedHosts:["localhost"],...typeof e=="object"?e:{}};n.allowedHosts.includes(window.location.hostname)&&io(t,n)}const wo=Qn;m.Auth=qn,m.IndexedDBStorage=ut,m.InstantAPIError=be,m.InstantCoreDatabase=Wn,m.InstantError=ie,m.QueryValidationError=k,m.Storage=zn,m.SyncTableCallbackEventType=Ln,m.TransactionValidationError=N,m.WindowNetworkListener=ft,m.coerceQuery=bo,m.coerceToDate=de,m.getOps=hn,m.i=so,m.id=M,m.init=Qn,m.init_experimental=wo,m.lookup=Us,m.tx=Ls,m.txInit=st,m.validateQuery=pt,m.validateTransactions=jn,m.version=ht,m.weakHash=A,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})});
|