@sidekickdb/resumable-stream 0.0.0-stage → 2.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.
- package/.tshy/build.json +8 -0
- package/.tshy/commonjs.json +16 -0
- package/.tshy/esm.json +15 -0
- package/.turbo/turbo-build.log +50 -0
- package/LICENSE.md +202 -0
- package/NOTICE +27 -0
- package/README.md +97 -2
- package/__tests__/src/apiURI.test.ts +56 -0
- package/__tests__/src/resumable-stream.test.ts +353 -0
- package/__tests__/src/testing-stream.ts +87 -0
- package/dist/commonjs/index.d.ts +71 -0
- package/dist/commonjs/index.d.ts.map +1 -0
- package/dist/commonjs/index.js +129 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/package.json +3 -0
- package/dist/esm/index.d.ts +71 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +126 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/standalone/index.js +4323 -0
- package/dist/standalone/index.umd.cjs +5 -0
- package/package.json +70 -3
- package/src/index.ts +247 -0
- package/tsconfig.cjs.dev.json +15 -0
- package/tsconfig.dev.json +14 -0
- package/tsconfig.json +12 -0
- package/tsconfig.test.json +5 -0
- package/vite.config.ts +19 -0
|
@@ -0,0 +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"})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,73 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sidekickdb/resumable-stream",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "SidekickDB's drop-in replacement for Vercel's resumable-stream package.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"homepage": "https://github.com/SidekickDB/sidekick/tree/main/client/packages/resumable-stream",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/SidekickDB/sidekick.git",
|
|
10
|
+
"directory": "client/packages/resumable-stream"
|
|
11
|
+
},
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/SidekickDB/sidekick/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"main": "./dist/commonjs/index.js",
|
|
17
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
18
|
+
"module": "./dist/esm/index.js",
|
|
19
|
+
"unpkg": "standalone/index.umd.js",
|
|
20
|
+
"exports": {
|
|
21
|
+
"./package.json": "./package.json",
|
|
22
|
+
".": {
|
|
23
|
+
"import": {
|
|
24
|
+
"types": "./dist/esm/index.d.ts",
|
|
25
|
+
"default": "./dist/esm/index.js"
|
|
26
|
+
},
|
|
27
|
+
"require": {
|
|
28
|
+
"types": "./dist/commonjs/index.d.ts",
|
|
29
|
+
"default": "./dist/commonjs/index.js"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"tshy": {
|
|
34
|
+
"selfLink": false,
|
|
35
|
+
"main": true,
|
|
36
|
+
"module": true,
|
|
37
|
+
"project": "./tsconfig.json",
|
|
38
|
+
"exports": {
|
|
39
|
+
"./package.json": "./package.json",
|
|
40
|
+
".": "./src/index.ts"
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
"devDependencies": {
|
|
44
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
45
|
+
"@babel/core": "^7.17.9",
|
|
46
|
+
"@babel/preset-env": "^7.16.11",
|
|
47
|
+
"@types/node": "^18.11.18",
|
|
48
|
+
"@types/uuid": "^10.0.0",
|
|
49
|
+
"@types/websocket": "^1.0.5",
|
|
50
|
+
"npm-run-all": "^4.1.5",
|
|
51
|
+
"tshy": "^3.0.2",
|
|
52
|
+
"typescript": "^5.9.3",
|
|
53
|
+
"vite": "^5.2.0",
|
|
54
|
+
"vitest": "^1.6.0"
|
|
55
|
+
},
|
|
56
|
+
"dependencies": {
|
|
57
|
+
"@sidekickdb/admin": "2.0.0"
|
|
58
|
+
},
|
|
59
|
+
"scripts": {
|
|
60
|
+
"test": "vitest",
|
|
61
|
+
"test:ci": "vitest run",
|
|
62
|
+
"check": "tsc --noEmit",
|
|
63
|
+
"check-exports": "attw --pack .",
|
|
64
|
+
"dev:module": "tsc --watch --preserveWatchOutput -p tsconfig.dev.json",
|
|
65
|
+
"dev:main": "tsc --watch --preserveWatchOutput -p tsconfig.cjs.dev.json",
|
|
66
|
+
"dev": "run-p dev:module dev:main",
|
|
67
|
+
"clean": "rm -rf dist",
|
|
68
|
+
"build": "rm -rf dist; npm run build:tshy && npm run build:standalone && npm run check-exports",
|
|
69
|
+
"build:tshy": "tshy",
|
|
70
|
+
"build:standalone": "vite build",
|
|
71
|
+
"publish-package": "pnpm pack && npm publish *.tgz --access public"
|
|
72
|
+
}
|
|
6
73
|
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
import { Config, init, InstantError, requireApiURI } from '@sidekickdb/admin';
|
|
2
|
+
|
|
3
|
+
export interface CreateResumableStreamContextOptions {
|
|
4
|
+
/**
|
|
5
|
+
* A function that takes a promise and ensures that the current program stays alive
|
|
6
|
+
* until the promise is resolved.
|
|
7
|
+
*
|
|
8
|
+
* If you are deploying to a server environment, where you don't have to worry about
|
|
9
|
+
* the function getting suspended, pass in null.
|
|
10
|
+
*/
|
|
11
|
+
waitUntil: ((promise: Promise<unknown>) => void) | null;
|
|
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).
|
|
15
|
+
*/
|
|
16
|
+
appId?: string;
|
|
17
|
+
/**
|
|
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).
|
|
20
|
+
*/
|
|
21
|
+
adminToken?: string;
|
|
22
|
+
/**
|
|
23
|
+
* 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.
|
|
26
|
+
*/
|
|
27
|
+
apiURI?: string;
|
|
28
|
+
/**
|
|
29
|
+
* Enable verbose logging from the underlying instant connection
|
|
30
|
+
*/
|
|
31
|
+
verbose?: boolean;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface ResumableStreamContext {
|
|
35
|
+
/**
|
|
36
|
+
* Creates or resumes a resumable stream.
|
|
37
|
+
*
|
|
38
|
+
* Does not throw if the underlying stream is already done. The output can always be read from the
|
|
39
|
+
* stream and does not have to be saved to a separate table after streaming is completed.
|
|
40
|
+
*
|
|
41
|
+
* By default returns the entire buffered stream. Use `skipCharacters` to resume from a specific point.
|
|
42
|
+
*
|
|
43
|
+
* @param streamId - The ID of the stream. Must be unique for each stream.
|
|
44
|
+
* @param makeStream - A function that returns a stream of strings. It's only executed if the stream it not yet in progress.
|
|
45
|
+
* @param skipCharacters - Number of characters to skip
|
|
46
|
+
* @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
|
|
47
|
+
*/
|
|
48
|
+
resumableStream: (
|
|
49
|
+
streamId: string,
|
|
50
|
+
makeStream: () => ReadableStream<string>,
|
|
51
|
+
skipCharacters?: number,
|
|
52
|
+
) => Promise<ReadableStream<string> | null>;
|
|
53
|
+
/**
|
|
54
|
+
* Resumes a stream that was previously created by `createNewResumableStream`.
|
|
55
|
+
*
|
|
56
|
+
* @param streamId - The ID of the stream. Must be unique for each stream.
|
|
57
|
+
* @param skipCharacters - Number of characters to skip
|
|
58
|
+
* @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
|
|
59
|
+
*/
|
|
60
|
+
resumeExistingStream: (
|
|
61
|
+
streamId: string,
|
|
62
|
+
skipCharacters?: number,
|
|
63
|
+
) => Promise<ReadableStream<string> | null | undefined>;
|
|
64
|
+
/**
|
|
65
|
+
* Creates a new resumable stream.
|
|
66
|
+
*
|
|
67
|
+
* @param streamId - The ID of the stream. Must be unique for each stream.
|
|
68
|
+
* @param makeStream - A function that returns a stream of strings.
|
|
69
|
+
* @param skipCharacters - Number of characters to skip
|
|
70
|
+
* @returns A readable stream of strings. Returns the stream even if it is fully done (streams are persisted until deleted)
|
|
71
|
+
*/
|
|
72
|
+
createNewResumableStream: (
|
|
73
|
+
streamId: string,
|
|
74
|
+
makeStream: () => ReadableStream<string>,
|
|
75
|
+
skipCharacters?: number,
|
|
76
|
+
) => Promise<ReadableStream<string> | null>;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Checks if a stream with the given streamId exists.
|
|
80
|
+
* @param streamId - The ID of the stream.
|
|
81
|
+
* @returns null if there is no stream with the given streamId. True if a stream with the given streamId exists. "DONE" if the stream is fully done.
|
|
82
|
+
*/
|
|
83
|
+
hasExistingStream: (streamId: string) => Promise<null | true | 'DONE'>;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function skipCharactersTransformer(skipCharacters: number) {
|
|
87
|
+
let skipLeft = skipCharacters;
|
|
88
|
+
return new TransformStream<string>({
|
|
89
|
+
transform(chunk, controller) {
|
|
90
|
+
if (!skipLeft) {
|
|
91
|
+
controller.enqueue(chunk);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
if (skipLeft > chunk.length) {
|
|
95
|
+
skipLeft -= chunk.length;
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
const remaining = chunk.slice(skipLeft);
|
|
99
|
+
skipLeft = 0;
|
|
100
|
+
controller.enqueue(remaining);
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
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());
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export function createResumableStreamContext(
|
|
118
|
+
options: CreateResumableStreamContextOptions,
|
|
119
|
+
): ResumableStreamContext {
|
|
120
|
+
const appId =
|
|
121
|
+
options.appId ||
|
|
122
|
+
readEnv('SIDEKICK_APP_ID') ||
|
|
123
|
+
readEnv('NEXT_PUBLIC_SIDEKICK_APP_ID');
|
|
124
|
+
if (!appId) {
|
|
125
|
+
throw new Error(
|
|
126
|
+
'Missing appId. Pass it as an argument to createResumableStreamContext or set either the SIDEKICK_APP_ID or NEXT_PUBLIC_SIDEKICK_APP_ID environment variable.',
|
|
127
|
+
);
|
|
128
|
+
}
|
|
129
|
+
const adminToken = options.adminToken || readEnv('SIDEKICK_APP_ADMIN_TOKEN');
|
|
130
|
+
if (!adminToken) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
'Missing adminToken. Pass it as an argument to createResumableStreamContext or set the SIDEKICK_APP_ADMIN_TOKEN environment variable.',
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const apiURI = requireApiURI(options.apiURI || readEnv('SIDEKICK_API_URI'), {
|
|
137
|
+
target: 'createResumableStreamContext()',
|
|
138
|
+
envVar: 'SIDEKICK_API_URI',
|
|
139
|
+
});
|
|
140
|
+
|
|
141
|
+
const config: Config = { appId, adminToken, apiURI };
|
|
142
|
+
|
|
143
|
+
if (options.verbose) {
|
|
144
|
+
config.verbose = options.verbose;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const db = init(config);
|
|
148
|
+
|
|
149
|
+
async function resumableStream(
|
|
150
|
+
streamId: string,
|
|
151
|
+
makeStream: () => ReadableStream<string>,
|
|
152
|
+
skipCharacters?: number,
|
|
153
|
+
): Promise<ReadableStream<string> | null> {
|
|
154
|
+
const writeStream = db.streams.createWriteStream({
|
|
155
|
+
clientId: streamId,
|
|
156
|
+
waitUntil: options.waitUntil ?? undefined,
|
|
157
|
+
});
|
|
158
|
+
try {
|
|
159
|
+
const s = await writeStream.streamId();
|
|
160
|
+
const inputStream = makeStream();
|
|
161
|
+
inputStream.pipeTo(writeStream);
|
|
162
|
+
const readStream = db.streams.createReadStream({ streamId: s });
|
|
163
|
+
if (skipCharacters) {
|
|
164
|
+
return readStream.pipeThrough(
|
|
165
|
+
skipCharactersTransformer(skipCharacters),
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return readStream;
|
|
169
|
+
} catch (e) {
|
|
170
|
+
const readStream = db.streams.createReadStream({ clientId: streamId });
|
|
171
|
+
if (skipCharacters) {
|
|
172
|
+
return readStream.pipeThrough(
|
|
173
|
+
skipCharactersTransformer(skipCharacters),
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
return readStream;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
async function resumeExistingStream(
|
|
181
|
+
streamId: string,
|
|
182
|
+
skipCharacters?: number,
|
|
183
|
+
): Promise<ReadableStream<string> | null | undefined> {
|
|
184
|
+
const readStream = db.streams.createReadStream({ clientId: streamId });
|
|
185
|
+
try {
|
|
186
|
+
await readStream.streamId();
|
|
187
|
+
} catch (e) {
|
|
188
|
+
if (
|
|
189
|
+
e instanceof InstantError &&
|
|
190
|
+
(e.hint as any)?.errors?.[0]?.message === 'Stream is missing.'
|
|
191
|
+
) {
|
|
192
|
+
return undefined;
|
|
193
|
+
}
|
|
194
|
+
throw e;
|
|
195
|
+
}
|
|
196
|
+
if (skipCharacters) {
|
|
197
|
+
return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
|
|
198
|
+
}
|
|
199
|
+
return readStream;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
async function createNewResumableStream(
|
|
203
|
+
streamId: string,
|
|
204
|
+
makeStream: () => ReadableStream<string>,
|
|
205
|
+
skipCharacters?: number,
|
|
206
|
+
): Promise<ReadableStream<string> | null> {
|
|
207
|
+
const inputStream = makeStream();
|
|
208
|
+
const writeStream = db.streams.createWriteStream({
|
|
209
|
+
clientId: streamId,
|
|
210
|
+
waitUntil: options.waitUntil ?? undefined,
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
// Wait for stream to be acknowledged by the server
|
|
214
|
+
await writeStream.streamId();
|
|
215
|
+
|
|
216
|
+
inputStream.pipeTo(writeStream);
|
|
217
|
+
const readStream = db.streams.createReadStream({ clientId: streamId });
|
|
218
|
+
if (skipCharacters) {
|
|
219
|
+
return readStream.pipeThrough(skipCharactersTransformer(skipCharacters));
|
|
220
|
+
}
|
|
221
|
+
return readStream;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function hasExistingStream(
|
|
225
|
+
streamId: string,
|
|
226
|
+
): Promise<null | true | 'DONE'> {
|
|
227
|
+
const data = await db.query({
|
|
228
|
+
$streams: { $: { where: { clientId: streamId } } },
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
const stream = data?.$streams?.[0];
|
|
232
|
+
if (stream?.done) {
|
|
233
|
+
return 'DONE';
|
|
234
|
+
}
|
|
235
|
+
if (stream) {
|
|
236
|
+
return true;
|
|
237
|
+
}
|
|
238
|
+
return null;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
resumableStream,
|
|
243
|
+
resumeExistingStream,
|
|
244
|
+
createNewResumableStream,
|
|
245
|
+
hasExistingStream,
|
|
246
|
+
};
|
|
247
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"composite": true,
|
|
5
|
+
|
|
6
|
+
"module": "es2015",
|
|
7
|
+
"moduleResolution": "bundler",
|
|
8
|
+
|
|
9
|
+
"outDir": "./dist/commonjs",
|
|
10
|
+
|
|
11
|
+
"declaration": true,
|
|
12
|
+
"declarationDir": "./dist/commonjs",
|
|
13
|
+
"incremental": true
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "./tsconfig.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"module": "es2022",
|
|
5
|
+
"target": "es2022",
|
|
6
|
+
"moduleResolution": "bundler",
|
|
7
|
+
|
|
8
|
+
"outDir": "./dist/esm",
|
|
9
|
+
|
|
10
|
+
"declaration": true,
|
|
11
|
+
"declarationDir": "./dist/esm",
|
|
12
|
+
"incremental": true
|
|
13
|
+
}
|
|
14
|
+
}
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../tsconfig.base.json",
|
|
3
|
+
"include": ["src"],
|
|
4
|
+
"exclude": ["node_modules", "dist", "src/__types__", "src/__tests__"],
|
|
5
|
+
"compilerOptions": {
|
|
6
|
+
"outDir": "dist/tsc",
|
|
7
|
+
"rewriteRelativeImportExtensions": true,
|
|
8
|
+
"rootDir": "src",
|
|
9
|
+
"checkJs": false,
|
|
10
|
+
"strictNullChecks": true
|
|
11
|
+
}
|
|
12
|
+
}
|
package/vite.config.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { defineConfig } from 'vite';
|
|
2
|
+
import { resolve } from 'path';
|
|
3
|
+
|
|
4
|
+
export default defineConfig({
|
|
5
|
+
clearScreen: false,
|
|
6
|
+
build: {
|
|
7
|
+
outDir: 'dist/standalone',
|
|
8
|
+
lib: {
|
|
9
|
+
formats: ['umd', 'es'],
|
|
10
|
+
// this is the file that exports our components
|
|
11
|
+
entry: resolve(__dirname, 'src', 'index.ts'),
|
|
12
|
+
name: 'instant',
|
|
13
|
+
fileName: 'index',
|
|
14
|
+
},
|
|
15
|
+
},
|
|
16
|
+
define: {
|
|
17
|
+
'process.env': {},
|
|
18
|
+
},
|
|
19
|
+
});
|