@verdant-web/store 2.7.1 → 2.7.2

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,17 +1,17 @@
1
- "use strict";var ar=Object.create;var vn=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var dr=Object.getPrototypeOf,ur=Object.prototype.hasOwnProperty;var $e=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),pr=(i,t)=>{for(var e in t)vn(i,e,{get:t[e],enumerable:!0})},fr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of lr(t))!ur.call(i,r)&&r!==e&&vn(i,r,{get:()=>t[r],enumerable:!(n=cr(t,r))||n.enumerable});return i};var ut=(i,t,e)=>(e=i!=null?ar(dr(i)):{},fr(t||!i||!i.__esModule?vn(e,"default",{value:i,enumerable:!0}):e,i));var Sn=$e((Ps,si)=>{si.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ai=$e((_s,oi)=>{var hr=Sn(),mr=typeof window=="object"?window:self,yr=Object.keys(mr).length,gr=navigator.mimeTypes?navigator.mimeTypes.length:0,br=hr((gr+navigator.userAgent.length).toString(36)+yr.toString(36),4);oi.exports=function(){return br}});var ui=$e((Ts,di)=>{var xn,ci=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ci?(li=Math.pow(2,32)-1,xn=function(){return Math.abs(ci.getRandomValues(new Uint32Array(1))[0]/li)}):xn=Math.random;var li;di.exports=xn});var ht=$e((As,mi)=>{var pt=ai(),pi=Sn(),wr=ui(),qe=0,In=4,ft=36,fi=Math.pow(ft,In);function On(){return pi((wr()*fi<<0).toString(ft),In)}function hi(){return qe=qe<fi?qe:0,qe++,qe-1}function We(){var i="c",t=new Date().getTime().toString(ft),e=pi(hi().toString(ft),In),n=pt(),r=On()+On();return i+t+e+n+r}We.slug=function(){var t=new Date().getTime().toString(36),e=hi().toString(36).slice(-4),n=pt().slice(0,1)+pt().slice(-1),r=On().slice(-2);return t.slice(-2)+e+n+r};We.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};We.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};We.fingerprint=pt;mi.exports=We});var Ti=$e((Pi,_i)=>{(function(i){var t;typeof Pi=="object"?_i.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(l,f){if(!e[l]){if(!t[l]){var h=typeof require=="function"&&require;if(!f&&h)return h(l,!0);if(s)return s(l,!0);throw new Error("Cannot find module '"+l+"'")}f=e[l]={exports:{}},t[l][0].call(f.exports,function(v){var E=t[l][1][v];return r(E||v)},f,f.exports,i,t,e,n)}return e[l].exports}for(var s=typeof require=="function"&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){"use strict";var b=i("crypto");function P(y,I){I=C(y,I);var d;return(d=I.algorithm!=="passthrough"?b.createHash(I.algorithm):new A).write===void 0&&(d.write=d.update,d.end=d.update),S(I,d).dispatch(y),d.update||d.end(""),d.digest?d.digest(I.encoding==="buffer"?void 0:I.encoding):(y=d.read(),I.encoding!=="buffer"?y.toString(I.encoding):y)}(e=t.exports=P).sha1=function(y){return P(y)},e.keys=function(y){return P(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return P(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return P(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var g=b.getHashes?b.getHashes().slice():["sha1","md5"],O=(g.push("passthrough"),["buffer","hex","binary","base64"]);function C(y,I){var d={};if(d.algorithm=(I=I||{}).algorithm||"sha1",d.encoding=I.encoding||"hex",d.excludeValues=!!I.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=I.ignoreUnknown===!0,d.respectType=I.respectType!==!1,d.respectFunctionNames=I.respectFunctionNames!==!1,d.respectFunctionProperties=I.respectFunctionProperties!==!1,d.unorderedArrays=I.unorderedArrays===!0,d.unorderedSets=I.unorderedSets!==!1,d.unorderedObjects=I.unorderedObjects!==!1,d.replacer=I.replacer||void 0,d.excludeKeys=I.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var p=0;p<g.length;++p)g[p].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=g[p]);if(g.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+g.join(", "));if(O.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+O.join(", "));return d}function x(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function S(y,I,d){d=d||[];function p(c){return I.update?I.update(c,"utf8"):I.write(c,"utf8")}return{dispatch:function(c){return this["_"+((c=y.replacer?y.replacer(c):c)===null?"null":typeof c)](c)},_object:function(c){var w,D=Object.prototype.toString.call(c),F=/\[object (.*)\]/i.exec(D);if(F=(F=F?F[1]:"unknown:["+D+"]").toLowerCase(),0<=(D=d.indexOf(c)))return this.dispatch("[CIRCULAR:"+D+"]");if(d.push(c),s!==void 0&&s.isBuffer&&s.isBuffer(c))return p("buffer:"),p(c);if(F==="object"||F==="function"||F==="asyncfunction")return D=Object.keys(c),y.unorderedObjects&&(D=D.sort()),y.respectType===!1||x(c)||D.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(D=D.filter(function(R){return!y.excludeKeys(R)})),p("object:"+D.length+":"),w=this,D.forEach(function(R){w.dispatch(R),p(":"),y.excludeValues||w.dispatch(c[R]),p(",")});if(!this["_"+F]){if(y.ignoreUnknown)return p("["+F+"]");throw new Error('Unknown object type "'+F+'"')}this["_"+F](c)},_array:function(c,R){R=R!==void 0?R:y.unorderedArrays!==!1;var D=this;if(p("array:"+c.length+":"),!R||c.length<=1)return c.forEach(function(j){return D.dispatch(j)});var F=[],R=c.map(function(j){var B=new A,q=d.slice();return S(y,B,q).dispatch(j),F=F.concat(q.slice(d.length)),B.read().toString()});return d=d.concat(F),R.sort(),this._array(R,!1)},_date:function(c){return p("date:"+c.toJSON())},_symbol:function(c){return p("symbol:"+c.toString())},_error:function(c){return p("error:"+c.toString())},_boolean:function(c){return p("bool:"+c.toString())},_string:function(c){p("string:"+c.length+":"),p(c.toString())},_function:function(c){p("fn:"),x(c)?this.dispatch("[native]"):this.dispatch(c.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(c.name)),y.respectFunctionProperties&&this._object(c)},_number:function(c){return p("number:"+c.toString())},_xml:function(c){return p("xml:"+c.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(c){return p("regex:"+c.toString())},_uint8array:function(c){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint8clampedarray:function(c){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(c))},_int8array:function(c){return p("int8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint16array:function(c){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(c))},_int16array:function(c){return p("int16array:"),this.dispatch(Array.prototype.slice.call(c))},_uint32array:function(c){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(c))},_int32array:function(c){return p("int32array:"),this.dispatch(Array.prototype.slice.call(c))},_float32array:function(c){return p("float32array:"),this.dispatch(Array.prototype.slice.call(c))},_float64array:function(c){return p("float64array:"),this.dispatch(Array.prototype.slice.call(c))},_arraybuffer:function(c){return p("arraybuffer:"),this.dispatch(new Uint8Array(c))},_url:function(c){return p("url:"+c.toString())},_map:function(c){return p("map:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_set:function(c){return p("set:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_file:function(c){return p("file:"),this.dispatch([c.name,c.size,c.type,c.lastModfied])},_blob:function(){if(y.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
1
+ "use strict";var cr=Object.create;var vn=Object.defineProperty;var lr=Object.getOwnPropertyDescriptor;var dr=Object.getOwnPropertyNames;var ur=Object.getPrototypeOf,fr=Object.prototype.hasOwnProperty;var $e=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),pr=(i,t)=>{for(var e in t)vn(i,e,{get:t[e],enumerable:!0})},hr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of dr(t))!fr.call(i,r)&&r!==e&&vn(i,r,{get:()=>t[r],enumerable:!(n=lr(t,r))||n.enumerable});return i};var ut=(i,t,e)=>(e=i!=null?cr(ur(i)):{},hr(t||!i||!i.__esModule?vn(e,"default",{value:i,enumerable:!0}):e,i));var Sn=$e((_s,si)=>{si.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ai=$e((Ts,oi)=>{var mr=Sn(),yr=typeof window=="object"?window:self,gr=Object.keys(yr).length,br=navigator.mimeTypes?navigator.mimeTypes.length:0,wr=mr((br+navigator.userAgent.length).toString(36)+gr.toString(36),4);oi.exports=function(){return wr}});var ui=$e((As,di)=>{var xn,ci=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ci?(li=Math.pow(2,32)-1,xn=function(){return Math.abs(ci.getRandomValues(new Uint32Array(1))[0]/li)}):xn=Math.random;var li;di.exports=xn});var ht=$e((Bs,mi)=>{var ft=ai(),fi=Sn(),vr=ui(),qe=0,In=4,pt=36,pi=Math.pow(pt,In);function On(){return fi((vr()*pi<<0).toString(pt),In)}function hi(){return qe=qe<pi?qe:0,qe++,qe-1}function We(){var i="c",t=new Date().getTime().toString(pt),e=fi(hi().toString(pt),In),n=ft(),r=On()+On();return i+t+e+n+r}We.slug=function(){var t=new Date().getTime().toString(36),e=hi().toString(36).slice(-4),n=ft().slice(0,1)+ft().slice(-1),r=On().slice(-2);return t.slice(-2)+e+n+r};We.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};We.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};We.fingerprint=ft;mi.exports=We});var Ti=$e((Pi,_i)=>{(function(i){var t;typeof Pi=="object"?_i.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(l,p){if(!e[l]){if(!t[l]){var h=typeof require=="function"&&require;if(!p&&h)return h(l,!0);if(s)return s(l,!0);throw new Error("Cannot find module '"+l+"'")}p=e[l]={exports:{}},t[l][0].call(p.exports,function(v){var E=t[l][1][v];return r(E||v)},p,p.exports,i,t,e,n)}return e[l].exports}for(var s=typeof require=="function"&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(i,t,e){(function(n,r,s,a,l,p,h,v,E){"use strict";var b=i("crypto");function P(y,I){I=C(y,I);var d;return(d=I.algorithm!=="passthrough"?b.createHash(I.algorithm):new A).write===void 0&&(d.write=d.update,d.end=d.update),S(I,d).dispatch(y),d.update||d.end(""),d.digest?d.digest(I.encoding==="buffer"?void 0:I.encoding):(y=d.read(),I.encoding!=="buffer"?y.toString(I.encoding):y)}(e=t.exports=P).sha1=function(y){return P(y)},e.keys=function(y){return P(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return P(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return P(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var g=b.getHashes?b.getHashes().slice():["sha1","md5"],O=(g.push("passthrough"),["buffer","hex","binary","base64"]);function C(y,I){var d={};if(d.algorithm=(I=I||{}).algorithm||"sha1",d.encoding=I.encoding||"hex",d.excludeValues=!!I.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=I.ignoreUnknown===!0,d.respectType=I.respectType!==!1,d.respectFunctionNames=I.respectFunctionNames!==!1,d.respectFunctionProperties=I.respectFunctionProperties!==!1,d.unorderedArrays=I.unorderedArrays===!0,d.unorderedSets=I.unorderedSets!==!1,d.unorderedObjects=I.unorderedObjects!==!1,d.replacer=I.replacer||void 0,d.excludeKeys=I.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var f=0;f<g.length;++f)g[f].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=g[f]);if(g.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+g.join(", "));if(O.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+O.join(", "));return d}function x(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function S(y,I,d){d=d||[];function f(c){return I.update?I.update(c,"utf8"):I.write(c,"utf8")}return{dispatch:function(c){return this["_"+((c=y.replacer?y.replacer(c):c)===null?"null":typeof c)](c)},_object:function(c){var w,D=Object.prototype.toString.call(c),F=/\[object (.*)\]/i.exec(D);if(F=(F=F?F[1]:"unknown:["+D+"]").toLowerCase(),0<=(D=d.indexOf(c)))return this.dispatch("[CIRCULAR:"+D+"]");if(d.push(c),s!==void 0&&s.isBuffer&&s.isBuffer(c))return f("buffer:"),f(c);if(F==="object"||F==="function"||F==="asyncfunction")return D=Object.keys(c),y.unorderedObjects&&(D=D.sort()),y.respectType===!1||x(c)||D.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(D=D.filter(function(R){return!y.excludeKeys(R)})),f("object:"+D.length+":"),w=this,D.forEach(function(R){w.dispatch(R),f(":"),y.excludeValues||w.dispatch(c[R]),f(",")});if(!this["_"+F]){if(y.ignoreUnknown)return f("["+F+"]");throw new Error('Unknown object type "'+F+'"')}this["_"+F](c)},_array:function(c,R){R=R!==void 0?R:y.unorderedArrays!==!1;var D=this;if(f("array:"+c.length+":"),!R||c.length<=1)return c.forEach(function(j){return D.dispatch(j)});var F=[],R=c.map(function(j){var M=new A,q=d.slice();return S(y,M,q).dispatch(j),F=F.concat(q.slice(d.length)),M.read().toString()});return d=d.concat(F),R.sort(),this._array(R,!1)},_date:function(c){return f("date:"+c.toJSON())},_symbol:function(c){return f("symbol:"+c.toString())},_error:function(c){return f("error:"+c.toString())},_boolean:function(c){return f("bool:"+c.toString())},_string:function(c){f("string:"+c.length+":"),f(c.toString())},_function:function(c){f("fn:"),x(c)?this.dispatch("[native]"):this.dispatch(c.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(c.name)),y.respectFunctionProperties&&this._object(c)},_number:function(c){return f("number:"+c.toString())},_xml:function(c){return f("xml:"+c.toString())},_null:function(){return f("Null")},_undefined:function(){return f("Undefined")},_regexp:function(c){return f("regex:"+c.toString())},_uint8array:function(c){return f("uint8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint8clampedarray:function(c){return f("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(c))},_int8array:function(c){return f("int8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint16array:function(c){return f("uint16array:"),this.dispatch(Array.prototype.slice.call(c))},_int16array:function(c){return f("int16array:"),this.dispatch(Array.prototype.slice.call(c))},_uint32array:function(c){return f("uint32array:"),this.dispatch(Array.prototype.slice.call(c))},_int32array:function(c){return f("int32array:"),this.dispatch(Array.prototype.slice.call(c))},_float32array:function(c){return f("float32array:"),this.dispatch(Array.prototype.slice.call(c))},_float64array:function(c){return f("float64array:"),this.dispatch(Array.prototype.slice.call(c))},_arraybuffer:function(c){return f("arraybuffer:"),this.dispatch(new Uint8Array(c))},_url:function(c){return f("url:"+c.toString())},_map:function(c){return f("map:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_set:function(c){return f("set:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_file:function(c){return f("file:"),this.dispatch([c.name,c.size,c.type,c.lastModfied])},_blob:function(){if(y.ignoreUnknown)return f("[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 p("domwindow")},_bigint:function(c){return p("bigint:"+c.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function A(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,I,d){return d===void 0&&(d=I,I={}),S(I=C(y,I),d).dispatch(y)}}).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,t,e){(function(n,r,s,a,l,f,h,v,E){(function(b){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,g="+".charCodeAt(0),O="/".charCodeAt(0),C="0".charCodeAt(0),x="a".charCodeAt(0),S="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function I(d){return d=d.charCodeAt(0),d===g||d===A?62:d===O||d===y?63:d<C?-1:d<C+10?d-C+26+26:d<S+26?d-S:d<x+26?d-x+26:void 0}b.toByteArray=function(d){var p,c;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=d.length,w=d.charAt(w-2)==="="?2:d.charAt(w-1)==="="?1:0,D=new P(3*d.length/4-w),F=0<w?d.length-4:d.length,R=0;function j(B){D[R++]=B}for(p=0;p<F;p+=4,0)j((16711680&(c=I(d.charAt(p))<<18|I(d.charAt(p+1))<<12|I(d.charAt(p+2))<<6|I(d.charAt(p+3))))>>16),j((65280&c)>>8),j(255&c);return w==2?j(255&(c=I(d.charAt(p))<<2|I(d.charAt(p+1))>>4)):w==1&&(j((c=I(d.charAt(p))<<10|I(d.charAt(p+1))<<4|I(d.charAt(p+2))>>2)>>8&255),j(255&c)),D},b.fromByteArray=function(d){var p,c,w,D,F=d.length%3,R="";function j(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(p=0,w=d.length-F;p<w;p+=3)c=(d[p]<<16)+(d[p+1]<<8)+d[p+2],R+=j((D=c)>>18&63)+j(D>>12&63)+j(D>>6&63)+j(63&D);switch(F){case 1:R=(R+=j((c=d[d.length-1])>>2))+j(c<<4&63)+"==";break;case 2:R=(R=(R+=j((c=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(c>>4&63))+j(c<<2&63)+"="}return R}})(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,t,e){(function(n,r,g,a,l,f,h,v,E){var b=i("base64-js"),P=i("ieee754");function g(o,u,m){if(!(this instanceof g))return new g(o,u,m);var T,_,M,L,Q=typeof o;if(u==="base64"&&Q=="string")for(o=(L=o).trim?L.trim():L.replace(/^\s+|\s+$/g,"");o.length%4!=0;)o+="=";if(Q=="number")T=ee(o);else if(Q=="string")T=g.byteLength(o,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");T=ee(o.length)}if(g._useTypedArrays?_=g._augment(new Uint8Array(T)):((_=this).length=T,_._isBuffer=!0),g._useTypedArrays&&typeof o.byteLength=="number")_._set(o);else if(H(L=o)||g.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(M=0;M<T;M++)g.isBuffer(o)?_[M]=o.readUInt8(M):_[M]=o[M];else if(Q=="string")_.write(o,0,u);else if(Q=="number"&&!g._useTypedArrays&&!m)for(M=0;M<T;M++)_[M]=0;return _}function O(o,u,m,T){return g._charsWritten=dt(function(_){for(var M=[],L=0;L<_.length;L++)M.push(255&_.charCodeAt(L));return M}(u),o,m,T)}function C(o,u,m,T){return g._charsWritten=dt(function(_){for(var M,L,Q=[],Y=0;Y<_.length;Y++)L=_.charCodeAt(Y),M=L>>8,L=L%256,Q.push(L),Q.push(M);return Q}(u),o,m,T)}function x(o,u,m){var T="";m=Math.min(o.length,m);for(var _=u;_<m;_++)T+=String.fromCharCode(o[_]);return T}function S(o,u,m,M){M||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+1<o.length,"Trying to read beyond buffer length"));var _,M=o.length;if(!(M<=u))return m?(_=o[u],u+1<M&&(_|=o[u+1]<<8)):(_=o[u]<<8,u+1<M&&(_|=o[u+1])),_}function A(o,u,m,M){M||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+3<o.length,"Trying to read beyond buffer length"));var _,M=o.length;if(!(M<=u))return m?(u+2<M&&(_=o[u+2]<<16),u+1<M&&(_|=o[u+1]<<8),_|=o[u],u+3<M&&(_+=o[u+3]<<24>>>0)):(u+1<M&&(_=o[u+1]<<16),u+2<M&&(_|=o[u+2]<<8),u+3<M&&(_|=o[u+3]),_+=o[u]<<24>>>0),_}function y(o,u,m,T){if(T||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+1<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=S(o,u,m,!0),32768&T?-1*(65535-T+1):T}function I(o,u,m,T){if(T||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+3<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=A(o,u,m,!0),2147483648&T?-1*(4294967295-T+1):T}function d(o,u,m,T){return T||(k(typeof m=="boolean","missing or invalid endian"),k(u+3<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,23,4)}function p(o,u,m,T){return T||(k(typeof m=="boolean","missing or invalid endian"),k(u+7<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,52,8)}function c(o,u,m,T,_){if(_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+1<o.length,"trying to write beyond buffer length"),bn(u,65535)),_=o.length,!(_<=m))for(var M=0,L=Math.min(_-m,2);M<L;M++)o[m+M]=(u&255<<8*(T?M:1-M))>>>8*(T?M:1-M)}function w(o,u,m,T,_){if(_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"trying to write beyond buffer length"),bn(u,4294967295)),_=o.length,!(_<=m))for(var M=0,L=Math.min(_-m,4);M<L;M++)o[m+M]=u>>>8*(T?M:3-M)&255}function D(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+1<o.length,"Trying to write beyond buffer length"),wn(u,32767,-32768)),o.length<=m||c(o,0<=u?u:65535+u+1,m,T,_)}function F(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"Trying to write beyond buffer length"),wn(u,2147483647,-2147483648)),o.length<=m||w(o,0<=u?u:4294967295+u+1,m,T,_)}function R(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"Trying to write beyond buffer length"),ii(u,34028234663852886e22,-34028234663852886e22)),o.length<=m||P.write(o,u,m,T,23,4)}function j(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+7<o.length,"Trying to write beyond buffer length"),ii(u,17976931348623157e292,-17976931348623157e292)),o.length<=m||P.write(o,u,m,T,52,8)}e.Buffer=g,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var o=new ArrayBuffer(0),u=new Uint8Array(o);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),g.isEncoding=function(o){switch(String(o).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}},g.isBuffer=function(o){return!(o==null||!o._isBuffer)},g.byteLength=function(o,u){var m;switch(o+="",u||"utf8"){case"hex":m=o.length/2;break;case"utf8":case"utf-8":m=be(o).length;break;case"ascii":case"binary":case"raw":m=o.length;break;case"base64":m=ti(o).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=2*o.length;break;default:throw new Error("Unknown encoding")}return m},g.concat=function(o,u){if(k(H(o),`Usage: Buffer.concat(list, [totalLength])
5
- list should be an Array.`),o.length===0)return new g(0);if(o.length===1)return o[0];if(typeof u!="number")for(_=u=0;_<o.length;_++)u+=o[_].length;for(var m=new g(u),T=0,_=0;_<o.length;_++){var M=o[_];M.copy(m,T),T+=M.length}return m},g.prototype.write=function(o,u,m,T){isFinite(u)?isFinite(m)||(T=m,m=void 0):(Y=T,T=u,u=m,m=Y),u=Number(u)||0;var _,M,L,Q,Y=this.length-u;switch((!m||Y<(m=Number(m)))&&(m=Y),T=String(T||"utf8").toLowerCase()){case"hex":_=function(he,ie,re,G){re=Number(re)||0;var J=he.length-re;(!G||J<(G=Number(G)))&&(G=J),k((J=ie.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var Fe=0;Fe<G;Fe++){var ri=parseInt(ie.substr(2*Fe,2),16);k(!isNaN(ri),"Invalid hex string"),he[re+Fe]=ri}return g._charsWritten=2*Fe,Fe}(this,o,u,m);break;case"utf8":case"utf-8":M=this,L=u,Q=m,_=g._charsWritten=dt(be(o),M,L,Q);break;case"ascii":case"binary":_=O(this,o,u,m);break;case"base64":M=this,L=u,Q=m,_=g._charsWritten=dt(ti(o),M,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=C(this,o,u,m);break;default:throw new Error("Unknown encoding")}return _},g.prototype.toString=function(o,u,m){var T,_,M,L,Q=this;if(o=String(o||"utf8").toLowerCase(),u=Number(u)||0,(m=m!==void 0?Number(m):Q.length)===u)return"";switch(o){case"hex":T=function(Y,he,ie){var re=Y.length;(!he||he<0)&&(he=0),(!ie||ie<0||re<ie)&&(ie=re);for(var G="",J=he;J<ie;J++)G+=$(Y[J]);return G}(Q,u,m);break;case"utf8":case"utf-8":T=function(Y,he,ie){var re="",G="";ie=Math.min(Y.length,ie);for(var J=he;J<ie;J++)Y[J]<=127?(re+=ni(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return re+ni(G)}(Q,u,m);break;case"ascii":case"binary":T=x(Q,u,m);break;case"base64":_=Q,L=m,T=(M=u)===0&&L===_.length?b.fromByteArray(_):b.fromByteArray(_.slice(M,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":T=function(Y,he,ie){for(var re=Y.slice(he,ie),G="",J=0;J<re.length;J+=2)G+=String.fromCharCode(re[J]+256*re[J+1]);return G}(Q,u,m);break;default:throw new Error("Unknown encoding")}return T},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(o,u,m,T){if(u=u||0,(T=T||T===0?T:this.length)!==(m=m||0)&&o.length!==0&&this.length!==0){k(m<=T,"sourceEnd < sourceStart"),k(0<=u&&u<o.length,"targetStart out of bounds"),k(0<=m&&m<this.length,"sourceStart out of bounds"),k(0<=T&&T<=this.length,"sourceEnd out of bounds"),T>this.length&&(T=this.length);var _=(T=o.length-u<T-m?o.length-u+m:T)-m;if(_<100||!g._useTypedArrays)for(var M=0;M<_;M++)o[M+u]=this[M+m];else o._set(this.subarray(m,m+_),u)}},g.prototype.slice=function(o,u){var m=this.length;if(o=q(o,m,0),u=q(u,m,m),g._useTypedArrays)return g._augment(this.subarray(o,u));for(var T=u-o,_=new g(T,void 0,!0),M=0;M<T;M++)_[M]=this[M+o];return _},g.prototype.get=function(o){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(o)},g.prototype.set=function(o,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(o,u)},g.prototype.readUInt8=function(o,u){if(u||(k(o!=null,"missing offset"),k(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return this[o]},g.prototype.readUInt16LE=function(o,u){return S(this,o,!0,u)},g.prototype.readUInt16BE=function(o,u){return S(this,o,!1,u)},g.prototype.readUInt32LE=function(o,u){return A(this,o,!0,u)},g.prototype.readUInt32BE=function(o,u){return A(this,o,!1,u)},g.prototype.readInt8=function(o,u){if(u||(k(o!=null,"missing offset"),k(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return 128&this[o]?-1*(255-this[o]+1):this[o]},g.prototype.readInt16LE=function(o,u){return y(this,o,!0,u)},g.prototype.readInt16BE=function(o,u){return y(this,o,!1,u)},g.prototype.readInt32LE=function(o,u){return I(this,o,!0,u)},g.prototype.readInt32BE=function(o,u){return I(this,o,!1,u)},g.prototype.readFloatLE=function(o,u){return d(this,o,!0,u)},g.prototype.readFloatBE=function(o,u){return d(this,o,!1,u)},g.prototype.readDoubleLE=function(o,u){return p(this,o,!0,u)},g.prototype.readDoubleBE=function(o,u){return p(this,o,!1,u)},g.prototype.writeUInt8=function(o,u,m){m||(k(o!=null,"missing value"),k(u!=null,"missing offset"),k(u<this.length,"trying to write beyond buffer length"),bn(o,255)),u>=this.length||(this[u]=o)},g.prototype.writeUInt16LE=function(o,u,m){c(this,o,u,!0,m)},g.prototype.writeUInt16BE=function(o,u,m){c(this,o,u,!1,m)},g.prototype.writeUInt32LE=function(o,u,m){w(this,o,u,!0,m)},g.prototype.writeUInt32BE=function(o,u,m){w(this,o,u,!1,m)},g.prototype.writeInt8=function(o,u,m){m||(k(o!=null,"missing value"),k(u!=null,"missing offset"),k(u<this.length,"Trying to write beyond buffer length"),wn(o,127,-128)),u>=this.length||(0<=o?this.writeUInt8(o,u,m):this.writeUInt8(255+o+1,u,m))},g.prototype.writeInt16LE=function(o,u,m){D(this,o,u,!0,m)},g.prototype.writeInt16BE=function(o,u,m){D(this,o,u,!1,m)},g.prototype.writeInt32LE=function(o,u,m){F(this,o,u,!0,m)},g.prototype.writeInt32BE=function(o,u,m){F(this,o,u,!1,m)},g.prototype.writeFloatLE=function(o,u,m){R(this,o,u,!0,m)},g.prototype.writeFloatBE=function(o,u,m){R(this,o,u,!1,m)},g.prototype.writeDoubleLE=function(o,u,m){j(this,o,u,!0,m)},g.prototype.writeDoubleBE=function(o,u,m){j(this,o,u,!1,m)},g.prototype.fill=function(o,u,m){if(u=u||0,m=m||this.length,k(typeof(o=typeof(o=o||0)=="string"?o.charCodeAt(0):o)=="number"&&!isNaN(o),"value is not a number"),k(u<=m,"end < start"),m!==u&&this.length!==0){k(0<=u&&u<this.length,"start out of bounds"),k(0<=m&&m<=this.length,"end out of bounds");for(var T=u;T<m;T++)this[T]=o}},g.prototype.inspect=function(){for(var o=[],u=this.length,m=0;m<u;m++)if(o[m]=$(this[m]),m===e.INSPECT_MAX_BYTES){o[m+1]="...";break}return"<Buffer "+o.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var o=new Uint8Array(this.length),u=0,m=o.length;u<m;u+=1)o[u]=this[u];return o.buffer};var B=g.prototype;function q(o,u,m){return typeof o!="number"?m:u<=(o=~~o)?u:0<=o||0<=(o+=u)?o:0}function ee(o){return(o=~~Math.ceil(+o))<0?0:o}function H(o){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(o)}function $(o){return o<16?"0"+o.toString(16):o.toString(16)}function be(o){for(var u=[],m=0;m<o.length;m++){var T=o.charCodeAt(m);if(T<=127)u.push(o.charCodeAt(m));else for(var _=m,M=(55296<=T&&T<=57343&&m++,encodeURIComponent(o.slice(_,m+1)).substr(1).split("%")),L=0;L<M.length;L++)u.push(parseInt(M[L],16))}return u}function ti(o){return b.toByteArray(o)}function dt(o,u,m,T){for(var _=0;_<T&&!(_+m>=u.length||_>=o.length);_++)u[_+m]=o[_];return _}function ni(o){try{return decodeURIComponent(o)}catch{return String.fromCharCode(65533)}}function bn(o,u){k(typeof o=="number","cannot write a non-number as a number"),k(0<=o,"specified a negative value for writing an unsigned value"),k(o<=u,"value is larger than maximum value for type"),k(Math.floor(o)===o,"value has a fractional component")}function wn(o,u,m){k(typeof o=="number","cannot write a non-number as a number"),k(o<=u,"value larger than maximum allowed value"),k(m<=o,"value smaller than minimum allowed value"),k(Math.floor(o)===o,"value has a fractional component")}function ii(o,u,m){k(typeof o=="number","cannot write a non-number as a number"),k(o<=u,"value larger than maximum allowed value"),k(m<=o,"value smaller than minimum allowed value")}function k(o,u){if(!o)throw new Error(u||"Failed assertion")}g._augment=function(o){return o._isBuffer=!0,o._get=o.get,o._set=o.set,o.get=B.get,o.set=B.set,o.write=B.write,o.toString=B.toString,o.toLocaleString=B.toString,o.toJSON=B.toJSON,o.copy=B.copy,o.slice=B.slice,o.readUInt8=B.readUInt8,o.readUInt16LE=B.readUInt16LE,o.readUInt16BE=B.readUInt16BE,o.readUInt32LE=B.readUInt32LE,o.readUInt32BE=B.readUInt32BE,o.readInt8=B.readInt8,o.readInt16LE=B.readInt16LE,o.readInt16BE=B.readInt16BE,o.readInt32LE=B.readInt32LE,o.readInt32BE=B.readInt32BE,o.readFloatLE=B.readFloatLE,o.readFloatBE=B.readFloatBE,o.readDoubleLE=B.readDoubleLE,o.readDoubleBE=B.readDoubleBE,o.writeUInt8=B.writeUInt8,o.writeUInt16LE=B.writeUInt16LE,o.writeUInt16BE=B.writeUInt16BE,o.writeUInt32LE=B.writeUInt32LE,o.writeUInt32BE=B.writeUInt32BE,o.writeInt8=B.writeInt8,o.writeInt16LE=B.writeInt16LE,o.writeInt16BE=B.writeInt16BE,o.writeInt32LE=B.writeInt32LE,o.writeInt32BE=B.writeInt32BE,o.writeFloatLE=B.writeFloatLE,o.writeFloatBE=B.writeFloatBE,o.writeDoubleLE=B.writeDoubleLE,o.writeDoubleBE=B.writeDoubleBE,o.fill=B.fill,o.inspect=B.inspect,o.toArrayBuffer=B.toArrayBuffer,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/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,b,a,l,f,h,v,E){var b=i("buffer").Buffer,P=4,g=new b(P);g.fill(0),t.exports={hash:function(O,C,x,S){for(var A=C(function(c,w){c.length%P!=0&&(D=c.length+(P-c.length%P),c=b.concat([c,g],D));for(var D,F=[],R=w?c.readInt32BE:c.readInt32LE,j=0;j<c.length;j+=P)F.push(R.call(c,j));return F}(O=b.isBuffer(O)?O:new b(O),S),8*O.length),C=S,y=new b(x),I=C?y.writeInt32BE:y.writeInt32LE,d=0;d<A.length;d++)I.call(y,A[d],4*d,!0);return y}}}).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,t,e){(function(n,r,b,a,l,f,h,v,E){var b=i("buffer").Buffer,P=i("./sha"),g=i("./sha256"),O=i("./rng"),C={sha1:P,sha256:g,md5:i("./md5")},x=64,S=new b(x);function A(c,w){var D=C[c=c||"sha1"],F=[];return D||y("algorithm:",c,"is not yet supported"),{update:function(R){return b.isBuffer(R)||(R=new b(R)),F.push(R),R.length,this},digest:function(R){var j=b.concat(F),j=w?function(B,q,ee){b.isBuffer(q)||(q=new b(q)),b.isBuffer(ee)||(ee=new b(ee)),q.length>x?q=B(q):q.length<x&&(q=b.concat([q,S],x));for(var H=new b(x),$=new b(x),be=0;be<x;be++)H[be]=54^q[be],$[be]=92^q[be];return ee=B(b.concat([H,ee])),B(b.concat([$,ee]))}(D,w,j):D(j);return F=null,R?j.toString(R):j}}}function y(){var c=[].slice.call(arguments).join(" ");throw new Error([c,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
- `))}S.fill(0),e.createHash=function(c){return A(c)},e.createHmac=A,e.randomBytes=function(c,w){if(!w||!w.call)return new b(O(c));try{w.call(this,void 0,new b(O(c)))}catch(D){w(D)}};var I,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(c){e[c]=function(){y("sorry,",c,"is not implemented yet")}};for(I in d)p(d[I],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/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,t,e){(function(n,r,s,a,l,f,h,v,E){var b=i("./helpers");function P(y,I){y[I>>5]|=128<<I%32,y[14+(I+64>>>9<<4)]=I;for(var d=1732584193,p=-271733879,c=-1732584194,w=271733878,D=0;D<y.length;D+=16){var F=d,R=p,j=c,B=w,d=O(d,p,c,w,y[D+0],7,-680876936),w=O(w,d,p,c,y[D+1],12,-389564586),c=O(c,w,d,p,y[D+2],17,606105819),p=O(p,c,w,d,y[D+3],22,-1044525330);d=O(d,p,c,w,y[D+4],7,-176418897),w=O(w,d,p,c,y[D+5],12,1200080426),c=O(c,w,d,p,y[D+6],17,-1473231341),p=O(p,c,w,d,y[D+7],22,-45705983),d=O(d,p,c,w,y[D+8],7,1770035416),w=O(w,d,p,c,y[D+9],12,-1958414417),c=O(c,w,d,p,y[D+10],17,-42063),p=O(p,c,w,d,y[D+11],22,-1990404162),d=O(d,p,c,w,y[D+12],7,1804603682),w=O(w,d,p,c,y[D+13],12,-40341101),c=O(c,w,d,p,y[D+14],17,-1502002290),d=C(d,p=O(p,c,w,d,y[D+15],22,1236535329),c,w,y[D+1],5,-165796510),w=C(w,d,p,c,y[D+6],9,-1069501632),c=C(c,w,d,p,y[D+11],14,643717713),p=C(p,c,w,d,y[D+0],20,-373897302),d=C(d,p,c,w,y[D+5],5,-701558691),w=C(w,d,p,c,y[D+10],9,38016083),c=C(c,w,d,p,y[D+15],14,-660478335),p=C(p,c,w,d,y[D+4],20,-405537848),d=C(d,p,c,w,y[D+9],5,568446438),w=C(w,d,p,c,y[D+14],9,-1019803690),c=C(c,w,d,p,y[D+3],14,-187363961),p=C(p,c,w,d,y[D+8],20,1163531501),d=C(d,p,c,w,y[D+13],5,-1444681467),w=C(w,d,p,c,y[D+2],9,-51403784),c=C(c,w,d,p,y[D+7],14,1735328473),d=x(d,p=C(p,c,w,d,y[D+12],20,-1926607734),c,w,y[D+5],4,-378558),w=x(w,d,p,c,y[D+8],11,-2022574463),c=x(c,w,d,p,y[D+11],16,1839030562),p=x(p,c,w,d,y[D+14],23,-35309556),d=x(d,p,c,w,y[D+1],4,-1530992060),w=x(w,d,p,c,y[D+4],11,1272893353),c=x(c,w,d,p,y[D+7],16,-155497632),p=x(p,c,w,d,y[D+10],23,-1094730640),d=x(d,p,c,w,y[D+13],4,681279174),w=x(w,d,p,c,y[D+0],11,-358537222),c=x(c,w,d,p,y[D+3],16,-722521979),p=x(p,c,w,d,y[D+6],23,76029189),d=x(d,p,c,w,y[D+9],4,-640364487),w=x(w,d,p,c,y[D+12],11,-421815835),c=x(c,w,d,p,y[D+15],16,530742520),d=S(d,p=x(p,c,w,d,y[D+2],23,-995338651),c,w,y[D+0],6,-198630844),w=S(w,d,p,c,y[D+7],10,1126891415),c=S(c,w,d,p,y[D+14],15,-1416354905),p=S(p,c,w,d,y[D+5],21,-57434055),d=S(d,p,c,w,y[D+12],6,1700485571),w=S(w,d,p,c,y[D+3],10,-1894986606),c=S(c,w,d,p,y[D+10],15,-1051523),p=S(p,c,w,d,y[D+1],21,-2054922799),d=S(d,p,c,w,y[D+8],6,1873313359),w=S(w,d,p,c,y[D+15],10,-30611744),c=S(c,w,d,p,y[D+6],15,-1560198380),p=S(p,c,w,d,y[D+13],21,1309151649),d=S(d,p,c,w,y[D+4],6,-145523070),w=S(w,d,p,c,y[D+11],10,-1120210379),c=S(c,w,d,p,y[D+2],15,718787259),p=S(p,c,w,d,y[D+9],21,-343485551),d=A(d,F),p=A(p,R),c=A(c,j),w=A(w,B)}return Array(d,p,c,w)}function g(y,I,d,p,c,w){return A((I=A(A(I,y),A(p,w)))<<c|I>>>32-c,d)}function O(y,I,d,p,c,w,D){return g(I&d|~I&p,y,I,c,w,D)}function C(y,I,d,p,c,w,D){return g(I&p|d&~p,y,I,c,w,D)}function x(y,I,d,p,c,w,D){return g(I^d^p,y,I,c,w,D)}function S(y,I,d,p,c,w,D){return g(d^(I|~p),y,I,c,w,D)}function A(y,I){var d=(65535&y)+(65535&I);return(y>>16)+(I>>16)+(d>>16)<<16|65535&d}t.exports=function(y){return b.hash(y,P,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,t,e){(function(n,r,s,a,l,f,h,v,E){var b;t.exports=b||function(P){for(var g,O=new Array(P),C=0;C<P;C++)!(3&C)&&(g=4294967296*Math.random()),O[C]=g>>>((3&C)<<3)&255;return 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/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){var b=i("./helpers");function P(C,x){C[x>>5]|=128<<24-x%32,C[15+(x+64>>9<<4)]=x;for(var S,A,y,I=Array(80),d=1732584193,p=-271733879,c=-1732584194,w=271733878,D=-1009589776,F=0;F<C.length;F+=16){for(var R=d,j=p,B=c,q=w,ee=D,H=0;H<80;H++){I[H]=H<16?C[F+H]:O(I[H-3]^I[H-8]^I[H-14]^I[H-16],1);var $=g(g(O(d,5),($=p,A=c,y=w,(S=H)<20?$&A|~$&y:!(S<40)&&S<60?$&A|$&y|A&y:$^A^y)),g(g(D,I[H]),(S=H)<20?1518500249:S<40?1859775393:S<60?-1894007588:-899497514)),D=w,w=c,c=O(p,30),p=d,d=$}d=g(d,R),p=g(p,j),c=g(c,B),w=g(w,q),D=g(D,ee)}return Array(d,p,c,w,D)}function g(C,x){var S=(65535&C)+(65535&x);return(C>>16)+(x>>16)+(S>>16)<<16|65535&S}function O(C,x){return C<<x|C>>>32-x}t.exports=function(C){return b.hash(C,P,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,t,e){(function(n,r,s,a,l,f,h,v,E){function b(x,S){var A=(65535&x)+(65535&S);return(x>>16)+(S>>16)+(A>>16)<<16|65535&A}function P(x,S){var A,y=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),I=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);x[S>>5]|=128<<24-S%32,x[15+(S+64>>9<<4)]=S;for(var p,c,w=0;w<x.length;w+=16){for(var D=I[0],F=I[1],R=I[2],j=I[3],B=I[4],q=I[5],ee=I[6],H=I[7],$=0;$<64;$++)d[$]=$<16?x[$+w]:b(b(b((c=d[$-2],O(c,17)^O(c,19)^C(c,10)),d[$-7]),(c=d[$-15],O(c,7)^O(c,18)^C(c,3))),d[$-16]),A=b(b(b(b(H,O(c=B,6)^O(c,11)^O(c,25)),B&q^~B&ee),y[$]),d[$]),p=b(O(p=D,2)^O(p,13)^O(p,22),D&F^D&R^F&R),H=ee,ee=q,q=B,B=b(j,A),j=R,R=F,F=D,D=b(A,p);I[0]=b(D,I[0]),I[1]=b(F,I[1]),I[2]=b(R,I[2]),I[3]=b(j,I[3]),I[4]=b(B,I[4]),I[5]=b(q,I[5]),I[6]=b(ee,I[6]),I[7]=b(H,I[7])}return I}var g=i("./helpers"),O=function(x,S){return x>>>S|x<<32-S},C=function(x,S){return x>>>S};t.exports=function(x){return g.hash(x,P,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,t,e){(function(n,r,s,a,l,f,h,v,E){e.read=function(b,P,g,O,w){var x,S,A=8*w-O-1,y=(1<<A)-1,I=y>>1,d=-7,p=g?w-1:0,c=g?-1:1,w=b[P+p];for(p+=c,x=w&(1<<-d)-1,w>>=-d,d+=A;0<d;x=256*x+b[P+p],p+=c,d-=8);for(S=x&(1<<-d)-1,x>>=-d,d+=O;0<d;S=256*S+b[P+p],p+=c,d-=8);if(x===0)x=1-I;else{if(x===y)return S?NaN:1/0*(w?-1:1);S+=Math.pow(2,O),x-=I}return(w?-1:1)*S*Math.pow(2,x-O)},e.write=function(b,P,g,O,C,D){var S,A,y=8*D-C-1,I=(1<<y)-1,d=I>>1,p=C===23?Math.pow(2,-24)-Math.pow(2,-77):0,c=O?0:D-1,w=O?1:-1,D=P<0||P===0&&1/P<0?1:0;for(P=Math.abs(P),isNaN(P)||P===1/0?(A=isNaN(P)?1:0,S=I):(S=Math.floor(Math.log(P)/Math.LN2),P*(O=Math.pow(2,-S))<1&&(S--,O*=2),2<=(P+=1<=S+d?p/O:p*Math.pow(2,1-d))*O&&(S++,O/=2),I<=S+d?(A=0,S=I):1<=S+d?(A=(P*O-1)*Math.pow(2,C),S+=d):(A=P*Math.pow(2,d-1)*Math.pow(2,C),S=0));8<=C;b[g+c]=255&A,c+=w,A/=256,C-=8);for(S=S<<C|A,y+=C;0<y;b[g+c]=255&S,c+=w,S/=256,y-=8);b[g+c-w]|=128*D}}).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,t,e){(function(n,r,s,a,l,f,h,v,E){var b,P,g;function O(){}(n=t.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(C){return window.setImmediate(C)}:g?(b=[],window.addEventListener("message",function(C){var x=C.source;x!==window&&x!==null||C.data!=="process-tick"||(C.stopPropagation(),0<b.length&&b.shift()())},!0),function(C){b.push(C),window.postMessage("process-tick","*")}):function(C){setTimeout(C,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=O,n.addListener=O,n.once=O,n.off=O,n.removeListener=O,n.removeAllListeners=O,n.emit=O,n.binding=function(C){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(C){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 ei={};pr(ei,{Client:()=>Re,ClientDescriptor:()=>gn,Entity:()=>ye,EntityFile:()=>Me,MigrationPathError:()=>Ve,ServerSync:()=>Ke,Storage:()=>Re,StorageDescriptor:()=>gn,collection:()=>Ki,createDefaultMigration:()=>zn,createMigration:()=>$n,migrate:()=>kt,schema:()=>zi});var Si=ut(ht(),1),mt=4,Qe=36;function yi(i){return i.toString(Qe).padStart(mt,"0")}function vr(i){return i.toString().padStart(6,"0")}var yt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Sr()};this.zeroCounter=0;this.now=t=>(this.latest=bi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=bi(this.latest),vr(t)+Or(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(mt);this.latest=xr(this.latest,wi(e))};this.get=(t,e)=>yi(t)+gi(e);this.zero=t=>yi(t)+gi({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>wi(t.slice(mt)).time}},gt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},bt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Dn=4,Cn=7,wt=60*1e3,He=9;function Sr(){return Si.default.slug().padStart(Cn,"0").slice(0,Cn)}function gi(i){let t=new Date(i.time).getTime().toString(Qe).padStart(He,"0"),e=i.counter.toString(Qe).padStart(Dn,"0"),n=i.node.padStart(Cn,"0");return`${t}${e}${n}`}function bi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>wt)throw new gt(e,t,wt);if(n>65535)throw new bt;return{time:e,counter:n,node:i.node}}function xr(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>wt)throw new gt(n,e,wt);if(s>65535)throw new bt;return{time:n,counter:s,node:i.node}}function wi(i){let t=i.slice(0,He),e=i.slice(He,He+Dn),n=i.slice(He+Dn),r=parseInt(t,Qe),s=parseInt(e,Qe);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function Or(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function vi(i){return parseInt(i.slice(0,mt),36)}function xi(i,t){return vi(i)-vi(t)}function se(i){return i&&i["@@type"]==="file"}function Oi(i){return{"@@type":"file",id:i}}var vt,Ir=new Uint8Array(16);function En(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(Ir)}var Ii=/^(?:[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 Dr(i){return typeof i=="string"&&Ii.test(i)}var Di=Dr;var X=[];for(St=0;St<256;++St)X.push((St+256).toString(16).substr(1));var St;function Cr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(X[i[t+0]]+X[i[t+1]]+X[i[t+2]]+X[i[t+3]]+"-"+X[i[t+4]]+X[i[t+5]]+"-"+X[i[t+6]]+X[i[t+7]]+"-"+X[i[t+8]]+X[i[t+9]]+"-"+X[i[t+10]]+X[i[t+11]]+X[i[t+12]]+X[i[t+13]]+X[i[t+14]]+X[i[t+15]]).toLowerCase();if(!Di(e))throw TypeError("Stringified UUID is invalid");return e}var Ci=Cr;function Er(i,t,e){i=i||{};var n=i.random||(i.rng||En)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return Ci(n)}var Je=Er;function ne(i){return te(i)||se(i)}function Ei(i,t){return i===t?!0:!(!ne(i)||!ne(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Ai=ut(Ti(),1);function Pr(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Ye(i){return JSON.stringify(i,Pr)}function oe(i,t=!0){if(z(i)||Array.isArray(i)){let e=ae(i),n;if(Array.isArray(i))n=i.map(r=>oe(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=oe(s,t)}return t&&e&&U(n,e),n}return i}function Se(i){return(0,Ai.default)(i)}function z(i){return i&&typeof i=="object"}function ki(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function xt(i=16){return Je().replace("-","").slice(0,i)}function Mi(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Bi(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Ie="__@@oid_do_not_use",De="@@id",_r="/",Xe=":",_n=new WeakMap;function ce(i){let t=ae(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function ae(i){if(z(i))return _n.get(i)??i[De]??i[Ie]}function U(i,t){return V(z(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Dt(i),_n.set(i,t),i}function Ze(i){return!!ae(i)}function Dt(i){return _n.delete(i),i}function Tn(i){return i===De||i===Ie}function An(i,t,e){if(Ze(i))return ce(i);{let n=ge(t,e);return U(i,n),n}}function Ri(i,t,e){if(Ze(i)){let n=ce(i);if(Ct(n,t))return ce(i);{let r=ge(t,e);return U(i,r),r}}else{let n=ge(t,e);return U(i,n),n}}var Pn={".":"&dot;","/":"&slash;",":":"&colon;"};function Fi(i){return i.replace(/[/]/g,Pn["/"]).replace(/[:]/g,Pn[":"]).replace(/[.]/g,Pn["."])}function ji(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,t,e){let n=Fi(i)+_r+Fi(t);return e&&(n+=Xe+e),n}function ge(i,t=Mr){let{collection:e,id:n}=le(i);return Z(e,n,t())}function le(i){let[t,e]=i.split(Xe),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:ji(n),id:ji(s),subId:e}}function je(i,t){let e=ce(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],z(n)&&!ne(n)&&(Ri(n,e,t),je(n,t))}else if(z(i)&&!ne(i))for(let n of Object.keys(i))z(i[n])&&!ne(i[n])&&(Ri(i[n],e,t),je(i[n],t))}function Tr(i){if(z(i))return i[De]||i[Ie]}function Ar(i){return z(i)&&(delete i[Ie],delete i[De]),i}function kr(i){let t=Tr(i);t&&U(i,t)}function Ge(i){if(kr(i),Ar(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ge(i[t]);else if(z(i))for(let t of Object.keys(i))Ge(i[t])}function Ot(i){if(Dt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ot(i[t]);else if(z(i))for(let t of Object.keys(i))Ot(i[t])}function Mr(){return Je().slice(0,8)}function we(i){return{"@@type":"ref",id:i}}function It(i,t=new Map){if(Array.isArray(i)){let e=ce(i),n=U([],e);for(let r=0;r<i.length;r++){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s)){n[r]=s;continue}else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else if(z(i)&&!ne(i)){let e=ce(i),n=U({},e);for(let r of Object.keys(i)){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s))n[r]=s;else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else ne(i);return t}function K(i){return i.split(".")[0].split(Xe)[0]}function kn(i,t){let e=K(i),n=ge(e,()=>"\uFFFF");return t?[`${e}.`,n]:[`${e}${Xe}`,n]}function Ct(i,t){return K(i)===K(t)}function Mn(i){return i.split(Xe)[0].includes(".")}function te(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Bn(i){return z(i)&&!ne(i)}function Br(i,t){return i===t?!0:ne(i)&&ne(t)?Ei(i,t):!1}function et(i,t,e,n,r=[],s={}){let a=ce(i);function l(f,h,v){if(!Bn(h))Br(h,v)||r.push({oid:a,timestamp:e(),data:{op:"set",name:f,value:h}});else{let E=ae(v),b=ae(h);b&&!Ct(a,b)?(h=oe(h,!1),b=ge(a,n),U(h,b)):s.mergeUnknownObjects?!b&&E?(U(h,E),b=E):b=An(h,a,n):b=An(h,a,n),V(!!b,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Ct(a,b),`Error: value OID ${b} is not related to parent OID ${a}. This is a bug in Verdant.`),v===void 0||b!==E?(xe(h,b,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:f,value:we(b)}}),E!==void 0&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})):et(v,h,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let h=0;h<t.length;h++){let v=t[h],E=i[h];l(h,v,E)}let f=i.length-t.length;if(f>0){for(let h=t.length;h<i.length;h++){let v=i[h],E=ae(v);E&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:f}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Bn(i)&&Bn(t)){let f=new Set(Object.keys(i));for(let[h,v]of Object.entries(t)){if(v===void 0&&s.defaultUndefined||(f.delete(h),Tn(h)))continue;let E=i[h];l(h,v,E)}if(!s.defaultUndefined)for(let h of f)Tn(h)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:h}})}}return r}function xe(i,t,e,n,r=[]){U(i,t),je(i,n);let s=It(i);for(let a of s.keys()){let l=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Dt(l)}})}return r}function Vi(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Rn(i){let t={};for(let e of i){let n=K(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Fn(i){let t={};for(let e of i){let n=K(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Ce(i){return Array.isArray(i)?!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: ${ae(i)})`),!1)}function Ee(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(l){e&&ne(l)&&e.push(l)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":Ce(i)&&i.push(t.value);break;case"list-delete":Ce(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Ce(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(Ce(i))do{let l=t.value;t.only==="last"?te(l)?r=Mi(i,f=>f.id===l.id):r=i.lastIndexOf(l):te(l)?r=i.findIndex(f=>f.id===l.id):r=i.indexOf(l),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Ce(i)&&(i.some(f=>te(f)&&te(t.value)?f.id===t.value.id:f===t.value)||i.push(t.value));break;case"list-move-by-ref":Ce(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(Ce(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):z(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return oe(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Et(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Li(r,t,e),z(i[n])&&Et(i[n],t,e)}else if(!se(i)){if(z(i)){V(ae(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Li(i[n],t,e),z(i[n])&&Et(i[n],t,e)}}return e}function Li(i,t,e){if(te(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),U(n,i.id)}else return i}function Rr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ln(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.type==="object"?!0:i.default!==void 0:!1}function Pt(i){return i.type==="map"||i.type==="object"||i.type==="array"||i.type==="file"||i.type==="any"?!1:i.indexed}function ve(i,t){for(let[e,n]of Object.entries(i.fields)){let r=Ni(n);(r!==void 0&&t[e]===void 0||!Rr(n)&&t[e]===null)&&(t[e]=r),t[e]&&Pe(t[e],n)}return t}function Pe(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=Ni(n);r!==void 0&&(i[e]=r)}Pe(i[e],n)}else if(t.type==="array")for(let e of i)Pe(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===De||e===Ie||Pe(n,t.values)}function Ni(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function Vn(i,t){for(let[e,n]of Object.entries(t))e===De||e===Ie||(i.fields[e]?jn(n,i.fields[e]):delete t[e]);return t}function jn(i,t){if(z(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?jn(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)jn(e,t.items)}function Nn(i){return i.equals!==void 0}function Un(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function Fr(i){return!!i.match}function Kn(i){return i.startsWith!==void 0}function Ui(i){return!Un(i)&&!Nn(i)&&!Fr(i)&&!Kn(i)&&i.order}function Ki({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,s]of Object.entries(e.fields))Pt(s)&&(n[r]={field:r});return{...e,indexes:n}}function zi(i){return i}var _t="\uFFFFFE",jr="\0",Lr="\uFFFFFF";function de(...i){let t=Vr(i);return t.length===1?t[0]:t}function _e(...i){return i.join(_t)+`${Lr}`}function Te(...i){return i.join(_t)+`${_t}${jr}`}function Vr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(_t))))}function Nr(i){return!!i.field}function Ur(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let s=r;Nr(s)?e[n]=me(t[s.field]):e[n]=me(s.compute(t))}return e}function Kr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=de(...r.of.map(s=>t[s])),e),{})}function zr(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>(Pt(r)&&(e[n]=me(t[n])),e),{})}function Tt(i,t){return{[i.primaryKey]:t[i.primaryKey],...zr(i,t),...Ur(i,t),...Kr(i,t),"@@@snapshot":t}}var $r="null";function me(i){if(i===null)return $r;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(me);throw new Error(`Unsupported index value: ${i}`)}var $i={version:0,collections:{}};function kt(i,t,e){let n=typeof t=="function",r=n?$i:i,s=n?i:t,a=n?t:e,l=Object.keys(s.collections).filter(O=>r.collections[O]&&Ye(r.collections[O])!==Ye(s.collections[O])),f=Object.keys(r.collections).filter(O=>!s.collections[O]),h=Object.keys(s.collections).filter(O=>!r.collections[O]),v=new Set;for(let O of l){let C=r.collections[O].fields,x=s.collections[O].fields;Object.keys(x).some(S=>!C[S]?.default&&x[S]?.default)&&v.add(O),Object.keys(C).some(S=>!x[S])&&v.add(O)}let E={},b={};for(let O of[...l,...h]){let C=At(r.collections[O]),x=At(s.collections[O]),S=x.filter(y=>!C.find(I=>I.name===y.name)),A=C.filter(y=>!x.find(I=>I.name===y.name));S.length>0&&(E[O]=S,l.includes(O)&&v.add(O)),A.length>0&&(b[O]=A,l.includes(O)&&v.add(O))}let P=(O,C)=>ve(s.collections[O],C),g=O=>C=>{let x=s.collections[O];return ve(x,Vn(x,C))};return{version:s.version,migrate:async O=>{let C=[];if(await a({migrate:async(x,S)=>{let A=g(x),y=async I=>{let d=await S(I);return U(d,ce(I)),A(d)};await O.migrate(x,y),C.push(x),v.delete(x)},identity:x=>x,withDefaults:P,info:{changedCollections:l,addedCollections:h,removedCollections:f},queries:O.queries,mutations:O.mutations}),s.version>1){O.log("debug","auto-migrating collections with new defaults",v);for(let S of v)await O.migrate(S,g(S)),C.push(S);let x=l.filter(S=>!C.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:f,addedIndexes:E,removedIndexes:b,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function At(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function zn(i,t){return kt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}function $n(i,t,e){let n=typeof t=="function"||t===void 0,r=n?$i:i,s=n?i:t,a=n?t:e;V(r,"Invalid arguments to createMigration"),V(s,"Invalid arguments to createMigration");let{changedCollections:l,addedCollections:f,removedCollections:h,addedIndexes:v,removedIndexes:E,autoMigratedCollections:b,autoMigration:P}=qr(r,s);return{version:s.version,migrate:async g=>{let O=[];if(await a?.({migrate:async(x,S)=>{let A=P(x),y=async I=>{let d=await S(I);return U(d,ce(I)),A(d)};await g.migrate(x,y),O.push(x),b.delete(x)},info:{changedCollections:l,addedCollections:f,removedCollections:h},queries:g.queries,mutations:g.mutations}),s.version>1){g.log("debug","auto-migrating collections with new defaults",b);for(let S of b)await g.migrate(S,P(S)),O.push(S);let x=l.filter(S=>!O.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:h,addedIndexes:v,removedIndexes:E,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:f,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function qr(i,t){let e=Object.keys(t.collections).filter(v=>i.collections[v]&&Ye(i.collections[v])!==Ye(t.collections[v])),n=Object.keys(i.collections).filter(v=>!t.collections[v]),r=Object.keys(t.collections).filter(v=>!i.collections[v]),s=new Set;for(let v of e){let E=i.collections[v].fields,b=t.collections[v].fields;Object.keys(b).some(P=>!Ln(E[P])&&Ln(b[P]))&&s.add(v),Object.keys(E).some(P=>!b[P])&&s.add(v)}let a={},l={};for(let v of[...e,...r]){let E=At(i.collections[v]),b=At(t.collections[v]),P=b.filter(O=>!E.find(C=>C.name===O.name)),g=E.filter(O=>!b.find(C=>C.name===O.name));P.length>0&&(a[v]=P,e.includes(v)&&s.add(v)),g.length>0&&(l[v]=g,e.includes(v)&&s.add(v))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:a,removedIndexes:l,autoMigratedCollections:s,withDefaults:(v,E)=>ve(t.collections[v],E),autoMigration:v=>E=>{let b=t.collections[v];return ve(b,Vn(b,E))}}}var Mt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>xe(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!z(n)||ne(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:we(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(z(e)){let n=ge(t,this.createSubId);return[...xe(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:we(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>z(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:we(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(z(n)){let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:we(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var N=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=xt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function qi(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=oe(t),s=[];for(let a of e){let l=Wr(i,r,a,n);s.unshift(...l),Ee(r,a.data)}return s}function Wr(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(l=>({oid:i,timestamp:n(),data:{op:"list-insert",index:l,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Le=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush())}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new qn({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},qn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);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 t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function tt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),l=0,f=0;a.onsuccess=function(h){let v=a.result;v&&(l++,f=f+ki(v.value),v.continue())},a.onerror=function(h){n(h)},r.oncomplete=function(h){e({count:l,size:f})},r.onabort=function(h){n(h)},r.onerror=function(h){n(h)}})}function Wi(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return W(s.getAll())});return Promise.all(n)}async function Ae(i){i.close(),await new Promise((t,e)=>{t()})}async function Bt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}function Hi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function Qi(i=window.indexedDB){return i.databases()}var pe=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return W(l)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return Promise.all(l.map(W))};this.iterate=async(t,e,n,r="readonly",s)=>{let l=(s||this.db.transaction(t,r)).objectStore(t),f=e(l);return Array.isArray(f)?Promise.all(f.map(h=>new Promise((v,E)=>{h.onsuccess=()=>{let b=h.result;b?(n(b.value,l),b.continue()):v()},h.onerror=E}))).then(()=>{}):new Promise((h,v)=>{f.onsuccess=()=>{let E=f.result;E?(n(E.value,l),E.continue()):h()},f.onerror=v})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var Rt=class extends pe{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var Ft=class extends pe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let l=K(e),f=Mn(e),[h,v]=kn(e,f);return[a.openCursor(IDBKeyRange.only(l)),a.openCursor(IDBKeyRange.bound(h,v,!1,!1))]},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.flatMap(a=>{let l=K(a),f=Mn(a),[h,v]=kn(a,f);return[s.get(l),s.getAll(IDBKeyRange.bound(h,v,!1,!1))]}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Ji=ut(ht(),1);var jt=class extends pe{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,Ji.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var Lt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(K(l.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(K(l.oid))},{mode:"readwrite"});let a=[];return n||(a=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var Vt=class extends pe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:l="readonly",transaction:f}={})=>{let v=(f||this.db.transaction("operations",l)).objectStore("operations"),E=v.index("d_t"),b=s||a,P=b?de(e,b):Te(e),g=r?de(e,r):_e(e),O=IDBKeyRange.bound(P,g,!!a,!1),C=E.openCursor(O,"next");return new Promise((x,S)=>{let A;C.onsuccess=y=>{let I=C.result;if(I){let d=I.value;V(d.oid.startsWith(e)),V(A===void 0||A<=d.timestamp,`expected ${A} <= ${d.timestamp}`),n(d,v),A=d.timestamp,I.continue()}else x()},C.onerror=y=>{S(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:l})=>{let h=(l||this.db.transaction("operations",a)).objectStore("operations"),v=r?de(e,r):Te(e),E=s?de(e,s):_e(e),b=IDBKeyRange.bound(v,E,!!r,!1),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(A.oid.startsWith(e)),V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,h),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let f=(a||this.db.transaction("operations",s)).objectStore("operations"),h=f.index("l_t"),v=r?de(!0,r):Te(!0),E=n?de(!0,n):_e(!0),b=IDBKeyRange.bound(v,E,!!r,!0),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),e(A,f),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",l=>{let f=a?Te(a):void 0,h=n?_e(n):void 0,v=f&&h?IDBKeyRange.bound(f,h,!1,!0):f?IDBKeyRange.lowerBound(f,!1):h?IDBKeyRange.upperBound(h,!0):void 0;return l.index("timestamp").openCursor(v,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:de(e.oid,e.timestamp),l_t:de(e.isLocal,e.timestamp),d_t:de(K(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add(K(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Nt=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await W(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(s)}}};var nt=class extends N{constructor({disableRebasing:e,context:n}){super();this.time=new yt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=K(e);V(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=K(e);V(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),l=new Map;for(let h of a)h.snapshot&&U(h.snapshot,h.oid),l.set(h.oid,h.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,h=>{let v=l.get(h.oid)||void 0,E=Ee(v,h.data);E&&U(E,h.oid),l.set(h.oid,E)},{transaction:s,to:n.to||this.now});let f=l.get(r);return f&&Et(f,l),f};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add(K(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(f=>{r.add(f.oid),n=f.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let l=[];for(let f of r)l.push(await this.rebase(f,n||e,s));this.emit("rebase",l)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),l=await this.baselines.get(e,{transaction:a}),f=l?.snapshot||void 0,h=0,v=[];await this.operations.iterateOverAllOperationsForEntity(e,(b,P)=>{(!l||b.timestamp>l.timestamp)&&(f=Ee(f,b.data,v)),h++,P.delete(b.oid_timestamp)},{to:n,transaction:a}),f&&U(f,e);let E={oid:e,snapshot:f,timestamp:n};if(E.snapshot?await this.baselines.set(E,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",f,"and deleted",h,"operations"),v.length){let b=v.filter(se);b.length&&this.emit("filesDeleted",b)}return E};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
4
+ `)},_domwindow:function(){return f("domwindow")},_bigint:function(c){return f("bigint:"+c.toString())},_process:function(){return f("process")},_timer:function(){return f("timer")},_pipe:function(){return f("pipe")},_tcp:function(){return f("tcp")},_udp:function(){return f("udp")},_tty:function(){return f("tty")},_statwatcher:function(){return f("statwatcher")},_securecontext:function(){return f("securecontext")},_connection:function(){return f("connection")},_zlib:function(){return f("zlib")},_context:function(){return f("context")},_nodescript:function(){return f("nodescript")},_httpparser:function(){return f("httpparser")},_dataview:function(){return f("dataview")},_signal:function(){return f("signal")},_fsevent:function(){return f("fsevent")},_tlswrap:function(){return f("tlswrap")}}}function A(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,I,d){return d===void 0&&(d=I,I={}),S(I=C(y,I),d).dispatch(y)}}).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,t,e){(function(n,r,s,a,l,p,h,v,E){(function(b){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,g="+".charCodeAt(0),O="/".charCodeAt(0),C="0".charCodeAt(0),x="a".charCodeAt(0),S="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function I(d){return d=d.charCodeAt(0),d===g||d===A?62:d===O||d===y?63:d<C?-1:d<C+10?d-C+26+26:d<S+26?d-S:d<x+26?d-x+26:void 0}b.toByteArray=function(d){var f,c;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=d.length,w=d.charAt(w-2)==="="?2:d.charAt(w-1)==="="?1:0,D=new P(3*d.length/4-w),F=0<w?d.length-4:d.length,R=0;function j(M){D[R++]=M}for(f=0;f<F;f+=4,0)j((16711680&(c=I(d.charAt(f))<<18|I(d.charAt(f+1))<<12|I(d.charAt(f+2))<<6|I(d.charAt(f+3))))>>16),j((65280&c)>>8),j(255&c);return w==2?j(255&(c=I(d.charAt(f))<<2|I(d.charAt(f+1))>>4)):w==1&&(j((c=I(d.charAt(f))<<10|I(d.charAt(f+1))<<4|I(d.charAt(f+2))>>2)>>8&255),j(255&c)),D},b.fromByteArray=function(d){var f,c,w,D,F=d.length%3,R="";function j(M){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(M)}for(f=0,w=d.length-F;f<w;f+=3)c=(d[f]<<16)+(d[f+1]<<8)+d[f+2],R+=j((D=c)>>18&63)+j(D>>12&63)+j(D>>6&63)+j(63&D);switch(F){case 1:R=(R+=j((c=d[d.length-1])>>2))+j(c<<4&63)+"==";break;case 2:R=(R=(R+=j((c=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(c>>4&63))+j(c<<2&63)+"="}return R}})(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,t,e){(function(n,r,g,a,l,p,h,v,E){var b=i("base64-js"),P=i("ieee754");function g(o,u,m){if(!(this instanceof g))return new g(o,u,m);var T,_,k,L,Q=typeof o;if(u==="base64"&&Q=="string")for(o=(L=o).trim?L.trim():L.replace(/^\s+|\s+$/g,"");o.length%4!=0;)o+="=";if(Q=="number")T=ee(o);else if(Q=="string")T=g.byteLength(o,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");T=ee(o.length)}if(g._useTypedArrays?_=g._augment(new Uint8Array(T)):((_=this).length=T,_._isBuffer=!0),g._useTypedArrays&&typeof o.byteLength=="number")_._set(o);else if(H(L=o)||g.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(k=0;k<T;k++)g.isBuffer(o)?_[k]=o.readUInt8(k):_[k]=o[k];else if(Q=="string")_.write(o,0,u);else if(Q=="number"&&!g._useTypedArrays&&!m)for(k=0;k<T;k++)_[k]=0;return _}function O(o,u,m,T){return g._charsWritten=dt(function(_){for(var k=[],L=0;L<_.length;L++)k.push(255&_.charCodeAt(L));return k}(u),o,m,T)}function C(o,u,m,T){return g._charsWritten=dt(function(_){for(var k,L,Q=[],Y=0;Y<_.length;Y++)L=_.charCodeAt(Y),k=L>>8,L=L%256,Q.push(L),Q.push(k);return Q}(u),o,m,T)}function x(o,u,m){var T="";m=Math.min(o.length,m);for(var _=u;_<m;_++)T+=String.fromCharCode(o[_]);return T}function S(o,u,m,k){k||(B(typeof m=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length"));var _,k=o.length;if(!(k<=u))return m?(_=o[u],u+1<k&&(_|=o[u+1]<<8)):(_=o[u]<<8,u+1<k&&(_|=o[u+1])),_}function A(o,u,m,k){k||(B(typeof m=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length"));var _,k=o.length;if(!(k<=u))return m?(u+2<k&&(_=o[u+2]<<16),u+1<k&&(_|=o[u+1]<<8),_|=o[u],u+3<k&&(_+=o[u+3]<<24>>>0)):(u+1<k&&(_=o[u+1]<<16),u+2<k&&(_|=o[u+2]<<8),u+3<k&&(_|=o[u+3]),_+=o[u]<<24>>>0),_}function y(o,u,m,T){if(T||(B(typeof m=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=S(o,u,m,!0),32768&T?-1*(65535-T+1):T}function I(o,u,m,T){if(T||(B(typeof m=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=A(o,u,m,!0),2147483648&T?-1*(4294967295-T+1):T}function d(o,u,m,T){return T||(B(typeof m=="boolean","missing or invalid endian"),B(u+3<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,23,4)}function f(o,u,m,T){return T||(B(typeof m=="boolean","missing or invalid endian"),B(u+7<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,52,8)}function c(o,u,m,T,_){if(_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+1<o.length,"trying to write beyond buffer length"),bn(u,65535)),_=o.length,!(_<=m))for(var k=0,L=Math.min(_-m,2);k<L;k++)o[m+k]=(u&255<<8*(T?k:1-k))>>>8*(T?k:1-k)}function w(o,u,m,T,_){if(_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+3<o.length,"trying to write beyond buffer length"),bn(u,4294967295)),_=o.length,!(_<=m))for(var k=0,L=Math.min(_-m,4);k<L;k++)o[m+k]=u>>>8*(T?k:3-k)&255}function D(o,u,m,T,_){_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+1<o.length,"Trying to write beyond buffer length"),wn(u,32767,-32768)),o.length<=m||c(o,0<=u?u:65535+u+1,m,T,_)}function F(o,u,m,T,_){_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+3<o.length,"Trying to write beyond buffer length"),wn(u,2147483647,-2147483648)),o.length<=m||w(o,0<=u?u:4294967295+u+1,m,T,_)}function R(o,u,m,T,_){_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+3<o.length,"Trying to write beyond buffer length"),ii(u,34028234663852886e22,-34028234663852886e22)),o.length<=m||P.write(o,u,m,T,23,4)}function j(o,u,m,T,_){_||(B(u!=null,"missing value"),B(typeof T=="boolean","missing or invalid endian"),B(m!=null,"missing offset"),B(m+7<o.length,"Trying to write beyond buffer length"),ii(u,17976931348623157e292,-17976931348623157e292)),o.length<=m||P.write(o,u,m,T,52,8)}e.Buffer=g,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var o=new ArrayBuffer(0),u=new Uint8Array(o);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),g.isEncoding=function(o){switch(String(o).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}},g.isBuffer=function(o){return!(o==null||!o._isBuffer)},g.byteLength=function(o,u){var m;switch(o+="",u||"utf8"){case"hex":m=o.length/2;break;case"utf8":case"utf-8":m=be(o).length;break;case"ascii":case"binary":case"raw":m=o.length;break;case"base64":m=ti(o).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=2*o.length;break;default:throw new Error("Unknown encoding")}return m},g.concat=function(o,u){if(B(H(o),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),o.length===0)return new g(0);if(o.length===1)return o[0];if(typeof u!="number")for(_=u=0;_<o.length;_++)u+=o[_].length;for(var m=new g(u),T=0,_=0;_<o.length;_++){var k=o[_];k.copy(m,T),T+=k.length}return m},g.prototype.write=function(o,u,m,T){isFinite(u)?isFinite(m)||(T=m,m=void 0):(Y=T,T=u,u=m,m=Y),u=Number(u)||0;var _,k,L,Q,Y=this.length-u;switch((!m||Y<(m=Number(m)))&&(m=Y),T=String(T||"utf8").toLowerCase()){case"hex":_=function(he,ie,re,G){re=Number(re)||0;var J=he.length-re;(!G||J<(G=Number(G)))&&(G=J),B((J=ie.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var Fe=0;Fe<G;Fe++){var ri=parseInt(ie.substr(2*Fe,2),16);B(!isNaN(ri),"Invalid hex string"),he[re+Fe]=ri}return g._charsWritten=2*Fe,Fe}(this,o,u,m);break;case"utf8":case"utf-8":k=this,L=u,Q=m,_=g._charsWritten=dt(be(o),k,L,Q);break;case"ascii":case"binary":_=O(this,o,u,m);break;case"base64":k=this,L=u,Q=m,_=g._charsWritten=dt(ti(o),k,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=C(this,o,u,m);break;default:throw new Error("Unknown encoding")}return _},g.prototype.toString=function(o,u,m){var T,_,k,L,Q=this;if(o=String(o||"utf8").toLowerCase(),u=Number(u)||0,(m=m!==void 0?Number(m):Q.length)===u)return"";switch(o){case"hex":T=function(Y,he,ie){var re=Y.length;(!he||he<0)&&(he=0),(!ie||ie<0||re<ie)&&(ie=re);for(var G="",J=he;J<ie;J++)G+=$(Y[J]);return G}(Q,u,m);break;case"utf8":case"utf-8":T=function(Y,he,ie){var re="",G="";ie=Math.min(Y.length,ie);for(var J=he;J<ie;J++)Y[J]<=127?(re+=ni(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return re+ni(G)}(Q,u,m);break;case"ascii":case"binary":T=x(Q,u,m);break;case"base64":_=Q,L=m,T=(k=u)===0&&L===_.length?b.fromByteArray(_):b.fromByteArray(_.slice(k,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":T=function(Y,he,ie){for(var re=Y.slice(he,ie),G="",J=0;J<re.length;J+=2)G+=String.fromCharCode(re[J]+256*re[J+1]);return G}(Q,u,m);break;default:throw new Error("Unknown encoding")}return T},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(o,u,m,T){if(u=u||0,(T=T||T===0?T:this.length)!==(m=m||0)&&o.length!==0&&this.length!==0){B(m<=T,"sourceEnd < sourceStart"),B(0<=u&&u<o.length,"targetStart out of bounds"),B(0<=m&&m<this.length,"sourceStart out of bounds"),B(0<=T&&T<=this.length,"sourceEnd out of bounds"),T>this.length&&(T=this.length);var _=(T=o.length-u<T-m?o.length-u+m:T)-m;if(_<100||!g._useTypedArrays)for(var k=0;k<_;k++)o[k+u]=this[k+m];else o._set(this.subarray(m,m+_),u)}},g.prototype.slice=function(o,u){var m=this.length;if(o=q(o,m,0),u=q(u,m,m),g._useTypedArrays)return g._augment(this.subarray(o,u));for(var T=u-o,_=new g(T,void 0,!0),k=0;k<T;k++)_[k]=this[k+o];return _},g.prototype.get=function(o){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(o)},g.prototype.set=function(o,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(o,u)},g.prototype.readUInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return this[o]},g.prototype.readUInt16LE=function(o,u){return S(this,o,!0,u)},g.prototype.readUInt16BE=function(o,u){return S(this,o,!1,u)},g.prototype.readUInt32LE=function(o,u){return A(this,o,!0,u)},g.prototype.readUInt32BE=function(o,u){return A(this,o,!1,u)},g.prototype.readInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return 128&this[o]?-1*(255-this[o]+1):this[o]},g.prototype.readInt16LE=function(o,u){return y(this,o,!0,u)},g.prototype.readInt16BE=function(o,u){return y(this,o,!1,u)},g.prototype.readInt32LE=function(o,u){return I(this,o,!0,u)},g.prototype.readInt32BE=function(o,u){return I(this,o,!1,u)},g.prototype.readFloatLE=function(o,u){return d(this,o,!0,u)},g.prototype.readFloatBE=function(o,u){return d(this,o,!1,u)},g.prototype.readDoubleLE=function(o,u){return f(this,o,!0,u)},g.prototype.readDoubleBE=function(o,u){return f(this,o,!1,u)},g.prototype.writeUInt8=function(o,u,m){m||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"trying to write beyond buffer length"),bn(o,255)),u>=this.length||(this[u]=o)},g.prototype.writeUInt16LE=function(o,u,m){c(this,o,u,!0,m)},g.prototype.writeUInt16BE=function(o,u,m){c(this,o,u,!1,m)},g.prototype.writeUInt32LE=function(o,u,m){w(this,o,u,!0,m)},g.prototype.writeUInt32BE=function(o,u,m){w(this,o,u,!1,m)},g.prototype.writeInt8=function(o,u,m){m||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"Trying to write beyond buffer length"),wn(o,127,-128)),u>=this.length||(0<=o?this.writeUInt8(o,u,m):this.writeUInt8(255+o+1,u,m))},g.prototype.writeInt16LE=function(o,u,m){D(this,o,u,!0,m)},g.prototype.writeInt16BE=function(o,u,m){D(this,o,u,!1,m)},g.prototype.writeInt32LE=function(o,u,m){F(this,o,u,!0,m)},g.prototype.writeInt32BE=function(o,u,m){F(this,o,u,!1,m)},g.prototype.writeFloatLE=function(o,u,m){R(this,o,u,!0,m)},g.prototype.writeFloatBE=function(o,u,m){R(this,o,u,!1,m)},g.prototype.writeDoubleLE=function(o,u,m){j(this,o,u,!0,m)},g.prototype.writeDoubleBE=function(o,u,m){j(this,o,u,!1,m)},g.prototype.fill=function(o,u,m){if(u=u||0,m=m||this.length,B(typeof(o=typeof(o=o||0)=="string"?o.charCodeAt(0):o)=="number"&&!isNaN(o),"value is not a number"),B(u<=m,"end < start"),m!==u&&this.length!==0){B(0<=u&&u<this.length,"start out of bounds"),B(0<=m&&m<=this.length,"end out of bounds");for(var T=u;T<m;T++)this[T]=o}},g.prototype.inspect=function(){for(var o=[],u=this.length,m=0;m<u;m++)if(o[m]=$(this[m]),m===e.INSPECT_MAX_BYTES){o[m+1]="...";break}return"<Buffer "+o.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var o=new Uint8Array(this.length),u=0,m=o.length;u<m;u+=1)o[u]=this[u];return o.buffer};var M=g.prototype;function q(o,u,m){return typeof o!="number"?m:u<=(o=~~o)?u:0<=o||0<=(o+=u)?o:0}function ee(o){return(o=~~Math.ceil(+o))<0?0:o}function H(o){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(o)}function $(o){return o<16?"0"+o.toString(16):o.toString(16)}function be(o){for(var u=[],m=0;m<o.length;m++){var T=o.charCodeAt(m);if(T<=127)u.push(o.charCodeAt(m));else for(var _=m,k=(55296<=T&&T<=57343&&m++,encodeURIComponent(o.slice(_,m+1)).substr(1).split("%")),L=0;L<k.length;L++)u.push(parseInt(k[L],16))}return u}function ti(o){return b.toByteArray(o)}function dt(o,u,m,T){for(var _=0;_<T&&!(_+m>=u.length||_>=o.length);_++)u[_+m]=o[_];return _}function ni(o){try{return decodeURIComponent(o)}catch{return String.fromCharCode(65533)}}function bn(o,u){B(typeof o=="number","cannot write a non-number as a number"),B(0<=o,"specified a negative value for writing an unsigned value"),B(o<=u,"value is larger than maximum value for type"),B(Math.floor(o)===o,"value has a fractional component")}function wn(o,u,m){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(m<=o,"value smaller than minimum allowed value"),B(Math.floor(o)===o,"value has a fractional component")}function ii(o,u,m){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(m<=o,"value smaller than minimum allowed value")}function B(o,u){if(!o)throw new Error(u||"Failed assertion")}g._augment=function(o){return o._isBuffer=!0,o._get=o.get,o._set=o.set,o.get=M.get,o.set=M.set,o.write=M.write,o.toString=M.toString,o.toLocaleString=M.toString,o.toJSON=M.toJSON,o.copy=M.copy,o.slice=M.slice,o.readUInt8=M.readUInt8,o.readUInt16LE=M.readUInt16LE,o.readUInt16BE=M.readUInt16BE,o.readUInt32LE=M.readUInt32LE,o.readUInt32BE=M.readUInt32BE,o.readInt8=M.readInt8,o.readInt16LE=M.readInt16LE,o.readInt16BE=M.readInt16BE,o.readInt32LE=M.readInt32LE,o.readInt32BE=M.readInt32BE,o.readFloatLE=M.readFloatLE,o.readFloatBE=M.readFloatBE,o.readDoubleLE=M.readDoubleLE,o.readDoubleBE=M.readDoubleBE,o.writeUInt8=M.writeUInt8,o.writeUInt16LE=M.writeUInt16LE,o.writeUInt16BE=M.writeUInt16BE,o.writeUInt32LE=M.writeUInt32LE,o.writeUInt32BE=M.writeUInt32BE,o.writeInt8=M.writeInt8,o.writeInt16LE=M.writeInt16LE,o.writeInt16BE=M.writeInt16BE,o.writeInt32LE=M.writeInt32LE,o.writeInt32BE=M.writeInt32BE,o.writeFloatLE=M.writeFloatLE,o.writeFloatBE=M.writeFloatBE,o.writeDoubleLE=M.writeDoubleLE,o.writeDoubleBE=M.writeDoubleBE,o.fill=M.fill,o.inspect=M.inspect,o.toArrayBuffer=M.toArrayBuffer,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/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,b,a,l,p,h,v,E){var b=i("buffer").Buffer,P=4,g=new b(P);g.fill(0),t.exports={hash:function(O,C,x,S){for(var A=C(function(c,w){c.length%P!=0&&(D=c.length+(P-c.length%P),c=b.concat([c,g],D));for(var D,F=[],R=w?c.readInt32BE:c.readInt32LE,j=0;j<c.length;j+=P)F.push(R.call(c,j));return F}(O=b.isBuffer(O)?O:new b(O),S),8*O.length),C=S,y=new b(x),I=C?y.writeInt32BE:y.writeInt32LE,d=0;d<A.length;d++)I.call(y,A[d],4*d,!0);return y}}}).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,t,e){(function(n,r,b,a,l,p,h,v,E){var b=i("buffer").Buffer,P=i("./sha"),g=i("./sha256"),O=i("./rng"),C={sha1:P,sha256:g,md5:i("./md5")},x=64,S=new b(x);function A(c,w){var D=C[c=c||"sha1"],F=[];return D||y("algorithm:",c,"is not yet supported"),{update:function(R){return b.isBuffer(R)||(R=new b(R)),F.push(R),R.length,this},digest:function(R){var j=b.concat(F),j=w?function(M,q,ee){b.isBuffer(q)||(q=new b(q)),b.isBuffer(ee)||(ee=new b(ee)),q.length>x?q=M(q):q.length<x&&(q=b.concat([q,S],x));for(var H=new b(x),$=new b(x),be=0;be<x;be++)H[be]=54^q[be],$[be]=92^q[be];return ee=M(b.concat([H,ee])),M(b.concat([$,ee]))}(D,w,j):D(j);return F=null,R?j.toString(R):j}}}function y(){var c=[].slice.call(arguments).join(" ");throw new Error([c,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
+ `))}S.fill(0),e.createHash=function(c){return A(c)},e.createHmac=A,e.randomBytes=function(c,w){if(!w||!w.call)return new b(O(c));try{w.call(this,void 0,new b(O(c)))}catch(D){w(D)}};var I,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],f=function(c){e[c]=function(){y("sorry,",c,"is not implemented yet")}};for(I in d)f(d[I],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/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,t,e){(function(n,r,s,a,l,p,h,v,E){var b=i("./helpers");function P(y,I){y[I>>5]|=128<<I%32,y[14+(I+64>>>9<<4)]=I;for(var d=1732584193,f=-271733879,c=-1732584194,w=271733878,D=0;D<y.length;D+=16){var F=d,R=f,j=c,M=w,d=O(d,f,c,w,y[D+0],7,-680876936),w=O(w,d,f,c,y[D+1],12,-389564586),c=O(c,w,d,f,y[D+2],17,606105819),f=O(f,c,w,d,y[D+3],22,-1044525330);d=O(d,f,c,w,y[D+4],7,-176418897),w=O(w,d,f,c,y[D+5],12,1200080426),c=O(c,w,d,f,y[D+6],17,-1473231341),f=O(f,c,w,d,y[D+7],22,-45705983),d=O(d,f,c,w,y[D+8],7,1770035416),w=O(w,d,f,c,y[D+9],12,-1958414417),c=O(c,w,d,f,y[D+10],17,-42063),f=O(f,c,w,d,y[D+11],22,-1990404162),d=O(d,f,c,w,y[D+12],7,1804603682),w=O(w,d,f,c,y[D+13],12,-40341101),c=O(c,w,d,f,y[D+14],17,-1502002290),d=C(d,f=O(f,c,w,d,y[D+15],22,1236535329),c,w,y[D+1],5,-165796510),w=C(w,d,f,c,y[D+6],9,-1069501632),c=C(c,w,d,f,y[D+11],14,643717713),f=C(f,c,w,d,y[D+0],20,-373897302),d=C(d,f,c,w,y[D+5],5,-701558691),w=C(w,d,f,c,y[D+10],9,38016083),c=C(c,w,d,f,y[D+15],14,-660478335),f=C(f,c,w,d,y[D+4],20,-405537848),d=C(d,f,c,w,y[D+9],5,568446438),w=C(w,d,f,c,y[D+14],9,-1019803690),c=C(c,w,d,f,y[D+3],14,-187363961),f=C(f,c,w,d,y[D+8],20,1163531501),d=C(d,f,c,w,y[D+13],5,-1444681467),w=C(w,d,f,c,y[D+2],9,-51403784),c=C(c,w,d,f,y[D+7],14,1735328473),d=x(d,f=C(f,c,w,d,y[D+12],20,-1926607734),c,w,y[D+5],4,-378558),w=x(w,d,f,c,y[D+8],11,-2022574463),c=x(c,w,d,f,y[D+11],16,1839030562),f=x(f,c,w,d,y[D+14],23,-35309556),d=x(d,f,c,w,y[D+1],4,-1530992060),w=x(w,d,f,c,y[D+4],11,1272893353),c=x(c,w,d,f,y[D+7],16,-155497632),f=x(f,c,w,d,y[D+10],23,-1094730640),d=x(d,f,c,w,y[D+13],4,681279174),w=x(w,d,f,c,y[D+0],11,-358537222),c=x(c,w,d,f,y[D+3],16,-722521979),f=x(f,c,w,d,y[D+6],23,76029189),d=x(d,f,c,w,y[D+9],4,-640364487),w=x(w,d,f,c,y[D+12],11,-421815835),c=x(c,w,d,f,y[D+15],16,530742520),d=S(d,f=x(f,c,w,d,y[D+2],23,-995338651),c,w,y[D+0],6,-198630844),w=S(w,d,f,c,y[D+7],10,1126891415),c=S(c,w,d,f,y[D+14],15,-1416354905),f=S(f,c,w,d,y[D+5],21,-57434055),d=S(d,f,c,w,y[D+12],6,1700485571),w=S(w,d,f,c,y[D+3],10,-1894986606),c=S(c,w,d,f,y[D+10],15,-1051523),f=S(f,c,w,d,y[D+1],21,-2054922799),d=S(d,f,c,w,y[D+8],6,1873313359),w=S(w,d,f,c,y[D+15],10,-30611744),c=S(c,w,d,f,y[D+6],15,-1560198380),f=S(f,c,w,d,y[D+13],21,1309151649),d=S(d,f,c,w,y[D+4],6,-145523070),w=S(w,d,f,c,y[D+11],10,-1120210379),c=S(c,w,d,f,y[D+2],15,718787259),f=S(f,c,w,d,y[D+9],21,-343485551),d=A(d,F),f=A(f,R),c=A(c,j),w=A(w,M)}return Array(d,f,c,w)}function g(y,I,d,f,c,w){return A((I=A(A(I,y),A(f,w)))<<c|I>>>32-c,d)}function O(y,I,d,f,c,w,D){return g(I&d|~I&f,y,I,c,w,D)}function C(y,I,d,f,c,w,D){return g(I&f|d&~f,y,I,c,w,D)}function x(y,I,d,f,c,w,D){return g(I^d^f,y,I,c,w,D)}function S(y,I,d,f,c,w,D){return g(d^(I|~f),y,I,c,w,D)}function A(y,I){var d=(65535&y)+(65535&I);return(y>>16)+(I>>16)+(d>>16)<<16|65535&d}t.exports=function(y){return b.hash(y,P,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,t,e){(function(n,r,s,a,l,p,h,v,E){var b;t.exports=b||function(P){for(var g,O=new Array(P),C=0;C<P;C++)!(3&C)&&(g=4294967296*Math.random()),O[C]=g>>>((3&C)<<3)&255;return 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/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,s,a,l,p,h,v,E){var b=i("./helpers");function P(C,x){C[x>>5]|=128<<24-x%32,C[15+(x+64>>9<<4)]=x;for(var S,A,y,I=Array(80),d=1732584193,f=-271733879,c=-1732584194,w=271733878,D=-1009589776,F=0;F<C.length;F+=16){for(var R=d,j=f,M=c,q=w,ee=D,H=0;H<80;H++){I[H]=H<16?C[F+H]:O(I[H-3]^I[H-8]^I[H-14]^I[H-16],1);var $=g(g(O(d,5),($=f,A=c,y=w,(S=H)<20?$&A|~$&y:!(S<40)&&S<60?$&A|$&y|A&y:$^A^y)),g(g(D,I[H]),(S=H)<20?1518500249:S<40?1859775393:S<60?-1894007588:-899497514)),D=w,w=c,c=O(f,30),f=d,d=$}d=g(d,R),f=g(f,j),c=g(c,M),w=g(w,q),D=g(D,ee)}return Array(d,f,c,w,D)}function g(C,x){var S=(65535&C)+(65535&x);return(C>>16)+(x>>16)+(S>>16)<<16|65535&S}function O(C,x){return C<<x|C>>>32-x}t.exports=function(C){return b.hash(C,P,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,t,e){(function(n,r,s,a,l,p,h,v,E){function b(x,S){var A=(65535&x)+(65535&S);return(x>>16)+(S>>16)+(A>>16)<<16|65535&A}function P(x,S){var A,y=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),I=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);x[S>>5]|=128<<24-S%32,x[15+(S+64>>9<<4)]=S;for(var f,c,w=0;w<x.length;w+=16){for(var D=I[0],F=I[1],R=I[2],j=I[3],M=I[4],q=I[5],ee=I[6],H=I[7],$=0;$<64;$++)d[$]=$<16?x[$+w]:b(b(b((c=d[$-2],O(c,17)^O(c,19)^C(c,10)),d[$-7]),(c=d[$-15],O(c,7)^O(c,18)^C(c,3))),d[$-16]),A=b(b(b(b(H,O(c=M,6)^O(c,11)^O(c,25)),M&q^~M&ee),y[$]),d[$]),f=b(O(f=D,2)^O(f,13)^O(f,22),D&F^D&R^F&R),H=ee,ee=q,q=M,M=b(j,A),j=R,R=F,F=D,D=b(A,f);I[0]=b(D,I[0]),I[1]=b(F,I[1]),I[2]=b(R,I[2]),I[3]=b(j,I[3]),I[4]=b(M,I[4]),I[5]=b(q,I[5]),I[6]=b(ee,I[6]),I[7]=b(H,I[7])}return I}var g=i("./helpers"),O=function(x,S){return x>>>S|x<<32-S},C=function(x,S){return x>>>S};t.exports=function(x){return g.hash(x,P,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,t,e){(function(n,r,s,a,l,p,h,v,E){e.read=function(b,P,g,O,w){var x,S,A=8*w-O-1,y=(1<<A)-1,I=y>>1,d=-7,f=g?w-1:0,c=g?-1:1,w=b[P+f];for(f+=c,x=w&(1<<-d)-1,w>>=-d,d+=A;0<d;x=256*x+b[P+f],f+=c,d-=8);for(S=x&(1<<-d)-1,x>>=-d,d+=O;0<d;S=256*S+b[P+f],f+=c,d-=8);if(x===0)x=1-I;else{if(x===y)return S?NaN:1/0*(w?-1:1);S+=Math.pow(2,O),x-=I}return(w?-1:1)*S*Math.pow(2,x-O)},e.write=function(b,P,g,O,C,D){var S,A,y=8*D-C-1,I=(1<<y)-1,d=I>>1,f=C===23?Math.pow(2,-24)-Math.pow(2,-77):0,c=O?0:D-1,w=O?1:-1,D=P<0||P===0&&1/P<0?1:0;for(P=Math.abs(P),isNaN(P)||P===1/0?(A=isNaN(P)?1:0,S=I):(S=Math.floor(Math.log(P)/Math.LN2),P*(O=Math.pow(2,-S))<1&&(S--,O*=2),2<=(P+=1<=S+d?f/O:f*Math.pow(2,1-d))*O&&(S++,O/=2),I<=S+d?(A=0,S=I):1<=S+d?(A=(P*O-1)*Math.pow(2,C),S+=d):(A=P*Math.pow(2,d-1)*Math.pow(2,C),S=0));8<=C;b[g+c]=255&A,c+=w,A/=256,C-=8);for(S=S<<C|A,y+=C;0<y;b[g+c]=255&S,c+=w,S/=256,y-=8);b[g+c-w]|=128*D}}).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,t,e){(function(n,r,s,a,l,p,h,v,E){var b,P,g;function O(){}(n=t.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(C){return window.setImmediate(C)}:g?(b=[],window.addEventListener("message",function(C){var x=C.source;x!==window&&x!==null||C.data!=="process-tick"||(C.stopPropagation(),0<b.length&&b.shift()())},!0),function(C){b.push(C),window.postMessage("process-tick","*")}):function(C){setTimeout(C,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=O,n.addListener=O,n.once=O,n.off=O,n.removeListener=O,n.removeAllListeners=O,n.emit=O,n.binding=function(C){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(C){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 ei={};pr(ei,{Client:()=>Re,ClientDescriptor:()=>gn,Entity:()=>ye,EntityFile:()=>ke,MigrationPathError:()=>Ve,ServerSync:()=>Ke,Storage:()=>Re,StorageDescriptor:()=>gn,collection:()=>zi,createDefaultMigration:()=>zn,createMigration:()=>$n,migrate:()=>Bt,schema:()=>$i});var Si=ut(ht(),1),mt=4,Qe=36;function yi(i){return i.toString(Qe).padStart(mt,"0")}function Sr(i){return i.toString().padStart(6,"0")}var yt=class{constructor(){this.latest={time:Date.now(),counter:0,node:xr()};this.zeroCounter=0;this.now=t=>(this.latest=bi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=bi(this.latest),Sr(t)+Ir(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(mt);this.latest=Or(this.latest,wi(e))};this.get=(t,e)=>yi(t)+gi(e);this.zero=t=>yi(t)+gi({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>wi(t.slice(mt)).time}},gt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},bt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Dn=4,Cn=7,wt=60*1e3,He=9;function xr(){return Si.default.slug().padStart(Cn,"0").slice(0,Cn)}function gi(i){let t=new Date(i.time).getTime().toString(Qe).padStart(He,"0"),e=i.counter.toString(Qe).padStart(Dn,"0"),n=i.node.padStart(Cn,"0");return`${t}${e}${n}`}function bi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>wt)throw new gt(e,t,wt);if(n>65535)throw new bt;return{time:e,counter:n,node:i.node}}function Or(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>wt)throw new gt(n,e,wt);if(s>65535)throw new bt;return{time:n,counter:s,node:i.node}}function wi(i){let t=i.slice(0,He),e=i.slice(He,He+Dn),n=i.slice(He+Dn),r=parseInt(t,Qe),s=parseInt(e,Qe);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function Ir(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function vi(i){return parseInt(i.slice(0,mt),36)}function xi(i,t){return vi(i)-vi(t)}function se(i){return i&&i["@@type"]==="file"}function Oi(i){return{"@@type":"file",id:i}}var vt,Dr=new Uint8Array(16);function En(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(Dr)}var Ii=/^(?:[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 Cr(i){return typeof i=="string"&&Ii.test(i)}var Di=Cr;var X=[];for(St=0;St<256;++St)X.push((St+256).toString(16).substr(1));var St;function Er(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(X[i[t+0]]+X[i[t+1]]+X[i[t+2]]+X[i[t+3]]+"-"+X[i[t+4]]+X[i[t+5]]+"-"+X[i[t+6]]+X[i[t+7]]+"-"+X[i[t+8]]+X[i[t+9]]+"-"+X[i[t+10]]+X[i[t+11]]+X[i[t+12]]+X[i[t+13]]+X[i[t+14]]+X[i[t+15]]).toLowerCase();if(!Di(e))throw TypeError("Stringified UUID is invalid");return e}var Ci=Er;function Pr(i,t,e){i=i||{};var n=i.random||(i.rng||En)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return Ci(n)}var Je=Pr;function ne(i){return te(i)||se(i)}function Ei(i,t){return i===t?!0:!(!ne(i)||!ne(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Ai=ut(Ti(),1);function _r(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Ye(i){return JSON.stringify(i,_r)}function oe(i,t=!0){if(z(i)||Array.isArray(i)){let e=ae(i),n;if(Array.isArray(i))n=i.map(r=>oe(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=oe(s,t)}return t&&e&&K(n,e),n}return i}function Se(i){return(0,Ai.default)(i)}function z(i){return i&&typeof i=="object"}function Bi(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function xt(i=16){return Je().replace("-","").slice(0,i)}function ki(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Mi(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Ie="__@@oid_do_not_use",De="@@id",Tr="/",Xe=":",_n=new WeakMap;function ce(i){let t=ae(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function ae(i){if(z(i))return _n.get(i)??i[De]??i[Ie]}function K(i,t){return V(z(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Dt(i),_n.set(i,t),i}function Ze(i){return!!ae(i)}function Dt(i){return _n.delete(i),i}function Tn(i){return i===De||i===Ie}function An(i,t,e){if(Ze(i))return ce(i);{let n=ge(t,e);return K(i,n),n}}function Ri(i,t,e){if(Ze(i)){let n=ce(i);if(Ct(n,t))return ce(i);{let r=ge(t,e);return K(i,r),r}}else{let n=ge(t,e);return K(i,n),n}}var Pn={".":"&dot;","/":"&slash;",":":"&colon;"};function Fi(i){return i.replace(/[/]/g,Pn["/"]).replace(/[:]/g,Pn[":"]).replace(/[.]/g,Pn["."])}function ji(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,t,e){let n=Fi(i)+Tr+Fi(t);return e&&(n+=Xe+e),n}function ge(i,t=Mr){let{collection:e,id:n}=le(i);return Z(e,n,t())}function le(i){let[t,e]=i.split(Xe),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:ji(n),id:ji(s),subId:e}}function je(i,t){let e=ce(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],z(n)&&!ne(n)&&(Ri(n,e,t),je(n,t))}else if(z(i)&&!ne(i))for(let n of Object.keys(i))z(i[n])&&!ne(i[n])&&(Ri(i[n],e,t),je(i[n],t))}function Ar(i){if(z(i))return i[De]||i[Ie]}function Br(i){return z(i)&&(delete i[Ie],delete i[De]),i}function kr(i){let t=Ar(i);t&&K(i,t)}function Ge(i){if(kr(i),Br(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ge(i[t]);else if(z(i))for(let t of Object.keys(i))Ge(i[t])}function Ot(i){if(Dt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ot(i[t]);else if(z(i))for(let t of Object.keys(i))Ot(i[t])}function Mr(){return Je().slice(0,8)}function we(i){return{"@@type":"ref",id:i}}function It(i,t=new Map){if(Array.isArray(i)){let e=ce(i),n=K([],e);for(let r=0;r<i.length;r++){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s)){n[r]=s;continue}else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else if(z(i)&&!ne(i)){let e=ce(i),n=K({},e);for(let r of Object.keys(i)){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s))n[r]=s;else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else ne(i);return t}function U(i){return i.split(".")[0].split(Xe)[0]}function Bn(i){let t=U(i),e=ge(t,()=>"\uFFFF");return[`${t}${Xe}`,e]}function Li(i){let t=U(i);return[`${t}.`,`${t}.\uFFFF`]}function Ct(i,t){return U(i)===U(t)}function kn(i){return i.split(Xe)[0].includes(".")}function te(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Mn(i){return z(i)&&!ne(i)}function Rr(i,t){return i===t?!0:ne(i)&&ne(t)?Ei(i,t):!1}function et(i,t,e,n,r=[],s={}){let a=ce(i);function l(p,h,v){if(!Mn(h))Rr(h,v)||r.push({oid:a,timestamp:e(),data:{op:"set",name:p,value:h}});else{let E=ae(v),b=ae(h);b&&!Ct(a,b)?(h=oe(h,!1),b=ge(a,n),K(h,b)):s.mergeUnknownObjects?!b&&E?(K(h,E),b=E):b=An(h,a,n):b=An(h,a,n),V(!!b,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Ct(a,b),`Error: value OID ${b} is not related to parent OID ${a}. This is a bug in Verdant.`),v===void 0||b!==E?(xe(h,b,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:p,value:we(b)}}),E!==void 0&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})):et(v,h,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let h=0;h<t.length;h++){let v=t[h],E=i[h];l(h,v,E)}let p=i.length-t.length;if(p>0){for(let h=t.length;h<i.length;h++){let v=i[h],E=ae(v);E&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:p}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Mn(i)&&Mn(t)){let p=new Set(Object.keys(i));for(let[h,v]of Object.entries(t)){if(v===void 0&&s.defaultUndefined||(p.delete(h),Tn(h)))continue;let E=i[h];l(h,v,E)}if(!s.defaultUndefined)for(let h of p)Tn(h)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:h}})}}return r}function xe(i,t,e,n,r=[]){K(i,t),je(i,n);let s=It(i);for(let a of s.keys()){let l=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Dt(l)}})}return r}function Ni(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Rn(i){let t={};for(let e of i){let n=U(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Fn(i){let t={};for(let e of i){let n=U(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Ce(i){return Array.isArray(i)?!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: ${ae(i)})`),!1)}function Ee(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(l){e&&ne(l)&&e.push(l)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":Ce(i)&&i.push(t.value);break;case"list-delete":Ce(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Ce(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(Ce(i))do{let l=t.value;t.only==="last"?te(l)?r=ki(i,p=>p.id===l.id):r=i.lastIndexOf(l):te(l)?r=i.findIndex(p=>p.id===l.id):r=i.indexOf(l),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Ce(i)&&(i.some(p=>te(p)&&te(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Ce(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(Ce(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):z(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return oe(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Et(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Vi(r,t,e),z(i[n])&&Et(i[n],t,e)}else if(!se(i)){if(z(i)){V(ae(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Vi(i[n],t,e),z(i[n])&&Et(i[n],t,e)}}return e}function Vi(i,t,e){if(te(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}function Fr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ln(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.type==="object"?!0:i.default!==void 0:!1}function Pt(i){return i.type==="map"||i.type==="object"||i.type==="array"||i.type==="file"||i.type==="any"?!1:i.indexed}function ve(i,t){for(let[e,n]of Object.entries(i.fields)){let r=Ui(n);(r!==void 0&&t[e]===void 0||!Fr(n)&&t[e]===null)&&(t[e]=r),t[e]&&Pe(t[e],n)}return t}function Pe(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=Ui(n);r!==void 0&&(i[e]=r)}Pe(i[e],n)}else if(t.type==="array")for(let e of i)Pe(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===De||e===Ie||Pe(n,t.values)}function Ui(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function Vn(i,t){for(let[e,n]of Object.entries(t))e===De||e===Ie||(i.fields[e]?jn(n,i.fields[e]):delete t[e]);return t}function jn(i,t){if(z(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?jn(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)jn(e,t.items)}function Nn(i){return i.equals!==void 0}function Un(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function jr(i){return!!i.match}function Kn(i){return i.startsWith!==void 0}function Ki(i){return!Un(i)&&!Nn(i)&&!jr(i)&&!Kn(i)&&i.order}function zi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,s]of Object.entries(e.fields))Pt(s)&&(n[r]={field:r});return{...e,indexes:n}}function $i(i){return i}var _t="\uFFFFFE",Lr="\0",Vr="\uFFFFFF";function de(...i){let t=Nr(i);return t.length===1?t[0]:t}function _e(...i){return i.join(_t)+`${Vr}`}function Te(...i){return i.join(_t)+`${_t}${Lr}`}function Nr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(_t))))}function Ur(i){return!!i.field}function Kr(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let s=r;Ur(s)?e[n]=me(t[s.field]):e[n]=me(s.compute(t))}return e}function zr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=de(...r.of.map(s=>t[s])),e),{})}function $r(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>(Pt(r)&&(e[n]=me(t[n])),e),{})}function Tt(i,t){return{[i.primaryKey]:t[i.primaryKey],...$r(i,t),...Kr(i,t),...zr(i,t),"@@@snapshot":t}}var qr="null";function me(i){if(i===null)return qr;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(me);throw new Error(`Unsupported index value: ${i}`)}var qi={version:0,collections:{}};function Bt(i,t,e){let n=typeof t=="function",r=n?qi:i,s=n?i:t,a=n?t:e,l=Object.keys(s.collections).filter(O=>r.collections[O]&&Ye(r.collections[O])!==Ye(s.collections[O])),p=Object.keys(r.collections).filter(O=>!s.collections[O]),h=Object.keys(s.collections).filter(O=>!r.collections[O]),v=new Set;for(let O of l){let C=r.collections[O].fields,x=s.collections[O].fields;Object.keys(x).some(S=>!C[S]?.default&&x[S]?.default)&&v.add(O),Object.keys(C).some(S=>!x[S])&&v.add(O)}let E={},b={};for(let O of[...l,...h]){let C=At(r.collections[O]),x=At(s.collections[O]),S=x.filter(y=>!C.find(I=>I.name===y.name)),A=C.filter(y=>!x.find(I=>I.name===y.name));S.length>0&&(E[O]=S,l.includes(O)&&v.add(O)),A.length>0&&(b[O]=A,l.includes(O)&&v.add(O))}let P=(O,C)=>ve(s.collections[O],C),g=O=>C=>{let x=s.collections[O];return ve(x,Vn(x,C))};return{version:s.version,migrate:async O=>{let C=[];if(await a({migrate:async(x,S)=>{let A=g(x),y=async I=>{let d=await S(I);return K(d,ce(I)),A(d)};await O.migrate(x,y),C.push(x),v.delete(x)},identity:x=>x,withDefaults:P,info:{changedCollections:l,addedCollections:h,removedCollections:p},queries:O.queries,mutations:O.mutations}),s.version>1){O.log("debug","auto-migrating collections with new defaults",v);for(let S of v)await O.migrate(S,g(S)),C.push(S);let x=l.filter(S=>!C.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:p,addedIndexes:E,removedIndexes:b,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function At(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function zn(i,t){return Bt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}function $n(i,t,e){let n=typeof t=="function"||t===void 0,r=n?qi:i,s=n?i:t,a=n?t:e;V(r,"Invalid arguments to createMigration"),V(s,"Invalid arguments to createMigration");let{changedCollections:l,addedCollections:p,removedCollections:h,addedIndexes:v,removedIndexes:E,autoMigratedCollections:b,autoMigration:P}=Wr(r,s);return{version:s.version,migrate:async g=>{let O=[];if(await a?.({migrate:async(x,S)=>{let A=P(x),y=async I=>{let d=await S(I);return K(d,ce(I)),A(d)};await g.migrate(x,y),O.push(x),b.delete(x)},info:{changedCollections:l,addedCollections:p,removedCollections:h},queries:g.queries,mutations:g.mutations}),s.version>1){g.log("debug","auto-migrating collections with new defaults",b);for(let S of b)await g.migrate(S,P(S)),O.push(S);let x=l.filter(S=>!O.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:h,addedIndexes:v,removedIndexes:E,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Wr(i,t){let e=Object.keys(t.collections).filter(v=>i.collections[v]&&Ye(i.collections[v])!==Ye(t.collections[v])),n=Object.keys(i.collections).filter(v=>!t.collections[v]),r=Object.keys(t.collections).filter(v=>!i.collections[v]),s=new Set;for(let v of e){let E=i.collections[v].fields,b=t.collections[v].fields;Object.keys(b).some(P=>!Ln(E[P])&&Ln(b[P]))&&s.add(v),Object.keys(E).some(P=>!b[P])&&s.add(v)}let a={},l={};for(let v of[...e,...r]){let E=At(i.collections[v]),b=At(t.collections[v]),P=b.filter(O=>!E.find(C=>C.name===O.name)),g=E.filter(O=>!b.find(C=>C.name===O.name));P.length>0&&(a[v]=P,e.includes(v)&&s.add(v)),g.length>0&&(l[v]=g,e.includes(v)&&s.add(v))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:a,removedIndexes:l,autoMigratedCollections:s,withDefaults:(v,E)=>ve(t.collections[v],E),autoMigration:v=>E=>{let b=t.collections[v];return ve(b,Vn(b,E))}}}var kt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>xe(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!z(n)||ne(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:we(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(z(e)){let n=ge(t,this.createSubId);return[...xe(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:we(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>z(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:we(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(z(n)){let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:we(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var N=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=xt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Wi(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=oe(t),s=[];for(let a of e){let l=Hr(i,r,a,n);s.unshift(...l),Ee(r,a.data)}return s}function Hr(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(l=>({oid:i,timestamp:n(),data:{op:"list-insert",index:l,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Le=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush())}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new qn({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},qn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);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 t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function tt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),l=0,p=0;a.onsuccess=function(h){let v=a.result;v&&(l++,p=p+Bi(v.value),v.continue())},a.onerror=function(h){n(h)},r.oncomplete=function(h){e({count:l,size:p})},r.onabort=function(h){n(h)},r.onerror=function(h){n(h)}})}function Hi(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return W(s.getAll())});return Promise.all(n)}async function Ae(i){i.close(),await new Promise((t,e)=>{t()})}async function Mt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}function Qi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function Ji(i=window.indexedDB){return i.databases()}var fe=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return W(l)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return Promise.all(l.map(W))};this.iterate=async(t,e,n,r="readonly",s)=>{let l=(s||this.db.transaction(t,r)).objectStore(t),p=e(l);return Array.isArray(p)?Promise.all(p.map(h=>new Promise((v,E)=>{h.onsuccess=()=>{let b=h.result;b?(n(b.value,l),b.continue()):v()},h.onerror=E}))).then(()=>{}):new Promise((h,v)=>{p.onsuccess=()=>{let E=p.result;E?(n(E.value,l),E.continue()):h()},p.onerror=v})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var Rt=class extends fe{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var Ft=class extends fe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let l=U(e),[p,h]=Bn(e);return kn(e)?[a.openCursor(IDBKeyRange.only(l)),a.openCursor(IDBKeyRange.bound(p,h,!1,!1)),a.openCursor(IDBKeyRange.bound(p,h,!1,!1))]:[a.openCursor(IDBKeyRange.only(l)),a.openCursor(IDBKeyRange.bound(p,h,!1,!1))]},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.flatMap(a=>{let l=U(a),[p,h]=Bn(a);if(kn(a)){let[v,E]=Li(a);return[s.get(l),s.getAll(IDBKeyRange.bound(p,h,!1,!1)),s.getAll(IDBKeyRange.bound(v,E,!1,!1))]}else return[s.get(l),s.getAll(IDBKeyRange.bound(p,h,!1,!1))]}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Yi=ut(ht(),1);var jt=class extends fe{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,Yi.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var Lt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(U(l.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(U(l.oid))},{mode:"readwrite"});let a=[];return n||(a=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var Vt=class extends fe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:l="readonly",transaction:p}={})=>{let v=(p||this.db.transaction("operations",l)).objectStore("operations"),E=v.index("d_t"),b=s||a,P=b?de(e,b):Te(e),g=r?de(e,r):_e(e),O=IDBKeyRange.bound(P,g,!!a,!1),C=E.openCursor(O,"next");return new Promise((x,S)=>{let A;C.onsuccess=y=>{let I=C.result;if(I){let d=I.value;V(d.oid.startsWith(e)),V(A===void 0||A<=d.timestamp,`expected ${A} <= ${d.timestamp}`),n(d,v),A=d.timestamp,I.continue()}else x()},C.onerror=y=>{S(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:l})=>{let h=(l||this.db.transaction("operations",a)).objectStore("operations"),v=r?de(e,r):Te(e),E=s?de(e,s):_e(e),b=IDBKeyRange.bound(v,E,!!r,!1),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(A.oid.startsWith(e)),V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,h),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let p=(a||this.db.transaction("operations",s)).objectStore("operations"),h=p.index("l_t"),v=r?de(!0,r):Te(!0),E=n?de(!0,n):_e(!0),b=IDBKeyRange.bound(v,E,!!r,!0),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),e(A,p),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",l=>{let p=a?Te(a):void 0,h=n?_e(n):void 0,v=p&&h?IDBKeyRange.bound(p,h,!1,!0):p?IDBKeyRange.lowerBound(p,!1):h?IDBKeyRange.upperBound(h,!0):void 0;return l.index("timestamp").openCursor(v,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:de(e.oid,e.timestamp),l_t:de(e.isLocal,e.timestamp),d_t:de(U(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add(U(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Nt=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await W(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(s)}}};var nt=class extends N{constructor({disableRebasing:e,context:n}){super();this.time=new yt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=U(e);V(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=U(e);V(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),l=new Map;for(let h of a)h.snapshot&&K(h.snapshot,h.oid),l.set(h.oid,h.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,h=>{let v=l.get(h.oid)||void 0,E=Ee(v,h.data);E&&K(E,h.oid),l.set(h.oid,E)},{transaction:s,to:n.to||this.now});let p=l.get(r);return p&&Et(p,l),p};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add(U(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let l=[];for(let p of r)l.push(await this.rebase(p,n||e,s));this.emit("rebase",l)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),l=await this.baselines.get(e,{transaction:a}),p=l?.snapshot||void 0,h=0,v=[];await this.operations.iterateOverAllOperationsForEntity(e,(b,P)=>{(!l||b.timestamp>l.timestamp)&&(p=Ee(p,b.data,v)),h++,P.delete(b.oid_timestamp)},{to:n,transaction:a}),p&&K(p,e);let E={oid:e,snapshot:p,timestamp:n};if(E.snapshot?await this.baselines.set(E,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",p,"and deleted",h,"operations"),v.length){let b=v.filter(se);b.length&&this.emit("filesDeleted",b)}return E};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
7
7
  ${JSON.stringify(r)}
8
- ${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Wi(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await W(r.objectStore("baselines").clear()),await W(r.objectStore("operations").clear()),await W(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await tt(e,"operations"),r=await tt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Nt(n.metaDb,n.schema.version),this.operations=new Vt(this.db),this.baselines=new Ft(this.db),this.localReplica=new jt(this.db),this.ackInfo=new Rt(this.db),this.messageCreator=new Lt(this),this.patchCreator=new Mt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Hr=[Qr,Jr,Yr,Gr];function Ut({indexedDB:i=window.indexedDB,namespace:t,log:e}){return new Promise((n,r)=>{let s=i.open(`${t}_meta`,4),a=!1;s.onupgradeneeded=async l=>{let f=s.result,h=s.transaction,v=Hr.slice(l.oldVersion);for(let E of v)await E(f,h);l.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{n({db:s.result,wasInitialized:a})}})}async function Yi({wipNamespace:i,namespace:t,indexedDB:e,log:n}){let r=await Ut({namespace:i,indexedDB:e,log:n});if(!r.wasInitialized)return r;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await Ut({namespace:t,indexedDB:e,log:n}),a=s.transaction(["baselines","operations","info"],"readonly"),[l,f,h]=await Promise.all([W(a.objectStore("baselines").getAll()),W(a.objectStore("operations").getAll()),W(a.objectStore("info").getAll())]),v=r.db.transaction(["baselines","operations","info"],"readwrite"),E=v.objectStore("baselines"),b=v.objectStore("operations"),P=v.objectStore("info");for(let g of l)E.put(g);for(let g of f)b.put(g);for(let g of h)P.put(g);return await new Promise((g,O)=>{v.oncomplete=()=>{g()},v.onerror=C=>{O(C)},v.onabort=C=>{O(C)}}),await Ae(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",l.length,"baselines,",f.length,"operations"),r}async function Qr(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Jr(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let{isLocal_timestamp:l,documentOid_timestamp:f,...h}=a.value;a.update({...h,l_t:l,d_t:f}),a.continue()}else n()},s.onerror=a=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Yr(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Gr(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var Xr=i=>IDBKeyRange.only(me(i.equals)),Zr=i=>{},es=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(me(t)):t?e?IDBKeyRange.bound(me(t),me(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(me(t),!!i.gt):IDBKeyRange.upperBound(me(e),!!i.lt)},ts=(i,t,e)=>{let n=i.collections[t].compounds[e.where];V(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((f,h)=>n.of.indexOf(f)-n.of.indexOf(h));for(let f of r)if(n.of.indexOf(f)!==r.indexOf(f))throw new Error(`Compound index ${e.where} does not have ${f} at the start of its order`);let s=r.map(f=>e.match[f]);if(r.length===n.of.length)return IDBKeyRange.only(de(...s));let a=Te(...s),l=_e(...s);return IDBKeyRange.bound(a,l)};function ns(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function Kt(i,t,e){if(e)return Un(e)?es(e):Nn(e)?Xr(e):Ui(e)?Zr(e):Kn(e)?ns(e):ts(i,t,e)}function Wn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function zt({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{l.onsuccess=()=>{let E=l.result;h(E?Z(i,E.primaryKey.toString()):null)},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",l.error),h(null)):v(l.error)}})}async function $t({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{let E=new Set;l.onsuccess=()=>{let b=l.result;b?(E.add(Z(i,b.primaryKey.toString())),b.continue()):h(Array.from(E))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",l.error),h([])):v(l.error)}})}async function it({collection:i,index:t,context:e,limit:n,offset:r}){let s=Wn(e.documentDb,i),a=t?s.index(t.where):s,l=Kt(e.schema,i,t),f=t?.order==="desc"?"prev":"next",h=a.openCursor(l,f),v=!r,E=!1,b=0;return{result:await new Promise((g,O)=>{let C=new Set;h.onsuccess=()=>{b++;let x=h.result;x?r&&!v?(x.advance(r),v=!0):(n&&C.size<n&&C.add(Z(i,x.primaryKey.toString())),n&&b>n?(E=!0,g(Array.from(C))):x.continue()):g(Array.from(C))},h.onerror=()=>{h.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",h.error),g([])):O(h.error)}}),hasNextPage:E}}async function Hn(i,t,e,n){function r(l,f){let h,v,E=i.open([t,"collections"].join("_"),e);E.onupgradeneeded=async b=>{h=b.oldVersion;let P=E.transaction;v=E.result,P.abort()},E.onsuccess=b=>{l([E.result.version,E.result])},E.onblocked=b=>{n?.("Database blocked, waiting...")},E.onerror=b=>{l([h,v])}}let[s,a]=await new Promise(r);return await qt(a),s}async function qt(i){i.close(),await new Promise(t=>t())}async function Gi(i,t,e,n,r){function s(a,l){let f=i.open([t,"collections"].join("_"),e),h=!1;f.onupgradeneeded=v=>{let E=f.transaction;n(E,f.result,v),h=!0},f.onsuccess=v=>{f.result.close(),h?a():l(new Error("Database was not upgraded when a version change was expected"))},f.onerror=v=>{l(f.error||new Error("Unknown error"))},f.onblocked=v=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Xi(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function ke(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((s,a)=>{let l=i.open([t,"collections"].join("_"),e);l.onupgradeneeded=async f=>{l.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",l.result.version),a(l.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${l.result.version}`))},l.onsuccess=f=>{s(l.result)},l.onblocked=f=>{a(new Error("Migration error: database blocked"))},l.onerror=f=>{a(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var Ve=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function Wt({currentVersion:i,targetVersion:t,migrations:e}){let n=Zi({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ve(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Zi({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let s=Zi({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var Jn=typeof window<"u"?window.indexedDB:void 0;async function rt({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await Hn(t,r.namespace,i,r.log);r.log("debug","Current database version:",s,"target version:",i);let a=Wt({currentVersion:s,targetVersion:i,migrations:e});return a.length>0&&(r.log("debug","Migrations to run:",a.map(l=>l.version)),await Qn({context:r,toRun:a,meta:n,indexedDB:t})),ke(t,r.namespace,i,r.log)}async function er({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let a=await Hn(t,s,i,r.log);if(a===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let l=Wt({currentVersion:a,targetVersion:i-1,migrations:e});if(l.length>0){await Qn({context:r,toRun:l,meta:n,indexedDB:t,namespace:s});let h=await ke(t,r.namespace,i-1,r.log),v=await ke(t,s,i-1,r.log),E=new Array;for(let x=0;x<h.objectStoreNames.length;x++)E.push(h.objectStoreNames[x]);let b=h.transaction(E,"readonly"),P=E.map(x=>b.objectStore(x)),g=await Promise.all(P.map(x=>W(x.getAll()))),O=v.transaction(E,"readwrite"),C=E.map(x=>O.objectStore(x));for(let x=0;x<C.length;x++)await Promise.all(g[x].map(S=>W(C[x].put(S))))}let f=Wt({currentVersion:i-1,targetVersion:i,migrations:e});f.length>0&&await Qn({context:r,toRun:f,meta:n,indexedDB:t,namespace:s})}return ke(t,s,i,r.log)}async function Qn({context:i,toRun:t,meta:e,indexedDB:n=Jn,namespace:r=i.namespace}){await Xi(r,async()=>{for(let s of t){let a;if(s.oldSchema.version===0)a=ss({meta:e,migration:s,context:i}),await s.migrate(a);else{let h=await ke(n,r,s.oldSchema.version,i.log);a=rs({meta:e,migration:s,context:{...i,documentDb:h}});try{await s.migrate(a),await Promise.all(a.awaitables)}catch(v){throw i.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,v),v}await qt(h)}i.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Gi(n,r,s.newSchema.version,(h,v)=>{for(let E of s.addedCollections)v.createObjectStore(E,{keyPath:s.newSchema.collections[E].primaryKey,autoIncrement:!1});for(let E of s.allCollections){let b=h.objectStore(E);for(let P of s.addedIndexes[E]||[])b.createIndex(P.name,P.name,{multiEntry:P.multiEntry});for(let P of s.removedIndexes[E]||[])b.deleteIndex(P.name)}for(let E of s.removedCollections)h.objectStore(E).clear()},i.log);let l=await ls({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),f=await ke(n,r,s.newSchema.version,i.log);for(let h of s.allCollections){let E=f.transaction(h,"readwrite").objectStore(h),P=(await os(E)).map(S=>Z(h,`${S}`));P.push(...a.newOids.filter(S=>le(S).collection===h),...l.filter(S=>le(S).collection===h));let O=(await Promise.all(P.map(async S=>{try{let A=await e.getDocumentSnapshot(S);return[S,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",S,"this document will not be preserved",A),null}}))).filter(S=>!!S).map(([S,A])=>{if(!A)return[S,void 0];let y=Tt(s.newSchema.collections[h],A);return[S,y]}),x=f.transaction(h,"readwrite").objectStore(h);await Promise.all(O.map(([S,A])=>{if(A)return cs(x,A).catch(y=>{throw y});{let{id:y}=le(S);return as(x,y)}}))}await qt(f),i.log("debug",`Migration of ${r} complete.`),i.log(`
8
+ ${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Hi(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await W(r.objectStore("baselines").clear()),await W(r.objectStore("operations").clear()),await W(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await tt(e,"operations"),r=await tt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Nt(n.metaDb,n.schema.version),this.operations=new Vt(this.db),this.baselines=new Ft(this.db),this.localReplica=new jt(this.db),this.ackInfo=new Rt(this.db),this.messageCreator=new Lt(this),this.patchCreator=new kt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Qr=[Jr,Yr,Gr,Xr];function Ut({indexedDB:i=window.indexedDB,namespace:t,log:e}){return new Promise((n,r)=>{let s=i.open(`${t}_meta`,4),a=!1;s.onupgradeneeded=async l=>{let p=s.result,h=s.transaction,v=Qr.slice(l.oldVersion);for(let E of v)await E(p,h);l.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{n({db:s.result,wasInitialized:a})}})}async function Gi({wipNamespace:i,namespace:t,indexedDB:e,log:n}){let r=await Ut({namespace:i,indexedDB:e,log:n});if(!r.wasInitialized)return r;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await Ut({namespace:t,indexedDB:e,log:n}),a=s.transaction(["baselines","operations","info"],"readonly"),[l,p,h]=await Promise.all([W(a.objectStore("baselines").getAll()),W(a.objectStore("operations").getAll()),W(a.objectStore("info").getAll())]),v=r.db.transaction(["baselines","operations","info"],"readwrite"),E=v.objectStore("baselines"),b=v.objectStore("operations"),P=v.objectStore("info");for(let g of l)E.put(g);for(let g of p)b.put(g);for(let g of h)P.put(g);return await new Promise((g,O)=>{v.oncomplete=()=>{g()},v.onerror=C=>{O(C)},v.onabort=C=>{O(C)}}),await Ae(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",l.length,"baselines,",p.length,"operations"),r}async function Jr(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Yr(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let{isLocal_timestamp:l,documentOid_timestamp:p,...h}=a.value;a.update({...h,l_t:l,d_t:p}),a.continue()}else n()},s.onerror=a=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Gr(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Xr(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var Zr=i=>IDBKeyRange.only(me(i.equals)),es=i=>{},ts=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(me(t)):t?e?IDBKeyRange.bound(me(t),me(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(me(t),!!i.gt):IDBKeyRange.upperBound(me(e),!!i.lt)},ns=(i,t,e)=>{let n=i.collections[t].compounds[e.where];V(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((p,h)=>n.of.indexOf(p)-n.of.indexOf(h));for(let p of r)if(n.of.indexOf(p)!==r.indexOf(p))throw new Error(`Compound index ${e.where} does not have ${p} at the start of its order`);let s=r.map(p=>e.match[p]);if(r.length===n.of.length)return IDBKeyRange.only(de(...s));let a=Te(...s),l=_e(...s);return IDBKeyRange.bound(a,l)};function is(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function Kt(i,t,e){if(e)return Un(e)?ts(e):Nn(e)?Zr(e):Ki(e)?es(e):Kn(e)?is(e):ns(i,t,e)}function Wn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function zt({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{l.onsuccess=()=>{let E=l.result;h(E?Z(i,E.primaryKey.toString()):null)},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",l.error),h(null)):v(l.error)}})}async function $t({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{let E=new Set;l.onsuccess=()=>{let b=l.result;b?(E.add(Z(i,b.primaryKey.toString())),b.continue()):h(Array.from(E))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",l.error),h([])):v(l.error)}})}async function it({collection:i,index:t,context:e,limit:n,offset:r}){let s=Wn(e.documentDb,i),a=t?s.index(t.where):s,l=Kt(e.schema,i,t),p=t?.order==="desc"?"prev":"next",h=a.openCursor(l,p),v=!r,E=!1,b=0;return{result:await new Promise((g,O)=>{let C=new Set;h.onsuccess=()=>{b++;let x=h.result;x?r&&!v?(x.advance(r),v=!0):(n&&C.size<n&&C.add(Z(i,x.primaryKey.toString())),n&&b>n?(E=!0,g(Array.from(C))):x.continue()):g(Array.from(C))},h.onerror=()=>{h.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",h.error),g([])):O(h.error)}}),hasNextPage:E}}async function Hn(i,t,e,n){function r(l,p){let h,v,E=i.open([t,"collections"].join("_"),e);E.onupgradeneeded=async b=>{h=b.oldVersion;let P=E.transaction;v=E.result,P.abort()},E.onsuccess=b=>{l([E.result.version,E.result])},E.onblocked=b=>{n?.("Database blocked, waiting...")},E.onerror=b=>{l([h,v])}}let[s,a]=await new Promise(r);return await qt(a),s}async function qt(i){i.close(),await new Promise(t=>t())}async function Xi(i,t,e,n,r){function s(a,l){let p=i.open([t,"collections"].join("_"),e),h=!1;p.onupgradeneeded=v=>{let E=p.transaction;n(E,p.result,v),h=!0},p.onsuccess=v=>{p.result.close(),h?a():l(new Error("Database was not upgraded when a version change was expected"))},p.onerror=v=>{l(p.error||new Error("Unknown error"))},p.onblocked=v=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Zi(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function Be(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((s,a)=>{let l=i.open([t,"collections"].join("_"),e);l.onupgradeneeded=async p=>{l.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",l.result.version),a(l.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${l.result.version}`))},l.onsuccess=p=>{s(l.result)},l.onblocked=p=>{a(new Error("Migration error: database blocked"))},l.onerror=p=>{a(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var Ve=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function Wt({currentVersion:i,targetVersion:t,migrations:e}){let n=er({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ve(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function er({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let s=er({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var Jn=typeof window<"u"?window.indexedDB:void 0;async function rt({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await Hn(t,r.namespace,i,r.log);r.log("debug","Current database version:",s,"target version:",i);let a=Wt({currentVersion:s,targetVersion:i,migrations:e});return a.length>0&&(r.log("debug","Migrations to run:",a.map(l=>l.version)),await Qn({context:r,toRun:a,meta:n,indexedDB:t})),Be(t,r.namespace,i,r.log)}async function tr({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let a=await Hn(t,s,i,r.log);if(a===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let l=Wt({currentVersion:a,targetVersion:i-1,migrations:e});if(l.length>0){await Qn({context:r,toRun:l,meta:n,indexedDB:t,namespace:s});let h=await Be(t,r.namespace,i-1,r.log),v=await Be(t,s,i-1,r.log),E=new Array;for(let x=0;x<h.objectStoreNames.length;x++)E.push(h.objectStoreNames[x]);let b=h.transaction(E,"readonly"),P=E.map(x=>b.objectStore(x)),g=await Promise.all(P.map(x=>W(x.getAll()))),O=v.transaction(E,"readwrite"),C=E.map(x=>O.objectStore(x));for(let x=0;x<C.length;x++)await Promise.all(g[x].map(S=>W(C[x].put(S))))}let p=Wt({currentVersion:i-1,targetVersion:i,migrations:e});p.length>0&&await Qn({context:r,toRun:p,meta:n,indexedDB:t,namespace:s})}return Be(t,s,i,r.log)}async function Qn({context:i,toRun:t,meta:e,indexedDB:n=Jn,namespace:r=i.namespace}){await Zi(r,async()=>{for(let s of t){let a;if(s.oldSchema.version===0)a=os({meta:e,migration:s,context:i}),await s.migrate(a);else{let h=await Be(n,r,s.oldSchema.version,i.log);a=ss({meta:e,migration:s,context:{...i,documentDb:h}});try{await s.migrate(a),await Promise.all(a.awaitables)}catch(v){throw i.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,v),v}await qt(h)}i.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Xi(n,r,s.newSchema.version,(h,v)=>{for(let E of s.addedCollections)v.createObjectStore(E,{keyPath:s.newSchema.collections[E].primaryKey,autoIncrement:!1});for(let E of s.allCollections){let b=h.objectStore(E);for(let P of s.addedIndexes[E]||[])b.createIndex(P.name,P.name,{multiEntry:P.multiEntry});for(let P of s.removedIndexes[E]||[])b.deleteIndex(P.name)}for(let E of s.removedCollections)h.objectStore(E).clear()},i.log);let l=await ds({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),p=await Be(n,r,s.newSchema.version,i.log);for(let h of s.allCollections){let E=p.transaction(h,"readwrite").objectStore(h),P=(await as(E)).map(S=>Z(h,`${S}`));P.push(...a.newOids.filter(S=>le(S).collection===h),...l.filter(S=>le(S).collection===h));let O=(await Promise.all(P.map(async S=>{try{let A=await e.getDocumentSnapshot(S);return[S,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",S,"this document will not be preserved",A),null}}))).filter(S=>!!S).map(([S,A])=>{if(!A)return[S,void 0];let y=Tt(s.newSchema.collections[h],A);return[S,y]}),x=p.transaction(h,"readwrite").objectStore(h);await Promise.all(O.map(([S,A])=>{if(A)return ls(x,A).catch(y=>{throw y});{let{id:y}=le(S);return cs(x,y)}}))}await qt(p),i.log("debug",`Migration of ${r} complete.`),i.log(`
9
9
  \u2B06\uFE0F v${s.newSchema.version} Migration complete. Here's the rundown:
10
10
  - Added collections: ${s.addedCollections.join(", ")}
11
11
  - Removed collections: ${s.removedCollections.join(", ")}
12
12
  - Changed collections: ${s.changedCollections.join(", ")}
13
13
  - New indexes: ${Object.keys(s.addedIndexes).map(h=>s.addedIndexes[h].map(v=>`${h}.${v.name}`)).flatMap(h=>h).join(", ")}
14
14
  - Removed indexes: ${Object.keys(s.removedIndexes).map(h=>s.removedIndexes[h].map(v=>`${h}.${v.name}`)).flatMap(h=>h).join(", ")}
15
- `)}})}function tr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{ve(i.newSchema.collections[s],a);let l=a[i.newSchema.collections[s].primaryKey],f=Z(s,l);return n.push(f),await t.insertLocalOperation(xe(a,f,e)),a},delete:a=>{let l=Z(s,a);return t.insertLocalOperation([{oid:l,timestamp:e(),data:{op:"delete"}}])}},r),{})}function is({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=Z(r,s);return await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await zt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await $t({collection:r,index:s,context:t});return await Promise.all(a.map(f=>e.getDocumentSnapshot(f,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function rs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=is({migration:t,context:e,meta:i}),a=tr({migration:t,getMigrationNow:n,newOids:r,meta:i}),l=new Array;return{log:e.log,newOids:r,migrate:async(h,v)=>{let E=await s[h].findAll();await Promise.all(E.filter(Boolean).map(async b=>{V(Ze(b),`Document is missing an OID: ${JSON.stringify(b)}`);let P=oe(b),g=await v(b);if(g){Ge(P),Ge(g),je(g);let O=et(P,g,n,void 0,[],{mergeUnknownObjects:!0});O.length>0&&await i.insertLocalOperation(O)}}))},queries:s,mutations:a,awaitables:l}}function ss({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=tr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function os(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function as(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function cs(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ls({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>K(r.oid))))}var st=class extends N{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var Ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return V(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return ve(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var Ne=Symbol("entity-file-update"),ot=Symbol("entity-file-mark-failed"),ds,us,Me=class extends N{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[ds]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[us]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{ds=Ne,us=ot}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var nr=ut(ht(),1);function ps(i){return{id:(0,nr.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Be(i,t){if(typeof window<"u"&&i instanceof File){let e=ps(i);return t(e),Oi(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=Be(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=Be(i[e],t);return i}return i}function ir(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Qt=class extends pe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ir(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?fs(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function fs(i,t){return new Blob([i],{type:t})}function hs(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Jt=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ne](e);else{let n=new Me(e.id);n[Ne](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new Me(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[ot]();return}let n=await this.storage.getFile(t.id);if(n)t[Ne](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ne](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[ot](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[ot](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new Qt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:hs,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var rr="@@refresh",Yt="@@deepChange";function at(i,t){return i[rr](t)}var ms,ys,ye=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a,readonlyKeys:l=[]}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[ms]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[Yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[ys]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return oe(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(te(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(se(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=oe(t,!1));let n=this.getChildFieldSchema(e);return n&&Pe(t,n),Be(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>te(e)?this.getSubObject(e.id,n)?.getSnapshot():se(e)?this.getFileSnapshot(e):e);else{t={...this.value};for(let[e,n]of Object.entries(t))te(n)?t[e]=this.getSubObject(n.id,e)?.getSnapshot():se(n)&&(t[e]=this.getFileSnapshot(n))}return U(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.readonlyKeys.includes(t))return!1;if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.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.');for(let[s,a]of Object.entries(t)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let l=this.getChildFieldSchema(s);l&&Pe(a,l)}let r=Be(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),U(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=ae(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(te(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>te(e)?e.id===ae(t):(se(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.includes=t=>this.has(t);this.oid=t;let{collection:f}=le(t);this.collection=f,this.store=e,this.fieldSchema=n,this.readonlyKeys=l,this.cache=r,this.parent=s&&this.cache.weakRef(s);let{view:h,deleted:v,lastTimestamp:E}=this.cache.computeView(t);if(this._current=h,this._deleted=v,this._updatedAt=E||null,this.cachedDeepUpdatedAt=null,this.events=new N(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");V(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}getFileSnapshot(t){let e=this.store.getFile(t.id);return e.url?{id:t.id,url:e.url}:e.loading||e.failed?{id:t.id,url:void 0}:{id:t.id,url:null}}get length(){return this.value.length}[(ms=rr,ys=Yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Gt=class{constructor(){let t,e;this.promise=new Promise((n,r)=>{t=n,e=r}),this._resolve=t,this._reject=e}resolve(t){this._resolve(t)}reject(t){this._reject(t)}};var Xt=class extends N{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Gt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(at(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],l=a.findIndex(h=>h.timestamp>=r.timestamp);if(l!==-1){if(a[l].timestamp===r.timestamp)continue;a.splice(l,0,r)}else a.push(r);this.operationsMap.set(s,a);let f=this.localOperationsMap.get(s);f&&this.localOperationsMap.set(s,f.filter(h=>h.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let l=this.operationsMap.get(s)||[];for(;l[0]?.timestamp<r.timestamp;)l.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let l of this.entities.values()){let f=l.deref();f&&at(f,a)}else for(let l of a.affectedOids){let h=this.entities.get(l)?.deref();h&&(at(h,a),this.emit(`change:${l}`),this.emit("change:*",l))}};this.applyOperations=(e,n,r,s)=>{let a,l=this.storeTools.now;for(let f of r)if(!(s&&f.timestamp<=s)){if(xi(f.timestamp,l)>0){a=f.timestamp;continue}f.data.op==="delete"?n=!0:(e=Ee(e,f.data),f.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{if(this.baselinesMap.size===0&&this.operationsMap.size===0&&this.localOperationsMap.size===0)return this.context.log("debug",`Entity ${e} accessed with no data at all`),{view:null,deleted:!0,lastTimestamp:null};let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&U(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=oe(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&U(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r,s)=>{let l=this.entities.get(e)?.deref();return l||(l=new ye({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r,readonlyKeys:s}),this.entities.set(e,this.context.weakRef(l))),l};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=({operations:e,baselines:n,dropExistingUnconfirmed:r=!1,unconfirmedOperations:s,dropAll:a})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let l={isLocal:!1,affectedOids:new Set};a&&this.baselinesMap.clear(),this.insertBaselines(n,l),a&&this.operationsMap.clear(),this.insertOperations(e,l),(s||r)&&(this.localOperationsMap.clear(),s&&this.insertLocalOperations(s));for(let f of this.entities.keys()){let v=this.entities.get(f)?.deref();v&&(at(v,l),this.emit(`change:${f}`),this.emit("change:*",f))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}get initializedPromise(){return this._initialized.promise}get weakRef(){return this.context.weakRef}};var Zt="@@default",en=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=Zt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=le(t);if(!this.schema.collections[e])return this.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]};let n=this.schema.collections[e];return{readonlyKeys:[n.primaryKey],schema:{type:"object",properties:n.fields}}};this.refreshFamilyCache=async(t,e=!1,n=!1)=>{if(this._disposed){this.context.log("debug",`EntityStore is disposed, not refreshing ${t.oid} cache`);return}let r=this.meta.createTransaction(["baselines","operations"]),s=[],a=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,l=>{s.push(l)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,l=>{l.confirmed=!0,a.push(l)},{transaction:r,mode:"readwrite"})]),t.reset({operations:a,baselines:s,dropExistingUnconfirmed:e,dropAll:n})};this.openFamilyCache=async t=>{let e=K(t),n=this.documentFamilyCaches.get(e);return n||(this.context.log("debug","opening family cache for",e),n=new Xt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n),n.setInitialized()),await n.initializedPromise,n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=K(t),{id:n,collection:r}=le(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let l=Tt(this.schema.collections[r],a);try{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.put(l)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",l)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
16
- `,"Invalid data:",JSON.stringify(l))}}else{let f=this.db.transaction(r,"readwrite").objectStore(r);await W(f.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null}return null};this.create=async(t,e,n)=>{Ot(t);let r=Be(t,this.files.add);U(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let{schema:l,readonlyKeys:f}=this.getDocumentSchema(e);if(!l)throw new Error(`Cannot create a document in the ${le(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,l,void 0,f)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Rn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Fn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Fn(t),a=Rn(e),l=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let f of l){let h=this.documentFamilyCaches.get(f);h?(h.addData({operations:a[f]||[],baselines:s[f]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",f,a[f]?.length??0,"operations",s[f]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",f,"because it is not open")}return l};this.addData=async({operations:t,baselines:e,reset:n})=>{if(this._disposed){this.log("warn","EntityStore is disposed, not adding data");return}let r=t;for(let l of r)l.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(l=>K(l.oid)).concat(t.map(l=>K(l.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0,!0);for(let l of s)await this.writeDocumentToStorage(l);let a=Array.from(new Set(s.map(l=>le(l).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=xt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:l=>(this.currentBatchKey=e,l(),this.currentBatchKey=Zt,a),flush:async()=>(await this.operationBatcher.flush(Zt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushAllBatches=async()=>{await Promise.all(this.operationBatcher.flushAll())};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>K(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>le(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Vi(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let l=await this.openFamilyCache(s),{view:f,deleted:h}=l.computeConfirmedView(s),v=qi(s,f,a,r);n.unshift(...v)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{V(t===K(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=async()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear(),await this.flushAllBatches()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await W(n.clear())}};this.refreshAllCaches=async(t=!1,e=!1)=>{for(let[n,r]of this.documentFamilyCaches)await this.refreshFamilyCache(r,t,e)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new Le(this.flushOperations),this.operationBatcher.add({key:Zt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var Yn=Symbol("handleMessage"),gs,ct=class extends N{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[gs]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,l]of Object.entries(n.peerPresence))this.isSelf(e,l)?(this._self=l,this._selfReplicaIds.add(l.replicaId),this.emit("selfChanged",l)):(r=!0,s.add(a),this._peers[a]=l,this.emit("peerChanged",a,l))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Le(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{gs=Yn}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 tn=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var Ue=class extends N{constructor({interval:e=15*1e3,deadlineLength:n=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.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var nn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let l of a.messages)this.handleServerMessage(l);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new Ue({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function Gn(i){this.message=i}Gn.prototype=new Error,Gn.prototype.name="InvalidCharacterError";var sr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Gn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function bs(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(sr(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return sr(t)}}function rn(i){this.message=i}function ws(i,t){if(typeof i!="string")throw new rn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(bs(i.split(".")[e]))}catch(n){throw new rn("Invalid token specified: "+n.message)}}rn.prototype=new Error,rn.prototype.name="InvalidTokenError";var or=ws;var sn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(l=>{if(l.ok)return l.json();throw new Error(`Auth endpoint returned non-200 response: ${l.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=or(t.accessToken);V(e.url,"No sync endpoint provided from auth endpoint"),V(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let l=new URL(r);l.pathname=l.pathname+"/files",a=l.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var on=class extends N{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}},an=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var cn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new Ue;this.reconnectScheduler=new on(new an(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e)};this.onMessage=async e=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var ln=class extends N{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new ct({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},Ke=class extends N{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:l,pullInterval:f,presenceUpdateBatchTimeout:h,defaultProfile:v,useBroadcastChannel:E},{meta:b,log:P,onData:g}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Yn](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=b,this.onData=g,this.log=P||(()=>{}),this.presence=new ct({initialPresence:r,defaultProfile:v,updateBatchTimeout:h}),this.endpointProvider=new sn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new cn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log}),this.pushPullSync=new nn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log,interval:f}),this.fileSync=new tn({endpointProvider:this.endpointProvider,log:this.log}),E&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),l==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let O=()=>{C&&clearTimeout(C);let S=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;S&&this.mode==="pull"?this.setMode("realtime"):!S&&this.mode==="realtime"&&(C=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},C;this.presence.subscribe("peersChanged",O),s!=="peers-only"&&this.presence.subscribe("selfChanged",O)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var ze=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function Ss(i){return i!==null}function Xn(i){return Array.isArray(i)?i.map(Xn).filter(Ss):i instanceof ye&&i.deleted?null:i}function Oe(i,t){return!i&&!t||i&&t&&Se(i)===Se(t)}var Zn=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),xs,fe=class extends ze{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Xn(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ye&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ye&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error&&(e.name==="InvalidStateError"||e.name==="InvalidAccessError"))return this._value;throw e}),this._executionPromise);this[xs]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new N(f=>{f==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let l=a||(f=>f.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",f=>{l(f)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{xs=Zn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var dn=class extends fe{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Os,un=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await zt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Os]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Os=ue}};var Is,pn=class extends fe{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Is]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Is=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ds,fn=class extends fe{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ds]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Ds=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Cs,hn=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await $t({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Cs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Cs=ue}};var mn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?Se(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new dn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new hn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new pn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[ue](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new fn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,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)}};var yn=class extends ze{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Zn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var Re=class extends N{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let h of e)n[h]=await tt(this.documentDb,h);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((h,{size:v})=>h+v,0),l=r.baselinesSize.size+r.operationsSize.size,f=l/a;return{collections:n,meta:r,storage:s,totalMetaSize:l,totalCollectionsSize:a,metaToDataRatio:f,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this.sync.stop(),this.sync.dispose(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ae(this.documentDb),await Ae(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Bt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ae(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((l,f)=>{s.onsuccess=l,s.onerror=f});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ae(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new Ke(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new ln,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new Jt({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new en({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new yn({context:n}),this._documentManager=new Ht(this.meta,this.schema,this._entities);let s=Bi(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[a,l]of Object.entries(n.schema.collections)){let f=a;this[f]=new mn({collection:f,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var lt=class{constructor(t){this.value=t}deref(){return this.value}};var gn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let{db:e}=await Ut({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace}),n={namespace:this._namespace,metaDb:e,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:f=>t.EXPERIMENTAL_weakRefs?new WeakRef(f):new lt(f)},r=new nt({context:n,disableRebasing:t.disableRebasing});await r.updateSchema(t.schema,t.overrideSchemaConflict);let s=await rt({context:n,version:t.schema.version,meta:r,migrations:t.migrations,indexedDB:t.indexedDb}),a=Object.assign(n,{documentDb:s});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},a,{meta:r})};this.initializeWIPDatabases=async t=>{let e=Se(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Yi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),s={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:v=>t.EXPERIMENTAL_weakRefs?new WeakRef(v):new lt(v)},a=new nt({context:s,disableRebasing:t.disableRebasing});await a.updateSchema(t.schema,t.overrideSchemaConflict);let l=await er({context:s,version:t.schema.version,meta:a,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),f=Object.assign(s,{documentDb:l});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},f,{meta:a})};this.cleanupWIPDatabases=async t=>{let r=(await Qi(t.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${t.namespace}_${Se(t.schema)}`));for(let s of r)await Hi(s,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Bt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=ei;
15
+ `)}})}function nr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{ve(i.newSchema.collections[s],a);let l=a[i.newSchema.collections[s].primaryKey],p=Z(s,l);return n.push(p),await t.insertLocalOperation(xe(a,p,e)),a},delete:a=>{let l=Z(s,a);return t.insertLocalOperation([{oid:l,timestamp:e(),data:{op:"delete"}}])}},r),{})}function rs({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=Z(r,s);return await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await zt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await $t({collection:r,index:s,context:t});return await Promise.all(a.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function ss({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=rs({migration:t,context:e,meta:i}),a=nr({migration:t,getMigrationNow:n,newOids:r,meta:i}),l=new Array;return{log:e.log,newOids:r,migrate:async(h,v)=>{let E=await s[h].findAll();await Promise.all(E.filter(Boolean).map(async b=>{V(Ze(b),`Document is missing an OID: ${JSON.stringify(b)}`);let P=oe(b),g=await v(b);if(g){Ge(P),Ge(g),je(g);let O=et(P,g,n,void 0,[],{mergeUnknownObjects:!0});O.length>0&&await i.insertLocalOperation(O)}}))},queries:s,mutations:a,awaitables:l}}function os({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=nr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function as(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function cs(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ls(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ds({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>U(r.oid))))}var st=class extends N{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var Ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return V(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return ve(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var Ne=Symbol("entity-file-update"),ot=Symbol("entity-file-mark-failed"),us,fs,ke=class extends N{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[us]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[fs]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{us=Ne,fs=ot}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var ir=ut(ht(),1);function ps(i){return{id:(0,ir.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Me(i,t){if(typeof window<"u"&&i instanceof File){let e=ps(i);return t(e),Oi(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=Me(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=Me(i[e],t);return i}return i}function rr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Qt=class extends fe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await rr(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?hs(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function hs(i,t){return new Blob([i],{type:t})}function ms(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Jt=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ne](e);else{let n=new ke(e.id);n[Ne](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ke(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[ot]();return}let n=await this.storage.getFile(t.id);if(n)t[Ne](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ne](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[ot](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[ot](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new Qt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ms,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var sr="@@refresh",Yt="@@deepChange";function at(i,t){return i[sr](t)}var ys,gs,ye=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a,readonlyKeys:l=[]}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[ys]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[Yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[gs]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return oe(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(te(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(se(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=oe(t,!1));let n=this.getChildFieldSchema(e);return n&&Pe(t,n),Me(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>te(e)?this.getSubObject(e.id,n)?.getSnapshot():se(e)?this.getFileSnapshot(e):e);else{t={...this.value};for(let[e,n]of Object.entries(t))te(n)?t[e]=this.getSubObject(n.id,e)?.getSnapshot():se(n)&&(t[e]=this.getFileSnapshot(n))}return K(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.readonlyKeys.includes(t))return!1;if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.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.');for(let[s,a]of Object.entries(t)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let l=this.getChildFieldSchema(s);l&&Pe(a,l)}let r=Me(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),K(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=ae(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(te(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>te(e)?e.id===ae(t):(se(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.includes=t=>this.has(t);this.oid=t;let{collection:p}=le(t);this.collection=p,this.store=e,this.fieldSchema=n,this.readonlyKeys=l,this.cache=r,this.parent=s&&this.cache.weakRef(s);let{view:h,deleted:v,lastTimestamp:E}=this.cache.computeView(t);if(this._current=h,this._deleted=v,this._updatedAt=E||null,this.cachedDeepUpdatedAt=null,this.events=new N(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");V(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}getFileSnapshot(t){let e=this.store.getFile(t.id);return e.url?{id:t.id,url:e.url}:e.loading||e.failed?{id:t.id,url:void 0}:{id:t.id,url:null}}get length(){return this.value.length}[(ys=sr,gs=Yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Gt=class{constructor(){let t,e;this.promise=new Promise((n,r)=>{t=n,e=r}),this._resolve=t,this._reject=e}resolve(t){this._resolve(t)}reject(t){this._reject(t)}};var Xt=class extends N{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Gt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(at(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],l=a.findIndex(h=>h.timestamp>=r.timestamp);if(l!==-1){if(a[l].timestamp===r.timestamp)continue;a.splice(l,0,r)}else a.push(r);this.operationsMap.set(s,a);let p=this.localOperationsMap.get(s);p&&this.localOperationsMap.set(s,p.filter(h=>h.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let l=this.operationsMap.get(s)||[];for(;l[0]?.timestamp<r.timestamp;)l.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let l of this.entities.values()){let p=l.deref();p&&at(p,a)}else for(let l of a.affectedOids){let h=this.entities.get(l)?.deref();h&&(at(h,a),this.emit(`change:${l}`),this.emit("change:*",l))}};this.applyOperations=(e,n,r,s)=>{let a,l=this.storeTools.now;for(let p of r)if(!(s&&p.timestamp<=s)){if(xi(p.timestamp,l)>0){a=p.timestamp;continue}p.data.op==="delete"?n=!0:(e=Ee(e,p.data),p.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{if(this.baselinesMap.size===0&&this.operationsMap.size===0&&this.localOperationsMap.size===0)return this.context.log("debug",`Entity ${e} accessed with no data at all`),{view:null,deleted:!0,lastTimestamp:null};let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&K(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=oe(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&K(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r,s)=>{let l=this.entities.get(e)?.deref();return l||(l=new ye({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r,readonlyKeys:s}),this.entities.set(e,this.context.weakRef(l))),l};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=({operations:e,baselines:n,dropExistingUnconfirmed:r=!1,unconfirmedOperations:s,dropAll:a})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let l={isLocal:!1,affectedOids:new Set};a&&this.baselinesMap.clear(),this.insertBaselines(n,l),a&&this.operationsMap.clear(),this.insertOperations(e,l),(s||r)&&(this.localOperationsMap.clear(),s&&this.insertLocalOperations(s));for(let p of this.entities.keys()){let v=this.entities.get(p)?.deref();v&&(at(v,l),this.emit(`change:${p}`),this.emit("change:*",p))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}get initializedPromise(){return this._initialized.promise}get weakRef(){return this.context.weakRef}};var Zt="@@default",en=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=Zt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=le(t);if(!this.schema.collections[e])return this.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]};let n=this.schema.collections[e];return{readonlyKeys:[n.primaryKey],schema:{type:"object",properties:n.fields}}};this.refreshFamilyCache=async(t,e=!1,n=!1)=>{if(this._disposed){this.context.log("debug",`EntityStore is disposed, not refreshing ${t.oid} cache`);return}let r=this.meta.createTransaction(["baselines","operations"]),s=[],a=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,l=>{s.push(l)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,l=>{l.confirmed=!0,a.push(l)},{transaction:r,mode:"readwrite"})]),t.reset({operations:a,baselines:s,dropExistingUnconfirmed:e,dropAll:n})};this.openFamilyCache=async t=>{let e=U(t),n=this.documentFamilyCaches.get(e);return n||(this.context.log("debug","opening family cache for",e),n=new Xt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n),n.setInitialized()),await n.initializedPromise,n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=U(t),{id:n,collection:r}=le(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let l=Tt(this.schema.collections[r],a);try{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.put(l)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",l)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
16
+ `,"Invalid data:",JSON.stringify(l))}}else{let p=this.db.transaction(r,"readwrite").objectStore(r);await W(p.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null}return null};this.create=async(t,e,n)=>{Ot(t);let r=Me(t,this.files.add);K(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let{schema:l,readonlyKeys:p}=this.getDocumentSchema(e);if(!l)throw new Error(`Cannot create a document in the ${le(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,l,void 0,p)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Rn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Fn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Fn(t),a=Rn(e),l=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let p of l){let h=this.documentFamilyCaches.get(p);h?(h.addData({operations:a[p]||[],baselines:s[p]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",p,a[p]?.length??0,"operations",s[p]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",p,"because it is not open")}return l};this.addData=async({operations:t,baselines:e,reset:n})=>{if(this._disposed){this.log("warn","EntityStore is disposed, not adding data");return}let r=t;for(let l of r)l.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(l=>U(l.oid)).concat(t.map(l=>U(l.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0,!0);for(let l of s)await this.writeDocumentToStorage(l);let a=Array.from(new Set(s.map(l=>le(l).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=xt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:l=>(this.currentBatchKey=e,l(),this.currentBatchKey=Zt,a),flush:async()=>(await this.operationBatcher.flush(Zt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushAllBatches=async()=>{await Promise.all(this.operationBatcher.flushAll())};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>U(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>le(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Ni(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let l=await this.openFamilyCache(s),{view:p,deleted:h}=l.computeConfirmedView(s),v=Wi(s,p,a,r);n.unshift(...v)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{V(t===U(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=async()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear(),await this.flushAllBatches()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await W(n.clear())}};this.refreshAllCaches=async(t=!1,e=!1)=>{for(let[n,r]of this.documentFamilyCaches)await this.refreshFamilyCache(r,t,e)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new Le(this.flushOperations),this.operationBatcher.add({key:Zt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var Yn=Symbol("handleMessage"),bs,ct=class extends N{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[bs]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,l]of Object.entries(n.peerPresence))this.isSelf(e,l)?(this._self=l,this._selfReplicaIds.add(l.replicaId),this.emit("selfChanged",l)):(r=!0,s.add(a),this._peers[a]=l,this.emit("peerChanged",a,l))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Le(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{bs=Yn}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 tn=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var Ue=class extends N{constructor({interval:e=15*1e3,deadlineLength:n=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.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var nn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let l of a.messages)this.handleServerMessage(l);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new Ue({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function Gn(i){this.message=i}Gn.prototype=new Error,Gn.prototype.name="InvalidCharacterError";var or=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Gn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function ws(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(or(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return or(t)}}function rn(i){this.message=i}function vs(i,t){if(typeof i!="string")throw new rn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(ws(i.split(".")[e]))}catch(n){throw new rn("Invalid token specified: "+n.message)}}rn.prototype=new Error,rn.prototype.name="InvalidTokenError";var ar=vs;var sn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(l=>{if(l.ok)return l.json();throw new Error(`Auth endpoint returned non-200 response: ${l.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=ar(t.accessToken);V(e.url,"No sync endpoint provided from auth endpoint"),V(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let l=new URL(r);l.pathname=l.pathname+"/files",a=l.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var on=class extends N{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}},an=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var cn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new Ue;this.reconnectScheduler=new on(new an(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e)};this.onMessage=async e=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var ln=class extends N{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new ct({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},Ke=class extends N{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:l,pullInterval:p,presenceUpdateBatchTimeout:h,defaultProfile:v,useBroadcastChannel:E},{meta:b,log:P,onData:g}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Yn](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=b,this.onData=g,this.log=P||(()=>{}),this.presence=new ct({initialPresence:r,defaultProfile:v,updateBatchTimeout:h}),this.endpointProvider=new sn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new cn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log}),this.pushPullSync=new nn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log,interval:p}),this.fileSync=new tn({endpointProvider:this.endpointProvider,log:this.log}),E&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),l==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let O=()=>{C&&clearTimeout(C);let S=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;S&&this.mode==="pull"?this.setMode("realtime"):!S&&this.mode==="realtime"&&(C=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},C;this.presence.subscribe("peersChanged",O),s!=="peers-only"&&this.presence.subscribe("selfChanged",O)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var ze=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function xs(i){return i!==null}function Xn(i){return Array.isArray(i)?i.map(Xn).filter(xs):i instanceof ye&&i.deleted?null:i}function Oe(i,t){return!i&&!t||i&&t&&Se(i)===Se(t)}var Zn=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Os,pe=class extends ze{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Xn(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ye&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ye&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error&&(e.name==="InvalidStateError"||e.name==="InvalidAccessError"))return this._value;throw e}),this._executionPromise);this[Os]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new N(p=>{p==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let l=a||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{l(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Os=Zn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var dn=class extends pe{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Is,un=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await zt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Is]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Is=ue}};var Ds,fn=class extends pe{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Ds]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Ds=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Cs,pn=class extends pe{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Cs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Cs=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Es,hn=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await $t({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Es]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Es=ue}};var mn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?Se(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new dn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new hn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new fn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[ue](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new pn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,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)}};var yn=class extends ze{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Zn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var Re=class extends N{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let h of e)n[h]=await tt(this.documentDb,h);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((h,{size:v})=>h+v,0),l=r.baselinesSize.size+r.operationsSize.size,p=l/a;return{collections:n,meta:r,storage:s,totalMetaSize:l,totalCollectionsSize:a,metaToDataRatio:p,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this.sync.stop(),this.sync.dispose(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ae(this.documentDb),await Ae(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Mt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ae(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((l,p)=>{s.onsuccess=l,s.onerror=p});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ae(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new Ke(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new ln,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new Jt({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new en({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new yn({context:n}),this._documentManager=new Ht(this.meta,this.schema,this._entities);let s=Mi(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[a,l]of Object.entries(n.schema.collections)){let p=a;this[p]=new mn({collection:p,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var lt=class{constructor(t){this.value=t}deref(){return this.value}};var gn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let{db:e}=await Ut({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace}),n={namespace:this._namespace,metaDb:e,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:p=>t.EXPERIMENTAL_weakRefs?new WeakRef(p):new lt(p)},r=new nt({context:n,disableRebasing:t.disableRebasing});await r.updateSchema(t.schema,t.overrideSchemaConflict);let s=await rt({context:n,version:t.schema.version,meta:r,migrations:t.migrations,indexedDB:t.indexedDb}),a=Object.assign(n,{documentDb:s});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},a,{meta:r})};this.initializeWIPDatabases=async t=>{let e=Se(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Gi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),s={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:v=>t.EXPERIMENTAL_weakRefs?new WeakRef(v):new lt(v)},a=new nt({context:s,disableRebasing:t.disableRebasing});await a.updateSchema(t.schema,t.overrideSchemaConflict);let l=await tr({context:s,version:t.schema.version,meta:a,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),p=Object.assign(s,{documentDb:l});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:a})};this.cleanupWIPDatabases=async t=>{let r=(await Ji(t.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${t.namespace}_${Se(t.schema)}`));for(let s of r)await Qi(s,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Mt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=ei;
17
17
  //# sourceMappingURL=index.js.map