(function(M,P){typeof exports=="object"&&typeof module<"u"?P(exports):typeof define=="function"&&define.amd?define(["exports"],P):(M=typeof globalThis<"u"?globalThis:M||self,P(M.instant={}))})(this,function(M){"use strict";var $i=Object.defineProperty;var Ni=(M,P,v)=>P in M?$i(M,P,{enumerable:!0,configurable:!0,writable:!0,value:v}):M[P]=v;var y=(M,P,v)=>Ni(M,typeof P!="symbol"?P+"":P,v);function P(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>>0;return e.toString(16)}if(Array.isArray(t)){let e=2166136261;for(let n=0;n>>0}return e.toString(16)}if(typeof t=="object"){let e=2166136261;const n=Object.keys(t).sort();for(let r=0;r>>0;const o=P(t[s]);e^=parseInt(o,16),e*=16777619,e=e>>>0}return e.toString(16)}return P(String(t))}const v={Remove:"remove",Replace:"replace",Add:"add"},_t=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Tn=Symbol("__MUTATIVE_RAW_RETURN_SYMBOL__"),de=Symbol.iterator,$={mutable:"mutable",immutable:"immutable"},Ce={};function se(t,e){return t instanceof Map?t.has(e):Object.prototype.hasOwnProperty.call(t,e)}function bt(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 ke(t){return Object.getPrototypeOf(t)===Set.prototype}function Te(t){return Object.getPrototypeOf(t)===Map.prototype}function N(t){var e;return(e=t.copy)!==null&&e!==void 0?e:t.original}function G(t){return!!m(t)}function m(t){return typeof t!="object"?null:t==null?void 0:t[_t]}function Ie(t){var e;const n=m(t);return n?(e=n.copy)!==null&&e!==void 0?e:n.original:t}function L(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,$))===$.immutable||typeof n=="function")}function wt(t,e=[]){if(Object.hasOwnProperty.call(t,"key")){const n=t.parent.copy,r=m(Q(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||se(n,i)))return null;e.push(i)}if(t.parent)return wt(t.parent,e);e.reverse();try{In(t.copy,e)}catch{return null}return e}function Y(t){return Array.isArray(t)?1:t instanceof Map?2:t instanceof Set?3:0}function Q(t,e){return Y(t)===2?t.get(e):t[e]}function ie(t,e,n){Y(t)===2?t.set(e,n):t[e]=n}function Ee(t,e){const n=m(t);return(n?N(n):t)[e]}function B(t,e){return t===e?t!==0||1/t===1/e:t!==t&&e!==e}function je(t){if(t)for(;t.finalities.revoke.length>0;)t.finalities.revoke.pop()()}function X(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 In(t,e){for(let n=0;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 jn=Object.prototype.propertyIsEnumerable;function gt(t,e){let n;if(Array.isArray(t))return Array.prototype.concat.call(t);if(t instanceof Set){if(!ke(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(!Te(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,$),n!==void 0)&&n!==$.mutable){if(n===$.immutable)return En(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=>{jn.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 E(t){t.copy||(t.copy=gt(t.original,t.options))}function oe(t){if(!L(t))return Ie(t);if(Array.isArray(t))return t.map(oe);if(t instanceof Map){const n=Array.from(t.entries()).map(([r,s])=>[r,oe(s)]);if(!Te(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(oe);if(!ke(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]=oe(t[n]);return e}function he(t){return G(t)?oe(t):t}function z(t){var e;t.assignedMap=(e=t.assignedMap)!==null&&e!==void 0?e:new Map,t.operated||(t.operated=!0,t.parent&&z(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)||G(t)){r.pop(),s.pop();return}switch(Y(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 Re(t,e){const n=Y(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 St(t,e,n){if(G(t)||!L(t,n)||e.has(t)||Object.isFrozen(t))return;const r=t instanceof Set,s=r?new Map:void 0;if(e.add(t),Re(t,(i,o)=>{var a;if(G(o)){const c=m(o);E(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;ie(r?s:t,i,u)}else St(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 Rn(t,e){const n=t.type===3?t.setMap:t.copy;t.finalities.revoke.length>1&&t.assignedMap.get(e)&&n&&St(Q(n,e),t.finalities.handledSet,t.options)}function xe(t){t.type===3&&t.copy&&(t.copy.clear(),t.setMap.forEach(e=>{t.copy.add(Ie(e))}))}function De(t,e,n,r){if(t.operated&&t.assignedMap&&t.assignedMap.size>0&&!t.finalized){if(n&&r){const i=wt(t);i&&e(t,i,n,r)}t.finalized=!0}}function Ue(t,e,n,r){const s=m(n);s&&(s.callbacks||(s.callbacks=[]),s.callbacks.push((i,o)=>{var a;const c=t.type===3?t.setMap:t.copy;if(B(Q(c,e),n)){let u=s.original;s.copy&&(u=s.copy),xe(t),De(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)),ie(c,e,u)}}),t.options.enableAutoFreeze&&s.finalities!==t.finalities&&(t.options.enableAutoFreeze=!1)),L(n,t.options)&&t.finalities.draft.push(()=>{const i=t.type===3?t.setMap:t.copy;B(Q(i,e),n)&&Rn(t,e)})}function xn(t,e,n,r,s){let{original:i,assignedMap:o,options:a}=t,c=t.copy;c.length{const u=Q(t,c),f=he(Q(e,c)),l=a?se(t,c)?v.Replace:v.Add:v.Remove;if(B(u,f)&&l===v.Replace)return;const d=r.concat(c),h=X(d,o);s.push(l===v.Remove?{op:l,path:h}:{op:l,path:h,value:f}),i.push(l===v.Add?{op:v.Remove,path:h}:l===v.Remove?{op:v.Add,path:h,value:u}:{op:v.Replace,path:h,value:u})})}function Un({original:t,copy:e},n,r,s,i){let o=0;t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=X(c,i);r.push({op:v.Remove,path:u,value:a}),s.unshift({op:v.Add,path:u,value:a})}o+=1}),o=0,e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=X(c,i);r.push({op:v.Add,path:u,value:a}),s.unshift({op:v.Remove,path:u,value:a})}o+=1})}function ae(t,e,n,r){const{pathAsArray:s=!0}=t.options.enablePatches;switch(t.type){case 0:case 2:return Dn(t,e,n,r,s);case 1:return xn(t,e,n,r,s);case 3:return Un(t,e,n,r,s)}}const pe=(t,e,n=!1)=>{if(typeof t=="object"&&t!==null&&(!L(t,e)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},$e={get size(){return N(m(this)).size},has(t){return N(m(this)).has(t)},set(t,e){const n=m(this),r=N(n);return(!r.has(t)||!B(r.get(t),e))&&(E(n),z(n),n.assignedMap.set(t,!0),n.copy.set(t,e),Ue(n,t,e,ae)),this},delete(t){if(!this.has(t))return!1;const e=m(this);return E(e),z(e),e.original.has(t)?e.assignedMap.set(t,!1):e.assignedMap.delete(t),e.copy.delete(t),!0},clear(){const t=m(this);if(this.size){E(t),z(t),t.assignedMap=new Map;for(const[e]of t.original)t.assignedMap.set(e,!1);t.copy.clear()}},forEach(t,e){const n=m(this);N(n).forEach((r,s)=>{t.call(e,this.get(s),s,this)})},get(t){var e,n;const r=m(this),s=N(r).get(t),i=((n=(e=r.options).mark)===null||n===void 0?void 0:n.call(e,s,$))===$.mutable;if(r.options.strict&&pe(s,r.options,i),i||r.finalized||!L(s,r.options)||s!==r.original.get(t))return s;const o=Ce.createDraft({original:s,parentDraft:r,key:t,finalities:r.finalities,options:r.options});return E(r),r.copy.set(t,o),o},keys(){return N(m(this)).keys()},values(){const t=this.keys();return{[de]:()=>this.values(),next:()=>{const e=t.next();return e.done?e:{done:!1,value:this.get(e.value)}}}},entries(){const t=this.keys();return{[de]:()=>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]}}}},[de](){return this.entries()}},$n=Reflect.ownKeys($e),Ot=(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=m(a),u=((s=(r=t.options).mark)===null||s===void 0?void 0:s.call(r,a,$))===$.mutable;if(t.options.strict&&pe(o,t.options,u),!u&&!c&&L(o,t.options)&&!t.finalized&&t.original.has(o)){const f=Ce.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]}},ye={get size(){return m(this).setMap.size},has(t){const e=m(this);if(e.setMap.has(t))return!0;E(e);const n=m(t);return!!(n&&e.setMap.has(n.original))},add(t){const e=m(this);return this.has(t)||(E(e),z(e),e.assignedMap.set(t,!0),e.setMap.set(t,t),Ue(e,t,t,ae)),this},delete(t){if(!this.has(t))return!1;const e=m(this);E(e),z(e);const n=m(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=m(this);E(t),z(t);for(const e of t.original)t.assignedMap.set(e,!1);t.setMap.clear()},values(){const t=m(this);E(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Ot(t,e,{isValuesIterator:!0})}},entries(){const t=m(this);E(t);const e=t.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Ot(t,e,{isValuesIterator:!1})}},keys(){return this.values()},[de](){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(ye,{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 Nn=Reflect.ownKeys(ye),Mt=new WeakSet,Pt={get(t,e,n){var r,s;const i=(r=t.copy)===null||r===void 0?void 0:r[e];if(i&&Mt.has(i))return i;if(e===_t)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,$),o===$.mutable)return t.options.strict&&pe(u,t.options,!0),u}const a=N(t);if(a instanceof Map&&$n.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(a instanceof Set&&Nn.includes(e)){if(e==="size")return Object.getOwnPropertyDescriptor(ye,"size").get.call(t.proxy);const u=ye[e];if(u)return u.bind(t.proxy)}if(!se(a,e)){const u=bt(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&&pe(c,t.options),t.finalized||!L(c,t.options))return c;if(c===Ee(t.original,e)){if(E(t),t.copy[e]=Ne({original:t.original[e],parentDraft:t,key:t.type===1?Number(e):e,finalities:t.finalities,options:t.options}),typeof o=="function"){const u=m(t.copy[e]);return E(u),z(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=bt(N(t),e);if(i!=null&&i.set)return i.set.call(t.proxy,n),!0;const o=Ee(N(t),e),a=m(o);return a&&B(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):(B(n,o)&&(n!==void 0||se(t.original,e))||(E(t),z(t),se(t.original,e)&&B(n,t.original[e])?t.assignedMap.delete(e):t.assignedMap.set(e,!0),t.copy[e]=n,Ue(t,e,n,ae)),!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?Pt.set.call(this,t,e,void 0,t.proxy):(Ee(t.original,e)!==void 0||e in t.original?(E(t),z(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 Ne(t){const{original:e,parentDraft:n,key:r,finalities:s,options:i}=t,o=Y(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,Pt);if(s.revoke.push(u),Mt.add(c),a.proxy=c,n){const f=n;f.finalities.draft.push((l,d)=>{var h,p;const b=m(c);let w=f.type===3?f.setMap:f.copy;const _=Q(w,r),g=m(_);if(g){let O=g.original;g.operated&&(O=Ie(_)),xe(g),De(g,ae,l,d),f.options.enableAutoFreeze&&(f.options.updatedValues=(h=f.options.updatedValues)!==null&&h!==void 0?h:new WeakMap,f.options.updatedValues.set(O,g.original)),ie(w,r,O)}(p=b.callbacks)===null||p===void 0||p.forEach(O=>{O(l,d)})})}else{const f=m(c);f.finalities.draft.push((l,d)=>{xe(f),De(f,ae,l,d)})}return c}Ce.createDraft=Ne;function Ln(t,e,n,r,s){var i;const o=m(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&&je(o),s&&ee(u,u,o==null?void 0:o.options.updatedValues),[u,n&&c?[{op:v.Replace,path:[],value:e[0]}]:n,r&&c?[{op:v.Replace,path:[],value:a}]:r]}function qn(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,$))===$.mutable||!L(t,e)?t:Ne({original:t,parentDraft:null,finalities:r,options:e});return[a,(c=[])=>{const[u,f,l]=Ln(a,c,s,i,e.enableAutoFreeze);return e.enablePatches?[u,f,l]:u}]}function Le(t){const{rootDraft:e,value:n,useRawReturn:r=!1,isRoot:s=!0}=t;Re(n,(i,o,a)=>{const c=m(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 ie(a,i,u)}else typeof o=="object"&&o!==null&&(t.value=o,t.isRoot=!1,Le(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 vt(t){var e;const n=m(t);if(!L(t,n==null?void 0:n.options))return t;const r=Y(t);if(n&&!n.operated)return n.original;let s;function i(){s=r===2?Te(t)?new Map(t):new(Object.getPrototypeOf(t)).constructor(t):r===3?Array.from(n.setMap.values()):gt(t,n==null?void 0:n.options)}if(n){n.finalized=!0;try{i()}finally{n.finalized=!1}}else s=t;if(Re(s,(o,a)=>{if(n&&B(Q(n.original,o),a))return;const c=vt(a);c!==a&&(s===t&&i(),ie(s,o,c))}),r===3){const o=(e=n==null?void 0:n.original)!==null&&e!==void 0?e:s;return ke(o)?new Set(s):new(Object.getPrototypeOf(o)).constructor(s)}return s}function At(t){if(!G(t))throw new Error(`current() is only used for Draft, parameter: ${t}`);return vt(t)}const qe=(t=>function e(n,r,s){var i,o,a;if(typeof n=="function"&&typeof r!="function")return function(S,...R){return e(S,I=>n.call(this,I,...R),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=G(c)?At(c):c,d=Array.isArray(f.mark)?(S,R)=>{for(const I of f.mark){if(typeof I!="function")throw new Error(`Invalid mark: ${I}, 'mark' should be a function.`);const W=I(S,R);if(W)return W}}: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(!L(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[_,g]=qn(l,w);if(typeof r!="function"){if(!L(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[_,g]}let O;try{O=u(_)}catch(S){throw je(m(_)),S}const j=S=>{const R=m(_);if(!G(S)){if(S!==void 0&&!B(S,_)&&(R!=null&&R.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 W=S==null?void 0:S[Tn];if(W){const mn=W[0];return w.strict&&typeof S=="object"&&S!==null&&Le({rootDraft:R,value:S,useRawReturn:!0}),g([mn])}if(S!==void 0)return typeof S=="object"&&S!==null&&Le({rootDraft:R,value:S}),g([S])}if(S===_||S===void 0)return g([]);const I=m(S);if(w===I.options){if(I.operated)throw new Error("Cannot return a modified child draft.");return g([At(S)])}return g([S])};return O instanceof Promise?O.then(j,S=>{throw je(m(_)),S}):j(O)})();Object.prototype.constructor.toString();function Ct(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 kt(t,e){return Object.keys(t).length===Object.keys(e).length&&Object.keys(t).every(n=>e.hasOwnProperty(n)&&t[n]===e[n])}function _e(t,e){return typeof t!="object"||typeof e!="object"||t===null||e===null?t===e:Ct(t,e)?Object.keys(t).every(n=>_e(t[n],e[n])):!1}function Fe(t){if(!ce(t))return t;const e={};for(const[n,r]of Object.entries(t))r!==void 0&&(e[n]=r);return e}function Tt(t,e){if(!ce(t)||!ce(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=ce(t[r])&&ce(e[r]);n[r]=s?Tt(t[r],e[r]):e[r]}return n}function ce(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fn(t,e,n){if(!t||e.length===0)return;let r=t||{};for(let i=0;in&&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 x(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)),x(i,s,n)}function Rt(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=ue(t,c);if(!l){console.warn("no such attr",a,t);continue}l["checked-data-type"]==="date"&&n&&(u=be(u),o[2]=u),ze(l)&&x(i,[u,c,a],o),x(r,[a,c,u],o),x(s,[c,a,u],o)}return{eav:r,aev:s,vae:i}}function xt(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(x(r,[c,u],i),Ve(i)&&x(e,[c,u],i),i["primary?"]&&x(n,[c],i),f){const[l,d,h]=f;x(s,[d,h],i)}}return{blobAttrs:e,primaryKeys:n,forwardIdents:r,revIdents:s}}function tr(t){return{__type:t.__type,attrs:t.attrs,triples:D(t.eav,3),cardinalityInference:t.cardinalityInference,linkIndex:t.linkIndex,useDateObjects:t.useDateObjects}}function nr(t){return Qe(t.attrs,t.triples,t.cardinalityInference,t.linkIndex,t.useDateObjects)}function We(t){t.attrIndexes=xt(t.attrs)}function Qe(t,e,n,r,s){const i=Rt(t,e,s);return i.useDateObjects=s,i.attrs=t,i.attrIndexes=xt(t),i.cardinalityInference=n,i.linkIndex=r,i.__type="store",i}function fe(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=D(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=D(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 rr(t,e){const n=fe(t,e);if(!n)return;const[r,s,i]=n,o=ue(t.attrs,s);o&&(q(t.eav,[r,s,i]),q(t.aev,[s,r,i]),ze(o)&&q(t.vae,[i,s,r]))}let sr=0;function Dt(t,e,n){const[r,s,i]=n;let o;const a=we(t.ea,[r,s,i]);return a&&(o=a[3]),o||Date.now()*10+sr++}function ir(t,e){const n=fe(t,e);if(!n)return;let[r,s,i]=n;const o=ue(t.attrs,s);if(!o)return;o["checked-data-type"]==="date"&&t.useDateObjects&&(i=be(i));const a=we(t.eav,[r,s,i]),c=(a==null?void 0:a[3])??Dt(t,o,n),u=[r,s,i,c];er(o)?(x(t.eav,[r,s],new Map([[i,u]])),x(t.aev,[s,r],new Map([[i,u]]))):(x(t.eav,[r,s,i],u),x(t.aev,[s,r,i],u)),ze(o)&&x(t.vae,[i,s,r],u)}function or(t,e){var d;const n=fe(t,e);if(!n)return;const[r,s,i]=n,o=ue(t.attrs,s);if(!o)return;if(!Ve(o))throw new Error("merge operation is not supported for links");const a=we(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=Tt(u,i),l=[r,s,f,Dt(t,o,c)];x(t.eav,[r,s],new Map([[f,l]]))}function Be(t,e){var c,u;const[n,r]=e,s=fe(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"&&D(o.get(f),1).forEach(([d,h,p])=>{var b;return Be(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)&&D(t.vae.get(i),2);a&&a.forEach(f=>{var b,w,_;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"&&((w=p["reverse-identity"])==null?void 0:w[1])===r&&Be(t,[l,(_=p["forward-identity"])==null?void 0:_[1]])}),((u=t.vae.get(i))==null?void 0:u.size)===0&&q(t.vae,[i])}function Ut(t,e){const n=Rt(t.attrs,e,t.useDateObjects);Object.keys(n).forEach(r=>{t[r]=n[r]})}function ar(t,[e]){t.attrs[e.id]=e,We(t)}function $t(t){return D(t.eav,3)}function cr(t,[e]){if(!t.attrs[e])return;const n=$t(t).filter(([r,s])=>s!==e);delete t.attrs[e],We(t),Ut(t,n)}function ur(t,[e]){const n=t.attrs[e.id];n&&(t.attrs[e.id]={...n,...e},We(t),Ut(t,$t(t)))}function fr(t,e){const[n,...r]=e;switch(n){case"add-triple":ir(t,r);break;case"deep-merge-triple":or(t,r);break;case"retract-triple":rr(t,r);break;case"delete-entity":Be(t,r);break;case"add-attr":ar(t,r);break;case"delete-attr":cr(t,r);break;case"update-attr":ur(t,r);break;case"rule-params":break;default:throw new Error(`unhandled transaction action: ${n}`)}}function D(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())D(r,e-1,n);return n}function ge(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 D(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 lr(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(lr(e,n,r)){case"e":{const a=t.eav.get(e);return D(a,2)}case"ea":{const a=(i=t.eav.get(e))==null?void 0:i.get(n);return D(a,1)}case"eav":{const a=(o=t.eav.get(e))==null?void 0:o.get(n);return a?ge(t,a,r):[]}case"ev":{const a=t.eav.get(e);if(!a)return[];const c=[];for(const u of a.values())c.push(...ge(t,u,r));return c}case"a":{const a=t.aev.get(n);return D(a,2)}case"av":{const a=t.aev.get(n);if(!a)return[];const c=[];for(const u of a.values())c.push(...ge(t,u,r));return c}case"v":{const a=[];for(const c of t.eav.values())for(const u of c.values())a.push(...ge(t,u,r));return a}default:return D(t.eav,3)}}function hr(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=D(a,1);for(const u of c)r[i]=u[2]}return r}function te(t,e,n){var r;return(r=t.attrIndexes.forwardIdents.get(e))==null?void 0:r.get(n)}function Nt(t,e,n){var r;return(r=t.attrIndexes.revIdents.get(e))==null?void 0:r.get(n)}function pr(t,e){return t.attrIndexes.blobAttrs.get(e)}function yr(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 _r(t,e){const n=fe(t,e);if(!n)return;const[r,s,i]=n;if(ue(t.attrs,s))return we(t.eav,[r,s])}function br(t,e){const n=e.filter(([r,...s])=>{var a;if(r!=="add-triple"&&r!=="deep-merge-triple")return!0;const i=(a=s[3])==null?void 0:a.mode;if(i!=="create"&&i!=="update")return!0;const o=_r(t,s);return!(i==="create"&&o||i==="update"&&!o)});return qe(t,r=>{n.forEach(s=>{fr(r,s)})})}function wr(t){return typeof t=="string"&&t.startsWith("?")}function gr(t,e,n){if(n.hasOwnProperty(t)){const r=n[t];return qt(r,e,n)}return{...n,[t]:e}}function Lt(t,e,n){return t===e?n:null}function mr(t){switch(typeof t){case"string":return t.startsWith("?")?gr:Lt;default:return Lt}}const Sr=["in","$in","$not","$isNull","$comparator"];function Or(t){for(const e of Sr)if(t.hasOwnProperty(e))return!0;return!1}function qt(t,e,n){return n?typeof t=="object"?Or(t)?n:null:mr(t)(t,e,n):null}function Mr(t,e,n){return t.reduce((r,s,i)=>{const o=e[i];return qt(s,o,r)},n)}function Pr(t,e,n){return Cr(t,e,n).map(r=>Mr(e,r,n)).filter(r=>r)}function vr(t,e,n){return e.or?e.or.patterns.flatMap(r=>Je(t,r,n)):e.and?e.and.patterns.reduce((r,s)=>Je(t,s,r),n):n.flatMap(r=>Pr(t,e,r))}function Je(t,e,n=[{}]){return e.reduce((r,s)=>vr(t,s,r),n)}function He(t,e){return Array.isArray(e)?e.map(n=>He(t,n)):wr(e)?t[e]:e}function Ar(t,{find:e,where:n}){return Je(t,n).map(s=>He(s,e))}function Cr(t,e,n){return dr(t,He(n,e))}const C=[];for(let t=0;t<256;++t)C.push((t+256).toString(16).slice(1));function kr(t,e=0){return(C[t[e+0]]+C[t[e+1]]+C[t[e+2]]+C[t[e+3]]+"-"+C[t[e+4]]+C[t[e+5]]+"-"+C[t[e+6]]+C[t[e+7]]+"-"+C[t[e+8]]+C[t[e+9]]+"-"+C[t[e+10]]+C[t[e+11]]+C[t[e+12]]+C[t[e+13]]+C[t[e+14]]+C[t[e+15]]).toLowerCase()}let Ke;const Tr=new Uint8Array(16);function Ir(){if(!Ke){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ke=crypto.getRandomValues.bind(crypto)}return Ke(Tr)}const Ft={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Er(t,e,n){var s;if(Ft.randomUUID&&!t)return Ft.randomUUID();t=t||{};const r=t.random??((s=t.rng)==null?void 0:s.call(t))??Ir();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,kr(r)}function zt(t){const e=t.replace(/-/g,""),n=[];for(let r=0;re[n])return 1}return 0}function Rr(t,e){return jr(zt(t),zt(e))}function k(){return Er()}let xr=0;function le(t){return me(`_${t}`,xr++)}function me(t,e){return`?${t}-${e}`}class ne extends Error{constructor(e){super(e),this.name="AttrNotFoundError"}}function Dr(t,e){const n=yr(t,e);if(!n)throw new ne(`Could not find id attr for ${e}`);return n}function Vt(t,e,n,r){return[Ur(t,e,n,r)]}function Ur(t,e,n,r){return[t(n,r),Dr(e,n).id,t(n,r),t("time",r)]}function $r(t,e,n){return t.map(r=>r===e?n:r)}function Wt(t,e,n,r,s){const i=te(e,n,s),o=Nt(e,n,s),a=i||o;if(!a)throw new ne(`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),le("time")]:[t(u,d),a.id,t(l,r),le("time")];return[i?l:u,d,h,a,!!i]}function Qt(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 Nr(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]){const[f,l,d]=c,[h,p,b]=Wt(t,e,f,l,u);return[h,p,[...d,b]]},[n,r,[]]);return[i,o,a]}function Ge(t,e,n,r,s,i){const o=s.slice(0,s.length-1),a=s[s.length-1],[c,u,f]=qr(t,e,n,r,o),l=Lr(t,e,c,u,a,i);return f.concat([l])}function Fr(t,e){return e?[e].concat(t):t}function zr([t,e]){return t==="or"&&Array.isArray(e)}function Vr([t,e]){return t==="and"&&Array.isArray(e)}function Wr(t,e,n){return(r,s)=>{const i=t(r,s);return e==i?i:`${i}-${n}`}}function Bt(t,e,n,r,s,i){const o=t(r,s),a=i.map((c,u)=>{const f=Wr(t,o,u);return Ht(f,n,r,s,c)});return{[e]:{patterns:a,joinSym:o}}}function Qr(t){const e=[];for(let n=1;n<=t.length;n++)e.push(t.slice(0,n));return e}function Jt(t,e,n,r,s){return Qr(s).map(i=>Ge(t,e,n,r,i,{$isNull:!0}))}function Ht(t,e,n,r,s){return Object.entries(s).flatMap(([i,o])=>{if(zr([i,o]))return Bt(t,"or",e,n,r,o);if(Vr([i,o]))return Bt(t,"and",e,n,r,o);if(i==="$entityIdStartsWith")return[];const a=i.split(".");if(o!=null&&o.hasOwnProperty("$not")){const c=Ge(t,e,n,r,a,o),u=Jt(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:Jt(t,e,n,r,a),joinSym:t(n,r)}}]:Ge(t,e,n,r,a,o)})}function Br(t,e,n,r){const s=me;return r?Ht(s,t,e,n,r).concat(Vt(s,t,e,n)):Vt(s,t,e,n)}function Jr(t,e,n){return[t(e,n),t("time",n)]}function Hr(t,e,n,r,s,i){const[o,a,c,u,f]=Wt(t,e,n,r,s),l=$r(c,t(n,r),i);return[o,a,l,u,f]}function Kr(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,w;const h=!!(e.cardinalityInference&&((w=(b=(p=e.linkIndex)==null?void 0:p[n])==null?void 0:b[d])!=null&&w.isSingular));try{const[_,g,O]=Hr(t,e,n,r,d,c),j=Kt(e,{etype:_,level:g,form:s[d],join:O}),S=h?j[0]:j;return{[d]:S}}catch(_){if(_ instanceof ne)return{[d]:h?void 0:[]};throw _}}).reduce(function(d,h){return{...d,...h}},u)}):Object.values(i)}function Se([t,e],[n,r]){return e===r||e==null&&r==null?Rr(t,n):r==null?1:e==null?-1:e>r?1:-1}function Ye(t){return t==null?t:new Date(t).getTime()}function Gr(t,e,n,r){var h;const[s,i,o,a]=t,c=n==="desc"?1:-1;if(((h=e["forward-identity"])==null?void 0:h[2])==="id")return Se(r,[s,a])===c;const[u,f]=r,l=e["checked-data-type"]==="date"?Ye(f):f,d=e["checked-data-type"]==="date"?Ye(o):o;return Se([u,l],[s,d])===c}function Yr(t,e){const n=e[1];return t.attrs[n]}function Xr(t,e,n){const r=Object.keys(n)[0];return te(t,e,r)}function Zr(t,e,n,r){if(n)return Yr(t,n);if(r)return Xr(t,e,r)}function es(t,e,n){var s,i;if(!Array.isArray(n.fields))return pr(t,e);const r=new Map;for(const o of n.fields){const a=te(t,e,o),c=(s=a==null?void 0:a["forward-identity"])==null?void 0:s[2];c&&Ve(a)&&r.set(c,a)}if(!r.has("id")){const o=te(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 ts(t,e,n,r,s,i){var l;let o=Ar(t,i);const a=r==null?void 0:r["start-cursor"],c=Zr(t,e,a,s);if(c&&((l=c==null?void 0:c["forward-identity"])==null?void 0:l[2])!=="id"){const d=c["checked-data-type"]==="date",h=c.id;o=o.map(([p])=>{var w,_,g,O,j;let b=(j=(O=(g=(_=(w=t.eav.get(p))==null?void 0:w.get(h))==null?void 0:_.values())==null?void 0:g.next())==null?void 0:O.value)==null?void 0:j[2];return d&&(b=Ye(b)),[p,b]})}o.sort(n==="asc"?function(h,p){return Se(h,p)}:function(h,p){return Se(p,h)});let u={};const f=es(t,e,i);for(const d of o){const[h]=d;if(u[h]||a&&c&&Gr(a,c,n,d))continue;const p=hr(t,f,h);p&&(u[h]=p)}return u}function ns(t){var n;const e=(n=t.$)==null?void 0:n.order;return e&&e[Object.keys(e)[0]]||"asc"}function rs(t,{etype:e,level:n,form:r,join:s,pageInfo:i}){var b,w,_,g,O,j,S,R,I;const o=((b=r.$)==null?void 0:b.limit)||((w=r.$)==null?void 0:w.first)||((_=r.$)==null?void 0:_.last),a=(g=r.$)==null?void 0:g.offset,c=(O=r.$)==null?void 0:O.before,u=(j=r.$)==null?void 0:j.after,f=(S=r.$)==null?void 0:S.order,l=(R=r.$)==null?void 0:R.fields;if((a||c||u)&&(!i||!i["start-cursor"]))return[];const d=Fr(Br(t,e,n,(I=r.$)==null?void 0:I.where),s),h=Jr(me,e,n),p=ts(t,e,ns(r),i,f,{where:d,find:h,fields:l});if(o!=null){const W=Object.entries(p);return W.length<=o?p:Object.fromEntries(W.slice(0,o))}return p}function ss(t,e){try{return rs(t,e)}catch(n){if(n instanceof ne)return{};throw n}}function Kt(t,e){const n=ss(t,e);return Kr(me,t,e,n)}function is(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 os({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]=Kt(t,{etype:c,form:r[c],level:0,pageInfo:e==null?void 0:e[c]})),a},{})};return e&&(i.pageInfo=is(e)),n&&(i.aggregate=n),i}function as(){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 cs=as();function Xe(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(cs.has(i))return(o,a)=>Xe(t,e,[...n,a?[i,t,e,o,a]:[i,t,e,o]])}})}function us(t,e){return`lookup__${t}__${JSON.stringify(e)}`}function Ze(t){return t.startsWith("lookup__")}function Gt(t){const[e,n,...r]=t.split("__");return[n,JSON.parse(r.join("__"))]}function fs(t){return new Proxy({__etype:t},{get(e,n){if(n==="__etype")return t;const r=n;return Ze(r)?Xe(t,Gt(r),[]):Xe(t,r,[])}})}function et(){return new Proxy({},{get(t,e){return fs(e)}})}const ls=et();function Yt(t){return t.__ops}function ds(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 T(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 hs(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 tt(t,e,n){return n.indexOf(".")!==-1&&!T(t,e,n)}function nt(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 ps(t,e,n){if(!tt(t,e,n))return T(t,e,n);const r=nt(n),s=T(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 rt(t){return typeof t=="string"&&!Ze(t)?null:typeof t=="string"&&Ze(t)?Gt(t):hs(t)}function U(t,e,n){const r=rt(n);if(r===null)return n;const[s,i]=r,o=ps(t,e,s);if(!o||!o["unique?"])throw new Error(`${s} is not a unique attribute.`);return[o.id,i]}function Xt(t,e,n,r){const s=U(t,e,n);return Array.isArray(s)?[["add-triple",s,T(t,e,"id").id,s]].concat(r):r}function ys({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=T(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 Xt(t,e,n,s)}function _s({attrs:t},[e,n,r]){const s=Object.entries(r).flatMap(([i,o])=>{const a=Array.isArray(o)?o:[o],c=T(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 Xt(t,e,n,s)}function bs(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 D(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 Zt({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:bs(t,n,r)?{mode:"update"}:null}function ws(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Fe(i),c=U(n,r,s);return[["id",c]].concat(Object.entries(a)).map(([f,l])=>{const d=T(n,r,f);return d["checked-data-type"]==="date"&&t.useDateObjects&&(l=be(l)),["add-triple",c,d.id,l,{mode:"create"}]})}function gs(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Fe(i),c=U(n,r,s),u=Zt(t,[r,c,i,o]);return[["id",c]].concat(Object.entries(a)).map(([l,d])=>{const h=T(n,r,l);return h["checked-data-type"]==="date"&&t.useDateObjects&&(d=be(d)),["add-triple",c,h.id,d,...u?[u]:[]]})}function ms({attrs:t},[e,n]){return[["delete-entity",U(t,e,n),e]]}function Ss(t,e){const{attrs:n}=t,[r,s,i,o]=e,a=Fe(i),c=U(n,r,s),u=Zt(t,[r,c,i,o]),f=Object.entries(a).map(([d,h])=>{const p=T(n,r,d);return["deep-merge-triple",c,p.id,h,...u?[u]:[]]});return[["add-triple",c,T(n,r,"id").id,c,...u?[u]:[]]].concat(f)}function Os({attrs:t},[e,n,r]){return[["rule-params",U(t,e,n),e,r]]}function Ms(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 Ps(t,e){const[n,...r]=Ms(e);switch(n){case"merge":return Ss(t,r);case"create":return ws(t,r);case"update":return gs(t,r);case"link":return ys(t,r);case"unlink":return _s(t,r);case"delete":return ms(t,r);case"ruleParams":return Os(t,r);default:throw new Error(`unsupported action ${n}`)}}function vs(t){switch(t){case"string":case"date":case"boolean":case"number":return t;default:return}}function As(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=vs(r==null?void 0:r.valueType);return{"index?":i,"unique?":s,"checked-data-type":o}}function st(t,e,n,r){const s=t?As(t,e,n):null,i=k(),a=[k(),e,n];return{id:i,"forward-identity":a,"value-type":"blob",cardinality:"one","unique?":!1,"index?":!1,isUnsynced:!0,...s||{},...r||{}}}function Cs(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 ks(t,e,n){const r=Cs(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":[k(),s.on,s.label],"reverse-identity":[k(),i.on,i.label],cardinality:s.has==="one"?"one":"many","unique?":i.has==="one","on-delete":s.onDelete,"on-delete-reverse":i.onDelete}}function en(t,e,n,r){const s=t?ks(t,e,n):null,i=k(),o=[k(),e,n],a=[k(),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 Ts=new Set(["create","update","merge","link","unlink"]),Is=new Set(["link","unlink"]),Es=new Set(["create","update","merge"]),js=new Set(["link","unlink","create","update","merge","delete","ruleParams"]),it={"unique?":!0,"index?":!0},Rs={...it,cardinality:"one"};function xs(t){const e=[],[n,r,s,i]=t;if(!js.has(n))return e;const o=rt(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=rt(f);l&&e.push({etype:r,lookupPair:l,linkLabel:a})}}return e}function Ds({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=T(s,l,d),p=Z(s,l,d);a(h),a(p),!h&&!p&&o(en(e,l,d,Rs))}for(const l of n)for(const{etype:d,lookupPair:h,linkLabel:p}of xs(l)){const b=h[0];if(p){c(d,p);const w=T(s,d,p),_=Z(s,d,p);a(w),a(_);const g=((u=w==null?void 0:w["reverse-identity"])==null?void 0:u[1])||((f=_==null?void 0:_["forward-identity"])==null?void 0:f[1])||p;if(tt(s,g,b))c(g,nt(b));else{const O=T(s,g,b);O||o(st(e,g,b,it)),a(O)}}else if(tt(s,d,b))c(d,nt(b));else{const w=T(s,d,b);w||o(st(e,d,b,it)),a(w)}}for(const l of n){const[d,h,p,b]=l;if(Ts.has(d)){const w=Object.keys(b);w.push("id");for(const _ of w){const g=T(s,h,_);if(a(g),Es.has(d)&&(g||o(st(e,h,_,_==="id"?{"unique?":!0}:null))),Is.has(d)){const O=Z(s,h,_);!g&&!O&&o(en(e,h,_)),a(O)}}}}return[s,i]}function Us(t,e){const r=(Array.isArray(e)?e:[e]).flatMap(c=>Yt(c)),[s,i]=Ds(t,r),o={...t,attrs:s},a=r.flatMap(c=>Ps(o,c));return[...i,...a]}class ot{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=>{e(s.target.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 at{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 Oe extends Error{constructor(e){var s;const n=((s=e.body)==null?void 0:s.message)||`API Error (${e.status})`;super(n);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,Oe),this.name="InstantAPIError",this.status=e.status,this.body=e.body}get[Symbol.toStringTag](){return"InstantAPIError"}}async function V(t,e){const n=await fetch(t,e),r=await n.json();return n.status===200?Promise.resolve(r):Promise.reject(new Oe({status:n.status,body:r}))}function $s({apiURI:t,appId:e,email:n}){return V(`${t}/runtime/auth/send_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n})})}async function Ns({apiURI:t,appId:e,email:n,code:r}){return await V(`${t}/runtime/auth/verify_magic_code`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,email:n,code:r})})}async function Ls({apiURI:t,appId:e,refreshToken:n}){return await V(`${t}/runtime/auth/verify_refresh_token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":e,"refresh-token":n})})}async function tn({apiURI:t,appId:e,code:n,codeVerifier:r}){return await V(`${t}/runtime/oauth/token`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,code:n,code_verifier:r})})}async function qs({apiURI:t,appId:e,nonce:n,idToken:r,clientName:s,refreshToken:i}){return await V(`${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 Fs({apiURI:t,appId:e,refreshToken:n}){return await V(`${t}/runtime/signout`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e,refresh_token:n})})}async function zs({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 V(`${t}/storage/upload`,{method:"PUT",headers:a,body:r})}async function Vs({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await V(`${t}/storage/files?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"DELETE",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}async function Ws({apiURI:t,appId:e,fileName:n,refreshToken:r,metadata:s={}}){const{data:i}=await V(`${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 Qs(t,e){return(await fetch(t,{method:"PUT",body:e,headers:{"Content-Type":e.type}})).ok}async function Bs({apiURI:t,appId:e,path:n,refreshToken:r}){const{data:s}=await V(`${t}/storage/signed-download-url?app_id=${e}&filename=${encodeURIComponent(n)}`,{method:"GET",headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return s}let ct=!1,nn=!1,rn=!1;typeof window<"u"&&typeof window.localStorage<"u"&&(ct=!!window.localStorage.getItem("devBackend"),nn=!!window.localStorage.getItem("__instantLogging"),rn=!!window.localStorage.getItem("__devtoolLocalDash"));function sn(t,e){if(!e)return t;const n={};return e.forEach(r=>{n[r]=t[r]}),n}function Js(t,e,n){const r={peers:{}};if(e&&"user"in e?e.user:!0){const i=sn(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=sn(t.peers[i],e==null?void 0:e.keys);r.peers[i]={...c,peerId:i}}}return r}function Hs(t,e){if(t.isLoading!==e.isLoading||t.error!==e.error||(t.user||e.user)&&(!t.user||!e.user||!kt(t.user,e.user))||!Ct(t.peers,e.peers))return!0;for(const r of Object.keys(t.peers))if(!kt(t.peers[r],e.peers[r]))return!0;return!1}class on{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)}}class an{constructor(e,n,r,s,i=c=>JSON.stringify(c),o=c=>JSON.parse(c),a=100){y(this,"_subs",[]);this._persister=e,this._key=n,this._onMerge=s,this._loadedCbs=[],this._isLoading=!0,this.currentValue=r,this.toJSON=i,this.fromJSON=o,this._saveThrottleMs=a,this._pendingSaveCbs=[],this._version=0,this._load()}async _load(){const e=this.fromJSON(await this._persister.getItem(this._key));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.toJSON(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(()=>{this._nextSave=null,this._writeToStorage()},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 cn(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);cn(n["child-nodes"],e)})}function un(t){const e=[];return cn(t,e),e}function fn(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 ut="v0.20.16";function Ks(t){return{info:t?console.info.bind(console):()=>{},debug:t?console.debug.bind(console):()=>{},error:t?console.error.bind(console):()=>{}}}const J={CONNECTING:"connecting",OPENED:"opened",AUTHENTICATED:"authenticated",CLOSED:"closed",ERRORED:"errored"},Gs=3e4,Ys=3e4,Xs=0,ln=1,Zs={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"},ft="_instant_oauth_redirect",lt="currentUser";let ei=0;function ti(t){const e=new WebSocket(t);return e._id=ei++,e}function ni(){return typeof window<"u"||typeof chrome<"u"}const dn={"set-presence":!0,"set-presence-ok":!0,"refresh-presence":!0,"patch-presence":!0};function ri(t,e){var r;const n=JSON.parse(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=nr({...o,useDateObjects:e})}}return n}function si(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:tr(s.result.store)}),e[r]=i}return JSON.stringify(e)}function hn(t){return[...t].sort((e,n)=>{const[r,s]=e,[i,o]=n,a=s.order||0,c=o.order||0;return a==c?ri?1:0:a-c})}class ii{constructor(e,n=ot,r=at,s){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,"_ws");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,"_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=P(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&&(_e(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=>{try{const n=Us({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=k(),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 on;return this.mutationDeferredStore.set(r,a),this._sendMutation(r,o),this.notifyAll(),a.promise});y(this,"_wsOnOpen",e=>{const n=e.target;if(this._ws!==n){this._log.info("[socket][open]",n._id,"skip; this is no longer the current ws");return}this._log.info("[socket][open]",this._ws._id),this._setStatus(J.OPENED),this.getCurrentUser().then(r=>{var s;this._trySend(k(),{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,"_wsOnMessage",e=>{const n=e.target,r=JSON.parse(e.data.toString());if(this._ws!==n){this._log.info("[socket][message]",n._id,r,"skip; this is no longer the current ws");return}this._handleReceive(n._id,JSON.parse(e.data.toString()))});y(this,"_wsOnError",e=>{const n=e.target;if(this._ws!==n){this._log.info("[socket][error]",n._id,"skip; this is no longer the current ws");return}this._log.error("[socket][error]",n._id,e)});y(this,"_wsOnClose",e=>{const n=e.target;if(this._ws!==n){this._log.info("[socket][close]",n._id,"skip; this is no longer the current ws");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),setTimeout(()=>{if(this._reconnectTimeoutMs=Math.min(this._reconnectTimeoutMs+1e3,1e4),!this._isOnline){this._log.info("[socket][close]",n._id,"we are offline, no need to start socket");return}this._startSocket()},this._reconnectTimeoutMs)});this.config={...Zs,...e},this.queryCacheLimit=this.config.queryCacheLimit??10,this._log=Ks(e.verbose||ct||nn),this.versions={...s||{},"@instantdb/core":ut},this.config.schema&&(this._linkIndex=fn(this.config.schema)),ni()&&(typeof BroadcastChannel=="function"&&(this._broadcastChannel=new BroadcastChannel("@instantdb"),this._broadcastChannel.addEventListener("message",async i=>{var o;try{if(((o=i.data)==null?void 0:o.type)==="auth"){const a=await this.getCurrentUser();this.updateUser(a.user)}}catch(a){this._log.error("[error] handle broadcast channel",a)}})),this._oauthCallbackResponse=this._oauthLoginInit(),this._initStorage(n),this.getCurrentUser(),r.getIsOnline().then(i=>{this._isOnline=i,this._startSocket(),r.listen(o=>{o!==this._isOnline&&(this._log.info("[network] online =",o),this._isOnline=o,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?fn(this.config.schema):null}_initStorage(e){this._persister=new e(`instant_${this.config.appId}_5`),this.querySubs=new an(this._persister,"querySubs",{},this._onMergeQuerySubs,si,n=>ri(n,this.config.useDateObjects)),this.pendingMutations=new an(this._persister,"pendingMutations",new Map,this._onMergePendingMutations,n=>JSON.stringify([...n.entries()]),n=>new Map(JSON.parse(n))),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";!s&&!i&&console.error("Mutation failed",{status:e,eventId:n,...r}),s&&(i?s.resolve({status:e,eventId:n}):s.reject({status:e,eventId:n,...r}))}_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 A of Object.keys(this._rooms)){const K=(i=(s=this._presence[A])==null?void 0:s.result)==null?void 0:i.user;this._tryJoinRoom(A,K)}break;case"add-query-exists":this.notifyOneQueryOnce(P(n.q));break;case"add-query-ok":const{q:f,result:l}=n,d=P(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,b=un(l),w=Qe(this.attrs,b,r,this._linkIndex,this.config.useDateObjects);this.querySubs.set(A=>(A[d].result={store:w,pageInfo:h,aggregate:p,processedTxId:n["processed-tx-id"]},A)),this._cleanupPendingMutationsQueries(),this.notifyOne(d),this.notifyOneQueryOnce(d),this._cleanupPendingMutationsTimeout();break;case"refresh-ok":const{computations:_,attrs:g}=n,O=n["processed-tx-id"];g&&this._setAttrs(g),this._cleanupPendingMutationsTimeout();const j=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue,O);j!==this.pendingMutations.currentValue&&this.pendingMutations.set(()=>j);const S=hn(j.entries()),R=_.map(A=>{var vn,An,Cn,kn;const K=A["instaql-query"],H=A["instaql-result"],yt=P(K),Ae=un(H),Ri=Qe(this.attrs,Ae,r,this._linkIndex,this.config.useDateObjects),xi=this._applyOptimisticUpdates(Ri,S,O),Di=(An=(vn=H==null?void 0:H[0])==null?void 0:vn.data)==null?void 0:An["page-info"],Ui=(kn=(Cn=H==null?void 0:H[0])==null?void 0:Cn.data)==null?void 0:kn.aggregate;return{hash:yt,store:xi,pageInfo:Di,aggregate:Ui}});R.forEach(({hash:A,store:K,pageInfo:H,aggregate:yt})=>{this.querySubs.set(Ae=>(Ae[A].result={store:K,pageInfo:H,aggregate:yt,processedTxId:O},Ae))}),this._cleanupPendingMutationsQueries(),R.forEach(({hash:A})=>{this.notifyOne(A)});break;case"transact-ok":const{"client-event-id":I,"tx-id":W}=n,Sn=this._rewriteMutations(this.attrs,this.pendingMutations.currentValue).get(I);if(!Sn)break;this.pendingMutations.set(A=>(A.set(I,{...A.get(I),"tx-id":W,confirmed:Date.now()}),A)),this._cleanupPendingMutationsTimeout();const Ii=Sn["tx-steps"].filter(([A,...K])=>A==="add-attr").map(([A,K])=>K).concat(Object.values(this.attrs));this._setAttrs(Ii),this._finishTransaction("synced",I);break;case"patch-presence":{const A=n["room-id"];this._patchPresencePeers(A,n.edits),this._notifyPresenceSubs(A);break}case"refresh-presence":{const A=n["room-id"];this._setPresencePeers(A,n.data),this._notifyPresenceSubs(A);break}case"server-broadcast":const Ei=n["room-id"],ji=n.topic;this._notifyBroadcastSubs(Ei,ji,n);break;case"join-room-ok":const re=n["room-id"],On=this._rooms[re];if(!On){this._roomsPendingLeave[re]&&(this._tryLeaveRoom(re),delete this._roomsPendingLeave[re]);break}On.isConnected=!0,this._notifyPresenceSubs(re),this._flushEnqueuedRoomData(re);break;case"join-room-error":const Mn=n["room-id"],Pn=this._rooms[Mn];Pn&&(Pn.error=n.error),this._notifyPresenceSubs(Mn);break;case"error":this._handleReceiveError(n);break}}_handleMutationError(e,n,r){const s=this.pendingMutations.currentValue.get(n);s&&(e!=="timeout"||!s["tx-id"])&&(this.pendingMutations.set(i=>(i.delete(n),i)),this.notifyAll(),this.notifyAttrsSubs(),this.notifyMutationErrorSubs(r),this._finishTransaction(e,n,r))}_handleReceiveError(e){var a,c,u,f,l;const n=e["client-event-id"],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){const d={message:e.message,hint:e.hint};this._handleMutationError("error",n,d);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=P(d);this.notifyQueryError(P(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: `,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=k();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){r&&"ruleParams"in r&&(e={$$ruleParams:r.ruleParams,...e});const s=P(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){n&&"ruleParams"in n&&(e={$$ruleParams:n.ruleParams,...e});const r=new on;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=P(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")),Gs),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(k(),{op:"remove-query",q:e}))}_rewriteMutations(e,n,r){if(!e)return n;const s=f=>{const[l,d,h]=f["forward-identity"];return T(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[w,_]=h,g=s(_);if(g&&_.id!==g.id){o.attrIdMap[_.id]=g.id,a=!0;continue}if(_["value-type"]==="ref"){const O=i(_);if(O){o.attrIdMap[_.id]=O.id,o.refSwapAttrIds.add(_.id),a=!0;continue}}}if(r&&l&&r>=l&&p==="add-attr"||p==="update-attr"||p==="delete-attr"){a=!0;continue}const b=a?ds(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 hn(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),w=os({store:b,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=br(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._ws)==null||e.close()}_sendMutation(e,n){if(n.error){this._handleMutationError("error",e,{error:n.error,message:n.error.message});return}if(this.status!==J.AUTHENTICATED){this._finishTransaction("enqueued",e);return}const r=Math.max(5e3,this.pendingMutations.currentValue.size*5e3);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(){const e=Date.now();this.pendingMutations.currentValue.size<200||this.pendingMutations.set(n=>{let r=!1,s=!1;for(const[i,o]of Array.from(n.entries()))o.confirmed||(s=!0),o.confirmed&&o.confirmed+Ys{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(ft))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{user:c}=await tn({apiURI:this.config.apiURI,appId:this.config.appId,code:r});return this.setCurrentUser(c),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||_e(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 n;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(lt,JSON.stringify(e))}getCurrentUserCached(){return this._currentUserCached}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 n=await this._persister.getItem(lt),r={user:JSON.parse(n),error:void 0};return this._currentUserCached={isLoading:!1,...r},r}async _hasCurrentUser(){const e=await this._persister.getItem(lt);return JSON.parse(e)!=null}async changeCurrentUser(e){var r;const{user:n}=await this.getCurrentUser();if(!_e(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._ws.close(),this._oauthCallbackResponse=null,this.notifyAuthSubs(n)}sendMagicCode({email:e}){return $s({apiURI:this.config.apiURI,appId:this.config.appId,email:e})}async signInWithMagicCode({email:e,code:n}){const r=await Ns({apiURI:this.config.apiURI,appId:this.config.appId,email:e,code:n});return await this.changeCurrentUser(r.user),r}async signInWithCustomToken(e){const n=await Ls({apiURI:this.config.apiURI,appId:this.config.appId,refreshToken:e});return await this.changeCurrentUser(n.user),n}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}Fs({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}){const r=await tn({apiURI:this.config.apiURI,appId:this.config.appId,code:e,codeVerifier:n});return await this.changeCurrentUser(r.user),r}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 qs({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){return this._rooms[e]||(this._rooms[e]={isConnected:!1,error:void 0}),this._presence[e]=this._presence[e]||{},n&&(this._presence[e].result=this._presence[e].result||{},this._presence[e].result.user=n,this._notifyPresenceSubs(e)),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:{...Js(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(k(),{op:"set-presence","room-id":e,data:n})}_tryJoinRoom(e,n){this._trySendAuthed(k(),{op:"join-room","room-id":e,data:n}),delete this._roomsPendingLeave[e]}_tryLeaveRoom(e){this._trySendAuthed(k(),{op:"leave-room","room-id":e})}subscribePresence(e,n,r,s){const i=this.joinRoom(n,r.data),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&&!Hs(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=qe(s,u=>{for(let[f,l,d]of n)switch(l){case"+":Fn(u,f,d);break;case"r":It(u,f,d);break;case"-":Et(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=qe(this._presence,i=>{It(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(k(),{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 zs({...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 Vs({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 Ws({apiURI:this.config.apiURI,appId:this.config.appId,fileName:i,refreshToken:s});return await Qs(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 Bs({apiURI:this.config.apiURI,appId:this.config.appId,path:e,refreshToken:r})}}class F{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 F(this.valueType,!1,this.isIndexed,this.config)}optional(){return new F(this.valueType,!1,this.isIndexed,this.config)}unique(){return new F(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new F(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 Pe{constructor(e,n,r){this.entities=e,this.links=n,this.rooms=r}withRoomSchema(){return new Pe(this.entities,this.links,{})}}function oi(t,e){return new Pe(pn(t,e),e,void 0)}function ai(t){return new Me(t,{})}function ci(){return new F("string",!0,!1)}function ui(){return new F("number",!0,!1)}function fi(){return new F("boolean",!0,!1)}function li(){return new F("date",!0,!1)}function di(){return new F("json",!0,!1)}function hi(){return new F("json",!0,!1)}function pn(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 pi({entities:t,links:e,rooms:n}){const r=e??{},s=n??{};return new Pe(pn(t,r),r,s)}const yi={graph:oi,schema:pi,entity:ai,string:ci,number:ui,boolean:fi,date:li,json:di,any:hi};let ve;function _i(t,e){ve==null||ve.dispose();const n=Oi(e),r=gi(e,a),s=wi(bi(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),ve={dispose:c}}return u()}function bi(t){return`${ct||rn?"http://localhost:3000":"https://instantdb.com"}/_devtool?appId=${t}`}function wi(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 gi(t,e){const n=` `,r=document.createElement("button");return r.innerHTML=n,r.className="instant-devtool-toggler",Object.assign(r.style,{position:"fixed",...mi(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 mi(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 Si(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 Oi(t){const e=document.createElement("div");Object.assign(e.style,{position:"fixed",...Si(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 Mi={apiURI:"https://api.instantdb.com",websocketURI:"wss://api.instantdb.com/runtime/session"};function Pi(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function vi(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}function dt(t){const e=t.__adminToken;return t.appId+"_"+(t.websocketURI||"default_ws_uri")+"_"+(t.apiURI||"default_api_uri")+"_"+(e||"client_only")+"_"+t.useDateObjects}const ht=vi(),pt=Pi();class yn{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.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 _n{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 Ai(t){return JSON.parse(JSON.stringify(t))}class bn{constructor(e){this.tx=et(),this._reactor=e,this.auth=new yn(this._reactor),this.storage=new _n(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 ht[dt(this._reactor.config)],this._reactor.shutdown()}queryOnce(e,n){return this._reactor.queryOnce(e,n)}}function wn(t){if(!t)return"0";if(pt.get(t))return pt.get(t);const e=P(t);return pt.set(t,e),e}function Ci(t,e){return wn(t._reactor.config.schema)!==wn(e)}function gn(t,e,n,r){const s=ht[dt(t)];if(s)return Ci(s,t.schema)&&s._reactor.updateSchema(t.schema),s;const i=new ii({...Mi,...t,cardinalityInference:!!t.schema},e||ot,n||at,{...r||{},"@instantdb/core":ut}),o=new bn(i);return ht[dt(t)]=o,ki(t.appId,t.devtool),o}function ki(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)&&_i(t,n)}const Ti=gn;M.Auth=yn,M.IndexedDBStorage=ot,M.InstantAPIError=Oe,M.InstantCoreDatabase=bn,M.Storage=_n,M.WindowNetworkListener=at,M.coerceQuery=Ai,M.getOps=Yt,M.i=yi,M.id=k,M.init=gn,M.init_experimental=Ti,M.lookup=us,M.tx=ls,M.txInit=et,M.version=ut,M.weakHash=P,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})});