@sidekickdb/resumable-stream 2.0.0 → 3.0.0

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,x){typeof exports=="object"&&typeof module<"u"?x(exports):typeof define=="function"&&define.amd?define(["exports"],x):(E=typeof globalThis<"u"?globalThis:E||self,x(E.instant={}))})(this,function(E){"use strict";var Ir=Object.defineProperty;var Mn=E=>{throw TypeError(E)};var kr=(E,x,P)=>x in E?Ir(E,x,{enumerable:!0,configurable:!0,writable:!0,value:P}):E[x]=P;var d=(E,x,P)=>kr(E,typeof x!="symbol"?x+"":x,P),Kt=(E,x,P)=>x.has(E)||Mn("Cannot "+P);var f=(E,x,P)=>(Kt(E,x,"read from private field"),P?P.call(E):x.get(E)),k=(E,x,P)=>x.has(E)?Mn("Cannot add the same private member more than once"):x instanceof WeakSet?x.add(E):x.set(E,P),S=(E,x,P,D)=>(Kt(E,x,"write to private field"),D?D.call(E,P):x.set(E,P),P),O=(E,x,P)=>(Kt(E,x,"access private method"),P);var q,be,ve,qe,Be,Qe,Me,Oe,De,le,Ee,Ce,xe,Ne,B,Vt,ct,ut,Dn,ft,dt,Ze,Jt,lt,Q,Ge,Le,Fe,Xe,ee,ae,Ye,Te,ze,K,_e,G,X,F,Ln,gt,Fn,zn,Wn,ht,pt,yt,Ht,Kn,mt;const x=/^(?:[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 P(e){return typeof e=="string"&&x.test(e)}const D=[];for(let e=0;e<256;++e)D.push((e+256).toString(16).slice(1));function Vn(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 Jn=new Uint8Array(16);function Hn(){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(Jn)}const qt={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function qn(e,t,n){var r;if(qt.randomUUID&&!e)return qt.randomUUID();e=e||{};const s=e.random??((r=e.rng)==null?void 0:r.call(e))??Hn();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,Vn(s)}const L={Remove:"remove",Replace:"replace",Add:"add"},Bt=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),et=Symbol.iterator,se={mutable:"mutable",immutable:"immutable"},St={};function Ke(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function Qt(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 Gt(e){return Object.getPrototypeOf(e)===Set.prototype}function Xt(e){return Object.getPrototypeOf(e)===Map.prototype}function Z(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function It(e){return!!C(e)}function C(e){return typeof e!="object"?null:e==null?void 0:e[Bt]}function kt(e){var t;const n=C(e);return n?(t=n.copy)!==null&&t!==void 0?t:n.original:e}function Se(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,se))===se.immutable||typeof n=="function")}function Yt(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,s=C(pe(n,e.key));if(s!==null&&(s==null?void 0:s.original)!==e.original)return null;const r=e.parent.type===3,i=r?Array.from(e.parent.setMap.keys()).indexOf(e.key):e.key;if(!(r&&n.size>i||Ke(n,i)))return null;t.push(i)}if(e.parent)return Yt(e.parent,t);t.reverse();try{Bn(e.copy,t)}catch{return null}return t}function Ve(e){return Array.isArray(e)?1:e instanceof Map?2:e instanceof Set?3:0}function pe(e,t){return Ve(e)===2?e.get(t):e[t]}function $t(e,t,n){Ve(e)===2?e.set(t,n):e[t]=n}function vt(e,t){const n=C(e);return(n?Z(n):e)[t]}function Ie(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ke(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 Bn(e,t){for(let n=0;n<t.length-1;n+=1){const s=t[n];if(e=pe(Ve(e)===3?Array.from(e):e,s),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function Qn(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 Gn=Object.prototype.propertyIsEnumerable;function Xn(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!Gt(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(!Xt(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,se),n!==void 0)&&n!==se.mutable){if(n===se.immutable)return Qn(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=>{Gn.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 H(e){e.copy||(e.copy=Xn(e.original,e.options))}function Je(e){if(!Se(e))return kt(e);if(Array.isArray(e))return e.map(Je);if(e instanceof Map){const n=Array.from(e.entries()).map(([s,r])=>[s,Je(r)]);if(!Xt(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(Je);if(!Gt(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]=Je(e[n]);return t}function tt(e){return It(e)?Je(e):e}function ce(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ce(e.parent))}function Yn(e,t){const n=Ve(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 Zt(e,t,n){if(It(e)||!Se(e,n)||t.has(e)||Object.isFrozen(e))return;const s=e instanceof Set,r=s?new Map:void 0;if(t.add(e),Yn(e,(i,o)=>{var a;if(It(o)){const c=C(o);H(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;$t(s?r:e,i,u)}else Zt(o,t,n)}),r){const i=e,o=Array.from(i);i.clear(),o.forEach(a=>{i.add(r.has(a)?r.get(a):a)})}}function Zn(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&Zt(pe(n,t),e.finalities.handledSet,e.options)}function Ot(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(kt(t))}))}function Et(e,t,n,s){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&s){const i=Yt(e);i&&t(e,i,n,s)}e.finalized=!0}}function Ct(e,t,n,s){const r=C(n);r&&(r.callbacks||(r.callbacks=[]),r.callbacks.push((i,o)=>{var a;const c=e.type===3?e.setMap:e.copy;if(Ie(pe(c,t),n)){let u=r.original;r.copy&&(u=r.copy),Ot(e),Et(e,s,i,o),e.options.enableAutoFreeze&&(e.options.updatedValues=(a=e.options.updatedValues)!==null&&a!==void 0?a:new WeakMap,e.options.updatedValues.set(u,r.original)),$t(c,t,u)}}),e.options.enableAutoFreeze&&r.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),Se(n,e.options)&&e.finalities.draft.push(()=>{const i=e.type===3?e.setMap:e.copy;Ie(pe(i,t),n)&&Zn(e,t)})}function es(e,t,n,s,r){let{original:i,assignedMap:o,options:a}=e,c=e.copy;c.length<i.length&&([i,c]=[c,i],[n,s]=[s,n]);for(let u=0;u<i.length;u+=1)if(o.get(u.toString())&&c[u]!==i[u]){const h=t.concat([u]),l=ke(h,r);n.push({op:L.Replace,path:l,value:tt(c[u])}),s.push({op:L.Replace,path:l,value:tt(i[u])})}for(let u=i.length;u<c.length;u+=1){const h=t.concat([u]),l=ke(h,r);n.push({op:L.Add,path:l,value:tt(c[u])})}if(i.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const h=t.concat(["length"]),l=ke(h,r);s.push({op:L.Replace,path:l,value:i.length})}else for(let h=c.length;i.length<h;h-=1){const l=t.concat([h-1]),y=ke(l,r);s.push({op:L.Remove,path:y})}}}function ts({original:e,copy:t,assignedMap:n},s,r,i,o){n.forEach((a,c)=>{const u=pe(e,c),h=tt(pe(t,c)),l=a?Ke(e,c)?L.Replace:L.Add:L.Remove;if(Ie(u,h)&&l===L.Replace)return;const y=s.concat(c),m=ke(y,o);r.push(l===L.Remove?{op:l,path:m}:{op:l,path:m,value:h}),i.push(l===L.Add?{op:L.Remove,path:m}:l===L.Remove?{op:L.Add,path:m,value:u}:{op:L.Replace,path:m,value:u})})}function ns({original:e,copy:t},n,s,r,i){let o=0;e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=ke(c,i);s.push({op:L.Remove,path:u,value:a}),r.unshift({op:L.Add,path:u,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=ke(c,i);s.push({op:L.Add,path:u,value:a}),r.unshift({op:L.Remove,path:u,value:a})}o+=1})}function He(e,t,n,s){const{pathAsArray:r=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ts(e,t,n,s,r);case 1:return es(e,t,n,s,r);case 3:return ns(e,t,n,s,r)}}const nt=(e,t,n=!1)=>{if(typeof e=="object"&&e!==null&&(!Se(e,t)||n))throw new Error("Strict mode: Mutable data cannot be accessed directly, please use 'unsafe(callback)' wrap.")},xt={get size(){return Z(C(this)).size},has(e){return Z(C(this)).has(e)},set(e,t){const n=C(this),s=Z(n);return(!s.has(e)||!Ie(s.get(e),t))&&(H(n),ce(n),n.assignedMap.set(e,!0),n.copy.set(e,t),Ct(n,e,t,He)),this},delete(e){if(!this.has(e))return!1;const t=C(this);return H(t),ce(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=C(this);if(this.size){H(e),ce(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=C(this);Z(n).forEach((s,r)=>{e.call(t,this.get(r),r,this)})},get(e){var t,n;const s=C(this),r=Z(s).get(e),i=((n=(t=s.options).mark)===null||n===void 0?void 0:n.call(t,r,se))===se.mutable;if(s.options.strict&&nt(r,s.options,i),i||s.finalized||!Se(r,s.options)||r!==s.original.get(e))return r;const o=St.createDraft({original:r,parentDraft:s,key:e,finalities:s.finalities,options:s.options});return H(s),s.copy.set(e,o),o},keys(){return Z(C(this)).keys()},values(){const e=this.keys();return{[et]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[et]:()=>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]}}}},[et](){return this.entries()}},ss=Reflect.ownKeys(xt),en=(e,t,{isValuesIterator:n})=>()=>{var s,r;const i=t.next();if(i.done)return i;const o=i.value;let a=e.setMap.get(o);const c=C(a),u=((r=(s=e.options).mark)===null||r===void 0?void 0:r.call(s,a,se))===se.mutable;if(e.options.strict&&nt(o,e.options,u),!u&&!c&&Se(o,e.options)&&!e.finalized&&e.original.has(o)){const h=St.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,h),a=h}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},st={get size(){return C(this).setMap.size},has(e){const t=C(this);if(t.setMap.has(e))return!0;H(t);const n=C(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=C(this);return this.has(e)||(H(t),ce(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),Ct(t,e,e,He)),this},delete(e){if(!this.has(e))return!1;const t=C(this);H(t),ce(t);const n=C(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=C(this);H(e),ce(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=C(this);H(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:en(e,t,{isValuesIterator:!0})}},entries(){const e=C(this);H(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:en(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[et](){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(st,{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 rs=Reflect.ownKeys(st),tn=new WeakSet,nn={get(e,t,n){var s,r;const i=(s=e.copy)===null||s===void 0?void 0:s[t];if(i&&tn.has(i))return i;if(t===Bt)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,se),o===se.mutable)return e.options.strict&&nt(u,e.options,!0),u}const a=Z(e);if(a instanceof Map&&ss.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(xt,"size").get.call(e.proxy);const u=xt[t];if(u)return u.bind(e.proxy)}if(a instanceof Set&&rs.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(st,"size").get.call(e.proxy);const u=st[t];if(u)return u.bind(e.proxy)}if(!Ke(a,t)){const u=Qt(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&&nt(c,e.options),e.finalized||!Se(c,e.options))return c;if(c===vt(e.original,t)){if(H(e),e.copy[t]=sn({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const u=C(e.copy[t]);return H(u),ce(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 i=Qt(Z(e),t);if(i!=null&&i.set)return i.set.call(e.proxy,n),!0;const o=vt(Z(e),t),a=C(o);return a&&Ie(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):(Ie(n,o)&&(n!==void 0||Ke(e.original,t))||(H(e),ce(e),Ke(e.original,t)&&Ie(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,Ct(e,t,n,He)),!0)},has(e,t){return t in Z(e)},ownKeys(e){return Reflect.ownKeys(Z(e))},getOwnPropertyDescriptor(e,t){const n=Z(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?nn.set.call(this,e,t,void 0,e.proxy):(vt(e.original,t)!==void 0||t in e.original?(H(e),ce(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 sn(e){const{original:t,parentDraft:n,key:s,finalities:r,options:i}=e,o=Ve(t),a={type:o,finalized:!1,parent:n,original:t,copy:null,proxy:null,finalities:r,options:i,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,nn);if(r.revoke.push(u),tn.add(c),a.proxy=c,n){const h=n;h.finalities.draft.push((l,y)=>{var m,g;const w=C(c);let p=h.type===3?h.setMap:h.copy;const $=pe(p,s),v=C($);if(v){let V=v.original;v.operated&&(V=kt($)),Ot(v),Et(v,He,l,y),h.options.enableAutoFreeze&&(h.options.updatedValues=(m=h.options.updatedValues)!==null&&m!==void 0?m:new WeakMap,h.options.updatedValues.set(V,v.original)),$t(p,s,V)}(g=w.callbacks)===null||g===void 0||g.forEach(V=>{V(l,y)})})}else{const h=C(c);h.finalities.draft.push((l,y)=>{Ot(h),Et(h,He,l,y)})}return c}St.createDraft=sn,Object.prototype.constructor.toString();function Pe(){return qn()}function is(e,t){return e.localeCompare(t)}function os(){let e=is;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}os();function as(){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 cs=as();function rt(e,t,n){const s={__etype:e,__ops:n};return new Proxy(s,{get:(r,i)=>{if(i==="__ops")return n;if(i==="__etype")return e;if(cs.has(i))return(o,a)=>rt(e,t,[...n,a?[i,e,t,o,a]:[i,e,t,o]])}})}function us(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function rn(e){return e.startsWith("lookup__")}function on(e){const[t,n,...s]=e.split("__");return[n,JSON.parse(s.join("__"))]}function fs(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(r,i)=>rt(e,on(us(r,i)),[]);if(n==="__etype")return e;const s=n;return rn(s)?rt(e,on(s),[]):rt(e,s,[])}})}function an(){return new Proxy({},{get(e,t){return fs(t)}})}an();function ds(e){return e.__ops}class _ extends Error{constructor(n,s,r){super(n);d(this,"hint");d(this,"traceId");this.hint=s,r&&(this.traceId=r);const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,_),this.name="InstantError"}get[Symbol.toStringTag](){return"InstantError"}}class ue extends _{constructor(n){var i,o;const s=((i=n.body)==null?void 0:i.message)||`API Error (${n.status})`;super(s,n.body.hint,((o=n.body)==null?void 0:o.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,ue),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 $e="v2.0.0";class fe{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 fe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new fe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new fe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new fe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class A extends Error{constructor(t,n){const s=n?`At path '${n}': ${t}`:t;super(s),this.name="QueryValidationError"}}const cn=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],ls=e=>e.valueType||"unknown",un=(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}},hs=(e,t,n,s,r,i,o)=>{const a=i.valueType==="json",c=(u,h,l)=>{if(!un(l,h,a))throw new A(`Invalid value for operator '${u}' on attribute '${s}' in entity '${r}'. Expected ${h}, but received: ${typeof l}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new A(`Operator '${e}' for attribute '${s}' in entity '${r}' 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"&&!i.isIndexed)throw new A(`Operator '${e}' can only be used with indexed attributes, but '${s}' in entity '${r}' is not indexed`,o);break;case"$isNull":c(e,"boolean",t);break;default:throw new A(`Unknown operator '${e}' for attribute '${s}' in entity '${r}'`,o)}},je=(e,t,n,s,r)=>{const i=ls(n),o=n.valueType==="json";if(typeof e=="object"&&e!==null&&!Array.isArray(e)){if(o)return;const c=e;for(const[u,h]of Object.entries(c))hs(u,h,i,t,s,n,`${r}.${u}`)}else if(!un(e,i,o))throw new A(`Invalid value for attribute '${t}' in entity '${s}'. Expected ${i}, but received: ${typeof e}`,r)},ps=(e,t,n,s,r)=>{const i=e.split(".");if(i.length<2)throw new A(`Invalid dot notation path '${e}'. Must contain at least one dot.`,r);let o=n;for(let h=0;h<i.length-1;h++){const l=i[h],y=s.entities[o];if(!y)throw new A(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,r);const m=y.links[l];if(!m){const g=Object.keys(y.links);throw new A(`Link '${l}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${g.length>0?g.join(", "):"none"}`,r)}o=m.entityName}const a=i[i.length-1],c=s.entities[o];if(!c)throw new A(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,r);if(a==="id"){if(typeof t=="string"&&!P(t))throw new A(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,r);je(t,e,new fe("string",!1,!0),n,r);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof t=="string"&&!P(t))throw new A(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,r);je(t,e,new fe("string",!1,!0),n,r);return}if(!u){const h=Object.keys(c.attrs);throw new A(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${h.length>0?h.join(", ")+", id":"id"}`,r)}je(t,e,u,n,r)},fn=(e,t,n,s)=>{for(const[r,i]of Object.entries(e)){if(r==="or"||r==="and"){if(Array.isArray(i))for(const u of i)typeof u=="object"&&u!==null&&fn(u,t,n,`${s}.${r}[${u}]`);continue}if(r==="id"){je(i,"id",new fe("string",!1,!0),t,`${s}.id`);continue}if(r.includes(".")){ps(r,i,t,n,`${s}.${r}`);continue}const o=n.entities[t];if(!o)continue;const a=o.attrs[r],c=o.links[r];if(!a&&!c){const u=Object.keys(o.attrs),h=Object.keys(o.links);throw new A(`Attribute or link '${r}' does not exist on entity '${t}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${h.length>0?h.join(", "):"none"}`,`${s}.${r}`)}if(a)je(i,r,a,t,`${s}.${r}`);else if(c){if(typeof i=="string"&&!P(i))throw new A(`Invalid value for link '${r}' in entity '${t}'. Expected a UUID, but received: ${i}`,`${s}.${r}`);const u=new fe("string",!1,!0);je(i,r,u,t,`${s}.${r}`)}}},ys=(e,t,n,s,r=0)=>{for(const o of Object.keys(e))if(!cn.includes(o))throw new A(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${cn.join(", ")}. Found: ${o}`,s);const i=["offset","before","beforeInclusive","after","afterInclusive","first","last"];for(const o of i)if(e[o]!==void 0&&r>0)throw new A(`'${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 A(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,s?`${s}.where`:void 0);fn(e.where,t,n,s?`${s}.where`:"where")}},dn=(e,t,n,s,r=0)=>{var i;if(!e||typeof e!="object")throw new A(`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 A(`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=(i=n==null?void 0:n.entities[t].links[o])==null?void 0:i.entityName;c&&dn(a,c,n,`${s}.${o}`,r+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new A(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${s}.$`);ys(a,t,n,`${s}.$`,r)}},ln=(e,t)=>{if(typeof e!="object"||e===null)throw new A(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new A(`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 A(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(typeof s!="string")throw new A(`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 A(`Entity '${s}' does not exist in schema. Available entities: ${r.length>0?r.join(", "):"none"}`,s)}dn(n[s],s,t,s,0)}}},hn=e=>typeof e!="string"?!1:rn(e)?!0:P(e);class te extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const pn=e=>e.length>0?e.join(", "):"none",ms=(e,t)=>new te(`Entity '${e}' does not exist in schema. Available entities: ${pn(t)}`),Tt={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},bs=(e,t)=>{var n;return e==null?!0:((n=Tt[t.valueType])==null?void 0:n.call(Tt,e))??!1},yn=(e,t)=>{const n=t.entities[e];if(!n)throw ms(e,Object.keys(t.entities));return n},_t=(e,t,n)=>{const s=yn(e,n);if(typeof t!="object"||t===null)throw new te(`Arguments for data operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[r,i]of Object.entries(t)){if(r==="id")continue;const o=s.attrs[r];if(o&&!bs(i,o))throw new te(`Invalid value for attribute '${r}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof i}`)}},mn=(e,t,n)=>{const s=yn(e,n);if(typeof t!="object"||t===null)throw new te(`Arguments for link operation on entity '${e}' must be an object, but received: ${typeof t}`);for(const[r,i]of Object.entries(t)){if(!s.links[r]){const a=Object.keys(s.links);throw new te(`Link '${r}' does not exist on entity '${e}'. Available links: ${pn(a)}`)}if(i!=null){if(Array.isArray(i)){for(const a of i)if(!hn(a))throw new te(`Invalid entity ID in link '${r}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!hn(i))throw new te(`Invalid UUID in link '${r}' for entity '${e}'. Expected a UUID, but received: ${i}`)}}},gs={create:_t,update:_t,merge:_t,link:mn,unlink:mn,delete:()=>{}},ws=(e,t)=>{if(!t)return;const[n,s,r,i]=e;if(!Array.isArray(r)&&!P(r))throw new te(`Invalid id for entity '${s}'. Expected a UUID, but received: ${r}`);if(typeof s!="string")throw new te(`Entity name must be a string, but received: ${typeof s}`);const o=gs[n];o&&i!==void 0&&o(s,i,t)},Ss=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const s of n){if(!s||typeof s!="object")throw new te(`Transaction chunk must be an object, but received: ${typeof s}`);if(!Array.isArray(s.__ops))throw new te(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);for(const r of s.__ops){if(!Array.isArray(r))throw new te(`Transaction operation must be an array, but received: ${typeof r}`);ws(r,t)}}};let Is=0;class ks{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}_${Is++}`,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 i=JSON.parse(r.data);if(Array.isArray(i))for(const o of i)this.handleMessage(o);else this.handleMessage(i)},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 bn;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(bn||(bn={}));function $s({WStream:e,opts:t,startStream:n,appendStream:s,registerStream:r}){const i=t.clientId;let o=null,a=null,c=null;const u=Pe();let h=!1,l=!1;const y=[],m=[],g=[];let w=!1,p=0,$=0;const v=[],V=new TextEncoder;function Re(){l=!0;for(const b of y)b(a??void 0)}function zt(b){return y.push(b),l&&b(a??void 0),()=>{const I=y.indexOf(b);I!==-1&&y.splice(I,1)}}function jn(b){return g.push(b),()=>{const I=g.indexOf(b);I!==-1&&g.splice(I,1)}}t.waitUntil&&t.waitUntil(new Promise(b=>{g.push(b)}));function j(){for(const b of g)try{b()}catch{}}function T(b){return m.push(b),o&&b(o),()=>{const I=m.indexOf(b);I!==-1&&m.splice(I,1)}}function ie(b){o=b;for(const I of m)I(o)}function R(){w=!0}function z(b){let I=p,W=0,Y=0;for(const{byteLen:oe}of v){const he=I+oe;if(he>b)break;I=he,W++,Y+=oe}W>0&&(p+=Y,$-=Y,v.splice(0,W))}function N(b,I){a=I,Re(),b.error(I),j()}async function ne(){const b=await n({clientId:i,reconnectToken:u,ruleParams:t.ruleParams});switch(b.type){case"ok":{const{streamId:I,offset:W}=b;o=I,z(W),v.length&&s({streamId:I,chunks:v.map(Y=>Y.chunk),offset:p}),w=!1;break}case"disconnect":{R();break}case"error":{c&&N(c,b.error);break}}}function J(){R(),ne()}function bt({offset:b,done:I}){z(b),I&&(h=!0,j())}function Un(b){return h?(N(b,new _("Stream has been closed.")),null):o||(N(b,new _("Stream has not been initialized.")),null)}async function We(b){c=b;let I=!0,W=0;for(;I;){let Y=Date.now()+Math.min(15e3,500*(W-1));I=!1;const oe=await n({clientId:t.clientId,reconnectToken:u,ruleParams:t.ruleParams});switch(oe.type){case"ok":{const{streamId:he,offset:Wt}=oe;if(Wt!==0){const Ae=new _("Write stream is corrupted");N(b,Ae);return}ie(he),r(he,{onDisconnect:R,onFlush:bt,onConnectionReconnect:ne,onAppendFailed:J}),w=!1;return}case"disconnect":{I=!0,R(),W++,await new Promise(he=>{setTimeout(he,Math.max(0,Y-Date.now()))});break}case"error":{N(b,oe.error);return}}}}class ge extends e{constructor(I,W){super(I,W)}async streamId(){return o||new Promise((I,W)=>{const Y=[],oe=()=>{for(const Ae of Y)Ae()},he=Ae=>{I(Ae),oe()},Wt=Ae=>{W(Ae||new _("Stream is closed.")),oe()};Y.push(T(he)),Y.push(zt(Wt))})}}return{stream:new ge({async start(b){try{await We(b)}catch(I){N(b,I)}},write(b,I){const W=Un(I);if(W){const Y=V.encode(b).length;v.push({chunk:b,byteLen:Y});const oe=p+$;$+=Y,w||s({streamId:W,chunks:[b],offset:oe})}},close(){o?s({streamId:o,chunks:[],offset:p+$,isDone:!0}):j(),Re()},abort(b){o?s({streamId:o,chunks:[],offset:p+$,isDone:!0,abortReason:b}):j(),Re()}}),addCompleteCb:jn,closed(){return l}}}class vs{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 Os({RStream:e,opts:t,startStream:n,cancelStream:s}){let r=t.byteOffset||0,i=!1;const o=new TextDecoder("utf-8"),a=new TextEncoder;let c,u=!1;const h=[],l=[];let y=null,m=null;function g(j){u=!0;for(const T of h)T(j)}function w(j){return h.push(j),()=>{const T=h.indexOf(j);T!==-1&&h.splice(T,1)}}function p(j){return l.push(j),y&&j(y),()=>{const T=l.indexOf(j);T!==-1&&l.splice(T,1)}}function $(j,T){m=T,j.error(T),g(T)}let v=0;async function V(j,T){c=Pe();const ie={...j||{},eventId:c};for await(const R of n(ie)){if(i)return;if(R.type==="reconnect")return{retry:!0};if(R.type==="error"){$(T,R.error);return}if(R.offset>r){$(T,new _("Stream is corrupted.")),i=!0;return}y=R.streamId;for(const N of l)N(y);let z=r-R.offset;if(R.files&&R.files.length){const N=new AbortController;let ne=fetch(R.files[0].url,{signal:N.signal});for(let J=0;J<R.files.length;J++){const bt=R.files[J+1],We=await ne;if(bt&&(ne=fetch(bt.url,{signal:N.signal})),!We.ok){if(v++,v>10){$(T,new _("Unable to process stream."));return}return{retry:!0}}if(We.body){const ge=We.body.getReader();try{for(;;){const{done:we,value:b}=await ge.read();if(we)break;if(i){N.abort();return}let I=b;if(z>0&&(I=b.subarray(z),z-=b.length-I.length),!I.length)continue;r+=I.length;const W=o.decode(I);T.enqueue(W)}}finally{ge.releaseLock()}}else{const ge=await We.arrayBuffer();let we=ge;if(i){N.abort();return}if(z>0&&(we=new Uint8Array(ge).subarray(z),z-=ge.byteLength-we.length),!we.byteLength)continue;r+=we.byteLength;const b=o.decode(we);T.enqueue(b)}}}if(v=0,R.content){let N=R.content,ne=a.encode(R.content);if(z>0){const J=ne.subarray(z);if(z-=ne.length-J.length,!J.length)continue;ne=J,N=o.decode(J)}r+=ne.length,T.enqueue(N)}}}async function Re(j){let T=!0,ie=0;for(;T;){T=!1;let R=Date.now()+Math.min(15e3,500*(ie-1));const z=await V({...t,offset:r},j);z!=null&&z.retry&&(T=!0,ie++,R<Date.now()-3e5&&(ie=0),await new Promise(N=>{setTimeout(N,Math.max(0,R-Date.now()))}))}!i&&!u&&(j.close(),g())}class zt extends e{constructor(T,ie){super(T,ie)}async streamId(){if(y)return y;if(m)throw m;return new Promise((T,ie)=>{const R=[],z=()=>{for(const J of R)J()},N=J=>{T(J),z()},ne=J=>{ie(J||new _("Stream is closed.")),z()};R.push(p(N)),R.push(w(ne))})}}return{stream:new zt({start(j){Re(j)},cancel(j){i=!0,c&&s({eventId:c}),g()}}),addCloseCb:w,closed(){return u}}}class Es{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}=$s({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}=Os({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=Pe();let s=null;const r=new Promise(o=>{s=o});this.startWriteStreamCbs[n]=s;const i={op:"start-stream","client-id":t.clientId,"reconnect-token":t.reconnectToken};return t.ruleParams&&(i["rule-params"]=t.ruleParams),this.trySend(n,i),r}registerWriteStream(t,n){this.writeStreams[t]=n}appendStream({streamId:t,chunks:n,isDone:s,offset:r,abortReason:i}){const o={op:"append-stream","stream-id":t,chunks:n,offset:r,done:!!s};i&&(o["abort-reason"]=i),this.trySend(Pe(),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:r,ruleParams:i}){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),r&&(o.offset=r),i&&(o["rule-params"]=i);const a=new vs;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(Pe(),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 _(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!==Cs.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 _(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 _(t.message||"Unknown error",t.hint)}),r.close(),delete this.readStreamIterators[s]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const Cs={AUTHENTICATED:"authenticated"};class xs extends _{constructor(t){super(t),this.name="MissingApiURIError"}get[Symbol.toStringTag](){return"MissingApiURIError"}}function Ts({target:e,option:t="apiURI",envVar:n}){return`No SidekickDB server URL configured. ${n?`Pass \`${t}\` to ${e} or set the ${n} environment variable`:`Pass \`${t}\` to ${e}`}, for example ${t}: 'https://sidekick.example.com'. SidekickDB has no default server.`}function Rt(e,t){if(typeof e=="string"&&e.trim()!=="")return e;throw new xs(Ts(t))}function _s(){return globalThis.__instantDbSchemaHashStore=globalThis.__instantDbSchemaHashStore??new WeakMap,globalThis.__instantDbSchemaHashStore}function Rs(){return globalThis.__instantDbStore=globalThis.__instantDbStore??{},globalThis.__instantDbStore}Rs(),_s();class gn extends Event{constructor(n,s){super(n);d(this,"code");d(this,"message");this.code=(s==null?void 0:s.code)??void 0,this.message=(s==null?void 0:s.message)??void 0}[Symbol.for("nodejs.util.inspect.custom")](n,s,r){return r(wn(this),s)}[Symbol.for("Deno.customInspect")](n,s){return n(wn(this),s)}}function As(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function At(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(At).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${At(e.cause)}`:e.message:`${e}`}function wn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}class Sn 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 Pt(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=Pt,onError:n=Pt,onRetry:s=Pt,onComment:r}=e;let i="",o=!0,a,c="",u="";function h(w){const p=o?w.replace(/^\xEF\xBB\xBF/,""):w,[$,v]=js(`${i}${p}`);for(const V of $)l(V);i=v,o=!1}function l(w){if(w===""){m();return}if(w.startsWith(":")){r&&r(w.slice(w.startsWith(": ")?2:1));return}const p=w.indexOf(":");if(p!==-1){const $=w.slice(0,p),v=w[p+1]===" "?2:1,V=w.slice(p+v);y($,V,w);return}y(w,"",w)}function y(w,p,$){switch(w){case"event":u=p;break;case"data":c=`${c}${p}
2
- `;break;case"id":a=p.includes("\0")?void 0:p;break;case"retry":/^\d+$/.test(p)?s(parseInt(p,10)):n(new Sn(`Invalid \`retry\` value: "${p}"`,{type:"invalid-retry",value:p,line:$}));break;default:n(new Sn(`Unknown field "${w.length>20?`${w.slice(0,20)}…`:w}"`,{type:"unknown-field",field:w,value:p,line:$}));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={}){i&&w.consume&&l(i),o=!0,a=void 0,c="",u="",i=""}return{feed:h,reset:g}}function js(e){const t=[];let n="",s=0;for(;s<e.length;){const r=e.indexOf("\r",s),i=e.indexOf(`
4
- `,s);let o=-1;if(r!==-1&&i!==-1?o=Math.min(r,i):r!==-1?r===e.length-1?o=-1:o=r:i!==-1&&(o=i),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 re extends EventTarget{constructor(n,s){super();k(this,B);d(this,"CONNECTING",0);d(this,"OPEN",1);d(this,"CLOSED",2);k(this,q);k(this,be);k(this,ve);k(this,qe);k(this,Be);k(this,Qe);k(this,Me);k(this,Oe);k(this,De,null);k(this,le);k(this,Ee);k(this,Ce,null);k(this,xe,null);k(this,Ne,null);k(this,ct,async n=>{var y;f(this,Ee).reset();const{body:s,redirected:r,status:i,headers:o}=n;if(i===204){O(this,B,Ze).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(r?S(this,ve,new URL(n.url)):S(this,ve,void 0),i!==200){O(this,B,Ze).call(this,`Non-200 status code (${i})`,i);return}if(!(o.get("content-type")||"").startsWith("text/event-stream")){O(this,B,Ze).call(this,'Invalid content type, expected "text/event-stream"',i);return}if(f(this,q)===this.CLOSED)return;S(this,q,this.OPEN);const c=new Event("open");if((y=f(this,Ne))==null||y.call(this,c),this.dispatchEvent(c),typeof s!="object"||!s||!("getReader"in s)){O(this,B,Ze).call(this,"Invalid response body, expected a web ReadableStream",i),this.close();return}const u=new TextDecoder,h=s.getReader();let l=!0;do{const{done:m,value:g}=await h.read();g&&f(this,Ee).feed(u.decode(g,{stream:!m})),m&&(l=!1,f(this,Ee).reset(),O(this,B,Jt).call(this))}while(l)});k(this,ut,n=>{S(this,le,void 0),!(n.name==="AbortError"||n.type==="aborted")&&O(this,B,Jt).call(this,At(n))});k(this,ft,n=>{typeof n.id=="string"&&S(this,De,n.id);const s=new(f(this,Qe))(n.event||"message",{data:n.data,origin:f(this,ve)?f(this,ve).origin:f(this,be).origin,lastEventId:n.id||""});f(this,xe)&&(!n.event||n.event==="message")&&f(this,xe).call(this,s),this.dispatchEvent(s)});k(this,dt,n=>{S(this,Me,n)});k(this,lt,()=>{S(this,Oe,void 0),f(this,q)===this.CONNECTING&&O(this,B,Vt).call(this)});try{if(n instanceof URL)S(this,be,n);else if(typeof n=="string")S(this,be,new URL(n,Us()));else throw new Error("Invalid URL")}catch{throw As("An invalid or illegal string was specified")}S(this,Ee,Ps({onEvent:f(this,ft),onRetry:f(this,dt)})),S(this,q,this.CONNECTING),S(this,Me,3e3),S(this,Be,(s==null?void 0:s.fetch)??globalThis.fetch),S(this,Qe,(s==null?void 0:s.messageEvent)??globalThis.MessageEvent),S(this,qe,(s==null?void 0:s.withCredentials)??!1),O(this,B,Vt).call(this)}get readyState(){return f(this,q)}get url(){return f(this,be).href}get withCredentials(){return f(this,qe)}get onerror(){return f(this,Ce)}set onerror(n){S(this,Ce,n)}get onmessage(){return f(this,xe)}set onmessage(n){S(this,xe,n)}get onopen(){return f(this,Ne)}set onopen(n){S(this,Ne,n)}addEventListener(n,s,r){const i=s;super.addEventListener(n,i,r)}removeEventListener(n,s,r){const i=s;super.removeEventListener(n,i,r)}close(){f(this,Oe)&&clearTimeout(f(this,Oe)),f(this,q)!==this.CLOSED&&(f(this,le)&&f(this,le).abort(),S(this,q,this.CLOSED),S(this,le,void 0))}}q=new WeakMap,be=new WeakMap,ve=new WeakMap,qe=new WeakMap,Be=new WeakMap,Qe=new WeakMap,Me=new WeakMap,Oe=new WeakMap,De=new WeakMap,le=new WeakMap,Ee=new WeakMap,Ce=new WeakMap,xe=new WeakMap,Ne=new WeakMap,B=new WeakSet,Vt=function(){S(this,q,this.CONNECTING),S(this,le,new AbortController),f(this,Be)(f(this,be),O(this,B,Dn).call(this)).then(f(this,ct)).catch(f(this,ut))},ct=new WeakMap,ut=new WeakMap,Dn=function(){var r;const s={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...f(this,De)?{"Last-Event-ID":f(this,De)}:void 0},cache:"no-store",signal:(r=f(this,le))==null?void 0:r.signal};return"window"in globalThis&&(s.credentials=this.withCredentials?"include":"same-origin"),s},ft=new WeakMap,dt=new WeakMap,Ze=function(n,s){var i;f(this,q)!==this.CLOSED&&S(this,q,this.CLOSED);const r=new gn("error",{code:s,message:n});(i=f(this,Ce))==null||i.call(this,r),this.dispatchEvent(r)},Jt=function(n,s){var i;if(f(this,q)===this.CLOSED)return;S(this,q,this.CONNECTING);const r=new gn("error",{code:s,message:n});(i=f(this,Ce))==null||i.call(this,r),this.dispatchEvent(r),S(this,Oe,setTimeout(f(this,lt),f(this,Me)))},lt=new WeakMap,d(re,"CONNECTING",0),d(re,"OPEN",1),d(re,"CLOSED",2),Object.defineProperty(re,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 In 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,i,o,a,c,u){}}function Ms(e,t,n,s){let r=null,i=!1;const o=[],a=l=>{o.push(l),o.length>100&&o.shift(),r&&(r(),r=null)};e(a);const c=()=>(n(a),Promise.resolve({done:!0,value:void 0}));return t(()=>{i=!0,r&&r(),c()}),{next:async()=>{for(;;){if(s()==="closed"||i)return c();const l=o.shift();if(l)return{value:l,done:!1};await new Promise(m=>{r=m})}},return:c,throw(l){return n(a),Promise.reject(l)},[Symbol.asyncIterator](){return this}}}function ye(e){switch(e.readyState){case e.CLOSED:return"closed";case e.CONNECTING:return"connecting";case e.OPEN:return"open";default:return"connecting"}}function Ds(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 kn(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 Ns(e,t,n){let s,r=!1;const i=Pe(),o=new re(`${n.apiURI}/admin/subscribe-query?local_connection_id=${i}`,{messageEvent:In,fetch(p,$){return s=null,fetch(p,{...$,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@instantdb/admin":$e,"@instantdb/core":$e}})}).then(v=>(v.ok||(s=Ds(v)),v))}}),a=[],c=[],u=p=>{a.push(p)},h=p=>{a.splice(a.indexOf(p),1)},l=p=>{c.push(p)};t&&u(t);let y=null;function m(p){if(!r)for(const $ of a)try{$(p)}catch(v){console.error("Error in subscribeQuery callback",v)}}function g(p){var $,v;switch(p.op){case"sse-init":{const V=p["machine-id"],Re=p["session-id"];y={machineId:V,sessionId:Re};break}case"add-query-ok":{m({type:"ok",data:p.result,pageInfo:kn(($=p["result-meta"])==null?void 0:$["page-info"]),sessionInfo:y});break}case"refresh-ok":{p.computations.length&&m({type:"ok",data:p.computations[0]["instaql-result"],pageInfo:kn((v=p.computations[0]["result-meta"])==null?void 0:v["page-info"]),sessionInfo:y});break}case"error":{m({type:"error",error:new ue({body:p,status:p.status}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:y});break}}}return o.onerror=p=>{if(s)s.text().then($=>{let v={type:void 0,message:$};try{v=JSON.parse($)}catch{}m({type:"error",error:new ue({status:s.status,body:v}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:y})});else{const $=()=>{m({type:"error",error:new ue({status:p.code||500,body:{type:void 0,message:p.message||"Unknown error in subscribe query."}}),get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},sessionInfo:y})};if(o.readyState===re.CLOSED){$();return}setTimeout(()=>{o.readyState!==re.OPEN&&$()},5e3)}},o.onmessage=p=>{g(JSON.parse(p.data))},{close:()=>{r=!0;for(const p of c)try{p()}catch($){console.error("Error in onClose callback",$)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return y},get readyState(){return ye(o)},get isClosed(){return ye(o)==="closed"},[Symbol.asyncIterator]:Ms.bind(this,u,l,h,()=>1)}}var de={};Object.defineProperty(de,"__esModule",{value:!0});var Ls=de.parseCookie=On;de.parse=On,de.stringifyCookie=Js,de.stringifySetCookie=it,de.serialize=it,de.parseSetCookie=Hs,de.stringifySetCookie=it,de.serialize=it;const $n=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,vn=/^[\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]*$/,Ws=/^-?\d+$/,Ks=Object.prototype.toString,Vs=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function On(e,t){const n=new Vs,s=e.length;if(s<2)return n;const r=(t==null?void 0:t.decode)||En;let i=0;do{const o=Ut(e,i,s);if(o===-1)break;const a=jt(e,i,s);if(o>a){i=e.lastIndexOf(";",o-1)+1;continue}const c=me(e,i,o);n[c]===void 0&&(n[c]=r(me(e,o+1,a))),i=a+1}while(i<s);return n}function Js(e,t){const n=(t==null?void 0:t.encode)||encodeURIComponent,s=[];for(const r of Object.keys(e)){const i=e[r];if(i===void 0)continue;if(!$n.test(r))throw new TypeError(`cookie name is invalid: ${r}`);const o=n(i);if(!vn.test(o))throw new TypeError(`cookie val is invalid: ${i}`);s.push(`${r}=${o}`)}return s.join("; ")}function it(e,t,n){const s=typeof e=="object"?e:{...n,name:e,value:String(t)},r=typeof t=="object"?t:n,i=(r==null?void 0:r.encode)||encodeURIComponent;if(!$n.test(s.name))throw new TypeError(`argument name is invalid: ${s.name}`);const o=s.value?i(s.value):"";if(!vn.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(!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(!qs(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 Hs(e,t){const n=(t==null?void 0:t.decode)||En,s=e.length,r=jt(e,0,s),i=Ut(e,0,r),o=i===-1?{name:"",value:n(me(e,0,r))}:{name:me(e,0,i),value:n(me(e,i+1,r))};let a=r+1;for(;a<s;){const c=jt(e,a,s),u=Ut(e,a,c),h=u===-1?me(e,a,c):me(e,a,u),l=u===-1?void 0:me(e,u+1,c);switch(h.toLowerCase()){case"httponly":o.httpOnly=!0;break;case"secure":o.secure=!0;break;case"partitioned":o.partitioned=!0;break;case"domain":o.domain=l;break;case"path":o.path=l;break;case"max-age":l&&Ws.test(l)&&(o.maxAge=Number(l));break;case"expires":if(!l)break;const y=new Date(l);Number.isFinite(y.valueOf())&&(o.expires=y);break;case"priority":if(!l)break;const m=l.toLowerCase();(m==="low"||m==="medium"||m==="high")&&(o.priority=m);break;case"samesite":if(!l)break;const g=l.toLowerCase();(g==="lax"||g==="strict"||g==="none")&&(o.sameSite=g);break}a=c+1}return o}function jt(e,t,n){const s=e.indexOf(";",t);return s===-1?n:s}function Ut(e,t,n){const s=e.indexOf("=",t);return s<n?s:-1}function me(e,t,n){let s=t,r=n;do{const i=e.charCodeAt(s);if(i!==32&&i!==9)break}while(++s<r);for(;r>s;){const i=e.charCodeAt(r-1);if(i!==32&&i!==9)break;r--}return e.slice(s,r)}function En(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function qs(e){return Ks.call(e)==="[object Date]"}const Bs={"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 Qs(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 Gs(e){const t=Qs(e),n=await crypto.subtle.importKey("jwk",e,t,!1,["verify"]);return{alg:t,key:n}}function Xs(e,t,n,s){return crypto.subtle.verify(e,t,n,s)}function Ys(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 Zs(e){let t,n,s;for(const i of e.split(",")){const[o,a]=i.split("=");switch(o){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 _("Invalid Instant-Signature header.",{header:e,missingKeys:r});return{t,kid:n,v1:s}}function er(e,t,n){if(Math.floor(e.getTime()/1e3)-parseInt(t,10)>n)throw new _("Webhook signature is too old",{tolerance:n,receivedAt:e,t})}const Cn={},tr=300;async function nr(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new ue({status:t.status,body:s}))}catch{return e(new ue({status:t.status,body:{type:void 0,message:n}}))}}const sr=async(e,t)=>{const n={...(t==null?void 0:t.headers)||{},"Instant-Core-Version":$e},s=await fetch(e,{...t,headers:n});return s.status===200?s.json():nr(r=>Promise.reject(r),s)};function xn(e){return e?new Date(e):null}function Ue(e){return{id:e.id,sink:e.sink,namespaces:e.namespaces??[],actions:e.actions,status:e.status,disabledReason:e.disabled_reason??null,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function rr(e){return{attemptAt:xn(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 Mt(e){return{isn:e.isn,status:e.status,attempts:e.attempts?e.attempts.map(rr):null,nextAttemptAfter:xn(e.next_attempt_after),createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}class ir{constructor(t){k(this,ee);k(this,Q);k(this,Ge);k(this,Le);k(this,Fe);k(this,Xe);S(this,Q,t.appId),S(this,Ge,t.apiURI),S(this,Le,t.token),S(this,Fe,t.withAuth),S(this,Xe,t.jsonFetch)}async list(){return((await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks`)).webhooks||[]).map(Ue)}async create(t){const n=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks`,{method:"POST",body:t});return Ue(n.webhook)}async update(t,n){const s=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}`,{method:"POST",body:n});return Ue(s.webhook)}async delete(t){const n=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}`,{method:"DELETE"});return Ue(n.webhook)}async enable(t){const n=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/enable`,{method:"POST",body:{}});return Ue(n.webhook)}async disable(t,n){const s=n!=null&&n.reason?{reason:n.reason}:{},r=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/disable`,{method:"POST",body:s});return Ue(r.webhook)}async listEvents(t,n){var i,o,a;const s=n!=null&&n.after?`?after=${encodeURIComponent(n.after)}`:"",r=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events${s}`);return{events:(r.events||[]).map(Mt),pageInfo:{startCursor:((i=r.pageInfo)==null?void 0:i.startCursor)??null,endCursor:((o=r.pageInfo)==null?void 0:o.endCursor)??null,hasNextPage:!!((a=r.pageInfo)!=null&&a.hasNextPage)}}}async getEvent(t,n){const s=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events/${n}`);return Mt(s.event)}async getPayload(t,n){return O(this,ee,ae).call(this,`/webhooks/payload/${f(this,Q)}/${t}/${n}`)}async resendEvent(t,n){const s=await O(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events/${n}`,{method:"POST",body:{}});return Mt(s.event)}}Q=new WeakMap,Ge=new WeakMap,Le=new WeakMap,Fe=new WeakMap,Xe=new WeakMap,ee=new WeakSet,ae=function(t,n){if(!f(this,Q))throw new _("appId is required to manage webhooks. Pass it to the Webhooks constructor.");const s=r=>{const i={method:n==null?void 0:n.method,headers:{authorization:`Bearer ${r}`,"content-type":"application/json"}};return(n==null?void 0:n.body)!==void 0&&(i.body=JSON.stringify(n.body)),f(this,Xe).call(this,`${f(this,Ge)}${t}`,i)};if(f(this,Fe))return f(this,Fe).call(this,s);if(!f(this,Le))throw new _("A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.");return s(f(this,Le))};const Lt=class Lt{constructor(t,n){d(this,"appId");d(this,"schema");k(this,Ye);d(this,"apiURI");k(this,Te);d(this,"manager");this.appId=t.appId,this.schema=t.schema,S(this,Ye,t.adminToken||t.token),this.apiURI=Rt(t.apiURI,{target:"new Webhooks()"}),S(this,Te,n||sr),this.manager=new ir({appId:this.appId,apiURI:this.apiURI,token:f(this,Ye),withAuth:t.withAuth,jsonFetch:f(this,Te)})}static helpers(){function t(...s){if(s.length===2)return{$default:s[1]};const[r,i,o]=s;return{[r]:{[i]:o}}}function n(...s){const r={};for(const i of s)for(const o of Object.keys(i))o==="$default"?r.$default=i.$default:r[o]={...r[o],...i[o]};return r}return{typedHandlers:t,combineHandlers:n}}helpers(){return Lt.helpers()}async fetchJwks(){return await f(this,Te).call(this,`${this.apiURI}/.well-known/webhooks/jwks.json`)}async keyOfKid(t){var o,a,c;const n=`${this.apiURI}:${t}`,s=Cn[n];if(s)return s;const r=((o=Bs[this.apiURI])==null?void 0:o.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 _("Could not find matching signing key",{kid:t});const i=await Gs(r);return Cn[n]=i,i}async validate(t,n,s){const r=(s==null?void 0:s.receivedAt)||new Date,{t:i,kid:o,v1:a}=Zs(t),c=(s==null?void 0:s.tolerance)??tr;er(r,i,c);const{alg:u,key:h}=await this.keyOfKid(o),l=typeof n=="function"?await n():n,y=new TextEncoder().encode(`${i}.${l}`);if(!await Xs(u,h,Ys(a),y))throw new _("Instant Signature did not validate",{header:t});const g=JSON.parse(l);if(typeof g!="object"||typeof g.payloadUrl!="string"||typeof g.token!="string")throw new _("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 _("Request is missing Instant-Signature header");return this.validate(s,()=>t.text(),n)}fetchPayloads({payloadUrl:t,token:n}){return f(this,Te).call(this,t,{headers:{Authorization:`Bearer ${n}`,accept:"application/json"}})}async processPayload(t,n){var r,i;const s=[];for(const o of n.data){const{namespace:a,action:c}=o,u=((r=t==null?void 0:t[a])==null?void 0:r[c])||((i=t==null?void 0:t[a])==null?void 0:i.$default)||(t==null?void 0:t.$default);u&&s.push(u(o))}await Promise.all(s)}async processRequest(t,n,s){const r=await this.validateRequest(n,s),i=await this.fetchPayloads(r);await this.processPayload(t,i)}async processNodeRequest(t,n,s){let r,i=!1,o=(s==null?void 0:s.body)??n.rawBody??n.body;if(o!=null&&typeof o.then=="function"&&(o=await o),typeof o=="string")r=o;else if(o instanceof Uint8Array)r=new TextDecoder("utf-8").decode(o);else if(o!=null&&typeof o=="object")try{r=JSON.stringify(o),i=!0}catch{throw new _("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 l=new TextEncoder,y=[];for await(const p of n)y.push(typeof p=="string"?l.encode(p):p);let m=0;for(const p of y)m+=p.byteLength;const g=new Uint8Array(m);let w=0;for(const p of y)g.set(p,w),w+=p.byteLength;r=new TextDecoder("utf-8").decode(g)}else throw new _("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[l,y]of Object.entries(n.headers))typeof y=="string"?u.set(l,y):Array.isArray(y)&&u.set(l,y.join(", "));const h=new Request(c,{method:n.method??"POST",headers:u,body:r});try{await this.processRequest(t,h,s)}catch(l){throw i&&l instanceof _&&l.message==="Instant Signature did not validate"?new _("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:l.hint}):l}}};Ye=new WeakMap,Te=new WeakMap;let Dt=Lt;const or={target:"init() in @sidekickdb/admin"};function ar(e){return{...e,apiURI:Rt(e.apiURI,or)}}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 U(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 ue({status:t.status,body:s}))}catch{return e(new ue({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=dr(),s={...(t==null?void 0:t.headers)||{},"Instant-Admin-Version":$e,"Instant-Core-Version":$e},r=await fetch(e,{...n,...t,headers:s});if(r.status===200){const i=await r.json();return Promise.resolve(i)}return lr(i=>Promise.reject(i),r)}function hr(e){var t,n,Nn;return t=class{constructor(i){k(this,n);d(this,"source");d(this,"url");this.url=i,this.source=O(this,n,Nn).call(this,i)}get onopen(){return this.source.onopen}set onopen(i){this.source.onopen=i}get onmessage(){return this.source.onmessage}set onmessage(i){this.source.onmessage=i}get onerror(){return this.source.onerror}set onerror(i){this.source.onerror=i}get readyState(){return this.source.readyState}close(){this.source.close()}},n=new WeakSet,Nn=function(i){return new re(i,{messageEvent:In,fetch(a,c){return fetch(a,{...c,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@instantdb/admin":$e,"@instantdb/core":$e}})})}})},d(t,"OPEN",re.OPEN),d(t,"CONNECTING",re.CONNECTING),d(t,"CLOSED",re.CLOSED),t}function pr(e){var n,s;(!e.appId||!P(e.appId))&&console.warn("warning: SidekickDB 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 Nt(t)}function Tn(e){return(Array.isArray(e)?e:[e]).flatMap(ds)}class yr{constructor(t){d(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:U(this.config)})).sessions||{}}}class mr{constructor(t){d(this,"config");d(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t})}));d(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t})}));d(this,"verifyMagicCode",async(t,n)=>{const{user:s}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t,code:n})});return s});d(this,"checkMagicCode",async(t,n,s)=>{const r=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(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 M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);d(this,"getUser",async t=>{const n=new URLSearchParams(Object.entries(t)).toString();return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:U(this.config)})).user});d(this,"deleteUser",async t=>{const n=new URLSearchParams(Object.entries(t)).toString();return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:U(this.config)})).deleted});d(this,"getUserFromRequest",async(t,n)=>{const s=t.headers.get("cookie")||"",r=Ls(s),i="instant_user_"+this.config.appId;if(!r[i])return null;const o=r[i],a=JSON.parse(o);return a!=null&&a.refresh_token?n!=null&&n.disableValidation?a:await this.verifyToken(a.refresh_token):null});this.config=t,this.createToken=this.createToken.bind(this)}async createToken(t){const n=typeof t=="string"?{email:t}:t;return(await M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,s=this.config;await M(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:U(s),body:JSON.stringify(n)})}}const _n=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",br=e=>e&&typeof e.getReader=="function";function Rn(e){return/^[\x20-\x7e\xa0-\xff]*$/.test(e)}class An{constructor(t,n){d(this,"config");d(this,"impersonationOpts");d(this,"uploadFile",async(t,n,s={})=>{const r={...U(this.config,this.impersonationOpts)};Rn(t)&&(r.path=t),s.contentDisposition&&Rn(s.contentDisposition)&&(r["content-disposition"]=s.contentDisposition),delete r["content-type"],s.contentType&&(r["content-type"]=s.contentType);let i;if(_n(n)&&(i="half"),_n(n)||br(n)){if(!s.fileSize)throw new Error("fileSize is required in metadata when uploading streams");r["content-length"]=s.fileSize.toString()}let o={method:"PUT",headers:r,body:n,...i&&{duplex:i}},a=`${this.config.apiURI}/admin/storage/upload?app_id=${encodeURIComponent(this.config.appId)}&path=${encodeURIComponent(t)}`;return s.contentDisposition&&(a+=`&content-disposition=${encodeURIComponent(s.contentDisposition)}`),M(a,o)});d(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:U(this.config,this.impersonationOpts)}));d(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));d(this,"upload",async(t,n,s={})=>{const{data:r}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({app_id:this.config.appId,filename:t})}),i={},o=s.contentType;o&&(i["Content-Type"]=o);const{ok:a}=await fetch(r,{method:"PUT",body:n,headers:i});return a});d(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:U(this.config)});return t});d(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:U(this.config)});return n});this.config=t,this.impersonationOpts=n}}class gr{constructor(t){k(this,ze);d(this,"createReadStream",t=>f(this,ze).call(this).createReadStream(t));d(this,"createWriteStream",t=>f(this,ze).call(this).createWriteStream(t));S(this,ze,t)}}ze=new WeakMap;function wr(e,t=console){return{info:e?(...n)=>t.info(...n):()=>{},debug:e?(...n)=>t.debug(...n):()=>{},error:e?(...n)=>t.error(...n):()=>{}}}const Ft=class Ft{constructor(t){k(this,F);d(this,"config");d(this,"auth");d(this,"storage");d(this,"streams");d(this,"rooms");d(this,"impersonationOpts");d(this,"webhooks");k(this,K,null);k(this,_e,0);k(this,G,null);k(this,X);d(this,"tx",an());d(this,"asUser",t=>{const n=new Ft({...this.config});return n.impersonationOpts=t,n.storage=new An(this.config,t),n});d(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||ln(t,this.config.schema);const s=n.fetchOpts||{},r=s.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...s,method:"POST",headers:{...r,...U(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});d(this,"transact",t=>(this.config.disableValidation||Ss(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify({steps:Tn(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 M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify(s)});return{result:r.result,checkResults:r["check-results"]}});d(this,"debugTransact",(t,n)=>{const s={steps:Tn(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),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify(s)})});k(this,ht,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][open]",t.target.id),S(this,_e,0),(n=f(this,G))==null||n.onConnectionStatusChange("authenticated")});k(this,pt,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][close]",t.target.id),(n=f(this,G))==null||n.onConnectionStatusChange("closed"),f(this,K)&&(S(this,K,null),O(this,F,Ht).call(this)||(setTimeout(()=>O(this,F,gt).call(this),f(this,_e)),S(this,_e,Math.min(15e3,Math.max(f(this,_e),500)*2))))});k(this,yt,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][error]",t.target.id),(n=f(this,G))==null||n.onConnectionStatusChange("closed")});k(this,mt,t=>{var s,r,i,o,a,c;if(t.target!==f(this,K)){f(this,X).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(f(this,X).info("[receive]",n),n.op){case"start-stream-ok":{(s=f(this,G))==null||s.onStartStreamOk(n);break}case"stream-flushed":{(r=f(this,G))==null||r.onStreamFlushed(n);break}case"append-failed":{(i=f(this,G))==null||i.onAppendFailed(n);break}case"stream-append":{(o=f(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=f(this,G))==null||c.onRecieveError(n);break}}break}}O(this,F,Kn).call(this)});this.config=ar(t),this.auth=new mr(this.config),this.storage=new An(this.config,this.impersonationOpts),this.streams=new gr(O(this,F,Wn).bind(this)),this.rooms=new yr(this.config),this.webhooks=new Dt(this.config,M),S(this,X,wr(!!this.config.verbose,this.config.logger))}subscribeQuery(t,n,s={}){t&&s&&"ruleParams"in s&&(t={$$ruleParams:s.ruleParams,...t}),this.config.disableValidation||ln(t,this.config.schema);const o={...(s.fetchOpts||{}).headers||{},...U(this.config,this.impersonationOpts)},a=!!this.config.schema;return Ns(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};K=new WeakMap,_e=new WeakMap,G=new WeakMap,X=new WeakMap,F=new WeakSet,Ln=function(){f(this,K)&&f(this,K).close();const t={...U(this.config,this.impersonationOpts)},n=!!this.config.schema,s=hr({headers:t,inference:n}),r=new ks(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=f(this,ht),r.onmessage=f(this,mt),r.onclose=f(this,pt),r.onerror=f(this,yt),S(this,K,r),r},gt=function(){return f(this,K)||O(this,F,Ln).call(this)},Fn=function(t,n){const s=O(this,F,gt).call(this);f(this,X).info("[send]",t,n,{isOpen:s.isOpen()}),s.isOpen()&&s.send({"client-event-id":t,...n})},zn=function(){O(this,F,gt).call(this);const t=new Es({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,s)=>{O(this,F,Fn).call(this,n,s)},log:f(this,X)});return S(this,G,t),t},Wn=function(){return f(this,G)||O(this,F,zn).call(this)},ht=new WeakMap,pt=new WeakMap,yt=new WeakMap,Ht=function(){return!f(this,G)||!f(this,G).hasActiveStreams()},Kn=function(){if(f(this,K)&&O(this,F,Ht).call(this)){const t=f(this,K);f(this,X).info("cleaning up unused socket",t.id),S(this,K,null),t.close()}},mt=new WeakMap;let Nt=Ft;var Pn={};function ot(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 at(e){return[Pn[e],Pn[e.replace("SIDEKICK_","INSTANT_")]].find(t=>t==null?void 0:t.trim())}function Sr(e){const t=e.appId||at("SIDEKICK_APP_ID")||at("NEXT_PUBLIC_SIDEKICK_APP_ID");if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.");const n=e.adminToken||at("SIDEKICK_APP_ADMIN_TOKEN");if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.");const s=Rt(e.apiURI||at("SIDEKICK_API_URI"),{target:"createResumableStreamContext()",envVar:"SIDEKICK_API_URI"}),r={appId:t,adminToken:n,apiURI:s};e.verbose&&(r.verbose=e.verbose);const i=pr(r);async function o(h,l,y){const m=i.streams.createWriteStream({clientId:h,waitUntil:e.waitUntil??void 0});try{const g=await m.streamId();l().pipeTo(m);const p=i.streams.createReadStream({streamId:g});return y?p.pipeThrough(ot(y)):p}catch{const w=i.streams.createReadStream({clientId:h});return y?w.pipeThrough(ot(y)):w}}async function a(h,l){var m,g,w;const y=i.streams.createReadStream({clientId:h});try{await y.streamId()}catch(p){if(p instanceof _&&((w=(g=(m=p.hint)==null?void 0:m.errors)==null?void 0:g[0])==null?void 0:w.message)==="Stream is missing.")return;throw p}return l?y.pipeThrough(ot(l)):y}async function c(h,l,y){const m=l(),g=i.streams.createWriteStream({clientId:h,waitUntil:e.waitUntil??void 0});await g.streamId(),m.pipeTo(g);const w=i.streams.createReadStream({clientId:h});return y?w.pipeThrough(ot(y)):w}async function u(h){var m;const l=await i.query({$streams:{$:{where:{clientId:h}}}}),y=(m=l==null?void 0:l.$streams)==null?void 0:m[0];return y!=null&&y.done?"DONE":y?!0:null}return{resumableStream:o,resumeExistingStream:a,createNewResumableStream:c,hasExistingStream:u}}E.createResumableStreamContext=Sr,Object.defineProperty(E,Symbol.toStringTag,{value:"Module"})});
1
+ (function(C,T){typeof exports=="object"&&typeof module<"u"?T(exports):typeof define=="function"&&define.amd?define(["exports"],T):(C=typeof globalThis<"u"?globalThis:C||self,T(C.sidekick={}))})(this,function(C){"use strict";var Hi=Object.defineProperty;var Gn=C=>{throw TypeError(C)};var Bi=(C,T,P)=>T in C?Hi(C,T,{enumerable:!0,configurable:!0,writable:!0,value:P}):C[T]=P;var l=(C,T,P)=>Bi(C,typeof T!="symbol"?T+"":T,P),Xt=(C,T,P)=>T.has(C)||Gn("Cannot "+P);var f=(C,T,P)=>(Xt(C,T,"read from private field"),P?P.call(C):T.get(C)),k=(C,T,P)=>T.has(C)?Gn("Cannot add the same private member more than once"):T instanceof WeakSet?T.add(C):T.set(C,P),I=(C,T,P,D)=>(Xt(C,T,"write to private field"),D?D.call(C,P):T.set(C,P),P),E=(C,T,P)=>(Xt(C,T,"access private method"),P);var B,ge,Oe,Ge,Xe,Ye,Ne,Ee,Le,he,Ce,xe,Te,Fe,q,Yt,pt,yt,Xn,mt,bt,st,Zt,gt,Q,Ze,We,ze,et,ee,ae,tt,_e,nt,en,Ke,K,Ae,G,X,F,Zn,$t,es,ts,ns,wt,St,kt,tn,ss,It;const T=/^(?:[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 P(e){return typeof e=="string"&&T.test(e)}const D=[];for(let e=0;e<256;++e)D.push((e+256).toString(16).slice(1));function is(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 Ot;const rs=new Uint8Array(16);function os(){if(!Ot){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Ot=crypto.getRandomValues.bind(crypto)}return Ot(rs)}const nn={randomUUID:typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function as(e,t,n){var i;if(nn.randomUUID&&!e)return nn.randomUUID();e=e||{};const s=e.random??((i=e.rng)==null?void 0:i.call(e))??os();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,is(s)}const L={Remove:"remove",Replace:"replace",Add:"add"},sn=Symbol.for("__MUTATIVE_PROXY_DRAFT__"),it=Symbol.iterator,se={mutable:"mutable",immutable:"immutable"},Et={};function Je(e,t){return e instanceof Map?e.has(t):Object.prototype.hasOwnProperty.call(e,t)}function rn(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 on(e){return Object.getPrototypeOf(e)===Set.prototype}function an(e){return Object.getPrototypeOf(e)===Map.prototype}function Z(e){var t;return(t=e.copy)!==null&&t!==void 0?t:e.original}function Ct(e){return!!x(e)}function x(e){return typeof e!="object"?null:e==null?void 0:e[sn]}function xt(e){var t;const n=x(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,se))===se.immutable||typeof n=="function")}function cn(e,t=[]){if(Object.hasOwnProperty.call(e,"key")){const n=e.parent.copy,s=x(ye(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||Je(n,r)))return null;t.push(r)}if(e.parent)return cn(e.parent,t);t.reverse();try{cs(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 ye(e,t){return He(e)===2?e.get(t):e[t]}function Tt(e,t,n){He(e)===2?e.set(t,n):e[t]=n}function _t(e,t){const n=x(e);return(n?Z(n):e)[t]}function Ie(e,t){return e===t?e!==0||1/e===1/t:e!==e&&t!==t}function ve(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 cs(e,t){for(let n=0;n<t.length-1;n+=1){const s=t[n];if(e=ye(He(e)===3?Array.from(e):e,s),typeof e!="object")throw new Error(`Cannot resolve patch at '${t.join("/")}'.`)}return e}function us(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 fs=Object.prototype.propertyIsEnumerable;function ds(e,t){let n;if(Array.isArray(e))return Array.prototype.concat.call(e);if(e instanceof Set){if(!on(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(!an(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,se),n!==void 0)&&n!==se.mutable){if(n===se.immutable)return us(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=>{fs.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 H(e){e.copy||(e.copy=ds(e.original,e.options))}function Be(e){if(!ke(e))return xt(e);if(Array.isArray(e))return e.map(Be);if(e instanceof Map){const n=Array.from(e.entries()).map(([s,i])=>[s,Be(i)]);if(!an(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(Be);if(!on(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]=Be(e[n]);return t}function rt(e){return Ct(e)?Be(e):e}function ce(e){var t;e.assignedMap=(t=e.assignedMap)!==null&&t!==void 0?t:new Map,e.operated||(e.operated=!0,e.parent&&ce(e.parent))}function ls(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 i of e)t(s,i,e),s+=1}else e.forEach((s,i)=>t(i,s,e))}function un(e,t,n){if(Ct(e)||!ke(e,n)||t.has(e)||Object.isFrozen(e))return;const s=e instanceof Set,i=s?new Map:void 0;if(t.add(e),ls(e,(r,o)=>{var a;if(Ct(o)){const c=x(o);H(c);const u=!((a=c.assignedMap)===null||a===void 0)&&a.size||c.operated?c.copy:c.original;Tt(s?i:e,r,u)}else un(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 hs(e,t){const n=e.type===3?e.setMap:e.copy;e.finalities.revoke.length>1&&e.assignedMap.get(t)&&n&&un(ye(n,t),e.finalities.handledSet,e.options)}function At(e){e.type===3&&e.copy&&(e.copy.clear(),e.setMap.forEach(t=>{e.copy.add(xt(t))}))}function Rt(e,t,n,s){if(e.operated&&e.assignedMap&&e.assignedMap.size>0&&!e.finalized){if(n&&s){const r=cn(e);r&&t(e,r,n,s)}e.finalized=!0}}function Pt(e,t,n,s){const i=x(n);i&&(i.callbacks||(i.callbacks=[]),i.callbacks.push((r,o)=>{var a;const c=e.type===3?e.setMap:e.copy;if(Ie(ye(c,t),n)){let u=i.original;i.copy&&(u=i.copy),At(e),Rt(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)),Tt(c,t,u)}}),e.options.enableAutoFreeze&&i.finalities!==e.finalities&&(e.options.enableAutoFreeze=!1)),ke(n,e.options)&&e.finalities.draft.push(()=>{const r=e.type===3?e.setMap:e.copy;Ie(ye(r,t),n)&&hs(e,t)})}function ps(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 p=t.concat([u]),d=ve(p,i);n.push({op:L.Replace,path:d,value:rt(c[u])}),s.push({op:L.Replace,path:d,value:rt(r[u])})}for(let u=r.length;u<c.length;u+=1){const p=t.concat([u]),d=ve(p,i);n.push({op:L.Add,path:d,value:rt(c[u])})}if(r.length<c.length){const{arrayLengthAssignment:u=!0}=a.enablePatches;if(u){const p=t.concat(["length"]),d=ve(p,i);s.push({op:L.Replace,path:d,value:r.length})}else for(let p=c.length;r.length<p;p-=1){const d=t.concat([p-1]),y=ve(d,i);s.push({op:L.Remove,path:y})}}}function ys({original:e,copy:t,assignedMap:n},s,i,r,o){n.forEach((a,c)=>{const u=ye(e,c),p=rt(ye(t,c)),d=a?Je(e,c)?L.Replace:L.Add:L.Remove;if(Ie(u,p)&&d===L.Replace)return;const y=s.concat(c),m=ve(y,o);i.push(d===L.Remove?{op:d,path:m}:{op:d,path:m,value:p}),r.push(d===L.Add?{op:L.Remove,path:m}:d===L.Remove?{op:L.Add,path:m,value:u}:{op:L.Replace,path:m,value:u})})}function ms({original:e,copy:t},n,s,i,r){let o=0;e.forEach(a=>{if(!t.has(a)){const c=n.concat([o]),u=ve(c,r);s.push({op:L.Remove,path:u,value:a}),i.unshift({op:L.Add,path:u,value:a})}o+=1}),o=0,t.forEach(a=>{if(!e.has(a)){const c=n.concat([o]),u=ve(c,r);s.push({op:L.Add,path:u,value:a}),i.unshift({op:L.Remove,path:u,value:a})}o+=1})}function qe(e,t,n,s){const{pathAsArray:i=!0}=e.options.enablePatches;switch(e.type){case 0:case 2:return ys(e,t,n,s,i);case 1:return ps(e,t,n,s,i);case 3:return ms(e,t,n,s,i)}}const ot=(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.")},jt={get size(){return Z(x(this)).size},has(e){return Z(x(this)).has(e)},set(e,t){const n=x(this),s=Z(n);return(!s.has(e)||!Ie(s.get(e),t))&&(H(n),ce(n),n.assignedMap.set(e,!0),n.copy.set(e,t),Pt(n,e,t,qe)),this},delete(e){if(!this.has(e))return!1;const t=x(this);return H(t),ce(t),t.original.has(e)?t.assignedMap.set(e,!1):t.assignedMap.delete(e),t.copy.delete(e),!0},clear(){const e=x(this);if(this.size){H(e),ce(e),e.assignedMap=new Map;for(const[t]of e.original)e.assignedMap.set(t,!1);e.copy.clear()}},forEach(e,t){const n=x(this);Z(n).forEach((s,i)=>{e.call(t,this.get(i),i,this)})},get(e){var t,n;const s=x(this),i=Z(s).get(e),r=((n=(t=s.options).mark)===null||n===void 0?void 0:n.call(t,i,se))===se.mutable;if(s.options.strict&&ot(i,s.options,r),r||s.finalized||!ke(i,s.options)||i!==s.original.get(e))return i;const o=Et.createDraft({original:i,parentDraft:s,key:e,finalities:s.finalities,options:s.options});return H(s),s.copy.set(e,o),o},keys(){return Z(x(this)).keys()},values(){const e=this.keys();return{[it]:()=>this.values(),next:()=>{const t=e.next();return t.done?t:{done:!1,value:this.get(t.value)}}}},entries(){const e=this.keys();return{[it]:()=>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]}}}},[it](){return this.entries()}},bs=Reflect.ownKeys(jt),fn=(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=x(a),u=((i=(s=e.options).mark)===null||i===void 0?void 0:i.call(s,a,se))===se.mutable;if(e.options.strict&&ot(o,e.options,u),!u&&!c&&ke(o,e.options)&&!e.finalized&&e.original.has(o)){const p=Et.createDraft({original:o,parentDraft:e,key:o,finalities:e.finalities,options:e.options});e.setMap.set(o,p),a=p}else c&&(a=c.proxy);return{done:!1,value:n?a:[a,a]}},at={get size(){return x(this).setMap.size},has(e){const t=x(this);if(t.setMap.has(e))return!0;H(t);const n=x(e);return!!(n&&t.setMap.has(n.original))},add(e){const t=x(this);return this.has(e)||(H(t),ce(t),t.assignedMap.set(e,!0),t.setMap.set(e,e),Pt(t,e,e,qe)),this},delete(e){if(!this.has(e))return!1;const t=x(this);H(t),ce(t);const n=x(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=x(this);H(e),ce(e);for(const t of e.original)e.assignedMap.set(t,!1);e.setMap.clear()},values(){const e=x(this);H(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.values(),next:fn(e,t,{isValuesIterator:!0})}},entries(){const e=x(this);H(e);const t=e.setMap.keys();return{[Symbol.iterator]:()=>this.entries(),next:fn(e,t,{isValuesIterator:!1})}},keys(){return this.values()},[it](){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(at,{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 gs=Reflect.ownKeys(at),dn=new WeakSet,ln={get(e,t,n){var s,i;const r=(s=e.copy)===null||s===void 0?void 0:s[t];if(r&&dn.has(r))return r;if(t===sn)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,se),o===se.mutable)return e.options.strict&&ot(u,e.options,!0),u}const a=Z(e);if(a instanceof Map&&bs.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(jt,"size").get.call(e.proxy);const u=jt[t];if(u)return u.bind(e.proxy)}if(a instanceof Set&&gs.includes(t)){if(t==="size")return Object.getOwnPropertyDescriptor(at,"size").get.call(e.proxy);const u=at[t];if(u)return u.bind(e.proxy)}if(!Je(a,t)){const u=rn(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&&ot(c,e.options),e.finalized||!ke(c,e.options))return c;if(c===_t(e.original,t)){if(H(e),e.copy[t]=hn({original:e.original[t],parentDraft:e,key:e.type===1?Number(t):t,finalities:e.finalities,options:e.options}),typeof o=="function"){const u=x(e.copy[t]);return H(u),ce(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=rn(Z(e),t);if(r!=null&&r.set)return r.set.call(e.proxy,n),!0;const o=_t(Z(e),t),a=x(o);return a&&Ie(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):(Ie(n,o)&&(n!==void 0||Je(e.original,t))||(H(e),ce(e),Je(e.original,t)&&Ie(n,e.original[t])?e.assignedMap.delete(t):e.assignedMap.set(t,!0),e.copy[t]=n,Pt(e,t,n,qe)),!0)},has(e,t){return t in Z(e)},ownKeys(e){return Reflect.ownKeys(Z(e))},getOwnPropertyDescriptor(e,t){const n=Z(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?ln.set.call(this,e,t,void 0,e.proxy):(_t(e.original,t)!==void 0||t in e.original?(H(e),ce(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 hn(e){const{original:t,parentDraft:n,key:s,finalities:i,options:r}=e,o=He(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,ln);if(i.revoke.push(u),dn.add(c),a.proxy=c,n){const p=n;p.finalities.draft.push((d,y)=>{var m,w;const b=x(c);let h=p.type===3?p.setMap:p.copy;const S=ye(h,s),O=x(S);if(O){let V=O.original;O.operated&&(V=xt(S)),At(O),Rt(O,qe,d,y),p.options.enableAutoFreeze&&(p.options.updatedValues=(m=p.options.updatedValues)!==null&&m!==void 0?m:new WeakMap,p.options.updatedValues.set(V,O.original)),Tt(h,s,V)}(w=b.callbacks)===null||w===void 0||w.forEach(V=>{V(d,y)})})}else{const p=x(c);p.finalities.draft.push((d,y)=>{At(p),Rt(p,qe,d,y)})}return c}Et.createDraft=hn,Object.prototype.constructor.toString();function je(){return as()}function ws(e,t){return e.localeCompare(t)}function Ss(){let e=ws;if(typeof Intl=="object"&&Intl.hasOwnProperty("Collator"))try{e=Intl.Collator("en-US").compare}catch{}return e}Ss();function ks(){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 Is=ks();function ct(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(Is.has(r))return(o,a)=>ct(e,t,[...n,a?[r,e,t,o,a]:[r,e,t,o]])}})}function vs(e,t){return`lookup__${e}__${JSON.stringify(t)}`}function pn(e){return e.startsWith("lookup__")}function yn(e){const[t,n,...s]=e.split("__");return[n,JSON.parse(s.join("__"))]}function $s(e){return new Proxy({__etype:e},{get(t,n){if(n==="lookup")return(i,r)=>ct(e,yn(vs(i,r)),[]);if(n==="__etype")return e;const s=n;return pn(s)?ct(e,yn(s),[]):ct(e,s,[])}})}function mn(){return new Proxy({},{get(e,t){return $s(t)}})}mn();function Os(e){return e.__ops}class $ extends Error{constructor(n,s,i){super(n);l(this,"hint");l(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,$),this.name="SidekickError"}get[Symbol.toStringTag](){return"SidekickError"}}class ue extends ${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"]);l(this,"body");l(this,"status");const i=new.target.prototype;Object.setPrototypeOf&&Object.setPrototypeOf(this,i),Error.captureStackTrace&&Error.captureStackTrace(this,ue),this.name="SidekickAPIError",this.status=n.status,this.body=n.body}get[Symbol.toStringTag](){return"SidekickAPIError"}}typeof window<"u"&&typeof window.localStorage<"u"&&(window.localStorage.getItem("devBackend"),window.localStorage.getItem("__sidekickLogging"),window.localStorage.getItem("__devtoolLocalDash"));const $e="v3.0.0";class fe{constructor(t,n,s,i={indexed:!1,unique:!1}){l(this,"valueType");l(this,"required");l(this,"isIndexed");l(this,"config");l(this,"metadata",{});this.valueType=t,this.required=n,this.isIndexed=s,this.config=i}clientRequired(){return new fe(this.valueType,!1,this.isIndexed,this.config)}optional(){return new fe(this.valueType,!1,this.isIndexed,this.config)}unique(){return new fe(this.valueType,this.required,this.isIndexed,{...this.config,unique:!0})}indexed(){return new fe(this.valueType,this.required,!0,{...this.config,indexed:!0})}}class R extends Error{constructor(t,n){const s=n?`At path '${n}': ${t}`:t;super(s),this.name="QueryValidationError"}}const bn=["where","order","limit","last","first","offset","after","afterInclusive","before","beforeInclusive","fields","aggregate"],Es=e=>e.valueType||"unknown",gn=(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}},Cs=(e,t,n,s,i,r,o)=>{const a=r.valueType==="json",c=(u,p,d)=>{if(!gn(d,p,a))throw new R(`Invalid value for operator '${u}' on attribute '${s}' in entity '${i}'. Expected ${p}, but received: ${typeof d}`,o)};switch(e){case"in":case"$in":if(!Array.isArray(t))throw new R(`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 R(`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 R(`Unknown operator '${e}' for attribute '${s}' in entity '${i}'`,o)}},Ue=(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,p]of Object.entries(c))Cs(u,p,r,t,s,n,`${i}.${u}`)}else if(!gn(e,r,o))throw new R(`Invalid value for attribute '${t}' in entity '${s}'. Expected ${r}, but received: ${typeof e}`,i)},xs=(e,t,n,s,i)=>{const r=e.split(".");if(r.length<2)throw new R(`Invalid dot notation path '${e}'. Must contain at least one dot.`,i);let o=n;for(let p=0;p<r.length-1;p++){const d=r[p],y=s.entities[o];if(!y)throw new R(`Entity '${o}' does not exist in schema while traversing dot notation path '${e}'.`,i);const m=y.links[d];if(!m){const w=Object.keys(y.links);throw new R(`Link '${d}' does not exist on entity '${o}' in dot notation path '${e}'. Available links: ${w.length>0?w.join(", "):"none"}`,i)}o=m.entityName}const a=r[r.length-1],c=s.entities[o];if(!c)throw new R(`Target entity '${o}' does not exist in schema for dot notation path '${e}'.`,i);if(a==="id"){if(typeof t=="string"&&!P(t))throw new R(`Invalid value for id field in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ue(t,e,new fe("string",!1,!0),n,i);return}const u=c.attrs[a];if(Object.keys(c.links).includes(a)){if(typeof t=="string"&&!P(t))throw new R(`Invalid value for link '${a}' in entity '${o}'. Expected a UUID, but received: ${t}`,i);Ue(t,e,new fe("string",!1,!0),n,i);return}if(!u){const p=Object.keys(c.attrs);throw new R(`Attribute '${a}' does not exist on entity '${o}' in dot notation path '${e}'. Available attributes: ${p.length>0?p.join(", ")+", id":"id"}`,i)}Ue(t,e,u,n,i)},wn=(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&&wn(u,t,n,`${s}.${i}[${u}]`);continue}if(i==="id"){Ue(r,"id",new fe("string",!1,!0),t,`${s}.id`);continue}if(i.includes(".")){xs(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),p=Object.keys(o.links);throw new R(`Attribute or link '${i}' does not exist on entity '${t}'. Available attributes: ${u.length>0?u.join(", "):"none"}. Available links: ${p.length>0?p.join(", "):"none"}`,`${s}.${i}`)}if(a)Ue(r,i,a,t,`${s}.${i}`);else if(c){if(typeof r=="string"&&!P(r))throw new R(`Invalid value for link '${i}' in entity '${t}'. Expected a UUID, but received: ${r}`,`${s}.${i}`);const u=new fe("string",!1,!0);Ue(r,i,u,t,`${s}.${i}`)}}},Ts=(e,t,n,s,i=0)=>{for(const o of Object.keys(e))if(!bn.includes(o))throw new R(`Invalid query parameter '${o}' in $ object. Valid parameters are: ${bn.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 R(`'${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 R(`'where' clause must be an object in entity '${t}', but received: ${typeof e.where}`,s?`${s}.where`:void 0);wn(e.where,t,n,s?`${s}.where`:"where")}},Sn=(e,t,n,s,i=0)=>{var r;if(!e||typeof e!="object")throw new R(`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 R(`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&&Sn(a,c,n,`${s}.${o}`,i+1)}}else{const a=e[o];if(typeof a!="object"||a===null)throw new R(`Query parameter '$' must be an object in entity '${t}', but received: ${typeof a}`,`${s}.$`);Ts(a,t,n,`${s}.$`,i)}},kn=(e,t)=>{if(typeof e!="object"||e===null)throw new R(`Query must be an object, but received: ${typeof e}${e===null?" (null)":""}`);if(Array.isArray(e))throw new R(`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 R(`Query keys must be strings, but found key of type: ${typeof s}`,s);if(typeof s!="string")throw new R(`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 R(`Entity '${s}' does not exist in schema. Available entities: ${i.length>0?i.join(", "):"none"}`,s)}Sn(n[s],s,t,s,0)}}},In=e=>typeof e!="string"?!1:pn(e)?!0:P(e);class te extends Error{constructor(t){super(t),this.name="TransactionValidationError"}}const vn=e=>e.length>0?e.join(", "):"none",_s=(e,t)=>new te(`Entity '${e}' does not exist in schema. Available entities: ${vn(t)}`),Ut={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},As=(e,t)=>{var n;return e==null?!0:((n=Ut[t.valueType])==null?void 0:n.call(Ut,e))??!1},$n=(e,t)=>{const n=t.entities[e];if(!n)throw _s(e,Object.keys(t.entities));return n},Mt=(e,t,n)=>{const s=$n(e,n);if(typeof t!="object"||t===null)throw new te(`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&&!As(r,o))throw new te(`Invalid value for attribute '${i}' in entity '${e}'. Expected ${o.valueType}, but received: ${typeof r}`)}},On=(e,t,n)=>{const s=$n(e,n);if(typeof t!="object"||t===null)throw new te(`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 te(`Link '${i}' does not exist on entity '${e}'. Available links: ${vn(a)}`)}if(r!=null){if(Array.isArray(r)){for(const a of r)if(!In(a))throw new te(`Invalid entity ID in link '${i}' for entity '${e}'. Expected a UUID or a lookup, but received: ${a}`)}else if(!In(r))throw new te(`Invalid UUID in link '${i}' for entity '${e}'. Expected a UUID, but received: ${r}`)}}},Rs={create:Mt,update:Mt,merge:Mt,link:On,unlink:On,delete:()=>{}},Ps=(e,t)=>{if(!t)return;const[n,s,i,r]=e;if(!Array.isArray(i)&&!P(i))throw new te(`Invalid id for entity '${s}'. Expected a UUID, but received: ${i}`);if(typeof s!="string")throw new te(`Entity name must be a string, but received: ${typeof s}`);const o=Rs[n];o&&r!==void 0&&o(s,r,t)},js=(e,t)=>{const n=Array.isArray(e)?e:[e];for(const s of n){if(!s||typeof s!="object")throw new te(`Transaction chunk must be an object, but received: ${typeof s}`);if(!Array.isArray(s.__ops))throw new te(`Transaction chunk must have __ops array, but received: ${typeof s.__ops}`);for(const i of s.__ops){if(!Array.isArray(i))throw new te(`Transaction operation must be an array, but received: ${typeof i}`);Ps(i,t)}}};let Us=0;function Ms(e,t){for(const n of e)try{t(n)}catch(s){setTimeout(()=>{throw s})}}class Ds{constructor(t,n,s){l(this,"type","sse");l(this,"initParams",null);l(this,"sendQueue",[]);l(this,"sendPromise");l(this,"closeFired",!1);l(this,"sseInitTimeout");l(this,"ES");l(this,"messageUrl");l(this,"conn");l(this,"url");l(this,"id");l(this,"onopen");l(this,"onmessage");l(this,"onclose");l(this,"onerror");this.id=`${this.type}_${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);Array.isArray(r)?Ms(r,o=>this.handleMessage(o)):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 En;(function(e){e.InitialSyncBatch="InitialSyncBatch",e.InitialSyncComplete="InitialSyncComplete",e.LoadFromStorage="LoadFromStorage",e.SyncTransaction="SyncTransaction",e.Error="Error"})(En||(En={}));function Ns({WStream:e,opts:t,startStream:n,appendStream:s,registerStream:i}){const r=t.clientId;let o=null,a=null,c=null;const u=je();let p=!1,d=!1;const y=[],m=[],w=[];let b=!1,h=0,S=0;const O=[],V=new TextEncoder;function Re(){d=!0;for(const g of y)g(a??void 0)}function Qt(g){return y.push(g),d&&g(a??void 0),()=>{const v=y.indexOf(g);v!==-1&&y.splice(v,1)}}function qn(g){return w.push(g),()=>{const v=w.indexOf(g);v!==-1&&w.splice(v,1)}}t.waitUntil&&t.waitUntil(new Promise(g=>{w.push(g)}));function j(){for(const g of w)try{g()}catch{}}function _(g){return m.push(g),o&&g(o),()=>{const v=m.indexOf(g);v!==-1&&m.splice(v,1)}}function re(g){o=g;for(const v of m)v(o)}function A(){b=!0}function W(g){let v=h,z=0,Y=0;for(const{byteLen:oe}of O){const pe=v+oe;if(pe>g)break;v=pe,z++,Y+=oe}z>0&&(h+=Y,S-=Y,O.splice(0,z))}function N(g,v){a=v,Re(),g.error(v),j()}async function ne(){const g=await n({clientId:r,reconnectToken:u,ruleParams:t.ruleParams});switch(g.type){case"ok":{const{streamId:v,offset:z}=g;o=v,W(z),O.length&&s({streamId:v,chunks:O.map(Y=>Y.chunk),offset:h}),b=!1;break}case"disconnect":{A();break}case"error":{c&&N(c,g.error);break}}}function J(){A(),ne()}function vt({offset:g,done:v}){W(g),v&&(p=!0,j())}function Qn(g){return p?(N(g,new $("Stream has been closed.")),null):o||(N(g,new $("Stream has not been initialized.")),null)}async function Ve(g){c=g;let v=!0,z=0;for(;v;){let Y=Date.now()+Math.min(15e3,500*(z-1));v=!1;const oe=await n({clientId:t.clientId,reconnectToken:u,ruleParams:t.ruleParams});switch(oe.type){case"ok":{const{streamId:pe,offset:Gt}=oe;if(Gt!==0){const Pe=new $("Write stream is corrupted");N(g,Pe);return}re(pe),i(pe,{onDisconnect:A,onFlush:vt,onConnectionReconnect:ne,onAppendFailed:J}),b=!1;return}case"disconnect":{v=!0,A(),z++,await new Promise(pe=>{setTimeout(pe,Math.max(0,Y-Date.now()))});break}case"error":{N(g,oe.error);return}}}}class we extends e{constructor(v,z){super(v,z)}async streamId(){return o||new Promise((v,z)=>{const Y=[],oe=()=>{for(const Pe of Y)Pe()},pe=Pe=>{v(Pe),oe()},Gt=Pe=>{z(Pe||new $("Stream is closed.")),oe()};Y.push(_(pe)),Y.push(Qt(Gt))})}}return{stream:new we({async start(g){try{await Ve(g)}catch(v){N(g,v)}},write(g,v){const z=Qn(v);if(z){const Y=V.encode(g).length;O.push({chunk:g,byteLen:Y});const oe=h+S;S+=Y,b||s({streamId:z,chunks:[g],offset:oe})}},close(){o?s({streamId:o,chunks:[],offset:h+S,isDone:!0}):j(),Re()},abort(g){o?s({streamId:o,chunks:[],offset:h+S,isDone:!0,abortReason:g}):j(),Re()}}),addCompleteCb:qn,closed(){return d}}}class Ls{constructor(){l(this,"items",[]);l(this,"resolvers",[]);l(this,"isClosed",!1)}push(t){if(this.isClosed)return;const n=this.resolvers.shift();n?n({value:t,done:!1}):this.items.push(t)}close(){for(this.isClosed=!0;this.resolvers.length>0;)this.resolvers.shift()({value:void 0,done:!0})}async*[Symbol.asyncIterator](){for(;;)if(this.items.length>0)yield this.items.shift();else{if(this.isClosed)return;{const{value:t,done:n}=await new Promise(s=>{this.resolvers.push(s)});if(n||!t)return;yield t}}}}function Fs({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 p=[],d=[];let y=null,m=null;function w(j){u=!0;for(const _ of p)_(j)}function b(j){return p.push(j),()=>{const _=p.indexOf(j);_!==-1&&p.splice(_,1)}}function h(j){return d.push(j),y&&j(y),()=>{const _=d.indexOf(j);_!==-1&&d.splice(_,1)}}function S(j,_){m=_,j.error(_),w(_)}let O=0;async function V(j,_){c=je();const re={...j||{},eventId:c};for await(const A of n(re)){if(r)return;if(A.type==="reconnect")return{retry:!0};if(A.type==="error"){S(_,A.error);return}if(A.offset>i){S(_,new $("Stream is corrupted.")),r=!0;return}y=A.streamId;for(const N of d)N(y);let W=i-A.offset;if(A.files&&A.files.length){const N=new AbortController;let ne=fetch(A.files[0].url,{signal:N.signal});for(let J=0;J<A.files.length;J++){const vt=A.files[J+1],Ve=await ne;if(vt&&(ne=fetch(vt.url,{signal:N.signal})),!Ve.ok){if(O++,O>10){S(_,new $("Unable to process stream."));return}return{retry:!0}}if(Ve.body){const we=Ve.body.getReader();try{for(;;){const{done:Se,value:g}=await we.read();if(Se)break;if(r){N.abort();return}let v=g;if(W>0&&(v=g.subarray(W),W-=g.length-v.length),!v.length)continue;i+=v.length;const z=o.decode(v);_.enqueue(z)}}finally{we.releaseLock()}}else{const we=await Ve.arrayBuffer();let Se=we;if(r){N.abort();return}if(W>0&&(Se=new Uint8Array(we).subarray(W),W-=we.byteLength-Se.length),!Se.byteLength)continue;i+=Se.byteLength;const g=o.decode(Se);_.enqueue(g)}}}if(O=0,A.content){let N=A.content,ne=a.encode(A.content);if(W>0){const J=ne.subarray(W);if(W-=ne.length-J.length,!J.length)continue;ne=J,N=o.decode(J)}i+=ne.length,_.enqueue(N)}}}async function Re(j){let _=!0,re=0;for(;_;){_=!1;let A=Date.now()+Math.min(15e3,500*(re-1));const W=await V({...t,offset:i},j);W!=null&&W.retry&&(_=!0,re++,A<Date.now()-3e5&&(re=0),await new Promise(N=>{setTimeout(N,Math.max(0,A-Date.now()))}))}!r&&!u&&(j.close(),w())}class Qt extends e{constructor(_,re){super(_,re)}async streamId(){if(y)return y;if(m)throw m;return new Promise((_,re)=>{const A=[],W=()=>{for(const J of A)J()},N=J=>{_(J),W()},ne=J=>{re(J||new $("Stream is closed.")),W()};A.push(h(N)),A.push(b(ne))})}}return{stream:new Qt({start(j){Re(j)},cancel(j){r=!0,c&&s({eventId:c}),w()}}),addCloseCb:b,closed(){return u}}}class Ws{constructor({WStream:t,RStream:n,trySend:s,log:i}){l(this,"trySend");l(this,"WStream");l(this,"RStream");l(this,"writeStreams",{});l(this,"startWriteStreamCbs",{});l(this,"readStreamIterators",{});l(this,"log");l(this,"activeStreams",new Set);this.WStream=t,this.RStream=n,this.trySend=s,this.log=i}createWriteStream(t){const{stream:n,addCompleteCb:s}=Ns({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}=Fs({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=je();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(je(),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 Ls;return this.readStreamIterators[t]=a,this.trySend(t,o),a}cancelReadStream({eventId:t}){const n={op:"unsubscribe-stream","subscribe-event-id":t};this.trySend(je(),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 $(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!==zs.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 $(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 $(t.message||"Unknown error",t.hint)}),i.close(),delete this.readStreamIterators[s]);break}}}hasActiveStreams(){return this.activeStreams.size>0}}const zs={AUTHENTICATED:"authenticated"};class Ks extends ${constructor(t){super(t),this.name="MissingApiURIError"}get[Symbol.toStringTag](){return"MissingApiURIError"}}function Vs({target:e,option:t="apiURI",envVar:n}){return`No SidekickDB server URL configured. ${n?`Pass \`${t}\` to ${e} or set the ${n} environment variable`:`Pass \`${t}\` to ${e}`}, for example ${t}: 'https://sidekick.example.com'. SidekickDB has no default server.`}function Dt(e,t){if(typeof e=="string"&&e.trim()!=="")return e;throw new Ks(Vs(t))}function Js(){return globalThis.__sidekickDbSchemaHashStore=globalThis.__sidekickDbSchemaHashStore??new WeakMap,globalThis.__sidekickDbSchemaHashStore}function Hs(){return globalThis.__sidekickDbStore=globalThis.__sidekickDbStore??{},globalThis.__sidekickDbStore}Hs(),Js();class Cn extends Event{constructor(n,s){super(n);l(this,"code");l(this,"message");this.code=(s==null?void 0:s.code)??void 0,this.message=(s==null?void 0:s.message)??void 0}[Symbol.for("nodejs.util.inspect.custom")](n,s,i){return i(xn(this),s)}[Symbol.for("Deno.customInspect")](n,s){return n(xn(this),s)}}function Bs(e){const t=globalThis.DOMException;return typeof t=="function"?new t(e,"SyntaxError"):new SyntaxError(e)}function Nt(e){return e instanceof Error?"errors"in e&&Array.isArray(e.errors)?e.errors.map(Nt).join(", "):"cause"in e&&e.cause instanceof Error?`${e}: ${Nt(e.cause)}`:e.message:`${e}`}function xn(e){return{type:e.type,message:e.message,code:e.code,defaultPrevented:e.defaultPrevented,cancelable:e.cancelable,timeStamp:e.timeStamp}}class Tn 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 Lt(e){}function qs(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=Lt,onError:n=Lt,onRetry:s=Lt,onComment:i}=e;let r="",o=!0,a,c="",u="";function p(b){const h=o?b.replace(/^\xEF\xBB\xBF/,""):b,[S,O]=Qs(`${r}${h}`);for(const V of S)d(V);r=O,o=!1}function d(b){if(b===""){m();return}if(b.startsWith(":")){i&&i(b.slice(b.startsWith(": ")?2:1));return}const h=b.indexOf(":");if(h!==-1){const S=b.slice(0,h),O=b[h+1]===" "?2:1,V=b.slice(h+O);y(S,V,b);return}y(b,"",b)}function y(b,h,S){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 Tn(`Invalid \`retry\` value: "${h}"`,{type:"invalid-retry",value:h,line:S}));break;default:n(new Tn(`Unknown field "${b.length>20?`${b.slice(0,20)}…`:b}"`,{type:"unknown-field",field:b,value:h,line:S}));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 w(b={}){r&&b.consume&&d(r),o=!0,a=void 0,c="",u="",r=""}return{feed:p,reset:w}}function Qs(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 ie extends EventTarget{constructor(n,s){super();k(this,q);l(this,"CONNECTING",0);l(this,"OPEN",1);l(this,"CLOSED",2);k(this,B);k(this,ge);k(this,Oe);k(this,Ge);k(this,Xe);k(this,Ye);k(this,Ne);k(this,Ee);k(this,Le,null);k(this,he);k(this,Ce);k(this,xe,null);k(this,Te,null);k(this,Fe,null);k(this,pt,async n=>{var y;f(this,Ce).reset();const{body:s,redirected:i,status:r,headers:o}=n;if(r===204){E(this,q,st).call(this,"Server sent HTTP 204, not reconnecting",204),this.close();return}if(i?I(this,Oe,new URL(n.url)):I(this,Oe,void 0),r!==200){E(this,q,st).call(this,`Non-200 status code (${r})`,r);return}if(!(o.get("content-type")||"").startsWith("text/event-stream")){E(this,q,st).call(this,'Invalid content type, expected "text/event-stream"',r);return}if(f(this,B)===this.CLOSED)return;I(this,B,this.OPEN);const c=new Event("open");if((y=f(this,Fe))==null||y.call(this,c),this.dispatchEvent(c),typeof s!="object"||!s||!("getReader"in s)){E(this,q,st).call(this,"Invalid response body, expected a web ReadableStream",r),this.close();return}const u=new TextDecoder,p=s.getReader();let d=!0;do{const{done:m,value:w}=await p.read();w&&f(this,Ce).feed(u.decode(w,{stream:!m})),m&&(d=!1,f(this,Ce).reset(),E(this,q,Zt).call(this))}while(d)});k(this,yt,n=>{I(this,he,void 0),!(n.name==="AbortError"||n.type==="aborted")&&E(this,q,Zt).call(this,Nt(n))});k(this,mt,n=>{typeof n.id=="string"&&I(this,Le,n.id);const s=new(f(this,Ye))(n.event||"message",{data:n.data,origin:f(this,Oe)?f(this,Oe).origin:f(this,ge).origin,lastEventId:n.id||""});f(this,Te)&&(!n.event||n.event==="message")&&f(this,Te).call(this,s),this.dispatchEvent(s)});k(this,bt,n=>{I(this,Ne,n)});k(this,gt,()=>{I(this,Ee,void 0),f(this,B)===this.CONNECTING&&E(this,q,Yt).call(this)});try{if(n instanceof URL)I(this,ge,n);else if(typeof n=="string")I(this,ge,new URL(n,Gs()));else throw new Error("Invalid URL")}catch{throw Bs("An invalid or illegal string was specified")}I(this,Ce,qs({onEvent:f(this,mt),onRetry:f(this,bt)})),I(this,B,this.CONNECTING),I(this,Ne,3e3),I(this,Xe,(s==null?void 0:s.fetch)??globalThis.fetch),I(this,Ye,(s==null?void 0:s.messageEvent)??globalThis.MessageEvent),I(this,Ge,(s==null?void 0:s.withCredentials)??!1),E(this,q,Yt).call(this)}get readyState(){return f(this,B)}get url(){return f(this,ge).href}get withCredentials(){return f(this,Ge)}get onerror(){return f(this,xe)}set onerror(n){I(this,xe,n)}get onmessage(){return f(this,Te)}set onmessage(n){I(this,Te,n)}get onopen(){return f(this,Fe)}set onopen(n){I(this,Fe,n)}addEventListener(n,s,i){const r=s;super.addEventListener(n,r,i)}removeEventListener(n,s,i){const r=s;super.removeEventListener(n,r,i)}close(){f(this,Ee)&&clearTimeout(f(this,Ee)),f(this,B)!==this.CLOSED&&(f(this,he)&&f(this,he).abort(),I(this,B,this.CLOSED),I(this,he,void 0))}}B=new WeakMap,ge=new WeakMap,Oe=new WeakMap,Ge=new WeakMap,Xe=new WeakMap,Ye=new WeakMap,Ne=new WeakMap,Ee=new WeakMap,Le=new WeakMap,he=new WeakMap,Ce=new WeakMap,xe=new WeakMap,Te=new WeakMap,Fe=new WeakMap,q=new WeakSet,Yt=function(){I(this,B,this.CONNECTING),I(this,he,new AbortController),f(this,Xe)(f(this,ge),E(this,q,Xn).call(this)).then(f(this,pt)).catch(f(this,yt))},pt=new WeakMap,yt=new WeakMap,Xn=function(){var i;const s={mode:"cors",redirect:"follow",headers:{Accept:"text/event-stream",...f(this,Le)?{"Last-Event-ID":f(this,Le)}:void 0},cache:"no-store",signal:(i=f(this,he))==null?void 0:i.signal};return"window"in globalThis&&(s.credentials=this.withCredentials?"include":"same-origin"),s},mt=new WeakMap,bt=new WeakMap,st=function(n,s){var r;f(this,B)!==this.CLOSED&&I(this,B,this.CLOSED);const i=new Cn("error",{code:s,message:n});(r=f(this,xe))==null||r.call(this,i),this.dispatchEvent(i)},Zt=function(n,s){var r;if(f(this,B)===this.CLOSED)return;I(this,B,this.CONNECTING);const i=new Cn("error",{code:s,message:n});(r=f(this,xe))==null||r.call(this,i),this.dispatchEvent(i),I(this,Ee,setTimeout(f(this,gt),f(this,Ne)))},gt=new WeakMap,l(ie,"CONNECTING",0),l(ie,"OPEN",1),l(ie,"CLOSED",2),Object.defineProperty(ie,Symbol.for("eventsource.supports-fetch-override"),{value:!0,writable:!1,configurable:!1,enumerable:!1});function Gs(){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);l(this,"data");l(this,"origin");l(this,"lastEventId");l(this,"source");l(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 Xs(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(m=>{i=m})}},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 Ys(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 An(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 Zs(e,t,n){let s,i=!1;const r=je(),o=new ie(`${n.apiURI}/admin/subscribe-query?local_connection_id=${r}`,{messageEvent:_n,fetch(h,S){return s=null,fetch(h,{...S,method:"POST",headers:n.headers,body:JSON.stringify({query:e,"inference?":n.inference,versions:{"@sidekickdb/admin":$e,"@sidekickdb/core":$e}})}).then(O=>(O.ok||(s=Ys(O)),O))}}),a=[],c=[],u=h=>{a.push(h)},p=h=>{a.splice(a.indexOf(h),1)},d=h=>{c.push(h)};t&&u(t);let y=null;function m(h){if(!i)for(const S of a)try{S(h)}catch(O){console.error("Error in subscribeQuery callback",O)}}function w(h){var S,O;switch(h.op){case"sse-init":{const V=h["machine-id"],Re=h["session-id"];y={machineId:V,sessionId:Re};break}case"add-query-ok":{m({type:"ok",data:h.result,pageInfo:An((S=h["result-meta"])==null?void 0:S["page-info"]),sessionInfo:y});break}case"refresh-ok":{h.computations.length&&m({type:"ok",data:h.computations[0]["sideql-result"],pageInfo:An((O=h.computations[0]["result-meta"])==null?void 0:O["page-info"]),sessionInfo:y});break}case"error":{m({type:"error",error:new ue({body:h,status:h.status}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:y});break}}}return o.onerror=h=>{if(s)s.text().then(S=>{let O={type:void 0,message:S};try{O=JSON.parse(S)}catch{}m({type:"error",error:new ue({status:s.status,body:O}),get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},sessionInfo:y})});else{const S=()=>{m({type:"error",error:new ue({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:y})};if(o.readyState===ie.CLOSED){S();return}setTimeout(()=>{o.readyState!==ie.OPEN&&S()},5e3)}},o.onmessage=h=>{w(JSON.parse(h.data))},{close:()=>{i=!0;for(const h of c)try{h()}catch(S){console.error("Error in onClose callback",S)}o.close()},[Symbol.iterator]:()=>{throw new Error("subscribeQuery does not support synchronous iteration. Use `for await` instead.")},get sessionInfo(){return y},get readyState(){return me(o)},get isClosed(){return me(o)==="closed"},[Symbol.asyncIterator]:Xs.bind(this,u,d,p,()=>1)}}var de={};Object.defineProperty(de,"__esModule",{value:!0});var ei=de.parseCookie=jn;de.parse=jn,de.stringifyCookie=oi,de.stringifySetCookie=ut,de.serialize=ut,de.parseSetCookie=ai,de.stringifySetCookie=ut,de.serialize=ut;const Rn=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Pn=/^[\u0021-\u003A\u003C-\u007E]*$/,ti=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,ni=/^[\u0020-\u003A\u003D-\u007E]*$/,si=/^-?\d+$/,ii=Object.prototype.toString,ri=(()=>{const e=function(){};return e.prototype=Object.create(null),e})();function jn(e,t){const n=new ri,s=e.length;if(s<2)return n;const i=(t==null?void 0:t.decode)||Un;let r=0;do{const o=Wt(e,r,s);if(o===-1)break;const a=Ft(e,r,s);if(o>a){r=e.lastIndexOf(";",o-1)+1;continue}const c=be(e,r,o);n[c]===void 0&&(n[c]=i(be(e,o+1,a))),r=a+1}while(r<s);return n}function oi(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(!Rn.test(i))throw new TypeError(`cookie name is invalid: ${i}`);const o=n(r);if(!Pn.test(o))throw new TypeError(`cookie val is invalid: ${r}`);s.push(`${i}=${o}`)}return s.join("; ")}function ut(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(!Rn.test(s.name))throw new TypeError(`argument name is invalid: ${s.name}`);const o=s.value?r(s.value):"";if(!Pn.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(!ti.test(s.domain))throw new TypeError(`option domain is invalid: ${s.domain}`);a+="; Domain="+s.domain}if(s.path){if(!ni.test(s.path))throw new TypeError(`option path is invalid: ${s.path}`);a+="; Path="+s.path}if(s.expires){if(!ci(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 ai(e,t){const n=(t==null?void 0:t.decode)||Un,s=e.length,i=Ft(e,0,s),r=Wt(e,0,i),o=r===-1?{name:"",value:n(be(e,0,i))}:{name:be(e,0,r),value:n(be(e,r+1,i))};let a=i+1;for(;a<s;){const c=Ft(e,a,s),u=Wt(e,a,c),p=u===-1?be(e,a,c):be(e,a,u),d=u===-1?void 0:be(e,u+1,c);switch(p.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&&si.test(d)&&(o.maxAge=Number(d));break;case"expires":if(!d)break;const y=new Date(d);Number.isFinite(y.valueOf())&&(o.expires=y);break;case"priority":if(!d)break;const m=d.toLowerCase();(m==="low"||m==="medium"||m==="high")&&(o.priority=m);break;case"samesite":if(!d)break;const w=d.toLowerCase();(w==="lax"||w==="strict"||w==="none")&&(o.sameSite=w);break}a=c+1}return o}function Ft(e,t,n){const s=e.indexOf(";",t);return s===-1?n:s}function Wt(e,t,n){const s=e.indexOf("=",t);return s<n?s:-1}function be(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 Un(e){if(e.indexOf("%")===-1)return e;try{return decodeURIComponent(e)}catch{return e}}function ci(e){return ii.call(e)==="[object Date]"}const ui=Object.assign(Object.create(null),{"http://localhost:8888":{keys:[{kty:"OKP",crv:"Ed25519",alg:"EdDSA",use:"sig",kid:"503090235",x:"qrSkwDaMITRMF9nOgpueqxgaAiuFmJperYE3mkyl8Ow"}]}});function fi(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 Mn(e){const t=fi(e),n=await crypto.subtle.importKey("jwk",e,t,!1,["verify"]);return{alg:t,key:n}}function di(e,t,n,s){return crypto.subtle.verify(e,t,n,s)}function li(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 hi(e){let t,n,s;for(const r of e.split(",")){const[o,a]=r.split("=");switch(o){case"t":{t=a;break}case"kid":{n=a;break}case"v1":{s=a;break}}}const i=[];if(t||i.push("t"),n||i.push("kid"),s||i.push("v1"),i.length||!t||!n||!s)throw new $("Invalid Sidekick-Signature header.",{header:e,missingKeys:i});return{t,kid:n,v1:s}}function pi(e,t,n){if(!/^[0-9]{1,12}$/.test(t))throw new $("Invalid timestamp in Sidekick-Signature header.",{t});const s=Math.floor(e.getTime()/1e3)-Number(t);if(s>n)throw new $("Webhook signature is too old",{tolerance:n,receivedAt:e,t});if(-s>n)throw new $("Webhook signature timestamp is in the future",{tolerance:n,receivedAt:e,t})}const ft=new Map;function yi(e,t){var n;return(n=ft.get(e))==null?void 0:n.get(t)}function Dn(e,t,n){let s=ft.get(e);s||(s=new Map,ft.set(e,s)),s.set(t,n)}function mi(e,t,n){const s=ft.get(e);(s==null?void 0:s.get(t))===n&&s.delete(t)}const bi=300,gi=10*6e4,wi=6*60*6e4,Nn=new Map,Si=6e4,Qe=5e3,ki=1e4,Ii=3,zt=8e3,vi=6e4;function le(){var e,t;return((t=(e=globalThis.performance)==null?void 0:e.now)==null?void 0:t.call(e))??Date.now()}function Me(e,t,n){return e>=t&&e-t<n}function $i(e,t){t<e.seen&&(e.fullAt=t),e.seen=t;const n=Math.max(e.fullAt,t);return n-t>(Ii-1)*zt?!1:(e.fullAt=n+zt,!0)}function Ln(e,t){let n;const s=new Promise(i=>{n=setTimeout(i,t)});return Promise.race([e.then(i=>({value:i}),i=>({error:i})),s]).finally(()=>clearTimeout(n))}function dt(e){return new $("Could not fetch signing keys, try again later",{apiURI:e})}function Kt(e){let t=Nn.get(e);return t||(t={limit:{fullAt:-1/0,seen:-1/0}},Nn.set(e,t)),t}class Fn extends Error{}function Wn(e){return new $("Could not confirm the signing key, try again later",{kid:e})}async function zn(e,t){const n=Kt(e),s=()=>n.ok&&Me(le(),n.ok.at,Si)?n.ok:void 0,i=s();if(i)return i;const r=le();let o=r+Qe,a=!1,c,u,p=0;for(;;){const b=n.pending,h=le();if(!b||b===c||!Me(h,b.at,Qe)){if(a)throw u??dt(e);break}if(!a&&b.at+Qe>o&&(a=!0,o=b.at+Qe),!(h>=r&&h<o))throw dt(e);c=b,u=void 0;const S=await Ln(b.keys,Math.min(b.at+Qe,o)-h);if(S&&"value"in S)return S.value;const O=s();if(O)return O;if(S&&(u=S.error,++p>=2))throw S.error}const d=le();if(d<r||!$i(n.limit,d))throw dt(e);const y=t().then(b=>{if(!Array.isArray(b==null?void 0:b.keys))throw new $("The signing key set has no keys array",{apiURI:e});const h={at:d,keys:b.keys};return n.recheckFailing=!1,(!s()||d>=n.ok.at)&&(n.ok=h),h});y.catch(()=>{}),n.pending={at:d,keys:y};const m=await Ln(y,r+ki-d);if(m&&"value"in m)return m.value;const w=s();if(w)return w;throw m?m.error:dt(e)}function Oi(e,t){return["kty","crv","alg","x","y","n","e"].every(n=>e[n]===t[n])}async function Ei(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new ue({status:t.status,body:s}))}catch{return e(new ue({status:t.status,body:{type:void 0,message:n}}))}}const Ci=async(e,t)=>{const n={...(t==null?void 0:t.headers)||{},"Sidekick-Core-Version":$e},s=await fetch(e,{...t,headers:n});return s.status===200?s.json():Ei(i=>Promise.reject(i),s)};function Kn(e){return e?new Date(e):null}function De(e){return{id:e.id,sink:e.sink,namespaces:e.namespaces??[],actions:e.actions,status:e.status,disabledReason:e.disabled_reason??null,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function xi(e){return{attemptAt:Kn(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 Vt(e){return{isn:e.isn,status:e.status,attempts:e.attempts?e.attempts.map(xi):null,nextAttemptAfter:Kn(e.next_attempt_after),createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}class Ti{constructor(t){k(this,ee);k(this,Q);k(this,Ze);k(this,We);k(this,ze);k(this,et);I(this,Q,t.appId),I(this,Ze,t.apiURI),I(this,We,t.token),I(this,ze,t.withAuth),I(this,et,t.jsonFetch)}async list(){return((await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks`)).webhooks||[]).map(De)}async create(t){const n=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks`,{method:"POST",body:t});return De(n.webhook)}async update(t,n){const s=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}`,{method:"POST",body:n});return De(s.webhook)}async delete(t){const n=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}`,{method:"DELETE"});return De(n.webhook)}async enable(t){const n=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/enable`,{method:"POST",body:{}});return De(n.webhook)}async disable(t,n){const s=n!=null&&n.reason?{reason:n.reason}:{},i=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/disable`,{method:"POST",body:s});return De(i.webhook)}async listEvents(t,n){var r,o,a;const s=n!=null&&n.after?`?after=${encodeURIComponent(n.after)}`:"",i=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events${s}`);return{events:(i.events||[]).map(Vt),pageInfo:{startCursor:((r=i.pageInfo)==null?void 0:r.startCursor)??null,endCursor:((o=i.pageInfo)==null?void 0:o.endCursor)??null,hasNextPage:!!((a=i.pageInfo)!=null&&a.hasNextPage)}}}async getEvent(t,n){const s=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events/${n}`);return Vt(s.event)}async getPayload(t,n){return E(this,ee,ae).call(this,`/webhooks/payload/${f(this,Q)}/${t}/${n}`)}async resendEvent(t,n){const s=await E(this,ee,ae).call(this,`/dash/apps/${f(this,Q)}/webhooks/${t}/events/${n}`,{method:"POST",body:{}});return Vt(s.event)}}Q=new WeakMap,Ze=new WeakMap,We=new WeakMap,ze=new WeakMap,et=new WeakMap,ee=new WeakSet,ae=function(t,n){if(!f(this,Q))throw new $("appId is required to manage webhooks. Pass it to the Webhooks constructor.");const s=i=>{const r={method:n==null?void 0:n.method,headers:{authorization:`Bearer ${i}`,"content-type":"application/json"}};return(n==null?void 0:n.body)!==void 0&&(r.body=JSON.stringify(n.body)),f(this,et).call(this,`${f(this,Ze)}${t}`,r)};if(f(this,ze))return f(this,ze).call(this,s);if(!f(this,We))throw new $("A token is required to manage webhooks. Pass `adminToken` or `token` to the Webhooks constructor.");return s(f(this,We))};const Bt=class Bt{constructor(t,n){k(this,nt);l(this,"appId");l(this,"schema");k(this,tt);l(this,"apiURI");k(this,_e);l(this,"manager");this.appId=t.appId,this.schema=t.schema,I(this,tt,t.adminToken||t.token),this.apiURI=Dt(t.apiURI,{target:"new Webhooks()"}),I(this,_e,n||Ci),this.manager=new Ti({appId:this.appId,apiURI:this.apiURI,token:f(this,tt),withAuth:t.withAuth,jsonFetch:f(this,_e)})}static helpers(){function t(...s){if(s.length===2)return{$default:s[1]};const[i,r,o]=s;return{[i]:{[r]:o}}}function n(...s){const i={};for(const r of s)for(const o of Object.keys(r))o==="$default"?i.$default=r.$default:i[o]={...i[o],...r[o]};return i}return{typedHandlers:t,combineHandlers:n}}helpers(){return Bt.helpers()}async fetchJwks(){return await f(this,_e).call(this,`${this.apiURI}/.well-known/webhooks/jwks.json`)}async keyOfKid(t){var a;const n=yi(this.apiURI,t);if(n&&(n.confirmedAt===void 0||Me(le(),n.confirmedAt,gi)))return n;if(n){const c=Kt(this.apiURI),u=le(),p=()=>Me(le(),n.confirmedAt,wi),d=c.recheckFailing&&Me(u,c.recheckAt,vi),y=!d||!Me(u,c.recheckAt,zt);if(d&&p())return y&&E(this,nt,en).call(this,t,n).catch(()=>{}),n;if(!y)throw Wn(t);try{return await E(this,nt,en).call(this,t,n)}catch(m){if(!(m instanceof Fn))throw m;if(p())return n;throw Wn(t)}}const s=(a=ui[this.apiURI])==null?void 0:a.keys.find(c=>c.kid===t),i=s?void 0:await zn(this.apiURI,()=>this.fetchJwks()),r=s||i.keys.find(c=>(c==null?void 0:c.kid)===t);if(!r)throw new $("Could not find matching signing key",{kid:t});const o={...await Mn(r),jwk:r,confirmedAt:i==null?void 0:i.at};return Dn(this.apiURI,t,o),o}async validate(t,n,s){const i=(s==null?void 0:s.tolerance)??bi;if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new $("Invalid tolerance option: expected a finite number of seconds, 0 or more",{tolerance:i});const r=(s==null?void 0:s.receivedAt)??new Date;if(!(r instanceof Date)||!Number.isFinite(r.getTime()))throw new $("Invalid receivedAt option: expected a valid Date",{receivedAt:r});const{t:o,kid:a,v1:c}=hi(t);pi(r,o,i);const{alg:u,key:p}=await this.keyOfKid(a),d=typeof n=="function"?await n():n,y=new TextEncoder().encode(`${o}.${d}`);if(!await di(u,p,li(c),y))throw new $("Sidekick Signature did not validate",{header:t});const w=JSON.parse(d);if(typeof w!="object"||typeof w.payloadUrl!="string"||typeof w.token!="string")throw new $("Invalid webhook body, expected an object with payloadUrl and token fields",{body:w});return w}async validateRequest(t,n){const s=t.headers.get("sidekick-signature");if(!s)throw new $("Request is missing Sidekick-Signature header");return this.validate(s,()=>t.text(),n)}fetchPayloads({payloadUrl:t,token:n}){return f(this,_e).call(this,t,{headers:{Authorization:`Bearer ${n}`,accept:"application/json"}})}async processPayload(t,n){var i,r;const s=[];for(const o of n.data){const{namespace:a,action:c}=o,u=((i=t==null?void 0:t[a])==null?void 0:i[c])||((r=t==null?void 0:t[a])==null?void 0:r.$default)||(t==null?void 0:t.$default);u&&s.push(u(o))}await Promise.all(s)}async processRequest(t,n,s){const i=await this.validateRequest(n,s),r=await this.fetchPayloads(i);await this.processPayload(t,r)}async processNodeRequest(t,n,s){let i,r=!1,o=(s==null?void 0:s.body)??n.rawBody??n.body;if(o!=null&&typeof o.then=="function"&&(o=await o),typeof o=="string")i=o;else if(o instanceof Uint8Array)i=new TextDecoder("utf-8").decode(o);else if(o!=null&&typeof o=="object")try{i=JSON.stringify(o),r=!0}catch{throw new $("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 d=new TextEncoder,y=[];for await(const h of n)y.push(typeof h=="string"?d.encode(h):h);let m=0;for(const h of y)m+=h.byteLength;const w=new Uint8Array(m);let b=0;for(const h of y)w.set(h,b),b+=h.byteLength;i=new TextDecoder("utf-8").decode(w)}else throw new $("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[d,y]of Object.entries(n.headers))typeof y=="string"?u.set(d,y):Array.isArray(y)&&u.set(d,y.join(", "));const p=new Request(c,{method:n.method??"POST",headers:u,body:i});try{await this.processRequest(t,p,s)}catch(d){throw r&&d instanceof $&&d.message==="Sidekick Signature did not validate"?new $("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:d.hint}):d}}};tt=new WeakMap,_e=new WeakMap,nt=new WeakSet,en=async function(t,n){const s=Kt(this.apiURI);s.recheckAt=le();let i;try{i=await zn(this.apiURI,()=>this.fetchJwks())}catch{throw s.recheckFailing=!0,s.recheckAt=le(),new Fn}const r=i.keys.find(a=>(a==null?void 0:a.kid)===t);if(r&&Oi(r,n.jwk))return n.confirmedAt=i.at,n;if(mi(this.apiURI,t,n),!r)throw new $("Signing key is no longer published",{kid:t});const o={...await Mn(r),jwk:r,confirmedAt:i.at};return Dn(this.apiURI,t,o),o};let Jt=Bt;const _i={target:"init() in @sidekickdb/admin"};function Ai(e){return{...e,apiURI:Dt(e.apiURI,_i)}}function Ri(e,t){return"email"in t?e["as-email"]=t.email:"token"in t?e["as-token"]=t.token:"guest"in t&&(e["as-guest"]="true"),e}function Pi(e,t){if(!(t&&("token"in t||"guest"in t))&&!e.adminToken)throw t&&"email"in t?new Error("Admin token required. To impersonate users with an email you must pass `adminToken` to `init`."):new Error("Admin token required. To run this operation pass `adminToken` to `init`, or use `db.asUser`.")}function U(e,t){Pi(e,t);const{adminToken:n,appId:s}=e,i={"content-type":"application/json","app-id":s};return n&&(i.authorization=`Bearer ${n}`),t?Ri(i,t):i}function ji(){return fetch.__nextPatched&&!globalThis[Symbol.for("next-patch")]}function Ui(){return ji()?{cache:"no-store"}:{}}async function Mi(e,t){const n=await t.text();try{const s=JSON.parse(n);return e(new ue({status:t.status,body:s}))}catch{return e(new ue({status:t.status,body:{type:void 0,message:n}}))}}async function M(e,t){const n=Ui(),s={...(t==null?void 0:t.headers)||{},"Sidekick-Admin-Version":$e,"Sidekick-Core-Version":$e},i=await fetch(e,{...n,...t,headers:s});if(i.status===200){const r=await i.json();return Promise.resolve(r)}return Mi(r=>Promise.reject(r),i)}function Di(e){var t,n,Yn;return t=class{constructor(r){k(this,n);l(this,"source");l(this,"url");this.url=r,this.source=E(this,n,Yn).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,Yn=function(r){return new ie(r,{messageEvent:_n,fetch(a,c){return fetch(a,{...c,method:"POST",headers:e.headers,body:JSON.stringify({"inference?":e.inference,versions:{"@sidekickdb/admin":$e,"@sidekickdb/core":$e}})})}})},l(t,"OPEN",ie.OPEN),l(t,"CONNECTING",ie.CONNECTING),l(t,"CLOSED",ie.CLOSED),t}function Ni(e){var n,s;(!e.appId||!P(e.appId))&&console.warn("warning: SidekickDB 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 Ht(t)}function Vn(e){return(Array.isArray(e)?e:[e]).flatMap(Os)}class Li{constructor(t){l(this,"config");this.config=t}async getPresence(t,n){return(await M(`${this.config.apiURI}/admin/rooms/presence?app_id=${this.config.appId}&room-type=${String(t)}&room-id=${n}`,{method:"GET",headers:U(this.config)})).sessions||{}}}class Fi{constructor(t){l(this,"config");l(this,"generateMagicCode",async t=>M(`${this.config.apiURI}/admin/magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t})}));l(this,"sendMagicCode",async t=>M(`${this.config.apiURI}/admin/send_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t})}));l(this,"verifyMagicCode",async(t,n)=>{const{user:s}=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t,code:n})});return s});l(this,"checkMagicCode",async(t,n,s)=>{const i=await M(`${this.config.apiURI}/admin/verify_magic_code?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify({email:t,code:n,...s!=null&&s.extraFields?{"extra-fields":s.extraFields}:{}})});return{user:i.user,created:i.created}});l(this,"verifyToken",async t=>(await M(`${this.config.apiURI}/runtime/auth/verify_refresh_token?app_id=${this.config.appId}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({"app-id":this.config.appId,"refresh-token":t})})).user);l(this,"getUser",async t=>{const n=new URLSearchParams(Object.entries(t)).toString();return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"GET",headers:U(this.config)})).user});l(this,"deleteUser",async t=>{const n=new URLSearchParams(Object.entries(t)).toString();return(await M(`${this.config.apiURI}/admin/users?app_id=${this.config.appId}&${n}`,{method:"DELETE",headers:U(this.config)})).deleted});l(this,"getUserFromRequest",async(t,n)=>{const s=t.headers.get("cookie")||"",i=ei(s),r="sidekick_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 M(`${this.config.apiURI}/admin/refresh_tokens?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config),body:JSON.stringify(n)})).user.refresh_token}async signOut(t){const n=typeof t=="string"?{email:t}:t,s=this.config;await M(`${s.apiURI}/admin/sign_out?app_id=${this.config.appId}`,{method:"POST",headers:U(s),body:JSON.stringify(n)})}}const Jn=e=>e&&typeof e=="object"&&typeof e.pipe=="function"&&typeof e.read=="function",Wi=e=>e&&typeof e.getReader=="function";function Hn(e){return/^[\x20-\x7e\xa0-\xff]*$/.test(e)}class Bn{constructor(t,n){l(this,"config");l(this,"impersonationOpts");l(this,"uploadFile",async(t,n,s={})=>{const i={...U(this.config,this.impersonationOpts)};Hn(t)&&(i.path=t),s.contentDisposition&&Hn(s.contentDisposition)&&(i["content-disposition"]=s.contentDisposition),delete i["content-type"],s.contentType&&(i["content-type"]=s.contentType);let r;if(Jn(n)&&(r="half"),Jn(n)||Wi(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}},a=`${this.config.apiURI}/admin/storage/upload?app_id=${encodeURIComponent(this.config.appId)}&path=${encodeURIComponent(t)}`;return s.contentDisposition&&(a+=`&content-disposition=${encodeURIComponent(s.contentDisposition)}`),M(a,o)});l(this,"delete",async t=>M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"DELETE",headers:U(this.config,this.impersonationOpts)}));l(this,"deleteMany",async t=>M(`${this.config.apiURI}/admin/storage/files/delete?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify({filenames:t})}));l(this,"upload",async(t,n,s={})=>{const{data:i}=await M(`${this.config.apiURI}/admin/storage/signed-upload-url?app_id=${this.config.appId}`,{method:"POST",headers:U(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});l(this,"list",async()=>{const{data:t}=await M(`${this.config.apiURI}/admin/storage/files?app_id=${this.config.appId}`,{method:"GET",headers:U(this.config)});return t});l(this,"getDownloadUrl",async t=>{const{data:n}=await M(`${this.config.apiURI}/admin/storage/signed-download-url?app_id=${this.config.appId}&filename=${encodeURIComponent(t)}`,{method:"GET",headers:U(this.config)});return n});this.config=t,this.impersonationOpts=n}}class zi{constructor(t){k(this,Ke);l(this,"createReadStream",t=>f(this,Ke).call(this).createReadStream(t));l(this,"createWriteStream",t=>f(this,Ke).call(this).createWriteStream(t));I(this,Ke,t)}}Ke=new WeakMap;function Ki(e,t=console){return{info:e?(...n)=>t.info(...n):()=>{},debug:e?(...n)=>t.debug(...n):()=>{},error:e?(...n)=>t.error(...n):()=>{}}}const qt=class qt{constructor(t){k(this,F);l(this,"config");l(this,"auth");l(this,"storage");l(this,"streams");l(this,"rooms");l(this,"impersonationOpts");l(this,"webhooks");k(this,K,null);k(this,Ae,0);k(this,G,null);k(this,X);l(this,"tx",mn());l(this,"asUser",t=>{const n=new qt({...this.config});return n.impersonationOpts=t,n.storage=new Bn(this.config,t),n});l(this,"query",(t,n={})=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t}),this.config.disableValidation||kn(t,this.config.schema);const s=n.fetchOpts||{},i=s.headers||{};return M(`${this.config.apiURI}/admin/query?app_id=${this.config.appId}`,{...s,method:"POST",headers:{...i,...U(this.config,this.impersonationOpts)},body:JSON.stringify({query:t,"inference?":!!this.config.schema})})});l(this,"transact",t=>(this.config.disableValidation||js(t,this.config.schema),M(`${this.config.apiURI}/admin/transact?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify({steps:Vn(t),"throw-on-missing-attrs?":!!this.config.schema})})));l(this,"debugQuery",async(t,n)=>{t&&n&&"ruleParams"in n&&(t={$$ruleParams:n.ruleParams,...t});const 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 M(`${this.config.apiURI}/admin/query_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify(s)});return{result:i.result,checkResults:i["check-results"]}});l(this,"debugTransact",(t,n)=>{const s={steps:Vn(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),M(`${this.config.apiURI}/admin/transact_perms_check?app_id=${this.config.appId}`,{method:"POST",headers:U(this.config,this.impersonationOpts),body:JSON.stringify(s)})});k(this,wt,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][open]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][open]",t.target.id),I(this,Ae,0),(n=f(this,G))==null||n.onConnectionStatusChange("authenticated")});k(this,St,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][close]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][close]",t.target.id),(n=f(this,G))==null||n.onConnectionStatusChange("closed"),f(this,K)&&(I(this,K,null),E(this,F,tn).call(this)||(setTimeout(()=>E(this,F,$t).call(this),f(this,Ae)),I(this,Ae,Math.min(15e3,Math.max(f(this,Ae),500)*2))))});k(this,kt,t=>{var n;if(t.target!==f(this,K)){f(this,X).info("[socket][error]",t.target.id,"skip; this is no longer the current transport");return}f(this,X).info("[socket][error]",t.target.id),(n=f(this,G))==null||n.onConnectionStatusChange("closed")});k(this,It,t=>{var s,i,r,o,a,c;if(t.target!==f(this,K)){f(this,X).info("[socket][message]",t.target.id,"skip; this is no longer the current transport");return}const n=t.message;switch(f(this,X).info("[receive]",n),n.op){case"start-stream-ok":{(s=f(this,G))==null||s.onStartStreamOk(n);break}case"stream-flushed":{(i=f(this,G))==null||i.onStreamFlushed(n);break}case"append-failed":{(r=f(this,G))==null||r.onAppendFailed(n);break}case"stream-append":{(o=f(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=f(this,G))==null||c.onRecieveError(n);break}}break}}E(this,F,ss).call(this)});this.config=Ai(t),this.auth=new Fi(this.config),this.storage=new Bn(this.config,this.impersonationOpts),this.streams=new zi(E(this,F,ns).bind(this)),this.rooms=new Li(this.config),this.webhooks=new Jt(this.config,M),I(this,X,Ki(!!this.config.verbose,this.config.logger))}subscribeQuery(t,n,s={}){t&&s&&"ruleParams"in s&&(t={$$ruleParams:s.ruleParams,...t}),this.config.disableValidation||kn(t,this.config.schema);const o={...(s.fetchOpts||{}).headers||{},...U(this.config,this.impersonationOpts)},a=!!this.config.schema;return Zs(t,n,{headers:o,inference:a,apiURI:this.config.apiURI})}};K=new WeakMap,Ae=new WeakMap,G=new WeakMap,X=new WeakMap,F=new WeakSet,Zn=function(){f(this,K)&&f(this,K).close();const t={...U(this.config,this.impersonationOpts)},n=!!this.config.schema,s=Di({headers:t,inference:n}),i=new Ds(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=f(this,wt),i.onmessage=f(this,It),i.onclose=f(this,St),i.onerror=f(this,kt),I(this,K,i),i},$t=function(){return f(this,K)||E(this,F,Zn).call(this)},es=function(t,n){const s=E(this,F,$t).call(this);f(this,X).info("[send]",t,n,{isOpen:s.isOpen()}),s.isOpen()&&s.send({"client-event-id":t,...n})},ts=function(){E(this,F,$t).call(this);const t=new Ws({WStream:this.config.WritableStream||WritableStream,RStream:this.config.ReadableStream||ReadableStream,trySend:(n,s)=>{E(this,F,es).call(this,n,s)},log:f(this,X)});return I(this,G,t),t},ns=function(){return f(this,G)||E(this,F,ts).call(this)},wt=new WeakMap,St=new WeakMap,kt=new WeakMap,tn=function(){return!f(this,G)||!f(this,G).hasActiveStreams()},ss=function(){if(f(this,K)&&E(this,F,tn).call(this)){const t=f(this,K);f(this,X).info("cleaning up unused socket",t.id),I(this,K,null),t.close()}},It=new WeakMap;let Ht=qt;var Vi={};function lt(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 ht(e){const t=Vi[e];return t!=null&&t.trim()?t:void 0}function Ji(e){const t=e.appId||ht("SIDEKICK_APP_ID")||ht("NEXT_PUBLIC_SIDEKICK_APP_ID");if(!t)throw new Error("Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.");const n=e.adminToken||ht("SIDEKICK_APP_ADMIN_TOKEN");if(!n)throw new Error("Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.");const s=Dt(e.apiURI||ht("SIDEKICK_API_URI"),{target:"createResumableStreamContext()",envVar:"SIDEKICK_API_URI"}),i={appId:t,adminToken:n,apiURI:s};e.verbose&&(i.verbose=e.verbose);const r=Ni(i);async function o(p,d,y){const m=r.streams.createWriteStream({clientId:p,waitUntil:e.waitUntil??void 0});try{const w=await m.streamId();d().pipeTo(m);const h=r.streams.createReadStream({streamId:w});return y?h.pipeThrough(lt(y)):h}catch{const b=r.streams.createReadStream({clientId:p});return y?b.pipeThrough(lt(y)):b}}async function a(p,d){var m,w,b;const y=r.streams.createReadStream({clientId:p});try{await y.streamId()}catch(h){if(h instanceof $&&((b=(w=(m=h.hint)==null?void 0:m.errors)==null?void 0:w[0])==null?void 0:b.message)==="Stream is missing.")return;throw h}return d?y.pipeThrough(lt(d)):y}async function c(p,d,y){const m=d(),w=r.streams.createWriteStream({clientId:p,waitUntil:e.waitUntil??void 0});await w.streamId(),m.pipeTo(w);const b=r.streams.createReadStream({clientId:p});return y?b.pipeThrough(lt(y)):b}async function u(p){var m;const d=await r.query({$streams:{$:{where:{clientId:p}}}}),y=(m=d==null?void 0:d.$streams)==null?void 0:m[0];return y!=null&&y.done?"DONE":y?!0:null}return{resumableStream:o,resumeExistingStream:a,createNewResumableStream:c,hasExistingStream:u}}C.createResumableStreamContext=Ji,Object.defineProperty(C,Symbol.toStringTag,{value:"Module"})});
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "@sidekickdb/resumable-stream",
3
- "version": "2.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "SidekickDB's drop-in replacement for Vercel's resumable-stream package.",
5
5
  "license": "Apache-2.0",
6
- "homepage": "https://github.com/SidekickDB/sidekick/tree/main/client/packages/resumable-stream",
6
+ "homepage": "https://sidekickdb.co/docs/streams",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/SidekickDB/sidekick.git",
@@ -54,7 +54,7 @@
54
54
  "vitest": "^1.6.0"
55
55
  },
56
56
  "dependencies": {
57
- "@sidekickdb/admin": "2.0.0"
57
+ "@sidekickdb/admin": "3.0.0"
58
58
  },
59
59
  "scripts": {
60
60
  "test": "vitest",
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { Config, init, InstantError, requireApiURI } from '@sidekickdb/admin';
1
+ import { Config, init, SidekickError, requireApiURI } from '@sidekickdb/admin';
2
2
 
3
3
  export interface CreateResumableStreamContextOptions {
4
4
  /**
@@ -10,23 +10,20 @@ export interface CreateResumableStreamContextOptions {
10
10
  */
11
11
  waitUntil: ((promise: Promise<unknown>) => void) | null;
12
12
  /**
13
- * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable
14
- * (or their older names, INSTANT_APP_ID and NEXT_PUBLIC_INSTANT_APP_ID).
13
+ * The appId for your app. It may also be provided with the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.
15
14
  */
16
15
  appId?: string;
17
16
  /**
18
- * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable
19
- * (or its older name, INSTANT_APP_ADMIN_TOKEN).
17
+ * The admin token for your app. It may also be provided with the SIDEKICK_APP_ADMIN_TOKEN environment variable.
20
18
  */
21
19
  adminToken?: string;
22
20
  /**
23
21
  * URL of your SidekickDB server. Falls back to the SIDEKICK_API_URI
24
- * environment variable (or its older name, INSTANT_API_URI); one of the two
25
- * is required.
22
+ * environment variable; one of the two is required.
26
23
  */
27
24
  apiURI?: string;
28
25
  /**
29
- * Enable verbose logging from the underlying instant connection
26
+ * Enable verbose logging from the underlying SidekickDB connection
30
27
  */
31
28
  verbose?: boolean;
32
29
  }
@@ -102,16 +99,10 @@ function skipCharactersTransformer(skipCharacters: number) {
102
99
  });
103
100
  }
104
101
 
105
- /**
106
- * Reads an environment variable that can be set under its SidekickDB name
107
- * (`SIDEKICK_APP_ID`) or its older name (`INSTANT_APP_ID`). The SidekickDB name
108
- * wins; a blank value counts as unset.
109
- */
110
- function readEnv(sidekickName: string): string | undefined {
111
- return [
112
- process.env[sidekickName],
113
- process.env[sidekickName.replace('SIDEKICK_', 'INSTANT_')],
114
- ].find((v) => v?.trim());
102
+ /** SidekickDB: an environment variable, with a blank value counting as unset. */
103
+ function readEnv(name: string): string | undefined {
104
+ const value = process.env[name];
105
+ return value?.trim() ? value : undefined;
115
106
  }
116
107
 
117
108
  export function createResumableStreamContext(
@@ -186,7 +177,7 @@ export function createResumableStreamContext(
186
177
  await readStream.streamId();
187
178
  } catch (e) {
188
179
  if (
189
- e instanceof InstantError &&
180
+ e instanceof SidekickError &&
190
181
  (e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'
191
182
  ) {
192
183
  return undefined;
package/vite.config.ts CHANGED
@@ -9,7 +9,7 @@ export default defineConfig({
9
9
  formats: ['umd', 'es'],
10
10
  // this is the file that exports our components
11
11
  entry: resolve(__dirname, 'src', 'index.ts'),
12
- name: 'instant',
12
+ name: 'sidekick',
13
13
  fileName: 'index',
14
14
  },
15
15
  },