@instantdb/resumable-stream 1.0.30 → 1.0.31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- (function(E,k){typeof exports=="object"&&typeof module<"u"?k(exports):typeof define=="function"&&define.amd?define(["exports"],k):(E=typeof globalThis<"u"?globalThis:E||self,k(E.instant={}))})(this,function(E){"use strict";var Bs=Object.defineProperty;var $n=E=>{throw TypeError(E)};var qs=(E,k,R)=>k in E?Bs(E,k,{enumerable:!0,configurable:!0,writable:!0,value:R}):E[k]=R;var f=(E,k,R)=>qs(E,typeof k!="symbol"?k+"":k,R),Ut=(E,k,R)=>k.has(E)||$n("Cannot "+R);var g=(E,k,R)=>(Ut(E,k,"read from private field"),R?R.call(E):k.get(E)),ee=(E,k,R)=>k.has(E)?$n("Cannot add the same private member more than once"):k instanceof WeakSet?k.add(E):k.set(E,R),de=(E,k,R,M)=>(Ut(E,k,"write to private field"),M?M.call(E,R):k.set(E,R),R),te=(E,k,R)=>(Ut(E,k,"access private method"),R);var je,z,Ee,G,H,L,_n,at,Cn,xn,Tn,nt,st,it,Nt,Rn,rt;const k=/^(?:[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 R(e){return typeof e=="string"&&k.test(e)}const M=[];for(let e=0;e<256;++e)M.push((e+256).toString(16).slice(1));function Pn(e,t=0){return(M[e[t+0]]+M[e[t+1]]+M[e[t+2]]+M[e[t+3]]+"-"+M[e[t+4]]+M[e[t+5]]+"-"+M[e[t+6]]+M[e[t+7]]+"-"+M[e[t+8]]+M[e[t+9]]+"-"+M[e[t+10]]+M[e[t+11]]+M[e[t+12]]+M[e[t+13]]+M[e[t+14]]+M[e[t+15]]).toLowerCase()}let ct;const An=new Uint8Array(16);function Mn(){if(!ct){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");ct=crypto.getRandomValues.bind(crypto)}return ct(An)}const Dt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function jn(e,t,n){var i;if(Dt.randomUUID&&!e)return Dt.randomUUID();e=e||{};const s=e.random??((i=e.rng)==null?void 0:i.call(e))??Mn();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Pn(s)}const D={Remove:"remove",Replace:"replace",Add:"add"},Lt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),Qe=Symbol.iterator,ne={mutable:"mutable",immutable:"immutable"},ut={};function Ne(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Wt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const s=Reflect.getOwnPropertyDescriptor(n,t);if(s)return s;n=Reflect.getPrototypeOf(n)}}}function Ft(e){return Object.getPrototypeOf(e)===Set.prototype}function zt(e){return Object.getPrototypeOf(e)===Map.prototype}function X(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function ft(e){return!!$(e)}function $(e){return typeof e!="object"?null:e==null?void 0:e[Lt]}function lt(e){var t;const n=$(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function we(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,ne))===ne.immutable||typeof n=="function")}function Vt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,s=$(he(n,e.key));if(s!==null&&(s==null?void 0:s.original)!==e.original)return null;const i=e.parent.type===3,r=i?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(i&&n.size>r||Ne(n,r)))return null;t.push(r)}if(e.parent)return Vt(e.parent,t);t.reverse();try{Un(e.copy,t)}catch{return null}return t}function De(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function he(e,t){return De(e)===2?e.get(t):e[t]}function dt(e,t,n){De(e)===2?e.set(t,n):e[t]=n}function ht(e,t){const n=$(e);return(n?X(n):e)[t]}function Se(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Ie(e,t){return t?e:[""].concat(e).map(n=>{const s=`${n}`;return s.indexOf("/")===-1&&s.indexOf("~")===-1?s:s.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Un(e,t){for(let n=0;n<t.length-1;n+=1){const s=t[n];if(e=he(De(e)===3?Array.from(e):e,s),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Nn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let s=Reflect.getOwnPropertyDescriptor(e,n);if(s.enumerable&&s.configurable&&s.writable){t[n]=e[n];return}s.writable||(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(s={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]}),Reflect.defineProperty(t,n,s)}),t}const Dn=Object.prototype.propertyIsEnumerable;function Ln(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Ft(e)){const s=Object.getPrototypeOf(e).constructor;return new s(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!zt(e)){const s=Object.getPrototypeOf(e).constructor;return new s(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,ne),n!==void 0)&&n!==ne.mutable){if(n===ne.immutable)return Nn(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const s={};return Object.keys(e).forEach(i=>{s[i]=e[i]}),Object.getOwnPropertySymbols(e).forEach(i=>{Dn.call(e,i)&&(s[i]=e[i])}),s}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function Q(e){e.copy||(e.copy=Ln(e.original,e.options))}function Le(e){if(!we(e))return lt(e);if(Array.isArray(e))return e.map(Le);if(e instanceof Map){const n=Array.from(e.entries()).map(([s,i])=>[s,Le(i)]);if(!zt(e)){const s=Object.getPrototypeOf(e).constructor;return new s(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Le);if(!Ft(e)){const s=Object.getPrototypeOf(e).constructor;return new s(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Le(e[n]);return t}function Ge(e){return ft(e)?Le(e):e}function ae(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ae(e.parent))}function Wn(e,t){const n=De(e);if(n===0)Reflect.ownKeys(e).forEach(s=>{t(s,e[s],e)});else if(n===1){let s=0;for(const i of e)t(s,i,e),s+=1}else e.forEach((s,i)=>t(i,s,e))}function Jt(e,t,n){if(ft(e)||!we(e,n)||t.has(e)||Object.isFrozen(e))return;const s=e instanceof Set,i=s?new Map:void 0;if(t.add(e),Wn(e,(r,o)=>{var a;if(ft(o)){const c=$(o);Q(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;dt(s?i:e,r,u)}else Jt(o,t,n)}),i){const r=e,o=Array.from(r);r.clear(),o.forEach(a=>{r.add(i.has(a)?i.get(a):a)})}}function Fn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Jt(he(n,t),e.finalities.handledSet,e.options)}function pt(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(lt(t))}))}function mt(e,t,n,s){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&s){const r=Vt(e);r&&t(e,r,n,s)}e.finalized=!0}}function yt(e,t,n,s){const i=$(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((r,o)=>{var a;const c=e.type===3?e.setMap:e.copy;if(Se(he(c,t),n)){let u=i.original;i.copy&&(u=i.copy),pt(e),mt(e,s,r,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(u,i.original)),dt(c,t,u)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),we(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;Se(he(r,t),n)&&Fn(e,t)})}function zn(e,t,n,s,i){let{original:r,assignedMap:o,options:a}=e,c=e.copy;c.length<r.length&&([r,c]=[c,r],[n,s]=[s,n]);for(let u=0;u<r.length;u+=1)if(o.get(u.toString())&&c[u]!==r[u]){const l=t.concat([u]),d=Ie(l,i);n.push({op:D.Replace,path:d,value:Ge(c[u])}),s.push({op:D.Replace,path:d,value:Ge(r[u])})}for(let u=r.length;u<c.length;u+=1){const l=t.concat([u]),d=Ie(l,i);n.push({op:D.Add,path:d,value:Ge(c[u])})}if(r.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const l=t.concat(["length"]),d=Ie(l,i);s.push({op:D.Replace,path:d,value:r.length})}else for(let l=c.length;r.length<l;l-=1){const d=t.concat([l-1]),p=Ie(d,i);s.push({op:D.Remove,path:p})}}}function Vn({original:e,copy:t,assignedMap:n},s,i,r,o){n.forEach((a,c)=>{const u=he(e,c),l=Ge(he(t,c)),d=a?Ne(e,c)?D.Replace:D.Add:D.Remove;if(Se(u,l)&&d===D.Replace)return;const p=s.concat(c),y=Ie(p,o);i.push(d===D.Remove?{op:d,path:y}:{op:d,path:y,value:l}),r.push(d===D.Add?{op:D.Remove,path:y}:d===D.Remove?{op:D.Add,path:y,value:u}:{op:D.Replace,path:y,value:u})})}function Jn({original:e,copy:t},n,s,i,r){let o=0;e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=Ie(c,r);s.push({op:D.Remove,path:u,value:a}),i.unshift({op:D.Add,path:u,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=Ie(c,r);s.push({op:D.Add,path:u,value:a}),i.unshift({op:D.Remove,path:u,value:a})}o+=1})}function We(e,t,n,s){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return Vn(e,t,n,s,i);case 1:return zn(e,t,n,s,i);case 3:return Jn(e,t,n,s,i)}}const He=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!we(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},bt={get size(){return X($(this)).size},has(e){return X($(this)).has(e)},set(e,t){const n=$(this),s=X(n);return(!s.has(e)||!Se(s.get(e),t))&&(Q(n),ae(n),n.assignedMap.set(e,!0),n.copy.set(e,t),yt(n,e,t,We)),this},delete(e){if(!this.has(e))return!1;const t=$(this);return Q(t),ae(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=$(this);if(this.size){Q(e),ae(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=$(this);X(n).forEach((s,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const s=$(this),i=X(s).get(e),r=((n=(t=s.options).mark)===null||n===void 0?void 0:n.call(t,i,ne))===ne.mutable;if(s.options.strict&&He(i,s.options,r),r||s.finalized||!we(i,s.options)||i!==s.original.get(e))return i;const o=ut.createDraft({original:i,parentDraft:s,key:e,finalities:s.finalities,options:s.options});return Q(s),s.copy.set(e,o),o},keys(){return X($(this)).keys()},values(){const e=this.keys();return{[Qe]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[Qe]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[Qe](){return this.entries()}},Qn=Reflect.ownKeys(bt),Qt=(e,t,{isValuesIterator:n})=>()=>{var s,i;const r=t.next();if(r.done)return r;const o=r.value;let a=e.setMap.get(o);const c=$(a),u=((i=(s=e.options).mark)===null||i===void 0?void 0:i.call(s,a,ne))===ne.mutable;if(e.options.strict&&He(o,e.options,u),!u&&!c&&we(o,e.options)&&!e.finalized&&e.original.has(o)){const l=ut.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,l),a=l}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},Be={get size(){return $(this).setMap.size},has(e){const t=$(this);if(t.setMap.has(e))return!0;Q(t);const n=$(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=$(this);return this.has(e)||(Q(t),ae(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),yt(t,e,e,We)),this},delete(e){if(!this.has(e))return!1;const t=$(this);Q(t),ae(t);const n=$(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=$(this);Q(e),ae(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=$(this);Q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:Qt(e,t,{isValuesIterator:!0})}},entries(){const e=$(this);Q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:Qt(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[Qe](){return this.values()},forEach(e,t){const n=this.values();let s=n.next();for(;!s.done;)e.call(t,s.value,s.value,this),s=n.next()}};Set.prototype.difference&&Object.assign(Be,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const Gn=Reflect.ownKeys(Be),Gt=new WeakSet,Ht={get(e,t,n){var s,i;const r=(s=e.copy)===null||s===void 0?void 0:s[t];if(r&&Gt.has(r))return r;if(t===Lt)return e;let o;if(e.options.mark){const u=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(o=e.options.mark(u,ne),o===ne.mutable)return e.options.strict&&He(u,e.options,!0),u}const a=X(e);if(a instanceof Map&&Qn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(bt,"size").get.call(e.proxy);const u=bt[t];if(u)return u.bind(e.proxy)}if(a instanceof Set&&Gn.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(Be,"size").get.call(e.proxy);const u=Be[t];if(u)return u.bind(e.proxy)}if(!Ne(a,t)){const u=Wt(a,t);return u?"value"in u?u.value:(i=u.get)===null||i===void 0?void 0:i.call(e.proxy):void 0}const c=a[t];if(e.options.strict&&He(c,e.options),e.finalized||!we(c,e.options))return c;if(c===ht(e.original,t)){if(Q(e),e.copy[t]=Bt({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const u=$(e.copy[t]);return Q(u),ae(u),u.copy}return e.copy[t]}return c},set(e,t,n){var s;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let i;if(e.type===1&&t!=="length"&&!(Number.isInteger(i=Number(t))&&i>=0&&(t===0||i===0||String(i)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const r=Wt(X(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=ht(X(e),t),a=$(o);return a&&Se(a.original,n)?(e.copy[t]=n,e.assignedMap=(s=e.assignedMap)!==null&&s!==void 0?s:new Map,e.assignedMap.set(t,!1),!0):(Se(n,o)&&(n!==void 0||Ne(e.original,t))||(Q(e),ae(e),Ne(e.original,t)&&Se(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,yt(e,t,n,We)),!0)},has(e,t){return t in X(e)},ownKeys(e){return Reflect.ownKeys(X(e))},getOwnPropertyDescriptor(e,t){const n=X(e),s=Reflect.getOwnPropertyDescriptor(n,t);return s&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:s.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?Ht.set.call(this,e,t,void 0,e.proxy):(ht(e.original,t)!==void 0||t in e.original?(Q(e),ae(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function Bt(e){const{original:t,parentDraft:n,key:s,finalities:i,options:r}=e,o=De(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:i,options:r,setMap:o===3?new Map(t.entries()):void 0};(s||"key"in e)&&(a.key=s);const{proxy:c,revoke:u}=Proxy.revocable(o===1?Object.assign([],a):a,Ht);if(i.revoke.push(u),Gt.add(c),a.proxy=c,n){const l=n;l.finalities.draft.push((d,p)=>{var y,v;const b=$(c);let h=l.type===3?l.setMap:l.copy;const I=he(h,s),O=$(I);if(O){let V=O.original;O.operated&&(V=lt(I)),pt(O),mt(O,We,d,p),l.options.enableAutoFreeze&&(l.options.updatedValues=(y=l.options.updatedValues)!==null&&y!==void 0?y:new WeakMap,l.options.updatedValues.set(V,O.original)),dt(h,s,V)}(v=b.callbacks)===null||v===void 0||v.forEach(V=>{V(d,p)})})}else{const l=$(c);l.finalities.draft.push((d,p)=>{pt(l),mt(l,We,d,p)})}return c}ut.createDraft=Bt,Object.prototype.constructor.toString();function _e(){return jn()}function Hn(e,t){return e.localeCompare(t)}function Bn(){let e=Hn;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Bn();function qn(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const Kn=qn();function qe(e,t,n){const s={__etype:e,__ops:n};return new Proxy(s,{get:(i,r)=>{if(r==="__ops")return n;if(r==="__etype")return e;if(Kn.has(r))return(o,a)=>qe(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function Xn(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function qt(e){return e.startsWith("lookup__")}function Kt(e){const[t,n,...s]=e.split("__");return[n,JSON.parse(s.join("__"))]}function Yn(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(i,r)=>qe(e,Kt(Xn(i,r)),[]);if(n==="__etype")return e;const s=n;return qt(s)?qe(e,Kt(s),[]):qe(e,s,[])}})}function Xt(){return new Proxy({},{get(e,t){return Yn(t)}})}Xt();function Zn(e){return e.__ops}class B extends Error{constructor(n,s,i){super(n);f(this,"hint");f(this,"traceId");this.hint=s,i&&(this.traceId=i);const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,B),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class ve extends B{constructor(n){var r,o;const s=((r=n.body)==null?void 0:r.message)||`API Error (${n.status})`;super(s,n.body.hint,((o=n.body)==null?void 0:o.traceId)||n.body["trace-id"]);f(this,"body");f(this,"status");const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,ve),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const Ce="v1.0.30";class ce{constructor(t,n,s,i={indexed:!1,unique:!1}){f(this,"valueType");f(this,"required");f(this,"isIndexed");f(this,"config");f(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=s,this.config=i}clientRequired(){return new ce(this.valueType,!1,this.isIndexed,this.config)}optional(){return new ce(this.valueType,!1,this.isIndexed,this.config)}unique(){return new ce(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new ce(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class x extends Error{constructor(t,n){const s=n?`At path '${n}': ${t}`:t;super(s),this.name="QueryValidationError"}}const Yt=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],es=e=>e.valueType||"unknown",Zt=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},ts=(e,t,n,s,i,r,o)=>{const a=r.valueType==="json",c=(u,l,d)=>{if(!Zt(d,l,a))throw new x(`Invalid value for operator '${u}' on attribute '${s}' in entity '${i}'. Expected ${l}, but received: ${typeof d}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new x(`Operator '${e}' for attribute '${s}' in entity '${i}' must be an array, but received: ${typeof t}`,o);for(const u of t)c(e,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(e,n,t);break;case"$like":case"$ilike":if(c(e,"string",t),e==="$ilike"&&!r.isIndexed)throw new x(`Operator '${e}' can only be used with indexed attributes, but '${s}' in entity '${i}' is not indexed`,o);break;case"$isNull":c(e,"boolean",t);break;default:throw new x(`Unknown operator '${e}' for attribute '${s}' in entity '${i}'`,o)}},xe=(e,t,n,s,i)=>{const r=es(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const c=e;for(const[u,l]of Object.entries(c))ts(u,l,r,t,s,n,`${i}.${u}`)}else if(!Zt(e,r,o))throw new x(`Invalid value for attribute '${t}' in entity '${s}'. Expected ${r}, but received: ${typeof e}`,i)},ns=(e,t,n,s,i)=>{const r=e.split(".");if(r.length<2)throw new x(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let l=0;l<r.length-1;l++){const d=r[l],p=s.entities[o];if(!p)throw new x(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const y=p.links[d];if(!y){const v=Object.keys(p.links);throw new x(`Link '${d}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${v.length>0?v.join(", "):"none"}`,i)}o=y.entityName}const a=r[r.length-1],c=s.entities[o];if(!c)throw new x(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(a==="id"){if(typeof t=="string"&&!R(t))throw new x(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);xe(t,e,new ce("string",!1,!0),n,i);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof t=="string"&&!R(t))throw new x(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);xe(t,e,new ce("string",!1,!0),n,i);return}if(!u){const l=Object.keys(c.attrs);throw new x(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${l.length>0?l.join(", ")+", id":"id"}`,i)}xe(t,e,u,n,i)},en=(e,t,n,s)=>{for(const[i,r]of Object.entries(e)){if(i==="or"||i==="and"){if(Array.isArray(r))for(const u of r)typeof u=="object"&&u!==null&&en(u,t,n,`${s}.${i}[${u}]`);continue}if(i==="id"){xe(r,"id",new ce("string",!1,!0),t,`${s}.id`);continue}if(i.includes(".")){ns(i,r,t,n,`${s}.${i}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[i],c=o.links[i];if(!a&&!c){const u=Object.keys(o.attrs),l=Object.keys(o.links);throw new x(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${l.length>0?l.join(", "):"none"}`,`${s}.${i}`)}if(a)xe(r,i,a,t,`${s}.${i}`);else if(c){if(typeof r=="string"&&!R(r))throw new x(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${s}.${i}`);const u=new ce("string",!1,!0);xe(r,i,u,t,`${s}.${i}`)}}},ss=(e,t,n,s,i=0)=>{for(const o of Object.keys(e))if(!Yt.includes(o))throw new x(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${Yt.join(", ")}. Found: ${o}`,s);const r=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const o of r)if(e[o]!==void 0&&i>0)throw new x(`'${o}' can only be used on top-level namespaces. It cannot be used in nested queries.`,s);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new x(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,s?`${s}.where`:void 0);en(e.where,t,n,s?`${s}.where`:"where")}},tn=(e,t,n,s,i=0)=>{var r;if(!e||typeof e!="object")throw new x(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,s);for(const o of Object.keys(e))if(o!=="$"){if(n&&!(o in n.entities[t].links)){const c=Object.keys(n.entities[t].links);throw new x(`Link '${o}' does not exist on entity '${t}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${s}.${o}`)}const a=e[o];if(typeof a=="object"&&a!==null){const c=(r=n==null?void 0:n.entities[t].links[o])==null?void 0:r.entityName;c&&tn(a,c,n,`${s}.${o}`,i+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new x(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${s}.$`);ss(a,t,n,`${s}.$`,i)}},nn=(e,t)=>{if(typeof e!="object"||e===null)throw new x(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new x(`Query must be an object, but received: ${typeof e}`);const n=e;for(const s of Object.keys(n)){if(Array.isArray(e[s]))throw new x(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(typeof s!="string")throw new x(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(s!=="$$ruleParams"){if(t&&!t.entities[s]){const i=Object.keys(t.entities);throw new x(`Entity '${s}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,s)}tn(n[s],s,t,s,0)}}},sn=e=>typeof e!="string"?!1:qt(e)?!0:R(e);class Y extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const rn=e=>e.length>0?e.join(", "):"none",is=(e,t)=>new Y(`Entity '${e}' does not exist in schema. Available entities: ${rn(t)}`),gt={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},rs=(e,t)=>{var n;return e==null?!0:((n=gt[t.valueType])==null?void 0:n.call(gt,e))??!1},on=(e,t)=>{const n=t.entities[e];if(!n)throw is(e,Object.keys(t.entities));return n},wt=(e,t,n)=>{const s=on(e,n);if(typeof t!="object"||t===null)throw new Y(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,r]of Object.entries(t)){if(i==="id")continue;const o=s.attrs[i];if(o&&!rs(r,o))throw new Y(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},an=(e,t,n)=>{const s=on(e,n);if(typeof t!="object"||t===null)throw new Y(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[i,r]of Object.entries(t)){if(!s.links[i]){const a=Object.keys(s.links);throw new Y(`Link '${i}' does not exist on entity '${e}'. Available links: ${rn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!sn(a))throw new Y(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!sn(r))throw new Y(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},os={create:wt,update:wt,merge:wt,link:an,unlink:an,delete:()=>{}},as=(e,t)=>{if(!t)return;const[n,s,i,r]=e;if(!Array.isArray(i)&&!R(i))throw new Y(`Invalid id for entity '${s}'. Expected a UUID, but received: ${i}`);if(typeof s!="string")throw new Y(`Entity name must be a string, but received: ${typeof s}`);const o=os[n];o&&r!==void 0&&o(s,r,t)},cs=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const s of n){if(!s||typeof s!="object")throw new Y(`Transaction chunk must be an object, but received: ${typeof s}`);if(!Array.isArray(s.__ops))throw new Y(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);for(const i of s.__ops){if(!Array.isArray(i))throw new Y(`Transaction operation must be an array, but received: ${typeof i}`);as(i,t)}}};let us=0;class fs{constructor(t,n,s){f(this,"type","sse");f(this,"initParams",null);f(this,"sendQueue",[]);f(this,"sendPromise");f(this,"closeFired",!1);f(this,"sseInitTimeout");f(this,"ES");f(this,"messageUrl");f(this,"conn");f(this,"url");f(this,"id");f(this,"onopen");f(this,"onmessage");f(this,"onclose");f(this,"onerror");this.id=`${this.type}_${us++}`,this.url=n,this.messageUrl=s||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=i=>{const r=JSON.parse(i.data);if(Array.isArray(r))for(const o of r)this.handleMessage(o);else this.handleMessage(r)},this.conn.onerror=i=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}async postMessages(t){var n,s,i;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(s=this.initParams)==null?void 0:s.sessionId,sse_token:(i=this.initParams)==null?void 0:i.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(t){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var cn;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(cn||(cn={}));function ls({WStream:e,opts:t,startStream:n,appendStream:s,registerStream:i}){const r=t.clientId;let o=null,a=null,c=null;const u=_e();let l=!1,d=!1;const p=[],y=[],v=[];let b=!1,h=0,I=0;const O=[],V=new TextEncoder;function $e(){d=!0;for(const m of p)m(a??void 0)}function Mt(m){return p.push(m),d&&m(a??void 0),()=>{const w=p.indexOf(m);w!==-1&&p.splice(w,1)}}function On(m){return v.push(m),()=>{const w=v.indexOf(m);w!==-1&&v.splice(w,1)}}t.waitUntil&&t.waitUntil(new Promise(m=>{v.push(m)}));function P(){for(const m of v)try{m()}catch{}}function _(m){return y.push(m),o&&m(o),()=>{const w=y.indexOf(m);w!==-1&&y.splice(w,1)}}function re(m){o=m;for(const w of y)w(o)}function C(){b=!0}function W(m){let w=h,F=0,K=0;for(const{byteLen:oe}of O){const le=w+oe;if(le>m)break;w=le,F++,K+=oe}F>0&&(h+=K,I-=K,O.splice(0,F))}function N(m,w){a=w,$e(),m.error(w),P()}async function Z(){const m=await n({clientId:r,reconnectToken:u,ruleParams:t.ruleParams});switch(m.type){case"ok":{const{streamId:w,offset:F}=m;o=w,W(F),O.length&&s({streamId:w,chunks:O.map(K=>K.chunk),offset:h}),b=!1;break}case"disconnect":{C();break}case"error":{c&&N(c,m.error);break}}}function J(){C(),Z()}function ot({offset:m,done:w}){W(m),w&&(l=!0,P())}function En(m){return l?(N(m,new B("Stream has been closed.")),null):o||(N(m,new B("Stream has not been initialized.")),null)}async function Ue(m){c=m;let w=!0,F=0;for(;w;){let K=Date.now()+Math.min(15e3,500*(F-1));w=!1;const oe=await n({clientId:t.clientId,reconnectToken:u,ruleParams:t.ruleParams});switch(oe.type){case"ok":{const{streamId:le,offset:jt}=oe;if(jt!==0){const ke=new B("Write stream is corrupted");N(m,ke);return}re(le),i(le,{onDisconnect:C,onFlush:ot,onConnectionReconnect:Z,onAppendFailed:J}),b=!1;return}case"disconnect":{w=!0,C(),F++,await new Promise(le=>{setTimeout(le,Math.max(0,K-Date.now()))});break}case"error":{N(m,oe.error);return}}}}class be extends e{constructor(w,F){super(w,F)}async streamId(){return o||new Promise((w,F)=>{const K=[],oe=()=>{for(const ke of K)ke()},le=ke=>{w(ke),oe()},jt=ke=>{F(ke||new B("Stream is closed.")),oe()};K.push(_(le)),K.push(Mt(jt))})}}return{stream:new be({async start(m){try{await Ue(m)}catch(w){N(m,w)}},write(m,w){const F=En(w);if(F){const K=V.encode(m).length;O.push({chunk:m,byteLen:K});const oe=h+I;I+=K,b||s({streamId:F,chunks:[m],offset:oe})}},close(){o?s({streamId:o,chunks:[],offset:h+I,isDone:!0}):P(),$e()},abort(m){o?s({streamId:o,chunks:[],offset:h+I,isDone:!0,abortReason:m}):P(),$e()}}),addCompleteCb:On,closed(){return d}}}class ds{constructor(){f(this,"items",[]);f(this,"resolvers",[]);f(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(s=>{this.resolvers.push(s)});if(n||!t)return;yield t}}}}function hs({RStream:e,opts:t,startStream:n,cancelStream:s}){let i=t.byteOffset||0,r=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let c,u=!1;const l=[],d=[];let p=null,y=null;function v(P){u=!0;for(const _ of l)_(P)}function b(P){return l.push(P),()=>{const _=l.indexOf(P);_!==-1&&l.splice(_,1)}}function h(P){return d.push(P),p&&P(p),()=>{const _=d.indexOf(P);_!==-1&&d.splice(_,1)}}function I(P,_){y=_,P.error(_),v(_)}let O=0;async function V(P,_){c=_e();const re={...P||{},eventId:c};for await(const C of n(re)){if(r)return;if(C.type==="reconnect")return{retry:!0};if(C.type==="error"){I(_,C.error);return}if(C.offset>i){I(_,new B("Stream is corrupted.")),r=!0;return}p=C.streamId;for(const N of d)N(p);let W=i-C.offset;if(C.files&&C.files.length){const N=new AbortController;let Z=fetch(C.files[0].url,{signal:N.signal});for(let J=0;J<C.files.length;J++){const ot=C.files[J+1],Ue=await Z;if(ot&&(Z=fetch(ot.url,{signal:N.signal})),!Ue.ok){if(O++,O>10){I(_,new B("Unable to process stream."));return}return{retry:!0}}if(Ue.body){const be=Ue.body.getReader();try{for(;;){const{done:ge,value:m}=await be.read();if(ge)break;if(r){N.abort();return}let w=m;if(W>0&&(w=m.subarray(W),W-=m.length-w.length),!w.length)continue;i+=w.length;const F=o.decode(w);_.enqueue(F)}}finally{be.releaseLock()}}else{const be=await Ue.arrayBuffer();let ge=be;if(r){N.abort();return}if(W>0&&(ge=new Uint8Array(be).subarray(W),W-=be.byteLength-ge.length),!ge.byteLength)continue;i+=ge.byteLength;const m=o.decode(ge);_.enqueue(m)}}}if(O=0,C.content){let N=C.content,Z=a.encode(C.content);if(W>0){const J=Z.subarray(W);if(W-=Z.length-J.length,!J.length)continue;Z=J,N=o.decode(J)}i+=Z.length,_.enqueue(N)}}}async function $e(P){let _=!0,re=0;for(;_;){_=!1;let C=Date.now()+Math.min(15e3,500*(re-1));const W=await V({...t,offset:i},P);W!=null&&W.retry&&(_=!0,re++,C<Date.now()-3e5&&(re=0),await new Promise(N=>{setTimeout(N,Math.max(0,C-Date.now()))}))}!r&&!u&&(P.close(),v())}class Mt extends e{constructor(_,re){super(_,re)}async streamId(){if(p)return p;if(y)throw y;return new Promise((_,re)=>{const C=[],W=()=>{for(const J of C)J()},N=J=>{_(J),W()},Z=J=>{re(J||new B("Stream is closed.")),W()};C.push(h(N)),C.push(b(Z))})}}return{stream:new Mt({start(P){$e(P)},cancel(P){r=!0,c&&s({eventId:c}),v()}}),addCloseCb:b,closed(){return u}}}class ps{constructor({WStream:t,RStream:n,trySend:s,log:i}){f(this,"trySend");f(this,"WStream");f(this,"RStream");f(this,"writeStreams",{});f(this,"startWriteStreamCbs",{});f(this,"readStreamIterators",{});f(this,"log");f(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=s,this.log=i}createWriteStream(t){const{stream:n,addCompleteCb:s}=ls({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),s(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:s}=hs({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),s(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=_e();let s=null;const i=new Promise(o=>{s=o});this.startWriteStreamCbs[n]=s;const r={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(r["rule-params"]=t.ruleParams),this.trySend(n,r),i}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:s,offset:i,abortReason:r}){const o={op:"append-stream","stream-id":t,chunks:n,offset:i,done:!!s};r&&(o["abort-reason"]=r),this.trySend(_e(),o)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],s=this.writeStreams[n];if(!s){this.log.info("No stream cbs for stream-flushed",t);return}s.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:s,offset:i,ruleParams:r}){const o={op:"subscribe-stream"};if(!s&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");s&&(o["stream-id"]=s),n&&(o["client-id"]=n),i&&(o.offset=i),r&&(o["rule-params"]=r);const a=new ds;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(_e(),n),delete this.readStreamIterators[t]}onStreamAppend(t){const n=t["client-event-id"],s=this.readStreamIterators[n];if(!s){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?s.push({type:"reconnect"}):s.push({type:"error",error:new B(t.error)}),s.close(),delete this.readStreamIterators[n];return}s.push({type:"append",offset:t.offset,files:t.files,content:t.content,streamId:t["stream-id"]}),t.done&&(s.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==ms.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const s=n["stream-id"],i=this.writeStreams[s];i==null||i.onAppendFailed();break}case"start-stream":{const s=t["client-event-id"],i=this.startWriteStreamCbs[s];i&&(i({type:"error",error:new B(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[s]);break}case"subscribe-stream":{const s=t["client-event-id"],i=this.readStreamIterators[s];i&&(i.push({type:"error",error:new B(t.message||"Unknown error",t.hint)}),i.close(),delete this.readStreamIterators[s]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const ms={AUTHENTICATED:"authenticated"};function ys(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function bs(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}bs(),ys();class un extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function St(e){}function gs(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=St,onError:n=St,onRetry:s=St,onComment:i}=e;let r="",o=!0,a,c="",u="";function l(b){const h=o?b.replace(/^\xEF\xBB\xBF/,""):b,[I,O]=ws(`${r}${h}`);for(const V of I)d(V);r=O,o=!1}function d(b){if(b===""){y();return}if(b.startsWith(":")){i&&i(b.slice(b.startsWith(": ")?2:1));return}const h=b.indexOf(":");if(h!==-1){const I=b.slice(0,h),O=b[h+1]===" "?2:1,V=b.slice(h+O);p(I,V,b);return}p(b,"",b)}function p(b,h,I){switch(b){case"event":u=h;break;case"data":c=`${c}${h}
2
- `;break;case"id":a=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?s(parseInt(h,10)):n(new un(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:I}));break;default:n(new un(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:h,line:I}));break}}function y(){c.length>0&&t({id:a,event:u||void 0,data:c.endsWith(`
3
- `)?c.slice(0,-1):c}),a=void 0,c="",u=""}function v(b={}){r&&b.consume&&d(r),o=!0,a=void 0,c="",u="",r=""}return{feed:l,reset:v}}function ws(e){const t=[];let n="",s=0;for(;s<e.length;){const i=e.indexOf("\r",s),r=e.indexOf(`
4
- `,s);let o=-1;if(i!==-1&&r!==-1?o=Math.min(i,r):i!==-1?i===e.length-1?o=-1:o=i:r!==-1&&(o=r),o===-1){n=e.slice(s);break}else{const a=e.slice(s,o);t.push(a),s=o+1,e[s-1]==="\r"&&e[s]===`
5
- `&&s++}}return[t,n]}class fn extends Event{constructor(t,n){var s,i;super(t),this.code=(s=n==null?void 0:n.code)!=null?s:void 0,this.message=(i=n==null?void 0:n.message)!=null?i:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,s){return s(ln(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t(ln(this),n)}}function Ss(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function It(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(It).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${It(e.cause)}`:e.message:`${e}`}function ln(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var dn=e=>{throw TypeError(e)},vt=(e,t,n)=>t.has(e)||dn("Cannot "+n),S=(e,t,n)=>(vt(e,t,"read from private field"),n?n.call(e):t.get(e)),j=(e,t,n)=>t.has(e)?dn("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),T=(e,t,n,s)=>(vt(e,t,"write to private field"),t.set(e,n),n),ue=(e,t,n)=>(vt(e,t,"access private method"),n),q,Oe,Te,Ke,Xe,Ye,Fe,Re,ze,pe,Pe,Ae,Me,Ve,se,Ot,Et,$t,hn,kt,_t,Je,Ct,xt;class ie extends EventTarget{constructor(t,n){var s,i,r;super(),j(this,se),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,j(this,q),j(this,Oe),j(this,Te),j(this,Ke),j(this,Xe),j(this,Ye),j(this,Fe),j(this,Re),j(this,ze,null),j(this,pe),j(this,Pe),j(this,Ae,null),j(this,Me,null),j(this,Ve,null),j(this,Et,async o=>{var a;S(this,Pe).reset();const{body:c,redirected:u,status:l,headers:d}=o;if(l===204){ue(this,se,Je).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?T(this,Te,new URL(o.url)):T(this,Te,void 0),l!==200){ue(this,se,Je).call(this,`Non-200 status code (${l})`,l);return}if(!(d.get("content-type")||"").startsWith("text/event-stream")){ue(this,se,Je).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(S(this,q)===this.CLOSED)return;T(this,q,this.OPEN);const p=new Event("open");if((a=S(this,Ve))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){ue(this,se,Je).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const y=new TextDecoder,v=c.getReader();let b=!0;do{const{done:h,value:I}=await v.read();I&&S(this,Pe).feed(y.decode(I,{stream:!h})),h&&(b=!1,S(this,Pe).reset(),ue(this,se,Ct).call(this))}while(b)}),j(this,$t,o=>{T(this,pe,void 0),!(o.name==="AbortError"||o.type==="aborted")&&ue(this,se,Ct).call(this,It(o))}),j(this,kt,o=>{typeof o.id=="string"&&T(this,ze,o.id);const a=new(S(this,Ye))(o.event||"message",{data:o.data,origin:S(this,Te)?S(this,Te).origin:S(this,Oe).origin,lastEventId:o.id||""});S(this,Me)&&(!o.event||o.event==="message")&&S(this,Me).call(this,a),this.dispatchEvent(a)}),j(this,_t,o=>{T(this,Fe,o)}),j(this,xt,()=>{T(this,Re,void 0),S(this,q)===this.CONNECTING&&ue(this,se,Ot).call(this)});try{if(t instanceof URL)T(this,Oe,t);else if(typeof t=="string")T(this,Oe,new URL(t,Is()));else throw new Error("Invalid URL")}catch{throw Ss("An invalid or illegal string was specified")}T(this,Pe,gs({onEvent:S(this,kt),onRetry:S(this,_t)})),T(this,q,this.CONNECTING),T(this,Fe,3e3),T(this,Xe,(s=n==null?void 0:n.fetch)!=null?s:globalThis.fetch),T(this,Ye,(i=n==null?void 0:n.messageEvent)!=null?i:globalThis.MessageEvent),T(this,Ke,(r=n==null?void 0:n.withCredentials)!=null?r:!1),ue(this,se,Ot).call(this)}get readyState(){return S(this,q)}get url(){return S(this,Oe).href}get withCredentials(){return S(this,Ke)}get onerror(){return S(this,Ae)}set onerror(t){T(this,Ae,t)}get onmessage(){return S(this,Me)}set onmessage(t){T(this,Me,t)}get onopen(){return S(this,Ve)}set onopen(t){T(this,Ve,t)}addEventListener(t,n,s){const i=n;super.addEventListener(t,i,s)}removeEventListener(t,n,s){const i=n;super.removeEventListener(t,i,s)}close(){S(this,Re)&&clearTimeout(S(this,Re)),S(this,q)!==this.CLOSED&&(S(this,pe)&&S(this,pe).abort(),T(this,q,this.CLOSED),T(this,pe,void 0))}}q=new WeakMap,Oe=new WeakMap,Te=new WeakMap,Ke=new WeakMap,Xe=new WeakMap,Ye=new WeakMap,Fe=new WeakMap,Re=new WeakMap,ze=new WeakMap,pe=new WeakMap,Pe=new WeakMap,Ae=new WeakMap,Me=new WeakMap,Ve=new WeakMap,se=new WeakSet,Ot=function(){T(this,q,this.CONNECTING),T(this,pe,new AbortController),S(this,Xe)(S(this,Oe),ue(this,se,hn).call(this)).then(S(this,Et)).catch(S(this,$t))},Et=new WeakMap,$t=new WeakMap,hn=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...S(this,ze)?{"Last-Event-ID":S(this,ze)}:void 0},cache:"no-store",signal:(e=S(this,pe))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},kt=new WeakMap,_t=new WeakMap,Je=function(e,t){var n;S(this,q)!==this.CLOSED&&T(this,q,this.CLOSED);const s=new fn("error",{code:t,message:e});(n=S(this,Ae))==null||n.call(this,s),this.dispatchEvent(s)},Ct=function(e,t){var n;if(S(this,q)===this.CLOSED)return;T(this,q,this.CONNECTING);const s=new fn("error",{code:t,message:e});(n=S(this,Ae))==null||n.call(this,s),this.dispatchEvent(s),T(this,Re,setTimeout(S(this,xt),S(this,Fe)))},xt=new WeakMap,ie.CONNECTING=0,ie.OPEN=1,ie.CLOSED=2,Object.defineProperty(ie,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});function Is(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class pn extends Event{constructor(n,s){super(n);f(this,"data");f(this,"origin");f(this,"lastEventId");f(this,"source");f(this,"ports");this.data=(s==null?void 0:s.data)??null,this.origin=(s==null?void 0:s.origin)??"",this.lastEventId=(s==null?void 0:s.lastEventId)??"",this.source=(s==null?void 0:s.source)??null,this.ports=(s==null?void 0:s.ports)??[]}initMessageEvent(n,s,i,r,o,a,c,u){}}function vs(e,t,n,s){let i=null,r=!1;const o=[],a=d=>{o.push(d),o.length>100&&o.shift(),i&&(i(),i=null)};e(a);const c=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{r=!0,i&&i(),c()}),{next:async()=>{for(;;){if(s()==="closed"||r)return c();const d=o.shift();if(d)return{value:d,done:!1};await new Promise(y=>{i=y})}},return:c,throw(d){return n(a),Promise.reject(d)},[Symbol.asyncIterator](){return this}}}function me(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function Os(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function mn(e){if(!e)return;const t={};for(const[n,s]of Object.entries(e))t[n]={startCursor:s["start-cursor"],endCursor:s["end-cursor"],hasNextPage:s["has-next-page?"],hasPreviousPage:s["has-previous-page?"]};return t}function Es(e,t,n){let s,i=!1;const r=_e(),o=new ie(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{messageEvent:pn,fetch(h,I){return s=null,fetch(h,{...I,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":Ce,"@instantdb/core":Ce}})}).then(O=>(O.ok||(s=Os(O)),O))}}),a=[],c=[],u=h=>{a.push(h)},l=h=>{a.splice(a.indexOf(h),1)},d=h=>{c.push(h)};t&&u(t);let p=null;function y(h){if(!i)for(const I of a)try{I(h)}catch(O){console.error("Error in subscribeQuery callback",O)}}function v(h){var I,O;switch(h.op){case"sse-init":{const V=h["machine-id"],$e=h["session-id"];p={machineId:V,sessionId:$e};break}case"add-query-ok":{y({type:"ok",data:h.result,pageInfo:mn((I=h["result-meta"])==null?void 0:I["page-info"]),sessionInfo:p});break}case"refresh-ok":{h.computations.length&&y({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:mn((O=h.computations[0]["result-meta"])==null?void 0:O["page-info"]),sessionInfo:p});break}case"error":{y({type:"error",error:new ve({body:h,status:h.status}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:p});break}}}return o.onerror=h=>{if(s)s.text().then(I=>{let O={type:void 0,message:I};try{O=JSON.parse(I)}catch{}y({type:"error",error:new ve({status:s.status,body:O}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:p})});else{const I=()=>{y({type:"error",error:new ve({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:p})};if(o.readyState===ie.CLOSED){I();return}setTimeout(()=>{o.readyState!==ie.OPEN&&I()},5e3)}},o.onmessage=h=>{v(JSON.parse(h.data))},{close:()=>{i=!0;for(const h of c)try{h()}catch(I){console.error("Error in onClose callback",I)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return p},get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},[Symbol.asyncIterator]:vs.bind(this,u,d,l,()=>1)}}var fe={};Object.defineProperty(fe,"__esModule",{value:!0});var $s=fe.parseCookie=gn;fe.parse=gn,fe.stringifyCookie=Rs,fe.stringifySetCookie=Ze,fe.serialize=Ze,fe.parseSetCookie=Ps,fe.stringifySetCookie=Ze,fe.serialize=Ze;const yn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,bn=/^[\u0021-\u003A\u003C-\u007E]*$/,ks=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,_s=/^[\u0020-\u003A\u003D-\u007E]*$/,Cs=/^-?\d+$/,xs=Object.prototype.toString,Ts=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function gn(e,t){const n=new Ts,s=e.length;if(s<2)return n;const i=(t==null?void 0:t.decode)||wn;let r=0;do{const o=Rt(e,r,s);if(o===-1)break;const a=Tt(e,r,s);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const c=ye(e,r,o);n[c]===void 0&&(n[c]=i(ye(e,o+1,a))),r=a+1}while(r<s);return n}function Rs(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,s=[];for(const i of Object.keys(e)){const r=e[i];if(r===void 0)continue;if(!yn.test(i))throw new TypeError(`cookie name is invalid: ${i}`);const o=n(r);if(!bn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);s.push(`${i}=${o}`)}return s.join("; ")}function Ze(e,t,n){const s=typeof e=="object"?e:{...n,name:e,value:String(t)},i=typeof t=="object"?t:n,r=(i==null?void 0:i.encode)||encodeURIComponent;if(!yn.test(s.name))throw new TypeError(`argument name is invalid: ${s.name}`);const o=s.value?r(s.value):"";if(!bn.test(o))throw new TypeError(`argument val is invalid: ${s.value}`);let a=s.name+"="+o;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw new TypeError(`option maxAge is invalid: ${s.maxAge}`);a+="; Max-Age="+s.maxAge}if(s.domain){if(!ks.test(s.domain))throw new TypeError(`option domain is invalid: ${s.domain}`);a+="; Domain="+s.domain}if(s.path){if(!_s.test(s.path))throw new TypeError(`option path is invalid: ${s.path}`);a+="; Path="+s.path}if(s.expires){if(!As(s.expires)||!Number.isFinite(s.expires.valueOf()))throw new TypeError(`option expires is invalid: ${s.expires}`);a+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(a+="; HttpOnly"),s.secure&&(a+="; Secure"),s.partitioned&&(a+="; Partitioned"),s.priority)switch(typeof s.priority=="string"?s.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${s.sameSite}`)}return a}function Ps(e,t){const n=(t==null?void 0:t.decode)||wn,s=e.length,i=Tt(e,0,s),r=Rt(e,0,i),o=r===-1?{name:"",value:n(ye(e,0,i))}:{name:ye(e,0,r),value:n(ye(e,r+1,i))};let a=i+1;for(;a<s;){const c=Tt(e,a,s),u=Rt(e,a,c),l=u===-1?ye(e,a,c):ye(e,a,u),d=u===-1?void 0:ye(e,u+1,c);switch(l.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=d;break;case"path":o.path=d;break;case"max-age":d&&Cs.test(d)&&(o.maxAge=Number(d));break;case"expires":if(!d)break;const p=new Date(d);Number.isFinite(p.valueOf())&&(o.expires=p);break;case"priority":if(!d)break;const y=d.toLowerCase();(y==="low"||y==="medium"||y==="high")&&(o.priority=y);break;case"samesite":if(!d)break;const v=d.toLowerCase();(v==="lax"||v==="strict"||v==="none")&&(o.sameSite=v);break}a=c+1}return o}function Tt(e,t,n){const s=e.indexOf(";",t);return s===-1?n:s}function Rt(e,t,n){const s=e.indexOf("=",t);return s<n?s:-1}function ye(e,t,n){let s=t,i=n;do{const r=e.charCodeAt(s);if(r!==32&&r!==9)break}while(++s<i);for(;i>s;){const r=e.charCodeAt(i-1);if(r!==32&&r!==9)break;i--}return e.slice(s,i)}function wn(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function As(e){return xs.call(e)==="[object Date]"}function Ms(e){const t={apiURI:"https://api.instantdb.com"},n={...t,...e};return n.apiURI||(n.apiURI=t.apiURI),n}function js(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function Us(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function A(e,t){Us(e,t);const{adminToken:n,appId:s}=e,i={"content-type":"application/json","app-id":s};return n&&(i.authorization=`Bearer ${n}`),t?js(i,t):i}function Ns(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function Ds(){return Ns()?{cache:"no-store"}:{}}async function Ls(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new ve({status:t.status,body:s}))}catch{return e(new ve({status:t.status,body:{type:void 0,message:n}}))}}async function U(e,t){const n=Ds(),s={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":Ce,"Instant-Core-Version":Ce},i=await fetch(e,{...n,...t,headers:s});if(i.status===200){const r=await i.json();return Promise.resolve(r)}return Ls(r=>Promise.reject(r),i)}function Ws(e){var t,n,kn;return t=class{constructor(r){ee(this,n);f(this,"source");f(this,"url");this.url=r,this.source=te(this,n,kn).call(this,r)}get onopen(){return this.source.onopen}set onopen(r){this.source.onopen=r}get onmessage(){return this.source.onmessage}set onmessage(r){this.source.onmessage=r}get onerror(){return this.source.onerror}set onerror(r){this.source.onerror=r}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,kn=function(r){return new ie(r,{messageEvent:pn,fetch(a,c){return fetch(a,{...c,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":Ce,"@instantdb/core":Ce}})})}})},f(t,"OPEN",ie.OPEN),f(t,"CONNECTING",ie.CONNECTING),f(t,"CLOSED",ie.CLOSED),t}function Fs(e){var n,s;(!e.appId||!R(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(s=e.adminToken)==null?void 0:s.trim(),useDateObjects:e.useDateObjects??!1};return new Pt(t)}function Sn(e){return(Array.isArray(e)?e:[e]).flatMap(Zn)}class zs{constructor(t){f(this,"config");this.config=t}async getPresence(t,n){return(await U(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:A(this.config)})).sessions||{}}}class Vs{constructor(t){f(this,"config");f(this,"generateMagicCode",async t=>U(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));f(this,"sendMagicCode",async t=>U(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t})}));f(this,"verifyMagicCode",async(t,n)=>{const{user:s}=await U(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n})});return s});f(this,"checkMagicCode",async(t,n,s)=>{const i=await U(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({email:t,code:n,...s!=null&&s.extraFields?{"extra-fields":s.extraFields}:{}})});return{user:i.user,created:i.created}});f(this,"verifyToken",async t=>(await U(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);f(this,"getUser",async t=>{const n=Object.entries(t).map(([i,r])=>`${i}=${encodeURIComponent(r)}`).join("&");return(await U(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:A(this.config)})).user});f(this,"deleteUser",async t=>{const n=Object.entries(t).map(([i,r])=>`${i}=${r}`);return(await U(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:A(this.config)})).deleted});f(this,"getUserFromRequest",async(t,n)=>{const s=t.headers.get("cookie")||"",i=$s(s),r="instant_user_"+this.config.appId;if(!i[r])return null;const o=i[r],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await U(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,s=this.config;await U(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:A(s),body:JSON.stringify(n)})}}const In=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Js=e=>e&&typeof e.getReader=="function";class vn{constructor(t,n){f(this,"config");f(this,"impersonationOpts");f(this,"uploadFile",async(t,n,s={})=>{const i={...A(this.config,this.impersonationOpts),path:t};s.contentDisposition&&(i["content-disposition"]=s.contentDisposition),delete i["content-type"],s.contentType&&(i["content-type"]=s.contentType);let r;if(In(n)&&(r="half"),In(n)||Js(n)){if(!s.fileSize)throw new Error("fileSize is required in metadata when uploading streams");i["content-length"]=s.fileSize.toString()}let o={method:"PUT",headers:i,body:n,...r&&{duplex:r}};return U(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,o)});f(this,"delete",async t=>U(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:A(this.config,this.impersonationOpts)}));f(this,"deleteMany",async t=>U(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));f(this,"upload",async(t,n,s={})=>{const{data:i}=await U(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),r={},o=s.contentType;o&&(r["Content-Type"]=o);const{ok:a}=await fetch(i,{method:"PUT",body:n,headers:r});return a});f(this,"list",async()=>{const{data:t}=await U(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:A(this.config)});return t});f(this,"getDownloadUrl",async t=>{const{data:n}=await U(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:A(this.config)});return n});this.config=t,this.impersonationOpts=n}}class Qs{constructor(t){ee(this,je);f(this,"createReadStream",t=>g(this,je).call(this).createReadStream(t));f(this,"createWriteStream",t=>g(this,je).call(this).createWriteStream(t));de(this,je,t)}}je=new WeakMap;function Gs(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const At=class At{constructor(t){ee(this,L);f(this,"config");f(this,"auth");f(this,"storage");f(this,"streams");f(this,"rooms");f(this,"impersonationOpts");ee(this,z,null);ee(this,Ee,0);ee(this,G,null);ee(this,H);f(this,"tx",Xt());f(this,"asUser",t=>{const n=new At({...this.config});return n.impersonationOpts=t,n.storage=new vn(this.config,t),n});f(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||nn(t,this.config.schema);const s=n.fetchOpts||{},i=s.headers||{};return U(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...s,method:"POST",headers:{...i,...A(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});f(this,"transact",t=>(this.config.disableValidation||cs(t,this.config.schema),U(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify({steps:Sn(t),"throw-on-missing-attrs?":!!this.config.schema})})));f(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const s={query:t,"rules-override":n==null?void 0:n.rules,"inference?":(n==null?void 0:n.cardinalityInference)??!!this.config.schema};n!=null&&n.ip&&(s["ip-override"]=n.ip),n!=null&&n.origin&&(s["origin-override"]=n.origin);const i=await U(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(s)});return{result:i.result,checkResults:i["check-results"]}});f(this,"debugTransact",(t,n)=>{const s={steps:Sn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(s["ip-override"]=n.ip),n!=null&&n.origin&&(s["origin-override"]=n.origin),U(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:A(this.config,this.impersonationOpts),body:JSON.stringify(s)})});ee(this,nt,t=>{var n;if(t.target!==g(this,z)){g(this,H).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}g(this,H).info("[socket][open]",t.target.id),de(this,Ee,0),(n=g(this,G))==null||n.onConnectionStatusChange("authenticated")});ee(this,st,t=>{var n;if(t.target!==g(this,z)){g(this,H).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}g(this,H).info("[socket][close]",t.target.id),(n=g(this,G))==null||n.onConnectionStatusChange("closed"),g(this,z)&&(de(this,z,null),te(this,L,Nt).call(this)||(setTimeout(()=>te(this,L,at).call(this),g(this,Ee)),de(this,Ee,Math.min(15e3,Math.max(g(this,Ee),500)*2))))});ee(this,it,t=>{var n;if(t.target!==g(this,z)){g(this,H).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}g(this,H).info("[socket][error]",t.target.id),(n=g(this,G))==null||n.onConnectionStatusChange("closed")});ee(this,rt,t=>{var s,i,r,o,a,c;if(t.target!==g(this,z)){g(this,H).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(g(this,H).info("[receive]",n),n.op){case"start-stream-ok":{(s=g(this,G))==null||s.onStartStreamOk(n);break}case"stream-flushed":{(i=g(this,G))==null||i.onStreamFlushed(n);break}case"append-failed":{(r=g(this,G))==null||r.onAppendFailed(n);break}case"stream-append":{(o=g(this,G))==null||o.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(c=g(this,G))==null||c.onRecieveError(n);break}}break}}te(this,L,Rn).call(this)});this.config=Ms(t),this.auth=new Vs(this.config),this.storage=new vn(this.config,this.impersonationOpts),this.streams=new Qs(te(this,L,Tn).bind(this)),this.rooms=new zs(this.config),de(this,H,Gs(!!this.config.verbose))}subscribeQuery(t,n,s={}){t&&s&&"ruleParams"in s&&(t={$$ruleParams:s.ruleParams,...t}),this.config.disableValidation||nn(t,this.config.schema);const o={...(s.fetchOpts||{}).headers||{},...A(this.config,this.impersonationOpts)},a=!!this.config.schema;return Es(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};z=new WeakMap,Ee=new WeakMap,G=new WeakMap,H=new WeakMap,L=new WeakSet,_n=function(){g(this,z)&&g(this,z).close();const t={...A(this.config,this.impersonationOpts)},n=!!this.config.schema,s=Ws({headers:t,inference:n}),i=new fs(s,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return i.onopen=g(this,nt),i.onmessage=g(this,rt),i.onclose=g(this,st),i.onerror=g(this,it),de(this,z,i),i},at=function(){return g(this,z)||te(this,L,_n).call(this)},Cn=function(t,n){const s=te(this,L,at).call(this);g(this,H).info("[send]",t,n,{isOpen:s.isOpen()}),s.isOpen()&&s.send({"client-event-id":t,...n})},xn=function(){te(this,L,at).call(this);const t=new ps({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,s)=>{te(this,L,Cn).call(this,n,s)},log:g(this,H)});return de(this,G,t),t},Tn=function(){return g(this,G)||te(this,L,xn).call(this)},nt=new WeakMap,st=new WeakMap,it=new WeakMap,Nt=function(){return!g(this,G)||!g(this,G).hasActiveStreams()},Rn=function(){if(g(this,z)&&te(this,L,Nt).call(this)){const t=g(this,z);g(this,H).info("cleaning up unused socket",t.id),de(this,z,null),t.close()}},rt=new WeakMap;let Pt=At;var et={};function tt(e){let t=e;return new TransformStream({transform(n,s){if(!t){s.enqueue(n);return}if(t>n.length){t-=n.length;return}const i=n.slice(t);t=0,s.enqueue(i)}})}function Hs(e){const t=e.appId||et.INSTANT_APP_ID||et.NEXT_PUBLIC_INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set either the INSTANT_APP_ID or NEXT_PUBLIC_INSTANT_APP_ID environment variable.");const n=e.adminToken||et.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const s={appId:t,adminToken:n},i=e.apiURI||et.INSTANT_API_URI;i&&(s.apiURI=i),e.verbose&&(s.verbose=e.verbose);const r=Fs(s);async function o(l,d,p){const y=r.streams.createWriteStream({clientId:l,waitUntil:e.waitUntil??void 0});try{const v=await y.streamId();d().pipeTo(y);const h=r.streams.createReadStream({streamId:v});return p?h.pipeThrough(tt(p)):h}catch{const b=r.streams.createReadStream({clientId:l});return p?b.pipeThrough(tt(p)):b}}async function a(l,d){var y,v,b;const p=r.streams.createReadStream({clientId:l});try{await p.streamId()}catch(h){if(h instanceof B&&((b=(v=(y=h.hint)==null?void 0:y.errors)==null?void 0:v[0])==null?void 0:b.message)==="Stream is missing.")return;throw h}return d?p.pipeThrough(tt(d)):p}async function c(l,d,p){const y=d(),v=r.streams.createWriteStream({clientId:l,waitUntil:e.waitUntil??void 0});await v.streamId(),y.pipeTo(v);const b=r.streams.createReadStream({clientId:l});return p?b.pipeThrough(tt(p)):b}async function u(l){var y;const d=await r.query({$streams:{$:{where:{clientId:l}}}}),p=(y=d==null?void 0:d.$streams)==null?void 0:y[0];return p!=null&&p.done?"DONE":p?!0:null}return{resumableStream:o,resumeExistingStream:a,createNewResumableStream:c,hasExistingStream:u}}E.createResumableStreamContext=Hs,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
1
+ (function($,E){typeof exports=="object"&&typeof module<"u"?E(exports):typeof define=="function"&&define.amd?define(["exports"],E):($=typeof globalThis<"u"?globalThis:$||self,E($.instant={}))})(this,function($){"use strict";var Ir=Object.defineProperty;var Ln=$=>{throw TypeError($)};var vr=($,E,A)=>E in $?Ir($,E,{enumerable:!0,configurable:!0,writable:!0,value:A}):$[E]=A;var d=($,E,A)=>vr($,typeof E!="symbol"?E+"":E,A),Qt=($,E,A)=>E.has($)||Ln("Cannot "+A);var y=($,E,A)=>(Qt($,E,"read from private field"),A?A.call($):E.get($)),L=($,E,A)=>E.has($)?Ln("Cannot add the same private member more than once"):E instanceof WeakSet?E.add($):E.set($,A),B=($,E,A,D)=>(Qt($,E,"write to private field"),D?D.call($,A):E.set($,A),A),j=($,E,A)=>(Qt($,E,"access private method"),A);var G,Ye,Le,Fe,Ze,ne,fe,et,Ce,ze,H,Te,X,Y,z,zn,bt,Vn,Jn,Hn,lt,ht,pt,Gt,Kn,yt;const E=/^(?:[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 A(e){return typeof e=="string"&&E.test(e)}const D=[];for(let e=0;e<256;++e)D.push((e+256).toString(16).slice(1));function qn(e,t=0){return(D[e[t+0]]+D[e[t+1]]+D[e[t+2]]+D[e[t+3]]+"-"+D[e[t+4]]+D[e[t+5]]+"-"+D[e[t+6]]+D[e[t+7]]+"-"+D[e[t+8]]+D[e[t+9]]+"-"+D[e[t+10]]+D[e[t+11]]+D[e[t+12]]+D[e[t+13]]+D[e[t+14]]+D[e[t+15]]).toLowerCase()}let wt;const Bn=new Uint8Array(16);function Qn(){if(!wt){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");wt=crypto.getRandomValues.bind(crypto)}return wt(Bn)}const Xt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Gn(e,t,n){var r;if(Xt.randomUUID&&!e)return Xt.randomUUID();e=e||{};const s=e.random??((r=e.rng)==null?void 0:r.call(e))??Qn();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,qn(s)}const F={Remove:"remove",Replace:"replace",Add:"add"},Yt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),tt=Symbol.iterator,ie={mutable:"mutable",immutable:"immutable"},gt={};function Je(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Zt(e,t){if(t in e){let n=Reflect.getPrototypeOf(e);for(;n;){const s=Reflect.getOwnPropertyDescriptor(n,t);if(s)return s;n=Reflect.getPrototypeOf(n)}}}function en(e){return Object.getPrototypeOf(e)===Set.prototype}function tn(e){return Object.getPrototypeOf(e)===Map.prototype}function te(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function St(e){return!!O(e)}function O(e){return typeof e!="object"?null:e==null?void 0:e[Yt]}function It(e){var t;const n=O(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function ke(e,t){if(!e||typeof e!="object")return!1;let n;return Object.getPrototypeOf(e)===Object.prototype||Array.isArray(e)||e instanceof Map||e instanceof Set||!!(t!=null&&t.mark)&&((n=t.mark(e,ie))===ie.immutable||typeof n=="function")}function nn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,s=O(be(n,e.key));if(s!==null&&(s==null?void 0:s.original)!==e.original)return null;const r=e.parent.type===3,o=r?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(r&&n.size>o||Je(n,o)))return null;t.push(o)}if(e.parent)return nn(e.parent,t);t.reverse();try{Xn(e.copy,t)}catch{return null}return t}function He(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function be(e,t){return He(e)===2?e.get(t):e[t]}function vt(e,t,n){He(e)===2?e.set(t,n):e[t]=n}function kt(e,t){const n=O(e);return(n?te(n):e)[t]}function $e(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function Oe(e,t){return t?e:[""].concat(e).map(n=>{const s=`${n}`;return s.indexOf("/")===-1&&s.indexOf("~")===-1?s:s.replace(/~/g,"~0").replace(/\//g,"~1")}).join("/")}function Xn(e,t){for(let n=0;n<t.length-1;n+=1){const s=t[n];if(e=be(He(e)===3?Array.from(e):e,s),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Yn(e){const t=Object.create(Object.getPrototypeOf(e));return Reflect.ownKeys(e).forEach(n=>{let s=Reflect.getOwnPropertyDescriptor(e,n);if(s.enumerable&&s.configurable&&s.writable){t[n]=e[n];return}s.writable||(s.writable=!0,s.configurable=!0),(s.get||s.set)&&(s={configurable:!0,writable:!0,enumerable:s.enumerable,value:e[n]}),Reflect.defineProperty(t,n,s)}),t}const Zn=Object.prototype.propertyIsEnumerable;function es(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!en(e)){const s=Object.getPrototypeOf(e).constructor;return new s(e.values())}return Set.prototype.difference?Set.prototype.difference.call(e,new Set):new Set(e.values())}else if(e instanceof Map){if(!tn(e)){const s=Object.getPrototypeOf(e).constructor;return new s(e)}return new Map(e)}else if(t!=null&&t.mark&&(n=t.mark(e,ie),n!==void 0)&&n!==ie.mutable){if(n===ie.immutable)return Yn(e);if(typeof n=="function"){if(t.enablePatches||t.enableAutoFreeze)throw new Error("You can't use mark and patches or auto freeze together.");return n()}throw new Error(`Unsupported mark result: ${n}`)}else if(typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype){const s={};return Object.keys(e).forEach(r=>{s[r]=e[r]}),Object.getOwnPropertySymbols(e).forEach(r=>{Zn.call(e,r)&&(s[r]=e[r])}),s}else throw new Error("Please check mark() to ensure that it is a stable marker draftable function.")}function Q(e){e.copy||(e.copy=es(e.original,e.options))}function Ke(e){if(!ke(e))return It(e);if(Array.isArray(e))return e.map(Ke);if(e instanceof Map){const n=Array.from(e.entries()).map(([s,r])=>[s,Ke(r)]);if(!tn(e)){const s=Object.getPrototypeOf(e).constructor;return new s(n)}return new Map(n)}if(e instanceof Set){const n=Array.from(e).map(Ke);if(!en(e)){const s=Object.getPrototypeOf(e).constructor;return new s(n)}return new Set(n)}const t=Object.create(Object.getPrototypeOf(e));for(const n in e)t[n]=Ke(e[n]);return t}function nt(e){return St(e)?Ke(e):e}function de(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&de(e.parent))}function ts(e,t){const n=He(e);if(n===0)Reflect.ownKeys(e).forEach(s=>{t(s,e[s],e)});else if(n===1){let s=0;for(const r of e)t(s,r,e),s+=1}else e.forEach((s,r)=>t(r,s,e))}function sn(e,t,n){if(St(e)||!ke(e,n)||t.has(e)||Object.isFrozen(e))return;const s=e instanceof Set,r=s?new Map:void 0;if(t.add(e),ts(e,(o,i)=>{var a;if(St(i)){const c=O(i);Q(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;vt(s?r:e,o,u)}else sn(i,t,n)}),r){const o=e,i=Array.from(o);o.clear(),i.forEach(a=>{o.add(r.has(a)?r.get(a):a)})}}function ns(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&sn(be(n,t),e.finalities.handledSet,e.options)}function $t(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(It(t))}))}function Ot(e,t,n,s){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&s){const o=nn(e);o&&t(e,o,n,s)}e.finalized=!0}}function Et(e,t,n,s){const r=O(n);r&&(r.callbacks||(r.callbacks=[]),r.callbacks.push((o,i)=>{var a;const c=e.type===3?e.setMap:e.copy;if($e(be(c,t),n)){let u=r.original;r.copy&&(u=r.copy),$t(e),Ot(e,s,o,i),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(u,r.original)),vt(c,t,u)}}),e.options.enableAutoFreeze&&r.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ke(n,e.options)&&e.finalities.draft.push(()=>{const o=e.type===3?e.setMap:e.copy;$e(be(o,t),n)&&ns(e,t)})}function ss(e,t,n,s,r){let{original:o,assignedMap:i,options:a}=e,c=e.copy;c.length<o.length&&([o,c]=[c,o],[n,s]=[s,n]);for(let u=0;u<o.length;u+=1)if(i.get(u.toString())&&c[u]!==o[u]){const l=t.concat([u]),f=Oe(l,r);n.push({op:F.Replace,path:f,value:nt(c[u])}),s.push({op:F.Replace,path:f,value:nt(o[u])})}for(let u=o.length;u<c.length;u+=1){const l=t.concat([u]),f=Oe(l,r);n.push({op:F.Add,path:f,value:nt(c[u])})}if(o.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const l=t.concat(["length"]),f=Oe(l,r);s.push({op:F.Replace,path:f,value:o.length})}else for(let l=c.length;o.length<l;l-=1){const f=t.concat([l-1]),p=Oe(f,r);s.push({op:F.Remove,path:p})}}}function rs({original:e,copy:t,assignedMap:n},s,r,o,i){n.forEach((a,c)=>{const u=be(e,c),l=nt(be(t,c)),f=a?Je(e,c)?F.Replace:F.Add:F.Remove;if($e(u,l)&&f===F.Replace)return;const p=s.concat(c),m=Oe(p,i);r.push(f===F.Remove?{op:f,path:m}:{op:f,path:m,value:l}),o.push(f===F.Add?{op:F.Remove,path:m}:f===F.Remove?{op:F.Add,path:m,value:u}:{op:F.Replace,path:m,value:u})})}function is({original:e,copy:t},n,s,r,o){let i=0;e.forEach(a=>{if(!t.has(a)){const c=n.concat([i]),u=Oe(c,o);s.push({op:F.Remove,path:u,value:a}),r.unshift({op:F.Add,path:u,value:a})}i+=1}),i=0,t.forEach(a=>{if(!e.has(a)){const c=n.concat([i]),u=Oe(c,o);s.push({op:F.Add,path:u,value:a}),r.unshift({op:F.Remove,path:u,value:a})}i+=1})}function qe(e,t,n,s){const{pathAsArray:r=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return rs(e,t,n,s,r);case 1:return ss(e,t,n,s,r);case 3:return is(e,t,n,s,r)}}const st=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!ke(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},_t={get size(){return te(O(this)).size},has(e){return te(O(this)).has(e)},set(e,t){const n=O(this),s=te(n);return(!s.has(e)||!$e(s.get(e),t))&&(Q(n),de(n),n.assignedMap.set(e,!0),n.copy.set(e,t),Et(n,e,t,qe)),this},delete(e){if(!this.has(e))return!1;const t=O(this);return Q(t),de(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=O(this);if(this.size){Q(e),de(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=O(this);te(n).forEach((s,r)=>{e.call(t,this.get(r),r,this)})},get(e){var t,n;const s=O(this),r=te(s).get(e),o=((n=(t=s.options).mark)===null||n===void 0?void 0:n.call(t,r,ie))===ie.mutable;if(s.options.strict&&st(r,s.options,o),o||s.finalized||!ke(r,s.options)||r!==s.original.get(e))return r;const i=gt.createDraft({original:r,parentDraft:s,key:e,finalities:s.finalities,options:s.options});return Q(s),s.copy.set(e,i),i},keys(){return te(O(this)).keys()},values(){const e=this.keys();return{[tt]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[tt]:()=>this.entries(),next:()=>{const t=e.next();if(t.done)return t;const n=this.get(t.value);return{done:!1,value:[t.value,n]}}}},[tt](){return this.entries()}},os=Reflect.ownKeys(_t),rn=(e,t,{isValuesIterator:n})=>()=>{var s,r;const o=t.next();if(o.done)return o;const i=o.value;let a=e.setMap.get(i);const c=O(a),u=((r=(s=e.options).mark)===null||r===void 0?void 0:r.call(s,a,ie))===ie.mutable;if(e.options.strict&&st(i,e.options,u),!u&&!c&&ke(i,e.options)&&!e.finalized&&e.original.has(i)){const l=gt.createDraft({original:i,parentDraft:e,key:i,finalities:e.finalities,options:e.options});e.setMap.set(i,l),a=l}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},rt={get size(){return O(this).setMap.size},has(e){const t=O(this);if(t.setMap.has(e))return!0;Q(t);const n=O(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=O(this);return this.has(e)||(Q(t),de(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),Et(t,e,e,qe)),this},delete(e){if(!this.has(e))return!1;const t=O(this);Q(t),de(t);const n=O(e);return n&&t.setMap.has(n.original)?(t.assignedMap.set(n.original,!1),t.setMap.delete(n.original)):(!n&&t.setMap.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.setMap.delete(e))},clear(){if(!this.size)return;const e=O(this);Q(e),de(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=O(this);Q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:rn(e,t,{isValuesIterator:!0})}},entries(){const e=O(this);Q(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:rn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[tt](){return this.values()},forEach(e,t){const n=this.values();let s=n.next();for(;!s.done;)e.call(t,s.value,s.value,this),s=n.next()}};Set.prototype.difference&&Object.assign(rt,{intersection(e){return Set.prototype.intersection.call(new Set(this.values()),e)},union(e){return Set.prototype.union.call(new Set(this.values()),e)},difference(e){return Set.prototype.difference.call(new Set(this.values()),e)},symmetricDifference(e){return Set.prototype.symmetricDifference.call(new Set(this.values()),e)},isSubsetOf(e){return Set.prototype.isSubsetOf.call(new Set(this.values()),e)},isSupersetOf(e){return Set.prototype.isSupersetOf.call(new Set(this.values()),e)},isDisjointFrom(e){return Set.prototype.isDisjointFrom.call(new Set(this.values()),e)}});const as=Reflect.ownKeys(rt),on=new WeakSet,an={get(e,t,n){var s,r;const o=(s=e.copy)===null||s===void 0?void 0:s[t];if(o&&on.has(o))return o;if(t===Yt)return e;let i;if(e.options.mark){const u=t==="size"&&(e.original instanceof Map||e.original instanceof Set)?Reflect.get(e.original,t):Reflect.get(e.original,t,n);if(i=e.options.mark(u,ie),i===ie.mutable)return e.options.strict&&st(u,e.options,!0),u}const a=te(e);if(a instanceof Map&&os.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(_t,"size").get.call(e.proxy);const u=_t[t];if(u)return u.bind(e.proxy)}if(a instanceof Set&&as.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(rt,"size").get.call(e.proxy);const u=rt[t];if(u)return u.bind(e.proxy)}if(!Je(a,t)){const u=Zt(a,t);return u?"value"in u?u.value:(r=u.get)===null||r===void 0?void 0:r.call(e.proxy):void 0}const c=a[t];if(e.options.strict&&st(c,e.options),e.finalized||!ke(c,e.options))return c;if(c===kt(e.original,t)){if(Q(e),e.copy[t]=cn({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof i=="function"){const u=O(e.copy[t]);return Q(u),de(u),u.copy}return e.copy[t]}return c},set(e,t,n){var s;if(e.type===3||e.type===2)throw new Error("Map/Set draft does not support any property assignment.");let r;if(e.type===1&&t!=="length"&&!(Number.isInteger(r=Number(t))&&r>=0&&(t===0||r===0||String(r)===String(t))))throw new Error("Only supports setting array indices and the 'length' property.");const o=Zt(te(e),t);if(o!=null&&o.set)return o.set.call(e.proxy,n),!0;const i=kt(te(e),t),a=O(i);return a&&$e(a.original,n)?(e.copy[t]=n,e.assignedMap=(s=e.assignedMap)!==null&&s!==void 0?s:new Map,e.assignedMap.set(t,!1),!0):($e(n,i)&&(n!==void 0||Je(e.original,t))||(Q(e),de(e),Je(e.original,t)&&$e(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,Et(e,t,n,qe)),!0)},has(e,t){return t in te(e)},ownKeys(e){return Reflect.ownKeys(te(e))},getOwnPropertyDescriptor(e,t){const n=te(e),s=Reflect.getOwnPropertyDescriptor(n,t);return s&&{writable:!0,configurable:e.type!==1||t!=="length",enumerable:s.enumerable,value:n[t]}},getPrototypeOf(e){return Reflect.getPrototypeOf(e.original)},setPrototypeOf(){throw new Error("Cannot call 'setPrototypeOf()' on drafts")},defineProperty(){throw new Error("Cannot call 'defineProperty()' on drafts")},deleteProperty(e,t){var n;return e.type===1?an.set.call(this,e,t,void 0,e.proxy):(kt(e.original,t)!==void 0||t in e.original?(Q(e),de(e),e.assignedMap.set(t,!1)):(e.assignedMap=(n=e.assignedMap)!==null&&n!==void 0?n:new Map,e.assignedMap.delete(t)),e.copy&&delete e.copy[t],!0)}};function cn(e){const{original:t,parentDraft:n,key:s,finalities:r,options:o}=e,i=He(t),a={type:i,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:r,options:o,setMap:i===3?new Map(t.entries()):void 0};(s||"key"in e)&&(a.key=s);const{proxy:c,revoke:u}=Proxy.revocable(i===1?Object.assign([],a):a,an);if(r.revoke.push(u),on.add(c),a.proxy=c,n){const l=n;l.finalities.draft.push((f,p)=>{var m,g;const w=O(c);let h=l.type===3?l.setMap:l.copy;const v=be(h,s),k=O(v);if(k){let K=k.original;k.operated&&(K=It(v)),$t(k),Ot(k,qe,f,p),l.options.enableAutoFreeze&&(l.options.updatedValues=(m=l.options.updatedValues)!==null&&m!==void 0?m:new WeakMap,l.options.updatedValues.set(K,k.original)),vt(h,s,K)}(g=w.callbacks)===null||g===void 0||g.forEach(K=>{K(f,p)})})}else{const l=O(c);l.finalities.draft.push((f,p)=>{$t(l),Ot(l,qe,f,p)})}return c}gt.createDraft=cn,Object.prototype.constructor.toString();function Ae(){return Gn()}function cs(e,t){return e.localeCompare(t)}function us(){let e=cs;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}us();function fs(){const t={__etype:1,__ops:1,create:1,update:1,link:1,unlink:1,delete:1,merge:1,ruleParams:1};return new Set(Object.keys(t))}const ds=fs();function it(e,t,n){const s={__etype:e,__ops:n};return new Proxy(s,{get:(r,o)=>{if(o==="__ops")return n;if(o==="__etype")return e;if(ds.has(o))return(i,a)=>it(e,t,[...n,a?[o,e,t,i,a]:[o,e,t,i]])}})}function ls(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function un(e){return e.startsWith("lookup__")}function fn(e){const[t,n,...s]=e.split("__");return[n,JSON.parse(s.join("__"))]}function hs(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(r,o)=>it(e,fn(ls(r,o)),[]);if(n==="__etype")return e;const s=n;return un(s)?it(e,fn(s),[]):it(e,s,[])}})}function dn(){return new Proxy({},{get(e,t){return hs(t)}})}dn();function ps(e){return e.__ops}class C extends Error{constructor(n,s,r){super(n);d(this,"hint");d(this,"traceId");this.hint=s,r&&(this.traceId=r);const o=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,o),Error.captureStackTrace&&Error.captureStackTrace(this,C),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class le extends C{constructor(n){var o,i;const s=((o=n.body)==null?void 0:o.message)||`API Error (${n.status})`;super(s,n.body.hint,((i=n.body)==null?void 0:i.traceId)||n.body["trace-id"]);d(this,"body");d(this,"status");const r=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,r),Error.captureStackTrace&&Error.captureStackTrace(this,le),this.name="InstantAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"InstantAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__instantLogging"),window.localStorage.getItem("__devtoolLocalDash"));const Ee="v1.0.31";class he{constructor(t,n,s,r={indexed:!1,unique:!1}){d(this,"valueType");d(this,"required");d(this,"isIndexed");d(this,"config");d(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=s,this.config=r}clientRequired(){return new he(this.valueType,!1,this.isIndexed,this.config)}optional(){return new he(this.valueType,!1,this.isIndexed,this.config)}unique(){return new he(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new he(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class x extends Error{constructor(t,n){const s=n?`At path '${n}': ${t}`:t;super(s),this.name="QueryValidationError"}}const ln=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],ys=e=>e.valueType||"unknown",hn=(e,t,n=!1)=>{if(n||e==null)return!0;switch(t){case"string":return typeof e=="string";case"number":return typeof e=="number"&&!isNaN(e);case"boolean":return typeof e=="boolean";case"date":return e instanceof Date||typeof e=="string"||typeof e=="number";default:return!0}},ms=(e,t,n,s,r,o,i)=>{const a=o.valueType==="json",c=(u,l,f)=>{if(!hn(f,l,a))throw new x(`Invalid value for operator '${u}' on attribute '${s}' in entity '${r}'. Expected ${l}, but received: ${typeof f}`,i)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new x(`Operator '${e}' for attribute '${s}' in entity '${r}' must be an array, but received: ${typeof t}`,i);for(const u of t)c(e,n,u);break;case"$not":case"$ne":case"$gt":case"$lt":case"$gte":case"$lte":c(e,n,t);break;case"$like":case"$ilike":if(c(e,"string",t),e==="$ilike"&&!o.isIndexed)throw new x(`Operator '${e}' can only be used with indexed attributes, but '${s}' in entity '${r}' is not indexed`,i);break;case"$isNull":c(e,"boolean",t);break;default:throw new x(`Unknown operator '${e}' for attribute '${s}' in entity '${r}'`,i)}},Pe=(e,t,n,s,r)=>{const o=ys(n),i=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(i)return;const c=e;for(const[u,l]of Object.entries(c))ms(u,l,o,t,s,n,`${r}.${u}`)}else if(!hn(e,o,i))throw new x(`Invalid value for attribute '${t}' in entity '${s}'. Expected ${o}, but received: ${typeof e}`,r)},bs=(e,t,n,s,r)=>{const o=e.split(".");if(o.length<2)throw new x(`Invalid dot notation path '${e}'. Must contain at least one dot.`,r);let i=n;for(let l=0;l<o.length-1;l++){const f=o[l],p=s.entities[i];if(!p)throw new x(`Entity '${i}' does not exist in schema while traversing dot notation path '${e}'.`,r);const m=p.links[f];if(!m){const g=Object.keys(p.links);throw new x(`Link '${f}' does not exist on entity '${i}' in dot notation path '${e}'. Available links: ${g.length>0?g.join(", "):"none"}`,r)}i=m.entityName}const a=o[o.length-1],c=s.entities[i];if(!c)throw new x(`Target entity '${i}' does not exist in schema for dot notation path '${e}'.`,r);if(a==="id"){if(typeof t=="string"&&!A(t))throw new x(`Invalid value for id field in entity '${i}'. Expected a UUID, but received: ${t}`,r);Pe(t,e,new he("string",!1,!0),n,r);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof t=="string"&&!A(t))throw new x(`Invalid value for link '${a}' in entity '${i}'. Expected a UUID, but received: ${t}`,r);Pe(t,e,new he("string",!1,!0),n,r);return}if(!u){const l=Object.keys(c.attrs);throw new x(`Attribute '${a}' does not exist on entity '${i}' in dot notation path '${e}'. Available attributes: ${l.length>0?l.join(", ")+", id":"id"}`,r)}Pe(t,e,u,n,r)},pn=(e,t,n,s)=>{for(const[r,o]of Object.entries(e)){if(r==="or"||r==="and"){if(Array.isArray(o))for(const u of o)typeof u=="object"&&u!==null&&pn(u,t,n,`${s}.${r}[${u}]`);continue}if(r==="id"){Pe(o,"id",new he("string",!1,!0),t,`${s}.id`);continue}if(r.includes(".")){bs(r,o,t,n,`${s}.${r}`);continue}const i=n.entities[t];if(!i)continue;const a=i.attrs[r],c=i.links[r];if(!a&&!c){const u=Object.keys(i.attrs),l=Object.keys(i.links);throw new x(`Attribute or link '${r}' does not exist on entity '${t}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${l.length>0?l.join(", "):"none"}`,`${s}.${r}`)}if(a)Pe(o,r,a,t,`${s}.${r}`);else if(c){if(typeof o=="string"&&!A(o))throw new x(`Invalid value for link '${r}' in entity '${t}'. Expected a UUID, but received: ${o}`,`${s}.${r}`);const u=new he("string",!1,!0);Pe(o,r,u,t,`${s}.${r}`)}}},ws=(e,t,n,s,r=0)=>{for(const i of Object.keys(e))if(!ln.includes(i))throw new x(`Invalid query parameter '${i}' in $ object. Valid parameters are: ${ln.join(", ")}. Found: ${i}`,s);const o=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const i of o)if(e[i]!==void 0&&r>0)throw new x(`'${i}' can only be used on top-level namespaces. It cannot be used in nested queries.`,s);if(e.where&&n){if(typeof e.where!="object"||e.where===null)throw new x(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,s?`${s}.where`:void 0);pn(e.where,t,n,s?`${s}.where`:"where")}},yn=(e,t,n,s,r=0)=>{var o;if(!e||typeof e!="object")throw new x(`Query part for entity '${t}' must be an object, but received: ${typeof e}`,s);for(const i of Object.keys(e))if(i!=="$"){if(n&&!(i in n.entities[t].links)){const c=Object.keys(n.entities[t].links);throw new x(`Link '${i}' does not exist on entity '${t}'. Available links: ${c.length>0?c.join(", "):"none"}`,`${s}.${i}`)}const a=e[i];if(typeof a=="object"&&a!==null){const c=(o=n==null?void 0:n.entities[t].links[i])==null?void 0:o.entityName;c&&yn(a,c,n,`${s}.${i}`,r+1)}}else{const a=e[i];if(typeof a!="object"||a===null)throw new x(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${s}.$`);ws(a,t,n,`${s}.$`,r)}},mn=(e,t)=>{if(typeof e!="object"||e===null)throw new x(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new x(`Query must be an object, but received: ${typeof e}`);const n=e;for(const s of Object.keys(n)){if(Array.isArray(e[s]))throw new x(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(typeof s!="string")throw new x(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(s!=="$$ruleParams"){if(t&&!t.entities[s]){const r=Object.keys(t.entities);throw new x(`Entity '${s}' does not exist in schema. Available entities: ${r.length>0?r.join(", "):"none"}`,s)}yn(n[s],s,t,s,0)}}},bn=e=>typeof e!="string"?!1:un(e)?!0:A(e);class se extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const wn=e=>e.length>0?e.join(", "):"none",gs=(e,t)=>new se(`Entity '${e}' does not exist in schema. Available entities: ${wn(t)}`),Ct={string:e=>typeof e=="string",number:e=>typeof e=="number"&&!isNaN(e),boolean:e=>typeof e=="boolean",date:e=>e instanceof Date||typeof e=="string"||typeof e=="number",json:()=>!0},Ss=(e,t)=>{var n;return e==null?!0:((n=Ct[t.valueType])==null?void 0:n.call(Ct,e))??!1},gn=(e,t)=>{const n=t.entities[e];if(!n)throw gs(e,Object.keys(t.entities));return n},Tt=(e,t,n)=>{const s=gn(e,n);if(typeof t!="object"||t===null)throw new se(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[r,o]of Object.entries(t)){if(r==="id")continue;const i=s.attrs[r];if(i&&!Ss(o,i))throw new se(`Invalid value for attribute '${r}' in entity '${e}'. Expected ${i.valueType}, but received: ${typeof o}`)}},Sn=(e,t,n)=>{const s=gn(e,n);if(typeof t!="object"||t===null)throw new se(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[r,o]of Object.entries(t)){if(!s.links[r]){const a=Object.keys(s.links);throw new se(`Link '${r}' does not exist on entity '${e}'. Available links: ${wn(a)}`)}if(o!=null){if(Array.isArray(o)){for(const a of o)if(!bn(a))throw new se(`Invalid entity ID in link '${r}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!bn(o))throw new se(`Invalid UUID in link '${r}' for entity '${e}'. Expected a UUID, but received: ${o}`)}}},Is={create:Tt,update:Tt,merge:Tt,link:Sn,unlink:Sn,delete:()=>{}},vs=(e,t)=>{if(!t)return;const[n,s,r,o]=e;if(!Array.isArray(r)&&!A(r))throw new se(`Invalid id for entity '${s}'. Expected a UUID, but received: ${r}`);if(typeof s!="string")throw new se(`Entity name must be a string, but received: ${typeof s}`);const i=Is[n];i&&o!==void 0&&i(s,o,t)},ks=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const s of n){if(!s||typeof s!="object")throw new se(`Transaction chunk must be an object, but received: ${typeof s}`);if(!Array.isArray(s.__ops))throw new se(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);for(const r of s.__ops){if(!Array.isArray(r))throw new se(`Transaction operation must be an array, but received: ${typeof r}`);vs(r,t)}}};let $s=0;class Os{constructor(t,n,s){d(this,"type","sse");d(this,"initParams",null);d(this,"sendQueue",[]);d(this,"sendPromise");d(this,"closeFired",!1);d(this,"sseInitTimeout");d(this,"ES");d(this,"messageUrl");d(this,"conn");d(this,"url");d(this,"id");d(this,"onopen");d(this,"onmessage");d(this,"onclose");d(this,"onerror");this.id=`${this.type}_${$s++}`,this.url=n,this.messageUrl=s||this.url,this.ES=t,this.conn=new t(n),this.sseInitTimeout=setTimeout(()=>{this.initParams||this.handleError()},1e4),this.conn.onmessage=r=>{const o=JSON.parse(r.data);if(Array.isArray(o))for(const i of o)this.handleMessage(i);else this.handleMessage(o)},this.conn.onerror=r=>{this.handleError()}}handleMessage(t){if(t.op==="sse-init"){this.initParams={machineId:t["machine-id"],sessionId:t["session-id"],sseToken:t["sse-token"]},this.onopen&&this.onopen({target:this}),clearTimeout(this.sseInitTimeout);return}this.onmessage&&this.onmessage({target:this,message:t})}handleError(){try{this.onerror&&this.onerror({target:this})}finally{this.handleClose()}}handleClose(){this.conn.close(),this.onclose&&!this.closeFired&&(this.closeFired=!0,this.onclose({target:this}))}async postMessages(t){var n,s,r;try{(await fetch(this.messageUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({machine_id:(n=this.initParams)==null?void 0:n.machineId,session_id:(s=this.initParams)==null?void 0:s.sessionId,sse_token:(r=this.initParams)==null?void 0:r.sseToken,messages:t})})).ok||this.handleError()}catch{this.handleError()}}async flushQueue(){if(this.sendPromise||!this.sendQueue.length)return;const t=this.sendQueue;this.sendQueue=[];const n=this.postMessages(t);this.sendPromise=n,n.then(()=>{this.sendPromise=null,this.flushQueue()})}send(t){if(!this.isOpen()||!this.initParams)throw this.isConnecting()?new Error("Failed to execute 'send' on 'EventSource': Still in CONNECTING state."):this.conn.readyState===this.ES.CLOSED?new Error("EventSource is already in CLOSING or CLOSED state."):new Error("EventSource is in invalid state.");this.sendQueue.push(t),this.flushQueue()}isOpen(){return this.conn.readyState===this.ES.OPEN&&this.initParams!==null}isConnecting(){return this.conn.readyState===this.ES.CONNECTING||this.conn.readyState===this.ES.OPEN&&this.initParams===null}close(){this.handleClose()}}var In;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(In||(In={}));function Es({WStream:e,opts:t,startStream:n,appendStream:s,registerStream:r}){const o=t.clientId;let i=null,a=null,c=null;const u=Ae();let l=!1,f=!1;const p=[],m=[],g=[];let w=!1,h=0,v=0;const k=[],K=new TextEncoder;function xe(){f=!0;for(const b of p)b(a??void 0)}function qt(b){return p.push(b),f&&b(a??void 0),()=>{const S=p.indexOf(b);S!==-1&&p.splice(S,1)}}function Nn(b){return g.push(b),()=>{const S=g.indexOf(b);S!==-1&&g.splice(S,1)}}t.waitUntil&&t.waitUntil(new Promise(b=>{g.push(b)}));function P(){for(const b of g)try{b()}catch{}}function _(b){return m.push(b),i&&b(i),()=>{const S=m.indexOf(b);S!==-1&&m.splice(S,1)}}function ce(b){i=b;for(const S of m)S(i)}function T(){w=!0}function V(b){let S=h,J=0,ee=0;for(const{byteLen:ue}of k){const me=S+ue;if(me>b)break;S=me,J++,ee+=ue}J>0&&(h+=ee,v-=ee,k.splice(0,J))}function W(b,S){a=S,xe(),b.error(S),P()}async function re(){const b=await n({clientId:o,reconnectToken:u,ruleParams:t.ruleParams});switch(b.type){case"ok":{const{streamId:S,offset:J}=b;i=S,V(J),k.length&&s({streamId:S,chunks:k.map(ee=>ee.chunk),offset:h}),w=!1;break}case"disconnect":{T();break}case"error":{c&&W(c,b.error);break}}}function q(){T(),re()}function mt({offset:b,done:S}){V(b),S&&(l=!0,P())}function Wn(b){return l?(W(b,new C("Stream has been closed.")),null):i||(W(b,new C("Stream has not been initialized.")),null)}async function Ve(b){c=b;let S=!0,J=0;for(;S;){let ee=Date.now()+Math.min(15e3,500*(J-1));S=!1;const ue=await n({clientId:t.clientId,reconnectToken:u,ruleParams:t.ruleParams});switch(ue.type){case"ok":{const{streamId:me,offset:Bt}=ue;if(Bt!==0){const Re=new C("Write stream is corrupted");W(b,Re);return}ce(me),r(me,{onDisconnect:T,onFlush:mt,onConnectionReconnect:re,onAppendFailed:q}),w=!1;return}case"disconnect":{S=!0,T(),J++,await new Promise(me=>{setTimeout(me,Math.max(0,ee-Date.now()))});break}case"error":{W(b,ue.error);return}}}}class Ie extends e{constructor(S,J){super(S,J)}async streamId(){return i||new Promise((S,J)=>{const ee=[],ue=()=>{for(const Re of ee)Re()},me=Re=>{S(Re),ue()},Bt=Re=>{J(Re||new C("Stream is closed.")),ue()};ee.push(_(me)),ee.push(qt(Bt))})}}return{stream:new Ie({async start(b){try{await Ve(b)}catch(S){W(b,S)}},write(b,S){const J=Wn(S);if(J){const ee=K.encode(b).length;k.push({chunk:b,byteLen:ee});const ue=h+v;v+=ee,w||s({streamId:J,chunks:[b],offset:ue})}},close(){i?s({streamId:i,chunks:[],offset:h+v,isDone:!0}):P(),xe()},abort(b){i?s({streamId:i,chunks:[],offset:h+v,isDone:!0,abortReason:b}):P(),xe()}}),addCompleteCb:Nn,closed(){return f}}}class _s{constructor(){d(this,"items",[]);d(this,"resolvers",[]);d(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(s=>{this.resolvers.push(s)});if(n||!t)return;yield t}}}}function Cs({RStream:e,opts:t,startStream:n,cancelStream:s}){let r=t.byteOffset||0,o=!1;const i=new TextDecoder("utf-8"),a=new TextEncoder;let c,u=!1;const l=[],f=[];let p=null,m=null;function g(P){u=!0;for(const _ of l)_(P)}function w(P){return l.push(P),()=>{const _=l.indexOf(P);_!==-1&&l.splice(_,1)}}function h(P){return f.push(P),p&&P(p),()=>{const _=f.indexOf(P);_!==-1&&f.splice(_,1)}}function v(P,_){m=_,P.error(_),g(_)}let k=0;async function K(P,_){c=Ae();const ce={...P||{},eventId:c};for await(const T of n(ce)){if(o)return;if(T.type==="reconnect")return{retry:!0};if(T.type==="error"){v(_,T.error);return}if(T.offset>r){v(_,new C("Stream is corrupted.")),o=!0;return}p=T.streamId;for(const W of f)W(p);let V=r-T.offset;if(T.files&&T.files.length){const W=new AbortController;let re=fetch(T.files[0].url,{signal:W.signal});for(let q=0;q<T.files.length;q++){const mt=T.files[q+1],Ve=await re;if(mt&&(re=fetch(mt.url,{signal:W.signal})),!Ve.ok){if(k++,k>10){v(_,new C("Unable to process stream."));return}return{retry:!0}}if(Ve.body){const Ie=Ve.body.getReader();try{for(;;){const{done:ve,value:b}=await Ie.read();if(ve)break;if(o){W.abort();return}let S=b;if(V>0&&(S=b.subarray(V),V-=b.length-S.length),!S.length)continue;r+=S.length;const J=i.decode(S);_.enqueue(J)}}finally{Ie.releaseLock()}}else{const Ie=await Ve.arrayBuffer();let ve=Ie;if(o){W.abort();return}if(V>0&&(ve=new Uint8Array(Ie).subarray(V),V-=Ie.byteLength-ve.length),!ve.byteLength)continue;r+=ve.byteLength;const b=i.decode(ve);_.enqueue(b)}}}if(k=0,T.content){let W=T.content,re=a.encode(T.content);if(V>0){const q=re.subarray(V);if(V-=re.length-q.length,!q.length)continue;re=q,W=i.decode(q)}r+=re.length,_.enqueue(W)}}}async function xe(P){let _=!0,ce=0;for(;_;){_=!1;let T=Date.now()+Math.min(15e3,500*(ce-1));const V=await K({...t,offset:r},P);V!=null&&V.retry&&(_=!0,ce++,T<Date.now()-3e5&&(ce=0),await new Promise(W=>{setTimeout(W,Math.max(0,T-Date.now()))}))}!o&&!u&&(P.close(),g())}class qt extends e{constructor(_,ce){super(_,ce)}async streamId(){if(p)return p;if(m)throw m;return new Promise((_,ce)=>{const T=[],V=()=>{for(const q of T)q()},W=q=>{_(q),V()},re=q=>{ce(q||new C("Stream is closed.")),V()};T.push(h(W)),T.push(w(re))})}}return{stream:new qt({start(P){xe(P)},cancel(P){o=!0,c&&s({eventId:c}),g()}}),addCloseCb:w,closed(){return u}}}class Ts{constructor({WStream:t,RStream:n,trySend:s,log:r}){d(this,"trySend");d(this,"WStream");d(this,"RStream");d(this,"writeStreams",{});d(this,"startWriteStreamCbs",{});d(this,"readStreamIterators",{});d(this,"log");d(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=s,this.log=r}createWriteStream(t){const{stream:n,addCompleteCb:s}=Es({WStream:this.WStream,startStream:this.startWriteStream.bind(this),appendStream:this.appendStream.bind(this),registerStream:this.registerWriteStream.bind(this),opts:t});return this.activeStreams.add(n),s(()=>{this.activeStreams.delete(n)}),n}createReadStream(t){const{stream:n,addCloseCb:s}=Cs({RStream:this.RStream,opts:t,startStream:this.startReadStream.bind(this),cancelStream:this.cancelReadStream.bind(this)});return this.activeStreams.add(n),s(()=>{this.activeStreams.delete(n)}),n}startWriteStream(t){const n=Ae();let s=null;const r=new Promise(i=>{s=i});this.startWriteStreamCbs[n]=s;const o={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(o["rule-params"]=t.ruleParams),this.trySend(n,o),r}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:s,offset:r,abortReason:o}){const i={op:"append-stream","stream-id":t,chunks:n,offset:r,done:!!s};o&&(i["abort-reason"]=o),this.trySend(Ae(),i)}onAppendFailed(t){const n=this.writeStreams[t["stream-id"]];n&&n.onAppendFailed()}onStartStreamOk(t){const n=this.startWriteStreamCbs[t["client-event-id"]];if(!n){this.log.info("No stream for start-stream-ok",t);return}n({type:"ok",streamId:t["stream-id"],offset:t.offset}),delete this.startWriteStreamCbs[t["client-event-id"]]}onStreamFlushed(t){const n=t["stream-id"],s=this.writeStreams[n];if(!s){this.log.info("No stream cbs for stream-flushed",t);return}s.onFlush({offset:t.offset,done:t.done}),t.done&&delete this.writeStreams[n]}startReadStream({eventId:t,clientId:n,streamId:s,offset:r,ruleParams:o}){const i={op:"subscribe-stream"};if(!s&&!n)throw new Error("Must provide one of streamId or clientId to subscribe to the stream.");s&&(i["stream-id"]=s),n&&(i["client-id"]=n),r&&(i.offset=r),o&&(i["rule-params"]=o);const a=new _s;return this.readStreamIterators[t]=a,this.trySend(t,i),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(Ae(),n),delete this.readStreamIterators[t]}onStreamAppend(t){const n=t["client-event-id"],s=this.readStreamIterators[n];if(!s){this.log.info("No iterator for read stream",t);return}if(t.error){t.retry?s.push({type:"reconnect"}):s.push({type:"error",error:new C(t.error)}),s.close(),delete this.readStreamIterators[n];return}s.push({type:"append",offset:t.offset,files:t.files,content:t.content,streamId:t["stream-id"]}),t.done&&(s.close(),delete this.readStreamIterators[n])}onConnectionStatusChange(t){for(const n of Object.values(this.startWriteStreamCbs))n({type:"disconnect"});if(this.startWriteStreamCbs={},t!==xs.AUTHENTICATED)for(const{onDisconnect:n}of Object.values(this.writeStreams))n();else{for(const{onConnectionReconnect:n}of Object.values(this.writeStreams))n();for(const n of Object.values(this.readStreamIterators))n.push({type:"reconnect"}),n.close();this.readStreamIterators={}}}onRecieveError(t){const n=t["original-event"];switch(n.op){case"append-stream":{const s=n["stream-id"],r=this.writeStreams[s];r==null||r.onAppendFailed();break}case"start-stream":{const s=t["client-event-id"],r=this.startWriteStreamCbs[s];r&&(r({type:"error",error:new C(t.message||"Unknown error",t.hint)}),delete this.startWriteStreamCbs[s]);break}case"subscribe-stream":{const s=t["client-event-id"],r=this.readStreamIterators[s];r&&(r.push({type:"error",error:new C(t.message||"Unknown error",t.hint)}),r.close(),delete this.readStreamIterators[s]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const xs={AUTHENTICATED:"authenticated"};function Rs(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function As(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}As(),Rs();class vn extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function xt(e){}function Ps(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=xt,onError:n=xt,onRetry:s=xt,onComment:r}=e;let o="",i=!0,a,c="",u="";function l(w){const h=i?w.replace(/^\xEF\xBB\xBF/,""):w,[v,k]=js(`${o}${h}`);for(const K of v)f(K);o=k,i=!1}function f(w){if(w===""){m();return}if(w.startsWith(":")){r&&r(w.slice(w.startsWith(": ")?2:1));return}const h=w.indexOf(":");if(h!==-1){const v=w.slice(0,h),k=w[h+1]===" "?2:1,K=w.slice(h+k);p(v,K,w);return}p(w,"",w)}function p(w,h,v){switch(w){case"event":u=h;break;case"data":c=`${c}${h}
2
+ `;break;case"id":a=h.includes("\0")?void 0:h;break;case"retry":/^\d+$/.test(h)?s(parseInt(h,10)):n(new vn(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:v}));break;default:n(new vn(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:h,line:v}));break}}function m(){c.length>0&&t({id:a,event:u||void 0,data:c.endsWith(`
3
+ `)?c.slice(0,-1):c}),a=void 0,c="",u=""}function g(w={}){o&&w.consume&&f(o),i=!0,a=void 0,c="",u="",o=""}return{feed:l,reset:g}}function js(e){const t=[];let n="",s=0;for(;s<e.length;){const r=e.indexOf("\r",s),o=e.indexOf(`
4
+ `,s);let i=-1;if(r!==-1&&o!==-1?i=Math.min(r,o):r!==-1?r===e.length-1?i=-1:i=r:o!==-1&&(i=o),i===-1){n=e.slice(s);break}else{const a=e.slice(s,i);t.push(a),s=i+1,e[s-1]==="\r"&&e[s]===`
5
+ `&&s++}}return[t,n]}class kn extends Event{constructor(t,n){var s,r;super(t),this.code=(s=n==null?void 0:n.code)!=null?s:void 0,this.message=(r=n==null?void 0:n.message)!=null?r:void 0}[Symbol.for("nodejs.util.inspect.custom")](t,n,s){return s($n(this),n)}[Symbol.for("Deno.customInspect")](t,n){return t($n(this),n)}}function Ms(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Rt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Rt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Rt(e.cause)}`:e.message:`${e}`}function $n(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}var On=e=>{throw TypeError(e)},At=(e,t,n)=>t.has(e)||On("Cannot "+n),I=(e,t,n)=>(At(e,t,"read from private field"),n?n.call(e):t.get(e)),N=(e,t,n)=>t.has(e)?On("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,n),R=(e,t,n,s)=>(At(e,t,"write to private field"),t.set(e,n),n),pe=(e,t,n)=>(At(e,t,"access private method"),n),Z,_e,je,ot,at,ct,Be,Me,Qe,we,Ue,De,Ne,Ge,oe,Pt,jt,Mt,En,Ut,Dt,Xe,Nt,Wt;class ae extends EventTarget{constructor(t,n){var s,r,o;super(),N(this,oe),this.CONNECTING=0,this.OPEN=1,this.CLOSED=2,N(this,Z),N(this,_e),N(this,je),N(this,ot),N(this,at),N(this,ct),N(this,Be),N(this,Me),N(this,Qe,null),N(this,we),N(this,Ue),N(this,De,null),N(this,Ne,null),N(this,Ge,null),N(this,jt,async i=>{var a;I(this,Ue).reset();const{body:c,redirected:u,status:l,headers:f}=i;if(l===204){pe(this,oe,Xe).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(u?R(this,je,new URL(i.url)):R(this,je,void 0),l!==200){pe(this,oe,Xe).call(this,`Non-200 status code (${l})`,l);return}if(!(f.get("content-type")||"").startsWith("text/event-stream")){pe(this,oe,Xe).call(this,'Invalid content type, expected "text/event-stream"',l);return}if(I(this,Z)===this.CLOSED)return;R(this,Z,this.OPEN);const p=new Event("open");if((a=I(this,Ge))==null||a.call(this,p),this.dispatchEvent(p),typeof c!="object"||!c||!("getReader"in c)){pe(this,oe,Xe).call(this,"Invalid response body, expected a web ReadableStream",l),this.close();return}const m=new TextDecoder,g=c.getReader();let w=!0;do{const{done:h,value:v}=await g.read();v&&I(this,Ue).feed(m.decode(v,{stream:!h})),h&&(w=!1,I(this,Ue).reset(),pe(this,oe,Nt).call(this))}while(w)}),N(this,Mt,i=>{R(this,we,void 0),!(i.name==="AbortError"||i.type==="aborted")&&pe(this,oe,Nt).call(this,Rt(i))}),N(this,Ut,i=>{typeof i.id=="string"&&R(this,Qe,i.id);const a=new(I(this,ct))(i.event||"message",{data:i.data,origin:I(this,je)?I(this,je).origin:I(this,_e).origin,lastEventId:i.id||""});I(this,Ne)&&(!i.event||i.event==="message")&&I(this,Ne).call(this,a),this.dispatchEvent(a)}),N(this,Dt,i=>{R(this,Be,i)}),N(this,Wt,()=>{R(this,Me,void 0),I(this,Z)===this.CONNECTING&&pe(this,oe,Pt).call(this)});try{if(t instanceof URL)R(this,_e,t);else if(typeof t=="string")R(this,_e,new URL(t,Us()));else throw new Error("Invalid URL")}catch{throw Ms("An invalid or illegal string was specified")}R(this,Ue,Ps({onEvent:I(this,Ut),onRetry:I(this,Dt)})),R(this,Z,this.CONNECTING),R(this,Be,3e3),R(this,at,(s=n==null?void 0:n.fetch)!=null?s:globalThis.fetch),R(this,ct,(r=n==null?void 0:n.messageEvent)!=null?r:globalThis.MessageEvent),R(this,ot,(o=n==null?void 0:n.withCredentials)!=null?o:!1),pe(this,oe,Pt).call(this)}get readyState(){return I(this,Z)}get url(){return I(this,_e).href}get withCredentials(){return I(this,ot)}get onerror(){return I(this,De)}set onerror(t){R(this,De,t)}get onmessage(){return I(this,Ne)}set onmessage(t){R(this,Ne,t)}get onopen(){return I(this,Ge)}set onopen(t){R(this,Ge,t)}addEventListener(t,n,s){const r=n;super.addEventListener(t,r,s)}removeEventListener(t,n,s){const r=n;super.removeEventListener(t,r,s)}close(){I(this,Me)&&clearTimeout(I(this,Me)),I(this,Z)!==this.CLOSED&&(I(this,we)&&I(this,we).abort(),R(this,Z,this.CLOSED),R(this,we,void 0))}}Z=new WeakMap,_e=new WeakMap,je=new WeakMap,ot=new WeakMap,at=new WeakMap,ct=new WeakMap,Be=new WeakMap,Me=new WeakMap,Qe=new WeakMap,we=new WeakMap,Ue=new WeakMap,De=new WeakMap,Ne=new WeakMap,Ge=new WeakMap,oe=new WeakSet,Pt=function(){R(this,Z,this.CONNECTING),R(this,we,new AbortController),I(this,at)(I(this,_e),pe(this,oe,En).call(this)).then(I(this,jt)).catch(I(this,Mt))},jt=new WeakMap,Mt=new WeakMap,En=function(){var e;const t={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...I(this,Qe)?{"Last-Event-ID":I(this,Qe)}:void 0},cache:"no-store",signal:(e=I(this,we))==null?void 0:e.signal};return"window"in globalThis&&(t.credentials=this.withCredentials?"include":"same-origin"),t},Ut=new WeakMap,Dt=new WeakMap,Xe=function(e,t){var n;I(this,Z)!==this.CLOSED&&R(this,Z,this.CLOSED);const s=new kn("error",{code:t,message:e});(n=I(this,De))==null||n.call(this,s),this.dispatchEvent(s)},Nt=function(e,t){var n;if(I(this,Z)===this.CLOSED)return;R(this,Z,this.CONNECTING);const s=new kn("error",{code:t,message:e});(n=I(this,De))==null||n.call(this,s),this.dispatchEvent(s),R(this,Me,setTimeout(I(this,Wt),I(this,Be)))},Wt=new WeakMap,ae.CONNECTING=0,ae.OPEN=1,ae.CLOSED=2,Object.defineProperty(ae,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});function Us(){const e="document"in globalThis?globalThis.document:void 0;return e&&typeof e=="object"&&"baseURI"in e&&typeof e.baseURI=="string"?e.baseURI:void 0}class _n extends Event{constructor(n,s){super(n);d(this,"data");d(this,"origin");d(this,"lastEventId");d(this,"source");d(this,"ports");this.data=(s==null?void 0:s.data)??null,this.origin=(s==null?void 0:s.origin)??"",this.lastEventId=(s==null?void 0:s.lastEventId)??"",this.source=(s==null?void 0:s.source)??null,this.ports=(s==null?void 0:s.ports)??[]}initMessageEvent(n,s,r,o,i,a,c,u){}}function Ds(e,t,n,s){let r=null,o=!1;const i=[],a=f=>{i.push(f),i.length>100&&i.shift(),r&&(r(),r=null)};e(a);const c=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{o=!0,r&&r(),c()}),{next:async()=>{for(;;){if(s()==="closed"||o)return c();const f=i.shift();if(f)return{value:f,done:!1};await new Promise(m=>{r=m})}},return:c,throw(f){return n(a),Promise.reject(f)},[Symbol.asyncIterator](){return this}}}function ge(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function Ns(e){let t=null;return{...e,text(){return t||(t=e.text()),t},json(){return t||(t=e.text()),t.then(n=>JSON.parse(n))}}}function Cn(e){if(!e)return;const t={};for(const[n,s]of Object.entries(e))t[n]={startCursor:s["start-cursor"],endCursor:s["end-cursor"],hasNextPage:s["has-next-page?"],hasPreviousPage:s["has-previous-page?"]};return t}function Ws(e,t,n){let s,r=!1;const o=Ae(),i=new ae(`${n.apiURI}/admin/subscribe-query?local_connection_id=${o}`,{messageEvent:_n,fetch(h,v){return s=null,fetch(h,{...v,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":Ee,"@instantdb/core":Ee}})}).then(k=>(k.ok||(s=Ns(k)),k))}}),a=[],c=[],u=h=>{a.push(h)},l=h=>{a.splice(a.indexOf(h),1)},f=h=>{c.push(h)};t&&u(t);let p=null;function m(h){if(!r)for(const v of a)try{v(h)}catch(k){console.error("Error in subscribeQuery callback",k)}}function g(h){var v,k;switch(h.op){case"sse-init":{const K=h["machine-id"],xe=h["session-id"];p={machineId:K,sessionId:xe};break}case"add-query-ok":{m({type:"ok",data:h.result,pageInfo:Cn((v=h["result-meta"])==null?void 0:v["page-info"]),sessionInfo:p});break}case"refresh-ok":{h.computations.length&&m({type:"ok",data:h.computations[0]["instaql-result"],pageInfo:Cn((k=h.computations[0]["result-meta"])==null?void 0:k["page-info"]),sessionInfo:p});break}case"error":{m({type:"error",error:new le({body:h,status:h.status}),get readyState(){return ge(i)},get isClosed(){return ge(i)==="closed"},sessionInfo:p});break}}}return i.onerror=h=>{if(s)s.text().then(v=>{let k={type:void 0,message:v};try{k=JSON.parse(v)}catch{}m({type:"error",error:new le({status:s.status,body:k}),get readyState(){return ge(i)},get isClosed(){return ge(i)==="closed"},sessionInfo:p})});else{const v=()=>{m({type:"error",error:new le({status:h.code||500,body:{type:void 0,message:h.message||"Unknown error in subscribe query."}}),get readyState(){return ge(i)},get isClosed(){return ge(i)==="closed"},sessionInfo:p})};if(i.readyState===ae.CLOSED){v();return}setTimeout(()=>{i.readyState!==ae.OPEN&&v()},5e3)}},i.onmessage=h=>{g(JSON.parse(h.data))},{close:()=>{r=!0;for(const h of c)try{h()}catch(v){console.error("Error in onClose callback",v)}i.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return p},get readyState(){return ge(i)},get isClosed(){return ge(i)==="closed"},[Symbol.asyncIterator]:Ds.bind(this,u,f,l,()=>1)}}var ye={};Object.defineProperty(ye,"__esModule",{value:!0});var Ls=ye.parseCookie=Rn;ye.parse=Rn,ye.stringifyCookie=Ks,ye.stringifySetCookie=ut,ye.serialize=ut,ye.parseSetCookie=qs,ye.stringifySetCookie=ut,ye.serialize=ut;const Tn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,xn=/^[\u0021-\u003A\u003C-\u007E]*$/,Fs=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,zs=/^[\u0020-\u003A\u003D-\u007E]*$/,Vs=/^-?\d+$/,Js=Object.prototype.toString,Hs=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function Rn(e,t){const n=new Hs,s=e.length;if(s<2)return n;const r=(t==null?void 0:t.decode)||An;let o=0;do{const i=Ft(e,o,s);if(i===-1)break;const a=Lt(e,o,s);if(i>a){o=e.lastIndexOf(";",i-1)+1;continue}const c=Se(e,o,i);n[c]===void 0&&(n[c]=r(Se(e,i+1,a))),o=a+1}while(o<s);return n}function Ks(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,s=[];for(const r of Object.keys(e)){const o=e[r];if(o===void 0)continue;if(!Tn.test(r))throw new TypeError(`cookie name is invalid: ${r}`);const i=n(o);if(!xn.test(i))throw new TypeError(`cookie val is invalid: ${o}`);s.push(`${r}=${i}`)}return s.join("; ")}function ut(e,t,n){const s=typeof e=="object"?e:{...n,name:e,value:String(t)},r=typeof t=="object"?t:n,o=(r==null?void 0:r.encode)||encodeURIComponent;if(!Tn.test(s.name))throw new TypeError(`argument name is invalid: ${s.name}`);const i=s.value?o(s.value):"";if(!xn.test(i))throw new TypeError(`argument val is invalid: ${s.value}`);let a=s.name+"="+i;if(s.maxAge!==void 0){if(!Number.isInteger(s.maxAge))throw new TypeError(`option maxAge is invalid: ${s.maxAge}`);a+="; Max-Age="+s.maxAge}if(s.domain){if(!Fs.test(s.domain))throw new TypeError(`option domain is invalid: ${s.domain}`);a+="; Domain="+s.domain}if(s.path){if(!zs.test(s.path))throw new TypeError(`option path is invalid: ${s.path}`);a+="; Path="+s.path}if(s.expires){if(!Bs(s.expires)||!Number.isFinite(s.expires.valueOf()))throw new TypeError(`option expires is invalid: ${s.expires}`);a+="; Expires="+s.expires.toUTCString()}if(s.httpOnly&&(a+="; HttpOnly"),s.secure&&(a+="; Secure"),s.partitioned&&(a+="; Partitioned"),s.priority)switch(typeof s.priority=="string"?s.priority.toLowerCase():void 0){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${s.priority}`)}if(s.sameSite)switch(typeof s.sameSite=="string"?s.sameSite.toLowerCase():s.sameSite){case!0:case"strict":a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"none":a+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${s.sameSite}`)}return a}function qs(e,t){const n=(t==null?void 0:t.decode)||An,s=e.length,r=Lt(e,0,s),o=Ft(e,0,r),i=o===-1?{name:"",value:n(Se(e,0,r))}:{name:Se(e,0,o),value:n(Se(e,o+1,r))};let a=r+1;for(;a<s;){const c=Lt(e,a,s),u=Ft(e,a,c),l=u===-1?Se(e,a,c):Se(e,a,u),f=u===-1?void 0:Se(e,u+1,c);switch(l.toLowerCase()){case"httponly":i.httpOnly=!0;break;case"secure":i.secure=!0;break;case"partitioned":i.partitioned=!0;break;case"domain":i.domain=f;break;case"path":i.path=f;break;case"max-age":f&&Vs.test(f)&&(i.maxAge=Number(f));break;case"expires":if(!f)break;const p=new Date(f);Number.isFinite(p.valueOf())&&(i.expires=p);break;case"priority":if(!f)break;const m=f.toLowerCase();(m==="low"||m==="medium"||m==="high")&&(i.priority=m);break;case"samesite":if(!f)break;const g=f.toLowerCase();(g==="lax"||g==="strict"||g==="none")&&(i.sameSite=g);break}a=c+1}return i}function Lt(e,t,n){const s=e.indexOf(";",t);return s===-1?n:s}function Ft(e,t,n){const s=e.indexOf("=",t);return s<n?s:-1}function Se(e,t,n){let s=t,r=n;do{const o=e.charCodeAt(s);if(o!==32&&o!==9)break}while(++s<r);for(;r>s;){const o=e.charCodeAt(r-1);if(o!==32&&o!==9)break;r--}return e.slice(s,r)}function An(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function Bs(e){return Js.call(e)==="[object Date]"}const Qs={"https://api.instantdb.com":{keys:[{kty:"OKP",crv:"Ed25519",alg:"EdDSA",use:"sig",kid:"1034696293",x:"N-C41432STKAKkXAWmeIOXMnZcGRR1b9u1L3bTVqI_o"}]},"http://localhost:8888":{keys:[{kty:"OKP",crv:"Ed25519",alg:"EdDSA",use:"sig",kid:"503090235",x:"qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow"}]}};function Gs(e){if(e.kty==="OKP"&&e.crv==="Ed25519")return{name:"Ed25519"};if(e.kty==="EC")return{name:"ECDSA",namedCurve:e.crv};if(e.kty==="RSA")return{name:"RSASSA-PKCS1-v1_5",hash:{RS256:"SHA-256",RS384:"SHA-384",RS512:"SHA-512"}[e.alg]||"SHA-256"};throw new Error(`Unsupported JWK configuration: kty=${e.kty}, crv=${e.crv}`)}async function Xs(e){const t=Gs(e),n=await crypto.subtle.importKey("jwk",e,t,!1,["verify"]);return{alg:t,key:n}}function Ys(e,t,n,s){return crypto.subtle.verify(e,t,n,s)}function Zs(e){const t=new Uint8Array(Math.ceil(e.length/2));for(let n=0;n<t.length;n++)t[n]=parseInt(e.substring(n*2,n*2+2),16);return t}function er(e){let t,n,s;for(const o of e.split(",")){const[i,a]=o.split("=");switch(i){case"t":{t=a;break}case"kid":{n=a;break}case"v1":{s=a;break}}}const r=[];if(t||r.push("t"),n||r.push("kid"),s||r.push("v1"),r.length||!t||!n||!s)throw new C("Invalid Instant-Signature header.",{header:e,missingKeys:r});return{t,kid:n,v1:s}}function tr(e,t,n){if(Math.floor(e.getTime()/1e3)-parseInt(t,10)>n)throw new C("Webhook signature is too old",{tolerance:n,receivedAt:e,t})}const Pn={},nr=300;async function sr(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new le({status:t.status,body:s}))}catch{return e(new le({status:t.status,body:{type:void 0,message:n}}))}}const rr=async(e,t)=>{const n={...(t==null?void 0:t.headers)||{},"Instant-Core-Version":Ee},s=await fetch(e,{...t,headers:n});return s.status===200?s.json():sr(r=>Promise.reject(r),s)};function jn(e){return e?new Date(e):null}function We(e){return{id:e.id,sink:e.sink,etypes:e.etypes??[],actions:e.actions,status:e.status,disabledReason:e.disabled_reason??null,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function ir(e){return{attemptAt:jn(e["attempt-at"]),durationMs:e["duration-ms"]??null,success:e["success?"]??null,statusCode:e["status-code"]??null,responseText:e["response-text"]??null,errorType:e["error-type"]??null,errorMessage:e["error-message"]??null}}function zt(e){return{isn:e.isn,status:e.status,attempts:e.attempts?e.attempts.map(ir):null,nextAttemptAfter:jn(e.next_attempt_after),createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}class or{constructor(t){L(this,ne);L(this,G);L(this,Ye);L(this,Le);L(this,Fe);L(this,Ze);B(this,G,t.appId),B(this,Ye,t.apiURI),B(this,Le,t.token),B(this,Fe,t.withAuth),B(this,Ze,t.jsonFetch)}async list(){return((await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks`)).webhooks||[]).map(We)}async create(t){const n=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks`,{method:"POST",body:t});return We(n.webhook)}async update(t,n){const s=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}`,{method:"POST",body:n});return We(s.webhook)}async delete(t){const n=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}`,{method:"DELETE"});return We(n.webhook)}async enable(t){const n=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}/enable`,{method:"POST",body:{}});return We(n.webhook)}async disable(t,n){const s=n!=null&&n.reason?{reason:n.reason}:{},r=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}/disable`,{method:"POST",body:s});return We(r.webhook)}async listEvents(t,n){var o,i,a;const s=n!=null&&n.after?`?after=${encodeURIComponent(n.after)}`:"",r=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}/events${s}`);return{events:(r.events||[]).map(zt),pageInfo:{startCursor:((o=r.pageInfo)==null?void 0:o.startCursor)??null,endCursor:((i=r.pageInfo)==null?void 0:i.endCursor)??null,hasNextPage:!!((a=r.pageInfo)!=null&&a.hasNextPage)}}}async getEvent(t,n){const s=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}/events/${n}`);return zt(s.event)}async getPayload(t,n){return j(this,ne,fe).call(this,`/webhooks/payload/${y(this,G)}/${t}/${n}`)}async resendEvent(t,n){const s=await j(this,ne,fe).call(this,`/dash/apps/${y(this,G)}/webhooks/${t}/events/${n}`,{method:"POST",body:{}});return zt(s.event)}}G=new WeakMap,Ye=new WeakMap,Le=new WeakMap,Fe=new WeakMap,Ze=new WeakMap,ne=new WeakSet,fe=function(t,n){if(!y(this,G))throw new C("appId is required to manage webhooks. Pass it to the Webhooks constructor.");const s=r=>{const o={method:n==null?void 0:n.method,headers:{authorization:`Bearer ${r}`,"content-type":"application/json"}};return(n==null?void 0:n.body)!==void 0&&(o.body=JSON.stringify(n.body)),y(this,Ze).call(this,`${y(this,Ye)}${t}`,o)};if(y(this,Fe))return y(this,Fe).call(this,s);if(!y(this,Le))throw new C("A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.");return s(y(this,Le))};const Ht=class Ht{constructor(t,n){d(this,"appId");d(this,"schema");L(this,et);d(this,"apiURI");L(this,Ce);d(this,"manager");this.appId=t.appId,this.schema=t.schema,B(this,et,t.adminToken||t.token),this.apiURI=t.apiURI||"https://api.instantdb.com",B(this,Ce,n||rr),this.manager=new or({appId:this.appId,apiURI:this.apiURI,token:y(this,et),withAuth:t.withAuth,jsonFetch:y(this,Ce)})}static helpers(){function t(...s){if(s.length===2)return{$default:s[1]};const[r,o,i]=s;return{[r]:{[o]:i}}}function n(...s){const r={};for(const o of s)for(const i of Object.keys(o))i==="$default"?r.$default=o.$default:r[i]={...r[i],...o[i]};return r}return{typedHandlers:t,combineHandlers:n}}helpers(){return Ht.helpers()}async fetchJwks(){return await y(this,Ce).call(this,`${this.apiURI}/.well-known/webhooks/jwks.json`)}async keyOfKid(t){var i,a,c;const n=`${this.apiURI}:${t}`,s=Pn[n];if(s)return s;const r=((i=Qs[this.apiURI])==null?void 0:i.keys.find(u=>u.kid===t))||((c=(a=await this.fetchJwks())==null?void 0:a.keys)==null?void 0:c.find(u=>u.kid===t));if(!r)throw new C("Could not find matching signing key",{kid:t});const o=await Xs(r);return Pn[n]=o,o}async validate(t,n,s){const r=(s==null?void 0:s.receivedAt)||new Date,{t:o,kid:i,v1:a}=er(t),c=(s==null?void 0:s.tolerance)??nr;tr(r,o,c);const{alg:u,key:l}=await this.keyOfKid(i),f=typeof n=="function"?await n():n,p=new TextEncoder().encode(`${o}.${f}`);if(!await Ys(u,l,Zs(a),p))throw new C("Instant Signature did not validate",{header:t});const g=JSON.parse(f);if(typeof g!="object"||typeof g.payloadUrl!="string"||typeof g.token!="string")throw new C("Invalid webhook body, expected an object with payloadUrl and token fields",{body:g});return g}async validateRequest(t,n){const s=t.headers.get("instant-signature");if(!s)throw new C("Request is missing Instant-Signature header");return this.validate(s,()=>t.text(),n)}fetchPayloads({payloadUrl:t,token:n}){return y(this,Ce).call(this,t,{headers:{Authorization:`Bearer ${n}`,accept:"application/json"}})}async processPayload(t,n){var r,o;const s=[];for(const i of n.data){const{etype:a,action:c}=i,u=((r=t==null?void 0:t[a])==null?void 0:r[c])||((o=t==null?void 0:t[a])==null?void 0:o.$default)||(t==null?void 0:t.$default);u&&s.push(u(i))}await Promise.all(s)}async processRequest(t,n,s){const r=await this.validateRequest(n,s),o=await this.fetchPayloads(r);await this.processPayload(t,o)}async processNodeRequest(t,n,s){let r,o=!1,i=(s==null?void 0:s.body)??n.rawBody??n.body;if(i!=null&&typeof i.then=="function"&&(i=await i),typeof i=="string")r=i;else if(i instanceof Uint8Array)r=new TextDecoder("utf-8").decode(i);else if(i!=null&&typeof i=="object")try{r=JSON.stringify(i),o=!0}catch{throw new C("Webhook request body has already been parsed and could not be re-serialized. Configure this route to receive the raw request body instead of parsed JSON.")}else if(n[Symbol.asyncIterator]){const f=new TextEncoder,p=[];for await(const h of n)p.push(typeof h=="string"?f.encode(h):h);let m=0;for(const h of p)m+=h.byteLength;const g=new Uint8Array(m);let w=0;for(const h of p)g.set(h,w),w+=h.byteLength;r=new TextDecoder("utf-8").decode(g)}else throw new C("Could not read the webhook request body. Pass a Node IncomingMessage with an unconsumed stream, or set `req.body` to the raw bytes (Buffer/Uint8Array) or string.");const a=typeof n.headers.host=="string"?n.headers.host:"localhost",c=new URL(n.url??"/",`https://${a}`),u=new Headers;for(const[f,p]of Object.entries(n.headers))typeof p=="string"?u.set(f,p):Array.isArray(p)&&u.set(f,p.join(", "));const l=new Request(c,{method:n.method??"POST",headers:u,body:r});try{await this.processRequest(t,l,s)}catch(f){throw o&&f instanceof C&&f.message==="Instant Signature did not validate"?new C("Webhook signature did not validate. The request body was re-serialized from a parsed JSON object, which can produce different bytes than the server signed. Configure this route to receive the raw request body instead of parsed JSON.",{hint:f.hint}):f}}};et=new WeakMap,Ce=new WeakMap;let Vt=Ht;function ar(e){const t={apiURI:"https://api.instantdb.com"},n={...t,...e};return n.apiURI||(n.apiURI=t.apiURI),n}function cr(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function ur(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function M(e,t){ur(e,t);const{adminToken:n,appId:s}=e,r={"content-type":"application/json","app-id":s};return n&&(r.authorization=`Bearer ${n}`),t?cr(r,t):r}function fr(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function dr(){return fr()?{cache:"no-store"}:{}}async function lr(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new le({status:t.status,body:s}))}catch{return e(new le({status:t.status,body:{type:void 0,message:n}}))}}async function U(e,t){const n=dr(),s={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":Ee,"Instant-Core-Version":Ee},r=await fetch(e,{...n,...t,headers:s});if(r.status===200){const o=await r.json();return Promise.resolve(o)}return lr(o=>Promise.reject(o),r)}function hr(e){var t,n,Fn;return t=class{constructor(o){L(this,n);d(this,"source");d(this,"url");this.url=o,this.source=j(this,n,Fn).call(this,o)}get onopen(){return this.source.onopen}set onopen(o){this.source.onopen=o}get onmessage(){return this.source.onmessage}set onmessage(o){this.source.onmessage=o}get onerror(){return this.source.onerror}set onerror(o){this.source.onerror=o}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,Fn=function(o){return new ae(o,{messageEvent:_n,fetch(a,c){return fetch(a,{...c,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":Ee,"@instantdb/core":Ee}})})}})},d(t,"OPEN",ae.OPEN),d(t,"CONNECTING",ae.CONNECTING),d(t,"CLOSED",ae.CLOSED),t}function pr(e){var n,s;(!e.appId||!A(e.appId))&&console.warn("warning: Instant Admin DB must be initialized with a valid appId. Received: "+JSON.stringify(e.appId));const t={...e,appId:(n=e.appId)==null?void 0:n.trim(),adminToken:(s=e.adminToken)==null?void 0:s.trim(),useDateObjects:e.useDateObjects??!1};return new Jt(t)}function Mn(e){return(Array.isArray(e)?e:[e]).flatMap(ps)}class yr{constructor(t){d(this,"config");this.config=t}async getPresence(t,n){return(await U(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:M(this.config)})).sessions||{}}}class mr{constructor(t){d(this,"config");d(this,"generateMagicCode",async t=>U(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify({email:t})}));d(this,"sendMagicCode",async t=>U(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify({email:t})}));d(this,"verifyMagicCode",async(t,n)=>{const{user:s}=await U(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify({email:t,code:n})});return s});d(this,"checkMagicCode",async(t,n,s)=>{const r=await U(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify({email:t,code:n,...s!=null&&s.extraFields?{"extra-fields":s.extraFields}:{}})});return{user:r.user,created:r.created}});d(this,"verifyToken",async t=>(await U(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);d(this,"getUser",async t=>{const n=Object.entries(t).map(([r,o])=>`${r}=${encodeURIComponent(o)}`).join("&");return(await U(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:M(this.config)})).user});d(this,"deleteUser",async t=>{const n=Object.entries(t).map(([r,o])=>`${r}=${o}`);return(await U(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:M(this.config)})).deleted});d(this,"getUserFromRequest",async(t,n)=>{const s=t.headers.get("cookie")||"",r=Ls(s),o="instant_user_"+this.config.appId;if(!r[o])return null;const i=r[o],a=JSON.parse(i);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await U(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,s=this.config;await U(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:M(s),body:JSON.stringify(n)})}}const Un=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",br=e=>e&&typeof e.getReader=="function";class Dn{constructor(t,n){d(this,"config");d(this,"impersonationOpts");d(this,"uploadFile",async(t,n,s={})=>{const r={...M(this.config,this.impersonationOpts),path:t};s.contentDisposition&&(r["content-disposition"]=s.contentDisposition),delete r["content-type"],s.contentType&&(r["content-type"]=s.contentType);let o;if(Un(n)&&(o="half"),Un(n)||br(n)){if(!s.fileSize)throw new Error("fileSize is required in metadata when uploading streams");r["content-length"]=s.fileSize.toString()}let i={method:"PUT",headers:r,body:n,...o&&{duplex:o}};return U(`${this.config.apiURI}/admin/storage/upload?app_id=${this.config.appId}`,i)});d(this,"delete",async t=>U(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:M(this.config,this.impersonationOpts)}));d(this,"deleteMany",async t=>U(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));d(this,"upload",async(t,n,s={})=>{const{data:r}=await U(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),o={},i=s.contentType;i&&(o["Content-Type"]=i);const{ok:a}=await fetch(r,{method:"PUT",body:n,headers:o});return a});d(this,"list",async()=>{const{data:t}=await U(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:M(this.config)});return t});d(this,"getDownloadUrl",async t=>{const{data:n}=await U(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:M(this.config)});return n});this.config=t,this.impersonationOpts=n}}class wr{constructor(t){L(this,ze);d(this,"createReadStream",t=>y(this,ze).call(this).createReadStream(t));d(this,"createWriteStream",t=>y(this,ze).call(this).createWriteStream(t));B(this,ze,t)}}ze=new WeakMap;function gr(e){return{info:e?(...t)=>console.info(...t):()=>{},debug:e?(...t)=>console.debug(...t):()=>{},error:e?(...t)=>console.error(...t):()=>{}}}const Kt=class Kt{constructor(t){L(this,z);d(this,"config");d(this,"auth");d(this,"storage");d(this,"streams");d(this,"rooms");d(this,"impersonationOpts");d(this,"webhooks");L(this,H,null);L(this,Te,0);L(this,X,null);L(this,Y);d(this,"tx",dn());d(this,"asUser",t=>{const n=new Kt({...this.config});return n.impersonationOpts=t,n.storage=new Dn(this.config,t),n});d(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||mn(t,this.config.schema);const s=n.fetchOpts||{},r=s.headers||{};return U(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...s,method:"POST",headers:{...r,...M(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});d(this,"transact",t=>(this.config.disableValidation||ks(t,this.config.schema),U(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config,this.impersonationOpts),body:JSON.stringify({steps:Mn(t),"throw-on-missing-attrs?":!!this.config.schema})})));d(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const s={query:t,"rules-override":n==null?void 0:n.rules,"inference?":(n==null?void 0:n.cardinalityInference)??!!this.config.schema};n!=null&&n.ip&&(s["ip-override"]=n.ip),n!=null&&n.origin&&(s["origin-override"]=n.origin);const r=await U(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config,this.impersonationOpts),body:JSON.stringify(s)});return{result:r.result,checkResults:r["check-results"]}});d(this,"debugTransact",(t,n)=>{const s={steps:Mn(t),"rules-override":n==null?void 0:n.rules,"dangerously-commit-tx":n==null?void 0:n.__dangerouslyCommit};return n!=null&&n.ip&&(s["ip-override"]=n.ip),n!=null&&n.origin&&(s["origin-override"]=n.origin),U(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:M(this.config,this.impersonationOpts),body:JSON.stringify(s)})});L(this,lt,t=>{var n;if(t.target!==y(this,H)){y(this,Y).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}y(this,Y).info("[socket][open]",t.target.id),B(this,Te,0),(n=y(this,X))==null||n.onConnectionStatusChange("authenticated")});L(this,ht,t=>{var n;if(t.target!==y(this,H)){y(this,Y).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}y(this,Y).info("[socket][close]",t.target.id),(n=y(this,X))==null||n.onConnectionStatusChange("closed"),y(this,H)&&(B(this,H,null),j(this,z,Gt).call(this)||(setTimeout(()=>j(this,z,bt).call(this),y(this,Te)),B(this,Te,Math.min(15e3,Math.max(y(this,Te),500)*2))))});L(this,pt,t=>{var n;if(t.target!==y(this,H)){y(this,Y).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}y(this,Y).info("[socket][error]",t.target.id),(n=y(this,X))==null||n.onConnectionStatusChange("closed")});L(this,yt,t=>{var s,r,o,i,a,c;if(t.target!==y(this,H)){y(this,Y).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(y(this,Y).info("[receive]",n),n.op){case"start-stream-ok":{(s=y(this,X))==null||s.onStartStreamOk(n);break}case"stream-flushed":{(r=y(this,X))==null||r.onStreamFlushed(n);break}case"append-failed":{(o=y(this,X))==null||o.onAppendFailed(n);break}case"stream-append":{(i=y(this,X))==null||i.onStreamAppend(n);break}case"error":{switch((a=n["original-event"])==null?void 0:a.op){case"start-stream":case"append-stream":case"subscribe-stream":case"unsubscribe-stream":{(c=y(this,X))==null||c.onRecieveError(n);break}}break}}j(this,z,Kn).call(this)});this.config=ar(t),this.auth=new mr(this.config),this.storage=new Dn(this.config,this.impersonationOpts),this.streams=new wr(j(this,z,Hn).bind(this)),this.rooms=new yr(this.config),this.webhooks=new Vt(this.config,U),B(this,Y,gr(!!this.config.verbose))}subscribeQuery(t,n,s={}){t&&s&&"ruleParams"in s&&(t={$$ruleParams:s.ruleParams,...t}),this.config.disableValidation||mn(t,this.config.schema);const i={...(s.fetchOpts||{}).headers||{},...M(this.config,this.impersonationOpts)},a=!!this.config.schema;return Ws(t,n,{headers:i,inference:a,apiURI:this.config.apiURI})}};H=new WeakMap,Te=new WeakMap,X=new WeakMap,Y=new WeakMap,z=new WeakSet,zn=function(){y(this,H)&&y(this,H).close();const t={...M(this.config,this.impersonationOpts)},n=!!this.config.schema,s=hr({headers:t,inference:n}),r=new Os(s,`${this.config.apiURI}/admin/sse?app_id=${this.config.appId}`,`${this.config.apiURI}/admin/sse/push?app_id=${this.config.appId}`);return r.onopen=y(this,lt),r.onmessage=y(this,yt),r.onclose=y(this,ht),r.onerror=y(this,pt),B(this,H,r),r},bt=function(){return y(this,H)||j(this,z,zn).call(this)},Vn=function(t,n){const s=j(this,z,bt).call(this);y(this,Y).info("[send]",t,n,{isOpen:s.isOpen()}),s.isOpen()&&s.send({"client-event-id":t,...n})},Jn=function(){j(this,z,bt).call(this);const t=new Ts({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,s)=>{j(this,z,Vn).call(this,n,s)},log:y(this,Y)});return B(this,X,t),t},Hn=function(){return y(this,X)||j(this,z,Jn).call(this)},lt=new WeakMap,ht=new WeakMap,pt=new WeakMap,Gt=function(){return!y(this,X)||!y(this,X).hasActiveStreams()},Kn=function(){if(y(this,H)&&j(this,z,Gt).call(this)){const t=y(this,H);y(this,Y).info("cleaning up unused socket",t.id),B(this,H,null),t.close()}},yt=new WeakMap;let Jt=Kt;var ft={};function dt(e){let t=e;return new TransformStream({transform(n,s){if(!t){s.enqueue(n);return}if(t>n.length){t-=n.length;return}const r=n.slice(t);t=0,s.enqueue(r)}})}function Sr(e){const t=e.appId||ft.INSTANT_APP_ID||ft.NEXT_PUBLIC_INSTANT_APP_ID;if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set either the INSTANT_APP_ID or NEXT_PUBLIC_INSTANT_APP_ID environment variable.");const n=e.adminToken||ft.INSTANT_APP_ADMIN_TOKEN;if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the INSTANT_APP_ADMIN_TOKEN environment variable.");const s={appId:t,adminToken:n},r=e.apiURI||ft.INSTANT_API_URI;r&&(s.apiURI=r),e.verbose&&(s.verbose=e.verbose);const o=pr(s);async function i(l,f,p){const m=o.streams.createWriteStream({clientId:l,waitUntil:e.waitUntil??void 0});try{const g=await m.streamId();f().pipeTo(m);const h=o.streams.createReadStream({streamId:g});return p?h.pipeThrough(dt(p)):h}catch{const w=o.streams.createReadStream({clientId:l});return p?w.pipeThrough(dt(p)):w}}async function a(l,f){var m,g,w;const p=o.streams.createReadStream({clientId:l});try{await p.streamId()}catch(h){if(h instanceof C&&((w=(g=(m=h.hint)==null?void 0:m.errors)==null?void 0:g[0])==null?void 0:w.message)==="Stream is missing.")return;throw h}return f?p.pipeThrough(dt(f)):p}async function c(l,f,p){const m=f(),g=o.streams.createWriteStream({clientId:l,waitUntil:e.waitUntil??void 0});await g.streamId(),m.pipeTo(g);const w=o.streams.createReadStream({clientId:l});return p?w.pipeThrough(dt(p)):w}async function u(l){var m;const f=await o.query({$streams:{$:{where:{clientId:l}}}}),p=(m=f==null?void 0:f.$streams)==null?void 0:m[0];return p!=null&&p.done?"DONE":p?!0:null}return{resumableStream:i,resumeExistingStream:a,createNewResumableStream:c,hasExistingStream:u}}$.createResumableStreamContext=Sr,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@instantdb/resumable-stream",
3
- "version": "1.0.30",
3
+ "version": "1.0.31",
4
4
  "description": "Instant's drop-in replacement for Vercel's resumable-stream package.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/instantdb/instant/tree/main/client/packages/resumable-stream",
@@ -51,7 +51,7 @@
51
51
  "vitest": "^1.6.0"
52
52
  },
53
53
  "dependencies": {
54
- "@instantdb/admin": "1.0.30"
54
+ "@instantdb/admin": "1.0.31"
55
55
  },
56
56
  "scripts": {
57
57
  "test": "vitest",