@verdant-web/store 3.0.6 → 3.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +6 -6
- package/dist/bundle/index.js.map +4 -4
- package/dist/cjs/__tests__/fixtures/testStorage.d.ts +52 -105
- package/dist/cjs/__tests__/fixtures/testStorage.js +36 -65
- package/dist/cjs/__tests__/fixtures/testStorage.js.map +1 -1
- package/dist/esm/__tests__/fixtures/testStorage.d.ts +52 -105
- package/dist/esm/__tests__/fixtures/testStorage.js +37 -66
- package/dist/esm/__tests__/fixtures/testStorage.js.map +1 -1
- package/dist/tsconfig-cjs.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/__tests__/fixtures/testStorage.ts +37 -66
- package/src/entities/EntityStore.ts +1 -1
package/dist/bundle/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var No=Object.create;var _t=Object.defineProperty;var Vo=Object.getOwnPropertyDescriptor;var Uo=Object.getOwnPropertyNames;var Ko=Object.getPrototypeOf,$o=Object.prototype.hasOwnProperty;var zo=(r,t)=>()=>(r&&(t=r(r=0)),t);var oe=(r,t)=>()=>(t||r((t={exports:{}}).exports,t),t.exports),Gr=(r,t)=>{for(var e in t)_t(r,e,{get:t[e],enumerable:!0})},Xr=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Uo(t))!$o.call(r,i)&&i!==e&&_t(r,i,{get:()=>t[i],enumerable:!(n=Vo(t,i))||n.enumerable});return r};var Qe=(r,t,e)=>(e=r!=null?No(Ko(r)):{},Xr(t||!r||!r.__esModule?_t(e,"default",{value:r,enumerable:!0}):e,r)),Je=r=>Xr(_t({},"__esModule",{value:!0}),r);var Hn=oe((Aa,Zr)=>{Zr.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ti=oe((Ta,ei)=>{var qo=Hn(),Ho=typeof window=="object"?window:self,Wo=Object.keys(Ho).length,Qo=navigator.mimeTypes?navigator.mimeTypes.length:0,Jo=qo((Qo+navigator.userAgent.length).toString(36)+Wo.toString(36),4);ei.exports=function(){return Jo}});var oi=oe((Ra,ii)=>{var Wn,ni=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ni?(ri=Math.pow(2,32)-1,Wn=function(){return Math.abs(ni.getRandomValues(new Uint32Array(1))[0]/ri)}):Wn=Math.random;var ri;ii.exports=Wn});var at=oe((Fa,li)=>{var Pt=ti(),si=Hn(),Yo=oi(),ot=0,Jn=4,At=36,ai=Math.pow(At,Jn);function Qn(){return si((Yo()*ai<<0).toString(At),Jn)}function ci(){return ot=ot<ai?ot:0,ot++,ot-1}function st(){var r="c",t=new Date().getTime().toString(At),e=si(ci().toString(At),Jn),n=Pt(),i=Qn()+Qn();return r+t+e+n+i}st.slug=function(){var t=new Date().getTime().toString(36),e=ci().toString(36).slice(-4),n=Pt().slice(0,1)+Pt().slice(-1),i=Qn().slice(-2);return t.slice(-2)+e+n+i};st.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};st.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};st.fingerprint=Pt;li.exports=st});var Si=oe((wi,vi)=>{(function(r){var t;typeof wi=="object"?vi.exports=r():typeof define=="function"&&define.amd?define(r):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=r())})(function(){return function r(t,e,n){function i(c,p){if(!e[c]){if(!t[c]){var u=typeof require=="function"&&require;if(!p&&u)return u(c,!0);if(o)return o(c,!0);throw new Error("Cannot find module '"+c+"'")}p=e[c]={exports:{}},t[c][0].call(p.exports,function(m){var S=t[c][1][m];return i(S||m)},p,p.exports,r,t,e,n)}return e[c].exports}for(var o=typeof require=="function"&&require,s=0;s<n.length;s++)i(n[s]);return i}({1:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){"use strict";var g=r("crypto");function _(b,E){E=I(b,E);var d;return(d=E.algorithm!=="passthrough"?g.createHash(E.algorithm):new T).write===void 0&&(d.write=d.update,d.end=d.update),D(E,d).dispatch(b),d.update||d.end(""),d.digest?d.digest(E.encoding==="buffer"?void 0:E.encoding):(b=d.read(),E.encoding!=="buffer"?b.toString(E.encoding):b)}(e=t.exports=_).sha1=function(b){return _(b)},e.keys=function(b){return _(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return _(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return _(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var w=g.getHashes?g.getHashes().slice():["sha1","md5"],v=(w.push("passthrough"),["buffer","hex","binary","base64"]);function I(b,E){var d={};if(d.algorithm=(E=E||{}).algorithm||"sha1",d.encoding=E.encoding||"hex",d.excludeValues=!!E.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=E.ignoreUnknown===!0,d.respectType=E.respectType!==!1,d.respectFunctionNames=E.respectFunctionNames!==!1,d.respectFunctionProperties=E.respectFunctionProperties!==!1,d.unorderedArrays=E.unorderedArrays===!0,d.unorderedSets=E.unorderedSets!==!1,d.unorderedObjects=E.unorderedObjects!==!1,d.replacer=E.replacer||void 0,d.excludeKeys=E.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var h=0;h<w.length;++h)w[h].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=w[h]);if(w.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+w.join(", "));if(v.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+v.join(", "));return d}function x(b){if(typeof b=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(b))!=null}function D(b,E,d){d=d||[];function h(l){return E.update?E.update(l,"utf8"):E.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=b.replacer?b.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var O,C=Object.prototype.toString.call(l),M=/\[object (.*)\]/i.exec(C);if(M=(M=M?M[1]:"unknown:["+C+"]").toLowerCase(),0<=(C=d.indexOf(l)))return this.dispatch("[CIRCULAR:"+C+"]");if(d.push(l),o!==void 0&&o.isBuffer&&o.isBuffer(l))return h("buffer:"),h(l);if(M==="object"||M==="function"||M==="asyncfunction")return C=Object.keys(l),b.unorderedObjects&&(C=C.sort()),b.respectType===!1||x(l)||C.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(C=C.filter(function(B){return!b.excludeKeys(B)})),h("object:"+C.length+":"),O=this,C.forEach(function(B){O.dispatch(B),h(":"),b.excludeValues||O.dispatch(l[B]),h(",")});if(!this["_"+M]){if(b.ignoreUnknown)return h("["+M+"]");throw new Error('Unknown object type "'+M+'"')}this["_"+M](l)},_array:function(l,B){B=B!==void 0?B:b.unorderedArrays!==!1;var C=this;if(h("array:"+l.length+":"),!B||l.length<=1)return l.forEach(function(j){return C.dispatch(j)});var M=[],B=l.map(function(j){var k=new T,q=d.slice();return D(b,k,q).dispatch(j),M=M.concat(q.slice(d.length)),k.read().toString()});return d=d.concat(M),B.sort(),this._array(B,!1)},_date:function(l){return h("date:"+l.toJSON())},_symbol:function(l){return h("symbol:"+l.toString())},_error:function(l){return h("error:"+l.toString())},_boolean:function(l){return h("bool:"+l.toString())},_string:function(l){h("string:"+l.length+":"),h(l.toString())},_function:function(l){h("fn:"),x(l)?this.dispatch("[native]"):this.dispatch(l.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),b.respectFunctionProperties&&this._object(l)},_number:function(l){return h("number:"+l.toString())},_xml:function(l){return h("xml:"+l.toString())},_null:function(){return h("Null")},_undefined:function(){return h("Undefined")},_regexp:function(l){return h("regex:"+l.toString())},_uint8array:function(l){return h("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return h("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return h("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return h("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return h("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return h("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return h("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return h("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return h("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return h("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return h("url:"+l.toString())},_map:function(l){return h("map:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_set:function(l){return h("set:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_file:function(l){return h("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(b.ignoreUnknown)return h("[blob]");throw Error(`Hashing Blob objects is currently not supported
|
|
2
2
|
(see https://github.com/puleos/object-hash/issues/26)
|
|
3
3
|
Use "options.replacer" or "options.ignoreUnknown"
|
|
4
|
-
`)},_domwindow:function(){return h("domwindow")},_bigint:function(l){return h("bigint:"+l.toString())},_process:function(){return h("process")},_timer:function(){return h("timer")},_pipe:function(){return h("pipe")},_tcp:function(){return h("tcp")},_udp:function(){return h("udp")},_tty:function(){return h("tty")},_statwatcher:function(){return h("statwatcher")},_securecontext:function(){return h("securecontext")},_connection:function(){return h("connection")},_zlib:function(){return h("zlib")},_context:function(){return h("context")},_nodescript:function(){return h("nodescript")},_httpparser:function(){return h("httpparser")},_dataview:function(){return h("dataview")},_signal:function(){return h("signal")},_fsevent:function(){return h("fsevent")},_tlswrap:function(){return h("tlswrap")}}}function
|
|
5
|
-
list should be an Array.`),a.length===0)return new w(0);if(a.length===1)return a[0];if(typeof f!="number")for(P=f=0;P<a.length;P++)f+=a[P].length;for(var y=new w(f),A=0,P=0;P<a.length;P++){var k=a[P];k.copy(y,A),A+=k.length}return y},w.prototype.write=function(a,f,y,A){isFinite(f)?isFinite(y)||(A=y,y=void 0):(G=A,A=f,f=y,y=G),f=Number(f)||0;var P,k,N,W,G=this.length-f;switch((!y||G<(y=Number(y)))&&(y=G),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,re,ie,X){ie=Number(ie)||0;var Y=ye.length-ie;(!X||Y<(X=Number(X)))&&(X=Y),T((Y=re.length)%2==0,"Invalid hex string"),Y/2<X&&(X=Y/2);for(var We=0;We<X;We++){var Wr=parseInt(re.substr(2*We,2),16);T(!isNaN(Wr),"Invalid hex string"),ye[ie+We]=Wr}return w._charsWritten=2*We,We}(this,a,f,y);break;case"utf8":case"utf-8":k=this,N=f,W=y,P=w._charsWritten=Dt(Ee(a),k,N,W);break;case"ascii":case"binary":P=v(this,a,f,y);break;case"base64":k=this,N=f,W=y,P=w._charsWritten=Dt(zr(a),k,N,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=I(this,a,f,y);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(a,f,y){var A,P,k,N,W=this;if(a=String(a||"utf8").toLowerCase(),f=Number(f)||0,(y=y!==void 0?Number(y):W.length)===f)return"";switch(a){case"hex":A=function(G,ye,re){var ie=G.length;(!ye||ye<0)&&(ye=0),(!re||re<0||ie<re)&&(re=ie);for(var X="",Y=ye;Y<re;Y++)X+=z(G[Y]);return X}(W,f,y);break;case"utf8":case"utf-8":A=function(G,ye,re){var ie="",X="";re=Math.min(G.length,re);for(var Y=ye;Y<re;Y++)G[Y]<=127?(ie+=qr(X)+String.fromCharCode(G[Y]),X=""):X+="%"+G[Y].toString(16);return ie+qr(X)}(W,f,y);break;case"ascii":case"binary":A=S(W,f,y);break;case"base64":P=W,N=y,A=(k=f)===0&&N===P.length?g.fromByteArray(P):g.fromByteArray(P.slice(k,N));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,ye,re){for(var ie=G.slice(ye,re),X="",Y=0;Y<ie.length;Y+=2)X+=String.fromCharCode(ie[Y]+256*ie[Y+1]);return X}(W,f,y);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(a,f,y,A){if(f=f||0,(A=A||A===0?A:this.length)!==(y=y||0)&&a.length!==0&&this.length!==0){T(y<=A,"sourceEnd < sourceStart"),T(0<=f&&f<a.length,"targetStart out of bounds"),T(0<=y&&y<this.length,"sourceStart out of bounds"),T(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=a.length-f<A-y?a.length-f+y:A)-y;if(P<100||!w._useTypedArrays)for(var k=0;k<P;k++)a[k+f]=this[k+y];else a._set(this.subarray(y,y+P),f)}},w.prototype.slice=function(a,f){var y=this.length;if(a=q(a,y,0),f=q(f,y,y),w._useTypedArrays)return w._augment(this.subarray(a,f));for(var A=f-a,P=new w(A,void 0,!0),k=0;k<A;k++)P[k]=this[k+a];return P},w.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},w.prototype.set=function(a,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,f)},w.prototype.readUInt8=function(a,f){if(f||(T(a!=null,"missing offset"),T(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return this[a]},w.prototype.readUInt16LE=function(a,f){return D(this,a,!0,f)},w.prototype.readUInt16BE=function(a,f){return D(this,a,!1,f)},w.prototype.readUInt32LE=function(a,f){return R(this,a,!0,f)},w.prototype.readUInt32BE=function(a,f){return R(this,a,!1,f)},w.prototype.readInt8=function(a,f){if(f||(T(a!=null,"missing offset"),T(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return 128&this[a]?-1*(255-this[a]+1):this[a]},w.prototype.readInt16LE=function(a,f){return b(this,a,!0,f)},w.prototype.readInt16BE=function(a,f){return b(this,a,!1,f)},w.prototype.readInt32LE=function(a,f){return E(this,a,!0,f)},w.prototype.readInt32BE=function(a,f){return E(this,a,!1,f)},w.prototype.readFloatLE=function(a,f){return d(this,a,!0,f)},w.prototype.readFloatBE=function(a,f){return d(this,a,!1,f)},w.prototype.readDoubleLE=function(a,f){return h(this,a,!0,f)},w.prototype.readDoubleBE=function(a,f){return h(this,a,!1,f)},w.prototype.writeUInt8=function(a,f,y){y||(T(a!=null,"missing value"),T(f!=null,"missing offset"),T(f<this.length,"trying to write beyond buffer length"),$n(a,255)),f>=this.length||(this[f]=a)},w.prototype.writeUInt16LE=function(a,f,y){l(this,a,f,!0,y)},w.prototype.writeUInt16BE=function(a,f,y){l(this,a,f,!1,y)},w.prototype.writeUInt32LE=function(a,f,y){O(this,a,f,!0,y)},w.prototype.writeUInt32BE=function(a,f,y){O(this,a,f,!1,y)},w.prototype.writeInt8=function(a,f,y){y||(T(a!=null,"missing value"),T(f!=null,"missing offset"),T(f<this.length,"Trying to write beyond buffer length"),zn(a,127,-128)),f>=this.length||(0<=a?this.writeUInt8(a,f,y):this.writeUInt8(255+a+1,f,y))},w.prototype.writeInt16LE=function(a,f,y){C(this,a,f,!0,y)},w.prototype.writeInt16BE=function(a,f,y){C(this,a,f,!1,y)},w.prototype.writeInt32LE=function(a,f,y){M(this,a,f,!0,y)},w.prototype.writeInt32BE=function(a,f,y){M(this,a,f,!1,y)},w.prototype.writeFloatLE=function(a,f,y){B(this,a,f,!0,y)},w.prototype.writeFloatBE=function(a,f,y){B(this,a,f,!1,y)},w.prototype.writeDoubleLE=function(a,f,y){j(this,a,f,!0,y)},w.prototype.writeDoubleBE=function(a,f,y){j(this,a,f,!1,y)},w.prototype.fill=function(a,f,y){if(f=f||0,y=y||this.length,T(typeof(a=typeof(a=a||0)=="string"?a.charCodeAt(0):a)=="number"&&!isNaN(a),"value is not a number"),T(f<=y,"end < start"),y!==f&&this.length!==0){T(0<=f&&f<this.length,"start out of bounds"),T(0<=y&&y<=this.length,"end out of bounds");for(var A=f;A<y;A++)this[A]=a}},w.prototype.inspect=function(){for(var a=[],f=this.length,y=0;y<f;y++)if(a[y]=z(this[y]),y===e.INSPECT_MAX_BYTES){a[y+1]="...";break}return"<Buffer "+a.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var a=new Uint8Array(this.length),f=0,y=a.length;f<y;f+=1)a[f]=this[f];return a.buffer};var F=w.prototype;function q(a,f,y){return typeof a!="number"?y:f<=(a=~~a)?f:0<=a||0<=(a+=f)?a:0}function te(a){return(a=~~Math.ceil(+a))<0?0:a}function H(a){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(a)}function z(a){return a<16?"0"+a.toString(16):a.toString(16)}function Ee(a){for(var f=[],y=0;y<a.length;y++){var A=a.charCodeAt(y);if(A<=127)f.push(a.charCodeAt(y));else for(var P=y,k=(55296<=A&&A<=57343&&y++,encodeURIComponent(a.slice(P,y+1)).substr(1).split("%")),N=0;N<k.length;N++)f.push(parseInt(k[N],16))}return f}function zr(a){return g.toByteArray(a)}function Dt(a,f,y,A){for(var P=0;P<A&&!(P+y>=f.length||P>=a.length);P++)f[P+y]=a[P];return P}function qr(a){try{return decodeURIComponent(a)}catch{return String.fromCharCode(65533)}}function $n(a,f){T(typeof a=="number","cannot write a non-number as a number"),T(0<=a,"specified a negative value for writing an unsigned value"),T(a<=f,"value is larger than maximum value for type"),T(Math.floor(a)===a,"value has a fractional component")}function zn(a,f,y){T(typeof a=="number","cannot write a non-number as a number"),T(a<=f,"value larger than maximum allowed value"),T(y<=a,"value smaller than minimum allowed value"),T(Math.floor(a)===a,"value has a fractional component")}function Hr(a,f,y){T(typeof a=="number","cannot write a non-number as a number"),T(a<=f,"value larger than maximum allowed value"),T(y<=a,"value smaller than minimum allowed value")}function T(a,f){if(!a)throw new Error(f||"Failed assertion")}w._augment=function(a){return a._isBuffer=!0,a._get=a.get,a._set=a.set,a.get=F.get,a.set=F.set,a.write=F.write,a.toString=F.toString,a.toLocaleString=F.toString,a.toJSON=F.toJSON,a.copy=F.copy,a.slice=F.slice,a.readUInt8=F.readUInt8,a.readUInt16LE=F.readUInt16LE,a.readUInt16BE=F.readUInt16BE,a.readUInt32LE=F.readUInt32LE,a.readUInt32BE=F.readUInt32BE,a.readInt8=F.readInt8,a.readInt16LE=F.readInt16LE,a.readInt16BE=F.readInt16BE,a.readInt32LE=F.readInt32LE,a.readInt32BE=F.readInt32BE,a.readFloatLE=F.readFloatLE,a.readFloatBE=F.readFloatBE,a.readDoubleLE=F.readDoubleLE,a.readDoubleBE=F.readDoubleBE,a.writeUInt8=F.writeUInt8,a.writeUInt16LE=F.writeUInt16LE,a.writeUInt16BE=F.writeUInt16BE,a.writeUInt32LE=F.writeUInt32LE,a.writeUInt32BE=F.writeUInt32BE,a.writeInt8=F.writeInt8,a.writeInt16LE=F.writeInt16LE,a.writeInt16BE=F.writeInt16BE,a.writeInt32LE=F.writeInt32LE,a.writeInt32BE=F.writeInt32BE,a.writeFloatLE=F.writeFloatLE,a.writeFloatBE=F.writeFloatBE,a.writeDoubleLE=F.writeDoubleLE,a.writeDoubleBE=F.writeDoubleBE,a.fill=F.fill,a.inspect=F.inspect,a.toArrayBuffer=F.toArrayBuffer,a}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(r,t,e){(function(n,i,g,s,c,p,u,m,x){var g=r("buffer").Buffer,_=4,w=new g(_);w.fill(0),t.exports={hash:function(v,I,S,D){for(var R=I(function(l,O){l.length%_!=0&&(C=l.length+(_-l.length%_),l=g.concat([l,w],C));for(var C,M=[],B=O?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=_)M.push(B.call(l,j));return M}(v=g.isBuffer(v)?v:new g(v),D),8*v.length),I=D,b=new g(S),E=I?b.writeInt32BE:b.writeInt32LE,d=0;d<R.length;d++)E.call(b,R[d],4*d,!0);return b}}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(r,t,e){(function(n,i,g,s,c,p,u,m,x){var g=r("buffer").Buffer,_=r("./sha"),w=r("./sha256"),v=r("./rng"),I={sha1:_,sha256:w,md5:r("./md5")},S=64,D=new g(S);function R(l,O){var C=I[l=l||"sha1"],M=[];return C||b("algorithm:",l,"is not yet supported"),{update:function(B){return g.isBuffer(B)||(B=new g(B)),M.push(B),B.length,this},digest:function(B){var j=g.concat(M),j=O?function(F,q,te){g.isBuffer(q)||(q=new g(q)),g.isBuffer(te)||(te=new g(te)),q.length>S?q=F(q):q.length<S&&(q=g.concat([q,D],S));for(var H=new g(S),z=new g(S),Ee=0;Ee<S;Ee++)H[Ee]=54^q[Ee],z[Ee]=92^q[Ee];return te=F(g.concat([H,te])),F(g.concat([z,te]))}(C,O,j):C(j);return M=null,B?j.toString(B):j}}}function b(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
-
`))}D.fill(0),e.createHash=function(l){return R(l)},e.createHmac=R,e.randomBytes=function(l,O){if(!O||!O.call)return new g(v(l));try{O.call(this,void 0,new g(v(l)))}catch(C){O(C)}};var E,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(E in d)h(d[E],E)}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){var g=r("./helpers");function _(b,E){b[E>>5]|=128<<E%32,b[14+(E+64>>>9<<4)]=E;for(var d=1732584193,h=-271733879,l=-1732584194,O=271733878,C=0;C<b.length;C+=16){var M=d,B=h,j=l,F=O,d=v(d,h,l,O,b[C+0],7,-680876936),O=v(O,d,h,l,b[C+1],12,-389564586),l=v(l,O,d,h,b[C+2],17,606105819),h=v(h,l,O,d,b[C+3],22,-1044525330);d=v(d,h,l,O,b[C+4],7,-176418897),O=v(O,d,h,l,b[C+5],12,1200080426),l=v(l,O,d,h,b[C+6],17,-1473231341),h=v(h,l,O,d,b[C+7],22,-45705983),d=v(d,h,l,O,b[C+8],7,1770035416),O=v(O,d,h,l,b[C+9],12,-1958414417),l=v(l,O,d,h,b[C+10],17,-42063),h=v(h,l,O,d,b[C+11],22,-1990404162),d=v(d,h,l,O,b[C+12],7,1804603682),O=v(O,d,h,l,b[C+13],12,-40341101),l=v(l,O,d,h,b[C+14],17,-1502002290),d=I(d,h=v(h,l,O,d,b[C+15],22,1236535329),l,O,b[C+1],5,-165796510),O=I(O,d,h,l,b[C+6],9,-1069501632),l=I(l,O,d,h,b[C+11],14,643717713),h=I(h,l,O,d,b[C+0],20,-373897302),d=I(d,h,l,O,b[C+5],5,-701558691),O=I(O,d,h,l,b[C+10],9,38016083),l=I(l,O,d,h,b[C+15],14,-660478335),h=I(h,l,O,d,b[C+4],20,-405537848),d=I(d,h,l,O,b[C+9],5,568446438),O=I(O,d,h,l,b[C+14],9,-1019803690),l=I(l,O,d,h,b[C+3],14,-187363961),h=I(h,l,O,d,b[C+8],20,1163531501),d=I(d,h,l,O,b[C+13],5,-1444681467),O=I(O,d,h,l,b[C+2],9,-51403784),l=I(l,O,d,h,b[C+7],14,1735328473),d=S(d,h=I(h,l,O,d,b[C+12],20,-1926607734),l,O,b[C+5],4,-378558),O=S(O,d,h,l,b[C+8],11,-2022574463),l=S(l,O,d,h,b[C+11],16,1839030562),h=S(h,l,O,d,b[C+14],23,-35309556),d=S(d,h,l,O,b[C+1],4,-1530992060),O=S(O,d,h,l,b[C+4],11,1272893353),l=S(l,O,d,h,b[C+7],16,-155497632),h=S(h,l,O,d,b[C+10],23,-1094730640),d=S(d,h,l,O,b[C+13],4,681279174),O=S(O,d,h,l,b[C+0],11,-358537222),l=S(l,O,d,h,b[C+3],16,-722521979),h=S(h,l,O,d,b[C+6],23,76029189),d=S(d,h,l,O,b[C+9],4,-640364487),O=S(O,d,h,l,b[C+12],11,-421815835),l=S(l,O,d,h,b[C+15],16,530742520),d=D(d,h=S(h,l,O,d,b[C+2],23,-995338651),l,O,b[C+0],6,-198630844),O=D(O,d,h,l,b[C+7],10,1126891415),l=D(l,O,d,h,b[C+14],15,-1416354905),h=D(h,l,O,d,b[C+5],21,-57434055),d=D(d,h,l,O,b[C+12],6,1700485571),O=D(O,d,h,l,b[C+3],10,-1894986606),l=D(l,O,d,h,b[C+10],15,-1051523),h=D(h,l,O,d,b[C+1],21,-2054922799),d=D(d,h,l,O,b[C+8],6,1873313359),O=D(O,d,h,l,b[C+15],10,-30611744),l=D(l,O,d,h,b[C+6],15,-1560198380),h=D(h,l,O,d,b[C+13],21,1309151649),d=D(d,h,l,O,b[C+4],6,-145523070),O=D(O,d,h,l,b[C+11],10,-1120210379),l=D(l,O,d,h,b[C+2],15,718787259),h=D(h,l,O,d,b[C+9],21,-343485551),d=R(d,M),h=R(h,B),l=R(l,j),O=R(O,F)}return Array(d,h,l,O)}function w(b,E,d,h,l,O){return R((E=R(R(E,b),R(h,O)))<<l|E>>>32-l,d)}function v(b,E,d,h,l,O,C){return w(E&d|~E&h,b,E,l,O,C)}function I(b,E,d,h,l,O,C){return w(E&h|d&~h,b,E,l,O,C)}function S(b,E,d,h,l,O,C){return w(E^d^h,b,E,l,O,C)}function D(b,E,d,h,l,O,C){return w(d^(E|~h),b,E,l,O,C)}function R(b,E){var d=(65535&b)+(65535&E);return(b>>16)+(E>>16)+(d>>16)<<16|65535&d}t.exports=function(b){return g.hash(b,_,16)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){var g;t.exports=g||function(_){for(var w,v=new Array(_),I=0;I<_;I++)!(3&I)&&(w=4294967296*Math.random()),v[I]=w>>>((3&I)<<3)&255;return v}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){var g=r("./helpers");function _(I,S){I[S>>5]|=128<<24-S%32,I[15+(S+64>>9<<4)]=S;for(var D,R,b,E=Array(80),d=1732584193,h=-271733879,l=-1732584194,O=271733878,C=-1009589776,M=0;M<I.length;M+=16){for(var B=d,j=h,F=l,q=O,te=C,H=0;H<80;H++){E[H]=H<16?I[M+H]:v(E[H-3]^E[H-8]^E[H-14]^E[H-16],1);var z=w(w(v(d,5),(z=h,R=l,b=O,(D=H)<20?z&R|~z&b:!(D<40)&&D<60?z&R|z&b|R&b:z^R^b)),w(w(C,E[H]),(D=H)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),C=O,O=l,l=v(h,30),h=d,d=z}d=w(d,B),h=w(h,j),l=w(l,F),O=w(O,q),C=w(C,te)}return Array(d,h,l,O,C)}function w(I,S){var D=(65535&I)+(65535&S);return(I>>16)+(S>>16)+(D>>16)<<16|65535&D}function v(I,S){return I<<S|I>>>32-S}t.exports=function(I){return g.hash(I,_,20,!0)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){function g(S,D){var R=(65535&S)+(65535&D);return(S>>16)+(D>>16)+(R>>16)<<16|65535&R}function _(S,D){var R,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),E=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);S[D>>5]|=128<<24-D%32,S[15+(D+64>>9<<4)]=D;for(var h,l,O=0;O<S.length;O+=16){for(var C=E[0],M=E[1],B=E[2],j=E[3],F=E[4],q=E[5],te=E[6],H=E[7],z=0;z<64;z++)d[z]=z<16?S[z+O]:g(g(g((l=d[z-2],v(l,17)^v(l,19)^I(l,10)),d[z-7]),(l=d[z-15],v(l,7)^v(l,18)^I(l,3))),d[z-16]),R=g(g(g(g(H,v(l=F,6)^v(l,11)^v(l,25)),F&q^~F&te),b[z]),d[z]),h=g(v(h=C,2)^v(h,13)^v(h,22),C&M^C&B^M&B),H=te,te=q,q=F,F=g(j,R),j=B,B=M,M=C,C=g(R,h);E[0]=g(C,E[0]),E[1]=g(M,E[1]),E[2]=g(B,E[2]),E[3]=g(j,E[3]),E[4]=g(F,E[4]),E[5]=g(q,E[5]),E[6]=g(te,E[6]),E[7]=g(H,E[7])}return E}var w=r("./helpers"),v=function(S,D){return S>>>D|S<<32-D},I=function(S,D){return S>>>D};t.exports=function(S){return w.hash(S,_,32,!0)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){e.read=function(g,_,w,v,O){var S,D,R=8*O-v-1,b=(1<<R)-1,E=b>>1,d=-7,h=w?O-1:0,l=w?-1:1,O=g[_+h];for(h+=l,S=O&(1<<-d)-1,O>>=-d,d+=R;0<d;S=256*S+g[_+h],h+=l,d-=8);for(D=S&(1<<-d)-1,S>>=-d,d+=v;0<d;D=256*D+g[_+h],h+=l,d-=8);if(S===0)S=1-E;else{if(S===b)return D?NaN:1/0*(O?-1:1);D+=Math.pow(2,v),S-=E}return(O?-1:1)*D*Math.pow(2,S-v)},e.write=function(g,_,w,v,I,C){var D,R,b=8*C-I-1,E=(1<<b)-1,d=E>>1,h=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:C-1,O=v?1:-1,C=_<0||_===0&&1/_<0?1:0;for(_=Math.abs(_),isNaN(_)||_===1/0?(R=isNaN(_)?1:0,D=E):(D=Math.floor(Math.log(_)/Math.LN2),_*(v=Math.pow(2,-D))<1&&(D--,v*=2),2<=(_+=1<=D+d?h/v:h*Math.pow(2,1-d))*v&&(D++,v/=2),E<=D+d?(R=0,D=E):1<=D+d?(R=(_*v-1)*Math.pow(2,I),D+=d):(R=_*Math.pow(2,d-1)*Math.pow(2,I),D=0));8<=I;g[w+l]=255&R,l+=O,R/=256,I-=8);for(D=D<<I|R,b+=I;0<b;g[w+l]=255&D,l+=O,D/=256,b-=8);g[w+l-O]|=128*C}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(r,t,e){(function(n,i,o,s,c,p,u,m,x){var g,_,w;function v(){}(n=t.exports={}).nextTick=(_=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,_?function(I){return window.setImmediate(I)}:w?(g=[],window.addEventListener("message",function(I){var S=I.source;S!==window&&S!==null||I.data!=="process-tick"||(I.stopPropagation(),0<g.length&&g.shift()())},!0),function(I){g.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.binding=function(I){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ze={};Qr(ze,{__addDisposableResource:()=>vo,__assign:()=>yn,__asyncDelegator:()=>fo,__asyncGenerator:()=>uo,__asyncValues:()=>po,__await:()=>tt,__awaiter:()=>io,__classPrivateFieldGet:()=>yo,__classPrivateFieldIn:()=>wo,__classPrivateFieldSet:()=>bo,__createBinding:()=>wn,__decorate:()=>to,__disposeResources:()=>xo,__esDecorate:()=>Qs,__exportStar:()=>so,__extends:()=>Zi,__generator:()=>oo,__importDefault:()=>go,__importStar:()=>mo,__makeTemplateObject:()=>ho,__metadata:()=>ro,__param:()=>no,__propKey:()=>Ys,__read:()=>Er,__rest:()=>eo,__runInitializers:()=>Js,__setFunctionName:()=>Gs,__spread:()=>ao,__spreadArray:()=>lo,__spreadArrays:()=>co,__values:()=>bn,default:()=>ea});function Zi(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Dr(r,t);function e(){this.constructor=r}r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function eo(r,t){var e={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&t.indexOf(n)<0&&(e[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(e[n[i]]=r[n[i]]);return e}function to(r,t,e,n){var i=arguments.length,o=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(r,t,e,n);else for(var c=r.length-1;c>=0;c--)(s=r[c])&&(o=(i<3?s(o):i>3?s(t,e,o):s(t,e))||o);return i>3&&o&&Object.defineProperty(t,e,o),o}function no(r,t){return function(e,n){t(e,n,r)}}function Qs(r,t,e,n,i,o){function s(S){if(S!==void 0&&typeof S!="function")throw new TypeError("Function expected");return S}for(var c=n.kind,p=c==="getter"?"get":c==="setter"?"set":"value",u=!t&&r?n.static?r:r.prototype:null,m=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),x,g=!1,_=e.length-1;_>=0;_--){var w={};for(var v in n)w[v]=v==="access"?{}:n[v];for(var v in n.access)w.access[v]=n.access[v];w.addInitializer=function(S){if(g)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(S||null))};var I=(0,e[_])(c==="accessor"?{get:m.get,set:m.set}:m[p],w);if(c==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(x=s(I.get))&&(m.get=x),(x=s(I.set))&&(m.set=x),(x=s(I.init))&&i.unshift(x)}else(x=s(I))&&(c==="field"?i.unshift(x):m[p]=x)}u&&Object.defineProperty(u,n.name,m),g=!0}function Js(r,t,e){for(var n=arguments.length>2,i=0;i<t.length;i++)e=n?t[i].call(r,e):t[i].call(r);return n?e:void 0}function Ys(r){return typeof r=="symbol"?r:"".concat(r)}function Gs(r,t,e){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(r,"name",{configurable:!0,value:e?"".concat(e," ",t):t})}function ro(r,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,t)}function io(r,t,e,n){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(m){try{u(n.next(m))}catch(x){s(x)}}function p(m){try{u(n.throw(m))}catch(x){s(x)}}function u(m){m.done?o(m.value):i(m.value).then(c,p)}u((n=n.apply(r,t||[])).next())})}function oo(r,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function c(u){return function(m){return p([u,m])}}function p(u){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(e=0)),e;)try{if(n=1,i&&(o=u[0]&2?i.return:u[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,u[1])).done)return o;switch(i=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,i=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=t.call(r,e)}catch(m){u=[6,m],i=0}finally{n=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function so(r,t){for(var e in r)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&wn(t,r,e)}function bn(r){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&r[t],n=0;if(e)return e.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Er(r,t){var e=typeof Symbol=="function"&&r[Symbol.iterator];if(!e)return r;var n=e.call(r),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(s)throw s.error}}return o}function ao(){for(var r=[],t=0;t<arguments.length;t++)r=r.concat(Er(arguments[t]));return r}function co(){for(var r=0,t=0,e=arguments.length;t<e;t++)r+=arguments[t].length;for(var n=Array(r),i=0,t=0;t<e;t++)for(var o=arguments[t],s=0,c=o.length;s<c;s++,i++)n[i]=o[s];return n}function lo(r,t,e){if(e||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return r.concat(o||Array.prototype.slice.call(t))}function tt(r){return this instanceof tt?(this.v=r,this):new tt(r)}function uo(r,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(r,t||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(g){n[g]&&(i[g]=function(_){return new Promise(function(w,v){o.push([g,_,w,v])>1||c(g,_)})})}function c(g,_){try{p(n[g](_))}catch(w){x(o[0][3],w)}}function p(g){g.value instanceof tt?Promise.resolve(g.value.v).then(u,m):x(o[0][2],g)}function u(g){c("next",g)}function m(g){c("throw",g)}function x(g,_){g(_),o.shift(),o.length&&c(o[0][0],o[0][1])}}function fo(r){var t,e;return t={},n("next"),n("throw",function(i){throw i}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(i,o){t[i]=r[i]?function(s){return(e=!e)?{value:tt(r[i](s)),done:!1}:o?o(s):s}:o}}function po(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=r[Symbol.asyncIterator],e;return t?t.call(r):(r=typeof bn=="function"?bn(r):r[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(o){e[o]=r[o]&&function(s){return new Promise(function(c,p){s=r[o](s),i(c,p,s.done,s.value)})}}function i(o,s,c,p){Promise.resolve(p).then(function(u){o({value:u,done:c})},s)}}function ho(r,t){return Object.defineProperty?Object.defineProperty(r,"raw",{value:t}):r.raw=t,r}function mo(r){if(r&&r.__esModule)return r;var t={};if(r!=null)for(var e in r)e!=="default"&&Object.prototype.hasOwnProperty.call(r,e)&&wn(t,r,e);return Xs(t,r),t}function go(r){return r&&r.__esModule?r:{default:r}}function yo(r,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?r!==t||!n:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(r):n?n.value:t.get(r)}function bo(r,t,e,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?r!==t||!i:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,e):i?i.value=e:t.set(r,e),e}function wo(r,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof r=="function"?t===r:r.has(t)}function vo(r,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");r.stack.push({value:t,dispose:n,async:e})}else e&&r.stack.push({async:!0});return t}function xo(r){function t(n){r.error=r.hasError?new Zs(n,r.error,"An error was suppressed during disposal."):n,r.hasError=!0}function e(){for(;r.stack.length;){var n=r.stack.pop();try{var i=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(i).then(e,function(o){return t(o),e()})}catch(o){t(o)}}if(r.hasError)throw r.error}return e()}var Dr,yn,wn,Xs,Zs,ea,qe=Ko(()=>{Dr=function(r,t){return Dr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])},Dr(r,t)};yn=function(){return yn=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},yn.apply(this,arguments)};wn=Object.create?function(r,t,e,n){n===void 0&&(n=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(r,n,i)}:function(r,t,e,n){n===void 0&&(n=e),r[n]=t[e]};Xs=Object.create?function(r,t){Object.defineProperty(r,"default",{enumerable:!0,value:t})}:function(r,t){r.default=t};Zs=typeof SuppressedError=="function"?SuppressedError:function(r,t,e){var n=new Error(e);return n.name="SuppressedError",n.error=r,n.suppressed=t,n};ea={__extends:Zi,__assign:yn,__rest:eo,__decorate:to,__param:no,__metadata:ro,__awaiter:io,__generator:oo,__createBinding:wn,__exportStar:so,__values:bn,__read:Er,__spread:ao,__spreadArrays:co,__spreadArray:lo,__await:tt,__asyncGenerator:uo,__asyncDelegator:fo,__asyncValues:po,__makeTemplateObject:ho,__importStar:mo,__importDefault:go,__classPrivateFieldGet:yo,__classPrivateFieldSet:bo,__classPrivateFieldIn:wo,__addDisposableResource:vo,__disposeResources:xo}});var Oo=oe(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0})});var _r=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var Io=(qe(),Qe(ze));function Do(r,t,e){try{return r(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}}De.eventHandlerSafeInvoke=Do;function Cr(r,t,e){return(0,Io.__awaiter)(this,void 0,void 0,function*(){try{return yield r(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Cr;function ta(r,t,e,n){for(let i of r){let{succeeded:o,error:s}=Do(i,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=ta;function na(r,t,e,n){return(0,Io.__awaiter)(this,void 0,void 0,function*(){if(n?.parallelize===!1)for(let i of r){let{succeeded:o,error:s}=yield Cr(i,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}else{let i=[];for(let o of r)i.push(Cr(o,t,e).then(({succeeded:s,error:c})=>{if(!s&&n?.swallowExceptions!==!0)throw c}));yield Promise.all(i)}})}De.invokeEventHandlersAsync=na});var _o=oe(vn=>{"use strict";Object.defineProperty(vn,"__esModule",{value:!0});vn.TypedEvent=void 0;var ra=(qe(),Qe(ze)),Eo=_r(),Co={swallowExceptions:!1,parallelize:!0},Pr=class{constructor(){this._handlers=[]}attach(t){this._handlers.push(t)}detach(t){this.tryRemoveHandler(t)}invoke(t,e,n=Co){(0,Eo.invokeEventHandlers)(this._handlers,t,e,n)}invokeAsync(t,e,n=Co){return(0,ra.__awaiter)(this,void 0,void 0,function*(){yield(0,Eo.invokeEventHandlersAsync)(this._handlers,t,e,n)})}tryRemoveHandler(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}};vn.TypedEvent=Pr});var Rr=oe(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});var ia=(qe(),Qe(ze));(0,ia.__exportStar)(_o(),Ar)});var Po=oe(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.FinalizationRegistryMissingError=void 0;var Tr=class extends Error{};xn.FinalizationRegistryMissingError=Tr});var Fr=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.WeakHandlerHolder=void 0;var oa=Po(),kr=class{constructor(t){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(t)}catch(e){throw e.name==="FinalizationRegistry"?new oa.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(t,e){let n=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:t,handlerRef:n},n),this._refs.push(n),n}releaseWeakHandler(t){let n=this._refs.find(i=>i?.deref()===t)||new WeakRef(t);return this._finalizationRegistry.unregister(n),n}unregisterRef(t){this._finalizationRegistry.unregister(t)}};Sn.WeakHandlerHolder=kr});var Ao=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.WeakEvent=void 0;var Br=(qe(),Qe(ze)),sa=Rr(),aa=Fr(),Mr=_r(),ca={swallowExceptions:!1,parallelize:!0},jr=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new sa.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new aa.WeakHandlerHolder(t=>{this.onHandlerFinalizer(t)})}invoke(t,e,n){for(let i of this._handlers){let o=i?.deref();if(o){let{succeeded:s,error:c}=(0,Mr.eventHandlerSafeInvoke)(o,t,e);if(!s&&n?.swallowExceptions!==!0)throw c}else this.releaseHandler(i)}}invokeAsync(t,e,n=ca){return(0,Br.__awaiter)(this,void 0,void 0,function*(){n?.parallelize===!1?yield this.sequentialInvokeAsync(t,e,n):yield this.parallelInvokeAsync(t,e,n)})}sequentialInvokeAsync(t,e,n){return(0,Br.__awaiter)(this,void 0,void 0,function*(){for(let i of this._handlers){let o=i?.deref();if(o){let{succeeded:s,error:c}=yield(0,Mr.eventHandlerSafeInvokeAsync)(o,t,e);if(!s&&n.swallowExceptions!==!0)throw c}else this.releaseHandler(i)}})}parallelInvokeAsync(t,e,n){return(0,Br.__awaiter)(this,void 0,void 0,function*(){let i=[];for(let o of this._handlers){let s=o?.deref();s?i.push((0,Mr.eventHandlerSafeInvokeAsync)(s,t,e).then(({succeeded:c,error:p})=>{if(!c&&n.swallowExceptions!==!0)throw p})):this.releaseHandler(o)}yield Promise.all(i)})}attach(t){this._handlers.push(this._refHolder.getWeakHandler(this,t))}detach(t){let e=this._refHolder.releaseWeakHandler(t);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(t){this.tryRemoveHandlerRef(t?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,t,{swallowExceptions:!0})}tryRemoveHandlerRef(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}releaseHandler(t){this._refHolder.unregisterRef(t),this.tryRemoveHandlerRef(t)}};On.WeakEvent=jr});var To=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});var Ro=(qe(),Qe(ze));(0,Ro.__exportStar)(Fr(),In);(0,Ro.__exportStar)(Ao(),In)});var ko=oe(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});var Lr=(qe(),Qe(ze));(0,Lr.__exportStar)(Oo(),St);(0,Lr.__exportStar)(Rr(),St);(0,Lr.__exportStar)(To(),St)});var $r={};Qr($r,{Client:()=>He,ClientDescriptor:()=>Kn,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>Xe,ServerSync:()=>rt,Storage:()=>He,StorageDescriptor:()=>Kn,collection:()=>ki,createDefaultMigration:()=>mr,createMigration:()=>gr,migrate:()=>Wt,schema:()=>Fi});var ui=it(Pt(),1),Ft=4,ct=36;function ai(r){return r.toString(ct).padStart(Ft,"0")}function Jo(r){return r.toString().padStart(6,"0")}var At=class{constructor(){this.latest={time:Date.now(),counter:0,node:Yo()};this.zeroCounter=0;this.now=t=>(this.latest=li(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=li(this.latest),Jo(t)+Xo(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Ft);this.latest=Go(this.latest,fi(e))};this.get=(t,e)=>ai(t)+ci(e);this.zero=t=>ai(t)+ci({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=Xn}},Rt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Tt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Jn=4,Yn=7,kt=60*1e3,at=9;function Yo(){return ui.default.slug().padStart(Yn,"0").slice(0,Yn)}function ci(r){let t=new Date(r.time).getTime().toString(ct).padStart(at,"0"),e=r.counter.toString(ct).padStart(Jn,"0"),n=r.node.padStart(Yn,"0");return`${t}${e}${n}`}function li(r){let t=Date.now(),e=Math.max(r.time,t),n=r.time===e?r.counter+1:0;if(e-t>kt)throw new Rt(e,t,kt);if(n>65535)throw new Tt;return{time:e,counter:n,node:r.node}}function Go(r,t){let e=Date.now(),n=Math.max(e,Math.max(r.time,t.time)),i=Math.max(r.counter,t.counter),o;if(r.time===n&&t.time===n?o=i+1:r.time===n?o=r.counter+1:t.time===n?o=t.counter+1:o=0,n-e>kt)throw new Rt(n,e,kt);if(o>65535)throw new Tt;return{time:n,counter:o,node:r.node}}function fi(r){let t=r.slice(0,at),e=r.slice(at,at+Jn),n=r.slice(at+Jn),i=parseInt(t,ct),o=parseInt(e,ct);if(isNaN(i)||isNaN(o))throw new Error("invalid clock format");return{time:i,counter:o,node:n}}function Xo(r){let t=new Date(r.time).toISOString(),e=r.counter.toString(16).toUpperCase().padStart(4,"0"),n=r.node.padStart(16,"0");return`${t}-${e}-${n}`}function di(r){return parseInt(r.slice(0,Ft),36)}function Gn(r,t){return di(r)-di(t)}function Xn(r){return fi(r.slice(Ft)).time}function be(r){return r&&r["@@type"]==="file"}function Bt(r){return{"@@type":"file",id:r}}var Mt,Zo=new Uint8Array(16);function Zn(){if(!Mt&&(Mt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Mt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Mt(Zo)}var pi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function es(r){return typeof r=="string"&&pi.test(r)}var hi=es;var ee=[];for(jt=0;jt<256;++jt)ee.push((jt+256).toString(16).substr(1));var jt;function ts(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[r[t+0]]+ee[r[t+1]]+ee[r[t+2]]+ee[r[t+3]]+"-"+ee[r[t+4]]+ee[r[t+5]]+"-"+ee[r[t+6]]+ee[r[t+7]]+"-"+ee[r[t+8]]+ee[r[t+9]]+"-"+ee[r[t+10]]+ee[r[t+11]]+ee[r[t+12]]+ee[r[t+13]]+ee[r[t+14]]+ee[r[t+15]]).toLowerCase();if(!hi(e))throw TypeError("Stringified UUID is invalid");return e}var mi=ts;function ns(r,t,e){r=r||{};var n=r.random||(r.rng||Zn)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=n[i];return t}return mi(n)}var lt=ns;function Q(r){return xe(r)||be(r)}function Je(r,t){return r===t?!0:!(!Q(r)||!Q(t)||r["@@type"]!==t["@@type"]||r.id!==t.id)}var wi=it(bi(),1);function rs(r,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function dt(r){return JSON.stringify(r,rs)}function ae(r,t=!0){if(U(r)||Array.isArray(r)){let e=pe(r),n;if(Array.isArray(r))n=r.map(i=>ae(i,t));else{n={};for(let[i,o]of Object.entries(r))n[i]=ae(o,t)}return t&&e&&K(n,e),n}return r}function Re(r){return(0,wi.default)(r)}function U(r){return r&&typeof r=="object"}function vi(r){for(var t=[],e=[r],n=0;e.length;){var i=e.pop();if(typeof i=="boolean")n+=4;else if(typeof i=="string")n+=i.length*2;else if(typeof i=="number")n+=8;else if(typeof i=="object"&&t.indexOf(i)===-1){t.push(i);for(var o in i)e.push(i[o])}}return n}function L(r,t="assertion failed"){if(!r)throw new Error(t)}function Lt(r=16){return lt().replace("-","").slice(0,r)}function xi(r,t){for(let e=r.length-1;e>=0;e--)if(t(r[e]))return e;return-1}function Si(r,t){let e;return function(...n){let i=this;clearTimeout(e),e=setTimeout(()=>r.apply(i,n),t)}}var Be="__@@oid_do_not_use",Oe="@@id",is="/",ft=":",tr=new WeakMap;function ne(r){let t=pe(r);return L(!!t,`Object ${JSON.stringify(r)} does not have an OID assigned to it`),t}function pe(r){if(U(r))return tr.get(r)??r[Oe]??r[Be]}function K(r,t){return L(U(r),`Only objects can be assigned OIDs, received ${JSON.stringify(r)}`),nr(r)&&Ut(r),tr.set(r,t),r}function nr(r){return!!pe(r)}function Ut(r){return tr.delete(r),r}function rr(r){return r===Oe||r===Be}function ir(r,t,e){if(nr(r))return ne(r);{let n=Se(t,e);return K(r,n),n}}function Oi(r,t,e){if(nr(r)){let n=ne(r);if(Ce(n,t))return ne(r);{let i=Se(t,e);return K(r,i),i}}else{let n=Se(t,e);return K(r,n),n}}var er={".":"˙","/":"&slash;",":":":"};function Ii(r){return r.replace(/[/]/g,er["/"]).replace(/[:]/g,er[":"]).replace(/[.]/g,er["."])}function Di(r){return r.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(r,t,e){let n=Ii(r)+is+Ii(t);return e&&(n+=ft+e),n}function Se(r,t=cs){let{collection:e,id:n}=me(r);return Z(e,n,t())}function me(r){let[t,e]=r.split(ft),[n,i,...o]=t.split("/");o.length&&(i+="/"+o.join("/"));let s;return i.includes(".")?s=i.slice(0,i.indexOf(".")):s=i,{collection:Di(n),id:Di(s),subId:e}}function Ye(r,t){let e=ne(r);if(Array.isArray(r)){let n;for(let i=0;i<r.length;i++)n=r[i],U(n)&&!Q(n)&&(Oi(n,e,t),Ye(n,t))}else if(U(r)&&!Q(r))for(let n of Object.keys(r))U(r[n])&&!Q(r[n])&&(Oi(r[n],e,t),Ye(r[n],t))}function os(r){if(U(r))return r[Oe]||r[Be]}function ss(r){return U(r)&&(delete r[Be],delete r[Oe]),r}function as(r){let t=os(r);t&&K(r,t)}function ut(r){if(as(r),ss(r),Array.isArray(r))for(let t=0;t<r.length;t++)ut(r[t]);else if(U(r))for(let t of Object.keys(r))ut(r[t])}function Nt(r){if(Ut(r),Array.isArray(r))for(let t=0;t<r.length;t++)Nt(r[t]);else if(U(r))for(let t of Object.keys(r))Nt(r[t])}function cs(){return lt().slice(0,8)}function he(r){return{"@@type":"ref",id:r}}function Vt(r,t=new Map){if(Array.isArray(r)){let e=ne(r),n=K([],e);for(let i=0;i<r.length;i++){let o=r[i];if(U(o)){if(xe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){n[i]=o;continue}else{let s=ne(o);n[i]=he(s),Vt(o,t)}}else n[i]=o}t.set(e,n)}else if(U(r)&&!Q(r)){let e=ne(r),n=K({},e);for(let i of Object.keys(r)){let o=r[i];if(U(o)){if(xe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))n[i]=o;else{let s=ne(o);n[i]=he(s),Vt(o,t)}}else n[i]=o}t.set(e,n)}else Q(r);return t}function $(r){return r.split(".")[0].split(ft)[0]}function or(r){let t=$(r),e=Se(t,()=>"\uFFFF");return[`${t}${ft}`,e]}function sr(r){let t=$(r);return[`${t}.`,`${t}.\uFFFF`]}function Ce(r,t){return $(r)===$(t)}function ls(r){let{collection:t,id:e,subId:n}=me(r);return Z(t,e,n)}var ds=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function us(r){return r.replaceAll(ds,t=>{let e=t.slice(1,t.length-1);return`"${ls(e)}"`})}function ar(r){return JSON.parse(us(JSON.stringify(r)))}function Ei(r){return!r.includes(ft)}function xe(r){return r&&typeof r=="object"&&r["@@type"]==="ref"}function cr(r){return U(r)&&!Q(r)}function fs(r,t){return r===t?!0:Q(r)&&Q(t)?Je(r,t):!1}function pt(r,t,e,n,i=[],o={}){let s=ne(r);function c(p,u,m){if(!cr(u))fs(u,m)||i.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:u}});else{let x=pe(m),g=pe(u);g&&!Ce(s,g)?(u=ae(u,!1),g=Se(s,n),K(u,g)):o.mergeUnknownObjects?!g&&x?(K(u,x),g=x):g=ir(u,s,n):g=ir(u,s,n),L(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ce(s,g),`Error: value OID ${g} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||g!==x?(Te(u,g,e,n,i),i.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:he(g)}}),x!==void 0&&i.push({oid:x,timestamp:e(),data:{op:"delete"}})):pt(m,u,e,n,i,o)}}if(Array.isArray(r)&&Array.isArray(t)){for(let u=0;u<t.length;u++){let m=t[u],x=r[u];c(u,m,x)}let p=r.length-t.length;if(p>0){for(let u=t.length;u<r.length;u++){let m=r[u],x=pe(m);x&&i.push({oid:x,timestamp:e(),data:{op:"delete"}})}i.push({oid:s,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(r)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(cr(r)&&cr(t)){let p=new Set(Object.keys(r));for(let[u,m]of Object.entries(t)){if(m===void 0&&o.defaultUndefined||(p.delete(u),rr(u)))continue;let x=r[u];c(u,m,x)}if(!o.defaultUndefined)for(let u of p)rr(u)||i.push({oid:s,timestamp:e(),data:{op:"remove",name:u}})}}return i}function Te(r,t,e,n,i=[]){K(r,t),Ye(r,n);let o=Vt(r);for(let s of o.keys()){let c=o.get(s);i.push({oid:s,timestamp:e(),data:{op:"initialize",value:Ut(c)}})}return i}function ht(r){let t={};for(let e of r)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function _i(r){let t={};for(let e of r){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Pi(r){let t={};for(let e of r){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Me(r){return Array.isArray(r)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(r)}. This suggests your data is changing from a list to an object over time. (OID: ${pe(r)})`),!1)}function je(r,t,e){if(r==null&&t.op!=="initialize")return r;let n=r,i,o;function s(c){e&&Q(c)&&e.push(c)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Me(r)&&r.push(t.value);break;case"list-delete":Me(r)&&(s(r[t.index]),r.splice(t.index,t.count));break;case"list-move-by-index":Me(r)&&(o=r.splice(t.from,1),r.splice(t.to,0,o[0]));break;case"list-remove":if(Me(r))do{let c=t.value;t.only==="last"?xe(c)?i=xi(r,p=>p.id===c.id):i=r.lastIndexOf(c):xe(c)?i=r.findIndex(p=>p.id===c.id):i=r.indexOf(c),i!==-1&&(s(r[i]),r.splice(i,1))}while(!t.only&&i!==-1);break;case"list-add":Me(r)&&(r.some(p=>xe(p)&&xe(t.value)?p.id===t.value.id:p===t.value)||r.push(t.value));break;case"list-move-by-ref":Me(r)&&(i=r.findIndex(c=>Je(c,t.value)),o=r.splice(i,1),r.splice(t.index,0,o[0]));break;case"list-insert":if(Me(r)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?r.splice(t.index,0,t.value):r.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(r)?r.forEach(s):U(r)&&Object.values(r||{}).forEach(s);return;case"initialize":return ae(t.value);case"touch":return r;default:throw new Error(`Unsupported patch operation: ${t.op}`)}return r}function Kt(r,t,e=[]){if(Array.isArray(r))for(let n=0;n<r.length;n++){let i=r[n];r[n]=Ci(i,t,e),U(r[n])&&Kt(r[n],t,e)}else if(!be(r)){if(U(r)){L(pe(r),`Object ${JSON.stringify(r)} must have an oid`);for(let n of Object.keys(r))r[n]=Ci(r[n],t,e),U(r[n])&&Kt(r[n],t,e)}}return e}function Ci(r,t,e){if(xe(r)){e.push(r.id);let n=t.get(r.id);return L(!!n,`No value was found in object map for ${r.id}`),K(n,r.id)}else return r}function we(r){return r.type==="any"?!0:r.type==="map"?!1:r.nullable}function _e(r){return r?r.type==="map"||r.type==="array"?!0:r.type==="file"||r.type==="object"?!1:r.default!==void 0:!1}function dr(r){if(!(!r||!_e(r)))return r.type==="file"?we(r)?null:void 0:r.type==="map"?{}:r.type==="array"?we(r)?null:[]:r.type==="object"?we(r)?null:void 0:typeof r.default=="function"?r.default():r.default}function $t(r){return r.type==="map"||r.type==="object"||r.type==="array"||r.type==="file"||r.type==="any"?!1:r.indexed}function Pe(r,t){for(let[e,n]of Object.entries(r.fields)){let i=Ai(n);(i!==void 0&&t[e]===void 0||!we(n)&&t[e]===null)&&(t[e]=i),t[e]&&Le(t[e],n)}return t}function Le(r,t){if(r==null)return r;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(r[e]===void 0){let i=Ai(n);i!==void 0&&(r[e]=i)}Le(r[e],n)}else if(t.type==="array")for(let e of r)Le(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(r))e===Oe||e===Be||Le(n,t.values)}function Ai(r){if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="any"){if(r.default&&typeof r.default=="function")return r.default();if(r.default!==void 0)return JSON.parse(JSON.stringify(r.default))}if(r.type==="array")return[];if(r.type==="map")return{};if(r.type!=="any"&&r.nullable)return null}function ur(r,t){for(let[e,n]of Object.entries(t))e===Oe||e===Be||(r.fields[e]?lr(n,r.fields[e]):delete t[e]);return t}function lr(r,t){if(U(r)&&t.type==="object")for(let[e,n]of Object.entries(r))t.properties[e]?lr(n,t.properties[e]):delete r[e];else if(Array.isArray(r)&&t.type==="array")for(let e of r)lr(e,t.items)}function fr(r){return r.equals!==void 0}function pr(r){return r.gte!==void 0||r.lte!==void 0||r.gt!==void 0||r.lt!==void 0}function ps(r){return!!r.match}function hr(r){return r.startsWith!==void 0}function Ri(r){return!pr(r)&&!fr(r)&&!ps(r)&&!hr(r)&&r.order}function Ti(r,t){for(let[e,n]of Object.entries(t))if(e!==Oe){if(!r[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(n){let i=ke({field:r[e],value:n,fieldPath:[e]});if(i)return i}}}function ke({field:r,value:t,fieldPath:e=[],depth:n,requireDefaults:i}){if(!(n!==void 0&&n<=0)&&!(we(r)&&t===null)){if(t===null&&(i||!_e(r)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ae(e)}`};if(r.type==="object"){if(!U(t))return{type:"invalid-type",fieldPath:e,message:`Expected object${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(r.properties))o!==Oe&&t[o]&&ke({field:s,value:t[o],fieldPath:[...e,o],depth:n!==void 0?n-1:void 0});for(let o of Object.keys(t))if(!r.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ae(e)}`}}else if(r.type==="array"){if(!Array.isArray(t))return t===null&&r.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let o of t)ke({field:r.items,value:o,fieldPath:[...e,"[]"],depth:n!==void 0?n-1:void 0})}else if(r.type==="map"){if(!U(t))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(t))ke({field:r.values,value:s,fieldPath:[...e,o],depth:n!==void 0?n-1:void 0})}else if(r.type==="string"){if(typeof t!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};if(r.options&&!r.options.includes(t))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${r.options.join(", ")} for field ${Ae(e)}, got ${t}`}}else if(r.type==="boolean"){if(typeof t!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else if(r.type==="number"){if(typeof t!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else r.type}}function Ae(r){return r.length===0?"root":r.join(".")}function Ne(r,t){return r.type==="object"?r.properties[t]:r.type==="array"?r.items:r.type==="map"?r.values:r.type==="any"?r:"type"in r?null:r[t]??null}function ki({synthetics:r,indexes:t,...e}){let n={...r,...t};for(let[i,o]of Object.entries(e.fields))$t(o)&&(n[i]={field:i});return{...e,indexes:n}}function Fi(r){return r}var zt="\uFFFFFE",hs="\0",ms="\uFFFFFF";function ce(...r){let t=gs(r);return t.length===1?t[0]:t}function Ve(...r){return r.join(zt)+`${ms}`}function Ue(...r){return r.join(zt)+`${zt}${hs}`}function gs(r){let t=[[]];for(let e of r)if(Array.isArray(e)){let n=[];for(let i of t)for(let o of e)n.push(i.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(zt))))}function ys(r){return!!r.field}function bs(r,t){let e={};for(let[n,i]of Object.entries(r.indexes||{})){let o=i;ys(o)?e[n]=ve(t[o.field]):e[n]=ve(o.compute(t))}return e}function ws(r,t){return Object.entries(r.compounds||{}).reduce((e,[n,i])=>(e[n]=ce(...i.of.map(o=>t[o])),e),{})}function vs(r,t){return Object.entries(r.fields).reduce((e,[n,i])=>($t(i)&&(e[n]=ve(t[n])),e),{})}function qt(r,t){let e={[r.primaryKey]:t[r.primaryKey],...vs(r,t),...bs(r,t)};return Object.assign(e,ws(r,{...t,...e})),e["@@@snapshot"]=t,e}var xs="null";function ve(r){if(r===null)return xs;if(typeof r=="string"||typeof r=="number")return r;if(typeof r=="boolean"||r===null)return`${r}`;if(r===void 0)return"undefined";if(Array.isArray(r))return r.map(ve);throw new Error(`Unsupported index value: ${r}`)}var Bi={version:0,collections:{}};function Wt(r,t,e){let n=typeof t=="function",i=n?Bi:r,o=n?r:t,s=n?t:e,c=Object.keys(o.collections).filter(v=>i.collections[v]&&dt(i.collections[v])!==dt(o.collections[v])),p=Object.keys(i.collections).filter(v=>!o.collections[v]),u=Object.keys(o.collections).filter(v=>!i.collections[v]),m=new Set;for(let v of c){let I=i.collections[v].fields,S=o.collections[v].fields;Object.keys(S).some(D=>!I[D]?.default&&S[D]?.default)&&m.add(v),Object.keys(I).some(D=>!S[D])&&m.add(v)}let x={},g={};for(let v of[...c,...u]){let I=Ht(i.collections[v]),S=Ht(o.collections[v]),D=S.filter(b=>!I.find(E=>E.name===b.name)),R=I.filter(b=>!S.find(E=>E.name===b.name));D.length>0&&(x[v]=D,c.includes(v)&&m.add(v)),R.length>0&&(g[v]=R,c.includes(v)&&m.add(v))}let _=(v,I)=>Pe(o.collections[v],I),w=v=>I=>{let S=o.collections[v];return Pe(S,ur(S,I))};return{version:o.version,migrate:async v=>{let I=[];if(await s({migrate:async(S,D)=>{let R=w(S),b=async E=>{let d=await D(E);return K(d,ne(E)),R(d)};await v.migrate(S,b),I.push(S),m.delete(S)},identity:S=>S,withDefaults:_,info:{changedCollections:c,addedCollections:u,removedCollections:p},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",m);for(let D of m)await v.migrate(D,w(D)),I.push(D);let S=c.filter(D=>!I.includes(D));S.length>0&&console.error(`Unmigrated changed collections from version ${i.version} to version ${o.version}:`,S)}},removedCollections:p,addedIndexes:x,removedIndexes:g,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:u,oldCollections:Object.keys(i.collections),oldSchema:i,newSchema:o}}function Ht(r){return r?[...Object.keys(r.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(r.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(r.compounds||{}).map(t=>({name:t,multiEntry:r.compounds[t].of.some(e=>(r.fields[e]||r.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function mr(r,t){return Wt(t?r:{version:0,collections:{}},t||r,async({migrate:n,info:i})=>{if((t||r).version!==1)for(let o of i.changedCollections)await n(o,s=>s)})}function gr(r,t,e){let n=typeof t=="function"||t===void 0,i=n?Bi:r,o=n?r:t,s=n?t:e;L(i,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:c,addedCollections:p,removedCollections:u,addedIndexes:m,removedIndexes:x,autoMigratedCollections:g,autoMigration:_}=Ss(i,o);return{version:o.version,migrate:async w=>{let v=[];if(await s?.({migrate:async(S,D)=>{let R=_(S),b=async E=>{let d=await D(E);K(d,ne(E));let h=R(d),l=Ti(o.collections[S].fields,h);return h};await w.migrate(S,b),v.push(S),g.delete(S)},info:{changedCollections:c,addedCollections:p,removedCollections:u},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",g);for(let D of g)await w.migrate(D,_(D)),v.push(D);for(let D of u)await w.deleteCollection(D);let S=c.filter(D=>!v.includes(D));S.length>0&&console.error(`Unmigrated changed collections from version ${i.version} to version ${o.version}:`,S)}},removedCollections:u,addedIndexes:m,removedIndexes:x,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:p,oldCollections:Object.keys(i.collections),oldSchema:i,newSchema:o}}function Ss(r,t){let e=Object.keys(t.collections).filter(m=>r.collections[m]&&dt(r.collections[m])!==dt(t.collections[m])),n=Object.keys(r.collections).filter(m=>!t.collections[m]),i=Object.keys(t.collections).filter(m=>!r.collections[m]),o=new Set;for(let m of e){let x=r.collections[m].fields,g=t.collections[m].fields;Object.keys(g).some(_=>!_e(x[_])&&_e(g[_]))&&o.add(m),Object.keys(x).some(_=>!g[_])&&o.add(m)}let s={},c={};for(let m of[...e,...i]){let x=Ht(r.collections[m]),g=Ht(t.collections[m]),_=g.filter(v=>!x.find(I=>I.name===v.name)),w=x.filter(v=>!g.find(I=>I.name===v.name));_.length>0&&(s[m]=_,e.includes(m)&&o.add(m)),w.length>0&&(c[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:i,removedCollections:n,addedIndexes:s,removedIndexes:c,autoMigratedCollections:o,withDefaults:(m,x)=>Pe(t.collections[m],x),autoMigration:m=>x=>{let g=t.collections[m];return Pe(g,ur(g,x))}}}var Qt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!U(t)||Q(t);this.createDiff=(t,e,n={})=>pt(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Te(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let i=Se(t,this.createSubId);return[...Te(n,i,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:he(i),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=Se(t,this.createSubId);return[...Te(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:he(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:he(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let i=Se(t,this.createSubId);return[...Te(n,i,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:he(i),index:e}}]}};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var V=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.disposed=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=Lt(),i=this.subscribers[t];return i||(i=this.subscribers[t]={}),i[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{this._disabled=!0,this.disposed=!0;let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Mi(r,t,e,n){if(t==null)return[{oid:r,timestamp:n(),data:{op:"delete"}}];let i=ae(t),o=[];for(let s of e){let c=Os(r,i,s,n);o.unshift(...c),je(i,s.data)}return o}function Os(r,t,e,n){let i=e.data;switch(i.op){case"set":case"remove":return[{oid:r,timestamp:n(),data:{op:"set",name:i.name,value:t[i.name]}}];case"list-insert":return[{oid:r,timestamp:n(),data:{op:"list-delete",index:i.index,count:1}}];case"list-delete":return[{oid:r,timestamp:n(),data:{op:"list-insert",index:i.index,values:t.slice(i.index,i.count)}}];case"list-move-by-ref":return[{oid:r,timestamp:n(),data:{op:"list-move-by-ref",value:i.value,index:t.indexOf(i.value)}}];case"list-move-by-index":return[{oid:r,timestamp:n(),data:{op:"list-move-by-index",from:i.to,to:i.from}}];case"delete":return[{oid:r,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:r,timestamp:n(),data:{op:"list-remove",value:i.value,only:"last"}}];case"list-remove":if(i.only==="last"){let o=t.lastIndexOf(i.value);return[{oid:r,timestamp:n(),data:{op:"list-insert",index:o,values:[i.value]}}]}else if(i.only==="first"){let o=t.indexOf(i.value);return[{oid:r,timestamp:n(),data:{op:"list-insert",index:o,values:[i.value]}}]}else{let o=[],s=t.indexOf(i.value);for(;s!==-1;)o.push(s),s=t.indexOf(i.value,s+1);return o.map(c=>({oid:r,timestamp:n(),data:{op:"list-insert",index:c,value:i.value}}))}case"list-add":return[{oid:r,timestamp:n(),data:{op:"list-remove",value:i.value,only:"last"}}];case"initialize":return[{oid:r,timestamp:n(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${i.op}`)}}var Ge=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush());this.getSize=t=>{let e=this.batches.get(t);return e?e.items.length:0}}add({key:t,userData:e,items:n,max:i,timeout:o}){let s=this.batches.get(t);return s||(s=new yr({max:i||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:i,timeout:o,userData:e}),s}},yr=class{constructor({max:t,startedAt:e,timeout:n,userData:i,flusher:o,key:s}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:i})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),i&&(this.userData=i);let o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=i,this.flusher=o,this.key=s}};function ji(r,t){let e,n;return(...i)=>{let o=t();return e&&e.length===o.length&&e.every((s,c)=>s===o[c])||(e=[...o],n=r(...i)),n}}var br=(i=>(i[i.Unexpected=5e3]="Unexpected",i[i.NoToken=4010]="NoToken",i[i.InvalidToken=4011]="InvalidToken",i[i.TokenExpired=4012]="TokenExpired",i))(br||{}),Li=class extends Error{constructor(e,n,i){super(i??`Verdant error: ${e}`,{cause:n});this.code=e;this.toResponse=()=>JSON.stringify({code:this.code})}static{this.Code=br}get httpStatus(){let e=Math.floor(this.code/10);return e<600?e:500}};function Ni(r){return typeof r=="object"&&"code"in r&&typeof r.code=="number"}function le(r){return r instanceof Error&&r.name==="AbortError"}function J(r){return new Promise((t,e)=>{r.onsuccess=()=>{t(r.result)},r.onerror=()=>{r.error&&le(r.error)?t(r.result):e(r.error)}})}function mt(r,t){return new Promise((e,n)=>{let i=r.transaction([t],"readonly"),s=i.objectStore(t).openCursor(),c=0,p=0;s.onsuccess=function(u){let m=s.result;m&&(c++,p=p+vi(m.value),m.continue())},s.onerror=function(u){s.error&&le(s.error)?e({count:c,size:p}):n(s.error)},i.oncomplete=function(u){e({count:c,size:p})},i.onabort=function(u){n(u)},i.onerror=function(u){n(u)}})}function Vi(r,t){let e=r.transaction(t,"readonly"),n=t.map(i=>{let o=e.objectStore(i);return J(o.getAll())});return Promise.all(n)}async function Ke(r){r.close(),await new Promise((t,e)=>{t()})}async function Jt(r,t=window.indexedDB){let e=t.deleteDatabase([r,"meta"].join("_")),n=t.deleteDatabase([r,"collections"].join("_"));await Promise.all([new Promise((i,o)=>{e.onsuccess=i,e.onerror=o}),new Promise((i,o)=>{n.onsuccess=i,n.onerror=o})]),window.location.reload()}function Ui(r,t=window.indexedDB){return J(t.deleteDatabase(r))}async function Ki(r=window.indexedDB){return r.databases()}function Yt(r,t,e,n,i){let o=r.transaction(t,e);if(n){let s=()=>{i?.("debug","aborting transaction");try{o.abort()}catch(c){i?.("debug","aborting transaction failed",c)}};n.addEventListener("abort",s),o.addEventListener("error",()=>{n.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{n.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};var se=class extends Ie{constructor(e,{log:n}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,n)=>{let i=Yt(this.db,e,n?.mode||"readonly",n?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",i.abort),i.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",i.abort)}),i.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",i.abort)}),i};this.run=async(e,n,i)=>{if(this.disposed||i?.transaction?.error)return Promise.resolve(void 0);let s=(i?.transaction||this.createTransaction([e],i)).objectStore(e),c=n(s);return J(c)};this.runAll=async(e,n,i)=>{if(this.disposed||i?.transaction?.error)return Promise.resolve([]);let s=(i?.transaction||this.createTransaction([e],i)).objectStore(e),c=n(s);return Promise.all(c.map(J))};this.iterate=async(e,n,i,o)=>{let c=(o?.transaction||this.createTransaction([e],o)).objectStore(e),p=n(c);return Array.isArray(p)?Promise.all(p.map(u=>new Promise((m,x)=>{u.onsuccess=()=>{let g=u.result;g?(i(g.value,c),g.continue()):m()},u.onerror=()=>{u.error&&le(u.error)?m():x(u.error)}}))).then(()=>{}):new Promise((u,m)=>{p.onsuccess=()=>{let x=p.result;x?(i(x.value,c),x.continue()):u()},p.onerror=()=>{p.error&&le(p.error)?u():m(p.error)}})};this.clear=e=>this.run(e,n=>n.clear(),{mode:"readwrite"});this.log=n,this.addDispose(()=>{this.globalAbortController.abort()})}};var Gt=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var Xt=class extends se{constructor(e,n){super(e,n);this.getAllForDocument=async(e,{mode:n="readonly",transaction:i}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:i}),o};this.iterateOverAllForDocument=async(e,n,{mode:i="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let c=$(e),[p,u]=or(e),[m,x]=sr(e);return[s.openCursor(IDBKeyRange.only(c)),s.openCursor(IDBKeyRange.bound(p,u,!1,!1)),s.openCursor(IDBKeyRange.bound(m,x,!1,!1))]},n,{mode:i,transaction:o});this.iterateOverAllForCollection=async(e,n,{mode:i="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,{mode:i,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let c=$(s),[p,u]=or(s),[m,x]=sr(s);return[o.get(c),o.getAll(IDBKeyRange.bound(p,u,!1,!1)),o.getAll(IDBKeyRange.bound(m,x,!1,!1))]}),{mode:n})).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",i=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return i.index("timestamp").getAll(o)},{mode:n});this.get=async(e,{transaction:n,mode:i="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:i,transaction:n});this.set=async(e,{transaction:n}={})=>{await this.run("baselines",i=>i.put(e),{mode:"readwrite",transaction:n})};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",i=>e.map(o=>i.put(o)),{mode:"readwrite",transaction:n})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",i=>i.delete(e),{mode:"readwrite",transaction:n})}}};var $i=it(Pt(),1);var Zt=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",i=>i.get("localReplicaInfo"),{transaction:e});return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,$i.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let i=await this.get({transaction:n});Object.assign(i,e),await this.run("info",o=>o.put(i),{mode:"readwrite"}),this.cached=i};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),{mode:"readwrite"})}}};var en=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(i=>({...i,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,i=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(c=>{i.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(c=>{i.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:i,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var tn=class extends se{constructor(e,n){super(e,n);this.iterateOverAllOperationsForDocument=async(e,n,{to:i,from:o,after:s,mode:c="readonly",transaction:p}={})=>{let m=(p||this.createTransaction(["operations"],{mode:c})).objectStore("operations"),x=m.index("d_t"),g=o||s,_=g?ce(e,g):Ue(e),w=i?ce(e,i):Ve(e),v=IDBKeyRange.bound(_,w,!!s,!1),I=x.openCursor(v,"next");return new Promise((S,D)=>{let R;I.onsuccess=b=>{let E=I.result;if(E){let d=E.value;L(d.oid.startsWith(e)),L(R===void 0||R<=d.timestamp,`expected ${R} <= ${d.timestamp}`),n(d,m),R=d.timestamp,E.continue()}else S()},I.onerror=b=>{if(le(I.error)){S();return}else D(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:i,to:o,mode:s,transaction:c})=>{let u=(c||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=i?ce(e,i):Ue(e),x=o?ce(e,o):Ve(e),g=IDBKeyRange.bound(m,x,!!i,!1),_=u.openCursor(g,"next");return new Promise((w,v)=>{let I;_.onsuccess=S=>{let D=_.result;if(D){let R=D.value;L(R.oid.startsWith(e)),L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),n(R,u),I=R.timestamp,D.continue()}else w()},_.onerror=S=>{le(_.error)?w():v(_.error)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:i,to:o,mode:s,transaction:c})=>{let p=c||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",u=>u.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,{mode:s,transaction:p})};this.iterateOverAllLocalOperations=async(e,{before:n,after:i,mode:o="readonly",transaction:s})=>{let p=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),u=p.index("l_t"),m=i?ce(!0,i):Ue(!0),x=n?ce(!0,n):Ve(!0),g=IDBKeyRange.bound(m,x,!!i,!0),_=u.openCursor(g,"next");return new Promise((w,v)=>{let I;_.onsuccess=S=>{let D=_.result;if(D){let R=D.value;L(I===void 0||I<=R.timestamp,`expected ${I} <= ${R.timestamp}`),e(R,p),I=R.timestamp,D.continue()}else w()},_.onerror=S=>{le(_.error)?w():v(_.error)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:i,mode:o,from:s})=>{await this.iterate("operations",c=>{let p=s?Ue(s):void 0,u=n?Ve(n):void 0,m=p&&u?window.IDBKeyRange.bound(p,u,!1,!0):p?window.IDBKeyRange.lowerBound(p,!1):u?window.IDBKeyRange.upperBound(u,!0):void 0;return c.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:i})};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let i=new Set;return await this.runAll("operations",o=>e.map(s=>(i.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:n}),Array.from(i)};this.reset=()=>this.clear("operations")}};var nn=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let i=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(i);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await J(o)}}};var gt=class extends V{constructor({disableRebasing:e,context:n}){super();this.time=new At;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,n={})=>Yt(this.db,e,"readwrite",n.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let n=new Set,i=$(e);L(i===e,"Must be root document OID"),n.add(i);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(i,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(i,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,i=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:i}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:i})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let i=$(e);L(i===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(i,{transaction:o}),c=new Map;for(let u of s)u.snapshot&&K(u.snapshot,u.oid),c.set(u.oid,u.snapshot);await this.operations.iterateOverAllOperationsForDocument(i,u=>{let m=c.get(u.oid)||void 0,x=je(m,u.data);x&&K(x,u.oid),c.set(u.oid,x)},{transaction:o,to:n.to||this.now});let p=c.get(i);return p&&Kt(p,c),p};this.getDocumentData=async(e,n)=>{let i=this.createTransaction(["baselines","operations"],n),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,c=>{o.push(c)},{transaction:i}),this.operations.iterateOverAllOperationsForDocument(e,c=>{s[c.oid]??=[],s[c.oid].push(c)},{transaction:i})]),{baselines:o,operations:s}};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,n)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,n);let i=await this.messageCreator.createOperation({operations:e});this.emit("message",i),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,n)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let i=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),n);return this.ack(e[e.length-1].timestamp),i};this.insertRemoteBaselines=async(e,n)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,n);let i=new Set;return e.forEach(o=>{i.add($(o.oid))}),Array.from(i)};this.insertData=async(e,n)=>{let i=this.createTransaction(["baselines","operations"],n);e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:i}),!n?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:i}):await this.insertRemoteOperations(e.operations,{transaction:i}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,i=new Set,o=this.createTransaction(["baselines","operations"]),s=0;if(await this.operations.iterateOverAllOperations(p=>{i.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!i.size||this._closing)return;let c=[];for(let p of i)c.push(await this.rebase(p,n||e,o));this.emit("rebase",c)};this.rebase=async(e,n,i)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=i||this.createTransaction(["operations","baselines"]),c=await this.baselines.get(e,{transaction:s}),p=c?.snapshot||void 0,u=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(g,_)=>{(!c||g.timestamp>c.timestamp)&&(p=je(p,g.data,m)),u++,_.delete(g.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let x={oid:e,snapshot:p,timestamp:n};if(x.snapshot?await this.baselines.set(x,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",n,":",p,"and deleted",u,"operations"),m.length){let g=m.filter(be);g.length&&this.emit("filesDeleted",g)}return x};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let i=await this.schema.get();if(i&&n===i.version&&i.version===e.version&&JSON.stringify(i)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
4
|
+
`)},_domwindow:function(){return h("domwindow")},_bigint:function(l){return h("bigint:"+l.toString())},_process:function(){return h("process")},_timer:function(){return h("timer")},_pipe:function(){return h("pipe")},_tcp:function(){return h("tcp")},_udp:function(){return h("udp")},_tty:function(){return h("tty")},_statwatcher:function(){return h("statwatcher")},_securecontext:function(){return h("securecontext")},_connection:function(){return h("connection")},_zlib:function(){return h("zlib")},_context:function(){return h("context")},_nodescript:function(){return h("nodescript")},_httpparser:function(){return h("httpparser")},_dataview:function(){return h("dataview")},_signal:function(){return h("signal")},_fsevent:function(){return h("fsevent")},_tlswrap:function(){return h("tlswrap")}}}function T(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,E,d){return d===void 0&&(d=E,E={}),D(E=I(b,E),d).dispatch(b)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){(function(g){"use strict";var _=typeof Uint8Array<"u"?Uint8Array:Array,w="+".charCodeAt(0),v="/".charCodeAt(0),I="0".charCodeAt(0),x="a".charCodeAt(0),D="A".charCodeAt(0),T="-".charCodeAt(0),b="_".charCodeAt(0);function E(d){return d=d.charCodeAt(0),d===w||d===T?62:d===v||d===b?63:d<I?-1:d<I+10?d-I+26+26:d<D+26?d-D:d<x+26?d-x+26:void 0}g.toByteArray=function(d){var h,l;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var O=d.length,O=d.charAt(O-2)==="="?2:d.charAt(O-1)==="="?1:0,C=new _(3*d.length/4-O),M=0<O?d.length-4:d.length,B=0;function j(k){C[B++]=k}for(h=0;h<M;h+=4,0)j((16711680&(l=E(d.charAt(h))<<18|E(d.charAt(h+1))<<12|E(d.charAt(h+2))<<6|E(d.charAt(h+3))))>>16),j((65280&l)>>8),j(255&l);return O==2?j(255&(l=E(d.charAt(h))<<2|E(d.charAt(h+1))>>4)):O==1&&(j((l=E(d.charAt(h))<<10|E(d.charAt(h+1))<<4|E(d.charAt(h+2))>>2)>>8&255),j(255&l)),C},g.fromByteArray=function(d){var h,l,O,C,M=d.length%3,B="";function j(k){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k)}for(h=0,O=d.length-M;h<O;h+=3)l=(d[h]<<16)+(d[h+1]<<8)+d[h+2],B+=j((C=l)>>18&63)+j(C>>12&63)+j(C>>6&63)+j(63&C);switch(M){case 1:B=(B+=j((l=d[d.length-1])>>2))+j(l<<4&63)+"==";break;case 2:B=(B=(B+=j((l=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(l>>4&63))+j(l<<2&63)+"="}return B}})(e===void 0?this.base64js={}:e)}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(r,t,e){(function(n,i,w,s,c,p,u,m,S){var g=r("base64-js"),_=r("ieee754");function w(a,f,y){if(!(this instanceof w))return new w(a,f,y);var A,P,F,N,W=typeof a;if(f==="base64"&&W=="string")for(a=(N=a).trim?N.trim():N.replace(/^\s+|\s+$/g,"");a.length%4!=0;)a+="=";if(W=="number")A=te(a);else if(W=="string")A=w.byteLength(a,f);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");A=te(a.length)}if(w._useTypedArrays?P=w._augment(new Uint8Array(A)):((P=this).length=A,P._isBuffer=!0),w._useTypedArrays&&typeof a.byteLength=="number")P._set(a);else if(H(N=a)||w.isBuffer(N)||N&&typeof N=="object"&&typeof N.length=="number")for(F=0;F<A;F++)w.isBuffer(a)?P[F]=a.readUInt8(F):P[F]=a[F];else if(W=="string")P.write(a,0,f);else if(W=="number"&&!w._useTypedArrays&&!y)for(F=0;F<A;F++)P[F]=0;return P}function v(a,f,y,A){return w._charsWritten=Ct(function(P){for(var F=[],N=0;N<P.length;N++)F.push(255&P.charCodeAt(N));return F}(f),a,y,A)}function I(a,f,y,A){return w._charsWritten=Ct(function(P){for(var F,N,W=[],G=0;G<P.length;G++)N=P.charCodeAt(G),F=N>>8,N=N%256,W.push(N),W.push(F);return W}(f),a,y,A)}function x(a,f,y){var A="";y=Math.min(a.length,y);for(var P=f;P<y;P++)A+=String.fromCharCode(a[P]);return A}function D(a,f,y,F){F||(R(typeof y=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(f+1<a.length,"Trying to read beyond buffer length"));var P,F=a.length;if(!(F<=f))return y?(P=a[f],f+1<F&&(P|=a[f+1]<<8)):(P=a[f]<<8,f+1<F&&(P|=a[f+1])),P}function T(a,f,y,F){F||(R(typeof y=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(f+3<a.length,"Trying to read beyond buffer length"));var P,F=a.length;if(!(F<=f))return y?(f+2<F&&(P=a[f+2]<<16),f+1<F&&(P|=a[f+1]<<8),P|=a[f],f+3<F&&(P+=a[f+3]<<24>>>0)):(f+1<F&&(P=a[f+1]<<16),f+2<F&&(P|=a[f+2]<<8),f+3<F&&(P|=a[f+3]),P+=a[f]<<24>>>0),P}function b(a,f,y,A){if(A||(R(typeof y=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(f+1<a.length,"Trying to read beyond buffer length")),!(a.length<=f))return A=D(a,f,y,!0),32768&A?-1*(65535-A+1):A}function E(a,f,y,A){if(A||(R(typeof y=="boolean","missing or invalid endian"),R(f!=null,"missing offset"),R(f+3<a.length,"Trying to read beyond buffer length")),!(a.length<=f))return A=T(a,f,y,!0),2147483648&A?-1*(4294967295-A+1):A}function d(a,f,y,A){return A||(R(typeof y=="boolean","missing or invalid endian"),R(f+3<a.length,"Trying to read beyond buffer length")),_.read(a,f,y,23,4)}function h(a,f,y,A){return A||(R(typeof y=="boolean","missing or invalid endian"),R(f+7<a.length,"Trying to read beyond buffer length")),_.read(a,f,y,52,8)}function l(a,f,y,A,P){if(P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+1<a.length,"trying to write beyond buffer length"),zn(f,65535)),P=a.length,!(P<=y))for(var F=0,N=Math.min(P-y,2);F<N;F++)a[y+F]=(f&255<<8*(A?F:1-F))>>>8*(A?F:1-F)}function O(a,f,y,A,P){if(P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+3<a.length,"trying to write beyond buffer length"),zn(f,4294967295)),P=a.length,!(P<=y))for(var F=0,N=Math.min(P-y,4);F<N;F++)a[y+F]=f>>>8*(A?F:3-F)&255}function C(a,f,y,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+1<a.length,"Trying to write beyond buffer length"),qn(f,32767,-32768)),a.length<=y||l(a,0<=f?f:65535+f+1,y,A,P)}function M(a,f,y,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+3<a.length,"Trying to write beyond buffer length"),qn(f,2147483647,-2147483648)),a.length<=y||O(a,0<=f?f:4294967295+f+1,y,A,P)}function B(a,f,y,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+3<a.length,"Trying to write beyond buffer length"),Jr(f,34028234663852886e22,-34028234663852886e22)),a.length<=y||_.write(a,f,y,A,23,4)}function j(a,f,y,A,P){P||(R(f!=null,"missing value"),R(typeof A=="boolean","missing or invalid endian"),R(y!=null,"missing offset"),R(y+7<a.length,"Trying to write beyond buffer length"),Jr(f,17976931348623157e292,-17976931348623157e292)),a.length<=y||_.write(a,f,y,A,52,8)}e.Buffer=w,e.SlowBuffer=w,e.INSPECT_MAX_BYTES=50,w.poolSize=8192,w._useTypedArrays=function(){try{var a=new ArrayBuffer(0),f=new Uint8Array(a);return f.foo=function(){return 42},f.foo()===42&&typeof f.subarray=="function"}catch{return!1}}(),w.isEncoding=function(a){switch(String(a).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},w.isBuffer=function(a){return!(a==null||!a._isBuffer)},w.byteLength=function(a,f){var y;switch(a+="",f||"utf8"){case"hex":y=a.length/2;break;case"utf8":case"utf-8":y=Ee(a).length;break;case"ascii":case"binary":case"raw":y=a.length;break;case"base64":y=Wr(a).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":y=2*a.length;break;default:throw new Error("Unknown encoding")}return y},w.concat=function(a,f){if(R(H(a),`Usage: Buffer.concat(list, [totalLength])
|
|
5
|
+
list should be an Array.`),a.length===0)return new w(0);if(a.length===1)return a[0];if(typeof f!="number")for(P=f=0;P<a.length;P++)f+=a[P].length;for(var y=new w(f),A=0,P=0;P<a.length;P++){var F=a[P];F.copy(y,A),A+=F.length}return y},w.prototype.write=function(a,f,y,A){isFinite(f)?isFinite(y)||(A=y,y=void 0):(G=A,A=f,f=y,y=G),f=Number(f)||0;var P,F,N,W,G=this.length-f;switch((!y||G<(y=Number(y)))&&(y=G),A=String(A||"utf8").toLowerCase()){case"hex":P=function(ye,re,ie,X){ie=Number(ie)||0;var Y=ye.length-ie;(!X||Y<(X=Number(X)))&&(X=Y),R((Y=re.length)%2==0,"Invalid hex string"),Y/2<X&&(X=Y/2);for(var We=0;We<X;We++){var Yr=parseInt(re.substr(2*We,2),16);R(!isNaN(Yr),"Invalid hex string"),ye[ie+We]=Yr}return w._charsWritten=2*We,We}(this,a,f,y);break;case"utf8":case"utf-8":F=this,N=f,W=y,P=w._charsWritten=Ct(Ee(a),F,N,W);break;case"ascii":case"binary":P=v(this,a,f,y);break;case"base64":F=this,N=f,W=y,P=w._charsWritten=Ct(Wr(a),F,N,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=I(this,a,f,y);break;default:throw new Error("Unknown encoding")}return P},w.prototype.toString=function(a,f,y){var A,P,F,N,W=this;if(a=String(a||"utf8").toLowerCase(),f=Number(f)||0,(y=y!==void 0?Number(y):W.length)===f)return"";switch(a){case"hex":A=function(G,ye,re){var ie=G.length;(!ye||ye<0)&&(ye=0),(!re||re<0||ie<re)&&(re=ie);for(var X="",Y=ye;Y<re;Y++)X+=z(G[Y]);return X}(W,f,y);break;case"utf8":case"utf-8":A=function(G,ye,re){var ie="",X="";re=Math.min(G.length,re);for(var Y=ye;Y<re;Y++)G[Y]<=127?(ie+=Qr(X)+String.fromCharCode(G[Y]),X=""):X+="%"+G[Y].toString(16);return ie+Qr(X)}(W,f,y);break;case"ascii":case"binary":A=x(W,f,y);break;case"base64":P=W,N=y,A=(F=f)===0&&N===P.length?g.fromByteArray(P):g.fromByteArray(P.slice(F,N));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(G,ye,re){for(var ie=G.slice(ye,re),X="",Y=0;Y<ie.length;Y+=2)X+=String.fromCharCode(ie[Y]+256*ie[Y+1]);return X}(W,f,y);break;default:throw new Error("Unknown encoding")}return A},w.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},w.prototype.copy=function(a,f,y,A){if(f=f||0,(A=A||A===0?A:this.length)!==(y=y||0)&&a.length!==0&&this.length!==0){R(y<=A,"sourceEnd < sourceStart"),R(0<=f&&f<a.length,"targetStart out of bounds"),R(0<=y&&y<this.length,"sourceStart out of bounds"),R(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=a.length-f<A-y?a.length-f+y:A)-y;if(P<100||!w._useTypedArrays)for(var F=0;F<P;F++)a[F+f]=this[F+y];else a._set(this.subarray(y,y+P),f)}},w.prototype.slice=function(a,f){var y=this.length;if(a=q(a,y,0),f=q(f,y,y),w._useTypedArrays)return w._augment(this.subarray(a,f));for(var A=f-a,P=new w(A,void 0,!0),F=0;F<A;F++)P[F]=this[F+a];return P},w.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},w.prototype.set=function(a,f){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,f)},w.prototype.readUInt8=function(a,f){if(f||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return this[a]},w.prototype.readUInt16LE=function(a,f){return D(this,a,!0,f)},w.prototype.readUInt16BE=function(a,f){return D(this,a,!1,f)},w.prototype.readUInt32LE=function(a,f){return T(this,a,!0,f)},w.prototype.readUInt32BE=function(a,f){return T(this,a,!1,f)},w.prototype.readInt8=function(a,f){if(f||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return 128&this[a]?-1*(255-this[a]+1):this[a]},w.prototype.readInt16LE=function(a,f){return b(this,a,!0,f)},w.prototype.readInt16BE=function(a,f){return b(this,a,!1,f)},w.prototype.readInt32LE=function(a,f){return E(this,a,!0,f)},w.prototype.readInt32BE=function(a,f){return E(this,a,!1,f)},w.prototype.readFloatLE=function(a,f){return d(this,a,!0,f)},w.prototype.readFloatBE=function(a,f){return d(this,a,!1,f)},w.prototype.readDoubleLE=function(a,f){return h(this,a,!0,f)},w.prototype.readDoubleBE=function(a,f){return h(this,a,!1,f)},w.prototype.writeUInt8=function(a,f,y){y||(R(a!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"trying to write beyond buffer length"),zn(a,255)),f>=this.length||(this[f]=a)},w.prototype.writeUInt16LE=function(a,f,y){l(this,a,f,!0,y)},w.prototype.writeUInt16BE=function(a,f,y){l(this,a,f,!1,y)},w.prototype.writeUInt32LE=function(a,f,y){O(this,a,f,!0,y)},w.prototype.writeUInt32BE=function(a,f,y){O(this,a,f,!1,y)},w.prototype.writeInt8=function(a,f,y){y||(R(a!=null,"missing value"),R(f!=null,"missing offset"),R(f<this.length,"Trying to write beyond buffer length"),qn(a,127,-128)),f>=this.length||(0<=a?this.writeUInt8(a,f,y):this.writeUInt8(255+a+1,f,y))},w.prototype.writeInt16LE=function(a,f,y){C(this,a,f,!0,y)},w.prototype.writeInt16BE=function(a,f,y){C(this,a,f,!1,y)},w.prototype.writeInt32LE=function(a,f,y){M(this,a,f,!0,y)},w.prototype.writeInt32BE=function(a,f,y){M(this,a,f,!1,y)},w.prototype.writeFloatLE=function(a,f,y){B(this,a,f,!0,y)},w.prototype.writeFloatBE=function(a,f,y){B(this,a,f,!1,y)},w.prototype.writeDoubleLE=function(a,f,y){j(this,a,f,!0,y)},w.prototype.writeDoubleBE=function(a,f,y){j(this,a,f,!1,y)},w.prototype.fill=function(a,f,y){if(f=f||0,y=y||this.length,R(typeof(a=typeof(a=a||0)=="string"?a.charCodeAt(0):a)=="number"&&!isNaN(a),"value is not a number"),R(f<=y,"end < start"),y!==f&&this.length!==0){R(0<=f&&f<this.length,"start out of bounds"),R(0<=y&&y<=this.length,"end out of bounds");for(var A=f;A<y;A++)this[A]=a}},w.prototype.inspect=function(){for(var a=[],f=this.length,y=0;y<f;y++)if(a[y]=z(this[y]),y===e.INSPECT_MAX_BYTES){a[y+1]="...";break}return"<Buffer "+a.join(" ")+">"},w.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(w._useTypedArrays)return new w(this).buffer;for(var a=new Uint8Array(this.length),f=0,y=a.length;f<y;f+=1)a[f]=this[f];return a.buffer};var k=w.prototype;function q(a,f,y){return typeof a!="number"?y:f<=(a=~~a)?f:0<=a||0<=(a+=f)?a:0}function te(a){return(a=~~Math.ceil(+a))<0?0:a}function H(a){return(Array.isArray||function(f){return Object.prototype.toString.call(f)==="[object Array]"})(a)}function z(a){return a<16?"0"+a.toString(16):a.toString(16)}function Ee(a){for(var f=[],y=0;y<a.length;y++){var A=a.charCodeAt(y);if(A<=127)f.push(a.charCodeAt(y));else for(var P=y,F=(55296<=A&&A<=57343&&y++,encodeURIComponent(a.slice(P,y+1)).substr(1).split("%")),N=0;N<F.length;N++)f.push(parseInt(F[N],16))}return f}function Wr(a){return g.toByteArray(a)}function Ct(a,f,y,A){for(var P=0;P<A&&!(P+y>=f.length||P>=a.length);P++)f[P+y]=a[P];return P}function Qr(a){try{return decodeURIComponent(a)}catch{return String.fromCharCode(65533)}}function zn(a,f){R(typeof a=="number","cannot write a non-number as a number"),R(0<=a,"specified a negative value for writing an unsigned value"),R(a<=f,"value is larger than maximum value for type"),R(Math.floor(a)===a,"value has a fractional component")}function qn(a,f,y){R(typeof a=="number","cannot write a non-number as a number"),R(a<=f,"value larger than maximum allowed value"),R(y<=a,"value smaller than minimum allowed value"),R(Math.floor(a)===a,"value has a fractional component")}function Jr(a,f,y){R(typeof a=="number","cannot write a non-number as a number"),R(a<=f,"value larger than maximum allowed value"),R(y<=a,"value smaller than minimum allowed value")}function R(a,f){if(!a)throw new Error(f||"Failed assertion")}w._augment=function(a){return a._isBuffer=!0,a._get=a.get,a._set=a.set,a.get=k.get,a.set=k.set,a.write=k.write,a.toString=k.toString,a.toLocaleString=k.toString,a.toJSON=k.toJSON,a.copy=k.copy,a.slice=k.slice,a.readUInt8=k.readUInt8,a.readUInt16LE=k.readUInt16LE,a.readUInt16BE=k.readUInt16BE,a.readUInt32LE=k.readUInt32LE,a.readUInt32BE=k.readUInt32BE,a.readInt8=k.readInt8,a.readInt16LE=k.readInt16LE,a.readInt16BE=k.readInt16BE,a.readInt32LE=k.readInt32LE,a.readInt32BE=k.readInt32BE,a.readFloatLE=k.readFloatLE,a.readFloatBE=k.readFloatBE,a.readDoubleLE=k.readDoubleLE,a.readDoubleBE=k.readDoubleBE,a.writeUInt8=k.writeUInt8,a.writeUInt16LE=k.writeUInt16LE,a.writeUInt16BE=k.writeUInt16BE,a.writeUInt32LE=k.writeUInt32LE,a.writeUInt32BE=k.writeUInt32BE,a.writeInt8=k.writeInt8,a.writeInt16LE=k.writeInt16LE,a.writeInt16BE=k.writeInt16BE,a.writeInt32LE=k.writeInt32LE,a.writeInt32BE=k.writeInt32BE,a.writeFloatLE=k.writeFloatLE,a.writeFloatBE=k.writeFloatBE,a.writeDoubleLE=k.writeDoubleLE,a.writeDoubleBE=k.writeDoubleBE,a.fill=k.fill,a.inspect=k.inspect,a.toArrayBuffer=k.toArrayBuffer,a}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(r,t,e){(function(n,i,g,s,c,p,u,m,S){var g=r("buffer").Buffer,_=4,w=new g(_);w.fill(0),t.exports={hash:function(v,I,x,D){for(var T=I(function(l,O){l.length%_!=0&&(C=l.length+(_-l.length%_),l=g.concat([l,w],C));for(var C,M=[],B=O?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=_)M.push(B.call(l,j));return M}(v=g.isBuffer(v)?v:new g(v),D),8*v.length),I=D,b=new g(x),E=I?b.writeInt32BE:b.writeInt32LE,d=0;d<T.length;d++)E.call(b,T[d],4*d,!0);return b}}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(r,t,e){(function(n,i,g,s,c,p,u,m,S){var g=r("buffer").Buffer,_=r("./sha"),w=r("./sha256"),v=r("./rng"),I={sha1:_,sha256:w,md5:r("./md5")},x=64,D=new g(x);function T(l,O){var C=I[l=l||"sha1"],M=[];return C||b("algorithm:",l,"is not yet supported"),{update:function(B){return g.isBuffer(B)||(B=new g(B)),M.push(B),B.length,this},digest:function(B){var j=g.concat(M),j=O?function(k,q,te){g.isBuffer(q)||(q=new g(q)),g.isBuffer(te)||(te=new g(te)),q.length>x?q=k(q):q.length<x&&(q=g.concat([q,D],x));for(var H=new g(x),z=new g(x),Ee=0;Ee<x;Ee++)H[Ee]=54^q[Ee],z[Ee]=92^q[Ee];return te=k(g.concat([H,te])),k(g.concat([z,te]))}(C,O,j):C(j);return M=null,B?j.toString(B):j}}}function b(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
+
`))}D.fill(0),e.createHash=function(l){return T(l)},e.createHmac=T,e.randomBytes=function(l,O){if(!O||!O.call)return new g(v(l));try{O.call(this,void 0,new g(v(l)))}catch(C){O(C)}};var E,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],h=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(E in d)h(d[E],E)}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){var g=r("./helpers");function _(b,E){b[E>>5]|=128<<E%32,b[14+(E+64>>>9<<4)]=E;for(var d=1732584193,h=-271733879,l=-1732584194,O=271733878,C=0;C<b.length;C+=16){var M=d,B=h,j=l,k=O,d=v(d,h,l,O,b[C+0],7,-680876936),O=v(O,d,h,l,b[C+1],12,-389564586),l=v(l,O,d,h,b[C+2],17,606105819),h=v(h,l,O,d,b[C+3],22,-1044525330);d=v(d,h,l,O,b[C+4],7,-176418897),O=v(O,d,h,l,b[C+5],12,1200080426),l=v(l,O,d,h,b[C+6],17,-1473231341),h=v(h,l,O,d,b[C+7],22,-45705983),d=v(d,h,l,O,b[C+8],7,1770035416),O=v(O,d,h,l,b[C+9],12,-1958414417),l=v(l,O,d,h,b[C+10],17,-42063),h=v(h,l,O,d,b[C+11],22,-1990404162),d=v(d,h,l,O,b[C+12],7,1804603682),O=v(O,d,h,l,b[C+13],12,-40341101),l=v(l,O,d,h,b[C+14],17,-1502002290),d=I(d,h=v(h,l,O,d,b[C+15],22,1236535329),l,O,b[C+1],5,-165796510),O=I(O,d,h,l,b[C+6],9,-1069501632),l=I(l,O,d,h,b[C+11],14,643717713),h=I(h,l,O,d,b[C+0],20,-373897302),d=I(d,h,l,O,b[C+5],5,-701558691),O=I(O,d,h,l,b[C+10],9,38016083),l=I(l,O,d,h,b[C+15],14,-660478335),h=I(h,l,O,d,b[C+4],20,-405537848),d=I(d,h,l,O,b[C+9],5,568446438),O=I(O,d,h,l,b[C+14],9,-1019803690),l=I(l,O,d,h,b[C+3],14,-187363961),h=I(h,l,O,d,b[C+8],20,1163531501),d=I(d,h,l,O,b[C+13],5,-1444681467),O=I(O,d,h,l,b[C+2],9,-51403784),l=I(l,O,d,h,b[C+7],14,1735328473),d=x(d,h=I(h,l,O,d,b[C+12],20,-1926607734),l,O,b[C+5],4,-378558),O=x(O,d,h,l,b[C+8],11,-2022574463),l=x(l,O,d,h,b[C+11],16,1839030562),h=x(h,l,O,d,b[C+14],23,-35309556),d=x(d,h,l,O,b[C+1],4,-1530992060),O=x(O,d,h,l,b[C+4],11,1272893353),l=x(l,O,d,h,b[C+7],16,-155497632),h=x(h,l,O,d,b[C+10],23,-1094730640),d=x(d,h,l,O,b[C+13],4,681279174),O=x(O,d,h,l,b[C+0],11,-358537222),l=x(l,O,d,h,b[C+3],16,-722521979),h=x(h,l,O,d,b[C+6],23,76029189),d=x(d,h,l,O,b[C+9],4,-640364487),O=x(O,d,h,l,b[C+12],11,-421815835),l=x(l,O,d,h,b[C+15],16,530742520),d=D(d,h=x(h,l,O,d,b[C+2],23,-995338651),l,O,b[C+0],6,-198630844),O=D(O,d,h,l,b[C+7],10,1126891415),l=D(l,O,d,h,b[C+14],15,-1416354905),h=D(h,l,O,d,b[C+5],21,-57434055),d=D(d,h,l,O,b[C+12],6,1700485571),O=D(O,d,h,l,b[C+3],10,-1894986606),l=D(l,O,d,h,b[C+10],15,-1051523),h=D(h,l,O,d,b[C+1],21,-2054922799),d=D(d,h,l,O,b[C+8],6,1873313359),O=D(O,d,h,l,b[C+15],10,-30611744),l=D(l,O,d,h,b[C+6],15,-1560198380),h=D(h,l,O,d,b[C+13],21,1309151649),d=D(d,h,l,O,b[C+4],6,-145523070),O=D(O,d,h,l,b[C+11],10,-1120210379),l=D(l,O,d,h,b[C+2],15,718787259),h=D(h,l,O,d,b[C+9],21,-343485551),d=T(d,M),h=T(h,B),l=T(l,j),O=T(O,k)}return Array(d,h,l,O)}function w(b,E,d,h,l,O){return T((E=T(T(E,b),T(h,O)))<<l|E>>>32-l,d)}function v(b,E,d,h,l,O,C){return w(E&d|~E&h,b,E,l,O,C)}function I(b,E,d,h,l,O,C){return w(E&h|d&~h,b,E,l,O,C)}function x(b,E,d,h,l,O,C){return w(E^d^h,b,E,l,O,C)}function D(b,E,d,h,l,O,C){return w(d^(E|~h),b,E,l,O,C)}function T(b,E){var d=(65535&b)+(65535&E);return(b>>16)+(E>>16)+(d>>16)<<16|65535&d}t.exports=function(b){return g.hash(b,_,16)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){var g;t.exports=g||function(_){for(var w,v=new Array(_),I=0;I<_;I++)!(3&I)&&(w=4294967296*Math.random()),v[I]=w>>>((3&I)<<3)&255;return v}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){var g=r("./helpers");function _(I,x){I[x>>5]|=128<<24-x%32,I[15+(x+64>>9<<4)]=x;for(var D,T,b,E=Array(80),d=1732584193,h=-271733879,l=-1732584194,O=271733878,C=-1009589776,M=0;M<I.length;M+=16){for(var B=d,j=h,k=l,q=O,te=C,H=0;H<80;H++){E[H]=H<16?I[M+H]:v(E[H-3]^E[H-8]^E[H-14]^E[H-16],1);var z=w(w(v(d,5),(z=h,T=l,b=O,(D=H)<20?z&T|~z&b:!(D<40)&&D<60?z&T|z&b|T&b:z^T^b)),w(w(C,E[H]),(D=H)<20?1518500249:D<40?1859775393:D<60?-1894007588:-899497514)),C=O,O=l,l=v(h,30),h=d,d=z}d=w(d,B),h=w(h,j),l=w(l,k),O=w(O,q),C=w(C,te)}return Array(d,h,l,O,C)}function w(I,x){var D=(65535&I)+(65535&x);return(I>>16)+(x>>16)+(D>>16)<<16|65535&D}function v(I,x){return I<<x|I>>>32-x}t.exports=function(I){return g.hash(I,_,20,!0)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){function g(x,D){var T=(65535&x)+(65535&D);return(x>>16)+(D>>16)+(T>>16)<<16|65535&T}function _(x,D){var T,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),E=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);x[D>>5]|=128<<24-D%32,x[15+(D+64>>9<<4)]=D;for(var h,l,O=0;O<x.length;O+=16){for(var C=E[0],M=E[1],B=E[2],j=E[3],k=E[4],q=E[5],te=E[6],H=E[7],z=0;z<64;z++)d[z]=z<16?x[z+O]:g(g(g((l=d[z-2],v(l,17)^v(l,19)^I(l,10)),d[z-7]),(l=d[z-15],v(l,7)^v(l,18)^I(l,3))),d[z-16]),T=g(g(g(g(H,v(l=k,6)^v(l,11)^v(l,25)),k&q^~k&te),b[z]),d[z]),h=g(v(h=C,2)^v(h,13)^v(h,22),C&M^C&B^M&B),H=te,te=q,q=k,k=g(j,T),j=B,B=M,M=C,C=g(T,h);E[0]=g(C,E[0]),E[1]=g(M,E[1]),E[2]=g(B,E[2]),E[3]=g(j,E[3]),E[4]=g(k,E[4]),E[5]=g(q,E[5]),E[6]=g(te,E[6]),E[7]=g(H,E[7])}return E}var w=r("./helpers"),v=function(x,D){return x>>>D|x<<32-D},I=function(x,D){return x>>>D};t.exports=function(x){return w.hash(x,_,32,!0)}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){e.read=function(g,_,w,v,O){var x,D,T=8*O-v-1,b=(1<<T)-1,E=b>>1,d=-7,h=w?O-1:0,l=w?-1:1,O=g[_+h];for(h+=l,x=O&(1<<-d)-1,O>>=-d,d+=T;0<d;x=256*x+g[_+h],h+=l,d-=8);for(D=x&(1<<-d)-1,x>>=-d,d+=v;0<d;D=256*D+g[_+h],h+=l,d-=8);if(x===0)x=1-E;else{if(x===b)return D?NaN:1/0*(O?-1:1);D+=Math.pow(2,v),x-=E}return(O?-1:1)*D*Math.pow(2,x-v)},e.write=function(g,_,w,v,I,C){var D,T,b=8*C-I-1,E=(1<<b)-1,d=E>>1,h=I===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:C-1,O=v?1:-1,C=_<0||_===0&&1/_<0?1:0;for(_=Math.abs(_),isNaN(_)||_===1/0?(T=isNaN(_)?1:0,D=E):(D=Math.floor(Math.log(_)/Math.LN2),_*(v=Math.pow(2,-D))<1&&(D--,v*=2),2<=(_+=1<=D+d?h/v:h*Math.pow(2,1-d))*v&&(D++,v/=2),E<=D+d?(T=0,D=E):1<=D+d?(T=(_*v-1)*Math.pow(2,I),D+=d):(T=_*Math.pow(2,d-1)*Math.pow(2,I),D=0));8<=I;g[w+l]=255&T,l+=O,T/=256,I-=8);for(D=D<<I|T,b+=I;0<b;g[w+l]=255&D,l+=O,D/=256,b-=8);g[w+l-O]|=128*C}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(r,t,e){(function(n,i,o,s,c,p,u,m,S){var g,_,w;function v(){}(n=t.exports={}).nextTick=(_=typeof window<"u"&&window.setImmediate,w=typeof window<"u"&&window.postMessage&&window.addEventListener,_?function(I){return window.setImmediate(I)}:w?(g=[],window.addEventListener("message",function(I){var x=I.source;x!==window&&x!==null||I.data!=="process-tick"||(I.stopPropagation(),0<g.length&&g.shift()())},!0),function(I){g.push(I),window.postMessage("process-tick","*")}):function(I){setTimeout(I,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.binding=function(I){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(I){throw new Error("process.chdir is not supported")}}).call(this,r("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},r("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ze={};Gr(ze,{__addDisposableResource:()=>xo,__assign:()=>bn,__asyncDelegator:()=>ho,__asyncGenerator:()=>po,__asyncValues:()=>mo,__await:()=>nt,__awaiter:()=>so,__classPrivateFieldGet:()=>wo,__classPrivateFieldIn:()=>So,__classPrivateFieldSet:()=>vo,__createBinding:()=>vn,__decorate:()=>ro,__disposeResources:()=>Oo,__esDecorate:()=>ia,__exportStar:()=>co,__extends:()=>to,__generator:()=>ao,__importDefault:()=>bo,__importStar:()=>yo,__makeTemplateObject:()=>go,__metadata:()=>oo,__param:()=>io,__propKey:()=>sa,__read:()=>Pr,__rest:()=>no,__runInitializers:()=>oa,__setFunctionName:()=>aa,__spread:()=>lo,__spreadArray:()=>fo,__spreadArrays:()=>uo,__values:()=>wn,default:()=>da});function to(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");_r(r,t);function e(){this.constructor=r}r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}function no(r,t){var e={};for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&t.indexOf(n)<0&&(e[n]=r[n]);if(r!=null&&typeof Object.getOwnPropertySymbols=="function")for(var i=0,n=Object.getOwnPropertySymbols(r);i<n.length;i++)t.indexOf(n[i])<0&&Object.prototype.propertyIsEnumerable.call(r,n[i])&&(e[n[i]]=r[n[i]]);return e}function ro(r,t,e,n){var i=arguments.length,o=i<3?t:n===null?n=Object.getOwnPropertyDescriptor(t,e):n,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(r,t,e,n);else for(var c=r.length-1;c>=0;c--)(s=r[c])&&(o=(i<3?s(o):i>3?s(t,e,o):s(t,e))||o);return i>3&&o&&Object.defineProperty(t,e,o),o}function io(r,t){return function(e,n){t(e,n,r)}}function ia(r,t,e,n,i,o){function s(x){if(x!==void 0&&typeof x!="function")throw new TypeError("Function expected");return x}for(var c=n.kind,p=c==="getter"?"get":c==="setter"?"set":"value",u=!t&&r?n.static?r:r.prototype:null,m=t||(u?Object.getOwnPropertyDescriptor(u,n.name):{}),S,g=!1,_=e.length-1;_>=0;_--){var w={};for(var v in n)w[v]=v==="access"?{}:n[v];for(var v in n.access)w.access[v]=n.access[v];w.addInitializer=function(x){if(g)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(x||null))};var I=(0,e[_])(c==="accessor"?{get:m.get,set:m.set}:m[p],w);if(c==="accessor"){if(I===void 0)continue;if(I===null||typeof I!="object")throw new TypeError("Object expected");(S=s(I.get))&&(m.get=S),(S=s(I.set))&&(m.set=S),(S=s(I.init))&&i.unshift(S)}else(S=s(I))&&(c==="field"?i.unshift(S):m[p]=S)}u&&Object.defineProperty(u,n.name,m),g=!0}function oa(r,t,e){for(var n=arguments.length>2,i=0;i<t.length;i++)e=n?t[i].call(r,e):t[i].call(r);return n?e:void 0}function sa(r){return typeof r=="symbol"?r:"".concat(r)}function aa(r,t,e){return typeof t=="symbol"&&(t=t.description?"[".concat(t.description,"]"):""),Object.defineProperty(r,"name",{configurable:!0,value:e?"".concat(e," ",t):t})}function oo(r,t){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(r,t)}function so(r,t,e,n){function i(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function c(m){try{u(n.next(m))}catch(S){s(S)}}function p(m){try{u(n.throw(m))}catch(S){s(S)}}function u(m){m.done?o(m.value):i(m.value).then(c,p)}u((n=n.apply(r,t||[])).next())})}function ao(r,t){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},n,i,o,s;return s={next:c(0),throw:c(1),return:c(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function c(u){return function(m){return p([u,m])}}function p(u){if(n)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(e=0)),e;)try{if(n=1,i&&(o=u[0]&2?i.return:u[0]?i.throw||((o=i.return)&&o.call(i),0):i.next)&&!(o=o.call(i,u[1])).done)return o;switch(i=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,i=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=t.call(r,e)}catch(m){u=[6,m],i=0}finally{n=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function co(r,t){for(var e in r)e!=="default"&&!Object.prototype.hasOwnProperty.call(t,e)&&vn(t,r,e)}function wn(r){var t=typeof Symbol=="function"&&Symbol.iterator,e=t&&r[t],n=0;if(e)return e.call(r);if(r&&typeof r.length=="number")return{next:function(){return r&&n>=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function Pr(r,t){var e=typeof Symbol=="function"&&r[Symbol.iterator];if(!e)return r;var n=e.call(r),i,o=[],s;try{for(;(t===void 0||t-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(e=n.return)&&e.call(n)}finally{if(s)throw s.error}}return o}function lo(){for(var r=[],t=0;t<arguments.length;t++)r=r.concat(Pr(arguments[t]));return r}function uo(){for(var r=0,t=0,e=arguments.length;t<e;t++)r+=arguments[t].length;for(var n=Array(r),i=0,t=0;t<e;t++)for(var o=arguments[t],s=0,c=o.length;s<c;s++,i++)n[i]=o[s];return n}function fo(r,t,e){if(e||arguments.length===2)for(var n=0,i=t.length,o;n<i;n++)(o||!(n in t))&&(o||(o=Array.prototype.slice.call(t,0,n)),o[n]=t[n]);return r.concat(o||Array.prototype.slice.call(t))}function nt(r){return this instanceof nt?(this.v=r,this):new nt(r)}function po(r,t,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=e.apply(r,t||[]),i,o=[];return i={},s("next"),s("throw"),s("return"),i[Symbol.asyncIterator]=function(){return this},i;function s(g){n[g]&&(i[g]=function(_){return new Promise(function(w,v){o.push([g,_,w,v])>1||c(g,_)})})}function c(g,_){try{p(n[g](_))}catch(w){S(o[0][3],w)}}function p(g){g.value instanceof nt?Promise.resolve(g.value.v).then(u,m):S(o[0][2],g)}function u(g){c("next",g)}function m(g){c("throw",g)}function S(g,_){g(_),o.shift(),o.length&&c(o[0][0],o[0][1])}}function ho(r){var t,e;return t={},n("next"),n("throw",function(i){throw i}),n("return"),t[Symbol.iterator]=function(){return this},t;function n(i,o){t[i]=r[i]?function(s){return(e=!e)?{value:nt(r[i](s)),done:!1}:o?o(s):s}:o}}function mo(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=r[Symbol.asyncIterator],e;return t?t.call(r):(r=typeof wn=="function"?wn(r):r[Symbol.iterator](),e={},n("next"),n("throw"),n("return"),e[Symbol.asyncIterator]=function(){return this},e);function n(o){e[o]=r[o]&&function(s){return new Promise(function(c,p){s=r[o](s),i(c,p,s.done,s.value)})}}function i(o,s,c,p){Promise.resolve(p).then(function(u){o({value:u,done:c})},s)}}function go(r,t){return Object.defineProperty?Object.defineProperty(r,"raw",{value:t}):r.raw=t,r}function yo(r){if(r&&r.__esModule)return r;var t={};if(r!=null)for(var e in r)e!=="default"&&Object.prototype.hasOwnProperty.call(r,e)&&vn(t,r,e);return ca(t,r),t}function bo(r){return r&&r.__esModule?r:{default:r}}function wo(r,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?r!==t||!n:!t.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(r):n?n.value:t.get(r)}function vo(r,t,e,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?r!==t||!i:!t.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,e):i?i.value=e:t.set(r,e),e}function So(r,t){if(t===null||typeof t!="object"&&typeof t!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof r=="function"?t===r:r.has(t)}function xo(r,t,e){if(t!=null){if(typeof t!="object"&&typeof t!="function")throw new TypeError("Object expected.");var n;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");n=t[Symbol.asyncDispose]}if(n===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");n=t[Symbol.dispose]}if(typeof n!="function")throw new TypeError("Object not disposable.");r.stack.push({value:t,dispose:n,async:e})}else e&&r.stack.push({async:!0});return t}function Oo(r){function t(n){r.error=r.hasError?new la(n,r.error,"An error was suppressed during disposal."):n,r.hasError=!0}function e(){for(;r.stack.length;){var n=r.stack.pop();try{var i=n.dispose&&n.dispose.call(n.value);if(n.async)return Promise.resolve(i).then(e,function(o){return t(o),e()})}catch(o){t(o)}}if(r.hasError)throw r.error}return e()}var _r,bn,vn,ca,la,da,qe=zo(()=>{_r=function(r,t){return _r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,n){e.__proto__=n}||function(e,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(e[i]=n[i])},_r(r,t)};bn=function(){return bn=Object.assign||function(t){for(var e,n=1,i=arguments.length;n<i;n++){e=arguments[n];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])}return t},bn.apply(this,arguments)};vn=Object.create?function(r,t,e,n){n===void 0&&(n=e);var i=Object.getOwnPropertyDescriptor(t,e);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[e]}}),Object.defineProperty(r,n,i)}:function(r,t,e,n){n===void 0&&(n=e),r[n]=t[e]};ca=Object.create?function(r,t){Object.defineProperty(r,"default",{enumerable:!0,value:t})}:function(r,t){r.default=t};la=typeof SuppressedError=="function"?SuppressedError:function(r,t,e){var n=new Error(e);return n.name="SuppressedError",n.error=r,n.suppressed=t,n};da={__extends:to,__assign:bn,__rest:no,__decorate:ro,__param:io,__metadata:oo,__awaiter:so,__generator:ao,__createBinding:vn,__exportStar:co,__values:wn,__read:Pr,__spread:lo,__spreadArrays:uo,__spreadArray:fo,__await:nt,__asyncGenerator:po,__asyncDelegator:ho,__asyncValues:mo,__makeTemplateObject:go,__importStar:yo,__importDefault:bo,__classPrivateFieldGet:wo,__classPrivateFieldSet:vo,__classPrivateFieldIn:So,__addDisposableResource:xo,__disposeResources:Oo}});var Do=oe(Io=>{"use strict";Object.defineProperty(Io,"__esModule",{value:!0})});var Tr=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var Eo=(qe(),Je(ze));function Co(r,t,e){try{return r(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}}De.eventHandlerSafeInvoke=Co;function Ar(r,t,e){return(0,Eo.__awaiter)(this,void 0,void 0,function*(){try{return yield r(t,e),{succeeded:!0}}catch(n){return{error:n,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Ar;function ua(r,t,e,n){for(let i of r){let{succeeded:o,error:s}=Co(i,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=ua;function fa(r,t,e,n){return(0,Eo.__awaiter)(this,void 0,void 0,function*(){if(n?.parallelize===!1)for(let i of r){let{succeeded:o,error:s}=yield Ar(i,t,e);if(!o&&n?.swallowExceptions!==!0)throw s}else{let i=[];for(let o of r)i.push(Ar(o,t,e).then(({succeeded:s,error:c})=>{if(!s&&n?.swallowExceptions!==!0)throw c}));yield Promise.all(i)}})}De.invokeEventHandlersAsync=fa});var Ao=oe(Sn=>{"use strict";Object.defineProperty(Sn,"__esModule",{value:!0});Sn.TypedEvent=void 0;var pa=(qe(),Je(ze)),_o=Tr(),Po={swallowExceptions:!1,parallelize:!0},Rr=class{constructor(){this._handlers=[]}attach(t){this._handlers.push(t)}detach(t){this.tryRemoveHandler(t)}invoke(t,e,n=Po){(0,_o.invokeEventHandlers)(this._handlers,t,e,n)}invokeAsync(t,e,n=Po){return(0,pa.__awaiter)(this,void 0,void 0,function*(){yield(0,_o.invokeEventHandlersAsync)(this._handlers,t,e,n)})}tryRemoveHandler(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}};Sn.TypedEvent=Rr});var kr=oe(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});var ha=(qe(),Je(ze));(0,ha.__exportStar)(Ao(),Fr)});var To=oe(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.FinalizationRegistryMissingError=void 0;var Br=class extends Error{};xn.FinalizationRegistryMissingError=Br});var jr=oe(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.WeakHandlerHolder=void 0;var ma=To(),Mr=class{constructor(t){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(t)}catch(e){throw e.name==="FinalizationRegistry"?new ma.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(t,e){let n=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:t,handlerRef:n},n),this._refs.push(n),n}releaseWeakHandler(t){let n=this._refs.find(i=>i?.deref()===t)||new WeakRef(t);return this._finalizationRegistry.unregister(n),n}unregisterRef(t){this._finalizationRegistry.unregister(t)}};On.WeakHandlerHolder=Mr});var Ro=oe(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.WeakEvent=void 0;var Lr=(qe(),Je(ze)),ga=kr(),ya=jr(),Nr=Tr(),ba={swallowExceptions:!1,parallelize:!0},Vr=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ga.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ya.WeakHandlerHolder(t=>{this.onHandlerFinalizer(t)})}invoke(t,e,n){for(let i of this._handlers){let o=i?.deref();if(o){let{succeeded:s,error:c}=(0,Nr.eventHandlerSafeInvoke)(o,t,e);if(!s&&n?.swallowExceptions!==!0)throw c}else this.releaseHandler(i)}}invokeAsync(t,e,n=ba){return(0,Lr.__awaiter)(this,void 0,void 0,function*(){n?.parallelize===!1?yield this.sequentialInvokeAsync(t,e,n):yield this.parallelInvokeAsync(t,e,n)})}sequentialInvokeAsync(t,e,n){return(0,Lr.__awaiter)(this,void 0,void 0,function*(){for(let i of this._handlers){let o=i?.deref();if(o){let{succeeded:s,error:c}=yield(0,Nr.eventHandlerSafeInvokeAsync)(o,t,e);if(!s&&n.swallowExceptions!==!0)throw c}else this.releaseHandler(i)}})}parallelInvokeAsync(t,e,n){return(0,Lr.__awaiter)(this,void 0,void 0,function*(){let i=[];for(let o of this._handlers){let s=o?.deref();s?i.push((0,Nr.eventHandlerSafeInvokeAsync)(s,t,e).then(({succeeded:c,error:p})=>{if(!c&&n.swallowExceptions!==!0)throw p})):this.releaseHandler(o)}yield Promise.all(i)})}attach(t){this._handlers.push(this._refHolder.getWeakHandler(this,t))}detach(t){let e=this._refHolder.releaseWeakHandler(t);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(t){this.tryRemoveHandlerRef(t?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,t,{swallowExceptions:!0})}tryRemoveHandlerRef(t){let e=this._handlers.findIndex(n=>n===t);e>=0&&this._handlers.splice(e,1)}releaseHandler(t){this._refHolder.unregisterRef(t),this.tryRemoveHandlerRef(t)}};In.WeakEvent=Vr});var ko=oe(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});var Fo=(qe(),Je(ze));(0,Fo.__exportStar)(jr(),Dn);(0,Fo.__exportStar)(Ro(),Dn)});var Bo=oe(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});var Ur=(qe(),Je(ze));(0,Ur.__exportStar)(Do(),It);(0,Ur.__exportStar)(kr(),It);(0,Ur.__exportStar)(ko(),It)});var Hr={};Gr(Hr,{Client:()=>He,ClientDescriptor:()=>$n,Entity:()=>ue,EntityFile:()=>de,MigrationPathError:()=>Ze,ServerSync:()=>it,Storage:()=>He,StorageDescriptor:()=>$n,collection:()=>yr,createDefaultMigration:()=>br,createMigration:()=>wr,migrate:()=>Qt,schema:()=>gt});var hi=Qe(at(),1),Bt=4,lt=36;function di(r){return r.toString(lt).padStart(Bt,"0")}function Go(r){return r.toString().padStart(6,"0")}var Tt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Xo()};this.zeroCounter=0;this.now=t=>(this.latest=fi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=fi(this.latest),Go(t)+es(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(Bt);this.latest=Zo(this.latest,mi(e))};this.get=(t,e)=>di(t)+ui(e);this.zero=t=>di(t)+ui({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=Zn}},Rt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},Ft=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Yn=4,Gn=7,kt=60*1e3,ct=9;function Xo(){return hi.default.slug().padStart(Gn,"0").slice(0,Gn)}function ui(r){let t=new Date(r.time).getTime().toString(lt).padStart(ct,"0"),e=r.counter.toString(lt).padStart(Yn,"0"),n=r.node.padStart(Gn,"0");return`${t}${e}${n}`}function fi(r){let t=Date.now(),e=Math.max(r.time,t),n=r.time===e?r.counter+1:0;if(e-t>kt)throw new Rt(e,t,kt);if(n>65535)throw new Ft;return{time:e,counter:n,node:r.node}}function Zo(r,t){let e=Date.now(),n=Math.max(e,Math.max(r.time,t.time)),i=Math.max(r.counter,t.counter),o;if(r.time===n&&t.time===n?o=i+1:r.time===n?o=r.counter+1:t.time===n?o=t.counter+1:o=0,n-e>kt)throw new Rt(n,e,kt);if(o>65535)throw new Ft;return{time:n,counter:o,node:r.node}}function mi(r){let t=r.slice(0,ct),e=r.slice(ct,ct+Yn),n=r.slice(ct+Yn),i=parseInt(t,lt),o=parseInt(e,lt);if(isNaN(i)||isNaN(o))throw new Error("invalid clock format");return{time:i,counter:o,node:n}}function es(r){let t=new Date(r.time).toISOString(),e=r.counter.toString(16).toUpperCase().padStart(4,"0"),n=r.node.padStart(16,"0");return`${t}-${e}-${n}`}function pi(r){return parseInt(r.slice(0,Bt),36)}function Xn(r,t){return pi(r)-pi(t)}function Zn(r){return mi(r.slice(Bt)).time}function be(r){return r&&r["@@type"]==="file"}function Mt(r){return{"@@type":"file",id:r}}var jt,ts=new Uint8Array(16);function er(){if(!jt&&(jt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!jt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return jt(ts)}var gi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function ns(r){return typeof r=="string"&&gi.test(r)}var yi=ns;var ee=[];for(Lt=0;Lt<256;++Lt)ee.push((Lt+256).toString(16).substr(1));var Lt;function rs(r){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[r[t+0]]+ee[r[t+1]]+ee[r[t+2]]+ee[r[t+3]]+"-"+ee[r[t+4]]+ee[r[t+5]]+"-"+ee[r[t+6]]+ee[r[t+7]]+"-"+ee[r[t+8]]+ee[r[t+9]]+"-"+ee[r[t+10]]+ee[r[t+11]]+ee[r[t+12]]+ee[r[t+13]]+ee[r[t+14]]+ee[r[t+15]]).toLowerCase();if(!yi(e))throw TypeError("Stringified UUID is invalid");return e}var bi=rs;function is(r,t,e){r=r||{};var n=r.random||(r.rng||er)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var i=0;i<16;++i)t[e+i]=n[i];return t}return bi(n)}var dt=is;function Q(r){return Se(r)||be(r)}function Ye(r,t){return r===t?!0:!(!Q(r)||!Q(t)||r["@@type"]!==t["@@type"]||r.id!==t.id)}var xi=Qe(Si(),1);function os(r,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function ut(r){return JSON.stringify(r,os)}function ae(r,t=!0){if(U(r)||Array.isArray(r)){let e=pe(r),n;if(Array.isArray(r))n=r.map(i=>ae(i,t));else{n={};for(let[i,o]of Object.entries(r))n[i]=ae(o,t)}return t&&e&&K(n,e),n}return r}function Te(r){return(0,xi.default)(r)}function U(r){return r&&typeof r=="object"}function Oi(r){for(var t=[],e=[r],n=0;e.length;){var i=e.pop();if(typeof i=="boolean")n+=4;else if(typeof i=="string")n+=i.length*2;else if(typeof i=="number")n+=8;else if(typeof i=="object"&&t.indexOf(i)===-1){t.push(i);for(var o in i)e.push(i[o])}}return n}function L(r,t="assertion failed"){if(!r)throw new Error(t)}function Nt(r=16){return dt().replace("-","").slice(0,r)}function Ii(r,t){for(let e=r.length-1;e>=0;e--)if(t(r[e]))return e;return-1}function Di(r,t){let e;return function(...n){let i=this;clearTimeout(e),e=setTimeout(()=>r.apply(i,n),t)}}var Be="__@@oid_do_not_use",Oe="@@id",ss="/",pt=":",nr=new WeakMap;function ne(r){let t=pe(r);return L(!!t,`Object ${JSON.stringify(r)} does not have an OID assigned to it`),t}function pe(r){if(U(r))return nr.get(r)??r[Oe]??r[Be]}function K(r,t){return L(U(r),`Only objects can be assigned OIDs, received ${JSON.stringify(r)}`),rr(r)&&Kt(r),nr.set(r,t),r}function rr(r){return!!pe(r)}function Kt(r){return nr.delete(r),r}function ir(r){return r===Oe||r===Be}function or(r,t,e){if(rr(r))return ne(r);{let n=xe(t,e);return K(r,n),n}}function Ei(r,t,e){if(rr(r)){let n=ne(r);if(Ce(n,t))return ne(r);{let i=xe(t,e);return K(r,i),i}}else{let n=xe(t,e);return K(r,n),n}}var tr={".":"˙","/":"&slash;",":":":"};function Ci(r){return r.replace(/[/]/g,tr["/"]).replace(/[:]/g,tr[":"]).replace(/[.]/g,tr["."])}function _i(r){return r.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Z(r,t,e){let n=Ci(r)+ss+Ci(t);return e&&(n+=pt+e),n}function xe(r,t=ds){let{collection:e,id:n}=me(r);return Z(e,n,t())}function me(r){let[t,e]=r.split(pt),[n,i,...o]=t.split("/");o.length&&(i+="/"+o.join("/"));let s;return i.includes(".")?s=i.slice(0,i.indexOf(".")):s=i,{collection:_i(n),id:_i(s),subId:e}}function Ge(r,t){let e=ne(r);if(Array.isArray(r)){let n;for(let i=0;i<r.length;i++)n=r[i],U(n)&&!Q(n)&&(Ei(n,e,t),Ge(n,t))}else if(U(r)&&!Q(r))for(let n of Object.keys(r))U(r[n])&&!Q(r[n])&&(Ei(r[n],e,t),Ge(r[n],t))}function as(r){if(U(r))return r[Oe]||r[Be]}function cs(r){return U(r)&&(delete r[Be],delete r[Oe]),r}function ls(r){let t=as(r);t&&K(r,t)}function ft(r){if(ls(r),cs(r),Array.isArray(r))for(let t=0;t<r.length;t++)ft(r[t]);else if(U(r))for(let t of Object.keys(r))ft(r[t])}function Vt(r){if(Kt(r),Array.isArray(r))for(let t=0;t<r.length;t++)Vt(r[t]);else if(U(r))for(let t of Object.keys(r))Vt(r[t])}function ds(){return dt().slice(0,8)}function he(r){return{"@@type":"ref",id:r}}function Ut(r,t=new Map){if(Array.isArray(r)){let e=ne(r),n=K([],e);for(let i=0;i<r.length;i++){let o=r[i];if(U(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o)){n[i]=o;continue}else{let s=ne(o);n[i]=he(s),Ut(o,t)}}else n[i]=o}t.set(e,n)}else if(U(r)&&!Q(r)){let e=ne(r),n=K({},e);for(let i of Object.keys(r)){let o=r[i];if(U(o)){if(Se(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(be(o))n[i]=o;else{let s=ne(o);n[i]=he(s),Ut(o,t)}}else n[i]=o}t.set(e,n)}else Q(r);return t}function $(r){return r.split(".")[0].split(pt)[0]}function sr(r){let t=$(r),e=xe(t,()=>"\uFFFF");return[`${t}${pt}`,e]}function ar(r){let t=$(r);return[`${t}.`,`${t}.\uFFFF`]}function Ce(r,t){return $(r)===$(t)}function us(r){let{collection:t,id:e,subId:n}=me(r);return Z(t,e,n)}var fs=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function ps(r){return r.replaceAll(fs,t=>{let e=t.slice(1,t.length-1);return`"${us(e)}"`})}function cr(r){return JSON.parse(ps(JSON.stringify(r)))}function Pi(r){return!r.includes(pt)}function Se(r){return r&&typeof r=="object"&&r["@@type"]==="ref"}function lr(r){return U(r)&&!Q(r)}function hs(r,t){return r===t?!0:Q(r)&&Q(t)?Ye(r,t):!1}function ht(r,t,e,n,i=[],o={}){let s=ne(r);function c(p,u,m){if(!lr(u))hs(u,m)||i.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:u}});else{let S=pe(m),g=pe(u);g&&!Ce(s,g)?(u=ae(u,!1),g=xe(s,n),K(u,g)):o.mergeUnknownObjects?!g&&S?(K(u,S),g=S):g=or(u,s,n):g=or(u,s,n),L(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ce(s,g),`Error: value OID ${g} is not related to parent OID ${s}. This is a bug in Verdant.`),m===void 0||g!==S?(Re(u,g,e,n,i),i.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:he(g)}}),S!==void 0&&i.push({oid:S,timestamp:e(),data:{op:"delete"}})):ht(m,u,e,n,i,o)}}if(Array.isArray(r)&&Array.isArray(t)){for(let u=0;u<t.length;u++){let m=t[u],S=r[u];c(u,m,S)}let p=r.length-t.length;if(p>0){for(let u=t.length;u<r.length;u++){let m=r[u],S=pe(m);S&&i.push({oid:S,timestamp:e(),data:{op:"delete"}})}i.push({oid:s,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(r)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(lr(r)&&lr(t)){let p=new Set(Object.keys(r));for(let[u,m]of Object.entries(t)){if(m===void 0&&o.defaultUndefined||(p.delete(u),ir(u)))continue;let S=r[u];c(u,m,S)}if(!o.defaultUndefined)for(let u of p)ir(u)||i.push({oid:s,timestamp:e(),data:{op:"remove",name:u}})}}return i}function Re(r,t,e,n,i=[]){K(r,t),Ge(r,n);let o=Ut(r);for(let s of o.keys()){let c=o.get(s);i.push({oid:s,timestamp:e(),data:{op:"initialize",value:Kt(c)}})}return i}function mt(r){let t={};for(let e of r)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Ti(r){let t={};for(let e of r){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Ri(r){let t={};for(let e of r){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Me(r){return Array.isArray(r)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(r)}. This suggests your data is changing from a list to an object over time. (OID: ${pe(r)})`),!1)}function je(r,t,e){if(r==null&&t.op!=="initialize")return r;let n=r,i,o;function s(c){e&&Q(c)&&e.push(c)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Me(r)&&r.push(t.value);break;case"list-delete":Me(r)&&(s(r[t.index]),r.splice(t.index,t.count));break;case"list-move-by-index":Me(r)&&(o=r.splice(t.from,1),r.splice(t.to,0,o[0]));break;case"list-remove":if(Me(r))do{let c=t.value;t.only==="last"?Se(c)?i=Ii(r,p=>p.id===c.id):i=r.lastIndexOf(c):Se(c)?i=r.findIndex(p=>p.id===c.id):i=r.indexOf(c),i!==-1&&(s(r[i]),r.splice(i,1))}while(!t.only&&i!==-1);break;case"list-add":Me(r)&&(r.some(p=>Se(p)&&Se(t.value)?p.id===t.value.id:p===t.value)||r.push(t.value));break;case"list-move-by-ref":Me(r)&&(i=r.findIndex(c=>Ye(c,t.value)),o=r.splice(i,1),r.splice(t.index,0,o[0]));break;case"list-insert":if(Me(r)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?r.splice(t.index,0,t.value):r.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(r)?r.forEach(s):U(r)&&Object.values(r||{}).forEach(s);return;case"initialize":return ae(t.value);case"touch":return r;default:throw new Error(`Unsupported patch operation: ${t.op}`)}return r}function $t(r,t,e=[]){if(Array.isArray(r))for(let n=0;n<r.length;n++){let i=r[n];r[n]=Ai(i,t,e),U(r[n])&&$t(r[n],t,e)}else if(!be(r)){if(U(r)){L(pe(r),`Object ${JSON.stringify(r)} must have an oid`);for(let n of Object.keys(r))r[n]=Ai(r[n],t,e),U(r[n])&&$t(r[n],t,e)}}return e}function Ai(r,t,e){if(Se(r)){e.push(r.id);let n=t.get(r.id);return L(!!n,`No value was found in object map for ${r.id}`),K(n,r.id)}else return r}function we(r){return r.type==="any"?!0:r.type==="map"?!1:r.nullable}function _e(r){return r?r.type==="map"||r.type==="array"?!0:r.type==="file"?!1:r.default!==void 0:!1}function ur(r){if(!(!r||!_e(r)))return r.type==="file"?we(r)?null:void 0:r.type==="map"?{}:r.type==="array"?we(r)?null:[]:r.type==="object"?we(r)?null:void 0:typeof r.default=="function"?r.default():r.default}function zt(r){return r.type==="map"||r.type==="object"||r.type==="array"||r.type==="file"||r.type==="any"?!1:r.indexed}function Pe(r,t){for(let[e,n]of Object.entries(r.fields)){let i=fr(n);(i!==void 0&&t[e]===void 0||!we(n)&&t[e]===null)&&(t[e]=i),t[e]&&Le(t[e],n)}return t}function Le(r,t){if(r==null)return r;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(r[e]===void 0){let i=fr(n);i!==void 0&&(r[e]=i)}Le(r[e],n)}else if(t.type==="array")for(let e of r)Le(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(r))e===Oe||e===Be||Le(n,t.values)}function fr(r){if(r.type==="string"||r.type==="number"||r.type==="boolean"||r.type==="any"){if(r.default&&typeof r.default=="function")return r.default();if(r.default!==void 0)return JSON.parse(JSON.stringify(r.default))}if(r.type==="array")return[];if(r.type==="map")return{};if(r.type!=="any"&&r.nullable)return null;if(r.type==="object"&&r.default){let t=typeof r.default=="function"?r.default():JSON.parse(JSON.stringify(r.default));for(let[e,n]of Object.entries(r.properties))t[e]===void 0&&(t[e]=fr(n));return t}}function pr(r,t){for(let[e,n]of Object.entries(t))e===Oe||e===Be||(r.fields[e]?dr(n,r.fields[e]):delete t[e]);return t}function dr(r,t){if(U(r)&&t.type==="object")for(let[e,n]of Object.entries(r))t.properties[e]?dr(n,t.properties[e]):delete r[e];else if(Array.isArray(r)&&t.type==="array")for(let e of r)dr(e,t.items)}var ms=r=>({type:"object",...r}),gs=r=>({type:"array",...r}),ys=r=>({type:"string",...r}),bs=r=>({type:"number",...r}),ws=r=>({type:"boolean",...r}),vs=r=>({type:"any",...r}),Ss=r=>({type:"map",...r}),xs=r=>({type:"file",...r}),Fi={object:ms,array:gs,string:ys,number:bs,boolean:ws,any:vs,map:Ss,file:xs};var Mi=Qe(at(),1);function hr(r){return r.equals!==void 0}function mr(r){return r.gte!==void 0||r.lte!==void 0||r.gt!==void 0||r.lt!==void 0}function Os(r){return!!r.match}function gr(r){return r.startsWith!==void 0}function ki(r){return!mr(r)&&!hr(r)&&!Os(r)&&!gr(r)&&r.order}function Bi(r,t){for(let[e,n]of Object.entries(t))if(e!==Oe){if(!r[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(n){let i=Fe({field:r[e],value:n,fieldPath:[e]});if(i)return i}}}function Fe({field:r,value:t,fieldPath:e=[],depth:n,requireDefaults:i}){if(!(n!==void 0&&n<=0)&&!(we(r)&&t===null)){if(t===null&&(i||!_e(r)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ae(e)}`};if(r.type==="object"){if(!U(t))return{type:"invalid-type",fieldPath:e,message:`Expected object${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(r.properties))o!==Oe&&t[o]&&Fe({field:s,value:t[o],fieldPath:[...e,o],depth:n!==void 0?n-1:void 0});for(let o of Object.keys(t))if(!r.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ae(e)}`}}else if(r.type==="array"){if(!Array.isArray(t))return t===null&&r.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};for(let o of t)Fe({field:r.items,value:o,fieldPath:[...e,"[]"],depth:n!==void 0?n-1:void 0})}else if(r.type==="map"){if(!U(t))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ae(e)}, got ${t}`};for(let[o,s]of Object.entries(t))Fe({field:r.values,value:s,fieldPath:[...e,o],depth:n!==void 0?n-1:void 0})}else if(r.type==="string"){if(typeof t!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`};if(r.options&&!r.options.includes(t))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${r.options.join(", ")} for field ${Ae(e)}, got ${t}`}}else if(r.type==="boolean"){if(typeof t!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else if(r.type==="number"){if(typeof t!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${r.nullable?" or null":""} for field ${Ae(e)}, got ${t}`}}else r.type}}function Ae(r){return r.length===0?"root":r.join(".")}function Ne(r,t){return r.type==="object"?r.properties[t]:r.type==="array"?r.items:r.type==="map"?r.values:r.type==="any"?r:"type"in r?null:r[t]??null}function yr({synthetics:r,indexes:t,...e}){let n={...r,...t};for(let[i,o]of Object.entries(e.fields))zt(o)&&(n[i]={field:i});return{...e,indexes:n}}function gt(r){return r}gt.collection=yr;gt.fields=Fi;gt.generated={id:Mi.default};var qt="\uFFFFFE",Is="\0",Ds="\uFFFFFF";function ce(...r){let t=Es(r);return t.length===1?t[0]:t}function Ve(...r){return r.join(qt)+`${Ds}`}function Ue(...r){return r.join(qt)+`${qt}${Is}`}function Es(r){let t=[[]];for(let e of r)if(Array.isArray(e)){let n=[];for(let i of t)for(let o of e)n.push(i.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(qt))))}function Cs(r){return!!r.field}function _s(r,t){let e={};for(let[n,i]of Object.entries(r.indexes||{})){let o=i;Cs(o)?e[n]=ve(t[o.field]):e[n]=ve(o.compute(t))}return e}function Ps(r,t){return Object.entries(r.compounds||{}).reduce((e,[n,i])=>(e[n]=ce(...i.of.map(o=>t[o])),e),{})}function As(r,t){return Object.entries(r.fields).reduce((e,[n,i])=>(zt(i)&&(e[n]=ve(t[n])),e),{})}function Ht(r,t){let e={[r.primaryKey]:t[r.primaryKey],...As(r,t),..._s(r,t)};return Object.assign(e,Ps(r,{...t,...e})),e["@@@snapshot"]=t,e}var Ts="null";function ve(r){if(r===null)return Ts;if(typeof r=="string"||typeof r=="number")return r;if(typeof r=="boolean"||r===null)return`${r}`;if(r===void 0)return"undefined";if(Array.isArray(r))return r.map(ve);throw new Error(`Unsupported index value: ${r}`)}var ji={version:0,collections:{}};function Qt(r,t,e){let n=typeof t=="function",i=n?ji:r,o=n?r:t,s=n?t:e,c=Object.keys(o.collections).filter(v=>i.collections[v]&&ut(i.collections[v])!==ut(o.collections[v])),p=Object.keys(i.collections).filter(v=>!o.collections[v]),u=Object.keys(o.collections).filter(v=>!i.collections[v]),m=new Set;for(let v of c){let I=i.collections[v].fields,x=o.collections[v].fields;Object.keys(x).some(D=>!I[D]?.default&&x[D]?.default)&&m.add(v),Object.keys(I).some(D=>!x[D])&&m.add(v)}let S={},g={};for(let v of[...c,...u]){let I=Wt(i.collections[v]),x=Wt(o.collections[v]),D=x.filter(b=>!I.find(E=>E.name===b.name)),T=I.filter(b=>!x.find(E=>E.name===b.name));D.length>0&&(S[v]=D,c.includes(v)&&m.add(v)),T.length>0&&(g[v]=T,c.includes(v)&&m.add(v))}let _=(v,I)=>Pe(o.collections[v],I),w=v=>I=>{let x=o.collections[v];return Pe(x,pr(x,I))};return{version:o.version,migrate:async v=>{let I=[];if(await s({migrate:async(x,D)=>{let T=w(x),b=async E=>{let d=await D(E);return K(d,ne(E)),T(d)};await v.migrate(x,b),I.push(x),m.delete(x)},identity:x=>x,withDefaults:_,info:{changedCollections:c,addedCollections:u,removedCollections:p},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",m);for(let D of m)await v.migrate(D,w(D)),I.push(D);let x=c.filter(D=>!I.includes(D));x.length>0&&console.error(`Unmigrated changed collections from version ${i.version} to version ${o.version}:`,x)}},removedCollections:p,addedIndexes:S,removedIndexes:g,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:u,oldCollections:Object.keys(i.collections),oldSchema:i,newSchema:o}}function Wt(r){return r?[...Object.keys(r.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(r.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(r.compounds||{}).map(t=>({name:t,multiEntry:r.compounds[t].of.some(e=>(r.fields[e]||r.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function br(r,t){return Qt(t?r:{version:0,collections:{}},t||r,async({migrate:n,info:i})=>{if((t||r).version!==1)for(let o of i.changedCollections)await n(o,s=>s)})}function wr(r,t,e){let n=typeof t=="function"||t===void 0,i=n?ji:r,o=n?r:t,s=n?t:e;L(i,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:c,addedCollections:p,removedCollections:u,addedIndexes:m,removedIndexes:S,autoMigratedCollections:g,autoMigration:_}=Rs(i,o);return{version:o.version,migrate:async w=>{let v=[];if(await s?.({migrate:async(x,D)=>{let T=_(x),b=async E=>{let d=await D(E);K(d,ne(E));let h=T(d),l=Bi(o.collections[x].fields,h);return h};await w.migrate(x,b),v.push(x),g.delete(x)},info:{changedCollections:c,addedCollections:p,removedCollections:u},queries:w.queries,mutations:w.mutations}),o.version>1){w.log("debug","auto-migrating collections with new defaults",g);for(let D of g)await w.migrate(D,_(D)),v.push(D);for(let D of u)await w.deleteCollection(D);let x=c.filter(D=>!v.includes(D));x.length>0&&console.error(`Unmigrated changed collections from version ${i.version} to version ${o.version}:`,x)}},removedCollections:u,addedIndexes:m,removedIndexes:S,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:p,oldCollections:Object.keys(i.collections),oldSchema:i,newSchema:o}}function Rs(r,t){let e=Object.keys(t.collections).filter(m=>r.collections[m]&&ut(r.collections[m])!==ut(t.collections[m])),n=Object.keys(r.collections).filter(m=>!t.collections[m]),i=Object.keys(t.collections).filter(m=>!r.collections[m]),o=new Set;for(let m of e){let S=r.collections[m].fields,g=t.collections[m].fields;Object.keys(g).some(_=>!_e(S[_])&&_e(g[_]))&&o.add(m),Object.keys(S).some(_=>!g[_])&&o.add(m)}let s={},c={};for(let m of[...e,...i]){let S=Wt(r.collections[m]),g=Wt(t.collections[m]),_=g.filter(v=>!S.find(I=>I.name===v.name)),w=S.filter(v=>!g.find(I=>I.name===v.name));_.length>0&&(s[m]=_,e.includes(m)&&o.add(m)),w.length>0&&(c[m]=w,e.includes(m)&&o.add(m))}return{changedCollections:e,addedCollections:i,removedCollections:n,addedIndexes:s,removedIndexes:c,autoMigratedCollections:o,withDefaults:(m,S)=>Pe(t.collections[m],S),autoMigration:m=>S=>{let g=t.collections[m];return Pe(g,pr(g,S))}}}var Jt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!U(t)||Q(t);this.createDiff=(t,e,n={})=>ht(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>Re(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let i=xe(t,this.createSubId);return[...Re(n,i,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:he(i),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=xe(t,this.createSubId);return[...Re(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:he(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:he(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let i=xe(t,this.createSubId);return[...Re(n,i,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:he(i),index:e}}]}};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var V=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.disposed=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=Nt(),i=this.subscribers[t];return i||(i=this.subscribers[t]={}),i[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{this._disabled=!0,this.disposed=!0;let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Li(r,t,e,n){if(t==null)return[{oid:r,timestamp:n(),data:{op:"delete"}}];let i=ae(t),o=[];for(let s of e){let c=Fs(r,i,s,n);o.unshift(...c),je(i,s.data)}return o}function Fs(r,t,e,n){let i=e.data;switch(i.op){case"set":case"remove":return[{oid:r,timestamp:n(),data:{op:"set",name:i.name,value:t[i.name]}}];case"list-insert":return[{oid:r,timestamp:n(),data:{op:"list-delete",index:i.index,count:1}}];case"list-delete":return[{oid:r,timestamp:n(),data:{op:"list-insert",index:i.index,values:t.slice(i.index,i.count)}}];case"list-move-by-ref":return[{oid:r,timestamp:n(),data:{op:"list-move-by-ref",value:i.value,index:t.indexOf(i.value)}}];case"list-move-by-index":return[{oid:r,timestamp:n(),data:{op:"list-move-by-index",from:i.to,to:i.from}}];case"delete":return[{oid:r,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:r,timestamp:n(),data:{op:"list-remove",value:i.value,only:"last"}}];case"list-remove":if(i.only==="last"){let o=t.lastIndexOf(i.value);return[{oid:r,timestamp:n(),data:{op:"list-insert",index:o,values:[i.value]}}]}else if(i.only==="first"){let o=t.indexOf(i.value);return[{oid:r,timestamp:n(),data:{op:"list-insert",index:o,values:[i.value]}}]}else{let o=[],s=t.indexOf(i.value);for(;s!==-1;)o.push(s),s=t.indexOf(i.value,s+1);return o.map(c=>({oid:r,timestamp:n(),data:{op:"list-insert",index:c,value:i.value}}))}case"list-add":return[{oid:r,timestamp:n(),data:{op:"list-remove",value:i.value,only:"last"}}];case"initialize":return[{oid:r,timestamp:n(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${i.op}`)}}var Xe=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush());this.getSize=t=>{let e=this.batches.get(t);return e?e.items.length:0}}add({key:t,userData:e,items:n,max:i,timeout:o}){let s=this.batches.get(t);return s||(s=new vr({max:i||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:i,timeout:o,userData:e}),s}},vr=class{constructor({max:t,startedAt:e,timeout:n,userData:i,flusher:o,key:s}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:i})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),i&&(this.userData=i);let o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=i,this.flusher=o,this.key=s}};function Ni(r,t){let e,n;return(...i)=>{let o=t();return e&&e.length===o.length&&e.every((s,c)=>s===o[c])||(e=[...o],n=r(...i)),n}}var Sr=(i=>(i[i.Unexpected=5e3]="Unexpected",i[i.NoToken=4010]="NoToken",i[i.InvalidToken=4011]="InvalidToken",i[i.TokenExpired=4012]="TokenExpired",i))(Sr||{}),Vi=class extends Error{constructor(e,n,i){super(i??`Verdant error: ${e}`,{cause:n});this.code=e;this.toResponse=()=>JSON.stringify({code:this.code})}static{this.Code=Sr}get httpStatus(){let e=Math.floor(this.code/10);return e<600?e:500}};function Ui(r){return typeof r=="object"&&"code"in r&&typeof r.code=="number"}function le(r){return r instanceof Error&&r.name==="AbortError"}function J(r){return new Promise((t,e)=>{r.onsuccess=()=>{t(r.result)},r.onerror=()=>{r.error&&le(r.error)?t(r.result):e(r.error)}})}function yt(r,t){return new Promise((e,n)=>{let i=r.transaction([t],"readonly"),s=i.objectStore(t).openCursor(),c=0,p=0;s.onsuccess=function(u){let m=s.result;m&&(c++,p=p+Oi(m.value),m.continue())},s.onerror=function(u){s.error&&le(s.error)?e({count:c,size:p}):n(s.error)},i.oncomplete=function(u){e({count:c,size:p})},i.onabort=function(u){n(u)},i.onerror=function(u){n(u)}})}function Ki(r,t){let e=r.transaction(t,"readonly"),n=t.map(i=>{let o=e.objectStore(i);return J(o.getAll())});return Promise.all(n)}async function Ke(r){r.close(),await new Promise((t,e)=>{t()})}async function Yt(r,t=window.indexedDB){let e=t.deleteDatabase([r,"meta"].join("_")),n=t.deleteDatabase([r,"collections"].join("_"));await Promise.all([new Promise((i,o)=>{e.onsuccess=i,e.onerror=o}),new Promise((i,o)=>{n.onsuccess=i,n.onerror=o})]),window.location.reload()}function $i(r,t=window.indexedDB){return J(t.deleteDatabase(r))}async function zi(r=window.indexedDB){return r.databases()}function Gt(r,t,e,n,i){let o=r.transaction(t,e);if(n){let s=()=>{i?.("debug","aborting transaction");try{o.abort()}catch(c){i?.("debug","aborting transaction failed",c)}};n.addEventListener("abort",s),o.addEventListener("error",()=>{n.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{n.removeEventListener("abort",s)})}return o}var Ie=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};var se=class extends Ie{constructor(e,{log:n}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,n)=>{let i=Gt(this.db,e,n?.mode||"readonly",n?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",i.abort),i.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",i.abort)}),i.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",i.abort)}),i};this.run=async(e,n,i)=>{if(this.disposed||i?.transaction?.error)return Promise.resolve(void 0);let s=(i?.transaction||this.createTransaction([e],i)).objectStore(e),c=n(s);return J(c)};this.runAll=async(e,n,i)=>{if(this.disposed||i?.transaction?.error)return Promise.resolve([]);let s=(i?.transaction||this.createTransaction([e],i)).objectStore(e),c=n(s);return Promise.all(c.map(J))};this.iterate=async(e,n,i,o)=>{let c=(o?.transaction||this.createTransaction([e],o)).objectStore(e),p=n(c);return Array.isArray(p)?Promise.all(p.map(u=>new Promise((m,S)=>{u.onsuccess=()=>{let g=u.result;g?(i(g.value,c),g.continue()):m()},u.onerror=()=>{u.error&&le(u.error)?m():S(u.error)}}))).then(()=>{}):new Promise((u,m)=>{p.onsuccess=()=>{let S=p.result;S?(i(S.value,c),S.continue()):u()},p.onerror=()=>{p.error&&le(p.error)?u():m(p.error)}})};this.clear=e=>this.run(e,n=>n.clear(),{mode:"readwrite"});this.log=n,this.addDispose(()=>{this.globalAbortController.abort()})}};var Xt=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var Zt=class extends se{constructor(e,n){super(e,n);this.getAllForDocument=async(e,{mode:n="readonly",transaction:i}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:i}),o};this.iterateOverAllForDocument=async(e,n,{mode:i="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let c=$(e),[p,u]=sr(e),[m,S]=ar(e);return[s.openCursor(IDBKeyRange.only(c)),s.openCursor(IDBKeyRange.bound(p,u,!1,!1)),s.openCursor(IDBKeyRange.bound(m,S,!1,!1))]},n,{mode:i,transaction:o});this.iterateOverAllForCollection=async(e,n,{mode:i="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,{mode:i,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let c=$(s),[p,u]=sr(s),[m,S]=ar(s);return[o.get(c),o.getAll(IDBKeyRange.bound(p,u,!1,!1)),o.getAll(IDBKeyRange.bound(m,S,!1,!1))]}),{mode:n})).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",i=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return i.index("timestamp").getAll(o)},{mode:n});this.get=async(e,{transaction:n,mode:i="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:i,transaction:n});this.set=async(e,{transaction:n}={})=>{await this.run("baselines",i=>i.put(e),{mode:"readwrite",transaction:n})};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",i=>e.map(o=>i.put(o)),{mode:"readwrite",transaction:n})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",i=>i.delete(e),{mode:"readwrite",transaction:n})}}};var qi=Qe(at(),1);var en=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",i=>i.get("localReplicaInfo"),{transaction:e});return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,qi.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let i=await this.get({transaction:n});Object.assign(i,e),await this.run("info",o=>o.put(i),{mode:"readwrite"}),this.cached=i};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),{mode:"readwrite"})}}};var tn=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(i=>({...i,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,i=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(c=>{i.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(c=>{i.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add($(c.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:i,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var nn=class extends se{constructor(e,n){super(e,n);this.iterateOverAllOperationsForDocument=async(e,n,{to:i,from:o,after:s,mode:c="readonly",transaction:p}={})=>{let m=(p||this.createTransaction(["operations"],{mode:c})).objectStore("operations"),S=m.index("d_t"),g=o||s,_=g?ce(e,g):Ue(e),w=i?ce(e,i):Ve(e),v=IDBKeyRange.bound(_,w,!!s,!1),I=S.openCursor(v,"next");return new Promise((x,D)=>{let T;I.onsuccess=b=>{let E=I.result;if(E){let d=E.value;L(d.oid.startsWith(e)),L(T===void 0||T<=d.timestamp,`expected ${T} <= ${d.timestamp}`),n(d,m),T=d.timestamp,E.continue()}else x()},I.onerror=b=>{if(le(I.error)){x();return}else D(I.error)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:i,to:o,mode:s,transaction:c})=>{let u=(c||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),m=i?ce(e,i):Ue(e),S=o?ce(e,o):Ve(e),g=IDBKeyRange.bound(m,S,!!i,!1),_=u.openCursor(g,"next");return new Promise((w,v)=>{let I;_.onsuccess=x=>{let D=_.result;if(D){let T=D.value;L(T.oid.startsWith(e)),L(I===void 0||I<=T.timestamp,`expected ${I} <= ${T.timestamp}`),n(T,u),I=T.timestamp,D.continue()}else w()},_.onerror=x=>{le(_.error)?w():v(_.error)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:i,to:o,mode:s,transaction:c})=>{let p=c||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",u=>u.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,{mode:s,transaction:p})};this.iterateOverAllLocalOperations=async(e,{before:n,after:i,mode:o="readonly",transaction:s})=>{let p=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),u=p.index("l_t"),m=i?ce(!0,i):Ue(!0),S=n?ce(!0,n):Ve(!0),g=IDBKeyRange.bound(m,S,!!i,!0),_=u.openCursor(g,"next");return new Promise((w,v)=>{let I;_.onsuccess=x=>{let D=_.result;if(D){let T=D.value;L(I===void 0||I<=T.timestamp,`expected ${I} <= ${T.timestamp}`),e(T,p),I=T.timestamp,D.continue()}else w()},_.onerror=x=>{le(_.error)?w():v(_.error)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:i,mode:o,from:s})=>{await this.iterate("operations",c=>{let p=s?Ue(s):void 0,u=n?Ve(n):void 0,m=p&&u?window.IDBKeyRange.bound(p,u,!1,!0):p?window.IDBKeyRange.lowerBound(p,!1):u?window.IDBKeyRange.upperBound(u,!0):void 0;return c.index("timestamp").openCursor(m,"next")},e,{mode:o,transaction:i})};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let i=new Set;return await this.runAll("operations",o=>e.map(s=>(i.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:n}),Array.from(i)};this.reset=()=>this.clear("operations")}};var rn=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let i=this.db.transaction("info","readonly").objectStore("info").get("schema"),o=await J(i);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await J(o)}}};var bt=class extends V{constructor({disableRebasing:e,context:n}){super();this.time=new Tt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,n={})=>Gt(this.db,e,"readwrite",n.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let n=new Set,i=$(e);L(i===e,"Must be root document OID"),n.add(i);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(i,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(i,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,i=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:i}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:i})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let i=$(e);L(i===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(i,{transaction:o}),c=new Map;for(let u of s)u.snapshot&&K(u.snapshot,u.oid),c.set(u.oid,u.snapshot);await this.operations.iterateOverAllOperationsForDocument(i,u=>{let m=c.get(u.oid)||void 0,S=je(m,u.data);S&&K(S,u.oid),c.set(u.oid,S)},{transaction:o,to:n.to||this.now});let p=c.get(i);return p&&$t(p,c),p};this.getDocumentData=async(e,n)=>{let i=this.createTransaction(["baselines","operations"],n),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,c=>{o.push(c)},{transaction:i}),this.operations.iterateOverAllOperationsForDocument(e,c=>{s[c.oid]??=[],s[c.oid].push(c)},{transaction:i})]),{baselines:o,operations:s}};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,n)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,n);let i=await this.messageCreator.createOperation({operations:e});this.emit("message",i),this.tryAutonomousRebase()};this.insertRemoteOperations=async(e,n)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let i=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),n);return this.ack(e[e.length-1].timestamp),i};this.insertRemoteBaselines=async(e,n)=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,n);let i=new Set;return e.forEach(o=>{i.add($(o.oid))}),Array.from(i)};this.insertData=async(e,n)=>{let i=this.createTransaction(["baselines","operations"],n);e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:i}),!n?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:i}):await this.insertRemoteOperations(e.operations,{transaction:i}))};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,i=new Set,o=this.createTransaction(["baselines","operations"]),s=0;if(await this.operations.iterateOverAllOperations(p=>{i.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!i.size||this._closing)return;let c=[];for(let p of i)c.push(await this.rebase(p,n||e,o));this.emit("rebase",c)};this.rebase=async(e,n,i)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=i||this.createTransaction(["operations","baselines"]),c=await this.baselines.get(e,{transaction:s}),p=c?.snapshot||void 0,u=0,m=[];await this.operations.iterateOverAllOperationsForEntity(e,(g,_)=>{(!c||g.timestamp>c.timestamp)&&(p=je(p,g.data,m)),u++,_.delete(g.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let S={oid:e,snapshot:p,timestamp:n};if(S.snapshot?await this.baselines.set(S,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",n,":",p,"and deleted",u,"operations"),m.length){let g=m.filter(be);g.length&&this.emit("filesDeleted",g)}return S};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let i=await this.schema.get();if(i&&n===i.version&&i.version===e.version&&JSON.stringify(i)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
7
7
|
${JSON.stringify(i)}
|
|
8
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,i]=await Vi(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:i,baselines:n,localReplica:o,schema:s}};this.resetFrom=async e=>{let i=this.db.transaction(["baselines","operations","info"],"readwrite");await J(i.objectStore("baselines").clear()),await J(i.objectStore("operations").clear()),await J(i.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:i})};this.stats=async()=>{let e=this.db,n=await mt(e,"operations"),i=await mt(e,"baselines");return{operationsSize:n,baselinesSize:i}};this.context=n,this.schema=new nn(n.metaDb,n.schema.version),this.operations=new tn(this.db,{log:n.log}),this.baselines=new Xt(this.db,{log:n.log}),this.localReplica=new Zt(this.db),this.ackInfo=new Gt(this.db),this.messageCreator=new en(this),this.patchCreator=new Qt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Is=[Ds,Es,Cs,_s,Ps];function rn({indexedDB:r=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((i,o)=>{let s=r.open(`${t}_meta`,n),c=!1;s.onupgradeneeded=async p=>{let u=s.result,m=s.transaction,x=Is.slice(p.oldVersion);for(let g of x)await g(u,m);await new Promise((g,_)=>{m.addEventListener("complete",g),m.addEventListener("error",_)}),p.oldVersion||(c=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{i({db:s.result,wasInitialized:c})}})}async function zi({wipNamespace:r,namespace:t,indexedDB:e,log:n,metadataVersion:i}){let o=await rn({namespace:r,indexedDB:e,log:n,metadataVersion:i});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await rn({namespace:t,indexedDB:e,log:n,metadataVersion:i}),c=s.transaction(["baselines","operations","info"],"readonly"),[p,u,m]=await Promise.all([J(c.objectStore("baselines").getAll()),J(c.objectStore("operations").getAll()),J(c.objectStore("info").getAll())]),x=o.db.transaction(["baselines","operations","info"],"readwrite"),g=x.objectStore("baselines"),_=x.objectStore("operations"),w=x.objectStore("info");for(let v of p)g.put(v);for(let v of u)_.put(v);for(let v of m)w.put(v);return await new Promise((v,I)=>{x.oncomplete=()=>{v()},x.onerror=S=>{I(S)},x.onabort=S=>{I(S)}}),await Ke(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",u.length,"operations"),o}async function Ds(r,t){let e=r.createObjectStore("baselines",{keyPath:"oid"}),n=r.createObjectStore("operations",{keyPath:"oid_timestamp"}),i=r.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Es(r,t){let e=t.objectStore("operations");await new Promise((n,i)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:c,documentOid_timestamp:p,...u}=s.value;s.update({...u,l_t:c,d_t:p}),s.continue()}else n()},o.onerror=s=>{i(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Cs(r,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function _s(r,t){let e=r.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ps(r,t){let e=t.objectStore("operations");await new Promise((i,o)=>{let s=e.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=ar(c.value);p.oid_timestamp!==c.primaryKey?(c.delete(),e.put(p)):c.update(p),c.continue()}else i()},s.onerror=c=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((i,o)=>{let s=n.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=ar(c.value);p.oid!==c.primaryKey?(c.delete(),n.put(p)):c.update(p),c.continue()}else i()},s.onerror=c=>{o(s.error)}})}var As=r=>IDBKeyRange.only(ve(r.equals)),Rs=r=>{},Ts=r=>{let t=r.gte||r.gt,e=r.lte||r.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!r.gt,!!r.lt):IDBKeyRange.lowerBound(ve(t),!!r.gt):IDBKeyRange.upperBound(ve(e),!!r.lt)},ks=(r,t,e)=>{let n=r.collections[t].compounds[e.where];L(n,`Index ${e.where} does not exist on collection ${t}`);let i=Object.keys(e.match).sort((p,u)=>n.of.indexOf(p)-n.of.indexOf(u));for(let p of i)if(n.of.indexOf(p)!==i.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let o=i.map(p=>e.match[p]);if(i.length===n.of.length)return IDBKeyRange.only(ce(...o));let s=Ue(...o),c=Ve(...o);return IDBKeyRange.bound(s,c)};function Fs(r){let t=r.startsWith,e=r.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function on(r,t,e){if(e)return pr(e)?Ts(e):fr(e)?As(e):Ri(e)?Rs(e):hr(e)?Fs(e):ks(r,t,e)}function wr(r,t,e){return r.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function sn({collection:r,index:t,context:e}){let n=wr(e.documentDb,r),i=t?.where?n.index(t.where):n,o=on(e.schema,r,t),s=t?.order==="desc"?"prev":"next",c=i.openCursor(o,s);return await new Promise((u,m)=>{c.onsuccess=()=>{let x=c.result;u(x?Z(r,x.primaryKey.toString()):null)},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",c.error),u(null)):le(c.error)?u(null):m(c.error)}})}async function an({collection:r,index:t,context:e}){let n=wr(e.documentDb,r),i=t?.where?n.index(t.where):n,o=on(e.schema,r,t),s=t?.order==="desc"?"prev":"next",c=i.openCursor(o,s);return await new Promise((u,m)=>{let x=new Set;c.onsuccess=()=>{let g=c.result;g?(x.add(Z(r,g.primaryKey.toString())),g.continue()):u(Array.from(x))},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",c.error),u([])):le(c.error)?u([]):m(c.error)}})}async function yt({collection:r,index:t,context:e,limit:n,offset:i}){let o=wr(e.documentDb,r),s=t?.where?o.index(t.where):o,c=on(e.schema,r,t),p=t?.order==="desc"?"prev":"next",u=s.openCursor(c,p),m=!i,x=!1,g=0;return{result:await new Promise((w,v)=>{let I=new Set;u.onsuccess=()=>{g++;let S=u.result;S?i&&!m?(S.advance(i),m=!0):(n&&I.size<n&&I.add(Z(r,S.primaryKey.toString())),n&&g>n?(x=!0,w(Array.from(I))):S.continue()):w(Array.from(I))},u.onerror=()=>{u.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",u.error),w([])):le(u.error)?w([]):v(u.error)}}),hasNextPage:x}}async function vr(r,t,e,n){function i(c,p){let u,m,x=r.open([t,"collections"].join("_"),e);x.onupgradeneeded=async g=>{u=g.oldVersion;let _=x.transaction;m=x.result,_.abort()},x.onsuccess=g=>{c([x.result.version,x.result])},x.onblocked=g=>{n?.("Database blocked, waiting...")},x.onerror=g=>{c([u,m])}}let[o,s]=await new Promise(i);return await cn(s),o}async function cn(r){r.close(),await new Promise(t=>t())}async function qi(r,t,e,n,i){function o(s,c){let p=r.open([t,"collections"].join("_"),e),u=!1;p.onupgradeneeded=m=>{let x=p.transaction;n(x,p.result,m),u=!0},p.onsuccess=m=>{p.result.close(),u?s():c(new Error("Database was not upgraded when a version change was expected"))},p.onerror=m=>{c(p.error||new Error("Unknown error"))},p.onblocked=m=>{i?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Hi(r,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${r}`,t):await t()}async function $e(r,t,e,n){n?.("debug","Opening database",t,"at version",e);let i=await new Promise((o,s)=>{let c=r.open([t,"collections"].join("_"),e);c.onupgradeneeded=async p=>{c.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",c.result.version),s(c.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${c.result.version}`))},c.onsuccess=p=>{o(c.result)},c.onblocked=p=>{s(new Error("Migration error: database blocked"))},c.onerror=p=>{s(new Error("Migration error: database error"))}});return i.addEventListener("versionchange",o=>{i.close()}),i}var Xe=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function ln({currentVersion:r,targetVersion:t,migrations:e}){let n=Wi({currentVersion:r,targetVersion:t,migrations:e});if(!n)throw new Xe(`No migration path found from ${r} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Wi({currentVersion:r,targetVersion:t,migrations:e}){if(r===t)return[];let n=e.filter(i=>i.oldSchema.version===r).sort((i,o)=>o.newSchema.version-i.newSchema.version);for(;n.length>0;){let i=n.shift();if(i.newSchema.version>t)return null;if(i.newSchema.version===t)return[i];let o=Wi({currentVersion:i.newSchema.version,targetVersion:t,migrations:e});if(o)return[i,...o]}return null}var Sr=typeof window<"u"?window.indexedDB:void 0;async function bt({version:r,indexedDB:t=Sr,migrations:e,meta:n,context:i}){if(i.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await vr(t,i.namespace,r,i.log);i.log("debug","Current database version:",o,"target version:",r);let s=ln({currentVersion:o,targetVersion:r,migrations:e});return s.length>0&&(i.log("debug","Migrations to run:",s.map(c=>c.version)),await xr({context:i,toRun:s,meta:n,indexedDB:t})),$e(t,i.namespace,r,i.log)}async function Qi({version:r,indexedDB:t=Sr,migrations:e,meta:n,context:i,wipNamespace:o}){i.log("debug","Opening WIP database",o);let s=await vr(t,o,r,i.log);if(s===r)i.log("info","WIP schema is up-to-date; not refreshing database");else{i.log("info","WIP schema is out-of-date; refreshing database");let c=ln({currentVersion:s,targetVersion:r-1,migrations:e});if(c.length>0){await xr({context:i,toRun:c,meta:n,indexedDB:t,namespace:o});let u=await $e(t,i.namespace,r-1,i.log),m=await $e(t,o,r-1,i.log),x=new Array;for(let S=0;S<u.objectStoreNames.length;S++)x.push(u.objectStoreNames[S]);let g=u.transaction(x,"readonly"),_=x.map(S=>g.objectStore(S)),w=await Promise.all(_.map(S=>J(S.getAll()))),v=m.transaction(x,"readwrite"),I=x.map(S=>v.objectStore(S));for(let S=0;S<I.length;S++)await Promise.all(w[S].map(D=>J(I[S].put(D))))}let p=ln({currentVersion:r-1,targetVersion:r,migrations:e});p.length>0&&await xr({context:i,toRun:p,meta:n,indexedDB:t,namespace:o})}return $e(t,o,r,i.log)}async function xr({context:r,toRun:t,meta:e,indexedDB:n=Sr,namespace:i=r.namespace}){await Hi(i,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=js({meta:e,migration:o,context:r}),await o.migrate(s);else{let u=await $e(n,i,o.oldSchema.version,r.log);s=Ms({meta:e,migration:o,context:{...r,documentDb:u}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw r.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await cn(u)}r.log("debug","Upgrading database",i,"to version",o.newSchema.version),await qi(n,i,o.newSchema.version,(u,m)=>{for(let x of o.addedCollections)m.createObjectStore(x,{keyPath:o.newSchema.collections[x].primaryKey,autoIncrement:!1});for(let x of o.allCollections){let g=u.objectStore(x);for(let _ of o.addedIndexes[x]||[])g.createIndex(_.name,_.name,{multiEntry:_.multiEntry});for(let _ of o.removedIndexes[x]||[])g.deleteIndex(_.name)}for(let x of o.removedCollections)u.objectStore(x).clear()},r.log);let c=await Us({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await $e(n,i,o.newSchema.version,r.log);for(let u of o.allCollections){let x=p.transaction(u,"readwrite").objectStore(u),_=(await Ls(x)).map(D=>Z(u,`${D}`));_.push(...s.newOids.filter(D=>me(D).collection===u),...c.filter(D=>me(D).collection===u));let v=(await Promise.all(_.map(async D=>{try{let R=await e.getDocumentSnapshot(D);return[D,R]}catch(R){return r.log("error","Could not regenerate snapshot during migration for oid",D,"this document will not be preserved",R),null}}))).filter(D=>!!D).map(([D,R])=>{if(!R)return[D,void 0];let b=qt(o.newSchema.collections[u],R);return[D,b]}),S=p.transaction(u,"readwrite").objectStore(u);await Promise.all(v.map(([D,R])=>{if(R)return Vs(S,R);{let{id:b}=me(D);return Ns(S,b)}}))}await cn(p),r.log("debug",`Migration of ${i} complete.`),r.log(`
|
|
8
|
+
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,i]=await Ki(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:i,baselines:n,localReplica:o,schema:s}};this.resetFrom=async e=>{let i=this.db.transaction(["baselines","operations","info"],"readwrite");await J(i.objectStore("baselines").clear()),await J(i.objectStore("operations").clear()),await J(i.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:i})};this.stats=async()=>{let e=this.db,n=await yt(e,"operations"),i=await yt(e,"baselines");return{operationsSize:n,baselinesSize:i}};this.context=n,this.schema=new rn(n.metaDb,n.schema.version),this.operations=new nn(this.db,{log:n.log}),this.baselines=new Zt(this.db,{log:n.log}),this.localReplica=new en(this.db),this.ackInfo=new Xt(this.db),this.messageCreator=new tn(this),this.patchCreator=new Jt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var ks=[Bs,Ms,js,Ls,Ns];function on({indexedDB:r=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((i,o)=>{let s=r.open(`${t}_meta`,n),c=!1;s.onupgradeneeded=async p=>{let u=s.result,m=s.transaction,S=ks.slice(p.oldVersion);for(let g of S)await g(u,m);await new Promise((g,_)=>{m.addEventListener("complete",g),m.addEventListener("error",_)}),p.oldVersion||(c=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{i({db:s.result,wasInitialized:c})}})}async function Hi({wipNamespace:r,namespace:t,indexedDB:e,log:n,metadataVersion:i}){let o=await on({namespace:r,indexedDB:e,log:n,metadataVersion:i});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await on({namespace:t,indexedDB:e,log:n,metadataVersion:i}),c=s.transaction(["baselines","operations","info"],"readonly"),[p,u,m]=await Promise.all([J(c.objectStore("baselines").getAll()),J(c.objectStore("operations").getAll()),J(c.objectStore("info").getAll())]),S=o.db.transaction(["baselines","operations","info"],"readwrite"),g=S.objectStore("baselines"),_=S.objectStore("operations"),w=S.objectStore("info");for(let v of p)g.put(v);for(let v of u)_.put(v);for(let v of m)w.put(v);return await new Promise((v,I)=>{S.oncomplete=()=>{v()},S.onerror=x=>{I(x)},S.onabort=x=>{I(x)}}),await Ke(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",u.length,"operations"),o}async function Bs(r,t){let e=r.createObjectStore("baselines",{keyPath:"oid"}),n=r.createObjectStore("operations",{keyPath:"oid_timestamp"}),i=r.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Ms(r,t){let e=t.objectStore("operations");await new Promise((n,i)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:c,documentOid_timestamp:p,...u}=s.value;s.update({...u,l_t:c,d_t:p}),s.continue()}else n()},o.onerror=s=>{i(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function js(r,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Ls(r,t){let e=r.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ns(r,t){let e=t.objectStore("operations");await new Promise((i,o)=>{let s=e.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=cr(c.value);p.oid_timestamp!==c.primaryKey?(c.delete(),e.put(p)):c.update(p),c.continue()}else i()},s.onerror=c=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((i,o)=>{let s=n.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=cr(c.value);p.oid!==c.primaryKey?(c.delete(),n.put(p)):c.update(p),c.continue()}else i()},s.onerror=c=>{o(s.error)}})}var Vs=r=>IDBKeyRange.only(ve(r.equals)),Us=r=>{},Ks=r=>{let t=r.gte||r.gt,e=r.lte||r.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!r.gt,!!r.lt):IDBKeyRange.lowerBound(ve(t),!!r.gt):IDBKeyRange.upperBound(ve(e),!!r.lt)},$s=(r,t,e)=>{let n=r.collections[t].compounds[e.where];L(n,`Index ${e.where} does not exist on collection ${t}`);let i=Object.keys(e.match).sort((p,u)=>n.of.indexOf(p)-n.of.indexOf(u));for(let p of i)if(n.of.indexOf(p)!==i.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let o=i.map(p=>e.match[p]);if(i.length===n.of.length)return IDBKeyRange.only(ce(...o));let s=Ue(...o),c=Ve(...o);return IDBKeyRange.bound(s,c)};function zs(r){let t=r.startsWith,e=r.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function sn(r,t,e){if(e)return mr(e)?Ks(e):hr(e)?Vs(e):ki(e)?Us(e):gr(e)?zs(e):$s(r,t,e)}function xr(r,t,e){return r.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function an({collection:r,index:t,context:e}){let n=xr(e.documentDb,r),i=t?.where?n.index(t.where):n,o=sn(e.schema,r,t),s=t?.order==="desc"?"prev":"next",c=i.openCursor(o,s);return await new Promise((u,m)=>{c.onsuccess=()=>{let S=c.result;u(S?Z(r,S.primaryKey.toString()):null)},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",c.error),u(null)):le(c.error)?u(null):m(c.error)}})}async function cn({collection:r,index:t,context:e}){let n=xr(e.documentDb,r),i=t?.where?n.index(t.where):n,o=sn(e.schema,r,t),s=t?.order==="desc"?"prev":"next",c=i.openCursor(o,s);return await new Promise((u,m)=>{let S=new Set;c.onsuccess=()=>{let g=c.result;g?(S.add(Z(r,g.primaryKey.toString())),g.continue()):u(Array.from(S))},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",c.error),u([])):le(c.error)?u([]):m(c.error)}})}async function wt({collection:r,index:t,context:e,limit:n,offset:i}){let o=xr(e.documentDb,r),s=t?.where?o.index(t.where):o,c=sn(e.schema,r,t),p=t?.order==="desc"?"prev":"next",u=s.openCursor(c,p),m=!i,S=!1,g=0;return{result:await new Promise((w,v)=>{let I=new Set;u.onsuccess=()=>{g++;let x=u.result;x?i&&!m?(x.advance(i),m=!0):(n&&I.size<n&&I.add(Z(r,x.primaryKey.toString())),n&&g>n?(S=!0,w(Array.from(I))):x.continue()):w(Array.from(I))},u.onerror=()=>{u.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",u.error),w([])):le(u.error)?w([]):v(u.error)}}),hasNextPage:S}}async function Or(r,t,e,n){function i(c,p){let u,m,S=r.open([t,"collections"].join("_"),e);S.onupgradeneeded=async g=>{u=g.oldVersion;let _=S.transaction;m=S.result,_.abort()},S.onsuccess=g=>{c([S.result.version,S.result])},S.onblocked=g=>{n?.("Database blocked, waiting...")},S.onerror=g=>{c([u,m])}}let[o,s]=await new Promise(i);return await ln(s),o}async function ln(r){r.close(),await new Promise(t=>t())}async function Wi(r,t,e,n,i){function o(s,c){let p=r.open([t,"collections"].join("_"),e),u=!1;p.onupgradeneeded=m=>{let S=p.transaction;n(S,p.result,m),u=!0},p.onsuccess=m=>{p.result.close(),u?s():c(new Error("Database was not upgraded when a version change was expected"))},p.onerror=m=>{c(p.error||new Error("Unknown error"))},p.onblocked=m=>{i?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function Qi(r,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${r}`,t):await t()}async function $e(r,t,e,n){n?.("debug","Opening database",t,"at version",e);let i=await new Promise((o,s)=>{let c=r.open([t,"collections"].join("_"),e);c.onupgradeneeded=async p=>{c.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",c.result.version),s(c.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${c.result.version}`))},c.onsuccess=p=>{o(c.result)},c.onblocked=p=>{s(new Error("Migration error: database blocked"))},c.onerror=p=>{s(new Error("Migration error: database error"))}});return i.addEventListener("versionchange",o=>{i.close()}),i}var Ze=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function dn({currentVersion:r,targetVersion:t,migrations:e}){let n=Ji({currentVersion:r,targetVersion:t,migrations:e});if(!n)throw new Ze(`No migration path found from ${r} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Ji({currentVersion:r,targetVersion:t,migrations:e}){if(r===t)return[];let n=e.filter(i=>i.oldSchema.version===r).sort((i,o)=>o.newSchema.version-i.newSchema.version);for(;n.length>0;){let i=n.shift();if(i.newSchema.version>t)return null;if(i.newSchema.version===t)return[i];let o=Ji({currentVersion:i.newSchema.version,targetVersion:t,migrations:e});if(o)return[i,...o]}return null}var Dr=typeof window<"u"?window.indexedDB:void 0;async function vt({version:r,indexedDB:t=Dr,migrations:e,meta:n,context:i}){if(i.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await Or(t,i.namespace,r,i.log);i.log("debug","Current database version:",o,"target version:",r);let s=dn({currentVersion:o,targetVersion:r,migrations:e});return s.length>0&&(i.log("debug","Migrations to run:",s.map(c=>c.version)),await Ir({context:i,toRun:s,meta:n,indexedDB:t})),$e(t,i.namespace,r,i.log)}async function Yi({version:r,indexedDB:t=Dr,migrations:e,meta:n,context:i,wipNamespace:o}){i.log("debug","Opening WIP database",o);let s=await Or(t,o,r,i.log);if(s===r)i.log("info","WIP schema is up-to-date; not refreshing database");else{i.log("info","WIP schema is out-of-date; refreshing database");let c=dn({currentVersion:s,targetVersion:r-1,migrations:e});if(c.length>0){await Ir({context:i,toRun:c,meta:n,indexedDB:t,namespace:o});let u=await $e(t,i.namespace,r-1,i.log),m=await $e(t,o,r-1,i.log),S=new Array;for(let x=0;x<u.objectStoreNames.length;x++)S.push(u.objectStoreNames[x]);let g=u.transaction(S,"readonly"),_=S.map(x=>g.objectStore(x)),w=await Promise.all(_.map(x=>J(x.getAll()))),v=m.transaction(S,"readwrite"),I=S.map(x=>v.objectStore(x));for(let x=0;x<I.length;x++)await Promise.all(w[x].map(D=>J(I[x].put(D))))}let p=dn({currentVersion:r-1,targetVersion:r,migrations:e});p.length>0&&await Ir({context:i,toRun:p,meta:n,indexedDB:t,namespace:o})}return $e(t,o,r,i.log)}async function Ir({context:r,toRun:t,meta:e,indexedDB:n=Dr,namespace:i=r.namespace}){await Qi(i,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=Ws({meta:e,migration:o,context:r}),await o.migrate(s);else{let u=await $e(n,i,o.oldSchema.version,r.log);s=Hs({meta:e,migration:o,context:{...r,documentDb:u}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(m){throw r.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,m),m instanceof Error?m:new Error("Unknown error during migration")}await ln(u)}r.log("debug","Upgrading database",i,"to version",o.newSchema.version),await Wi(n,i,o.newSchema.version,(u,m)=>{for(let S of o.addedCollections)m.createObjectStore(S,{keyPath:o.newSchema.collections[S].primaryKey,autoIncrement:!1});for(let S of o.allCollections){let g=u.objectStore(S);for(let _ of o.addedIndexes[S]||[])g.createIndex(_.name,_.name,{multiEntry:_.multiEntry});for(let _ of o.removedIndexes[S]||[])g.deleteIndex(_.name)}for(let S of o.removedCollections)u.objectStore(S).clear()},r.log);let c=await Gs({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await $e(n,i,o.newSchema.version,r.log);for(let u of o.allCollections){let S=p.transaction(u,"readwrite").objectStore(u),_=(await Qs(S)).map(D=>Z(u,`${D}`));_.push(...s.newOids.filter(D=>me(D).collection===u),...c.filter(D=>me(D).collection===u));let v=(await Promise.all(_.map(async D=>{try{let T=await e.getDocumentSnapshot(D);return[D,T]}catch(T){return r.log("error","Could not regenerate snapshot during migration for oid",D,"this document will not be preserved",T),null}}))).filter(D=>!!D).map(([D,T])=>{if(!T)return[D,void 0];let b=Ht(o.newSchema.collections[u],T);return[D,b]}),x=p.transaction(u,"readwrite").objectStore(u);await Promise.all(v.map(([D,T])=>{if(T)return Ys(x,T);{let{id:b}=me(D);return Js(x,b)}}))}await ln(p),r.log("debug",`Migration of ${i} complete.`),r.log(`
|
|
9
9
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
10
10
|
- Added collections: ${o.addedCollections.join(", ")}
|
|
11
11
|
- Removed collections: ${o.removedCollections.join(", ")}
|
|
12
12
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
13
|
- New indexes: ${Object.keys(o.addedIndexes).map(u=>o.addedIndexes[u].map(m=>`${u}.${m.name}`)).flatMap(u=>u).join(", ")}
|
|
14
14
|
- Removed indexes: ${Object.keys(o.removedIndexes).map(u=>o.removedIndexes[u].map(m=>`${u}.${m.name}`)).flatMap(u=>u).join(", ")}
|
|
15
|
-
`)}})}function Ji({migration:r,meta:t,getMigrationNow:e,newOids:n}){return r.allCollections.reduce((i,o)=>(i[o]={put:async s=>{Pe(r.newSchema.collections[o],s);let c=s[r.newSchema.collections[o].primaryKey],p=Z(o,c);return n.push(p),await t.insertLocalOperations(Te(s,p,e)),s},delete:async s=>{let c=Z(o,s),p=await t.getAllDocumentRelatedOids(c);return t.insertLocalOperations(p.map(u=>({oid:u,timestamp:e(),data:{op:"delete"}})))}},i),{})}function Bs({migration:r,context:t,meta:e}){return r.oldCollections.reduce((n,i)=>(n[i]={get:async o=>{let s=Z(i,o);return await e.getDocumentSnapshot(s,{to:e.time.now(r.oldSchema.version)})},findOne:async o=>{let s=await sn({collection:i,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(r.oldSchema.version)}):null},findAll:async o=>{let s=await an({collection:i,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(r.oldSchema.version)})))}},n),{})}function Ms({meta:r,migration:t,context:e}){function n(){return r.time.zero(t.version)}let i=new Array,o=Bs({migration:t,context:e,meta:r}),s=Ji({migration:t,getMigrationNow:n,newOids:i,meta:r}),c=async m=>{let x=await r.getAllCollectionRelatedOids(m);return r.insertLocalOperations(x.map(g=>({oid:g,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:i,deleteCollection:c,migrate:async(m,x)=>{let g=await o[m].findAll();await Promise.all(g.filter(Boolean).map(async _=>{let w=ne(_);L(!!w,`Document is missing an OID: ${JSON.stringify(_)}`);let v=ae(_),I=await x(_);if(I){ut(v),ut(I),Ye(I);let S=pt(v,I,n,void 0,[],{mergeUnknownObjects:!0});S.length>0&&await r.insertLocalOperations(S)}}))},queries:o,mutations:s,awaitables:p}}function js({meta:r,migration:t,context:e}){function n(){return r.time.zero(t.version)}let i=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Ji({migration:t,getMigrationNow:n,newOids:i,meta:r});return{log:e.log,newOids:i,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Ls(r){return new Promise((t,e)=>{let n=r.getAllKeys();n.onsuccess=i=>{t(n.result)},n.onerror=i=>{e(n.error)}})}async function Ns(r,t){let e=r.delete(t);return new Promise((n,i)=>{e.onsuccess=o=>{n()},e.onerror=o=>{i(e.error)}})}async function Vs(r,t){let e=r.put(t);return new Promise((n,i)=>{e.onsuccess=o=>{n()},e.onerror=o=>{i(e.error)}})}async function Us({meta:r,currentVersion:t,newVersion:e}){let n=[];return await r.operations.iterateOverAllOperations(i=>n.push(i),{from:r.time.zero(t+1)}),Array.from(new Set(n.map(i=>$(i.oid))))}var wt=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let n=await e();return n&&this._undone.push(n),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let n=await e();return n&&this._undoable.push(n),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var dn=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,i=e[n];return L(i,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,i)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Pe(n,e)};this.create=(t,e,n={})=>{let i=this.addDefaults(t,e),o=this.getOid(t,i);return this.entities.create(i,o,n)};this.delete=async(t,e,n={})=>{let i=Z(t,e);return this.entities.delete(i,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,i])=>Z(n,i)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(i=>Z(t,i)),n)}};var Ze=Symbol("entity-file-update"),vt=Symbol("entity-file-mark-failed"),Ks,$s,de=class extends V{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Ks]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[$s]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=n}static{Ks=Ze,$s=vt}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Yi=it(Pt(),1);function zs(r){return{id:(0,Yi.default)(),file:r,url:void 0,remote:!1,name:r.name,type:r.type}}function Or(r){return r instanceof File||typeof Blob<"u"&&r instanceof Blob}function et(r,t){if(typeof window<"u"&&Or(r)){let e=zs(r);return t(e),Bt(e.id)}if(Array.isArray(r)){for(let e=0;e<r.length;e++)r[e]=et(r[e],t);return r}if(typeof r=="object"){for(let e in r)r[e]=et(r[e],t);return r}return r}function Gi(r){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(r)})}var un=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:i=!1}={})=>{let o=e.file?await Gi(e.file):void 0;if(!o&&i&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:n})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?qs(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(!i)throw new Error("File is not in local database");return this.run("files",o=>o.put({...i,remote:"true"}),{mode:"readwrite",transaction:n})};this.getFileRaw=async(e,{transaction:n}={})=>{let i=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:n});if(i)return i};this.getFile=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(i)return this.hydrateFileData(i)};this.markPendingDelete=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(!i)throw new Error("File is not in local database");return this.run("files",o=>o.put({...i,deletedAt:Date.now()}),{mode:"readwrite",transaction:n})};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",i=>i.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(i,o)=>{e(this.hydrateFileData(i),o)},{mode:"readwrite",transaction:n})}deleteFile(e,{transaction:n}={}){return this.run("files",i=>i.delete(e),{mode:"readwrite",transaction:n})}};function qs(r,t){return new Blob([r],{type:t})}function Hs(r){return r.deletedAt!==null&&r.deletedAt<Date.now()-1e3*60*24*3}var fn=class{constructor({db:t,sync:e,context:n,meta:i,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ze](e);else{let n=new de(e.id);n[Ze](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(t,e)=>{if(this.files.has(t))return this.files.get(t);let n=new de(t,e);return this.files.set(t,n),this.load(n),n};this.load=async(t,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),t[vt]();return}let n=await this.storage.getFile(t.id);if(n)t[Ze](n);else try{let i=await this.sync.getFile(t.id);i.success?(t[Ze](i.data),await this.storage.addFile(i.data,{downloadRemote:t.downloadRemote})):(this.context.log("error","Failed to load file",i),t[vt](),i.retry&&setTimeout(this.load,1e3,t,e+1))}catch(i){this.context.log("error","Failed to load file",i),t[vt](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,i)=>{this.config.canCleanupDeletedFile(n)?(t++,i.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(i){this.context.log("error","Failed to mark file for deletion",i)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new un(t),this.sync=e,this.context=n,this.meta=i,this.config={canCleanupDeletedFile:Hs,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var pn=class{constructor({initial:t}={}){this.cache=new Map;this.get=t=>{if(this.cache.has(t.oid))return this.cache.get(t.oid);let e=new ue(t);return this.cache.set(t.oid,e),e};this.has=t=>this.cache.has(t);this.getFile=(t,e)=>{if(this.cache.has(t))return this.cache.get(t);let n=new de(t,e);return this.cache.set(t,n),n};this.getCached=t=>this.cache.get(t);if(t)for(let e of t)this.cache.set(e.oid,e)}};var ue=class r extends V{constructor({oid:e,schema:n,entityFamily:i,parent:o,ctx:s,metadataFamily:c,readonlyKeys:p,files:u,patchCreator:m,events:x}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,n)=>{n.oid===this.oid&&this.addConfirmedData(n)};this.onReplace=(e,n)=>{n.oid===this.oid&&this.replaceAllData(n)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof r){let n=e.view;return n==null}return e==null};this.validate=ji(()=>(this.validationError=ke({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let n=this.view;if(!n)return null;if(Array.isArray(n)){let i=n.map(o=>o instanceof r||o instanceof de?e(o):o);return K(i,this.oid),i}else{let i=Object.entries(n).reduce((o,[s,c])=>(c instanceof r||c instanceof de?o[s]=e(c):o[s]=c,o),{});return K(i,this.oid),i}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let n=this.metadataFamily.addPendingData(e);for(let i of n)this.change(i)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let n=this.metadataFamily.addConfirmedData(e);for(let i of n)this.change(i)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let n=this.metadataFamily.replaceAllData(e);for(let i of n)this.change(i)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let n of e)this.change(n)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let n=this.entityFamily.getCached(e.oid);n&&n instanceof r&&n.change(e)}};this.deepChange=(e,n)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,n),this.parent?.deepChange(e,n)};this.getChild=(e,n)=>{let i=Ne(this.schema,e);if(!i)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:n,schema:i,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{Xi(e);let n=this.rawView;if(!n)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let i=n[e],o=Ne(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(i))if(be(i)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(i.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,i.id);else return ke({field:o,value:i,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?_e(o)?dr(o):we(o)?null:void 0:i};this.processInputValue=(e,n)=>{if(this.readonlyKeys.includes(n))throw new Error(`Cannot set readonly key ${n.toString()}`);Or(e)||(e=ae(e,!1));let i=Ne(this.schema,n);if(i){Le(e,i);let o=ke({field:i,value:e,fieldPath:[...this.fieldPath,n]});if(o)throw new Error(o.message)}return et(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let n=this.schema.properties[e];if(!n||n.type==="any")return"delete";if(n.type==="map")return!1;if(n.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof r)return he(e.oid);if(e instanceof de)return Bt(e.id);if(typeof e=="object"){let n=pe(e);if(!n||!this.entityFamily.has(n))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return he(n)}else return e};this.set=(e,n)=>{Xi(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(n,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)Ws(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let n=this.getDeleteMode(e);if(!n)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);n==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:n=!0,replaceSubObjects:i=!1}={})=>{if(!n&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};K(o,this.oid);for(let[s,c]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let p=Ne(this.schema,s);p&&Le(c,p),o[s]=this.processInputValue(c,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!i,defaultUndefined:n}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,n)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(n,e)))};this.move=(e,n)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,n))};this.moveItem=(e,n)=>{let i=this.getItemRefValue(e);if(Q(i))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,i,n));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,n)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let n=this.getItemRefValue(e);return Q(n)?this.view.some(i=>{if(Q(i))return Je(i,n)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,n)=>this.metadataFamily.get(e).computeView(n==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=p||[],this.ctx=s,this.files=u,this.schema=n,this.entityFamily=i||new pn({initial:[this]}),this.patchCreator=m,this.metadataFamily=c,this.events=x,this.parent=o,this.parent||(x.add.attach(this.onAdd),x.replace.attach(this.onReplace),x.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!U(e))return _e(this.schema)?dr(this.schema):null;if(this.cachedView=this.isList?[]:{},K(this.cachedView,this.oid),Array.isArray(e)){let i=Ne(this.schema,0);if(!i)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(i)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(U(e)){let i=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of i){let s=Ne(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let c=this.get(o);if(this.childIsNull(c)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=c}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(n=>{if(n instanceof r){let i=n.deepUpdatedAt;i&&(!e||i>e)&&(e=i)}}):this.values().forEach(n=>{if(n instanceof r){let i=n.deepUpdatedAt;i&&(!e||i>e)&&(e=i)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,n=this.view?.length;return{next:()=>e<n?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Xi(r){if(typeof r=="symbol")throw new Error("Symbol keys aren't supported")}function Ws(r){if(typeof r!="number")throw new Error("Only number keys are supported in list entities")}var Ir=class{constructor({oid:t,ctx:e,confirmedOperations:n,pendingOperations:i,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(t=!1)=>{let e=ae(this.baseline?.snapshot??void 0),n=this.baseline?.timestamp??null,i=this.applyOperations(e,!e,this.confirmedOperations,n,n);i.futureSeen&&this.ctx.globalEvents.emit("futureSeen",i.futureSeen);let o=t?i:this.applyOperations(i.view,i.deleted,this.pendingOperations,i.latestTimestamp,null);o.view&&K(o.view,this.oid);let s=!!i.latestTimestamp&&Gn(i.latestTimestamp,this.ctx.getNow())<0,c=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;c&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??i.latestTimestamp??n,u=p?Xn(p):0;if(!o.view&&!o.deleted&&!c){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:c,fromOlderVersion:s,updatedAt:u}};this.addBaseline=t=>{if(!(this.baseline&&this.baseline.timestamp>=t.timestamp))for(this.baseline=t;this.confirmedOperations[0]?.timestamp<t.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=t=>{let e=0;for(let n of t){let i=this.confirmedOperations.findIndex(s=>s.timestamp>=n.timestamp);i!==-1?this.confirmedOperations[i].timestamp!==n.timestamp&&(this.confirmedOperations.splice(i,0,n),e++):(this.confirmedOperations.push(n),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>n.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=t=>{this.pendingOperations.push(t)};this.applyOperations=(t,e,n,i,o)=>{let s,c=this.ctx.getNow();for(let p of n)if(!(o&&p.timestamp<=o)){if(Gn(p.timestamp,c)>0){s=p.timestamp;continue}p.data.op==="delete"?e=!0:(t=je(t,p.data),p.data.op==="initialize"&&(e=!1)),(!i||p.timestamp>i)&&(i=p.timestamp)}return{view:t,latestTimestamp:i??null,deleted:e,futureSeen:s}};L(t,"oid is required"),this.ctx=e,this.oid=t,n&&(this.confirmedOperations=n),i&&(this.pendingOperations=i),o&&(this.baseline=o)}},hn=class{constructor({ctx:t,onPendingOperations:e,rootOid:n}){this.entities=new Map;this.get=t=>(L(t,"oid is required"),this.entities.has(t)||this.entities.set(t,new Ir({oid:t,ctx:this.ctx})),this.entities.get(t));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:t=[],operations:e={},isLocal:n=!1})=>{let i={};for(let o of t){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(i[o]??={oid:o,isLocal:n})}return Object.values(i)};this.addPendingData=t=>{let e={};for(let n of t)this.get(n.oid).addPendingOperation(n),e[n.oid]??={oid:n.oid,isLocal:!0};return this.onPendingOperations(t),Object.values(e)};this.replaceAllData=({operations:t={},baselines:e=[]})=>{let n=Array.from(this.entities.keys());this.entities.clear();let i={};for(let o of n)i[o]={oid:o,isLocal:!1};for(let o of e){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),i[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(t)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),i[o]??={oid:o,isLocal:!1}}return Object.values(i)};this.ctx=t,this.rootOid=n,this.onPendingOperations=e}};var xt="@@default",mn=class{constructor({batchTimeout:t=200,meta:e,ctx:n,entities:i}){this.currentBatchKey=xt;this.flushOperations=async(t,e,n)=>{if(this.ctx.log("debug","Flushing",t.length,"operations from batch",e,"to storage / sync"),!!t.length){for(let i of t)i.timestamp=this.meta.now;await this.commitOperations(t,n)}};this.commitOperations=async(t,e)=>{if(t.length){if(e.undoable){let n=await this.createUndo({ops:t,source:e.source});n&&this.ctx.undoHistory.addUndo(n)}await this.entities.addData({operations:t,baselines:[],isLocal:!0})}};this.addOperations=t=>{t.length&&(this.batcher.add({key:this.currentBatchKey,items:t}),this.ctx.log("debug","added",t.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:t=!0,batchName:e=Lt(),max:n=null,timeout:i=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:n,timeout:i,items:[],userData:{undoable:t}}),s={run:c=>(this.currentBatchKey=e,c(),this.currentBatchKey=xt,s),commit:async()=>(await this.batcher.flush(xt),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async t=>{let e=await this.getInverseOperations(t);return e.length?async()=>{let n=await this.createUndo({ops:e,source:t.source});for(let i of e)i.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),n}:null};this.getInverseOperations=async({ops:t,source:e})=>{let n=ht(t),i=[],o=()=>this.meta.now;return await Promise.all(Object.entries(n).map(async([s,c])=>{let u=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!u){this.ctx.log("warn","could not find entity",s,"for undo operation",t);return}let m=Mi(s,u.view,c,o);i.unshift(...m)})),i};this.meta=e,this.ctx=n,this.entities=i,this.defaultBatchTimeout=t,this.batcher=new Ge(this.flushOperations),this.batcher.add({key:xt,items:[],max:100,timeout:t,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===xt}};var gn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),n=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(i=>{let o=n.objectStore(i);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,n)=>{if(e.length===0)return;let i=Array.from(new Set(e.map(s=>me(s.oid).collection))),o={transaction:this.createTransaction(i,{mode:"readwrite",abort:n?.abort})};await Promise.all(e.map(async s=>{let c=s.getSnapshot();try{await this.saveDocument(s.oid,c,o)}catch(p){throw this.ctx.log("error",`Error saving document ${s.oid} (${JSON.stringify(c)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",i);for(let s of e)this.ctx.entityEvents.emit("documentChanged",s.oid)};this.saveDocument=async(e,n,{transaction:i})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,n);let{collection:o,id:s}=me(e);if(!n)await this.run(o,c=>c.delete(s),{mode:"readwrite",transaction:i}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let c=this.ctx.schema.collections[o],p=qt(c,n);await this.run(o,u=>u.put(p),{mode:"readwrite",transaction:i}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,n)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",n=>{this.db=n}))}};var Dn=it(ko(),1);var En=class extends Ie{constructor({ctx:e,meta:n,files:i}){super();this.events={add:new Dn.WeakEvent,replace:new Dn.WeakEvent,resetAll:new Dn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let n=e?.baselines??[],i=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:i.length,baselines:n.length,reset:!!e.reset});let o=Array.from(new Set(n.map(m=>$(m.oid)).concat(i.map(m=>$(m.oid))))),s=Pi(n),c=_i(i);this.ctx.log("debug","Applying data to live entities");for(let m of o){let x=s[m],g=c[m]??[],_=ht(g),w=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(m);v?v.then(()=>{w.invoke(this,{oid:m,baselines:x,operations:_,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:x,operations:_,isLocal:!1}))}let p={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,p);let u=await Promise.all(o.map(async m=>await this.hydrate(m,p)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(u,p)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,n)=>{if(!Ei(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let i=this.pendingEntityPromises.get(e);if(i)return this.ctx.log("debug","Waiting for entity hydration",e),i;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,n);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,n,{undoable:i=!0}={})=>{this.ctx.log("debug","Creating new entity",n);let{collection:o}=me(n);Nt(e);let s=et(e,this.files.add);K(s,n);let c=this.constructEntity(n);if(!c)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.meta.patchCreator.createInitialize(s,n);await this.batcher.commitOperations(p,{undoable:!!i,source:c});let u=ht(p);return this.events.add.invoke(this,{operations:u,isLocal:!0,oid:n}),this.cache.set(n,this.ctx.weakRef(c)),c};this.deleteAll=async(e,n)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let i=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(i.flat());await this.batcher.commitOperations(o,{undoable:n?.undoable===void 0?!0:n.undoable})};this.delete=async(e,n)=>this.deleteAll([e],n);this.getCollectionSchema=e=>{let n=this.ctx.schema.collections[e];return n?{schema:{type:"object",nullable:!1,properties:n.fields},readonlyKeys:[n.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:n}=me(e),{schema:i,readonlyKeys:o}=this.getCollectionSchema(n);if(!i)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new hn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:i,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,n)=>{let{operations:i,baselines:o}=await this.meta.getDocumentData(e.oid,n);return!o.length&&!Object.keys(i).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:i,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=n,this.files=i,this.queryableStorage=new gn({ctx:e}),this.batcher=new mn({ctx:e,meta:n,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Nr=Symbol("handleMessage"),la,Ot=class extends V{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:i}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[la]=async(e,n)=>{let i=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,i=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,c]of Object.entries(n.peerPresence))this.isSelf(e,c)?(this._self=c,this._selfReplicaIds.add(c.replicaId),this.emit("selfChanged",c)):(i=!0,o.add(s),this._peers[s]=c,this.emit("peerChanged",s,c))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],i=!0,this.emit("peerLeft",n.userId,s)}i&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((i,o)=>({...i,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=i,this._updateBatcher=new Ge(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{la=Nr}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var Cn=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:i}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${i}`}});return s.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let i=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return i.ok?{success:!0,data:await i.json()}:(this.log("error","File information fetch failed",i.status,await i.text()),{success:!1,retry:i.status>=500||i.status===404})}catch(i){return this.log("error","File information fetch failed",i),{success:!1,error:i,retry:!0}}};this.endpointProvider=t,this.log=e}};var nt=class extends V{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:i=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&i&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var _n=class extends V{constructor({endpointProvider:e,meta:n,presence:i,interval:o=15*1e3,log:s=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:i}=await this.endpointProvider.getEndpoints(),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let c of s.messages)this.handleServerMessage(c);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Ni(s)&&s.code===4012&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=n,this.presence=i,this.endpointProvider=e,this.heartbeat=new nt({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function Vr(r){this.message=r}Vr.prototype=new Error,Vr.prototype.name="InvalidCharacterError";var Fo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new Vr("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,i=0,o=0,s="";n=t.charAt(o++);~n&&(e=i%4?64*e+n:n,i++%4)?s+=String.fromCharCode(255&e>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function da(r){var t=r.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Fo(e).replace(/(.)/g,function(n,i){var o=i.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return Fo(t)}}function Pn(r){this.message=r}function ua(r,t){if(typeof r!="string")throw new Pn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(da(r.split(".")[e]))}catch(n){throw new Pn("Invalid token specified: "+n.message)}}Pn.prototype=new Error,Pn.prototype.name="InvalidTokenError";var Bo=ua;var An=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(c=>{if(c.ok)return c.json();throw new Error(`Auth endpoint returned non-200 response: ${c.status}`)}),L(t.accessToken,"No access token provided from auth endpoint");let e=Bo(t.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let i=n.toString();n.protocol=n.protocol.replace("http","ws");let o=n.toString(),s=e.file;if(!s){let c=new URL(i);c.pathname=c.pathname+"/files",s=c.toString()}return this.cached={http:i,websocket:o,files:s,token:t.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var Rn=class extends V{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Tn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var kn=class extends V{constructor({endpointProvider:e,meta:n,presence:i,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new nt;this.reconnectScheduler=new Rn(new Tn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(n.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let i of this.syncQueue)this.send(i);this.syncQueue=[]}if(this.emit("message",n),this.incomingQueue.length){for(let i of this.incomingQueue)this.emit("message",i);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",n),this.incomingQueue.push(n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=n,this.presence=i,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Fn=class extends V{constructor(){super(...arguments);this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new Ot({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},rt=class extends V{constructor({authEndpoint:e,fetchAuth:n,initialPresence:i,automaticTransportSelection:o=!0,autoStart:s,initialTransport:c,pullInterval:p,presenceUpdateBatchTimeout:u,defaultProfile:m,useBroadcastChannel:x},{meta:g,log:_,onData:w}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let i of e.operations)this.meta.time.update(i.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Nr](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=g,this.onData=w,this.log=_||(()=>{}),this.presence=new Ot({initialPresence:i,defaultProfile:m,updateBatchTimeout:u}),this.endpointProvider=new An({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new kn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log}),this.pushPullSync=new _n({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log,interval:p}),this.fileSync=new Cn({endpointProvider:this.endpointProvider,log:this.log}),x&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),c==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let v=()=>{I&&clearTimeout(I);let D=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;D&&this.mode==="pull"?this.setMode("realtime"):!D&&this.mode==="realtime"&&(I=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},I;this.presence.subscribe("peersChanged",v),o!=="peers-only"&&this.presence.subscribe("selfChanged",v)}s&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function pa(r){return r!==null}function Ur(r){return Array.isArray(r)?r.map(Ur).filter(pa):r instanceof ue&&r.deleted?null:r}function Fe(r,t){return!r&&!t||r&&t&&Re(r)===Re(t)}var Kr=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),ha,ge=class extends Ie{constructor({initial:e,context:n,collection:i,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Ur(e),Array.isArray(this._value)&&this._value.some(n=>n.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ue&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[ha]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new V(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=o,this.collection=i;let c=s||(p=>p.includes(i));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{c(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{ha=Kr}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Bn=class extends ge{constructor({id:e,hydrate:n,...i}){super({initial:null,...i});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(i.collection,e),this.hydrate=n}};var ma,Mn=class extends ge{constructor({index:e,hydrate:n,...i}){super({initial:null,...i});this.run=async()=>{let e=await sn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[ma]=e=>{Fe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{ma=fe}};var ga,jn=class extends ge{constructor({index:e,hydrate:n,pageSize:i,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await yt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[ga]=e=>{Fe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=i,this._page=o}static{ga=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var ya,Ln=class extends ge{constructor({hydrate:e,pageSize:n,index:i,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await yt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await yt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[ya]=e=>{Fe(this.index,e)||(this.index=e,this.execute())};this.index=i,this.hydrate=e,this._pageSize=n}static{ya=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var ba,Nn=class extends ge{constructor({index:e,hydrate:n,...i}){super({initial:[],...i});this.run=async()=>{let e=await an({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[ba]=e=>{Fe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{ba=fe}};var Vn=class{constructor({collection:t,cache:e,entities:n,context:i,documentManager:o}){this.serializeIndex=t=>t?Re(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Bn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Mn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),i=>{i[fe](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Nn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),i=>{i[fe](t)})};this.findPage=({index:t,pageSize:e,page:n,key:i})=>{let o=i||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new jn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[fe](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let i=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(i,()=>new Ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:i,pageSize:e}),o=>{o[fe](t)})};this.cache=e,this.collection=t,this.hydrate=n.hydrate,this.context=i,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Un=class extends Ie{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Kr](this.onQueryUnsubscribed),e}getOrSet(e,n,i){let o=this.get(e);return o?(i?.(o),o):this.set(n())}};var He=class extends V{constructor(e,n,i){super();this.config=e;this.context=n;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let u of e)try{n[u]=await mt(this.documentDb,u)}catch(m){this.context.log?.("error",m)}let i=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((u,{size:m})=>u+m,0),c=i.baselinesSize.size+i.operationsSize.size,p=c/s;return{collections:n,meta:i,storage:o,totalMetaSize:c,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Jt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ke(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let i=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((c,p)=>{o.onsuccess=c,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await bt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:i}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await bt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.meta=i.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new rt(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Fn,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new fn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new En({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Un({context:n}),this._documentManager=new dn(this.meta,this.schema,this._entities);let o=Si(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,c]of Object.entries(n.schema.collections)){let p=s;this[p]=new Vn({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var It=class{constructor(t){this.value=t}deref(){return this.value}};var Mo=Symbol("metadataVersion");var Kn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let e=t[Mo],{db:n}=await rn({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),i={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new wt,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:m=>t.EXPERIMENTAL_weakRefs?new WeakRef(m):new It(m),migrations:t.migrations},o=new gt({context:i,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=Object.assign(i,{getNow:()=>o.now}),c=await bt({context:s,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),p=Object.assign(s,{documentDb:c});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Re(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:i}=await zi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:i,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new wt,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:x=>t.EXPERIMENTAL_weakRefs?new WeakRef(x):new It(x),migrations:t.migrations},s=new gt({context:o,disableRebasing:t.disableRebasing}),c=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(t.schema,t.overrideSchemaConflict);let p=await Qi({context:c,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),u=Object.assign(c,{documentDb:p});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},u,{meta:s})};this.cleanupWIPDatabases=async t=>{let i=(await Ki(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Re(t.schema)}`));for(let o of i)await Ui(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Jt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=$r;
|
|
15
|
+
`)}})}function Gi({migration:r,meta:t,getMigrationNow:e,newOids:n}){return r.allCollections.reduce((i,o)=>(i[o]={put:async s=>{Pe(r.newSchema.collections[o],s);let c=s[r.newSchema.collections[o].primaryKey],p=Z(o,c);return n.push(p),await t.insertLocalOperations(Re(s,p,e)),s},delete:async s=>{let c=Z(o,s),p=await t.getAllDocumentRelatedOids(c);return t.insertLocalOperations(p.map(u=>({oid:u,timestamp:e(),data:{op:"delete"}})))}},i),{})}function qs({migration:r,context:t,meta:e}){return r.oldCollections.reduce((n,i)=>(n[i]={get:async o=>{let s=Z(i,o);return await e.getDocumentSnapshot(s,{to:e.time.now(r.oldSchema.version)})},findOne:async o=>{let s=await an({collection:i,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(r.oldSchema.version)}):null},findAll:async o=>{let s=await cn({collection:i,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(r.oldSchema.version)})))}},n),{})}function Hs({meta:r,migration:t,context:e}){function n(){return r.time.zero(t.version)}let i=new Array,o=qs({migration:t,context:e,meta:r}),s=Gi({migration:t,getMigrationNow:n,newOids:i,meta:r}),c=async m=>{let S=await r.getAllCollectionRelatedOids(m);return r.insertLocalOperations(S.map(g=>({oid:g,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:i,deleteCollection:c,migrate:async(m,S)=>{let g=await o[m].findAll();await Promise.all(g.filter(Boolean).map(async _=>{let w=ne(_);L(!!w,`Document is missing an OID: ${JSON.stringify(_)}`);let v=ae(_),I=await S(_);if(I){ft(v),ft(I),Ge(I);let x=ht(v,I,n,void 0,[],{mergeUnknownObjects:!0});x.length>0&&await r.insertLocalOperations(x)}}))},queries:o,mutations:s,awaitables:p}}function Ws({meta:r,migration:t,context:e}){function n(){return r.time.zero(t.version)}let i=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Gi({migration:t,getMigrationNow:n,newOids:i,meta:r});return{log:e.log,newOids:i,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function Qs(r){return new Promise((t,e)=>{let n=r.getAllKeys();n.onsuccess=i=>{t(n.result)},n.onerror=i=>{e(n.error)}})}async function Js(r,t){let e=r.delete(t);return new Promise((n,i)=>{e.onsuccess=o=>{n()},e.onerror=o=>{i(e.error)}})}async function Ys(r,t){let e=r.put(t);return new Promise((n,i)=>{e.onsuccess=o=>{n()},e.onerror=o=>{i(e.error)}})}async function Gs({meta:r,currentVersion:t,newVersion:e}){let n=[];return await r.operations.iterateOverAllOperations(i=>n.push(i),{from:r.time.zero(t+1)}),Array.from(new Set(n.map(i=>$(i.oid))))}var St=class extends V{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let n=await e();return n&&this._undone.push(n),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let n=await e();return n&&this._undoable.push(n),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var un=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,i=e[n];return L(i,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,i)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return Pe(n,e)};this.create=(t,e,n={})=>{let i=this.addDefaults(t,e),o=this.getOid(t,i);return this.entities.create(i,o,n)};this.delete=async(t,e,n={})=>{let i=Z(t,e);return this.entities.delete(i,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,i])=>Z(n,i)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(i=>Z(t,i)),n)}};var et=Symbol("entity-file-update"),xt=Symbol("entity-file-mark-failed"),Xs,Zs,de=class extends V{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Xs]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Zs]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=n}static{Xs=et,Zs=xt}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return{id:this.id,url:this.loading||this.failed?void 0:this.url}}};var Xi=Qe(at(),1);function ea(r){return{id:(0,Xi.default)(),file:r,url:void 0,remote:!1,name:r.name,type:r.type}}function Er(r){return r instanceof File||typeof Blob<"u"&&r instanceof Blob}function tt(r,t){if(typeof window<"u"&&Er(r)){let e=ea(r);return t(e),Mt(e.id)}if(Array.isArray(r)){for(let e=0;e<r.length;e++)r[e]=tt(r[e],t);return r}if(typeof r=="object"){for(let e in r)r[e]=tt(r[e],t);return r}return r}function Zi(r){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(r)})}var fn=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:i=!1}={})=>{let o=e.file?await Zi(e.file):void 0;if(!o&&i&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),{mode:"readwrite",transaction:n})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?ta(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(!i)throw new Error("File is not in local database");return this.run("files",o=>o.put({...i,remote:"true"}),{mode:"readwrite",transaction:n})};this.getFileRaw=async(e,{transaction:n}={})=>{let i=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:n});if(i)return i};this.getFile=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(i)return this.hydrateFileData(i)};this.markPendingDelete=async(e,{transaction:n}={})=>{let i=await this.getFileRaw(e,{transaction:n});if(!i)throw new Error("File is not in local database");return this.run("files",o=>o.put({...i,deletedAt:Date.now()}),{mode:"readwrite",transaction:n})};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",i=>i.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(i,o)=>{e(this.hydrateFileData(i),o)},{mode:"readwrite",transaction:n})}deleteFile(e,{transaction:n}={}){return this.run("files",i=>i.delete(e),{mode:"readwrite",transaction:n})}};function ta(r,t){return new Blob([r],{type:t})}function na(r){return r.deletedAt!==null&&r.deletedAt<Date.now()-1e3*60*24*3}var pn=class{constructor({db:t,sync:e,context:n,meta:i,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[et](e);else{let n=new de(e.id);n[et](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=(t,e)=>{if(this.files.has(t))return this.files.get(t);let n=new de(t,e);return this.files.set(t,n),this.load(n),n};this.load=async(t,e=0)=>{if(e>5){this.context.log("error","Failed to load file after 5 retries"),t[xt]();return}let n=await this.storage.getFile(t.id);if(n)t[et](n);else try{let i=await this.sync.getFile(t.id);i.success?(t[et](i.data),await this.storage.addFile(i.data,{downloadRemote:t.downloadRemote})):(this.context.log("error","Failed to load file",i),t[xt](),i.retry&&setTimeout(this.load,1e3,t,e+1))}catch(i){this.context.log("error","Failed to load file",i),t[xt](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,i)=>{this.config.canCleanupDeletedFile(n)?(t++,i.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(i){this.context.log("error","Failed to mark file for deletion",i)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new fn(t),this.sync=e,this.context=n,this.meta=i,this.config={canCleanupDeletedFile:na,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var hn=class{constructor({initial:t}={}){this.cache=new Map;this.get=t=>{if(this.cache.has(t.oid))return this.cache.get(t.oid);let e=new ue(t);return this.cache.set(t.oid,e),e};this.has=t=>this.cache.has(t);this.getFile=(t,e)=>{if(this.cache.has(t))return this.cache.get(t);let n=new de(t,e);return this.cache.set(t,n),n};this.getCached=t=>this.cache.get(t);if(t)for(let e of t)this.cache.set(e.oid,e)}};var ue=class r extends V{constructor({oid:e,schema:n,entityFamily:i,parent:o,ctx:s,metadataFamily:c,readonlyKeys:p,files:u,patchCreator:m,events:S}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,n)=>{n.oid===this.oid&&this.addConfirmedData(n)};this.onReplace=(e,n)=>{n.oid===this.oid&&this.replaceAllData(n)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof r){let n=e.view;return n==null}return e==null};this.validate=Ni(()=>(this.validationError=Fe({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let n=this.view;if(!n)return null;if(Array.isArray(n)){let i=n.map(o=>o instanceof r||o instanceof de?e(o):o);return K(i,this.oid),i}else{let i=Object.entries(n).reduce((o,[s,c])=>(c instanceof r||c instanceof de?o[s]=e(c):o[s]=c,o),{});return K(i,this.oid),i}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid);let n=this.metadataFamily.addPendingData(e);for(let i of n)this.change(i)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let n=this.metadataFamily.addConfirmedData(e);for(let i of n)this.change(i)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let n=this.metadataFamily.replaceAllData(e);for(let i of n)this.change(i)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let n of e)this.change(n)};this.change=e=>{if(e.oid===this.oid)this._viewData=void 0,this.cachedView=void 0,this.deepChange(this,e),this.ctx.log("Emitting change event",this.oid),this.emit("change",{isLocal:e.isLocal}),this.parent||(this.deleted&&!this.wasDeletedLastChange?(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):!this.deleted&&this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1));else{let n=this.entityFamily.getCached(e.oid);n&&n instanceof r&&n.change(e)}};this.deepChange=(e,n)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.ctx.log("debug","Deep change detected at",this.oid,"reset cached view"),this.ctx.log("debug","Emitting deep change event",this.oid),this.emit("changeDeep",e,n),this.parent?.deepChange(e,n)};this.getChild=(e,n)=>{let i=Ne(this.schema,e);if(!i)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:n,schema:i,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,events:this.events})};this.get=e=>{eo(e);let n=this.rawView;if(!n)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let i=n[e],o=Ne(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(i))if(be(i)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(i.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,i.id);else return Fe({field:o,value:i,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?_e(o)?ur(o):we(o)?null:void 0:i};this.processInputValue=(e,n)=>{if(this.readonlyKeys.includes(n))throw new Error(`Cannot set readonly key ${n.toString()}`);Er(e)||(e=ae(e,!1));let i=Ne(this.schema,n);if(i){Le(e,i);let o=Fe({field:i,value:e,fieldPath:[...this.fieldPath,n]});if(o)throw new Error(o.message)}return tt(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let n=this.schema.properties[e];if(!n||n.type==="any")return"delete";if(n.type==="map")return!1;if(n.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof r)return he(e.oid);if(e instanceof de)return Mt(e.id);if(typeof e=="object"){let n=pe(e);if(!n||!this.entityFamily.has(n))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return he(n)}else return e};this.set=(e,n)=>{eo(e),this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(n,e)))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)ra(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let n=this.getDeleteMode(e);if(!n)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);n==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:n=!0,replaceSubObjects:i=!1}={})=>{if(!n&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let o={};K(o,this.oid);for(let[s,c]of Object.entries(e)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let p=Ne(this.schema,s);p&&Le(c,p),o[s]=this.processInputValue(c,s)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),o,{mergeUnknownObjects:!i,defaultUndefined:n}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,n)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(n,e)))};this.move=(e,n)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,n))};this.moveItem=(e,n)=>{let i=this.getItemRefValue(e);if(Q(i))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,i,n));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,n)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let n=this.getItemRefValue(e);return Q(n)?this.view.some(i=>{if(Q(i))return Ye(i,n)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.__getViewData__=(e,n)=>this.metadataFamily.get(e).computeView(n==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=p||[],this.ctx=s,this.files=u,this.schema=n,this.entityFamily=i||new hn({initial:[this]}),this.patchCreator=m,this.metadataFamily=c,this.events=S,this.parent=o,this.parent||(S.add.attach(this.onAdd),S.replace.attach(this.onReplace),S.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!we(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!U(e))return _e(this.schema)?ur(this.schema):null;if(this.cachedView=this.isList?[]:{},K(this.cachedView,this.oid),Array.isArray(e)){let i=Ne(this.schema,0);if(!i)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!we(i)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(U(e)){let i=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of i){let s=Ne(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let c=this.get(o);if(this.childIsNull(c)&&!we(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=c}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(n=>{if(n instanceof r){let i=n.deepUpdatedAt;i&&(!e||i>e)&&(e=i)}}):this.values().forEach(n=>{if(n instanceof r){let i=n.deepUpdatedAt;i&&(!e||i>e)&&(e=i)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get length(){return this.view.length}[Symbol.iterator](){let e=0,n=this.view?.length;return{next:()=>e<n?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function eo(r){if(typeof r=="symbol")throw new Error("Symbol keys aren't supported")}function ra(r){if(typeof r!="number")throw new Error("Only number keys are supported in list entities")}var Cr=class{constructor({oid:t,ctx:e,confirmedOperations:n,pendingOperations:i,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(t=!1)=>{let e=ae(this.baseline?.snapshot??void 0),n=this.baseline?.timestamp??null,i=this.applyOperations(e,!e,this.confirmedOperations,n,n);i.futureSeen&&this.ctx.globalEvents.emit("futureSeen",i.futureSeen);let o=t?i:this.applyOperations(i.view,i.deleted,this.pendingOperations,i.latestTimestamp,null);o.view&&K(o.view,this.oid);let s=!!i.latestTimestamp&&Xn(i.latestTimestamp,this.ctx.getNow())<0,c=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;c&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let p=o.latestTimestamp??i.latestTimestamp??n,u=p?Zn(p):0;if(!o.view&&!o.deleted&&!c){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:o.view??void 0,deleted:o.deleted,empty:c,fromOlderVersion:s,updatedAt:u}};this.addBaseline=t=>{if(!(this.baseline&&this.baseline.timestamp>=t.timestamp))for(this.baseline=t;this.confirmedOperations[0]?.timestamp<t.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=t=>{let e=0;for(let n of t){let i=this.confirmedOperations.findIndex(s=>s.timestamp>=n.timestamp);i!==-1?this.confirmedOperations[i].timestamp!==n.timestamp&&(this.confirmedOperations.splice(i,0,n),e++):(this.confirmedOperations.push(n),e++);let o=this.pendingOperations.length;this.pendingOperations=this.pendingOperations.filter(s=>n.timestamp!==s.timestamp),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=t=>{this.pendingOperations.push(t)};this.applyOperations=(t,e,n,i,o)=>{let s,c=this.ctx.getNow();for(let p of n)if(!(o&&p.timestamp<=o)){if(Xn(p.timestamp,c)>0){s=p.timestamp;continue}p.data.op==="delete"?e=!0:(t=je(t,p.data),p.data.op==="initialize"&&(e=!1)),(!i||p.timestamp>i)&&(i=p.timestamp)}return{view:t,latestTimestamp:i??null,deleted:e,futureSeen:s}};L(t,"oid is required"),this.ctx=e,this.oid=t,n&&(this.confirmedOperations=n),i&&(this.pendingOperations=i),o&&(this.baseline=o)}},mn=class{constructor({ctx:t,onPendingOperations:e,rootOid:n}){this.entities=new Map;this.get=t=>(L(t,"oid is required"),this.entities.has(t)||this.entities.set(t,new Cr({oid:t,ctx:this.ctx})),this.entities.get(t));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:t=[],operations:e={},isLocal:n=!1})=>{let i={};for(let o of t){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(i[o]??={oid:o,isLocal:n})}return Object.values(i)};this.addPendingData=t=>{let e={};for(let n of t)this.get(n.oid).addPendingOperation(n),e[n.oid]??={oid:n.oid,isLocal:!0};return this.onPendingOperations(t),Object.values(e)};this.replaceAllData=({operations:t={},baselines:e=[]})=>{let n=Array.from(this.entities.keys());this.entities.clear();let i={};for(let o of n)i[o]={oid:o,isLocal:!1};for(let o of e){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),i[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(t)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),i[o]??={oid:o,isLocal:!1}}return Object.values(i)};this.ctx=t,this.rootOid=n,this.onPendingOperations=e}};var Ot="@@default",gn=class{constructor({batchTimeout:t=200,meta:e,ctx:n,entities:i}){this.currentBatchKey=Ot;this.flushOperations=async(t,e,n)=>{if(this.ctx.log("debug","Flushing",t.length,"operations from batch",e,"to storage / sync"),!!t.length){for(let i of t)i.timestamp=this.meta.now;await this.commitOperations(t,n)}};this.commitOperations=async(t,e)=>{if(t.length){if(e.undoable){let n=await this.createUndo({ops:t,source:e.source});n&&this.ctx.undoHistory.addUndo(n)}await this.entities.addData({operations:t,baselines:[],isLocal:!0})}};this.addOperations=t=>{t.length&&(this.batcher.add({key:this.currentBatchKey,items:t}),this.ctx.log("debug","added",t.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:t=!0,batchName:e=Nt(),max:n=null,timeout:i=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:n,timeout:i,items:[],userData:{undoable:t}}),s={run:c=>(this.currentBatchKey=e,c(),this.currentBatchKey=Ot,s),commit:async()=>(await this.batcher.flush(Ot),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async t=>{let e=await this.getInverseOperations(t);return e.length?async()=>{let n=await this.createUndo({ops:e,source:t.source});for(let i of e)i.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),n}:null};this.getInverseOperations=async({ops:t,source:e})=>{let n=mt(t),i=[],o=()=>this.meta.now;return await Promise.all(Object.entries(n).map(async([s,c])=>{let u=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!u){this.ctx.log("warn","could not find entity",s,"for undo operation",t);return}let m=Li(s,u.view,c,o);i.unshift(...m)})),i};this.meta=e,this.ctx=n,this.entities=i,this.defaultBatchTimeout=t,this.batcher=new Xe(this.flushOperations),this.batcher.add({key:Ot,items:[],max:100,timeout:t,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Ot}};var yn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),n=this.ctx.documentDb.transaction(e,"readwrite");await Promise.all(e.map(i=>{let o=n.objectStore(i);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,n)=>{if(e.length===0)return;let i=Array.from(new Set(e.map(s=>me(s.oid).collection))),o={transaction:this.createTransaction(i,{mode:"readwrite",abort:n?.abort})};await Promise.all(e.map(async s=>{let c=s.getSnapshot();try{await this.saveDocument(s.oid,c,o)}catch(p){throw this.ctx.log("error",`Error saving document ${s.oid} (${JSON.stringify(c)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",i);for(let s of e)this.ctx.entityEvents.emit("documentChanged",s.oid)};this.saveDocument=async(e,n,{transaction:i})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,n);let{collection:o,id:s}=me(e);if(!n)await this.run(o,c=>c.delete(s),{mode:"readwrite",transaction:i}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let c=this.ctx.schema.collections[o],p=Ht(c,n);await this.run(o,u=>u.put(p),{mode:"readwrite",transaction:i}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,n)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",n=>{this.db=n}))}};var En=Qe(Bo(),1);var Cn=class extends Ie{constructor({ctx:e,meta:n,files:i}){super();this.events={add:new En.WeakEvent,replace:new En.WeakEvent,resetAll:new En.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let n=e?.baselines??[],i=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:i.length,baselines:n.length,reset:!!e.reset});let o=Array.from(new Set(n.map(m=>$(m.oid)).concat(i.map(m=>$(m.oid))))),s=Ri(n),c=Ti(i);this.ctx.log("debug","Applying data to live entities");for(let m of o){let S=s[m],g=c[m]??[],_=mt(g),w=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(m);v?v.then(()=>{w.invoke(this,{oid:m,baselines:S,operations:_,isLocal:!1})}):(this.cache.has(m)&&this.ctx.log("debug","Cache has",m,", an event should follow."),w.invoke(this,{oid:m,baselines:S,operations:_,isLocal:!1}))}let p={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,p);let u=await Promise.all(o.map(async m=>await this.hydrate(m,p)??{oid:m,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(u,p)}catch(m){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",m):this.ctx.log("error","Error saving entities to queryable storage",m)}};this.hydrate=async(e,n)=>{if(!Pi(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let i=this.pendingEntityPromises.get(e);if(i)return this.ctx.log("debug","Waiting for entity hydration",e),i;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,n);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,n,{undoable:i=!0}={})=>{this.ctx.log("debug","Creating new entity",n);let{collection:o}=me(n);Vt(e);let s=tt(e,this.files.add);K(s,n);let c=this.constructEntity(n);if(!c)throw new Error(`Could not put new document: no schema exists for collection ${o}`);let p=this.meta.patchCreator.createInitialize(s,n);await this.batcher.commitOperations(p,{undoable:!!i,source:c});let u=mt(p);return this.events.add.invoke(this,{operations:u,isLocal:!0,oid:n}),this.cache.set(n,this.ctx.weakRef(c)),c};this.deleteAll=async(e,n)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let i=await Promise.all(e.flatMap(async s=>(await this.hydrate(s))?.__getFamilyOids__()??[]));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=this.meta.patchCreator.createDeleteAll(i.flat());await this.batcher.commitOperations(o,{undoable:n?.undoable===void 0?!0:n.undoable})};this.delete=async(e,n)=>this.deleteAll([e],n);this.getCollectionSchema=e=>{let n=this.ctx.schema.collections[e];return n?{schema:{type:"object",nullable:!1,properties:n.fields},readonlyKeys:[n.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:n}=me(e),{schema:i,readonlyKeys:o}=this.getCollectionSchema(n);if(!i)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new mn({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new ue({ctx:this.ctx,oid:e,schema:i,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,events:this.events})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.loadEntity=async(e,n)=>{let{operations:i,baselines:o}=await this.meta.getDocumentData(e.oid,n);return!o.length&&!Object.keys(i).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:i,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=n,this.files=i,this.queryableStorage=new yn({ctx:e}),this.batcher=new gn({ctx:e,meta:n,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Kr=Symbol("handleMessage"),wa,Dt=class extends V{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:i}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[wa]=async(e,n)=>{let i=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,i=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,c]of Object.entries(n.peerPresence))this.isSelf(e,c)?(this._self=c,this._selfReplicaIds.add(c.replicaId),this.emit("selfChanged",c)):(i=!0,o.add(s),this._peers[s]=c,this.emit("peerChanged",s,c))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],i=!0,this.emit("peerLeft",n.userId,s)}i&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((i,o)=>({...i,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=i,this._updateBatcher=new Xe(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{wa=Kr}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var _n=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:i}=await this.endpointProvider.getEndpoints(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${i}`}});return s.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let i=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return i.ok?{success:!0,data:await i.json()}:(this.log("error","File information fetch failed",i.status,await i.text()),{success:!1,retry:i.status>=500||i.status===404})}catch(i){return this.log("error","File information fetch failed",i),{success:!1,error:i,retry:!0}}};this.endpointProvider=t,this.log=e}};var rt=class extends V{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:i=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&i&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Pn=class extends V{constructor({endpointProvider:e,meta:n,presence:i,interval:o=15*1e3,log:s=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:i}=await this.endpointProvider.getEndpoints(),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let c of s.messages)this.handleServerMessage(c);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();Ui(s)&&s.code===4012&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=s,this.meta=n,this.presence=i,this.endpointProvider=e,this.heartbeat=new rt({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function $r(r){this.message=r}$r.prototype=new Error,$r.prototype.name="InvalidCharacterError";var Mo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new $r("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,i=0,o=0,s="";n=t.charAt(o++);~n&&(e=i%4?64*e+n:n,i++%4)?s+=String.fromCharCode(255&e>>(-2*i&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function va(r){var t=r.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Mo(e).replace(/(.)/g,function(n,i){var o=i.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return Mo(t)}}function An(r){this.message=r}function Sa(r,t){if(typeof r!="string")throw new An("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(va(r.split(".")[e]))}catch(n){throw new An("Invalid token specified: "+n.message)}}An.prototype=new Error,An.prototype.name="InvalidTokenError";var jo=Sa;var Tn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(c=>{if(c.ok)return c.json();throw new Error(`Auth endpoint returned non-200 response: ${c.status}`)}),L(t.accessToken,"No access token provided from auth endpoint");let e=jo(t.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let i=n.toString();n.protocol=n.protocol.replace("http","ws");let o=n.toString(),s=e.file;if(!s){let c=new URL(i);c.pathname=c.pathname+"/files",s=c.toString()}return this.cached={http:i,websocket:o,files:s,token:t.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var Rn=class extends V{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},Fn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var kn=class extends V{constructor({endpointProvider:e,meta:n,presence:i,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new rt;this.reconnectScheduler=new Rn(new Fn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(n.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let i of this.syncQueue)this.send(i);this.syncQueue=[]}if(this.emit("message",n),this.incomingQueue.length){for(let i of this.incomingQueue)this.emit("message",i);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",n),this.incomingQueue.push(n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=n,this.presence=i,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Bn=class extends V{constructor(){super(...arguments);this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new Dt({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},it=class extends V{constructor({authEndpoint:e,fetchAuth:n,initialPresence:i,automaticTransportSelection:o=!0,autoStart:s,initialTransport:c,pullInterval:p,presenceUpdateBatchTimeout:u,defaultProfile:m,useBroadcastChannel:S},{meta:g,log:_,onData:w}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let i of e.operations)this.meta.time.update(i.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Kr](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=g,this.onData=w,this.log=_||(()=>{}),this.presence=new Dt({initialPresence:i,defaultProfile:m,updateBatchTimeout:u}),this.endpointProvider=new Tn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new kn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log}),this.pushPullSync=new Pn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log,interval:p}),this.fileSync=new _n({endpointProvider:this.endpointProvider,log:this.log}),S&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),c==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let v=()=>{I&&clearTimeout(I);let D=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;D&&this.mode==="pull"?this.setMode("realtime"):!D&&this.mode==="realtime"&&(I=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},I;this.presence.subscribe("peersChanged",v),o!=="peers-only"&&this.presence.subscribe("selfChanged",v)}s&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};function Oa(r){return r!==null}function zr(r){return Array.isArray(r)?r.map(zr).filter(Oa):r instanceof ue&&r.deleted?null:r}function ke(r,t){return!r&&!t||r&&t&&Te(r)===Te(t)}var qr=Symbol("ON_ALL_UNSUBSCRIBED"),fe=Symbol("UPDATE"),Ia,ge=class extends Ie{constructor({initial:e,context:n,collection:i,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{if(this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=zr(e),Array.isArray(this._value)&&this._value.some(n=>n.getSnapshot()===null))debugger;this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ue&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ue&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Ia]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new V(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=o,this.collection=i;let c=s||(p=>p.includes(i));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{c(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ia=qr}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var Mn=class extends ge{constructor({id:e,hydrate:n,...i}){super({initial:null,...i});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(i.collection,e),this.hydrate=n}};var Da,jn=class extends ge{constructor({index:e,hydrate:n,...i}){super({initial:null,...i});this.run=async()=>{let e=await an({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Da]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Da=fe}};var Ea,Ln=class extends ge{constructor({index:e,hydrate:n,pageSize:i,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Ea]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=i,this._page=o}static{Ea=fe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ca,Nn=class extends ge{constructor({hydrate:e,pageSize:n,index:i,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await wt({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ca]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=i,this.hydrate=e,this._pageSize=n}static{Ca=fe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var _a,Vn=class extends ge{constructor({index:e,hydrate:n,...i}){super({initial:[],...i});this.run=async()=>{let e=await cn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[_a]=e=>{ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{_a=fe}};var Un=class{constructor({collection:t,cache:e,entities:n,context:i,documentManager:o}){this.serializeIndex=t=>t?Te(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new Mn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new jn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),i=>{i[fe](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new Vn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),i=>{i[fe](t)})};this.findPage=({index:t,pageSize:e,page:n,key:i})=>{let o=i||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new Ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[fe](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let i=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(i,()=>new Nn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:i,pageSize:e}),o=>{o[fe](t)})};this.cache=e,this.collection=t,this.hydrate=n.hydrate,this.context=i,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var Kn=class extends Ie{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[qr](this.onQueryUnsubscribed),e}getOrSet(e,n,i){let o=this.get(e);return o?(i?.(o),o):this.set(n())}};var He=class extends V{constructor(e,n,i){super();this.config=e;this.context=n;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let u of e)try{n[u]=await yt(this.documentDb,u)}catch(m){this.context.log?.("error",m)}let i=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((u,{size:m})=>u+m,0),c=i.baselinesSize.size+i.operationsSize.size,p=c/s;return{collections:n,meta:i,storage:o,totalMetaSize:c,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ke(this.documentDb),await Ke(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Yt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ke(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let i=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((c,p)=>{o.onsuccess=c,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:i}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ke(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await vt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.meta=i.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new it(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new Bn,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new pn({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new Cn({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new Kn({context:n}),this._documentManager=new un(this.meta,this.schema,this._entities);let o=Di(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,c]of Object.entries(n.schema.collections)){let p=s;this[p]=new Un({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var Et=class{constructor(t){this.value=t}deref(){return this.value}};var Lo=Symbol("metadataVersion");var $n=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let e=t[Lo],{db:n}=await on({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),i={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:m=>t.EXPERIMENTAL_weakRefs?new WeakRef(m):new Et(m),migrations:t.migrations},o=new bt({context:i,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=Object.assign(i,{getNow:()=>o.now}),c=await vt({context:s,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),p=Object.assign(s,{documentDb:c});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Te(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:i}=await Hi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:i,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new St,entityEvents:new V,globalEvents:new V,internalEvents:new V,weakRef:S=>t.EXPERIMENTAL_weakRefs?new WeakRef(S):new Et(S),migrations:t.migrations},s=new bt({context:o,disableRebasing:t.disableRebasing}),c=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(t.schema,t.overrideSchemaConflict);let p=await Yi({context:c,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),u=Object.assign(c,{documentDb:p});return new He({syncConfig:t.sync,migrations:t.migrations,files:t.files},u,{meta:s})};this.cleanupWIPDatabases=async t=>{let i=(await zi(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Te(t.schema)}`));for(let o of i)await $i(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Yt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=Hr;
|
|
16
16
|
//# sourceMappingURL=index.js.map
|