@verdant-web/store 5.4.4 → 5.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,18 +1,18 @@
1
- "use strict";var Oo=Object.create;var jt=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var _o=Object.getOwnPropertyNames;var Eo=Object.getPrototypeOf,Po=Object.prototype.hasOwnProperty;var Co=(i,n)=>()=>(i&&(n=i(i=0)),n);var he=(i,n)=>()=>(n||i((n={exports:{}}).exports,n),n.exports),mr=(i,n)=>{for(var e in n)jt(i,e,{get:n[e],enumerable:!0})},gr=(i,n,e,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of _o(n))!Po.call(i,r)&&r!==e&&jt(i,r,{get:()=>n[r],enumerable:!(t=Io(n,r))||t.enumerable});return i};var Me=(i,n,e)=>(e=i!=null?Oo(Eo(i)):{},gr(n||!i||!i.__esModule?jt(e,"default",{value:i,enumerable:!0}):e,i)),it=i=>gr(jt({},"__esModule",{value:!0}),i);var Ir=he((Sr,Or)=>{(function(i){var n;typeof Sr=="object"?Or.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?n=window:typeof global<"u"?n=global:typeof self<"u"&&(n=self),n.objectHash=i())})(function(){return function i(n,e,t){function r(a,l){if(!e[a]){if(!n[a]){var p=typeof require=="function"&&require;if(!l&&p)return p(a,!0);if(s)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}l=e[a]={exports:{}},n[a][0].call(l.exports,function(f){var S=n[a][1][f];return r(S||f)},l,l.exports,i,n,e,t)}return e[a].exports}for(var s=typeof require=="function"&&require,o=0;o<t.length;o++)r(t[o]);return r}({1:[function(i,n,e){(function(t,r,s,o,a,l,p,f,S){"use strict";var w=i("crypto");function A(b,O){O=_(b,O);var u;return(u=O.algorithm!=="passthrough"?w.createHash(O.algorithm):new F).write===void 0&&(u.write=u.update,u.end=u.update),P(O,u).dispatch(b),u.update||u.end(""),u.digest?u.digest(O.encoding==="buffer"?void 0:O.encoding):(b=u.read(),O.encoding!=="buffer"?b.toString(O.encoding):b)}(e=n.exports=A).sha1=function(b){return A(b)},e.keys=function(b){return A(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return A(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return A(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var y=w.getHashes?w.getHashes().slice():["sha1","md5"],I=(y.push("passthrough"),["buffer","hex","binary","base64"]);function _(b,O){var u={};if(u.algorithm=(O=O||{}).algorithm||"sha1",u.encoding=O.encoding||"hex",u.excludeValues=!!O.excludeValues,u.algorithm=u.algorithm.toLowerCase(),u.encoding=u.encoding.toLowerCase(),u.ignoreUnknown=O.ignoreUnknown===!0,u.respectType=O.respectType!==!1,u.respectFunctionNames=O.respectFunctionNames!==!1,u.respectFunctionProperties=O.respectFunctionProperties!==!1,u.unorderedArrays=O.unorderedArrays===!0,u.unorderedSets=O.unorderedSets!==!1,u.unorderedObjects=O.unorderedObjects!==!1,u.replacer=O.replacer||void 0,u.excludeKeys=O.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var m=0;m<y.length;++m)y[m].toLowerCase()===u.algorithm.toLowerCase()&&(u.algorithm=y[m]);if(y.indexOf(u.algorithm)===-1)throw new Error('Algorithm "'+u.algorithm+'" not supported. supported values: '+y.join(", "));if(I.indexOf(u.encoding)===-1&&u.algorithm!=="passthrough")throw new Error('Encoding "'+u.encoding+'" not supported. supported values: '+I.join(", "));return u}function E(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 P(b,O,u){u=u||[];function m(d){return O.update?O.update(d,"utf8"):O.write(d,"utf8")}return{dispatch:function(d){return this["_"+((d=b.replacer?b.replacer(d):d)===null?"null":typeof d)](d)},_object:function(d){var v,x=Object.prototype.toString.call(d),L=/\[object (.*)\]/i.exec(x);if(L=(L=L?L[1]:"unknown:["+x+"]").toLowerCase(),0<=(x=u.indexOf(d)))return this.dispatch("[CIRCULAR:"+x+"]");if(u.push(d),s!==void 0&&s.isBuffer&&s.isBuffer(d))return m("buffer:"),m(d);if(L==="object"||L==="function"||L==="asyncfunction")return x=Object.keys(d),b.unorderedObjects&&(x=x.sort()),b.respectType===!1||E(d)||x.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(x=x.filter(function(B){return!b.excludeKeys(B)})),m("object:"+x.length+":"),v=this,x.forEach(function(B){v.dispatch(B),m(":"),b.excludeValues||v.dispatch(d[B]),m(",")});if(!this["_"+L]){if(b.ignoreUnknown)return m("["+L+"]");throw new Error('Unknown object type "'+L+'"')}this["_"+L](d)},_array:function(d,B){B=B!==void 0?B:b.unorderedArrays!==!1;var x=this;if(m("array:"+d.length+":"),!B||d.length<=1)return d.forEach(function(j){return x.dispatch(j)});var L=[],B=d.map(function(j){var k=new F,Q=u.slice();return P(b,k,Q).dispatch(j),L=L.concat(Q.slice(u.length)),k.read().toString()});return u=u.concat(L),B.sort(),this._array(B,!1)},_date:function(d){return m("date:"+d.toJSON())},_symbol:function(d){return m("symbol:"+d.toString())},_error:function(d){return m("error:"+d.toString())},_boolean:function(d){return m("bool:"+d.toString())},_string:function(d){m("string:"+d.length+":"),m(d.toString())},_function:function(d){m("fn:"),E(d)?this.dispatch("[native]"):this.dispatch(d.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(d.name)),b.respectFunctionProperties&&this._object(d)},_number:function(d){return m("number:"+d.toString())},_xml:function(d){return m("xml:"+d.toString())},_null:function(){return m("Null")},_undefined:function(){return m("Undefined")},_regexp:function(d){return m("regex:"+d.toString())},_uint8array:function(d){return m("uint8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint8clampedarray:function(d){return m("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(d))},_int8array:function(d){return m("int8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint16array:function(d){return m("uint16array:"),this.dispatch(Array.prototype.slice.call(d))},_int16array:function(d){return m("int16array:"),this.dispatch(Array.prototype.slice.call(d))},_uint32array:function(d){return m("uint32array:"),this.dispatch(Array.prototype.slice.call(d))},_int32array:function(d){return m("int32array:"),this.dispatch(Array.prototype.slice.call(d))},_float32array:function(d){return m("float32array:"),this.dispatch(Array.prototype.slice.call(d))},_float64array:function(d){return m("float64array:"),this.dispatch(Array.prototype.slice.call(d))},_arraybuffer:function(d){return m("arraybuffer:"),this.dispatch(new Uint8Array(d))},_url:function(d){return m("url:"+d.toString())},_map:function(d){return m("map:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_set:function(d){return m("set:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_file:function(d){return m("file:"),this.dispatch([d.name,d.size,d.type,d.lastModfied])},_blob:function(){if(b.ignoreUnknown)return m("[blob]");throw Error(`Hashing Blob objects is currently not supported
1
+ "use strict";var So=Object.create;var Lt=Object.defineProperty;var Oo=Object.getOwnPropertyDescriptor;var Io=Object.getOwnPropertyNames;var _o=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Po=(n,i)=>()=>(n&&(i=n(n=0)),i);var he=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),pr=(n,i)=>{for(var e in i)Lt(n,e,{get:i[e],enumerable:!0})},mr=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of Io(i))!Eo.call(n,r)&&r!==e&&Lt(n,r,{get:()=>i[r],enumerable:!(t=Oo(i,r))||t.enumerable});return n};var Me=(n,i,e)=>(e=n!=null?So(_o(n)):{},mr(i||!n||!n.__esModule?Lt(e,"default",{value:n,enumerable:!0}):e,n)),it=n=>mr(Lt({},"__esModule",{value:!0}),n);var Or=he((xr,Sr)=>{(function(n){var i;typeof xr=="object"?Sr.exports=n():typeof define=="function"&&define.amd?define(n):(typeof window<"u"?i=window:typeof global<"u"?i=global:typeof self<"u"&&(i=self),i.objectHash=n())})(function(){return function n(i,e,t){function r(a,l){if(!e[a]){if(!i[a]){var p=typeof require=="function"&&require;if(!l&&p)return p(a,!0);if(s)return s(a,!0);throw new Error("Cannot find module '"+a+"'")}l=e[a]={exports:{}},i[a][0].call(l.exports,function(f){var S=i[a][1][f];return r(S||f)},l,l.exports,n,i,e,t)}return e[a].exports}for(var s=typeof require=="function"&&require,o=0;o<t.length;o++)r(t[o]);return r}({1:[function(n,i,e){(function(t,r,s,o,a,l,p,f,S){"use strict";var w=n("crypto");function A(b,O){O=_(b,O);var u;return(u=O.algorithm!=="passthrough"?w.createHash(O.algorithm):new F).write===void 0&&(u.write=u.update,u.end=u.update),P(O,u).dispatch(b),u.update||u.end(""),u.digest?u.digest(O.encoding==="buffer"?void 0:O.encoding):(b=u.read(),O.encoding!=="buffer"?b.toString(O.encoding):b)}(e=i.exports=A).sha1=function(b){return A(b)},e.keys=function(b){return A(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return A(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return A(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var y=w.getHashes?w.getHashes().slice():["sha1","md5"],I=(y.push("passthrough"),["buffer","hex","binary","base64"]);function _(b,O){var u={};if(u.algorithm=(O=O||{}).algorithm||"sha1",u.encoding=O.encoding||"hex",u.excludeValues=!!O.excludeValues,u.algorithm=u.algorithm.toLowerCase(),u.encoding=u.encoding.toLowerCase(),u.ignoreUnknown=O.ignoreUnknown===!0,u.respectType=O.respectType!==!1,u.respectFunctionNames=O.respectFunctionNames!==!1,u.respectFunctionProperties=O.respectFunctionProperties!==!1,u.unorderedArrays=O.unorderedArrays===!0,u.unorderedSets=O.unorderedSets!==!1,u.unorderedObjects=O.unorderedObjects!==!1,u.replacer=O.replacer||void 0,u.excludeKeys=O.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var m=0;m<y.length;++m)y[m].toLowerCase()===u.algorithm.toLowerCase()&&(u.algorithm=y[m]);if(y.indexOf(u.algorithm)===-1)throw new Error('Algorithm "'+u.algorithm+'" not supported. supported values: '+y.join(", "));if(I.indexOf(u.encoding)===-1&&u.algorithm!=="passthrough")throw new Error('Encoding "'+u.encoding+'" not supported. supported values: '+I.join(", "));return u}function E(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 P(b,O,u){u=u||[];function m(d){return O.update?O.update(d,"utf8"):O.write(d,"utf8")}return{dispatch:function(d){return this["_"+((d=b.replacer?b.replacer(d):d)===null?"null":typeof d)](d)},_object:function(d){var v,x=Object.prototype.toString.call(d),L=/\[object (.*)\]/i.exec(x);if(L=(L=L?L[1]:"unknown:["+x+"]").toLowerCase(),0<=(x=u.indexOf(d)))return this.dispatch("[CIRCULAR:"+x+"]");if(u.push(d),s!==void 0&&s.isBuffer&&s.isBuffer(d))return m("buffer:"),m(d);if(L==="object"||L==="function"||L==="asyncfunction")return x=Object.keys(d),b.unorderedObjects&&(x=x.sort()),b.respectType===!1||E(d)||x.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(x=x.filter(function(B){return!b.excludeKeys(B)})),m("object:"+x.length+":"),v=this,x.forEach(function(B){v.dispatch(B),m(":"),b.excludeValues||v.dispatch(d[B]),m(",")});if(!this["_"+L]){if(b.ignoreUnknown)return m("["+L+"]");throw new Error('Unknown object type "'+L+'"')}this["_"+L](d)},_array:function(d,B){B=B!==void 0?B:b.unorderedArrays!==!1;var x=this;if(m("array:"+d.length+":"),!B||d.length<=1)return d.forEach(function(j){return x.dispatch(j)});var L=[],B=d.map(function(j){var k=new F,Q=u.slice();return P(b,k,Q).dispatch(j),L=L.concat(Q.slice(u.length)),k.read().toString()});return u=u.concat(L),B.sort(),this._array(B,!1)},_date:function(d){return m("date:"+d.toJSON())},_symbol:function(d){return m("symbol:"+d.toString())},_error:function(d){return m("error:"+d.toString())},_boolean:function(d){return m("bool:"+d.toString())},_string:function(d){m("string:"+d.length+":"),m(d.toString())},_function:function(d){m("fn:"),E(d)?this.dispatch("[native]"):this.dispatch(d.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(d.name)),b.respectFunctionProperties&&this._object(d)},_number:function(d){return m("number:"+d.toString())},_xml:function(d){return m("xml:"+d.toString())},_null:function(){return m("Null")},_undefined:function(){return m("Undefined")},_regexp:function(d){return m("regex:"+d.toString())},_uint8array:function(d){return m("uint8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint8clampedarray:function(d){return m("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(d))},_int8array:function(d){return m("int8array:"),this.dispatch(Array.prototype.slice.call(d))},_uint16array:function(d){return m("uint16array:"),this.dispatch(Array.prototype.slice.call(d))},_int16array:function(d){return m("int16array:"),this.dispatch(Array.prototype.slice.call(d))},_uint32array:function(d){return m("uint32array:"),this.dispatch(Array.prototype.slice.call(d))},_int32array:function(d){return m("int32array:"),this.dispatch(Array.prototype.slice.call(d))},_float32array:function(d){return m("float32array:"),this.dispatch(Array.prototype.slice.call(d))},_float64array:function(d){return m("float64array:"),this.dispatch(Array.prototype.slice.call(d))},_arraybuffer:function(d){return m("arraybuffer:"),this.dispatch(new Uint8Array(d))},_url:function(d){return m("url:"+d.toString())},_map:function(d){return m("map:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_set:function(d){return m("set:"),d=Array.from(d),this._array(d,b.unorderedSets!==!1)},_file:function(d){return m("file:"),this.dispatch([d.name,d.size,d.type,d.lastModfied])},_blob:function(){if(b.ignoreUnknown)return m("[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 m("domwindow")},_bigint:function(d){return m("bigint:"+d.toString())},_process:function(){return m("process")},_timer:function(){return m("timer")},_pipe:function(){return m("pipe")},_tcp:function(){return m("tcp")},_udp:function(){return m("udp")},_tty:function(){return m("tty")},_statwatcher:function(){return m("statwatcher")},_securecontext:function(){return m("securecontext")},_connection:function(){return m("connection")},_zlib:function(){return m("zlib")},_context:function(){return m("context")},_nodescript:function(){return m("nodescript")},_httpparser:function(){return m("httpparser")},_dataview:function(){return m("dataview")},_signal:function(){return m("signal")},_fsevent:function(){return m("fsevent")},_tlswrap:function(){return m("tlswrap")}}}function F(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,O,u){return u===void 0&&(u=O,O={}),P(O=_(b,O),u).dispatch(b)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(i,n,e){(function(t,r,s,o,a,l,p,f,S){(function(w){"use strict";var A=typeof Uint8Array<"u"?Uint8Array:Array,y="+".charCodeAt(0),I="/".charCodeAt(0),_="0".charCodeAt(0),E="a".charCodeAt(0),P="A".charCodeAt(0),F="-".charCodeAt(0),b="_".charCodeAt(0);function O(u){return u=u.charCodeAt(0),u===y||u===F?62:u===I||u===b?63:u<_?-1:u<_+10?u-_+26+26:u<P+26?u-P:u<E+26?u-E+26:void 0}w.toByteArray=function(u){var m,d;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var v=u.length,v=u.charAt(v-2)==="="?2:u.charAt(v-1)==="="?1:0,x=new A(3*u.length/4-v),L=0<v?u.length-4:u.length,B=0;function j(k){x[B++]=k}for(m=0;m<L;m+=4,0)j((16711680&(d=O(u.charAt(m))<<18|O(u.charAt(m+1))<<12|O(u.charAt(m+2))<<6|O(u.charAt(m+3))))>>16),j((65280&d)>>8),j(255&d);return v==2?j(255&(d=O(u.charAt(m))<<2|O(u.charAt(m+1))>>4)):v==1&&(j((d=O(u.charAt(m))<<10|O(u.charAt(m+1))<<4|O(u.charAt(m+2))>>2)>>8&255),j(255&d)),x},w.fromByteArray=function(u){var m,d,v,x,L=u.length%3,B="";function j(k){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k)}for(m=0,v=u.length-L;m<v;m+=3)d=(u[m]<<16)+(u[m+1]<<8)+u[m+2],B+=j((x=d)>>18&63)+j(x>>12&63)+j(x>>6&63)+j(63&x);switch(L){case 1:B=(B+=j((d=u[u.length-1])>>2))+j(d<<4&63)+"==";break;case 2:B=(B=(B+=j((d=(u[u.length-2]<<8)+u[u.length-1])>>10))+j(d>>4&63))+j(d<<2&63)+"="}return B}})(e===void 0?this.base64js={}:e)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,y,o,a,l,p,f,S){var w=i("base64-js"),A=i("ieee754");function y(c,h,g){if(!(this instanceof y))return new y(c,h,g);var D,C,R,V,J=typeof c;if(h==="base64"&&J=="string")for(c=(V=c).trim?V.trim():V.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(J=="number")D=re(c);else if(J=="string")D=y.byteLength(c,h);else{if(J!="object")throw new Error("First argument needs to be a number, array or string.");D=re(c.length)}if(y._useTypedArrays?C=y._augment(new Uint8Array(D)):((C=this).length=D,C._isBuffer=!0),y._useTypedArrays&&typeof c.byteLength=="number")C._set(c);else if(q(V=c)||y.isBuffer(V)||V&&typeof V=="object"&&typeof V.length=="number")for(R=0;R<D;R++)y.isBuffer(c)?C[R]=c.readUInt8(R):C[R]=c[R];else if(J=="string")C.write(c,0,h);else if(J=="number"&&!y._useTypedArrays&&!g)for(R=0;R<D;R++)C[R]=0;return C}function I(c,h,g,D){return y._charsWritten=Lt(function(C){for(var R=[],V=0;V<C.length;V++)R.push(255&C.charCodeAt(V));return R}(h),c,g,D)}function _(c,h,g,D){return y._charsWritten=Lt(function(C){for(var R,V,J=[],X=0;X<C.length;X++)V=C.charCodeAt(X),R=V>>8,V=V%256,J.push(V),J.push(R);return J}(h),c,g,D)}function E(c,h,g){var D="";g=Math.min(c.length,g);for(var C=h;C<g;C++)D+=String.fromCharCode(c[C]);return D}function P(c,h,g,R){R||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+1<c.length,"Trying to read beyond buffer length"));var C,R=c.length;if(!(R<=h))return g?(C=c[h],h+1<R&&(C|=c[h+1]<<8)):(C=c[h]<<8,h+1<R&&(C|=c[h+1])),C}function F(c,h,g,R){R||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+3<c.length,"Trying to read beyond buffer length"));var C,R=c.length;if(!(R<=h))return g?(h+2<R&&(C=c[h+2]<<16),h+1<R&&(C|=c[h+1]<<8),C|=c[h],h+3<R&&(C+=c[h+3]<<24>>>0)):(h+1<R&&(C=c[h+1]<<16),h+2<R&&(C|=c[h+2]<<8),h+3<R&&(C|=c[h+3]),C+=c[h]<<24>>>0),C}function b(c,h,g,D){if(D||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+1<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return D=P(c,h,g,!0),32768&D?-1*(65535-D+1):D}function O(c,h,g,D){if(D||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+3<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return D=F(c,h,g,!0),2147483648&D?-1*(4294967295-D+1):D}function u(c,h,g,D){return D||(T(typeof g=="boolean","missing or invalid endian"),T(h+3<c.length,"Trying to read beyond buffer length")),A.read(c,h,g,23,4)}function m(c,h,g,D){return D||(T(typeof g=="boolean","missing or invalid endian"),T(h+7<c.length,"Trying to read beyond buffer length")),A.read(c,h,g,52,8)}function d(c,h,g,D,C){if(C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"trying to write beyond buffer length"),nn(h,65535)),C=c.length,!(C<=g))for(var R=0,V=Math.min(C-g,2);R<V;R++)c[g+R]=(h&255<<8*(D?R:1-R))>>>8*(D?R:1-R)}function v(c,h,g,D,C){if(C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"trying to write beyond buffer length"),nn(h,4294967295)),C=c.length,!(C<=g))for(var R=0,V=Math.min(C-g,4);R<V;R++)c[g+R]=h>>>8*(D?R:3-R)&255}function x(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"Trying to write beyond buffer length"),rn(h,32767,-32768)),c.length<=g||d(c,0<=h?h:65535+h+1,g,D,C)}function L(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),rn(h,2147483647,-2147483648)),c.length<=g||v(c,0<=h?h:4294967295+h+1,g,D,C)}function B(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),fr(h,34028234663852886e22,-34028234663852886e22)),c.length<=g||A.write(c,h,g,D,23,4)}function j(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+7<c.length,"Trying to write beyond buffer length"),fr(h,17976931348623157e292,-17976931348623157e292)),c.length<=g||A.write(c,h,g,D,52,8)}e.Buffer=y,e.SlowBuffer=y,e.INSPECT_MAX_BYTES=50,y.poolSize=8192,y._useTypedArrays=function(){try{var c=new ArrayBuffer(0),h=new Uint8Array(c);return h.foo=function(){return 42},h.foo()===42&&typeof h.subarray=="function"}catch{return!1}}(),y.isEncoding=function(c){switch(String(c).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}},y.isBuffer=function(c){return!(c==null||!c._isBuffer)},y.byteLength=function(c,h){var g;switch(c+="",h||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=Ae(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=ur(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":g=2*c.length;break;default:throw new Error("Unknown encoding")}return g},y.concat=function(c,h){if(T(q(c),`Usage: Buffer.concat(list, [totalLength])
5
- list should be an Array.`),c.length===0)return new y(0);if(c.length===1)return c[0];if(typeof h!="number")for(C=h=0;C<c.length;C++)h+=c[C].length;for(var g=new y(h),D=0,C=0;C<c.length;C++){var R=c[C];R.copy(g,D),D+=R.length}return g},y.prototype.write=function(c,h,g,D){isFinite(h)?isFinite(g)||(D=g,g=void 0):(X=D,D=h,h=g,g=X),h=Number(h)||0;var C,R,V,J,X=this.length-h;switch((!g||X<(g=Number(g)))&&(g=X),D=String(D||"utf8").toLowerCase()){case"hex":C=function(Oe,de,ue,Z){ue=Number(ue)||0;var Y=Oe.length-ue;(!Z||Y<(Z=Number(Z)))&&(Z=Y),T((Y=de.length)%2==0,"Invalid hex string"),Y/2<Z&&(Z=Y/2);for(var tt=0;tt<Z;tt++){var pr=parseInt(de.substr(2*tt,2),16);T(!isNaN(pr),"Invalid hex string"),Oe[ue+tt]=pr}return y._charsWritten=2*tt,tt}(this,c,h,g);break;case"utf8":case"utf-8":R=this,V=h,J=g,C=y._charsWritten=Lt(Ae(c),R,V,J);break;case"ascii":case"binary":C=I(this,c,h,g);break;case"base64":R=this,V=h,J=g,C=y._charsWritten=Lt(ur(c),R,V,J);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":C=_(this,c,h,g);break;default:throw new Error("Unknown encoding")}return C},y.prototype.toString=function(c,h,g){var D,C,R,V,J=this;if(c=String(c||"utf8").toLowerCase(),h=Number(h)||0,(g=g!==void 0?Number(g):J.length)===h)return"";switch(c){case"hex":D=function(X,Oe,de){var ue=X.length;(!Oe||Oe<0)&&(Oe=0),(!de||de<0||ue<de)&&(de=ue);for(var Z="",Y=Oe;Y<de;Y++)Z+=H(X[Y]);return Z}(J,h,g);break;case"utf8":case"utf-8":D=function(X,Oe,de){var ue="",Z="";de=Math.min(X.length,de);for(var Y=Oe;Y<de;Y++)X[Y]<=127?(ue+=hr(Z)+String.fromCharCode(X[Y]),Z=""):Z+="%"+X[Y].toString(16);return ue+hr(Z)}(J,h,g);break;case"ascii":case"binary":D=E(J,h,g);break;case"base64":C=J,V=g,D=(R=h)===0&&V===C.length?w.fromByteArray(C):w.fromByteArray(C.slice(R,V));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":D=function(X,Oe,de){for(var ue=X.slice(Oe,de),Z="",Y=0;Y<ue.length;Y+=2)Z+=String.fromCharCode(ue[Y]+256*ue[Y+1]);return Z}(J,h,g);break;default:throw new Error("Unknown encoding")}return D},y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},y.prototype.copy=function(c,h,g,D){if(h=h||0,(D=D||D===0?D:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){T(g<=D,"sourceEnd < sourceStart"),T(0<=h&&h<c.length,"targetStart out of bounds"),T(0<=g&&g<this.length,"sourceStart out of bounds"),T(0<=D&&D<=this.length,"sourceEnd out of bounds"),D>this.length&&(D=this.length);var C=(D=c.length-h<D-g?c.length-h+g:D)-g;if(C<100||!y._useTypedArrays)for(var R=0;R<C;R++)c[R+h]=this[R+g];else c._set(this.subarray(g,g+C),h)}},y.prototype.slice=function(c,h){var g=this.length;if(c=Q(c,g,0),h=Q(h,g,g),y._useTypedArrays)return y._augment(this.subarray(c,h));for(var D=h-c,C=new y(D,void 0,!0),R=0;R<D;R++)C[R]=this[R+c];return C},y.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},y.prototype.set=function(c,h){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,h)},y.prototype.readUInt8=function(c,h){if(h||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},y.prototype.readUInt16LE=function(c,h){return P(this,c,!0,h)},y.prototype.readUInt16BE=function(c,h){return P(this,c,!1,h)},y.prototype.readUInt32LE=function(c,h){return F(this,c,!0,h)},y.prototype.readUInt32BE=function(c,h){return F(this,c,!1,h)},y.prototype.readInt8=function(c,h){if(h||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},y.prototype.readInt16LE=function(c,h){return b(this,c,!0,h)},y.prototype.readInt16BE=function(c,h){return b(this,c,!1,h)},y.prototype.readInt32LE=function(c,h){return O(this,c,!0,h)},y.prototype.readInt32BE=function(c,h){return O(this,c,!1,h)},y.prototype.readFloatLE=function(c,h){return u(this,c,!0,h)},y.prototype.readFloatBE=function(c,h){return u(this,c,!1,h)},y.prototype.readDoubleLE=function(c,h){return m(this,c,!0,h)},y.prototype.readDoubleBE=function(c,h){return m(this,c,!1,h)},y.prototype.writeUInt8=function(c,h,g){g||(T(c!=null,"missing value"),T(h!=null,"missing offset"),T(h<this.length,"trying to write beyond buffer length"),nn(c,255)),h>=this.length||(this[h]=c)},y.prototype.writeUInt16LE=function(c,h,g){d(this,c,h,!0,g)},y.prototype.writeUInt16BE=function(c,h,g){d(this,c,h,!1,g)},y.prototype.writeUInt32LE=function(c,h,g){v(this,c,h,!0,g)},y.prototype.writeUInt32BE=function(c,h,g){v(this,c,h,!1,g)},y.prototype.writeInt8=function(c,h,g){g||(T(c!=null,"missing value"),T(h!=null,"missing offset"),T(h<this.length,"Trying to write beyond buffer length"),rn(c,127,-128)),h>=this.length||(0<=c?this.writeUInt8(c,h,g):this.writeUInt8(255+c+1,h,g))},y.prototype.writeInt16LE=function(c,h,g){x(this,c,h,!0,g)},y.prototype.writeInt16BE=function(c,h,g){x(this,c,h,!1,g)},y.prototype.writeInt32LE=function(c,h,g){L(this,c,h,!0,g)},y.prototype.writeInt32BE=function(c,h,g){L(this,c,h,!1,g)},y.prototype.writeFloatLE=function(c,h,g){B(this,c,h,!0,g)},y.prototype.writeFloatBE=function(c,h,g){B(this,c,h,!1,g)},y.prototype.writeDoubleLE=function(c,h,g){j(this,c,h,!0,g)},y.prototype.writeDoubleBE=function(c,h,g){j(this,c,h,!1,g)},y.prototype.fill=function(c,h,g){if(h=h||0,g=g||this.length,T(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),T(h<=g,"end < start"),g!==h&&this.length!==0){T(0<=h&&h<this.length,"start out of bounds"),T(0<=g&&g<=this.length,"end out of bounds");for(var D=h;D<g;D++)this[D]=c}},y.prototype.inspect=function(){for(var c=[],h=this.length,g=0;g<h;g++)if(c[g]=H(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},y.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(y._useTypedArrays)return new y(this).buffer;for(var c=new Uint8Array(this.length),h=0,g=c.length;h<g;h+=1)c[h]=this[h];return c.buffer};var k=y.prototype;function Q(c,h,g){return typeof c!="number"?g:h<=(c=~~c)?h:0<=c||0<=(c+=h)?c:0}function re(c){return(c=~~Math.ceil(+c))<0?0:c}function q(c){return(Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"})(c)}function H(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ae(c){for(var h=[],g=0;g<c.length;g++){var D=c.charCodeAt(g);if(D<=127)h.push(c.charCodeAt(g));else for(var C=g,R=(55296<=D&&D<=57343&&g++,encodeURIComponent(c.slice(C,g+1)).substr(1).split("%")),V=0;V<R.length;V++)h.push(parseInt(R[V],16))}return h}function ur(c){return w.toByteArray(c)}function Lt(c,h,g,D){for(var C=0;C<D&&!(C+g>=h.length||C>=c.length);C++)h[C+g]=c[C];return C}function hr(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function nn(c,h){T(typeof c=="number","cannot write a non-number as a number"),T(0<=c,"specified a negative value for writing an unsigned value"),T(c<=h,"value is larger than maximum value for type"),T(Math.floor(c)===c,"value has a fractional component")}function rn(c,h,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=h,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value"),T(Math.floor(c)===c,"value has a fractional component")}function fr(c,h,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=h,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value")}function T(c,h){if(!c)throw new Error(h||"Failed assertion")}y._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,w,o,a,l,p,f,S){var w=i("buffer").Buffer,A=4,y=new w(A);y.fill(0),n.exports={hash:function(I,_,E,P){for(var F=_(function(d,v){d.length%A!=0&&(x=d.length+(A-d.length%A),d=w.concat([d,y],x));for(var x,L=[],B=v?d.readInt32BE:d.readInt32LE,j=0;j<d.length;j+=A)L.push(B.call(d,j));return L}(I=w.isBuffer(I)?I:new w(I),P),8*I.length),_=P,b=new w(E),O=_?b.writeInt32BE:b.writeInt32LE,u=0;u<F.length;u++)O.call(b,F[u],4*u,!0);return b}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,w,o,a,l,p,f,S){var w=i("buffer").Buffer,A=i("./sha"),y=i("./sha256"),I=i("./rng"),_={sha1:A,sha256:y,md5:i("./md5")},E=64,P=new w(E);function F(d,v){var x=_[d=d||"sha1"],L=[];return x||b("algorithm:",d,"is not yet supported"),{update:function(B){return w.isBuffer(B)||(B=new w(B)),L.push(B),B.length,this},digest:function(B){var j=w.concat(L),j=v?function(k,Q,re){w.isBuffer(Q)||(Q=new w(Q)),w.isBuffer(re)||(re=new w(re)),Q.length>E?Q=k(Q):Q.length<E&&(Q=w.concat([Q,P],E));for(var q=new w(E),H=new w(E),Ae=0;Ae<E;Ae++)q[Ae]=54^Q[Ae],H[Ae]=92^Q[Ae];return re=k(w.concat([q,re])),k(w.concat([H,re]))}(x,v,j):x(j);return L=null,B?j.toString(B):j}}}function b(){var d=[].slice.call(arguments).join(" ");throw new Error([d,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
- `))}P.fill(0),e.createHash=function(d){return F(d)},e.createHmac=F,e.randomBytes=function(d,v){if(!v||!v.call)return new w(I(d));try{v.call(this,void 0,new w(I(d)))}catch(x){v(x)}};var O,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],m=function(d){e[d]=function(){b("sorry,",d,"is not implemented yet")}};for(O in u)m(u[O],O)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){var w=i("./helpers");function A(b,O){b[O>>5]|=128<<O%32,b[14+(O+64>>>9<<4)]=O;for(var u=1732584193,m=-271733879,d=-1732584194,v=271733878,x=0;x<b.length;x+=16){var L=u,B=m,j=d,k=v,u=I(u,m,d,v,b[x+0],7,-680876936),v=I(v,u,m,d,b[x+1],12,-389564586),d=I(d,v,u,m,b[x+2],17,606105819),m=I(m,d,v,u,b[x+3],22,-1044525330);u=I(u,m,d,v,b[x+4],7,-176418897),v=I(v,u,m,d,b[x+5],12,1200080426),d=I(d,v,u,m,b[x+6],17,-1473231341),m=I(m,d,v,u,b[x+7],22,-45705983),u=I(u,m,d,v,b[x+8],7,1770035416),v=I(v,u,m,d,b[x+9],12,-1958414417),d=I(d,v,u,m,b[x+10],17,-42063),m=I(m,d,v,u,b[x+11],22,-1990404162),u=I(u,m,d,v,b[x+12],7,1804603682),v=I(v,u,m,d,b[x+13],12,-40341101),d=I(d,v,u,m,b[x+14],17,-1502002290),u=_(u,m=I(m,d,v,u,b[x+15],22,1236535329),d,v,b[x+1],5,-165796510),v=_(v,u,m,d,b[x+6],9,-1069501632),d=_(d,v,u,m,b[x+11],14,643717713),m=_(m,d,v,u,b[x+0],20,-373897302),u=_(u,m,d,v,b[x+5],5,-701558691),v=_(v,u,m,d,b[x+10],9,38016083),d=_(d,v,u,m,b[x+15],14,-660478335),m=_(m,d,v,u,b[x+4],20,-405537848),u=_(u,m,d,v,b[x+9],5,568446438),v=_(v,u,m,d,b[x+14],9,-1019803690),d=_(d,v,u,m,b[x+3],14,-187363961),m=_(m,d,v,u,b[x+8],20,1163531501),u=_(u,m,d,v,b[x+13],5,-1444681467),v=_(v,u,m,d,b[x+2],9,-51403784),d=_(d,v,u,m,b[x+7],14,1735328473),u=E(u,m=_(m,d,v,u,b[x+12],20,-1926607734),d,v,b[x+5],4,-378558),v=E(v,u,m,d,b[x+8],11,-2022574463),d=E(d,v,u,m,b[x+11],16,1839030562),m=E(m,d,v,u,b[x+14],23,-35309556),u=E(u,m,d,v,b[x+1],4,-1530992060),v=E(v,u,m,d,b[x+4],11,1272893353),d=E(d,v,u,m,b[x+7],16,-155497632),m=E(m,d,v,u,b[x+10],23,-1094730640),u=E(u,m,d,v,b[x+13],4,681279174),v=E(v,u,m,d,b[x+0],11,-358537222),d=E(d,v,u,m,b[x+3],16,-722521979),m=E(m,d,v,u,b[x+6],23,76029189),u=E(u,m,d,v,b[x+9],4,-640364487),v=E(v,u,m,d,b[x+12],11,-421815835),d=E(d,v,u,m,b[x+15],16,530742520),u=P(u,m=E(m,d,v,u,b[x+2],23,-995338651),d,v,b[x+0],6,-198630844),v=P(v,u,m,d,b[x+7],10,1126891415),d=P(d,v,u,m,b[x+14],15,-1416354905),m=P(m,d,v,u,b[x+5],21,-57434055),u=P(u,m,d,v,b[x+12],6,1700485571),v=P(v,u,m,d,b[x+3],10,-1894986606),d=P(d,v,u,m,b[x+10],15,-1051523),m=P(m,d,v,u,b[x+1],21,-2054922799),u=P(u,m,d,v,b[x+8],6,1873313359),v=P(v,u,m,d,b[x+15],10,-30611744),d=P(d,v,u,m,b[x+6],15,-1560198380),m=P(m,d,v,u,b[x+13],21,1309151649),u=P(u,m,d,v,b[x+4],6,-145523070),v=P(v,u,m,d,b[x+11],10,-1120210379),d=P(d,v,u,m,b[x+2],15,718787259),m=P(m,d,v,u,b[x+9],21,-343485551),u=F(u,L),m=F(m,B),d=F(d,j),v=F(v,k)}return Array(u,m,d,v)}function y(b,O,u,m,d,v){return F((O=F(F(O,b),F(m,v)))<<d|O>>>32-d,u)}function I(b,O,u,m,d,v,x){return y(O&u|~O&m,b,O,d,v,x)}function _(b,O,u,m,d,v,x){return y(O&m|u&~m,b,O,d,v,x)}function E(b,O,u,m,d,v,x){return y(O^u^m,b,O,d,v,x)}function P(b,O,u,m,d,v,x){return y(u^(O|~m),b,O,d,v,x)}function F(b,O){var u=(65535&b)+(65535&O);return(b>>16)+(O>>16)+(u>>16)<<16|65535&u}n.exports=function(b){return w.hash(b,A,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){var w;n.exports=w||function(A){for(var y,I=new Array(A),_=0;_<A;_++)!(3&_)&&(y=4294967296*Math.random()),I[_]=y>>>((3&_)<<3)&255;return I}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){var w=i("./helpers");function A(_,E){_[E>>5]|=128<<24-E%32,_[15+(E+64>>9<<4)]=E;for(var P,F,b,O=Array(80),u=1732584193,m=-271733879,d=-1732584194,v=271733878,x=-1009589776,L=0;L<_.length;L+=16){for(var B=u,j=m,k=d,Q=v,re=x,q=0;q<80;q++){O[q]=q<16?_[L+q]:I(O[q-3]^O[q-8]^O[q-14]^O[q-16],1);var H=y(y(I(u,5),(H=m,F=d,b=v,(P=q)<20?H&F|~H&b:!(P<40)&&P<60?H&F|H&b|F&b:H^F^b)),y(y(x,O[q]),(P=q)<20?1518500249:P<40?1859775393:P<60?-1894007588:-899497514)),x=v,v=d,d=I(m,30),m=u,u=H}u=y(u,B),m=y(m,j),d=y(d,k),v=y(v,Q),x=y(x,re)}return Array(u,m,d,v,x)}function y(_,E){var P=(65535&_)+(65535&E);return(_>>16)+(E>>16)+(P>>16)<<16|65535&P}function I(_,E){return _<<E|_>>>32-E}n.exports=function(_){return w.hash(_,A,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){function w(E,P){var F=(65535&E)+(65535&P);return(E>>16)+(P>>16)+(F>>16)<<16|65535&F}function A(E,P){var F,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),O=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);E[P>>5]|=128<<24-P%32,E[15+(P+64>>9<<4)]=P;for(var m,d,v=0;v<E.length;v+=16){for(var x=O[0],L=O[1],B=O[2],j=O[3],k=O[4],Q=O[5],re=O[6],q=O[7],H=0;H<64;H++)u[H]=H<16?E[H+v]:w(w(w((d=u[H-2],I(d,17)^I(d,19)^_(d,10)),u[H-7]),(d=u[H-15],I(d,7)^I(d,18)^_(d,3))),u[H-16]),F=w(w(w(w(q,I(d=k,6)^I(d,11)^I(d,25)),k&Q^~k&re),b[H]),u[H]),m=w(I(m=x,2)^I(m,13)^I(m,22),x&L^x&B^L&B),q=re,re=Q,Q=k,k=w(j,F),j=B,B=L,L=x,x=w(F,m);O[0]=w(x,O[0]),O[1]=w(L,O[1]),O[2]=w(B,O[2]),O[3]=w(j,O[3]),O[4]=w(k,O[4]),O[5]=w(Q,O[5]),O[6]=w(re,O[6]),O[7]=w(q,O[7])}return O}var y=i("./helpers"),I=function(E,P){return E>>>P|E<<32-P},_=function(E,P){return E>>>P};n.exports=function(E){return y.hash(E,A,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){e.read=function(w,A,y,I,v){var E,P,F=8*v-I-1,b=(1<<F)-1,O=b>>1,u=-7,m=y?v-1:0,d=y?-1:1,v=w[A+m];for(m+=d,E=v&(1<<-u)-1,v>>=-u,u+=F;0<u;E=256*E+w[A+m],m+=d,u-=8);for(P=E&(1<<-u)-1,E>>=-u,u+=I;0<u;P=256*P+w[A+m],m+=d,u-=8);if(E===0)E=1-O;else{if(E===b)return P?NaN:1/0*(v?-1:1);P+=Math.pow(2,I),E-=O}return(v?-1:1)*P*Math.pow(2,E-I)},e.write=function(w,A,y,I,_,x){var P,F,b=8*x-_-1,O=(1<<b)-1,u=O>>1,m=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=I?0:x-1,v=I?1:-1,x=A<0||A===0&&1/A<0?1:0;for(A=Math.abs(A),isNaN(A)||A===1/0?(F=isNaN(A)?1:0,P=O):(P=Math.floor(Math.log(A)/Math.LN2),A*(I=Math.pow(2,-P))<1&&(P--,I*=2),2<=(A+=1<=P+u?m/I:m*Math.pow(2,1-u))*I&&(P++,I/=2),O<=P+u?(F=0,P=O):1<=P+u?(F=(A*I-1)*Math.pow(2,_),P+=u):(F=A*Math.pow(2,u-1)*Math.pow(2,_),P=0));8<=_;w[y+d]=255&F,d+=v,F/=256,_-=8);for(P=P<<_|F,b+=_;0<b;w[y+d]=255&P,d+=v,P/=256,b-=8);w[y+d-v]|=128*x}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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(i,n,e){(function(t,r,s,o,a,l,p,f,S){var w,A,y;function I(){}(t=n.exports={}).nextTick=(A=typeof window<"u"&&window.setImmediate,y=typeof window<"u"&&window.postMessage&&window.addEventListener,A?function(_){return window.setImmediate(_)}:y?(w=[],window.addEventListener("message",function(_){var E=_.source;E!==window&&E!==null||_.data!=="process-tick"||(_.stopPropagation(),0<w.length&&w.shift()())},!0),function(_){w.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=I,t.addListener=I,t.once=I,t.off=I,t.removeListener=I,t.removeAllListeners=I,t.emit=I,t.binding=function(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("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 wn=he((Tl,Qr)=>{Qr.exports=function(n,e){var t="000000000"+n;return t.substr(t.length-e)}});var Jr=he((Rl,qr)=>{var ta=wn(),ia=typeof window=="object"?window:self,na=Object.keys(ia).length,ra=navigator.mimeTypes?navigator.mimeTypes.length:0,sa=ta((ra+navigator.userAgent.length).toString(36)+na.toString(36),4);qr.exports=function(){return sa}});var Zr=he((Fl,Xr)=>{var vn,Gr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;Gr?(Yr=Math.pow(2,32)-1,vn=function(){return Math.abs(Gr.getRandomValues(new Uint32Array(1))[0]/Yr)}):vn=Math.random;var Yr;Xr.exports=vn});var Je=he((kl,ns)=>{var Xt=Jr(),es=wn(),oa=Zr(),Pt=0,Sn=4,Zt=36,ts=Math.pow(Zt,Sn);function xn(){return es((oa()*ts<<0).toString(Zt),Sn)}function is(){return Pt=Pt<ts?Pt:0,Pt++,Pt-1}function Ct(){var i="c",n=new Date().getTime().toString(Zt),e=es(is().toString(Zt),Sn),t=Xt(),r=xn()+xn();return i+n+e+t+r}Ct.slug=function(){var n=new Date().getTime().toString(36),e=is().toString(36).slice(-4),t=Xt().slice(0,1)+Xt().slice(-1),r=xn().slice(-2);return n.slice(-2)+e+t+r};Ct.isCuid=function(n){return typeof n!="string"?!1:!!n.startsWith("c")};Ct.isSlug=function(n){if(typeof n!="string")return!1;var e=n.length;return e>=7&&e<=10};Ct.fingerprint=Xt;ns.exports=Ct});var Ze={};mr(Ze,{__addDisposableResource:()=>Zs,__assign:()=>Ii,__asyncDelegator:()=>Ws,__asyncGenerator:()=>Ks,__asyncValues:()=>Hs,__await:()=>pt,__awaiter:()=>js,__classPrivateFieldGet:()=>Gs,__classPrivateFieldIn:()=>Xs,__classPrivateFieldSet:()=>Ys,__createBinding:()=>Ei,__decorate:()=>Bs,__disposeResources:()=>eo,__esDecorate:()=>qa,__exportStar:()=>Vs,__extends:()=>Fs,__generator:()=>Ns,__importDefault:()=>Js,__importStar:()=>qs,__makeTemplateObject:()=>Qs,__metadata:()=>Ls,__param:()=>Ms,__propKey:()=>Ga,__read:()=>Vn,__rest:()=>ks,__runInitializers:()=>Ja,__setFunctionName:()=>Ya,__spread:()=>Us,__spreadArray:()=>$s,__spreadArrays:()=>zs,__values:()=>_i,default:()=>ec});function Fs(i,n){if(typeof n!="function"&&n!==null)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");Nn(i,n);function e(){this.constructor=i}i.prototype=n===null?Object.create(n):(e.prototype=n.prototype,new e)}function ks(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e}function Bs(i,n,e,t){var r=arguments.length,s=r<3?n:t===null?t=Object.getOwnPropertyDescriptor(n,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(i,n,e,t);else for(var a=i.length-1;a>=0;a--)(o=i[a])&&(s=(r<3?o(s):r>3?o(n,e,s):o(n,e))||s);return r>3&&s&&Object.defineProperty(n,e,s),s}function Ms(i,n){return function(e,t){n(e,t,i)}}function qa(i,n,e,t,r,s){function o(E){if(E!==void 0&&typeof E!="function")throw new TypeError("Function expected");return E}for(var a=t.kind,l=a==="getter"?"get":a==="setter"?"set":"value",p=!n&&i?t.static?i:i.prototype:null,f=n||(p?Object.getOwnPropertyDescriptor(p,t.name):{}),S,w=!1,A=e.length-1;A>=0;A--){var y={};for(var I in t)y[I]=I==="access"?{}:t[I];for(var I in t.access)y.access[I]=t.access[I];y.addInitializer=function(E){if(w)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(E||null))};var _=(0,e[A])(a==="accessor"?{get:f.get,set:f.set}:f[l],y);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(S=o(_.get))&&(f.get=S),(S=o(_.set))&&(f.set=S),(S=o(_.init))&&r.unshift(S)}else(S=o(_))&&(a==="field"?r.unshift(S):f[l]=S)}p&&Object.defineProperty(p,t.name,f),w=!0}function Ja(i,n,e){for(var t=arguments.length>2,r=0;r<n.length;r++)e=t?n[r].call(i,e):n[r].call(i);return t?e:void 0}function Ga(i){return typeof i=="symbol"?i:"".concat(i)}function Ya(i,n,e){return typeof n=="symbol"&&(n=n.description?"[".concat(n.description,"]"):""),Object.defineProperty(i,"name",{configurable:!0,value:e?"".concat(e," ",n):n})}function Ls(i,n){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(i,n)}function js(i,n,e,t){function r(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(f){try{p(t.next(f))}catch(S){o(S)}}function l(f){try{p(t.throw(f))}catch(S){o(S)}}function p(f){f.done?s(f.value):r(f.value).then(a,l)}p((t=t.apply(i,n||[])).next())})}function Ns(i,n){var e={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},t,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(p){return function(f){return l([p,f])}}function l(p){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,p[0]&&(e=0)),e;)try{if(t=1,r&&(s=p[0]&2?r.return:p[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,p[1])).done)return s;switch(r=0,s&&(p=[p[0]&2,s.value]),p[0]){case 0:case 1:s=p;break;case 4:return e.label++,{value:p[1],done:!1};case 5:e.label++,r=p[1],p=[0];continue;case 7:p=e.ops.pop(),e.trys.pop();continue;default:if(s=e.trys,!(s=s.length>0&&s[s.length-1])&&(p[0]===6||p[0]===2)){e=0;continue}if(p[0]===3&&(!s||p[1]>s[0]&&p[1]<s[3])){e.label=p[1];break}if(p[0]===6&&e.label<s[1]){e.label=s[1],s=p;break}if(s&&e.label<s[2]){e.label=s[2],e.ops.push(p);break}s[2]&&e.ops.pop(),e.trys.pop();continue}p=n.call(i,e)}catch(f){p=[6,f],r=0}finally{t=s=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function Vs(i,n){for(var e in i)e!=="default"&&!Object.prototype.hasOwnProperty.call(n,e)&&Ei(n,i,e)}function _i(i){var n=typeof Symbol=="function"&&Symbol.iterator,e=n&&i[n],t=0;if(e)return e.call(i);if(i&&typeof i.length=="number")return{next:function(){return i&&t>=i.length&&(i=void 0),{value:i&&i[t++],done:!i}}};throw new TypeError(n?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vn(i,n){var e=typeof Symbol=="function"&&i[Symbol.iterator];if(!e)return i;var t=e.call(i),r,s=[],o;try{for(;(n===void 0||n-- >0)&&!(r=t.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return s}function Us(){for(var i=[],n=0;n<arguments.length;n++)i=i.concat(Vn(arguments[n]));return i}function zs(){for(var i=0,n=0,e=arguments.length;n<e;n++)i+=arguments[n].length;for(var t=Array(i),r=0,n=0;n<e;n++)for(var s=arguments[n],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function $s(i,n,e){if(e||arguments.length===2)for(var t=0,r=n.length,s;t<r;t++)(s||!(t in n))&&(s||(s=Array.prototype.slice.call(n,0,t)),s[t]=n[t]);return i.concat(s||Array.prototype.slice.call(n))}function pt(i){return this instanceof pt?(this.v=i,this):new pt(i)}function Ks(i,n,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(i,n||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(w){t[w]&&(r[w]=function(A){return new Promise(function(y,I){s.push([w,A,y,I])>1||a(w,A)})})}function a(w,A){try{l(t[w](A))}catch(y){S(s[0][3],y)}}function l(w){w.value instanceof pt?Promise.resolve(w.value.v).then(p,f):S(s[0][2],w)}function p(w){a("next",w)}function f(w){a("throw",w)}function S(w,A){w(A),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Ws(i){var n,e;return n={},t("next"),t("throw",function(r){throw r}),t("return"),n[Symbol.iterator]=function(){return this},n;function t(r,s){n[r]=i[r]?function(o){return(e=!e)?{value:pt(i[r](o)),done:!1}:s?s(o):o}:s}}function Hs(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=i[Symbol.asyncIterator],e;return n?n.call(i):(i=typeof _i=="function"?_i(i):i[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=i[s]&&function(o){return new Promise(function(a,l){o=i[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(p){s({value:p,done:a})},o)}}function Qs(i,n){return Object.defineProperty?Object.defineProperty(i,"raw",{value:n}):i.raw=n,i}function qs(i){if(i&&i.__esModule)return i;var n={};if(i!=null)for(var e in i)e!=="default"&&Object.prototype.hasOwnProperty.call(i,e)&&Ei(n,i,e);return Xa(n,i),n}function Js(i){return i&&i.__esModule?i:{default:i}}function Gs(i,n,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof n=="function"?i!==n||!t:!n.has(i))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(i):t?t.value:n.get(i)}function Ys(i,n,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof n=="function"?i!==n||!r:!n.has(i))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(i,e):r?r.value=e:n.set(i,e),e}function Xs(i,n){if(n===null||typeof n!="object"&&typeof n!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof i=="function"?n===i:i.has(n)}function Zs(i,n,e){if(n!=null){if(typeof n!="object"&&typeof n!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=n[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=n[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");i.stack.push({value:n,dispose:t,async:e})}else e&&i.stack.push({async:!0});return n}function eo(i){function n(t){i.error=i.hasError?new Za(t,i.error,"An error was suppressed during disposal."):t,i.hasError=!0}function e(){for(;i.stack.length;){var t=i.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return n(s),e()})}catch(s){n(s)}}if(i.hasError)throw i.error}return e()}var Nn,Ii,Ei,Xa,Za,ec,et=Co(()=>{Nn=function(i,n){return Nn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Nn(i,n)};Ii=function(){return Ii=Object.assign||function(n){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(n[s]=e[s])}return n},Ii.apply(this,arguments)};Ei=Object.create?function(i,n,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(n,e);(!r||("get"in r?!n.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return n[e]}}),Object.defineProperty(i,t,r)}:function(i,n,e,t){t===void 0&&(t=e),i[t]=n[e]};Xa=Object.create?function(i,n){Object.defineProperty(i,"default",{enumerable:!0,value:n})}:function(i,n){i.default=n};Za=typeof SuppressedError=="function"?SuppressedError:function(i,n,e){var t=new Error(e);return t.name="SuppressedError",t.error=i,t.suppressed=n,t};ec={__extends:Fs,__assign:Ii,__rest:ks,__decorate:Bs,__param:Ms,__metadata:Ls,__awaiter:js,__generator:Ns,__createBinding:Ei,__exportStar:Vs,__values:_i,__read:Vn,__spread:Us,__spreadArrays:zs,__spreadArray:$s,__await:pt,__asyncGenerator:Ks,__asyncDelegator:Ws,__asyncValues:Hs,__makeTemplateObject:Qs,__importStar:qs,__importDefault:Js,__classPrivateFieldGet:Gs,__classPrivateFieldSet:Ys,__classPrivateFieldIn:Xs,__addDisposableResource:Zs,__disposeResources:eo}});var io=he(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0})});var zn=he(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var no=(et(),it(Ze));function ro(i,n,e){try{return i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}De.eventHandlerSafeInvoke=ro;function Un(i,n,e){return(0,no.__awaiter)(this,void 0,void 0,function*(){try{return yield i(n,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Un;function tc(i,n,e,t){for(let r of i){let{succeeded:s,error:o}=ro(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}}De.invokeEventHandlers=tc;function ic(i,n,e,t){return(0,no.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of i){let{succeeded:s,error:o}=yield Un(r,n,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of i)r.push(Un(s,n,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=ic});var ao=he(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.TypedEvent=void 0;var nc=(et(),it(Ze)),so=zn(),oo={swallowExceptions:!1,parallelize:!0},$n=class{constructor(){this._handlers=[]}attach(n){this._handlers.push(n)}detach(n){this.tryRemoveHandler(n)}invoke(n,e,t=oo){(0,so.invokeEventHandlers)(this._handlers,n,e,t)}invokeAsync(n,e,t=oo){return(0,nc.__awaiter)(this,void 0,void 0,function*(){yield(0,so.invokeEventHandlersAsync)(this._handlers,n,e,t)})}tryRemoveHandler(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}};Pi.TypedEvent=$n});var Wn=he(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});var rc=(et(),it(Ze));(0,rc.__exportStar)(ao(),Kn)});var co=he(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.FinalizationRegistryMissingError=void 0;var Hn=class extends Error{};Ci.FinalizationRegistryMissingError=Hn});var qn=he(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.WeakHandlerHolder=void 0;var sc=co(),Qn=class{constructor(n){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(n)}catch(e){throw e.name==="FinalizationRegistry"?new sc.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(n,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:n,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(n){let t=this._refs.find(r=>r?.deref()===n)||new WeakRef(n);return this._finalizationRegistry.unregister(t),t}unregisterRef(n){this._finalizationRegistry.unregister(n)}};Di.WeakHandlerHolder=Qn});var lo=he(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.WeakEvent=void 0;var Jn=(et(),it(Ze)),oc=Wn(),ac=qn(),Gn=zn(),cc={swallowExceptions:!1,parallelize:!0},Yn=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new oc.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new ac.WeakHandlerHolder(n=>{this.onHandlerFinalizer(n)})}invoke(n,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,Gn.eventHandlerSafeInvoke)(s,n,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(n,e,t=cc){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(n,e,t):yield this.parallelInvokeAsync(n,e,t)})}sequentialInvokeAsync(n,e,t){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=yield(0,Gn.eventHandlerSafeInvokeAsync)(s,n,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(n,e,t){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,Gn.eventHandlerSafeInvokeAsync)(o,n,e).then(({succeeded:a,error:l})=>{if(!a&&t.swallowExceptions!==!0)throw l})):this.releaseHandler(s)}yield Promise.all(r)})}attach(n){this._handlers.push(this._refHolder.getWeakHandler(this,n))}detach(n){let e=this._refHolder.releaseWeakHandler(n);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(n){this.tryRemoveHandlerRef(n?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,n,{swallowExceptions:!0})}tryRemoveHandlerRef(n){let e=this._handlers.findIndex(t=>t===n);e>=0&&this._handlers.splice(e,1)}releaseHandler(n){this._refHolder.unregisterRef(n),this.tryRemoveHandlerRef(n)}};Ai.WeakEvent=Yn});var ho=he(Ti=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var uo=(et(),it(Ze));(0,uo.__exportStar)(qn(),Ti);(0,uo.__exportStar)(lo(),Ti)});var fo=he(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});var Xn=(et(),it(Ze));(0,Xn.__exportStar)(io(),kt);(0,Xn.__exportStar)(Wn(),kt);(0,Xn.__exportStar)(ho(),kt)});var dr={};mr(dr,{Client:()=>tn,Entity:()=>le,EntityFile:()=>xe,IdbPersistence:()=>ft,ServerSync:()=>bt,Storage:()=>tn,UndoHistory:()=>lt,authorization:()=>Ic,cliSync:()=>_c,createMigration:()=>yn,debugLogger:()=>An,getEntityClient:()=>go,id:()=>Ec,makeLogger:()=>gs,noLogger:()=>ui,schema:()=>Dt});function Do(i){return typeof Buffer<"u"?Buffer.from(i).toString("base64"):btoa(i)}function Ao(i){return typeof Buffer<"u"?Buffer.from(i,"base64").toString():atob(i)}var We={onlyUser:i=>Do(`u:${i}:*`),onlyMe:()=>We.onlyUser(sn),decode:i=>{let e=Ao(i).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},sn="$$_originator_$$";function yr(i,n){let{operations:e,baselines:t}=i;if(e)for(let r of e)r.authz&&We.decode(r.authz).subject===sn&&(r.authz=We.onlyUser(n));if(t)for(let r of t)r.authz&&We.decode(r.authz).subject===sn&&(r.authz=We.onlyUser(n))}var nt=class{constructor(n){this.flusher=n,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:n,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(n);return o||(o=new on({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:n}),this.batches.set(n,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},on=class{constructor({max:n,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:l,timeout:p,userData:f})=>{this.items.push(...a),l!==void 0&&(this.max=l),p!==void 0&&(this.timeout=p),f&&(this.userData=f);let S=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():S&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=n,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};var wt;(function(i){i[i.InvalidRequest=4e3]="InvalidRequest",i[i.BodyRequired=4001]="BodyRequired",i[i.NoToken=4010]="NoToken",i[i.InvalidToken=4011]="InvalidToken",i[i.TokenExpired=4012]="TokenExpired",i[i.Forbidden=4030]="Forbidden",i[i.NotFound=4040]="NotFound",i[i.Unexpected=5e3]="Unexpected",i[i.ConfigurationError=5010]="ConfigurationError",i[i.NoFileStorage=5011]="NoFileStorage",i[i.MigrationPathNotFound=7001]="MigrationPathNotFound",i[i.ImportFailed=7002]="ImportFailed",i[i.Offline=7003]="Offline"})(wt||(wt={}));var U=class extends Error{constructor(n,e,t){super(t??`Verdant error: ${n}`,{cause:e}),this.code=n,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let n=Math.floor(this.code/10);return n<600?n:500}};U.Code=wt;function br(i){return typeof i=="object"&&"code"in i&&typeof i.code=="number"}var Nt,To=new Uint8Array(16);function an(){if(!Nt&&(Nt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!Nt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Nt(To)}var wr=/^(?:[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 Ro(i){return typeof i=="string"&&wr.test(i)}var vr=Ro;var te=[];for(Vt=0;Vt<256;++Vt)te.push((Vt+256).toString(16).substr(1));var Vt;function Fo(i){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(te[i[n+0]]+te[i[n+1]]+te[i[n+2]]+te[i[n+3]]+"-"+te[i[n+4]]+te[i[n+5]]+"-"+te[i[n+6]]+te[i[n+7]]+"-"+te[i[n+8]]+te[i[n+9]]+"-"+te[i[n+10]]+te[i[n+11]]+te[i[n+12]]+te[i[n+13]]+te[i[n+14]]+te[i[n+15]]).toLowerCase();if(!vr(e))throw TypeError("Stringified UUID is invalid");return e}var xr=Fo;function ko(i,n,e){i=i||{};var t=i.random||(i.rng||an)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,n){e=e||0;for(var r=0;r<16;++r)n[e+r]=t[r];return n}return xr(t)}var vt=ko;var _r=Me(Ir(),1);function Bo(i,n){return typeof n!="object"||n===null||Array.isArray(n)?n:Object.fromEntries(Object.entries(n).sort(([e],[t])=>e<t?-1:e>t?1:0))}function cn(i){let n=new WeakMap,e=0;return JSON.stringify(i,(t,r)=>{if(typeof r=="object"&&r!==null){if(n.has(r))return{$ref:n.get(r)};n.set(r,`cyclic-ref:${e++}`)}return Bo(t,r)})}function fe(i,n=!0){if(!n&&typeof structuredClone=="function")return structuredClone(i);if(N(i)||Array.isArray(i)){let e=G(i),t;if(Array.isArray(i))t=i.map(r=>fe(r,n));else{t={};for(let[r,s]of Object.entries(i))t[r]=fe(s,n)}return n&&e&&z(t,e),t}return i}function He(i){return(0,_r.default)(i)}function N(i){return i&&typeof i=="object"}function Er(i){for(var n=[],e=[i],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&n.indexOf(r)===-1){n.push(r);for(var s in r)e.push(r[s])}}return t}function M(i,n="assertion failed"){if(!i)throw new Error(n)}function xt(i=16){return vt().replace("-","").slice(0,i)}function Pr(i,n){for(let e=i.length-1;e>=0;e--)if(n(i[e]))return e;return-1}function Cr(i,n){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,t),n)}}function Dr(i,n){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=n?(e=o,i.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,i.apply(s,r)},n))}}function ln(i){try{return JSON.stringify(i)}catch{return`[recursive/invalid:${String(i)}]`}}function me(i){return i&&i["@@type"]==="file"}function St(i){return{"@@type":"file",id:i}}function rt(i){return typeof File<"u"&&i instanceof File||typeof Blob<"u"&&i instanceof Blob}function Ut(i){return i&&N(i)&&typeof i.id=="string"&&typeof i.remote=="boolean"&&typeof i.name=="string"&&typeof i.type=="string"}function $(i){return oe(i)||me(i)}function Te(i,n){return i===n?!0:!(!$(i)||!$(n)||i["@@type"]!==n["@@type"]||i.id!==n.id)}function oe(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Qe(i,n,e,t,r=[],s){z(i,n),st(i,t);let o=Ht(i);for(let a of o.keys()){let l=o.get(a),p={oid:a,timestamp:e(),data:{op:"initialize",value:Wt(l)}};r.push(Rr(p,s?.authz))}return r}function Tr(i,n,e,t=[],r){let s={oid:n,timestamp:e(),data:{op:"initialize",value:i}};return t.push(Rr(s,r?.authz)),t}function Rr(i,n){return n&&(i.authz=n),i}function $t(i){let n={};for(let e of i)e.oid in n?n[e.oid].push(e):n[e.oid]=[e];return n}function Fr(i){let n={};for(let e of i){let t=K(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function kr(i){let n={};for(let e of i){let t=K(e.oid);t in n?n[t].push(e):n[t]=[e]}return n}function Le(i,n){return Array.isArray(i)?!0:(i===void 0&&console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${G(i)})
7
- Patch that was not applied: ${JSON.stringify(n)}`),!1)}function je(i,n,e){if(i==null&&n.op!=="initialize")return i;let t=i,r,s;function o(a){e&&$(a)&&e.push(a)}switch(n.op){case"set":o(t[n.name]),t[n.name]=n.value;break;case"remove":o(t[n.name]),delete t[n.name];break;case"list-set":Le(i,n)&&(o(i[n.index]),i[n.index]=n.value);break;case"list-push":Le(i,n)&&i.push(n.value);break;case"list-delete":Le(i,n)&&(o(i[n.index]),i.splice(n.index,n.count));break;case"list-move-by-index":Le(i,n)&&(s=i.splice(n.from,1),i.splice(n.to,0,s[0]));break;case"list-remove":if(Le(i,n))do{let a=n.value;n.only==="last"?$(a)?r=Pr(i,l=>$(l)&&Te(l,a)):r=i.lastIndexOf(a):$(a)?r=i.findIndex(l=>$(l)&&Te(l,a)):r=i.indexOf(a),r!==-1&&(o(i[r]),i.splice(r,1))}while(!n.only&&r!==-1);break;case"list-add":Le(i,n)&&(i.some(l=>oe(l)&&oe(n.value)?l.id===n.value.id:l===n.value)||i.push(n.value));break;case"list-move-by-ref":Le(i,n)&&(r=i.findIndex(a=>Te(a,n.value)),s=i.splice(r,1),i.splice(n.index,0,s[0]));break;case"list-insert":if(Le(i,n)){if(!n.value&&!n.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(n)}`);n.value?i.splice(n.index,0,n.value):i.splice(n.index,0,...n.values)}break;case"delete":Array.isArray(i)?i.forEach(o):N(i)&&Object.values(i||{}).forEach(o);return;case"initialize":return fe(n.value);case"touch":return i;default:throw new Error(`Unsupported patch operation: ${n.op}`)}return i}function zt(i,n,e=[]){if(Array.isArray(i))for(let t=0;t<i.length;t++){let r=i[t];i[t]=Ar(r,n,e),N(i[t])&&zt(i[t],n,e)}else if(!me(i)){if(N(i)){M(G(i),`Object ${JSON.stringify(i)} must have an oid`);for(let t of Object.keys(i))i[t]=Ar(i[t],n,e),N(i[t])&&zt(i[t],n,e)}}return e}function Ar(i,n,e){if(oe(i)){e.push(i.id);let t=n.get(i.id);return M(!!t,`No value was found in object map for ${i.id}`),z(t,i.id)}else return i}function Br(i){return i.data.op==="set"?i.data.name:!1}function Mr(i,n){return n.has(!0)?!0:i.data.op==="set"||i.data.op==="remove"?n.has(i.data.name):!1}function Kt(i){return{oid:i.oid,timestamp:i.timestamp,data:i.data,authz:i.authz}}var Mo="/",Ot=":",un=new WeakMap;function ae(i){let n=G(i);return M(!!n,`Object ${ln(i)} does not have an OID assigned to it`),n}function G(i){if(N(i))return un.get(i)}function z(i,n){return M(N(i),`Only objects can be assigned OIDs, received ${ln(i)}`),Vr(i)&&Wt(i),un.set(i,n),i}function Vr(i){return!!G(i)}function Wt(i){return un.delete(i),i}function Lr(i,n,e){if(Vr(i)){let t=ae(i);if(Ne(t,n))return ae(i);{let r=Ie(n,e);return z(i,r),r}}else{let t=Ie(n,e);return z(i,t),t}}var dn={".":"&dot;","/":"&slash;",":":"&colon;"};function jr(i){return i.replace(/[/]/g,dn["/"]).replace(/[:]/g,dn[":"]).replace(/[.]/g,dn["."])}function Nr(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function ee(i,n,e){let t=jr(i)+Mo+jr(n);return e&&(t+=Ot+e),t}function Ie(i,n=Lo){let{collection:e,id:t}=ne(i);return ee(e,t,n())}function ne(i){let[n,e,...t]=i.split("/");t.length&&(console.error(`OID ${i} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(Ot),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:Nr(n),id:Nr(o),subId:s}}function st(i,n){let e=ae(i);if(Array.isArray(i)){let t;for(let r=0;r<i.length;r++)t=i[r],N(t)&&!$(t)&&(Lr(t,e,n),st(t,n))}else if(N(i)&&!$(i))for(let t of Object.keys(i))N(i[t])&&!$(i[t])&&(Lr(i[t],e,n),st(i[t],n))}function Qt(i){if(Wt(i),Array.isArray(i))for(let n=0;n<i.length;n++)Qt(i[n]);else if(N(i))for(let n of Object.keys(i))Qt(i[n])}function Lo(){return vt().slice(0,8)}function ie(i){return{"@@type":"ref",id:i}}function Ht(i,n=new Map){if(Array.isArray(i)){let e=ae(i),t=z([],e);for(let r=0;r<i.length;r++){let s=i[r];if(N(s)){if(oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s)){t[r]=s;continue}else{let o=ae(s);t[r]=ie(o),Ht(s,n)}}else t[r]=s}n.set(e,t)}else if(N(i)&&!$(i)){let e=ae(i),t=z({},e);for(let r of Object.keys(i)){let s=i[r];if(N(s)){if(oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(me(s))t[r]=s;else{let o=ae(s);t[r]=ie(o),Ht(s,n)}}else t[r]=s}n.set(e,t)}else $(i);return n}function K(i){return i.split(".")[0].split(Ot)[0]}function hn(i){let n=K(i),e=Ie(n,()=>"\uFFFF");return[`${n}${Ot}`,e]}function Ne(i,n){return K(i)===K(n)}function qt(i){return!i.includes(Ot)}var ot="__@@oid_do_not_use",Re="@@id";function jo(i){if(N(i))return i[Re]||i[ot]}function No(i){return N(i)&&(delete i[ot],delete i[Re]),i}function Vo(i){let n=jo(i);n&&z(i,n)}function It(i){if(Vo(i),No(i),Array.isArray(i))for(let n=0;n<i.length;n++)It(i[n]);else if(N(i))for(let n of Object.keys(i))It(i[n])}function Uo(i){let{collection:n,id:e,subId:t}=ne(i);return ee(n,e,t)}var zo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function $o(i){return i.replaceAll(zo,n=>{let e=n.slice(1,n.length-1);return`"${Uo(e)}"`})}function fn(i){return JSON.parse($o(JSON.stringify(i)))}function pn(i){return i===Re||i===ot}var Ve=class{constructor(n,e){this.getNow=n,this.createSubId=e,this.isPrimitive=t=>!N(t)||$(t),this.createDiff=(t,r,s={})=>Jt(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s,o)=>o?Tr(t,r,this.getNow,void 0,s?{authz:s}:void 0):Qe(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s},authz:o}];{let a=Ie(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ie(a),name:r},authz:o}]}},this.createRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r},authz:s}],this.createListSet=(t,r,s,o)=>{if(M(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s},authz:o}];{let a=Ie(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ie(a)},authz:o}]}},this.createListPush=(t,r,s)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r},authz:s}];{let o=Ie(t,this.createSubId);return[...Qe(r,o,this.getNow,void 0,void 0,{authz:s}),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ie(o)},authz:s}]}},this.createListAdd=(t,r,s)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r},authz:s}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ie(r)},authz:s}],this.createListInsert=(t,r,s,o)=>{if(M(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r},authz:o}];{let a=Ie(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,o?{authz:o}:void 0),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ie(a),index:r},authz:o}]}},this.createListInsertMany=(t,r,s,o)=>{M(r>=0,"List index must be non-negative");let a=[],l=s.map(p=>{if(this.isPrimitive(p))return p;let f=Ie(t,this.createSubId);return a.push(...Qe(p,f,this.getNow,this.createSubId,void 0,{authz:o})),ie(f)});return a.push({oid:t,timestamp:this.getNow(),data:{op:"list-insert",values:l,index:r},authz:o}),a},this.createListRemove=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s},authz:o}],this.createListDelete=(t,r,s=1,o)=>(M(r>=0,"List index must be non-negative"),M(s>0,"Count must be positive and non-zero"),[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s},authz:o}]),this.createListMoveByRef=(t,r,s,o)=>(M(s>=0,"List index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s},authz:o}]),this.createListMoveByIndex=(t,r,s,o)=>(M(r>=0,"List move from index must be non-negative"),M(s>=0,"List move to index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s},authz:o}]),this.createDelete=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"},authz:r}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};function at(i,n){if(i===n)return!0;if($(i)&&$(n))return Te(i,n);let e=G(i),t=G(n);return!!(e&&t&&e===t)}function Ur(i,n,e,t){if(!_t(n))return n;let r=G(n);if(!r)t.mergeUnknownObjects&&e&&z(n,e);else if(!Ne(i,r))return fe(n,!1);return n}function _t(i){return N(i)&&!$(i)}function Jt(i,n,e,t,r,s){var o;let a={patches:[],mergeUnknownObjects:s?.mergeUnknownObjects,merge:(o=s?.merge)!==null&&o!==void 0?o:s?.defaultUndefined,authz:s?.authz,patchCreator:new Ve(e,t)};return Gt(i,n,a),a.patches}function Gt(i,n,e){if(Array.isArray(i)&&Array.isArray(n))Ko(i,n,e);else{if(Array.isArray(i)||Array.isArray(n))throw new U(U.Code.Unexpected,void 0,"Cannot diff between array and non-array");_t(i)&&_t(n)&&Wo(i,n,e)}}function Ko(i,n,e){let t=ae(i),r=[],s=new Set;for(let f=0;f<i.length;f++){let S=i[f];r[f]=S;let w=G(S);w&&s.add(w)}for(let f=0;f<n.length;f++){let S=n[f],w=i[f];n[f]=Ur(t,S,G(w),e)}let o=!0,a=new Set,l=new Set;for(let f=0;f<n.length;f++){let S=n[f],w=r[f];S===void 0&&(o=!1);let A=G(S),y=o&&f>=r.length;if(A&&s.has(A))if(at(S,w))Gt(w,S,e);else{e.patches.push(...e.patchCreator.createListMoveByRef(t,ie(A),f,e.authz));let I=G(w);I&&l.add(I),a.add(A)}else if(y)e.patches.push(...e.patchCreator.createListPush(t,S,e.authz));else if(at(S,w))Gt(w,S,e);else{let I=f===0||at(n[f-1],r[f-1]),_=f===n.length-1||at(n[f+1],r[f]);I&&_?(e.patches.push(...e.patchCreator.createListInsert(t,f,S,e.authz)),r.splice(f,0,void 0)):e.patches.push(...e.patchCreator.createListSet(t,f,S,e.authz))}}if(r.length-n.length>0)for(let f=r.length-1;f>=n.length;f--){let S=r[f],w=G(S);w?a.has(w)||(ct(S,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(w),"last",e.authz))):e.patches.push(...e.patchCreator.createListRemove(t,S,"last",e.authz))}for(let f of l){if(a.has(f))continue;let S=i.find(w=>G(w)===f);S&&ct(S,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(f),"last",e.authz))}}function Wo(i,n,e){let t=new Set(Object.keys(i)),r=ae(i);for(let s in n){let o=n[s];if(o===void 0&&e.merge||(t.delete(s),pn(s)))continue;let a=i[s];_t(o)?(Ur(r,o,G(a),e),a?at(o,a)?Gt(a,o,e):(e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),ct(a,e)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz))):at(o,a)||(o===void 0?e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),ct(a,e))}if(!e.merge)for(let s of t)pn(s)||(e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)),ct(i[s],e))}function ct(i,n){if(!_t(i))return;let e=G(i);if(e){n.patches.push(...n.patchCreator.createDelete(e,n.authz));for(let t in i){let r=i[t];ct(r,n)}}}var W=class{constructor(n){this._onAllUnsubscribed=n,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=xt(),s=this.subscribers[e];return s||(s=this.subscribers[e]={}),s[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};var Yt="\uFFFFFE",Ho="\0",Qo="\uFFFFFF";function be(...i){let n=qo(i);return n.length===1?n[0]:n}function Pe(...i){return i.join(Yt)+`${Qo}`}function Ee(...i){return i.join(Yt)+`${Yt}${Ho}`}function qo(i){let n=[[]];for(let e of i)if(Array.isArray(e)){let t=[];for(let r of n)for(let s of e)t.push(r.concat(s));n=t}else for(let t of n)t.push(`${e}`);return Array.from(new Set(n.map(e=>e.join(Yt))))}function zr(i){return!!i.field}function Jo(i,n){let e={};for(let[t,r]of Object.entries(i.indexes||{})){let s=r;zr(s)?e[t]=_e(n[s.field]):e[t]=_e(s.compute(n))}return e}function Go(i,n){return Object.entries(i.compounds||{}).reduce((e,[t,r])=>(e[t]=be(...r.of.map(s=>n[s])),e),{})}function Yo(i,n){return Object.entries(i.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=_e(n[t])),e),{})}function mn(i,n){let e=Object.assign(Object.assign({[i.primaryKey]:n[i.primaryKey]},Yo(i,n)),Jo(i,n));return Object.assign(e,Go(i,Object.assign(Object.assign({},n),e))),e}var Xo="null";function _e(i){if(i===null)return Xo;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(_e);throw new Error(`Unsupported index value: ${i}`)}function $r(i,n){let e,t;return(...r)=>{let s=n();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=i(...r)),t}}var Zo={version:0,collections:{}};function Kr(i){return i?[...Object.keys(i.indexes||{}).map(n=>{let e=i.indexes[n],t=e.type;!t&&e.field&&(t=i.fields[e.field].type),M(t,`Could not determine type of index ${i}.${n}. Index must have a type. Perhaps your schema is malformed?`);let r=Et(i,n);return{name:n,multiEntry:r,synthetic:!0,compound:!1,type:t?.replace("[]","")}}),...Object.keys(i.compounds||{}).map(n=>({name:n,multiEntry:Et(i,n),synthetic:!1,compound:!0,type:"string"}))]:[]}function yn(i,n,e){let t=typeof n=="function"||n===void 0,r=t?Zo:i,s=t?i:n,o=t?n:e;M(r,"Invalid arguments to createMigration"),M(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:l,removedCollections:p,addedIndexes:f,removedIndexes:S,autoMigratedCollections:w,autoMigration:A}=ea(r,s);return{version:s.version,migrate:async y=>{let I=[];if(await o?.({migrate:async(E,P)=>{let F=A(E),b=async O=>{let u=await P(O);z(u,ae(O));let m=F(u),d=Hr(s.collections[E].fields,m);return m};await y.migrate(E,b),I.push(E),w.delete(E)},info:{changedCollections:a,addedCollections:l,removedCollections:p},queries:y.queries,mutations:y.mutations}),s.version>1){y.log("debug","auto-migrating collections with new defaults",w);for(let P of w)await y.migrate(P,A(P)),I.push(P);for(let P of p)await y.deleteCollection(P);let E=a.filter(P=>!I.includes(P));E.length>0&&y.log("error",`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,E)}},removedCollections:p,addedIndexes:f,removedIndexes:S,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function ea(i,n){let e=Object.keys(n.collections).filter(f=>i.collections[f]&&cn(i.collections[f])!==cn(n.collections[f])),t=Object.keys(i.collections).filter(f=>!n.collections[f]),r=Object.keys(n.collections).filter(f=>!i.collections[f]),s=new Set;for(let f of e){let S=i.collections[f].fields,w=n.collections[f].fields;Object.keys(w).some(A=>(!S[A]||gn(S[A]))&&!gn(w[A]))&&s.add(f),Object.keys(S).some(A=>!w[A])&&s.add(f)}let o={},a={};for(let f of[...e,...r]){let S=Kr(i.collections[f]),w=Kr(n.collections[f]),A=w.filter(I=>!S.find(_=>_.name===I.name)),y=S.filter(I=>!w.find(_=>_.name===I.name));A.length>0&&(o[f]=A,e.includes(f)&&s.add(f)),y.length>0&&(a[f]=y,e.includes(f)&&s.add(f))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(f,S)=>qe(n.collections[f],S),autoMigration:f=>S=>{let w=n.collections[f];return qe(w,Wr(w,S))}}}var bn={};var Ue;(function(i){i[i.Realtime=0]="Realtime",i[i.Push=1]="Push",i[i.PassiveRealtime=2]="PassiveRealtime",i[i.PassivePush=3]="PassivePush",i[i.ReadOnlyPull=4]="ReadOnlyPull",i[i.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Ue||(Ue={}));var rs=Me(Je(),1),aa=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function ca(i){let{properties:n,fields:e}=i,t=aa(i,["properties","fields"]),r=n||e;if(!r)throw new Error("objectField must be passed a properties object");return Object.assign(Object.assign({type:"object"},t),{properties:r})}function la(i,n){return i.properties=n,i}function da(i){return Object.assign({type:"array"},i)}function ua(i,n){return i.items=n,i}var ha=i=>Object.assign({type:"string"},i),fa=i=>Object.assign({type:"number"},i),pa=i=>Object.assign({type:"boolean"},i),ma=i=>Object.assign({type:"any"},i);function ga(i){return Object.assign({type:"map"},i)}function ya(i,n){return i.values=n,i}var ba=i=>Object.assign({type:"file"},i),wa=()=>({type:"string",default:rs.default}),ss={object:ca,array:da,replaceObjectFields:la,replaceArrayItems:ua,string:ha,number:fa,boolean:pa,any:ma,map:ga,replaceMapValues:ya,file:ba,id:wa};var ls=Me(Je(),1);function ei(i){return i.equals!==void 0}function ti(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function os(i){return!!i.match}function ii(i){return i.startsWith!==void 0}function In(i){return!ti(i)&&!ei(i)&&!os(i)&&!ii(i)&&i.order}function Et(i,n){var e,t;let r=(e=i.compounds)===null||e===void 0?void 0:e[n];if(r)return r.of.some(a=>Et(i,a));let s=(t=i.indexes)===null||t===void 0?void 0:t[n];if(s){if("type"in s)return On(s.type);if("field"in s){let a=i.fields[s.field];return a?On(a.type):!1}}let o=i.fields[n];return o?On(o.type):!1}function On(i){return i==="array"||i.endsWith("[]")}function ge(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Fe(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.default!==void 0:!1}function gn(i){return!ge(i)&&!Fe(i)}function qe(i,n){for(let[e,t]of Object.entries(i.fields)){let r=Ce(t);(r!==void 0&&n[e]===void 0||!ge(t)&&n[e]===null)&&(n[e]=r),n[e]&&Ge(n[e],t)}return n}function Ge(i,n){if(i==null)return i;if(n.type==="object")for(let[e,t]of Object.entries(n.properties)){if(i[e]===void 0){let r=Ce(t);r!==void 0&&(i[e]=r)}Ge(i[e],t)}else if(n.type==="array")for(let e of i)Ge(e,n.items);else if(n.type==="map")for(let[e,t]of Object.entries(i))e===Re||e===ot||Ge(t,n.values)}function Ce(i){if("default"in i){let n=typeof i.default=="function"?i.default():i.default;if(n===null)return n;let e=structuredClone(n);if(i.type==="object")for(let[t,r]of Object.entries(i.properties))e[t]===void 0&&(e[t]=Ce(r));return e}if(ge(i))return null;if(i.type==="array")return[];if(i.type==="map")return{}}function Wr(i,n){for(let[e,t]of Object.entries(n))e===Re||e===ot||(i.fields[e]?_n(t,i.fields[e]):delete n[e]);return n}function _n(i,n){if(N(i)&&n.type==="object")for(let[e,t]of Object.entries(i))n.properties[e]?_n(t,n.properties[e]):delete i[e];else if(Array.isArray(i)&&n.type==="array")for(let e of i)_n(e,n.items)}function as(i){return i.type==="string"||i.type==="number"||i.type==="boolean"}function Hr(i,n){for(let[e,t]of Object.entries(n))if(e!==Re){if(!i[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=ke({field:i[e],value:t,fieldPath:[e]});if(r)return r}}}function ke({field:i,value:n,fieldPath:e=[],depth:t,requireDefaults:r,expectRefs:s,hasPassedFirstLevel:o}){let a=s&&o;if(!(t!==void 0&&t<=0)&&!(ge(i)&&n==null)){if(n==null&&(r||!Fe(i)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${pe(e)}`};if(i.type==="object")if(a){if(!oe(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${pe(e)}, got ${we(n)}`}}else{if(!N(n))return{type:"invalid-type",fieldPath:e,message:`Expected object ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`};for(let[l,p]of Object.entries(i.properties)){if(l===Re)continue;let f=ke({field:p,value:n[l],fieldPath:[...e,l],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(f)return f}for(let l of Object.keys(n))if(!i.properties[l])return{type:"invalid-key",fieldPath:[...e,l],message:`Invalid unexpected field "${l}" on value ${pe(e)}`}}else if(i.type==="array")if(a){if(!oe(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${pe(e)}, got ${we(n)}`}}else{if(!Array.isArray(n))return n===null&&i.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`};for(let l of n){let p=ke({field:i.items,value:l,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(p)return p}}else if(i.type==="map")if(a){if(!oe(n))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${pe(e)}, got ${we(n)}`}}else{if(!N(n))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${pe(e)}, got ${we(n)}`};for(let[l,p]of Object.entries(n)){let f=ke({field:i.values,value:p,fieldPath:[...e,l],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(f)return f}}else if(i.type==="string"){if(typeof n!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`};if(i.options&&!i.options.includes(n))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${i.options.join(", ")} for field ${pe(e)}, got ${we(n)}`}}else if(i.type==="boolean"){if(typeof n!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`}}else if(i.type==="number"){if(typeof n!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`}}else if(i.type==="file"){if(a){if(!me(n))return{type:"invalid-type",fieldPath:e,message:`Expected file ref for field ${pe(e)}, got ${we(n)}`}}else if(!rt(n)&&!Ut(n))return{type:"invalid-type",fieldPath:e,message:`Expected file ${i.nullable?"or null ":""}for field ${pe(e)}, got ${we(n)}`}}}}function we(i){try{return JSON.stringify(i)}catch{return String(i)}}function pe(i){return i.length===0?"root":i.join(".")}function cs(i,n){let e={};for(let[t,r]of Object.entries(n))i[t]&&(e[t]=ni({field:i[t],value:r,fieldPath:[t]}));return e}function ni({field:i,value:n,fieldPath:e=[],depth:t}){let r=ke({field:i,value:n,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(i.type==="object"){if(!N(n))return n;let s={};for(let[o,a]of Object.entries(i.properties))s[o]=ni({field:a,value:n[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(i.type==="array")return Array.isArray(n)?n.map(s=>ni({field:i.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):n;if(i.type==="map"){if(!N(n))return n;let s={};for(let[o,a]of Object.entries(n))s[o]=ni({field:i.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return n}}function ze(i,n){var e;return i.type==="object"?i.properties[n]:i.type==="array"?i.items:i.type==="map"?i.values:i.type==="any"?i:"type"in i?null:(e=i[n])!==null&&e!==void 0?e:null}var va=function(i,n){var e={};for(var t in i)Object.prototype.hasOwnProperty.call(i,t)&&n.indexOf(t)<0&&(e[t]=i[t]);if(i!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(i);r<t.length;r++)n.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(i,t[r])&&(e[t[r]]=i[t[r]]);return e};function xa(i){var{synthetics:n,indexes:e}=i,t=va(i,["synthetics","indexes"]);let r=Object.assign(Object.assign({},n),e);for(let[s,o]of Object.entries(t.fields))"indexed"in o&&(r[s]={field:s});return Object.assign(Object.assign({},t),{indexes:r})}function Dt(i){return i}Dt.collection=xa;Dt.fields=ss;Dt.generated={id:ls.default};var fs=Me(Je(),1),li=4,Tt=36;function ds(i){return i.toString(Tt).padStart(li,"0")}function Sa(i){return i.toString().padStart(6,"0")}var ri=class{constructor(){this.latest={time:Date.now(),counter:0,node:Oa()},this.zeroCounter=0,this.now=n=>(this.latest=hs(this.latest),this.get(n,this.latest)),this.OLD_now=n=>(this.latest=hs(this.latest),Sa(n)+_a(this.latest)),this.timerState=()=>this.latest,this.update=n=>{let e=n.slice(li);this.latest=Ia(this.latest,ps(e))},this.get=(n,e)=>ds(n)+us(e),this.zero=n=>ds(n)+us({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=Dn}},si=class extends Error{constructor(...n){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(n).join(" ")}},oi=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},En=4,Pn=7,ai=60*1e3,At=9;function Oa(){return fs.default.slug().padStart(Pn,"0").slice(0,Pn)}function us(i){let n=new Date(i.time).getTime().toString(Tt).padStart(At,"0"),e=i.counter.toString(Tt).padStart(En,"0"),t=i.node.padStart(Pn,"0");return`${n}${e}${t}`}function hs(i){let n=Date.now(),e=Math.max(i.time,n),t=i.time===e?i.counter+1:0;if(e-n>ai)throw new si(e,n,ai);if(t>65535)throw new oi;return{time:e,counter:t,node:i.node}}function Ia(i,n){let e=Date.now(),t=Math.max(e,Math.max(i.time,n.time)),r=Math.max(i.counter,n.counter),s;if(i.time===t&&n.time===t?s=r+1:i.time===t?s=i.counter+1:n.time===t?s=n.counter+1:s=0,t-e>ai)throw new si(t,e,ai);if(s>65535)throw new oi;return{time:t,counter:s,node:i.node}}function ps(i){let n=i.slice(0,At),e=i.slice(At,At+En),t=i.slice(At+En),r=parseInt(n,Tt),s=parseInt(e,Tt);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function _a(i){let n=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),t=i.node.padStart(16,"0");return`${n}-${e}-${t}`}function ci(i){return parseInt(i.slice(0,li),36)}function Cn(i,n){return ci(i)-ci(n)}function Dn(i){return ps(i.slice(li)).time}function ms(i,n,e,t,r,s){let o=new Ve(t,r);if(n==null)return[{oid:i,timestamp:t(),data:{op:"delete"},authz:s}];let a=fe(n),l=[];for(let p of e){let f=Ea(i,a,p,o,s);l.unshift(...f),je(a,p.data)}return l}function Ea(i,n,e,t,r){var s,o;let a=e.data;switch(a.op){case"set":return n[a.name]===void 0?t.createRemove(i,a.name,r):t.createSet(i,a.name,n[a.name],r);case"remove":return n[a.name]===void 0?[]:t.createSet(i,a.name,n[a.name],r);case"list-insert":return a.value===void 0&&((s=a.values)===null||s===void 0?void 0:s.length)===0?[]:t.createListDelete(i,a.index,a.value?1:((o=a.values)===null||o===void 0?void 0:o.length)||0,r);case"list-delete":return t.createListInsertMany(i,a.index,n.slice(a.index,a.index+a.count),r);case"list-move-by-ref":return t.createListMoveByRef(i,a.value,Rt(n,a.value),r);case"list-move-by-index":return t.createListMoveByIndex(i,a.to,a.from,r);case"delete":return t.createInitialize(n,i,r,!0);case"list-push":return t.createListRemove(i,a.value,"last",r);case"list-remove":if(a.only==="last"){let l=Rt(n,a.value,0,"backward");return l===-1?[]:t.createListInsert(i,l,a.value,r)}else if(a.only==="first"){let l=Rt(n,a.value);return l===-1?[]:t.createListInsert(i,l,a.value,r)}else{let l=[],p=Rt(n,a.value);for(;p!==-1;)l.push(p),p=Rt(n,a.value,p+1);return l.flatMap(f=>t.createListInsert(i,f,a.value,r))}case"list-add":return t.createListRemove(i,a.value,"last",r);case"list-set":return n[a.index]!==void 0?t.createListSet(i,a.index,n[a.index],r):t.createListDelete(i,a.index,1,r);case"initialize":return t.createDelete(i,r);case"touch":return[];default:throw new Error(`Cannot undo operation type: ${a.op}`)}}function Rt(i,n,e=0,t="forward"){let r=t==="forward"?"findIndex":"findLastIndex";return $(n)?i[r]((s,o)=>$(s)&&s.id===n.id&&o>=e):i[r]((s,o)=>s===n&&o>=e)}var di=class{constructor(n){this.value=n}deref(){return this.value}};var lt=class extends W{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),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}get undoLength(){return this._undoable.length}get redoLength(){return this._undone.length}};var ui=()=>{},gs=i=>(n,...e)=>{n==="critical"&&e.unshift("[CRITICAL]"),i&&e.unshift(`[${i}]`),n==="critical"?console.error(...e):console[n](...e)};function An(i){return localStorage.getItem("DEBUG")?gs(i):ui}var ce=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(async n=>{try{await n()}catch(e){console.error("Error disposing",e)}})),this._disposes=[]};this.compose=n=>this.addDispose(n.dispose.bind(n));this.addDispose=n=>{this._disposes.push(n)}}};var ys=typeof window<"u"?window.indexedDB:void 0;function Ye(i){return i instanceof Error&&i.name==="AbortError"}function dt(i){return new Promise((n,e)=>{i.onsuccess=()=>{n(i.result)},i.onerror=()=>{i.error&&Ye(i.error)?n(i.result):e(i.error)}})}function Xe(i,n){return new Promise((e,t)=>{let r=i.transaction([n],"readonly"),o=r.objectStore(n).openCursor(),a=0,l=0;o.onsuccess=function(p){let f=o.result;f&&(a++,l=l+Er(f.value),f.continue())},o.onerror=function(p){o.error&&Ye(o.error)?e({count:a,size:l}):t(o.error)},r.oncomplete=function(p){e({count:a,size:l})},r.onabort=function(p){t(p)},r.onerror=function(p){t(p)}})}function Tn(i,n){let e=i.transaction(n,"readonly"),t=n.map(r=>{let s=e.objectStore(r);return dt(s.getAll())});return Promise.all(t)}async function ve(i){i.close(),await new Promise(n=>{n()}),await new Promise(n=>{n()})}async function bs(i,n){let e=n.indexedDB.deleteDatabase([i,"meta"].join("_")),t=n.indexedDB.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{t.onsuccess=r,t.onerror=s})]),n.location.reload()}function hi(i,n=window.indexedDB){return dt(n.deleteDatabase(i))}async function Pa(i=window.indexedDB){return i.databases()}function ws(i,n,e,t,r){try{let s=i.transaction(n,e);if(t){let o=()=>{r?.("debug","aborting transaction");try{s.abort(),s.__aborted=!0}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",o),s.addEventListener("error",()=>{t.removeEventListener("abort",o)}),s.addEventListener("complete",()=>{t.removeEventListener("abort",o)})}return s}catch(s){if(s instanceof Error&&s.name==="InvalidStateError")return r?.("warn","Failed to create transaction, database is closing"),{abort:()=>{},addEventListener:()=>{},objectStore:()=>({add:()=>{},put:()=>{},get:()=>{},getAll:()=>{},delete:()=>{},clear:()=>{},openCursor:()=>{let o={onsuccess:()=>{},onerror:a=>{},result:null};return setTimeout(()=>{o.onerror({})},0),o},index:()=>{throw new Error("Transaction is not active")}}),oncomplete:null,onerror:null,onabort:null,error:new Error("Transaction is not active"),commit:()=>{},db:i,dispatchEvent:()=>!1,removeEventListener:()=>{},durability:"default",mode:"readonly",objectStoreNames:n,__aborted:!0};throw s}}function ut(i){return i.__aborted}async function Rn(i,n,e,t=window.indexedDB){(await Pa(t)).some(o=>o.name===n)&&(await hi(n,t),e.log("debug","Deleted existing database",n));let s=await new Promise((o,a)=>{e.log("debug","Copying to database",n,"at",i.version,"from",i.name);let l=t.open(n,i.version);l.onupgradeneeded=()=>{e.log("debug","Upgrading database",n,"to version",i.version);let p=i,f=l.transaction;if(!f)throw new Error("No transaction");for(let S of Array.from(p.objectStoreNames)){e.log("debug","Copying object store",S);let w=p.transaction(S).objectStore(S);f.db.createObjectStore(S,{keyPath:w.keyPath,autoIncrement:w.autoIncrement});let A=f.objectStore(S),y=p.transaction(S).objectStore(S);for(let I of Array.from(y.indexNames)){let _=y.index(I);e.log("debug","Copying index",I),A.createIndex(I,_.keyPath,{unique:_.unique,multiEntry:_.multiEntry})}}},l.onsuccess=()=>{e.log("debug","Opened reset database",n),o(l.result)},l.onerror=()=>a(l.error??new Error("Unknown database upgrade error"))});if(s.objectStoreNames.length>0){let o=await Tn(i,Array.from(i.objectStoreNames));await new Promise((a,l)=>{let p=s.transaction(Array.from(s.objectStoreNames),"readwrite");for(let f=0;f<o.length;f++){let S=p.objectStore(i.objectStoreNames[f]);for(let w of o[f])S.add(w)}p.oncomplete=()=>a(),p.onerror=f=>{let S=p.error??f.target.transaction?.error??new Error("Unknown error");e.log("critical","Error copying data",S),l(S)}})}await ve(s)}function vs(i,n,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(i,n);s.onsuccess=()=>{if(s.result.version!==n){s.result.close(),r(new Error(`Migration error: opened database version ${s.result.version} but expected version ${n} for database ${i}`));return}t(s.result)},s.onerror=()=>{r(s.error)},s.onblocked=()=>{r(new Error("Database blocked"))},s.onupgradeneeded=o=>{let a=s.result;a.version!==n&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${n}, got ${a.version}`)))}})}function Ft(i){return[i,"meta"].join("_")}function ht(i){return[i,"collections"].join("_")}function xs(i){return i.name?.split("_")[0]}var $e=class extends ce{constructor(e,t){super();this.db=e;this.ctx=t;this.createTransaction=(e,t)=>{try{if(this.globalAbortController.signal.aborted)throw new Error("Global abort signal is already aborted");let r=ws(this.db,e,t?.mode||"readonly",t?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r}catch(r){throw this.log?.("error","Failed to create abortable transaction for store names",e,r),r}};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=r?.transaction||this.createTransaction([e],r);if(ut(s))return Promise.resolve(void 0);let o=s.objectStore(e),a=t(o);return dt(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);if(r?.transaction&&ut(r.transaction))return Promise.resolve([]);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return Promise.all(a.map(dt))};this.iterate=async(e,t,r,s)=>{let o=s?.transaction||this.createTransaction([e],s);if(ut(o))return;let a=o.objectStore(e),l=t(a);return Array.isArray(l)?Promise.all(l.map(p=>new Promise((f,S)=>{p.onsuccess=()=>{let w=p.result;w?r(w.value,a,w)?f():w.continue():f()},p.onerror=()=>{p.error&&Ye(p.error)?f():S(p.error)}}))).then(()=>{}):new Promise((p,f)=>{l.onsuccess=()=>{let S=l.result;S?r(S.value,a,S)?p():S.continue():p()},l.onerror=()=>{l.error&&Ye(l.error)?p():f(l.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.onVersionChange=e=>{if(this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u")try{this.ctx.environment.location.reload()}catch(t){this.log?.("error","Failed to reload the page",t)}};let r=new AbortController;this.globalAbortController=r,this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var fi=class extends $e{constructor(){super(...arguments);this.add=async e=>{let t=e.file?await Da(e.file):void 0;await this.run("files",r=>r.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:t,timestamp:e.timestamp}),{mode:"readwrite"})};this.markUploaded=async e=>{if(this.disposed)return;let t=await this.getFileRaw(e);if(!t){this.ctx.log("error","Tried to mark unknown file as uploaded",e);return}await this.run("files",r=>r.put({...t,remote:"true"}),{mode:"readwrite"})};this.get=async e=>{let t=await this.getFileRaw(e);return t?this.hydrateFileData(t):null};this.delete=e=>this.run("files",t=>t.delete(e),{mode:"readwrite"});this.markPendingDelete=async e=>{let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,deletedAt:Date.now()}),{mode:"readwrite"})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"}))?.map(this.hydrateFileData)??[];this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),s=(await this.run("files",o=>o.index("remote").getAll("true"),{transaction:t})).filter(o=>!o.timestamp||!e||o.timestamp>e);await Promise.all(s.map(o=>this.run("files",a=>a.put({...o,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=e=>this.iterate("files",t=>t.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(t,r)=>{e(this.hydrateFileData(t),r)},{mode:"readwrite"});this.getAll=async e=>{let[t]=await Tn(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await Xe(this.db,"files")});this.loadFileContents=async(e,t)=>{if(e.file)return e.file;if(e.localPath)throw new Error("Local file paths are not supported in browser");if(e.url){let r=await t.environment.fetch(e.url);if(!r.ok)throw new Error(`Failed to download file ${e.url}: ${r.statusText}`);return r.blob()}throw new Error("File is missing url, file, and localPath")};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Ca(t,e.type,e.name):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{if(this.disposed)return;let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function Ca(i,n,e){return new File([new Blob([i],{type:n})],e??"blob",{type:n})}function Da(i){return"__testReadBuffer"in i?Promise.resolve(i.__testReadBuffer):new Promise((n,e)=>{let t=new FileReader;t.onload=()=>{n(t.result)},t.onerror=e,t.readAsArrayBuffer(i)})}var se={IS_LOCAL__TIMESTAMP:"l_t",ROOT_OID__TIMESTAMP:"d_t",OID__TIMESTAMP:"oid_timestamp"};var pi=class extends $e{constructor(e,t){super(e,t);this.transaction=async(e,t)=>{let r=this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});return await t(r)};this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>this.run("info",t=>t.get("localReplicaInfo"),e);this.updateLocalReplica=async(e,t)=>{try{await this.run("info",r=>r.put({...e,type:"localReplicaInfo"}),{mode:"readwrite",transaction:t?.transaction})}catch(r){throw this.ctx.log("critical","Error updating local replica",e,r),r}};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=K(e),[a,l]=hn(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,l,!1,!1))]},t,r)};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,r)};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,t)};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),t);this.setBaselines=async(e,t=Fn)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),t)};this.deleteBaseline=async(e,t=Fn)=>{await this.run("baselines",r=>r.delete(e),t)};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index(se.ROOT_OID__TIMESTAMP),a=Ee(e),l=r?.to?be(e,r.to):Pe(e),p=IDBKeyRange.bound(a,l,!1,!1);return o.openCursor(p)},t,r);this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=Ee(e),a=r?.to?be(e,r.to):Pe(e),l=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(l,r?.reverse?"prev":"next")},t,r);this.deleteEntityOperations=(e,t)=>this.iterate("operations",r=>{let s=Ee(e),o=t?.to?be(e,t.to):Pe(e),a=IDBKeyRange.bound(s,o,!1,!1);return r.openCursor(a)},(r,s)=>{s.delete(r.oid_timestamp)},t);this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,r);this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?be(!0,t.after):Ee(!0),o=Pe(!0);return r.index(se.IS_LOCAL__TIMESTAMP).openCursor(IDBKeyRange.bound(s,o,!!t?.after,!1),"next")},e);this.iterateAllOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.from?Ee(t.from):void 0,o=t?.before?Pe(t.before):Ee(!0),a=s&&o?IDBKeyRange.bound(s,o,!1,!0):s?IDBKeyRange.lowerBound(s,!1):o?IDBKeyRange.upperBound(o,!0):void 0;return r.index("timestamp").openCursor(a,"next")},e,t);this.addOperations=async(e,t=Fn)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add(K(o.oid)),s.put(this.addOperationIndexes(o)))),t),Array.from(r)};this.reset=async({clearReplica:e,transaction:t}={})=>{let r=t||this.createTransaction(["info","operations","baselines"],{mode:"readwrite"});await Promise.all([this.resetLocalReplica(r,e),this.resetBaselines(r),this.resetOperations(r)])};this.stats=async()=>{let e=await Xe(this.db,"operations"),t=await Xe(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",r=>r.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});{let r=await this.getLocalReplica({transaction:e});r&&(r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put({...r,type:"localReplicaInfo"}),{mode:"readwrite",transaction:e}))}};this.resetBaselines=async e=>this.clear("baselines",e);this.resetOperations=async e=>this.clear("operations",e);this.addOperationIndexes=e=>({...e,[se.OID__TIMESTAMP]:be(e.oid,e.timestamp),[se.IS_LOCAL__TIMESTAMP]:be(e.isLocal,e.timestamp),[se.ROOT_OID__TIMESTAMP]:be(K(e.oid),e.timestamp)});this.addDispose(()=>(this.ctx.log("info","Closing metadata DB for",t.namespace),ve(e)))}purgeDocumentData(e,t){let r=K(e),s=t?.transaction;return this.transaction({mode:"readwrite",storeNames:["baselines","operations"]},async o=>{let a=s??o;await this.iterate("baselines",l=>{let[p,f]=hn(r);return[l.openCursor(IDBKeyRange.only(r)),l.openCursor(IDBKeyRange.bound(p,f,!1,!1))]},(l,p)=>{p.delete(l.oid)},{mode:"readwrite",transaction:a}),await this.iterate("operations",l=>{let p=l.index(se.ROOT_OID__TIMESTAMP),f=Ee(r),S=Pe(r);return p.openCursor(IDBKeyRange.bound(f,S,!1,!1))},(l,p)=>{p.delete(l[se.OID__TIMESTAMP])},{mode:"readwrite",transaction:a})})}},Fn={mode:"readwrite"};var Ss=[Ta,Ra,Fa,ka,Ba,Ma],Aa=Ss.length;function kn({indexedDB:i=window.indexedDB,namespace:n,log:e}){return new Promise((t,r)=>{let s=i.open(Ft(n),Aa),o=!1;s.onupgradeneeded=async a=>{let l=s.result,p=s.transaction,f=Ss.slice(a.oldVersion);for(let S of f)await S(l,p);await new Promise((S,w)=>{p.addEventListener("complete",S),p.addEventListener("error",w)}),a.oldVersion||(o=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{t({db:s.result,wasInitialized:o})}})}async function Ta(i,n){let e=i.createObjectStore("baselines",{keyPath:"oid"}),t=i.createObjectStore("operations",{keyPath:se.OID__TIMESTAMP}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Ra(i,n){let e=n.objectStore("operations");await new Promise((t,r)=>{let s=e.openCursor();s.onsuccess=()=>{let o=s.result;if(o){let{isLocal_timestamp:a,documentOid_timestamp:l,...p}=o.value;o.update({...p,[se.IS_LOCAL__TIMESTAMP]:a,[se.ROOT_OID__TIMESTAMP]:l}),o.continue()}else t()},s.onerror=o=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex(se.IS_LOCAL__TIMESTAMP,se.IS_LOCAL__TIMESTAMP,{unique:!1}),e.createIndex(se.ROOT_OID__TIMESTAMP,se.ROOT_OID__TIMESTAMP,{unique:!1})}async function Fa(i,n){n.objectStore("operations").createIndex("timestamp","timestamp")}async function ka(i,n){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function Ba(i,n){let e=n.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let l=fn(a.value);l.oid_timestamp!==a.primaryKey?(a.delete(),e.put(l)):a.update(l),a.continue()}else r()},o.onerror=a=>{s(o.error)}});let t=n.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let l=fn(a.value);l.oid!==a.primaryKey?(a.delete(),t.put(l)):a.update(l),a.continue()}else r()},o.onerror=a=>{s(o.error)}})}async function Ma(i,n){n.objectStore("files").createIndex("timestamp","timestamp")}var La=i=>IDBKeyRange.only(_e(i.equals)),ja=i=>{},Na=i=>{let n=i.gte||i.gt,e=i.lte||i.lt;return n===e?IDBKeyRange.only(_e(n)):n?e?IDBKeyRange.bound(_e(n),_e(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(_e(n),!!i.gt):IDBKeyRange.upperBound(_e(e),!!i.lt)},Va=(i,n,e)=>{let t=i.collections[n].compounds?.[e.where];M(t,`Index ${e.where} does not exist on collection ${n}`);let r=Object.keys(e.match).sort((l,p)=>t.of.indexOf(l)-t.of.indexOf(p));for(let l of r)if(t.of.indexOf(l)!==r.indexOf(l))throw new Error(`Compound index ${e.where} does not have ${l} at the start of its order`);let s=r.map(l=>e.match[l]);if(r.length===t.of.length)return IDBKeyRange.only(be(...s));let o=Ee(...s),a=Pe(...s);return IDBKeyRange.bound(o,a)};function Ua(i){let n=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(n,e)}function Bn(i,n,e){if(e)return ti(e)?Na(e):ei(e)?La(e):In(e)?ja(e):ii(e)?Ua(e):Va(i,n,e)}var mi=class extends $e{constructor(e,t){super(e,t);this.context=t;this.close=async()=>{await this.dispose()};this.stats=async()=>{let e=Object.keys(this.context.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await Xe(this.db,r);t[r]=s})),t};this.findOneOid=async e=>{let t=await this.run(e.collection,r=>{let s=e.index?.where?r.index(e.index.where):r,o=e.index?.order==="desc"?"prev":"next",a=Bn(this.context.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?ee(e.collection,t.primaryKey.toString()):null};this.findAllOids=async({collection:e,index:t,offset:r,limit:s})=>{let o=this.createTransaction([e],{mode:"readonly"});if(ut(o))return{result:[],hasNextPage:!1};let a=o.objectStore(e),l=t?.where?a.index(t.where):a,p=t?.order==="desc"?"prev":"next",f=Bn(this.context.schema,e,t),S=l.openCursor(f,p),w=!1;return{result:await new Promise((y,I)=>{let _=!r,E=0,P=new Set;S.onsuccess=()=>{E++;let F=S.result;if(!F){y(Array.from(P));return}r&&!_?(F.advance(r),_=!0):((!s||P.size<s)&&P.add(ee(e,F.primaryKey.toString())),s&&E>s?(w=!0,y(Array.from(P))):F.continue())},S.onerror=()=>{S.error?.name==="InvalidStateError"?(this.context.log("error","find query failed with InvalidStateError",S.error),y([])):S.error&&Ye(S.error)?y([]):I(S.error)}}),hasNextPage:w}};this.saveEntities=async(e,t)=>{let r={transaction:this.createTransaction(t.collections,{mode:"readwrite",abort:t.abort})},s=await Promise.allSettled(e.map(async a=>{let l=a.getSnapshot();try{await this.saveDocument(a.oid,l,r)}catch(p){throw this.context.log("error",`Error saving document ${a.oid} (${JSON.stringify(l)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o=s.filter(a=>a.status==="rejected");if(o.length){if(o.length===s.length)throw new Error("Failed to save any documents. Something must be quite wrong.");this.context.log("error","Failed to save documents:",o,". See logs above. This only affects querying these documents. Let's hope a future attempt will correct them...")}r.transaction.commit()};this.reset=async()=>{let e=Object.keys(this.context.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>this.run(r,s=>s.clear(),{transaction:t}))),this.context.entityEvents.emit("collectionsChanged",e),this.context.log("info","\u{1F4A8} Reset queryable storage")};this.saveDocument=async(e,t,{transaction:r})=>{this.context.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=ne(e);try{if(!t)await this.run(s,a=>a.delete(o),{mode:"readwrite",transaction:r}),this.context.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.context.schema.collections[s],l=mn(a,t);l["@@@snapshot"]=JSON.stringify(t),await this.run(s,p=>p.put(l),{mode:"readwrite",transaction:r}),this.context.log("debug",`Save complete for ${e}`,l)}}catch(a){throw this.context.log("error",`Error saving document ${e}`,a),a}};this.addDispose(()=>(this.context.log("info","Closing document database for",t.namespace),ve(this.db)))}};async function Os(i,n,e,t,r){r?.("debug","Upgrading database",n,"to version",e);function s(o,a){let l=i.open(ht(n),e),p=!1;l.onupgradeneeded=f=>{let S=l.transaction;t(S,l.result,f),p=!0},l.onsuccess=async f=>{p?(await ve(l.result),o(l.result)):a(new Error("Database was not upgraded when a version change was expected"))},l.onerror=f=>{a(l.error||new Error("Unknown error"))},l.onblocked=f=>{r?.("Database upgrade blocked!")}}return new Promise(s)}async function Mn({indexedDB:i=ys,namespace:n,version:e,log:t}){if(e<=0)throw new Error("Cannot open database at version less than 1");t?.("debug","Opening database",n,"at version",e);let r=await vs(ht(n),e,i);return t?.("debug","Database opened",n,"at version",r.version),r.version!==e&&t?.("warn",`Opened database version ${r.version} but expected version ${e} for namespace ${n}`),r.addEventListener("versionchange",s=>{r.close()}),r.addEventListener("close",()=>{t?.("warn","Database closed",n)}),r}var ft=class{constructor(n=window.indexedDB){this.indexedDB=n;this.name="IdbPersistence";this.getNamespaces=async()=>{let n=await this.indexedDB.databases();return Array.from(new Set(n.map(xs).filter(e=>!!e)))};this.getNamespaceVersion=async n=>{let e=ht(n),r=(await this.indexedDB.databases()).find(s=>s.name===e);return r?r.version??0:0};this.deleteNamespace=async n=>{await Promise.all([hi(Ft(n),this.indexedDB),hi([n,"collections"].join("_"),this.indexedDB)])};this.openNamespace=async n=>new Ln(this.indexedDB,n);this.copyNamespace=async(n,e,t)=>{let r=t.cloneWithOptions({namespace:n}),s=t.cloneWithOptions({namespace:e}),{db:o}=await kn({indexedDB:this.indexedDB,log:r.log,namespace:r.namespace}),a=await Mn({indexedDB:this.indexedDB,namespace:r.namespace,version:r.schema.version,log:r.log});r.log("info",`Copying data from ${r.namespace} to ${s.namespace}`),await Rn(o,Ft(s.namespace),s,this.indexedDB),await Rn(a,ht(s.namespace),s,this.indexedDB),await ve(o),await ve(a)}}},Ln=class{constructor(n,e){this.indexedDB=n;this.namespace=e;this.openMetadata=async n=>{let{db:e}=await kn({indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return this.metadataDb=e,n.persistenceShutdownHandler.register(()=>ve(e)),new pi(e,n)};this.openDocuments=async n=>{let e=await Mn({version:n.schema.version,indexedDB:this.indexedDB,log:n.log,namespace:this.namespace});return n.persistenceShutdownHandler.register(()=>ve(e)),new mi(e,n)};this.applyMigration=async(n,e)=>{n.log("debug","Applying migration",e.newSchema.version,e),await Os(this.indexedDB,this.namespace,e.newSchema.version,(t,r)=>{for(let s of e.addedCollections)r.createObjectStore(s,{keyPath:e.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of e.allCollections){if(!r.objectStoreNames.contains(s))throw new Error(`Expected object store for collection ${s} to exist during migration, but it did not`);let o=t.objectStore(s);for(let a of e.addedIndexes[s]||[])o.createIndex(a.name,a.name,{multiEntry:a.multiEntry});for(let a of e.removedIndexes[s]||[])o.deleteIndex(a.name)}for(let s of e.removedCollections)t.objectStore(s).clear()},n.log)}}openFiles(n){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new fi(this.metadataDb,n))}};var Be=class{constructor(n){this.log=n;this.consumed=!1;this.handlers=[];this.reset=()=>{this.consumed=!1}}register(n){this.handlers.push(n)}async shutdown(){this.consumed&&this.log?.("warn","ShutdownHandler already consumed"),this.consumed=!0,await Promise.all(this.handlers.map(n=>n())),this.handlers.length=0}get isShuttingDown(){return this.consumed}};function Is(i,n){return`@@wip-${i}-${He(n)}`}function _s({migration:i,newOids:n,ctx:e,meta:t}){return i.allCollections.reduce((r,s)=>(r[s]={put:async(o,a)=>{qe(i.newSchema.collections[s],o);let l=o[i.newSchema.collections[s].primaryKey],p=ee(s,l);return n.push(p),await e.time.withMigrationTime(i.version,()=>t.insertData({operations:e.patchCreator.createInitialize(o,p,a?.access),isLocal:!0})),o},delete:async o=>{let a=ee(s,o);await e.time.withMigrationTime(i.version,()=>t.deleteDocument(a))}},r),{})}function za({migration:i,context:n,documents:e,meta:t}){return i.oldCollections.reduce((r,s)=>(r[s]={get:async o=>{let a=ee(s,o);return await t.getDocumentSnapshot(a,{to:n.time.nowWithVersion(i.oldSchema.version)})},findOne:async o=>{let a=await e.findOneOid({collection:s,index:o});return a?await t.getDocumentSnapshot(a,{to:n.time.nowWithVersion(i.oldSchema.version)}):null},findAll:async o=>{let{result:a}=await e.findAllOids({collection:s,index:o});return await Promise.all(a.map(async p=>t.getDocumentSnapshot(p,{to:n.time.nowWithVersion(i.oldSchema.version)})))}},r),{})}async function Es({migration:i,context:n,ns:e,meta:t}){let r=n.cloneWithOptions({schema:i.oldSchema});if(i.oldSchema.version===0)return $a({migration:i,context:r,meta:t});let s=new Array,o=await e.openDocuments(r),a=za({migration:i,context:r,documents:o,meta:t}),l=_s({migration:i,newOids:s,ctx:r,meta:t}),p=async w=>{await t.deleteCollection(w)},f=new Array;return{log:n.log,newOids:s,deleteCollection:p,migrate:async(w,A)=>{let y=await a[w].findAll();n.log("debug",`Migrating ${y.length} documents in ${w}`),await Promise.all(y.filter(Boolean).map(async I=>{let _=ae(I);M(!!_,`Document is missing an OID: ${JSON.stringify(I)}`);let E=await t.getDocumentAuthz(_),P=fe(I),F=await A(I);if(F){It(P),It(F),st(F);let b=Jt(P,F,()=>n.time.zeroWithVersion(i.version),void 0,[],{mergeUnknownObjects:!0,defaultUndefined:!1,authz:E});b.length>0&&await t.insertData({operations:b,isLocal:!0})}}))},queries:a,mutations:l,awaitables:f,close:async()=>{await o.close()}}}function $a({migration:i,context:n,meta:e}){let t=new Array,r=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=_s({migration:i,newOids:t,ctx:n,meta:e});return{log:n.log,newOids:t,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:r,mutations:s,awaitables:[],close:()=>Promise.resolve()}}async function Ps({ctx:i,documents:n,migration:e,meta:t,engine:r}){let s=await Ka({currentVersion:e.oldSchema.version,newVersion:e.newSchema.version,ctx:i,meta:t});for(let o of e.allCollections){let{result:a}=await n.findAllOids({collection:o});a.push(...r.newOids.filter(f=>ne(f).collection===o),...s.filter(f=>ne(f).collection===o));let p=(await Promise.all(a.map(async f=>{try{let S=await t.getDocumentSnapshot(f);return[f,S]}catch(S){return i.log("error","Could not regenerate snapshot during migration for oid",f,"this document will not be preserved",S),null}}))).filter(f=>!!f);await n.saveEntities(p.map(([f,S])=>({oid:f,getSnapshot(){return S}})),{collections:[o]})}}async function Ka({currentVersion:i,newVersion:n,ctx:e,meta:t}){let r=[];return await t.iterateAllOperations(s=>{r.push(s)},{from:e.time.zeroWithVersion(i+1)}),Array.from(new Set(r.map(s=>K(s.oid))))}function Cs({currentVersion:i,targetVersion:n,migrations:e}){let t=Ds({currentVersion:i,targetVersion:n,migrations:e});if(!t)throw new U(U.Code.MigrationPathNotFound,void 0,`No migration path found from ${i} to ${n}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function Ds({currentVersion:i,targetVersion:n,migrations:e}){if(i===n)return[];let t=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>n)return null;if(r.newSchema.version===n)return[r];let s=Ds({currentVersion:r.newSchema.version,targetVersion:n,migrations:e});if(s)return[r,...s]}return null}async function As({context:i,version:n,meta:e}){let t=await i.persistence.openNamespace(i.namespace,i);await Wa(i.namespace,async()=>{let r=await i.persistence.getNamespaceVersion(i.namespace);i.log("debug","Opening index database",i.namespace,"Current database version:",r,"target version:",n,i.schema.wip?"(wip)":"");let s=Cs({currentVersion:r,targetVersion:n,migrations:i.migrations});s.length>0&&(i.log("debug","Migrations to run:",s.map(o=>o.version)),await Ha({context:i,ns:t,toRun:s,meta:e}))})}async function Wa(i,n){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,n):await n()}async function Ha({context:i,toRun:n,ns:e,meta:t}){i.pauseRebasing=!0;for(let r of n){i.log("info",`\u{1F680} Running migration v${r.oldSchema.version} -> v${r.newSchema.version}`);let s=i.cloneWithOptions({schema:r.oldSchema,persistenceShutdownHandler:new Be(i.log)}),o=await Es({migration:r,context:s,ns:e,meta:t});try{i.log("debug","Migrating data",s.namespace,"from version",r.oldSchema.version,"to version",r.newSchema.version),await r.migrate(o),i.log("debug","Awaiting remaining migration tasks"),await Promise.all(o.awaitables)}catch(l){throw i.log("critical",`Migration failed (${r.oldSchema.version} -> ${r.newSchema.version})`,l),l instanceof Error?l:new Error("Unknown error during migration")}await o.close(),s.log("debug","Upgrading database",s.namespace,"from version",s.schema.version,"to version",r.newSchema.version),await e.applyMigration(s,r),s.schema=r.newSchema;let a=await e.openDocuments(s);await Ps({ctx:s,migration:r,engine:o,documents:a,meta:t}),await a.close(),s.log("debug",`Migration of ${s.namespace} complete.`),s.log("info",`
4
+ `)},_domwindow:function(){return m("domwindow")},_bigint:function(d){return m("bigint:"+d.toString())},_process:function(){return m("process")},_timer:function(){return m("timer")},_pipe:function(){return m("pipe")},_tcp:function(){return m("tcp")},_udp:function(){return m("udp")},_tty:function(){return m("tty")},_statwatcher:function(){return m("statwatcher")},_securecontext:function(){return m("securecontext")},_connection:function(){return m("connection")},_zlib:function(){return m("zlib")},_context:function(){return m("context")},_nodescript:function(){return m("nodescript")},_httpparser:function(){return m("httpparser")},_dataview:function(){return m("dataview")},_signal:function(){return m("signal")},_fsevent:function(){return m("fsevent")},_tlswrap:function(){return m("tlswrap")}}}function F(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,O,u){return u===void 0&&(u=O,O={}),P(O=_(b,O),u).dispatch(b)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,i,e){(function(t,r,s,o,a,l,p,f,S){(function(w){"use strict";var A=typeof Uint8Array<"u"?Uint8Array:Array,y="+".charCodeAt(0),I="/".charCodeAt(0),_="0".charCodeAt(0),E="a".charCodeAt(0),P="A".charCodeAt(0),F="-".charCodeAt(0),b="_".charCodeAt(0);function O(u){return u=u.charCodeAt(0),u===y||u===F?62:u===I||u===b?63:u<_?-1:u<_+10?u-_+26+26:u<P+26?u-P:u<E+26?u-E+26:void 0}w.toByteArray=function(u){var m,d;if(0<u.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var v=u.length,v=u.charAt(v-2)==="="?2:u.charAt(v-1)==="="?1:0,x=new A(3*u.length/4-v),L=0<v?u.length-4:u.length,B=0;function j(k){x[B++]=k}for(m=0;m<L;m+=4,0)j((16711680&(d=O(u.charAt(m))<<18|O(u.charAt(m+1))<<12|O(u.charAt(m+2))<<6|O(u.charAt(m+3))))>>16),j((65280&d)>>8),j(255&d);return v==2?j(255&(d=O(u.charAt(m))<<2|O(u.charAt(m+1))>>4)):v==1&&(j((d=O(u.charAt(m))<<10|O(u.charAt(m+1))<<4|O(u.charAt(m+2))>>2)>>8&255),j(255&d)),x},w.fromByteArray=function(u){var m,d,v,x,L=u.length%3,B="";function j(k){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(k)}for(m=0,v=u.length-L;m<v;m+=3)d=(u[m]<<16)+(u[m+1]<<8)+u[m+2],B+=j((x=d)>>18&63)+j(x>>12&63)+j(x>>6&63)+j(63&x);switch(L){case 1:B=(B+=j((d=u[u.length-1])>>2))+j(d<<4&63)+"==";break;case 2:B=(B=(B+=j((d=(u[u.length-2]<<8)+u[u.length-1])>>10))+j(d>>4&63))+j(d<<2&63)+"="}return B}})(e===void 0?this.base64js={}:e)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,y,o,a,l,p,f,S){var w=n("base64-js"),A=n("ieee754");function y(c,h,g){if(!(this instanceof y))return new y(c,h,g);var D,C,R,V,J=typeof c;if(h==="base64"&&J=="string")for(c=(V=c).trim?V.trim():V.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(J=="number")D=re(c);else if(J=="string")D=y.byteLength(c,h);else{if(J!="object")throw new Error("First argument needs to be a number, array or string.");D=re(c.length)}if(y._useTypedArrays?C=y._augment(new Uint8Array(D)):((C=this).length=D,C._isBuffer=!0),y._useTypedArrays&&typeof c.byteLength=="number")C._set(c);else if(q(V=c)||y.isBuffer(V)||V&&typeof V=="object"&&typeof V.length=="number")for(R=0;R<D;R++)y.isBuffer(c)?C[R]=c.readUInt8(R):C[R]=c[R];else if(J=="string")C.write(c,0,h);else if(J=="number"&&!y._useTypedArrays&&!g)for(R=0;R<D;R++)C[R]=0;return C}function I(c,h,g,D){return y._charsWritten=Mt(function(C){for(var R=[],V=0;V<C.length;V++)R.push(255&C.charCodeAt(V));return R}(h),c,g,D)}function _(c,h,g,D){return y._charsWritten=Mt(function(C){for(var R,V,J=[],X=0;X<C.length;X++)V=C.charCodeAt(X),R=V>>8,V=V%256,J.push(V),J.push(R);return J}(h),c,g,D)}function E(c,h,g){var D="";g=Math.min(c.length,g);for(var C=h;C<g;C++)D+=String.fromCharCode(c[C]);return D}function P(c,h,g,R){R||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+1<c.length,"Trying to read beyond buffer length"));var C,R=c.length;if(!(R<=h))return g?(C=c[h],h+1<R&&(C|=c[h+1]<<8)):(C=c[h]<<8,h+1<R&&(C|=c[h+1])),C}function F(c,h,g,R){R||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+3<c.length,"Trying to read beyond buffer length"));var C,R=c.length;if(!(R<=h))return g?(h+2<R&&(C=c[h+2]<<16),h+1<R&&(C|=c[h+1]<<8),C|=c[h],h+3<R&&(C+=c[h+3]<<24>>>0)):(h+1<R&&(C=c[h+1]<<16),h+2<R&&(C|=c[h+2]<<8),h+3<R&&(C|=c[h+3]),C+=c[h]<<24>>>0),C}function b(c,h,g,D){if(D||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+1<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return D=P(c,h,g,!0),32768&D?-1*(65535-D+1):D}function O(c,h,g,D){if(D||(T(typeof g=="boolean","missing or invalid endian"),T(h!=null,"missing offset"),T(h+3<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return D=F(c,h,g,!0),2147483648&D?-1*(4294967295-D+1):D}function u(c,h,g,D){return D||(T(typeof g=="boolean","missing or invalid endian"),T(h+3<c.length,"Trying to read beyond buffer length")),A.read(c,h,g,23,4)}function m(c,h,g,D){return D||(T(typeof g=="boolean","missing or invalid endian"),T(h+7<c.length,"Trying to read beyond buffer length")),A.read(c,h,g,52,8)}function d(c,h,g,D,C){if(C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"trying to write beyond buffer length"),nn(h,65535)),C=c.length,!(C<=g))for(var R=0,V=Math.min(C-g,2);R<V;R++)c[g+R]=(h&255<<8*(D?R:1-R))>>>8*(D?R:1-R)}function v(c,h,g,D,C){if(C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"trying to write beyond buffer length"),nn(h,4294967295)),C=c.length,!(C<=g))for(var R=0,V=Math.min(C-g,4);R<V;R++)c[g+R]=h>>>8*(D?R:3-R)&255}function x(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+1<c.length,"Trying to write beyond buffer length"),rn(h,32767,-32768)),c.length<=g||d(c,0<=h?h:65535+h+1,g,D,C)}function L(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),rn(h,2147483647,-2147483648)),c.length<=g||v(c,0<=h?h:4294967295+h+1,g,D,C)}function B(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+3<c.length,"Trying to write beyond buffer length"),hr(h,34028234663852886e22,-34028234663852886e22)),c.length<=g||A.write(c,h,g,D,23,4)}function j(c,h,g,D,C){C||(T(h!=null,"missing value"),T(typeof D=="boolean","missing or invalid endian"),T(g!=null,"missing offset"),T(g+7<c.length,"Trying to write beyond buffer length"),hr(h,17976931348623157e292,-17976931348623157e292)),c.length<=g||A.write(c,h,g,D,52,8)}e.Buffer=y,e.SlowBuffer=y,e.INSPECT_MAX_BYTES=50,y.poolSize=8192,y._useTypedArrays=function(){try{var c=new ArrayBuffer(0),h=new Uint8Array(c);return h.foo=function(){return 42},h.foo()===42&&typeof h.subarray=="function"}catch{return!1}}(),y.isEncoding=function(c){switch(String(c).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}},y.isBuffer=function(c){return!(c==null||!c._isBuffer)},y.byteLength=function(c,h){var g;switch(c+="",h||"utf8"){case"hex":g=c.length/2;break;case"utf8":case"utf-8":g=Ae(c).length;break;case"ascii":case"binary":case"raw":g=c.length;break;case"base64":g=dr(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":g=2*c.length;break;default:throw new Error("Unknown encoding")}return g},y.concat=function(c,h){if(T(q(c),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),c.length===0)return new y(0);if(c.length===1)return c[0];if(typeof h!="number")for(C=h=0;C<c.length;C++)h+=c[C].length;for(var g=new y(h),D=0,C=0;C<c.length;C++){var R=c[C];R.copy(g,D),D+=R.length}return g},y.prototype.write=function(c,h,g,D){isFinite(h)?isFinite(g)||(D=g,g=void 0):(X=D,D=h,h=g,g=X),h=Number(h)||0;var C,R,V,J,X=this.length-h;switch((!g||X<(g=Number(g)))&&(g=X),D=String(D||"utf8").toLowerCase()){case"hex":C=function(Se,de,ue,Z){ue=Number(ue)||0;var Y=Se.length-ue;(!Z||Y<(Z=Number(Z)))&&(Z=Y),T((Y=de.length)%2==0,"Invalid hex string"),Y/2<Z&&(Z=Y/2);for(var tt=0;tt<Z;tt++){var fr=parseInt(de.substr(2*tt,2),16);T(!isNaN(fr),"Invalid hex string"),Se[ue+tt]=fr}return y._charsWritten=2*tt,tt}(this,c,h,g);break;case"utf8":case"utf-8":R=this,V=h,J=g,C=y._charsWritten=Mt(Ae(c),R,V,J);break;case"ascii":case"binary":C=I(this,c,h,g);break;case"base64":R=this,V=h,J=g,C=y._charsWritten=Mt(dr(c),R,V,J);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":C=_(this,c,h,g);break;default:throw new Error("Unknown encoding")}return C},y.prototype.toString=function(c,h,g){var D,C,R,V,J=this;if(c=String(c||"utf8").toLowerCase(),h=Number(h)||0,(g=g!==void 0?Number(g):J.length)===h)return"";switch(c){case"hex":D=function(X,Se,de){var ue=X.length;(!Se||Se<0)&&(Se=0),(!de||de<0||ue<de)&&(de=ue);for(var Z="",Y=Se;Y<de;Y++)Z+=H(X[Y]);return Z}(J,h,g);break;case"utf8":case"utf-8":D=function(X,Se,de){var ue="",Z="";de=Math.min(X.length,de);for(var Y=Se;Y<de;Y++)X[Y]<=127?(ue+=ur(Z)+String.fromCharCode(X[Y]),Z=""):Z+="%"+X[Y].toString(16);return ue+ur(Z)}(J,h,g);break;case"ascii":case"binary":D=E(J,h,g);break;case"base64":C=J,V=g,D=(R=h)===0&&V===C.length?w.fromByteArray(C):w.fromByteArray(C.slice(R,V));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":D=function(X,Se,de){for(var ue=X.slice(Se,de),Z="",Y=0;Y<ue.length;Y+=2)Z+=String.fromCharCode(ue[Y]+256*ue[Y+1]);return Z}(J,h,g);break;default:throw new Error("Unknown encoding")}return D},y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},y.prototype.copy=function(c,h,g,D){if(h=h||0,(D=D||D===0?D:this.length)!==(g=g||0)&&c.length!==0&&this.length!==0){T(g<=D,"sourceEnd < sourceStart"),T(0<=h&&h<c.length,"targetStart out of bounds"),T(0<=g&&g<this.length,"sourceStart out of bounds"),T(0<=D&&D<=this.length,"sourceEnd out of bounds"),D>this.length&&(D=this.length);var C=(D=c.length-h<D-g?c.length-h+g:D)-g;if(C<100||!y._useTypedArrays)for(var R=0;R<C;R++)c[R+h]=this[R+g];else c._set(this.subarray(g,g+C),h)}},y.prototype.slice=function(c,h){var g=this.length;if(c=Q(c,g,0),h=Q(h,g,g),y._useTypedArrays)return y._augment(this.subarray(c,h));for(var D=h-c,C=new y(D,void 0,!0),R=0;R<D;R++)C[R]=this[R+c];return C},y.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},y.prototype.set=function(c,h){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,h)},y.prototype.readUInt8=function(c,h){if(h||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},y.prototype.readUInt16LE=function(c,h){return P(this,c,!0,h)},y.prototype.readUInt16BE=function(c,h){return P(this,c,!1,h)},y.prototype.readUInt32LE=function(c,h){return F(this,c,!0,h)},y.prototype.readUInt32BE=function(c,h){return F(this,c,!1,h)},y.prototype.readInt8=function(c,h){if(h||(T(c!=null,"missing offset"),T(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},y.prototype.readInt16LE=function(c,h){return b(this,c,!0,h)},y.prototype.readInt16BE=function(c,h){return b(this,c,!1,h)},y.prototype.readInt32LE=function(c,h){return O(this,c,!0,h)},y.prototype.readInt32BE=function(c,h){return O(this,c,!1,h)},y.prototype.readFloatLE=function(c,h){return u(this,c,!0,h)},y.prototype.readFloatBE=function(c,h){return u(this,c,!1,h)},y.prototype.readDoubleLE=function(c,h){return m(this,c,!0,h)},y.prototype.readDoubleBE=function(c,h){return m(this,c,!1,h)},y.prototype.writeUInt8=function(c,h,g){g||(T(c!=null,"missing value"),T(h!=null,"missing offset"),T(h<this.length,"trying to write beyond buffer length"),nn(c,255)),h>=this.length||(this[h]=c)},y.prototype.writeUInt16LE=function(c,h,g){d(this,c,h,!0,g)},y.prototype.writeUInt16BE=function(c,h,g){d(this,c,h,!1,g)},y.prototype.writeUInt32LE=function(c,h,g){v(this,c,h,!0,g)},y.prototype.writeUInt32BE=function(c,h,g){v(this,c,h,!1,g)},y.prototype.writeInt8=function(c,h,g){g||(T(c!=null,"missing value"),T(h!=null,"missing offset"),T(h<this.length,"Trying to write beyond buffer length"),rn(c,127,-128)),h>=this.length||(0<=c?this.writeUInt8(c,h,g):this.writeUInt8(255+c+1,h,g))},y.prototype.writeInt16LE=function(c,h,g){x(this,c,h,!0,g)},y.prototype.writeInt16BE=function(c,h,g){x(this,c,h,!1,g)},y.prototype.writeInt32LE=function(c,h,g){L(this,c,h,!0,g)},y.prototype.writeInt32BE=function(c,h,g){L(this,c,h,!1,g)},y.prototype.writeFloatLE=function(c,h,g){B(this,c,h,!0,g)},y.prototype.writeFloatBE=function(c,h,g){B(this,c,h,!1,g)},y.prototype.writeDoubleLE=function(c,h,g){j(this,c,h,!0,g)},y.prototype.writeDoubleBE=function(c,h,g){j(this,c,h,!1,g)},y.prototype.fill=function(c,h,g){if(h=h||0,g=g||this.length,T(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),T(h<=g,"end < start"),g!==h&&this.length!==0){T(0<=h&&h<this.length,"start out of bounds"),T(0<=g&&g<=this.length,"end out of bounds");for(var D=h;D<g;D++)this[D]=c}},y.prototype.inspect=function(){for(var c=[],h=this.length,g=0;g<h;g++)if(c[g]=H(this[g]),g===e.INSPECT_MAX_BYTES){c[g+1]="...";break}return"<Buffer "+c.join(" ")+">"},y.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(y._useTypedArrays)return new y(this).buffer;for(var c=new Uint8Array(this.length),h=0,g=c.length;h<g;h+=1)c[h]=this[h];return c.buffer};var k=y.prototype;function Q(c,h,g){return typeof c!="number"?g:h<=(c=~~c)?h:0<=c||0<=(c+=h)?c:0}function re(c){return(c=~~Math.ceil(+c))<0?0:c}function q(c){return(Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"})(c)}function H(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ae(c){for(var h=[],g=0;g<c.length;g++){var D=c.charCodeAt(g);if(D<=127)h.push(c.charCodeAt(g));else for(var C=g,R=(55296<=D&&D<=57343&&g++,encodeURIComponent(c.slice(C,g+1)).substr(1).split("%")),V=0;V<R.length;V++)h.push(parseInt(R[V],16))}return h}function dr(c){return w.toByteArray(c)}function Mt(c,h,g,D){for(var C=0;C<D&&!(C+g>=h.length||C>=c.length);C++)h[C+g]=c[C];return C}function ur(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function nn(c,h){T(typeof c=="number","cannot write a non-number as a number"),T(0<=c,"specified a negative value for writing an unsigned value"),T(c<=h,"value is larger than maximum value for type"),T(Math.floor(c)===c,"value has a fractional component")}function rn(c,h,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=h,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value"),T(Math.floor(c)===c,"value has a fractional component")}function hr(c,h,g){T(typeof c=="number","cannot write a non-number as a number"),T(c<=h,"value larger than maximum allowed value"),T(g<=c,"value smaller than minimum allowed value")}function T(c,h){if(!c)throw new Error(h||"Failed assertion")}y._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,w,o,a,l,p,f,S){var w=n("buffer").Buffer,A=4,y=new w(A);y.fill(0),i.exports={hash:function(I,_,E,P){for(var F=_(function(d,v){d.length%A!=0&&(x=d.length+(A-d.length%A),d=w.concat([d,y],x));for(var x,L=[],B=v?d.readInt32BE:d.readInt32LE,j=0;j<d.length;j+=A)L.push(B.call(d,j));return L}(I=w.isBuffer(I)?I:new w(I),P),8*I.length),_=P,b=new w(E),O=_?b.writeInt32BE:b.writeInt32LE,u=0;u<F.length;u++)O.call(b,F[u],4*u,!0);return b}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,w,o,a,l,p,f,S){var w=n("buffer").Buffer,A=n("./sha"),y=n("./sha256"),I=n("./rng"),_={sha1:A,sha256:y,md5:n("./md5")},E=64,P=new w(E);function F(d,v){var x=_[d=d||"sha1"],L=[];return x||b("algorithm:",d,"is not yet supported"),{update:function(B){return w.isBuffer(B)||(B=new w(B)),L.push(B),B.length,this},digest:function(B){var j=w.concat(L),j=v?function(k,Q,re){w.isBuffer(Q)||(Q=new w(Q)),w.isBuffer(re)||(re=new w(re)),Q.length>E?Q=k(Q):Q.length<E&&(Q=w.concat([Q,P],E));for(var q=new w(E),H=new w(E),Ae=0;Ae<E;Ae++)q[Ae]=54^Q[Ae],H[Ae]=92^Q[Ae];return re=k(w.concat([q,re])),k(w.concat([H,re]))}(x,v,j):x(j);return L=null,B?j.toString(B):j}}}function b(){var d=[].slice.call(arguments).join(" ");throw new Error([d,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
+ `))}P.fill(0),e.createHash=function(d){return F(d)},e.createHmac=F,e.randomBytes=function(d,v){if(!v||!v.call)return new w(I(d));try{v.call(this,void 0,new w(I(d)))}catch(x){v(x)}};var O,u=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],m=function(d){e[d]=function(){b("sorry,",d,"is not implemented yet")}};for(O in u)m(u[O],O)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){var w=n("./helpers");function A(b,O){b[O>>5]|=128<<O%32,b[14+(O+64>>>9<<4)]=O;for(var u=1732584193,m=-271733879,d=-1732584194,v=271733878,x=0;x<b.length;x+=16){var L=u,B=m,j=d,k=v,u=I(u,m,d,v,b[x+0],7,-680876936),v=I(v,u,m,d,b[x+1],12,-389564586),d=I(d,v,u,m,b[x+2],17,606105819),m=I(m,d,v,u,b[x+3],22,-1044525330);u=I(u,m,d,v,b[x+4],7,-176418897),v=I(v,u,m,d,b[x+5],12,1200080426),d=I(d,v,u,m,b[x+6],17,-1473231341),m=I(m,d,v,u,b[x+7],22,-45705983),u=I(u,m,d,v,b[x+8],7,1770035416),v=I(v,u,m,d,b[x+9],12,-1958414417),d=I(d,v,u,m,b[x+10],17,-42063),m=I(m,d,v,u,b[x+11],22,-1990404162),u=I(u,m,d,v,b[x+12],7,1804603682),v=I(v,u,m,d,b[x+13],12,-40341101),d=I(d,v,u,m,b[x+14],17,-1502002290),u=_(u,m=I(m,d,v,u,b[x+15],22,1236535329),d,v,b[x+1],5,-165796510),v=_(v,u,m,d,b[x+6],9,-1069501632),d=_(d,v,u,m,b[x+11],14,643717713),m=_(m,d,v,u,b[x+0],20,-373897302),u=_(u,m,d,v,b[x+5],5,-701558691),v=_(v,u,m,d,b[x+10],9,38016083),d=_(d,v,u,m,b[x+15],14,-660478335),m=_(m,d,v,u,b[x+4],20,-405537848),u=_(u,m,d,v,b[x+9],5,568446438),v=_(v,u,m,d,b[x+14],9,-1019803690),d=_(d,v,u,m,b[x+3],14,-187363961),m=_(m,d,v,u,b[x+8],20,1163531501),u=_(u,m,d,v,b[x+13],5,-1444681467),v=_(v,u,m,d,b[x+2],9,-51403784),d=_(d,v,u,m,b[x+7],14,1735328473),u=E(u,m=_(m,d,v,u,b[x+12],20,-1926607734),d,v,b[x+5],4,-378558),v=E(v,u,m,d,b[x+8],11,-2022574463),d=E(d,v,u,m,b[x+11],16,1839030562),m=E(m,d,v,u,b[x+14],23,-35309556),u=E(u,m,d,v,b[x+1],4,-1530992060),v=E(v,u,m,d,b[x+4],11,1272893353),d=E(d,v,u,m,b[x+7],16,-155497632),m=E(m,d,v,u,b[x+10],23,-1094730640),u=E(u,m,d,v,b[x+13],4,681279174),v=E(v,u,m,d,b[x+0],11,-358537222),d=E(d,v,u,m,b[x+3],16,-722521979),m=E(m,d,v,u,b[x+6],23,76029189),u=E(u,m,d,v,b[x+9],4,-640364487),v=E(v,u,m,d,b[x+12],11,-421815835),d=E(d,v,u,m,b[x+15],16,530742520),u=P(u,m=E(m,d,v,u,b[x+2],23,-995338651),d,v,b[x+0],6,-198630844),v=P(v,u,m,d,b[x+7],10,1126891415),d=P(d,v,u,m,b[x+14],15,-1416354905),m=P(m,d,v,u,b[x+5],21,-57434055),u=P(u,m,d,v,b[x+12],6,1700485571),v=P(v,u,m,d,b[x+3],10,-1894986606),d=P(d,v,u,m,b[x+10],15,-1051523),m=P(m,d,v,u,b[x+1],21,-2054922799),u=P(u,m,d,v,b[x+8],6,1873313359),v=P(v,u,m,d,b[x+15],10,-30611744),d=P(d,v,u,m,b[x+6],15,-1560198380),m=P(m,d,v,u,b[x+13],21,1309151649),u=P(u,m,d,v,b[x+4],6,-145523070),v=P(v,u,m,d,b[x+11],10,-1120210379),d=P(d,v,u,m,b[x+2],15,718787259),m=P(m,d,v,u,b[x+9],21,-343485551),u=F(u,L),m=F(m,B),d=F(d,j),v=F(v,k)}return Array(u,m,d,v)}function y(b,O,u,m,d,v){return F((O=F(F(O,b),F(m,v)))<<d|O>>>32-d,u)}function I(b,O,u,m,d,v,x){return y(O&u|~O&m,b,O,d,v,x)}function _(b,O,u,m,d,v,x){return y(O&m|u&~m,b,O,d,v,x)}function E(b,O,u,m,d,v,x){return y(O^u^m,b,O,d,v,x)}function P(b,O,u,m,d,v,x){return y(u^(O|~m),b,O,d,v,x)}function F(b,O){var u=(65535&b)+(65535&O);return(b>>16)+(O>>16)+(u>>16)<<16|65535&u}i.exports=function(b){return w.hash(b,A,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){var w;i.exports=w||function(A){for(var y,I=new Array(A),_=0;_<A;_++)!(3&_)&&(y=4294967296*Math.random()),I[_]=y>>>((3&_)<<3)&255;return I}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){var w=n("./helpers");function A(_,E){_[E>>5]|=128<<24-E%32,_[15+(E+64>>9<<4)]=E;for(var P,F,b,O=Array(80),u=1732584193,m=-271733879,d=-1732584194,v=271733878,x=-1009589776,L=0;L<_.length;L+=16){for(var B=u,j=m,k=d,Q=v,re=x,q=0;q<80;q++){O[q]=q<16?_[L+q]:I(O[q-3]^O[q-8]^O[q-14]^O[q-16],1);var H=y(y(I(u,5),(H=m,F=d,b=v,(P=q)<20?H&F|~H&b:!(P<40)&&P<60?H&F|H&b|F&b:H^F^b)),y(y(x,O[q]),(P=q)<20?1518500249:P<40?1859775393:P<60?-1894007588:-899497514)),x=v,v=d,d=I(m,30),m=u,u=H}u=y(u,B),m=y(m,j),d=y(d,k),v=y(v,Q),x=y(x,re)}return Array(u,m,d,v,x)}function y(_,E){var P=(65535&_)+(65535&E);return(_>>16)+(E>>16)+(P>>16)<<16|65535&P}function I(_,E){return _<<E|_>>>32-E}i.exports=function(_){return w.hash(_,A,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){function w(E,P){var F=(65535&E)+(65535&P);return(E>>16)+(P>>16)+(F>>16)<<16|65535&F}function A(E,P){var F,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),O=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),u=new Array(64);E[P>>5]|=128<<24-P%32,E[15+(P+64>>9<<4)]=P;for(var m,d,v=0;v<E.length;v+=16){for(var x=O[0],L=O[1],B=O[2],j=O[3],k=O[4],Q=O[5],re=O[6],q=O[7],H=0;H<64;H++)u[H]=H<16?E[H+v]:w(w(w((d=u[H-2],I(d,17)^I(d,19)^_(d,10)),u[H-7]),(d=u[H-15],I(d,7)^I(d,18)^_(d,3))),u[H-16]),F=w(w(w(w(q,I(d=k,6)^I(d,11)^I(d,25)),k&Q^~k&re),b[H]),u[H]),m=w(I(m=x,2)^I(m,13)^I(m,22),x&L^x&B^L&B),q=re,re=Q,Q=k,k=w(j,F),j=B,B=L,L=x,x=w(F,m);O[0]=w(x,O[0]),O[1]=w(L,O[1]),O[2]=w(B,O[2]),O[3]=w(j,O[3]),O[4]=w(k,O[4]),O[5]=w(Q,O[5]),O[6]=w(re,O[6]),O[7]=w(q,O[7])}return O}var y=n("./helpers"),I=function(E,P){return E>>>P|E<<32-P},_=function(E,P){return E>>>P};i.exports=function(E){return y.hash(E,A,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){e.read=function(w,A,y,I,v){var E,P,F=8*v-I-1,b=(1<<F)-1,O=b>>1,u=-7,m=y?v-1:0,d=y?-1:1,v=w[A+m];for(m+=d,E=v&(1<<-u)-1,v>>=-u,u+=F;0<u;E=256*E+w[A+m],m+=d,u-=8);for(P=E&(1<<-u)-1,E>>=-u,u+=I;0<u;P=256*P+w[A+m],m+=d,u-=8);if(E===0)E=1-O;else{if(E===b)return P?NaN:1/0*(v?-1:1);P+=Math.pow(2,I),E-=O}return(v?-1:1)*P*Math.pow(2,E-I)},e.write=function(w,A,y,I,_,x){var P,F,b=8*x-_-1,O=(1<<b)-1,u=O>>1,m=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,d=I?0:x-1,v=I?1:-1,x=A<0||A===0&&1/A<0?1:0;for(A=Math.abs(A),isNaN(A)||A===1/0?(F=isNaN(A)?1:0,P=O):(P=Math.floor(Math.log(A)/Math.LN2),A*(I=Math.pow(2,-P))<1&&(P--,I*=2),2<=(A+=1<=P+u?m/I:m*Math.pow(2,1-u))*I&&(P++,I/=2),O<=P+u?(F=0,P=O):1<=P+u?(F=(A*I-1)*Math.pow(2,_),P+=u):(F=A*Math.pow(2,u-1)*Math.pow(2,_),P=0));8<=_;w[y+d]=255&F,d+=v,F/=256,_-=8);for(P=P<<_|F,b+=_;0<b;w[y+d]=255&P,d+=v,P/=256,b-=8);w[y+d-v]|=128*x}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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(n,i,e){(function(t,r,s,o,a,l,p,f,S){var w,A,y;function I(){}(t=i.exports={}).nextTick=(A=typeof window<"u"&&window.setImmediate,y=typeof window<"u"&&window.postMessage&&window.addEventListener,A?function(_){return window.setImmediate(_)}:y?(w=[],window.addEventListener("message",function(_){var E=_.source;E!==window&&E!==null||_.data!=="process-tick"||(_.stopPropagation(),0<w.length&&w.shift()())},!0),function(_){w.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=I,t.addListener=I,t.once=I,t.off=I,t.removeListener=I,t.removeAllListeners=I,t.emit=I,t.binding=function(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){throw new Error("process.chdir is not supported")}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("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 wn=he((Dl,Hr)=>{Hr.exports=function(i,e){var t="000000000"+i;return t.substr(t.length-e)}});var qr=he((Al,Qr)=>{var ea=wn(),ta=typeof window=="object"?window:self,ia=Object.keys(ta).length,na=navigator.mimeTypes?navigator.mimeTypes.length:0,ra=ea((na+navigator.userAgent.length).toString(36)+ia.toString(36),4);Qr.exports=function(){return ra}});var Xr=he((Tl,Yr)=>{var vn,Jr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;Jr?(Gr=Math.pow(2,32)-1,vn=function(){return Math.abs(Jr.getRandomValues(new Uint32Array(1))[0]/Gr)}):vn=Math.random;var Gr;Yr.exports=vn});var Je=he((Rl,is)=>{var Yt=qr(),Zr=wn(),sa=Xr(),Et=0,Sn=4,Xt=36,es=Math.pow(Xt,Sn);function xn(){return Zr((sa()*es<<0).toString(Xt),Sn)}function ts(){return Et=Et<es?Et:0,Et++,Et-1}function Pt(){var n="c",i=new Date().getTime().toString(Xt),e=Zr(ts().toString(Xt),Sn),t=Yt(),r=xn()+xn();return n+i+e+t+r}Pt.slug=function(){var i=new Date().getTime().toString(36),e=ts().toString(36).slice(-4),t=Yt().slice(0,1)+Yt().slice(-1),r=xn().slice(-2);return i.slice(-2)+e+t+r};Pt.isCuid=function(i){return typeof i!="string"?!1:!!i.startsWith("c")};Pt.isSlug=function(i){if(typeof i!="string")return!1;var e=i.length;return e>=7&&e<=10};Pt.fingerprint=Yt;is.exports=Pt});var Ze={};pr(Ze,{__addDisposableResource:()=>Xs,__assign:()=>Oi,__asyncDelegator:()=>Ks,__asyncGenerator:()=>$s,__asyncValues:()=>Ws,__await:()=>pt,__awaiter:()=>Ls,__classPrivateFieldGet:()=>Js,__classPrivateFieldIn:()=>Ys,__classPrivateFieldSet:()=>Gs,__createBinding:()=>_i,__decorate:()=>ks,__disposeResources:()=>Zs,__esDecorate:()=>Qa,__exportStar:()=>Ns,__extends:()=>Rs,__generator:()=>js,__importDefault:()=>qs,__importStar:()=>Qs,__makeTemplateObject:()=>Hs,__metadata:()=>Ms,__param:()=>Bs,__propKey:()=>Ja,__read:()=>Vn,__rest:()=>Fs,__runInitializers:()=>qa,__setFunctionName:()=>Ga,__spread:()=>Vs,__spreadArray:()=>zs,__spreadArrays:()=>Us,__values:()=>Ii,default:()=>Za});function Rs(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Nn(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function Fs(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function ks(n,i,e,t){var r=arguments.length,s=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,o;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")s=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(o=n[a])&&(s=(r<3?o(s):r>3?o(i,e,s):o(i,e))||s);return r>3&&s&&Object.defineProperty(i,e,s),s}function Bs(n,i){return function(e,t){i(e,t,n)}}function Qa(n,i,e,t,r,s){function o(E){if(E!==void 0&&typeof E!="function")throw new TypeError("Function expected");return E}for(var a=t.kind,l=a==="getter"?"get":a==="setter"?"set":"value",p=!i&&n?t.static?n:n.prototype:null,f=i||(p?Object.getOwnPropertyDescriptor(p,t.name):{}),S,w=!1,A=e.length-1;A>=0;A--){var y={};for(var I in t)y[I]=I==="access"?{}:t[I];for(var I in t.access)y.access[I]=t.access[I];y.addInitializer=function(E){if(w)throw new TypeError("Cannot add initializers after decoration has completed");s.push(o(E||null))};var _=(0,e[A])(a==="accessor"?{get:f.get,set:f.set}:f[l],y);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(S=o(_.get))&&(f.get=S),(S=o(_.set))&&(f.set=S),(S=o(_.init))&&r.unshift(S)}else(S=o(_))&&(a==="field"?r.unshift(S):f[l]=S)}p&&Object.defineProperty(p,t.name,f),w=!0}function qa(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function Ja(n){return typeof n=="symbol"?n:"".concat(n)}function Ga(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function Ms(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function Ls(n,i,e,t){function r(s){return s instanceof e?s:new e(function(o){o(s)})}return new(e||(e=Promise))(function(s,o){function a(f){try{p(t.next(f))}catch(S){o(S)}}function l(f){try{p(t.throw(f))}catch(S){o(S)}}function p(f){f.done?s(f.value):r(f.value).then(a,l)}p((t=t.apply(n,i||[])).next())})}function js(n,i){var e={label:0,sent:function(){if(s[0]&1)throw s[1];return s[1]},trys:[],ops:[]},t,r,s,o;return o={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(o[Symbol.iterator]=function(){return this}),o;function a(p){return function(f){return l([p,f])}}function l(p){if(t)throw new TypeError("Generator is already executing.");for(;o&&(o=0,p[0]&&(e=0)),e;)try{if(t=1,r&&(s=p[0]&2?r.return:p[0]?r.throw||((s=r.return)&&s.call(r),0):r.next)&&!(s=s.call(r,p[1])).done)return s;switch(r=0,s&&(p=[p[0]&2,s.value]),p[0]){case 0:case 1:s=p;break;case 4:return e.label++,{value:p[1],done:!1};case 5:e.label++,r=p[1],p=[0];continue;case 7:p=e.ops.pop(),e.trys.pop();continue;default:if(s=e.trys,!(s=s.length>0&&s[s.length-1])&&(p[0]===6||p[0]===2)){e=0;continue}if(p[0]===3&&(!s||p[1]>s[0]&&p[1]<s[3])){e.label=p[1];break}if(p[0]===6&&e.label<s[1]){e.label=s[1],s=p;break}if(s&&e.label<s[2]){e.label=s[2],e.ops.push(p);break}s[2]&&e.ops.pop(),e.trys.pop();continue}p=i.call(n,e)}catch(f){p=[6,f],r=0}finally{t=s=0}if(p[0]&5)throw p[1];return{value:p[0]?p[1]:void 0,done:!0}}}function Ns(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&_i(i,n,e)}function Ii(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vn(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,s=[],o;try{for(;(i===void 0||i-- >0)&&!(r=t.next()).done;)s.push(r.value)}catch(a){o={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(o)throw o.error}}return s}function Vs(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Vn(arguments[i]));return n}function Us(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var s=arguments[i],o=0,a=s.length;o<a;o++,r++)t[r]=s[o];return t}function zs(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,s;t<r;t++)(s||!(t in i))&&(s||(s=Array.prototype.slice.call(i,0,t)),s[t]=i[t]);return n.concat(s||Array.prototype.slice.call(i))}function pt(n){return this instanceof pt?(this.v=n,this):new pt(n)}function $s(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(w){t[w]&&(r[w]=function(A){return new Promise(function(y,I){s.push([w,A,y,I])>1||a(w,A)})})}function a(w,A){try{l(t[w](A))}catch(y){S(s[0][3],y)}}function l(w){w.value instanceof pt?Promise.resolve(w.value.v).then(p,f):S(s[0][2],w)}function p(w){a("next",w)}function f(w){a("throw",w)}function S(w,A){w(A),s.shift(),s.length&&a(s[0][0],s[0][1])}}function Ks(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,s){i[r]=n[r]?function(o){return(e=!e)?{value:pt(n[r](o)),done:!1}:s?s(o):o}:s}}function Ws(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof Ii=="function"?Ii(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(s){e[s]=n[s]&&function(o){return new Promise(function(a,l){o=n[s](o),r(a,l,o.done,o.value)})}}function r(s,o,a,l){Promise.resolve(l).then(function(p){s({value:p,done:a})},o)}}function Hs(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function Qs(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&_i(i,n,e);return Ya(i,n),i}function qs(n){return n&&n.__esModule?n:{default:n}}function Js(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function Gs(n,i,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function Ys(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function Xs(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function Zs(n){function i(t){n.error=n.hasError?new Xa(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(s){return i(s),e()})}catch(s){i(s)}}if(n.hasError)throw n.error}return e()}var Nn,Oi,_i,Ya,Xa,Za,et=Po(()=>{Nn=function(n,i){return Nn=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Nn(n,i)};Oi=function(){return Oi=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&(i[s]=e[s])}return i},Oi.apply(this,arguments)};_i=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};Ya=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};Xa=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};Za={__extends:Rs,__assign:Oi,__rest:Fs,__decorate:ks,__param:Bs,__metadata:Ms,__awaiter:Ls,__generator:js,__createBinding:_i,__exportStar:Ns,__values:Ii,__read:Vn,__spread:Vs,__spreadArrays:Us,__spreadArray:zs,__await:pt,__asyncGenerator:$s,__asyncDelegator:Ks,__asyncValues:Ws,__makeTemplateObject:Hs,__importStar:Qs,__importDefault:qs,__classPrivateFieldGet:Js,__classPrivateFieldSet:Gs,__classPrivateFieldIn:Ys,__addDisposableResource:Xs,__disposeResources:Zs}});var to=he(eo=>{"use strict";Object.defineProperty(eo,"__esModule",{value:!0})});var zn=he(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var io=(et(),it(Ze));function no(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}De.eventHandlerSafeInvoke=no;function Un(n,i,e){return(0,io.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Un;function ec(n,i,e,t){for(let r of n){let{succeeded:s,error:o}=no(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}}De.invokeEventHandlers=ec;function tc(n,i,e,t){return(0,io.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:s,error:o}=yield Un(r,i,e);if(!s&&t?.swallowExceptions!==!0)throw o}else{let r=[];for(let s of n)r.push(Un(s,i,e).then(({succeeded:o,error:a})=>{if(!o&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=tc});var oo=he(Ei=>{"use strict";Object.defineProperty(Ei,"__esModule",{value:!0});Ei.TypedEvent=void 0;var ic=(et(),it(Ze)),ro=zn(),so={swallowExceptions:!1,parallelize:!0},$n=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=so){(0,ro.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=so){return(0,ic.__awaiter)(this,void 0,void 0,function*(){yield(0,ro.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};Ei.TypedEvent=$n});var Wn=he(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});var nc=(et(),it(Ze));(0,nc.__exportStar)(oo(),Kn)});var ao=he(Pi=>{"use strict";Object.defineProperty(Pi,"__esModule",{value:!0});Pi.FinalizationRegistryMissingError=void 0;var Hn=class extends Error{};Pi.FinalizationRegistryMissingError=Hn});var qn=he(Ci=>{"use strict";Object.defineProperty(Ci,"__esModule",{value:!0});Ci.WeakHandlerHolder=void 0;var rc=ao(),Qn=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new rc.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(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};Ci.WeakHandlerHolder=Qn});var co=he(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.WeakEvent=void 0;var Jn=(et(),it(Ze)),sc=Wn(),oc=qn(),Gn=zn(),ac={swallowExceptions:!1,parallelize:!0},Yn=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new sc.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new oc.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=(0,Gn.eventHandlerSafeInvoke)(s,i,e);if(!o&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=ac){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let s=r?.deref();if(s){let{succeeded:o,error:a}=yield(0,Gn.eventHandlerSafeInvokeAsync)(s,i,e);if(!o&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Jn.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let s of this._handlers){let o=s?.deref();o?r.push((0,Gn.eventHandlerSafeInvokeAsync)(o,i,e).then(({succeeded:a,error:l})=>{if(!a&&t.swallowExceptions!==!0)throw l})):this.releaseHandler(s)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};Di.WeakEvent=Yn});var uo=he(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});var lo=(et(),it(Ze));(0,lo.__exportStar)(qn(),Ai);(0,lo.__exportStar)(co(),Ai)});var ho=he(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});var Xn=(et(),it(Ze));(0,Xn.__exportStar)(to(),Ft);(0,Xn.__exportStar)(Wn(),Ft);(0,Xn.__exportStar)(uo(),Ft)});var lr={};pr(lr,{Client:()=>tn,Entity:()=>le,EntityFile:()=>Ee,IdbPersistence:()=>ft,ServerSync:()=>yt,Storage:()=>tn,UndoHistory:()=>lt,authorization:()=>Sc,cliSync:()=>Oc,createMigration:()=>yn,debugLogger:()=>An,getEntityClient:()=>mo,id:()=>Ic,makeLogger:()=>ms,noLogger:()=>di,schema:()=>Ct});function Co(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}function Do(n){return typeof Buffer<"u"?Buffer.from(n,"base64").toString():atob(n)}var We={onlyUser:n=>Co(`u:${n}:*`),onlyMe:()=>We.onlyUser(sn),decode:n=>{let e=Do(n).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},sn="$$_originator_$$";function gr(n,i){let{operations:e,baselines:t}=n;if(e)for(let r of e)r.authz&&We.decode(r.authz).subject===sn&&(r.authz=We.onlyUser(i));if(t)for(let r of t)r.authz&&We.decode(r.authz).subject===sn&&(r.authz=We.onlyUser(i))}var nt=class{constructor(i){this.flusher=i,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:i,userData:e,items:t,max:r,timeout:s}){let o=this.batches.get(i);return o||(o=new on({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:i}),this.batches.set(i,o)),o.update({items:t,max:r,timeout:s,userData:e}),o}},on=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:s,key:o}){this.items=[],this.update=({items:a,max:l,timeout:p,userData:f})=>{this.items.push(...a),l!==void 0&&(this.max=l),p!==void 0&&(this.timeout=p),f&&(this.userData=f);let S=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():S&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=s,this.key=o}};var bt;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage",n[n.MigrationPathNotFound=7001]="MigrationPathNotFound",n[n.ImportFailed=7002]="ImportFailed",n[n.Offline=7003]="Offline"})(bt||(bt={}));var U=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};U.Code=bt;function yr(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}var jt,Ao=new Uint8Array(16);function an(){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(Ao)}var br=/^(?:[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 To(n){return typeof n=="string"&&br.test(n)}var wr=To;var te=[];for(Nt=0;Nt<256;++Nt)te.push((Nt+256).toString(16).substr(1));var Nt;function Ro(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(te[n[i+0]]+te[n[i+1]]+te[n[i+2]]+te[n[i+3]]+"-"+te[n[i+4]]+te[n[i+5]]+"-"+te[n[i+6]]+te[n[i+7]]+"-"+te[n[i+8]]+te[n[i+9]]+"-"+te[n[i+10]]+te[n[i+11]]+te[n[i+12]]+te[n[i+13]]+te[n[i+14]]+te[n[i+15]]).toLowerCase();if(!wr(e))throw TypeError("Stringified UUID is invalid");return e}var vr=Ro;function Fo(n,i,e){n=n||{};var t=n.random||(n.rng||an)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return vr(t)}var wt=Fo;var Ir=Me(Or(),1);function ko(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function cn(n){let i=new WeakMap,e=0;return JSON.stringify(n,(t,r)=>{if(typeof r=="object"&&r!==null){if(i.has(r))return{$ref:i.get(r)};i.set(r,`cyclic-ref:${e++}`)}return ko(t,r)})}function fe(n,i=!0){if(!i&&typeof structuredClone=="function")return structuredClone(n);if(N(n)||Array.isArray(n)){let e=G(n),t;if(Array.isArray(n))t=n.map(r=>fe(r,i));else{t={};for(let[r,s]of Object.entries(n))t[r]=fe(s,i)}return i&&e&&z(t,e),t}return n}function He(n){return(0,Ir.default)(n)}function N(n){return n&&typeof n=="object"}function _r(n){for(var i=[],e=[n],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&i.indexOf(r)===-1){i.push(r);for(var s in r)e.push(r[s])}}return t}function M(n,i="assertion failed"){if(!n)throw new Error(i)}function vt(n=16){return wt().replace("-","").slice(0,n)}function Er(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Pr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function Cr(n,i){let e=0,t;return function(...r){let s=this,o=Date.now();o-e>=i?(e=o,n.apply(s,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=o,n.apply(s,r)},i))}}function ln(n){try{return JSON.stringify(n)}catch{return`[recursive/invalid:${String(n)}]`}}function pe(n){return n&&n["@@type"]==="file"}function xt(n,i){return{"@@type":"file",id:n,alt:i}}function rt(n){return typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob}function Vt(n){return n&&N(n)&&typeof n.id=="string"&&typeof n.remote=="boolean"&&typeof n.name=="string"&&typeof n.type=="string"}function $(n){return oe(n)||pe(n)}function Te(n,i){return n===i?!0:!(!$(n)||!$(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}function oe(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function Qe(n,i,e,t,r=[],s){z(n,i),st(n,t);let o=Wt(n);for(let a of o.keys()){let l=o.get(a),p={oid:a,timestamp:e(),data:{op:"initialize",value:Kt(l)}};r.push(Tr(p,s?.authz))}return r}function Ar(n,i,e,t=[],r){let s={oid:i,timestamp:e(),data:{op:"initialize",value:n}};return t.push(Tr(s,r?.authz)),t}function Tr(n,i){return i&&(n.authz=i),n}function zt(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function Rr(n){let i={};for(let e of n){let t=K(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Fr(n){let i={};for(let e of n){let t=K(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Le(n,i){return Array.isArray(n)?!0:(n===void 0&&console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${G(n)})
7
+ Patch that was not applied: ${JSON.stringify(i)}`),!1)}function je(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,s;function o(a){e&&$(a)&&e.push(a)}switch(i.op){case"set":o(t[i.name]),t[i.name]=i.value;break;case"remove":o(t[i.name]),delete t[i.name];break;case"list-set":Le(n,i)&&(o(n[i.index]),n[i.index]=i.value);break;case"list-push":Le(n,i)&&n.push(i.value);break;case"list-delete":Le(n,i)&&(o(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Le(n,i)&&(s=n.splice(i.from,1),n.splice(i.to,0,s[0]));break;case"list-remove":if(Le(n,i))do{let a=i.value;i.only==="last"?$(a)?r=Er(n,l=>$(l)&&Te(l,a)):r=n.lastIndexOf(a):$(a)?r=n.findIndex(l=>$(l)&&Te(l,a)):r=n.indexOf(a),r!==-1&&(o(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":Le(n,i)&&(n.some(l=>oe(l)&&oe(i.value)?l.id===i.value.id:l===i.value)||n.push(i.value));break;case"list-move-by-ref":Le(n,i)&&(r=n.findIndex(a=>Te(a,i.value)),s=n.splice(r,1),n.splice(i.index,0,s[0]));break;case"list-insert":if(Le(n,i)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(o):N(n)&&Object.values(n||{}).forEach(o);return;case"initialize":return fe(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function Ut(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=Dr(r,i,e),N(n[t])&&Ut(n[t],i,e)}else if(!pe(n)){if(N(n)){M(G(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=Dr(n[t],i,e),N(n[t])&&Ut(n[t],i,e)}}return e}function Dr(n,i,e){if(oe(n)){e.push(n.id);let t=i.get(n.id);return M(!!t,`No value was found in object map for ${n.id}`),z(t,n.id)}else return n}function kr(n){return n.data.op==="set"?n.data.name:!1}function Br(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}function $t(n){return{oid:n.oid,timestamp:n.timestamp,data:n.data,authz:n.authz}}var Bo="/",St=":",un=new WeakMap;function ae(n){let i=G(n);return M(!!i,`Object ${ln(n)} does not have an OID assigned to it`),i}function G(n){if(N(n))return un.get(n)}function z(n,i){return M(N(n),`Only objects can be assigned OIDs, received ${ln(n)}`),Nr(n)&&Kt(n),un.set(n,i),n}function Nr(n){return!!G(n)}function Kt(n){return un.delete(n),n}function Mr(n,i,e){if(Nr(n)){let t=ae(n);if(Ne(t,i))return ae(n);{let r=Oe(i,e);return z(n,r),r}}else{let t=Oe(i,e);return z(n,t),t}}var dn={".":"&dot;","/":"&slash;",":":"&colon;"};function Lr(n){return n.replace(/[/]/g,dn["/"]).replace(/[:]/g,dn[":"]).replace(/[.]/g,dn["."])}function jr(n){return n.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function ee(n,i,e){let t=Lr(n)+Bo+Lr(i);return e&&(t+=St+e),t}function Oe(n,i=Mo){let{collection:e,id:t}=ne(n);return ee(e,t,i())}function ne(n){let[i,e,...t]=n.split("/");t.length&&(console.error(`OID ${n} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,s]=e.split(St),o;return r.includes(".")?o=r.slice(0,r.indexOf(".")):o=r,{collection:jr(i),id:jr(o),subId:s}}function st(n,i){let e=ae(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],N(t)&&!$(t)&&(Mr(t,e,i),st(t,i))}else if(N(n)&&!$(n))for(let t of Object.keys(n))N(n[t])&&!$(n[t])&&(Mr(n[t],e,i),st(n[t],i))}function Ht(n){if(Kt(n),Array.isArray(n))for(let i=0;i<n.length;i++)Ht(n[i]);else if(N(n))for(let i of Object.keys(n))Ht(n[i])}function Mo(){return wt().slice(0,8)}function ie(n){return{"@@type":"ref",id:n}}function Wt(n,i=new Map){if(Array.isArray(n)){let e=ae(n),t=z([],e);for(let r=0;r<n.length;r++){let s=n[r];if(N(s)){if(oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(pe(s)){t[r]=s;continue}else{let o=ae(s);t[r]=ie(o),Wt(s,i)}}else t[r]=s}i.set(e,t)}else if(N(n)&&!$(n)){let e=ae(n),t=z({},e);for(let r of Object.keys(n)){let s=n[r];if(N(s)){if(oe(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(pe(s))t[r]=s;else{let o=ae(s);t[r]=ie(o),Wt(s,i)}}else t[r]=s}i.set(e,t)}else $(n);return i}function K(n){return n.split(".")[0].split(St)[0]}function hn(n){let i=K(n),e=Oe(i,()=>"\uFFFF");return[`${i}${St}`,e]}function Ne(n,i){return K(n)===K(i)}function Qt(n){return!n.includes(St)}var ot="__@@oid_do_not_use",Re="@@id";function Lo(n){if(N(n))return n[Re]||n[ot]}function jo(n){return N(n)&&(delete n[ot],delete n[Re]),n}function No(n){let i=Lo(n);i&&z(n,i)}function Ot(n){if(No(n),jo(n),Array.isArray(n))for(let i=0;i<n.length;i++)Ot(n[i]);else if(N(n))for(let i of Object.keys(n))Ot(n[i])}function Vo(n){let{collection:i,id:e,subId:t}=ne(n);return ee(i,e,t)}var Uo=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function zo(n){return n.replaceAll(Uo,i=>{let e=i.slice(1,i.length-1);return`"${Vo(e)}"`})}function fn(n){return JSON.parse(zo(JSON.stringify(n)))}function pn(n){return n===Re||n===ot}var Ve=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!N(t)||$(t),this.createDiff=(t,r,s={})=>qt(t,r,this.getNow,this.createSubId,[],s),this.createInitialize=(t,r,s,o)=>o?Ar(t,r,this.getNow,void 0,s?{authz:s}:void 0):Qe(t,r,this.getNow,this.createSubId,void 0,s?{authz:s}:void 0),this.createSet=(t,r,s,o)=>{if(this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:s},authz:o}];{let a=Oe(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ie(a),name:r},authz:o}]}},this.createRemove=(t,r,s)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r},authz:s}],this.createListSet=(t,r,s,o)=>{if(M(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:s},authz:o}];{let a=Oe(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,{authz:o}),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ie(a)},authz:o}]}},this.createListPush=(t,r,s)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r},authz:s}];{let o=Oe(t,this.createSubId);return[...Qe(r,o,this.getNow,void 0,void 0,{authz:s}),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ie(o)},authz:s}]}},this.createListAdd=(t,r,s)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r},authz:s}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ie(r)},authz:s}],this.createListInsert=(t,r,s,o)=>{if(M(r>=0,"List index must be non-negative"),this.isPrimitive(s))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:s,index:r},authz:o}];{let a=Oe(t,this.createSubId);return[...Qe(s,a,this.getNow,this.createSubId,void 0,o?{authz:o}:void 0),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ie(a),index:r},authz:o}]}},this.createListInsertMany=(t,r,s,o)=>{M(r>=0,"List index must be non-negative");let a=[],l=s.map(p=>{if(this.isPrimitive(p))return p;let f=Oe(t,this.createSubId);return a.push(...Qe(p,f,this.getNow,this.createSubId,void 0,{authz:o})),ie(f)});return a.push({oid:t,timestamp:this.getNow(),data:{op:"list-insert",values:l,index:r},authz:o}),a},this.createListRemove=(t,r,s,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:s},authz:o}],this.createListDelete=(t,r,s=1,o)=>(M(r>=0,"List index must be non-negative"),M(s>0,"Count must be positive and non-zero"),[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:s},authz:o}]),this.createListMoveByRef=(t,r,s,o)=>(M(s>=0,"List index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:s},authz:o}]),this.createListMoveByIndex=(t,r,s,o)=>(M(r>=0,"List move from index must be non-negative"),M(s>=0,"List move to index must be non-negative"),[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:s},authz:o}]),this.createDelete=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"},authz:r}],this.createDeleteAll=(t,r)=>t.map(s=>({oid:s,timestamp:this.getNow(),data:{op:"delete"},authz:r}))}};function at(n,i){if(n===i)return!0;if($(n)&&$(i))return Te(n,i);let e=G(n),t=G(i);return!!(e&&t&&e===t)}function Vr(n,i,e,t){if(!It(i))return i;let r=G(i);if(!r)t.mergeUnknownObjects&&e&&z(i,e);else if(!Ne(n,r))return fe(i,!1);return i}function It(n){return N(n)&&!$(n)}function qt(n,i,e,t,r,s){var o;let a={patches:[],mergeUnknownObjects:s?.mergeUnknownObjects,merge:(o=s?.merge)!==null&&o!==void 0?o:s?.defaultUndefined,authz:s?.authz,patchCreator:new Ve(e,t)};return Jt(n,i,a),a.patches}function Jt(n,i,e){if(Array.isArray(n)&&Array.isArray(i))$o(n,i,e);else{if(Array.isArray(n)||Array.isArray(i))throw new U(U.Code.Unexpected,void 0,"Cannot diff between array and non-array");It(n)&&It(i)&&Ko(n,i,e)}}function $o(n,i,e){let t=ae(n),r=[],s=new Set;for(let f=0;f<n.length;f++){let S=n[f];r[f]=S;let w=G(S);w&&s.add(w)}for(let f=0;f<i.length;f++){let S=i[f],w=n[f];i[f]=Vr(t,S,G(w),e)}let o=!0,a=new Set,l=new Set;for(let f=0;f<i.length;f++){let S=i[f],w=r[f];S===void 0&&(o=!1);let A=G(S),y=o&&f>=r.length;if(A&&s.has(A))if(at(S,w))Jt(w,S,e);else{e.patches.push(...e.patchCreator.createListMoveByRef(t,ie(A),f,e.authz));let I=G(w);I&&l.add(I),a.add(A)}else if(y)e.patches.push(...e.patchCreator.createListPush(t,S,e.authz));else if(at(S,w))Jt(w,S,e);else{let I=f===0||at(i[f-1],r[f-1]),_=f===i.length-1||at(i[f+1],r[f]);I&&_?(e.patches.push(...e.patchCreator.createListInsert(t,f,S,e.authz)),r.splice(f,0,void 0)):e.patches.push(...e.patchCreator.createListSet(t,f,S,e.authz))}}if(r.length-i.length>0)for(let f=r.length-1;f>=i.length;f--){let S=r[f],w=G(S);w?a.has(w)||(ct(S,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(w),"last",e.authz))):e.patches.push(...e.patchCreator.createListRemove(t,S,"last",e.authz))}for(let f of l){if(a.has(f))continue;let S=n.find(w=>G(w)===f);S&&ct(S,e),e.patches.push(...e.patchCreator.createListRemove(t,ie(f),"last",e.authz))}}function Ko(n,i,e){let t=new Set(Object.keys(n)),r=ae(n);for(let s in i){let o=i[s];if(o===void 0&&e.merge||(t.delete(s),pn(s)))continue;let a=n[s];It(o)?(Vr(r,o,G(a),e),a?at(o,a)?Jt(a,o,e):(e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),ct(a,e)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz))):at(o,a)||(o===void 0?e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)):e.patches.push(...e.patchCreator.createSet(r,s,o,e.authz)),ct(a,e))}if(!e.merge)for(let s of t)pn(s)||(e.patches.push(...e.patchCreator.createRemove(r,s,e.authz)),ct(n[s],e))}function ct(n,i){if(!It(n))return;let e=G(n);if(e){i.patches.push(...i.patchCreator.createDelete(e,i.authz));for(let t in n){let r=n[t];ct(r,i)}}}var W=class{constructor(i){this._onAllUnsubscribed=i,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=vt(),s=this.subscribers[e];return s||(s=this.subscribers[e]={}),s[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};var Gt="\uFFFFFE",Wo="\0",Ho="\uFFFFFF";function be(...n){let i=Qo(n);return i.length===1?i[0]:i}function Pe(...n){return n.join(Gt)+`${Ho}`}function _e(...n){return n.join(Gt)+`${Gt}${Wo}`}function Qo(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let s of e)t.push(r.concat(s));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(Gt))))}function Ur(n){return!!n.field}function qo(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let s=r;Ur(s)?e[t]=Ie(i[s.field]):e[t]=Ie(s.compute(i))}return e}function Jo(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=be(...r.of.map(s=>i[s])),e),{})}function Go(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=Ie(i[t])),e),{})}function mn(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},Go(n,i)),qo(n,i));return Object.assign(e,Jo(n,Object.assign(Object.assign({},i),e))),e}var Yo="null";function Ie(n){if(n===null)return Yo;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(Ie);throw new Error(`Unsupported index value: ${n}`)}function zr(n,i){let e,t;return(...r)=>{let s=i();return e&&e.length===s.length&&e.every((o,a)=>o===s[a])||(e=[...s],t=n(...r)),t}}var Xo={version:0,collections:{}};function $r(n){return n?[...Object.keys(n.indexes||{}).map(i=>{let e=n.indexes[i],t=e.type;!t&&e.field&&(t=n.fields[e.field].type),M(t,`Could not determine type of index ${n}.${i}. Index must have a type. Perhaps your schema is malformed?`);let r=_t(n,i);return{name:i,multiEntry:r,synthetic:!0,compound:!1,type:t?.replace("[]","")}}),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:_t(n,i),synthetic:!1,compound:!0,type:"string"}))]:[]}function yn(n,i,e){let t=typeof i=="function"||i===void 0,r=t?Xo:n,s=t?n:i,o=t?i:e;M(r,"Invalid arguments to createMigration"),M(s,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:l,removedCollections:p,addedIndexes:f,removedIndexes:S,autoMigratedCollections:w,autoMigration:A}=Zo(r,s);return{version:s.version,migrate:async y=>{let I=[];if(await o?.({migrate:async(E,P)=>{let F=A(E),b=async O=>{let u=await P(O);z(u,ae(O));let m=F(u),d=Wr(s.collections[E].fields,m);return m};await y.migrate(E,b),I.push(E),w.delete(E)},info:{changedCollections:a,addedCollections:l,removedCollections:p},queries:y.queries,mutations:y.mutations}),s.version>1){y.log("debug","auto-migrating collections with new defaults",w);for(let P of w)await y.migrate(P,A(P)),I.push(P);for(let P of p)await y.deleteCollection(P);let E=a.filter(P=>!I.includes(P));E.length>0&&y.log("error",`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,E)}},removedCollections:p,addedIndexes:f,removedIndexes:S,allCollections:Object.keys(s.collections),changedCollections:a,addedCollections:l,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Zo(n,i){let e=Object.keys(i.collections).filter(f=>n.collections[f]&&cn(n.collections[f])!==cn(i.collections[f])),t=Object.keys(n.collections).filter(f=>!i.collections[f]),r=Object.keys(i.collections).filter(f=>!n.collections[f]),s=new Set;for(let f of e){let S=n.collections[f].fields,w=i.collections[f].fields;Object.keys(w).some(A=>(!S[A]||gn(S[A]))&&!gn(w[A]))&&s.add(f),Object.keys(S).some(A=>!w[A])&&s.add(f)}let o={},a={};for(let f of[...e,...r]){let S=$r(n.collections[f]),w=$r(i.collections[f]),A=w.filter(I=>!S.find(_=>_.name===I.name)),y=S.filter(I=>!w.find(_=>_.name===I.name));A.length>0&&(o[f]=A,e.includes(f)&&s.add(f)),y.length>0&&(a[f]=y,e.includes(f)&&s.add(f))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:o,removedIndexes:a,autoMigratedCollections:s,withDefaults:(f,S)=>qe(i.collections[f],S),autoMigration:f=>S=>{let w=i.collections[f];return qe(w,Kr(w,S))}}}var bn={};var Ue;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Ue||(Ue={}));var ns=Me(Je(),1),oa=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function aa(n){let{properties:i,fields:e}=n,t=oa(n,["properties","fields"]),r=i||e;if(!r)throw new Error("objectField must be passed a properties object");return Object.assign(Object.assign({type:"object"},t),{properties:r})}function ca(n,i){return n.properties=i,n}function la(n){return Object.assign({type:"array"},n)}function da(n,i){return n.items=i,n}var ua=n=>Object.assign({type:"string"},n),ha=n=>Object.assign({type:"number"},n),fa=n=>Object.assign({type:"boolean"},n),pa=n=>Object.assign({type:"any"},n);function ma(n){return Object.assign({type:"map"},n)}function ga(n,i){return n.values=i,n}var ya=n=>Object.assign({type:"file"},n),ba=()=>({type:"string",default:ns.default}),rs={object:aa,array:la,replaceObjectFields:ca,replaceArrayItems:da,string:ua,number:ha,boolean:fa,any:pa,map:ma,replaceMapValues:ga,file:ya,id:ba};var cs=Me(Je(),1);function Zt(n){return n.equals!==void 0}function ei(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function ss(n){return!!n.match}function ti(n){return n.startsWith!==void 0}function In(n){return!ei(n)&&!Zt(n)&&!ss(n)&&!ti(n)&&n.order}function _t(n,i){var e,t;let r=(e=n.compounds)===null||e===void 0?void 0:e[i];if(r)return r.of.some(a=>_t(n,a));let s=(t=n.indexes)===null||t===void 0?void 0:t[i];if(s){if("type"in s)return On(s.type);if("field"in s){let a=n.fields[s.field];return a?On(a.type):!1}}let o=n.fields[i];return o?On(o.type):!1}function On(n){return n==="array"||n.endsWith("[]")}function ge(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Fe(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function gn(n){return!ge(n)&&!Fe(n)}function qe(n,i){for(let[e,t]of Object.entries(n.fields)){let r=Ce(t);(r!==void 0&&i[e]===void 0||!ge(t)&&i[e]===null)&&(i[e]=r),i[e]&&Ge(i[e],t)}return i}function Ge(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=Ce(t);r!==void 0&&(n[e]=r)}Ge(n[e],t)}else if(i.type==="array")for(let e of n)Ge(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Re||e===ot||Ge(t,i.values)}function Ce(n){if("default"in n){let i=typeof n.default=="function"?n.default():n.default;if(i===null)return i;let e=structuredClone(i);if(n.type==="object")for(let[t,r]of Object.entries(n.properties))e[t]===void 0&&(e[t]=Ce(r));return e}if(ge(n))return null;if(n.type==="array")return[];if(n.type==="map")return{}}function Kr(n,i){for(let[e,t]of Object.entries(i))e===Re||e===ot||(n.fields[e]?_n(t,n.fields[e]):delete i[e]);return i}function _n(n,i){if(N(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?_n(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)_n(e,i.items)}function os(n){return n.type==="string"||n.type==="number"||n.type==="boolean"}function Wr(n,i){for(let[e,t]of Object.entries(i))if(e!==Re){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=ke({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function ke({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r,expectRefs:s,hasPassedFirstLevel:o}){let a=s&&o;if(!(t!==void 0&&t<=0)&&!(ge(n)&&i==null)){if(i==null&&(r||!Fe(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${me(e)}`};if(n.type==="object")if(a){if(!oe(i))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${me(e)}, got ${we(i)}`}}else{if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected object ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`};for(let[l,p]of Object.entries(n.properties)){if(l===Re)continue;let f=ke({field:p,value:i[l],fieldPath:[...e,l],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(f)return f}for(let l of Object.keys(i))if(!n.properties[l])return{type:"invalid-key",fieldPath:[...e,l],message:`Invalid unexpected field "${l}" on value ${me(e)}`}}else if(n.type==="array")if(a){if(!oe(i))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${me(e)}, got ${we(i)}`}}else{if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`};for(let l of i){let p=ke({field:n.items,value:l,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(p)return p}}else if(n.type==="map")if(a){if(!oe(i))return{type:"invalid-type",fieldPath:e,message:`Expected ref for field ${me(e)}, got ${we(i)}`}}else{if(!N(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${me(e)}, got ${we(i)}`};for(let[l,p]of Object.entries(i)){let f=ke({field:n.values,value:p,fieldPath:[...e,l],depth:t!==void 0?t-1:void 0,expectRefs:s,hasPassedFirstLevel:!0});if(f)return f}}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${me(e)}, got ${we(i)}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`}}else if(n.type==="file"){if(a){if(!pe(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ref for field ${me(e)}, got ${we(i)}`}}else if(!rt(i)&&!Vt(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ${n.nullable?"or null ":""}for field ${me(e)}, got ${we(i)}`}}}}function we(n){try{return JSON.stringify(n)}catch{return String(n)}}function me(n){return n.length===0?"root":n.join(".")}function as(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=ii({field:n[t],value:r,fieldPath:[t]}));return e}function ii({field:n,value:i,fieldPath:e=[],depth:t}){let r=ke({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!N(i))return i;let s={};for(let[o,a]of Object.entries(n.properties))s[o]=ii({field:a,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else{if(n.type==="array")return Array.isArray(i)?i.map(s=>ii({field:n.items,value:s,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!N(i))return i;let s={};for(let[o,a]of Object.entries(i))s[o]=ii({field:n.values,value:a,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});return s}else return i}}function ze(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var wa=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function va(n){var{synthetics:i,indexes:e}=n,t=wa(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),e);for(let[s,o]of Object.entries(t.fields))"indexed"in o&&(r[s]={field:s});return Object.assign(Object.assign({},t),{indexes:r})}function Ct(n){return n}Ct.collection=va;Ct.fields=rs;Ct.generated={id:cs.default};var hs=Me(Je(),1),ci=4,At=36;function ls(n){return n.toString(At).padStart(ci,"0")}function xa(n){return n.toString().padStart(6,"0")}var ni=class{constructor(){this.latest={time:Date.now(),counter:0,node:Sa()},this.zeroCounter=0,this.now=i=>(this.latest=us(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=us(this.latest),xa(i)+Ia(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(ci);this.latest=Oa(this.latest,fs(e))},this.get=(i,e)=>ls(i)+ds(e),this.zero=i=>ls(i)+ds({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=Dn}},ri=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},si=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},En=4,Pn=7,oi=60*1e3,Dt=9;function Sa(){return hs.default.slug().padStart(Pn,"0").slice(0,Pn)}function ds(n){let i=new Date(n.time).getTime().toString(At).padStart(Dt,"0"),e=n.counter.toString(At).padStart(En,"0"),t=n.node.padStart(Pn,"0");return`${i}${e}${t}`}function us(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>oi)throw new ri(e,i,oi);if(t>65535)throw new si;return{time:e,counter:t,node:n.node}}function Oa(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),s;if(n.time===t&&i.time===t?s=r+1:n.time===t?s=n.counter+1:i.time===t?s=i.counter+1:s=0,t-e>oi)throw new ri(t,e,oi);if(s>65535)throw new si;return{time:t,counter:s,node:n.node}}function fs(n){let i=n.slice(0,Dt),e=n.slice(Dt,Dt+En),t=n.slice(Dt+En),r=parseInt(i,At),s=parseInt(e,At);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:t}}function Ia(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function ai(n){return parseInt(n.slice(0,ci),36)}function Cn(n,i){return ai(n)-ai(i)}function Dn(n){return fs(n.slice(ci)).time}function ps(n,i,e,t,r,s){let o=new Ve(t,r);if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"},authz:s}];let a=fe(i),l=[];for(let p of e){let f=_a(n,a,p,o,s);l.unshift(...f),je(a,p.data)}return l}function _a(n,i,e,t,r){var s,o;let a=e.data;switch(a.op){case"set":return i[a.name]===void 0?t.createRemove(n,a.name,r):t.createSet(n,a.name,i[a.name],r);case"remove":return i[a.name]===void 0?[]:t.createSet(n,a.name,i[a.name],r);case"list-insert":return a.value===void 0&&((s=a.values)===null||s===void 0?void 0:s.length)===0?[]:t.createListDelete(n,a.index,a.value?1:((o=a.values)===null||o===void 0?void 0:o.length)||0,r);case"list-delete":return t.createListInsertMany(n,a.index,i.slice(a.index,a.index+a.count),r);case"list-move-by-ref":return t.createListMoveByRef(n,a.value,Tt(i,a.value),r);case"list-move-by-index":return t.createListMoveByIndex(n,a.to,a.from,r);case"delete":return t.createInitialize(i,n,r,!0);case"list-push":return t.createListRemove(n,a.value,"last",r);case"list-remove":if(a.only==="last"){let l=Tt(i,a.value,0,"backward");return l===-1?[]:t.createListInsert(n,l,a.value,r)}else if(a.only==="first"){let l=Tt(i,a.value);return l===-1?[]:t.createListInsert(n,l,a.value,r)}else{let l=[],p=Tt(i,a.value);for(;p!==-1;)l.push(p),p=Tt(i,a.value,p+1);return l.flatMap(f=>t.createListInsert(n,f,a.value,r))}case"list-add":return t.createListRemove(n,a.value,"last",r);case"list-set":return i[a.index]!==void 0?t.createListSet(n,a.index,i[a.index],r):t.createListDelete(n,a.index,1,r);case"initialize":return t.createDelete(n,r);case"touch":return[];default:throw new Error(`Cannot undo operation type: ${a.op}`)}}function Tt(n,i,e=0,t="forward"){let r=t==="forward"?"findIndex":"findLastIndex";return $(i)?n[r]((s,o)=>$(s)&&s.id===i.id&&o>=e):n[r]((s,o)=>s===i&&o>=e)}var li=class{constructor(i){this.value=i}deref(){return this.value}};var lt=class extends W{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),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}get undoLength(){return this._undoable.length}get redoLength(){return this._undone.length}};var di=()=>{},ms=n=>(i,...e)=>{i==="critical"&&e.unshift("[CRITICAL]"),n&&e.unshift(`[${n}]`),i==="critical"?console.error(...e):console[i](...e)};function An(n){return localStorage.getItem("DEBUG")?ms(n):di}var ce=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=async()=>{this.disposed=!0,await Promise.all(this._disposes.map(async i=>{try{await i()}catch(e){console.error("Error disposing",e)}})),this._disposes=[]};this.compose=i=>this.addDispose(i.dispose.bind(i));this.addDispose=i=>{this._disposes.push(i)}}};var gs=typeof window<"u"?window.indexedDB:void 0;function Ye(n){return n instanceof Error&&n.name==="AbortError"}function dt(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&Ye(n.error)?i(n.result):e(n.error)}})}function Xe(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),o=r.objectStore(i).openCursor(),a=0,l=0;o.onsuccess=function(p){let f=o.result;f&&(a++,l=l+_r(f.value),f.continue())},o.onerror=function(p){o.error&&Ye(o.error)?e({count:a,size:l}):t(o.error)},r.oncomplete=function(p){e({count:a,size:l})},r.onabort=function(p){t(p)},r.onerror=function(p){t(p)}})}function Tn(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let s=e.objectStore(r);return dt(s.getAll())});return Promise.all(t)}async function ve(n){n.close(),await new Promise(i=>{i()}),await new Promise(i=>{i()})}async function ys(n,i){let e=i.indexedDB.deleteDatabase([n,"meta"].join("_")),t=i.indexedDB.deleteDatabase([n,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{t.onsuccess=r,t.onerror=s})]),i.location.reload()}function ui(n,i=window.indexedDB){return dt(i.deleteDatabase(n))}async function Ea(n=window.indexedDB){return n.databases()}function bs(n,i,e,t,r){try{let s=n.transaction(i,e);if(t){let o=()=>{r?.("debug","aborting transaction");try{s.abort(),s.__aborted=!0}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",o),s.addEventListener("error",()=>{t.removeEventListener("abort",o)}),s.addEventListener("complete",()=>{t.removeEventListener("abort",o)})}return s}catch(s){if(s instanceof Error&&s.name==="InvalidStateError")return r?.("warn","Failed to create transaction, database is closing"),{abort:()=>{},addEventListener:()=>{},objectStore:()=>({add:()=>{},put:()=>{},get:()=>{},getAll:()=>{},delete:()=>{},clear:()=>{},openCursor:()=>{let o={onsuccess:()=>{},onerror:a=>{},result:null};return setTimeout(()=>{o.onerror({})},0),o},index:()=>{throw new Error("Transaction is not active")}}),oncomplete:null,onerror:null,onabort:null,error:new Error("Transaction is not active"),commit:()=>{},db:n,dispatchEvent:()=>!1,removeEventListener:()=>{},durability:"default",mode:"readonly",objectStoreNames:i,__aborted:!0};throw s}}function ut(n){return n.__aborted}async function Rn(n,i,e,t=window.indexedDB){(await Ea(t)).some(o=>o.name===i)&&(await ui(i,t),e.log("debug","Deleted existing database",i));let s=await new Promise((o,a)=>{e.log("debug","Copying to database",i,"at",n.version,"from",n.name);let l=t.open(i,n.version);l.onupgradeneeded=()=>{e.log("debug","Upgrading database",i,"to version",n.version);let p=n,f=l.transaction;if(!f)throw new Error("No transaction");for(let S of Array.from(p.objectStoreNames)){e.log("debug","Copying object store",S);let w=p.transaction(S).objectStore(S);f.db.createObjectStore(S,{keyPath:w.keyPath,autoIncrement:w.autoIncrement});let A=f.objectStore(S),y=p.transaction(S).objectStore(S);for(let I of Array.from(y.indexNames)){let _=y.index(I);e.log("debug","Copying index",I),A.createIndex(I,_.keyPath,{unique:_.unique,multiEntry:_.multiEntry})}}},l.onsuccess=()=>{e.log("debug","Opened reset database",i),o(l.result)},l.onerror=()=>a(l.error??new Error("Unknown database upgrade error"))});if(s.objectStoreNames.length>0){let o=await Tn(n,Array.from(n.objectStoreNames));await new Promise((a,l)=>{let p=s.transaction(Array.from(s.objectStoreNames),"readwrite");for(let f=0;f<o.length;f++){let S=p.objectStore(n.objectStoreNames[f]);for(let w of o[f])S.add(w)}p.oncomplete=()=>a(),p.onerror=f=>{let S=p.error??f.target.transaction?.error??new Error("Unknown error");e.log("critical","Error copying data",S),l(S)}})}await ve(s)}function ws(n,i,e=window.indexedDB){return new Promise((t,r)=>{let s=e.open(n,i);s.onsuccess=()=>{if(s.result.version!==i){s.result.close(),r(new Error(`Migration error: opened database version ${s.result.version} but expected version ${i} for database ${n}`));return}t(s.result)},s.onerror=()=>{r(s.error)},s.onblocked=()=>{r(new Error("Database blocked"))},s.onupgradeneeded=o=>{let a=s.result;a.version!==i&&(a.close(),r(new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${i}, got ${a.version}`)))}})}function Rt(n){return[n,"meta"].join("_")}function ht(n){return[n,"collections"].join("_")}function vs(n){return n.name?.split("_")[0]}var $e=class extends ce{constructor(e,t){super();this.db=e;this.ctx=t;this.createTransaction=(e,t)=>{try{if(this.globalAbortController.signal.aborted)throw new Error("Global abort signal is already aborted");let r=bs(this.db,e,t?.mode||"readonly",t?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r}catch(r){throw this.log?.("error","Failed to create abortable transaction for store names",e,r),r}};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=r?.transaction||this.createTransaction([e],r);if(ut(s))return Promise.resolve(void 0);let o=s.objectStore(e),a=t(o);return dt(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);if(r?.transaction&&ut(r.transaction))return Promise.resolve([]);let o=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(o);return Promise.all(a.map(dt))};this.iterate=async(e,t,r,s)=>{let o=s?.transaction||this.createTransaction([e],s);if(ut(o))return;let a=o.objectStore(e),l=t(a);return Array.isArray(l)?Promise.all(l.map(p=>new Promise((f,S)=>{p.onsuccess=()=>{let w=p.result;w?r(w.value,a,w)?f():w.continue():f()},p.onerror=()=>{p.error&&Ye(p.error)?f():S(p.error)}}))).then(()=>{}):new Promise((p,f)=>{l.onsuccess=()=>{let S=l.result;S?r(S.value,a,S)?p():S.continue():p()},l.onerror=()=>{l.error&&Ye(l.error)?p():f(l.error)}})};this.clear=(e,t)=>this.run(e,r=>r.clear(),{mode:"readwrite",transaction:t});this.onVersionChange=e=>{if(this.log?.("warn",`Another tab has requested a version change for ${this.db.name}`),this.db.close(),typeof window<"u")try{this.ctx.environment.location.reload()}catch(t){this.log?.("error","Failed to reload the page",t)}};let r=new AbortController;this.globalAbortController=r,this.db.addEventListener("versionchange",this.onVersionChange),this.addDispose(()=>{this.db.removeEventListener("versionchange",this.onVersionChange)})}};var hi=class extends $e{constructor(){super(...arguments);this.add=async e=>{let t=e.file?await Ca(e.file):void 0;await this.run("files",r=>r.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:t,timestamp:e.timestamp}),{mode:"readwrite"})};this.markUploaded=async e=>{if(this.disposed)return;let t=await this.getFileRaw(e);if(!t){this.ctx.log("error","Tried to mark unknown file as uploaded",e);return}await this.run("files",r=>r.put({...t,remote:"true"}),{mode:"readwrite"})};this.get=async e=>{let t=await this.getFileRaw(e);return t?this.hydrateFileData(t):null};this.delete=e=>this.run("files",t=>t.delete(e),{mode:"readwrite"});this.markPendingDelete=async e=>{let t=await this.getFileRaw(e);if(!t)throw new Error("File is not in local database");await this.run("files",r=>r.put({...t,deletedAt:Date.now()}),{mode:"readwrite"})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"}))?.map(this.hydrateFileData)??[];this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),s=(await this.run("files",o=>o.index("remote").getAll("true"),{transaction:t})).filter(o=>!o.timestamp||!e||o.timestamp>e);await Promise.all(s.map(o=>this.run("files",a=>a.put({...o,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=e=>this.iterate("files",t=>t.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(t,r)=>{e(this.hydrateFileData(t),r)},{mode:"readwrite"});this.getAll=async e=>{let[t]=await Tn(this.db,["files"]);return t.map(this.hydrateFileData)};this.stats=async()=>({size:await Xe(this.db,"files")});this.loadFileContents=async(e,t)=>{if(e.file)return e.file;if(e.localPath)throw new Error("Local file paths are not supported in browser");if(e.url){let r=await t.environment.fetch(e.url);if(!r.ok)throw new Error(`Failed to download file ${e.url}: ${r.statusText}`);return r.blob()}throw new Error("File is missing url, file, and localPath")};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Pa(t,e.type,e.name):void 0,e};this.getFileRaw=async(e,{transaction:t}={})=>{if(this.disposed)return;let r=await this.run("files",s=>s.get(e),{mode:"readonly",transaction:t});if(r)return r}}};function Pa(n,i,e){return new File([new Blob([n],{type:i})],e??"blob",{type:i})}function Ca(n){return"__testReadBuffer"in n?Promise.resolve(n.__testReadBuffer):new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var se={IS_LOCAL__TIMESTAMP:"l_t",ROOT_OID__TIMESTAMP:"d_t",OID__TIMESTAMP:"oid_timestamp"};var fi=class extends $e{constructor(e,t){super(e,t);this.transaction=async(e,t)=>{let r=this.createTransaction(e.storeNames,{mode:e.mode,abort:e.abort});return await t(r)};this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})};this.getLocalReplica=async e=>this.run("info",t=>t.get("localReplicaInfo"),e);this.updateLocalReplica=async(e,t)=>{try{await this.run("info",r=>r.put({...e,type:"localReplicaInfo"}),{mode:"readwrite",transaction:t?.transaction})}catch(r){throw this.ctx.log("critical","Error updating local replica",e,r),r}};this.iterateDocumentBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>{let o=K(e),[a,l]=hn(e);return[s.openCursor(IDBKeyRange.only(o)),s.openCursor(IDBKeyRange.bound(a,l,!1,!1))]},t,r)};this.iterateCollectionBaselines=async(e,t,r)=>{await this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,r)};this.iterateAllBaselines=async(e,t)=>{await this.iterate("baselines",r=>r.index("timestamp").openCursor(),e,t)};this.getBaseline=(e,t)=>this.run("baselines",r=>r.get(e),t);this.setBaselines=async(e,t=Fn)=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),t)};this.deleteBaseline=async(e,t=Fn)=>{await this.run("baselines",r=>r.delete(e),t)};this.iterateDocumentOperations=(e,t,r)=>this.iterate("operations",s=>{let o=s.index(se.ROOT_OID__TIMESTAMP),a=_e(e),l=r?.to?be(e,r.to):Pe(e),p=IDBKeyRange.bound(a,l,!1,!1);return o.openCursor(p)},t,r);this.iterateEntityOperations=(e,t,r)=>this.iterate("operations",s=>{let o=_e(e),a=r?.to?be(e,r.to):Pe(e),l=IDBKeyRange.bound(o,a,!1,!1);return s.openCursor(l,r?.reverse?"prev":"next")},t,r);this.deleteEntityOperations=(e,t)=>this.iterate("operations",r=>{let s=_e(e),o=t?.to?be(e,t.to):Pe(e),a=IDBKeyRange.bound(s,o,!1,!1);return r.openCursor(a)},(r,s)=>{s.delete(r.oid_timestamp)},t);this.iterateCollectionOperations=(e,t,r)=>this.iterate("operations",s=>s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,r);this.iterateLocalOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.after?be(!0,t.after):_e(!0),o=Pe(!0);return r.index(se.IS_LOCAL__TIMESTAMP).openCursor(IDBKeyRange.bound(s,o,!!t?.after,!1),"next")},e);this.iterateAllOperations=(e,t)=>this.iterate("operations",r=>{let s=t?.from?_e(t.from):void 0,o=t?.before?Pe(t.before):_e(!0),a=s&&o?IDBKeyRange.bound(s,o,!1,!0):s?IDBKeyRange.lowerBound(s,!1):o?IDBKeyRange.upperBound(o,!0):void 0;return r.index("timestamp").openCursor(a,"next")},e,t);this.addOperations=async(e,t=Fn)=>{let r=new Set;return await this.runAll("operations",s=>e.map(o=>(r.add(K(o.oid)),s.put(this.addOperationIndexes(o)))),t),Array.from(r)};this.reset=async({clearReplica:e,transaction:t}={})=>{let r=t||this.createTransaction(["info","operations","baselines"],{mode:"readwrite"});await Promise.all([this.resetLocalReplica(r,e),this.resetBaselines(r),this.resetOperations(r)])};this.stats=async()=>{let e=await Xe(this.db,"operations"),t=await Xe(this.db,"baselines");return{operationsSize:e,baselinesSize:t}};this.resetLocalReplica=async(e,t=!1)=>{if(t)return this.run("info",r=>r.delete("localReplicaInfo"),{mode:"readwrite",transaction:e});{let r=await this.getLocalReplica({transaction:e});r&&(r.ackedLogicalTime=null,r.lastSyncedLogicalTime=null,await this.run("info",s=>s.put({...r,type:"localReplicaInfo"}),{mode:"readwrite",transaction:e}))}};this.resetBaselines=async e=>this.clear("baselines",e);this.resetOperations=async e=>this.clear("operations",e);this.addOperationIndexes=e=>({...e,[se.OID__TIMESTAMP]:be(e.oid,e.timestamp),[se.IS_LOCAL__TIMESTAMP]:be(e.isLocal,e.timestamp),[se.ROOT_OID__TIMESTAMP]:be(K(e.oid),e.timestamp)});this.addDispose(()=>(this.ctx.log("info","Closing metadata DB for",t.namespace),ve(e)))}purgeDocumentData(e,t){let r=K(e),s=t?.transaction;return this.transaction({mode:"readwrite",storeNames:["baselines","operations"]},async o=>{let a=s??o;await this.iterate("baselines",l=>{let[p,f]=hn(r);return[l.openCursor(IDBKeyRange.only(r)),l.openCursor(IDBKeyRange.bound(p,f,!1,!1))]},(l,p)=>{p.delete(l.oid)},{mode:"readwrite",transaction:a}),await this.iterate("operations",l=>{let p=l.index(se.ROOT_OID__TIMESTAMP),f=_e(r),S=Pe(r);return p.openCursor(IDBKeyRange.bound(f,S,!1,!1))},(l,p)=>{p.delete(l[se.OID__TIMESTAMP])},{mode:"readwrite",transaction:a})})}},Fn={mode:"readwrite"};var xs=[Aa,Ta,Ra,Fa,ka,Ba],Da=xs.length;function kn({indexedDB:n=window.indexedDB,namespace:i,log:e}){return new Promise((t,r)=>{let s=n.open(Rt(i),Da),o=!1;s.onupgradeneeded=async a=>{let l=s.result,p=s.transaction,f=xs.slice(a.oldVersion);for(let S of f)await S(l,p);await new Promise((S,w)=>{p.addEventListener("complete",S),p.addEventListener("error",w)}),a.oldVersion||(o=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{t({db:s.result,wasInitialized:o})}})}async function Aa(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:se.OID__TIMESTAMP}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Ta(n,i){let e=i.objectStore("operations");await new Promise((t,r)=>{let s=e.openCursor();s.onsuccess=()=>{let o=s.result;if(o){let{isLocal_timestamp:a,documentOid_timestamp:l,...p}=o.value;o.update({...p,[se.IS_LOCAL__TIMESTAMP]:a,[se.ROOT_OID__TIMESTAMP]:l}),o.continue()}else t()},s.onerror=o=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex(se.IS_LOCAL__TIMESTAMP,se.IS_LOCAL__TIMESTAMP,{unique:!1}),e.createIndex(se.ROOT_OID__TIMESTAMP,se.ROOT_OID__TIMESTAMP,{unique:!1})}async function Ra(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function Fa(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function ka(n,i){let e=i.objectStore("operations");await new Promise((r,s)=>{let o=e.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let l=fn(a.value);l.oid_timestamp!==a.primaryKey?(a.delete(),e.put(l)):a.update(l),a.continue()}else r()},o.onerror=a=>{s(o.error)}});let t=i.objectStore("baselines");await new Promise((r,s)=>{let o=t.openCursor();o.onsuccess=()=>{let a=o.result;if(a){let l=fn(a.value);l.oid!==a.primaryKey?(a.delete(),t.put(l)):a.update(l),a.continue()}else r()},o.onerror=a=>{s(o.error)}})}async function Ba(n,i){i.objectStore("files").createIndex("timestamp","timestamp")}var Ma=n=>IDBKeyRange.only(Ie(n.equals)),La=n=>{},ja=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(Ie(i)):i?e?IDBKeyRange.bound(Ie(i),Ie(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(Ie(i),!!n.gt):IDBKeyRange.upperBound(Ie(e),!!n.lt)},Na=(n,i,e)=>{let t=n.collections[i].compounds?.[e.where];M(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((l,p)=>t.of.indexOf(l)-t.of.indexOf(p));for(let l of r)if(t.of.indexOf(l)!==r.indexOf(l))throw new Error(`Compound index ${e.where} does not have ${l} at the start of its order`);let s=r.map(l=>e.match[l]);if(r.length===t.of.length)return IDBKeyRange.only(be(...s));let o=_e(...s),a=Pe(...s);return IDBKeyRange.bound(o,a)};function Va(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function Bn(n,i,e){if(e)return ei(e)?ja(e):Zt(e)?Ma(e):In(e)?La(e):ti(e)?Va(e):Na(n,i,e)}var pi=class extends $e{constructor(e,t){super(e,t);this.context=t;this.close=async()=>{await this.dispose()};this.stats=async()=>{let e=Object.keys(this.context.schema.collections),t={};return await Promise.all(e.map(async r=>{let s=await Xe(this.db,r);t[r]=s})),t};this.findOneOid=async e=>{let t=await this.run(e.collection,r=>{let s=e.index?.where?r.index(e.index.where):r,o=e.index?.order==="desc"?"prev":"next",a=Bn(this.context.schema,e.collection,e.index);return s.openCursor(a,o)},{mode:"readonly"});return t?ee(e.collection,t.primaryKey.toString()):null};this.findAllOids=async({collection:e,index:t,offset:r,limit:s})=>{let o=this.createTransaction([e],{mode:"readonly"});if(ut(o))return{result:[],hasNextPage:!1};let a=o.objectStore(e),l=t?.where?a.index(t.where):a,p=t?.order==="desc"?"prev":"next",f=Bn(this.context.schema,e,t),S=l.openCursor(f,p),w=!1;return{result:await new Promise((y,I)=>{let _=!r,E=0,P=new Set;S.onsuccess=()=>{E++;let F=S.result;if(!F){y(Array.from(P));return}r&&!_?(F.advance(r),_=!0):((!s||P.size<s)&&P.add(ee(e,F.primaryKey.toString())),s&&E>s?(w=!0,y(Array.from(P))):F.continue())},S.onerror=()=>{S.error?.name==="InvalidStateError"?(this.context.log("error","find query failed with InvalidStateError",S.error),y([])):S.error&&Ye(S.error)?y([]):I(S.error)}}),hasNextPage:w}};this.saveEntities=async(e,t)=>{let r={transaction:this.createTransaction(t.collections,{mode:"readwrite",abort:t.abort})},s=await Promise.allSettled(e.map(async a=>{let l=a.getSnapshot();try{await this.saveDocument(a.oid,l,r)}catch(p){throw this.context.log("error",`Error saving document ${a.oid} (${JSON.stringify(l)})`,p),p instanceof Error?p:new Error("Unknown error saving document")}})),o=s.filter(a=>a.status==="rejected");if(o.length){if(o.length===s.length)throw new Error("Failed to save any documents. Something must be quite wrong.");this.context.log("error","Failed to save documents:",o,". See logs above. This only affects querying these documents. Let's hope a future attempt will correct them...")}r.transaction.commit()};this.reset=async()=>{let e=Object.keys(this.context.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>this.run(r,s=>s.clear(),{transaction:t}))),this.context.entityEvents.emit("collectionsChanged",e),this.context.log("info","\u{1F4A8} Reset queryable storage")};this.saveDocument=async(e,t,{transaction:r})=>{this.context.log("debug",`Saving document indexes for querying ${e}`);let{collection:s,id:o}=ne(e);try{if(!t)await this.run(s,a=>a.delete(o),{mode:"readwrite",transaction:r}),this.context.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.context.schema.collections[s],l=mn(a,t);l["@@@snapshot"]=JSON.stringify(t),await this.run(s,p=>p.put(l),{mode:"readwrite",transaction:r}),this.context.log("debug",`Save complete for ${e}`,l)}}catch(a){throw this.context.log("error",`Error saving document ${e}`,a),a}};this.addDispose(()=>(this.context.log("info","Closing document database for",t.namespace),ve(this.db)))}};async function Ss(n,i,e,t,r){r?.("debug","Upgrading database",i,"to version",e);function s(o,a){let l=n.open(ht(i),e),p=!1;l.onupgradeneeded=f=>{let S=l.transaction;t(S,l.result,f),p=!0},l.onsuccess=async f=>{p?(await ve(l.result),o(l.result)):a(new Error("Database was not upgraded when a version change was expected"))},l.onerror=f=>{a(l.error||new Error("Unknown error"))},l.onblocked=f=>{r?.("Database upgrade blocked!")}}return new Promise(s)}async function Mn({indexedDB:n=gs,namespace:i,version:e,log:t}){if(e<=0)throw new Error("Cannot open database at version less than 1");t?.("debug","Opening database",i,"at version",e);let r=await ws(ht(i),e,n);return t?.("debug","Database opened",i,"at version",r.version),r.version!==e&&t?.("warn",`Opened database version ${r.version} but expected version ${e} for namespace ${i}`),r.addEventListener("versionchange",s=>{r.close()}),r.addEventListener("close",()=>{t?.("warn","Database closed",i)}),r}var ft=class{constructor(i=window.indexedDB){this.indexedDB=i;this.name="IdbPersistence";this.getNamespaces=async()=>{let i=await this.indexedDB.databases();return Array.from(new Set(i.map(vs).filter(e=>!!e)))};this.getNamespaceVersion=async i=>{let e=ht(i),r=(await this.indexedDB.databases()).find(s=>s.name===e);return r?r.version??0:0};this.deleteNamespace=async i=>{await Promise.all([ui(Rt(i),this.indexedDB),ui([i,"collections"].join("_"),this.indexedDB)])};this.openNamespace=async i=>new Ln(this.indexedDB,i);this.copyNamespace=async(i,e,t)=>{let r=t.cloneWithOptions({namespace:i}),s=t.cloneWithOptions({namespace:e}),{db:o}=await kn({indexedDB:this.indexedDB,log:r.log,namespace:r.namespace}),a=await Mn({indexedDB:this.indexedDB,namespace:r.namespace,version:r.schema.version,log:r.log});r.log("info",`Copying data from ${r.namespace} to ${s.namespace}`),await Rn(o,Rt(s.namespace),s,this.indexedDB),await Rn(a,ht(s.namespace),s,this.indexedDB),await ve(o),await ve(a)}}},Ln=class{constructor(i,e){this.indexedDB=i;this.namespace=e;this.openMetadata=async i=>{let{db:e}=await kn({indexedDB:this.indexedDB,log:i.log,namespace:this.namespace});return this.metadataDb=e,i.persistenceShutdownHandler.register(()=>ve(e)),new fi(e,i)};this.openDocuments=async i=>{let e=await Mn({version:i.schema.version,indexedDB:this.indexedDB,log:i.log,namespace:this.namespace});return i.persistenceShutdownHandler.register(()=>ve(e)),new pi(e,i)};this.applyMigration=async(i,e)=>{i.log("debug","Applying migration",e.newSchema.version,e),await Ss(this.indexedDB,this.namespace,e.newSchema.version,(t,r)=>{for(let s of e.addedCollections)r.createObjectStore(s,{keyPath:e.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of e.allCollections){if(!r.objectStoreNames.contains(s))throw new Error(`Expected object store for collection ${s} to exist during migration, but it did not`);let o=t.objectStore(s);for(let a of e.addedIndexes[s]||[])o.createIndex(a.name,a.name,{multiEntry:a.multiEntry});for(let a of e.removedIndexes[s]||[])o.deleteIndex(a.name)}for(let s of e.removedCollections)t.objectStore(s).clear()},i.log)}}openFiles(i){if(!this.metadataDb)throw new Error("Metadata database must be opened first. This is a bug in Verdant.");return Promise.resolve(new hi(this.metadataDb,i))}};var Be=class{constructor(i){this.log=i;this.consumed=!1;this.handlers=[];this.reset=()=>{this.consumed=!1}}register(i){this.handlers.push(i)}async shutdown(){this.consumed&&this.log?.("warn","ShutdownHandler already consumed"),this.consumed=!0,await Promise.all(this.handlers.map(i=>i())),this.handlers.length=0}get isShuttingDown(){return this.consumed}};function Os(n,i){return`@@wip-${n}-${He(i)}`}function Is({migration:n,newOids:i,ctx:e,meta:t}){return n.allCollections.reduce((r,s)=>(r[s]={put:async(o,a)=>{qe(n.newSchema.collections[s],o);let l=o[n.newSchema.collections[s].primaryKey],p=ee(s,l);return i.push(p),await e.time.withMigrationTime(n.version,()=>t.insertData({operations:e.patchCreator.createInitialize(o,p,a?.access),isLocal:!0})),o},delete:async o=>{let a=ee(s,o);await e.time.withMigrationTime(n.version,()=>t.deleteDocument(a))}},r),{})}function Ua({migration:n,context:i,documents:e,meta:t}){return n.oldCollections.reduce((r,s)=>(r[s]={get:async o=>{let a=ee(s,o);return await t.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)})},findOne:async o=>{let a=await e.findOneOid({collection:s,index:o});return a?await t.getDocumentSnapshot(a,{to:i.time.nowWithVersion(n.oldSchema.version)}):null},findAll:async o=>{let{result:a}=await e.findAllOids({collection:s,index:o});return await Promise.all(a.map(async p=>t.getDocumentSnapshot(p,{to:i.time.nowWithVersion(n.oldSchema.version)})))}},r),{})}async function _s({migration:n,context:i,ns:e,meta:t}){let r=i.cloneWithOptions({schema:n.oldSchema});if(n.oldSchema.version===0)return za({migration:n,context:r,meta:t});let s=new Array,o=await e.openDocuments(r),a=Ua({migration:n,context:r,documents:o,meta:t}),l=Is({migration:n,newOids:s,ctx:r,meta:t}),p=async w=>{await t.deleteCollection(w)},f=new Array;return{log:i.log,newOids:s,deleteCollection:p,migrate:async(w,A)=>{let y=await a[w].findAll();i.log("debug",`Migrating ${y.length} documents in ${w}`),await Promise.all(y.filter(Boolean).map(async I=>{let _=ae(I);M(!!_,`Document is missing an OID: ${JSON.stringify(I)}`);let E=await t.getDocumentAuthz(_),P=fe(I),F=await A(I);if(F){Ot(P),Ot(F),st(F);let b=qt(P,F,()=>i.time.zeroWithVersion(n.version),void 0,[],{mergeUnknownObjects:!0,defaultUndefined:!1,authz:E});b.length>0&&await t.insertData({operations:b,isLocal:!0})}}))},queries:a,mutations:l,awaitables:f,close:async()=>{await o.close()}}}function za({migration:n,context:i,meta:e}){let t=new Array,r=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=Is({migration:n,newOids:t,ctx:i,meta:e});return{log:i.log,newOids:t,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:r,mutations:s,awaitables:[],close:()=>Promise.resolve()}}async function Es({ctx:n,documents:i,migration:e,meta:t,engine:r}){let s=await $a({currentVersion:e.oldSchema.version,newVersion:e.newSchema.version,ctx:n,meta:t});for(let o of e.allCollections){let{result:a}=await i.findAllOids({collection:o});a.push(...r.newOids.filter(f=>ne(f).collection===o),...s.filter(f=>ne(f).collection===o));let p=(await Promise.all(a.map(async f=>{try{let S=await t.getDocumentSnapshot(f);return[f,S]}catch(S){return n.log("error","Could not regenerate snapshot during migration for oid",f,"this document will not be preserved",S),null}}))).filter(f=>!!f);await i.saveEntities(p.map(([f,S])=>({oid:f,getSnapshot(){return S}})),{collections:[o]})}}async function $a({currentVersion:n,newVersion:i,ctx:e,meta:t}){let r=[];return await t.iterateAllOperations(s=>{r.push(s)},{from:e.time.zeroWithVersion(n+1)}),Array.from(new Set(r.map(s=>K(s.oid))))}function Ps({currentVersion:n,targetVersion:i,migrations:e}){let t=Cs({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new U(U.Code.MigrationPathNotFound,void 0,`No migration path found from ${n} to ${i}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function Cs({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let s=Cs({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(s)return[r,...s]}return null}async function Ds({context:n,version:i,meta:e}){let t=await n.persistence.openNamespace(n.namespace,n);await Ka(n.namespace,async()=>{let r=await n.persistence.getNamespaceVersion(n.namespace);n.log("debug","Opening index database",n.namespace,"Current database version:",r,"target version:",i,n.schema.wip?"(wip)":"");let s=Ps({currentVersion:r,targetVersion:i,migrations:n.migrations});s.length>0&&(n.log("debug","Migrations to run:",s.map(o=>o.version)),await Wa({context:n,ns:t,toRun:s,meta:e}))})}async function Ka(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Wa({context:n,toRun:i,ns:e,meta:t}){n.pauseRebasing=!0;for(let r of i){n.log("info",`\u{1F680} Running migration v${r.oldSchema.version} -> v${r.newSchema.version}`);let s=n.cloneWithOptions({schema:r.oldSchema,persistenceShutdownHandler:new Be(n.log)}),o=await _s({migration:r,context:s,ns:e,meta:t});try{n.log("debug","Migrating data",s.namespace,"from version",r.oldSchema.version,"to version",r.newSchema.version),await r.migrate(o),n.log("debug","Awaiting remaining migration tasks"),await Promise.all(o.awaitables)}catch(l){throw n.log("critical",`Migration failed (${r.oldSchema.version} -> ${r.newSchema.version})`,l),l instanceof Error?l:new Error("Unknown error during migration")}await o.close(),s.log("debug","Upgrading database",s.namespace,"from version",s.schema.version,"to version",r.newSchema.version),await e.applyMigration(s,r),s.schema=r.newSchema;let a=await e.openDocuments(s);await Es({ctx:s,migration:r,engine:o,documents:a,meta:t}),await a.close(),s.log("debug",`Migration of ${s.namespace} complete.`),s.log("info",`
8
8
  \u2B06\uFE0F v${r.newSchema.version} Migration complete. Here's the rundown:
9
9
  - Added collections: ${r.addedCollections.join(", ")}
10
10
  - Removed collections: ${r.removedCollections.join(", ")}
11
11
  - Changed collections: ${r.changedCollections.join(", ")}
12
12
  - New indexes: ${Object.keys(r.addedIndexes).map(l=>r.addedIndexes[l].map(p=>`${l}.${p.name}`)).flatMap(l=>l).join(", ")}
13
13
  - Removed indexes: ${Object.keys(r.removedIndexes).map(l=>r.removedIndexes[l].map(p=>`${l}.${p.name}`)).flatMap(l=>l).join(", ")}
14
- `)}i.pauseRebasing=!1}var gi=class{constructor(n,e){this.db=n;this.context=e;this.onServerReset=n=>this.db.resetSyncedStatusSince(n);this.add=async(n,e)=>{if(n.url&&!(n.localPath||n.file)&&e?.cloneRemote){this.context.log("debug","Cloning remote file added to a new entity. Downloading remote file...",n.id);let t=await this.loadFileContents(n,0,3);n.file=new File([t],n.name,{type:n.type}),delete n.url,this.context.log("debug","Downloaded remote file",n.id,n.name,". Cleared its remote URL.")}else!n.url&&!n.file&&!n.localPath&&this.context.log("warn","File added without a file or URL. This file will not be available for use.",n.id);return n.remote=!1,this.context.log("debug","Adding file to persistence",n),await this.db.add(n),this.context.internalEvents.emit("fileAdded",n),this.context.globalEvents.emit("fileSaved",n),this.context.log("debug","File added",n.id,n.name,n.type,n.file?"with binary file":n.url?"with url":n.localPath?"with local path":"with no data"),n};this.update=async n=>{await this.db.add(n),this.context.globalEvents.emit("fileSaved",n),this.context.log("debug","File updated",n.id,n.name)};this.onUploaded=this.db.markUploaded.bind(this.db);this.get=this.db.get.bind(this.db);this.getAll=this.db.getAll.bind(this.db);this.listUnsynced=this.db.listUnsynced.bind(this.db);this.iterateOverPendingDelete=this.db.iterateOverPendingDelete.bind(this.db);this.stats=this.db.stats.bind(this.db);this.getFileExportName=(n,e)=>`${e}___${n}`;this.export=async(n=!0)=>{let e=await this.getAll();if(n)for(let s of e)if(!s.file&&(s.url||s.localPath))try{let o=await this.loadFileContents(s);s.file=o}catch(o){this.context.log("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,o)}else s.file||this.context.log("warn",`File ${s.id} has no file or URL. It will be missing in the export.`,s);let t=[],r=[];for(let s of e){let o=s.file;if(delete s.file,t.push(s),o){let a=new File([o],this.getFileExportName(s.name,s.id),{type:s.type});r.push(a)}else this.context.log("warn",`File ${s.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:t,files:r}};this.import=async({fileData:n,files:e})=>{let t=new Map(e.map(s=>{let{id:o}=this.parseFileExportname(s.name);return[o,s]})),r=n.map(s=>{let o=t.get(s.id);return o?{...s,file:o}:(this.context.log("warn",`File ${s.id} was not found in import`),s)});await Promise.all(r.map(s=>this.add(s)))};this.parseFileExportname=n=>{let[e,t]=n.split("___");return{id:e,originalFileName:t}};this.loadFileContents=async(n,e=0,t=0)=>{try{return await this.db.loadFileContents(n,this.context)}catch(r){if(e<t)return new Promise((s,o)=>{setTimeout(()=>{this.loadFileContents(n,e+1,t).then(s,o)},1e3)});throw this.context.log("error",`Failed to download file after ${t} retries`,r),new Error(`Failed to download file after ${t} retries`,{cause:r})}};this.cleanupDeletedFiles=async()=>{let n=0,e=0,t=[];await this.iterateOverPendingDelete(r=>{this.config.canCleanupDeletedFile(r)?(n++,t.push(r.id)):e++});for(let r of t)await this.db.delete(r);this.context.log("info",`Cleaned up ${n} files, skipped ${e} files`)};this.onFileRefsDeleted=async n=>{await Promise.all(n.map(async e=>{try{await this.db.markPendingDelete(e.id)}catch(t){this.context.log("error","Failed to mark file for deletion",t)}})),this.context.log("info",`Marked ${n.length} files as pending delete`)};e.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var Ts=Me(Je(),1);var yi=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.createOperation=async n=>{let e=await this.meta.getLocalReplica();return this.ctx.log("debug","Creating operation message",n.operations.length),{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:n.operations.map(Kt)}};this.createSyncStep1=async n=>{let e=await this.meta.getLocalReplica(),t=n===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;return this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]},async o=>{t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(l=>{r.push(Kt(l)),s.add(K(l.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(l=>{r.push(Kt(l)),s.add(K(l.oid))},{transaction:o}));let a=[];return t||await this.db.iterateAllBaselines(l=>{a.push(l)},{transaction:o}),r.length>0&&this.ctx.log("debug",`Syncing ${r.length} operations since ${t}`),{type:"sync",schemaVersion:this.ctx.schema.version,timestamp:this.ctx.time.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:t}})};this.createPresenceUpdate=async n=>{let e=await this.meta.getLocalReplica();return{type:"presence-update",presence:n.presence,replicaId:e.id,internal:n.internal}};this.createHeartbeat=async()=>({type:"heartbeat"});this.createAck=async n=>{let e=await this.meta.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:n}};this.createDisconnecting=async n=>({type:"disconnecting",replicaId:(await this.meta.getLocalReplica()).id,reason:n})}};var bi=class{constructor(n,e,t){this.db=n;this.meta=e;this.ctx=t;this.tryAutonomousRebase=async()=>{(await this.meta.getLocalReplica()).lastSyncedLogicalTime||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(this.ctx.log("debug","Running autonomous library rebase"),await this.runRebase(this.ctx.time.now))};this.runRebase=async n=>{this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(await this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async e=>{let t=new Set,r,s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),r=a.timestamp,s++},{before:n,transaction:e}),!t.size||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let o=[];for(let a of t)o.push(await this.rebase(a,r||n,e))}),this.ctx.globalEvents.emit("rebase"))};this.scheduleRebase=async n=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,n),this.ctx.log("debug","Scheduled rebase up to global ack",n)};this.rebaseTimeout=null;this.rebase=async(n,e,t)=>{if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let r=await this.db.getBaseline(n,{transaction:t}),s=r?.snapshot||void 0,o=0,a=r?.authz,l=[];if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;await this.db.iterateEntityOperations(n,f=>{(!r||f.timestamp>r.timestamp)&&(s=je(s,f.data,l),f.data.op==="initialize"&&(a=f.authz)),o++},{to:e,transaction:t}),s&&z(s,n);let p={oid:n,snapshot:s,timestamp:e,authz:a};if(!(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown))return this.ctx.closeLock=(async()=>{if(p.snapshot?await this.db.setBaselines([p],{transaction:t}):await this.db.deleteBaseline(n,{transaction:t}),await this.db.deleteEntityOperations(n,{to:e,transaction:t}),this.ctx.log("debug","rebased",n,"up to",e,":",s,"and deleted",o,"operations"),l.length){let f=l.filter(me);f.length&&this.ctx.internalEvents.emit("filesDeleted",f)}})(),p}}};var wi=class{constructor(n,e){this.db=n;this.ctx=e;this.insertOperations=async(n,e)=>{this.ctx.log("debug",`Inserting ${n.length} operations`,n);let t=await this.db.addOperations(n,e);for(let r of n)this.ctx.globalEvents.emit("operation",r);return!this.ctx.config.persistence?.disableRebasing&&!this.ctx.pauseRebasing&&this.rebaser.tryAutonomousRebase(),t};this.insertLocalOperations=async(n,e)=>{if(n.length===0)return;for(let r of n)r.isLocal=!0;await this.insertOperations(n,e),this.ctx.log("debug",`Inserted ${n.length} local operations; sending sync message`);let t=await this.messageCreator.createOperation({operations:n});this.ctx.internalEvents.emit("outgoingSyncMessage",t)};this.insertRemoteOperations=async(n,e)=>{if(n.length===0)return[];for(let t of n)t.isLocal=!1;await this.insertOperations(n,e),this.ack(n[n.length-1].timestamp)};this.insertRemoteBaselines=async(n,e)=>{if(n.length===0)return[];this.ctx.log("debug",`Inserting ${n.length} remote baselines`),await this.db.setBaselines(n,e);let t=new Set;return n.forEach(r=>{t.add(K(r.oid))}),Array.from(t)};this.deleteDocument=async n=>{let e=new Set,t=K(n);return M(t===n,"Must be root document OID"),e.add(t),this.db.transaction({storeNames:["baselines","operations"]},async r=>{await Promise.all([this.db.iterateDocumentBaselines(t,a=>{e.add(a.oid)},{transaction:r}),this.db.iterateDocumentOperations(t,a=>{e.add(a.oid)},{transaction:r})]);let s=await this.getDocumentAuthz(t),o=new Array;for(let a of e)o.push({oid:a,timestamp:this.ctx.time.now,data:{op:"delete"},authz:s});return this.insertLocalOperations(o,{transaction:r})})};this.deleteCollection=async n=>{let e=new Set;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await Promise.all([this.db.iterateCollectionBaselines(n,s=>{e.add(s.oid)},{transaction:t}),this.db.iterateCollectionOperations(n,s=>{e.add(s.oid)},{transaction:t})]);let r=new Array;for(let s of e)r.push({oid:s,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(r,{transaction:t})})};this.getDocumentSnapshot=async(n,e={})=>{let t=K(n);return M(t===n,"Must be root document OID"),this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async r=>{let s=[];await this.db.iterateDocumentBaselines(t,l=>{s.push(l)},{transaction:r});let o=new Map;for(let l of s)l.snapshot&&z(l.snapshot,l.oid),o.set(l.oid,l.snapshot);await this.db.iterateDocumentOperations(t,l=>{let p=o.get(l.oid)||void 0,f=je(p,l.data);f&&z(f,l.oid),o.set(l.oid,f)},{transaction:r,to:e.to||this.ctx.time.now});let a=o.get(t);return a&&zt(a,o),a})};this.getDocumentData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort},async t=>{let r=[],s={};return await Promise.all([this.db.iterateDocumentBaselines(n,o=>{r.push(o)},{transaction:t}),this.db.iterateDocumentOperations(n,o=>{s[o.oid]??=[],s[o.oid].push(o)},{transaction:t})]),{baselines:r,operations:s}});this.getDocumentAuthz=async n=>{let e;return await this.db.iterateEntityOperations(n,r=>{if(r.data.op==="initialize")return e=r.authz,!0},{reverse:!0}),e||(await this.db.getBaseline(n))?.authz};this.insertData=async(n,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort,mode:"readwrite"},async t=>{if(this.ctx.log("debug","Begin insert data transaction"),n.baselines&&await this.insertRemoteBaselines(n.baselines,{transaction:t}),this.ctx.log("debug","Inserted baselines (if any)"),e?.abort?.aborted)throw new Error("Aborted");n.operations&&(n.isLocal?(this.ctx.log("debug","Inserting local operations"),await this.insertLocalOperations(n.operations,{transaction:t})):(this.ctx.log("debug","Inserting remote operations"),await this.insertRemoteOperations(n.operations,{transaction:t}))),this.ctx.log("debug","End insert data transaction")});this.updateLastSynced=async n=>{if(!this.ctx.closing)return this.updateLocalReplica({lastSyncedLogicalTime:n})};this.setGlobalAck=async n=>{this.ctx.closing||(await this.db.setGlobalAck(n),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(n))};this._cachedLocalReplica=null;this._creatingLocalReplica=void 0;this.getLocalReplica=async n=>{if(this._cachedLocalReplica)return this._cachedLocalReplica;let e=await this.db.getLocalReplica(n);return e?(this.ctx.log("debug","Read local replica",e),this._cachedLocalReplica=e,e):this._creatingLocalReplica?this._creatingLocalReplica:(this._creatingLocalReplica=(async()=>{let r={id:(0,Ts.default)(),userId:null,ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.db.updateLocalReplica(r),this._cachedLocalReplica=r,r})(),this._creatingLocalReplica)};this.updateLocalReplica=async(n,e)=>{let t=await this.getLocalReplica(e);M(!!t,"Local replica must exist"),Object.assign(t,n),this._cachedLocalReplica=t,await this.db.updateLocalReplica(t,e)};this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=async()=>{this.ctx.closing||await this.db.reset()};this.stats=this.db.stats;this.export=async()=>{let n=new Array,e=new Array;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await this.iterateAllOperations(s=>{e.push(s)},{transaction:t}),await this.iterateAllBaselines(s=>{n.push(s)},{transaction:t});let r=await this.getLocalReplica();return{operations:e,baselines:n,localReplica:r,schemaVersion:this.ctx.schema.version}})};this.resetFrom=async n=>{this._cachedLocalReplica=null,await this.db.reset({clearReplica:!0}),n.localReplica&&await this.updateLocalReplica({ackedLogicalTime:n.localReplica.ackedLogicalTime,lastSyncedLogicalTime:n.localReplica.lastSyncedLogicalTime}),this.ctx.log("debug","Resetting metadata from export",n),await this.insertData({operations:n.operations,baselines:n.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let n=await this.db.getAckInfo();n.globalAckTimestamp&&await this.rebaser.scheduleRebase(n.globalAckTimestamp)};this.ack=async n=>{let e=await this.getLocalReplica();n>this.ctx.time.now||(this.ctx.internalEvents.emit("outgoingSyncMessage",{type:"ack",replicaId:e.id,timestamp:n}),!this.ctx.closing&&(!e.ackedLogicalTime||n>e.ackedLogicalTime)&&this.updateLocalReplica({ackedLogicalTime:n}))};this.__unstable__purgeRemovedCollections=async()=>{let n=this.ctx.schema,e=new Set(Object.keys(n.collections)),t=new Set;await this.db.iterateAllBaselines(r=>{let{collection:s}=ne(r.oid);e.has(s)||(this.ctx.log("debug",`Deleting baseline for removed collection ${s}`,r.oid),t.add(r.oid))}),await this.db.iterateAllOperations(r=>{let{collection:s}=ne(r.oid);e.has(s)||(this.ctx.log("debug",`Deleting operation for removed collection ${s}`,r.oid),t.add(r.oid))});for(let r of t)await this.db.purgeDocumentData(r);this.ctx.log("debug",`Purged ${t.size} document metadata groups for removed collections`)};this.rebaser=new bi(n,this,e),this.messageCreator=new yi(n,this,e)}};var vi=class{constructor(n,e){this.db=n;this.ctx=e;this.reset=this.db.reset.bind(this.db);this.close=this.db.close.bind(this.db);this.saveEntities=async(n,e)=>{if(n.length===0)return;let t=new Set(Object.keys(this.ctx.schema.collections)),r=[],s=n.filter(o=>{let{collection:a}=ne(o.oid);return t.has(a)?(r.includes(a)||r.push(a),!0):(this.ctx.log("warn",`Entity ${o.oid} is in a collection that no longer exists in the schema. It will not be saved.`),!1)});if(r.length!==0){this.ctx.log("debug","Saving",s.length,"entities"),await this.db.saveEntities(s,{abort:e?.abort,collections:r}),this.ctx.log("debug","Saved",s.length,"entities"),this.ctx.entityEvents.emit("collectionsChanged",r);for(let o of n)this.ctx.entityEvents.emit("documentChanged",o.oid)}};this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db)}};async function jn(i){let n=i.schema;if(i.schema.wip&&(i.namespace=Is(i.originalNamespace,i.schema),i.log("info","\u{1F528}","Switched to WIP namespace",i.namespace),!(await i.persistence.getNamespaces()).includes(i.namespace))){let a=await i.persistence.getNamespaceVersion(i.originalNamespace);if(a===0)i.log("debug","No existing data to copy to WIP namespace");else{let l=i.oldSchemas?.find(p=>p.version===a);if(!l)throw new U(U.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${i.schema.version}, but the current local data is version ${a} and a historical schema for that version is not available.`);i.log("info",`Copying data from ${i.originalNamespace} to ${i.namespace}`),await i.persistence.copyNamespace(i.originalNamespace,i.namespace,i.cloneWithOptions({schema:l}))}}let e=await i.persistence.openNamespace(i.namespace,i);i.log("info","Opening persistence metadata",i.namespace);let t=new wi(await e.openMetadata(i),i);i.log("info","Opening persistence files",i.namespace);let r=new gi(await e.openFiles(i),i);if(i.log("info","Migrating document database"),await As({context:i,version:i.schema.version,meta:t}),i.log("info","Opening persistence documents"),i.schema.version<=0)throw i.schema!==n?(i.log("critical","Schema at initialization does not match original schema. This is likely a bug in Verdant!"),new U(U.Code.ConfigurationError,void 0,"Schema at initialization does not match original schema. This is likely a bug in Verdant!")):new U(U.Code.ConfigurationError,void 0,`Schema version must be greater than 0. Found version ${i.schema.version} with collections [${Object.keys(i.schema.collections).join(", ")}]
15
- ${JSON.stringify(i.schema)}`);let s=new vi(await e.openDocuments(i),i);if(!i.schema.wip){let o=await i.persistence.getNamespaces();for(let a of o)a.startsWith("@@wip_")&&(i.log("debug","Cleaning up old WIP namespace",a),await i.persistence.deleteNamespace(a,i))}return{meta:t,files:r,documents:s}}async function Rs(i,n){i.log("info","Importing data from export");let e=i.oldSchemas?.find(l=>l.version===n.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${n.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=i.cloneWithOptions({schema:e,namespace:t,disableRebasing:!0,persistenceShutdownHandler:new Be(i.log)});await r.reinitialize();let s=await r.meta;await s.resetFrom(n.data);let o=new Set;for(let l of n.data.baselines)o.add(K(l.oid));for(let l of n.data.operations)o.add(K(l.oid));let a=await Promise.all(Array.from(o).map(async l=>{let p=await s.getDocumentSnapshot(l);return{oid:l,getSnapshot:()=>p}}));if(await(await r.documents).saveEntities(a),await(await r.files).import(n),i.log("debug","Imported data into temporary namespace",t),await r.persistenceShutdownHandler.shutdown(),e.version!==i.schema.version){let l=r.cloneWithOptions({persistenceShutdownHandler:new Be(i.log),schema:i.schema,oldSchemas:i.oldSchemas});await l.reinitialize(),i.log("debug","Upgraded imported data to current schema"),await l.persistenceShutdownHandler.shutdown(),i.log("debug","Shut down upgraded databases")}if(await i.persistenceShutdownHandler.shutdown(),await i.persistence.copyNamespace(t,i.namespace,i),i.log("debug","Copied imported data to primary namespace"),await i.reinitialize(),i.log("debug","Reinitialized primary persistence layer"),n.data.schemaVersion===i.schema.version){let l=await(await i.meta).stats();if(l.operationsSize.count!==n.data.operations.length)throw i.log("critical","Imported operations count mismatch","expected",n.data.operations.length,"actual",l.operationsSize.count),new U(U.Code.ImportFailed,void 0,"Imported operations count mismatch");if(l.baselinesSize.count!==n.data.baselines.length)throw i.log("critical","Imported documents count mismatch","expected",n.data.baselines.length,"actual",l.baselinesSize.count),new U(U.Code.ImportFailed,void 0,"Imported documents count mismatch")}else i.log("debug","Skipping integrity check due to schema version mismatch (not an error)",{exportedVersion:n.data.schemaVersion,currentVersion:i.schema.version});i.log("debug","Data copied to primary namespace"),await i.persistence.deleteNamespace(t,i),i.log("debug","Deleted temporary namespace"),i.internalEvents.emit("persistenceReset"),i.log("info","Data imported successfully"),i.persistenceShutdownHandler.reset()}var xi=class{constructor(n,e){this.base=n;this.version=e;this.withMigrationTime=async(n,e)=>{this.overrideNow=()=>this.base.zero(n),e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=n=>this.base.now(n);this.zeroWithVersion=n=>this.base.zero(n)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Qa={WebSocket:typeof WebSocket<"u"?WebSocket:void 0,fetch:typeof window<"u"?window.fetch.bind(window):fetch,indexedDB:typeof indexedDB<"u"?indexedDB:void 0,location:typeof window<"u"?window.location:void 0,history:typeof window<"u"?window.history:void 0},Si=class i{constructor(n,e){this.init=n;this.weakRef=n=>this.init.EXPERIMENTAL_weakRefs?new WeakRef(n):new di(n);this.closing=!1;this.pauseRebasing=!1;this.getClient=()=>{throw new U(U.Code.Unexpected,void 0,"Client not yet initialized. This is a Verdant bug, please report it.")};this.reinitialize=async()=>{this.initializedPromise=jn(this),await this.initializedPromise};if(typeof window>"u"&&!this.init.environment)throw new Error("A Verdant client was initialized in an environment without a global Window or `environment` configuration. 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 the environment to the Client options.");this.namespace=this.init.namespace,this.originalNamespace=this.init.namespace,this.time=new xi(new ri,this.init.schema.version),this.log=this.init.log===!1?ui:this.init.log||An("\u{1F33F}"),this.migrations=n.migrations,this.undoHistory=n.undoHistory||new lt,this.entityEvents=new W,this.internalEvents=new W,this.globalEvents=new W,this.schema=n.schema,this.oldSchemas=n.oldSchemas,this.patchCreator=new Ve(()=>this.time.now),this.persistenceShutdownHandler=n.persistenceShutdownHandler||new Be(this.log),this.config={files:n.files,sync:n.sync,persistence:{disableRebasing:n.disableRebasing,rebaseTimeout:n.rebaseTimeout},queries:n.queries},this.environment={...Qa,...n.environment},this.persistence=n.persistence||new ft(this.environment.indexedDB),this.initializedPromise=e||jn(this),this.initializedPromise.then(()=>{this.log("info","Persistence initialized")})}get meta(){return this.initializedPromise.then(n=>n.meta)}get documents(){return this.initializedPromise.then(n=>n.documents)}get files(){return this.initializedPromise.then(n=>n.files)}get waitForInitialization(){return this.initializedPromise.then(()=>{})}cloneWithOptions(n){return new i({...this.init,...n},this.initializedPromise)}};var Oi=class{constructor(n,e){this.schema=n;this.entities=e;this.getOid=(n,e)=>{let t=this.schema.collections[n].primaryKey,r=e[t];return M(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),ee(n,r)};this.addDefaults=(n,e)=>{let t=this.schema.collections[n];return qe(t,e)};this.validate=(n,e)=>{let t=this.schema.collections[n];return cs(t.fields,e)};this.create=async(n,e,t={})=>{let r=t,s=this.addDefaults(n,e),o=this.validate(n,s),a=this.getOid(n,o);if(t.access){let l=this.schema.collections[n];t.access!=="shared"&&e[l.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(o,a,r)};this.delete=async(n,e,t={})=>{let r=ee(n,e);return this.entities.delete(r,t)};this.deleteAll=async(n,e={})=>this.entities.deleteAll(n.map(([t,r])=>ee(t,r)),e);this.deleteAllFromCollection=async(n,e,t={})=>this.entities.deleteAll(e.map(r=>ee(n,r)),t);this.clone=async(n,e,t={})=>{if(!qt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[n];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${n}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[s.primaryKey]=t.primaryKey}e.access&&!t.access&&(t.access=e.access);let o=t.update?t.update(r):r;return this.create(n,o,t)}}};var Mi=Me(fo(),1);var Zn=Me(Je(),1);function lc(i){return{id:(0,Zn.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function mt(i,n){if(typeof window<"u"&&rt(i)){let e=lc(i);return n(e),St(e.id)}if(Ut(i)){let e={...i,id:(0,Zn.default)()};return n(e),St(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=mt(i[e],n);return i}if(typeof i=="object"){for(let e in i)i[e]=mt(i[e],n);return i}return i}var gt=Symbol("entity-file-update"),Ri=Symbol("entity-file-mark-failed"),er=Symbol("child-file-changed"),dc,uc,xe=class extends W{constructor(e,{downloadRemote:t=!1,ctx:r,parent:s}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this._uploaded=!1;this.unsubscribes=[];this[dc]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&"revokeObjectURL"in URL&&URL.revokeObjectURL(this._objectUrl),this.ctx.log("debug","Creating object URL for file",this.id),this._objectUrl=URL.createObjectURL(e.file)),this.emitChange()};this[uc]=e=>{this._failed=!0,this._failedReason=e,this._loading=!1,this.emitChange()};this.onUploaded=e=>{this._fileData??=e,this._uploaded=!0,this.ctx.log("debug","File marked uploaded",this.id,this._fileData),this.emitChange()};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this.ctx=r,this.parent=s,this._downloadRemote=t,this.unsubscribes.push(this.ctx.internalEvents.subscribe(`fileUploaded:${e}`,this.onUploaded))}static{dc=gt,uc=Ri}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._uploaded||this._fileData?.remote||!1}get error(){return this._failedReason||null}emitChange(){this.parent[er](this),this.emit("change")}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._fileData?.url??this._objectUrl??void 0,name:this.name??"unknown-file",remote:this._fileData?.remote??!1,type:this.type??"",file:this._fileData?.file}}};var Fi=class{constructor({initial:n,ctx:e}){this.cache=new Map;this.get=n=>{let e=this.getCached(n.oid);if(e)return e;let t=new le(n);return this.cache.set(n.oid,this.ctx.weakRef(t)),t};this.has=n=>this.cache.has(n);this.getCached=n=>{if(this.cache.has(n)){let t=this.cache.get(n)?.deref();if(t)return t;this.cache.delete(n)}return null};if(this.ctx=e,n)for(let t of n)this.cache.set(t.oid,e.weakRef(t))}};function po(i,n,e){let t={previousValue:i.get(n),isLocal:!1};function r(s){if(i.deleted)return;let o=i.get(n);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return i.subscribe("change",r.bind(t))}var mo=Symbol("private entity context key"),fc,le=class i extends W{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:l,files:p,storeEvents:f,deleteSelf:S,fieldPath:w}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this._deleting=!1;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof i){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=ze(this.schema,e);return M(t,`No schema for key ${e}`),t};this.validate=$r(()=>(this.validationError=ke({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,expectRefs:!0})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(s=>s instanceof i||s instanceof xe?e(s):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof i||a instanceof xe?s[o]=e(a):s[o]=a,s),{});return z(r,this.oid),r}};this.rawViewWithMappedChildren=e=>{let t=this.rawView;if(!t)return null;if(Array.isArray(t)){let r=t.map((s,o)=>$(s)?e(this.getChild(o,s.id)):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>($(a)?s[o]=e(this.getChild(o,a.id)):s[o]=a,s),{});return z(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.getUnprunedSnapshot=()=>this.rawViewWithMappedChildren(e=>e instanceof xe?e.getSnapshot():e.getUnprunedSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid,e),this.deepInvalid&&(this.ctx.log("warn","Changes are being applied to a pruned entity. This means that the pruned version is being treated as the new baseline and any pruned invalid data is lost.",this.oid),this.canonizePrunedVersion()),this.applyPendingOperations(e)};this.applyPendingOperations=e=>{if(this.access)for(let r of e)r.authz=this.access,r.data.op==="initialize"&&(this._deleting=!1);let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.getPruneDiff=()=>{let e=this.getSnapshot(),t=this.getUnprunedSnapshot();return this.patchCreator.createDiff(t,e,{authz:this.access,merge:!1})};this.canonizePrunedVersion=()=>{this.applyPendingOperations(this.getPruneDiff())};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)this.change(r)};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 t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.invalidate=e=>{if(e.oid===this.oid)this.invalidateCachedView();else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof i&&t.invalidate(e)}};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof i&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange?this.ctx.log("debug","Entity already deleted, not emitting delete or change events",this.oid):(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{if(this.deleted){this.ctx.log("debug","Entity deleted, not emitting change",this.oid);return}this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{if(this.deleted){this.ctx.log("debug","Entity deleted, not emitting deep change",this.oid);return}this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this[fc]=e=>{this.deepChange(this,{isLocal:!1,oid:this.oid})};this.getChild=(e,t)=>{let r=ze(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>po(this,e,r);this.get=e=>{tr(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],s=ze(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if($(r))if(me(r)){if(s.type!=="file"){if(ge(s))return null;if(Fe(s))return Ce(s);throw new Error(`Expected file schema for key ${String(e)}, got ${s.type}`)}return this.files.get(r.id,{downloadRemote:!!s.downloadRemote,ctx:this.ctx,parent:this})}else{if(s.type==="file"){if(console.error(`Expected file ref for key ${String(e)}, got ${r}`),ge(s))return null;if(Fe(s))return Ce(s);throw new Error(`No valid value for key ${String(e)} in ${JSON.stringify(this.schema)}`)}let o=this.getChild(e,r.id);if(o.deepInvalid){if(s.type==="array"||s.type==="map")return o;if(ge(s))return null;if(Fe(s)){let a=o.getUnprunedSnapshot(),l=this.patchCreator.createDiff(a,Ce(s),{merge:!1,mergeUnknownObjects:!0,authz:this.access});return this.processPrunedChild(e,o,l)}}return o}else{if(this.schema.type==="map"&&r===void 0)return;if(ke({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0}))if(Fe(s)){if(as(s))return Ce(s);let o=Ce(s),a=Ie(this.oid),l=this.patchCreator.createInitialize(o,a,this.access);l.push(...this.patchCreator.createSet(this.oid,e,ie(a),this.access));let p=this.getChild(e,a);return this.processPrunedChild(e,p,l)}else return;return r}};this.processPrunedChild=(e,t,r)=>{this.ctx.log("warn","Replacing invalid child object field with ephemeral, valid data",this.oid,e);let s=this.metadataFamily.addEphemeralData(r);for(let o of s)this.invalidate(o);return t};this.getOrSet=(e,t)=>{tr(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);rt(e)||(e=fe(e,!1));let r=ze(this.schema,t);if(r){Ge(e,r);let s=ke({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return mt(e,s=>this.files.add(s,this))};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 t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof i)return ie(e.oid);if(e instanceof xe)return St(e.id);if(typeof e=="object"){let t=G(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ie(t)}else return e};this.set=(e,t,r)=>{tr(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)hc(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="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:t=!0,replaceSubObjects:r=!1,preserveUndefined:s=!1,dangerouslyDisableMerge:o=!1}={})=>{if(!t&&!o&&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 a={};z(a,this.oid);for(let[l,p]of Object.entries(e)){if(this.readonlyKeys.includes(l))throw new Error(`Cannot set readonly key ${l.toString()}`);if(p===void 0&&!s)continue;let f=ze(this.schema,l);f&&Ge(p,f),a[l]=this.processInputValue(p,l)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),a,{mergeUnknownObjects:!r,merge:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if($(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let s=this.view.indexOf(e);if(s===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(s,t)}};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 t=this.getItemRefValue(e);return $(t)?this.view.some(r=>{if($(r))return Te(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);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.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};this.__markDeleting__=()=>{this._deleting=!0};M(!!e,"oid is required"),this.oid=e,this.readonlyKeys=l||[],this.ctx=o,this.files=p,this.schema=t,this.fieldPath=w||[],this.entityFamily=r||new Fi({initial:[this],ctx:o}),this.metadataFamily=a,this.storeEvents=f,this.parent=s,this._deleteSelf=S,this.parent||(f.add.attach(this.onAdd),f.replace.attach(this.onReplace),f.resetAll.attach(this.onResetAll))}get[mo](){return this.ctx}get metadata(){return this.metadataFamily.get(this.oid)}get patchCreator(){return this.ctx.patchCreator}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&&!ge(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!N(e))return Fe(this.schema)?Ce(this.schema):null;let r=this.isList?[]:{};if(z(r,this.oid),Array.isArray(e)){let s=ze(this.schema,0);if(!s)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let a=this.get(o);this.childIsNull(a)&&!ge(s)?this._deleting||this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):r.push(a)}}else if(N(e)){let s=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of s){let a=ze(this.schema,o);if(!a){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?r={}:r=null;break}let l=this.get(o);if(this.childIsNull(l)&&!ge(a)){if(this._deleting||this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){r=null;break}}else ge(a)&&l===void 0?r[o]=null:r[o]=l}}return this.cachedView=r,r}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get deepInvalid(){if(this.invalid)return!0;if(Array.isArray(this.rawView)){for(let e=0;e<this.rawView.length;e++)if(oe(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}else if(N(this.rawView)){for(let e in this.rawView)if(oe(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}return!1}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(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof i){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[(fc=er,Symbol.iterator)](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function tr(i){if(typeof i=="symbol")throw new Error("Symbol keys aren't supported")}function hc(i){if(typeof i!="number")throw new Error("Only number keys are supported in list entities")}function go(i){return i[mo].getClient()}var ir=class{constructor({oid:n,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.ephemeralOperations=[];this.pendingOperations=[];this.computeView=(n=!1)=>{let e=fe(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,s=this.applyOperations(e,!e,this.confirmedOperations,t,t);s.futureSeen&&this.ctx.globalEvents.emit("futureSeen",s.futureSeen),s.authz&&(r=s.authz);let o=!this.ephemeralOperations||n?s:this.applyOperations(s.view,s.deleted,this.ephemeralOperations,s.latestTimestamp,null),a=n?s:this.applyOperations(o.view,o.deleted,this.pendingOperations,o.latestTimestamp,null);a.authz&&(r=a.authz),a.view&&z(a.view,this.oid);let l=!!s.latestTimestamp&&Cn(s.latestTimestamp,this.ctx.time.now)<0,p=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;p&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let f=a.latestTimestamp??s.latestTimestamp??t,S=f?Dn(f):0;return!a.view&&!a.deleted&&!p&&this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`),{view:a.view??void 0,deleted:a.deleted,empty:p,fromOlderVersion:l,updatedAt:S,latestTimestamp:f,authz:r}};this.addBaseline=n=>{if(!(this.baseline&&this.baseline.timestamp>=n.timestamp))for(this.baseline=n;this.confirmedOperations[0]?.timestamp<n.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=n=>{let e=0;for(let t of n){let r=this.confirmedOperations.findIndex(o=>o.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let s=this.pendingOperations.length;this.discardPendingOperation(t),e-=s-this.pendingOperations.length}return e};this.addPendingOperation=n=>{this.pendingOperations.push(n)};this.addEphemeralOperation=n=>{this.ephemeralOperations||(this.ephemeralOperations=[]),this.ephemeralOperations.push(n)};this.clearEphemeralOperations=()=>{let n=this.ephemeralOperations;return this.ephemeralOperations=[],n};this.discardPendingOperation=n=>{let e=this.pendingOperations.findIndex(t=>t.timestamp===n.timestamp);e!==-1&&this.pendingOperations.splice(e,1)};this.applyOperations=(n,e,t,r,s)=>{let o,a,l=this.ctx.time.now;for(let p of t)if(!(s&&p.timestamp<=s)){if(Cn(p.timestamp,l)>0){o=p.timestamp;continue}if(p.data.op==="delete")e=!0;else try{n=je(n,p.data),p.data.op==="initialize"&&(e=!1,p.authz&&(a=p.authz))}catch(f){throw this.ctx.log("critical",`Failed to apply operation to entity ${this.oid}: ${JSON.stringify(p)}`,f),f}(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:n,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};M(n,"oid is required"),this.ctx=e,this.oid=n,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},ki=class{constructor({ctx:n,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=n=>(M(n,"oid is required"),this.entities.has(n)||this.entities.set(n,new ir({oid:n,ctx:this.ctx})),this.entities.get(n));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:n=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of n){if(!Ne(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:t}}for(let[s,o]of Object.entries(e)){if(!Ne(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o)!==0&&(r[s]??={oid:s,isLocal:t})}return Object.values(r)};this.addPendingData=n=>{this.flushAllEphemeral();let e={};for(let t of n)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(n),Object.values(e)};this.ephemeralMemo=new Array;this.flushAllEphemeral=()=>{for(let n of this.entities.values()){let e=n.clearEphemeralOperations();e&&this.ephemeralMemo.push(...e)}if(this.ephemeralMemo.length){let n=this.ephemeralMemo.slice();this.ephemeralMemo.length=0,this.addPendingData(n)}};this.addEphemeralData=n=>{let e={};for(let t of n)this.get(t.oid).addEphemeralOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return Object.values(e)};this.replaceAllData=({operations:n={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let s of t)r[s]={oid:s,isLocal:!1};for(let s of e){if(!Ne(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:!1}}for(let[s,o]of Object.entries(n)){if(!Ne(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o),r[s]??={oid:s,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=n=>{this.entities.get(n.oid)?.discardPendingOperation(n)};this.ctx=n,this.rootOid=t,this.onPendingOperations=e}};var Bt="@@default",Bi=class{constructor({batchTimeout:n=200,ctx:e,entities:t}){this.currentBatchKey=Bt;this.flushOperations=async(n,e,t)=>{if(!n.length)return;this.ctx.log("debug","Flushing",n.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=n.length-1;o>=0;o--){let a=n[o],l=s[a.oid];if(l&&Mr(a,l)){this.entities.discardPendingOperation(a);continue}let p=Br(a);p!==!1&&(s[a.oid]||(s[a.oid]=new Set),s[a.oid].add(p)),r.unshift(a)}for(let o of r)o.timestamp=this.ctx.time.now;await this.commitOperations(r,t)};this.commitOperations=async(n,e)=>{if(n.length){if(e.undoable){let t=await this.createUndo({ops:n,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:n,baselines:[],isLocal:!0})}};this.addOperations=n=>{n.length&&(this.batcher.add({key:this.currentBatchKey,items:n}),this.ctx.log("debug","added",n.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:n=!0,batchName:e=xt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:n}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Bt,o),commit:async()=>(await this.batcher.flush(Bt),s.flush()),flush:()=>o.commit(),discard:()=>{this.batcher.discard(e)}};return o};this.flushAll=()=>(this.ctx.log("debug","Flushing all operations"),Promise.all(this.batcher.flushAll()));this.createUndo=async n=>{let e=await this.getInverseOperations(n);return e.length?async()=>{let t=await this.createUndo({ops:e,source:n.source,isRedo:!0});for(let r of e)r.timestamp=this.ctx.time.now;return this.ctx.log("debug",n.isRedo?"Redo":"Undo",e,`
14
+ `)}n.pauseRebasing=!1}var mi=class{constructor(i,e){this.db=i;this.context=e;this.onServerReset=i=>this.db.resetSyncedStatusSince(i);this.add=async(i,e)=>{if(i.url&&!(i.localPath||i.file)&&e?.cloneRemote){this.context.log("debug","Cloning remote file added to a new entity. Downloading remote file...",i.id);let t=await this.loadFileContents(i,0,3);i.file=new File([t],i.name,{type:i.type}),delete i.url,this.context.log("debug","Downloaded remote file",i.id,i.name,". Cleared its remote URL.")}else!i.url&&!i.file&&!i.localPath&&this.context.log("warn","File added without a file or URL. This file will not be available for use.",i.id);return i.remote=!1,this.context.log("debug","Adding file to persistence",i),await this.db.add(i),this.context.internalEvents.emit("fileAdded",i),this.context.globalEvents.emit("fileSaved",i),this.context.log("debug","File added",i.id,i.name,i.type,i.file?"with binary file":i.url?"with url":i.localPath?"with local path":"with no data"),i};this.update=async i=>{await this.db.add(i),this.context.globalEvents.emit("fileSaved",i),this.context.log("debug","File updated",i.id,i.name)};this.onUploaded=this.db.markUploaded.bind(this.db);this.get=this.db.get.bind(this.db);this.getAll=this.db.getAll.bind(this.db);this.listUnsynced=this.db.listUnsynced.bind(this.db);this.iterateOverPendingDelete=this.db.iterateOverPendingDelete.bind(this.db);this.stats=this.db.stats.bind(this.db);this.getFileExportName=(i,e)=>`${e}___${i}`;this.export=async(i=!0)=>{let e=await this.getAll();if(i)for(let s of e)if(!s.file&&(s.url||s.localPath))try{let o=await this.loadFileContents(s);s.file=o}catch(o){this.context.log("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,o)}else s.file||this.context.log("warn",`File ${s.id} has no file or URL. It will be missing in the export.`,s);let t=[],r=[];for(let s of e){let o=s.file;if(delete s.file,t.push(s),o){let a=new File([o],this.getFileExportName(s.name,s.id),{type:s.type});r.push(a)}else this.context.log("warn",`File ${s.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{fileData:t,files:r}};this.import=async({fileData:i,files:e})=>{let t=new Map(e.map(s=>{let{id:o}=this.parseFileExportname(s.name);return[o,s]})),r=i.map(s=>{let o=t.get(s.id);return o?{...s,file:o}:(this.context.log("warn",`File ${s.id} was not found in import`),s)});await Promise.all(r.map(s=>this.add(s)))};this.parseFileExportname=i=>{let[e,t]=i.split("___");return{id:e,originalFileName:t}};this.loadFileContents=async(i,e=0,t=0)=>{try{return await this.db.loadFileContents(i,this.context)}catch(r){if(e<t)return new Promise((s,o)=>{setTimeout(()=>{this.loadFileContents(i,e+1,t).then(s,o)},1e3)});throw this.context.log("error",`Failed to download file after ${t} retries`,r),new Error(`Failed to download file after ${t} retries`,{cause:r})}};this.cleanupDeletedFiles=async()=>{let i=0,e=0,t=[];await this.iterateOverPendingDelete(r=>{this.config.canCleanupDeletedFile(r)?(i++,t.push(r.id)):e++});for(let r of t)await this.db.delete(r);this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.onFileRefsDeleted=async i=>{await Promise.all(i.map(async e=>{try{await this.db.markPendingDelete(e.id)}catch(t){this.context.log("error","Failed to mark file for deletion",t)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};e.internalEvents.subscribe("filesDeleted",this.onFileRefsDeleted),this.cleanupDeletedFiles()}get config(){return{canCleanupDeletedFile(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3},...this.context.config.files}}};var As=Me(Je(),1);var gi=class{constructor(i,e,t){this.db=i;this.meta=e;this.ctx=t;this.createOperation=async i=>{let e=await this.meta.getLocalReplica();return this.ctx.log("debug","Creating operation message",i.operations.length),{type:"op",timestamp:this.ctx.time.now,replicaId:e.id,operations:i.operations.map($t)}};this.createSyncStep1=async i=>{let e=await this.meta.getLocalReplica(),t=i===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;return this.db.transaction({mode:"readwrite",storeNames:["operations","baselines"]},async o=>{t?(this.ctx.log("debug","Syncing local operations since",t),await this.db.iterateLocalOperations(l=>{r.push($t(l)),s.add(K(l.oid))},{after:t,transaction:o})):(this.ctx.log("debug","Syncing all operations"),await this.db.iterateAllOperations(l=>{r.push($t(l)),s.add(K(l.oid))},{transaction:o}));let a=[];return t||await this.db.iterateAllBaselines(l=>{a.push(l)},{transaction:o}),r.length>0&&this.ctx.log("debug",`Syncing ${r.length} operations since ${t}`),{type:"sync",schemaVersion:this.ctx.schema.version,timestamp:this.ctx.time.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:t}})};this.createPresenceUpdate=async i=>{let e=await this.meta.getLocalReplica();return{type:"presence-update",presence:i.presence,replicaId:e.id,internal:i.internal}};this.createHeartbeat=async()=>({type:"heartbeat"});this.createAck=async i=>{let e=await this.meta.getLocalReplica();return{type:"ack",timestamp:this.ctx.time.now,replicaId:e.id,nonce:i}};this.createDisconnecting=async i=>({type:"disconnecting",replicaId:(await this.meta.getLocalReplica()).id,reason:i})}};var yi=class{constructor(i,e,t){this.db=i;this.meta=e;this.ctx=t;this.tryAutonomousRebase=async()=>{(await this.meta.getLocalReplica()).lastSyncedLogicalTime||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(this.ctx.log("debug","Running autonomous library rebase"),await this.runRebase(this.ctx.time.now))};this.runRebase=async i=>{this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown||(await this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async e=>{let t=new Set,r,s=0;if(await this.db.iterateAllOperations(a=>{t.add(a.oid),r=a.timestamp,s++},{before:i,transaction:e}),!t.size||this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let o=[];for(let a of t)o.push(await this.rebase(a,r||i,e))}),this.ctx.globalEvents.emit("rebase"))};this.scheduleRebase=async i=>{this.rebaseTimeout&&clearTimeout(this.rebaseTimeout),this.rebaseTimeout=setTimeout(this.runRebase,this.ctx.config.persistence?.rebaseTimeout??1e4,i),this.ctx.log("debug","Scheduled rebase up to global ack",i)};this.rebaseTimeout=null;this.rebase=async(i,e,t)=>{if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;let r=await this.db.getBaseline(i,{transaction:t}),s=r?.snapshot||void 0,o=0,a=r?.authz,l=[];if(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown)return;await this.db.iterateEntityOperations(i,f=>{(!r||f.timestamp>r.timestamp)&&(s=je(s,f.data,l),f.data.op==="initialize"&&(a=f.authz)),o++},{to:e,transaction:t}),s&&z(s,i);let p={oid:i,snapshot:s,timestamp:e,authz:a};if(!(this.ctx.closing||this.ctx.persistenceShutdownHandler.isShuttingDown))return this.ctx.closeLock=(async()=>{if(p.snapshot?await this.db.setBaselines([p],{transaction:t}):await this.db.deleteBaseline(i,{transaction:t}),await this.db.deleteEntityOperations(i,{to:e,transaction:t}),this.ctx.log("debug","rebased",i,"up to",e,":",s,"and deleted",o,"operations"),l.length){let f=l.filter(pe);f.length&&this.ctx.internalEvents.emit("filesDeleted",f)}})(),p}}};var bi=class{constructor(i,e){this.db=i;this.ctx=e;this.insertOperations=async(i,e)=>{this.ctx.log("debug",`Inserting ${i.length} operations`,i);let t=await this.db.addOperations(i,e);for(let r of i)this.ctx.globalEvents.emit("operation",r);return!this.ctx.config.persistence?.disableRebasing&&!this.ctx.pauseRebasing&&this.rebaser.tryAutonomousRebase(),t};this.insertLocalOperations=async(i,e)=>{if(i.length===0)return;for(let r of i)r.isLocal=!0;await this.insertOperations(i,e),this.ctx.log("debug",`Inserted ${i.length} local operations; sending sync message`);let t=await this.messageCreator.createOperation({operations:i});this.ctx.internalEvents.emit("outgoingSyncMessage",t)};this.insertRemoteOperations=async(i,e)=>{if(i.length===0)return[];for(let t of i)t.isLocal=!1;await this.insertOperations(i,e),this.ack(i[i.length-1].timestamp)};this.insertRemoteBaselines=async(i,e)=>{if(i.length===0)return[];this.ctx.log("debug",`Inserting ${i.length} remote baselines`),await this.db.setBaselines(i,e);let t=new Set;return i.forEach(r=>{t.add(K(r.oid))}),Array.from(t)};this.deleteDocument=async i=>{let e=new Set,t=K(i);return M(t===i,"Must be root document OID"),e.add(t),this.db.transaction({storeNames:["baselines","operations"]},async r=>{await Promise.all([this.db.iterateDocumentBaselines(t,a=>{e.add(a.oid)},{transaction:r}),this.db.iterateDocumentOperations(t,a=>{e.add(a.oid)},{transaction:r})]);let s=await this.getDocumentAuthz(t),o=new Array;for(let a of e)o.push({oid:a,timestamp:this.ctx.time.now,data:{op:"delete"},authz:s});return this.insertLocalOperations(o,{transaction:r})})};this.deleteCollection=async i=>{let e=new Set;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await Promise.all([this.db.iterateCollectionBaselines(i,s=>{e.add(s.oid)},{transaction:t}),this.db.iterateCollectionOperations(i,s=>{e.add(s.oid)},{transaction:t})]);let r=new Array;for(let s of e)r.push({oid:s,timestamp:this.ctx.time.now,data:{op:"delete"},authz:void 0});return this.insertLocalOperations(r,{transaction:t})})};this.getDocumentSnapshot=async(i,e={})=>{let t=K(i);return M(t===i,"Must be root document OID"),this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async r=>{let s=[];await this.db.iterateDocumentBaselines(t,l=>{s.push(l)},{transaction:r});let o=new Map;for(let l of s)l.snapshot&&z(l.snapshot,l.oid),o.set(l.oid,l.snapshot);await this.db.iterateDocumentOperations(t,l=>{let p=o.get(l.oid)||void 0,f=je(p,l.data);f&&z(f,l.oid),o.set(l.oid,f)},{transaction:r,to:e.to||this.ctx.time.now});let a=o.get(t);return a&&Ut(a,o),a})};this.getDocumentData=async(i,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort},async t=>{let r=[],s={};return await Promise.all([this.db.iterateDocumentBaselines(i,o=>{r.push(o)},{transaction:t}),this.db.iterateDocumentOperations(i,o=>{s[o.oid]??=[],s[o.oid].push(o)},{transaction:t})]),{baselines:r,operations:s}});this.getDocumentAuthz=async i=>{let e;return await this.db.iterateEntityOperations(i,r=>{if(r.data.op==="initialize")return e=r.authz,!0},{reverse:!0}),e||(await this.db.getBaseline(i))?.authz};this.insertData=async(i,e)=>this.db.transaction({storeNames:["baselines","operations"],abort:e?.abort,mode:"readwrite"},async t=>{if(this.ctx.log("debug","Begin insert data transaction"),i.baselines&&await this.insertRemoteBaselines(i.baselines,{transaction:t}),this.ctx.log("debug","Inserted baselines (if any)"),e?.abort?.aborted)throw new Error("Aborted");i.operations&&(i.isLocal?(this.ctx.log("debug","Inserting local operations"),await this.insertLocalOperations(i.operations,{transaction:t})):(this.ctx.log("debug","Inserting remote operations"),await this.insertRemoteOperations(i.operations,{transaction:t}))),this.ctx.log("debug","End insert data transaction")});this.updateLastSynced=async i=>{if(!this.ctx.closing)return this.updateLocalReplica({lastSyncedLogicalTime:i})};this.setGlobalAck=async i=>{this.ctx.closing||(await this.db.setGlobalAck(i),this.ctx.config.persistence?.disableRebasing||await this.rebaser.scheduleRebase(i))};this._cachedLocalReplica=null;this._creatingLocalReplica=void 0;this.getLocalReplica=async i=>{if(this._cachedLocalReplica)return this._cachedLocalReplica;let e=await this.db.getLocalReplica(i);return e?(this.ctx.log("debug","Read local replica",e),this._cachedLocalReplica=e,e):this._creatingLocalReplica?this._creatingLocalReplica:(this._creatingLocalReplica=(async()=>{let r={id:(0,As.default)(),userId:null,ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.db.updateLocalReplica(r),this._cachedLocalReplica=r,r})(),this._creatingLocalReplica)};this.updateLocalReplica=async(i,e)=>{let t=await this.getLocalReplica(e);M(!!t,"Local replica must exist"),Object.assign(t,i),this._cachedLocalReplica=t,await this.db.updateLocalReplica(t,e)};this.iterateLocalOperations=this.db.iterateLocalOperations;this.iterateAllOperations=this.db.iterateAllOperations;this.iterateAllBaselines=this.db.iterateAllBaselines;this.reset=async()=>{this.ctx.closing||await this.db.reset()};this.stats=this.db.stats;this.export=async()=>{let i=new Array,e=new Array;return this.db.transaction({storeNames:["baselines","operations"],mode:"readwrite"},async t=>{await this.iterateAllOperations(s=>{e.push(s)},{transaction:t}),await this.iterateAllBaselines(s=>{i.push(s)},{transaction:t});let r=await this.getLocalReplica();return{operations:e,baselines:i,localReplica:r,schemaVersion:this.ctx.schema.version}})};this.resetFrom=async i=>{this._cachedLocalReplica=null,await this.db.reset({clearReplica:!0}),i.localReplica&&await this.updateLocalReplica({ackedLogicalTime:i.localReplica.ackedLogicalTime,lastSyncedLogicalTime:i.localReplica.lastSyncedLogicalTime}),this.ctx.log("debug","Resetting metadata from export",i),await this.insertData({operations:i.operations,baselines:i.baselines,isLocal:!0})};this.manualRebase=async()=>{if(this.ctx.closing||this.ctx.config.persistence?.disableRebasing)return;let i=await this.db.getAckInfo();i.globalAckTimestamp&&await this.rebaser.scheduleRebase(i.globalAckTimestamp)};this.ack=async i=>{let e=await this.getLocalReplica();i>this.ctx.time.now||(this.ctx.internalEvents.emit("outgoingSyncMessage",{type:"ack",replicaId:e.id,timestamp:i}),!this.ctx.closing&&(!e.ackedLogicalTime||i>e.ackedLogicalTime)&&this.updateLocalReplica({ackedLogicalTime:i}))};this.__unstable__purgeRemovedCollections=async()=>{let i=this.ctx.schema,e=new Set(Object.keys(i.collections)),t=new Set;await this.db.iterateAllBaselines(r=>{let{collection:s}=ne(r.oid);e.has(s)||(this.ctx.log("debug",`Deleting baseline for removed collection ${s}`,r.oid),t.add(r.oid))}),await this.db.iterateAllOperations(r=>{let{collection:s}=ne(r.oid);e.has(s)||(this.ctx.log("debug",`Deleting operation for removed collection ${s}`,r.oid),t.add(r.oid))});for(let r of t)await this.db.purgeDocumentData(r);this.ctx.log("debug",`Purged ${t.size} document metadata groups for removed collections`)};this.rebaser=new yi(i,this,e),this.messageCreator=new gi(i,this,e)}};var wi=class{constructor(i,e){this.db=i;this.ctx=e;this.reset=this.db.reset.bind(this.db);this.close=this.db.close.bind(this.db);this.saveEntities=async(i,e)=>{if(i.length===0)return;let t=new Set(Object.keys(this.ctx.schema.collections)),r=[],s=i.filter(o=>{let{collection:a}=ne(o.oid);return t.has(a)?(r.includes(a)||r.push(a),!0):(this.ctx.log("warn",`Entity ${o.oid} is in a collection that no longer exists in the schema. It will not be saved.`),!1)});if(r.length!==0){this.ctx.log("debug","Saving",s.length,"entities"),await this.db.saveEntities(s,{abort:e?.abort,collections:r}),this.ctx.log("debug","Saved",s.length,"entities"),this.ctx.entityEvents.emit("collectionsChanged",r);for(let o of i)this.ctx.entityEvents.emit("documentChanged",o.oid)}};this.findOneOid=this.db.findOneOid.bind(this.db);this.findAllOids=this.db.findAllOids.bind(this.db);this.stats=this.db.stats.bind(this.db)}};async function jn(n){let i=n.schema;if(n.schema.wip&&(n.namespace=Os(n.originalNamespace,n.schema),n.log("info","\u{1F528}","Switched to WIP namespace",n.namespace),!(await n.persistence.getNamespaces()).includes(n.namespace))){let a=await n.persistence.getNamespaceVersion(n.originalNamespace);if(a===0)n.log("debug","No existing data to copy to WIP namespace");else{let l=n.oldSchemas?.find(p=>p.version===a);if(!l)throw new U(U.Code.MigrationPathNotFound,void 0,`Trying to open WIP database for version ${n.schema.version}, but the current local data is version ${a} and a historical schema for that version is not available.`);n.log("info",`Copying data from ${n.originalNamespace} to ${n.namespace}`),await n.persistence.copyNamespace(n.originalNamespace,n.namespace,n.cloneWithOptions({schema:l}))}}let e=await n.persistence.openNamespace(n.namespace,n);n.log("info","Opening persistence metadata",n.namespace);let t=new bi(await e.openMetadata(n),n);n.log("info","Opening persistence files",n.namespace);let r=new mi(await e.openFiles(n),n);if(n.log("info","Migrating document database"),await Ds({context:n,version:n.schema.version,meta:t}),n.log("info","Opening persistence documents"),n.schema.version<=0)throw n.schema!==i?(n.log("critical","Schema at initialization does not match original schema. This is likely a bug in Verdant!"),new U(U.Code.ConfigurationError,void 0,"Schema at initialization does not match original schema. This is likely a bug in Verdant!")):new U(U.Code.ConfigurationError,void 0,`Schema version must be greater than 0. Found version ${n.schema.version} with collections [${Object.keys(n.schema.collections).join(", ")}]
15
+ ${JSON.stringify(n.schema)}`);let s=new wi(await e.openDocuments(n),n);if(!n.schema.wip){let o=await n.persistence.getNamespaces();for(let a of o)a.startsWith("@@wip_")&&(n.log("debug","Cleaning up old WIP namespace",a),await n.persistence.deleteNamespace(a,n))}return{meta:t,files:r,documents:s}}async function Ts(n,i){n.log("info","Importing data from export");let e=n.oldSchemas?.find(l=>l.version===i.data.schemaVersion);if(!e)throw new Error(`Could not find schema for version ${i.data.schemaVersion}`);let t=`@@import_${Date.now()}`,r=n.cloneWithOptions({schema:e,namespace:t,disableRebasing:!0,persistenceShutdownHandler:new Be(n.log)});await r.reinitialize();let s=await r.meta;await s.resetFrom(i.data);let o=new Set;for(let l of i.data.baselines)o.add(K(l.oid));for(let l of i.data.operations)o.add(K(l.oid));let a=await Promise.all(Array.from(o).map(async l=>{let p=await s.getDocumentSnapshot(l);return{oid:l,getSnapshot:()=>p}}));if(await(await r.documents).saveEntities(a),await(await r.files).import(i),n.log("debug","Imported data into temporary namespace",t),await r.persistenceShutdownHandler.shutdown(),e.version!==n.schema.version){let l=r.cloneWithOptions({persistenceShutdownHandler:new Be(n.log),schema:n.schema,oldSchemas:n.oldSchemas});await l.reinitialize(),n.log("debug","Upgraded imported data to current schema"),await l.persistenceShutdownHandler.shutdown(),n.log("debug","Shut down upgraded databases")}if(await n.persistenceShutdownHandler.shutdown(),await n.persistence.copyNamespace(t,n.namespace,n),n.log("debug","Copied imported data to primary namespace"),await n.reinitialize(),n.log("debug","Reinitialized primary persistence layer"),i.data.schemaVersion===n.schema.version){let l=await(await n.meta).stats();if(l.operationsSize.count!==i.data.operations.length)throw n.log("critical","Imported operations count mismatch","expected",i.data.operations.length,"actual",l.operationsSize.count),new U(U.Code.ImportFailed,void 0,"Imported operations count mismatch");if(l.baselinesSize.count!==i.data.baselines.length)throw n.log("critical","Imported documents count mismatch","expected",i.data.baselines.length,"actual",l.baselinesSize.count),new U(U.Code.ImportFailed,void 0,"Imported documents count mismatch")}else n.log("debug","Skipping integrity check due to schema version mismatch (not an error)",{exportedVersion:i.data.schemaVersion,currentVersion:n.schema.version});n.log("debug","Data copied to primary namespace"),await n.persistence.deleteNamespace(t,n),n.log("debug","Deleted temporary namespace"),n.internalEvents.emit("persistenceReset"),n.log("info","Data imported successfully"),n.persistenceShutdownHandler.reset()}var vi=class{constructor(i,e){this.base=i;this.version=e;this.withMigrationTime=async(i,e)=>{this.overrideNow=()=>this.base.zero(i),e(),this.overrideNow=void 0};this.update=this.base.update.bind(this.base);this.nowWithVersion=i=>this.base.now(i);this.zeroWithVersion=i=>this.base.zero(i)}get now(){return this.overrideNow?this.overrideNow():this.base.now(this.version)}get zero(){return this.base.zero(this.version)}};var Ha={WebSocket:typeof WebSocket<"u"?WebSocket:void 0,fetch:typeof window<"u"?window.fetch.bind(window):fetch,indexedDB:typeof indexedDB<"u"?indexedDB:void 0,location:typeof window<"u"?window.location:void 0,history:typeof window<"u"?window.history:void 0},xi=class n{constructor(i,e){this.init=i;this.weakRef=i=>this.init.EXPERIMENTAL_weakRefs?new WeakRef(i):new li(i);this.closing=!1;this.pauseRebasing=!1;this.getClient=()=>{throw new U(U.Code.Unexpected,void 0,"Client not yet initialized. This is a Verdant bug, please report it.")};this.reinitialize=async()=>{this.initializedPromise=jn(this),await this.initializedPromise};if(typeof window>"u"&&!this.init.environment)throw new Error("A Verdant client was initialized in an environment without a global Window or `environment` configuration. 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 the environment to the Client options.");this.namespace=this.init.namespace,this.originalNamespace=this.init.namespace,this.time=new vi(new ni,this.init.schema.version),this.log=this.init.log===!1?di:this.init.log||An("\u{1F33F}"),this.migrations=i.migrations,this.undoHistory=i.undoHistory||new lt,this.entityEvents=new W,this.internalEvents=new W,this.globalEvents=new W,this.schema=i.schema,this.oldSchemas=i.oldSchemas,this.patchCreator=new Ve(()=>this.time.now),this.persistenceShutdownHandler=i.persistenceShutdownHandler||new Be(this.log),this.config={files:i.files,sync:i.sync,persistence:{disableRebasing:i.disableRebasing,rebaseTimeout:i.rebaseTimeout},queries:i.queries},this.environment={...Ha,...i.environment},this.persistence=i.persistence||new ft(this.environment.indexedDB),this.initializedPromise=e||jn(this),this.initializedPromise.then(()=>{this.log("info","Persistence initialized")})}get meta(){return this.initializedPromise.then(i=>i.meta)}get documents(){return this.initializedPromise.then(i=>i.documents)}get files(){return this.initializedPromise.then(i=>i.files)}get waitForInitialization(){return this.initializedPromise.then(()=>{})}cloneWithOptions(i){return new n({...this.init,...i},this.initializedPromise)}};var Si=class{constructor(i,e){this.schema=i;this.entities=e;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return M(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),ee(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return qe(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return as(t.fields,e)};this.create=async(i,e,t={})=>{let r=t,s=this.addDefaults(i,e),o=this.validate(i,s),a=this.getOid(i,o);if(t.access){let l=this.schema.collections[i];t.access!=="shared"&&e[l.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(o,a,r)};this.delete=async(i,e,t={})=>{let r=ee(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>ee(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>ee(i,r)),t);this.clone=async(i,e,t={})=>{if(!Qt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),s=this.schema.collections[i];if(delete r[s.primaryKey],!s.fields[s.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${i}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[s.primaryKey]=t.primaryKey}e.access&&!t.access&&(t.access=e.access);let o=t.update?t.update(r):r;return this.create(i,o,t)}}};var ki=Me(ho(),1);var Zn=Me(Je(),1);function cc(n){return{id:(0,Zn.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function mt(n,i){if(typeof window<"u"&&rt(n)){let e=cc(n);return i(e),xt(e.id)}if(Vt(n)){let e={...n,id:(0,Zn.default)()};return i(e),xt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=mt(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=mt(n[e],i);return n}return n}var Ti=class{constructor({initial:i,ctx:e}){this.cache=new Map;this.get=i=>{let e=this.getCached(i.oid);if(e)return e;let t=new le(i);return this.cache.set(i.oid,this.ctx.weakRef(t)),t};this.has=i=>this.cache.has(i);this.getCached=i=>{if(this.cache.has(i)){let t=this.cache.get(i)?.deref();if(t)return t;this.cache.delete(i)}return null};if(this.ctx=e,i)for(let t of i)this.cache.set(t.oid,e.weakRef(t))}};function fo(n,i,e){let t={previousValue:n.get(i),isLocal:!1};function r(s){if(n.deleted)return;let o=n.get(i);o!==this.previousValue&&(this.isLocal=s.isLocal,e(o,this),this.previousValue=o)}return n.subscribe("change",r.bind(t))}var po=Symbol("private entity context key"),le=class n extends W{constructor({oid:e,schema:t,entityFamily:r,parent:s,ctx:o,metadataFamily:a,readonlyKeys:l,files:p,storeEvents:f,deleteSelf:S,fieldPath:w}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this._deleting=!1;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof n){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=ze(this.schema,e);return M(t,`No schema for key ${e}`),t};this.validate=zr(()=>(this.validationError=ke({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,expectRefs:!0})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(s=>s instanceof n||s instanceof Ee?e(s):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>(a instanceof n||a instanceof Ee?s[o]=e(a):s[o]=a,s),{});return z(r,this.oid),r}};this.rawViewWithMappedChildren=e=>{let t=this.rawView;if(!t)return null;if(Array.isArray(t)){let r=t.map((s,o)=>$(s)?e(this.getChild(o,s.id)):s);return z(r,this.oid),r}else{let r=Object.entries(t).reduce((s,[o,a])=>($(a)?s[o]=e(this.getChild(o,a.id)):s[o]=a,s),{});return z(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.getUnprunedSnapshot=()=>this.rawViewWithMappedChildren(e=>e instanceof Ee?e.getSnapshot():e.getUnprunedSnapshot());this.addPendingOperations=e=>{this.ctx.log("debug","Entity: adding pending operations",this.oid,e),this.deepInvalid&&(this.ctx.log("warn","Changes are being applied to a pruned entity. This means that the pruned version is being treated as the new baseline and any pruned invalid data is lost.",this.oid),this.canonizePrunedVersion()),this.applyPendingOperations(e)};this.applyPendingOperations=e=>{if(this.access)for(let r of e)r.authz=this.access,r.data.op==="initialize"&&(this._deleting=!1);let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.getPruneDiff=()=>{let e=this.getSnapshot(),t=this.getUnprunedSnapshot();return this.patchCreator.createDiff(t,e,{authz:this.access,merge:!1})};this.canonizePrunedVersion=()=>{this.applyPendingOperations(this.getPruneDiff())};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)this.change(r)};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 t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.invalidate=e=>{if(e.oid===this.oid)this.invalidateCachedView();else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof n&&t.invalidate(e)}};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof n&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange?this.ctx.log("debug","Entity already deleted, not emitting delete or change events",this.oid):(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{if(this.deleted){this.ctx.log("debug","Entity deleted, not emitting change",this.oid);return}this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{if(this.deleted){this.ctx.log("debug","Entity deleted, not emitting deep change",this.oid);return}this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.createFileContext=e=>({oid:this.oid,key:e,getFileRef:()=>{let t=this.rawView?.[e];return pe(t)?t:null},applyFileRef:t=>{if(this.readonlyKeys.includes(e))throw new Error(`Cannot set readonly key ${e.toString()}`);this.addPendingOperations(this.isList?this.patchCreator.createListSet(this.oid,e,t):this.patchCreator.createSet(this.oid,e,t))},subscribe:t=>this.subscribe("change",t),onChange:()=>this.deepChange(this,{isLocal:!1,oid:this.oid})});this.getChild=(e,t)=>{let r=ze(this.schema,e);if(!r){let s="";try{s=JSON.stringify(this.schema)}catch{s="<unable to stringify schema>"}throw new Error(`No schema for key ${String(e)} in ${s} (${this.oid})`)}return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>fo(this,e,r);this.get=e=>{er(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],s=ze(this.schema,e);if(!s)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if($(r))if(pe(r)){if(s.type!=="file"){if(ge(s))return null;if(Fe(s))return Ce(s);throw new Error(`Expected file schema for key ${String(e)}, got ${s.type}`)}return this.files.get(r.id,{downloadRemote:!!s.downloadRemote,ctx:this.ctx,fileContext:this.createFileContext(e)})}else{if(s.type==="file"){if(console.error(`Expected file ref for key ${String(e)}, got ${r}`),ge(s))return null;if(Fe(s))return Ce(s);throw new Error(`No valid value for key ${String(e)} in ${JSON.stringify(this.schema)}`)}let o=this.getChild(e,r.id);if(o.deepInvalid){if(s.type==="array"||s.type==="map")return o;if(ge(s))return null;if(Fe(s)){let a=o.getUnprunedSnapshot(),l=this.patchCreator.createDiff(a,Ce(s),{merge:!1,mergeUnknownObjects:!0,authz:this.access});return this.processPrunedChild(e,o,l)}}return o}else{if(this.schema.type==="map"&&r===void 0)return;if(ke({field:s,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0}))if(Fe(s)){if(os(s))return Ce(s);let o=Ce(s),a=Oe(this.oid),l=this.patchCreator.createInitialize(o,a,this.access);l.push(...this.patchCreator.createSet(this.oid,e,ie(a),this.access));let p=this.getChild(e,a);return this.processPrunedChild(e,p,l)}else return;return r}};this.processPrunedChild=(e,t,r)=>{this.ctx.log("warn","Replacing invalid child object field with ephemeral, valid data",this.oid,e);let s=this.metadataFamily.addEphemeralData(r);for(let o of s)this.invalidate(o);return t};this.getOrSet=(e,t)=>{er(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);rt(e)||(e=fe(e,!1));let r=ze(this.schema,t);if(r){Ge(e,r);let s=ke({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(s)throw new Error(`Validation error: ${s.message}`,{cause:s})}return mt(e,s=>this.files.add(s))};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 t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof n)return ie(e.oid);if(e instanceof Ee)return xt(e.id);if(typeof e=="object"){let t=G(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ie(t)}else return e};this.set=(e,t,r)=>{er(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)lc(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="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:t=!0,replaceSubObjects:r=!1,preserveUndefined:s=!1,dangerouslyDisableMerge:o=!1}={})=>{if(!t&&!o&&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 a={};z(a,this.oid);for(let[l,p]of Object.entries(e)){if(this.readonlyKeys.includes(l))throw new Error(`Cannot set readonly key ${l.toString()}`);if(p===void 0&&!s)continue;let f=ze(this.schema,l);f&&Ge(p,f),a[l]=this.processInputValue(p,l)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),a,{mergeUnknownObjects:!r,merge:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if($(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let s=this.view.indexOf(e);if(s===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(s,t)}};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 t=this.getItemRefValue(e);return $(t)?this.view.some(r=>{if($(r))return Te(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);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.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};this.__markDeleting__=()=>{this._deleting=!0};M(!!e,"oid is required"),this.oid=e,this.readonlyKeys=l||[],this.ctx=o,this.files=p,this.schema=t,this.fieldPath=w||[],this.entityFamily=r||new Ti({initial:[this],ctx:o}),this.metadataFamily=a,this.storeEvents=f,this.parent=s,this._deleteSelf=S,this.parent||(f.add.attach(this.onAdd),f.replace.attach(this.onReplace),f.resetAll.attach(this.onResetAll))}get[po](){return this.ctx}get metadata(){return this.metadataFamily.get(this.oid)}get patchCreator(){return this.ctx.patchCreator}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&&!ge(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!N(e))return Fe(this.schema)?Ce(this.schema):null;let r=this.isList?[]:{};if(z(r,this.oid),Array.isArray(e)){let s=ze(this.schema,0);if(!s)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let a=this.get(o);this.childIsNull(a)&&!ge(s)?this._deleting||this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):r.push(a)}}else if(N(e)){let s=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of s){let a=ze(this.schema,o);if(!a){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?r={}:r=null;break}let l=this.get(o);if(this.childIsNull(l)&&!ge(a)){if(this._deleting||this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){r=null;break}}else ge(a)&&l===void 0?r[o]=null:r[o]=l}}return this.cachedView=r,r}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get deepInvalid(){if(this.invalid)return!0;if(Array.isArray(this.rawView)){for(let e=0;e<this.rawView.length;e++)if(oe(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}else if(N(this.rawView)){for(let e in this.rawView)if(oe(this.rawView[e])&&this.getChild(e,this.rawView[e].id).deepInvalid)return!0}return!1}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(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function er(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function lc(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}function mo(n){return n[po].getClient()}var tr=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:s}){this.baseline=null;this.confirmedOperations=[];this.ephemeralOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=fe(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,s=this.applyOperations(e,!e,this.confirmedOperations,t,t);s.futureSeen&&this.ctx.globalEvents.emit("futureSeen",s.futureSeen),s.authz&&(r=s.authz);let o=!this.ephemeralOperations||i?s:this.applyOperations(s.view,s.deleted,this.ephemeralOperations,s.latestTimestamp,null),a=i?s:this.applyOperations(o.view,o.deleted,this.pendingOperations,o.latestTimestamp,null);a.authz&&(r=a.authz),a.view&&z(a.view,this.oid);let l=!!s.latestTimestamp&&Cn(s.latestTimestamp,this.ctx.time.now)<0,p=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;p&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let f=a.latestTimestamp??s.latestTimestamp??t,S=f?Dn(f):0;return!a.view&&!a.deleted&&!p&&this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`),{view:a.view??void 0,deleted:a.deleted,empty:p,fromOlderVersion:l,updatedAt:S,latestTimestamp:f,authz:r}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){let r=this.confirmedOperations.findIndex(o=>o.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let s=this.pendingOperations.length;this.discardPendingOperation(t),e-=s-this.pendingOperations.length}return e};this.addPendingOperation=i=>{this.pendingOperations.push(i)};this.addEphemeralOperation=i=>{this.ephemeralOperations||(this.ephemeralOperations=[]),this.ephemeralOperations.push(i)};this.clearEphemeralOperations=()=>{let i=this.ephemeralOperations;return this.ephemeralOperations=[],i};this.discardPendingOperation=i=>{let e=this.pendingOperations.findIndex(t=>t.timestamp===i.timestamp);e!==-1&&this.pendingOperations.splice(e,1)};this.applyOperations=(i,e,t,r,s)=>{let o,a,l=this.ctx.time.now;for(let p of t)if(!(s&&p.timestamp<=s)){if(Cn(p.timestamp,l)>0){o=p.timestamp;continue}if(p.data.op==="delete")e=!0;else try{i=je(i,p.data),p.data.op==="initialize"&&(e=!1,p.authz&&(a=p.authz))}catch(f){throw this.ctx.log("critical",`Failed to apply operation to entity ${this.oid}: ${JSON.stringify(p)}`,f),f}(!r||p.timestamp>r)&&(r=p.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:o,authz:a}};M(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),s&&(this.baseline=s)}},Ri=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(M(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new tr({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let s of i){if(!Ne(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:t}}for(let[s,o]of Object.entries(e)){if(!Ne(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o)!==0&&(r[s]??={oid:s,isLocal:t})}return Object.values(r)};this.addPendingData=i=>{this.flushAllEphemeral();let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.ephemeralMemo=new Array;this.flushAllEphemeral=()=>{for(let i of this.entities.values()){let e=i.clearEphemeralOperations();e&&this.ephemeralMemo.push(...e)}if(this.ephemeralMemo.length){let i=this.ephemeralMemo.slice();this.ephemeralMemo.length=0,this.addPendingData(i)}};this.addEphemeralData=i=>{let e={};for(let t of i)this.get(t.oid).addEphemeralOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return Object.values(e)};this.replaceAllData=({operations:i={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let s of t)r[s]={oid:s,isLocal:!1};for(let s of e){if(!Ne(this.rootOid,s.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(s));this.get(s.oid).addBaseline(s),r[s.oid]??={oid:s.oid,isLocal:!1}}for(let[s,o]of Object.entries(i)){if(!Ne(this.rootOid,s))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(o));this.get(s).addConfirmedOperations(o),r[s]??={oid:s,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var kt="@@default",Fi=class{constructor({batchTimeout:i=200,ctx:e,entities:t}){this.currentBatchKey=kt;this.flushOperations=async(i,e,t)=>{if(!i.length)return;this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync");let r=[],s={};for(let o=i.length-1;o>=0;o--){let a=i[o],l=s[a.oid];if(l&&Br(a,l)){this.entities.discardPendingOperation(a);continue}let p=kr(a);p!==!1&&(s[a.oid]||(s[a.oid]=new Set),s[a.oid].add(p)),r.unshift(a)}for(let o of r)o.timestamp=this.ctx.time.now;await this.commitOperations(r,t)};this.commitOperations=async(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=vt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),o={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=kt,o),commit:async()=>(await this.batcher.flush(kt),s.flush()),flush:()=>o.commit(),discard:()=>{this.batcher.discard(e)}};return o};this.flushAll=()=>(this.ctx.log("debug","Flushing all operations"),Promise.all(this.batcher.flushAll()));this.createUndo=async i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.source,isRedo:!0});for(let r of e)r.timestamp=this.ctx.time.now;return this.ctx.log("debug",i.isRedo?"Redo":"Undo",e,`
16
16
  was
17
- `,n.ops),await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:n,source:e})=>{let t=$t(n),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let p=(e??await this.entities.hydrate(K(o)))?.__getViewData__(o,"confirmed");if(!p){this.ctx.log("warn","could not find entity",o,"for undo operation",n);return}let f=ms(o,p.view,a,s);r.unshift(...f)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=n,this.batcher=new nt(this.flushOperations),this.batcher.add({key:Bt,items:[],max:100,timeout:n,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Bt}};var Li=class extends ce{constructor({ctx:e,files:t}){super();this.events={add:new Mi.WeakEvent,replace:new Mi.WeakEvent,resetAll:new Mi.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.ctx.globalEvents.emit("resetToServer")})),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.empty=async()=>{await(await this.ctx.documents).reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await(await this.ctx.meta).reset(),await(await this.ctx.documents).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 t=e?.baselines??[],r=e?.operations??[];if(t.length===0&&r.length===0){this.ctx.log("debug","No data to process");return}this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let s=Array.from(new Set(t.map(f=>K(f.oid)).concat(r.map(f=>K(f.oid))))),o=kr(t),a=Fr(r);this.ctx.log("debug","Applying data to live entities");for(let f of s){let S=o[f],w=a[f]??[],A=$t(w),y=e.reset?this.events.replace:this.events.add,I=this.pendingEntityPromises.get(f);I?(this.ctx.log("debug","Waiting for ongoing entity hydration",f),I.then(()=>{y.invoke(this,{oid:f,baselines:S,operations:A,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",f),y.invoke(this,{oid:f,baselines:S,operations:A,isLocal:!1}))}let l={abort:this.abortDataQueueController.signal};await(await this.ctx.meta).insertData(e,l),this.ctx.log("debug","Data processing complete, all data saved to metadata db.");let p=await Promise.all(s.map(async f=>await this.hydrate(f,l)??{oid:f,getSnapshot(){return null}}));try{this.ctx.log("debug","Saving entities to queryable storage"),await(await this.ctx.documents).saveEntities(p,l)}catch(f){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",f):this.ctx.log("error","Error saving entities to queryable storage",f)}};this.hydrate=async(e,t)=>{if(!qt(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){let s=this.cache.get(e);if(s){let o=s.deref();if(o)return o.deleted?(this.ctx.log("debug","Cached entity is deleted",e),null):(this.ctx.log("debug","Using cached hydrated entity",e),o);this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for ongoing entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let s=this.constructEntity(e);if(!s)return this.ctx.log("warn","Entity schema not found, cannot construct",e),null;let o=this.loadEntity(s,t);return o.finally(()=>{this.pendingEntityPromises.delete(e),this.ctx.log("debug","Hydration complete",e)}),this.pendingEntityPromises.set(e,o),o}};this.destroy=async()=>{this.ctx.log("warn","Disposing EntityStore"),this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:s}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=ne(t);Qt(e);let a=[],l=mt(e,a.push.bind(a));z(l,t);let{schema:p}=this.getCollectionSchema(o);if(!p)throw new Error(`Collection schema not found for ${o}`);let f=this.ctx.patchCreator.createInitialize(l,t,s);await this.batcher.commitOperations(f,{undoable:!!r});let S=await this.hydrate(t);if(!S)throw this.ctx.log("error","Failed to create entity; hydrated entity is null. Hopefully an error is logged above.",t),new U(U.Code.Unexpected,void 0,`Failed to create document ${t}`);return this.ctx.log("debug","Associating",a.length,"files to new entity",t),a.forEach(w=>this.files.add(w,S)),S};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),M(e.every(o=>o===K(o)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(o=>this.hydrate(o))),s=[];for(let o of r)if(o){let a=o.__getFamilyOids__(),l=this.ctx.patchCreator.createDeleteAll(a);for(let p of l)p.authz=o.access;s.push(...l),o.__markDeleting__()}await this.batcher.commitOperations(s,{undoable:t?.undoable===void 0?!0:t.undoable}),e.forEach(o=>{this.cache.delete(o),this.ctx.log("debug","Deleted document from cache",o)})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{M(!!e,"Cannot construct entity without OID");let{collection:t}=ne(e),{schema:r,readonlyKeys:s}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)return this.ctx.log("warn","Cannot hydrate entity after store has been disposed"),null;let o=new ki({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new le({ctx:this.ctx,oid:e,schema:r,readonlyKeys:s,files:this.files,metadataFamily:o,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=K(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>(await this.loadEntityData(e,t),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e);this.loadEntityData=async(e,t)=>{let{operations:r,baselines:s}=await(await this.ctx.meta).getDocumentData(e.oid,t);return!s.length&&!Object.keys(r).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:s,operations:r,isLocal:!1}),e)};this.clearCache=()=>{this.ctx.log("debug","Emptying entity cache"),this.cache.clear()};this.ctx=e,this.files=t,this.batcher=new Bi({ctx:e,entities:this}),this.addDispose(this.ctx.internalEvents.subscribe("persistenceReset",this.clearCache))}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var ji=class extends ce{constructor({sync:e,context:t}){super();this.cache=new Map;this.add=async(e,t)=>{let r=this.cache.get(e.id);r||(r=new xe(e.id,{ctx:this.context,parent:t}),this.cache.set(e.id,r)),e.remote||r[gt](e);let s=await(await this.context.files).add(e,{cloneRemote:!0});r[gt](s)};this.get=(e,t)=>{if(this.cache.has(e))return this.cache.get(e);let r=new xe(e,t);return this.cache.set(e,r),this.load(r),r};this.load=async e=>{let t=await(await this.context.files).get(e.id);if(t&&e[gt](t),!t?.url&&(!t||t.remote))try{if(this.sync.status!=="active"){this.context.log("info","Sync is not active, waiting for online to load file",e.id,e.name);let s=this.sync.subscribe("onlineChange",o=>{o&&(s(),this.load(e))});return}let r=await this.sync.getFile(e.id);if(r.success){let s={...r.data,...t,url:r.data.url};await(await this.context.files).update(s),e[gt](r.data)}else this.context.log("error","Failed to load file",r),t||e[Ri](r.error?.toString())}catch(r){this.context.log("error","Failed to load file",r),t||e[Ri](r instanceof Error?r.message:String(r))}};this.onFileUploaded=async e=>{this.context.log("debug","Marking file as uploaded",e.id),(await this.context.files).onUploaded(e.id)};this.sync=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("fileUploaded",this.onFileUploaded))}};var nr=i=>Array.isArray(i)?i.map(nr):i instanceof le?i.getSnapshot():i;var rr=class{constructor(){this.queue=[];this.scheduled=!1;this.flush=()=>{let n=this.queue.splice(0,20);for(let{run:e,resolve:t,reject:r}of n)e().then(t,r);this.queue.length?setTimeout(this.flush,0):this.scheduled=!1}}enqueue(n){let e=new Promise((t,r)=>{this.queue.push({run:n,resolve:t,reject:r})});return this.scheduled||(this.scheduled=!0,queueMicrotask(this.flush)),e}},yo=new WeakMap;function bo(i,n){let e=yo.get(i);return e||(e=new rr,yo.set(i,e)),e.enqueue(n)}function pc(i){return i!==null}function sr(i){return Array.isArray(i)?i.map(sr).filter(pc):i instanceof le&&i.deleted?null:i}function Ke(i,n){return!i&&!n||i&&n&&He(i)===He(n)}var or=Symbol("ON_ALL_UNSUBSCRIBED"),ye=Symbol("UPDATE"),mc=50,gc,Se=class extends ce{constructor({initial:e,context:t,collection:r,key:s,shouldUpdate:o}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this._timing={sweep:null,hydration:null,total:null};this._startedAt=null;this._timingHistory=[];this._needsTrailingRevalidation=!1;this.revalidate=()=>{this._revalidationTimeout!==void 0?(this._needsTrailingRevalidation=!0,clearTimeout(this._revalidationTimeout)):this.execute(),this._revalidationTimeout=setTimeout(()=>{this._revalidationTimeout=void 0,this._needsTrailingRevalidation&&(this._needsTrailingRevalidation=!1,this.execute())},mc)};this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue);let t=sr(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((s,o)=>s===t[o])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof le&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof le&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>{let e=performance.now();return this._startedAt=Date.now(),this.context.log("debug","Executing query",this.key),this.status==="initial"?this.status="initializing":this.status==="ready"&&(this.status="revalidating"),this._executionPromise=bo(this.context,this.run).then(()=>this._value).catch(t=>{if(t instanceof Error){if(t.name==="InvalidStateError"||t.name==="InvalidAccessError")return this._value;throw t}else throw new Error("Unknown error executing query")}).finally(()=>{let t=performance.now()-e;this._timing.total=t,this._timingHistory=[...this._timingHistory,{startedAt:this._startedAt??Date.now(),...this._timing}].slice(-100),this.context.log("debug","Query executed",this.key,`Duration: ${t}ms`)}),this._executionPromise};this.measureSweep=async e=>{let t=performance.now();try{return await e()}finally{this._timing.sweep=performance.now()-t}};this.measureHydration=async e=>{let t=performance.now();try{return await e()}finally{this._timing.hydration=performance.now()-t}};this.getDiagnostic=e=>({key:this.key,startedAt:this._startedAt,collection:this.collection,type:this.type,status:this.status,active:e,result:nr(this.current),timing:{...this._timing},runs:this._timingHistory.map(t=>({...t}))});this[gc]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new W(l=>{l==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=s,this.collection=r,this.type=this.constructor.name,this.addDispose(()=>clearTimeout(this._revalidationTimeout));let a=o||(l=>l.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",l=>{a(l)&&this.revalidate()}))}static{gc=or}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}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}get __rawValue(){return this._rawValue}};var yc,Ni=class extends Se{constructor({index:e,hydrate:t,limit:r,...s}){super({initial:[],...s});this.run=async()=>{let{result:e}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,index:this.index,limit:this.limit}));this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await this.measureHydration(()=>Promise.all(e.map(this.hydrate))))};this[yc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.limit=r,this.index=e,this.hydrate=t}static{yc=ye}};var bc,Vi=class extends Se{constructor({hydrate:e,pageSize:t,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,limit:this._pageSize*this._upToPage,offset:0,index:this.index}));this._hasNextPage=t,this.setValue(await this.measureHydration(()=>Promise.all(e.map(this.hydrate))))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index}));this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await this.measureHydration(()=>Promise.all(e.map(this.hydrate)))])};this[bc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{bc=ye}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var wc,Ui=class extends Se{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.measureSweep(async()=>(await this.context.documents).findOneOid({collection:this.collection,index:this.index}));this.setValue(e?await this.measureHydration(()=>this.hydrate(e)):null)};this[wc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{wc=ye}};var vc,zi=class extends Se{constructor({index:e,hydrate:t,pageSize:r,page:s,...o}){super({initial:[],...o});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,index:this.index,limit:this._pageSize,offset:this._page*this._pageSize}));this._hasNextPage=t,this.setValue(await this.measureHydration(()=>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[vc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{vc=ye}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var $i=class extends Se{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.measureHydration(()=>this.hydrate(this.oid));this.setValue(e)};this.oid=ee(r.collection,e),this.hydrate=t}};var Ki=class{constructor({collection:n,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=n=>n?He(n):"";this.get=n=>{let e=`get:${this.collection}:${n}`;return this.cache.getOrSet(e,()=>new $i({id:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:n,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(n)}`;return this.cache.getOrSet(t,()=>new Ui({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ye](n)})};this.findAll=({index:n,key:e,limit:t}={})=>{let r=e||`findAll:${this.collection}:${t}:${this.serializeIndex(n)}`;return this.cache.getOrSet(r,()=>new Ni({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,limit:t}),s=>{s[ye](n)})};this.findPage=({index:n,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(s,()=>new zi({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[ye](n)})};this.findAllInfinite=({index:n,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(n)}:${e}`;return this.cache.getOrSet(r,()=>new Vi({index:n,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ye](n)})};this.cache=e,this.collection=n,this.hydrate=t.hydrate,this.context=r,this.documentManager=s,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var Wi=class extends ce{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this._holds=new Set;this._inactiveDiagnostics=new Map;this.enqueueQueryEviction=e=>{setTimeout(()=>{if(!e.subscribed){if(this._holds.has(e.key)){this.context.log("debug","QueryCache: keepAlive hold on query preserves after unsubscribe",e.key);return}this._cache.get(e.key)===e&&(this._cache.delete(e.key),this._inactiveDiagnostics.set(e.key,e.getDiagnostic(!1)),this.context.log("debug","QueryCache: evicted query",e.key))}},this._evictionTime)};this.dropAll=()=>{this.context.log("debug","QueryCache: drop all",this._cache.size,"queries"),this._cache.forEach(e=>{this._inactiveDiagnostics.set(e.key,e.getDiagnostic(!1)),e.dispose()}),this._cache.clear()};this.forceRefreshAll=()=>{this.context.log("debug","QueryCache: force refresh all",this._cache.size,"queries"),this._cache.forEach(e=>e.execute())};this._evictionTime=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("persistenceReset",this.forceRefreshAll))}get activeKeys(){return Array.from(this._cache.keys())}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),this._inactiveDiagnostics.delete(e.key),e[or](this.enqueueQueryEviction),this.enqueueQueryEviction(e),e}get diagnostics(){return{queries:[...this._cache.values().map(e=>e.getDiagnostic(!0)),...this._inactiveDiagnostics.values()]}}getOrSet(e,t,r){let s=this.get(e);return s?(r?.(s),s):(this.context.log("debug","QueryCache: creating new query",e),this.set(t()))}keepAlive(e){this._holds.add(e),this.context.log("debug","QueryCache: keepAlive",e)}dropKeepAlive(e){this._holds.delete(e);let t=this.get(e);t&&(t.subscribed||(this.context.log("debug","QueryCache: dropKeepAlive on unsubscribed query; queuing eviction",e),this.enqueueQueryEviction(t)))}get keepAlives(){return this._holds}};async function wo(){try{let i=await navigator.permissions.query({name:"periodic-background-sync"});if(i.state==="granted"){let n=await navigator.serviceWorker.ready;if("periodicSync"in n)try{await n.periodicSync.register("verdant-sync",{minInterval:24*60*60*1e3})}catch(e){console.warn("Failed to register background sync:",e)}}else console.debug("Background sync permission is not granted:",i)}catch(i){console.error("Failed to initiate background sync:",i)}}var Hi=class extends ce{constructor({endpointProvider:e,ctx:t}){super();this.onFileAdded=async e=>{if(!e.remote){this.ctx.log("debug","Uploading file",e.id,e.name);try{await this.uploadFile(e)}catch(t){this.ctx.log("error","File upload failed",t)}}};this.uploadFile=async(e,t={current:0,max:3})=>{let r=e.file;if(!r)throw new Error("Cannot upload a non-local file");let{files:s,token:o}=await this.endpointProvider.getEndpoints(),a=new FormData;a.append("file",r);try{let l=await this.ctx.environment.fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(l.ok)return this.ctx.internalEvents.emit(`fileUploaded:${e.id}`,e),this.ctx.internalEvents.emit("fileUploaded",e),this.ctx.log("info","File upload successful"),{success:!0};{let p=await l.text();return this.ctx.log("error","File upload failed",l.status,p),l.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${l.status} ${p}`}:(await new Promise(f=>setTimeout(f,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}}catch(l){return this.ctx.log("error","File upload failed",l),t.current>=t.max?{success:!1,error:l.message}:(await new Promise(p=>setTimeout(p,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}};this.getFile=async(e,t={current:0,max:3})=>{let{files:r,token:s}=await this.endpointProvider.getEndpoints();try{let o=await this.ctx.environment.fetch(r+`/${e}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});return o.ok?{success:!0,data:await o.json()}:(this.ctx.log("warn","File information fetch failed",r+`/${e}`,o.status,await o.text()),o.status<500&&o.status!==404||t.current>=t.max?{success:!1,error:`Failed to fetch file: ${o.status}`}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max})))}catch(o){return this.ctx.log("warn","File information fetch failed",`${r}/${e}`,o),t.current>=t.max?{success:!1,error:o.message}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max}))}};this.endpointProvider=e,this.ctx=t,this.addDispose(t.internalEvents.subscribe("fileAdded",this.onFileAdded))}};var ar=Symbol("handleMessage"),xc,Mt=class extends W{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,ctx:s}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[xc]=async(e,t)=>{let r=!1,s=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),s=!0,this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[a,l]of Object.entries(t.peerPresence))this.isSelf(e,l)?(this._self=l,this._selfReplicaIds.add(l.replicaId),s=!0,this.emit("selfChanged",l)):(r=!0,o.add(a),this._peers[a]=l,this.emit("peerChanged",a,l))}else if(t.type==="presence-offline"){o.delete(t.userId);let a=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,a)}r&&(this._peerIds=Array.from(o).sort(),this.emit("peersChanged",this._peers)),(r||s)&&this.emit("change")};this.update=async e=>{this._updateBatch.update({items:[{presence:e}]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self),this.emit("change")};this.flushPresenceUpdates=e=>{let t={presence:this.self.presence,internal:this.self.internal};for(let r of e)r.presence&&Object.assign(t.presence,r.presence),r.internal&&Object.assign(t.internal,r.internal);this.emit("update",t)};this.setViewId=e=>{this._updateBatch.update({items:[{internal:{viewId:e}}]}),this.self.internal.viewId=e,this.emit("selfChanged",this.self),this.emit("change")};this.setFieldId=(e,t=Date.now())=>{this._updateBatch.update({items:[{internal:{lastFieldId:e,lastFieldTimestamp:t}}]}),this.self.internal.lastFieldId=e,this.emit("selfChanged",this.self),this.emit("change")};this.getViewPeers=()=>this._peerIds.map(e=>this._peers[e]).filter(e=>this.self.internal.viewId===void 0||e.internal.viewId===this.self.internal.viewId);this.getFieldPeers=(e,t=60*1e3)=>this._peerIds.map(r=>this._peers[r]).filter(r=>r.internal.lastFieldId===e&&Date.now()-r.internal.lastFieldTimestamp<t);this.self.presence=e,this.self.profile=r,this.self.internal=bn,this.self.id="",this.self.replicaId="",s.waitForInitialization.then(()=>s.meta).then(o=>o.getLocalReplica()).then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new nt(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{xc=ar}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 yt=class extends W{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!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.nextBeat=null),this.deadline&&(clearTimeout(this.deadline),this.deadline=null)};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=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Qi=class extends W{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,ctx: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.ctx.log("debug","Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),s=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let o=await s.json(),a=Promise.all(o.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.ctx.log("error","Sync request failed",t,s.status),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let o=await s.json();br(o)&&(o.code===wt.TokenExpired?(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()):this.ctx.log("error","Server error",o)),s.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.ctx.log("error",t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.ctx.log("debug","Sending sync ack",e.ackThisNonce),await this.sendRequest([await(await this.ctx.meta).messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=Dr(e=>{this.sendRequest([e])},3e3);this.send=e=>{if(this.status!=="active"){this.ctx.log("warn","Attempted to send message while sync is not active",e);return}switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(this.ctx.log("debug","Starting push-pull sync"),await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await(await this.ctx.meta).messageCreator.createPresenceUpdate(this.presence.self),await(await this.ctx.meta).messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.ctx.log("warn","Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await(await this.ctx.meta).messageCreator.createSyncStep1()])};this.ctx=s,this.presence=t,this.endpointProvider=e,this.heartbeat=new yt({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get fetch(){return this.ctx.environment.fetch}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}stop(){this.ctx.log("debug","Stopping push-pull sync"),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 cr(i){this.message=i}cr.prototype=new Error,cr.prototype.name="InvalidCharacterError";var vo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var n=String(i).replace(/=+$/,"");if(n.length%4==1)throw new cr("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=n.charAt(s++);~t&&(e=r%4?64*e+t:t,r++%4)?o+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return o};function Sc(i){var n=i.replace(/-/g,"+").replace(/_/g,"/");switch(n.length%4){case 0:break;case 2:n+="==";break;case 3:n+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(vo(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(n)}catch{return vo(n)}}function qi(i){this.message=i}function Oc(i,n){if(typeof i!="string")throw new qi("Invalid token specified");var e=(n=n||{}).header===!0?0:1;try{return JSON.parse(Sc(i.split(".")[e]))}catch(t){throw new qi("Invalid token specified: "+t.message)}}qi.prototype=new Error,qi.prototype.name="InvalidTokenError";var xo=Oc;var Ji=class{constructor(n,e){this.config=n;this.ctx=e;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let n;if(this.config.fetchAuth)n=await this.config.fetchAuth();else{let a=this.ctx.environment.fetch;n=await a(this.config.authEndpoint,{credentials:"include"}).then(l=>{if(l.ok)return l.json();throw new Error(`Auth endpoint returned non-200 response: ${l.status}`)})}M(n.accessToken,"No access token provided from auth endpoint");let e=xo(n.accessToken);M(e.url,"No sync endpoint provided from auth endpoint"),M(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let s=t.toString(),o=e.file;if(!o){let a=new URL(r);a.pathname=a.pathname+"/files",o=a.toString()}return this.cached={http:r,websocket:s,files:o,token:n.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!n.authEndpoint&&!n.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Ue.Realtime}};var Gi=class extends W{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}},Yi=class{constructor(n,e,t){this.current=0;this.next=()=>{this.current=Math.min(this.max,Math.max(1,this.current)*this.factor)};this.reset=()=>{this.current=0};this.current=n,this.max=e,this.factor=t}};var Zi=class extends W{constructor({endpointProvider:e,ctx:t,presence:r}){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.heartbeat=new yt;this.reconnectScheduler=new Gi(new Yi(2e3,6e4,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.ctx.log("debug","Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.ctx.log("debug","Sync connected"),this.onOnlineChange(!0)};this.onOnlineChange=async e=>{if(this.ctx.log("info","Socket online change",e),!this.disposed&&!this.ctx.closing){if(!e)this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop();else{this.ctx.log("debug","Starting sync"),this.hasStartedSync=!0,this.synced=!1;let t=await this.ctx.meta;this.send(await t.messageCreator.createPresenceUpdate(this.presence.self)),this.send(await t.messageCreator.createSyncStep1()),this.heartbeat.start()}this.emit("onlineChange",e)}};this.onMessage=async e=>{if(this.reconnectScheduler.reset(),this._ignoreIncoming){this.ctx.log("warn","Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(this.ctx.log("debug","Received",t.type,"message"),t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await(await this.ctx.meta).messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.ctx.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",t),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",t);break;case"op-re":if(!this.synced){this.ctx.log("debug","Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.ctx.log("error","Sync socket error",e,e.target),!this.disposed&&(this.endpointProvider.clearCache(),this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync"))};this.onClose=e=>{this.ctx.log("info","Sync socket disconnected",e.code),this.onOnlineChange(!1),!this.disposed&&(this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync"))};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new this.ctx.environment.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(await this.ctx.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=>{if(this.status!=="active"){this.ctx.log("debug","Ignoring outgoing message",e.type,"sync is not active");return}if(!this.hasStartedSync&&!this.canSkipSyncWait(e)){this.ctx.log("debug","Ignoring outgoing message",e.type,"still waiting to begin initial sync");return}this.canSkipSyncWait(e)?this.socket?.readyState===Xi?(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.ctx.log("debug","Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===Xi&&(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.ctx.log("debug","Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))};this.sendDisconnecting=async(e="client-shutdown")=>this.send(await(await this.ctx.meta).messageCreator.createDisconnecting(e));this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await this.initializeSocket(),this._status="active")};this.stop=async()=>{await this.sendDisconnecting(),this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.removeEventListener("error",this.onError),this.socket?.removeEventListener("open",this.onOpen),this.socket?.readyState===Xi&&this.socket.close(),this.socket=null,this._status="paused"};this.ctx=t,this.endpointProvider=e,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat),window.addEventListener("beforeunload",()=>this.sendDisconnecting())}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===Xi}get status(){return this._status}},Xi=1;var en=class extends W{constructor(e){super();this.mode="pull";this.hasSynced=!1;this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new Mt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},bt=class extends W{constructor({authEndpoint:e,fetchAuth:t,initialPresence:r,automaticTransportSelection:s=!0,autoStart:o,initialTransport:a,pullInterval:l,presenceUpdateBatchTimeout:p,defaultProfile:f,useBroadcastChannel:S,onOutgoingMessage:w,EXPERIMENTAL_backgroundSync:A},{ctx:y,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this._hasSynced=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(!this.ctx.closing){if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.ctx.time.update(r.timestamp);switch(this.ctx.log("debug","sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await(await this.ctx.meta).setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await(await this.ctx.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(await this.ctx.meta).setGlobalAck(e.globalAckTimestamp),await(await this.ctx.meta).updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1),this._hasSynced=!0,this.emit("synced");break;case"need-since":this.emit("serverReset",e.since),(await this.ctx.files).onServerReset(e.since),this.activeSync.send(await(await this.ctx.meta).messageCreator.createSyncStep1(e.since));break;case"server-ack":await(await this.ctx.meta).updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[ar](await(await this.ctx.meta).getLocalReplica(),e)}};this.handleOnlineChange=async e=>{if(this.emit("onlineChange",e),e){let t=await(await this.ctx.files).listUnsynced(),r=await Promise.allSettled(t.map(s=>this.fileSync.uploadFile(s)));r.some(s=>s.status==="rejected")&&this.ctx.log("error","Failed to upload unsynced files",r.filter(s=>s.status==="rejected").map(s=>s.reason))}};this.handlePresenceUpdate=async e=>{this.send(await(await this.ctx.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 t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.ctx.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new U(U.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&yr(e,t),this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.ctx.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);if(await this.getSyncStartPromise(),this.activeSync.status==="paused")throw new U(U.Code.Offline,void 0,"Sync is not active");return this.fileSync.getFile(e)};this.getSyncStartPromise=(e=5e3)=>new Promise((t,r)=>{let s=setTimeout(()=>{r(new Error("Sync did not start in time")),o()},e),o=this.subscribe("onlineChange",a=>{a&&(clearTimeout(s),o(),t())})});this.start=()=>(this.ctx.log("info","Starting sync"),this.activeSync.start());this.stop=()=>(this.ctx.log("info","Stopping sync"),this.activeSync.stop());this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.onData=I,this.ctx=y,this.onOutgoingMessage=w,this.presence=new Mt({initialPresence:r,defaultProfile:f,updateBatchTimeout:p,ctx:y}),this.endpointProvider=new Ji({authEndpoint:e,fetchAuth:t},y),this.webSocketSync=new Zi({endpointProvider:this.endpointProvider,presence:this.presence,ctx:y}),this.pushPullSync=new Qi({endpointProvider:this.endpointProvider,presence:this.presence,interval:l,ctx:y}),this.fileSync=new Hi({endpointProvider:this.endpointProvider,ctx:y}),S&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${y.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),y.log("info","Sync initialized with transport:",a??"pull"),a==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),y.internalEvents.subscribe("outgoingSyncMessage",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),s&&this.canDoRealtime){let _=()=>{E&&clearTimeout(E);let F=this.presence.getViewPeers().length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;F&&this.mode==="pull"?this.setMode("realtime"):!F&&this.mode==="realtime"&&(E=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},E;this.presence.subscribe("peersChanged",_),s!=="peers-only"&&this.presence.subscribe("selfChanged",_)}o&&this.start(),A&&wo()}get canDoRealtime(){return this.endpointProvider.type===Ue.Realtime||this.endpointProvider.type===Ue.PassiveRealtime||this.endpointProvider.type===Ue.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get hasSynced(){return this._hasSynced}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 So(i){return i.operations.map(t=>t.timestamp).concat(i.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=ci(r);return s>t?s:t},1)}var tn=class extends W{constructor(e){super();this.contextInit=e;this.importingPromise=Promise.resolve();this.addData=async e=>{if(this.context.closing){this.context.log("warn","Client is closing; ignoring incoming sync data");return}await this.importingPromise;try{let t=e.reset?So(e):this.schema.version;return t<this.schema.version?(this.context.log("warn","Incoming reset sync data is from an old schema version",t,`(current ${this.schema.version})`),await this.import({data:{operations:e.operations,baselines:e.baselines??[],localReplica:void 0,schemaVersion:t},fileData:[],files:[]})):await this._entities.addData(e)}catch(t){throw this.context.log("critical","Sync failed. To avoid data corruption, the client will now shut down.",t),this.emit("developerError",new U(U.Code.Unexpected,t,"Sync failed. To avoid data corruption, the client will now shut down.")),await this.close(),t}};this.stats=async()=>{if(this.disposed)return{};let e=await(await this.context.documents).stats(),t=await(await this.context.meta).stats(),r=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=await(await this.context.files).stats(),o=Object.values(e).reduce((p,{size:f})=>p+f,0),a=t.baselinesSize.size+t.operationsSize.size,l=a/o;return{collections:e,meta:t,storage:r,totalMetaSize:a,totalCollectionsSize:o,metaToDataRatio:l,files:s,quotaUsage:r?.usage&&r?.quota?r.usage/r.quota:void 0}};this.close=async()=>{if(this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.context.closing=!0,this.context.closeLock&&await this.context.closeLock,await this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.persistenceShutdownHandler.shutdown(),this.context.internalEvents.disable(),this.context.entityEvents.disable(),typeof window<"u"){let e=window;e.__VERDANT_CLIENT__===this&&delete e.__VERDANT_CLIENT__}await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await bs(this.namespace,this.context.environment)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await(await this.context.meta).export(),{fileData:r,files:s}=await(await this.context.files).export(e);return{data:t,fileData:r,files:s}};this.import=async({data:e,fileData:t,files:r})=>{let s=()=>{};this.importingPromise=new Promise(o=>{s=o}),this.context.log("info","Importing data..."),await Rs(this.context,{data:e,files:r,fileData:t}),s()};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=async()=>(await this.context.files).cleanupDeletedFiles();this.__manualRebase=async()=>((await this.context.meta).manualRebase(),new Promise(e=>{let t=this.subscribe("rebase",()=>{t(),e()})}));this.context=new Si(this.contextInit),this.context.getClient=()=>this,this.collectionNames=Object.keys(this.context.schema.collections),this._sync=this.context.config.sync&&!this.context.schema.wip?new bt(this.context.config.sync,{onData:this.addData,ctx:this.context}):new en(this.context),this.context.schema.wip&&this.context.config.sync&&this.context.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 ji({sync:this.sync,context:this.context}),this._entities=new Li({ctx:this.context,files:this._fileManager}),this._queryCache=new Wi({context:this.context,evictionTime:this.context.config.queries?.evictionTime}),this._documentManager=new Oi(this.schema,this._entities);let t=Cr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",t),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.context.globalEvents.subscribe("operation",r=>{this.emit("operation",r)}),this.context.globalEvents.subscribe("rebase",()=>{this.emit("rebase")}),this.context.globalEvents.subscribe("fileSaved",r=>{this.emit("fileSaved",r)});for(let[r,s]of Object.entries(this.context.schema.collections)){let o=r;this[o]=new Ki({collection:o,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}typeof window<"u"&&(window.__VERDANT_CLIENT__=this)}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get queries(){return this._queryCache}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}async getReplicaId(){return(await(await this.context.meta).getLocalReplica()).id}get batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.documents,files:this.context.files}}get __persistenceReady(){return this.context.waitForInitialization}};var Ic={private:We.onlyMe(),public:void 0};function _c(i,{port:n=3242,initialPresence:e={}}={}){let t=localStorage.getItem("verdant-userId");return t||(t=`user-${Math.random().toString(36).slice(2)}`,localStorage.setItem("verdant-userId",t)),{defaultProfile:{id:t},initialPresence:e,authEndpoint:`http://localhost:${n}/auth/${i}?userId=${t}`}}var lr=Me(Je(),1);function Ec(i){return i?lr.default.slug():(0,lr.default)()}window.Verdant=dr;
17
+ `,i.ops),await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=zt(i),r=[],s=()=>this.ctx.time.now;return await Promise.all(Object.entries(t).map(async([o,a])=>{let p=(e??await this.entities.hydrate(K(o)))?.__getViewData__(o,"confirmed");if(!p){this.ctx.log("warn","could not find entity",o,"for undo operation",i);return}let f=ps(o,p.view,a,s);r.unshift(...f)})),r};this.ctx=e,this.entities=t,this.defaultBatchTimeout=i,this.batcher=new nt(this.flushOperations),this.batcher.add({key:kt,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===kt}};var Bi=class extends ce{constructor({ctx:e,files:t}){super();this.events={add:new ki.WeakEvent,replace:new ki.WeakEvent,resetAll:new ki.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.ctx.globalEvents.emit("resetToServer")})),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.empty=async()=>{await(await this.ctx.documents).reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await(await this.ctx.meta).reset(),await(await this.ctx.documents).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 t=e?.baselines??[],r=e?.operations??[];if(t.length===0&&r.length===0){this.ctx.log("debug","No data to process");return}this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let s=Array.from(new Set(t.map(f=>K(f.oid)).concat(r.map(f=>K(f.oid))))),o=Fr(t),a=Rr(r);this.ctx.log("debug","Applying data to live entities");for(let f of s){let S=o[f],w=a[f]??[],A=zt(w),y=e.reset?this.events.replace:this.events.add,I=this.pendingEntityPromises.get(f);I?(this.ctx.log("debug","Waiting for ongoing entity hydration",f),I.then(()=>{y.invoke(this,{oid:f,baselines:S,operations:A,isLocal:!1})})):(this.ctx.log("debug","Applying data to entity",f),y.invoke(this,{oid:f,baselines:S,operations:A,isLocal:!1}))}let l={abort:this.abortDataQueueController.signal};await(await this.ctx.meta).insertData(e,l),this.ctx.log("debug","Data processing complete, all data saved to metadata db.");let p=await Promise.all(s.map(async f=>await this.hydrate(f,l)??{oid:f,getSnapshot(){return null}}));try{this.ctx.log("debug","Saving entities to queryable storage"),await(await this.ctx.documents).saveEntities(p,l)}catch(f){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",f):this.ctx.log("error","Error saving entities to queryable storage",f)}};this.hydrate=async(e,t)=>{if(!Qt(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){let s=this.cache.get(e);if(s){let o=s.deref();if(o)return o.deleted?(this.ctx.log("debug","Cached entity is deleted",e),null):(this.ctx.log("debug","Using cached hydrated entity",e),o);this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for ongoing entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let s=this.constructEntity(e);if(!s)return this.ctx.log("warn","Entity schema not found, cannot construct",e),null;let o=this.loadEntity(s,t);return o.finally(()=>{this.pendingEntityPromises.delete(e),this.ctx.log("debug","Hydration complete",e)}),this.pendingEntityPromises.set(e,o),o}};this.destroy=async()=>{this.ctx.log("warn","Disposing EntityStore"),this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:s}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:o}=ne(t);Ht(e);let a=[],l=mt(e,a.push.bind(a));z(l,t);let{schema:p}=this.getCollectionSchema(o);if(!p)throw new Error(`Collection schema not found for ${o}`);let f=this.ctx.patchCreator.createInitialize(l,t,s);await this.batcher.commitOperations(f,{undoable:!!r});let S=await this.hydrate(t);if(!S)throw this.ctx.log("error","Failed to create entity; hydrated entity is null. Hopefully an error is logged above.",t),new U(U.Code.Unexpected,void 0,`Failed to create document ${t}`);return this.ctx.log("debug","Associating",a.length,"files to new entity",t),a.forEach(w=>this.files.add(w)),S};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),M(e.every(o=>o===K(o)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(o=>this.hydrate(o))),s=[];for(let o of r)if(o){let a=o.__getFamilyOids__(),l=this.ctx.patchCreator.createDeleteAll(a);for(let p of l)p.authz=o.access;s.push(...l),o.__markDeleting__()}await this.batcher.commitOperations(s,{undoable:t?.undoable===void 0?!0:t.undoable}),e.forEach(o=>{this.cache.delete(o),this.ctx.log("debug","Deleted document from cache",o)})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{M(!!e,"Cannot construct entity without OID");let{collection:t}=ne(e),{schema:r,readonlyKeys:s}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)return this.ctx.log("warn","Cannot hydrate entity after store has been disposed"),null;let o=new Ri({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new le({ctx:this.ctx,oid:e,schema:r,readonlyKeys:s,files:this.files,metadataFamily:o,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=K(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>(await this.loadEntityData(e,t),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e);this.loadEntityData=async(e,t)=>{let{operations:r,baselines:s}=await(await this.ctx.meta).getDocumentData(e.oid,t);return!s.length&&!Object.keys(r).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:s,operations:r,isLocal:!1}),e)};this.clearCache=()=>{this.ctx.log("debug","Emptying entity cache"),this.cache.clear()};this.ctx=e,this.files=t,this.batcher=new Fi({ctx:e,entities:this}),this.addDispose(this.ctx.internalEvents.subscribe("persistenceReset",this.clearCache))}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Mi=Symbol("entity-file-update"),Li=Symbol("entity-file-mark-failed"),dc,uc,Ee=class extends W{constructor(e,{downloadRemote:t=!1,ctx:r,fileContext:s}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this._uploaded=!1;this._alt=null;this.unsubscribes=[];this.setAlt=e=>{let t=this.fileContext.getFileRef();if(!t||t.id!==this.id)throw new Error("Cannot set alt text on a file which is no longer present");(t.alt??null)!==e&&this.fileContext.applyFileRef({...t,alt:e})};this.onContextChange=()=>{let e=this.fileContext.getFileRef()?.alt??null;e!==this._alt&&(this._alt=e,this.emitChange())};this[dc]=e=>{this.ctx.log("debug","EntityFile updated",this.id,e),this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&"revokeObjectURL"in URL&&URL.revokeObjectURL(this._objectUrl),this.ctx.log("debug","Creating object URL for file",this.id),this._objectUrl=URL.createObjectURL(e.file)),this.emitChange()};this[uc]=e=>{this._failed=!0,this._failedReason=e,this._loading=!1,this.emitChange()};this.onUploaded=e=>{this._fileData??=e,this._uploaded=!0,this.ctx.log("debug","File marked uploaded",this.id,this._fileData),this.emitChange()};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this.ctx=r,this.fileContext=s,this._downloadRemote=t,this._alt=s.getFileRef()?.alt??null,this.unsubscribes.push(s.subscribe(this.onContextChange)),this.unsubscribes.push(this.ctx.internalEvents.subscribe(`fileUploaded:${e}`,this.onUploaded))}static{dc=Mi,uc=Li}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._uploaded||this._fileData?.remote||!1}get error(){return this._failedReason||null}get alt(){return this._alt}emitChange(){this.fileContext.onChange(),this.emit("change")}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._fileData?.url??this._objectUrl??void 0,name:this.name??"unknown-file",remote:this._fileData?.remote??!1,type:this.type??"",file:this._fileData?.file,alt:this.alt}}};var ji=class extends ce{constructor({sync:e,context:t}){super();this.cache=new Map;this.fileData=new Map;this.add=async e=>{e.remote||this.updateFileData(e);let t=await(await this.context.files).add(e,{cloneRemote:!0});this.updateFileData(t)};this.get=(e,t)=>{let r=`${t.fileContext.oid}:${String(t.fileContext.key)}:${e}`,s=this.cache.get(r)?.deref();if(s)return s;this.cache.delete(r);let o=new Ee(e,t);this.cache.set(r,this.context.weakRef(o));let a=this.fileData.get(e)?.deref();return a?o[Mi](a):(this.fileData.delete(e),this.load(o)),o};this.updateFileData=e=>{this.fileData.set(e.id,this.context.weakRef(e));for(let[t,r]of this.cache){let s=r.deref();if(!s){this.cache.delete(t);continue}s.id===e.id&&s[Mi](e)}};this.load=async e=>{let t=await(await this.context.files).get(e.id);if(t&&this.updateFileData(t),!t?.url&&(!t||t.remote))try{if(this.sync.status!=="active"){this.context.log("info","Sync is not active, waiting for online to load file",e.id,e.name);let s=this.sync.subscribe("onlineChange",o=>{o&&(s(),this.load(e))});return}let r=await this.sync.getFile(e.id);if(r.success){let s={...r.data,...t,url:r.data.url};await(await this.context.files).update(s),this.updateFileData(r.data)}else this.context.log("error","Failed to load file",r),t||e[Li](r.error?.toString())}catch(r){this.context.log("error","Failed to load file",r),t||e[Li](r instanceof Error?r.message:String(r))}};this.onFileUploaded=async e=>{this.context.log("debug","Marking file as uploaded",e.id),(await this.context.files).onUploaded(e.id)};this.sync=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("fileUploaded",this.onFileUploaded))}};var ir=n=>Array.isArray(n)?n.map(ir):n instanceof le?n.getSnapshot():n;var nr=class{constructor(){this.queue=[];this.scheduled=!1;this.flush=()=>{let i=this.queue.splice(0,20);for(let{run:e,resolve:t,reject:r}of i)e().then(t,r);this.queue.length?setTimeout(this.flush,0):this.scheduled=!1}}enqueue(i){let e=new Promise((t,r)=>{this.queue.push({run:i,resolve:t,reject:r})});return this.scheduled||(this.scheduled=!0,queueMicrotask(this.flush)),e}},go=new WeakMap;function yo(n,i){let e=go.get(n);return e||(e=new nr,go.set(n,e)),e.enqueue(i)}function hc(n){return n!==null}function rr(n){return Array.isArray(n)?n.map(rr).filter(hc):n instanceof le&&n.deleted?null:n}function Ke(n,i){return!n&&!i||n&&i&&He(n)===He(i)}var sr=Symbol("ON_ALL_UNSUBSCRIBED"),ye=Symbol("UPDATE"),fc=50,pc,xe=class extends ce{constructor({initial:e,context:t,collection:r,key:s,shouldUpdate:o}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this._timing={sweep:null,hydration:null,total:null};this._startedAt=null;this._timingHistory=[];this._needsTrailingRevalidation=!1;this.revalidate=()=>{this._revalidationTimeout!==void 0?(this._needsTrailingRevalidation=!0,clearTimeout(this._revalidationTimeout)):this.execute(),this._revalidationTimeout=setTimeout(()=>{this._revalidationTimeout=void 0,this._needsTrailingRevalidation&&(this._needsTrailingRevalidation=!1,this.execute())},fc)};this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue);let t=rr(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((s,o)=>s===t[o])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof le&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof le&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>{let e=performance.now();return this._startedAt=Date.now(),this.context.log("debug","Executing query",this.key),this.status==="initial"?this.status="initializing":this.status==="ready"&&(this.status="revalidating"),this._executionPromise=yo(this.context,this.run).then(()=>this._value).catch(t=>{if(t instanceof Error){if(t.name==="InvalidStateError"||t.name==="InvalidAccessError")return this._value;throw t}else throw new Error("Unknown error executing query")}).finally(()=>{let t=performance.now()-e;this._timing.total=t,this._timingHistory=[...this._timingHistory,{startedAt:this._startedAt??Date.now(),...this._timing}].slice(-100),this.context.log("debug","Query executed",this.key,`Duration: ${t}ms`)}),this._executionPromise};this.measureSweep=async e=>{let t=performance.now();try{return await e()}finally{this._timing.sweep=performance.now()-t}};this.measureHydration=async e=>{let t=performance.now();try{return await e()}finally{this._timing.hydration=performance.now()-t}};this.getDiagnostic=e=>({key:this.key,startedAt:this._startedAt,collection:this.collection,type:this.type,status:this.status,active:e,result:ir(this.current),timing:{...this._timing},runs:this._timingHistory.map(t=>({...t}))});this[pc]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new W(l=>{l==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=s,this.collection=r,this.type=this.constructor.name,this.addDispose(()=>clearTimeout(this._revalidationTimeout));let a=o||(l=>l.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",l=>{a(l)&&this.revalidate()}))}static{pc=sr}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}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}get __rawValue(){return this._rawValue}};var mc,Ni=class extends xe{constructor({index:e,hydrate:t,limit:r,...s}){super({initial:[],...s});this.run=async()=>{let{result:e}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,index:this.index,limit:this.limit}));this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await this.measureHydration(()=>Promise.all(e.map(this.hydrate))))};this[mc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.limit=r,this.index=e,this.hydrate=t}static{mc=ye}};var gc,Vi=class extends xe{constructor({hydrate:e,pageSize:t,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,limit:this._pageSize*this._upToPage,offset:0,index:this.index}));this._hasNextPage=t,this.setValue(await this.measureHydration(()=>Promise.all(e.map(this.hydrate))))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index}));this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await this.measureHydration(()=>Promise.all(e.map(this.hydrate)))])};this[gc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{gc=ye}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var yc,Ui=class extends xe{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.measureSweep(async()=>(await this.context.documents).findOneOid({collection:this.collection,index:this.index}));this.setValue(e?await this.measureHydration(()=>this.hydrate(e)):null)};this[yc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{yc=ye}};var bc,zi=class extends xe{constructor({index:e,hydrate:t,pageSize:r,page:s,...o}){super({initial:[],...o});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await this.measureSweep(async()=>(await this.context.documents).findAllOids({collection:this.collection,index:this.index,limit:this._pageSize,offset:this._page*this._pageSize}));this._hasNextPage=t,this.setValue(await this.measureHydration(()=>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[bc]=e=>{Ke(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=s}static{bc=ye}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var $i=class extends xe{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.measureHydration(()=>this.hydrate(this.oid));this.setValue(e)};this.oid=ee(r.collection,e),this.hydrate=t}};var Ki=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:s}){this.serializeIndex=i=>i?He(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new $i({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Ui({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[ye](i)})};this.findAll=({index:i,key:e,limit:t}={})=>{let r=e||`findAll:${this.collection}:${t}:${this.serializeIndex(i)}`;return this.cache.getOrSet(r,()=>new Ni({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,limit:t}),s=>{s[ye](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(s,()=>new zi({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:t}),o=>{o[ye](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new Vi({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ye](i)})};this.cache=e,this.collection=i,this.hydrate=t.hydrate,this.context=r,this.documentManager=s,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var Wi=class extends ce{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this._holds=new Set;this._inactiveDiagnostics=new Map;this.enqueueQueryEviction=e=>{setTimeout(()=>{if(!e.subscribed){if(this._holds.has(e.key)){this.context.log("debug","QueryCache: keepAlive hold on query preserves after unsubscribe",e.key);return}this._cache.get(e.key)===e&&(this._cache.delete(e.key),this._inactiveDiagnostics.set(e.key,e.getDiagnostic(!1)),this.context.log("debug","QueryCache: evicted query",e.key))}},this._evictionTime)};this.dropAll=()=>{this.context.log("debug","QueryCache: drop all",this._cache.size,"queries"),this._cache.forEach(e=>{this._inactiveDiagnostics.set(e.key,e.getDiagnostic(!1)),e.dispose()}),this._cache.clear()};this.forceRefreshAll=()=>{this.context.log("debug","QueryCache: force refresh all",this._cache.size,"queries"),this._cache.forEach(e=>e.execute())};this._evictionTime=e,this.context=t,this.addDispose(this.context.internalEvents.subscribe("persistenceReset",this.forceRefreshAll))}get activeKeys(){return Array.from(this._cache.keys())}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),this._inactiveDiagnostics.delete(e.key),e[sr](this.enqueueQueryEviction),this.enqueueQueryEviction(e),e}get diagnostics(){return{queries:[...this._cache.values().map(e=>e.getDiagnostic(!0)),...this._inactiveDiagnostics.values()]}}getOrSet(e,t,r){let s=this.get(e);return s?(r?.(s),s):(this.context.log("debug","QueryCache: creating new query",e),this.set(t()))}keepAlive(e){this._holds.add(e),this.context.log("debug","QueryCache: keepAlive",e)}dropKeepAlive(e){this._holds.delete(e);let t=this.get(e);t&&(t.subscribed||(this.context.log("debug","QueryCache: dropKeepAlive on unsubscribed query; queuing eviction",e),this.enqueueQueryEviction(t)))}get keepAlives(){return this._holds}};async function bo(){try{let n=await navigator.permissions.query({name:"periodic-background-sync"});if(n.state==="granted"){let i=await navigator.serviceWorker.ready;if("periodicSync"in i)try{await i.periodicSync.register("verdant-sync",{minInterval:24*60*60*1e3})}catch(e){console.warn("Failed to register background sync:",e)}}else console.debug("Background sync permission is not granted:",n)}catch(n){console.error("Failed to initiate background sync:",n)}}var Hi=class extends ce{constructor({endpointProvider:e,ctx:t}){super();this.onFileAdded=async e=>{if(!e.remote){this.ctx.log("debug","Uploading file",e.id,e.name);try{await this.uploadFile(e)}catch(t){this.ctx.log("error","File upload failed",t)}}};this.uploadFile=async(e,t={current:0,max:3})=>{let r=e.file;if(!r)throw new Error("Cannot upload a non-local file");let{files:s,token:o}=await this.endpointProvider.getEndpoints(),a=new FormData;a.append("file",r);try{let l=await this.ctx.environment.fetch(s+`/${e.id}`,{method:"POST",body:a,credentials:"include",headers:{Authorization:`Bearer ${o}`}});if(l.ok)return this.ctx.internalEvents.emit(`fileUploaded:${e.id}`,e),this.ctx.internalEvents.emit("fileUploaded",e),this.ctx.log("info","File upload successful"),{success:!0};{let p=await l.text();return this.ctx.log("error","File upload failed",l.status,p),l.status<500||t.current>=t.max?{success:!1,error:`Failed to upload file: ${l.status} ${p}`}:(await new Promise(f=>setTimeout(f,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}}catch(l){return this.ctx.log("error","File upload failed",l),t.current>=t.max?{success:!1,error:l.message}:(await new Promise(p=>setTimeout(p,1e3)),this.uploadFile(e,{max:t.max,current:t.current+1}))}};this.getFile=async(e,t={current:0,max:3})=>{let{files:r,token:s}=await this.endpointProvider.getEndpoints();try{let o=await this.ctx.environment.fetch(r+`/${e}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${s}`}});return o.ok?{success:!0,data:await o.json()}:(this.ctx.log("warn","File information fetch failed",r+`/${e}`,o.status,await o.text()),o.status<500&&o.status!==404||t.current>=t.max?{success:!1,error:`Failed to fetch file: ${o.status}`}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max})))}catch(o){return this.ctx.log("warn","File information fetch failed",`${r}/${e}`,o),t.current>=t.max?{success:!1,error:o.message}:(await new Promise(a=>setTimeout(a,1e3)),this.getFile(e,{current:t.current+1,max:t.max}))}};this.endpointProvider=e,this.ctx=t,this.addDispose(t.internalEvents.subscribe("fileAdded",this.onFileAdded))}};var or=Symbol("handleMessage"),wc,Bt=class extends W{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,ctx:s}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[wc]=async(e,t)=>{let r=!1,s=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),s=!0,this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[a,l]of Object.entries(t.peerPresence))this.isSelf(e,l)?(this._self=l,this._selfReplicaIds.add(l.replicaId),s=!0,this.emit("selfChanged",l)):(r=!0,o.add(a),this._peers[a]=l,this.emit("peerChanged",a,l))}else if(t.type==="presence-offline"){o.delete(t.userId);let a=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,a)}r&&(this._peerIds=Array.from(o).sort(),this.emit("peersChanged",this._peers)),(r||s)&&this.emit("change")};this.update=async e=>{this._updateBatch.update({items:[{presence:e}]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self),this.emit("change")};this.flushPresenceUpdates=e=>{let t={presence:this.self.presence,internal:this.self.internal};for(let r of e)r.presence&&Object.assign(t.presence,r.presence),r.internal&&Object.assign(t.internal,r.internal);this.emit("update",t)};this.setViewId=e=>{this._updateBatch.update({items:[{internal:{viewId:e}}]}),this.self.internal.viewId=e,this.emit("selfChanged",this.self),this.emit("change")};this.setFieldId=(e,t=Date.now())=>{this._updateBatch.update({items:[{internal:{lastFieldId:e,lastFieldTimestamp:t}}]}),this.self.internal.lastFieldId=e,this.emit("selfChanged",this.self),this.emit("change")};this.getViewPeers=()=>this._peerIds.map(e=>this._peers[e]).filter(e=>this.self.internal.viewId===void 0||e.internal.viewId===this.self.internal.viewId);this.getFieldPeers=(e,t=60*1e3)=>this._peerIds.map(r=>this._peers[r]).filter(r=>r.internal.lastFieldId===e&&Date.now()-r.internal.lastFieldTimestamp<t);this.self.presence=e,this.self.profile=r,this.self.internal=bn,this.self.id="",this.self.replicaId="",s.waitForInitialization.then(()=>s.meta).then(o=>o.getLocalReplica()).then(o=>{this.self.replicaId=o.id}),this._updateBatcher=new nt(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{wc=or}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 gt=class extends W{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!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.nextBeat=null),this.deadline&&(clearTimeout(this.deadline),this.deadline=null)};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=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Qi=class extends W{constructor({endpointProvider:e,presence:t,interval:r=15*1e3,ctx: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.ctx.log("debug","Sending sync request",e);try{let{http:t,token:r}=await this.endpointProvider.getEndpoints(),s=await this.fetch(t,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let o=await s.json(),a=Promise.all(o.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.ctx.log("error","Sync request failed",t,s.status),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let o=await s.json();yr(o)&&(o.code===bt.TokenExpired?(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()):this.ctx.log("error","Server error",o)),s.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.ctx.log("error",t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.ctx.log("debug","Sending sync ack",e.ackThisNonce),await this.sendRequest([await(await this.ctx.meta).messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=Cr(e=>{this.sendRequest([e])},3e3);this.send=e=>{if(this.status!=="active"){this.ctx.log("warn","Attempted to send message while sync is not active",e);return}switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(this.ctx.log("debug","Starting push-pull sync"),await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await(await this.ctx.meta).messageCreator.createPresenceUpdate(this.presence.self),await(await this.ctx.meta).messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.ctx.log("warn","Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await(await this.ctx.meta).messageCreator.createSyncStep1()])};this.ctx=s,this.presence=t,this.endpointProvider=e,this.heartbeat=new gt({interval:r}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get fetch(){return this.ctx.environment.fetch}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}stop(){this.ctx.log("debug","Stopping push-pull sync"),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 ar(n){this.message=n}ar.prototype=new Error,ar.prototype.name="InvalidCharacterError";var wo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new ar("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,s=0,o="";t=i.charAt(s++);~t&&(e=r%4?64*e+t:t,r++%4)?o+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return o};function vc(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(wo(e).replace(/(.)/g,function(t,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(i)}catch{return wo(i)}}function qi(n){this.message=n}function xc(n,i){if(typeof n!="string")throw new qi("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(vc(n.split(".")[e]))}catch(t){throw new qi("Invalid token specified: "+t.message)}}qi.prototype=new Error,qi.prototype.name="InvalidTokenError";var vo=xc;var Ji=class{constructor(i,e){this.config=i;this.ctx=e;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;if(this.config.fetchAuth)i=await this.config.fetchAuth();else{let a=this.ctx.environment.fetch;i=await a(this.config.authEndpoint,{credentials:"include"}).then(l=>{if(l.ok)return l.json();throw new Error(`Auth endpoint returned non-200 response: ${l.status}`)})}M(i.accessToken,"No access token provided from auth endpoint");let e=vo(i.accessToken);M(e.url,"No sync endpoint provided from auth endpoint"),M(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let s=t.toString(),o=e.file;if(!o){let a=new URL(r);a.pathname=a.pathname+"/files",o=a.toString()}return this.cached={http:r,websocket:s,files:o,token:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Ue.Realtime}};var Gi=class extends W{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}},Yi=class{constructor(i,e,t){this.current=0;this.next=()=>{this.current=Math.min(this.max,Math.max(1,this.current)*this.factor)};this.reset=()=>{this.current=0};this.current=i,this.max=e,this.factor=t}};var Zi=class extends W{constructor({endpointProvider:e,ctx:t,presence:r}){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.heartbeat=new gt;this.reconnectScheduler=new Gi(new Yi(2e3,6e4,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.ctx.log("debug","Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.ctx.log("debug","Sync connected"),this.onOnlineChange(!0)};this.onOnlineChange=async e=>{if(this.ctx.log("info","Socket online change",e),!this.disposed&&!this.ctx.closing){if(!e)this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop();else{this.ctx.log("debug","Starting sync"),this.hasStartedSync=!0,this.synced=!1;let t=await this.ctx.meta;this.send(await t.messageCreator.createPresenceUpdate(this.presence.self)),this.send(await t.messageCreator.createSyncStep1()),this.heartbeat.start()}this.emit("onlineChange",e)}};this.onMessage=async e=>{if(this.reconnectScheduler.reset(),this._ignoreIncoming){this.ctx.log("warn","Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(this.ctx.log("debug","Received",t.type,"message"),t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await(await this.ctx.meta).messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.ctx.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",t),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",t);break;case"op-re":if(!this.synced){this.ctx.log("debug","Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.ctx.log("error","Sync socket error",e,e.target),!this.disposed&&(this.endpointProvider.clearCache(),this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync"))};this.onClose=e=>{this.ctx.log("info","Sync socket disconnected",e.code),this.onOnlineChange(!1),!this.disposed&&(this.reconnectScheduler.next(),this.ctx.log("info","Attempting reconnect to websocket sync"))};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new this.ctx.environment.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(await this.ctx.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=>{if(this.status!=="active"){this.ctx.log("debug","Ignoring outgoing message",e.type,"sync is not active");return}if(!this.hasStartedSync&&!this.canSkipSyncWait(e)){this.ctx.log("debug","Ignoring outgoing message",e.type,"still waiting to begin initial sync");return}this.canSkipSyncWait(e)?this.socket?.readyState===Xi?(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.ctx.log("debug","Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===Xi&&(this.ctx.log("debug","Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.ctx.log("debug","Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))};this.sendDisconnecting=async(e="client-shutdown")=>this.send(await(await this.ctx.meta).messageCreator.createDisconnecting(e));this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await this.initializeSocket(),this._status="active")};this.stop=async()=>{await this.sendDisconnecting(),this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.removeEventListener("error",this.onError),this.socket?.removeEventListener("open",this.onOpen),this.socket?.readyState===Xi&&this.socket.close(),this.socket=null,this._status="paused"};this.ctx=t,this.endpointProvider=e,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat),window.addEventListener("beforeunload",()=>this.sendDisconnecting())}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===Xi}get status(){return this._status}},Xi=1;var en=class extends W{constructor(e){super();this.mode="pull";this.hasSynced=!1;this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,error:"Sync is not active"});this.syncOnce=async()=>{};this.presence=new Bt({initialPresence:null,defaultProfile:null,ctx:e})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},yt=class extends W{constructor({authEndpoint:e,fetchAuth:t,initialPresence:r,automaticTransportSelection:s=!0,autoStart:o,initialTransport:a,pullInterval:l,presenceUpdateBatchTimeout:p,defaultProfile:f,useBroadcastChannel:S,onOutgoingMessage:w,EXPERIMENTAL_backgroundSync:A},{ctx:y,onData:I}){super();this.broadcastChannel=null;this._activelySyncing=!1;this._hasSynced=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:t}={source:"network"})=>{if(!this.ctx.closing){if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.ctx.time.update(r.timestamp);switch(this.ctx.log("debug","sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await(await this.ctx.meta).setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await(await this.ctx.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(await this.ctx.meta).setGlobalAck(e.globalAckTimestamp),await(await this.ctx.meta).updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1),this._hasSynced=!0,this.emit("synced");break;case"need-since":this.emit("serverReset",e.since),(await this.ctx.files).onServerReset(e.since),this.activeSync.send(await(await this.ctx.meta).messageCreator.createSyncStep1(e.since));break;case"server-ack":await(await this.ctx.meta).updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[or](await(await this.ctx.meta).getLocalReplica(),e)}};this.handleOnlineChange=async e=>{if(this.emit("onlineChange",e),e){let t=await(await this.ctx.files).listUnsynced(),r=await Promise.allSettled(t.map(s=>this.fileSync.uploadFile(s)));r.some(s=>s.status==="rejected")&&this.ctx.log("error","Failed to upload unsynced files",r.filter(s=>s.status==="rejected").map(s=>s.reason))}};this.handlePresenceUpdate=async e=>{this.send(await(await this.ctx.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 t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.ctx.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new U(U.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&gr(e,t),this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.ctx.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);if(await this.getSyncStartPromise(),this.activeSync.status==="paused")throw new U(U.Code.Offline,void 0,"Sync is not active");return this.fileSync.getFile(e)};this.getSyncStartPromise=(e=5e3)=>new Promise((t,r)=>{let s=setTimeout(()=>{r(new Error("Sync did not start in time")),o()},e),o=this.subscribe("onlineChange",a=>{a&&(clearTimeout(s),o(),t())})});this.start=()=>(this.ctx.log("info","Starting sync"),this.activeSync.start());this.stop=()=>(this.ctx.log("info","Stopping sync"),this.activeSync.stop());this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.onData=I,this.ctx=y,this.onOutgoingMessage=w,this.presence=new Bt({initialPresence:r,defaultProfile:f,updateBatchTimeout:p,ctx:y}),this.endpointProvider=new Ji({authEndpoint:e,fetchAuth:t},y),this.webSocketSync=new Zi({endpointProvider:this.endpointProvider,presence:this.presence,ctx:y}),this.pushPullSync=new Qi({endpointProvider:this.endpointProvider,presence:this.presence,interval:l,ctx:y}),this.fileSync=new Hi({endpointProvider:this.endpointProvider,ctx:y}),S&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${y.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),y.log("info","Sync initialized with transport:",a??"pull"),a==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),y.internalEvents.subscribe("outgoingSyncMessage",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),s&&this.canDoRealtime){let _=()=>{E&&clearTimeout(E);let F=this.presence.getViewPeers().length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;F&&this.mode==="pull"?this.setMode("realtime"):!F&&this.mode==="realtime"&&(E=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},E;this.presence.subscribe("peersChanged",_),s!=="peers-only"&&this.presence.subscribe("selfChanged",_)}o&&this.start(),A&&bo()}get canDoRealtime(){return this.endpointProvider.type===Ue.Realtime||this.endpointProvider.type===Ue.PassiveRealtime||this.endpointProvider.type===Ue.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get hasSynced(){return this._hasSynced}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 xo(n){return n.operations.map(t=>t.timestamp).concat(n.baselines?.map(t=>t.timestamp)??[]).reduce((t,r)=>{let s=ai(r);return s>t?s:t},1)}var tn=class extends W{constructor(e){super();this.contextInit=e;this.importingPromise=Promise.resolve();this.addData=async e=>{if(this.context.closing){this.context.log("warn","Client is closing; ignoring incoming sync data");return}await this.importingPromise;try{let t=e.reset?xo(e):this.schema.version;return t<this.schema.version?(this.context.log("warn","Incoming reset sync data is from an old schema version",t,`(current ${this.schema.version})`),await this.import({data:{operations:e.operations,baselines:e.baselines??[],localReplica:void 0,schemaVersion:t},fileData:[],files:[]})):await this._entities.addData(e)}catch(t){throw this.context.log("critical","Sync failed. To avoid data corruption, the client will now shut down.",t),this.emit("developerError",new U(U.Code.Unexpected,t,"Sync failed. To avoid data corruption, the client will now shut down.")),await this.close(),t}};this.stats=async()=>{if(this.disposed)return{};let e=await(await this.context.documents).stats(),t=await(await this.context.meta).stats(),r=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=await(await this.context.files).stats(),o=Object.values(e).reduce((p,{size:f})=>p+f,0),a=t.baselinesSize.size+t.operationsSize.size,l=a/o;return{collections:e,meta:t,storage:r,totalMetaSize:a,totalCollectionsSize:o,metaToDataRatio:l,files:s,quotaUsage:r?.usage&&r?.quota?r.usage/r.quota:void 0}};this.close=async()=>{if(this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this.context.closing=!0,this.context.closeLock&&await this.context.closeLock,await this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.context.persistenceShutdownHandler.shutdown(),this.context.internalEvents.disable(),this.context.entityEvents.disable(),typeof window<"u"){let e=window;e.__VERDANT_CLIENT__===this&&delete e.__VERDANT_CLIENT__}await new Promise(e=>{e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await ys(this.namespace,this.context.environment)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await(await this.context.meta).export(),{fileData:r,files:s}=await(await this.context.files).export(e);return{data:t,fileData:r,files:s}};this.import=async({data:e,fileData:t,files:r})=>{let s=()=>{};this.importingPromise=new Promise(o=>{s=o}),this.context.log("info","Importing data..."),await Ts(this.context,{data:e,files:r,fileData:t}),s()};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=async()=>(await this.context.files).cleanupDeletedFiles();this.__manualRebase=async()=>((await this.context.meta).manualRebase(),new Promise(e=>{let t=this.subscribe("rebase",()=>{t(),e()})}));this.context=new xi(this.contextInit),this.context.getClient=()=>this,this.collectionNames=Object.keys(this.context.schema.collections),this._sync=this.context.config.sync&&!this.context.schema.wip?new yt(this.context.config.sync,{onData:this.addData,ctx:this.context}):new en(this.context),this.context.schema.wip&&this.context.config.sync&&this.context.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 ji({sync:this.sync,context:this.context}),this._entities=new Bi({ctx:this.context,files:this._fileManager}),this._queryCache=new Wi({context:this.context,evictionTime:this.context.config.queries?.evictionTime}),this._documentManager=new Si(this.schema,this._entities);let t=Pr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",t),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.context.globalEvents.subscribe("operation",r=>{this.emit("operation",r)}),this.context.globalEvents.subscribe("rebase",()=>{this.emit("rebase")}),this.context.globalEvents.subscribe("fileSaved",r=>{this.emit("fileSaved",r)});for(let[r,s]of Object.entries(this.context.schema.collections)){let o=r;this[o]=new Ki({collection:o,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}typeof window<"u"&&(window.__VERDANT_CLIENT__=this)}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get queries(){return this._queryCache}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}async getReplicaId(){return(await(await this.context.meta).getLocalReplica()).id}get batch(){return this.entities.batch}get __persistence(){return{meta:this.context.meta,queries:this.context.documents,files:this.context.files}}get __persistenceReady(){return this.context.waitForInitialization}};var Sc={private:We.onlyMe(),public:void 0};function Oc(n,{port:i=3242,initialPresence:e={}}={}){let t=localStorage.getItem("verdant-userId");return t||(t=`user-${Math.random().toString(36).slice(2)}`,localStorage.setItem("verdant-userId",t)),{defaultProfile:{id:t},initialPresence:e,authEndpoint:`http://localhost:${i}/auth/${n}?userId=${t}`}}var cr=Me(Je(),1);function Ic(n){return n?cr.default.slug():(0,cr.default)()}window.Verdant=lr;
18
18
  //# sourceMappingURL=index.js.map