@verdant-web/store 3.9.0 → 3.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle/index.js +6 -6
- package/dist/bundle/index.js.map +4 -4
- package/dist/esm/client/ClientDescriptor.d.ts +1 -1
- package/dist/esm/entities/Entity.d.ts +4 -0
- package/dist/esm/entities/Entity.js +8 -0
- package/dist/esm/entities/Entity.js.map +1 -1
- package/dist/esm/entities/types.d.ts +3 -1
- package/dist/esm/index.d.ts +2 -1
- package/dist/esm/index.js +1 -0
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/metadata/MessageCreator.d.ts +5 -2
- package/dist/esm/metadata/MessageCreator.js +3 -2
- package/dist/esm/metadata/MessageCreator.js.map +1 -1
- package/dist/esm/sync/PresenceManager.d.ts +22 -3
- package/dist/esm/sync/PresenceManager.js +65 -7
- package/dist/esm/sync/PresenceManager.js.map +1 -1
- package/dist/esm/sync/PushPullSync.js +1 -1
- package/dist/esm/sync/PushPullSync.js.map +1 -1
- package/dist/esm/sync/Sync.js +6 -5
- package/dist/esm/sync/Sync.js.map +1 -1
- package/dist/esm/sync/WebSocketSync.js +1 -1
- package/dist/esm/sync/WebSocketSync.js.map +1 -1
- package/dist/esm/sync/cliSync.d.ts +10 -0
- package/dist/esm/sync/cliSync.js +13 -0
- package/dist/esm/sync/cliSync.js.map +1 -0
- package/package.json +2 -2
- package/src/client/ClientDescriptor.ts +1 -1
- package/src/entities/Entity.ts +9 -0
- package/src/entities/types.ts +11 -1
- package/src/index.ts +2 -0
- package/src/metadata/MessageCreator.ts +7 -4
- package/src/sync/PresenceManager.ts +94 -9
- package/src/sync/PushPullSync.ts +1 -3
- package/src/sync/Sync.ts +10 -5
- package/src/sync/WebSocketSync.ts +1 -3
- package/src/sync/cliSync.ts +18 -0
package/dist/bundle/index.js
CHANGED
|
@@ -1,16 +1,16 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var rs=Object.create;var Mt=Object.defineProperty;var os=Object.getOwnPropertyDescriptor;var ss=Object.getOwnPropertyNames;var as=Object.getPrototypeOf,cs=Object.prototype.hasOwnProperty;var ls=(n,i)=>()=>(n&&(i=n(n=0)),i);var oe=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports),dr=(n,i)=>{for(var e in i)Mt(n,e,{get:i[e],enumerable:!0})},ur=(n,i,e,t)=>{if(i&&typeof i=="object"||typeof i=="function")for(let r of ss(i))!cs.call(n,r)&&r!==e&&Mt(n,r,{get:()=>i[r],enumerable:!(t=os(i,r))||t.enumerable});return n};var Be=(n,i,e)=>(e=n!=null?rs(as(n)):{},ur(i||!n||!n.__esModule?Mt(e,"default",{value:n,enumerable:!0}):e,n)),et=n=>ur(Mt({},"__esModule",{value:!0}),n);var ii=oe((rc,fr)=>{fr.exports=function(i,e){var t="000000000"+i;return t.substr(t.length-e)}});var pr=oe((oc,hr)=>{var ds=ii(),us=typeof window=="object"?window:self,fs=Object.keys(us).length,hs=navigator.mimeTypes?navigator.mimeTypes.length:0,ps=ds((hs+navigator.userAgent.length).toString(36)+fs.toString(36),4);hr.exports=function(){return ps}});var br=oe((sc,yr)=>{var ri,mr=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;mr?(gr=Math.pow(2,32)-1,ri=function(){return Math.abs(mr.getRandomValues(new Uint32Array(1))[0]/gr)}):ri=Math.random;var gr;yr.exports=ri});var Ne=oe((ac,Sr)=>{var Lt=pr(),wr=ii(),ms=br(),ht=0,si=4,Vt=36,vr=Math.pow(Vt,si);function oi(){return wr((ms()*vr<<0).toString(Vt),si)}function xr(){return ht=ht<vr?ht:0,ht++,ht-1}function pt(){var n="c",i=new Date().getTime().toString(Vt),e=wr(xr().toString(Vt),si),t=Lt(),r=oi()+oi();return n+i+e+t+r}pt.slug=function(){var i=new Date().getTime().toString(36),e=xr().toString(36).slice(-4),t=Lt().slice(0,1)+Lt().slice(-1),r=oi().slice(-2);return i.slice(-2)+e+t+r};pt.isCuid=function(i){return typeof i!="string"?!1:!!i.startsWith("c")};pt.isSlug=function(i){if(typeof i!="string")return!1;var e=i.length;return e>=7&&e<=10};pt.fingerprint=Lt;Sr.exports=pt});var Mr=oe((kr,jr)=>{(function(n){var i;typeof kr=="object"?jr.exports=n():typeof define=="function"&&define.amd?define(n):(typeof window<"u"?i=window:typeof global<"u"?i=global:typeof self<"u"&&(i=self),i.objectHash=n())})(function(){return function n(i,e,t){function r(a,d){if(!e[a]){if(!i[a]){var u=typeof require=="function"&&require;if(!d&&u)return u(a,!0);if(o)return o(a,!0);throw new Error("Cannot find module '"+a+"'")}d=e[a]={exports:{}},i[a][0].call(d.exports,function(p){var S=i[a][1][p];return r(S||p)},d,d.exports,n,i,e,t)}return e[a].exports}for(var o=typeof require=="function"&&require,s=0;s<t.length;s++)r(t[s]);return r}({1:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){"use strict";var w=n("crypto");function C(b,D){D=_(b,D);var f;return(f=D.algorithm!=="passthrough"?w.createHash(D.algorithm):new R).write===void 0&&(f.write=f.update,f.end=f.update),O(D,f).dispatch(b),f.update||f.end(""),f.digest?f.digest(D.encoding==="buffer"?void 0:D.encoding):(b=f.read(),D.encoding!=="buffer"?b.toString(D.encoding):b)}(e=i.exports=C).sha1=function(b){return C(b)},e.keys=function(b){return C(b,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(b){return C(b,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(b){return C(b,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var g=w.getHashes?w.getHashes().slice():["sha1","md5"],v=(g.push("passthrough"),["buffer","hex","binary","base64"]);function _(b,D){var f={};if(f.algorithm=(D=D||{}).algorithm||"sha1",f.encoding=D.encoding||"hex",f.excludeValues=!!D.excludeValues,f.algorithm=f.algorithm.toLowerCase(),f.encoding=f.encoding.toLowerCase(),f.ignoreUnknown=D.ignoreUnknown===!0,f.respectType=D.respectType!==!1,f.respectFunctionNames=D.respectFunctionNames!==!1,f.respectFunctionProperties=D.respectFunctionProperties!==!1,f.unorderedArrays=D.unorderedArrays===!0,f.unorderedSets=D.unorderedSets!==!1,f.unorderedObjects=D.unorderedObjects!==!1,f.replacer=D.replacer||void 0,f.excludeKeys=D.excludeKeys||void 0,b===void 0)throw new Error("Object argument required.");for(var m=0;m<g.length;++m)g[m].toLowerCase()===f.algorithm.toLowerCase()&&(f.algorithm=g[m]);if(g.indexOf(f.algorithm)===-1)throw new Error('Algorithm "'+f.algorithm+'" not supported. supported values: '+g.join(", "));if(v.indexOf(f.encoding)===-1&&f.algorithm!=="passthrough")throw new Error('Encoding "'+f.encoding+'" not supported. supported values: '+v.join(", "));return f}function I(b){if(typeof b=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(b))!=null}function O(b,D,f){f=f||[];function m(l){return D.update?D.update(l,"utf8"):D.write(l,"utf8")}return{dispatch:function(l){return this["_"+((l=b.replacer?b.replacer(l):l)===null?"null":typeof l)](l)},_object:function(l){var x,E=Object.prototype.toString.call(l),j=/\[object (.*)\]/i.exec(E);if(j=(j=j?j[1]:"unknown:["+E+"]").toLowerCase(),0<=(E=f.indexOf(l)))return this.dispatch("[CIRCULAR:"+E+"]");if(f.push(l),o!==void 0&&o.isBuffer&&o.isBuffer(l))return m("buffer:"),m(l);if(j==="object"||j==="function"||j==="asyncfunction")return E=Object.keys(l),b.unorderedObjects&&(E=E.sort()),b.respectType===!1||I(l)||E.splice(0,0,"prototype","__proto__","constructor"),b.excludeKeys&&(E=E.filter(function(k){return!b.excludeKeys(k)})),m("object:"+E.length+":"),x=this,E.forEach(function(k){x.dispatch(k),m(":"),b.excludeValues||x.dispatch(l[k]),m(",")});if(!this["_"+j]){if(b.ignoreUnknown)return m("["+j+"]");throw new Error('Unknown object type "'+j+'"')}this["_"+j](l)},_array:function(l,k){k=k!==void 0?k:b.unorderedArrays!==!1;var E=this;if(m("array:"+l.length+":"),!k||l.length<=1)return l.forEach(function(M){return E.dispatch(M)});var j=[],k=l.map(function(M){var B=new R,q=f.slice();return O(b,B,q).dispatch(M),j=j.concat(q.slice(f.length)),B.read().toString()});return f=f.concat(j),k.sort(),this._array(k,!1)},_date:function(l){return m("date:"+l.toJSON())},_symbol:function(l){return m("symbol:"+l.toString())},_error:function(l){return m("error:"+l.toString())},_boolean:function(l){return m("bool:"+l.toString())},_string:function(l){m("string:"+l.length+":"),m(l.toString())},_function:function(l){m("fn:"),I(l)?this.dispatch("[native]"):this.dispatch(l.toString()),b.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(l.name)),b.respectFunctionProperties&&this._object(l)},_number:function(l){return m("number:"+l.toString())},_xml:function(l){return m("xml:"+l.toString())},_null:function(){return m("Null")},_undefined:function(){return m("Undefined")},_regexp:function(l){return m("regex:"+l.toString())},_uint8array:function(l){return m("uint8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint8clampedarray:function(l){return m("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(l))},_int8array:function(l){return m("int8array:"),this.dispatch(Array.prototype.slice.call(l))},_uint16array:function(l){return m("uint16array:"),this.dispatch(Array.prototype.slice.call(l))},_int16array:function(l){return m("int16array:"),this.dispatch(Array.prototype.slice.call(l))},_uint32array:function(l){return m("uint32array:"),this.dispatch(Array.prototype.slice.call(l))},_int32array:function(l){return m("int32array:"),this.dispatch(Array.prototype.slice.call(l))},_float32array:function(l){return m("float32array:"),this.dispatch(Array.prototype.slice.call(l))},_float64array:function(l){return m("float64array:"),this.dispatch(Array.prototype.slice.call(l))},_arraybuffer:function(l){return m("arraybuffer:"),this.dispatch(new Uint8Array(l))},_url:function(l){return m("url:"+l.toString())},_map:function(l){return m("map:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_set:function(l){return m("set:"),l=Array.from(l),this._array(l,b.unorderedSets!==!1)},_file:function(l){return m("file:"),this.dispatch([l.name,l.size,l.type,l.lastModfied])},_blob:function(){if(b.ignoreUnknown)return m("[blob]");throw Error(`Hashing Blob objects is currently not supported
|
|
2
2
|
(see https://github.com/puleos/object-hash/issues/26)
|
|
3
3
|
Use "options.replacer" or "options.ignoreUnknown"
|
|
4
|
-
`)},_domwindow:function(){return m("domwindow")},_bigint:function(l){return m("bigint:"+l.toString())},_process:function(){return m("process")},_timer:function(){return m("timer")},_pipe:function(){return m("pipe")},_tcp:function(){return m("tcp")},_udp:function(){return m("udp")},_tty:function(){return m("tty")},_statwatcher:function(){return m("statwatcher")},_securecontext:function(){return m("securecontext")},_connection:function(){return m("connection")},_zlib:function(){return m("zlib")},_context:function(){return m("context")},_nodescript:function(){return m("nodescript")},_httpparser:function(){return m("httpparser")},_dataview:function(){return m("dataview")},_signal:function(){return m("signal")},_fsevent:function(){return m("fsevent")},_tlswrap:function(){return m("tlswrap")}}}function R(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,D,
|
|
5
|
-
list should be an Array.`),c.length===0)return new g(0);if(c.length===1)return c[0];if(typeof h!="number")for(A=h=0;A<c.length;A++)h+=c[A].length;for(var y=new g(h),P=0,A=0;A<c.length;A++){var T=c[A];T.copy(y,P),P+=T.length}return y},g.prototype.write=function(c,h,y,P){isFinite(h)?isFinite(y)||(P=y,y=void 0):(X=P,P=h,h=y,y=X),h=Number(h)||0;var A,T,U,W,X=this.length-h;switch((!y||X<(y=Number(y)))&&(y=X),P=String(P||"utf8").toLowerCase()){case"hex":A=function(be,ie,re,Z){re=Number(re)||0;var G=be.length-re;(!Z||G<(Z=Number(Z)))&&(Z=G),F((G=ie.length)%2==0,"Invalid hex string"),G/2<Z&&(Z=G/2);for(var Xe=0;Xe<Z;Xe++){var cr=parseInt(ie.substr(2*Xe,2),16);F(!isNaN(cr),"Invalid hex string"),be[re+Xe]=cr}return g._charsWritten=2*Xe,Xe}(this,c,h,y);break;case"utf8":case"utf-8":T=this,U=h,W=y,A=g._charsWritten=jt(Ee(c),T,U,W);break;case"ascii":case"binary":A=v(this,c,h,y);break;case"base64":T=this,U=h,W=y,A=g._charsWritten=jt(or(c),T,U,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=_(this,c,h,y);break;default:throw new Error("Unknown encoding")}return A},g.prototype.toString=function(c,h,y){var P,A,T,U,W=this;if(c=String(c||"utf8").toLowerCase(),h=Number(h)||0,(y=y!==void 0?Number(y):W.length)===h)return"";switch(c){case"hex":P=function(X,be,ie){var re=X.length;(!be||be<0)&&(be=0),(!ie||ie<0||re<ie)&&(ie=re);for(var Z="",G=be;G<ie;G++)Z+=K(X[G]);return Z}(W,h,y);break;case"utf8":case"utf-8":P=function(X,be,ie){var re="",Z="";ie=Math.min(X.length,ie);for(var G=be;G<ie;G++)X[G]<=127?(re+=sr(Z)+String.fromCharCode(X[G]),Z=""):Z+="%"+X[G].toString(16);return re+sr(Z)}(W,h,y);break;case"ascii":case"binary":P=I(W,h,y);break;case"base64":A=W,U=y,P=(T=h)===0&&U===A.length?w.fromByteArray(A):w.fromByteArray(A.slice(T,U));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=function(X,be,ie){for(var re=X.slice(be,ie),Z="",G=0;G<re.length;G+=2)Z+=String.fromCharCode(re[G]+256*re[G+1]);return Z}(W,h,y);break;default:throw new Error("Unknown encoding")}return P},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(c,h,y,P){if(h=h||0,(P=P||P===0?P:this.length)!==(y=y||0)&&c.length!==0&&this.length!==0){F(y<=P,"sourceEnd < sourceStart"),F(0<=h&&h<c.length,"targetStart out of bounds"),F(0<=y&&y<this.length,"sourceStart out of bounds"),F(0<=P&&P<=this.length,"sourceEnd out of bounds"),P>this.length&&(P=this.length);var A=(P=c.length-h<P-y?c.length-h+y:P)-y;if(A<100||!g._useTypedArrays)for(var T=0;T<A;T++)c[T+h]=this[T+y];else c._set(this.subarray(y,y+A),h)}},g.prototype.slice=function(c,h){var y=this.length;if(c=q(c,y,0),h=q(h,y,y),g._useTypedArrays)return g._augment(this.subarray(c,h));for(var P=h-c,A=new g(P,void 0,!0),T=0;T<P;T++)A[T]=this[T+c];return A},g.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},g.prototype.set=function(c,h){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,h)},g.prototype.readUInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},g.prototype.readUInt16LE=function(c,h){return O(this,c,!0,h)},g.prototype.readUInt16BE=function(c,h){return O(this,c,!1,h)},g.prototype.readUInt32LE=function(c,h){return R(this,c,!0,h)},g.prototype.readUInt32BE=function(c,h){return R(this,c,!1,h)},g.prototype.readInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},g.prototype.readInt16LE=function(c,h){return b(this,c,!0,h)},g.prototype.readInt16BE=function(c,h){return b(this,c,!1,h)},g.prototype.readInt32LE=function(c,h){return D(this,c,!0,h)},g.prototype.readInt32BE=function(c,h){return D(this,c,!1,h)},g.prototype.readFloatLE=function(c,h){return d(this,c,!0,h)},g.prototype.readFloatBE=function(c,h){return d(this,c,!1,h)},g.prototype.readDoubleLE=function(c,h){return m(this,c,!0,h)},g.prototype.readDoubleBE=function(c,h){return m(this,c,!1,h)},g.prototype.writeUInt8=function(c,h,y){y||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"trying to write beyond buffer length"),ti(c,255)),h>=this.length||(this[h]=c)},g.prototype.writeUInt16LE=function(c,h,y){l(this,c,h,!0,y)},g.prototype.writeUInt16BE=function(c,h,y){l(this,c,h,!1,y)},g.prototype.writeUInt32LE=function(c,h,y){x(this,c,h,!0,y)},g.prototype.writeUInt32BE=function(c,h,y){x(this,c,h,!1,y)},g.prototype.writeInt8=function(c,h,y){y||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"Trying to write beyond buffer length"),ni(c,127,-128)),h>=this.length||(0<=c?this.writeUInt8(c,h,y):this.writeUInt8(255+c+1,h,y))},g.prototype.writeInt16LE=function(c,h,y){E(this,c,h,!0,y)},g.prototype.writeInt16BE=function(c,h,y){E(this,c,h,!1,y)},g.prototype.writeInt32LE=function(c,h,y){j(this,c,h,!0,y)},g.prototype.writeInt32BE=function(c,h,y){j(this,c,h,!1,y)},g.prototype.writeFloatLE=function(c,h,y){B(this,c,h,!0,y)},g.prototype.writeFloatBE=function(c,h,y){B(this,c,h,!1,y)},g.prototype.writeDoubleLE=function(c,h,y){M(this,c,h,!0,y)},g.prototype.writeDoubleBE=function(c,h,y){M(this,c,h,!1,y)},g.prototype.fill=function(c,h,y){if(h=h||0,y=y||this.length,F(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),F(h<=y,"end < start"),y!==h&&this.length!==0){F(0<=h&&h<this.length,"start out of bounds"),F(0<=y&&y<=this.length,"end out of bounds");for(var P=h;P<y;P++)this[P]=c}},g.prototype.inspect=function(){for(var c=[],h=this.length,y=0;y<h;y++)if(c[y]=K(this[y]),y===e.INSPECT_MAX_BYTES){c[y+1]="...";break}return"<Buffer "+c.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var c=new Uint8Array(this.length),h=0,y=c.length;h<y;h+=1)c[h]=this[h];return c.buffer};var k=g.prototype;function q(c,h,y){return typeof c!="number"?y:h<=(c=~~c)?h:0<=c||0<=(c+=h)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ee(c){for(var h=[],y=0;y<c.length;y++){var P=c.charCodeAt(y);if(P<=127)h.push(c.charCodeAt(y));else for(var A=y,T=(55296<=P&&P<=57343&&y++,encodeURIComponent(c.slice(A,y+1)).substr(1).split("%")),U=0;U<T.length;U++)h.push(parseInt(T[U],16))}return h}function or(c){return w.toByteArray(c)}function jt(c,h,y,P){for(var A=0;A<P&&!(A+y>=h.length||A>=c.length);A++)h[A+y]=c[A];return A}function sr(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function ti(c,h){F(typeof c=="number","cannot write a non-number as a number"),F(0<=c,"specified a negative value for writing an unsigned value"),F(c<=h,"value is larger than maximum value for type"),F(Math.floor(c)===c,"value has a fractional component")}function ni(c,h,y){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(y<=c,"value smaller than minimum allowed value"),F(Math.floor(c)===c,"value has a fractional component")}function ar(c,h,y){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(y<=c,"value smaller than minimum allowed value")}function F(c,h){if(!c)throw new Error(h||"Failed assertion")}g._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=k.get,c.set=k.set,c.write=k.write,c.toString=k.toString,c.toLocaleString=k.toString,c.toJSON=k.toJSON,c.copy=k.copy,c.slice=k.slice,c.readUInt8=k.readUInt8,c.readUInt16LE=k.readUInt16LE,c.readUInt16BE=k.readUInt16BE,c.readUInt32LE=k.readUInt32LE,c.readUInt32BE=k.readUInt32BE,c.readInt8=k.readInt8,c.readInt16LE=k.readInt16LE,c.readInt16BE=k.readInt16BE,c.readInt32LE=k.readInt32LE,c.readInt32BE=k.readInt32BE,c.readFloatLE=k.readFloatLE,c.readFloatBE=k.readFloatBE,c.readDoubleLE=k.readDoubleLE,c.readDoubleBE=k.readDoubleBE,c.writeUInt8=k.writeUInt8,c.writeUInt16LE=k.writeUInt16LE,c.writeUInt16BE=k.writeUInt16BE,c.writeUInt32LE=k.writeUInt32LE,c.writeUInt32BE=k.writeUInt32BE,c.writeInt8=k.writeInt8,c.writeInt16LE=k.writeInt16LE,c.writeInt16BE=k.writeInt16BE,c.writeInt32LE=k.writeInt32LE,c.writeInt32BE=k.writeInt32BE,c.writeFloatLE=k.writeFloatLE,c.writeFloatBE=k.writeFloatBE,c.writeDoubleLE=k.writeDoubleLE,c.writeDoubleBE=k.writeDoubleBE,c.fill=k.fill,c.inspect=k.inspect,c.toArrayBuffer=k.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,i,e){(function(t,r,w,s,a,f,u,p,S){var w=n("buffer").Buffer,C=4,g=new w(C);g.fill(0),i.exports={hash:function(v,_,I,O){for(var R=_(function(l,x){l.length%C!=0&&(E=l.length+(C-l.length%C),l=w.concat([l,g],E));for(var E,j=[],B=x?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=C)j.push(B.call(l,M));return j}(v=w.isBuffer(v)?v:new w(v),O),8*v.length),_=O,b=new w(I),D=_?b.writeInt32BE:b.writeInt32LE,d=0;d<R.length;d++)D.call(b,R[d],4*d,!0);return b}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(n,i,e){(function(t,r,w,s,a,f,u,p,S){var w=n("buffer").Buffer,C=n("./sha"),g=n("./sha256"),v=n("./rng"),_={sha1:C,sha256:g,md5:n("./md5")},I=64,O=new w(I);function R(l,x){var E=_[l=l||"sha1"],j=[];return E||b("algorithm:",l,"is not yet supported"),{update:function(B){return w.isBuffer(B)||(B=new w(B)),j.push(B),B.length,this},digest:function(B){var M=w.concat(j),M=x?function(k,q,te){w.isBuffer(q)||(q=new w(q)),w.isBuffer(te)||(te=new w(te)),q.length>I?q=k(q):q.length<I&&(q=w.concat([q,O],I));for(var H=new w(I),K=new w(I),Ee=0;Ee<I;Ee++)H[Ee]=54^q[Ee],K[Ee]=92^q[Ee];return te=k(w.concat([H,te])),k(w.concat([K,te]))}(E,x,M):E(M);return j=null,B?M.toString(B):M}}}function b(){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 R(l)},e.createHmac=R,e.randomBytes=function(l,x){if(!x||!x.call)return new w(v(l));try{x.call(this,void 0,new w(v(l)))}catch(E){x(E)}};var D,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],m=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(D in d)m(d[D],D)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){var w=n("./helpers");function C(b,D){b[D>>5]|=128<<D%32,b[14+(D+64>>>9<<4)]=D;for(var d=1732584193,m=-271733879,l=-1732584194,x=271733878,E=0;E<b.length;E+=16){var j=d,B=m,M=l,k=x,d=v(d,m,l,x,b[E+0],7,-680876936),x=v(x,d,m,l,b[E+1],12,-389564586),l=v(l,x,d,m,b[E+2],17,606105819),m=v(m,l,x,d,b[E+3],22,-1044525330);d=v(d,m,l,x,b[E+4],7,-176418897),x=v(x,d,m,l,b[E+5],12,1200080426),l=v(l,x,d,m,b[E+6],17,-1473231341),m=v(m,l,x,d,b[E+7],22,-45705983),d=v(d,m,l,x,b[E+8],7,1770035416),x=v(x,d,m,l,b[E+9],12,-1958414417),l=v(l,x,d,m,b[E+10],17,-42063),m=v(m,l,x,d,b[E+11],22,-1990404162),d=v(d,m,l,x,b[E+12],7,1804603682),x=v(x,d,m,l,b[E+13],12,-40341101),l=v(l,x,d,m,b[E+14],17,-1502002290),d=_(d,m=v(m,l,x,d,b[E+15],22,1236535329),l,x,b[E+1],5,-165796510),x=_(x,d,m,l,b[E+6],9,-1069501632),l=_(l,x,d,m,b[E+11],14,643717713),m=_(m,l,x,d,b[E+0],20,-373897302),d=_(d,m,l,x,b[E+5],5,-701558691),x=_(x,d,m,l,b[E+10],9,38016083),l=_(l,x,d,m,b[E+15],14,-660478335),m=_(m,l,x,d,b[E+4],20,-405537848),d=_(d,m,l,x,b[E+9],5,568446438),x=_(x,d,m,l,b[E+14],9,-1019803690),l=_(l,x,d,m,b[E+3],14,-187363961),m=_(m,l,x,d,b[E+8],20,1163531501),d=_(d,m,l,x,b[E+13],5,-1444681467),x=_(x,d,m,l,b[E+2],9,-51403784),l=_(l,x,d,m,b[E+7],14,1735328473),d=I(d,m=_(m,l,x,d,b[E+12],20,-1926607734),l,x,b[E+5],4,-378558),x=I(x,d,m,l,b[E+8],11,-2022574463),l=I(l,x,d,m,b[E+11],16,1839030562),m=I(m,l,x,d,b[E+14],23,-35309556),d=I(d,m,l,x,b[E+1],4,-1530992060),x=I(x,d,m,l,b[E+4],11,1272893353),l=I(l,x,d,m,b[E+7],16,-155497632),m=I(m,l,x,d,b[E+10],23,-1094730640),d=I(d,m,l,x,b[E+13],4,681279174),x=I(x,d,m,l,b[E+0],11,-358537222),l=I(l,x,d,m,b[E+3],16,-722521979),m=I(m,l,x,d,b[E+6],23,76029189),d=I(d,m,l,x,b[E+9],4,-640364487),x=I(x,d,m,l,b[E+12],11,-421815835),l=I(l,x,d,m,b[E+15],16,530742520),d=O(d,m=I(m,l,x,d,b[E+2],23,-995338651),l,x,b[E+0],6,-198630844),x=O(x,d,m,l,b[E+7],10,1126891415),l=O(l,x,d,m,b[E+14],15,-1416354905),m=O(m,l,x,d,b[E+5],21,-57434055),d=O(d,m,l,x,b[E+12],6,1700485571),x=O(x,d,m,l,b[E+3],10,-1894986606),l=O(l,x,d,m,b[E+10],15,-1051523),m=O(m,l,x,d,b[E+1],21,-2054922799),d=O(d,m,l,x,b[E+8],6,1873313359),x=O(x,d,m,l,b[E+15],10,-30611744),l=O(l,x,d,m,b[E+6],15,-1560198380),m=O(m,l,x,d,b[E+13],21,1309151649),d=O(d,m,l,x,b[E+4],6,-145523070),x=O(x,d,m,l,b[E+11],10,-1120210379),l=O(l,x,d,m,b[E+2],15,718787259),m=O(m,l,x,d,b[E+9],21,-343485551),d=R(d,j),m=R(m,B),l=R(l,M),x=R(x,k)}return Array(d,m,l,x)}function g(b,D,d,m,l,x){return R((D=R(R(D,b),R(m,x)))<<l|D>>>32-l,d)}function v(b,D,d,m,l,x,E){return g(D&d|~D&m,b,D,l,x,E)}function _(b,D,d,m,l,x,E){return g(D&m|d&~m,b,D,l,x,E)}function I(b,D,d,m,l,x,E){return g(D^d^m,b,D,l,x,E)}function O(b,D,d,m,l,x,E){return g(d^(D|~m),b,D,l,x,E)}function R(b,D){var d=(65535&b)+(65535&D);return(b>>16)+(D>>16)+(d>>16)<<16|65535&d}i.exports=function(b){return w.hash(b,C,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){var w;i.exports=w||function(C){for(var g,v=new Array(C),_=0;_<C;_++)!(3&_)&&(g=4294967296*Math.random()),v[_]=g>>>((3&_)<<3)&255;return v}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){var w=n("./helpers");function C(_,I){_[I>>5]|=128<<24-I%32,_[15+(I+64>>9<<4)]=I;for(var O,R,b,D=Array(80),d=1732584193,m=-271733879,l=-1732584194,x=271733878,E=-1009589776,j=0;j<_.length;j+=16){for(var B=d,M=m,k=l,q=x,te=E,H=0;H<80;H++){D[H]=H<16?_[j+H]:v(D[H-3]^D[H-8]^D[H-14]^D[H-16],1);var K=g(g(v(d,5),(K=m,R=l,b=x,(O=H)<20?K&R|~K&b:!(O<40)&&O<60?K&R|K&b|R&b:K^R^b)),g(g(E,D[H]),(O=H)<20?1518500249:O<40?1859775393:O<60?-1894007588:-899497514)),E=x,x=l,l=v(m,30),m=d,d=K}d=g(d,B),m=g(m,M),l=g(l,k),x=g(x,q),E=g(E,te)}return Array(d,m,l,x,E)}function g(_,I){var O=(65535&_)+(65535&I);return(_>>16)+(I>>16)+(O>>16)<<16|65535&O}function v(_,I){return _<<I|_>>>32-I}i.exports=function(_){return w.hash(_,C,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){function w(I,O){var R=(65535&I)+(65535&O);return(I>>16)+(O>>16)+(R>>16)<<16|65535&R}function C(I,O){var R,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),D=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);I[O>>5]|=128<<24-O%32,I[15+(O+64>>9<<4)]=O;for(var m,l,x=0;x<I.length;x+=16){for(var E=D[0],j=D[1],B=D[2],M=D[3],k=D[4],q=D[5],te=D[6],H=D[7],K=0;K<64;K++)d[K]=K<16?I[K+x]:w(w(w((l=d[K-2],v(l,17)^v(l,19)^_(l,10)),d[K-7]),(l=d[K-15],v(l,7)^v(l,18)^_(l,3))),d[K-16]),R=w(w(w(w(H,v(l=k,6)^v(l,11)^v(l,25)),k&q^~k&te),b[K]),d[K]),m=w(v(m=E,2)^v(m,13)^v(m,22),E&j^E&B^j&B),H=te,te=q,q=k,k=w(M,R),M=B,B=j,j=E,E=w(R,m);D[0]=w(E,D[0]),D[1]=w(j,D[1]),D[2]=w(B,D[2]),D[3]=w(M,D[3]),D[4]=w(k,D[4]),D[5]=w(q,D[5]),D[6]=w(te,D[6]),D[7]=w(H,D[7])}return D}var g=n("./helpers"),v=function(I,O){return I>>>O|I<<32-O},_=function(I,O){return I>>>O};i.exports=function(I){return g.hash(I,C,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){e.read=function(w,C,g,v,x){var I,O,R=8*x-v-1,b=(1<<R)-1,D=b>>1,d=-7,m=g?x-1:0,l=g?-1:1,x=w[C+m];for(m+=l,I=x&(1<<-d)-1,x>>=-d,d+=R;0<d;I=256*I+w[C+m],m+=l,d-=8);for(O=I&(1<<-d)-1,I>>=-d,d+=v;0<d;O=256*O+w[C+m],m+=l,d-=8);if(I===0)I=1-D;else{if(I===b)return O?NaN:1/0*(x?-1:1);O+=Math.pow(2,v),I-=D}return(x?-1:1)*O*Math.pow(2,I-v)},e.write=function(w,C,g,v,_,E){var O,R,b=8*E-_-1,D=(1<<b)-1,d=D>>1,m=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:E-1,x=v?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(R=isNaN(C)?1:0,O=D):(O=Math.floor(Math.log(C)/Math.LN2),C*(v=Math.pow(2,-O))<1&&(O--,v*=2),2<=(C+=1<=O+d?m/v:m*Math.pow(2,1-d))*v&&(O++,v/=2),D<=O+d?(R=0,O=D):1<=O+d?(R=(C*v-1)*Math.pow(2,_),O+=d):(R=C*Math.pow(2,d-1)*Math.pow(2,_),O=0));8<=_;w[g+l]=255&R,l+=x,R/=256,_-=8);for(O=O<<_|R,b+=_;0<b;w[g+l]=255&O,l+=x,O/=256,b-=8);w[g+l-x]|=128*E}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(n,i,e){(function(t,r,o,s,a,f,u,p,S){var w,C,g;function v(){}(t=i.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(_){return window.setImmediate(_)}:g?(w=[],window.addEventListener("message",function(_){var I=_.source;I!==window&&I!==null||_.data!=="process-tick"||(_.stopPropagation(),0<w.length&&w.shift()())},!0),function(_){w.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=v,t.addListener=v,t.once=v,t.off=v,t.removeListener=v,t.removeAllListeners=v,t.emit=v,t.binding=function(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){throw new Error("process.chdir is not supported")}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var Je={};lr(Je,{__addDisposableResource:()=>Uo,__assign:()=>En,__asyncDelegator:()=>Ro,__asyncGenerator:()=>Po,__asyncValues:()=>Fo,__await:()=>ut,__awaiter:()=>Io,__classPrivateFieldGet:()=>jo,__classPrivateFieldIn:()=>Lo,__classPrivateFieldSet:()=>Mo,__createBinding:()=>An,__decorate:()=>xo,__disposeResources:()=>Vo,__esDecorate:()=>Ia,__exportStar:()=>Do,__extends:()=>wo,__generator:()=>_o,__importDefault:()=>Bo,__importStar:()=>ko,__makeTemplateObject:()=>To,__metadata:()=>Oo,__param:()=>So,__propKey:()=>Da,__read:()=>Vi,__rest:()=>vo,__runInitializers:()=>_a,__setFunctionName:()=>Ea,__spread:()=>Eo,__spreadArray:()=>Ao,__spreadArrays:()=>Co,__values:()=>Cn,default:()=>Pa});function wo(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Ui(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function vo(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function xo(n,i,e,t){var r=arguments.length,o=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(o=(r<3?s(o):r>3?s(i,e,o):s(i,e))||o);return r>3&&o&&Object.defineProperty(i,e,o),o}function So(n,i){return function(e,t){i(e,t,n)}}function Ia(n,i,e,t,r,o){function s(I){if(I!==void 0&&typeof I!="function")throw new TypeError("Function expected");return I}for(var a=t.kind,f=a==="getter"?"get":a==="setter"?"set":"value",u=!i&&n?t.static?n:n.prototype:null,p=i||(u?Object.getOwnPropertyDescriptor(u,t.name):{}),S,w=!1,C=e.length-1;C>=0;C--){var g={};for(var v in t)g[v]=v==="access"?{}:t[v];for(var v in t.access)g.access[v]=t.access[v];g.addInitializer=function(I){if(w)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(I||null))};var _=(0,e[C])(a==="accessor"?{get:p.get,set:p.set}:p[f],g);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(S=s(_.get))&&(p.get=S),(S=s(_.set))&&(p.set=S),(S=s(_.init))&&r.unshift(S)}else(S=s(_))&&(a==="field"?r.unshift(S):p[f]=S)}u&&Object.defineProperty(u,t.name,p),w=!0}function _a(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function Da(n){return typeof n=="symbol"?n:"".concat(n)}function Ea(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function Oo(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function Io(n,i,e,t){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(p){try{u(t.next(p))}catch(S){s(S)}}function f(p){try{u(t.throw(p))}catch(S){s(S)}}function u(p){p.done?o(p.value):r(p.value).then(a,f)}u((t=t.apply(n,i||[])).next())})}function _o(n,i){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},t,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(p){return f([u,p])}}function f(u){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(e=0)),e;)try{if(t=1,r&&(o=u[0]&2?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=i.call(n,e)}catch(p){u=[6,p],r=0}finally{t=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Do(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&An(i,n,e)}function Cn(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function Vi(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,o=[],s;try{for(;(i===void 0||i-- >0)&&!(r=t.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(s)throw s.error}}return o}function Eo(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(Vi(arguments[i]));return n}function Co(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var o=arguments[i],s=0,a=o.length;s<a;s++,r++)t[r]=o[s];return t}function Ao(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,o;t<r;t++)(o||!(t in i))&&(o||(o=Array.prototype.slice.call(i,0,t)),o[t]=i[t]);return n.concat(o||Array.prototype.slice.call(i))}function ut(n){return this instanceof ut?(this.v=n,this):new ut(n)}function Po(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(w){t[w]&&(r[w]=function(C){return new Promise(function(g,v){o.push([w,C,g,v])>1||a(w,C)})})}function a(w,C){try{f(t[w](C))}catch(g){S(o[0][3],g)}}function f(w){w.value instanceof ut?Promise.resolve(w.value.v).then(u,p):S(o[0][2],w)}function u(w){a("next",w)}function p(w){a("throw",w)}function S(w,C){w(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function Ro(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,o){i[r]=n[r]?function(s){return(e=!e)?{value:ut(n[r](s)),done:!1}:o?o(s):s}:o}}function Fo(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof Cn=="function"?Cn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(o){e[o]=n[o]&&function(s){return new Promise(function(a,f){s=n[o](s),r(a,f,s.done,s.value)})}}function r(o,s,a,f){Promise.resolve(f).then(function(u){o({value:u,done:a})},s)}}function To(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function ko(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&An(i,n,e);return Ca(i,n),i}function Bo(n){return n&&n.__esModule?n:{default:n}}function jo(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function Mo(n,i,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function Lo(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function Uo(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function Vo(n){function i(t){n.error=n.hasError?new Aa(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(o){return i(o),e()})}catch(o){i(o)}}if(n.hasError)throw n.error}return e()}var Ui,En,An,Ca,Aa,Pa,Ge=as(()=>{Ui=function(n,i){return Ui=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Ui(n,i)};En=function(){return En=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(i[o]=e[o])}return i},En.apply(this,arguments)};An=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};Ca=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};Aa=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};Pa={__extends:wo,__assign:En,__rest:vo,__decorate:xo,__param:So,__metadata:Oo,__awaiter:Io,__generator:_o,__createBinding:An,__exportStar:Do,__values:Cn,__read:Vi,__spread:Eo,__spreadArrays:Co,__spreadArray:Ao,__await:ut,__asyncGenerator:Po,__asyncDelegator:Ro,__asyncValues:Fo,__makeTemplateObject:To,__importStar:ko,__importDefault:Bo,__classPrivateFieldGet:jo,__classPrivateFieldSet:Mo,__classPrivateFieldIn:Lo,__addDisposableResource:Uo,__disposeResources:Vo}});var No=oe(zo=>{"use strict";Object.defineProperty(zo,"__esModule",{value:!0})});var Ni=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var $o=(Ge(),Ze(Je));function Ko(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}De.eventHandlerSafeInvoke=Ko;function zi(n,i,e){return(0,$o.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=zi;function Ra(n,i,e,t){for(let r of n){let{succeeded:o,error:s}=Ko(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=Ra;function Fa(n,i,e,t){return(0,$o.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:o,error:s}=yield zi(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of n)r.push(zi(o,i,e).then(({succeeded:s,error:a})=>{if(!s&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=Fa});var Wo=oe(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.TypedEvent=void 0;var Ta=(Ge(),Ze(Je)),qo=Ni(),Ho={swallowExceptions:!1,parallelize:!0},$i=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Ho){(0,qo.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Ho){return(0,Ta.__awaiter)(this,void 0,void 0,function*(){yield(0,qo.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};Pn.TypedEvent=$i});var qi=oe(Ki=>{"use strict";Object.defineProperty(Ki,"__esModule",{value:!0});var ka=(Ge(),Ze(Je));(0,ka.__exportStar)(Wo(),Ki)});var Qo=oe(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.FinalizationRegistryMissingError=void 0;var Hi=class extends Error{};Rn.FinalizationRegistryMissingError=Hi});var Qi=oe(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.WeakHandlerHolder=void 0;var Ba=Qo(),Wi=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new Ba.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};Fn.WeakHandlerHolder=Wi});var Jo=oe(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.WeakEvent=void 0;var Ji=(Ge(),Ze(Je)),ja=qi(),Ma=Qi(),Gi=Ni(),La={swallowExceptions:!1,parallelize:!0},Yi=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new ja.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new Ma.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,Gi.eventHandlerSafeInvoke)(o,i,e);if(!s&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=La){return(0,Ji.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Ji.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,Gi.eventHandlerSafeInvokeAsync)(o,i,e);if(!s&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Ji.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Gi.eventHandlerSafeInvokeAsync)(s,i,e).then(({succeeded:a,error:f})=>{if(!a&&t.swallowExceptions!==!0)throw f})):this.releaseHandler(o)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};Tn.WeakEvent=Yi});var Yo=oe(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});var Go=(Ge(),Ze(Je));(0,Go.__exportStar)(Qi(),kn);(0,Go.__exportStar)(Jo(),kn)});var Xo=oe(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});var Xi=(Ge(),Ze(Je));(0,Xi.__exportStar)(No(),Ft);(0,Xi.__exportStar)(qi(),Ft);(0,Xi.__exportStar)(Yo(),Ft)});var rr={};lr(rr,{Client:()=>Ye,ClientDescriptor:()=>ei,Entity:()=>he,EntityFile:()=>fe,MigrationPathError:()=>at,ServerSync:()=>ft,Storage:()=>Ye,StorageDescriptor:()=>ei,UndoHistory:()=>Qe,authorization:()=>Xa,collection:()=>Ci,createDefaultMigration:()=>Ai,createMigration:()=>Pi,id:()=>Ya,migrate:()=>sn,schema:()=>It});var Dr=Ve(et(),1),Kt=4,gt=36;function Sr(n){return n.toString(gt).padStart(Kt,"0")}function ps(n){return n.toString().padStart(6,"0")}var Vt=class{constructor(){this.latest={time:Date.now(),counter:0,node:ms()},this.zeroCounter=0,this.now=i=>(this.latest=Ir(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=Ir(this.latest),ps(i)+ys(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Kt);this.latest=gs(this.latest,Er(e))},this.get=(i,e)=>Sr(i)+Or(e),this.zero=i=>Sr(i)+Or({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=ui}},zt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},Nt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},ai=4,ci=7,$t=60*1e3,mt=9;function ms(){return Dr.default.slug().padStart(ci,"0").slice(0,ci)}function Or(n){let i=new Date(n.time).getTime().toString(gt).padStart(mt,"0"),e=n.counter.toString(gt).padStart(ai,"0"),t=n.node.padStart(ci,"0");return`${i}${e}${t}`}function Ir(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>$t)throw new zt(e,i,$t);if(t>65535)throw new Nt;return{time:e,counter:t,node:n.node}}function gs(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),o;if(n.time===t&&i.time===t?o=r+1:n.time===t?o=n.counter+1:i.time===t?o=i.counter+1:o=0,t-e>$t)throw new zt(t,e,$t);if(o>65535)throw new Nt;return{time:t,counter:o,node:n.node}}function Er(n){let i=n.slice(0,mt),e=n.slice(mt,mt+ai),t=n.slice(mt+ai),r=parseInt(i,gt),o=parseInt(e,gt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:t}}function ys(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function _r(n){return parseInt(n.slice(0,Kt),36)}function li(n,i){return _r(n)-_r(i)}function ui(n){return Er(n.slice(Kt)).time}var qt,bs=new Uint8Array(16);function di(){if(!qt&&(qt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qt(bs)}var Cr=/^(?:[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 ws(n){return typeof n=="string"&&Cr.test(n)}var Ar=ws;var ee=[];for(Ht=0;Ht<256;++Ht)ee.push((Ht+256).toString(16).substr(1));var Ht;function vs(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[n[i+0]]+ee[n[i+1]]+ee[n[i+2]]+ee[n[i+3]]+"-"+ee[n[i+4]]+ee[n[i+5]]+"-"+ee[n[i+6]]+ee[n[i+7]]+"-"+ee[n[i+8]]+ee[n[i+9]]+"-"+ee[n[i+10]]+ee[n[i+11]]+ee[n[i+12]]+ee[n[i+13]]+ee[n[i+14]]+ee[n[i+15]]).toLowerCase();if(!Ar(e))throw TypeError("Stringified UUID is invalid");return e}var Pr=vs;function xs(n,i,e){n=n||{};var t=n.random||(n.rng||di)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return Pr(t)}var yt=xs;function Q(n){return Oe(n)||we(n)}function tt(n,i){return n===i?!0:!(!Q(n)||!Q(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Ss="/",bt=":",hi=new WeakMap;function ne(n){let i=me(n);return L(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function me(n){if(V(n))return hi.get(n)}function N(n,i){return L(V(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),pi(n)&&Jt(n),hi.set(n,i),n}function pi(n){return!!me(n)}function Jt(n){return hi.delete(n),n}function mi(n,i,e){if(pi(n))return ne(n);{let t=ve(i,e);return N(n,t),t}}function Rr(n,i,e){if(pi(n)){let t=ne(n);if(Ce(t,i))return ne(n);{let r=ve(i,e);return N(n,r),r}}else{let t=ve(i,e);return N(n,t),t}}var fi={".":"˙","/":"&slash;",":":":"};function Fr(n){return n.replace(/[/]/g,fi["/"]).replace(/[:]/g,fi[":"]).replace(/[.]/g,fi["."])}function Tr(n){return n.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Y(n,i,e){let t=Fr(n)+Ss+Fr(i);return e&&(t+=bt+e),t}function ve(n,i=Os){let{collection:e,id:t}=ce(n);return Y(e,t,i())}function ce(n){let[i,e,...t]=n.split("/");t.length&&(console.error(`OID ${n} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,o]=e.split(bt),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Tr(i),id:Tr(s),subId:o}}function nt(n,i){let e=ne(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],V(t)&&!Q(t)&&(Rr(t,e,i),nt(t,i))}else if(V(n)&&!Q(n))for(let t of Object.keys(n))V(n[t])&&!Q(n[t])&&(Rr(n[t],e,i),nt(n[t],i))}function Wt(n){if(Jt(n),Array.isArray(n))for(let i=0;i<n.length;i++)Wt(n[i]);else if(V(n))for(let i of Object.keys(n))Wt(n[i])}function Os(){return yt().slice(0,8)}function ae(n){return{"@@type":"ref",id:n}}function Qt(n,i=new Map){if(Array.isArray(n)){let e=ne(n),t=N([],e);for(let r=0;r<n.length;r++){let o=n[r];if(V(o)){if(Oe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o)){t[r]=o;continue}else{let s=ne(o);t[r]=ae(s),Qt(o,i)}}else t[r]=o}i.set(e,t)}else if(V(n)&&!Q(n)){let e=ne(n),t=N({},e);for(let r of Object.keys(n)){let o=n[r];if(V(o)){if(Oe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o))t[r]=o;else{let s=ne(o);t[r]=ae(s),Qt(o,i)}}else t[r]=o}i.set(e,t)}else Q(n);return i}function $(n){return n.split(".")[0].split(bt)[0]}function gi(n){let i=$(n),e=ve(i,()=>"\uFFFF");return[`${i}${bt}`,e]}function Ce(n,i){return $(n)===$(i)}function Gt(n){return!n.includes(bt)}var Mr=Ve(jr(),1);function Is(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function wt(n){return JSON.stringify(n,Is)}function le(n,i=!0){if(V(n)||Array.isArray(n)){let e=me(n),t;if(Array.isArray(n))t=n.map(r=>le(r,i));else{t={};for(let[r,o]of Object.entries(n))t[r]=le(o,i)}return i&&e&&N(t,e),t}return n}function ke(n){return(0,Mr.default)(n)}function V(n){return n&&typeof n=="object"}function Lr(n){for(var i=[],e=[n],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&i.indexOf(r)===-1){i.push(r);for(var o in r)e.push(r[o])}}return t}function L(n,i="assertion failed"){if(!n)throw new Error(i)}function Yt(n=16){return yt().replace("-","").slice(0,n)}function Ur(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function Vr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function zr(n,i){let e=0,t;return function(...r){let o=this,s=Date.now();s-e>=i?(e=s,n.apply(o,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=s,n.apply(o,r)},i))}}function we(n){return n&&n["@@type"]==="file"}function vt(n){return{"@@type":"file",id:n}}function it(n){return typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob}function Xt(n){return n&&V(n)&&typeof n.id=="string"&&typeof n.remote=="boolean"&&typeof n.name=="string"&&typeof n.type=="string"}var rt="__@@oid_do_not_use",Ae="@@id";function _s(n){if(V(n))return n[Ae]||n[rt]}function Ds(n){return V(n)&&(delete n[rt],delete n[Ae]),n}function Es(n){let i=_s(n);i&&N(n,i)}function xt(n){if(Es(n),Ds(n),Array.isArray(n))for(let i=0;i<n.length;i++)xt(n[i]);else if(V(n))for(let i of Object.keys(n))xt(n[i])}function Cs(n){let{collection:i,id:e,subId:t}=ce(n);return Y(i,e,t)}var As=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Ps(n){return n.replaceAll(As,i=>{let e=i.slice(1,i.length-1);return`"${Cs(e)}"`})}function yi(n){return JSON.parse(Ps(JSON.stringify(n)))}function bi(n){let i=$(n);return[`${i}.`,`${i}.\uFFFF`]}function wi(n){return n===Ae||n===rt}function Oe(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function vi(n){return V(n)&&!Q(n)}function Rs(n,i){return n===i?!0:Q(n)&&Q(i)?tt(n,i):!1}function St(n,i,e,t,r=[],o){let s=o?.authz,a=ne(n);function f(u,p,S,w){if(!vi(p))Rs(p,S)||(w?r.push(je({oid:a,timestamp:e(),data:{op:"list-set",index:u,value:p}},s)):r.push(je({oid:a,timestamp:e(),data:{op:"set",name:u,value:p}},s)));else{let C=me(S),g=me(p);g&&!Ce(a,g)?(p=le(p,!1),g=ve(a,t),N(p,g)):o?.mergeUnknownObjects?!g&&C?(N(p,C),g=C):g=mi(p,a,t):g=mi(p,a,t),L(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ce(a,g),`Error: value OID ${g} is not related to parent OID ${a}. This is a bug in Verdant.`),S===void 0||g!==C?(Pe(p,g,e,t,r),r.push(je({oid:a,timestamp:e(),data:{op:"set",name:u,value:ae(g)}},s)),C!==void 0&&r.push(je({oid:C,timestamp:e(),data:{op:"delete"}},s))):St(S,p,e,t,r,o)}}if(Array.isArray(n)&&Array.isArray(i)){for(let p=0;p<i.length;p++){let S=i[p],w=n[p];f(p,S,w,!0)}let u=n.length-i.length;if(u>0){for(let p=i.length;p<n.length;p++){let S=n[p],w=me(S);w&&r.push(je({oid:w,timestamp:e(),data:{op:"delete"}},s))}r.push(je({oid:a,timestamp:e(),data:{op:"list-delete",index:i.length,count:u}},s))}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(vi(n)&&vi(i)){let u=new Set(Object.keys(n));for(let[p,S]of Object.entries(i)){if(S===void 0&&o?.defaultUndefined||(u.delete(p),wi(p)))continue;let w=n[p];f(p,S,w,!1)}if(!o?.defaultUndefined)for(let p of u)wi(p)||r.push(je({oid:a,timestamp:e(),data:{op:"remove",name:p}},s))}}return r}function Pe(n,i,e,t,r=[],o){N(n,i),nt(n,t);let s=Qt(n);for(let a of s.keys()){let f=s.get(a),u={oid:a,timestamp:e(),data:{op:"initialize",value:Jt(f)}};r.push(je(u,o?.authz))}return r}function je(n,i){return i&&(n.authz=i),n}function Ot(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function $r(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Kr(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function Be(n){return Array.isArray(n)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${me(n)})`),!1)}function ze(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(i.op){case"set":s(t[i.name]),t[i.name]=i.value;break;case"remove":s(t[i.name]),delete t[i.name];break;case"list-set":Be(n)&&(s(n[i.index]),n[i.index]=i.value);break;case"list-push":Be(n)&&n.push(i.value);break;case"list-delete":Be(n)&&(s(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":Be(n)&&(o=n.splice(i.from,1),n.splice(i.to,0,o[0]));break;case"list-remove":if(Be(n))do{let a=i.value;i.only==="last"?Oe(a)?r=Ur(n,f=>f.id===a.id):r=n.lastIndexOf(a):Oe(a)?r=n.findIndex(f=>f.id===a.id):r=n.indexOf(a),r!==-1&&(s(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":Be(n)&&(n.some(f=>Oe(f)&&Oe(i.value)?f.id===i.value.id:f===i.value)||n.push(i.value));break;case"list-move-by-ref":Be(n)&&(r=n.findIndex(a=>tt(a,i.value)),o=n.splice(r,1),n.splice(i.index,0,o[0]));break;case"list-insert":if(Be(n)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(s):V(n)&&Object.values(n||{}).forEach(s);return;case"initialize":return le(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function Zt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=Nr(r,i,e),V(n[t])&&Zt(n[t],i,e)}else if(!we(n)){if(V(n)){L(me(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=Nr(n[t],i,e),V(n[t])&&Zt(n[t],i,e)}}return e}function Nr(n,i,e){if(Oe(n)){e.push(n.id);let t=i.get(n.id);return L(!!t,`No value was found in object map for ${n.id}`),N(t,n.id)}else return n}function qr(n){return n.data.op==="set"?n.data.name:!1}function Hr(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}function en(n){return{oid:n.oid,timestamp:n.timestamp,data:n.data,authz:n.authz}}var Me;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Me||(Me={}));var Fs=n=>Object.assign({type:"object"},n),Ts=n=>Object.assign({type:"array"},n),ks=n=>Object.assign({type:"string"},n),Bs=n=>Object.assign({type:"number"},n),js=n=>Object.assign({type:"boolean"},n),Ms=n=>Object.assign({type:"any"},n),Ls=n=>Object.assign({type:"map"},n),Us=n=>Object.assign({type:"file"},n),Wr={object:Fs,array:Ts,string:ks,number:Bs,boolean:js,any:Ms,map:Ls,file:Us};var Yr=Ve(et(),1);function xi(n){return n.equals!==void 0}function Si(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function Vs(n){return!!n.match}function Oi(n){return n.startsWith!==void 0}function Qr(n){return!Si(n)&&!xi(n)&&!Vs(n)&&!Oi(n)&&n.order}function xe(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Re(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function _i(n){if(!(!n||!Re(n)))return n.type==="file"?xe(n)?null:void 0:n.type==="map"?{}:n.type==="array"?xe(n)?null:[]:n.type==="object"?xe(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Fe(n,i){for(let[e,t]of Object.entries(n.fields)){let r=Di(t);(r!==void 0&&i[e]===void 0||!xe(t)&&i[e]===null)&&(i[e]=r),i[e]&&Ne(i[e],t)}return i}function Ne(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=Di(t);r!==void 0&&(n[e]=r)}Ne(n[e],t)}else if(i.type==="array")for(let e of n)Ne(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Ae||e===rt||Ne(t,i.values)}function Di(n){if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="any"){if(n.default&&typeof n.default=="function")return n.default();if(n.default!==void 0)return JSON.parse(JSON.stringify(n.default))}if(n.type==="array")return[];if(n.type==="map")return{};if(n.type!=="any"&&n.nullable)return null;if(n.type==="object"&&n.default){let i=typeof n.default=="function"?n.default():JSON.parse(JSON.stringify(n.default));for(let[e,t]of Object.entries(n.properties))i[e]===void 0&&(i[e]=Di(t));return i}}function Ei(n,i){for(let[e,t]of Object.entries(i))e===Ae||e===rt||(n.fields[e]?Ii(t,n.fields[e]):delete i[e]);return i}function Ii(n,i){if(V(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?Ii(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)Ii(e,i.items)}function Jr(n,i){for(let[e,t]of Object.entries(i))if(e!==Ae){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Te({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Te({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(xe(n)&&i===null)){if(i===null&&(r||!Re(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ie(e)}`};if(n.type==="object"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected object ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};for(let[o,s]of Object.entries(n.properties))o!==Ae&&i[o]&&Te({field:s,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});for(let o of Object.keys(i))if(!n.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ie(e)}`}}else if(n.type==="array"){if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};for(let o of i)Te({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!V(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ie(e)}, got ${i}`};for(let[o,s]of Object.entries(i))Te({field:n.values,value:s,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0})}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${Ie(e)}, got ${i}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}else if(n.type==="file"&&!it(i)&&!Xt(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}}function Ie(n){return n.length===0?"root":n.join(".")}function Gr(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=tn({field:n[t],value:r,fieldPath:[t]}));return e}function tn({field:n,value:i,fieldPath:e=[],depth:t}){let r=Te({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!V(i))return i;let o={};for(let[s,a]of Object.entries(n.properties))o[s]=tn({field:a,value:i[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else{if(n.type==="array")return Array.isArray(i)?i.map(o=>tn({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!V(i))return i;let o={};for(let[s,a]of Object.entries(i))o[s]=tn({field:n.values,value:a,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else return i}}function $e(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var zs=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function Ci(n){var{synthetics:i,indexes:e}=n,t=zs(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),e);for(let[o,s]of Object.entries(t.fields))"indexed"in s&&(r[o]={field:o});return Object.assign(Object.assign({},t),{indexes:r})}function It(n){return n}It.collection=Ci;It.fields=Wr;It.generated={id:Yr.default};var nn="\uFFFFFE",Ns="\0",$s="\uFFFFFF";function ue(...n){let i=Ks(n);return i.length===1?i[0]:i}function Ke(...n){return n.join(nn)+`${$s}`}function qe(...n){return n.join(nn)+`${nn}${Ns}`}function Ks(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let o of e)t.push(r.concat(o));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(nn))))}function qs(n){return!!n.field}function Hs(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let o=r;qs(o)?e[t]=Se(i[o.field]):e[t]=Se(o.compute(i))}return e}function Ws(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=ue(...r.of.map(o=>i[o])),e),{})}function Qs(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=Se(i[t])),e),{})}function rn(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},Qs(n,i)),Hs(n,i));return Object.assign(e,Ws(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=JSON.stringify(i),e}var Js="null";function Se(n){if(n===null)return Js;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(Se);throw new Error(`Unsupported index value: ${n}`)}var Xr={version:0,collections:{}};function sn(n,i,e){let t=typeof i=="function",r=t?Xr:n,o=t?n:i,s=t?i:e,a=Object.keys(o.collections).filter(v=>r.collections[v]&&wt(r.collections[v])!==wt(o.collections[v])),f=Object.keys(r.collections).filter(v=>!o.collections[v]),u=Object.keys(o.collections).filter(v=>!r.collections[v]),p=new Set;for(let v of a){let _=r.collections[v].fields,I=o.collections[v].fields;Object.keys(I).some(O=>{var R,b;return!(!((R=_[O])===null||R===void 0)&&R.default)&&((b=I[O])===null||b===void 0?void 0:b.default)})&&p.add(v),Object.keys(_).some(O=>!I[O])&&p.add(v)}let S={},w={};for(let v of[...a,...u]){let _=on(r.collections[v]),I=on(o.collections[v]),O=I.filter(b=>!_.find(D=>D.name===b.name)),R=_.filter(b=>!I.find(D=>D.name===b.name));O.length>0&&(S[v]=O,a.includes(v)&&p.add(v)),R.length>0&&(w[v]=R,a.includes(v)&&p.add(v))}let C=(v,_)=>Fe(o.collections[v],_),g=v=>_=>{let I=o.collections[v];return Fe(I,Ei(I,_))};return{version:o.version,migrate:async v=>{let _=[];if(await s({migrate:async(I,O)=>{let R=g(I),b=async D=>{let d=await O(D);return N(d,ne(D)),R(d)};await v.migrate(I,b),_.push(I),p.delete(I)},identity:I=>I,withDefaults:C,info:{changedCollections:a,addedCollections:u,removedCollections:f},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",p);for(let O of p)await v.migrate(O,g(O)),_.push(O);let I=a.filter(O=>!_.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:f,addedIndexes:S,removedIndexes:w,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:u,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function on(n){return n?[...Object.keys(n.indexes||{}).map(i=>({name:i,multiEntry:["array","string[]","number[]","boolean[]"].includes(n.indexes[i].type),synthetic:!0,compound:!1})),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:n.compounds[i].of.some(e=>(n.fields[e]||n.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function Ai(n,i){return sn(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let o of r.changedCollections)await t(o,s=>s)})}function Pi(n,i,e){let t=typeof i=="function"||i===void 0,r=t?Xr:n,o=t?n:i,s=t?i:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:f,removedCollections:u,addedIndexes:p,removedIndexes:S,autoMigratedCollections:w,autoMigration:C}=Gs(r,o);return{version:o.version,migrate:async g=>{let v=[];if(await s?.({migrate:async(I,O)=>{let R=C(I),b=async D=>{let d=await O(D);N(d,ne(D));let m=R(d),l=Jr(o.collections[I].fields,m);return m};await g.migrate(I,b),v.push(I),w.delete(I)},info:{changedCollections:a,addedCollections:f,removedCollections:u},queries:g.queries,mutations:g.mutations}),o.version>1){g.log("debug","auto-migrating collections with new defaults",w);for(let O of w)await g.migrate(O,C(O)),v.push(O);for(let O of u)await g.deleteCollection(O);let I=a.filter(O=>!v.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:u,addedIndexes:p,removedIndexes:S,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:f,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Gs(n,i){let e=Object.keys(i.collections).filter(p=>n.collections[p]&&wt(n.collections[p])!==wt(i.collections[p])),t=Object.keys(n.collections).filter(p=>!i.collections[p]),r=Object.keys(i.collections).filter(p=>!n.collections[p]),o=new Set;for(let p of e){let S=n.collections[p].fields,w=i.collections[p].fields;Object.keys(w).some(C=>!Re(S[C])&&Re(w[C]))&&o.add(p),Object.keys(S).some(C=>!w[C])&&o.add(p)}let s={},a={};for(let p of[...e,...r]){let S=on(n.collections[p]),w=on(i.collections[p]),C=w.filter(v=>!S.find(_=>_.name===v.name)),g=S.filter(v=>!w.find(_=>_.name===v.name));C.length>0&&(s[p]=C,e.includes(p)&&o.add(p)),g.length>0&&(a[p]=g,e.includes(p)&&o.add(p))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(p,S)=>Fe(i.collections[p],S),autoMigration:p=>S=>{let w=i.collections[p];return Fe(w,Ei(w,S))}}}var an=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!V(t)||Q(t),this.createDiff=(t,r,o={})=>St(t,r,this.getNow,this.createSubId,[],o),this.createInitialize=(t,r)=>Pe(t,r,this.getNow,this.createSubId),this.createSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:o}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ae(s),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:o}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ae(s)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let o=ve(t,this.createSubId);return[...Pe(r,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ae(o)}}]}},this.createListAdd=(t,r)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ae(r)}}],this.createListInsert=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:o,index:r}}];{let s=ve(t,this.createSubId);return[...Pe(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ae(s),index:r}}]}},this.createListRemove=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:o}}],this.createListDelete=(t,r,o=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:o}}],this.createListMoveByRef=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:o}}],this.createListMoveByIndex=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:o}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=t=>t.map(r=>({oid:r,timestamp:this.getNow(),data:{op:"delete"}}))}};var z=class{constructor(i){this._onAllUnsubscribed=i,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=Yt(),o=this.subscribers[e];return o||(o=this.subscribers[e]={}),o[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Zr(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=le(i),o=[];for(let s of e){let a=Ys(n,r,s,t);o.unshift(...a),ze(r,s.data)}return o}function Ys(n,i,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:n,timestamp:t(),data:{op:"set",name:r.name,value:i[r.name]}}];case"list-insert":return[{oid:n,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:n,timestamp:t(),data:{op:"list-insert",index:r.index,values:i.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:n,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:i.indexOf(r.value)}}];case"list-move-by-index":return[{oid:n,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:n,timestamp:t(),data:{op:"initialize",value:i}}];case"list-push":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=i.indexOf(r.value);for(;s!==-1;)o.push(s),s=i.indexOf(r.value,s+1);return o.map(a=>({oid:n,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-set":return[{oid:n,timestamp:t(),data:{op:"list-set",index:r.index,value:i[r.index]}}];case"initialize":return[{oid:n,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var ot=class{constructor(i){this.flusher=i,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:i,userData:e,items:t,max:r,timeout:o}){let s=this.batches.get(i);return s||(s=new Ri({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:i}),this.batches.set(i,s)),s.update({items:t,max:r,timeout:o,userData:e}),s}},Ri=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:o,key:s}){this.items=[],this.update=({items:a,max:f,timeout:u,userData:p})=>{this.items.push(...a),f!==void 0&&(this.max=f),u!==void 0&&(this.timeout=u),p&&(this.userData=p);let S=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():S&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=o,this.key=s}};function eo(n,i){let e,t;return(...r)=>{let o=i();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],t=n(...r)),t}}var _t;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage"})(_t||(_t={}));var st=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};st.Code=_t;function to(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function Xs(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}function Zs(n){return typeof Buffer<"u"?Buffer.from(n,"base64").toString():atob(n)}var He={onlyUser:n=>Xs(`u:${n}:*`),onlyMe:()=>He.onlyUser(Fi),decode:n=>{let e=Zs(n).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},Fi="$$_originator_$$";function no(n,i){let{operations:e,baselines:t}=n;if(e)for(let r of e)r.authz&&He.decode(r.authz).subject===Fi&&(r.authz=He.onlyUser(i));if(t)for(let r of t)r.authz&&He.decode(r.authz).subject===Fi&&(r.authz=He.onlyUser(i))}var Ti=typeof window<"u"?window.indexedDB:void 0;function de(n){return n instanceof Error&&n.name==="AbortError"}function J(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&de(n.error)?i(n.result):e(n.error)}})}function We(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),s=r.objectStore(i).openCursor(),a=0,f=0;s.onsuccess=function(u){let p=s.result;p&&(a++,f=f+Lr(p.value),p.continue())},s.onerror=function(u){s.error&&de(s.error)?e({count:a,size:f}):t(s.error)},r.oncomplete=function(u){e({count:a,size:f})},r.onabort=function(u){t(u)},r.onerror=function(u){t(u)}})}function cn(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(t)}async function ge(n){n.close(),await new Promise((i,e)=>{i()})}async function ln(n,i=Ti){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{t.onsuccess=r,t.onerror=o})]),window.location.reload()}function io(n,i=window.indexedDB){return J(i.deleteDatabase(n))}async function ro(n=window.indexedDB){return n.databases()}function un(n,i,e,t,r){let o=n.transaction(i,e);if(t){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",s),o.addEventListener("error",()=>{t.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{t.removeEventListener("abort",s)})}return o}var _e=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(i=>i()),this._disposes=[]};this.addDispose=i=>{this._disposes.push(i)}}};var se=class extends _e{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=un(this.db,e,t?.mode||"readonly",t?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return J(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return Promise.all(a.map(J))};this.iterate=async(e,t,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),f=t(a);return Array.isArray(f)?Promise.all(f.map(u=>new Promise((p,S)=>{u.onsuccess=()=>{let w=u.result;w?(r(w.value,a),w.continue()):p()},u.onerror=()=>{u.error&&de(u.error)?p():S(u.error)}}))).then(()=>{}):new Promise((u,p)=>{f.onsuccess=()=>{let S=f.result;S?r(S.value,a)?u():S.continue():u()},f.onerror=()=>{f.error&&de(f.error)?u():p(f.error)}})};this.clear=e=>this.run(e,t=>t.clear(),{mode:"readwrite"});this.log=t,this.addDispose(()=>{this.globalAbortController.abort()})}};var dn=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var fn=class extends se{constructor(e,t){super(e,t);this.getAllForDocument=async(e,{mode:t="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:t,transaction:r}),o};this.iterateOverAllForDocument=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=$(e),[f,u]=gi(e),[p,S]=bi(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(f,u,!1,!1)),s.openCursor(IDBKeyRange.bound(p,S,!1,!1))]},t,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:t="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=$(s),[f,u]=gi(s),[p,S]=bi(s);return[o.get(a),o.getAll(IDBKeyRange.bound(f,u,!1,!1)),o.getAll(IDBKeyRange.bound(p,S,!1,!1))]}),{mode:t})).flat();this.getAllSince=async(e,{mode:t="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:t});this.get=async(e,{transaction:t,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:t});this.set=async(e,{transaction:t}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:t})};this.setAll=async(e,{transaction:t}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:t})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:t})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:t})}}};var oo=Ve(et(),1);var hn=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let t=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return t?(this.cached=t,t):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,oo.default)(),userId:void 0,ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:t}={})=>{let r=await this.get({transaction:t});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",t=>t.put(e),{mode:"readwrite"})}}};var pn=class{constructor(i){this.meta=i;this.createOperation=async i=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:i.operations.map(en)}};this.createMigrationOperation=async({targetVersion:i,...e})=>{let t=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(i)})),timestamp:this.meta.time.zero(i),replicaId:t.id}};this.createSyncStep1=async i=>{let e=await this.meta.localReplica.get(),t=i===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;t?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push(en(a)),o.add($(a.oid))},{after:t,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push(en(a)),o.add($(a.oid))},{mode:"readwrite"});let s=[];return t||(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:t}};this.createPresenceUpdate=async i=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:i,replicaId:e.id}};this.createHeartbeat=async()=>{let i=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:i}}}};var mn=class extends se{constructor(e,t){super(e,t);this.iterateOverAllOperationsForDocument=async(e,t,{to:r,from:o,after:s,mode:a="readonly",transaction:f}={})=>{let p=(f||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),S=p.index("d_t"),w=o||s,C=w?ue(e,w):qe(e),g=r?ue(e,r):Ke(e),v=IDBKeyRange.bound(C,g,!!s,!1),_=S.openCursor(v,"next");return new Promise((I,O)=>{let R;_.onsuccess=b=>{let D=_.result;if(D){let d=D.value;L(d.oid.startsWith(e)),L(R===void 0||R<=d.timestamp,`expected ${R} <= ${d.timestamp}`),t(d,p),R=d.timestamp,D.continue()}else I()},_.onerror=b=>{if(de(_.error)){I();return}else O(_.error)}})};this.iterateOverAllOperationsForEntity=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let u=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),p=r?ue(e,r):qe(e),S=o?ue(e,o):Ke(e),w=IDBKeyRange.bound(p,S,!!r,!1),C=u.openCursor(w,"next");return new Promise((g,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(R.oid.startsWith(e)),L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),t(R,u),_=R.timestamp,O.continue()}else g()},C.onerror=I=>{de(C.error)?g():v(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let f=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",u=>u.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,{mode:s,transaction:f})};this.iterateOverAllLocalOperations=async(e,{before:t,after:r,mode:o="readonly",transaction:s})=>{let f=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),u=f.index("l_t"),p=r?ue(!0,r):qe(!0),S=t?ue(!0,t):Ke(!0),w=IDBKeyRange.bound(p,S,!!r,!0),C=u.openCursor(w,"next");return new Promise((g,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),e(R,f),_=R.timestamp,O.continue()}else g()},C.onerror=I=>{de(C.error)?g():v(C.error)}})};this.iterateOverAllOperations=async(e,{before:t,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let f=s?qe(s):void 0,u=t?Ke(t):void 0,p=f&&u?IDBKeyRange.bound(f,u,!1,!0):f?IDBKeyRange.lowerBound(f,!1):u?IDBKeyRange.upperBound(u,!0):void 0;return a.index("timestamp").openCursor(p,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:t}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:t});this.addCompoundIndexes=e=>({...e,oid_timestamp:ue(e.oid,e.timestamp),l_t:ue(e.isLocal,e.timestamp),d_t:ue($(e.oid),e.timestamp)});this.insert=async(e,{transaction:t})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:t}),Array.from(r)};this.reset=()=>this.clear("operations")}};var gn=class{constructor(i,e){this.db=i;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 J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async i=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(i)});this.cached=i,await J(o)}}};var Dt=class extends z{constructor({disableRebasing:e,context:t,onOperation:r}){super();this.time=new Vt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,t={})=>un(this.db,e,t.write?"readwrite":"readonly",t.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let t=new Set,r=$(e);L(r===e,"Must be root document OID"),t.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{t.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{t.add(s.oid)},{transaction:o})]),Array.from(t)};this.getAllCollectionRelatedOids=async e=>{let t=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{t.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{t.add(o.oid)},{transaction:r})]),Array.from(t)};this.getDocumentSnapshot=async(e,t={})=>{let r=$(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let u of s)u.snapshot&&N(u.snapshot,u.oid),a.set(u.oid,u.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,u=>{let p=a.get(u.oid)||void 0,S=ze(p,u.data);S&&N(S,u.oid),a.set(u.oid,S)},{transaction:o,to:t.to||this.now});let f=a.get(r);return f&&Zt(f,a),f};this.getDocumentData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],t),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.getDocumentAuthz=async e=>{let t=await this.baselines.get(e);if(t)return t.authz;let r;return await this.operations.iterateOverAllOperationsForEntity(e,o=>{if(o.data.op==="initialize")return r=o.authz,!0},{}),r};this.ack=async e=>{let t=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:t.id,timestamp:e}),!this._closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase(),this.onOperation&&e.forEach(o=>this.onOperation(o))};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),t);return this.ack(e[e.length-1].timestamp),this.onOperation&&e.forEach(o=>this.onOperation(o)),r};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,t);let r=new Set;return e.forEach(o=>{r.add($(o.oid))}),Array.from(r)};this.insertData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],{...t,write:!0});e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!t?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};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 t,r=new Set,o=this.createTransaction(["baselines","operations"],{write:!0}),s=0;if(await this.operations.iterateOverAllOperations(f=>{r.add(f.oid),t=f.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let f of r)a.push(await this.rebase(f,t||e,o));this.emit("rebase",a)};this.rebase=async(e,t,r)=>{let o=(await this.localReplica.get()).id;this.log("debug","[",o,"]","Rebasing",e,"up to",t);let s=r||this.createTransaction(["operations","baselines"],{write:!0}),a=await this.baselines.get(e,{transaction:s}),f=a?.snapshot||void 0,u=0,p=a?.authz,S=[];await this.operations.iterateOverAllOperationsForEntity(e,(C,g)=>{(!a||C.timestamp>a.timestamp)&&(f=ze(f,C.data,S),C.data.op==="initialize"&&(p=C.authz)),u++,g.delete(C.oid_timestamp)},{to:t,transaction:s}),f&&N(f,e);let w={oid:e,snapshot:f,timestamp:t,authz:p};if(w.snapshot?await this.baselines.set(w,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",t,":",f,"and deleted",u,"operations"),S.length){let C=S.filter(we);C.length&&this.emit("filesDeleted",C)}return w};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,t)=>{let r=await this.schema.get();if(r&&t===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
4
|
+
`)},_domwindow:function(){return m("domwindow")},_bigint:function(l){return m("bigint:"+l.toString())},_process:function(){return m("process")},_timer:function(){return m("timer")},_pipe:function(){return m("pipe")},_tcp:function(){return m("tcp")},_udp:function(){return m("udp")},_tty:function(){return m("tty")},_statwatcher:function(){return m("statwatcher")},_securecontext:function(){return m("securecontext")},_connection:function(){return m("connection")},_zlib:function(){return m("zlib")},_context:function(){return m("context")},_nodescript:function(){return m("nodescript")},_httpparser:function(){return m("httpparser")},_dataview:function(){return m("dataview")},_signal:function(){return m("signal")},_fsevent:function(){return m("fsevent")},_tlswrap:function(){return m("tlswrap")}}}function R(){return{buf:"",write:function(b){this.buf+=b},end:function(b){this.buf+=b},read:function(){return this.buf}}}e.writeToStream=function(b,D,f){return f===void 0&&(f=D,D={}),O(D=_(b,D),f).dispatch(b)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){(function(w){"use strict";var C=typeof Uint8Array<"u"?Uint8Array:Array,g="+".charCodeAt(0),v="/".charCodeAt(0),_="0".charCodeAt(0),I="a".charCodeAt(0),O="A".charCodeAt(0),R="-".charCodeAt(0),b="_".charCodeAt(0);function D(f){return f=f.charCodeAt(0),f===g||f===R?62:f===v||f===b?63:f<_?-1:f<_+10?f-_+26+26:f<O+26?f-O:f<I+26?f-I+26:void 0}w.toByteArray=function(f){var m,l;if(0<f.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var x=f.length,x=f.charAt(x-2)==="="?2:f.charAt(x-1)==="="?1:0,E=new C(3*f.length/4-x),j=0<x?f.length-4:f.length,k=0;function M(B){E[k++]=B}for(m=0;m<j;m+=4,0)M((16711680&(l=D(f.charAt(m))<<18|D(f.charAt(m+1))<<12|D(f.charAt(m+2))<<6|D(f.charAt(m+3))))>>16),M((65280&l)>>8),M(255&l);return x==2?M(255&(l=D(f.charAt(m))<<2|D(f.charAt(m+1))>>4)):x==1&&(M((l=D(f.charAt(m))<<10|D(f.charAt(m+1))<<4|D(f.charAt(m+2))>>2)>>8&255),M(255&l)),E},w.fromByteArray=function(f){var m,l,x,E,j=f.length%3,k="";function M(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(m=0,x=f.length-j;m<x;m+=3)l=(f[m]<<16)+(f[m+1]<<8)+f[m+2],k+=M((E=l)>>18&63)+M(E>>12&63)+M(E>>6&63)+M(63&E);switch(j){case 1:k=(k+=M((l=f[f.length-1])>>2))+M(l<<4&63)+"==";break;case 2:k=(k=(k+=M((l=(f[f.length-2]<<8)+f[f.length-1])>>10))+M(l>>4&63))+M(l<<2&63)+"="}return k}})(e===void 0?this.base64js={}:e)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(n,i,e){(function(t,r,g,s,a,d,u,p,S){var w=n("base64-js"),C=n("ieee754");function g(c,h,y){if(!(this instanceof g))return new g(c,h,y);var A,P,T,V,W=typeof c;if(h==="base64"&&W=="string")for(c=(V=c).trim?V.trim():V.replace(/^\s+|\s+$/g,"");c.length%4!=0;)c+="=";if(W=="number")A=te(c);else if(W=="string")A=g.byteLength(c,h);else{if(W!="object")throw new Error("First argument needs to be a number, array or string.");A=te(c.length)}if(g._useTypedArrays?P=g._augment(new Uint8Array(A)):((P=this).length=A,P._isBuffer=!0),g._useTypedArrays&&typeof c.byteLength=="number")P._set(c);else if(H(V=c)||g.isBuffer(V)||V&&typeof V=="object"&&typeof V.length=="number")for(T=0;T<A;T++)g.isBuffer(c)?P[T]=c.readUInt8(T):P[T]=c[T];else if(W=="string")P.write(c,0,h);else if(W=="number"&&!g._useTypedArrays&&!y)for(T=0;T<A;T++)P[T]=0;return P}function v(c,h,y,A){return g._charsWritten=jt(function(P){for(var T=[],V=0;V<P.length;V++)T.push(255&P.charCodeAt(V));return T}(h),c,y,A)}function _(c,h,y,A){return g._charsWritten=jt(function(P){for(var T,V,W=[],X=0;X<P.length;X++)V=P.charCodeAt(X),T=V>>8,V=V%256,W.push(V),W.push(T);return W}(h),c,y,A)}function I(c,h,y){var A="";y=Math.min(c.length,y);for(var P=h;P<y;P++)A+=String.fromCharCode(c[P]);return A}function O(c,h,y,T){T||(F(typeof y=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+1<c.length,"Trying to read beyond buffer length"));var P,T=c.length;if(!(T<=h))return y?(P=c[h],h+1<T&&(P|=c[h+1]<<8)):(P=c[h]<<8,h+1<T&&(P|=c[h+1])),P}function R(c,h,y,T){T||(F(typeof y=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+3<c.length,"Trying to read beyond buffer length"));var P,T=c.length;if(!(T<=h))return y?(h+2<T&&(P=c[h+2]<<16),h+1<T&&(P|=c[h+1]<<8),P|=c[h],h+3<T&&(P+=c[h+3]<<24>>>0)):(h+1<T&&(P=c[h+1]<<16),h+2<T&&(P|=c[h+2]<<8),h+3<T&&(P|=c[h+3]),P+=c[h]<<24>>>0),P}function b(c,h,y,A){if(A||(F(typeof y=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+1<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return A=O(c,h,y,!0),32768&A?-1*(65535-A+1):A}function D(c,h,y,A){if(A||(F(typeof y=="boolean","missing or invalid endian"),F(h!=null,"missing offset"),F(h+3<c.length,"Trying to read beyond buffer length")),!(c.length<=h))return A=R(c,h,y,!0),2147483648&A?-1*(4294967295-A+1):A}function f(c,h,y,A){return A||(F(typeof y=="boolean","missing or invalid endian"),F(h+3<c.length,"Trying to read beyond buffer length")),C.read(c,h,y,23,4)}function m(c,h,y,A){return A||(F(typeof y=="boolean","missing or invalid endian"),F(h+7<c.length,"Trying to read beyond buffer length")),C.read(c,h,y,52,8)}function l(c,h,y,A,P){if(P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+1<c.length,"trying to write beyond buffer length"),ti(h,65535)),P=c.length,!(P<=y))for(var T=0,V=Math.min(P-y,2);T<V;T++)c[y+T]=(h&255<<8*(A?T:1-T))>>>8*(A?T:1-T)}function x(c,h,y,A,P){if(P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+3<c.length,"trying to write beyond buffer length"),ti(h,4294967295)),P=c.length,!(P<=y))for(var T=0,V=Math.min(P-y,4);T<V;T++)c[y+T]=h>>>8*(A?T:3-T)&255}function E(c,h,y,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+1<c.length,"Trying to write beyond buffer length"),ni(h,32767,-32768)),c.length<=y||l(c,0<=h?h:65535+h+1,y,A,P)}function j(c,h,y,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+3<c.length,"Trying to write beyond buffer length"),ni(h,2147483647,-2147483648)),c.length<=y||x(c,0<=h?h:4294967295+h+1,y,A,P)}function k(c,h,y,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+3<c.length,"Trying to write beyond buffer length"),cr(h,34028234663852886e22,-34028234663852886e22)),c.length<=y||C.write(c,h,y,A,23,4)}function M(c,h,y,A,P){P||(F(h!=null,"missing value"),F(typeof A=="boolean","missing or invalid endian"),F(y!=null,"missing offset"),F(y+7<c.length,"Trying to write beyond buffer length"),cr(h,17976931348623157e292,-17976931348623157e292)),c.length<=y||C.write(c,h,y,A,52,8)}e.Buffer=g,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var c=new ArrayBuffer(0),h=new Uint8Array(c);return h.foo=function(){return 42},h.foo()===42&&typeof h.subarray=="function"}catch{return!1}}(),g.isEncoding=function(c){switch(String(c).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.isBuffer=function(c){return!(c==null||!c._isBuffer)},g.byteLength=function(c,h){var y;switch(c+="",h||"utf8"){case"hex":y=c.length/2;break;case"utf8":case"utf-8":y=Ee(c).length;break;case"ascii":case"binary":case"raw":y=c.length;break;case"base64":y=sr(c).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":y=2*c.length;break;default:throw new Error("Unknown encoding")}return y},g.concat=function(c,h){if(F(H(c),`Usage: Buffer.concat(list, [totalLength])
|
|
5
|
+
list should be an Array.`),c.length===0)return new g(0);if(c.length===1)return c[0];if(typeof h!="number")for(P=h=0;P<c.length;P++)h+=c[P].length;for(var y=new g(h),A=0,P=0;P<c.length;P++){var T=c[P];T.copy(y,A),A+=T.length}return y},g.prototype.write=function(c,h,y,A){isFinite(h)?isFinite(y)||(A=y,y=void 0):(X=A,A=h,h=y,y=X),h=Number(h)||0;var P,T,V,W,X=this.length-h;switch((!y||X<(y=Number(y)))&&(y=X),A=String(A||"utf8").toLowerCase()){case"hex":P=function(be,ie,re,Z){re=Number(re)||0;var G=be.length-re;(!Z||G<(Z=Number(Z)))&&(Z=G),F((G=ie.length)%2==0,"Invalid hex string"),G/2<Z&&(Z=G/2);for(var Ze=0;Ze<Z;Ze++){var lr=parseInt(ie.substr(2*Ze,2),16);F(!isNaN(lr),"Invalid hex string"),be[re+Ze]=lr}return g._charsWritten=2*Ze,Ze}(this,c,h,y);break;case"utf8":case"utf-8":T=this,V=h,W=y,P=g._charsWritten=jt(Ee(c),T,V,W);break;case"ascii":case"binary":P=v(this,c,h,y);break;case"base64":T=this,V=h,W=y,P=g._charsWritten=jt(sr(c),T,V,W);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":P=_(this,c,h,y);break;default:throw new Error("Unknown encoding")}return P},g.prototype.toString=function(c,h,y){var A,P,T,V,W=this;if(c=String(c||"utf8").toLowerCase(),h=Number(h)||0,(y=y!==void 0?Number(y):W.length)===h)return"";switch(c){case"hex":A=function(X,be,ie){var re=X.length;(!be||be<0)&&(be=0),(!ie||ie<0||re<ie)&&(ie=re);for(var Z="",G=be;G<ie;G++)Z+=K(X[G]);return Z}(W,h,y);break;case"utf8":case"utf-8":A=function(X,be,ie){var re="",Z="";ie=Math.min(X.length,ie);for(var G=be;G<ie;G++)X[G]<=127?(re+=ar(Z)+String.fromCharCode(X[G]),Z=""):Z+="%"+X[G].toString(16);return re+ar(Z)}(W,h,y);break;case"ascii":case"binary":A=I(W,h,y);break;case"base64":P=W,V=y,A=(T=h)===0&&V===P.length?w.fromByteArray(P):w.fromByteArray(P.slice(T,V));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":A=function(X,be,ie){for(var re=X.slice(be,ie),Z="",G=0;G<re.length;G+=2)Z+=String.fromCharCode(re[G]+256*re[G+1]);return Z}(W,h,y);break;default:throw new Error("Unknown encoding")}return A},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(c,h,y,A){if(h=h||0,(A=A||A===0?A:this.length)!==(y=y||0)&&c.length!==0&&this.length!==0){F(y<=A,"sourceEnd < sourceStart"),F(0<=h&&h<c.length,"targetStart out of bounds"),F(0<=y&&y<this.length,"sourceStart out of bounds"),F(0<=A&&A<=this.length,"sourceEnd out of bounds"),A>this.length&&(A=this.length);var P=(A=c.length-h<A-y?c.length-h+y:A)-y;if(P<100||!g._useTypedArrays)for(var T=0;T<P;T++)c[T+h]=this[T+y];else c._set(this.subarray(y,y+P),h)}},g.prototype.slice=function(c,h){var y=this.length;if(c=q(c,y,0),h=q(h,y,y),g._useTypedArrays)return g._augment(this.subarray(c,h));for(var A=h-c,P=new g(A,void 0,!0),T=0;T<A;T++)P[T]=this[T+c];return P},g.prototype.get=function(c){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(c)},g.prototype.set=function(c,h){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(c,h)},g.prototype.readUInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return this[c]},g.prototype.readUInt16LE=function(c,h){return O(this,c,!0,h)},g.prototype.readUInt16BE=function(c,h){return O(this,c,!1,h)},g.prototype.readUInt32LE=function(c,h){return R(this,c,!0,h)},g.prototype.readUInt32BE=function(c,h){return R(this,c,!1,h)},g.prototype.readInt8=function(c,h){if(h||(F(c!=null,"missing offset"),F(c<this.length,"Trying to read beyond buffer length")),!(c>=this.length))return 128&this[c]?-1*(255-this[c]+1):this[c]},g.prototype.readInt16LE=function(c,h){return b(this,c,!0,h)},g.prototype.readInt16BE=function(c,h){return b(this,c,!1,h)},g.prototype.readInt32LE=function(c,h){return D(this,c,!0,h)},g.prototype.readInt32BE=function(c,h){return D(this,c,!1,h)},g.prototype.readFloatLE=function(c,h){return f(this,c,!0,h)},g.prototype.readFloatBE=function(c,h){return f(this,c,!1,h)},g.prototype.readDoubleLE=function(c,h){return m(this,c,!0,h)},g.prototype.readDoubleBE=function(c,h){return m(this,c,!1,h)},g.prototype.writeUInt8=function(c,h,y){y||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"trying to write beyond buffer length"),ti(c,255)),h>=this.length||(this[h]=c)},g.prototype.writeUInt16LE=function(c,h,y){l(this,c,h,!0,y)},g.prototype.writeUInt16BE=function(c,h,y){l(this,c,h,!1,y)},g.prototype.writeUInt32LE=function(c,h,y){x(this,c,h,!0,y)},g.prototype.writeUInt32BE=function(c,h,y){x(this,c,h,!1,y)},g.prototype.writeInt8=function(c,h,y){y||(F(c!=null,"missing value"),F(h!=null,"missing offset"),F(h<this.length,"Trying to write beyond buffer length"),ni(c,127,-128)),h>=this.length||(0<=c?this.writeUInt8(c,h,y):this.writeUInt8(255+c+1,h,y))},g.prototype.writeInt16LE=function(c,h,y){E(this,c,h,!0,y)},g.prototype.writeInt16BE=function(c,h,y){E(this,c,h,!1,y)},g.prototype.writeInt32LE=function(c,h,y){j(this,c,h,!0,y)},g.prototype.writeInt32BE=function(c,h,y){j(this,c,h,!1,y)},g.prototype.writeFloatLE=function(c,h,y){k(this,c,h,!0,y)},g.prototype.writeFloatBE=function(c,h,y){k(this,c,h,!1,y)},g.prototype.writeDoubleLE=function(c,h,y){M(this,c,h,!0,y)},g.prototype.writeDoubleBE=function(c,h,y){M(this,c,h,!1,y)},g.prototype.fill=function(c,h,y){if(h=h||0,y=y||this.length,F(typeof(c=typeof(c=c||0)=="string"?c.charCodeAt(0):c)=="number"&&!isNaN(c),"value is not a number"),F(h<=y,"end < start"),y!==h&&this.length!==0){F(0<=h&&h<this.length,"start out of bounds"),F(0<=y&&y<=this.length,"end out of bounds");for(var A=h;A<y;A++)this[A]=c}},g.prototype.inspect=function(){for(var c=[],h=this.length,y=0;y<h;y++)if(c[y]=K(this[y]),y===e.INSPECT_MAX_BYTES){c[y+1]="...";break}return"<Buffer "+c.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var c=new Uint8Array(this.length),h=0,y=c.length;h<y;h+=1)c[h]=this[h];return c.buffer};var B=g.prototype;function q(c,h,y){return typeof c!="number"?y:h<=(c=~~c)?h:0<=c||0<=(c+=h)?c:0}function te(c){return(c=~~Math.ceil(+c))<0?0:c}function H(c){return(Array.isArray||function(h){return Object.prototype.toString.call(h)==="[object Array]"})(c)}function K(c){return c<16?"0"+c.toString(16):c.toString(16)}function Ee(c){for(var h=[],y=0;y<c.length;y++){var A=c.charCodeAt(y);if(A<=127)h.push(c.charCodeAt(y));else for(var P=y,T=(55296<=A&&A<=57343&&y++,encodeURIComponent(c.slice(P,y+1)).substr(1).split("%")),V=0;V<T.length;V++)h.push(parseInt(T[V],16))}return h}function sr(c){return w.toByteArray(c)}function jt(c,h,y,A){for(var P=0;P<A&&!(P+y>=h.length||P>=c.length);P++)h[P+y]=c[P];return P}function ar(c){try{return decodeURIComponent(c)}catch{return String.fromCharCode(65533)}}function ti(c,h){F(typeof c=="number","cannot write a non-number as a number"),F(0<=c,"specified a negative value for writing an unsigned value"),F(c<=h,"value is larger than maximum value for type"),F(Math.floor(c)===c,"value has a fractional component")}function ni(c,h,y){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(y<=c,"value smaller than minimum allowed value"),F(Math.floor(c)===c,"value has a fractional component")}function cr(c,h,y){F(typeof c=="number","cannot write a non-number as a number"),F(c<=h,"value larger than maximum allowed value"),F(y<=c,"value smaller than minimum allowed value")}function F(c,h){if(!c)throw new Error(h||"Failed assertion")}g._augment=function(c){return c._isBuffer=!0,c._get=c.get,c._set=c.set,c.get=B.get,c.set=B.set,c.write=B.write,c.toString=B.toString,c.toLocaleString=B.toString,c.toJSON=B.toJSON,c.copy=B.copy,c.slice=B.slice,c.readUInt8=B.readUInt8,c.readUInt16LE=B.readUInt16LE,c.readUInt16BE=B.readUInt16BE,c.readUInt32LE=B.readUInt32LE,c.readUInt32BE=B.readUInt32BE,c.readInt8=B.readInt8,c.readInt16LE=B.readInt16LE,c.readInt16BE=B.readInt16BE,c.readInt32LE=B.readInt32LE,c.readInt32BE=B.readInt32BE,c.readFloatLE=B.readFloatLE,c.readFloatBE=B.readFloatBE,c.readDoubleLE=B.readDoubleLE,c.readDoubleBE=B.readDoubleBE,c.writeUInt8=B.writeUInt8,c.writeUInt16LE=B.writeUInt16LE,c.writeUInt16BE=B.writeUInt16BE,c.writeUInt32LE=B.writeUInt32LE,c.writeUInt32BE=B.writeUInt32BE,c.writeInt8=B.writeInt8,c.writeInt16LE=B.writeInt16LE,c.writeInt16BE=B.writeInt16BE,c.writeInt32LE=B.writeInt32LE,c.writeInt32BE=B.writeInt32BE,c.writeFloatLE=B.writeFloatLE,c.writeFloatBE=B.writeFloatBE,c.writeDoubleLE=B.writeDoubleLE,c.writeDoubleBE=B.writeDoubleBE,c.fill=B.fill,c.inspect=B.inspect,c.toArrayBuffer=B.toArrayBuffer,c}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(n,i,e){(function(t,r,w,s,a,d,u,p,S){var w=n("buffer").Buffer,C=4,g=new w(C);g.fill(0),i.exports={hash:function(v,_,I,O){for(var R=_(function(l,x){l.length%C!=0&&(E=l.length+(C-l.length%C),l=w.concat([l,g],E));for(var E,j=[],k=x?l.readInt32BE:l.readInt32LE,M=0;M<l.length;M+=C)j.push(k.call(l,M));return j}(v=w.isBuffer(v)?v:new w(v),O),8*v.length),_=O,b=new w(I),D=_?b.writeInt32BE:b.writeInt32LE,f=0;f<R.length;f++)D.call(b,R[f],4*f,!0);return b}}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(n,i,e){(function(t,r,w,s,a,d,u,p,S){var w=n("buffer").Buffer,C=n("./sha"),g=n("./sha256"),v=n("./rng"),_={sha1:C,sha256:g,md5:n("./md5")},I=64,O=new w(I);function R(l,x){var E=_[l=l||"sha1"],j=[];return E||b("algorithm:",l,"is not yet supported"),{update:function(k){return w.isBuffer(k)||(k=new w(k)),j.push(k),k.length,this},digest:function(k){var M=w.concat(j),M=x?function(B,q,te){w.isBuffer(q)||(q=new w(q)),w.isBuffer(te)||(te=new w(te)),q.length>I?q=B(q):q.length<I&&(q=w.concat([q,O],I));for(var H=new w(I),K=new w(I),Ee=0;Ee<I;Ee++)H[Ee]=54^q[Ee],K[Ee]=92^q[Ee];return te=B(w.concat([H,te])),B(w.concat([K,te]))}(E,x,M):E(M);return j=null,k?M.toString(k):M}}}function b(){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 R(l)},e.createHmac=R,e.randomBytes=function(l,x){if(!x||!x.call)return new w(v(l));try{x.call(this,void 0,new w(v(l)))}catch(E){x(E)}};var D,f=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],m=function(l){e[l]=function(){b("sorry,",l,"is not implemented yet")}};for(D in f)m(f[D],D)}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){var w=n("./helpers");function C(b,D){b[D>>5]|=128<<D%32,b[14+(D+64>>>9<<4)]=D;for(var f=1732584193,m=-271733879,l=-1732584194,x=271733878,E=0;E<b.length;E+=16){var j=f,k=m,M=l,B=x,f=v(f,m,l,x,b[E+0],7,-680876936),x=v(x,f,m,l,b[E+1],12,-389564586),l=v(l,x,f,m,b[E+2],17,606105819),m=v(m,l,x,f,b[E+3],22,-1044525330);f=v(f,m,l,x,b[E+4],7,-176418897),x=v(x,f,m,l,b[E+5],12,1200080426),l=v(l,x,f,m,b[E+6],17,-1473231341),m=v(m,l,x,f,b[E+7],22,-45705983),f=v(f,m,l,x,b[E+8],7,1770035416),x=v(x,f,m,l,b[E+9],12,-1958414417),l=v(l,x,f,m,b[E+10],17,-42063),m=v(m,l,x,f,b[E+11],22,-1990404162),f=v(f,m,l,x,b[E+12],7,1804603682),x=v(x,f,m,l,b[E+13],12,-40341101),l=v(l,x,f,m,b[E+14],17,-1502002290),f=_(f,m=v(m,l,x,f,b[E+15],22,1236535329),l,x,b[E+1],5,-165796510),x=_(x,f,m,l,b[E+6],9,-1069501632),l=_(l,x,f,m,b[E+11],14,643717713),m=_(m,l,x,f,b[E+0],20,-373897302),f=_(f,m,l,x,b[E+5],5,-701558691),x=_(x,f,m,l,b[E+10],9,38016083),l=_(l,x,f,m,b[E+15],14,-660478335),m=_(m,l,x,f,b[E+4],20,-405537848),f=_(f,m,l,x,b[E+9],5,568446438),x=_(x,f,m,l,b[E+14],9,-1019803690),l=_(l,x,f,m,b[E+3],14,-187363961),m=_(m,l,x,f,b[E+8],20,1163531501),f=_(f,m,l,x,b[E+13],5,-1444681467),x=_(x,f,m,l,b[E+2],9,-51403784),l=_(l,x,f,m,b[E+7],14,1735328473),f=I(f,m=_(m,l,x,f,b[E+12],20,-1926607734),l,x,b[E+5],4,-378558),x=I(x,f,m,l,b[E+8],11,-2022574463),l=I(l,x,f,m,b[E+11],16,1839030562),m=I(m,l,x,f,b[E+14],23,-35309556),f=I(f,m,l,x,b[E+1],4,-1530992060),x=I(x,f,m,l,b[E+4],11,1272893353),l=I(l,x,f,m,b[E+7],16,-155497632),m=I(m,l,x,f,b[E+10],23,-1094730640),f=I(f,m,l,x,b[E+13],4,681279174),x=I(x,f,m,l,b[E+0],11,-358537222),l=I(l,x,f,m,b[E+3],16,-722521979),m=I(m,l,x,f,b[E+6],23,76029189),f=I(f,m,l,x,b[E+9],4,-640364487),x=I(x,f,m,l,b[E+12],11,-421815835),l=I(l,x,f,m,b[E+15],16,530742520),f=O(f,m=I(m,l,x,f,b[E+2],23,-995338651),l,x,b[E+0],6,-198630844),x=O(x,f,m,l,b[E+7],10,1126891415),l=O(l,x,f,m,b[E+14],15,-1416354905),m=O(m,l,x,f,b[E+5],21,-57434055),f=O(f,m,l,x,b[E+12],6,1700485571),x=O(x,f,m,l,b[E+3],10,-1894986606),l=O(l,x,f,m,b[E+10],15,-1051523),m=O(m,l,x,f,b[E+1],21,-2054922799),f=O(f,m,l,x,b[E+8],6,1873313359),x=O(x,f,m,l,b[E+15],10,-30611744),l=O(l,x,f,m,b[E+6],15,-1560198380),m=O(m,l,x,f,b[E+13],21,1309151649),f=O(f,m,l,x,b[E+4],6,-145523070),x=O(x,f,m,l,b[E+11],10,-1120210379),l=O(l,x,f,m,b[E+2],15,718787259),m=O(m,l,x,f,b[E+9],21,-343485551),f=R(f,j),m=R(m,k),l=R(l,M),x=R(x,B)}return Array(f,m,l,x)}function g(b,D,f,m,l,x){return R((D=R(R(D,b),R(m,x)))<<l|D>>>32-l,f)}function v(b,D,f,m,l,x,E){return g(D&f|~D&m,b,D,l,x,E)}function _(b,D,f,m,l,x,E){return g(D&m|f&~m,b,D,l,x,E)}function I(b,D,f,m,l,x,E){return g(D^f^m,b,D,l,x,E)}function O(b,D,f,m,l,x,E){return g(f^(D|~m),b,D,l,x,E)}function R(b,D){var f=(65535&b)+(65535&D);return(b>>16)+(D>>16)+(f>>16)<<16|65535&f}i.exports=function(b){return w.hash(b,C,16)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){var w;i.exports=w||function(C){for(var g,v=new Array(C),_=0;_<C;_++)!(3&_)&&(g=4294967296*Math.random()),v[_]=g>>>((3&_)<<3)&255;return v}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){var w=n("./helpers");function C(_,I){_[I>>5]|=128<<24-I%32,_[15+(I+64>>9<<4)]=I;for(var O,R,b,D=Array(80),f=1732584193,m=-271733879,l=-1732584194,x=271733878,E=-1009589776,j=0;j<_.length;j+=16){for(var k=f,M=m,B=l,q=x,te=E,H=0;H<80;H++){D[H]=H<16?_[j+H]:v(D[H-3]^D[H-8]^D[H-14]^D[H-16],1);var K=g(g(v(f,5),(K=m,R=l,b=x,(O=H)<20?K&R|~K&b:!(O<40)&&O<60?K&R|K&b|R&b:K^R^b)),g(g(E,D[H]),(O=H)<20?1518500249:O<40?1859775393:O<60?-1894007588:-899497514)),E=x,x=l,l=v(m,30),m=f,f=K}f=g(f,k),m=g(m,M),l=g(l,B),x=g(x,q),E=g(E,te)}return Array(f,m,l,x,E)}function g(_,I){var O=(65535&_)+(65535&I);return(_>>16)+(I>>16)+(O>>16)<<16|65535&O}function v(_,I){return _<<I|_>>>32-I}i.exports=function(_){return w.hash(_,C,20,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){function w(I,O){var R=(65535&I)+(65535&O);return(I>>16)+(O>>16)+(R>>16)<<16|65535&R}function C(I,O){var R,b=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),D=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),f=new Array(64);I[O>>5]|=128<<24-O%32,I[15+(O+64>>9<<4)]=O;for(var m,l,x=0;x<I.length;x+=16){for(var E=D[0],j=D[1],k=D[2],M=D[3],B=D[4],q=D[5],te=D[6],H=D[7],K=0;K<64;K++)f[K]=K<16?I[K+x]:w(w(w((l=f[K-2],v(l,17)^v(l,19)^_(l,10)),f[K-7]),(l=f[K-15],v(l,7)^v(l,18)^_(l,3))),f[K-16]),R=w(w(w(w(H,v(l=B,6)^v(l,11)^v(l,25)),B&q^~B&te),b[K]),f[K]),m=w(v(m=E,2)^v(m,13)^v(m,22),E&j^E&k^j&k),H=te,te=q,q=B,B=w(M,R),M=k,k=j,j=E,E=w(R,m);D[0]=w(E,D[0]),D[1]=w(j,D[1]),D[2]=w(k,D[2]),D[3]=w(M,D[3]),D[4]=w(B,D[4]),D[5]=w(q,D[5]),D[6]=w(te,D[6]),D[7]=w(H,D[7])}return D}var g=n("./helpers"),v=function(I,O){return I>>>O|I<<32-O},_=function(I,O){return I>>>O};i.exports=function(I){return g.hash(I,C,32,!0)}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){e.read=function(w,C,g,v,x){var I,O,R=8*x-v-1,b=(1<<R)-1,D=b>>1,f=-7,m=g?x-1:0,l=g?-1:1,x=w[C+m];for(m+=l,I=x&(1<<-f)-1,x>>=-f,f+=R;0<f;I=256*I+w[C+m],m+=l,f-=8);for(O=I&(1<<-f)-1,I>>=-f,f+=v;0<f;O=256*O+w[C+m],m+=l,f-=8);if(I===0)I=1-D;else{if(I===b)return O?NaN:1/0*(x?-1:1);O+=Math.pow(2,v),I-=D}return(x?-1:1)*O*Math.pow(2,I-v)},e.write=function(w,C,g,v,_,E){var O,R,b=8*E-_-1,D=(1<<b)-1,f=D>>1,m=_===23?Math.pow(2,-24)-Math.pow(2,-77):0,l=v?0:E-1,x=v?1:-1,E=C<0||C===0&&1/C<0?1:0;for(C=Math.abs(C),isNaN(C)||C===1/0?(R=isNaN(C)?1:0,O=D):(O=Math.floor(Math.log(C)/Math.LN2),C*(v=Math.pow(2,-O))<1&&(O--,v*=2),2<=(C+=1<=O+f?m/v:m*Math.pow(2,1-f))*v&&(O++,v/=2),D<=O+f?(R=0,O=D):1<=O+f?(R=(C*v-1)*Math.pow(2,_),O+=f):(R=C*Math.pow(2,f-1)*Math.pow(2,_),O=0));8<=_;w[g+l]=255&R,l+=x,R/=256,_-=8);for(O=O<<_|R,b+=_;0<b;w[g+l]=255&O,l+=x,O/=256,b-=8);w[g+l-x]|=128*E}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(n,i,e){(function(t,r,o,s,a,d,u,p,S){var w,C,g;function v(){}(t=i.exports={}).nextTick=(C=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,C?function(_){return window.setImmediate(_)}:g?(w=[],window.addEventListener("message",function(_){var I=_.source;I!==window&&I!==null||_.data!=="process-tick"||(_.stopPropagation(),0<w.length&&w.shift()())},!0),function(_){w.push(_),window.postMessage("process-tick","*")}):function(_){setTimeout(_,0)}),t.title="browser",t.browser=!0,t.env={},t.argv=[],t.on=v,t.addListener=v,t.once=v,t.off=v,t.removeListener=v,t.removeAllListeners=v,t.emit=v,t.binding=function(_){throw new Error("process.binding is not supported")},t.cwd=function(){return"/"},t.chdir=function(_){throw new Error("process.chdir is not supported")}}).call(this,n("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},n("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var Ge={};dr(Ge,{__addDisposableResource:()=>zo,__assign:()=>En,__asyncDelegator:()=>To,__asyncGenerator:()=>Fo,__asyncValues:()=>Bo,__await:()=>dt,__awaiter:()=>Do,__classPrivateFieldGet:()=>Lo,__classPrivateFieldIn:()=>Uo,__classPrivateFieldSet:()=>Vo,__createBinding:()=>Pn,__decorate:()=>Oo,__disposeResources:()=>No,__esDecorate:()=>Ea,__exportStar:()=>Co,__extends:()=>xo,__generator:()=>Eo,__importDefault:()=>Mo,__importStar:()=>jo,__makeTemplateObject:()=>ko,__metadata:()=>_o,__param:()=>Io,__propKey:()=>Pa,__read:()=>zi,__rest:()=>So,__runInitializers:()=>Ca,__setFunctionName:()=>Aa,__spread:()=>Po,__spreadArray:()=>Ro,__spreadArrays:()=>Ao,__values:()=>Cn,default:()=>Ta});function xo(n,i){if(typeof i!="function"&&i!==null)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");Ui(n,i);function e(){this.constructor=n}n.prototype=i===null?Object.create(i):(e.prototype=i.prototype,new e)}function So(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e}function Oo(n,i,e,t){var r=arguments.length,o=r<3?i:t===null?t=Object.getOwnPropertyDescriptor(i,e):t,s;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")o=Reflect.decorate(n,i,e,t);else for(var a=n.length-1;a>=0;a--)(s=n[a])&&(o=(r<3?s(o):r>3?s(i,e,o):s(i,e))||o);return r>3&&o&&Object.defineProperty(i,e,o),o}function Io(n,i){return function(e,t){i(e,t,n)}}function Ea(n,i,e,t,r,o){function s(I){if(I!==void 0&&typeof I!="function")throw new TypeError("Function expected");return I}for(var a=t.kind,d=a==="getter"?"get":a==="setter"?"set":"value",u=!i&&n?t.static?n:n.prototype:null,p=i||(u?Object.getOwnPropertyDescriptor(u,t.name):{}),S,w=!1,C=e.length-1;C>=0;C--){var g={};for(var v in t)g[v]=v==="access"?{}:t[v];for(var v in t.access)g.access[v]=t.access[v];g.addInitializer=function(I){if(w)throw new TypeError("Cannot add initializers after decoration has completed");o.push(s(I||null))};var _=(0,e[C])(a==="accessor"?{get:p.get,set:p.set}:p[d],g);if(a==="accessor"){if(_===void 0)continue;if(_===null||typeof _!="object")throw new TypeError("Object expected");(S=s(_.get))&&(p.get=S),(S=s(_.set))&&(p.set=S),(S=s(_.init))&&r.unshift(S)}else(S=s(_))&&(a==="field"?r.unshift(S):p[d]=S)}u&&Object.defineProperty(u,t.name,p),w=!0}function Ca(n,i,e){for(var t=arguments.length>2,r=0;r<i.length;r++)e=t?i[r].call(n,e):i[r].call(n);return t?e:void 0}function Pa(n){return typeof n=="symbol"?n:"".concat(n)}function Aa(n,i,e){return typeof i=="symbol"&&(i=i.description?"[".concat(i.description,"]"):""),Object.defineProperty(n,"name",{configurable:!0,value:e?"".concat(e," ",i):i})}function _o(n,i){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(n,i)}function Do(n,i,e,t){function r(o){return o instanceof e?o:new e(function(s){s(o)})}return new(e||(e=Promise))(function(o,s){function a(p){try{u(t.next(p))}catch(S){s(S)}}function d(p){try{u(t.throw(p))}catch(S){s(S)}}function u(p){p.done?o(p.value):r(p.value).then(a,d)}u((t=t.apply(n,i||[])).next())})}function Eo(n,i){var e={label:0,sent:function(){if(o[0]&1)throw o[1];return o[1]},trys:[],ops:[]},t,r,o,s;return s={next:a(0),throw:a(1),return:a(2)},typeof Symbol=="function"&&(s[Symbol.iterator]=function(){return this}),s;function a(u){return function(p){return d([u,p])}}function d(u){if(t)throw new TypeError("Generator is already executing.");for(;s&&(s=0,u[0]&&(e=0)),e;)try{if(t=1,r&&(o=u[0]&2?r.return:u[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,u[1])).done)return o;switch(r=0,o&&(u=[u[0]&2,o.value]),u[0]){case 0:case 1:o=u;break;case 4:return e.label++,{value:u[1],done:!1};case 5:e.label++,r=u[1],u=[0];continue;case 7:u=e.ops.pop(),e.trys.pop();continue;default:if(o=e.trys,!(o=o.length>0&&o[o.length-1])&&(u[0]===6||u[0]===2)){e=0;continue}if(u[0]===3&&(!o||u[1]>o[0]&&u[1]<o[3])){e.label=u[1];break}if(u[0]===6&&e.label<o[1]){e.label=o[1],o=u;break}if(o&&e.label<o[2]){e.label=o[2],e.ops.push(u);break}o[2]&&e.ops.pop(),e.trys.pop();continue}u=i.call(n,e)}catch(p){u=[6,p],r=0}finally{t=o=0}if(u[0]&5)throw u[1];return{value:u[0]?u[1]:void 0,done:!0}}}function Co(n,i){for(var e in n)e!=="default"&&!Object.prototype.hasOwnProperty.call(i,e)&&Pn(i,n,e)}function Cn(n){var i=typeof Symbol=="function"&&Symbol.iterator,e=i&&n[i],t=0;if(e)return e.call(n);if(n&&typeof n.length=="number")return{next:function(){return n&&t>=n.length&&(n=void 0),{value:n&&n[t++],done:!n}}};throw new TypeError(i?"Object is not iterable.":"Symbol.iterator is not defined.")}function zi(n,i){var e=typeof Symbol=="function"&&n[Symbol.iterator];if(!e)return n;var t=e.call(n),r,o=[],s;try{for(;(i===void 0||i-- >0)&&!(r=t.next()).done;)o.push(r.value)}catch(a){s={error:a}}finally{try{r&&!r.done&&(e=t.return)&&e.call(t)}finally{if(s)throw s.error}}return o}function Po(){for(var n=[],i=0;i<arguments.length;i++)n=n.concat(zi(arguments[i]));return n}function Ao(){for(var n=0,i=0,e=arguments.length;i<e;i++)n+=arguments[i].length;for(var t=Array(n),r=0,i=0;i<e;i++)for(var o=arguments[i],s=0,a=o.length;s<a;s++,r++)t[r]=o[s];return t}function Ro(n,i,e){if(e||arguments.length===2)for(var t=0,r=i.length,o;t<r;t++)(o||!(t in i))&&(o||(o=Array.prototype.slice.call(i,0,t)),o[t]=i[t]);return n.concat(o||Array.prototype.slice.call(i))}function dt(n){return this instanceof dt?(this.v=n,this):new dt(n)}function Fo(n,i,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(n,i||[]),r,o=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(w){t[w]&&(r[w]=function(C){return new Promise(function(g,v){o.push([w,C,g,v])>1||a(w,C)})})}function a(w,C){try{d(t[w](C))}catch(g){S(o[0][3],g)}}function d(w){w.value instanceof dt?Promise.resolve(w.value.v).then(u,p):S(o[0][2],w)}function u(w){a("next",w)}function p(w){a("throw",w)}function S(w,C){w(C),o.shift(),o.length&&a(o[0][0],o[0][1])}}function To(n){var i,e;return i={},t("next"),t("throw",function(r){throw r}),t("return"),i[Symbol.iterator]=function(){return this},i;function t(r,o){i[r]=n[r]?function(s){return(e=!e)?{value:dt(n[r](s)),done:!1}:o?o(s):s}:o}}function Bo(n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=n[Symbol.asyncIterator],e;return i?i.call(n):(n=typeof Cn=="function"?Cn(n):n[Symbol.iterator](),e={},t("next"),t("throw"),t("return"),e[Symbol.asyncIterator]=function(){return this},e);function t(o){e[o]=n[o]&&function(s){return new Promise(function(a,d){s=n[o](s),r(a,d,s.done,s.value)})}}function r(o,s,a,d){Promise.resolve(d).then(function(u){o({value:u,done:a})},s)}}function ko(n,i){return Object.defineProperty?Object.defineProperty(n,"raw",{value:i}):n.raw=i,n}function jo(n){if(n&&n.__esModule)return n;var i={};if(n!=null)for(var e in n)e!=="default"&&Object.prototype.hasOwnProperty.call(n,e)&&Pn(i,n,e);return Ra(i,n),i}function Mo(n){return n&&n.__esModule?n:{default:n}}function Lo(n,i,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof i=="function"?n!==i||!t:!i.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(n):t?t.value:i.get(n)}function Vo(n,i,e,t,r){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof i=="function"?n!==i||!r:!i.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?r.call(n,e):r?r.value=e:i.set(n,e),e}function Uo(n,i){if(i===null||typeof i!="object"&&typeof i!="function")throw new TypeError("Cannot use 'in' operator on non-object");return typeof n=="function"?i===n:n.has(i)}function zo(n,i,e){if(i!=null){if(typeof i!="object"&&typeof i!="function")throw new TypeError("Object expected.");var t;if(e){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");t=i[Symbol.asyncDispose]}if(t===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");t=i[Symbol.dispose]}if(typeof t!="function")throw new TypeError("Object not disposable.");n.stack.push({value:i,dispose:t,async:e})}else e&&n.stack.push({async:!0});return i}function No(n){function i(t){n.error=n.hasError?new Fa(t,n.error,"An error was suppressed during disposal."):t,n.hasError=!0}function e(){for(;n.stack.length;){var t=n.stack.pop();try{var r=t.dispose&&t.dispose.call(t.value);if(t.async)return Promise.resolve(r).then(e,function(o){return i(o),e()})}catch(o){i(o)}}if(n.hasError)throw n.error}return e()}var Ui,En,Pn,Ra,Fa,Ta,Ye=ls(()=>{Ui=function(n,i){return Ui=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Ui(n,i)};En=function(){return En=Object.assign||function(i){for(var e,t=1,r=arguments.length;t<r;t++){e=arguments[t];for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(i[o]=e[o])}return i},En.apply(this,arguments)};Pn=Object.create?function(n,i,e,t){t===void 0&&(t=e);var r=Object.getOwnPropertyDescriptor(i,e);(!r||("get"in r?!i.__esModule:r.writable||r.configurable))&&(r={enumerable:!0,get:function(){return i[e]}}),Object.defineProperty(n,t,r)}:function(n,i,e,t){t===void 0&&(t=e),n[t]=i[e]};Ra=Object.create?function(n,i){Object.defineProperty(n,"default",{enumerable:!0,value:i})}:function(n,i){n.default=i};Fa=typeof SuppressedError=="function"?SuppressedError:function(n,i,e){var t=new Error(e);return t.name="SuppressedError",t.error=n,t.suppressed=i,t};Ta={__extends:xo,__assign:En,__rest:So,__decorate:Oo,__param:Io,__metadata:_o,__awaiter:Do,__generator:Eo,__createBinding:Pn,__exportStar:Co,__values:Cn,__read:zi,__spread:Po,__spreadArrays:Ao,__spreadArray:Ro,__await:dt,__asyncGenerator:Fo,__asyncDelegator:To,__asyncValues:Bo,__makeTemplateObject:ko,__importStar:jo,__importDefault:Mo,__classPrivateFieldGet:Lo,__classPrivateFieldSet:Vo,__classPrivateFieldIn:Uo,__addDisposableResource:zo,__disposeResources:No}});var Ko=oe($o=>{"use strict";Object.defineProperty($o,"__esModule",{value:!0})});var $i=oe(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.invokeEventHandlersAsync=De.invokeEventHandlers=De.eventHandlerSafeInvokeAsync=De.eventHandlerSafeInvoke=void 0;var qo=(Ye(),et(Ge));function Ho(n,i,e){try{return n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}}De.eventHandlerSafeInvoke=Ho;function Ni(n,i,e){return(0,qo.__awaiter)(this,void 0,void 0,function*(){try{return yield n(i,e),{succeeded:!0}}catch(t){return{error:t,succeeded:!1}}})}De.eventHandlerSafeInvokeAsync=Ni;function Ba(n,i,e,t){for(let r of n){let{succeeded:o,error:s}=Ho(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}}De.invokeEventHandlers=Ba;function ka(n,i,e,t){return(0,qo.__awaiter)(this,void 0,void 0,function*(){if(t?.parallelize===!1)for(let r of n){let{succeeded:o,error:s}=yield Ni(r,i,e);if(!o&&t?.swallowExceptions!==!0)throw s}else{let r=[];for(let o of n)r.push(Ni(o,i,e).then(({succeeded:s,error:a})=>{if(!s&&t?.swallowExceptions!==!0)throw a}));yield Promise.all(r)}})}De.invokeEventHandlersAsync=ka});var Jo=oe(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.TypedEvent=void 0;var ja=(Ye(),et(Ge)),Wo=$i(),Qo={swallowExceptions:!1,parallelize:!0},Ki=class{constructor(){this._handlers=[]}attach(i){this._handlers.push(i)}detach(i){this.tryRemoveHandler(i)}invoke(i,e,t=Qo){(0,Wo.invokeEventHandlers)(this._handlers,i,e,t)}invokeAsync(i,e,t=Qo){return(0,ja.__awaiter)(this,void 0,void 0,function*(){yield(0,Wo.invokeEventHandlersAsync)(this._handlers,i,e,t)})}tryRemoveHandler(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}};An.TypedEvent=Ki});var Hi=oe(qi=>{"use strict";Object.defineProperty(qi,"__esModule",{value:!0});var Ma=(Ye(),et(Ge));(0,Ma.__exportStar)(Jo(),qi)});var Go=oe(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.FinalizationRegistryMissingError=void 0;var Wi=class extends Error{};Rn.FinalizationRegistryMissingError=Wi});var Ji=oe(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.WeakHandlerHolder=void 0;var La=Go(),Qi=class{constructor(i){this._refs=[];try{this._finalizationRegistry=new FinalizationRegistry(i)}catch(e){throw e.name==="FinalizationRegistry"?new La.FinalizationRegistryMissingError("FinalizationRegistry is not defined. Weak Events cannot be used. Please consult 'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/FinalizationRegistry' for compatibility information"):e}}getWeakHandler(i,e){let t=new WeakRef(e);return this._finalizationRegistry.register(e,{eventSource:i,handlerRef:t},t),this._refs.push(t),t}releaseWeakHandler(i){let t=this._refs.find(r=>r?.deref()===i)||new WeakRef(i);return this._finalizationRegistry.unregister(t),t}unregisterRef(i){this._finalizationRegistry.unregister(i)}};Fn.WeakHandlerHolder=Qi});var Yo=oe(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.WeakEvent=void 0;var Gi=(Ye(),et(Ge)),Va=Hi(),Ua=Ji(),Yi=$i(),za={swallowExceptions:!1,parallelize:!0},Xi=class{constructor(){this._handlers=[],this._handlerFinalizedEvent=new Va.TypedEvent,this.handlerFinalizedEvent=this._handlerFinalizedEvent,this._refHolder=new Ua.WeakHandlerHolder(i=>{this.onHandlerFinalizer(i)})}invoke(i,e,t){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=(0,Yi.eventHandlerSafeInvoke)(o,i,e);if(!s&&t?.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}}invokeAsync(i,e,t=za){return(0,Gi.__awaiter)(this,void 0,void 0,function*(){t?.parallelize===!1?yield this.sequentialInvokeAsync(i,e,t):yield this.parallelInvokeAsync(i,e,t)})}sequentialInvokeAsync(i,e,t){return(0,Gi.__awaiter)(this,void 0,void 0,function*(){for(let r of this._handlers){let o=r?.deref();if(o){let{succeeded:s,error:a}=yield(0,Yi.eventHandlerSafeInvokeAsync)(o,i,e);if(!s&&t.swallowExceptions!==!0)throw a}else this.releaseHandler(r)}})}parallelInvokeAsync(i,e,t){return(0,Gi.__awaiter)(this,void 0,void 0,function*(){let r=[];for(let o of this._handlers){let s=o?.deref();s?r.push((0,Yi.eventHandlerSafeInvokeAsync)(s,i,e).then(({succeeded:a,error:d})=>{if(!a&&t.swallowExceptions!==!0)throw d})):this.releaseHandler(o)}yield Promise.all(r)})}attach(i){this._handlers.push(this._refHolder.getWeakHandler(this,i))}detach(i){let e=this._refHolder.releaseWeakHandler(i);this.tryRemoveHandlerRef(e)}onHandlerFinalizer(i){this.tryRemoveHandlerRef(i?.handlerRef),this._handlerFinalizedEvent.invokeAsync(this,i,{swallowExceptions:!0})}tryRemoveHandlerRef(i){let e=this._handlers.findIndex(t=>t===i);e>=0&&this._handlers.splice(e,1)}releaseHandler(i){this._refHolder.unregisterRef(i),this.tryRemoveHandlerRef(i)}};Tn.WeakEvent=Xi});var Zo=oe(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});var Xo=(Ye(),et(Ge));(0,Xo.__exportStar)(Ji(),Bn);(0,Xo.__exportStar)(Yo(),Bn)});var es=oe(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});var Zi=(Ye(),et(Ge));(0,Zi.__exportStar)(Ko(),Ft);(0,Zi.__exportStar)(Hi(),Ft);(0,Zi.__exportStar)(Zo(),Ft)});var or={};dr(or,{Client:()=>Xe,ClientDescriptor:()=>ei,Entity:()=>he,EntityFile:()=>fe,MigrationPathError:()=>at,ServerSync:()=>ft,Storage:()=>Xe,StorageDescriptor:()=>ei,UndoHistory:()=>Je,authorization:()=>tc,cliSync:()=>nc,collection:()=>Ci,createDefaultMigration:()=>Pi,createMigration:()=>Ai,id:()=>ec,migrate:()=>sn,schema:()=>It});var Er=Be(Ne(),1),Kt=4,gt=36;function Or(n){return n.toString(gt).padStart(Kt,"0")}function gs(n){return n.toString().padStart(6,"0")}var Ut=class{constructor(){this.latest={time:Date.now(),counter:0,node:ys()},this.zeroCounter=0,this.now=i=>(this.latest=_r(this.latest),this.get(i,this.latest)),this.OLD_now=i=>(this.latest=_r(this.latest),gs(i)+ws(this.latest)),this.timerState=()=>this.latest,this.update=i=>{let e=i.slice(Kt);this.latest=bs(this.latest,Cr(e))},this.get=(i,e)=>Or(i)+Ir(e),this.zero=i=>Or(i)+Ir({time:0,counter:this.zeroCounter++,node:this.latest.node}),this.getWallClockTime=di}},zt=class extends Error{constructor(...i){super(),this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(i).join(" ")}},Nt=class extends Error{constructor(){super(),this.type="OverflowError",this.message="timestamp counter overflow"}},ai=4,ci=7,$t=60*1e3,mt=9;function ys(){return Er.default.slug().padStart(ci,"0").slice(0,ci)}function Ir(n){let i=new Date(n.time).getTime().toString(gt).padStart(mt,"0"),e=n.counter.toString(gt).padStart(ai,"0"),t=n.node.padStart(ci,"0");return`${i}${e}${t}`}function _r(n){let i=Date.now(),e=Math.max(n.time,i),t=n.time===e?n.counter+1:0;if(e-i>$t)throw new zt(e,i,$t);if(t>65535)throw new Nt;return{time:e,counter:t,node:n.node}}function bs(n,i){let e=Date.now(),t=Math.max(e,Math.max(n.time,i.time)),r=Math.max(n.counter,i.counter),o;if(n.time===t&&i.time===t?o=r+1:n.time===t?o=n.counter+1:i.time===t?o=i.counter+1:o=0,t-e>$t)throw new zt(t,e,$t);if(o>65535)throw new Nt;return{time:t,counter:o,node:n.node}}function Cr(n){let i=n.slice(0,mt),e=n.slice(mt,mt+ai),t=n.slice(mt+ai),r=parseInt(i,gt),o=parseInt(e,gt);if(isNaN(r)||isNaN(o))throw new Error("invalid clock format");return{time:r,counter:o,node:t}}function ws(n){let i=new Date(n.time).toISOString(),e=n.counter.toString(16).toUpperCase().padStart(4,"0"),t=n.node.padStart(16,"0");return`${i}-${e}-${t}`}function Dr(n){return parseInt(n.slice(0,Kt),36)}function li(n,i){return Dr(n)-Dr(i)}function di(n){return Cr(n.slice(Kt)).time}var qt,vs=new Uint8Array(16);function ui(){if(!qt&&(qt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!qt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return qt(vs)}var Pr=/^(?:[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 xs(n){return typeof n=="string"&&Pr.test(n)}var Ar=xs;var ee=[];for(Ht=0;Ht<256;++Ht)ee.push((Ht+256).toString(16).substr(1));var Ht;function Ss(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(ee[n[i+0]]+ee[n[i+1]]+ee[n[i+2]]+ee[n[i+3]]+"-"+ee[n[i+4]]+ee[n[i+5]]+"-"+ee[n[i+6]]+ee[n[i+7]]+"-"+ee[n[i+8]]+ee[n[i+9]]+"-"+ee[n[i+10]]+ee[n[i+11]]+ee[n[i+12]]+ee[n[i+13]]+ee[n[i+14]]+ee[n[i+15]]).toLowerCase();if(!Ar(e))throw TypeError("Stringified UUID is invalid");return e}var Rr=Ss;function Os(n,i,e){n=n||{};var t=n.random||(n.rng||ui)();if(t[6]=t[6]&15|64,t[8]=t[8]&63|128,i){e=e||0;for(var r=0;r<16;++r)i[e+r]=t[r];return i}return Rr(t)}var yt=Os;function Q(n){return Oe(n)||we(n)}function tt(n,i){return n===i?!0:!(!Q(n)||!Q(i)||n["@@type"]!==i["@@type"]||n.id!==i.id)}var Is="/",bt=":",hi=new WeakMap;function ne(n){let i=me(n);return L(!!i,`Object ${JSON.stringify(n)} does not have an OID assigned to it`),i}function me(n){if(U(n))return hi.get(n)}function N(n,i){return L(U(n),`Only objects can be assigned OIDs, received ${JSON.stringify(n)}`),pi(n)&&Jt(n),hi.set(n,i),n}function pi(n){return!!me(n)}function Jt(n){return hi.delete(n),n}function mi(n,i,e){if(pi(n))return ne(n);{let t=ve(i,e);return N(n,t),t}}function Fr(n,i,e){if(pi(n)){let t=ne(n);if(Ce(t,i))return ne(n);{let r=ve(i,e);return N(n,r),r}}else{let t=ve(i,e);return N(n,t),t}}var fi={".":"˙","/":"&slash;",":":":"};function Tr(n){return n.replace(/[/]/g,fi["/"]).replace(/[:]/g,fi[":"]).replace(/[.]/g,fi["."])}function Br(n){return n.replace(/&slash;/g,"/").replace(/:/g,":").replace(/˙/g,".")}function Y(n,i,e){let t=Tr(n)+Is+Tr(i);return e&&(t+=bt+e),t}function ve(n,i=_s){let{collection:e,id:t}=ce(n);return Y(e,t,i())}function ce(n){let[i,e,...t]=n.split("/");t.length&&(console.error(`OID ${n} has more than 3 segments. Attempting to parse it anyway.`),e+="/"+t.join("/"));let[r,o]=e.split(bt),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Br(i),id:Br(s),subId:o}}function nt(n,i){let e=ne(n);if(Array.isArray(n)){let t;for(let r=0;r<n.length;r++)t=n[r],U(t)&&!Q(t)&&(Fr(t,e,i),nt(t,i))}else if(U(n)&&!Q(n))for(let t of Object.keys(n))U(n[t])&&!Q(n[t])&&(Fr(n[t],e,i),nt(n[t],i))}function Wt(n){if(Jt(n),Array.isArray(n))for(let i=0;i<n.length;i++)Wt(n[i]);else if(U(n))for(let i of Object.keys(n))Wt(n[i])}function _s(){return yt().slice(0,8)}function ae(n){return{"@@type":"ref",id:n}}function Qt(n,i=new Map){if(Array.isArray(n)){let e=ne(n),t=N([],e);for(let r=0;r<n.length;r++){let o=n[r];if(U(o)){if(Oe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o)){t[r]=o;continue}else{let s=ne(o);t[r]=ae(s),Qt(o,i)}}else t[r]=o}i.set(e,t)}else if(U(n)&&!Q(n)){let e=ne(n),t=N({},e);for(let r of Object.keys(n)){let o=n[r];if(U(o)){if(Oe(o))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(we(o))t[r]=o;else{let s=ne(o);t[r]=ae(s),Qt(o,i)}}else t[r]=o}i.set(e,t)}else Q(n);return i}function $(n){return n.split(".")[0].split(bt)[0]}function gi(n){let i=$(n),e=ve(i,()=>"\uFFFF");return[`${i}${bt}`,e]}function Ce(n,i){return $(n)===$(i)}function Gt(n){return!n.includes(bt)}var Lr=Be(Mr(),1);function Ds(n,i){return typeof i!="object"||i===null||Array.isArray(i)?i:Object.fromEntries(Object.entries(i).sort(([e],[t])=>e<t?-1:e>t?1:0))}function wt(n){return JSON.stringify(n,Ds)}function le(n,i=!0){if(U(n)||Array.isArray(n)){let e=me(n),t;if(Array.isArray(n))t=n.map(r=>le(r,i));else{t={};for(let[r,o]of Object.entries(n))t[r]=le(o,i)}return i&&e&&N(t,e),t}return n}function ke(n){return(0,Lr.default)(n)}function U(n){return n&&typeof n=="object"}function Vr(n){for(var i=[],e=[n],t=0;e.length;){var r=e.pop();if(typeof r=="boolean")t+=4;else if(typeof r=="string")t+=r.length*2;else if(typeof r=="number")t+=8;else if(typeof r=="object"&&i.indexOf(r)===-1){i.push(r);for(var o in r)e.push(r[o])}}return t}function L(n,i="assertion failed"){if(!n)throw new Error(i)}function Yt(n=16){return yt().replace("-","").slice(0,n)}function Ur(n,i){for(let e=n.length-1;e>=0;e--)if(i(n[e]))return e;return-1}function zr(n,i){let e;return function(...t){let r=this;clearTimeout(e),e=setTimeout(()=>n.apply(r,t),i)}}function Nr(n,i){let e=0,t;return function(...r){let o=this,s=Date.now();s-e>=i?(e=s,n.apply(o,r),clearTimeout(t)):(clearTimeout(t),t=setTimeout(()=>{e=s,n.apply(o,r)},i))}}function we(n){return n&&n["@@type"]==="file"}function vt(n){return{"@@type":"file",id:n}}function it(n){return typeof File<"u"&&n instanceof File||typeof Blob<"u"&&n instanceof Blob}function Xt(n){return n&&U(n)&&typeof n.id=="string"&&typeof n.remote=="boolean"&&typeof n.name=="string"&&typeof n.type=="string"}var rt="__@@oid_do_not_use",Pe="@@id";function Es(n){if(U(n))return n[Pe]||n[rt]}function Cs(n){return U(n)&&(delete n[rt],delete n[Pe]),n}function Ps(n){let i=Es(n);i&&N(n,i)}function xt(n){if(Ps(n),Cs(n),Array.isArray(n))for(let i=0;i<n.length;i++)xt(n[i]);else if(U(n))for(let i of Object.keys(n))xt(n[i])}function As(n){let{collection:i,id:e,subId:t}=ce(n);return Y(i,e,t)}var Rs=/"\w+\/[^"]+?(\.[^"]+)+\:[\S]+?"/g;function Fs(n){return n.replaceAll(Rs,i=>{let e=i.slice(1,i.length-1);return`"${As(e)}"`})}function yi(n){return JSON.parse(Fs(JSON.stringify(n)))}function bi(n){let i=$(n);return[`${i}.`,`${i}.\uFFFF`]}function wi(n){return n===Pe||n===rt}function Oe(n){return n&&typeof n=="object"&&n["@@type"]==="ref"}function vi(n){return U(n)&&!Q(n)}function Ts(n,i){return n===i?!0:Q(n)&&Q(i)?tt(n,i):!1}function St(n,i,e,t,r=[],o){let s=o?.authz,a=ne(n);function d(u,p,S,w){if(!vi(p))Ts(p,S)||(w?r.push(Me({oid:a,timestamp:e(),data:{op:"list-set",index:u,value:p}},s)):r.push(Me({oid:a,timestamp:e(),data:{op:"set",name:u,value:p}},s)));else{let C=me(S),g=me(p);g&&!Ce(a,g)?(p=le(p,!1),g=ve(a,t),N(p,g)):o?.mergeUnknownObjects?!g&&C?(N(p,C),g=C):g=mi(p,a,t):g=mi(p,a,t),L(!!g,"Error: no value OID was resolved during diff. This is a bug in Verdant."),L(Ce(a,g),`Error: value OID ${g} is not related to parent OID ${a}. This is a bug in Verdant.`),S===void 0||g!==C?(Ae(p,g,e,t,r),r.push(Me({oid:a,timestamp:e(),data:{op:"set",name:u,value:ae(g)}},s)),C!==void 0&&r.push(Me({oid:C,timestamp:e(),data:{op:"delete"}},s))):St(S,p,e,t,r,o)}}if(Array.isArray(n)&&Array.isArray(i)){for(let p=0;p<i.length;p++){let S=i[p],w=n[p];d(p,S,w,!0)}let u=n.length-i.length;if(u>0){for(let p=i.length;p<n.length;p++){let S=n[p],w=me(S);w&&r.push(Me({oid:w,timestamp:e(),data:{op:"delete"}},s))}r.push(Me({oid:a,timestamp:e(),data:{op:"list-delete",index:i.length,count:u}},s))}}else{if(Array.isArray(n)||Array.isArray(i))throw new Error("Cannot diff an array with an object");if(vi(n)&&vi(i)){let u=new Set(Object.keys(n));for(let[p,S]of Object.entries(i)){if(S===void 0&&o?.defaultUndefined||(u.delete(p),wi(p)))continue;let w=n[p];d(p,S,w,!1)}if(!o?.defaultUndefined)for(let p of u)wi(p)||r.push(Me({oid:a,timestamp:e(),data:{op:"remove",name:p}},s))}}return r}function Ae(n,i,e,t,r=[],o){N(n,i),nt(n,t);let s=Qt(n);for(let a of s.keys()){let d=s.get(a),u={oid:a,timestamp:e(),data:{op:"initialize",value:Jt(d)}};r.push(Me(u,o?.authz))}return r}function Me(n,i){return i&&(n.authz=i),n}function Ot(n){let i={};for(let e of n)e.oid in i?i[e.oid].push(e):i[e.oid]=[e];return i}function Kr(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function qr(n){let i={};for(let e of n){let t=$(e.oid);t in i?i[t].push(e):i[t]=[e]}return i}function je(n){return Array.isArray(n)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(n)}. This suggests your data is changing from a list to an object over time. (OID: ${me(n)})`),!1)}function $e(n,i,e){if(n==null&&i.op!=="initialize")return n;let t=n,r,o;function s(a){e&&Q(a)&&e.push(a)}switch(i.op){case"set":s(t[i.name]),t[i.name]=i.value;break;case"remove":s(t[i.name]),delete t[i.name];break;case"list-set":je(n)&&(s(n[i.index]),n[i.index]=i.value);break;case"list-push":je(n)&&n.push(i.value);break;case"list-delete":je(n)&&(s(n[i.index]),n.splice(i.index,i.count));break;case"list-move-by-index":je(n)&&(o=n.splice(i.from,1),n.splice(i.to,0,o[0]));break;case"list-remove":if(je(n))do{let a=i.value;i.only==="last"?Oe(a)?r=Ur(n,d=>d.id===a.id):r=n.lastIndexOf(a):Oe(a)?r=n.findIndex(d=>d.id===a.id):r=n.indexOf(a),r!==-1&&(s(n[r]),n.splice(r,1))}while(!i.only&&r!==-1);break;case"list-add":je(n)&&(n.some(d=>Oe(d)&&Oe(i.value)?d.id===i.value.id:d===i.value)||n.push(i.value));break;case"list-move-by-ref":je(n)&&(r=n.findIndex(a=>tt(a,i.value)),o=n.splice(r,1),n.splice(i.index,0,o[0]));break;case"list-insert":if(je(n)){if(!i.value&&!i.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(i)}`);i.value?n.splice(i.index,0,i.value):n.splice(i.index,0,...i.values)}break;case"delete":Array.isArray(n)?n.forEach(s):U(n)&&Object.values(n||{}).forEach(s);return;case"initialize":return le(i.value);case"touch":return n;default:throw new Error(`Unsupported patch operation: ${i.op}`)}return n}function Zt(n,i,e=[]){if(Array.isArray(n))for(let t=0;t<n.length;t++){let r=n[t];n[t]=$r(r,i,e),U(n[t])&&Zt(n[t],i,e)}else if(!we(n)){if(U(n)){L(me(n),`Object ${JSON.stringify(n)} must have an oid`);for(let t of Object.keys(n))n[t]=$r(n[t],i,e),U(n[t])&&Zt(n[t],i,e)}}return e}function $r(n,i,e){if(Oe(n)){e.push(n.id);let t=i.get(n.id);return L(!!t,`No value was found in object map for ${n.id}`),N(t,n.id)}else return n}function Hr(n){return n.data.op==="set"?n.data.name:!1}function Wr(n,i){return i.has(!0)?!0:n.data.op==="set"||n.data.op==="remove"?i.has(n.data.name):!1}function en(n){return{oid:n.oid,timestamp:n.timestamp,data:n.data,authz:n.authz}}var Le;(function(n){n[n.Realtime=0]="Realtime",n[n.Push=1]="Push",n[n.PassiveRealtime=2]="PassiveRealtime",n[n.PassivePush=3]="PassivePush",n[n.ReadOnlyPull=4]="ReadOnlyPull",n[n.ReadOnlyRealtime=5]="ReadOnlyRealtime"})(Le||(Le={}));var Qr=Be(Ne(),1),Bs=n=>Object.assign({type:"object"},n),ks=n=>Object.assign({type:"array"},n),js=n=>Object.assign({type:"string"},n),Ms=n=>Object.assign({type:"number"},n),Ls=n=>Object.assign({type:"boolean"},n),Vs=n=>Object.assign({type:"any"},n),Us=n=>Object.assign({type:"map"},n),zs=n=>Object.assign({type:"file"},n),Ns=()=>({type:"string",default:Qr.default}),Jr={object:Bs,array:ks,string:js,number:Ms,boolean:Ls,any:Vs,map:Us,file:zs,id:Ns};var Zr=Be(Ne(),1);function xi(n){return n.equals!==void 0}function Si(n){return n.gte!==void 0||n.lte!==void 0||n.gt!==void 0||n.lt!==void 0}function $s(n){return!!n.match}function Oi(n){return n.startsWith!==void 0}function Gr(n){return!Si(n)&&!xi(n)&&!$s(n)&&!Oi(n)&&n.order}function xe(n){return n.type==="any"?!0:n.type==="map"?!1:n.nullable}function Re(n){return n?n.type==="map"||n.type==="array"?!0:n.type==="file"?!1:n.default!==void 0:!1}function _i(n){if(!(!n||!Re(n)))return n.type==="file"?xe(n)?null:void 0:n.type==="map"?{}:n.type==="array"?xe(n)?null:[]:n.type==="object"?xe(n)?null:void 0:typeof n.default=="function"?n.default():n.default}function Fe(n,i){for(let[e,t]of Object.entries(n.fields)){let r=Di(t);(r!==void 0&&i[e]===void 0||!xe(t)&&i[e]===null)&&(i[e]=r),i[e]&&Ke(i[e],t)}return i}function Ke(n,i){if(n==null)return n;if(i.type==="object")for(let[e,t]of Object.entries(i.properties)){if(n[e]===void 0){let r=Di(t);r!==void 0&&(n[e]=r)}Ke(n[e],t)}else if(i.type==="array")for(let e of n)Ke(e,i.items);else if(i.type==="map")for(let[e,t]of Object.entries(n))e===Pe||e===rt||Ke(t,i.values)}function Di(n){if(n.type==="string"||n.type==="number"||n.type==="boolean"||n.type==="any"){if(n.default&&typeof n.default=="function")return n.default();if(n.default!==void 0)return JSON.parse(JSON.stringify(n.default))}if(n.type==="array")return[];if(n.type==="map")return{};if(n.type!=="any"&&n.nullable)return null;if(n.type==="object"&&n.default){let i=typeof n.default=="function"?n.default():JSON.parse(JSON.stringify(n.default));for(let[e,t]of Object.entries(n.properties))i[e]===void 0&&(i[e]=Di(t));return i}}function Ei(n,i){for(let[e,t]of Object.entries(i))e===Pe||e===rt||(n.fields[e]?Ii(t,n.fields[e]):delete i[e]);return i}function Ii(n,i){if(U(n)&&i.type==="object")for(let[e,t]of Object.entries(n))i.properties[e]?Ii(t,i.properties[e]):delete n[e];else if(Array.isArray(n)&&i.type==="array")for(let e of n)Ii(e,i.items)}function Yr(n,i){for(let[e,t]of Object.entries(i))if(e!==Pe){if(!n[e])return{type:"invalid-key",fieldPath:[e],message:`Invalid field "${e}"`};if(t){let r=Te({field:n[e],value:t,fieldPath:[e]});if(r)return r}}}function Te({field:n,value:i,fieldPath:e=[],depth:t,requireDefaults:r}){if(!(t!==void 0&&t<=0)&&!(xe(n)&&i===null)){if(i===null&&(r||!Re(n)))return{type:"no-default",fieldPath:e,message:`Invalid null value for field ${Ie(e)}`};if(n.type==="object"){if(!U(i))return{type:"invalid-type",fieldPath:e,message:`Expected object ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};for(let[o,s]of Object.entries(n.properties))o!==Pe&&i[o]&&Te({field:s,value:i[o],fieldPath:[...e,o],depth:t!==void 0?t-1:void 0});for(let o of Object.keys(i))if(!n.properties[o])return{type:"invalid-key",fieldPath:[...e,o],message:`Invalid unexpected field "${o}" on value ${Ie(e)}`}}else if(n.type==="array"){if(!Array.isArray(i))return i===null&&n.nullable?void 0:{type:"invalid-value",fieldPath:e,message:`Expected array ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};for(let o of i)Te({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})}else if(n.type==="map"){if(!U(i))return{type:"invalid-type",fieldPath:e,message:`Expected map for field ${Ie(e)}, got ${i}`};for(let[o,s]of Object.entries(i))Te({field:n.values,value:s,fieldPath:[...e,o],depth:t!==void 0?t-1:void 0})}else if(n.type==="string"){if(typeof i!="string")return{type:"invalid-type",fieldPath:e,message:`Expected string ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`};if(n.options&&!n.options.includes(i))return{type:"invalid-value",fieldPath:e,message:`Expected one of ${n.options.join(", ")} for field ${Ie(e)}, got ${i}`}}else if(n.type==="boolean"){if(typeof i!="boolean")return{type:"invalid-type",fieldPath:e,message:`Expected boolean ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}else if(n.type==="number"){if(typeof i!="number")return{type:"invalid-type",fieldPath:e,message:`Expected number ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}else if(n.type==="file"&&!it(i)&&!Xt(i))return{type:"invalid-type",fieldPath:e,message:`Expected file ${n.nullable?"or null ":""}for field ${Ie(e)}, got ${i}`}}}function Ie(n){return n.length===0?"root":n.join(".")}function Xr(n,i){let e={};for(let[t,r]of Object.entries(i))n[t]&&(e[t]=tn({field:n[t],value:r,fieldPath:[t]}));return e}function tn({field:n,value:i,fieldPath:e=[],depth:t}){let r=Te({field:n,value:i,fieldPath:e,depth:t,requireDefaults:!0});if(r)throw new Error(`Validation error: ${r.message}`);if(n.type==="object"){if(!U(i))return i;let o={};for(let[s,a]of Object.entries(n.properties))o[s]=tn({field:a,value:i[s],fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else{if(n.type==="array")return Array.isArray(i)?i.map(o=>tn({field:n.items,value:o,fieldPath:[...e,"[]"],depth:t!==void 0?t-1:void 0})):i;if(n.type==="map"){if(!U(i))return i;let o={};for(let[s,a]of Object.entries(i))o[s]=tn({field:n.values,value:a,fieldPath:[...e,s],depth:t!==void 0?t-1:void 0});return o}else return i}}function Ve(n,i){var e;return n.type==="object"?n.properties[i]:n.type==="array"?n.items:n.type==="map"?n.values:n.type==="any"?n:"type"in n?null:(e=n[i])!==null&&e!==void 0?e:null}var Ks=function(n,i){var e={};for(var t in n)Object.prototype.hasOwnProperty.call(n,t)&&i.indexOf(t)<0&&(e[t]=n[t]);if(n!=null&&typeof Object.getOwnPropertySymbols=="function")for(var r=0,t=Object.getOwnPropertySymbols(n);r<t.length;r++)i.indexOf(t[r])<0&&Object.prototype.propertyIsEnumerable.call(n,t[r])&&(e[t[r]]=n[t[r]]);return e};function Ci(n){var{synthetics:i,indexes:e}=n,t=Ks(n,["synthetics","indexes"]);let r=Object.assign(Object.assign({},i),e);for(let[o,s]of Object.entries(t.fields))"indexed"in s&&(r[o]={field:o});return Object.assign(Object.assign({},t),{indexes:r})}function It(n){return n}It.collection=Ci;It.fields=Jr;It.generated={id:Zr.default};var nn="\uFFFFFE",qs="\0",Hs="\uFFFFFF";function de(...n){let i=Ws(n);return i.length===1?i[0]:i}function qe(...n){return n.join(nn)+`${Hs}`}function He(...n){return n.join(nn)+`${nn}${qs}`}function Ws(n){let i=[[]];for(let e of n)if(Array.isArray(e)){let t=[];for(let r of i)for(let o of e)t.push(r.concat(o));i=t}else for(let t of i)t.push(`${e}`);return Array.from(new Set(i.map(e=>e.join(nn))))}function Qs(n){return!!n.field}function Js(n,i){let e={};for(let[t,r]of Object.entries(n.indexes||{})){let o=r;Qs(o)?e[t]=Se(i[o.field]):e[t]=Se(o.compute(i))}return e}function Gs(n,i){return Object.entries(n.compounds||{}).reduce((e,[t,r])=>(e[t]=de(...r.of.map(o=>i[o])),e),{})}function Ys(n,i){return Object.entries(n.fields).reduce((e,[t,r])=>("indexed"in r&&(e[t]=Se(i[t])),e),{})}function rn(n,i){let e=Object.assign(Object.assign({[n.primaryKey]:i[n.primaryKey]},Ys(n,i)),Js(n,i));return Object.assign(e,Gs(n,Object.assign(Object.assign({},i),e))),e["@@@snapshot"]=JSON.stringify(i),e}var Xs="null";function Se(n){if(n===null)return Xs;if(typeof n=="string"||typeof n=="number")return n;if(typeof n=="boolean"||n===null)return`${n}`;if(n===void 0)return"undefined";if(Array.isArray(n))return n.map(Se);throw new Error(`Unsupported index value: ${n}`)}var eo={version:0,collections:{}};function sn(n,i,e){let t=typeof i=="function",r=t?eo:n,o=t?n:i,s=t?i:e,a=Object.keys(o.collections).filter(v=>r.collections[v]&&wt(r.collections[v])!==wt(o.collections[v])),d=Object.keys(r.collections).filter(v=>!o.collections[v]),u=Object.keys(o.collections).filter(v=>!r.collections[v]),p=new Set;for(let v of a){let _=r.collections[v].fields,I=o.collections[v].fields;Object.keys(I).some(O=>{var R,b;return!(!((R=_[O])===null||R===void 0)&&R.default)&&((b=I[O])===null||b===void 0?void 0:b.default)})&&p.add(v),Object.keys(_).some(O=>!I[O])&&p.add(v)}let S={},w={};for(let v of[...a,...u]){let _=on(r.collections[v]),I=on(o.collections[v]),O=I.filter(b=>!_.find(D=>D.name===b.name)),R=_.filter(b=>!I.find(D=>D.name===b.name));O.length>0&&(S[v]=O,a.includes(v)&&p.add(v)),R.length>0&&(w[v]=R,a.includes(v)&&p.add(v))}let C=(v,_)=>Fe(o.collections[v],_),g=v=>_=>{let I=o.collections[v];return Fe(I,Ei(I,_))};return{version:o.version,migrate:async v=>{let _=[];if(await s({migrate:async(I,O)=>{let R=g(I),b=async D=>{let f=await O(D);return N(f,ne(D)),R(f)};await v.migrate(I,b),_.push(I),p.delete(I)},identity:I=>I,withDefaults:C,info:{changedCollections:a,addedCollections:u,removedCollections:d},queries:v.queries,mutations:v.mutations}),o.version>1){v.log("debug","auto-migrating collections with new defaults",p);for(let O of p)await v.migrate(O,g(O)),_.push(O);let I=a.filter(O=>!_.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:d,addedIndexes:S,removedIndexes:w,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:u,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function on(n){return n?[...Object.keys(n.indexes||{}).map(i=>({name:i,multiEntry:["array","string[]","number[]","boolean[]"].includes(n.indexes[i].type),synthetic:!0,compound:!1})),...Object.keys(n.compounds||{}).map(i=>({name:i,multiEntry:n.compounds[i].of.some(e=>(n.fields[e]||n.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function Pi(n,i){return sn(i?n:{version:0,collections:{}},i||n,async({migrate:t,info:r})=>{if((i||n).version!==1)for(let o of r.changedCollections)await t(o,s=>s)})}function Ai(n,i,e){let t=typeof i=="function"||i===void 0,r=t?eo:n,o=t?n:i,s=t?i:e;L(r,"Invalid arguments to createMigration"),L(o,"Invalid arguments to createMigration");let{changedCollections:a,addedCollections:d,removedCollections:u,addedIndexes:p,removedIndexes:S,autoMigratedCollections:w,autoMigration:C}=Zs(r,o);return{version:o.version,migrate:async g=>{let v=[];if(await s?.({migrate:async(I,O)=>{let R=C(I),b=async D=>{let f=await O(D);N(f,ne(D));let m=R(f),l=Yr(o.collections[I].fields,m);return m};await g.migrate(I,b),v.push(I),w.delete(I)},info:{changedCollections:a,addedCollections:d,removedCollections:u},queries:g.queries,mutations:g.mutations}),o.version>1){g.log("debug","auto-migrating collections with new defaults",w);for(let O of w)await g.migrate(O,C(O)),v.push(O);for(let O of u)await g.deleteCollection(O);let I=a.filter(O=>!v.includes(O));I.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${o.version}:`,I)}},removedCollections:u,addedIndexes:p,removedIndexes:S,allCollections:Object.keys(o.collections),changedCollections:a,addedCollections:d,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:o}}function Zs(n,i){let e=Object.keys(i.collections).filter(p=>n.collections[p]&&wt(n.collections[p])!==wt(i.collections[p])),t=Object.keys(n.collections).filter(p=>!i.collections[p]),r=Object.keys(i.collections).filter(p=>!n.collections[p]),o=new Set;for(let p of e){let S=n.collections[p].fields,w=i.collections[p].fields;Object.keys(w).some(C=>!Re(S[C])&&Re(w[C]))&&o.add(p),Object.keys(S).some(C=>!w[C])&&o.add(p)}let s={},a={};for(let p of[...e,...r]){let S=on(n.collections[p]),w=on(i.collections[p]),C=w.filter(v=>!S.find(_=>_.name===v.name)),g=S.filter(v=>!w.find(_=>_.name===v.name));C.length>0&&(s[p]=C,e.includes(p)&&o.add(p)),g.length>0&&(a[p]=g,e.includes(p)&&o.add(p))}return{changedCollections:e,addedCollections:r,removedCollections:t,addedIndexes:s,removedIndexes:a,autoMigratedCollections:o,withDefaults:(p,S)=>Fe(i.collections[p],S),autoMigration:p=>S=>{let w=i.collections[p];return Fe(w,Ei(w,S))}}}var Ri={};var an=class{constructor(i,e){this.getNow=i,this.createSubId=e,this.isPrimitive=t=>!U(t)||Q(t),this.createDiff=(t,r,o={})=>St(t,r,this.getNow,this.createSubId,[],o),this.createInitialize=(t,r)=>Ae(t,r,this.getNow,this.createSubId),this.createSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:r,value:o}}];{let s=ve(t,this.createSubId);return[...Ae(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:ae(s),name:r}}]}},this.createRemove=(t,r)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:r}}],this.createListSet=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:o}}];{let s=ve(t,this.createSubId);return[...Ae(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-set",index:r,value:ae(s)}}]}},this.createListPush=(t,r)=>{if(this.isPrimitive(r))return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:r}}];{let o=ve(t,this.createSubId);return[...Ae(r,o,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:ae(o)}}]}},this.createListAdd=(t,r)=>this.isPrimitive(r)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:r}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:ae(r)}}],this.createListInsert=(t,r,o)=>{if(this.isPrimitive(o))return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:o,index:r}}];{let s=ve(t,this.createSubId);return[...Ae(o,s,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:ae(s),index:r}}]}},this.createListRemove=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:r,only:o}}],this.createListDelete=(t,r,o=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:r,count:o}}],this.createListMoveByRef=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:r,index:o}}],this.createListMoveByIndex=(t,r,o)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:r,to:o}}],this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}],this.createDeleteAll=t=>t.map(r=>({oid:r,timestamp:this.getNow(),data:{op:"delete"}}))}};var z=class{constructor(i){this._onAllUnsubscribed=i,this.subscribers={},this.counts={},this._disabled=!1,this.disposed=!1,this.subscriberCount=e=>{var t;return(t=this.counts[e])!==null&&t!==void 0?t:0},this.totalSubscriberCount=()=>Object.values(this.counts).reduce((e,t)=>e+t,0),this.subscribe=(e,t)=>{let r=Yt(),o=this.subscribers[e];return o||(o=this.subscribers[e]={}),o[r]=t,this.counts[e]=(this.counts[e]||0)+1,()=>{this.subscribers[e]&&(delete this.subscribers[e][r],this.counts[e]--,this.counts[e]===0&&(delete this.subscribers[e],delete this.counts[e],this._onAllUnsubscribed&&this._onAllUnsubscribed(e)))}},this.emit=(e,...t)=>{this._disabled||this.subscribers[e]&&Object.values(this.subscribers[e]).forEach(r=>r(...t))},this.dispose=()=>{this._disabled=!0,this.disposed=!0;let e=Object.keys(this.subscribers);this.subscribers={},this.counts={},e.forEach(t=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(t)})},this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function to(n,i,e,t){if(i==null)return[{oid:n,timestamp:t(),data:{op:"delete"}}];let r=le(i),o=[];for(let s of e){let a=ea(n,r,s,t);o.unshift(...a),$e(r,s.data)}return o}function ea(n,i,e,t){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:n,timestamp:t(),data:{op:"set",name:r.name,value:i[r.name]}}];case"list-insert":return[{oid:n,timestamp:t(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:n,timestamp:t(),data:{op:"list-insert",index:r.index,values:i.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:n,timestamp:t(),data:{op:"list-move-by-ref",value:r.value,index:i.indexOf(r.value)}}];case"list-move-by-index":return[{oid:n,timestamp:t(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:n,timestamp:t(),data:{op:"initialize",value:i}}];case"list-push":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let o=i.lastIndexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else if(r.only==="first"){let o=i.indexOf(r.value);return[{oid:n,timestamp:t(),data:{op:"list-insert",index:o,values:[r.value]}}]}else{let o=[],s=i.indexOf(r.value);for(;s!==-1;)o.push(s),s=i.indexOf(r.value,s+1);return o.map(a=>({oid:n,timestamp:t(),data:{op:"list-insert",index:a,value:r.value}}))}case"list-add":return[{oid:n,timestamp:t(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-set":return[{oid:n,timestamp:t(),data:{op:"list-set",index:r.index,value:i[r.index]}}];case"initialize":return[{oid:n,timestamp:t(),data:{op:"delete"}}];case"touch":return[];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var ot=class{constructor(i){this.flusher=i,this.batches=new Map,this.flush=e=>{let t=this.batches.get(e);if(t)return t.flush()},this.discard=e=>{let t=this.batches.get(e);t&&(t.discard(),this.batches.delete(e))},this.flushAll=()=>[...this.batches.values()].map(e=>e.flush()),this.getSize=e=>{let t=this.batches.get(e);return t?t.items.length:0}}add({key:i,userData:e,items:t,max:r,timeout:o}){let s=this.batches.get(i);return s||(s=new Fi({max:r||null,startedAt:Date.now(),userData:e,timeout:o||null,flusher:this.flusher,key:i}),this.batches.set(i,s)),s.update({items:t,max:r,timeout:o,userData:e}),s}},Fi=class{constructor({max:i,startedAt:e,timeout:t,userData:r,flusher:o,key:s}){this.items=[],this.update=({items:a,max:d,timeout:u,userData:p})=>{this.items.push(...a),d!==void 0&&(this.max=d),u!==void 0&&(this.timeout=u),p&&(this.userData=p);let S=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():S&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))},this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let a=this.items;return this.items=[],this.flusher(a,this.key,this.userData)},this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]},this.max=i,this.startedAt=e,this.timeout=t,this.userData=r,this.flusher=o,this.key=s}};function no(n,i){let e,t;return(...r)=>{let o=i();return e&&e.length===o.length&&e.every((s,a)=>s===o[a])||(e=[...o],t=n(...r)),t}}var _t;(function(n){n[n.InvalidRequest=4e3]="InvalidRequest",n[n.BodyRequired=4001]="BodyRequired",n[n.NoToken=4010]="NoToken",n[n.InvalidToken=4011]="InvalidToken",n[n.TokenExpired=4012]="TokenExpired",n[n.Forbidden=4030]="Forbidden",n[n.NotFound=4040]="NotFound",n[n.Unexpected=5e3]="Unexpected",n[n.ConfigurationError=5010]="ConfigurationError",n[n.NoFileStorage=5011]="NoFileStorage"})(_t||(_t={}));var st=class extends Error{constructor(i,e,t){super(t??`Verdant error: ${i}`,{cause:e}),this.code=i,this.toResponse=()=>JSON.stringify({code:this.code})}get httpStatus(){let i=Math.floor(this.code/10);return i<600?i:500}};st.Code=_t;function io(n){return typeof n=="object"&&"code"in n&&typeof n.code=="number"}function ta(n){return typeof Buffer<"u"?Buffer.from(n).toString("base64"):btoa(n)}function na(n){return typeof Buffer<"u"?Buffer.from(n,"base64").toString():atob(n)}var We={onlyUser:n=>ta(`u:${n}:*`),onlyMe:()=>We.onlyUser(Ti),decode:n=>{let e=na(n).split(":");if(e.length!==3)throw new Error("Invalid authz string");return{scope:e[0],subject:e[1],action:e[2]}}},Ti="$$_originator_$$";function ro(n,i){let{operations:e,baselines:t}=n;if(e)for(let r of e)r.authz&&We.decode(r.authz).subject===Ti&&(r.authz=We.onlyUser(i));if(t)for(let r of t)r.authz&&We.decode(r.authz).subject===Ti&&(r.authz=We.onlyUser(i))}var Bi=typeof window<"u"?window.indexedDB:void 0;function ue(n){return n instanceof Error&&n.name==="AbortError"}function J(n){return new Promise((i,e)=>{n.onsuccess=()=>{i(n.result)},n.onerror=()=>{n.error&&ue(n.error)?i(n.result):e(n.error)}})}function Qe(n,i){return new Promise((e,t)=>{let r=n.transaction([i],"readonly"),s=r.objectStore(i).openCursor(),a=0,d=0;s.onsuccess=function(u){let p=s.result;p&&(a++,d=d+Vr(p.value),p.continue())},s.onerror=function(u){s.error&&ue(s.error)?e({count:a,size:d}):t(s.error)},r.oncomplete=function(u){e({count:a,size:d})},r.onabort=function(u){t(u)},r.onerror=function(u){t(u)}})}function cn(n,i){let e=n.transaction(i,"readonly"),t=i.map(r=>{let o=e.objectStore(r);return J(o.getAll())});return Promise.all(t)}async function ge(n){n.close(),await new Promise((i,e)=>{i()})}async function ln(n,i=Bi){let e=i.deleteDatabase([n,"meta"].join("_")),t=i.deleteDatabase([n,"collections"].join("_"));await Promise.all([new Promise((r,o)=>{e.onsuccess=r,e.onerror=o}),new Promise((r,o)=>{t.onsuccess=r,t.onerror=o})]),window.location.reload()}function oo(n,i=window.indexedDB){return J(i.deleteDatabase(n))}async function so(n=window.indexedDB){return n.databases()}function dn(n,i,e,t,r){let o=n.transaction(i,e);if(t){let s=()=>{r?.("debug","aborting transaction");try{o.abort()}catch(a){r?.("debug","aborting transaction failed",a)}};t.addEventListener("abort",s),o.addEventListener("error",()=>{t.removeEventListener("abort",s)}),o.addEventListener("complete",()=>{t.removeEventListener("abort",s)})}return o}var _e=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(i=>i()),this._disposes=[]};this.addDispose=i=>{this._disposes.push(i)}}};var se=class extends _e{constructor(e,{log:t}={}){super();this.db=e;this.globalAbortController=new AbortController;this.createTransaction=(e,t)=>{let r=dn(this.db,e,t?.mode||"readonly",t?.abort,this.log);return this.globalAbortController.signal.addEventListener("abort",r.abort),r.addEventListener("complete",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r.addEventListener("error",()=>{this.globalAbortController.signal.removeEventListener("abort",r.abort)}),r};this.run=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve(void 0);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return J(a)};this.runAll=async(e,t,r)=>{if(this.disposed||r?.transaction?.error)return Promise.resolve([]);let s=(r?.transaction||this.createTransaction([e],r)).objectStore(e),a=t(s);return Promise.all(a.map(J))};this.iterate=async(e,t,r,o)=>{let a=(o?.transaction||this.createTransaction([e],o)).objectStore(e),d=t(a);return Array.isArray(d)?Promise.all(d.map(u=>new Promise((p,S)=>{u.onsuccess=()=>{let w=u.result;w?(r(w.value,a),w.continue()):p()},u.onerror=()=>{u.error&&ue(u.error)?p():S(u.error)}}))).then(()=>{}):new Promise((u,p)=>{d.onsuccess=()=>{let S=d.result;S?r(S.value,a)?u():S.continue():u()},d.onerror=()=>{d.error&&ue(d.error)?u():p(d.error)}})};this.clear=e=>this.run(e,t=>t.clear(),{mode:"readwrite"});this.log=t,this.addDispose(()=>{this.globalAbortController.abort()})}};var un=class extends se{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",t=>t.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",t=>t.put({type:"ack",globalAckTimestamp:e}),{mode:"readwrite"})}}};var fn=class extends se{constructor(e,t){super(e,t);this.getAllForDocument=async(e,{mode:t="readonly",transaction:r}={})=>{let o=[];return await this.iterateOverAllForDocument(e,s=>{o.push(s)},{mode:t,transaction:r}),o};this.iterateOverAllForDocument=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>{let a=$(e),[d,u]=gi(e),[p,S]=bi(e);return[s.openCursor(IDBKeyRange.only(a)),s.openCursor(IDBKeyRange.bound(d,u,!1,!1)),s.openCursor(IDBKeyRange.bound(p,S,!1,!1))]},t,{mode:r,transaction:o});this.iterateOverAllForCollection=async(e,t,{mode:r="readonly",transaction:o}={})=>this.iterate("baselines",s=>[s.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1))],t,{mode:r,transaction:o});this.getAllForMultipleDocuments=async(e,{mode:t="readonly"}={})=>(await this.runAll("baselines",o=>e.flatMap(s=>{let a=$(s),[d,u]=gi(s),[p,S]=bi(s);return[o.get(a),o.getAll(IDBKeyRange.bound(d,u,!1,!1)),o.getAll(IDBKeyRange.bound(p,S,!1,!1))]}),{mode:t})).flat();this.getAllSince=async(e,{mode:t="readonly"}={})=>this.run("baselines",r=>{let o=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(o)},{mode:t});this.get=async(e,{transaction:t,mode:r="readonly"}={})=>this.run("baselines",o=>o.get(e),{mode:r,transaction:t});this.set=async(e,{transaction:t}={})=>{await this.run("baselines",r=>r.put(e),{mode:"readwrite",transaction:t})};this.setAll=async(e,{transaction:t}={})=>{await this.runAll("baselines",r=>e.map(o=>r.put(o)),{mode:"readwrite",transaction:t})};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:t})=>{await this.run("baselines",r=>r.delete(e),{mode:"readwrite",transaction:t})}}};var ao=Be(Ne(),1);var hn=class extends se{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let t=await this.run("info",r=>r.get("localReplicaInfo"),{transaction:e});return t?(this.cached=t,t):(this._creating||(this._creating=(async()=>{let o={type:"localReplicaInfo",id:(0,ao.default)(),userId:void 0,ackedLogicalTime:null,lastSyncedLogicalTime:null};await this.run("info",s=>s.put(o),{mode:"readwrite"}),this.cached=o})()),await this._creating,this.get({transaction:e}))};this.update=async(e,{transaction:t}={})=>{let r=await this.get({transaction:t});Object.assign(r,e),await this.run("info",o=>o.put(r),{mode:"readwrite"}),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",t=>t.put(e),{mode:"readwrite"})}}};var pn=class{constructor(i){this.meta=i;this.createOperation=async i=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:i.operations.map(en)}};this.createMigrationOperation=async({targetVersion:i,...e})=>{let t=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(i)})),timestamp:this.meta.time.zero(i),replicaId:t.id}};this.createSyncStep1=async i=>{let e=await this.meta.localReplica.get(),t=i===null?null:e.lastSyncedLogicalTime,r=[],o=new Set;t?await this.meta.operations.iterateOverAllLocalOperations(a=>{r.push(en(a)),o.add($(a.oid))},{after:t,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(a=>{r.push(en(a)),o.add($(a.oid))},{mode:"readwrite"});let s=[];return t||(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:t}};this.createPresenceUpdate=async i=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:i.presence,replicaId:e.id,internal:i.internal}};this.createHeartbeat=async()=>{let i=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:i.id}};this.createAck=async i=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:i}}}};var mn=class extends se{constructor(e,t){super(e,t);this.iterateOverAllOperationsForDocument=async(e,t,{to:r,from:o,after:s,mode:a="readonly",transaction:d}={})=>{let p=(d||this.createTransaction(["operations"],{mode:a})).objectStore("operations"),S=p.index("d_t"),w=o||s,C=w?de(e,w):He(e),g=r?de(e,r):qe(e),v=IDBKeyRange.bound(C,g,!!s,!1),_=S.openCursor(v,"next");return new Promise((I,O)=>{let R;_.onsuccess=b=>{let D=_.result;if(D){let f=D.value;L(f.oid.startsWith(e)),L(R===void 0||R<=f.timestamp,`expected ${R} <= ${f.timestamp}`),t(f,p),R=f.timestamp,D.continue()}else I()},_.onerror=b=>{if(ue(_.error)){I();return}else O(_.error)}})};this.iterateOverAllOperationsForEntity=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let u=(a||this.createTransaction(["operations"],{mode:s})).objectStore("operations"),p=r?de(e,r):He(e),S=o?de(e,o):qe(e),w=IDBKeyRange.bound(p,S,!!r,!1),C=u.openCursor(w,"next");return new Promise((g,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(R.oid.startsWith(e)),L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),t(R,u),_=R.timestamp,O.continue()}else g()},C.onerror=I=>{ue(C.error)?g():v(C.error)}})};this.iterateOverAllOperationsForCollection=async(e,t,{after:r,to:o,mode:s,transaction:a})=>{let d=a||this.createTransaction(["operations"],{mode:s});return this.iterate("operations",u=>u.openCursor(IDBKeyRange.bound(e,e+"\uFFFF",!1,!1),"next"),t,{mode:s,transaction:d})};this.iterateOverAllLocalOperations=async(e,{before:t,after:r,mode:o="readonly",transaction:s})=>{let d=(s||this.createTransaction(["operations"],{mode:o})).objectStore("operations"),u=d.index("l_t"),p=r?de(!0,r):He(!0),S=t?de(!0,t):qe(!0),w=IDBKeyRange.bound(p,S,!!r,!0),C=u.openCursor(w,"next");return new Promise((g,v)=>{let _;C.onsuccess=I=>{let O=C.result;if(O){let R=O.value;L(_===void 0||_<=R.timestamp,`expected ${_} <= ${R.timestamp}`),e(R,d),_=R.timestamp,O.continue()}else g()},C.onerror=I=>{ue(C.error)?g():v(C.error)}})};this.iterateOverAllOperations=async(e,{before:t,transaction:r,mode:o,from:s})=>{await this.iterate("operations",a=>{let d=s?He(s):void 0,u=t?qe(t):void 0,p=d&&u?IDBKeyRange.bound(d,u,!1,!0):d?IDBKeyRange.lowerBound(d,!1):u?IDBKeyRange.upperBound(u,!0):void 0;return a.index("timestamp").openCursor(p,"next")},e,{mode:o,transaction:r})};this.addOperations=async(e,{transaction:t}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:t});this.addCompoundIndexes=e=>({...e,oid_timestamp:de(e.oid,e.timestamp),l_t:de(e.isLocal,e.timestamp),d_t:de($(e.oid),e.timestamp)});this.insert=async(e,{transaction:t})=>{let r=new Set;return await this.runAll("operations",o=>e.map(s=>(r.add($(s.oid)),o.put(s))),{mode:"readwrite",transaction:t}),Array.from(r)};this.reset=()=>this.clear("operations")}};var gn=class{constructor(i,e){this.db=i;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 J(r);return o?(this.cached=JSON.parse(o.schema),this.cached):null};this.set=async i=>{let o=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(i)});this.cached=i,await J(o)}}};var Dt=class extends z{constructor({disableRebasing:e,context:t,onOperation:r}){super();this.time=new Ut;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=(e,t={})=>dn(this.db,e,t.write?"readwrite":"readonly",t.abort,this.context.log);this.getAllDocumentRelatedOids=async e=>{let t=new Set,r=$(e);L(r===e,"Must be root document OID"),t.add(r);let o=this.createTransaction(["baselines","operations"]);return await Promise.all([this.baselines.iterateOverAllForDocument(r,s=>{t.add(s.oid)},{transaction:o}),this.operations.iterateOverAllOperationsForDocument(r,s=>{t.add(s.oid)},{transaction:o})]),Array.from(t)};this.getAllCollectionRelatedOids=async e=>{let t=new Set,r=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForCollection(e,o=>{t.add(o.oid)},{transaction:r}),this.operations.iterateOverAllOperationsForCollection(e,o=>{t.add(o.oid)},{transaction:r})]),Array.from(t)};this.getDocumentSnapshot=async(e,t={})=>{let r=$(e);L(r===e,"Must be root document OID");let o=this.db.transaction(["baselines","operations"],"readwrite"),s=await this.baselines.getAllForDocument(r,{transaction:o}),a=new Map;for(let u of s)u.snapshot&&N(u.snapshot,u.oid),a.set(u.oid,u.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,u=>{let p=a.get(u.oid)||void 0,S=$e(p,u.data);S&&N(S,u.oid),a.set(u.oid,S)},{transaction:o,to:t.to||this.now});let d=a.get(r);return d&&Zt(d,a),d};this.getDocumentData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],t),o=[],s={};return await Promise.all([this.baselines.iterateOverAllForDocument(e,a=>{o.push(a)},{transaction:r}),this.operations.iterateOverAllOperationsForDocument(e,a=>{s[a.oid]??=[],s[a.oid].push(a)},{transaction:r})]),{baselines:o,operations:s}};this.getDocumentAuthz=async e=>{let t=await this.baselines.get(e);if(t)return t.authz;let r;return await this.operations.iterateOverAllOperationsForEntity(e,o=>{if(o.data.op==="initialize")return r=o.authz,!0},{}),r};this.ack=async e=>{let t=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:t.id,timestamp:e}),!this._closing&&(!t.ackedLogicalTime||e>t.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperations=async(e,t)=>{if(e.length===0)return;this.log("debug",`Inserting ${e.length} local operations`,e);for(let o of e)o.isLocal=!0;await this.operations.addOperations(e,t);let r=await this.messageCreator.createOperation({operations:e});this.emit("message",r),this.tryAutonomousRebase(),this.onOperation&&e.forEach(o=>this.onOperation(o))};this.insertRemoteOperations=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote operations`,e);let r=await this.operations.addOperations(e.map(o=>({...o,isLocal:!1})),t);return this.ack(e[e.length-1].timestamp),this.onOperation&&e.forEach(o=>this.onOperation(o)),r};this.insertRemoteBaselines=async(e,t)=>{if(e.length===0)return[];this.log("debug",`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e,t);let r=new Set;return e.forEach(o=>{r.add($(o.oid))}),Array.from(r)};this.insertData=async(e,t)=>{let r=this.createTransaction(["baselines","operations"],{...t,write:!0});e.baselines&&await this.insertRemoteBaselines(e.baselines,{transaction:r}),!t?.abort?.aborted&&e.operations&&(e.isLocal?await this.insertLocalOperations(e.operations,{transaction:r}):await this.insertRemoteOperations(e.operations,{transaction:r}))};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 t,r=new Set,o=this.createTransaction(["baselines","operations"],{write:!0}),s=0;if(await this.operations.iterateOverAllOperations(d=>{r.add(d.oid),t=d.timestamp,s++},{before:e,transaction:o}),!r.size||this._closing)return;let a=[];for(let d of r)a.push(await this.rebase(d,t||e,o));this.emit("rebase",a)};this.rebase=async(e,t,r)=>{let o=(await this.localReplica.get()).id;this.log("debug","[",o,"]","Rebasing",e,"up to",t);let s=r||this.createTransaction(["operations","baselines"],{write:!0}),a=await this.baselines.get(e,{transaction:s}),d=a?.snapshot||void 0,u=0,p=a?.authz,S=[];await this.operations.iterateOverAllOperationsForEntity(e,(C,g)=>{(!a||C.timestamp>a.timestamp)&&(d=$e(d,C.data,S),C.data.op==="initialize"&&(p=C.authz)),u++,g.delete(C.oid_timestamp)},{to:t,transaction:s}),d&&N(d,e);let w={oid:e,snapshot:d,timestamp:t,authz:p};if(w.snapshot?await this.baselines.set(w,{transaction:s}):await this.baselines.delete(e,{transaction:s}),this.log("debug","successfully rebased",e,"up to",t,":",d,"and deleted",u,"operations"),S.length){let C=S.filter(we);C.length&&this.emit("filesDeleted",C)}return w};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,t)=>{let r=await this.schema.get();if(r&&t===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
|
|
7
7
|
${JSON.stringify(r)}
|
|
8
|
-
${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.manualRebase=async()=>{if(this._closing||this.disableRebasing)return;let e=await this.ackInfo.getAckInfo();e.globalAckTimestamp&&this.runRebase(e.globalAckTimestamp)};this.export=async()=>{let e=this.db,[t,r]=await cn(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:t,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(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,t=await We(e,"operations"),r=await We(e,"baselines");return{operationsSize:t,baselinesSize:r}};this.context=t,this.schema=new gn(t.metaDb,t.schema.version),this.operations=new mn(this.db,{log:t.log}),this.baselines=new fn(this.db,{log:t.log}),this.localReplica=new hn(this.db),this.ackInfo=new dn(this.db),this.messageCreator=new pn(this),this.patchCreator=new an(()=>this.now),this.onOperation=r,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 ea=[ta,na,ia,ra,oa,sa];function yn({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=5}){return new Promise((r,o)=>{let s=n.open(`${i}_meta`,t),a=!1;s.onupgradeneeded=async f=>{let u=s.result,p=s.transaction,S=ea.slice(f.oldVersion);for(let w of S)await w(u,p);await new Promise((w,C)=>{p.addEventListener("complete",w),p.addEventListener("error",C)}),f.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function so({wipNamespace:n,namespace:i,indexedDB:e,log:t,metadataVersion:r}){let o=await yn({namespace:n,indexedDB:e,log:t,metadataVersion:r});if(!o.wasInitialized)return o;t?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await yn({namespace:i,indexedDB:e,log:t,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[f,u,p]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),S=o.db.transaction(["baselines","operations","info"],"readwrite"),w=S.objectStore("baselines"),C=S.objectStore("operations"),g=S.objectStore("info");for(let v of f)w.put(v);for(let v of u)C.put(v);for(let v of p)g.put(v);return await new Promise((v,_)=>{S.oncomplete=()=>{v()},S.onerror=I=>{_(I)},S.onabort=I=>{_(I)}}),await ge(s),t?.("debug","Finished copy of production metadata database to WIP. Copied:",f.length,"baselines,",u.length,"operations"),o}async function ta(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function na(n,i){let e=i.objectStore("operations");await new Promise((t,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:f,...u}=s.value;s.update({...u,l_t:a,d_t:f}),s.continue()}else t()},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 ia(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function ra(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function oa(n,i){let e=i.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let f=yi(a.value);f.oid_timestamp!==a.primaryKey?(a.delete(),e.put(f)):a.update(f),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let t=i.objectStore("baselines");await new Promise((r,o)=>{let s=t.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let f=yi(a.value);f.oid!==a.primaryKey?(a.delete(),t.put(f)):a.update(f),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}async function sa(n,i){i.objectStore("files").createIndex("timestamp","timestamp")}async function bn(n,i,e,t){function r(a,f){let u,p,S=n.open([i,"collections"].join("_"),e);S.onupgradeneeded=async w=>{u=w.oldVersion;let C=S.transaction;p=S.result,C.abort()},S.onsuccess=w=>{a([S.result.version,S.result])},S.onblocked=w=>{t?.("Database blocked, waiting...")},S.onerror=w=>{a([u,p])}}let[o,s]=await new Promise(r);return await ge(s),o}async function ao(n,i,e,t,r){function o(s,a){let f=n.open([i,"collections"].join("_"),e),u=!1;f.onupgradeneeded=p=>{let S=f.transaction;t(S,f.result,p),u=!0},f.onsuccess=p=>{u?s(f.result):a(new Error("Database was not upgraded when a version change was expected"))},f.onerror=p=>{a(f.error||new Error("Unknown error"))},f.onblocked=p=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function co(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Le({indexedDB:n=Ti,namespace:i,version:e,context:t}){t.log("debug","Opening database",i,"at version",e);let r=await new Promise((o,s)=>{let a=n.open([i,"collections"].join("_"),e);a.onupgradeneeded=async f=>{a.transaction.abort(),t.log("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=f=>{o(a.result)},a.onblocked=f=>{s(new Error("Migration error: database blocked"))},a.onerror=f=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}async function lo(n,i){let e=new Array;for(let f=0;f<n.objectStoreNames.length;f++)e.push(n.objectStoreNames[f]);let t=n.transaction(e,"readonly"),r=e.map(f=>t.objectStore(f)),o=await Promise.all(r.map(f=>J(f.getAll()))),s=i.transaction(e,"readwrite"),a=e.map(f=>s.objectStore(f));for(let f=0;f<a.length;f++)await Promise.all(o[f].map(u=>J(a[f].put(u))))}var aa=n=>IDBKeyRange.only(Se(n.equals)),ca=n=>{},la=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(Se(i)):i?e?IDBKeyRange.bound(Se(i),Se(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(Se(i),!!n.gt):IDBKeyRange.upperBound(Se(e),!!n.lt)},ua=(n,i,e)=>{let t=n.collections[i].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((f,u)=>t.of.indexOf(f)-t.of.indexOf(u));for(let f of r)if(t.of.indexOf(f)!==r.indexOf(f))throw new Error(`Compound index ${e.where} does not have ${f} at the start of its order`);let o=r.map(f=>e.match[f]);if(r.length===t.of.length)return IDBKeyRange.only(ue(...o));let s=qe(...o),a=Ke(...o);return IDBKeyRange.bound(s,a)};function da(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function wn(n,i,e){if(e)return Si(e)?la(e):xi(e)?aa(e):Qr(e)?ca(e):Oi(e)?da(e):ua(n,i,e)}function ki(n,i,e){return n.transaction(i,e?"readwrite":"readonly").objectStore(i)}async function vn({collection:n,index:i,context:e}){let t=ki(e.documentDb,n),r=i?.where?t.index(i.where):t,o=wn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,p)=>{a.onsuccess=()=>{let S=a.result;u(S?Y(n,S.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),u(null)):de(a.error)?u(null):p(a.error)}})}async function xn({collection:n,index:i,context:e}){let t=ki(e.documentDb,n),r=i?.where?t.index(i.where):t,o=wn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,p)=>{let S=new Set;a.onsuccess=()=>{let w=a.result;w?(S.add(Y(n,w.primaryKey.toString())),w.continue()):u(Array.from(S))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),u([])):de(a.error)?u([]):p(a.error)}})}async function Et({collection:n,index:i,context:e,limit:t,offset:r}){let o=ki(e.documentDb,n),s=i?.where?o.index(i.where):o,a=wn(e.schema,n,i),f=i?.order==="desc"?"prev":"next",u=s.openCursor(a,f),p=!r,S=!1,w=0;return{result:await new Promise((g,v)=>{let _=new Set;u.onsuccess=()=>{w++;let I=u.result;I?r&&!p?(I.advance(r),p=!0):(t&&_.size<t&&_.add(Y(n,I.primaryKey.toString())),t&&w>t?(S=!0,g(Array.from(_))):I.continue()):g(Array.from(_))},u.onerror=()=>{u.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",u.error),g([])):de(u.error)?g([]):v(u.error)}}),hasNextPage:S}}function uo({migration:n,meta:i,getMigrationNow:e,newOids:t}){return n.allCollections.reduce((r,o)=>(r[o]={put:async(s,a)=>{Fe(n.newSchema.collections[o],s);let f=s[n.newSchema.collections[o].primaryKey],u=Y(o,f);return t.push(u),await i.insertLocalOperations(Pe(s,u,e,void 0,void 0,{authz:a?.access})),s},delete:async s=>{let a=Y(o,s),f=await i.getDocumentAuthz(a),u=await i.getAllDocumentRelatedOids(a);return i.insertLocalOperations(u.map(p=>({oid:p,timestamp:e(),data:{op:"delete"},authz:f})))}},r),{})}function fa({migration:n,context:i,meta:e}){return n.oldCollections.reduce((t,r)=>(t[r]={get:async o=>{let s=Y(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)})},findOne:async o=>{let s=await vn({collection:r,index:o,context:i});return s?await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)}):null},findAll:async o=>{let s=await xn({collection:r,index:o,context:i});return await Promise.all(s.map(f=>e.getDocumentSnapshot(f,{to:e.time.now(n.oldSchema.version)})))}},t),{})}function fo({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=fa({migration:i,context:e,meta:n}),s=uo({migration:i,getMigrationNow:t,newOids:r,meta:n}),a=async p=>{let S=await n.getAllCollectionRelatedOids(p);return n.insertLocalOperations(S.map(w=>({oid:w,timestamp:t(),data:{op:"delete"}})))},f=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(p,S)=>{let w=await o[p].findAll();await Promise.all(w.filter(Boolean).map(async C=>{let g=ne(C);L(!!g,`Document is missing an OID: ${JSON.stringify(C)}`);let v=await n.getDocumentAuthz(g),_=le(C),I=await S(C);if(I){xt(_),xt(I),nt(I);let O=St(_,I,t,void 0,[],{mergeUnknownObjects:!0,authz:v});O.length>0&&await n.insertLocalOperations(O)}}))},queries:o,mutations:s,awaitables:f}}function ho({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.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=uo({migration:i,getMigrationNow:t,newOids:r,meta:n});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:[]}}var po=typeof window<"u"?window.indexedDB:void 0;async function Ct({context:n,toRun:i,meta:e,indexedDB:t=po,namespace:r=n.namespace}){await co(r,async()=>{for(let o of i){let s;if(o.oldSchema.version===0)s=ho({meta:e,migration:o,context:n}),await o.migrate(s);else{let u=await Le({indexedDB:t,namespace:r,version:o.oldSchema.version,context:n});s=fo({meta:e,migration:o,context:{...n,documentDb:u}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(p){throw n.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,p),p instanceof Error?p:new Error("Unknown error during migration")}await ge(u)}n.log("debug","Upgrading database",r,"to version",o.newSchema.version);let a=await ya({migration:o,indexedDB:t,namespace:r,context:n}),f=await ga({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version});for(let u of o.allCollections){let S=a.transaction(u,"readwrite").objectStore(u),C=(await ha(S)).map(O=>Y(u,`${O}`));C.push(...s.newOids.filter(O=>ce(O).collection===u),...f.filter(O=>ce(O).collection===u));let v=(await Promise.all(C.map(async O=>{try{let R=await e.getDocumentSnapshot(O);return[O,R]}catch(R){return n.log("error","Could not regenerate snapshot during migration for oid",O,"this document will not be preserved",R),null}}))).filter(O=>!!O).map(([O,R])=>{if(!R)return[O,void 0];let b=rn(o.newSchema.collections[u],R);return[O,b]}),I=a.transaction(u,"readwrite").objectStore(u);await Promise.all(v.map(([O,R])=>{if(R)return ma(I,R);{let{id:b}=ce(O);return pa(I,b)}}))}await ge(a),n.log("debug",`Migration of ${r} complete.`),n.log("info",`
|
|
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.manualRebase=async()=>{if(this._closing||this.disableRebasing)return;let e=await this.ackInfo.getAckInfo();e.globalAckTimestamp&&this.runRebase(e.globalAckTimestamp)};this.export=async()=>{let e=this.db,[t,r]=await cn(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:t,localReplica:o,schema:s}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await J(r.objectStore("baselines").clear()),await J(r.objectStore("operations").clear()),await J(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,t=await Qe(e,"operations"),r=await Qe(e,"baselines");return{operationsSize:t,baselinesSize:r}};this.context=t,this.schema=new gn(t.metaDb,t.schema.version),this.operations=new mn(this.db,{log:t.log}),this.baselines=new fn(this.db,{log:t.log}),this.localReplica=new hn(this.db),this.ackInfo=new un(this.db),this.messageCreator=new pn(this),this.patchCreator=new an(()=>this.now),this.onOperation=r,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 ia=[ra,oa,sa,aa,ca,la];function yn({indexedDB:n=window.indexedDB,namespace:i,log:e,metadataVersion:t=5}){return new Promise((r,o)=>{let s=n.open(`${i}_meta`,t),a=!1;s.onupgradeneeded=async d=>{let u=s.result,p=s.transaction,S=ia.slice(d.oldVersion);for(let w of S)await w(u,p);await new Promise((w,C)=>{p.addEventListener("complete",w),p.addEventListener("error",C)}),d.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),o(s.error)},s.onsuccess=()=>{r({db:s.result,wasInitialized:a})}})}async function co({wipNamespace:n,namespace:i,indexedDB:e,log:t,metadataVersion:r}){let o=await yn({namespace:n,indexedDB:e,log:t,metadataVersion:r});if(!o.wasInitialized)return o;t?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await yn({namespace:i,indexedDB:e,log:t,metadataVersion:r}),a=s.transaction(["baselines","operations","info"],"readonly"),[d,u,p]=await Promise.all([J(a.objectStore("baselines").getAll()),J(a.objectStore("operations").getAll()),J(a.objectStore("info").getAll())]),S=o.db.transaction(["baselines","operations","info"],"readwrite"),w=S.objectStore("baselines"),C=S.objectStore("operations"),g=S.objectStore("info");for(let v of d)w.put(v);for(let v of u)C.put(v);for(let v of p)g.put(v);return await new Promise((v,_)=>{S.oncomplete=()=>{v()},S.onerror=I=>{_(I)},S.onabort=I=>{_(I)}}),await ge(s),t?.("debug","Finished copy of production metadata database to WIP. Copied:",d.length,"baselines,",u.length,"operations"),o}async function ra(n,i){let e=n.createObjectStore("baselines",{keyPath:"oid"}),t=n.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=n.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),t.createIndex("isLocal_timestamp","isLocal_timestamp"),t.createIndex("documentOid_timestamp","documentOid_timestamp")}async function oa(n,i){let e=i.objectStore("operations");await new Promise((t,r)=>{let o=e.openCursor();o.onsuccess=()=>{let s=o.result;if(s){let{isLocal_timestamp:a,documentOid_timestamp:d,...u}=s.value;s.update({...u,l_t:a,d_t:d}),s.continue()}else t()},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 sa(n,i){i.objectStore("operations").createIndex("timestamp","timestamp")}async function aa(n,i){let e=n.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}async function ca(n,i){let e=i.objectStore("operations");await new Promise((r,o)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let d=yi(a.value);d.oid_timestamp!==a.primaryKey?(a.delete(),e.put(d)):a.update(d),a.continue()}else r()},s.onerror=a=>{o(s.error)}});let t=i.objectStore("baselines");await new Promise((r,o)=>{let s=t.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let d=yi(a.value);d.oid!==a.primaryKey?(a.delete(),t.put(d)):a.update(d),a.continue()}else r()},s.onerror=a=>{o(s.error)}})}async function la(n,i){i.objectStore("files").createIndex("timestamp","timestamp")}async function bn(n,i,e,t){function r(a,d){let u,p,S=n.open([i,"collections"].join("_"),e);S.onupgradeneeded=async w=>{u=w.oldVersion;let C=S.transaction;p=S.result,C.abort()},S.onsuccess=w=>{a([S.result.version,S.result])},S.onblocked=w=>{t?.("Database blocked, waiting...")},S.onerror=w=>{a([u,p])}}let[o,s]=await new Promise(r);return await ge(s),o}async function lo(n,i,e,t,r){function o(s,a){let d=n.open([i,"collections"].join("_"),e),u=!1;d.onupgradeneeded=p=>{let S=d.transaction;t(S,d.result,p),u=!0},d.onsuccess=p=>{u?s(d.result):a(new Error("Database was not upgraded when a version change was expected"))},d.onerror=p=>{a(d.error||new Error("Unknown error"))},d.onblocked=p=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(o)}async function uo(n,i){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${n}`,i):await i()}async function Ue({indexedDB:n=Bi,namespace:i,version:e,context:t}){t.log("debug","Opening database",i,"at version",e);let r=await new Promise((o,s)=>{let a=n.open([i,"collections"].join("_"),e);a.onupgradeneeded=async d=>{a.transaction.abort(),t.log("error","Database upgrade needed, but not expected","Expected",e,"Got",a.result.version),s(a.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${a.result.version}`))},a.onsuccess=d=>{o(a.result)},a.onblocked=d=>{s(new Error("Migration error: database blocked"))},a.onerror=d=>{s(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",o=>{r.close()}),r}async function fo(n,i){let e=new Array;for(let d=0;d<n.objectStoreNames.length;d++)e.push(n.objectStoreNames[d]);let t=n.transaction(e,"readonly"),r=e.map(d=>t.objectStore(d)),o=await Promise.all(r.map(d=>J(d.getAll()))),s=i.transaction(e,"readwrite"),a=e.map(d=>s.objectStore(d));for(let d=0;d<a.length;d++)await Promise.all(o[d].map(u=>J(a[d].put(u))))}var da=n=>IDBKeyRange.only(Se(n.equals)),ua=n=>{},fa=n=>{let i=n.gte||n.gt,e=n.lte||n.lt;return i===e?IDBKeyRange.only(Se(i)):i?e?IDBKeyRange.bound(Se(i),Se(e),!!n.gt,!!n.lt):IDBKeyRange.lowerBound(Se(i),!!n.gt):IDBKeyRange.upperBound(Se(e),!!n.lt)},ha=(n,i,e)=>{let t=n.collections[i].compounds[e.where];L(t,`Index ${e.where} does not exist on collection ${i}`);let r=Object.keys(e.match).sort((d,u)=>t.of.indexOf(d)-t.of.indexOf(u));for(let d of r)if(t.of.indexOf(d)!==r.indexOf(d))throw new Error(`Compound index ${e.where} does not have ${d} at the start of its order`);let o=r.map(d=>e.match[d]);if(r.length===t.of.length)return IDBKeyRange.only(de(...o));let s=He(...o),a=qe(...o);return IDBKeyRange.bound(s,a)};function pa(n){let i=n.startsWith,e=n.startsWith+"\uFFFF";return IDBKeyRange.bound(i,e)}function wn(n,i,e){if(e)return Si(e)?fa(e):xi(e)?da(e):Gr(e)?ua(e):Oi(e)?pa(e):ha(n,i,e)}function ki(n,i,e){return n.transaction(i,e?"readwrite":"readonly").objectStore(i)}async function vn({collection:n,index:i,context:e}){let t=ki(e.documentDb,n),r=i?.where?t.index(i.where):t,o=wn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,p)=>{a.onsuccess=()=>{let S=a.result;u(S?Y(n,S.primaryKey.toString()):null)},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",a.error),u(null)):ue(a.error)?u(null):p(a.error)}})}async function xn({collection:n,index:i,context:e}){let t=ki(e.documentDb,n),r=i?.where?t.index(i.where):t,o=wn(e.schema,n,i),s=i?.order==="desc"?"prev":"next",a=r.openCursor(o,s);return await new Promise((u,p)=>{let S=new Set;a.onsuccess=()=>{let w=a.result;w?(S.add(Y(n,w.primaryKey.toString())),w.continue()):u(Array.from(S))},a.onerror=()=>{a.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",a.error),u([])):ue(a.error)?u([]):p(a.error)}})}async function Et({collection:n,index:i,context:e,limit:t,offset:r}){let o=ki(e.documentDb,n),s=i?.where?o.index(i.where):o,a=wn(e.schema,n,i),d=i?.order==="desc"?"prev":"next",u=s.openCursor(a,d),p=!r,S=!1,w=0;return{result:await new Promise((g,v)=>{let _=new Set;u.onsuccess=()=>{w++;let I=u.result;I?r&&!p?(I.advance(r),p=!0):(t&&_.size<t&&_.add(Y(n,I.primaryKey.toString())),t&&w>t?(S=!0,g(Array.from(_))):I.continue()):g(Array.from(_))},u.onerror=()=>{u.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",u.error),g([])):ue(u.error)?g([]):v(u.error)}}),hasNextPage:S}}function ho({migration:n,meta:i,getMigrationNow:e,newOids:t}){return n.allCollections.reduce((r,o)=>(r[o]={put:async(s,a)=>{Fe(n.newSchema.collections[o],s);let d=s[n.newSchema.collections[o].primaryKey],u=Y(o,d);return t.push(u),await i.insertLocalOperations(Ae(s,u,e,void 0,void 0,{authz:a?.access})),s},delete:async s=>{let a=Y(o,s),d=await i.getDocumentAuthz(a),u=await i.getAllDocumentRelatedOids(a);return i.insertLocalOperations(u.map(p=>({oid:p,timestamp:e(),data:{op:"delete"},authz:d})))}},r),{})}function ma({migration:n,context:i,meta:e}){return n.oldCollections.reduce((t,r)=>(t[r]={get:async o=>{let s=Y(r,o);return await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)})},findOne:async o=>{let s=await vn({collection:r,index:o,context:i});return s?await e.getDocumentSnapshot(s,{to:e.time.now(n.oldSchema.version)}):null},findAll:async o=>{let s=await xn({collection:r,index:o,context:i});return await Promise.all(s.map(d=>e.getDocumentSnapshot(d,{to:e.time.now(n.oldSchema.version)})))}},t),{})}function po({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.version)}let r=new Array,o=ma({migration:i,context:e,meta:n}),s=ho({migration:i,getMigrationNow:t,newOids:r,meta:n}),a=async p=>{let S=await n.getAllCollectionRelatedOids(p);return n.insertLocalOperations(S.map(w=>({oid:w,timestamp:t(),data:{op:"delete"}})))},d=new Array;return{log:e.log,newOids:r,deleteCollection:a,migrate:async(p,S)=>{let w=await o[p].findAll();await Promise.all(w.filter(Boolean).map(async C=>{let g=ne(C);L(!!g,`Document is missing an OID: ${JSON.stringify(C)}`);let v=await n.getDocumentAuthz(g),_=le(C),I=await S(C);if(I){xt(_),xt(I),nt(I);let O=St(_,I,t,void 0,[],{mergeUnknownObjects:!0,authz:v});O.length>0&&await n.insertLocalOperations(O)}}))},queries:o,mutations:s,awaitables:d}}function mo({meta:n,migration:i,context:e}){function t(){return n.time.zero(i.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=ho({migration:i,getMigrationNow:t,newOids:r,meta:n});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:[]}}var go=typeof window<"u"?window.indexedDB:void 0;async function Ct({context:n,toRun:i,meta:e,indexedDB:t=go,namespace:r=n.namespace}){await uo(r,async()=>{for(let o of i){let s;if(o.oldSchema.version===0)s=mo({meta:e,migration:o,context:n}),await o.migrate(s);else{let u=await Ue({indexedDB:t,namespace:r,version:o.oldSchema.version,context:n});s=po({meta:e,migration:o,context:{...n,documentDb:u}});try{await o.migrate(s),await Promise.all(s.awaitables)}catch(p){throw n.log("critical",`Migration failed (${o.oldSchema.version} -> ${o.newSchema.version})`,p),p instanceof Error?p:new Error("Unknown error during migration")}await ge(u)}n.log("debug","Upgrading database",r,"to version",o.newSchema.version);let a=await va({migration:o,indexedDB:t,namespace:r,context:n}),d=await wa({meta:e,currentVersion:o.oldSchema.version,newVersion:o.newSchema.version});for(let u of o.allCollections){let S=a.transaction(u,"readwrite").objectStore(u),C=(await ga(S)).map(O=>Y(u,`${O}`));C.push(...s.newOids.filter(O=>ce(O).collection===u),...d.filter(O=>ce(O).collection===u));let v=(await Promise.all(C.map(async O=>{try{let R=await e.getDocumentSnapshot(O);return[O,R]}catch(R){return n.log("error","Could not regenerate snapshot during migration for oid",O,"this document will not be preserved",R),null}}))).filter(O=>!!O).map(([O,R])=>{if(!R)return[O,void 0];let b=rn(o.newSchema.collections[u],R);return[O,b]}),I=a.transaction(u,"readwrite").objectStore(u);await Promise.all(v.map(([O,R])=>{if(R)return ba(I,R);{let{id:b}=ce(O);return ya(I,b)}}))}await ge(a),n.log("debug",`Migration of ${r} complete.`),n.log("info",`
|
|
9
9
|
\u2B06\uFE0F v${o.newSchema.version} Migration complete. Here's the rundown:
|
|
10
10
|
- Added collections: ${o.addedCollections.join(", ")}
|
|
11
11
|
- Removed collections: ${o.removedCollections.join(", ")}
|
|
12
12
|
- Changed collections: ${o.changedCollections.join(", ")}
|
|
13
13
|
- New indexes: ${Object.keys(o.addedIndexes).map(u=>o.addedIndexes[u].map(p=>`${u}.${p.name}`)).flatMap(u=>u).join(", ")}
|
|
14
14
|
- Removed indexes: ${Object.keys(o.removedIndexes).map(u=>o.removedIndexes[u].map(p=>`${u}.${p.name}`)).flatMap(u=>u).join(", ")}
|
|
15
|
-
`)}})}async function ha(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function pa(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function ma(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function ga({meta:n,currentVersion:i,newVersion:e}){let t=[];return await n.operations.iterateOverAllOperations(r=>t.push(r),{from:n.time.zero(i+1)}),Array.from(new Set(t.map(r=>$(r.oid))))}function ya({migration:n,indexedDB:i=po,namespace:e,context:t}){return ao(i,e,n.newSchema.version,(r,o)=>{for(let s of n.addedCollections)o.createObjectStore(s,{keyPath:n.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of n.allCollections){let a=r.objectStore(s);for(let f of n.addedIndexes[s]||[])a.createIndex(f.name,f.name,{multiEntry:f.multiEntry});for(let f of n.removedIndexes[s]||[])a.deleteIndex(f.name)}for(let s of n.removedCollections)r.objectStore(s).clear()},t.log)}var at=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function At({currentVersion:n,targetVersion:i,migrations:e}){let t=mo({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new at(`No migration path found from ${n} to ${i}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function mo({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let o=mo({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(o)return[r,...o]}return null}var ba=typeof window<"u"?window.indexedDB:void 0;async function go({version:n,indexedDB:i=ba,migrations:e,meta:t,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await bn(i,o,n,r.log);if(s===n)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 a=At({currentVersion:s,targetVersion:n-1,migrations:e});if(a.length>0){await Ct({context:r,toRun:a,meta:t,indexedDB:i,namespace:o});let u=await Le({indexedDB:i,namespace:r.namespace,version:n-1,context:r}),p=await Le({indexedDB:i,namespace:o,version:n-1,context:r});await lo(u,p)}let f=At({currentVersion:n-1,targetVersion:n,migrations:e});f.length>0&&await Ct({context:r,toRun:f,meta:t,indexedDB:i,namespace:o})}return Le({indexedDB:i,namespace:o,version:n,context:r})}var Qe=class extends z{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var Sn=class{constructor(i,e){this.schema=i;this.entities=e;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return L(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Y(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Fe(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return Gr(t.fields,e)};this.create=async(i,e,t={})=>{let r=t,o=this.addDefaults(i,e),s=this.validate(i,o),a=this.getOid(i,s);if(t.access){let f=this.schema.collections[i];t.access!=="shared"&&e[f.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(s,a,r)};this.delete=async(i,e,t={})=>{let r=Y(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Y(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Y(i,r)),t);this.clone=async(i,e,t={})=>{if(!Gt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),o=this.schema.collections[i];if(delete r[o.primaryKey],!o.fields[o.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${i}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[o.primaryKey]=t.primaryKey}return this.create(i,r,t)}}};var Bi=Ve(et(),1);function wa(n){return{id:(0,Bi.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function ct(n,i){if(typeof window<"u"&&it(n)){let e=wa(n);return i(e),vt(e.id)}if(Xt(n)){let e={...n,id:(0,Bi.default)()};return i(e),vt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=ct(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=ct(n[e],i);return n}return n}function yo(n){return"__testReadBuffer"in n?n.__testReadBuffer:new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var lt=Symbol("entity-file-update"),Pt=Symbol("entity-file-mark-failed"),ji=Symbol("entity-file-mark-uploaded"),va,xa,Sa,fe=class extends z{constructor(e,{downloadRemote:t=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[va]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[xa]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this[Sa]=()=>{this._fileData&&(this._fileData.remote=!0,this.emit("change"))};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=t}static{va=lt,xa=Pt,Sa=ji}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._fileData?.remote??!1}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return this._fileData?this._fileData:{id:this.id,url:this._objectUrl??void 0,name:this.name??"unknown-file",remote:!1,type:this.type??""}}};var On=class{constructor({initial:i}={}){this.cache=new Map;this.get=i=>{if(this.cache.has(i.oid))return this.cache.get(i.oid);let e=new he(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getFile=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new fe(i,e);return this.cache.set(i,t),t};this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};function bo(n,i,e){let t={previousValue:n.get(i),isLocal:!1};function r(o){if(n.deleted)return;let s=n.get(i);s!==this.previousValue&&(this.isLocal=o.isLocal,e(s,this),this.previousValue=s)}return n.subscribe("change",r.bind(t))}var he=class n extends z{constructor({oid:e,schema:t,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:f,files:u,patchCreator:p,storeEvents:S,deleteSelf:w}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof n){let t=e.view;return t==null}return e==null};this.validate=eo(()=>(this.validationError=Te({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(o=>o instanceof n||o instanceof fe?e(o):o);return N(r,this.oid),r}else{let r=Object.entries(t).reduce((o,[s,a])=>(a instanceof n||a instanceof fe?o[s]=e(a):o[s]=a,o),{});return N(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{if(this.ctx.log("debug","Entity: adding pending operations",this.oid),this.access)for(let r of e)r.authz=this.access;let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof n&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange||(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=$e(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>bo(this,e,r);this.get=e=>{Mi(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],o=$e(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(we(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return this.schema.type==="map"&&r===void 0?void 0:Te({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Re(o)?_i(o):xe(o)?null:void 0:r};this.getOrSet=(e,t)=>{Mi(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);it(e)||(e=le(e,!1));let r=$e(this.schema,t);if(r){Ne(e,r);let o=Te({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(o)throw new Error(`Validation error: ${o.message}`,{cause:o})}return ct(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof n)return ae(e.oid);if(e instanceof fe)return vt(e.id);if(typeof e=="object"){let t=me(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ae(t)}else return e};this.set=(e,t,r)=>{Mi(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)Oa(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:t=!0,replaceSubObjects:r=!1,preserveUndefined:o=!1}={})=>{if(!t&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let s={};N(s,this.oid);for(let[a,f]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(f===void 0&&!o)continue;let u=$e(this.schema,a);u&&Ne(f,u),s[a]=this.processInputValue(f,a)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),s,{mergeUnknownObjects:!r,defaultUndefined:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,t)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let t=this.getItemRefValue(e);return Q(t)?this.view.some(r=>{if(Q(r))return tt(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=f||[],this.ctx=s,this.files=u,this.schema=t,this.entityFamily=r||new On({initial:[this]}),this.patchCreator=p,this.metadataFamily=a,this.storeEvents=S,this.parent=o,this._deleteSelf=w,this.parent||(S.add.attach(this.onAdd),S.replace.attach(this.onReplace),S.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!xe(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!V(e))return Re(this.schema)?_i(this.schema):null;if(this.cachedView=this.isList?[]:{},N(this.cachedView,this.oid),Array.isArray(e)){let r=$e(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!xe(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(V(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=$e(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!xe(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Mi(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function Oa(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var Li=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=le(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,o=this.applyOperations(e,!e,this.confirmedOperations,t,t);o.futureSeen&&this.ctx.globalEvents.emit("futureSeen",o.futureSeen),o.authz&&(r=o.authz);let s=i?o:this.applyOperations(o.view,o.deleted,this.pendingOperations,o.latestTimestamp,null);s.authz&&(r=s.authz),s.view&&N(s.view,this.oid);let a=!!o.latestTimestamp&&li(o.latestTimestamp,this.ctx.getNow())<0,f=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;f&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let u=s.latestTimestamp??o.latestTimestamp??t,p=u?ui(u):0;if(!s.view&&!s.deleted&&!f){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:s.view??void 0,deleted:s.deleted,empty:f,fromOlderVersion:a,updatedAt:p,latestTimestamp:u,authz:r}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let o=this.pendingOperations.length;this.discardPendingOperation(t),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=i=>{this.pendingOperations.push(i)};this.discardPendingOperation=i=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==i.timestamp)};this.applyOperations=(i,e,t,r,o)=>{let s,a,f=this.ctx.getNow();for(let u of t)if(!(o&&u.timestamp<=o)){if(li(u.timestamp,f)>0){s=u.timestamp;continue}u.data.op==="delete"?e=!0:(i=ze(i,u.data),u.data.op==="initialize"&&(e=!1,u.authz&&(a=u.authz))),(!r||u.timestamp>r)&&(r=u.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:s,authz:a}};L(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},In=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(L(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Li({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let o of i){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:t})}return Object.values(r)};this.addPendingData=i=>{let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.replaceAllData=({operations:i={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of t)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(i)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var Rt="@@default",_n=class{constructor({batchTimeout:i=200,meta:e,ctx:t,entities:r}){this.currentBatchKey=Rt;this.flushOperations=async(i,e,t)=>{if(this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync"),!i.length)return;let r=[],o={};for(let s=i.length-1;s>=0;s--){let a=i[s],f=o[a.oid];if(f&&Hr(a,f)){this.entities.discardPendingOperation(a);continue}let u=qr(a);u!==!1&&(o[a.oid]||(o[a.oid]=new Set),o[a.oid].add(u)),r.unshift(a)}for(let s of r)s.timestamp=this.meta.now;await this.commitOperations(r,t)};this.commitOperations=async(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=Yt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Rt,s),commit:async()=>(await this.batcher.flush(Rt),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=Ot(i),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(t).map(async([s,a])=>{let u=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!u){this.ctx.log("warn","could not find entity",s,"for undo operation",i);return}let p=Zr(s,u.view,a,o);r.unshift(...p)})),r};this.meta=e,this.ctx=t,this.entities=r,this.defaultBatchTimeout=i,this.batcher=new ot(this.flushOperations),this.batcher.add({key:Rt,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Rt}};var Dn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>{let o=t.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>ce(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(f=>a.delete(f)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async a=>{let f=a.getSnapshot();try{await this.saveDocument(a.oid,f,s)}catch(u){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(f)})`,u),u instanceof Error?u:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,t);let{collection:o,id:s}=ce(e);if(!t)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],f=rn(a,t);await this.run(o,u=>u.put(f),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,t)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",t=>{this.db=t}))}};var Bn=Ve(Xo(),1);var jn=class extends _e{constructor({ctx:e,meta:t,files:r}){super();this.events={add:new Bn.WeakEvent,replace:new Bn.WeakEvent,resetAll:new Bn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null,this.ctx.globalEvents.emit("resetToServer")})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.empty=async()=>{await this.queryableStorage.reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let t=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let o=Array.from(new Set(t.map(p=>$(p.oid)).concat(r.map(p=>$(p.oid))))),s=Kr(t),a=$r(r);this.ctx.log("debug","Applying data to live entities");for(let p of o){let S=s[p],w=a[p]??[],C=Ot(w),g=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(p);v?v.then(()=>{g.invoke(this,{oid:p,baselines:S,operations:C,isLocal:!1})}):g.invoke(this,{oid:p,baselines:S,operations:C,isLocal:!1})}let f={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,f);let u=await Promise.all(o.map(async p=>await this.hydrate(p,f)??{oid:p,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(u,f)}catch(p){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",p):this.ctx.log("error","Error saving entities to queryable storage",p)}};this.hydrate=async(e,t)=>{if(!Gt(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,t);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:o}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:s}=ce(t);Wt(e);let a=ct(e,this.files.add);N(a,t);let f=this.constructEntity(t);if(!f)throw new Error(`Could not put new document: no schema exists for collection ${s}`);let u=this.meta.patchCreator.createInitialize(a,t);o&&u.forEach(S=>{S.authz=o}),await this.batcher.commitOperations(u,{undoable:!!r,source:f});let p=Ot(u);return this.events.add.invoke(this,{operations:p,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(f)),f};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(s=>this.hydrate(s)));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=[];for(let s of r)if(s){let a=s.__getFamilyOids__(),f=this.meta.patchCreator.createDeleteAll(a);for(let u of f)u.authz=s.access;o.push(...f)}await this.batcher.commitOperations(o,{undoable:t?.undoable===void 0?!0:t.undoable})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:t}=ce(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new In({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new he({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=$(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,t);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=t,this.files=r,this.queryableStorage=new Dn({ctx:e}),this.batcher=new _n({ctx:e,meta:t,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Mn=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:t,downloadRemote:r=!1}={})=>{let o=e.file?await yo(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}),{mode:"readwrite",transaction:t})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Ua(t,e.type):void 0,e};this.markUploaded=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:t})};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:t});if(r)return r};this.getFile=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),o=(await this.run("files",s=>s.index("remote").getAll("true"),{transaction:t})).filter(s=>!s.timestamp||!e||s.timestamp>e);await Promise.all(o.map(s=>this.run("files",a=>a.put({...s,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:t});this.getAll=async()=>{let[e]=await cn(this.db,["files"]);return e.map(this.hydrateFileData)};this.stats=async()=>({size:await We(this.db,"files")})}deleteFile(e,{transaction:t}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t})}};function Ua(n,i){return new Blob([n],{type:i})}function Va(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3}var Ln=class{constructor({db:i,sync:e,context:t,meta:r,config:o={}}){this.files=new Map;this.maxUploadRetries=3;this.maxDownloadRetries=3;this.add=async i=>{if(i.url&&!i.file){let e=await this.downloadRemoteFile(i.url);i.file=new File([e],i.name,{type:i.type})}if(i.remote=!1,this.files.has(i.id))this.files.get(i.id)[lt](i);else{let e=new fe(i.id);e[lt](i),this.files.set(i.id,e)}await this.storage.addFile(i),i.file&&this.sync.status==="active"&&await this.uploadFile(i)};this.uploadFile=async(i,e=0)=>{let t=await this.sync.uploadFile(i);if(t.success){await this.storage.markUploaded(i.id);let r=this.files.get(i.id);r&&r[ji](),this.context.log("info","File uploaded",i.id)}else t.retry&&e<this.maxUploadRetries?(this.context.log("error",`Error uploading file ${i.id}, retrying...`,t.error),setTimeout(this.uploadFile,1e3,i,e+1)):this.context.log("error",`Failed to upload file ${i.id}. Not retrying until next sync.`,t.error)};this.downloadRemoteFile=async(i,e=0)=>{let t=await fetch(i,{method:"GET",credentials:"include"});if(!t.ok){if(e<this.maxDownloadRetries)return new Promise((o,s)=>{setTimeout(()=>{this.downloadRemoteFile(i,e+1).then(o,s)},1e3)});throw new Error(`Failed to download file: ${t.status}`)}return await t.blob()};this.get=(i,e)=>{if(this.files.has(i))return this.files.get(i);let t=new fe(i,e);return this.files.set(i,t),this.load(t),t};this.load=async(i,e=0)=>{if(e>this.maxDownloadRetries){this.context.log("error","Failed to load file after 5 retries"),i[Pt]();return}let t=await this.storage.getFile(i.id);if(t)i[lt](t);else try{let r=await this.sync.getFile(i.id);r.success?(i[lt](r.data),await this.storage.addFile(r.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",r),i[Pt](),r.retry&&setTimeout(this.load,1e3,i,e+1))}catch(r){this.context.log("error","Failed to load file",r),i[Pt](),setTimeout(this.load,1e3,i,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(i=!1)=>{let e=await this.storage.getAll();if(i){for(let t of e)if(!t.file&&t.url)try{let r=await fetch(t.url,{method:"GET",credentials:"include"}).then(o=>o.blob());t.file=r}catch(r){this.context.log("error","Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",r)}}return e};this.importAll=async i=>{await Promise.all(i.map(e=>this.add(e)))};this.onOnlineChange=async i=>{if(i){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let i=0,e=0;await this.storage.iterateOverPendingDelete((t,r)=>{this.config.canCleanupDeletedFile(t)?(i++,r.delete(t.id)):e++}),this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.handleFileRefsDeleted=async i=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(i.map(async t=>{try{await this.storage.markPendingDelete(t.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};this.close=()=>{this.storage.dispose()};this.stats=()=>this.storage.stats();this.storage=new Mn(i),this.sync=e,this.context=t,this.meta=r,this.config={canCleanupDeletedFile:Va,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.sync.subscribe("serverReset",this.storage.resetSyncedStatusSince),this.tryCleanupDeletedFiles()}};var za=typeof window<"u"?window.indexedDB:void 0;async function Tt({version:n,indexedDB:i=za,migrations:e,meta:t,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await bn(i,r.namespace,n,r.log);r.log("debug","Current database version:",o,"target version:",n);let s=At({currentVersion:o,targetVersion:n,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await Ct({context:r,toRun:s,meta:t,indexedDB:i})),Le({indexedDB:i,namespace:r.namespace,version:n,context:r})}function Na(n){return n!==null}function Zi(n){return Array.isArray(n)?n.map(Zi).filter(Na):n instanceof he&&n.deleted?null:n}function Ue(n,i){return!n&&!i||n&&i&&ke(n)===ke(i)}var er=Symbol("ON_ALL_UNSUBSCRIBED"),pe=Symbol("UPDATE"),$a,ye=class extends _e{constructor({initial:e,context:t,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);let t=Zi(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((o,s)=>o===t[s])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof he&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof he&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this.status==="initial"?this.status="initializing":this.status==="ready"&&(this.status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[$a]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new z(f=>{f==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=o,this.collection=r;let a=s||(f=>f.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",f=>{a(f)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{$a=er}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}};var Un=class extends ye{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Y(r.collection,e),this.hydrate=t}};var Ka,Vn=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await vn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Ka]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ka=pe}};var qa,zn=class extends ye{constructor({index:e,hydrate:t,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=t,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[qa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=o}static{qa=pe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ha,Nn=class extends ye{constructor({hydrate:e,pageSize:t,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ha]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Ha=pe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Wa,$n=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let e=await xn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Wa]=e=>{Ue(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Wa=pe}};var Kn=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:o}){this.serializeIndex=i=>i?ke(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new Un({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Vn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[pe](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new $n({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[pe](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(o,()=>new zn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:t}),s=>{s[pe](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new Nn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[pe](i)})};this.cache=e,this.collection=i,this.hydrate=t.hydrate,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var qn=class extends _e{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=t}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[er](this.onQueryUnsubscribed),e}getOrSet(e,t,r){let o=this.get(e);return o?(r?.(o),o):this.set(t())}};var tr=Symbol("handleMessage"),Qa,kt=class extends z{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[Qa]=async(e,t)=>{let r=!1,o=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),this.emit("selfChanged",t.userInfo)):(o.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},o.clear();for(let[s,a]of Object.entries(t.peerPresence))this.isSelf(e,a)?(this._self=a,this._selfReplicaIds.add(a.replicaId),this.emit("selfChanged",a)):(r=!0,o.add(s),this._peers[s]=a,this.emit("peerChanged",s,a))}else if(t.type==="presence-offline"){o.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let s=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.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 t=e.reduce((r,o)=>({...r,...o}),this.self.presence);this.emit("update",t)};this.self.presence=e,this.self.profile=r,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new ot(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Qa=tr}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 Hn=class{constructor({endpointProvider:i,log:e}){this.uploadFile=async i=>{let e=i.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:t,token:r}=await this.endpointProvider.getEndpoints(),o=new FormData;o.append("file",e);try{let s=await fetch(t+`/${i.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});if(s.ok)return this.log("info","File upload successful"),{success:!0,retry:!1};{let a=await s.text();return this.log("error","File upload failed",s.status,a),{success:!1,retry:s.status>=500,error:`Failed to upload file: ${s.status} ${a}`}}}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0,error:s.message}}};this.getFile=async i=>{let{files:e,token:t}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${i}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});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,error:r,retry:!0}}};this.endpointProvider=i,this.log=e}};var dt=class extends z{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.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=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Wn=class extends z{constructor({endpointProvider:e,meta:t,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch.bind(window)}){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:t,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(t,{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(),a=Promise.all(s.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();to(s)&&s.code===_t.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=zr(e=>{this.sendRequest([e])},3e3);this.send=e=>{switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.meta.messageCreator.createSyncStep1()])};this.log=s,this.meta=t,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new dt({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function nr(n){this.message=n}nr.prototype=new Error,nr.prototype.name="InvalidCharacterError";var Zo=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new nr("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,o=0,s="";t=i.charAt(o++);~t&&(e=r%4?64*e+t:t,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return s};function Ja(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(Zo(e).replace(/(.)/g,function(t,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(i)}catch{return Zo(i)}}function Qn(n){this.message=n}function Ga(n,i){if(typeof n!="string")throw new Qn("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(Ja(n.split(".")[e]))}catch(t){throw new Qn("Invalid token specified: "+t.message)}}Qn.prototype=new Error,Qn.prototype.name="InvalidTokenError";var es=Ga;var Jn=class{constructor(i){this.config=i;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;this.config.fetchAuth?i=await this.config.fetchAuth():i=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(f=>{if(f.ok)return f.json();throw new Error(`Auth endpoint returned non-200 response: ${f.status}`)}),L(i.accessToken,"No access token provided from auth endpoint");let e=es(i.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let o=t.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Me.Realtime}};var Gn=class extends z{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}},Yn=class{constructor(i,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=i,this.factor=e}};var Xn=class extends z{constructor({endpointProvider:e,meta:t,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new dt;this.reconnectScheduler=new Gn(new Yn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",t),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",t);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=t,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Zn=class extends z{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.syncOnce=async()=>{};this.presence=new kt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},ft=class extends z{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:f,pullInterval:u,presenceUpdateBatchTimeout:p,defaultProfile:S,useBroadcastChannel:w,onOutgoingMessage:C},{meta:g,ctx:v,onData:_}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:t}={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("debug","sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await 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.emit("serverReset",e.since),this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[tr](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 t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new st(st.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&no(e,t),await this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.meta=g,this.onData=_,this.log=v.log,this.onOutgoingMessage=C,this.presence=new kt({initialPresence:o,defaultProfile:S,updateBatchTimeout:p,replicaStore:g.localReplica}),this.endpointProvider=new Jn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new Xn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:v.log}),this.pushPullSync=new Wn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:v.log,interval:u,fetch:r}),this.fileSync=new Hn({endpointProvider:this.endpointProvider,log:v.log}),w&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${v.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),f==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{O&&clearTimeout(O);let b=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;b&&this.mode==="pull"?this.setMode("realtime"):!b&&this.mode==="realtime"&&(O=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},O;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===Me.Realtime||this.endpointProvider.type===Me.PassiveRealtime||this.endpointProvider.type===Me.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var Ye=class extends z{constructor(e,t,r){super();this.config=e;this.context=t;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),t={};if(this.disposed)return{};for(let p of e)try{t[p]=await We(this.documentDb,p)}catch(S){this.context.log?.("error",S)}if(this.disposed)return{collections:t};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=await this._fileManager.stats(),a=Object.values(t).reduce((p,{size:S})=>p+S,0),f=r.baselinesSize.size+r.operationsSize.size,u=f/a;return{collections:t,meta:r,storage:o,totalMetaSize:f,totalCollectionsSize:a,metaToDataRatio:u,files:s,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this._fileManager.close(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await ge(this.documentDb),await ge(this.metaDb),e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await ln(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.meta.export(),r=await this._fileManager.exportAll(e),o=[],s=[];for(let a of r){let f=a.file;if(delete a.file,o.push(a),f){let u=new File([f],this.getFileExportName(a.name,a.id),{type:a.type});s.push(u)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:t,fileData:o,files:s}};this.getFileExportName=(e,t)=>`${t}___${e}`;this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.import=async({data:e,fileData:t,files:r})=>{this.context.log("info","Importing data..."),await ge(this.context.documentDb),await this.meta.resetFrom(e);let o=new Map(r.map(p=>{let{id:S}=this.parseFileExportname(p.name);return[S,p]})),s=t.map(p=>{let S=o.get(p.id);return{...p,file:S}});await this._fileManager.importAll(s);let a=e.schema.version,f=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((p,S)=>{f.onsuccess=p,f.onerror=S});let u=this.context.schema;if(u.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await Tt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("info","Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await ge(this.context.documentDb),this.context.log("info","Migrating up to latest schema..."),this.context.schema=u,this.context.documentDb=await Tt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:u.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=()=>this._fileManager.tryCleanupDeletedFiles();this.__manualRebase=()=>this.meta.manualRebase();this.meta=r.meta,this.collectionNames=Object.keys(t.schema.collections),this._sync=this.config.syncConfig&&!t.schema.wip?new ft(this.config.syncConfig,{meta:this.meta,onData:this.addData,ctx:this.context}):new Zn({meta:this.meta}),t.schema.wip&&this.config.syncConfig&&t.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 Ln({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new jn({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new qn({context:t}),this._documentManager=new Sn(this.schema,this._entities);let o=Vr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.("warn",`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?.("warn",`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(t.schema.collections)){let f=s;this[f]=new Kn({collection:f,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get batch(){return this.entities.batch}};var Bt=class{constructor(i){this.value=i}deref(){return this.value}};var ts=Symbol("metadataVersion");var ei=class{constructor(i){this.init=i;this._initializing=!1;this.initialize=async i=>{if(typeof window>"u"&&!i.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 i.schema.wip?e=await this.initializeWIPDatabases(i):(e=await this.initializeDatabases(i),this.cleanupWIPDatabases(i)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async i=>{let e=i[ts],{db:t}=await yn({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:t,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Qe,entityEvents:new z,globalEvents:new z,internalEvents:new z,weakRef:p=>i.EXPERIMENTAL_weakRefs?new WeakRef(p):new Bt(p),migrations:i.migrations,oldSchemas:i.oldSchemas},o=new Dt({context:r,disableRebasing:i.disableRebasing,onOperation:i.onOperation});await o.updateSchema(i.schema,i.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await Tt({context:s,version:i.schema.version,meta:o,migrations:i.migrations,indexedDB:i.indexedDb}),f=Object.assign(s,{documentDb:a});return new Ye({syncConfig:i.sync,migrations:i.migrations,files:i.files},f,{meta:o})};this.initializeWIPDatabases=async i=>{let e=ke(i.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let t=`@@wip_${i.namespace}_${e}`,{db:r}=await so({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,wipNamespace:t}),o={namespace:this._namespace,metaDb:r,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Qe,entityEvents:new z,globalEvents:new z,internalEvents:new z,weakRef:S=>i.EXPERIMENTAL_weakRefs?new WeakRef(S):new Bt(S),migrations:i.migrations,oldSchemas:i.oldSchemas},s=new Dt({context:o,disableRebasing:i.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(i.schema,i.overrideSchemaConflict);let f=await go({context:a,version:i.schema.version,meta:s,migrations:i.migrations,indexedDB:i.indexedDb,wipNamespace:t}),u=Object.assign(a,{documentDb:f});return new Ye({syncConfig:i.sync,migrations:i.migrations,files:i.files},u,{meta:s})};this.cleanupWIPDatabases=async i=>{let r=(await ro(i.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${i.namespace}_${ke(i.schema)}`));for(let o of r)await io(o,i.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 ln(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=i.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};var ir=Ve(et(),1);function Ya(n){return n?ir.default.slug():(0,ir.default)()}var Xa={private:He.onlyMe(),public:void 0};window.Verdant=rr;
|
|
15
|
+
`)}})}async function ga(n){return new Promise((i,e)=>{let t=n.getAllKeys();t.onsuccess=r=>{i(t.result)},t.onerror=r=>{e(t.error)}})}async function ya(n,i){let e=n.delete(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function ba(n,i){let e=n.put(i);return new Promise((t,r)=>{e.onsuccess=o=>{t()},e.onerror=o=>{r(e.error)}})}async function wa({meta:n,currentVersion:i,newVersion:e}){let t=[];return await n.operations.iterateOverAllOperations(r=>t.push(r),{from:n.time.zero(i+1)}),Array.from(new Set(t.map(r=>$(r.oid))))}function va({migration:n,indexedDB:i=go,namespace:e,context:t}){return lo(i,e,n.newSchema.version,(r,o)=>{for(let s of n.addedCollections)o.createObjectStore(s,{keyPath:n.newSchema.collections[s].primaryKey,autoIncrement:!1});for(let s of n.allCollections){let a=r.objectStore(s);for(let d of n.addedIndexes[s]||[])a.createIndex(d.name,d.name,{multiEntry:d.multiEntry});for(let d of n.removedIndexes[s]||[])a.deleteIndex(d.name)}for(let s of n.removedCollections)r.objectStore(s).clear()},t.log)}var at=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function Pt({currentVersion:n,targetVersion:i,migrations:e}){let t=yo({currentVersion:n,targetVersion:i,migrations:e});if(!t)throw new at(`No migration path found from ${n} to ${i}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return t}function yo({currentVersion:n,targetVersion:i,migrations:e}){if(n===i)return[];let t=e.filter(r=>r.oldSchema.version===n).sort((r,o)=>o.newSchema.version-r.newSchema.version);for(;t.length>0;){let r=t.shift();if(r.newSchema.version>i)return null;if(r.newSchema.version===i)return[r];let o=yo({currentVersion:r.newSchema.version,targetVersion:i,migrations:e});if(o)return[r,...o]}return null}var xa=typeof window<"u"?window.indexedDB:void 0;async function bo({version:n,indexedDB:i=xa,migrations:e,meta:t,context:r,wipNamespace:o}){r.log("debug","Opening WIP database",o);let s=await bn(i,o,n,r.log);if(s===n)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 a=Pt({currentVersion:s,targetVersion:n-1,migrations:e});if(a.length>0){await Ct({context:r,toRun:a,meta:t,indexedDB:i,namespace:o});let u=await Ue({indexedDB:i,namespace:r.namespace,version:n-1,context:r}),p=await Ue({indexedDB:i,namespace:o,version:n-1,context:r});await fo(u,p)}let d=Pt({currentVersion:n-1,targetVersion:n,migrations:e});d.length>0&&await Ct({context:r,toRun:d,meta:t,indexedDB:i,namespace:o})}return Ue({indexedDB:i,namespace:o,version:n,context:r})}var Je=class extends z{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();if(e){let t=await e();return t&&this._undone.push(t),this.emit("change"),!0}return!1};this.redo=async()=>{let e=this._undone.pop();if(e){let t=await e();return t&&this._undoable.push(t),this.emit("change"),!0}return!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var Sn=class{constructor(i,e){this.schema=i;this.entities=e;this.getOid=(i,e)=>{let t=this.schema.collections[i].primaryKey,r=e[t];return L(r,`Document must have a primary key: ${t.toString()} (got: ${JSON.stringify(e)})`),Y(i,r)};this.addDefaults=(i,e)=>{let t=this.schema.collections[i];return Fe(t,e)};this.validate=(i,e)=>{let t=this.schema.collections[i];return Xr(t.fields,e)};this.create=async(i,e,t={})=>{let r=t,o=this.addDefaults(i,e),s=this.validate(i,o),a=this.getOid(i,s);if(t.access){let d=this.schema.collections[i];t.access!=="shared"&&e[d.primaryKey]&&!t.silenceAccessControlWithPrimaryKeyWarning&&console.warn("Using a custom primary key with access control is not supported. This may result in corrupted documents. Read more about why: https://verdant.dev/docs/sync/access#a-warning-about-custom-primaryKey"),r.access=t.access}return this.entities.create(s,a,r)};this.delete=async(i,e,t={})=>{let r=Y(i,e);return this.entities.delete(r,t)};this.deleteAll=async(i,e={})=>this.entities.deleteAll(i.map(([t,r])=>Y(t,r)),e);this.deleteAllFromCollection=async(i,e,t={})=>this.entities.deleteAll(e.map(r=>Y(i,r)),t);this.clone=async(i,e,t={})=>{if(!Gt(e.uid))throw new Error("Cannot clone non-root documents");let r=e.getSnapshot(),o=this.schema.collections[i];if(delete r[o.primaryKey],!o.fields[o.primaryKey].default){if(!t.primaryKey)throw new Error(`Error cloning document from collection ${i}: collection does not have a default on primary key. You must supply a value to options.primaryKey for the clone.`);r[o.primaryKey]=t.primaryKey}return this.create(i,r,t)}}};var ji=Be(Ne(),1);function Sa(n){return{id:(0,ji.default)(),file:n,url:void 0,remote:!1,name:n.name,type:n.type}}function ct(n,i){if(typeof window<"u"&&it(n)){let e=Sa(n);return i(e),vt(e.id)}if(Xt(n)){let e={...n,id:(0,ji.default)()};return i(e),vt(e.id)}if(Array.isArray(n)){for(let e=0;e<n.length;e++)n[e]=ct(n[e],i);return n}if(typeof n=="object"){for(let e in n)n[e]=ct(n[e],i);return n}return n}function wo(n){return"__testReadBuffer"in n?n.__testReadBuffer:new Promise((i,e)=>{let t=new FileReader;t.onload=()=>{i(t.result)},t.onerror=e,t.readAsArrayBuffer(n)})}var lt=Symbol("entity-file-update"),At=Symbol("entity-file-mark-failed"),Mi=Symbol("entity-file-mark-uploaded"),Oa,Ia,_a,fe=class extends z{constructor(e,{downloadRemote:t=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._downloadRemote=!1;this[Oa]=e=>{this._loading=!1,this._failed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[Ia]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this[_a]=()=>{this._fileData&&(this._fileData.remote=!0,this.emit("change"))};this.destroy=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this.dispose()};this._downloadRemote=t}static{Oa=lt,Ia=At,_a=Mi}get downloadRemote(){return this._downloadRemote}get isFile(){return!0}get isUploaded(){return this._fileData?.remote??!1}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}getSnapshot(){return this._fileData?this._fileData:{id:this.id,url:this._objectUrl??void 0,name:this.name??"unknown-file",remote:!1,type:this.type??""}}};var On=class{constructor({initial:i}={}){this.cache=new Map;this.get=i=>{if(this.cache.has(i.oid))return this.cache.get(i.oid);let e=new he(i);return this.cache.set(i.oid,e),e};this.has=i=>this.cache.has(i);this.getFile=(i,e)=>{if(this.cache.has(i))return this.cache.get(i);let t=new fe(i,e);return this.cache.set(i,t),t};this.getCached=i=>this.cache.get(i);if(i)for(let e of i)this.cache.set(e.oid,e)}};function vo(n,i,e){let t={previousValue:n.get(i),isLocal:!1};function r(o){if(n.deleted)return;let s=n.get(i);s!==this.previousValue&&(this.isLocal=o.isLocal,e(s,this),this.previousValue=s)}return n.subscribe("change",r.bind(t))}var he=class n extends z{constructor({oid:e,schema:t,entityFamily:r,parent:o,ctx:s,metadataFamily:a,readonlyKeys:d,files:u,patchCreator:p,storeEvents:S,deleteSelf:w}){super();this.fieldPath=[];this._viewData=void 0;this.validationError=void 0;this.cachedDeepUpdatedAt=null;this.wasDeletedLastChange=!1;this.cachedView=void 0;this.onAdd=(e,t)=>{t.oid===this.oid&&this.addConfirmedData(t)};this.onReplace=(e,t)=>{t.oid===this.oid&&this.replaceAllData(t)};this.onResetAll=()=>{this.resetAllData()};this.childIsNull=e=>{if(e instanceof n){let t=e.view;return t==null}return e==null};this.getFieldSchema=e=>{let t=Ve(this.schema,e);return L(t,`No schema for key ${e}`),t};this.validate=no(()=>(this.validationError=Te({field:this.schema,value:this.rawView,fieldPath:this.fieldPath,depth:1})??void 0,this.validationError),()=>[this.viewData]);this.viewWithMappedChildren=e=>{let t=this.view;if(!t)return null;if(Array.isArray(t)){let r=t.map(o=>o instanceof n||o instanceof fe?e(o):o);return N(r,this.oid),r}else{let r=Object.entries(t).reduce((o,[s,a])=>(a instanceof n||a instanceof fe?o[s]=e(a):o[s]=a,o),{});return N(r,this.oid),r}};this.getSnapshot=()=>this.viewWithMappedChildren(e=>e.getSnapshot());this.addPendingOperations=e=>{if(this.ctx.log("debug","Entity: adding pending operations",this.oid),this.access)for(let r of e)r.authz=this.access;let t=this.metadataFamily.addPendingData(e);for(let r of t)this.change(r)};this.addConfirmedData=e=>{this.ctx.log("debug","Entity: adding confirmed data",this.oid);let t=this.metadataFamily.addConfirmedData(e);for(let r of t)this.change(r)};this.replaceAllData=e=>{this.ctx.log("debug","Entity: replacing all data",this.oid);let t=this.metadataFamily.replaceAllData(e);for(let r of t)this.change(r)};this.resetAllData=()=>{this.ctx.log("debug","Entity: resetting all data",this.oid),this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this._viewData=void 0;let e=this.metadataFamily.replaceAllData({});for(let t of e)this.change(t)};this.invalidateCachedView=()=>{this._viewData=void 0,this.cachedView=void 0};this.change=e=>{if(e.oid===this.oid)this.invalidateCachedView(),this.parent?this.changeNested(e):this.changeRoot(e);else{let t=this.entityFamily.getCached(e.oid);t&&t instanceof n&&t.change(e)}};this.changeRoot=e=>{this.deleted?this.wasDeletedLastChange||(this.ctx.log("debug","Entity deleted",this.oid),this.emit("delete",{isLocal:e.isLocal}),this.wasDeletedLastChange=!0):(this.wasDeletedLastChange&&(this.ctx.log("debug","Entity restored",this.oid),this.emit("restore",{isLocal:e.isLocal}),this.wasDeletedLastChange=!1),this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal}))};this.changeNested=e=>{this.deepChange(this,e),this.emit("change",{isLocal:e.isLocal})};this.deepChange=(e,t)=>{this.cachedDeepUpdatedAt=null,this.cachedView=void 0,this.emit("changeDeep",e,t),this.parent?.deepChange(e,t)};this.getChild=(e,t)=>{let r=Ve(this.schema,e);if(!r)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);return this.entityFamily.get({oid:t,schema:r,entityFamily:this.entityFamily,metadataFamily:this.metadataFamily,parent:this,ctx:this.ctx,files:this.files,fieldPath:[...this.fieldPath,e],patchCreator:this.patchCreator,storeEvents:this.storeEvents,deleteSelf:this.delete.bind(this,e)})};this.subscribeToField=(e,t,r)=>vo(this,e,r);this.get=e=>{Li(e);let t=this.rawView;if(!t)throw new Error(`Cannot access data at key ${e} on deleted entity ${this.oid}`);let r=t[e],o=Ve(this.schema,e);if(!o)throw new Error(`No schema for key ${String(e)} in ${JSON.stringify(this.schema)}`);if(Q(r))if(we(r)){if(o.type!=="file")throw new Error(`Expected file schema for key ${String(e)}, got ${o.type}`);let s=this.files.get(r.id,{downloadRemote:!!o.downloadRemote});return s.subscribe("change",()=>{this.deepChange(this,{isLocal:!1,oid:this.oid})}),s}else return this.getChild(e,r.id);else return this.schema.type==="map"&&r===void 0?void 0:Te({field:o,value:r,fieldPath:[...this.fieldPath,e],depth:1,requireDefaults:!0})?Re(o)?_i(o):xe(o)?null:void 0:r};this.getOrSet=(e,t)=>{Li(e);let r=this.get(e);return r||(this.set(e,t),this.get(e))};this.processInputValue=(e,t)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);it(e)||(e=le(e,!1));let r=Ve(this.schema,t);if(r){Ke(e,r);let o=Te({field:r,value:e,fieldPath:[...this.fieldPath,t]});if(o)throw new Error(`Validation error: ${o.message}`,{cause:o})}return ct(e,this.files.add)};this.getDeleteMode=e=>{if(this.readonlyKeys.includes(e))return!1;if(this.schema.type==="any"||this.schema.type==="map")return"delete";if(this.schema.type==="object"){let t=this.schema.properties[e];if(!t||t.type==="any")return"delete";if(t.type==="map")return!1;if(t.nullable)return"null"}return!1};this.getItemRefValue=e=>{if(e instanceof n)return ae(e.oid);if(e instanceof fe)return vt(e.id);if(typeof e=="object"){let t=me(e);if(!t||!this.entityFamily.has(t))throw new Error(`Cannot move object ${JSON.stringify(e)} which does not exist in this list`);return ae(t)}else return e};this.set=(e,t,r)=>{Li(e),!(!r?.force&&this.get(e)===t)&&(this.isList?this.addPendingOperations(this.patchCreator.createListSet(this.oid,e,this.processInputValue(t,e))):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,this.processInputValue(t,e))))};this.getAll=()=>this.view;this.delete=e=>{if(this.isList)Da(e),this.addPendingOperations(this.patchCreator.createListDelete(this.oid,e));else{let t=this.getDeleteMode(e);if(!t)throw new Error(`Cannot delete key ${e.toString()} - the property is not marked as optional in the schema.`);t==="delete"?this.addPendingOperations(this.patchCreator.createRemove(this.oid,e)):this.addPendingOperations(this.patchCreator.createSet(this.oid,e,null))}};this.keys=()=>this.view?Object.keys(this.view):[];this.entries=()=>this.view?Object.entries(this.view):[];this.values=()=>this.view?Object.values(this.view):[];this.update=(e,{merge:t=!0,replaceSubObjects:r=!1,preserveUndefined:o=!1}={})=>{if(!t&&this.schema.type!=="any"&&this.schema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');let s={};N(s,this.oid);for(let[a,d]of Object.entries(e)){if(this.readonlyKeys.includes(a))throw new Error(`Cannot set readonly key ${a.toString()}`);if(d===void 0&&!o)continue;let u=Ve(this.schema,a);u&&Ke(d,u),s[a]=this.processInputValue(d,a)}this.addPendingOperations(this.patchCreator.createDiff(this.getSnapshot(),s,{mergeUnknownObjects:!r,defaultUndefined:t}))};this.push=e=>{this.addPendingOperations(this.patchCreator.createListPush(this.oid,this.processInputValue(e,this.view.length)))};this.insert=(e,t)=>{this.addPendingOperations(this.patchCreator.createListInsert(this.oid,e,this.processInputValue(t,e)))};this.move=(e,t)=>{this.addPendingOperations(this.patchCreator.createListMoveByIndex(this.oid,e,t))};this.moveItem=(e,t)=>{let r=this.getItemRefValue(e);if(Q(r))this.addPendingOperations(this.patchCreator.createListMoveByRef(this.oid,r,t));else{let o=this.view.indexOf(e);if(o===-1)throw new Error(`Cannot move item ${JSON.stringify(e)} which does not exist in this list`);this.move(o,t)}};this.add=e=>{this.addPendingOperations(this.patchCreator.createListAdd(this.oid,this.processInputValue(e,this.view.length)))};this.removeAll=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e)))};this.removeFirst=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"first"))};this.removeLast=e=>{this.addPendingOperations(this.patchCreator.createListRemove(this.oid,this.getItemRefValue(e),"last"))};this.map=e=>this.view.map(e);this.filter=e=>this.view.filter(e);this.has=e=>{if(!this.isList)throw new Error("has() is only available on list entities");let t=this.getItemRefValue(e);return Q(t)?this.view.some(r=>{if(Q(r))return tt(r,t)}):this.view.includes(e)};this.forEach=e=>{this.view.forEach(e)};this.reduce=(e,t)=>this.view.reduce(e,t);this.some=e=>this.view.some(e);this.every=e=>this.view.every(e);this.find=e=>this.view.find(e);this.includes=this.has;this.deleteSelf=()=>this._deleteSelf();this.__getViewData__=(e,t)=>this.metadataFamily.get(e).computeView(t==="confirmed");this.__getFamilyOids__=()=>this.metadataFamily.getAllOids();this.__discardPendingOperation__=e=>{this.metadataFamily.discardPendingOperation(e),this.invalidateCachedView()};L(!!e,"oid is required"),this.oid=e,this.readonlyKeys=d||[],this.ctx=s,this.files=u,this.schema=t,this.entityFamily=r||new On({initial:[this]}),this.patchCreator=p,this.metadataFamily=a,this.storeEvents=S,this.parent=o,this._deleteSelf=w,this.parent||(S.add.attach(this.onAdd),S.replace.attach(this.onReplace),S.resetAll.attach(this.onResetAll))}get metadata(){return this.metadataFamily.get(this.oid)}get viewData(){return this._viewData===void 0&&(this._viewData=this.metadata.computeView(),this.validate()),this._viewData}get rawView(){return this.viewData.view}get view(){if(this.cachedView!==void 0)return this.cachedView;if(this.viewData.deleted)return null;let e=this.rawView;if(!e&&!xe(this.schema)||this.schema.type==="array"&&!Array.isArray(e)||(this.schema.type==="object"||this.schema.type==="map")&&!U(e))return Re(this.schema)?_i(this.schema):null;if(this.cachedView=this.isList?[]:{},N(this.cachedView,this.oid),Array.isArray(e)){let r=Ve(this.schema,0);if(!r)this.ctx.log("error","No child field schema for list entity.",this.oid);else for(let o=0;o<e.length;o++){let s=this.get(o);this.childIsNull(s)&&!xe(r)?this.ctx.log("error","Child missing in non-nullable field",this.oid,"index:",o):this.cachedView.push(s)}}else if(U(e)){let r=this.schema.type==="object"?Object.keys(this.schema.properties):Object.keys(e);for(let o of r){let s=Ve(this.schema,o);if(!s){this.ctx.log("error","No child field schema for object entity at key",o),this.schema.type==="map"?this.cachedView={}:this.cachedView=null;break}let a=this.get(o);if(this.childIsNull(a)&&!xe(s)){if(this.ctx.log("error","Child entity is missing for non-nullable field",this.oid,"key:",o),this.schema.type!=="map"){this.cachedView=null;break}}else this.cachedView[o]=a}}return this.cachedView}get uid(){return this.oid}get deleted(){return this.viewData.deleted||this.view===null}get invalid(){return!!this.validate()}get isList(){return this.schema.type==="array"||Array.isArray(this.viewData.view)}get updatedAt(){return this.viewData.updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let e=this.updatedAt;return this.isList?this.forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}):this.values().forEach(t=>{if(t instanceof n){let r=t.deepUpdatedAt;r&&(!e||r>e)&&(e=r)}}),this.cachedDeepUpdatedAt=e,e}get isOutdatedVersion(){return this.parent?this.parent.isOutdatedVersion:this.viewData.fromOlderVersion}get namespace(){return this.ctx.namespace}get access(){return this.viewData.authz}get isAuthorized(){return!!this.access}get size(){return this.isList?this.length:this.keys().length}get length(){return this.view.length}[Symbol.iterator](){let e=0,t=this.view?.length;return{next:()=>e<t?{value:this.get(e++),done:!1}:{value:void 0,done:!0}}}};function Li(n){if(typeof n=="symbol")throw new Error("Symbol keys aren't supported")}function Da(n){if(typeof n!="number")throw new Error("Only number keys are supported in list entities")}var Vi=class{constructor({oid:i,ctx:e,confirmedOperations:t,pendingOperations:r,baseline:o}){this.baseline=null;this.confirmedOperations=[];this.pendingOperations=[];this.computeView=(i=!1)=>{let e=le(this.baseline?.snapshot??void 0),t=this.baseline?.timestamp??null,r=this.baseline?.authz,o=this.applyOperations(e,!e,this.confirmedOperations,t,t);o.futureSeen&&this.ctx.globalEvents.emit("futureSeen",o.futureSeen),o.authz&&(r=o.authz);let s=i?o:this.applyOperations(o.view,o.deleted,this.pendingOperations,o.latestTimestamp,null);s.authz&&(r=s.authz),s.view&&N(s.view,this.oid);let a=!!o.latestTimestamp&&li(o.latestTimestamp,this.ctx.getNow())<0,d=!this.baseline&&!this.pendingOperations.length&&!this.confirmedOperations.length;d&&this.ctx.log("warn",`Tried to load Entity ${this.oid} with no data`);let u=s.latestTimestamp??o.latestTimestamp??t,p=u?di(u):0;if(!s.view&&!s.deleted&&!d){this.ctx.log("warn",`Entity ${this.oid} has no view, no deleted flag, and not empty`);debugger}return{view:s.view??void 0,deleted:s.deleted,empty:d,fromOlderVersion:a,updatedAt:p,latestTimestamp:u,authz:r}};this.addBaseline=i=>{if(!(this.baseline&&this.baseline.timestamp>=i.timestamp))for(this.baseline=i;this.confirmedOperations[0]?.timestamp<i.timestamp;)this.confirmedOperations.shift()};this.addConfirmedOperations=i=>{let e=0;for(let t of i){let r=this.confirmedOperations.findIndex(s=>s.timestamp>=t.timestamp);r!==-1?this.confirmedOperations[r].timestamp!==t.timestamp&&(this.confirmedOperations.splice(r,0,t),e++):(this.confirmedOperations.push(t),e++);let o=this.pendingOperations.length;this.discardPendingOperation(t),e-=o-this.pendingOperations.length}return e};this.addPendingOperation=i=>{this.pendingOperations.push(i)};this.discardPendingOperation=i=>{this.pendingOperations=this.pendingOperations.filter(e=>e.timestamp!==i.timestamp)};this.applyOperations=(i,e,t,r,o)=>{let s,a,d=this.ctx.getNow();for(let u of t)if(!(o&&u.timestamp<=o)){if(li(u.timestamp,d)>0){s=u.timestamp;continue}u.data.op==="delete"?e=!0:(i=$e(i,u.data),u.data.op==="initialize"&&(e=!1,u.authz&&(a=u.authz))),(!r||u.timestamp>r)&&(r=u.timestamp)}return{view:i,latestTimestamp:r??null,deleted:e,futureSeen:s,authz:a}};L(i,"oid is required"),this.ctx=e,this.oid=i,t&&(this.confirmedOperations=t),r&&(this.pendingOperations=r),o&&(this.baseline=o)}},In=class{constructor({ctx:i,onPendingOperations:e,rootOid:t}){this.entities=new Map;this.get=i=>(L(i,"oid is required"),this.entities.has(i)||this.entities.set(i,new Vi({oid:i,ctx:this.ctx})),this.entities.get(i));this.getAllOids=()=>Array.from(this.entities.keys());this.addConfirmedData=({baselines:i=[],operations:e={},isLocal:t=!1})=>{let r={};for(let o of i){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o)}for(let[o,s]of Object.entries(e)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s)!==0&&(r[o]??={oid:o,isLocal:t})}return Object.values(r)};this.addPendingData=i=>{let e={};for(let t of i)this.get(t.oid).addPendingOperation(t),e[t.oid]??={oid:t.oid,isLocal:!0};return this.onPendingOperations(i),Object.values(e)};this.replaceAllData=({operations:i={},baselines:e=[]})=>{let t=Array.from(this.entities.keys());this.entities.clear();let r={};for(let o of t)r[o]={oid:o,isLocal:!1};for(let o of e){if(!Ce(this.rootOid,o.oid))throw new Error(`Invalid baseline for entity ${this.rootOid}: `+JSON.stringify(o));this.get(o.oid).addBaseline(o),r[o.oid]??={oid:o.oid,isLocal:!1}}for(let[o,s]of Object.entries(i)){if(!Ce(this.rootOid,o))throw new Error(`Invalid operations for entity ${this.rootOid}: `+JSON.stringify(s));this.get(o).addConfirmedOperations(s),r[o]??={oid:o,isLocal:!1}}return Object.values(r)};this.discardPendingOperation=i=>{this.entities.get(i.oid)?.discardPendingOperation(i)};this.ctx=i,this.rootOid=t,this.onPendingOperations=e}};var Rt="@@default",_n=class{constructor({batchTimeout:i=200,meta:e,ctx:t,entities:r}){this.currentBatchKey=Rt;this.flushOperations=async(i,e,t)=>{if(this.ctx.log("debug","Flushing",i.length,"operations from batch",e,"to storage / sync"),!i.length)return;let r=[],o={};for(let s=i.length-1;s>=0;s--){let a=i[s],d=o[a.oid];if(d&&Wr(a,d)){this.entities.discardPendingOperation(a);continue}let u=Hr(a);u!==!1&&(o[a.oid]||(o[a.oid]=new Set),o[a.oid].add(u)),r.unshift(a)}for(let s of r)s.timestamp=this.meta.now;await this.commitOperations(r,t)};this.commitOperations=async(i,e)=>{if(i.length){if(e.undoable){let t=await this.createUndo({ops:i,source:e.source});t&&this.ctx.undoHistory.addUndo(t)}await this.entities.addData({operations:i,baselines:[],isLocal:!0})}};this.addOperations=i=>{i.length&&(this.batcher.add({key:this.currentBatchKey,items:i}),this.ctx.log("debug","added",i.length,"ops to batch",this.currentBatchKey,", size = ",this.batcher.getSize(this.currentBatchKey)))};this.batch=({undoable:i=!0,batchName:e=Yt(),max:t=null,timeout:r=this.defaultBatchTimeout}={})=>{let o=this.batcher.add({key:e,max:t,timeout:r,items:[],userData:{undoable:i}}),s={run:a=>(this.currentBatchKey=e,a(),this.currentBatchKey=Rt,s),commit:async()=>(await this.batcher.flush(Rt),o.flush()),flush:()=>s.commit(),discard:()=>{this.batcher.discard(e)}};return s};this.flushAll=()=>Promise.all(this.batcher.flushAll());this.createUndo=async i=>{let e=await this.getInverseOperations(i);return e.length?async()=>{let t=await this.createUndo({ops:e,source:i.source});for(let r of e)r.timestamp=this.meta.now;return await this.commitOperations(e,{undoable:!1}),t}:null};this.getInverseOperations=async({ops:i,source:e})=>{let t=Ot(i),r=[],o=()=>this.meta.now;return await Promise.all(Object.entries(t).map(async([s,a])=>{let u=(e??await this.entities.hydrate($(s)))?.__getViewData__(s,"confirmed");if(!u){this.ctx.log("warn","could not find entity",s,"for undo operation",i);return}let p=to(s,u.view,a,o);r.unshift(...p)})),r};this.meta=e,this.ctx=t,this.entities=r,this.defaultBatchTimeout=i,this.batcher=new ot(this.flushOperations),this.batcher.add({key:Rt,items:[],max:100,timeout:i,userData:{undoable:!0}})}get isDefaultBatch(){return this.currentBatchKey===Rt}};var Dn=class extends se{constructor({ctx:e}){super(e.documentDb,{log:e.log});this.reset=async()=>{let e=Object.keys(this.ctx.schema.collections),t=this.createTransaction(e,{mode:"readwrite"});await Promise.all(e.map(r=>{let o=t.objectStore(r);return J(o.clear())})),this.ctx.entityEvents.emit("collectionsChanged",e),this.ctx.log("info","\u{1F4A8} Reset queryable storage")};this.saveEntities=async(e,t)=>{if(e.length===0)return;let r=Array.from(new Set(e.map(a=>ce(a.oid).collection))),o=r.filter(a=>!this.ctx.schema.collections[a]);if(o.length>0){this.ctx.log("warn",`Ignoring entities from collections that no longer exist: ${o.join(", ")}`);let a=new Set(r);o.forEach(d=>a.delete(d)),r=Array.from(a)}let s={transaction:this.createTransaction(r,{mode:"readwrite",abort:t?.abort})};await Promise.all(e.map(async a=>{let d=a.getSnapshot();try{await this.saveDocument(a.oid,d,s)}catch(u){throw this.ctx.log("error",`Error saving document ${a.oid} (${JSON.stringify(d)})`,u),u instanceof Error?u:new Error("Unknown error saving document")}})),s.transaction.commit(),this.ctx.entityEvents.emit("collectionsChanged",r);for(let a of e)this.ctx.entityEvents.emit("documentChanged",a.oid)};this.saveDocument=async(e,t,{transaction:r})=>{this.ctx.log("debug",`Saving document indexes for querying ${e}`,t);let{collection:o,id:s}=ce(e);if(!t)await this.run(o,a=>a.delete(s),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Deleted document indexes for querying ${e}`);else{let a=this.ctx.schema.collections[o],d=rn(a,t);await this.run(o,u=>u.put(d),{mode:"readwrite",transaction:r}),this.ctx.log("debug",`Saved document indexes for querying ${e}`,t)}};this.ctx=e,this.addDispose(this.ctx.internalEvents.subscribe("documentDbChanged",t=>{this.db=t}))}};var kn=Be(es(),1);var jn=class extends _e{constructor({ctx:e,meta:t,files:r}){super();this.events={add:new kn.WeakEvent,replace:new kn.WeakEvent,resetAll:new kn.WeakEvent};this.cache=new Map;this.pendingEntityPromises=new Map;this.abortDataQueueController=new AbortController;this.ongoingResetPromise=null;this.entityFinalizationRegistry=new FinalizationRegistry(e=>{this.ctx.log("debug","Entity GC",e)});this.addData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not adding incoming data");return}e.reset&&(this.ctx.log("info","Resetting local store to replicate remote synced data - dropping any current transactions"),this.abortDataQueueController.abort(0),this.abortDataQueueController=new AbortController,this.ongoingResetPromise=this.resetData().finally(()=>{this.ongoingResetPromise=null,this.ctx.globalEvents.emit("resetToServer")})),this.ongoingResetPromise&&(this.ctx.log("debug","Waiting for ongoing reset to complete"),await this.ongoingResetPromise,this.ctx.log("debug","Ongoing reset complete")),await this.processData(e)};this.empty=async()=>{await this.queryableStorage.reset(),this.events.resetAll.invoke(this),this.cache.clear()};this.resetData=async()=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not resetting local data");return}await this.meta.reset(),await this.queryableStorage.reset(),this.events.resetAll.invoke(this)};this.processData=async e=>{if(this.disposed){this.ctx.log("warn","EntityStore is disposed, not processing incoming data");return}let t=e?.baselines??[],r=e?.operations??[];this.ctx.log("debug","Processing incoming data",{operations:r.length,baselines:t.length,reset:!!e.reset});let o=Array.from(new Set(t.map(p=>$(p.oid)).concat(r.map(p=>$(p.oid))))),s=qr(t),a=Kr(r);this.ctx.log("debug","Applying data to live entities");for(let p of o){let S=s[p],w=a[p]??[],C=Ot(w),g=e.reset?this.events.replace:this.events.add,v=this.pendingEntityPromises.get(p);v?v.then(()=>{g.invoke(this,{oid:p,baselines:S,operations:C,isLocal:!1})}):g.invoke(this,{oid:p,baselines:S,operations:C,isLocal:!1})}let d={abort:this.abortDataQueueController.signal};await this.meta.insertData(e,d);let u=await Promise.all(o.map(async p=>await this.hydrate(p,d)??{oid:p,getSnapshot(){return null}}));try{await this.queryableStorage.saveEntities(u,d)}catch(p){this.disposed?this.ctx.log("warn","Error saving entities to queryable storage - EntityStore is disposed",p):this.ctx.log("error","Error saving entities to queryable storage",p)}};this.hydrate=async(e,t)=>{if(!Gt(e))throw new Error("Cannot hydrate non-root entity");if(this.cache.has(e)){this.ctx.log("debug","Hydrating entity from cache",e);let o=this.cache.get(e);if(o){let s=o.deref();if(s)return s.deleted?null:s;this.ctx.log("debug","Removing GC'd entity from cache",e),this.cache.delete(e)}}let r=this.pendingEntityPromises.get(e);if(r)return this.ctx.log("debug","Waiting for entity hydration",e),r;{this.ctx.log("debug","Hydrating entity from storage",e);let o=this.constructEntity(e);if(!o)return null;let s=this.loadEntity(o,t);return s.finally(()=>{this.pendingEntityPromises.delete(e)}),this.pendingEntityPromises.set(e,s),s}};this.destroy=async()=>{this.dispose(),await this.batcher.flushAll()};this.create=async(e,t,{undoable:r=!0,access:o}={})=>{this.ctx.log("debug","Creating new entity",t);let{collection:s}=ce(t);Wt(e);let a=ct(e,this.files.add);N(a,t);let d=this.constructEntity(t);if(!d)throw new Error(`Could not put new document: no schema exists for collection ${s}`);let u=this.meta.patchCreator.createInitialize(a,t);o&&u.forEach(S=>{S.authz=o}),await this.batcher.commitOperations(u,{undoable:!!r,source:d});let p=Ot(u);return this.events.add.invoke(this,{operations:p,isLocal:!0,oid:t}),this.cache.set(t,this.ctx.weakRef(d)),d};this.deleteAll=async(e,t)=>{this.ctx.log("info","Deleting documents",e),L(e.every(s=>s===$(s)),"Only root documents may be deleted via client methods");let r=await Promise.all(e.map(s=>this.hydrate(s)));e.forEach(s=>{this.cache.delete(s),this.ctx.log("debug","Deleted document from cache",s)});let o=[];for(let s of r)if(s){let a=s.__getFamilyOids__(),d=this.meta.patchCreator.createDeleteAll(a);for(let u of d)u.authz=s.access;o.push(...d)}await this.batcher.commitOperations(o,{undoable:t?.undoable===void 0?!0:t.undoable})};this.delete=async(e,t)=>this.deleteAll([e],t);this.getCollectionSchema=e=>{let t=this.ctx.schema.collections[e];return t?{schema:{type:"object",nullable:!1,properties:t.fields},readonlyKeys:[t.primaryKey]}:(this.ctx.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]})};this.constructEntity=e=>{let{collection:t}=ce(e),{schema:r,readonlyKeys:o}=this.getCollectionSchema(t);if(!r)return null;if(this.disposed)throw new Error("Cannot hydrate entity after store has been disposed");let s=new In({ctx:this.ctx,onPendingOperations:this.onPendingOperations,rootOid:e});return new he({ctx:this.ctx,oid:e,schema:r,readonlyKeys:o,files:this.files,metadataFamily:s,patchCreator:this.meta.patchCreator,storeEvents:this.events,deleteSelf:this.delete.bind(this,e)})};this.onPendingOperations=e=>{this.batcher.addOperations(e)};this.discardPendingOperation=e=>{let t=$(e.oid);this.cache.get(t)?.deref()?.__discardPendingOperation__(e)};this.loadEntity=async(e,t)=>{let{operations:r,baselines:o}=await this.meta.getDocumentData(e.oid,t);return!o.length&&!Object.keys(r).length?(this.ctx.log("debug","No data found for entity",e.oid),null):(this.ctx.log("debug","Loaded entity from storage",e.oid),this.events.replace.invoke(this,{oid:e.oid,baselines:o,operations:r,isLocal:!1}),this.cache.set(e.oid,this.ctx.weakRef(e)),this.entityFinalizationRegistry.register(e,e.oid),e)};this.ctx=e,this.meta=t,this.files=r,this.queryableStorage=new Dn({ctx:e}),this.batcher=new _n({ctx:e,meta:t,entities:this})}get batch(){return this.batcher.batch}get flushAllBatches(){return this.batcher.flushAll}};var Mn=class extends se{constructor(){super(...arguments);this.addFile=async(e,{transaction:t,downloadRemote:r=!1}={})=>{let o=e.file?await wo(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}),{mode:"readwrite",transaction:t})};this.hydrateFileData=e=>{e.remote=e.remote==="true";let t=e.buffer;return delete e.buffer,e.file=t?Na(t,e.type):void 0,e};this.markUploaded=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,remote:"true"}),{mode:"readwrite",transaction:t})};this.getFileRaw=async(e,{transaction:t}={})=>{let r=await this.run("files",o=>o.get(e),{mode:"readonly",transaction:t});if(r)return r};this.getFile=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:t}={})=>{let r=await this.getFileRaw(e,{transaction:t});if(!r)throw new Error("File is not in local database");return this.run("files",o=>o.put({...r,deletedAt:Date.now()}),{mode:"readwrite",transaction:t})};this.listUnsynced=async()=>(await this.run("files",t=>t.index("remote").getAll("false"),{mode:"readonly"})).map(this.hydrateFileData);this.resetSyncedStatusSince=async e=>{let t=this.createTransaction(["files"],{mode:"readwrite"}),o=(await this.run("files",s=>s.index("remote").getAll("true"),{transaction:t})).filter(s=>!s.timestamp||!e||s.timestamp>e);await Promise.all(o.map(s=>this.run("files",a=>a.put({...s,remote:"false"}),{transaction:t})))};this.iterateOverPendingDelete=(e,t)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,o)=>{e(this.hydrateFileData(r),o)},{mode:"readwrite",transaction:t});this.getAll=async()=>{let[e]=await cn(this.db,["files"]);return e.map(this.hydrateFileData)};this.stats=async()=>({size:await Qe(this.db,"files")})}deleteFile(e,{transaction:t}={}){return this.run("files",r=>r.delete(e),{mode:"readwrite",transaction:t})}};function Na(n,i){return new Blob([n],{type:i})}function $a(n){return n.deletedAt!==null&&n.deletedAt<Date.now()-1e3*60*24*3}var Ln=class{constructor({db:i,sync:e,context:t,meta:r,config:o={}}){this.files=new Map;this.maxUploadRetries=3;this.maxDownloadRetries=3;this.add=async i=>{if(i.url&&!i.file){let e=await this.downloadRemoteFile(i.url);i.file=new File([e],i.name,{type:i.type})}if(i.remote=!1,this.files.has(i.id))this.files.get(i.id)[lt](i);else{let e=new fe(i.id);e[lt](i),this.files.set(i.id,e)}await this.storage.addFile(i),i.file&&this.sync.status==="active"&&await this.uploadFile(i)};this.uploadFile=async(i,e=0)=>{let t=await this.sync.uploadFile(i);if(t.success){await this.storage.markUploaded(i.id);let r=this.files.get(i.id);r&&r[Mi](),this.context.log("info","File uploaded",i.id)}else t.retry&&e<this.maxUploadRetries?(this.context.log("error",`Error uploading file ${i.id}, retrying...`,t.error),setTimeout(this.uploadFile,1e3,i,e+1)):this.context.log("error",`Failed to upload file ${i.id}. Not retrying until next sync.`,t.error)};this.downloadRemoteFile=async(i,e=0)=>{let t=await fetch(i,{method:"GET",credentials:"include"});if(!t.ok){if(e<this.maxDownloadRetries)return new Promise((o,s)=>{setTimeout(()=>{this.downloadRemoteFile(i,e+1).then(o,s)},1e3)});throw new Error(`Failed to download file: ${t.status}`)}return await t.blob()};this.get=(i,e)=>{if(this.files.has(i))return this.files.get(i);let t=new fe(i,e);return this.files.set(i,t),this.load(t),t};this.load=async(i,e=0)=>{if(e>this.maxDownloadRetries){this.context.log("error","Failed to load file after 5 retries"),i[At]();return}let t=await this.storage.getFile(i.id);if(t)i[lt](t);else try{let r=await this.sync.getFile(i.id);r.success?(i[lt](r.data),await this.storage.addFile(r.data,{downloadRemote:i.downloadRemote})):(this.context.log("error","Failed to load file",r),i[At](),r.retry&&setTimeout(this.load,1e3,i,e+1))}catch(r){this.context.log("error","Failed to load file",r),i[At](),setTimeout(this.load,1e3,i,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.exportAll=async(i=!1)=>{let e=await this.storage.getAll();if(i){for(let t of e)if(!t.file&&t.url)try{let r=await fetch(t.url,{method:"GET",credentials:"include"}).then(o=>o.blob());t.file=r}catch(r){this.context.log("error","Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",r)}}return e};this.importAll=async i=>{await Promise.all(i.map(e=>this.add(e)))};this.onOnlineChange=async i=>{if(i){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let i=0,e=0;await this.storage.iterateOverPendingDelete((t,r)=>{this.config.canCleanupDeletedFile(t)?(i++,r.delete(t.id)):e++}),this.context.log("info",`Cleaned up ${i} files, skipped ${e} files`)};this.handleFileRefsDeleted=async i=>{let e=this.storage.createTransaction(["files"],{mode:"readwrite"});await Promise.all(i.map(async t=>{try{await this.storage.markPendingDelete(t.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${i.length} files as pending delete`)};this.close=()=>{this.storage.dispose()};this.stats=()=>this.storage.stats();this.storage=new Mn(i),this.sync=e,this.context=t,this.meta=r,this.config={canCleanupDeletedFile:$a,...o},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.sync.subscribe("serverReset",this.storage.resetSyncedStatusSince),this.tryCleanupDeletedFiles()}};var Ka=typeof window<"u"?window.indexedDB:void 0;async function Tt({version:n,indexedDB:i=Ka,migrations:e,meta:t,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let o=await bn(i,r.namespace,n,r.log);r.log("debug","Current database version:",o,"target version:",n);let s=Pt({currentVersion:o,targetVersion:n,migrations:e});return s.length>0&&(r.log("debug","Migrations to run:",s.map(a=>a.version)),await Ct({context:r,toRun:s,meta:t,indexedDB:i})),Ue({indexedDB:i,namespace:r.namespace,version:n,context:r})}function qa(n){return n!==null}function er(n){return Array.isArray(n)?n.map(er).filter(qa):n instanceof he&&n.deleted?null:n}function ze(n,i){return!n&&!i||n&&i&&ke(n)===ke(i)}var tr=Symbol("ON_ALL_UNSUBSCRIBED"),pe=Symbol("UPDATE"),Ha,ye=class extends _e{constructor({initial:e,context:t,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);let t=er(e),r=!0;this.status==="initializing"||this.status==="initial"?r=!0:this.isListQuery?this._value.length===t.length&&this._value.every((o,s)=>o===t[s])&&(r=!1):this._value===t&&(r=!1),this._value=t,r&&(this.context.log("debug","Query value changed",this.key),this._events.emit("change",this._value)),this.status="ready"};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(t=>{t instanceof he&&(this._internalUnsubscribes.push(t.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(t.subscribe("restore",this.refreshValue)))}):e instanceof he&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this.status==="initial"?this.status="initializing":this.status==="ready"&&(this.status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error){if(e.name==="InvalidStateError"||e.name==="InvalidAccessError")return this._value;throw e}else throw new Error("Unknown error executing query")}),this._executionPromise);this[Ha]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this.isListQuery=Array.isArray(e),this._events=new z(d=>{d==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=t,this.key=o,this.collection=r;let a=s||(d=>d.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",d=>{a(d)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{Ha=tr}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}set status(e){this._status!==e&&(this._status=e,this._events.emit("statusChange",this._status))}get hasDeleted(){return this.isListQuery?this._rawValue.length!==this._value.length:!!this._rawValue&&!this._value}subscribe(e,t){if(t===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&t!==void 0)return this.resolved,this._events.subscribe("change",t);if(e==="statusChange"&&typeof t=="function")return this._events.subscribe(e,t);throw new Error("Invalid invocation of Query.subscribe")}};var Vn=class extends ye{constructor({id:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Y(r.collection,e),this.hydrate=t}};var Wa,Un=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:null,...r});this.run=async()=>{let e=await vn({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Wa]=e=>{ze(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Wa=pe}};var Qa,zn=class extends ye{constructor({index:e,hydrate:t,pageSize:r,page:o,...s}){super({initial:[],...s});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=t,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[Qa]=e=>{ze(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t,this._pageSize=r,this._page=o}static{Qa=pe}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ja,Nn=class extends ye{constructor({hydrate:e,pageSize:t,index:r,...o}){super({initial:[],...o});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=t,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:t}=await Et({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=t,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ja]=e=>{ze(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=t}static{Ja=pe}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Ga,$n=class extends ye{constructor({index:e,hydrate:t,...r}){super({initial:[],...r});this.run=async()=>{let e=await xn({collection:this.collection,index:this.index,context:this.context});this.context.log("debug",`FindAllQuery: ${e.length} oids found: ${e}`),this.setValue(await Promise.all(e.map(this.hydrate)))};this[Ga]=e=>{ze(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=t}static{Ga=pe}};var Kn=class{constructor({collection:i,cache:e,entities:t,context:r,documentManager:o}){this.serializeIndex=i=>i?ke(i):"";this.get=i=>{let e=`get:${this.collection}:${i}`;return this.cache.getOrSet(e,()=>new Vn({id:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:i,key:e}={})=>{let t=e||`findOne:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new Un({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[pe](i)})};this.findAll=({index:i,key:e}={})=>{let t=e||`findAll:${this.collection}:${this.serializeIndex(i)}`;return this.cache.getOrSet(t,()=>new $n({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:t}),r=>{r[pe](i)})};this.findPage=({index:i,pageSize:e,page:t,key:r})=>{let o=r||`findPage:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(o,()=>new zn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:o,pageSize:e,page:t}),s=>{s[pe](i)})};this.findAllInfinite=({index:i,pageSize:e,key:t})=>{let r=t||`findAllInfinite:${this.collection}:${this.serializeIndex(i)}:${e}`;return this.cache.getOrSet(r,()=>new Nn({index:i,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),o=>{o[pe](i)})};this.cache=e,this.collection=i,this.hydrate=t.hydrate,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),this.clone=this.documentManager.clone.bind(this.documentManager,this.collection)}};var qn=class extends _e{constructor({evictionTime:e=5*1e3,context:t}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this.dropAll=()=>{this._cache.forEach(e=>e.dispose()),this._cache.clear()};this._evictionTime=e,this.context=t}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[tr](this.onQueryUnsubscribed),e}getOrSet(e,t,r){let o=this.get(e);return o?(r?.(o),o):this.set(t())}};var nr=Symbol("handleMessage"),Ya,Bt=class extends z{constructor({initialPresence:e,updateBatchTimeout:t=200,defaultProfile:r,replicaStore:o}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,t)=>e.id===t.replicaId||this._selfReplicaIds.has(t.replicaId)||this._self.id===t.id;this[Ya]=async(e,t)=>{let r=!1,o=!1,s=new Set(this.peerIds);if(t.type==="presence-changed")this.isSelf(e,t.userInfo)?(this._self=t.userInfo,this._selfReplicaIds.add(t.userInfo.replicaId),o=!0,this.emit("selfChanged",t.userInfo)):(s.add(t.userInfo.id),this._peers[t.userInfo.id]=t.userInfo,r=!0,this.emit("peerChanged",t.userInfo.id,t.userInfo));else if(t.type==="sync-resp"){this._peers={},s.clear();for(let[a,d]of Object.entries(t.peerPresence))this.isSelf(e,d)?(this._self=d,this._selfReplicaIds.add(d.replicaId),o=!0,this.emit("selfChanged",d)):(r=!0,s.add(a),this._peers[a]=d,this.emit("peerChanged",a,d))}else if(t.type==="presence-offline"){s.delete(t.userId),this._selfReplicaIds.delete(t.replicaId);let a=this._peers[t.userId];delete this._peers[t.userId],r=!0,this.emit("peerLeft",t.userId,a)}r&&(this._peerIds=Array.from(s).sort(),this.emit("peersChanged",this._peers)),(r||o)&&this.emit("change")};this.update=async e=>{this._updateBatch.update({items:[{presence:e}]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self),this.emit("change")};this.flushPresenceUpdates=e=>{let t={presence:this.self.presence,internal:this.self.internal};for(let r of e)r.presence&&Object.assign(t.presence,r.presence),r.internal&&Object.assign(t.internal,r.internal);this.emit("update",t)};this.setViewId=e=>{this._updateBatch.update({items:[{internal:{viewId:e}}]}),this.self.internal.viewId=e,this.emit("selfChanged",this.self),this.emit("change")};this.setFieldId=(e,t=Date.now())=>{this._updateBatch.update({items:[{internal:{lastFieldId:e,lastFieldTimestamp:t}}]}),this.self.internal.lastFieldId=e,this.emit("selfChanged",this.self),this.emit("change")};this.getViewPeers=()=>this._peerIds.map(e=>this._peers[e]).filter(e=>this.self.internal.viewId===void 0||e.internal.viewId===this.self.internal.viewId);this.getFieldPeers=(e,t=60*1e3)=>this._peerIds.map(r=>this._peers[r]).filter(r=>r.internal.lastFieldId===e&&Date.now()-r.internal.lastFieldTimestamp<t);this.self.presence=e,this.self.profile=r,this.self.internal=Ri,this.self.id="",this.self.replicaId="",o.get().then(s=>{this.self.replicaId=s.id}),this._updateBatcher=new ot(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:t,items:[],key:"default"})}static{Ya=nr}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var Hn=class{constructor({endpointProvider:i,log:e}){this.uploadFile=async i=>{let e=i.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:t,token:r}=await this.endpointProvider.getEndpoints(),o=new FormData;o.append("file",e);try{let s=await fetch(t+`/${i.id}`,{method:"POST",body:o,credentials:"include",headers:{Authorization:`Bearer ${r}`}});if(s.ok)return this.log("info","File upload successful"),{success:!0,retry:!1};{let a=await s.text();return this.log("error","File upload failed",s.status,a),{success:!1,retry:s.status>=500,error:`Failed to upload file: ${s.status} ${a}`}}}catch(s){return this.log("error","File upload failed",s),{success:!1,retry:!0,error:s.message}}};this.getFile=async i=>{let{files:e,token:t}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${i}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`}});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,error:r,retry:!0}}};this.endpointProvider=i,this.log=e}};var ut=class extends z{constructor({interval:e=15*1e3,deadlineLength:t=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.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=t,typeof window<"u"&&r&&(window.addEventListener("pageshow",()=>this.start(!0)),document.addEventListener("visibilitychange",()=>{document.visibilityState==="visible"&&this.start(!0)}))}get interval(){return this._interval}};var Wn=class extends z{constructor({endpointProvider:e,meta:t,presence:r,interval:o=15*1e3,log:s=()=>{},fetch:a=window.fetch.bind(window)}){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:t,token:r}=await this.endpointProvider.getEndpoints(),o=await this.fetch(t,{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(),a=Promise.all(s.messages.map(this.handleServerMessage));this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0)),await a}else{this.log("Sync request failed",o.status,await o.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1));let s=await o.json();io(s)&&s.code===_t.TokenExpired&&(this.endpointProvider.clearCache(),this.heartbeat.keepAlive()),o.status>=500&&this.heartbeat.keepAlive()}}catch(t){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(t),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(this._hasSynced=!0,e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),await this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)]))),this.emit("message",e)};this.throttledPresenceUpdate=Nr(e=>{this.sendRequest([e])},3e3);this.send=e=>{switch(e.type){case"presence-update":return this.throttledPresenceUpdate(e);case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.start=async()=>{this.status!=="active"&&(await this.endpointProvider.getEndpoints(),this.heartbeat.start(!0),this._status="active")};this.destroy=()=>{this.dispose(),this.stop()};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.syncOnce=async()=>{await this.sendRequest([await this.meta.messageCreator.createSyncStep1()])};this.log=s,this.meta=t,this.presence=r,this.endpointProvider=e,this.fetch=a,this.heartbeat=new ut({interval:o}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}get hasSynced(){return this._hasSynced}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}ignoreIncoming(){this.stop()}get isConnected(){return this._isConnected}get status(){return this._status}};function ir(n){this.message=n}ir.prototype=new Error,ir.prototype.name="InvalidCharacterError";var ts=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(n){var i=String(n).replace(/=+$/,"");if(i.length%4==1)throw new ir("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,t,r=0,o=0,s="";t=i.charAt(o++);~t&&(e=r%4?64*e+t:t,r++%4)?s+=String.fromCharCode(255&e>>(-2*r&6)):0)t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(t);return s};function Xa(n){var i=n.replace(/-/g,"+").replace(/_/g,"/");switch(i.length%4){case 0:break;case 2:i+="==";break;case 3:i+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(ts(e).replace(/(.)/g,function(t,r){var o=r.charCodeAt(0).toString(16).toUpperCase();return o.length<2&&(o="0"+o),"%"+o}))}(i)}catch{return ts(i)}}function Qn(n){this.message=n}function Za(n,i){if(typeof n!="string")throw new Qn("Invalid token specified");var e=(i=i||{}).header===!0?0:1;try{return JSON.parse(Xa(n.split(".")[e]))}catch(t){throw new Qn("Invalid token specified: "+t.message)}}Qn.prototype=new Error,Qn.prototype.name="InvalidTokenError";var ns=Za;var Jn=class{constructor(i){this.config=i;this.cached=null;this.tokenInfo=null;this.getEndpoints=async()=>{if(this.cached)return this.cached;let i;this.config.fetchAuth?i=await this.config.fetchAuth():i=await(this.config.fetch||fetch.bind(window))(this.config.authEndpoint,{credentials:"include"}).then(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)}),L(i.accessToken,"No access token provided from auth endpoint");let e=ns(i.accessToken);L(e.url,"No sync endpoint provided from auth endpoint"),L(e.type!==void 0,"No replica type provided from auth endpoint"),this.tokenInfo={userId:e.sub,libraryId:e.lib,url:e.url,fileUrl:e.file,role:e.role,type:parseInt(e.type+"")};let t=new URL(e.url);t.protocol=t.protocol.replace("ws","http");let r=t.toString();t.protocol=t.protocol.replace("http","ws");let o=t.toString(),s=e.file;if(!s){let a=new URL(r);a.pathname=a.pathname+"/files",s=a.toString()}return this.cached={http:r,websocket:o,files:s,token:i.accessToken},this.cached};this.clearCache=()=>{this.cached=null};if(!i.authEndpoint&&!i.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}get type(){return this.tokenInfo?.type??Le.Realtime}};var Gn=class extends z{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}},Yn=class{constructor(i,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=i,this.factor=e}};var Xn=class extends z{constructor({endpointProvider:e,meta:t,presence:r,log:o}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this.incomingQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this._ignoreIncoming=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new ut;this.reconnectScheduler=new Gn(new Yn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),!this.disposed&&(e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e))};this.onMessage=async e=>{if(this._ignoreIncoming){this.log("Ignoring incoming message (ignore incoming flag set)",e.data);return}let t=JSON.parse(e.data);switch(t.type){case"sync-resp":if(t.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(t.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length)if(t.overwriteLocalData)this.log("warn","Overwriting local data - dropping outgoing message queue"),this.syncQueue=[];else{for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}if(this.emit("message",t),this.incomingQueue.length){for(let r of this.incomingQueue)this.emit("message",r);this.incomingQueue=[]}break;case"need-since":case"presence-changed":case"presence-offline":this.emit("message",t);break;case"op-re":if(!this.synced){this.log("Enqueueing op-re message because sync hasn't finished yet",t),this.incomingQueue.push(t);break}this.emit("message",t);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",t);break;default:this.synced&&this.emit("message",t);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.destroy=()=>{this.dispose(),this.stop()};this.start=async()=>{this.socket||(await this.initializeSocket(),this._status="active")};this.stop=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close(),this.socket=null,this._status="paused"};this.log=o||this.log,this.endpointProvider=e,this.meta=t,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get hasSynced(){return this.synced}ignoreIncoming(){this.incomingQueue=[],this._ignoreIncoming=!0}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var Zn=class extends z{constructor({meta:e}){super();this.mode="pull";this.destroy=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1});this.syncOnce=async()=>{};this.presence=new Bt({initialPresence:null,defaultProfile:null,replicaStore:e.localReplica})}send(){}async start(){}stop(){}ignoreIncoming(){}reconnect(){}setMode(){}setPullInterval(){}},ft=class extends z{constructor({authEndpoint:e,fetchAuth:t,fetch:r,initialPresence:o,automaticTransportSelection:s=!0,autoStart:a,initialTransport:d,pullInterval:u,presenceUpdateBatchTimeout:p,defaultProfile:S,useBroadcastChannel:w,onOutgoingMessage:C},{meta:g,ctx:v,onData:_}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message,{source:"broadcastChannel"})};this.onTokenExpired=()=>{this.endpointProvider.clearCache()};this.handleMessage=async(e,{source:t}={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("debug","sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await 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.emit("serverReset",e.since),this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}t==="network"&&this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[nr](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let t;e==="realtime"?t=this.webSocketSync:t=this.pushPullSync,t!==this.activeSync&&(this.log("debug","switching to",e,"mode"),this.activeSync.status==="active"&&t.start(),this.activeSync.stop(),this.activeSync=t)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=async e=>{if(this.activeSync.status==="active"){let t=this.endpointProvider.tokenInfo?.userId;if(!t)throw new st(st.Code.Unexpected,void 0,"Active sync has invalid token info");(e.type==="sync"||e.type==="op")&&ro(e,t),await this.activeSync.send(e),this.onOutgoingMessage?.(e)}};this.uploadFile=async e=>(this.log("info","Uploading file",{name:e.name,type:e.type,id:e.id,size:e.file?.size}),this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1,error:"Sync is not active"});this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.destroy=()=>{this.dispose(),this.webSocketSync.destroy(),this.pushPullSync.destroy()};this.reconnect=()=>this.activeSync.reconnect();this.syncOnce=()=>this.pushPullSync.syncOnce();if(this.meta=g,this.onData=_,this.log=v.log,this.onOutgoingMessage=C,this.presence=new Bt({initialPresence:o,defaultProfile:S,updateBatchTimeout:p,replicaStore:g.localReplica}),this.endpointProvider=new Jn({authEndpoint:e,fetchAuth:t,fetch:r}),this.webSocketSync=new Xn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:v.log}),this.pushPullSync=new Wn({endpointProvider:this.endpointProvider,meta:g,presence:this.presence,log:v.log,interval:u,fetch:r}),this.fileSync=new Hn({endpointProvider:this.endpointProvider,log:v.log}),w&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel(`verdant-${v.namespace}`),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),d==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let I=()=>{O&&clearTimeout(O);let b=this.presence.getViewPeers().length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;b&&this.mode==="pull"?this.setMode("realtime"):!b&&this.mode==="realtime"&&(O=setTimeout(()=>{this.presence.getViewPeers().length===0&&this.setMode("pull")},1e3))},O;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===Le.Realtime||this.endpointProvider.type===Le.PassiveRealtime||this.endpointProvider.type===Le.ReadOnlyRealtime}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}ignoreIncoming(){this.activeSync.ignoreIncoming()}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var Xe=class extends z{constructor(e,t,r){super();this.config=e;this.context=t;this._closed=!1;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),t={};if(this.disposed)return{};for(let p of e)try{t[p]=await Qe(this.documentDb,p)}catch(S){this.context.log?.("error",S)}if(this.disposed)return{collections:t};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=await this._fileManager.stats(),a=Object.values(t).reduce((p,{size:S})=>p+S,0),d=r.baselinesSize.size+r.operationsSize.size,u=d/a;return{collections:t,meta:r,storage:o,totalMetaSize:d,totalCollectionsSize:a,metaToDataRatio:u,files:s,quotaUsage:o?.usage&&o?.quota?o.usage/o.quota:void 0}};this.close=async()=>{this._closed=!0,this.sync.ignoreIncoming(),await this._entities.flushAllBatches(),this._fileManager.close(),this.sync.stop(),this.sync.destroy(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await ge(this.documentDb),await ge(this.metaDb),e()}),this.context.log?.("info","Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await ln(this.namespace,indexedDB)};this.export=async({downloadRemoteFiles:e}={downloadRemoteFiles:!0})=>{this.context.log("info","Exporting data...");let t=await this.meta.export(),r=await this._fileManager.exportAll(e),o=[],s=[];for(let a of r){let d=a.file;if(delete a.file,o.push(a),d){let u=new File([d],this.getFileExportName(a.name,a.id),{type:a.type});s.push(u)}else this.context.log("warn",`File ${a.id} was could not be loaded locally or from the server. It will be missing in the export.`)}return{data:t,fileData:o,files:s}};this.getFileExportName=(e,t)=>`${t}___${e}`;this.parseFileExportname=e=>{let[t,r]=e.split("___");return{id:t,originalFileName:r}};this.import=async({data:e,fileData:t,files:r})=>{this.context.log("info","Importing data..."),await ge(this.context.documentDb),await this.meta.resetFrom(e);let o=new Map(r.map(p=>{let{id:S}=this.parseFileExportname(p.name);return[S,p]})),s=t.map(p=>{let S=o.get(p.id);return{...p,file:S}});await this._fileManager.importAll(s);let a=e.schema.version,d=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((p,S)=>{d.onsuccess=p,d.onerror=S});let u=this.context.schema;if(u.version!==a)throw new Error("Only exports from the current schema version can be imported");this.context.documentDb=await Tt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a}),this.context.internalEvents.emit("documentDbChanged",this.documentDb),this.context.log("info","Re-initializing data from imported data..."),await this._entities.addData({operations:e.operations,baselines:e.baselines,reset:!0}),await ge(this.context.documentDb),this.context.log("info","Migrating up to latest schema..."),this.context.schema=u,this.context.documentDb=await Tt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:u.version}),this.context.internalEvents.emit("documentDbChanged",this.documentDb)};this.__dangerous__hardReset=async()=>{let e=await this.export();await this.import(e)};this.__cleanupFilesImmediately=()=>this._fileManager.tryCleanupDeletedFiles();this.__manualRebase=()=>this.meta.manualRebase();this.meta=r.meta,this.collectionNames=Object.keys(t.schema.collections),this._sync=this.config.syncConfig&&!t.schema.wip?new ft(this.config.syncConfig,{meta:this.meta,onData:this.addData,ctx:this.context}):new Zn({meta:this.meta}),t.schema.wip&&this.config.syncConfig&&t.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 Ln({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new jn({ctx:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new qn({context:t}),this._documentManager=new Sn(this.schema,this._entities);let o=zr(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",o),this.context.globalEvents.subscribe("resetToServer",()=>{this.emit("resetToServer")}),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.("warn",`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?.("warn",`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[s,a]of Object.entries(t.schema.collections)){let d=s;this[d]=new Kn({collection:d,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 batch(){return this.entities.batch}};var kt=class{constructor(i){this.value=i}deref(){return this.value}};var is=Symbol("metadataVersion");var ei=class{constructor(i){this.init=i;this._initializing=!1;this.initialize=async i=>{if(typeof window>"u"&&!i.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 i.schema.wip?e=await this.initializeWIPDatabases(i):(e=await this.initializeDatabases(i),this.cleanupWIPDatabases(i)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw e instanceof Error?(this.rejectReady(e),e):new Error("Unknown error initializing storage")}finally{this._initializing=!1}};this.initializeDatabases=async i=>{let e=i[is],{db:t}=await yn({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,metadataVersion:e}),r={namespace:this._namespace,metaDb:t,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Je,entityEvents:new z,globalEvents:new z,internalEvents:new z,weakRef:p=>i.EXPERIMENTAL_weakRefs?new WeakRef(p):new kt(p),migrations:i.migrations,oldSchemas:i.oldSchemas},o=new Dt({context:r,disableRebasing:i.disableRebasing,onOperation:i.onOperation});await o.updateSchema(i.schema,i.overrideSchemaConflict);let s=Object.assign(r,{getNow:()=>o.now}),a=await Tt({context:s,version:i.schema.version,meta:o,migrations:i.migrations,indexedDB:i.indexedDb}),d=Object.assign(s,{documentDb:a});return new Xe({syncConfig:i.sync,migrations:i.migrations,files:i.files},d,{meta:o})};this.initializeWIPDatabases=async i=>{let e=ke(i.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let t=`@@wip_${i.namespace}_${e}`,{db:r}=await co({indexedDB:i.indexedDb,log:i.log,namespace:i.namespace,wipNamespace:t}),o={namespace:this._namespace,metaDb:r,schema:i.schema,log:i.log||(()=>{}),undoHistory:i.undoHistory||new Je,entityEvents:new z,globalEvents:new z,internalEvents:new z,weakRef:S=>i.EXPERIMENTAL_weakRefs?new WeakRef(S):new kt(S),migrations:i.migrations,oldSchemas:i.oldSchemas},s=new Dt({context:o,disableRebasing:i.disableRebasing}),a=Object.assign(o,{getNow:()=>s.now});await s.updateSchema(i.schema,i.overrideSchemaConflict);let d=await bo({context:a,version:i.schema.version,meta:s,migrations:i.migrations,indexedDB:i.indexedDb,wipNamespace:t}),u=Object.assign(a,{documentDb:d});return new Xe({syncConfig:i.sync,migrations:i.migrations,files:i.files},u,{meta:s})};this.cleanupWIPDatabases=async i=>{let r=(await so(i.indexedDb)).filter(o=>o.name?.startsWith("@@wip_")).map(o=>o.name).filter(o=>!o.startsWith(`@@wip_${i.namespace}_${ke(i.schema)}`));for(let o of r)await oo(o,i.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 ln(this.namespace)};this._readyPromise=new Promise((e,t)=>{this.resolveReady=e,this.rejectReady=t}),this._namespace=i.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};var rr=Be(Ne(),1);function ec(n){return n?rr.default.slug():(0,rr.default)()}var tc={private:We.onlyMe(),public:void 0};function nc(n,{port:i=3242,initialPresence:e={}}={}){let t=localStorage.getItem("verdant-userId");return t||(t=`user-${Math.random().toString(36).slice(2)}`,localStorage.setItem("verdant-userId",t)),{defaultProfile:{id:t},initialPresence:e,authEndpoint:`http://localhost:${i}/auth/${n}?userId=${t}`}}window.Verdant=or;
|
|
16
16
|
//# sourceMappingURL=index.js.map
|