@verdant-web/store 2.8.3 → 2.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +4 -4
- package/dist/bundle/index.js.map +3 -3
- package/dist/cjs/__tests__/documents.test.js +17 -0
- package/dist/cjs/__tests__/documents.test.js.map +1 -1
- package/dist/cjs/__tests__/fixtures/testStorage.d.ts +6 -0
- package/dist/cjs/__tests__/fixtures/testStorage.js +6 -0
- package/dist/cjs/__tests__/fixtures/testStorage.js.map +1 -1
- package/dist/cjs/__tests__/setup/indexedDB.js +5 -0
- package/dist/cjs/__tests__/setup/indexedDB.js.map +1 -1
- package/dist/cjs/files/utils.js +4 -1
- package/dist/cjs/files/utils.js.map +1 -1
- package/dist/cjs/sync/Sync.d.ts +2 -3
- package/dist/cjs/sync/Sync.js.map +1 -1
- package/dist/esm/__tests__/documents.test.js +17 -0
- package/dist/esm/__tests__/documents.test.js.map +1 -1
- package/dist/esm/__tests__/fixtures/testStorage.d.ts +6 -0
- package/dist/esm/__tests__/fixtures/testStorage.js +6 -0
- package/dist/esm/__tests__/fixtures/testStorage.js.map +1 -1
- package/dist/esm/__tests__/setup/indexedDB.js +5 -0
- package/dist/esm/__tests__/setup/indexedDB.js.map +1 -1
- package/dist/esm/files/utils.js +4 -1
- package/dist/esm/files/utils.js.map +1 -1
- package/dist/esm/sync/Sync.d.ts +2 -3
- package/dist/esm/sync/Sync.js.map +1 -1
- package/dist/tsconfig-cjs.tsbuildinfo +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/package.json +2 -2
- package/src/__tests__/documents.test.ts +22 -0
- package/src/__tests__/fixtures/testStorage.ts +6 -0
- package/src/__tests__/setup/indexedDB.ts +6 -0
- package/src/files/utils.ts +5 -1
- package/src/sync/Sync.ts +2 -3
package/dist/bundle/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
"use strict";var ur=Object.create;var xn=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,mr=Object.prototype.hasOwnProperty;var qe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),yr=(i,t)=>{for(var e in t)xn(i,e,{get:t[e],enumerable:!0})},gr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pr(t))!mr.call(i,r)&&r!==e&&xn(i,r,{get:()=>t[r],enumerable:!(n=fr(t,r))||n.enumerable});return i};var ft=(i,t,e)=>(e=i!=null?ur(hr(i)):{},gr(t||!i||!i.__esModule?xn(e,"default",{value:i,enumerable:!0}):e,i));var On=qe((
|
|
1
|
+
"use strict";var ur=Object.create;var xn=Object.defineProperty;var fr=Object.getOwnPropertyDescriptor;var pr=Object.getOwnPropertyNames;var hr=Object.getPrototypeOf,mr=Object.prototype.hasOwnProperty;var qe=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),yr=(i,t)=>{for(var e in t)xn(i,e,{get:t[e],enumerable:!0})},gr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of pr(t))!mr.call(i,r)&&r!==e&&xn(i,r,{get:()=>t[r],enumerable:!(n=fr(t,r))||n.enumerable});return i};var ft=(i,t,e)=>(e=i!=null?ur(hr(i)):{},gr(t||!i||!i.__esModule?xn(e,"default",{value:i,enumerable:!0}):e,i));var On=qe((Lo,li)=>{li.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ui=qe((Vo,di)=>{var br=On(),wr=typeof window=="object"?window:self,vr=Object.keys(wr).length,Sr=navigator.mimeTypes?navigator.mimeTypes.length:0,xr=br((Sr+navigator.userAgent.length).toString(36)+vr.toString(36),4);di.exports=function(){return xr}});var mi=qe((No,hi)=>{var In,fi=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;fi?(pi=Math.pow(2,32)-1,In=function(){return Math.abs(fi.getRandomValues(new Uint32Array(1))[0]/pi)}):In=Math.random;var pi;hi.exports=In});var mt=qe((Uo,wi)=>{var pt=ui(),yi=On(),Or=mi(),We=0,Cn=4,ht=36,gi=Math.pow(ht,Cn);function Dn(){return yi((Or()*gi<<0).toString(ht),Cn)}function bi(){return We=We<gi?We:0,We++,We-1}function He(){var i="c",t=new Date().getTime().toString(ht),e=yi(bi().toString(ht),Cn),n=pt(),r=Dn()+Dn();return i+t+e+n+r}He.slug=function(){var t=new Date().getTime().toString(36),e=bi().toString(36).slice(-4),n=pt().slice(0,1)+pt().slice(-1),r=Dn().slice(-2);return t.slice(-2)+e+n+r};He.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};He.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};He.fingerprint=pt;wi.exports=He});var ki=qe((Ai,Ri)=>{(function(i){var t;typeof Ai=="object"?Ri.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(c,p){if(!e[c]){if(!t[c]){var h=typeof require=="function"&&require;if(!p&&h)return h(c,!0);if(o)return o(c,!0);throw new Error("Cannot find module '"+c+"'")}p=e[c]={exports:{}},t[c][0].call(p.exports,function(S){var E=t[c][1][S];return r(E||S)},p,p.exports,i,t,e,n)}return e[c].exports}for(var o=typeof require=="function"&&require,s=0;s<n.length;s++)r(n[s]);return r}({1:[function(i,t,e){(function(n,r,o,s,c,p,h,S,E){"use strict";var g=i("crypto");function P(y,I){I=C(y,I);var d;return(d=I.algorithm!=="passthrough"?g.createHash(I.algorithm):new A).write===void 0&&(d.write=d.update,d.end=d.update),O(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 b=g.getHashes?g.getHashes().slice():["sha1","md5"],v=(b.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<b.length;++f)b[f].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=b[f]);if(b.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+b.join(", "));if(v.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+v.join(", "));return d}function x(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 O(y,I,d){d=d||[];function f(l){return I.update?I.update(l,"utf8"):I.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=y.replacer?y.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var w,D=Object.prototype.toString.call(l),F=/\[object (.*)\]/i.exec(D);if(F=(F=F?F[1]:"unknown:["+D+"]").toLowerCase(),0<=(D=d.indexOf(l)))return this.dispatch("[CIRCULAR:"+D+"]");if(d.push(l),o!==void 0&&o.isBuffer&&o.isBuffer(l))return f("buffer:"),f(l);if(F==="object"||F==="function"||F==="asyncfunction")return D=Object.keys(l),y.unorderedObjects&&(D=D.sort()),y.respectType===!1||x(l)||D.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(D=D.filter(function(M){return!y.excludeKeys(M)})),f("object:"+D.length+":"),w=this,D.forEach(function(M){w.dispatch(M),f(":"),y.excludeValues||w.dispatch(l[M]),f(",")});if(!this["_"+F]){if(y.ignoreUnknown)return f("["+F+"]");throw new Error('Unknown object type "'+F+'"')}this["_"+F](l)},_array:function(l,M){M=M!==void 0?M:y.unorderedArrays!==!1;var D=this;if(f("array:"+l.length+":"),!M||l.length<=1)return l.forEach(function(j){return D.dispatch(j)});var F=[],M=l.map(function(j){var B=new A,q=d.slice();return O(y,B,q).dispatch(j),F=F.concat(q.slice(d.length)),B.read().toString()});return d=d.concat(F),M.sort(),this._array(M,!1)},_date:function(l){return f("date:"+l.toJSON())},_symbol:function(l){return f("symbol:"+l.toString())},_error:function(l){return f("error:"+l.toString())},_boolean:function(l){return f("bool:"+l.toString())},_string:function(l){f("string:"+l.length+":"),f(l.toString())},_function:function(l){f("fn:"),x(l)?this.dispatch("[native]"):this.dispatch(l.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),y.respectFunctionProperties&&this._object(l)},_number:function(l){return f("number:"+l.toString())},_xml:function(l){return f("xml:"+l.toString())},_null:function(){return f("Null")},_undefined:function(){return f("Undefined")},_regexp:function(l){return f("regex:"+l.toString())},_uint8array:function(l){return f("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return f("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return f("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return f("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return f("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return f("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return f("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return f("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return f("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return f("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return f("url:"+l.toString())},_map:function(l){return f("map:"),l=Array.from(l),this._array(l,y.unorderedSets!==!1)},_set:function(l){return f("set:"),l=Array.from(l),this._array(l,y.unorderedSets!==!1)},_file:function(l){return f("file:"),this.dispatch([l.name,l.size,l.type,l.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
4
|
`)},_domwindow:function(){return f("domwindow")},_bigint:function(l){return f("bigint:"+l.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={}),O(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,o,s,c,p,h,S,E){(function(g){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,b="+".charCodeAt(0),v="/".charCodeAt(0),C="0".charCodeAt(0),x="a".charCodeAt(0),O="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function I(d){return d=d.charCodeAt(0),d===b||d===A?62:d===v||d===y?63:d<C?-1:d<C+10?d-C+26+26:d<O+26?d-O:d<x+26?d-x+26:void 0}g.toByteArray=function(d){var f,l;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,M=0;function j(B){D[M++]=B}for(f=0;f<F;f+=4,0)j((16711680&(l=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&l)>>8),j(255&l);return w==2?j(255&(l=I(d.charAt(f))<<2|I(d.charAt(f+1))>>4)):w==1&&(j((l=I(d.charAt(f))<<10|I(d.charAt(f+1))<<4|I(d.charAt(f+2))>>2)>>8&255),j(255&l)),D},g.fromByteArray=function(d){var f,l,w,D,F=d.length%3,M="";function j(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(f=0,w=d.length-F;f<w;f+=3)l=(d[f]<<16)+(d[f+1]<<8)+d[f+2],M+=j((D=l)>>18&63)+j(D>>12&63)+j(D>>6&63)+j(63&D);switch(F){case 1:M=(M+=j((l=d[d.length-1])>>2))+j(l<<4&63)+"==";break;case 2:M=(M=(M+=j((l=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(l>>4&63))+j(l<<2&63)+"="}return M}})(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,b,s,c,p,h,S,E){var g=i("base64-js"),P=i("ieee754");function b(a,u,m){if(!(this instanceof b))return new b(a,u,m);var T,_,k,L,Q=typeof a;if(u==="base64"&&Q=="string")for(a=(L=a).trim?L.trim():L.replace(/^\s+|\s+$/g,"");a.length%4!=0;)a+="=";if(Q=="number")T=ee(a);else if(Q=="string")T=b.byteLength(a,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");T=ee(a.length)}if(b._useTypedArrays?_=b._augment(new Uint8Array(T)):((_=this).length=T,_._isBuffer=!0),b._useTypedArrays&&typeof a.byteLength=="number")_._set(a);else if(H(L=a)||b.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(k=0;k<T;k++)b.isBuffer(a)?_[k]=a.readUInt8(k):_[k]=a[k];else if(Q=="string")_.write(a,0,u);else if(Q=="number"&&!b._useTypedArrays&&!m)for(k=0;k<T;k++)_[k]=0;return _}function v(a,u,m,T){return b._charsWritten=ut(function(_){for(var k=[],L=0;L<_.length;L++)k.push(255&_.charCodeAt(L));return k}(u),a,m,T)}function C(a,u,m,T){return b._charsWritten=ut(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),a,m,T)}function x(a,u,m){var T="";m=Math.min(a.length,m);for(var _=u;_<m;_++)T+=String.fromCharCode(a[_]);return T}function O(a,u,m,k){k||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+1<a.length,"Trying to read beyond buffer length"));var _,k=a.length;if(!(k<=u))return m?(_=a[u],u+1<k&&(_|=a[u+1]<<8)):(_=a[u]<<8,u+1<k&&(_|=a[u+1])),_}function A(a,u,m,k){k||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+3<a.length,"Trying to read beyond buffer length"));var _,k=a.length;if(!(k<=u))return m?(u+2<k&&(_=a[u+2]<<16),u+1<k&&(_|=a[u+1]<<8),_|=a[u],u+3<k&&(_+=a[u+3]<<24>>>0)):(u+1<k&&(_=a[u+1]<<16),u+2<k&&(_|=a[u+2]<<8),u+3<k&&(_|=a[u+3]),_+=a[u]<<24>>>0),_}function y(a,u,m,T){if(T||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+1<a.length,"Trying to read beyond buffer length")),!(a.length<=u))return T=O(a,u,m,!0),32768&T?-1*(65535-T+1):T}function I(a,u,m,T){if(T||(R(typeof m=="boolean","missing or invalid endian"),R(u!=null,"missing offset"),R(u+3<a.length,"Trying to read beyond buffer length")),!(a.length<=u))return T=A(a,u,m,!0),2147483648&T?-1*(4294967295-T+1):T}function d(a,u,m,T){return T||(R(typeof m=="boolean","missing or invalid endian"),R(u+3<a.length,"Trying to read beyond buffer length")),P.read(a,u,m,23,4)}function f(a,u,m,T){return T||(R(typeof m=="boolean","missing or invalid endian"),R(u+7<a.length,"Trying to read beyond buffer length")),P.read(a,u,m,52,8)}function l(a,u,m,T,_){if(_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+1<a.length,"trying to write beyond buffer length"),vn(u,65535)),_=a.length,!(_<=m))for(var k=0,L=Math.min(_-m,2);k<L;k++)a[m+k]=(u&255<<8*(T?k:1-k))>>>8*(T?k:1-k)}function w(a,u,m,T,_){if(_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<a.length,"trying to write beyond buffer length"),vn(u,4294967295)),_=a.length,!(_<=m))for(var k=0,L=Math.min(_-m,4);k<L;k++)a[m+k]=u>>>8*(T?k:3-k)&255}function D(a,u,m,T,_){_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+1<a.length,"Trying to write beyond buffer length"),Sn(u,32767,-32768)),a.length<=m||l(a,0<=u?u:65535+u+1,m,T,_)}function F(a,u,m,T,_){_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<a.length,"Trying to write beyond buffer length"),Sn(u,2147483647,-2147483648)),a.length<=m||w(a,0<=u?u:4294967295+u+1,m,T,_)}function M(a,u,m,T,_){_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+3<a.length,"Trying to write beyond buffer length"),ai(u,34028234663852886e22,-34028234663852886e22)),a.length<=m||P.write(a,u,m,T,23,4)}function j(a,u,m,T,_){_||(R(u!=null,"missing value"),R(typeof T=="boolean","missing or invalid endian"),R(m!=null,"missing offset"),R(m+7<a.length,"Trying to write beyond buffer length"),ai(u,17976931348623157e292,-17976931348623157e292)),a.length<=m||P.write(a,u,m,T,52,8)}e.Buffer=b,e.SlowBuffer=b,e.INSPECT_MAX_BYTES=50,b.poolSize=8192,b._useTypedArrays=function(){try{var a=new ArrayBuffer(0),u=new Uint8Array(a);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),b.isEncoding=function(a){switch(String(a).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},b.isBuffer=function(a){return!(a==null||!a._isBuffer)},b.byteLength=function(a,u){var m;switch(a+="",u||"utf8"){case"hex":m=a.length/2;break;case"utf8":case"utf-8":m=be(a).length;break;case"ascii":case"binary":case"raw":m=a.length;break;case"base64":m=oi(a).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=2*a.length;break;default:throw new Error("Unknown encoding")}return m},b.concat=function(a,u){if(R(H(a),`Usage: Buffer.concat(list, [totalLength])
|
|
5
5
|
list should be an Array.`),a.length===0)return new b(0);if(a.length===1)return a[0];if(typeof u!="number")for(_=u=0;_<a.length;_++)u+=a[_].length;for(var m=new b(u),T=0,_=0;_<a.length;_++){var k=a[_];k.copy(m,T),T+=k.length}return m},b.prototype.write=function(a,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),R((J=ie.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var je=0;je<G;je++){var ci=parseInt(ie.substr(2*je,2),16);R(!isNaN(ci),"Invalid hex string"),he[re+je]=ci}return b._charsWritten=2*je,je}(this,a,u,m);break;case"utf8":case"utf-8":k=this,L=u,Q=m,_=b._charsWritten=ut(be(a),k,L,Q);break;case"ascii":case"binary":_=v(this,a,u,m);break;case"base64":k=this,L=u,Q=m,_=b._charsWritten=ut(oi(a),k,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=C(this,a,u,m);break;default:throw new Error("Unknown encoding")}return _},b.prototype.toString=function(a,u,m){var T,_,k,L,Q=this;if(a=String(a||"utf8").toLowerCase(),u=Number(u)||0,(m=m!==void 0?Number(m):Q.length)===u)return"";switch(a){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+=z(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+=si(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return re+si(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?g.fromByteArray(_):g.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},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},b.prototype.copy=function(a,u,m,T){if(u=u||0,(T=T||T===0?T:this.length)!==(m=m||0)&&a.length!==0&&this.length!==0){R(m<=T,"sourceEnd < sourceStart"),R(0<=u&&u<a.length,"targetStart out of bounds"),R(0<=m&&m<this.length,"sourceStart out of bounds"),R(0<=T&&T<=this.length,"sourceEnd out of bounds"),T>this.length&&(T=this.length);var _=(T=a.length-u<T-m?a.length-u+m:T)-m;if(_<100||!b._useTypedArrays)for(var k=0;k<_;k++)a[k+u]=this[k+m];else a._set(this.subarray(m,m+_),u)}},b.prototype.slice=function(a,u){var m=this.length;if(a=q(a,m,0),u=q(u,m,m),b._useTypedArrays)return b._augment(this.subarray(a,u));for(var T=u-a,_=new b(T,void 0,!0),k=0;k<T;k++)_[k]=this[k+a];return _},b.prototype.get=function(a){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(a)},b.prototype.set=function(a,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(a,u)},b.prototype.readUInt8=function(a,u){if(u||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return this[a]},b.prototype.readUInt16LE=function(a,u){return O(this,a,!0,u)},b.prototype.readUInt16BE=function(a,u){return O(this,a,!1,u)},b.prototype.readUInt32LE=function(a,u){return A(this,a,!0,u)},b.prototype.readUInt32BE=function(a,u){return A(this,a,!1,u)},b.prototype.readInt8=function(a,u){if(u||(R(a!=null,"missing offset"),R(a<this.length,"Trying to read beyond buffer length")),!(a>=this.length))return 128&this[a]?-1*(255-this[a]+1):this[a]},b.prototype.readInt16LE=function(a,u){return y(this,a,!0,u)},b.prototype.readInt16BE=function(a,u){return y(this,a,!1,u)},b.prototype.readInt32LE=function(a,u){return I(this,a,!0,u)},b.prototype.readInt32BE=function(a,u){return I(this,a,!1,u)},b.prototype.readFloatLE=function(a,u){return d(this,a,!0,u)},b.prototype.readFloatBE=function(a,u){return d(this,a,!1,u)},b.prototype.readDoubleLE=function(a,u){return f(this,a,!0,u)},b.prototype.readDoubleBE=function(a,u){return f(this,a,!1,u)},b.prototype.writeUInt8=function(a,u,m){m||(R(a!=null,"missing value"),R(u!=null,"missing offset"),R(u<this.length,"trying to write beyond buffer length"),vn(a,255)),u>=this.length||(this[u]=a)},b.prototype.writeUInt16LE=function(a,u,m){l(this,a,u,!0,m)},b.prototype.writeUInt16BE=function(a,u,m){l(this,a,u,!1,m)},b.prototype.writeUInt32LE=function(a,u,m){w(this,a,u,!0,m)},b.prototype.writeUInt32BE=function(a,u,m){w(this,a,u,!1,m)},b.prototype.writeInt8=function(a,u,m){m||(R(a!=null,"missing value"),R(u!=null,"missing offset"),R(u<this.length,"Trying to write beyond buffer length"),Sn(a,127,-128)),u>=this.length||(0<=a?this.writeUInt8(a,u,m):this.writeUInt8(255+a+1,u,m))},b.prototype.writeInt16LE=function(a,u,m){D(this,a,u,!0,m)},b.prototype.writeInt16BE=function(a,u,m){D(this,a,u,!1,m)},b.prototype.writeInt32LE=function(a,u,m){F(this,a,u,!0,m)},b.prototype.writeInt32BE=function(a,u,m){F(this,a,u,!1,m)},b.prototype.writeFloatLE=function(a,u,m){M(this,a,u,!0,m)},b.prototype.writeFloatBE=function(a,u,m){M(this,a,u,!1,m)},b.prototype.writeDoubleLE=function(a,u,m){j(this,a,u,!0,m)},b.prototype.writeDoubleBE=function(a,u,m){j(this,a,u,!1,m)},b.prototype.fill=function(a,u,m){if(u=u||0,m=m||this.length,R(typeof(a=typeof(a=a||0)=="string"?a.charCodeAt(0):a)=="number"&&!isNaN(a),"value is not a number"),R(u<=m,"end < start"),m!==u&&this.length!==0){R(0<=u&&u<this.length,"start out of bounds"),R(0<=m&&m<=this.length,"end out of bounds");for(var T=u;T<m;T++)this[T]=a}},b.prototype.inspect=function(){for(var a=[],u=this.length,m=0;m<u;m++)if(a[m]=z(this[m]),m===e.INSPECT_MAX_BYTES){a[m+1]="...";break}return"<Buffer "+a.join(" ")+">"},b.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(b._useTypedArrays)return new b(this).buffer;for(var a=new Uint8Array(this.length),u=0,m=a.length;u<m;u+=1)a[u]=this[u];return a.buffer};var B=b.prototype;function q(a,u,m){return typeof a!="number"?m:u<=(a=~~a)?u:0<=a||0<=(a+=u)?a:0}function ee(a){return(a=~~Math.ceil(+a))<0?0:a}function H(a){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(a)}function z(a){return a<16?"0"+a.toString(16):a.toString(16)}function be(a){for(var u=[],m=0;m<a.length;m++){var T=a.charCodeAt(m);if(T<=127)u.push(a.charCodeAt(m));else for(var _=m,k=(55296<=T&&T<=57343&&m++,encodeURIComponent(a.slice(_,m+1)).substr(1).split("%")),L=0;L<k.length;L++)u.push(parseInt(k[L],16))}return u}function oi(a){return g.toByteArray(a)}function ut(a,u,m,T){for(var _=0;_<T&&!(_+m>=u.length||_>=a.length);_++)u[_+m]=a[_];return _}function si(a){try{return decodeURIComponent(a)}catch{return String.fromCharCode(65533)}}function vn(a,u){R(typeof a=="number","cannot write a non-number as a number"),R(0<=a,"specified a negative value for writing an unsigned value"),R(a<=u,"value is larger than maximum value for type"),R(Math.floor(a)===a,"value has a fractional component")}function Sn(a,u,m){R(typeof a=="number","cannot write a non-number as a number"),R(a<=u,"value larger than maximum allowed value"),R(m<=a,"value smaller than minimum allowed value"),R(Math.floor(a)===a,"value has a fractional component")}function ai(a,u,m){R(typeof a=="number","cannot write a non-number as a number"),R(a<=u,"value larger than maximum allowed value"),R(m<=a,"value smaller than minimum allowed value")}function R(a,u){if(!a)throw new Error(u||"Failed assertion")}b._augment=function(a){return a._isBuffer=!0,a._get=a.get,a._set=a.set,a.get=B.get,a.set=B.set,a.write=B.write,a.toString=B.toString,a.toLocaleString=B.toString,a.toJSON=B.toJSON,a.copy=B.copy,a.slice=B.slice,a.readUInt8=B.readUInt8,a.readUInt16LE=B.readUInt16LE,a.readUInt16BE=B.readUInt16BE,a.readUInt32LE=B.readUInt32LE,a.readUInt32BE=B.readUInt32BE,a.readInt8=B.readInt8,a.readInt16LE=B.readInt16LE,a.readInt16BE=B.readInt16BE,a.readInt32LE=B.readInt32LE,a.readInt32BE=B.readInt32BE,a.readFloatLE=B.readFloatLE,a.readFloatBE=B.readFloatBE,a.readDoubleLE=B.readDoubleLE,a.readDoubleBE=B.readDoubleBE,a.writeUInt8=B.writeUInt8,a.writeUInt16LE=B.writeUInt16LE,a.writeUInt16BE=B.writeUInt16BE,a.writeUInt32LE=B.writeUInt32LE,a.writeUInt32BE=B.writeUInt32BE,a.writeInt8=B.writeInt8,a.writeInt16LE=B.writeInt16LE,a.writeInt16BE=B.writeInt16BE,a.writeInt32LE=B.writeInt32LE,a.writeInt32BE=B.writeInt32BE,a.writeFloatLE=B.writeFloatLE,a.writeFloatBE=B.writeFloatBE,a.writeDoubleLE=B.writeDoubleLE,a.writeDoubleBE=B.writeDoubleBE,a.fill=B.fill,a.inspect=B.inspect,a.toArrayBuffer=B.toArrayBuffer,a}}).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,g,s,c,p,h,S,E){var g=i("buffer").Buffer,P=4,b=new g(P);b.fill(0),t.exports={hash:function(v,C,x,O){for(var A=C(function(l,w){l.length%P!=0&&(D=l.length+(P-l.length%P),l=g.concat([l,b],D));for(var D,F=[],M=w?l.readInt32BE:l.readInt32LE,j=0;j<l.length;j+=P)F.push(M.call(l,j));return F}(v=g.isBuffer(v)?v:new g(v),O),8*v.length),C=O,y=new g(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,g,s,c,p,h,S,E){var g=i("buffer").Buffer,P=i("./sha"),b=i("./sha256"),v=i("./rng"),C={sha1:P,sha256:b,md5:i("./md5")},x=64,O=new g(x);function A(l,w){var D=C[l=l||"sha1"],F=[];return D||y("algorithm:",l,"is not yet supported"),{update:function(M){return g.isBuffer(M)||(M=new g(M)),F.push(M),M.length,this},digest:function(M){var j=g.concat(F),j=w?function(B,q,ee){g.isBuffer(q)||(q=new g(q)),g.isBuffer(ee)||(ee=new g(ee)),q.length>x?q=B(q):q.length<x&&(q=g.concat([q,O],x));for(var H=new g(x),z=new g(x),be=0;be<x;be++)H[be]=54^q[be],z[be]=92^q[be];return ee=B(g.concat([H,ee])),B(g.concat([z,ee]))}(D,w,j):D(j);return F=null,M?j.toString(M):j}}}function y(){var l=[].slice.call(arguments).join(" ");throw new Error([l,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
|
|
6
|
-
`))}O.fill(0),e.createHash=function(l){return A(l)},e.createHmac=A,e.randomBytes=function(l,w){if(!w||!w.call)return new g(v(l));try{w.call(this,void 0,new g(v(l)))}catch(D){w(D)}};var I,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],f=function(l){e[l]=function(){y("sorry,",l,"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,o,s,c,p,h,S,E){var g=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,l=-1732584194,w=271733878,D=0;D<y.length;D+=16){var F=d,M=f,j=l,B=w,d=v(d,f,l,w,y[D+0],7,-680876936),w=v(w,d,f,l,y[D+1],12,-389564586),l=v(l,w,d,f,y[D+2],17,606105819),f=v(f,l,w,d,y[D+3],22,-1044525330);d=v(d,f,l,w,y[D+4],7,-176418897),w=v(w,d,f,l,y[D+5],12,1200080426),l=v(l,w,d,f,y[D+6],17,-1473231341),f=v(f,l,w,d,y[D+7],22,-45705983),d=v(d,f,l,w,y[D+8],7,1770035416),w=v(w,d,f,l,y[D+9],12,-1958414417),l=v(l,w,d,f,y[D+10],17,-42063),f=v(f,l,w,d,y[D+11],22,-1990404162),d=v(d,f,l,w,y[D+12],7,1804603682),w=v(w,d,f,l,y[D+13],12,-40341101),l=v(l,w,d,f,y[D+14],17,-1502002290),d=C(d,f=v(f,l,w,d,y[D+15],22,1236535329),l,w,y[D+1],5,-165796510),w=C(w,d,f,l,y[D+6],9,-1069501632),l=C(l,w,d,f,y[D+11],14,643717713),f=C(f,l,w,d,y[D+0],20,-373897302),d=C(d,f,l,w,y[D+5],5,-701558691),w=C(w,d,f,l,y[D+10],9,38016083),l=C(l,w,d,f,y[D+15],14,-660478335),f=C(f,l,w,d,y[D+4],20,-405537848),d=C(d,f,l,w,y[D+9],5,568446438),w=C(w,d,f,l,y[D+14],9,-1019803690),l=C(l,w,d,f,y[D+3],14,-187363961),f=C(f,l,w,d,y[D+8],20,1163531501),d=C(d,f,l,w,y[D+13],5,-1444681467),w=C(w,d,f,l,y[D+2],9,-51403784),l=C(l,w,d,f,y[D+7],14,1735328473),d=x(d,f=C(f,l,w,d,y[D+12],20,-1926607734),l,w,y[D+5],4,-378558),w=x(w,d,f,l,y[D+8],11,-2022574463),l=x(l,w,d,f,y[D+11],16,1839030562),f=x(f,l,w,d,y[D+14],23,-35309556),d=x(d,f,l,w,y[D+1],4,-1530992060),w=x(w,d,f,l,y[D+4],11,1272893353),l=x(l,w,d,f,y[D+7],16,-155497632),f=x(f,l,w,d,y[D+10],23,-1094730640),d=x(d,f,l,w,y[D+13],4,681279174),w=x(w,d,f,l,y[D+0],11,-358537222),l=x(l,w,d,f,y[D+3],16,-722521979),f=x(f,l,w,d,y[D+6],23,76029189),d=x(d,f,l,w,y[D+9],4,-640364487),w=x(w,d,f,l,y[D+12],11,-421815835),l=x(l,w,d,f,y[D+15],16,530742520),d=O(d,f=x(f,l,w,d,y[D+2],23,-995338651),l,w,y[D+0],6,-198630844),w=O(w,d,f,l,y[D+7],10,1126891415),l=O(l,w,d,f,y[D+14],15,-1416354905),f=O(f,l,w,d,y[D+5],21,-57434055),d=O(d,f,l,w,y[D+12],6,1700485571),w=O(w,d,f,l,y[D+3],10,-1894986606),l=O(l,w,d,f,y[D+10],15,-1051523),f=O(f,l,w,d,y[D+1],21,-2054922799),d=O(d,f,l,w,y[D+8],6,1873313359),w=O(w,d,f,l,y[D+15],10,-30611744),l=O(l,w,d,f,y[D+6],15,-1560198380),f=O(f,l,w,d,y[D+13],21,1309151649),d=O(d,f,l,w,y[D+4],6,-145523070),w=O(w,d,f,l,y[D+11],10,-1120210379),l=O(l,w,d,f,y[D+2],15,718787259),f=O(f,l,w,d,y[D+9],21,-343485551),d=A(d,F),f=A(f,M),l=A(l,j),w=A(w,B)}return Array(d,f,l,w)}function b(y,I,d,f,l,w){return A((I=A(A(I,y),A(f,w)))<<l|I>>>32-l,d)}function v(y,I,d,f,l,w,D){return b(I&d|~I&f,y,I,l,w,D)}function C(y,I,d,f,l,w,D){return b(I&f|d&~f,y,I,l,w,D)}function x(y,I,d,f,l,w,D){return b(I^d^f,y,I,l,w,D)}function O(y,I,d,f,l,w,D){return b(d^(I|~f),y,I,l,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 g.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,o,s,c,p,h,S,E){var g;t.exports=g||function(P){for(var b,v=new Array(P),C=0;C<P;C++)!(3&C)&&(b=4294967296*Math.random()),v[C]=b>>>((3&C)<<3)&255;return v}}).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,o,s,c,p,h,S,E){var g=i("./helpers");function P(C,x){C[x>>5]|=128<<24-x%32,C[15+(x+64>>9<<4)]=x;for(var O,A,y,I=Array(80),d=1732584193,f=-271733879,l=-1732584194,w=271733878,D=-1009589776,F=0;F<C.length;F+=16){for(var M=d,j=f,B=l,q=w,ee=D,H=0;H<80;H++){I[H]=H<16?C[F+H]:v(I[H-3]^I[H-8]^I[H-14]^I[H-16],1);var z=b(b(v(d,5),(z=f,A=l,y=w,(O=H)<20?z&A|~z&y:!(O<40)&&O<60?z&A|z&y|A&y:z^A^y)),b(b(D,I[H]),(O=H)<20?1518500249:O<40?1859775393:O<60?-1894007588:-899497514)),D=w,w=l,l=v(f,30),f=d,d=z}d=b(d,M),f=b(f,j),l=b(l,B),w=b(w,q),D=b(D,ee)}return Array(d,f,l,w,D)}function b(C,x){var O=(65535&C)+(65535&x);return(C>>16)+(x>>16)+(O>>16)<<16|65535&O}function v(C,x){return C<<x|C>>>32-x}t.exports=function(C){return g.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,o,s,c,p,h,S,E){function g(x,O){var A=(65535&x)+(65535&O);return(x>>16)+(O>>16)+(A>>16)<<16|65535&A}function P(x,O){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[O>>5]|=128<<24-O%32,x[15+(O+64>>9<<4)]=O;for(var f,l,w=0;w<x.length;w+=16){for(var D=I[0],F=I[1],M=I[2],j=I[3],B=I[4],q=I[5],ee=I[6],H=I[7],z=0;z<64;z++)d[z]=z<16?x[z+w]:g(g(g((l=d[z-2],v(l,17)^v(l,19)^C(l,10)),d[z-7]),(l=d[z-15],v(l,7)^v(l,18)^C(l,3))),d[z-16]),A=g(g(g(g(H,v(l=B,6)^v(l,11)^v(l,25)),B&q^~B&ee),y[z]),d[z]),f=g(v(f=D,2)^v(f,13)^v(f,22),D&F^D&M^F&M),H=ee,ee=q,q=B,B=g(j,A),j=M,M=F,F=D,D=g(A,f);I[0]=g(D,I[0]),I[1]=g(F,I[1]),I[2]=g(M,I[2]),I[3]=g(j,I[3]),I[4]=g(B,I[4]),I[5]=g(q,I[5]),I[6]=g(ee,I[6]),I[7]=g(H,I[7])}return I}var b=i("./helpers"),v=function(x,O){return x>>>O|x<<32-O},C=function(x,O){return x>>>O};t.exports=function(x){return b.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,o,s,c,p,h,S,E){e.read=function(g,P,b,v,w){var x,O,A=8*w-v-1,y=(1<<A)-1,I=y>>1,d=-7,f=b?w-1:0,l=b?-1:1,w=g[P+f];for(f+=l,x=w&(1<<-d)-1,w>>=-d,d+=A;0<d;x=256*x+g[P+f],f+=l,d-=8);for(O=x&(1<<-d)-1,x>>=-d,d+=v;0<d;O=256*O+g[P+f],f+=l,d-=8);if(x===0)x=1-I;else{if(x===y)return O?NaN:1/0*(w?-1:1);O+=Math.pow(2,v),x-=I}return(w?-1:1)*O*Math.pow(2,x-v)},e.write=function(g,P,b,v,C,D){var O,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,l=v?0:D-1,w=v?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,O=I):(O=Math.floor(Math.log(P)/Math.LN2),P*(v=Math.pow(2,-O))<1&&(O--,v*=2),2<=(P+=1<=O+d?f/v:f*Math.pow(2,1-d))*v&&(O++,v/=2),I<=O+d?(A=0,O=I):1<=O+d?(A=(P*v-1)*Math.pow(2,C),O+=d):(A=P*Math.pow(2,d-1)*Math.pow(2,C),O=0));8<=C;g[b+l]=255&A,l+=w,A/=256,C-=8);for(O=O<<C|A,y+=C;0<y;g[b+l]=255&O,l+=w,O/=256,y-=8);g[b+l-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,o,s,c,p,h,S,E){var g,P,b;function v(){}(n=t.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(C){return window.setImmediate(C)}:b?(g=[],window.addEventListener("message",function(C){var x=C.source;x!==window&&x!==null||C.data!=="process-tick"||(C.stopPropagation(),0<g.length&&g.shift()())},!0),function(C){g.push(C),window.postMessage("process-tick","*")}):function(C){setTimeout(C,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.binding=function(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 ri={};yr(ri,{Client:()=>Fe,ClientDescriptor:()=>wn,Entity:()=>ye,EntityFile:()=>Be,MigrationPathError:()=>Ne,ServerSync:()=>$e,Storage:()=>Fe,StorageDescriptor:()=>wn,collection:()=>qi,createDefaultMigration:()=>Hn,createMigration:()=>Qn,migrate:()=>Bt,schema:()=>Wi});var Di=ft(mt(),1),yt=4,Je=36;function vi(i){return i.toString(Je).padStart(yt,"0")}function Ir(i){return i.toString().padStart(6,"0")}var gt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Dr()};this.zeroCounter=0;this.now=t=>(this.latest=xi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=xi(this.latest),Ir(t)+Er(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(yt);this.latest=Cr(this.latest,Oi(e))};this.get=(t,e)=>vi(t)+Si(e);this.zero=t=>vi(t)+Si({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>Oi(t.slice(yt)).time}},bt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},wt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},En=4,Pn=7,vt=60*1e3,Qe=9;function Dr(){return Di.default.slug().padStart(Pn,"0").slice(0,Pn)}function Si(i){let t=new Date(i.time).getTime().toString(Je).padStart(Qe,"0"),e=i.counter.toString(Je).padStart(En,"0"),n=i.node.padStart(Pn,"0");return`${t}${e}${n}`}function xi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>vt)throw new bt(e,t,vt);if(n>65535)throw new wt;return{time:e,counter:n,node:i.node}}function Cr(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),o;if(i.time===n&&t.time===n?o=r+1:i.time===n?o=i.counter+1:t.time===n?o=t.counter+1:o=0,n-e>vt)throw new bt(n,e,vt);if(o>65535)throw new wt;return{time:n,counter:o,node:i.node}}function Oi(i){let t=i.slice(0,Qe),e=i.slice(Qe,Qe+En),n=i.slice(Qe+En),r=parseInt(t,Je),o=parseInt(e,Je);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:n}}function Er(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 Ii(i){return parseInt(i.slice(0,yt),36)}function Ci(i,t){return Ii(i)-Ii(t)}function oe(i){return i&&i["@@type"]==="file"}function Ei(i){return{"@@type":"file",id:i}}var St,Pr=new Uint8Array(16);function _n(){if(!St&&(St=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!St))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return St(Pr)}var Pi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function _r(i){return typeof i=="string"&&Pi.test(i)}var _i=_r;var Z=[];for(xt=0;xt<256;++xt)Z.push((xt+256).toString(16).substr(1));var xt;function Tr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(Z[i[t+0]]+Z[i[t+1]]+Z[i[t+2]]+Z[i[t+3]]+"-"+Z[i[t+4]]+Z[i[t+5]]+"-"+Z[i[t+6]]+Z[i[t+7]]+"-"+Z[i[t+8]]+Z[i[t+9]]+"-"+Z[i[t+10]]+Z[i[t+11]]+Z[i[t+12]]+Z[i[t+13]]+Z[i[t+14]]+Z[i[t+15]]).toLowerCase();if(!_i(e))throw TypeError("Stringified UUID is invalid");return e}var Ti=Tr;function Ar(i,t,e){i=i||{};var n=i.random||(i.rng||_n)();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 Ti(n)}var Ye=Ar;function te(i){return ne(i)||oe(i)}function Tn(i,t){return i===t?!0:!(!te(i)||!te(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Bi=ft(ki(),1);function Rr(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 Ge(i){return JSON.stringify(i,Rr)}function se(i,t=!0){if(U(i)||Array.isArray(i)){let e=ce(i),n;if(Array.isArray(i))n=i.map(r=>se(r,t));else{n={};for(let[r,o]of Object.entries(i))n[r]=se(o,t)}return t&&e&&$(n,e),n}return i}function Ie(i){return(0,Bi.default)(i)}function U(i){return i&&typeof i=="object"}function Mi(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 o in r)e.push(r[o])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function Ot(i=16){return Ye().replace("-","").slice(0,i)}function Fi(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function ji(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var ve="__@@oid_do_not_use",Se="@@id",kr="/",Ct=":",Rn=new WeakMap;function le(i){let t=ce(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function ce(i){if(U(i))return Rn.get(i)??i[Se]??i[ve]}function $(i,t){return V(U(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Et(i),Rn.set(i,t),i}function Ze(i){return!!ce(i)}function Et(i){return Rn.delete(i),i}function kn(i){return i===Se||i===ve}function Bn(i,t,e){if(Ze(i))return le(i);{let n=ge(t,e);return $(i,n),n}}function Li(i,t,e){if(Ze(i)){let n=le(i);if(Pt(n,t))return le(i);{let r=ge(t,e);return $(i,r),r}}else{let n=ge(t,e);return $(i,n),n}}var An={".":"˙","/":"&slash;",":":":"};function Vi(i){return i.replace(/[/]/g,An["/"]).replace(/[:]/g,An[":"]).replace(/[.]/g,An["."])}function Ni(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function X(i,t,e){let n=Vi(i)+kr+Vi(t);return e&&(n+=Ct+e),n}function ge(i,t=jr){let{collection:e,id:n}=ae(i);return X(e,n,t())}function ae(i){let[t,e]=i.split(Ct),[n,r,...o]=t.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Ni(n),id:Ni(s),subId:e}}function Le(i,t){let e=le(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],U(n)&&!te(n)&&(Li(n,e,t),Le(n,t))}else if(U(i)&&!te(i))for(let n of Object.keys(i))U(i[n])&&!te(i[n])&&(Li(i[n],e,t),Le(i[n],t))}function Br(i){if(U(i))return i[Se]||i[ve]}function Mr(i){return U(i)&&(delete i[ve],delete i[Se]),i}function Fr(i){let t=Br(i);t&&$(i,t)}function Xe(i){if(Fr(i),Mr(i),Array.isArray(i))for(let t=0;t<i.length;t++)Xe(i[t]);else if(U(i))for(let t of Object.keys(i))Xe(i[t])}function It(i){if(Et(i),Array.isArray(i))for(let t=0;t<i.length;t++)It(i[t]);else if(U(i))for(let t of Object.keys(i))It(i[t])}function jr(){return Ye().slice(0,8)}function we(i){return{"@@type":"ref",id:i}}function Dt(i,t=new Map){if(Array.isArray(i)){let e=le(i),n=$([],e);for(let r=0;r<i.length;r++){let o=i[r];if(U(o)){if(ne(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(oe(o)){n[r]=o;continue}else{let s=le(o);n[r]=we(s),Dt(o,t)}}else n[r]=o}t.set(e,n)}else if(U(i)&&!te(i)){let e=le(i),n=$({},e);for(let r of Object.keys(i)){let o=i[r];if(U(o)){if(ne(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(oe(o))n[r]=o;else{let s=le(o);n[r]=we(s),Dt(o,t)}}else n[r]=o}t.set(e,n)}else te(i);return t}function K(i){return i.split(".")[0].split(Ct)[0]}function Mn(i){let t=K(i),e=ge(t,()=>"\uFFFF");return[`${t}${Ct}`,e]}function Fn(i){let t=K(i);return[`${t}.`,`${t}.\uFFFF`]}function Pt(i,t){return K(i)===K(t)}function Lr(i){let{collection:t,id:e,subId:n}=ae(i);return X(t,e,n)}var Vr=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Nr(i){return i.replaceAll(Vr,t=>{let e=t.slice(1,t.length-1);return`"${Lr(e)}"`})}function jn(i){return JSON.parse(Nr(JSON.stringify(i)))}function ne(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Ln(i){return U(i)&&!te(i)}function Ur(i,t){return i===t?!0:te(i)&&te(t)?Tn(i,t):!1}function et(i,t,e,n,r=[],o={}){let s=le(i);function c(p,h,S){if(!Ln(h))Ur(h,S)||r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:h}});else{let E=ce(S),g=ce(h);g&&!Pt(s,g)?(h=se(h,!1),g=ge(s,n),$(h,g)):o.mergeUnknownObjects?!g&&E?($(h,E),g=E):g=Bn(h,s,n):g=Bn(h,s,n),V(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Pt(s,g),`Error: value OID ${g} is not related to parent OID ${s}. This is a bug in Verdant.`),S===void 0||g!==E?(De(h,g,e,n,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:we(g)}}),E!==void 0&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})):et(S,h,e,n,r,o)}}if(Array.isArray(i)&&Array.isArray(t)){for(let h=0;h<t.length;h++){let S=t[h],E=i[h];c(h,S,E)}let p=i.length-t.length;if(p>0){for(let h=t.length;h<i.length;h++){let S=i[h],E=ce(S);E&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,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(Ln(i)&&Ln(t)){let p=new Set(Object.keys(i));for(let[h,S]of Object.entries(t)){if(S===void 0&&o.defaultUndefined||(p.delete(h),kn(h)))continue;let E=i[h];c(h,S,E)}if(!o.defaultUndefined)for(let h of p)kn(h)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:h}})}}return r}function De(i,t,e,n,r=[]){$(i,t),Le(i,n);let o=Dt(i);for(let s of o.keys()){let c=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Et(c)}})}return r}function Ki(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Vn(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 Nn(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 Ee(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: ${ce(i)})`),!1)}function Pe(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,o;function s(c){e&&te(c)&&e.push(c)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Ee(i)&&i.push(t.value);break;case"list-delete":Ee(i)&&(s(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Ee(i)&&(o=i.splice(t.from,1),i.splice(t.to,0,o[0]));break;case"list-remove":if(Ee(i))do{let c=t.value;t.only==="last"?ne(c)?r=Fi(i,p=>p.id===c.id):r=i.lastIndexOf(c):ne(c)?r=i.findIndex(p=>p.id===c.id):r=i.indexOf(c),r!==-1&&(s(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Ee(i)&&(i.some(p=>ne(p)&&ne(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Ee(i)&&(r=i.indexOf(t.value),o=i.splice(r,1),i.splice(t.index,0,o[0]));break;case"list-insert":if(Ee(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(s):U(i)&&Object.values(i||{}).forEach(s);return;case"initialize":return se(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function _t(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Ui(r,t,e),U(i[n])&&_t(i[n],t,e)}else if(!oe(i)){if(U(i)){V(ce(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Ui(i[n],t,e),U(i[n])&&_t(i[n],t,e)}}return e}function Ui(i,t,e){if(ne(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),$(n,i.id)}else return i}function Kr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Kn(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.type==="object"?!0:i.default!==void 0:!1}function Tt(i){return i.type==="map"||i.type==="object"||i.type==="array"||i.type==="file"||i.type==="any"?!1:i.indexed}function xe(i,t){for(let[e,n]of Object.entries(i.fields)){let r=$i(n);(r!==void 0&&t[e]===void 0||!Kr(n)&&t[e]===null)&&(t[e]=r),t[e]&&_e(t[e],n)}return t}function _e(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=$i(n);r!==void 0&&(i[e]=r)}_e(i[e],n)}else if(t.type==="array")for(let e of i)_e(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Se||e===ve||_e(n,t.values)}function $i(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 $n(i,t){for(let[e,n]of Object.entries(t))e===Se||e===ve||(i.fields[e]?Un(n,i.fields[e]):delete t[e]);return t}function Un(i,t){if(U(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?Un(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)Un(e,t.items)}function zn(i){return i.equals!==void 0}function qn(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function $r(i){return!!i.match}function Wn(i){return i.startsWith!==void 0}function zi(i){return!qn(i)&&!zn(i)&&!$r(i)&&!Wn(i)&&i.order}function tt(i,t,e=[]){if(i.type==="object"){if(!U(t))return t===null&&i.nullable?void 0:`Expected object${i.nullable?" or null":""} for field ${Oe(e)}}`;for(let[n,r]of Object.entries(i.properties))t[n]&&tt(r,t[n]);for(let n of Object.keys(t))if(!i.properties[n])return`Invalid field "${n}" on value ${Oe(e)}`}else if(i.type==="array"){if(!Array.isArray(t))return t===null&&i.nullable?void 0:`Expected array${i.nullable?" or null":""} for field ${Oe(e)}}`;for(let n of t)tt(i.items,n)}else if(i.type==="map"){if(!U(t))return`Expected map for field ${Oe(e)}}`;for(let[n,r]of Object.entries(t))n===Se||n===ve||tt(i.values,r)}else if(i.type==="string"){if(typeof t!="string")return t===null&&i.nullable?void 0:`Expected string ${i.nullable?" or null":""} for field ${Oe(e)}}`;if(i.options&&!i.options.includes(t))return`Expected one of ${i.options.join(", ")} for field ${Oe(e)}`}else if(i.type==="boolean"){if(typeof t!="boolean")return t===null&&i.nullable?void 0:`Expected boolean ${i.nullable?" or null":""} for field ${Oe(e)}}`}else if(i.type==="number"){if(typeof t!="number")return t===null&&i.nullable?void 0:`Expected number ${i.nullable?" or null":""} for field ${Oe(e)}}`}else if(i.type==="file"&&t===null&&!i.nullable)return`Expected file for field ${Oe(e)}}`}function Oe(i){return i.join(".")}function qi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,o]of Object.entries(e.fields))Tt(o)&&(n[r]={field:r});return{...e,indexes:n}}function Wi(i){return i}var At="\uFFFFFE",zr="\0",qr="\uFFFFFF";function de(...i){let t=Wr(i);return t.length===1?t[0]:t}function Te(...i){return i.join(At)+`${qr}`}function Ae(...i){return i.join(At)+`${At}${zr}`}function Wr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let o of e)n.push(r.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(At))))}function Hr(i){return!!i.field}function Qr(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let o=r;Hr(o)?e[n]=me(t[o.field]):e[n]=me(o.compute(t))}return e}function Jr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=de(...r.of.map(o=>t[o])),e),{})}function Yr(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>(Tt(r)&&(e[n]=me(t[n])),e),{})}function Rt(i,t){let e={[i.primaryKey]:t[i.primaryKey],...Yr(i,t),...Qr(i,t)};return Object.assign(e,Jr(i,{...t,...e})),e["@@@snapshot"]=t,e}var Gr="null";function me(i){if(i===null)return Gr;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 Hi={version:0,collections:{}};function Bt(i,t,e){let n=typeof t=="function",r=n?Hi:i,o=n?i:t,s=n?t:e,c=Object.keys(o.collections).filter(v=>r.collections[v]&&Ge(r.collections[v])!==Ge(o.collections[v])),p=Object.keys(r.collections).filter(v=>!o.collections[v]),h=Object.keys(o.collections).filter(v=>!r.collections[v]),S=new Set;for(let v of c){let C=r.collections[v].fields,x=o.collections[v].fields;Object.keys(x).some(O=>!C[O]?.default&&x[O]?.default)&&S.add(v),Object.keys(C).some(O=>!x[O])&&S.add(v)}let E={},g={};for(let v of[...c,...h]){let C=kt(r.collections[v]),x=kt(o.collections[v]),O=x.filter(y=>!C.find(I=>I.name===y.name)),A=C.filter(y=>!x.find(I=>I.name===y.name));O.length>0&&(E[v]=O,c.includes(v)&&S.add(v)),A.length>0&&(g[v]=A,c.includes(v)&&S.add(v))}let P=(v,C)=>xe(o.collections[v],C),b=v=>C=>{let x=o.collections[v];return xe(x,$n(x,C))};return{version:o.version,migrate:async v=>{let C=[];if(await s({migrate:async(x,O)=>{let A=b(x),y=async I=>{let d=await O(I);return $(d,le(I)),A(d)};await v.migrate(x,y),C.push(x),S.delete(x)},identity:x=>x,withDefaults:P,info:{changedCollections:c,addedCollections:h,removedCollections:p},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",S);for(let O of S)await v.migrate(O,b(O)),C.push(O);let x=c.filter(O=>!C.includes(O));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:p,addedIndexes:E,removedIndexes:g,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function kt(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 Hn(i,t){return Bt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let o of r.changedCollections)await n(o,s=>s)})}function Qn(i,t,e){let n=typeof t=="function"||t===void 0,r=n?Hi:i,o=n?i:t,s=n?t:e;V(r,"Invalid arguments to createMigration"),V(o,"Invalid arguments to createMigration");let{changedCollections:c,addedCollections:p,removedCollections:h,addedIndexes:S,removedIndexes:E,autoMigratedCollections:g,autoMigration:P}=Xr(r,o);return{version:o.version,migrate:async b=>{let v=[];if(await s?.({migrate:async(x,O)=>{let A=P(x),y=async I=>{let d=await O(I);return $(d,le(I)),A(d)};await b.migrate(x,y),v.push(x),g.delete(x)},info:{changedCollections:c,addedCollections:p,removedCollections:h},queries:b.queries,mutations:b.mutations}),o.version>1){b.log("debug","auto-migrating collections with new defaults",g);for(let O of g)await b.migrate(O,P(O)),v.push(O);for(let O of h)await b.deleteCollection(O);let x=c.filter(O=>!v.includes(O));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:h,addedIndexes:S,removedIndexes:E,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Xr(i,t){let e=Object.keys(t.collections).filter(S=>i.collections[S]&&Ge(i.collections[S])!==Ge(t.collections[S])),n=Object.keys(i.collections).filter(S=>!t.collections[S]),r=Object.keys(t.collections).filter(S=>!i.collections[S]),o=new Set;for(let S of e){let E=i.collections[S].fields,g=t.collections[S].fields;Object.keys(g).some(P=>!Kn(E[P])&&Kn(g[P]))&&o.add(S),Object.keys(E).some(P=>!g[P])&&o.add(S)}let s={},c={};for(let S of[...e,...r]){let E=kt(i.collections[S]),g=kt(t.collections[S]),P=g.filter(v=>!E.find(C=>C.name===v.name)),b=E.filter(v=>!g.find(C=>C.name===v.name));P.length>0&&(s[S]=P,e.includes(S)&&o.add(S)),b.length>0&&(c[S]=b,e.includes(S)&&o.add(S))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:s,removedIndexes:c,autoMigratedCollections:o,withDefaults:(S,E)=>xe(t.collections[S],E),autoMigration:S=>E=>{let g=t.collections[S];return xe(g,$n(g,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)=>De(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!U(n)||te(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...De(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(U(e)){let n=ge(t,this.createSubId);return[...De(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)=>U(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(U(n)){let r=ge(t,this.createSubId);return[...De(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=Ot(),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=se(t),o=[];for(let s of e){let c=Zr(i,r,s,n);o.unshift(...c),Pe(r,s.data)}return o}function Zr(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 o=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=t.indexOf(r.value);for(;s!==-1;)o.push(s),s=t.indexOf(r.value,s+1);return o.map(c=>({oid:i,timestamp:n(),data:{op:"list-insert",index:c,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 Ve=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:o}){let s=this.batches.get(t);return s||(s=new Jn({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:r,timeout:o,userData:e}),s}},Jn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:o,key:s}){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 o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=o,this.key=s}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function nt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),s=r.objectStore(t).openCursor(),c=0,p=0;s.onsuccess=function(h){let S=s.result;S&&(c++,p=p+Mi(S.value),S.continue())},s.onerror=function(h){n(h)},r.oncomplete=function(h){e({count:c,size:p})},r.onabort=function(h){n(h)},r.onerror=function(h){n(h)}})}function Ji(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let o=e.objectStore(r);return W(o.getAll())});return Promise.all(n)}async function Re(i){i.close(),await new Promise((t,e)=>{t()})}async function Ft(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{n.onsuccess=r,n.onerror=o})]),window.location.reload()}function Yi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function Gi(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 s=(r||this.db.transaction(t,n)).objectStore(t),c=e(s);return W(c)};this.runAll=async(t,e,n="readonly",r)=>{let s=(r||this.db.transaction(t,n)).objectStore(t),c=e(s);return Promise.all(c.map(W))};this.iterate=async(t,e,n,r="readonly",o)=>{let c=(o||this.db.transaction(t,r)).objectStore(t),p=e(c);return Array.isArray(p)?Promise.all(p.map(h=>new Promise((S,E)=>{h.onsuccess=()=>{let g=h.result;g?(n(g.value,c),g.continue()):S()},h.onerror=E}))).then(()=>{}):new Promise((h,S)=>{p.onsuccess=()=>{let E=p.result;E?(n(E.value,c),E.continue()):h()},p.onerror=S})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var jt=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 Lt=class extends fe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:r}),o};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let c=K(e),[p,h]=Mn(e),[S,E]=Fn(e);return[s.openCursor(IDBKeyRange.only(c)),s.openCursor(IDBKeyRange.bound(p,h,!1,!1)),s.openCursor(IDBKeyRange.bound(S,E,!1,!1))]},n,r,o);this.iterateOverAllForCollection=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,r,o);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let c=K(s),[p,h]=Mn(s),[S,E]=Fn(s);return[o.get(c),o.getAll(IDBKeyRange.bound(p,h,!1,!1)),o.getAll(IDBKeyRange.bound(S,E,!1,!1))]}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",o=>o.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(o=>r.put(o)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Xi=ft(mt(),1);var Vt=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);return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,Xi.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),"readwrite"),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",o=>o.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 Nt=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=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add(K(c.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add(K(c.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var Ut=class extends fe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:o,after:s,mode:c="readonly",transaction:p}={})=>{let S=(p||this.db.transaction("operations",c)).objectStore("operations"),E=S.index("d_t"),g=o||s,P=g?de(e,g):Ae(e),b=r?de(e,r):Te(e),v=IDBKeyRange.bound(P,b,!!s,!1),C=E.openCursor(v,"next");return new Promise((x,O)=>{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,S),A=d.timestamp,I.continue()}else x()},C.onerror=y=>{O(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let h=(c||this.db.transaction("operations",s)).objectStore("operations"),S=r?de(e,r):Ae(e),E=o?de(e,o):Te(e),g=IDBKeyRange.bound(S,E,!!r,!1),P=h.openCursor(g,"next");return new Promise((b,v)=>{let C;P.onsuccess=x=>{let O=P.result;if(O){let A=O.value;V(A.oid.startsWith(e)),V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,h),C=A.timestamp,O.continue()}else b()},P.onerror=x=>{v(x)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let p=c||this.db.transaction("operations",s);return this.iterate("operations",h=>h.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,s,p)};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:o="readonly",transaction:s})=>{let p=(s||this.db.transaction("operations",o)).objectStore("operations"),h=p.index("l_t"),S=r?de(!0,r):Ae(!0),E=n?de(!0,n):Te(!0),g=IDBKeyRange.bound(S,E,!!r,!0),P=h.openCursor(g,"next");return new Promise((b,v)=>{let C;P.onsuccess=x=>{let O=P.result;if(O){let A=O.value;V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),e(A,p),C=A.timestamp,O.continue()}else b()},P.onerror=x=>{v(x)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:o,from:s})=>{await this.iterate("operations",c=>{let p=s?Ae(s):void 0,h=n?Te(n):void 0,S=p&&h?IDBKeyRange.bound(p,h,!1,!0):p?IDBKeyRange.lowerBound(p,!1):h?IDBKeyRange.upperBound(h,!0):void 0;return c.index("timestamp").openCursor(S,"next")},e,o,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",o=>e.map(s=>(r.add(K(s.oid)),o.put(s))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Kt=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"),o=await W(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(o)}}};var it=class extends N{constructor({disableRebasing:e,context:n}){super();this.time=new gt;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 o=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:r})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=K(e);V(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),c=new Map;for(let h of s)h.snapshot&&$(h.snapshot,h.oid),c.set(h.oid,h.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,h=>{let S=c.get(h.oid)||void 0,E=Pe(S,h.data);E&&$(E,h.oid),c.set(h.oid,E)},{transaction:o,to:n.to||this.now});let p=c.get(r);return p&&_t(p,c),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(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,o=this.db.transaction(["baselines","operations"],"readwrite"),s=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let c=[];for(let p of r)c.push(await this.rebase(p,n||e,o));this.emit("rebase",c)};this.rebase=async(e,n,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=r||this.db.transaction(["operations","baselines"],"readwrite"),c=await this.baselines.get(e,{transaction:s}),p=c?.snapshot||void 0,h=0,S=[];await this.operations.iterateOverAllOperationsForEntity(e,(g,P)=>{(!c||g.timestamp>c.timestamp)&&(p=Pe(p,g.data,S)),h++,P.delete(g.oid_timestamp)},{to:n,transaction:s}),p&&$(p,e);let E={oid:e,snapshot:p,timestamp:n};if(E.snapshot?await this.baselines.set(E,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("successfully rebased",e,"up to",n,":",p,"and deleted",h,"operations"),S.length){let g=S.filter(oe);g.length&&this.emit("filesDeleted",g)}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}
|
|
6
|
+
`))}O.fill(0),e.createHash=function(l){return A(l)},e.createHmac=A,e.randomBytes=function(l,w){if(!w||!w.call)return new g(v(l));try{w.call(this,void 0,new g(v(l)))}catch(D){w(D)}};var I,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],f=function(l){e[l]=function(){y("sorry,",l,"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,o,s,c,p,h,S,E){var g=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,l=-1732584194,w=271733878,D=0;D<y.length;D+=16){var F=d,M=f,j=l,B=w,d=v(d,f,l,w,y[D+0],7,-680876936),w=v(w,d,f,l,y[D+1],12,-389564586),l=v(l,w,d,f,y[D+2],17,606105819),f=v(f,l,w,d,y[D+3],22,-1044525330);d=v(d,f,l,w,y[D+4],7,-176418897),w=v(w,d,f,l,y[D+5],12,1200080426),l=v(l,w,d,f,y[D+6],17,-1473231341),f=v(f,l,w,d,y[D+7],22,-45705983),d=v(d,f,l,w,y[D+8],7,1770035416),w=v(w,d,f,l,y[D+9],12,-1958414417),l=v(l,w,d,f,y[D+10],17,-42063),f=v(f,l,w,d,y[D+11],22,-1990404162),d=v(d,f,l,w,y[D+12],7,1804603682),w=v(w,d,f,l,y[D+13],12,-40341101),l=v(l,w,d,f,y[D+14],17,-1502002290),d=C(d,f=v(f,l,w,d,y[D+15],22,1236535329),l,w,y[D+1],5,-165796510),w=C(w,d,f,l,y[D+6],9,-1069501632),l=C(l,w,d,f,y[D+11],14,643717713),f=C(f,l,w,d,y[D+0],20,-373897302),d=C(d,f,l,w,y[D+5],5,-701558691),w=C(w,d,f,l,y[D+10],9,38016083),l=C(l,w,d,f,y[D+15],14,-660478335),f=C(f,l,w,d,y[D+4],20,-405537848),d=C(d,f,l,w,y[D+9],5,568446438),w=C(w,d,f,l,y[D+14],9,-1019803690),l=C(l,w,d,f,y[D+3],14,-187363961),f=C(f,l,w,d,y[D+8],20,1163531501),d=C(d,f,l,w,y[D+13],5,-1444681467),w=C(w,d,f,l,y[D+2],9,-51403784),l=C(l,w,d,f,y[D+7],14,1735328473),d=x(d,f=C(f,l,w,d,y[D+12],20,-1926607734),l,w,y[D+5],4,-378558),w=x(w,d,f,l,y[D+8],11,-2022574463),l=x(l,w,d,f,y[D+11],16,1839030562),f=x(f,l,w,d,y[D+14],23,-35309556),d=x(d,f,l,w,y[D+1],4,-1530992060),w=x(w,d,f,l,y[D+4],11,1272893353),l=x(l,w,d,f,y[D+7],16,-155497632),f=x(f,l,w,d,y[D+10],23,-1094730640),d=x(d,f,l,w,y[D+13],4,681279174),w=x(w,d,f,l,y[D+0],11,-358537222),l=x(l,w,d,f,y[D+3],16,-722521979),f=x(f,l,w,d,y[D+6],23,76029189),d=x(d,f,l,w,y[D+9],4,-640364487),w=x(w,d,f,l,y[D+12],11,-421815835),l=x(l,w,d,f,y[D+15],16,530742520),d=O(d,f=x(f,l,w,d,y[D+2],23,-995338651),l,w,y[D+0],6,-198630844),w=O(w,d,f,l,y[D+7],10,1126891415),l=O(l,w,d,f,y[D+14],15,-1416354905),f=O(f,l,w,d,y[D+5],21,-57434055),d=O(d,f,l,w,y[D+12],6,1700485571),w=O(w,d,f,l,y[D+3],10,-1894986606),l=O(l,w,d,f,y[D+10],15,-1051523),f=O(f,l,w,d,y[D+1],21,-2054922799),d=O(d,f,l,w,y[D+8],6,1873313359),w=O(w,d,f,l,y[D+15],10,-30611744),l=O(l,w,d,f,y[D+6],15,-1560198380),f=O(f,l,w,d,y[D+13],21,1309151649),d=O(d,f,l,w,y[D+4],6,-145523070),w=O(w,d,f,l,y[D+11],10,-1120210379),l=O(l,w,d,f,y[D+2],15,718787259),f=O(f,l,w,d,y[D+9],21,-343485551),d=A(d,F),f=A(f,M),l=A(l,j),w=A(w,B)}return Array(d,f,l,w)}function b(y,I,d,f,l,w){return A((I=A(A(I,y),A(f,w)))<<l|I>>>32-l,d)}function v(y,I,d,f,l,w,D){return b(I&d|~I&f,y,I,l,w,D)}function C(y,I,d,f,l,w,D){return b(I&f|d&~f,y,I,l,w,D)}function x(y,I,d,f,l,w,D){return b(I^d^f,y,I,l,w,D)}function O(y,I,d,f,l,w,D){return b(d^(I|~f),y,I,l,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 g.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,o,s,c,p,h,S,E){var g;t.exports=g||function(P){for(var b,v=new Array(P),C=0;C<P;C++)!(3&C)&&(b=4294967296*Math.random()),v[C]=b>>>((3&C)<<3)&255;return v}}).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,o,s,c,p,h,S,E){var g=i("./helpers");function P(C,x){C[x>>5]|=128<<24-x%32,C[15+(x+64>>9<<4)]=x;for(var O,A,y,I=Array(80),d=1732584193,f=-271733879,l=-1732584194,w=271733878,D=-1009589776,F=0;F<C.length;F+=16){for(var M=d,j=f,B=l,q=w,ee=D,H=0;H<80;H++){I[H]=H<16?C[F+H]:v(I[H-3]^I[H-8]^I[H-14]^I[H-16],1);var z=b(b(v(d,5),(z=f,A=l,y=w,(O=H)<20?z&A|~z&y:!(O<40)&&O<60?z&A|z&y|A&y:z^A^y)),b(b(D,I[H]),(O=H)<20?1518500249:O<40?1859775393:O<60?-1894007588:-899497514)),D=w,w=l,l=v(f,30),f=d,d=z}d=b(d,M),f=b(f,j),l=b(l,B),w=b(w,q),D=b(D,ee)}return Array(d,f,l,w,D)}function b(C,x){var O=(65535&C)+(65535&x);return(C>>16)+(x>>16)+(O>>16)<<16|65535&O}function v(C,x){return C<<x|C>>>32-x}t.exports=function(C){return g.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,o,s,c,p,h,S,E){function g(x,O){var A=(65535&x)+(65535&O);return(x>>16)+(O>>16)+(A>>16)<<16|65535&A}function P(x,O){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[O>>5]|=128<<24-O%32,x[15+(O+64>>9<<4)]=O;for(var f,l,w=0;w<x.length;w+=16){for(var D=I[0],F=I[1],M=I[2],j=I[3],B=I[4],q=I[5],ee=I[6],H=I[7],z=0;z<64;z++)d[z]=z<16?x[z+w]:g(g(g((l=d[z-2],v(l,17)^v(l,19)^C(l,10)),d[z-7]),(l=d[z-15],v(l,7)^v(l,18)^C(l,3))),d[z-16]),A=g(g(g(g(H,v(l=B,6)^v(l,11)^v(l,25)),B&q^~B&ee),y[z]),d[z]),f=g(v(f=D,2)^v(f,13)^v(f,22),D&F^D&M^F&M),H=ee,ee=q,q=B,B=g(j,A),j=M,M=F,F=D,D=g(A,f);I[0]=g(D,I[0]),I[1]=g(F,I[1]),I[2]=g(M,I[2]),I[3]=g(j,I[3]),I[4]=g(B,I[4]),I[5]=g(q,I[5]),I[6]=g(ee,I[6]),I[7]=g(H,I[7])}return I}var b=i("./helpers"),v=function(x,O){return x>>>O|x<<32-O},C=function(x,O){return x>>>O};t.exports=function(x){return b.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,o,s,c,p,h,S,E){e.read=function(g,P,b,v,w){var x,O,A=8*w-v-1,y=(1<<A)-1,I=y>>1,d=-7,f=b?w-1:0,l=b?-1:1,w=g[P+f];for(f+=l,x=w&(1<<-d)-1,w>>=-d,d+=A;0<d;x=256*x+g[P+f],f+=l,d-=8);for(O=x&(1<<-d)-1,x>>=-d,d+=v;0<d;O=256*O+g[P+f],f+=l,d-=8);if(x===0)x=1-I;else{if(x===y)return O?NaN:1/0*(w?-1:1);O+=Math.pow(2,v),x-=I}return(w?-1:1)*O*Math.pow(2,x-v)},e.write=function(g,P,b,v,C,D){var O,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,l=v?0:D-1,w=v?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,O=I):(O=Math.floor(Math.log(P)/Math.LN2),P*(v=Math.pow(2,-O))<1&&(O--,v*=2),2<=(P+=1<=O+d?f/v:f*Math.pow(2,1-d))*v&&(O++,v/=2),I<=O+d?(A=0,O=I):1<=O+d?(A=(P*v-1)*Math.pow(2,C),O+=d):(A=P*Math.pow(2,d-1)*Math.pow(2,C),O=0));8<=C;g[b+l]=255&A,l+=w,A/=256,C-=8);for(O=O<<C|A,y+=C;0<y;g[b+l]=255&O,l+=w,O/=256,y-=8);g[b+l-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,o,s,c,p,h,S,E){var g,P,b;function v(){}(n=t.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(C){return window.setImmediate(C)}:b?(g=[],window.addEventListener("message",function(C){var x=C.source;x!==window&&x!==null||C.data!=="process-tick"||(C.stopPropagation(),0<g.length&&g.shift()())},!0),function(C){g.push(C),window.postMessage("process-tick","*")}):function(C){setTimeout(C,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=v,n.addListener=v,n.once=v,n.off=v,n.removeListener=v,n.removeAllListeners=v,n.emit=v,n.binding=function(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 ri={};yr(ri,{Client:()=>Fe,ClientDescriptor:()=>wn,Entity:()=>ye,EntityFile:()=>Be,MigrationPathError:()=>Ne,ServerSync:()=>$e,Storage:()=>Fe,StorageDescriptor:()=>wn,collection:()=>qi,createDefaultMigration:()=>Hn,createMigration:()=>Qn,migrate:()=>Bt,schema:()=>Wi});var Di=ft(mt(),1),yt=4,Je=36;function vi(i){return i.toString(Je).padStart(yt,"0")}function Ir(i){return i.toString().padStart(6,"0")}var gt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Dr()};this.zeroCounter=0;this.now=t=>(this.latest=xi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=xi(this.latest),Ir(t)+Er(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(yt);this.latest=Cr(this.latest,Oi(e))};this.get=(t,e)=>vi(t)+Si(e);this.zero=t=>vi(t)+Si({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>Oi(t.slice(yt)).time}},bt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},wt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},En=4,Pn=7,vt=60*1e3,Qe=9;function Dr(){return Di.default.slug().padStart(Pn,"0").slice(0,Pn)}function Si(i){let t=new Date(i.time).getTime().toString(Je).padStart(Qe,"0"),e=i.counter.toString(Je).padStart(En,"0"),n=i.node.padStart(Pn,"0");return`${t}${e}${n}`}function xi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>vt)throw new bt(e,t,vt);if(n>65535)throw new wt;return{time:e,counter:n,node:i.node}}function Cr(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),o;if(i.time===n&&t.time===n?o=r+1:i.time===n?o=i.counter+1:t.time===n?o=t.counter+1:o=0,n-e>vt)throw new bt(n,e,vt);if(o>65535)throw new wt;return{time:n,counter:o,node:i.node}}function Oi(i){let t=i.slice(0,Qe),e=i.slice(Qe,Qe+En),n=i.slice(Qe+En),r=parseInt(t,Je),o=parseInt(e,Je);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:n}}function Er(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 Ii(i){return parseInt(i.slice(0,yt),36)}function Ci(i,t){return Ii(i)-Ii(t)}function oe(i){return i&&i["@@type"]==="file"}function Ei(i){return{"@@type":"file",id:i}}var St,Pr=new Uint8Array(16);function _n(){if(!St&&(St=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!St))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return St(Pr)}var Pi=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function _r(i){return typeof i=="string"&&Pi.test(i)}var _i=_r;var Z=[];for(xt=0;xt<256;++xt)Z.push((xt+256).toString(16).substr(1));var xt;function Tr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(Z[i[t+0]]+Z[i[t+1]]+Z[i[t+2]]+Z[i[t+3]]+"-"+Z[i[t+4]]+Z[i[t+5]]+"-"+Z[i[t+6]]+Z[i[t+7]]+"-"+Z[i[t+8]]+Z[i[t+9]]+"-"+Z[i[t+10]]+Z[i[t+11]]+Z[i[t+12]]+Z[i[t+13]]+Z[i[t+14]]+Z[i[t+15]]).toLowerCase();if(!_i(e))throw TypeError("Stringified UUID is invalid");return e}var Ti=Tr;function Ar(i,t,e){i=i||{};var n=i.random||(i.rng||_n)();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 Ti(n)}var Ye=Ar;function te(i){return ne(i)||oe(i)}function Tn(i,t){return i===t?!0:!(!te(i)||!te(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Bi=ft(ki(),1);function Rr(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 Ge(i){return JSON.stringify(i,Rr)}function se(i,t=!0){if($(i)||Array.isArray(i)){let e=ce(i),n;if(Array.isArray(i))n=i.map(r=>se(r,t));else{n={};for(let[r,o]of Object.entries(i))n[r]=se(o,t)}return t&&e&&K(n,e),n}return i}function Ie(i){return(0,Bi.default)(i)}function $(i){return i&&typeof i=="object"}function Mi(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 o in r)e.push(r[o])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function Ot(i=16){return Ye().replace("-","").slice(0,i)}function Fi(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function ji(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var ve="__@@oid_do_not_use",Se="@@id",kr="/",Ct=":",Rn=new WeakMap;function le(i){let t=ce(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function ce(i){if($(i))return Rn.get(i)??i[Se]??i[ve]}function K(i,t){return V($(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Et(i),Rn.set(i,t),i}function Ze(i){return!!ce(i)}function Et(i){return Rn.delete(i),i}function kn(i){return i===Se||i===ve}function Bn(i,t,e){if(Ze(i))return le(i);{let n=ge(t,e);return K(i,n),n}}function Li(i,t,e){if(Ze(i)){let n=le(i);if(Pt(n,t))return le(i);{let r=ge(t,e);return K(i,r),r}}else{let n=ge(t,e);return K(i,n),n}}var An={".":"˙","/":"&slash;",":":":"};function Vi(i){return i.replace(/[/]/g,An["/"]).replace(/[:]/g,An[":"]).replace(/[.]/g,An["."])}function Ni(i){return i.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function X(i,t,e){let n=Vi(i)+kr+Vi(t);return e&&(n+=Ct+e),n}function ge(i,t=jr){let{collection:e,id:n}=ae(i);return X(e,n,t())}function ae(i){let[t,e]=i.split(Ct),[n,r,...o]=t.split("/");o.length&&(r+="/"+o.join("/"));let s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Ni(n),id:Ni(s),subId:e}}function Le(i,t){let e=le(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],$(n)&&!te(n)&&(Li(n,e,t),Le(n,t))}else if($(i)&&!te(i))for(let n of Object.keys(i))$(i[n])&&!te(i[n])&&(Li(i[n],e,t),Le(i[n],t))}function Br(i){if($(i))return i[Se]||i[ve]}function Mr(i){return $(i)&&(delete i[ve],delete i[Se]),i}function Fr(i){let t=Br(i);t&&K(i,t)}function Xe(i){if(Fr(i),Mr(i),Array.isArray(i))for(let t=0;t<i.length;t++)Xe(i[t]);else if($(i))for(let t of Object.keys(i))Xe(i[t])}function It(i){if(Et(i),Array.isArray(i))for(let t=0;t<i.length;t++)It(i[t]);else if($(i))for(let t of Object.keys(i))It(i[t])}function jr(){return Ye().slice(0,8)}function we(i){return{"@@type":"ref",id:i}}function Dt(i,t=new Map){if(Array.isArray(i)){let e=le(i),n=K([],e);for(let r=0;r<i.length;r++){let o=i[r];if($(o)){if(ne(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(oe(o)){n[r]=o;continue}else{let s=le(o);n[r]=we(s),Dt(o,t)}}else n[r]=o}t.set(e,n)}else if($(i)&&!te(i)){let e=le(i),n=K({},e);for(let r of Object.keys(i)){let o=i[r];if($(o)){if(ne(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(oe(o))n[r]=o;else{let s=le(o);n[r]=we(s),Dt(o,t)}}else n[r]=o}t.set(e,n)}else te(i);return t}function U(i){return i.split(".")[0].split(Ct)[0]}function Mn(i){let t=U(i),e=ge(t,()=>"\uFFFF");return[`${t}${Ct}`,e]}function Fn(i){let t=U(i);return[`${t}.`,`${t}.\uFFFF`]}function Pt(i,t){return U(i)===U(t)}function Lr(i){let{collection:t,id:e,subId:n}=ae(i);return X(t,e,n)}var Vr=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Nr(i){return i.replaceAll(Vr,t=>{let e=t.slice(1,t.length-1);return`"${Lr(e)}"`})}function jn(i){return JSON.parse(Nr(JSON.stringify(i)))}function ne(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Ln(i){return $(i)&&!te(i)}function Ur(i,t){return i===t?!0:te(i)&&te(t)?Tn(i,t):!1}function et(i,t,e,n,r=[],o={}){let s=le(i);function c(p,h,S){if(!Ln(h))Ur(h,S)||r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:h}});else{let E=ce(S),g=ce(h);g&&!Pt(s,g)?(h=se(h,!1),g=ge(s,n),K(h,g)):o.mergeUnknownObjects?!g&&E?(K(h,E),g=E):g=Bn(h,s,n):g=Bn(h,s,n),V(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Pt(s,g),`Error: value OID ${g} is not related to parent OID ${s}. This is a bug in Verdant.`),S===void 0||g!==E?(De(h,g,e,n,r),r.push({oid:s,timestamp:e(),data:{op:"set",name:p,value:we(g)}}),E!==void 0&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})):et(S,h,e,n,r,o)}}if(Array.isArray(i)&&Array.isArray(t)){for(let h=0;h<t.length;h++){let S=t[h],E=i[h];c(h,S,E)}let p=i.length-t.length;if(p>0){for(let h=t.length;h<i.length;h++){let S=i[h],E=ce(S);E&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})}r.push({oid:s,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(Ln(i)&&Ln(t)){let p=new Set(Object.keys(i));for(let[h,S]of Object.entries(t)){if(S===void 0&&o.defaultUndefined||(p.delete(h),kn(h)))continue;let E=i[h];c(h,S,E)}if(!o.defaultUndefined)for(let h of p)kn(h)||r.push({oid:s,timestamp:e(),data:{op:"remove",name:h}})}}return r}function De(i,t,e,n,r=[]){K(i,t),Le(i,n);let o=Dt(i);for(let s of o.keys()){let c=o.get(s);r.push({oid:s,timestamp:e(),data:{op:"initialize",value:Et(c)}})}return r}function Ki(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Vn(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 Nn(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 Ee(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: ${ce(i)})`),!1)}function Pe(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,o;function s(c){e&&te(c)&&e.push(c)}switch(t.op){case"set":s(n[t.name]),n[t.name]=t.value;break;case"remove":s(n[t.name]),delete n[t.name];break;case"list-push":Ee(i)&&i.push(t.value);break;case"list-delete":Ee(i)&&(s(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Ee(i)&&(o=i.splice(t.from,1),i.splice(t.to,0,o[0]));break;case"list-remove":if(Ee(i))do{let c=t.value;t.only==="last"?ne(c)?r=Fi(i,p=>p.id===c.id):r=i.lastIndexOf(c):ne(c)?r=i.findIndex(p=>p.id===c.id):r=i.indexOf(c),r!==-1&&(s(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Ee(i)&&(i.some(p=>ne(p)&&ne(t.value)?p.id===t.value.id:p===t.value)||i.push(t.value));break;case"list-move-by-ref":Ee(i)&&(r=i.indexOf(t.value),o=i.splice(r,1),i.splice(t.index,0,o[0]));break;case"list-insert":if(Ee(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(s):$(i)&&Object.values(i||{}).forEach(s);return;case"initialize":return se(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function _t(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Ui(r,t,e),$(i[n])&&_t(i[n],t,e)}else if(!oe(i)){if($(i)){V(ce(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Ui(i[n],t,e),$(i[n])&&_t(i[n],t,e)}}return e}function Ui(i,t,e){if(ne(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 Kr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Kn(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.type==="object"?!0:i.default!==void 0:!1}function Tt(i){return i.type==="map"||i.type==="object"||i.type==="array"||i.type==="file"||i.type==="any"?!1:i.indexed}function xe(i,t){for(let[e,n]of Object.entries(i.fields)){let r=$i(n);(r!==void 0&&t[e]===void 0||!Kr(n)&&t[e]===null)&&(t[e]=r),t[e]&&_e(t[e],n)}return t}function _e(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=$i(n);r!==void 0&&(i[e]=r)}_e(i[e],n)}else if(t.type==="array")for(let e of i)_e(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Se||e===ve||_e(n,t.values)}function $i(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 $n(i,t){for(let[e,n]of Object.entries(t))e===Se||e===ve||(i.fields[e]?Un(n,i.fields[e]):delete t[e]);return t}function Un(i,t){if($(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?Un(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)Un(e,t.items)}function zn(i){return i.equals!==void 0}function qn(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function $r(i){return!!i.match}function Wn(i){return i.startsWith!==void 0}function zi(i){return!qn(i)&&!zn(i)&&!$r(i)&&!Wn(i)&&i.order}function tt(i,t,e=[]){if(i.type==="object"){if(!$(t))return t===null&&i.nullable?void 0:`Expected object${i.nullable?" or null":""} for field ${Oe(e)}}`;for(let[n,r]of Object.entries(i.properties))t[n]&&tt(r,t[n]);for(let n of Object.keys(t))if(!i.properties[n])return`Invalid field "${n}" on value ${Oe(e)}`}else if(i.type==="array"){if(!Array.isArray(t))return t===null&&i.nullable?void 0:`Expected array${i.nullable?" or null":""} for field ${Oe(e)}}`;for(let n of t)tt(i.items,n)}else if(i.type==="map"){if(!$(t))return`Expected map for field ${Oe(e)}}`;for(let[n,r]of Object.entries(t))n===Se||n===ve||tt(i.values,r)}else if(i.type==="string"){if(typeof t!="string")return t===null&&i.nullable?void 0:`Expected string ${i.nullable?" or null":""} for field ${Oe(e)}}`;if(i.options&&!i.options.includes(t))return`Expected one of ${i.options.join(", ")} for field ${Oe(e)}`}else if(i.type==="boolean"){if(typeof t!="boolean")return t===null&&i.nullable?void 0:`Expected boolean ${i.nullable?" or null":""} for field ${Oe(e)}}`}else if(i.type==="number"){if(typeof t!="number")return t===null&&i.nullable?void 0:`Expected number ${i.nullable?" or null":""} for field ${Oe(e)}}`}else if(i.type==="file"&&t===null&&!i.nullable)return`Expected file for field ${Oe(e)}}`}function Oe(i){return i.join(".")}function qi({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,o]of Object.entries(e.fields))Tt(o)&&(n[r]={field:r});return{...e,indexes:n}}function Wi(i){return i}var At="\uFFFFFE",zr="\0",qr="\uFFFFFF";function de(...i){let t=Wr(i);return t.length===1?t[0]:t}function Te(...i){return i.join(At)+`${qr}`}function Ae(...i){return i.join(At)+`${At}${zr}`}function Wr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let o of e)n.push(r.concat(o));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(At))))}function Hr(i){return!!i.field}function Qr(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let o=r;Hr(o)?e[n]=me(t[o.field]):e[n]=me(o.compute(t))}return e}function Jr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=de(...r.of.map(o=>t[o])),e),{})}function Yr(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>(Tt(r)&&(e[n]=me(t[n])),e),{})}function Rt(i,t){let e={[i.primaryKey]:t[i.primaryKey],...Yr(i,t),...Qr(i,t)};return Object.assign(e,Jr(i,{...t,...e})),e["@@@snapshot"]=t,e}var Gr="null";function me(i){if(i===null)return Gr;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 Hi={version:0,collections:{}};function Bt(i,t,e){let n=typeof t=="function",r=n?Hi:i,o=n?i:t,s=n?t:e,c=Object.keys(o.collections).filter(v=>r.collections[v]&&Ge(r.collections[v])!==Ge(o.collections[v])),p=Object.keys(r.collections).filter(v=>!o.collections[v]),h=Object.keys(o.collections).filter(v=>!r.collections[v]),S=new Set;for(let v of c){let C=r.collections[v].fields,x=o.collections[v].fields;Object.keys(x).some(O=>!C[O]?.default&&x[O]?.default)&&S.add(v),Object.keys(C).some(O=>!x[O])&&S.add(v)}let E={},g={};for(let v of[...c,...h]){let C=kt(r.collections[v]),x=kt(o.collections[v]),O=x.filter(y=>!C.find(I=>I.name===y.name)),A=C.filter(y=>!x.find(I=>I.name===y.name));O.length>0&&(E[v]=O,c.includes(v)&&S.add(v)),A.length>0&&(g[v]=A,c.includes(v)&&S.add(v))}let P=(v,C)=>xe(o.collections[v],C),b=v=>C=>{let x=o.collections[v];return xe(x,$n(x,C))};return{version:o.version,migrate:async v=>{let C=[];if(await s({migrate:async(x,O)=>{let A=b(x),y=async I=>{let d=await O(I);return K(d,le(I)),A(d)};await v.migrate(x,y),C.push(x),S.delete(x)},identity:x=>x,withDefaults:P,info:{changedCollections:c,addedCollections:h,removedCollections:p},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",S);for(let O of S)await v.migrate(O,b(O)),C.push(O);let x=c.filter(O=>!C.includes(O));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:p,addedIndexes:E,removedIndexes:g,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function kt(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 Hn(i,t){return Bt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let o of r.changedCollections)await n(o,s=>s)})}function Qn(i,t,e){let n=typeof t=="function"||t===void 0,r=n?Hi:i,o=n?i:t,s=n?t:e;V(r,"Invalid arguments to createMigration"),V(o,"Invalid arguments to createMigration");let{changedCollections:c,addedCollections:p,removedCollections:h,addedIndexes:S,removedIndexes:E,autoMigratedCollections:g,autoMigration:P}=Xr(r,o);return{version:o.version,migrate:async b=>{let v=[];if(await s?.({migrate:async(x,O)=>{let A=P(x),y=async I=>{let d=await O(I);return K(d,le(I)),A(d)};await b.migrate(x,y),v.push(x),g.delete(x)},info:{changedCollections:c,addedCollections:p,removedCollections:h},queries:b.queries,mutations:b.mutations}),o.version>1){b.log("debug","auto-migrating collections with new defaults",g);for(let O of g)await b.migrate(O,P(O)),v.push(O);for(let O of h)await b.deleteCollection(O);let x=c.filter(O=>!v.includes(O));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,x)}},removedCollections:h,addedIndexes:S,removedIndexes:E,allCollections:Object.keys(o.collections),changedCollections:c,addedCollections:p,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Xr(i,t){let e=Object.keys(t.collections).filter(S=>i.collections[S]&&Ge(i.collections[S])!==Ge(t.collections[S])),n=Object.keys(i.collections).filter(S=>!t.collections[S]),r=Object.keys(t.collections).filter(S=>!i.collections[S]),o=new Set;for(let S of e){let E=i.collections[S].fields,g=t.collections[S].fields;Object.keys(g).some(P=>!Kn(E[P])&&Kn(g[P]))&&o.add(S),Object.keys(E).some(P=>!g[P])&&o.add(S)}let s={},c={};for(let S of[...e,...r]){let E=kt(i.collections[S]),g=kt(t.collections[S]),P=g.filter(v=>!E.find(C=>C.name===v.name)),b=E.filter(v=>!g.find(C=>C.name===v.name));P.length>0&&(s[S]=P,e.includes(S)&&o.add(S)),b.length>0&&(c[S]=b,e.includes(S)&&o.add(S))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:s,removedIndexes:c,autoMigratedCollections:o,withDefaults:(S,E)=>xe(t.collections[S],E),autoMigration:S=>E=>{let g=t.collections[S];return xe(g,$n(g,E))}}}var Mt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.isPrimitive=t=>!$(t)||te(t);this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>De(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...De(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(this.isPrimitive(e))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}];{let n=ge(t,this.createSubId);return[...De(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:we(n)}}]}};this.createListAdd=(t,e)=>this.isPrimitive(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:we(e)}}];this.createListInsert=(t,e,n)=>{if(this.isPrimitive(n))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}];{let r=ge(t,this.createSubId);return[...De(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:we(r),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=Ot(),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=se(t),o=[];for(let s of e){let c=Zr(i,r,s,n);o.unshift(...c),Pe(r,s.data)}return o}function Zr(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 o=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=t.indexOf(r.value);for(;s!==-1;)o.push(s),s=t.indexOf(r.value,s+1);return o.map(c=>({oid:i,timestamp:n(),data:{op:"list-insert",index:c,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 Ve=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:o}){let s=this.batches.get(t);return s||(s=new Jn({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:t}),this.batches.set(t,s)),s.update({items:n,max:r,timeout:o,userData:e}),s}},Jn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:o,key:s}){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 o=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():o&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=o,this.key=s}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function nt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),s=r.objectStore(t).openCursor(),c=0,p=0;s.onsuccess=function(h){let S=s.result;S&&(c++,p=p+Mi(S.value),S.continue())},s.onerror=function(h){n(h)},r.oncomplete=function(h){e({count:c,size:p})},r.onabort=function(h){n(h)},r.onerror=function(h){n(h)}})}function Ji(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let o=e.objectStore(r);return W(o.getAll())});return Promise.all(n)}async function Re(i){i.close(),await new Promise((t,e)=>{t()})}async function Ft(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{n.onsuccess=r,n.onerror=o})]),window.location.reload()}function Yi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function Gi(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 s=(r||this.db.transaction(t,n)).objectStore(t),c=e(s);return W(c)};this.runAll=async(t,e,n="readonly",r)=>{let s=(r||this.db.transaction(t,n)).objectStore(t),c=e(s);return Promise.all(c.map(W))};this.iterate=async(t,e,n,r="readonly",o)=>{let c=(o||this.db.transaction(t,r)).objectStore(t),p=e(c);return Array.isArray(p)?Promise.all(p.map(h=>new Promise((S,E)=>{h.onsuccess=()=>{let g=h.result;g?(n(g.value,c),g.continue()):S()},h.onerror=E}))).then(()=>{}):new Promise((h,S)=>{p.onsuccess=()=>{let E=p.result;E?(n(E.value,c),E.continue()):h()},p.onerror=S})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var jt=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 Lt=class extends fe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:n,transaction:r}),o};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let c=U(e),[p,h]=Mn(e),[S,E]=Fn(e);return[s.openCursor(IDBKeyRange.only(c)),s.openCursor(IDBKeyRange.bound(p,h,!1,!1)),s.openCursor(IDBKeyRange.bound(S,E,!1,!1))]},n,r,o);this.iterateOverAllForCollection=async(e,n,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],n,r,o);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let c=U(s),[p,h]=Mn(s),[S,E]=Fn(s);return[o.get(c),o.getAll(IDBKeyRange.bound(p,h,!1,!1)),o.getAll(IDBKeyRange.bound(S,E,!1,!1))]}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",o=>o.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(o=>r.put(o)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Xi=ft(mt(),1);var Vt=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);return n?(this.cached=n,n):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,Xi.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),"readwrite"),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",o=>o.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 Nt=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=[],o=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add(U(c.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(c=>{r.push({data:c.data,oid:c.oid,timestamp:c.timestamp}),o.add(U(c.oid))},{mode:"readwrite"});let s=[];return n||(s=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:s,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var Ut=class extends fe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:o,after:s,mode:c="readonly",transaction:p}={})=>{let S=(p||this.db.transaction("operations",c)).objectStore("operations"),E=S.index("d_t"),g=o||s,P=g?de(e,g):Ae(e),b=r?de(e,r):Te(e),v=IDBKeyRange.bound(P,b,!!s,!1),C=E.openCursor(v,"next");return new Promise((x,O)=>{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,S),A=d.timestamp,I.continue()}else x()},C.onerror=y=>{O(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let h=(c||this.db.transaction("operations",s)).objectStore("operations"),S=r?de(e,r):Ae(e),E=o?de(e,o):Te(e),g=IDBKeyRange.bound(S,E,!!r,!1),P=h.openCursor(g,"next");return new Promise((b,v)=>{let C;P.onsuccess=x=>{let O=P.result;if(O){let A=O.value;V(A.oid.startsWith(e)),V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,h),C=A.timestamp,O.continue()}else b()},P.onerror=x=>{v(x)}})};this.iterateOverAllOperationsForCollection=async(e,n,{after:r,to:o,mode:s,transaction:c})=>{let p=c||this.db.transaction("operations",s);return this.iterate("operations",h=>h.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),n,s,p)};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:o="readonly",transaction:s})=>{let p=(s||this.db.transaction("operations",o)).objectStore("operations"),h=p.index("l_t"),S=r?de(!0,r):Ae(!0),E=n?de(!0,n):Te(!0),g=IDBKeyRange.bound(S,E,!!r,!0),P=h.openCursor(g,"next");return new Promise((b,v)=>{let C;P.onsuccess=x=>{let O=P.result;if(O){let A=O.value;V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),e(A,p),C=A.timestamp,O.continue()}else b()},P.onerror=x=>{v(x)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:o,from:s})=>{await this.iterate("operations",c=>{let p=s?Ae(s):void 0,h=n?Te(n):void 0,S=p&&h?IDBKeyRange.bound(p,h,!1,!0):p?IDBKeyRange.lowerBound(p,!1):h?IDBKeyRange.upperBound(h,!0):void 0;return c.index("timestamp").openCursor(S,"next")},e,o,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",o=>e.map(s=>(r.add(U(s.oid)),o.put(s))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Kt=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"),o=await W(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async t=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(o)}}};var it=class extends N{constructor({disableRebasing:e,context:n}){super();this.time=new gt;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 o=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{n.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{n.add(s.oid)},{transaction:o})]),Array.from(n)};this.getAllCollectionRelatedOids=async e=>{let n=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{n.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{n.add(o.oid)},{transaction:r})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=U(e);V(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),c=new Map;for(let h of s)h.snapshot&&K(h.snapshot,h.oid),c.set(h.oid,h.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,h=>{let S=c.get(h.oid)||void 0,E=Pe(S,h.data);E&&K(E,h.oid),c.set(h.oid,E)},{transaction:o,to:n.to||this.now});let p=c.get(r);return p&&_t(p,c),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,o=this.db.transaction(["baselines","operations"],"readwrite"),s=0;if(await this.operations.iterateOverAllOperations(p=>{r.add(p.oid),n=p.timestamp,s++},{before:e,transaction:o}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let c=[];for(let p of r)c.push(await this.rebase(p,n||e,o));this.emit("rebase",c)};this.rebase=async(e,n,r)=>{let o=(await this.localReplica.get()).id;this.log("[",o,"]","Rebasing",e,"up to",n);let s=r||this.db.transaction(["operations","baselines"],"readwrite"),c=await this.baselines.get(e,{transaction:s}),p=c?.snapshot||void 0,h=0,S=[];await this.operations.iterateOverAllOperationsForEntity(e,(g,P)=>{(!c||g.timestamp>c.timestamp)&&(p=Pe(p,g.data,S)),h++,P.delete(g.oid_timestamp)},{to:n,transaction:s}),p&&K(p,e);let E={oid:e,snapshot:p,timestamp:n};if(E.snapshot?await this.baselines.set(E,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("successfully rebased",e,"up to",n,":",p,"and deleted",h,"operations"),S.length){let g=S.filter(oe);g.length&&this.emit("filesDeleted",g)}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
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 Ji(e,["baselines","operations"]),o=await this.localReplica.get(),s=await this.schema.get();if(!s)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:o,schema:s}};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 nt(e,"operations"),r=await nt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Kt(n.metaDb,n.schema.version),this.operations=new Ut(this.db),this.baselines=new Lt(this.db),this.localReplica=new Vt(this.db),this.ackInfo=new jt(this.db),this.messageCreator=new Nt(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 eo=[to,no,io,ro,oo];function $t({indexedDB:i=window.indexedDB,namespace:t,log:e,metadataVersion:n=5}){return new Promise((r,o)=>{let s=i.open(`${t}_meta`,n),c=!1;s.onupgradeneeded=async p=>{let h=s.result,S=s.transaction,E=eo.slice(p.oldVersion);for(let g of E)await g(h,S);await new Promise((g,P)=>{S.addEventListener("complete",g),S.addEventListener("error",P)}),p.oldVersion||(c=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:c})}})}async function Zi({wipNamespace:i,namespace:t,indexedDB:e,log:n,metadataVersion:r}){let o=await $t({namespace:i,indexedDB:e,log:n,metadataVersion:r});if(!o.wasInitialized)return o;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await $t({namespace:t,indexedDB:e,log:n,metadataVersion:r}),c=s.transaction(["baselines","operations","info"],"readonly"),[p,h,S]=await Promise.all([W(c.objectStore("baselines").getAll()),W(c.objectStore("operations").getAll()),W(c.objectStore("info").getAll())]),E=o.db.transaction(["baselines","operations","info"],"readwrite"),g=E.objectStore("baselines"),P=E.objectStore("operations"),b=E.objectStore("info");for(let v of p)g.put(v);for(let v of h)P.put(v);for(let v of S)b.put(v);return await new Promise((v,C)=>{E.oncomplete=()=>{v()},E.onerror=x=>{C(x)},E.onabort=x=>{C(x)}}),await Re(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",p.length,"baselines,",h.length,"operations"),o}async function to(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 no(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:c,documentOid_timestamp:p,...h}=s.value;s.update({...h,l_t:c,d_t:p}),s.continue()}else n()},o.onerror=s=>{r(o.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function io(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function ro(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function oo(i,t){let e=t.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=jn(c.value);p.oid_timestamp!==c.primaryKey?(c.delete(),e.put(p)):c.update(p),c.continue()}else r()},s.onerror=c=>{o(s.error)}});let n=t.objectStore("baselines");await new Promise((r,o)=>{let s=n.openCursor();s.onsuccess=()=>{let c=s.result;if(c){let p=jn(c.value);p.oid!==c.primaryKey?(c.delete(),n.put(p)):c.update(p),c.continue()}else r()},s.onerror=c=>{o(s.error)}})}var so=i=>IDBKeyRange.only(me(i.equals)),ao=i=>{},co=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)},lo=(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 o=r.map(p=>e.match[p]);if(r.length===n.of.length)return IDBKeyRange.only(de(...o));let s=Ae(...o),c=Te(...o);return IDBKeyRange.bound(s,c)};function uo(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function zt(i,t,e){if(e)return qn(e)?co(e):zn(e)?so(e):zi(e)?ao(e):Wn(e)?uo(e):lo(i,t,e)}function Yn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function qt({collection:i,index:t,context:e}){let n=Yn(e.documentDb,i),r=t?n.index(t.where):n,o=zt(e.schema,i,t),s=t?.order==="desc"?"prev":"next",c=r.openCursor(o,s);return await new Promise((h,S)=>{c.onsuccess=()=>{let E=c.result;h(E?X(i,E.primaryKey.toString()):null)},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",c.error),h(null)):S(c.error)}})}async function Wt({collection:i,index:t,context:e}){let n=Yn(e.documentDb,i),r=t?n.index(t.where):n,o=zt(e.schema,i,t),s=t?.order==="desc"?"prev":"next",c=r.openCursor(o,s);return await new Promise((h,S)=>{let E=new Set;c.onsuccess=()=>{let g=c.result;g?(E.add(X(i,g.primaryKey.toString())),g.continue()):h(Array.from(E))},c.onerror=()=>{c.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",c.error),h([])):S(c.error)}})}async function rt({collection:i,index:t,context:e,limit:n,offset:r}){let o=Yn(e.documentDb,i),s=t?o.index(t.where):o,c=zt(e.schema,i,t),p=t?.order==="desc"?"prev":"next",h=s.openCursor(c,p),S=!r,E=!1,g=0;return{result:await new Promise((b,v)=>{let C=new Set;h.onsuccess=()=>{g++;let x=h.result;x?r&&!S?(x.advance(r),S=!0):(n&&C.size<n&&C.add(X(i,x.primaryKey.toString())),n&&g>n?(E=!0,b(Array.from(C))):x.continue()):b(Array.from(C))},h.onerror=()=>{h.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",h.error),b([])):v(h.error)}}),hasNextPage:E}}async function Gn(i,t,e,n){function r(c,p){let h,S,E=i.open([t,"collections"].join("_"),e);E.onupgradeneeded=async g=>{h=g.oldVersion;let P=E.transaction;S=E.result,P.abort()},E.onsuccess=g=>{c([E.result.version,E.result])},E.onblocked=g=>{n?.("Database blocked, waiting...")},E.onerror=g=>{c([h,S])}}let[o,s]=await new Promise(r);return await Ht(s),o}async function Ht(i){i.close(),await new Promise(t=>t())}async function er(i,t,e,n,r){function o(s,c){let p=i.open([t,"collections"].join("_"),e),h=!1;p.onupgradeneeded=S=>{let E=p.transaction;n(E,p.result,S),h=!0},p.onsuccess=S=>{p.result.close(),h?s():c(new Error("Database was not upgraded when a version change was expected"))},p.onerror=S=>{c(p.error||new Error("Unknown error"))},p.onblocked=S=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function tr(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((o,s)=>{let c=i.open([t,"collections"].join("_"),e);c.onupgradeneeded=async p=>{c.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",c.result.version),s(c.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${c.result.version}`))},c.onsuccess=p=>{o(c.result)},c.onblocked=p=>{s(new Error("Migration error: database blocked"))},c.onerror=p=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}var Ne=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function Qt({currentVersion:i,targetVersion:t,migrations:e}){let n=nr({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ne(`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 nr({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,o)=>o.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 o=nr({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(o)return[r,...o]}return null}var Zn=typeof window<"u"?window.indexedDB:void 0;async function ot({version:i,indexedDB:t=Zn,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await Gn(t,r.namespace,i,r.log);r.log("debug","Current database version:",o,"target version:",i);let s=Qt({currentVersion:o,targetVersion:i,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(c=>c.version)),await Xn({context:r,toRun:s,meta:n,indexedDB:t})),ke(t,r.namespace,i,r.log)}async function ir({version:i,indexedDB:t=Zn,migrations:e,meta:n,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await Gn(t,o,i,r.log);if(s===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 c=Qt({currentVersion:s,targetVersion:i-1,migrations:e});if(c.length>0){await Xn({context:r,toRun:c,meta:n,indexedDB:t,namespace:o});let h=await ke(t,r.namespace,i-1,r.log),S=await ke(t,o,i-1,r.log),E=new Array;for(let x=0;x<h.objectStoreNames.length;x++)E.push(h.objectStoreNames[x]);let g=h.transaction(E,"readonly"),P=E.map(x=>g.objectStore(x)),b=await Promise.all(P.map(x=>W(x.getAll()))),v=S.transaction(E,"readwrite"),C=E.map(x=>v.objectStore(x));for(let x=0;x<C.length;x++)await Promise.all(b[x].map(O=>W(C[x].put(O))))}let p=Qt({currentVersion:i-1,targetVersion:i,migrations:e});p.length>0&&await Xn({context:r,toRun:p,meta:n,indexedDB:t,namespace:o})}return ke(t,o,i,r.log)}async function Xn({context:i,toRun:t,meta:e,indexedDB:n=Zn,namespace:r=i.namespace}){await tr(r,async()=>{for(let o of t){let s;if(o.oldSchema.version===0)s=ho({meta:e,migration:o,context:i}),await o.migrate(s);else{let h=await ke(n,r,o.oldSchema.version,i.log);s=po({meta:e,migration:o,context:{...i,documentDb:h}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(S){throw i.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,S),S}await Ht(h)}i.log("debug","Upgrading database",r,"to version",o.newSchema.version),await er(n,r,o.newSchema.version,(h,S)=>{for(let E of o.addedCollections)S.createObjectStore(E,{keyPath:o.newSchema.collections[E].primaryKey,autoIncrement:!1});for(let E of o.allCollections){let g=h.objectStore(E);for(let P of o.addedIndexes[E]||[])g.createIndex(P.name,P.name,{multiEntry:P.multiEntry});for(let P of o.removedIndexes[E]||[])g.deleteIndex(P.name)}for(let E of o.removedCollections)h.objectStore(E).clear()},i.log);let c=await bo({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version}),p=await ke(n,r,o.newSchema.version,i.log);for(let h of o.allCollections){let E=p.transaction(h,"readwrite").objectStore(h),P=(await mo(E)).map(O=>X(h,`${O}`));P.push(...s.newOids.filter(O=>ae(O).collection===h),...c.filter(O=>ae(O).collection===h));let v=(await Promise.all(P.map(async O=>{try{let A=await e.getDocumentSnapshot(O);return[O,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",O,"this document will not be preserved",A),null}}))).filter(O=>!!O).map(([O,A])=>{if(!A)return[O,void 0];let y=Rt(o.newSchema.collections[h],A);return[O,y]}),x=p.transaction(h,"readwrite").objectStore(h);await Promise.all(v.map(([O,A])=>{if(A)return go(x,A).catch(y=>{throw y});{let{id:y}=ae(O);return yo(x,y)}}))}await Ht(p),i.log("debug",`Migration of ${r} complete.`),i.log(`
|
|
9
9
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
@@ -12,6 +12,6 @@ list should be an Array.`),a.length===0)return new b(0);if(a.length===1)return a
|
|
|
12
12
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
13
|
- New indexes: ${Object.keys(o.addedIndexes).map(h=>o.addedIndexes[h].map(S=>`${h}.${S.name}`)).flatMap(h=>h).join(", ")}
|
|
14
14
|
- Removed indexes: ${Object.keys(o.removedIndexes).map(h=>o.removedIndexes[h].map(S=>`${h}.${S.name}`)).flatMap(h=>h).join(", ")}
|
|
15
|
-
`)}})}function rr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,o)=>(r[o]={put:async s=>{xe(i.newSchema.collections[o],s);let c=s[i.newSchema.collections[o].primaryKey],p=X(o,c);return n.push(p),await t.insertLocalOperation(De(s,p,e)),s},delete:async s=>{let c=X(o,s),p=await t.getAllDocumentRelatedOids(c);return t.insertLocalOperation(p.map(h=>({oid:h,timestamp:e(),data:{op:"delete"}})))}},r),{})}function fo({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async o=>{let s=X(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)})},findOne:async o=>{let s=await qt({collection:r,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)}):null},findAll:async o=>{let s=await Wt({collection:r,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function po({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=fo({migration:t,context:e,meta:i}),s=rr({migration:t,getMigrationNow:n,newOids:r,meta:i}),c=async S=>{let E=await i.getAllCollectionRelatedOids(S);return i.insertLocalOperation(E.map(g=>({oid:g,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:r,deleteCollection:c,migrate:async(S,E)=>{let g=await o[S].findAll();await Promise.all(g.filter(Boolean).map(async P=>{V(Ze(P),`Document is missing an OID: ${JSON.stringify(P)}`);let b=se(P),v=await E(P);if(v){Xe(b),Xe(v),Le(v);let C=et(b,v,n,void 0,[],{mergeUnknownObjects:!0});C.length>0&&await i.insertLocalOperation(C)}}))},queries:o,mutations:s,awaitables:p}}function ho({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=rr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function mo(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function yo(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function go(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function bo({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 Jt=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)})`),X(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return xe(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),o=this.getOid(t,r);return this.entities.create(r,o,n)};this.delete=async(t,e,n={})=>{let r=X(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>X(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>X(t,r)),n)}};var Ue=Symbol("entity-file-update"),at=Symbol("entity-file-mark-failed"),wo,vo,Be=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[wo]=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[vo]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{wo=Ue,vo=at}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 or=ft(mt(),1);function So(i){return{id:(0,or.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=So(i);return t(e),Ei(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 sr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Yt=class extends fe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let o=e.file?await sr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?xo(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",o=>o.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",o=>o.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",o=>o.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,o)=>{e(this.hydrateFileData(r),o)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function xo(i,t){return new Blob([i],{type:t})}function Oo(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Gt=class{constructor({db:t,sync:e,context:n,meta:r,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ue](e);else{let n=new Be(e.id);n[Ue](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 Be(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[at]();return}let n=await this.storage.getFile(t.id);if(n)t[Ue](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ue](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[at](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[at](),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 Yt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:Oo,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var ar="@@refresh",Xt="@@deepChange";function ct(i,t){return i[ar](t)}var Io,Do,ye=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:o,onAllUnsubscribed:s,readonlyKeys:c=[],fieldPath:p=[]}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[Io]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let o=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[Xt](this,t)),o&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Do]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Xt](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 se(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity({oid:t,fieldSchema:n,parent:this,fieldKey:e})};this.wrapValue=(t,e)=>{if(ne(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(oe(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Xt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=se(t,!1));let n=this.getChildFieldSchema(e);n&&_e(t,n);let r=tt(n,t,[...this.fieldPath,e]);if(r)throw new Error(r);return 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)=>ne(e)?this.getSubObject(e.id,n)?.getSnapshot():oe(e)?this.getFileSnapshot(e):e);else{t={...this.value};for(let[e,n]of Object.entries(t))ne(n)?t[e]=this.getSubObject(n.id,e)?.getSnapshot():oe(n)&&(t[e]=this.getFileSnapshot(n))}return $(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[o,s]of Object.entries(t)){if(this.readonlyKeys.includes(o))throw new Error(`Cannot set readonly key ${o.toString()}`);let c=this.getChildFieldSchema(o);c&&_e(s,c)}let r=Me(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),$(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=ce(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(ne(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=>ne(e)?e.id===ce(t):(oe(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:h}=ae(t);this.collection=h,this.store=e,this.fieldSchema=n,this.fieldPath=p,this.readonlyKeys=c,this.cache=r,this.parent=o&&this.cache.weakRef(o);let{view:S,deleted:E,lastTimestamp:g}=this.cache.computeView(t);if(this._current=S,this._deleted=E,this._updatedAt=g||null,this.cachedDeepUpdatedAt=null,this.events=new N(()=>{this.hasSubscribers||s?.()}),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}[(Io=ar,Do=Xt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Zt=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 en=class extends N{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Zt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:o}=r;n.add(o);let s=this.localOperationsMap.get(o)||[];s.push(r),this.localOperationsMap.set(o,s)}for(let r of n){let s=this.entities.get(r)?.deref();s&&(ct(s,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:o}=r;n.affectedOids?.add(o);let s=this.operationsMap.get(o)||[],c=s.findIndex(h=>h.timestamp>=r.timestamp);if(c!==-1){if(s[c].timestamp===r.timestamp)continue;s.splice(c,0,r)}else s.push(r);this.operationsMap.set(o,s);let p=this.localOperationsMap.get(o);p&&this.localOperationsMap.set(o,p.filter(h=>h.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:o}=r,s=this.baselinesMap.get(o);if(s?.timestamp&&s.timestamp>=r.timestamp)continue;n?.add(o),this.baselinesMap.set(o,r);let c=this.operationsMap.get(o)||[];for(;c[0]?.timestamp<r.timestamp;)c.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:o})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let s={isLocal:o||!1,affectedOids:new Set};if(this.insertBaselines(n,s),this.insertOperations(e,s),r)for(let c of this.entities.values()){let p=c.deref();p&&ct(p,s)}else for(let c of s.affectedOids){let h=this.entities.get(c)?.deref();h&&(ct(h,s),this.emit(`change:${c}`),this.emit("change:*",c))}};this.applyOperations=(e,n,r,o)=>{let s,c=this.storeTools.now;for(let p of r)if(!(o&&p.timestamp<=o)){if(Ci(p.timestamp,c)>0){s=p.timestamp;continue}p.data.op==="delete"?n=!0:(e=Pe(e,p.data),p.data.op==="initialize"&&(n=!1))}return s&&this.context.globalEvents.emit("futureSeen",s),{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:o,deleted:s}=this.applyOperations(n.view,n.deleted,r);return o&&$(o,e),{view:o,deleted:s,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],o=se(n?.snapshot||void 0),s=this.applyOperations(o,!o,r,n?.timestamp);return s.view&&$(s.view,e),s.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),s};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=({oid:e,fieldSchema:n,parent:r,readonlyKeys:o,fieldKey:s})=>{let p=this.entities.get(e)?.deref();return p||(p=new ye({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r,readonlyKeys:o,fieldPath:s?[...r?.fieldPath??[],s]:void 0}),this.entities.set(e,this.context.weakRef(p))),p};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:o,dropAll:s})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let c={isLocal:!1,affectedOids:new Set};s&&this.baselinesMap.clear(),this.insertBaselines(n,c),s&&this.operationsMap.clear(),this.insertOperations(e,c),(o||r)&&(this.localOperationsMap.clear(),o&&this.insertLocalOperations(o));for(let p of this.entities.keys()){let S=this.entities.get(p)?.deref();S&&(ct(S,c),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 tn="@@default",nn=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=tn;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=ae(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"]),o=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,c=>{o.push(c)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,c=>{c.confirmed=!0,s.push(c)},{transaction:r,mode:"readwrite"})]),t.reset({operations:s,baselines:o,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 en({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}=ae(e),o=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let s=o?.getSnapshot();if(s){let c=Rt(this.schema.collections[r],s);try{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.put(c)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",c)}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(c))}}else try{let p=this.db.transaction(r,"readwrite").objectStore(r);await W(p.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}catch(c){if(c instanceof Error)if(c instanceof DOMException&&c.message?.includes("not found"))this.log("debug","document not found in storage",t);else throw c}};this.get=async t=>{let e=await this.openFamilyCache(t),{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity({oid:t,fieldSchema:n,readonlyKeys: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({oid:t,fieldSchema:n,readonlyKeys:r}):null}return null};this.create=async(t,e,n)=>{It(t);let r=Me(t,this.files.add);$(r,e);let o=this.meta.patchCreator.createInitialize(r,e),s=await this.openFamilyCache(e);s.insertLocalOperations(o),await this.submitOperations(o,n);let{schema:c,readonlyKeys:p}=this.getDocumentSchema(e);if(!c)throw new Error(`Cannot create a document in the ${ae(e).collection} collection; it is not defined in the current schema version.`);return s.getEntity({oid:e,fieldSchema:c,readonlyKeys:p})};this.addOperationsToOpenCaches=async(t,e)=>{let n=Vn(t);Object.keys(n).forEach(o=>{let s=this.documentFamilyCaches.get(o);s&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",o,n[o].length),e.isLocal?s.insertLocalOperations(n[o]):s.insertOperations(n[o],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Nn(t);Object.keys(n).forEach(o=>{let s=this.documentFamilyCaches.get(o);s&&(this.log("adding","baselines to cache",o,n[o].length),s.insertBaselines(n[o],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let o=Nn(t),s=Vn(e),c=Array.from(new Set(Object.keys(o).concat(Object.keys(s))));for(let p of c){let h=this.documentFamilyCaches.get(p);h?(h.addData({operations:s[p]||[],baselines:o[p]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",p,s[p]?.length??0,"operations",o[p]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",p,"because it is not open")}return c};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 c of r)c.confirmed=!1;let o=[];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(),o=Array.from(new Set(e.map(c=>K(c.oid)).concat(t.map(c=>K(c.oid)))))):o=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 c of o)await this.writeDocumentToStorage(c);let s=Array.from(new Set(o.map(c=>ae(c).collection)));this.context.log("changes to collections",s),this.context.entityEvents.emit("collectionsChanged",s)};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=Ot(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),s={run:c=>(this.currentBatchKey=e,c(),this.currentBatchKey=tn,s),flush:async()=>(await this.operationBatcher.flush(tn),o.flush()),discard:()=>{this.operationBatcher.discard(e)}};return s};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(o=>K(o.oid))));for(let o of n)await this.writeDocumentToStorage(o);let r=new Set(t.map(({oid:o})=>ae(o).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Ki(t),n=[],r=()=>this.meta.now;for(let[o,s]of Object.entries(e)){let c=await this.openFamilyCache(o),{view:p,deleted:h}=c.computeConfirmedView(o),S=Qi(o,p,s,r);n.unshift(...S)}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(o=>this.meta.getAllDocumentRelatedOids(o))),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 Ve(this.flushOperations),this.operationBatcher.add({key:tn,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 ei=Symbol("handleMessage"),Co,lt=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[Co]=async(e,n)=>{let r=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,c]of Object.entries(n.peerPresence))this.isSelf(e,c)?(this._self=c,this._selfReplicaIds.add(c.replicaId),this.emit("selfChanged",c)):(r=!0,o.add(s),this._peers[s]=c,this.emit("peerChanged",s,c))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Ve(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{Co=ei}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 rn=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(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let 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 Ke=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)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var on=class extends N{constructor({endpointProvider:e,meta:n,presence:r,interval:o=15*1e3,log:s=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let c of s.messages)this.handleServerMessage(c);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),o.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.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=s,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new Ke({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function ti(i){this.message=i}ti.prototype=new Error,ti.prototype.name="InvalidCharacterError";var cr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new ti("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,o=0,s="";n=t.charAt(o++);~n&&(e=r%4?64*e+n:n,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function Eo(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(cr(e).replace(/(.)/g,function(n,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return cr(t)}}function sn(i){this.message=i}function Po(i,t){if(typeof i!="string")throw new sn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(Eo(i.split(".")[e]))}catch(n){throw new sn("Invalid token specified: "+n.message)}}sn.prototype=new Error,sn.prototype.name="InvalidTokenError";var lr=Po;var an=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(c=>{if(c.ok)return c.json();throw new Error(`Auth endpoint returned non-200 response: ${c.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=lr(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 o=n.toString(),s=e.file;if(!s){let c=new URL(r);c.pathname=c.pathname+"/files",s=c.toString()}return this.cached={http:r,websocket:o,files:s,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var cn=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}},ln=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 dn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,log:o}){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 Ke;this.reconnectScheduler=new cn(new ln(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=o||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 un=class extends N{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new lt({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},$e=class extends N{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:o=!0,autoStart:s,initialTransport:c,pullInterval:p,presenceUpdateBatchTimeout:h,defaultProfile:S,useBroadcastChannel:E},{meta:g,log:P,onData:b}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[ei](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=g,this.onData=b,this.log=P||(()=>{}),this.presence=new lt({initialPresence:r,defaultProfile:S,updateBatchTimeout:h}),this.endpointProvider=new an({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new dn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log}),this.pushPullSync=new on({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log,interval:p}),this.fileSync=new rn({endpointProvider:this.endpointProvider,log:this.log}),E&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),c==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let v=()=>{C&&clearTimeout(C);let O=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;O&&this.mode==="pull"?this.setMode("realtime"):!O&&this.mode==="realtime"&&(C=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},C;this.presence.subscribe("peersChanged",v),o!=="peers-only"&&this.presence.subscribe("selfChanged",v)}s&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}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 To(i){return i!==null}function ni(i){return Array.isArray(i)?i.map(ni).filter(To):i instanceof ye&&i.deleted?null:i}function Ce(i,t){return!i&&!t||i&&t&&Ie(i)===Ie(t)}var ii=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Ao,pe=class extends ze{constructor({initial:e,context:n,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=ni(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[Ao]=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=o,this.collection=r;let c=s||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{c(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ao=ii}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 fn=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=X(r.collection,e),this.hydrate=n}};var Ro,pn=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await qt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ro]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Ro=ue}};var ko,hn=class extends pe{constructor({index:e,hydrate:n,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await rt({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[ko]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=o}static{ko=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Bo,mn=class extends pe{constructor({hydrate:e,pageSize:n,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await rt({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 rt({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[Bo]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Bo=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Mo,yn=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await Wt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Mo]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Mo=ue}};var gn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:o}){this.serializeIndex=t=>t?Ie(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new fn({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 pn({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 yn({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 o=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new hn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[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 mn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[ue](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var bn=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[ii](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let o=this.get(e);return o?(r?.(o),o):this.set(n())}};var Fe=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 nt(this.documentDb,h);let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((h,{size:S})=>h+S,0),c=r.baselinesSize.size+r.operationsSize.size,p=c/s;return{collections:n,meta:r,storage:o,totalMetaSize:c,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.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 Re(this.documentDb),await Re(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Ft(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 Re(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((c,p)=>{o.onsuccess=c,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await ot({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 Re(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await ot({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new $e(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new un,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 Gt({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new nn({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new bn({context:n}),this._documentManager=new Jt(this.meta,this.schema,this._entities);let o=ji(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,c]of Object.entries(n.schema.collections)){let p=s;this[p]=new gn({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 dt=class{constructor(t){this.value=t}deref(){return this.value}};var dr=Symbol("metadataVersion");var wn=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 e=t[dr],{db:n}=await $t({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:h=>t.EXPERIMENTAL_weakRefs?new WeakRef(h):new dt(h)},o=new it({context:r,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=await ot({context:r,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),c=Object.assign(r,{documentDb:s});return new Fe({syncConfig:t.sync,migrations:t.migrations,files:t.files},c,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Ie(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Zi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:S=>t.EXPERIMENTAL_weakRefs?new WeakRef(S):new dt(S)},s=new it({context:o,disableRebasing:t.disableRebasing});await s.updateSchema(t.schema,t.overrideSchemaConflict);let c=await ir({context:o,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),p=Object.assign(o,{documentDb:c});return new Fe({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:s})};this.cleanupWIPDatabases=async t=>{let r=(await Gi(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Ie(t.schema)}`));for(let o of r)await Yi(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Ft(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=ri;
|
|
15
|
+
`)}})}function rr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,o)=>(r[o]={put:async s=>{xe(i.newSchema.collections[o],s);let c=s[i.newSchema.collections[o].primaryKey],p=X(o,c);return n.push(p),await t.insertLocalOperation(De(s,p,e)),s},delete:async s=>{let c=X(o,s),p=await t.getAllDocumentRelatedOids(c);return t.insertLocalOperation(p.map(h=>({oid:h,timestamp:e(),data:{op:"delete"}})))}},r),{})}function fo({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async o=>{let s=X(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)})},findOne:async o=>{let s=await qt({collection:r,index:o,context:t});return s?await e.getDocumentSnapshot(s,{to:e.time.now(i.oldSchema.version)}):null},findAll:async o=>{let s=await Wt({collection:r,index:o,context:t});return await Promise.all(s.map(p=>e.getDocumentSnapshot(p,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function po({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=fo({migration:t,context:e,meta:i}),s=rr({migration:t,getMigrationNow:n,newOids:r,meta:i}),c=async S=>{let E=await i.getAllCollectionRelatedOids(S);return i.insertLocalOperation(E.map(g=>({oid:g,timestamp:n(),data:{op:"delete"}})))},p=new Array;return{log:e.log,newOids:r,deleteCollection:c,migrate:async(S,E)=>{let g=await o[S].findAll();await Promise.all(g.filter(Boolean).map(async P=>{V(Ze(P),`Document is missing an OID: ${JSON.stringify(P)}`);let b=se(P),v=await E(P);if(v){Xe(b),Xe(v),Le(v);let C=et(b,v,n,void 0,[],{mergeUnknownObjects:!0});C.length>0&&await i.insertLocalOperation(C)}}))},queries:o,mutations:s,awaitables:p}}function ho({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,o=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),s=rr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,deleteCollection:()=>{throw new Error("Calling deleteCollection() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:o,mutations:s,awaitables:[]}}async function mo(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function yo(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function go(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=o=>{n()},e.onerror=o=>{r(e.error)}})}async function bo({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 Jt=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)})`),X(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return xe(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),o=this.getOid(t,r);return this.entities.create(r,o,n)};this.delete=async(t,e,n={})=>{let r=X(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>X(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>X(t,r)),n)}};var Ue=Symbol("entity-file-update"),at=Symbol("entity-file-mark-failed"),wo,vo,Be=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[wo]=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[vo]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{wo=Ue,vo=at}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 or=ft(mt(),1);function So(i){return{id:(0,or.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function xo(i){return i instanceof File}function Me(i,t){if(typeof window<"u"&&xo(i)){let e=So(i);return t(e),Ei(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 sr(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Yt=class extends fe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let o=e.file?await sr(e.file):void 0;if(!o&&r&&e.url)try{o=await fetch(e.url,{method:"GET",credentials:"include"}).then(s=>s.arrayBuffer())}catch(s){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",s)}return this.run("files",s=>s.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:o}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?Oo(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",o=>o.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",o=>o.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",o=>o.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,o)=>{e(this.hydrateFileData(r),o)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function Oo(i,t){return new Blob([i],{type:t})}function Io(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Gt=class{constructor({db:t,sync:e,context:n,meta:r,config:o={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ue](e);else{let n=new Be(e.id);n[Ue](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 Be(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[at]();return}let n=await this.storage.getFile(t.id);if(n)t[Ue](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ue](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[at](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[at](),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 Yt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:Io,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var ar="@@refresh",Xt="@@deepChange";function ct(i,t){return i[ar](t)}var Do,Co,ye=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:o,onAllUnsubscribed:s,readonlyKeys:c=[],fieldPath:p=[]}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[Do]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let o=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[Xt](this,t)),o&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[Co]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Xt](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 se(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity({oid:t,fieldSchema:n,parent:this,fieldKey:e})};this.wrapValue=(t,e)=>{if(ne(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(oe(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Xt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=se(t,!1));let n=this.getChildFieldSchema(e);n&&_e(t,n);let r=tt(n,t,[...this.fieldPath,e]);if(r)throw new Error(r);return 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)=>ne(e)?this.getSubObject(e.id,n)?.getSnapshot():oe(e)?this.getFileSnapshot(e):e);else{t={...this.value};for(let[e,n]of Object.entries(t))ne(n)?t[e]=this.getSubObject(n.id,e)?.getSnapshot():oe(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[o,s]of Object.entries(t)){if(this.readonlyKeys.includes(o))throw new Error(`Cannot set readonly key ${o.toString()}`);let c=this.getChildFieldSchema(o);c&&_e(s,c)}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=ce(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(ne(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=>ne(e)?e.id===ce(t):(oe(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:h}=ae(t);this.collection=h,this.store=e,this.fieldSchema=n,this.fieldPath=p,this.readonlyKeys=c,this.cache=r,this.parent=o&&this.cache.weakRef(o);let{view:S,deleted:E,lastTimestamp:g}=this.cache.computeView(t);if(this._current=S,this._deleted=E,this._updatedAt=g||null,this.cachedDeepUpdatedAt=null,this.events=new N(()=>{this.hasSubscribers||s?.()}),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}[(Do=ar,Co=Xt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Zt=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 en=class extends N{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Zt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:o}=r;n.add(o);let s=this.localOperationsMap.get(o)||[];s.push(r),this.localOperationsMap.set(o,s)}for(let r of n){let s=this.entities.get(r)?.deref();s&&(ct(s,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:o}=r;n.affectedOids?.add(o);let s=this.operationsMap.get(o)||[],c=s.findIndex(h=>h.timestamp>=r.timestamp);if(c!==-1){if(s[c].timestamp===r.timestamp)continue;s.splice(c,0,r)}else s.push(r);this.operationsMap.set(o,s);let p=this.localOperationsMap.get(o);p&&this.localOperationsMap.set(o,p.filter(h=>h.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:o}=r,s=this.baselinesMap.get(o);if(s?.timestamp&&s.timestamp>=r.timestamp)continue;n?.add(o),this.baselinesMap.set(o,r);let c=this.operationsMap.get(o)||[];for(;c[0]?.timestamp<r.timestamp;)c.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:o})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let s={isLocal:o||!1,affectedOids:new Set};if(this.insertBaselines(n,s),this.insertOperations(e,s),r)for(let c of this.entities.values()){let p=c.deref();p&&ct(p,s)}else for(let c of s.affectedOids){let h=this.entities.get(c)?.deref();h&&(ct(h,s),this.emit(`change:${c}`),this.emit("change:*",c))}};this.applyOperations=(e,n,r,o)=>{let s,c=this.storeTools.now;for(let p of r)if(!(o&&p.timestamp<=o)){if(Ci(p.timestamp,c)>0){s=p.timestamp;continue}p.data.op==="delete"?n=!0:(e=Pe(e,p.data),p.data.op==="initialize"&&(n=!1))}return s&&this.context.globalEvents.emit("futureSeen",s),{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:o,deleted:s}=this.applyOperations(n.view,n.deleted,r);return o&&K(o,e),{view:o,deleted:s,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],o=se(n?.snapshot||void 0),s=this.applyOperations(o,!o,r,n?.timestamp);return s.view&&K(s.view,e),s.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),s};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=({oid:e,fieldSchema:n,parent:r,readonlyKeys:o,fieldKey:s})=>{let p=this.entities.get(e)?.deref();return p||(p=new ye({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r,readonlyKeys:o,fieldPath:s?[...r?.fieldPath??[],s]:void 0}),this.entities.set(e,this.context.weakRef(p))),p};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:o,dropAll:s})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let c={isLocal:!1,affectedOids:new Set};s&&this.baselinesMap.clear(),this.insertBaselines(n,c),s&&this.operationsMap.clear(),this.insertOperations(e,c),(o||r)&&(this.localOperationsMap.clear(),o&&this.insertLocalOperations(o));for(let p of this.entities.keys()){let S=this.entities.get(p)?.deref();S&&(ct(S,c),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 tn="@@default",nn=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=tn;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=ae(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"]),o=[],s=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,c=>{o.push(c)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,c=>{c.confirmed=!0,s.push(c)},{transaction:r,mode:"readwrite"})]),t.reset({operations:s,baselines:o,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 en({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}=ae(e),o=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let s=o?.getSnapshot();if(s){let c=Rt(this.schema.collections[r],s);try{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.put(c)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",c)}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(c))}}else try{let p=this.db.transaction(r,"readwrite").objectStore(r);await W(p.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}catch(c){if(c instanceof Error)if(c instanceof DOMException&&c.message?.includes("not found"))this.log("debug","document not found in storage",t);else throw c}};this.get=async t=>{let e=await this.openFamilyCache(t),{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity({oid:t,fieldSchema:n,readonlyKeys: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({oid:t,fieldSchema:n,readonlyKeys:r}):null}return null};this.create=async(t,e,n)=>{It(t);let r=Me(t,this.files.add);K(r,e);let o=this.meta.patchCreator.createInitialize(r,e),s=await this.openFamilyCache(e);s.insertLocalOperations(o),await this.submitOperations(o,n);let{schema:c,readonlyKeys:p}=this.getDocumentSchema(e);if(!c)throw new Error(`Cannot create a document in the ${ae(e).collection} collection; it is not defined in the current schema version.`);return s.getEntity({oid:e,fieldSchema:c,readonlyKeys:p})};this.addOperationsToOpenCaches=async(t,e)=>{let n=Vn(t);Object.keys(n).forEach(o=>{let s=this.documentFamilyCaches.get(o);s&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",o,n[o].length),e.isLocal?s.insertLocalOperations(n[o]):s.insertOperations(n[o],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Nn(t);Object.keys(n).forEach(o=>{let s=this.documentFamilyCaches.get(o);s&&(this.log("adding","baselines to cache",o,n[o].length),s.insertBaselines(n[o],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let o=Nn(t),s=Vn(e),c=Array.from(new Set(Object.keys(o).concat(Object.keys(s))));for(let p of c){let h=this.documentFamilyCaches.get(p);h?(h.addData({operations:s[p]||[],baselines:o[p]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",p,s[p]?.length??0,"operations",o[p]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",p,"because it is not open")}return c};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 c of r)c.confirmed=!1;let o=[];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(),o=Array.from(new Set(e.map(c=>U(c.oid)).concat(t.map(c=>U(c.oid)))))):o=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 c of o)await this.writeDocumentToStorage(c);let s=Array.from(new Set(o.map(c=>ae(c).collection)));this.context.log("changes to collections",s),this.context.entityEvents.emit("collectionsChanged",s)};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=Ot(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),s={run:c=>(this.currentBatchKey=e,c(),this.currentBatchKey=tn,s),flush:async()=>(await this.operationBatcher.flush(tn),o.flush()),discard:()=>{this.operationBatcher.discard(e)}};return s};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(o=>U(o.oid))));for(let o of n)await this.writeDocumentToStorage(o);let r=new Set(t.map(({oid:o})=>ae(o).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Ki(t),n=[],r=()=>this.meta.now;for(let[o,s]of Object.entries(e)){let c=await this.openFamilyCache(o),{view:p,deleted:h}=c.computeConfirmedView(o),S=Qi(o,p,s,r);n.unshift(...S)}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(o=>this.meta.getAllDocumentRelatedOids(o))),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 Ve(this.flushOperations),this.operationBatcher.add({key:tn,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 ei=Symbol("handleMessage"),Eo,lt=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[Eo]=async(e,n)=>{let r=!1,o=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(o.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},o.clear();for(let[s,c]of Object.entries(n.peerPresence))this.isSelf(e,c)?(this._self=c,this._selfReplicaIds.add(c.replicaId),this.emit("selfChanged",c)):(r=!0,o.add(s),this._peers[s]=c,this.emit("peerChanged",s,c))}else if(n.type==="presence-offline"){o.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let s=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,s)}r&&(this._peerIds=Array.from(o),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Ve(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{Eo=ei}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 rn=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(),o=new window.FormData;o.append("file",e);try{let s=await fetch(n+`/${t.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return s.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",s.status,await s.text()),{success:!1,retry:s.status>=500})}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let 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 Ke=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)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var on=class extends N{constructor({endpointProvider:e,meta:n,presence:r,interval:o=15*1e3,log:s=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),o=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(o.ok){this.heartbeat.keepAlive();let s=await o.json();for(let c of s.messages)this.handleServerMessage(c);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),o.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.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=s,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new Ke({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function ti(i){this.message=i}ti.prototype=new Error,ti.prototype.name="InvalidCharacterError";var cr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new ti("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,o=0,s="";n=t.charAt(o++);~n&&(e=r%4?64*e+n:n,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return s};function Po(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(cr(e).replace(/(.)/g,function(n,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(t)}catch{return cr(t)}}function sn(i){this.message=i}function _o(i,t){if(typeof i!="string")throw new sn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(Po(i.split(".")[e]))}catch(n){throw new sn("Invalid token specified: "+n.message)}}sn.prototype=new Error,sn.prototype.name="InvalidTokenError";var lr=_o;var an=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(c=>{if(c.ok)return c.json();throw new Error(`Auth endpoint returned non-200 response: ${c.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=lr(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 o=n.toString(),s=e.file;if(!s){let c=new URL(r);c.pathname=c.pathname+"/files",s=c.toString()}return this.cached={http:r,websocket:o,files:s,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var cn=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}},ln=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 dn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,log:o}){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 Ke;this.reconnectScheduler=new cn(new ln(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=o||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 un=class extends N{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new lt({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},$e=class extends N{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:o=!0,autoStart:s,initialTransport:c,pullInterval:p,presenceUpdateBatchTimeout:h,defaultProfile:S,useBroadcastChannel:E},{meta:g,log:P,onData:b}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.handleMessage=async(e,{source:n}={source:"network"})=>{if(e.type==="op-re"||e.type==="sync-resp")for(let r of e.operations)this.meta.time.update(r.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}n==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[ei](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=g,this.onData=b,this.log=P||(()=>{}),this.presence=new lt({initialPresence:r,defaultProfile:S,updateBatchTimeout:h}),this.endpointProvider=new an({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new dn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log}),this.pushPullSync=new on({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:this.log,interval:p}),this.fileSync=new rn({endpointProvider:this.endpointProvider,log:this.log}),E&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),c==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),o&&this.canDoRealtime){let v=()=>{C&&clearTimeout(C);let O=Object.keys(this.presence.peers).length>0||o!=="peers-only"&&this.presence.selfReplicaIds.size>1;O&&this.mode==="pull"?this.setMode("realtime"):!O&&this.mode==="realtime"&&(C=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},C;this.presence.subscribe("peersChanged",v),o!=="peers-only"&&this.presence.subscribe("selfChanged",v)}s&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}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 Ao(i){return i!==null}function ni(i){return Array.isArray(i)?i.map(ni).filter(Ao):i instanceof ye&&i.deleted?null:i}function Ce(i,t){return!i&&!t||i&&t&&Ie(i)===Ie(t)}var ii=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),Ro,pe=class extends ze{constructor({initial:e,context:n,collection:r,key:o,shouldUpdate:s}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=ni(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[Ro]=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=o,this.collection=r;let c=s||(p=>p.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",p=>{c(p)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ro=ii}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 fn=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=X(r.collection,e),this.hydrate=n}};var ko,pn=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await qt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[ko]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{ko=ue}};var Bo,hn=class extends pe{constructor({index:e,hydrate:n,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await rt({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[Bo]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=o}static{Bo=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Mo,mn=class extends pe{constructor({hydrate:e,pageSize:n,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await rt({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 rt({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[Mo]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Mo=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Fo,yn=class extends pe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await Wt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Fo]=e=>{Ce(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Fo=ue}};var gn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:o}){this.serializeIndex=t=>t?Ie(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new fn({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 pn({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 yn({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 o=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(o,()=>new hn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:n}),s=>{s[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 mn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[ue](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,this.context=r,this.documentManager=o,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var bn=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[ii](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let o=this.get(e);return o?(r?.(o),o):this.set(n())}};var Fe=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 nt(this.documentDb,h);let r=await this.meta.stats(),o=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,s=Object.values(n).reduce((h,{size:S})=>h+S,0),c=r.baselinesSize.size+r.operationsSize.size,p=c/s;return{collections:n,meta:r,storage:o,totalMetaSize:c,totalCollectionsSize:s,metaToDataRatio:p,quotaUsage:o?.usage&&o?.quota?o.usage/o.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 Re(this.documentDb),await Re(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Ft(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 Re(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,o=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((c,p)=>{o.onsuccess=c,o.onerror=p});let s=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await ot({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 Re(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=s,this.context.documentDb=await ot({meta:this.meta,migrations:this.config.migrations,context:this.context,version:s.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new $e(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new un,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 Gt({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new nn({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new bn({context:n}),this._documentManager=new Jt(this.meta,this.schema,this._entities);let o=ji(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,c]of Object.entries(n.schema.collections)){let p=s;this[p]=new gn({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 dt=class{constructor(t){this.value=t}deref(){return this.value}};var dr=Symbol("metadataVersion");var wn=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 e=t[dr],{db:n}=await $t({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:n,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:h=>t.EXPERIMENTAL_weakRefs?new WeakRef(h):new dt(h)},o=new it({context:r,disableRebasing:t.disableRebasing});await o.updateSchema(t.schema,t.overrideSchemaConflict);let s=await ot({context:r,version:t.schema.version,meta:o,migrations:t.migrations,indexedDB:t.indexedDb}),c=Object.assign(r,{documentDb:s});return new Fe({syncConfig:t.sync,migrations:t.migrations,files:t.files},c,{meta:o})};this.initializeWIPDatabases=async t=>{let e=Ie(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Zi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),o={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:S=>t.EXPERIMENTAL_weakRefs?new WeakRef(S):new dt(S)},s=new it({context:o,disableRebasing:t.disableRebasing});await s.updateSchema(t.schema,t.overrideSchemaConflict);let c=await ir({context:o,version:t.schema.version,meta:s,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),p=Object.assign(o,{documentDb:c});return new Fe({syncConfig:t.sync,migrations:t.migrations,files:t.files},p,{meta:s})};this.cleanupWIPDatabases=async t=>{let r=(await Gi(t.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${t.namespace}_${Ie(t.schema)}`));for(let o of r)await Yi(o,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Ft(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=ri;
|
|
17
17
|
//# sourceMappingURL=index.js.map
|