@verdant-web/store 2.6.0 → 2.7.1

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.
Files changed (105) hide show
  1. package/dist/bundle/index.js +9 -9
  2. package/dist/bundle/index.js.map +4 -4
  3. package/dist/cjs/{entities/FakeWeakRef.d.ts → FakeWeakRef.d.ts} +2 -2
  4. package/dist/cjs/{entities/FakeWeakRef.js → FakeWeakRef.js} +4 -4
  5. package/dist/cjs/FakeWeakRef.js.map +1 -0
  6. package/dist/cjs/IDBService.d.ts +1 -1
  7. package/dist/cjs/IDBService.js +18 -1
  8. package/dist/cjs/IDBService.js.map +1 -1
  9. package/dist/cjs/__tests__/documents.test.js +17 -0
  10. package/dist/cjs/__tests__/documents.test.js.map +1 -1
  11. package/dist/cjs/__tests__/fixtures/testStorage.d.ts +1 -1
  12. package/dist/cjs/__tests__/fixtures/testStorage.js +3 -2
  13. package/dist/cjs/__tests__/fixtures/testStorage.js.map +1 -1
  14. package/dist/cjs/__tests__/mutations.test.d.ts +1 -0
  15. package/dist/cjs/__tests__/mutations.test.js +42 -0
  16. package/dist/cjs/__tests__/mutations.test.js.map +1 -0
  17. package/dist/cjs/client/Client.d.ts +6 -4
  18. package/dist/cjs/client/Client.js +1 -5
  19. package/dist/cjs/client/Client.js.map +1 -1
  20. package/dist/cjs/client/ClientDescriptor.d.ts +12 -4
  21. package/dist/cjs/client/ClientDescriptor.js +17 -0
  22. package/dist/cjs/client/ClientDescriptor.js.map +1 -1
  23. package/dist/cjs/context.d.ts +1 -0
  24. package/dist/cjs/entities/DocumentFamiliyCache.d.ts +2 -1
  25. package/dist/cjs/entities/DocumentFamiliyCache.js +6 -3
  26. package/dist/cjs/entities/DocumentFamiliyCache.js.map +1 -1
  27. package/dist/cjs/entities/Entity.d.ts +7 -2
  28. package/dist/cjs/entities/Entity.js +33 -3
  29. package/dist/cjs/entities/Entity.js.map +1 -1
  30. package/dist/cjs/entities/EntityStore.js +14 -13
  31. package/dist/cjs/entities/EntityStore.js.map +1 -1
  32. package/dist/cjs/index.d.ts +1 -1
  33. package/dist/cjs/index.js +2 -1
  34. package/dist/cjs/index.js.map +1 -1
  35. package/dist/cjs/metadata/BaselinesStore.js +19 -5
  36. package/dist/cjs/metadata/BaselinesStore.js.map +1 -1
  37. package/dist/cjs/migration/openDatabase.js +5 -16
  38. package/dist/cjs/migration/openDatabase.js.map +1 -1
  39. package/dist/cjs/sync/Sync.d.ts +6 -5
  40. package/dist/cjs/sync/Sync.js.map +1 -1
  41. package/dist/esm/{entities/FakeWeakRef.d.ts → FakeWeakRef.d.ts} +2 -2
  42. package/dist/esm/{entities/FakeWeakRef.js → FakeWeakRef.js} +2 -2
  43. package/dist/esm/FakeWeakRef.js.map +1 -0
  44. package/dist/esm/IDBService.d.ts +1 -1
  45. package/dist/esm/IDBService.js +18 -1
  46. package/dist/esm/IDBService.js.map +1 -1
  47. package/dist/esm/__tests__/documents.test.js +17 -0
  48. package/dist/esm/__tests__/documents.test.js.map +1 -1
  49. package/dist/esm/__tests__/fixtures/testStorage.d.ts +1 -1
  50. package/dist/esm/__tests__/fixtures/testStorage.js +4 -3
  51. package/dist/esm/__tests__/fixtures/testStorage.js.map +1 -1
  52. package/dist/esm/__tests__/mutations.test.d.ts +1 -0
  53. package/dist/esm/__tests__/mutations.test.js +40 -0
  54. package/dist/esm/__tests__/mutations.test.js.map +1 -0
  55. package/dist/esm/client/Client.d.ts +6 -4
  56. package/dist/esm/client/Client.js +2 -6
  57. package/dist/esm/client/Client.js.map +1 -1
  58. package/dist/esm/client/ClientDescriptor.d.ts +12 -4
  59. package/dist/esm/client/ClientDescriptor.js +17 -0
  60. package/dist/esm/client/ClientDescriptor.js.map +1 -1
  61. package/dist/esm/context.d.ts +1 -0
  62. package/dist/esm/entities/DocumentFamiliyCache.d.ts +2 -1
  63. package/dist/esm/entities/DocumentFamiliyCache.js +6 -3
  64. package/dist/esm/entities/DocumentFamiliyCache.js.map +1 -1
  65. package/dist/esm/entities/Entity.d.ts +7 -2
  66. package/dist/esm/entities/Entity.js +33 -3
  67. package/dist/esm/entities/Entity.js.map +1 -1
  68. package/dist/esm/entities/EntityStore.js +15 -14
  69. package/dist/esm/entities/EntityStore.js.map +1 -1
  70. package/dist/esm/index.d.ts +1 -1
  71. package/dist/esm/index.js +1 -1
  72. package/dist/esm/index.js.map +1 -1
  73. package/dist/esm/metadata/BaselinesStore.js +20 -6
  74. package/dist/esm/metadata/BaselinesStore.js.map +1 -1
  75. package/dist/esm/migration/openDatabase.js +6 -17
  76. package/dist/esm/migration/openDatabase.js.map +1 -1
  77. package/dist/esm/sync/Sync.d.ts +6 -5
  78. package/dist/esm/sync/Sync.js.map +1 -1
  79. package/dist/tsconfig-cjs.tsbuildinfo +1 -1
  80. package/dist/tsconfig.tsbuildinfo +1 -1
  81. package/package.json +9 -4
  82. package/src/{entities/FakeWeakRef.ts → FakeWeakRef.ts} +2 -2
  83. package/src/IDBService.ts +20 -2
  84. package/src/__tests__/documents.test.ts +19 -0
  85. package/src/__tests__/fixtures/testStorage.ts +4 -7
  86. package/src/__tests__/mutations.test.ts +51 -0
  87. package/src/client/Client.ts +5 -11
  88. package/src/client/ClientDescriptor.ts +34 -7
  89. package/src/context.ts +1 -0
  90. package/src/entities/DocumentFamiliyCache.ts +7 -2
  91. package/src/entities/Entity.ts +41 -6
  92. package/src/entities/EntityStore.ts +23 -15
  93. package/src/index.ts +1 -0
  94. package/src/metadata/BaselinesStore.ts +22 -6
  95. package/src/migration/openDatabase.ts +11 -21
  96. package/src/sync/Sync.ts +13 -9
  97. package/dist/cjs/entities/FakeWeakRef.js.map +0 -1
  98. package/dist/cjs/indexes.d.ts +0 -3
  99. package/dist/cjs/indexes.js +0 -20
  100. package/dist/cjs/indexes.js.map +0 -1
  101. package/dist/esm/entities/FakeWeakRef.js.map +0 -1
  102. package/dist/esm/indexes.d.ts +0 -3
  103. package/dist/esm/indexes.js +0 -15
  104. package/dist/esm/indexes.js.map +0 -1
  105. package/src/indexes.ts +0 -31
@@ -1,17 +1,17 @@
1
- "use strict";var ir=Object.create;var bn=Object.defineProperty;var rr=Object.getOwnPropertyDescriptor;var sr=Object.getOwnPropertyNames;var or=Object.getPrototypeOf,ar=Object.prototype.hasOwnProperty;var We=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),cr=(i,t)=>{for(var e in t)bn(i,e,{get:t[e],enumerable:!0})},lr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of sr(t))!ar.call(i,r)&&r!==e&&bn(i,r,{get:()=>t[r],enumerable:!(n=rr(t,r))||n.enumerable});return i};var dt=(i,t,e)=>(e=i!=null?ir(or(i)):{},lr(t||!i||!i.__esModule?bn(e,"default",{value:i,enumerable:!0}):e,i));var vn=We((Is,ei)=>{ei.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ni=We((Ds,ti)=>{var dr=vn(),ur=typeof window=="object"?window:self,pr=Object.keys(ur).length,fr=navigator.mimeTypes?navigator.mimeTypes.length:0,hr=dr((fr+navigator.userAgent.length).toString(36)+pr.toString(36),4);ti.exports=function(){return hr}});var oi=We((Cs,si)=>{var wn,ii=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ii?(ri=Math.pow(2,32)-1,wn=function(){return Math.abs(ii.getRandomValues(new Uint32Array(1))[0]/ri)}):wn=Math.random;var ri;si.exports=wn});var ft=We((Es,di)=>{var ut=ni(),ai=vn(),mr=oi(),He=0,xn=4,pt=36,ci=Math.pow(pt,xn);function Sn(){return ai((mr()*ci<<0).toString(pt),xn)}function li(){return He=He<ci?He:0,He++,He-1}function Qe(){var i="c",t=new Date().getTime().toString(pt),e=ai(li().toString(pt),xn),n=ut(),r=Sn()+Sn();return i+t+e+n+r}Qe.slug=function(){var t=new Date().getTime().toString(36),e=li().toString(36).slice(-4),n=ut().slice(0,1)+ut().slice(-1),r=Sn().slice(-2);return t.slice(-2)+e+n+r};Qe.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};Qe.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};Qe.fingerprint=ut;di.exports=Qe});var Di=We((Oi,Ii)=>{(function(i){var t;typeof Oi=="object"?Ii.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(d,h){if(!e[d]){if(!t[d]){var m=typeof require=="function"&&require;if(!h&&m)return m(d,!0);if(s)return s(d,!0);throw new Error("Cannot find module '"+d+"'")}h=e[d]={exports:{}},t[d][0].call(h.exports,function(C){var P=t[d][1][C];return r(P||C)},h,h.exports,i,t,e,n)}return e[d].exports}for(var s=typeof require=="function"&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){"use strict";var v=i("crypto");function T(y,w){w=D(y,w);var l;return(l=w.algorithm!=="passthrough"?v.createHash(w.algorithm):new A).write===void 0&&(l.write=l.update,l.end=l.update),x(w,l).dispatch(y),l.update||l.end(""),l.digest?l.digest(w.encoding==="buffer"?void 0:w.encoding):(y=l.read(),w.encoding!=="buffer"?y.toString(w.encoding):y)}(e=t.exports=T).sha1=function(y){return T(y)},e.keys=function(y){return T(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return T(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return T(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var b=v.getHashes?v.getHashes().slice():["sha1","md5"],I=(b.push("passthrough"),["buffer","hex","binary","base64"]);function D(y,w){var l={};if(l.algorithm=(w=w||{}).algorithm||"sha1",l.encoding=w.encoding||"hex",l.excludeValues=!!w.excludeValues,l.algorithm=l.algorithm.toLowerCase(),l.encoding=l.encoding.toLowerCase(),l.ignoreUnknown=w.ignoreUnknown===!0,l.respectType=w.respectType!==!1,l.respectFunctionNames=w.respectFunctionNames!==!1,l.respectFunctionProperties=w.respectFunctionProperties!==!1,l.unorderedArrays=w.unorderedArrays===!0,l.unorderedSets=w.unorderedSets!==!1,l.unorderedObjects=w.unorderedObjects!==!1,l.replacer=w.replacer||void 0,l.excludeKeys=w.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var p=0;p<b.length;++p)b[p].toLowerCase()===l.algorithm.toLowerCase()&&(l.algorithm=b[p]);if(b.indexOf(l.algorithm)===-1)throw new Error('Algorithm "'+l.algorithm+'" not supported. supported values: '+b.join(", "));if(I.indexOf(l.encoding)===-1&&l.algorithm!=="passthrough")throw new Error('Encoding "'+l.encoding+'" not supported. supported values: '+I.join(", "));return l}function O(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function x(y,w,l){l=l||[];function p(c){return w.update?w.update(c,"utf8"):w.write(c,"utf8")}return{dispatch:function(c){return this["_"+((c=y.replacer?y.replacer(c):c)===null?"null":typeof c)](c)},_object:function(c){var g,S=Object.prototype.toString.call(c),M=/\[object (.*)\]/i.exec(S);if(M=(M=M?M[1]:"unknown:["+S+"]").toLowerCase(),0<=(S=l.indexOf(c)))return this.dispatch("[CIRCULAR:"+S+"]");if(l.push(c),s!==void 0&&s.isBuffer&&s.isBuffer(c))return p("buffer:"),p(c);if(M==="object"||M==="function"||M==="asyncfunction")return S=Object.keys(c),y.unorderedObjects&&(S=S.sort()),y.respectType===!1||O(c)||S.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(S=S.filter(function(R){return!y.excludeKeys(R)})),p("object:"+S.length+":"),g=this,S.forEach(function(R){g.dispatch(R),p(":"),y.excludeValues||g.dispatch(c[R]),p(",")});if(!this["_"+M]){if(y.ignoreUnknown)return p("["+M+"]");throw new Error('Unknown object type "'+M+'"')}this["_"+M](c)},_array:function(c,R){R=R!==void 0?R:y.unorderedArrays!==!1;var S=this;if(p("array:"+c.length+":"),!R||c.length<=1)return c.forEach(function(j){return S.dispatch(j)});var M=[],R=c.map(function(j){var F=new A,q=l.slice();return x(y,F,q).dispatch(j),M=M.concat(q.slice(l.length)),F.read().toString()});return l=l.concat(M),R.sort(),this._array(R,!1)},_date:function(c){return p("date:"+c.toJSON())},_symbol:function(c){return p("symbol:"+c.toString())},_error:function(c){return p("error:"+c.toString())},_boolean:function(c){return p("bool:"+c.toString())},_string:function(c){p("string:"+c.length+":"),p(c.toString())},_function:function(c){p("fn:"),O(c)?this.dispatch("[native]"):this.dispatch(c.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(c.name)),y.respectFunctionProperties&&this._object(c)},_number:function(c){return p("number:"+c.toString())},_xml:function(c){return p("xml:"+c.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(c){return p("regex:"+c.toString())},_uint8array:function(c){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint8clampedarray:function(c){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(c))},_int8array:function(c){return p("int8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint16array:function(c){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(c))},_int16array:function(c){return p("int16array:"),this.dispatch(Array.prototype.slice.call(c))},_uint32array:function(c){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(c))},_int32array:function(c){return p("int32array:"),this.dispatch(Array.prototype.slice.call(c))},_float32array:function(c){return p("float32array:"),this.dispatch(Array.prototype.slice.call(c))},_float64array:function(c){return p("float64array:"),this.dispatch(Array.prototype.slice.call(c))},_arraybuffer:function(c){return p("arraybuffer:"),this.dispatch(new Uint8Array(c))},_url:function(c){return p("url:"+c.toString())},_map:function(c){return p("map:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_set:function(c){return p("set:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_file:function(c){return p("file:"),this.dispatch([c.name,c.size,c.type,c.lastModfied])},_blob:function(){if(y.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
1
+ "use strict";var ar=Object.create;var vn=Object.defineProperty;var cr=Object.getOwnPropertyDescriptor;var lr=Object.getOwnPropertyNames;var dr=Object.getPrototypeOf,ur=Object.prototype.hasOwnProperty;var $e=(i,t)=>()=>(t||i((t={exports:{}}).exports,t),t.exports),pr=(i,t)=>{for(var e in t)vn(i,e,{get:t[e],enumerable:!0})},fr=(i,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of lr(t))!ur.call(i,r)&&r!==e&&vn(i,r,{get:()=>t[r],enumerable:!(n=cr(t,r))||n.enumerable});return i};var ut=(i,t,e)=>(e=i!=null?ar(dr(i)):{},fr(t||!i||!i.__esModule?vn(e,"default",{value:i,enumerable:!0}):e,i));var Sn=$e((Ps,si)=>{si.exports=function(t,e){var n="000000000"+t;return n.substr(n.length-e)}});var ai=$e((_s,oi)=>{var hr=Sn(),mr=typeof window=="object"?window:self,yr=Object.keys(mr).length,gr=navigator.mimeTypes?navigator.mimeTypes.length:0,br=hr((gr+navigator.userAgent.length).toString(36)+yr.toString(36),4);oi.exports=function(){return br}});var ui=$e((Ts,di)=>{var xn,ci=typeof window<"u"&&(window.crypto||window.msCrypto)||typeof self<"u"&&self.crypto;ci?(li=Math.pow(2,32)-1,xn=function(){return Math.abs(ci.getRandomValues(new Uint32Array(1))[0]/li)}):xn=Math.random;var li;di.exports=xn});var ht=$e((As,mi)=>{var pt=ai(),pi=Sn(),wr=ui(),qe=0,In=4,ft=36,fi=Math.pow(ft,In);function On(){return pi((wr()*fi<<0).toString(ft),In)}function hi(){return qe=qe<fi?qe:0,qe++,qe-1}function We(){var i="c",t=new Date().getTime().toString(ft),e=pi(hi().toString(ft),In),n=pt(),r=On()+On();return i+t+e+n+r}We.slug=function(){var t=new Date().getTime().toString(36),e=hi().toString(36).slice(-4),n=pt().slice(0,1)+pt().slice(-1),r=On().slice(-2);return t.slice(-2)+e+n+r};We.isCuid=function(t){return typeof t!="string"?!1:!!t.startsWith("c")};We.isSlug=function(t){if(typeof t!="string")return!1;var e=t.length;return e>=7&&e<=10};We.fingerprint=pt;mi.exports=We});var Ti=$e((Pi,_i)=>{(function(i){var t;typeof Pi=="object"?_i.exports=i():typeof define=="function"&&define.amd?define(i):(typeof window<"u"?t=window:typeof global<"u"?t=global:typeof self<"u"&&(t=self),t.objectHash=i())})(function(){return function i(t,e,n){function r(l,f){if(!e[l]){if(!t[l]){var h=typeof require=="function"&&require;if(!f&&h)return h(l,!0);if(s)return s(l,!0);throw new Error("Cannot find module '"+l+"'")}f=e[l]={exports:{}},t[l][0].call(f.exports,function(v){var E=t[l][1][v];return r(E||v)},f,f.exports,i,t,e,n)}return e[l].exports}for(var s=typeof require=="function"&&require,a=0;a<n.length;a++)r(n[a]);return r}({1:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){"use strict";var b=i("crypto");function P(y,I){I=C(y,I);var d;return(d=I.algorithm!=="passthrough"?b.createHash(I.algorithm):new A).write===void 0&&(d.write=d.update,d.end=d.update),S(I,d).dispatch(y),d.update||d.end(""),d.digest?d.digest(I.encoding==="buffer"?void 0:I.encoding):(y=d.read(),I.encoding!=="buffer"?y.toString(I.encoding):y)}(e=t.exports=P).sha1=function(y){return P(y)},e.keys=function(y){return P(y,{excludeValues:!0,algorithm:"sha1",encoding:"hex"})},e.MD5=function(y){return P(y,{algorithm:"md5",encoding:"hex"})},e.keysMD5=function(y){return P(y,{algorithm:"md5",encoding:"hex",excludeValues:!0})};var g=b.getHashes?b.getHashes().slice():["sha1","md5"],O=(g.push("passthrough"),["buffer","hex","binary","base64"]);function C(y,I){var d={};if(d.algorithm=(I=I||{}).algorithm||"sha1",d.encoding=I.encoding||"hex",d.excludeValues=!!I.excludeValues,d.algorithm=d.algorithm.toLowerCase(),d.encoding=d.encoding.toLowerCase(),d.ignoreUnknown=I.ignoreUnknown===!0,d.respectType=I.respectType!==!1,d.respectFunctionNames=I.respectFunctionNames!==!1,d.respectFunctionProperties=I.respectFunctionProperties!==!1,d.unorderedArrays=I.unorderedArrays===!0,d.unorderedSets=I.unorderedSets!==!1,d.unorderedObjects=I.unorderedObjects!==!1,d.replacer=I.replacer||void 0,d.excludeKeys=I.excludeKeys||void 0,y===void 0)throw new Error("Object argument required.");for(var p=0;p<g.length;++p)g[p].toLowerCase()===d.algorithm.toLowerCase()&&(d.algorithm=g[p]);if(g.indexOf(d.algorithm)===-1)throw new Error('Algorithm "'+d.algorithm+'" not supported. supported values: '+g.join(", "));if(O.indexOf(d.encoding)===-1&&d.algorithm!=="passthrough")throw new Error('Encoding "'+d.encoding+'" not supported. supported values: '+O.join(", "));return d}function x(y){if(typeof y=="function")return/^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i.exec(Function.prototype.toString.call(y))!=null}function S(y,I,d){d=d||[];function p(c){return I.update?I.update(c,"utf8"):I.write(c,"utf8")}return{dispatch:function(c){return this["_"+((c=y.replacer?y.replacer(c):c)===null?"null":typeof c)](c)},_object:function(c){var w,D=Object.prototype.toString.call(c),F=/\[object (.*)\]/i.exec(D);if(F=(F=F?F[1]:"unknown:["+D+"]").toLowerCase(),0<=(D=d.indexOf(c)))return this.dispatch("[CIRCULAR:"+D+"]");if(d.push(c),s!==void 0&&s.isBuffer&&s.isBuffer(c))return p("buffer:"),p(c);if(F==="object"||F==="function"||F==="asyncfunction")return D=Object.keys(c),y.unorderedObjects&&(D=D.sort()),y.respectType===!1||x(c)||D.splice(0,0,"prototype","__proto__","constructor"),y.excludeKeys&&(D=D.filter(function(R){return!y.excludeKeys(R)})),p("object:"+D.length+":"),w=this,D.forEach(function(R){w.dispatch(R),p(":"),y.excludeValues||w.dispatch(c[R]),p(",")});if(!this["_"+F]){if(y.ignoreUnknown)return p("["+F+"]");throw new Error('Unknown object type "'+F+'"')}this["_"+F](c)},_array:function(c,R){R=R!==void 0?R:y.unorderedArrays!==!1;var D=this;if(p("array:"+c.length+":"),!R||c.length<=1)return c.forEach(function(j){return D.dispatch(j)});var F=[],R=c.map(function(j){var B=new A,q=d.slice();return S(y,B,q).dispatch(j),F=F.concat(q.slice(d.length)),B.read().toString()});return d=d.concat(F),R.sort(),this._array(R,!1)},_date:function(c){return p("date:"+c.toJSON())},_symbol:function(c){return p("symbol:"+c.toString())},_error:function(c){return p("error:"+c.toString())},_boolean:function(c){return p("bool:"+c.toString())},_string:function(c){p("string:"+c.length+":"),p(c.toString())},_function:function(c){p("fn:"),x(c)?this.dispatch("[native]"):this.dispatch(c.toString()),y.respectFunctionNames!==!1&&this.dispatch("function-name:"+String(c.name)),y.respectFunctionProperties&&this._object(c)},_number:function(c){return p("number:"+c.toString())},_xml:function(c){return p("xml:"+c.toString())},_null:function(){return p("Null")},_undefined:function(){return p("Undefined")},_regexp:function(c){return p("regex:"+c.toString())},_uint8array:function(c){return p("uint8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint8clampedarray:function(c){return p("uint8clampedarray:"),this.dispatch(Array.prototype.slice.call(c))},_int8array:function(c){return p("int8array:"),this.dispatch(Array.prototype.slice.call(c))},_uint16array:function(c){return p("uint16array:"),this.dispatch(Array.prototype.slice.call(c))},_int16array:function(c){return p("int16array:"),this.dispatch(Array.prototype.slice.call(c))},_uint32array:function(c){return p("uint32array:"),this.dispatch(Array.prototype.slice.call(c))},_int32array:function(c){return p("int32array:"),this.dispatch(Array.prototype.slice.call(c))},_float32array:function(c){return p("float32array:"),this.dispatch(Array.prototype.slice.call(c))},_float64array:function(c){return p("float64array:"),this.dispatch(Array.prototype.slice.call(c))},_arraybuffer:function(c){return p("arraybuffer:"),this.dispatch(new Uint8Array(c))},_url:function(c){return p("url:"+c.toString())},_map:function(c){return p("map:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_set:function(c){return p("set:"),c=Array.from(c),this._array(c,y.unorderedSets!==!1)},_file:function(c){return p("file:"),this.dispatch([c.name,c.size,c.type,c.lastModfied])},_blob:function(){if(y.ignoreUnknown)return p("[blob]");throw Error(`Hashing Blob objects is currently not supported
2
2
  (see https://github.com/puleos/object-hash/issues/26)
3
3
  Use "options.replacer" or "options.ignoreUnknown"
4
- `)},_domwindow:function(){return p("domwindow")},_bigint:function(c){return p("bigint:"+c.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function A(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,w,l){return l===void 0&&(l=w,w={}),x(w=D(y,w),l).dispatch(y)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){(function(v){"use strict";var T=typeof Uint8Array<"u"?Uint8Array:Array,b="+".charCodeAt(0),I="/".charCodeAt(0),D="0".charCodeAt(0),O="a".charCodeAt(0),x="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function w(l){return l=l.charCodeAt(0),l===b||l===A?62:l===I||l===y?63:l<D?-1:l<D+10?l-D+26+26:l<x+26?l-x:l<O+26?l-O+26:void 0}v.toByteArray=function(l){var p,c;if(0<l.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var g=l.length,g=l.charAt(g-2)==="="?2:l.charAt(g-1)==="="?1:0,S=new T(3*l.length/4-g),M=0<g?l.length-4:l.length,R=0;function j(F){S[R++]=F}for(p=0;p<M;p+=4,0)j((16711680&(c=w(l.charAt(p))<<18|w(l.charAt(p+1))<<12|w(l.charAt(p+2))<<6|w(l.charAt(p+3))))>>16),j((65280&c)>>8),j(255&c);return g==2?j(255&(c=w(l.charAt(p))<<2|w(l.charAt(p+1))>>4)):g==1&&(j((c=w(l.charAt(p))<<10|w(l.charAt(p+1))<<4|w(l.charAt(p+2))>>2)>>8&255),j(255&c)),S},v.fromByteArray=function(l){var p,c,g,S,M=l.length%3,R="";function j(F){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(F)}for(p=0,g=l.length-M;p<g;p+=3)c=(l[p]<<16)+(l[p+1]<<8)+l[p+2],R+=j((S=c)>>18&63)+j(S>>12&63)+j(S>>6&63)+j(63&S);switch(M){case 1:R=(R+=j((c=l[l.length-1])>>2))+j(c<<4&63)+"==";break;case 2:R=(R=(R+=j((c=(l[l.length-2]<<8)+l[l.length-1])>>10))+j(c>>4&63))+j(c<<2&63)+"="}return R}})(e===void 0?this.base64js={}:e)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(i,t,e){(function(n,r,b,a,d,h,m,C,P){var v=i("base64-js"),T=i("ieee754");function b(o,u,f){if(!(this instanceof b))return new b(o,u,f);var _,E,k,L,Q=typeof o;if(u==="base64"&&Q=="string")for(o=(L=o).trim?L.trim():L.replace(/^\s+|\s+$/g,"");o.length%4!=0;)o+="=";if(Q=="number")_=ee(o);else if(Q=="string")_=b.byteLength(o,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");_=ee(o.length)}if(b._useTypedArrays?E=b._augment(new Uint8Array(_)):((E=this).length=_,E._isBuffer=!0),b._useTypedArrays&&typeof o.byteLength=="number")E._set(o);else if(H(L=o)||b.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(k=0;k<_;k++)b.isBuffer(o)?E[k]=o.readUInt8(k):E[k]=o[k];else if(Q=="string")E.write(o,0,u);else if(Q=="number"&&!b._useTypedArrays&&!f)for(k=0;k<_;k++)E[k]=0;return E}function I(o,u,f,_){return b._charsWritten=lt(function(E){for(var k=[],L=0;L<E.length;L++)k.push(255&E.charCodeAt(L));return k}(u),o,f,_)}function D(o,u,f,_){return b._charsWritten=lt(function(E){for(var k,L,Q=[],Y=0;Y<E.length;Y++)L=E.charCodeAt(Y),k=L>>8,L=L%256,Q.push(L),Q.push(k);return Q}(u),o,f,_)}function O(o,u,f){var _="";f=Math.min(o.length,f);for(var E=u;E<f;E++)_+=String.fromCharCode(o[E]);return _}function x(o,u,f,k){k||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length"));var E,k=o.length;if(!(k<=u))return f?(E=o[u],u+1<k&&(E|=o[u+1]<<8)):(E=o[u]<<8,u+1<k&&(E|=o[u+1])),E}function A(o,u,f,k){k||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length"));var E,k=o.length;if(!(k<=u))return f?(u+2<k&&(E=o[u+2]<<16),u+1<k&&(E|=o[u+1]<<8),E|=o[u],u+3<k&&(E+=o[u+3]<<24>>>0)):(u+1<k&&(E=o[u+1]<<16),u+2<k&&(E|=o[u+2]<<8),u+3<k&&(E|=o[u+3]),E+=o[u]<<24>>>0),E}function y(o,u,f,_){if(_||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+1<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return _=x(o,u,f,!0),32768&_?-1*(65535-_+1):_}function w(o,u,f,_){if(_||(B(typeof f=="boolean","missing or invalid endian"),B(u!=null,"missing offset"),B(u+3<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return _=A(o,u,f,!0),2147483648&_?-1*(4294967295-_+1):_}function l(o,u,f,_){return _||(B(typeof f=="boolean","missing or invalid endian"),B(u+3<o.length,"Trying to read beyond buffer length")),T.read(o,u,f,23,4)}function p(o,u,f,_){return _||(B(typeof f=="boolean","missing or invalid endian"),B(u+7<o.length,"Trying to read beyond buffer length")),T.read(o,u,f,52,8)}function c(o,u,f,_,E){if(E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+1<o.length,"trying to write beyond buffer length"),yn(u,65535)),E=o.length,!(E<=f))for(var k=0,L=Math.min(E-f,2);k<L;k++)o[f+k]=(u&255<<8*(_?k:1-k))>>>8*(_?k:1-k)}function g(o,u,f,_,E){if(E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"trying to write beyond buffer length"),yn(u,4294967295)),E=o.length,!(E<=f))for(var k=0,L=Math.min(E-f,4);k<L;k++)o[f+k]=u>>>8*(_?k:3-k)&255}function S(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+1<o.length,"Trying to write beyond buffer length"),gn(u,32767,-32768)),o.length<=f||c(o,0<=u?u:65535+u+1,f,_,E)}function M(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"Trying to write beyond buffer length"),gn(u,2147483647,-2147483648)),o.length<=f||g(o,0<=u?u:4294967295+u+1,f,_,E)}function R(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+3<o.length,"Trying to write beyond buffer length"),Xn(u,34028234663852886e22,-34028234663852886e22)),o.length<=f||T.write(o,u,f,_,23,4)}function j(o,u,f,_,E){E||(B(u!=null,"missing value"),B(typeof _=="boolean","missing or invalid endian"),B(f!=null,"missing offset"),B(f+7<o.length,"Trying to write beyond buffer length"),Xn(u,17976931348623157e292,-17976931348623157e292)),o.length<=f||T.write(o,u,f,_,52,8)}e.Buffer=b,e.SlowBuffer=b,e.INSPECT_MAX_BYTES=50,b.poolSize=8192,b._useTypedArrays=function(){try{var o=new ArrayBuffer(0),u=new Uint8Array(o);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),b.isEncoding=function(o){switch(String(o).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},b.isBuffer=function(o){return!(o==null||!o._isBuffer)},b.byteLength=function(o,u){var f;switch(o+="",u||"utf8"){case"hex":f=o.length/2;break;case"utf8":case"utf-8":f=ye(o).length;break;case"ascii":case"binary":case"raw":f=o.length;break;case"base64":f=Yn(o).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":f=2*o.length;break;default:throw new Error("Unknown encoding")}return f},b.concat=function(o,u){if(B(H(o),`Usage: Buffer.concat(list, [totalLength])
5
- list should be an Array.`),o.length===0)return new b(0);if(o.length===1)return o[0];if(typeof u!="number")for(E=u=0;E<o.length;E++)u+=o[E].length;for(var f=new b(u),_=0,E=0;E<o.length;E++){var k=o[E];k.copy(f,_),_+=k.length}return f},b.prototype.write=function(o,u,f,_){isFinite(u)?isFinite(f)||(_=f,f=void 0):(Y=_,_=u,u=f,f=Y),u=Number(u)||0;var E,k,L,Q,Y=this.length-u;switch((!f||Y<(f=Number(f)))&&(f=Y),_=String(_||"utf8").toLowerCase()){case"hex":E=function(he,re,se,G){se=Number(se)||0;var J=he.length-se;(!G||J<(G=Number(G)))&&(G=J),B((J=re.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var Me=0;Me<G;Me++){var Zn=parseInt(re.substr(2*Me,2),16);B(!isNaN(Zn),"Invalid hex string"),he[se+Me]=Zn}return b._charsWritten=2*Me,Me}(this,o,u,f);break;case"utf8":case"utf-8":k=this,L=u,Q=f,E=b._charsWritten=lt(ye(o),k,L,Q);break;case"ascii":case"binary":E=I(this,o,u,f);break;case"base64":k=this,L=u,Q=f,E=b._charsWritten=lt(Yn(o),k,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":E=D(this,o,u,f);break;default:throw new Error("Unknown encoding")}return E},b.prototype.toString=function(o,u,f){var _,E,k,L,Q=this;if(o=String(o||"utf8").toLowerCase(),u=Number(u)||0,(f=f!==void 0?Number(f):Q.length)===u)return"";switch(o){case"hex":_=function(Y,he,re){var se=Y.length;(!he||he<0)&&(he=0),(!re||re<0||se<re)&&(re=se);for(var G="",J=he;J<re;J++)G+=z(Y[J]);return G}(Q,u,f);break;case"utf8":case"utf-8":_=function(Y,he,re){var se="",G="";re=Math.min(Y.length,re);for(var J=he;J<re;J++)Y[J]<=127?(se+=Gn(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return se+Gn(G)}(Q,u,f);break;case"ascii":case"binary":_=O(Q,u,f);break;case"base64":E=Q,L=f,_=(k=u)===0&&L===E.length?v.fromByteArray(E):v.fromByteArray(E.slice(k,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=function(Y,he,re){for(var se=Y.slice(he,re),G="",J=0;J<se.length;J+=2)G+=String.fromCharCode(se[J]+256*se[J+1]);return G}(Q,u,f);break;default:throw new Error("Unknown encoding")}return _},b.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},b.prototype.copy=function(o,u,f,_){if(u=u||0,(_=_||_===0?_:this.length)!==(f=f||0)&&o.length!==0&&this.length!==0){B(f<=_,"sourceEnd < sourceStart"),B(0<=u&&u<o.length,"targetStart out of bounds"),B(0<=f&&f<this.length,"sourceStart out of bounds"),B(0<=_&&_<=this.length,"sourceEnd out of bounds"),_>this.length&&(_=this.length);var E=(_=o.length-u<_-f?o.length-u+f:_)-f;if(E<100||!b._useTypedArrays)for(var k=0;k<E;k++)o[k+u]=this[k+f];else o._set(this.subarray(f,f+E),u)}},b.prototype.slice=function(o,u){var f=this.length;if(o=q(o,f,0),u=q(u,f,f),b._useTypedArrays)return b._augment(this.subarray(o,u));for(var _=u-o,E=new b(_,void 0,!0),k=0;k<_;k++)E[k]=this[k+o];return E},b.prototype.get=function(o){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(o)},b.prototype.set=function(o,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(o,u)},b.prototype.readUInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return this[o]},b.prototype.readUInt16LE=function(o,u){return x(this,o,!0,u)},b.prototype.readUInt16BE=function(o,u){return x(this,o,!1,u)},b.prototype.readUInt32LE=function(o,u){return A(this,o,!0,u)},b.prototype.readUInt32BE=function(o,u){return A(this,o,!1,u)},b.prototype.readInt8=function(o,u){if(u||(B(o!=null,"missing offset"),B(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return 128&this[o]?-1*(255-this[o]+1):this[o]},b.prototype.readInt16LE=function(o,u){return y(this,o,!0,u)},b.prototype.readInt16BE=function(o,u){return y(this,o,!1,u)},b.prototype.readInt32LE=function(o,u){return w(this,o,!0,u)},b.prototype.readInt32BE=function(o,u){return w(this,o,!1,u)},b.prototype.readFloatLE=function(o,u){return l(this,o,!0,u)},b.prototype.readFloatBE=function(o,u){return l(this,o,!1,u)},b.prototype.readDoubleLE=function(o,u){return p(this,o,!0,u)},b.prototype.readDoubleBE=function(o,u){return p(this,o,!1,u)},b.prototype.writeUInt8=function(o,u,f){f||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"trying to write beyond buffer length"),yn(o,255)),u>=this.length||(this[u]=o)},b.prototype.writeUInt16LE=function(o,u,f){c(this,o,u,!0,f)},b.prototype.writeUInt16BE=function(o,u,f){c(this,o,u,!1,f)},b.prototype.writeUInt32LE=function(o,u,f){g(this,o,u,!0,f)},b.prototype.writeUInt32BE=function(o,u,f){g(this,o,u,!1,f)},b.prototype.writeInt8=function(o,u,f){f||(B(o!=null,"missing value"),B(u!=null,"missing offset"),B(u<this.length,"Trying to write beyond buffer length"),gn(o,127,-128)),u>=this.length||(0<=o?this.writeUInt8(o,u,f):this.writeUInt8(255+o+1,u,f))},b.prototype.writeInt16LE=function(o,u,f){S(this,o,u,!0,f)},b.prototype.writeInt16BE=function(o,u,f){S(this,o,u,!1,f)},b.prototype.writeInt32LE=function(o,u,f){M(this,o,u,!0,f)},b.prototype.writeInt32BE=function(o,u,f){M(this,o,u,!1,f)},b.prototype.writeFloatLE=function(o,u,f){R(this,o,u,!0,f)},b.prototype.writeFloatBE=function(o,u,f){R(this,o,u,!1,f)},b.prototype.writeDoubleLE=function(o,u,f){j(this,o,u,!0,f)},b.prototype.writeDoubleBE=function(o,u,f){j(this,o,u,!1,f)},b.prototype.fill=function(o,u,f){if(u=u||0,f=f||this.length,B(typeof(o=typeof(o=o||0)=="string"?o.charCodeAt(0):o)=="number"&&!isNaN(o),"value is not a number"),B(u<=f,"end < start"),f!==u&&this.length!==0){B(0<=u&&u<this.length,"start out of bounds"),B(0<=f&&f<=this.length,"end out of bounds");for(var _=u;_<f;_++)this[_]=o}},b.prototype.inspect=function(){for(var o=[],u=this.length,f=0;f<u;f++)if(o[f]=z(this[f]),f===e.INSPECT_MAX_BYTES){o[f+1]="...";break}return"<Buffer "+o.join(" ")+">"},b.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(b._useTypedArrays)return new b(this).buffer;for(var o=new Uint8Array(this.length),u=0,f=o.length;u<f;u+=1)o[u]=this[u];return o.buffer};var F=b.prototype;function q(o,u,f){return typeof o!="number"?f:u<=(o=~~o)?u:0<=o||0<=(o+=u)?o:0}function ee(o){return(o=~~Math.ceil(+o))<0?0:o}function H(o){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(o)}function z(o){return o<16?"0"+o.toString(16):o.toString(16)}function ye(o){for(var u=[],f=0;f<o.length;f++){var _=o.charCodeAt(f);if(_<=127)u.push(o.charCodeAt(f));else for(var E=f,k=(55296<=_&&_<=57343&&f++,encodeURIComponent(o.slice(E,f+1)).substr(1).split("%")),L=0;L<k.length;L++)u.push(parseInt(k[L],16))}return u}function Yn(o){return v.toByteArray(o)}function lt(o,u,f,_){for(var E=0;E<_&&!(E+f>=u.length||E>=o.length);E++)u[E+f]=o[E];return E}function Gn(o){try{return decodeURIComponent(o)}catch{return String.fromCharCode(65533)}}function yn(o,u){B(typeof o=="number","cannot write a non-number as a number"),B(0<=o,"specified a negative value for writing an unsigned value"),B(o<=u,"value is larger than maximum value for type"),B(Math.floor(o)===o,"value has a fractional component")}function gn(o,u,f){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(f<=o,"value smaller than minimum allowed value"),B(Math.floor(o)===o,"value has a fractional component")}function Xn(o,u,f){B(typeof o=="number","cannot write a non-number as a number"),B(o<=u,"value larger than maximum allowed value"),B(f<=o,"value smaller than minimum allowed value")}function B(o,u){if(!o)throw new Error(u||"Failed assertion")}b._augment=function(o){return o._isBuffer=!0,o._get=o.get,o._set=o.set,o.get=F.get,o.set=F.set,o.write=F.write,o.toString=F.toString,o.toLocaleString=F.toString,o.toJSON=F.toJSON,o.copy=F.copy,o.slice=F.slice,o.readUInt8=F.readUInt8,o.readUInt16LE=F.readUInt16LE,o.readUInt16BE=F.readUInt16BE,o.readUInt32LE=F.readUInt32LE,o.readUInt32BE=F.readUInt32BE,o.readInt8=F.readInt8,o.readInt16LE=F.readInt16LE,o.readInt16BE=F.readInt16BE,o.readInt32LE=F.readInt32LE,o.readInt32BE=F.readInt32BE,o.readFloatLE=F.readFloatLE,o.readFloatBE=F.readFloatBE,o.readDoubleLE=F.readDoubleLE,o.readDoubleBE=F.readDoubleBE,o.writeUInt8=F.writeUInt8,o.writeUInt16LE=F.writeUInt16LE,o.writeUInt16BE=F.writeUInt16BE,o.writeUInt32LE=F.writeUInt32LE,o.writeUInt32BE=F.writeUInt32BE,o.writeInt8=F.writeInt8,o.writeInt16LE=F.writeInt16LE,o.writeInt16BE=F.writeInt16BE,o.writeInt32LE=F.writeInt32LE,o.writeInt32BE=F.writeInt32BE,o.writeFloatLE=F.writeFloatLE,o.writeFloatBE=F.writeFloatBE,o.writeDoubleLE=F.writeDoubleLE,o.writeDoubleBE=F.writeDoubleBE,o.fill=F.fill,o.inspect=F.inspect,o.toArrayBuffer=F.toArrayBuffer,o}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,v,a,d,h,m,C,P){var v=i("buffer").Buffer,T=4,b=new v(T);b.fill(0),t.exports={hash:function(I,D,O,x){for(var A=D(function(c,g){c.length%T!=0&&(S=c.length+(T-c.length%T),c=v.concat([c,b],S));for(var S,M=[],R=g?c.readInt32BE:c.readInt32LE,j=0;j<c.length;j+=T)M.push(R.call(c,j));return M}(I=v.isBuffer(I)?I:new v(I),x),8*I.length),D=x,y=new v(O),w=D?y.writeInt32BE:y.writeInt32LE,l=0;l<A.length;l++)w.call(y,A[l],4*l,!0);return y}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,v,a,d,h,m,C,P){var v=i("buffer").Buffer,T=i("./sha"),b=i("./sha256"),I=i("./rng"),D={sha1:T,sha256:b,md5:i("./md5")},O=64,x=new v(O);function A(c,g){var S=D[c=c||"sha1"],M=[];return S||y("algorithm:",c,"is not yet supported"),{update:function(R){return v.isBuffer(R)||(R=new v(R)),M.push(R),R.length,this},digest:function(R){var j=v.concat(M),j=g?function(F,q,ee){v.isBuffer(q)||(q=new v(q)),v.isBuffer(ee)||(ee=new v(ee)),q.length>O?q=F(q):q.length<O&&(q=v.concat([q,x],O));for(var H=new v(O),z=new v(O),ye=0;ye<O;ye++)H[ye]=54^q[ye],z[ye]=92^q[ye];return ee=F(v.concat([H,ee])),F(v.concat([z,ee]))}(S,g,j):S(j);return M=null,R?j.toString(R):j}}}function y(){var c=[].slice.call(arguments).join(" ");throw new Error([c,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
- `))}x.fill(0),e.createHash=function(c){return A(c)},e.createHmac=A,e.randomBytes=function(c,g){if(!g||!g.call)return new v(I(c));try{g.call(this,void 0,new v(I(c)))}catch(S){g(S)}};var w,l=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(c){e[c]=function(){y("sorry,",c,"is not implemented yet")}};for(w in l)p(l[w],w)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v=i("./helpers");function T(y,w){y[w>>5]|=128<<w%32,y[14+(w+64>>>9<<4)]=w;for(var l=1732584193,p=-271733879,c=-1732584194,g=271733878,S=0;S<y.length;S+=16){var M=l,R=p,j=c,F=g,l=I(l,p,c,g,y[S+0],7,-680876936),g=I(g,l,p,c,y[S+1],12,-389564586),c=I(c,g,l,p,y[S+2],17,606105819),p=I(p,c,g,l,y[S+3],22,-1044525330);l=I(l,p,c,g,y[S+4],7,-176418897),g=I(g,l,p,c,y[S+5],12,1200080426),c=I(c,g,l,p,y[S+6],17,-1473231341),p=I(p,c,g,l,y[S+7],22,-45705983),l=I(l,p,c,g,y[S+8],7,1770035416),g=I(g,l,p,c,y[S+9],12,-1958414417),c=I(c,g,l,p,y[S+10],17,-42063),p=I(p,c,g,l,y[S+11],22,-1990404162),l=I(l,p,c,g,y[S+12],7,1804603682),g=I(g,l,p,c,y[S+13],12,-40341101),c=I(c,g,l,p,y[S+14],17,-1502002290),l=D(l,p=I(p,c,g,l,y[S+15],22,1236535329),c,g,y[S+1],5,-165796510),g=D(g,l,p,c,y[S+6],9,-1069501632),c=D(c,g,l,p,y[S+11],14,643717713),p=D(p,c,g,l,y[S+0],20,-373897302),l=D(l,p,c,g,y[S+5],5,-701558691),g=D(g,l,p,c,y[S+10],9,38016083),c=D(c,g,l,p,y[S+15],14,-660478335),p=D(p,c,g,l,y[S+4],20,-405537848),l=D(l,p,c,g,y[S+9],5,568446438),g=D(g,l,p,c,y[S+14],9,-1019803690),c=D(c,g,l,p,y[S+3],14,-187363961),p=D(p,c,g,l,y[S+8],20,1163531501),l=D(l,p,c,g,y[S+13],5,-1444681467),g=D(g,l,p,c,y[S+2],9,-51403784),c=D(c,g,l,p,y[S+7],14,1735328473),l=O(l,p=D(p,c,g,l,y[S+12],20,-1926607734),c,g,y[S+5],4,-378558),g=O(g,l,p,c,y[S+8],11,-2022574463),c=O(c,g,l,p,y[S+11],16,1839030562),p=O(p,c,g,l,y[S+14],23,-35309556),l=O(l,p,c,g,y[S+1],4,-1530992060),g=O(g,l,p,c,y[S+4],11,1272893353),c=O(c,g,l,p,y[S+7],16,-155497632),p=O(p,c,g,l,y[S+10],23,-1094730640),l=O(l,p,c,g,y[S+13],4,681279174),g=O(g,l,p,c,y[S+0],11,-358537222),c=O(c,g,l,p,y[S+3],16,-722521979),p=O(p,c,g,l,y[S+6],23,76029189),l=O(l,p,c,g,y[S+9],4,-640364487),g=O(g,l,p,c,y[S+12],11,-421815835),c=O(c,g,l,p,y[S+15],16,530742520),l=x(l,p=O(p,c,g,l,y[S+2],23,-995338651),c,g,y[S+0],6,-198630844),g=x(g,l,p,c,y[S+7],10,1126891415),c=x(c,g,l,p,y[S+14],15,-1416354905),p=x(p,c,g,l,y[S+5],21,-57434055),l=x(l,p,c,g,y[S+12],6,1700485571),g=x(g,l,p,c,y[S+3],10,-1894986606),c=x(c,g,l,p,y[S+10],15,-1051523),p=x(p,c,g,l,y[S+1],21,-2054922799),l=x(l,p,c,g,y[S+8],6,1873313359),g=x(g,l,p,c,y[S+15],10,-30611744),c=x(c,g,l,p,y[S+6],15,-1560198380),p=x(p,c,g,l,y[S+13],21,1309151649),l=x(l,p,c,g,y[S+4],6,-145523070),g=x(g,l,p,c,y[S+11],10,-1120210379),c=x(c,g,l,p,y[S+2],15,718787259),p=x(p,c,g,l,y[S+9],21,-343485551),l=A(l,M),p=A(p,R),c=A(c,j),g=A(g,F)}return Array(l,p,c,g)}function b(y,w,l,p,c,g){return A((w=A(A(w,y),A(p,g)))<<c|w>>>32-c,l)}function I(y,w,l,p,c,g,S){return b(w&l|~w&p,y,w,c,g,S)}function D(y,w,l,p,c,g,S){return b(w&p|l&~p,y,w,c,g,S)}function O(y,w,l,p,c,g,S){return b(w^l^p,y,w,c,g,S)}function x(y,w,l,p,c,g,S){return b(l^(w|~p),y,w,c,g,S)}function A(y,w){var l=(65535&y)+(65535&w);return(y>>16)+(w>>16)+(l>>16)<<16|65535&l}t.exports=function(y){return v.hash(y,T,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v;t.exports=v||function(T){for(var b,I=new Array(T),D=0;D<T;D++)!(3&D)&&(b=4294967296*Math.random()),I[D]=b>>>((3&D)<<3)&255;return I}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v=i("./helpers");function T(D,O){D[O>>5]|=128<<24-O%32,D[15+(O+64>>9<<4)]=O;for(var x,A,y,w=Array(80),l=1732584193,p=-271733879,c=-1732584194,g=271733878,S=-1009589776,M=0;M<D.length;M+=16){for(var R=l,j=p,F=c,q=g,ee=S,H=0;H<80;H++){w[H]=H<16?D[M+H]:I(w[H-3]^w[H-8]^w[H-14]^w[H-16],1);var z=b(b(I(l,5),(z=p,A=c,y=g,(x=H)<20?z&A|~z&y:!(x<40)&&x<60?z&A|z&y|A&y:z^A^y)),b(b(S,w[H]),(x=H)<20?1518500249:x<40?1859775393:x<60?-1894007588:-899497514)),S=g,g=c,c=I(p,30),p=l,l=z}l=b(l,R),p=b(p,j),c=b(c,F),g=b(g,q),S=b(S,ee)}return Array(l,p,c,g,S)}function b(D,O){var x=(65535&D)+(65535&O);return(D>>16)+(O>>16)+(x>>16)<<16|65535&x}function I(D,O){return D<<O|D>>>32-O}t.exports=function(D){return v.hash(D,T,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){function v(O,x){var A=(65535&O)+(65535&x);return(O>>16)+(x>>16)+(A>>16)<<16|65535&A}function T(O,x){var A,y=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),w=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),l=new Array(64);O[x>>5]|=128<<24-x%32,O[15+(x+64>>9<<4)]=x;for(var p,c,g=0;g<O.length;g+=16){for(var S=w[0],M=w[1],R=w[2],j=w[3],F=w[4],q=w[5],ee=w[6],H=w[7],z=0;z<64;z++)l[z]=z<16?O[z+g]:v(v(v((c=l[z-2],I(c,17)^I(c,19)^D(c,10)),l[z-7]),(c=l[z-15],I(c,7)^I(c,18)^D(c,3))),l[z-16]),A=v(v(v(v(H,I(c=F,6)^I(c,11)^I(c,25)),F&q^~F&ee),y[z]),l[z]),p=v(I(p=S,2)^I(p,13)^I(p,22),S&M^S&R^M&R),H=ee,ee=q,q=F,F=v(j,A),j=R,R=M,M=S,S=v(A,p);w[0]=v(S,w[0]),w[1]=v(M,w[1]),w[2]=v(R,w[2]),w[3]=v(j,w[3]),w[4]=v(F,w[4]),w[5]=v(q,w[5]),w[6]=v(ee,w[6]),w[7]=v(H,w[7])}return w}var b=i("./helpers"),I=function(O,x){return O>>>x|O<<32-x},D=function(O,x){return O>>>x};t.exports=function(O){return b.hash(O,T,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){e.read=function(v,T,b,I,g){var O,x,A=8*g-I-1,y=(1<<A)-1,w=y>>1,l=-7,p=b?g-1:0,c=b?-1:1,g=v[T+p];for(p+=c,O=g&(1<<-l)-1,g>>=-l,l+=A;0<l;O=256*O+v[T+p],p+=c,l-=8);for(x=O&(1<<-l)-1,O>>=-l,l+=I;0<l;x=256*x+v[T+p],p+=c,l-=8);if(O===0)O=1-w;else{if(O===y)return x?NaN:1/0*(g?-1:1);x+=Math.pow(2,I),O-=w}return(g?-1:1)*x*Math.pow(2,O-I)},e.write=function(v,T,b,I,D,S){var x,A,y=8*S-D-1,w=(1<<y)-1,l=w>>1,p=D===23?Math.pow(2,-24)-Math.pow(2,-77):0,c=I?0:S-1,g=I?1:-1,S=T<0||T===0&&1/T<0?1:0;for(T=Math.abs(T),isNaN(T)||T===1/0?(A=isNaN(T)?1:0,x=w):(x=Math.floor(Math.log(T)/Math.LN2),T*(I=Math.pow(2,-x))<1&&(x--,I*=2),2<=(T+=1<=x+l?p/I:p*Math.pow(2,1-l))*I&&(x++,I/=2),w<=x+l?(A=0,x=w):1<=x+l?(A=(T*I-1)*Math.pow(2,D),x+=l):(A=T*Math.pow(2,l-1)*Math.pow(2,D),x=0));8<=D;v[b+c]=255&A,c+=g,A/=256,D-=8);for(x=x<<D|A,y+=D;0<y;v[b+c]=255&x,c+=g,x/=256,y-=8);v[b+c-g]|=128*S}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,s,a,d,h,m,C,P){var v,T,b;function I(){}(n=t.exports={}).nextTick=(T=typeof window<"u"&&window.setImmediate,b=typeof window<"u"&&window.postMessage&&window.addEventListener,T?function(D){return window.setImmediate(D)}:b?(v=[],window.addEventListener("message",function(D){var O=D.source;O!==window&&O!==null||D.data!=="process-tick"||(D.stopPropagation(),0<v.length&&v.shift()())},!0),function(D){v.push(D),window.postMessage("process-tick","*")}):function(D){setTimeout(D,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=I,n.addListener=I,n.once=I,n.off=I,n.removeListener=I,n.removeAllListeners=I,n.emit=I,n.binding=function(D){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(D){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var Jn={};cr(Jn,{Client:()=>Re,ClientDescriptor:()=>mn,Entity:()=>me,EntityFile:()=>ke,MigrationPathError:()=>Ue,ServerSync:()=>$e,Storage:()=>Re,StorageDescriptor:()=>mn,collection:()=>Li,createDefaultMigration:()=>Vn,migrate:()=>Tt,schema:()=>Vi});var yi=dt(ft(),1),ht=4,Ye=36;function ui(i){return i.toString(Ye).padStart(ht,"0")}function yr(i){return i.toString().padStart(6,"0")}var mt=class{constructor(){this.latest={time:Date.now(),counter:0,node:gr()};this.zeroCounter=0;this.now=t=>(this.latest=fi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=fi(this.latest),yr(t)+vr(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(ht);this.latest=br(this.latest,hi(e))};this.get=(t,e)=>ui(t)+pi(e);this.zero=t=>ui(t)+pi({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>hi(t.slice(ht)).time}},yt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},gt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},On=4,In=7,bt=60*1e3,Je=9;function gr(){return yi.default.slug().padStart(In,"0").slice(0,In)}function pi(i){let t=new Date(i.time).getTime().toString(Ye).padStart(Je,"0"),e=i.counter.toString(Ye).padStart(On,"0"),n=i.node.padStart(In,"0");return`${t}${e}${n}`}function fi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>bt)throw new yt(e,t,bt);if(n>65535)throw new gt;return{time:e,counter:n,node:i.node}}function br(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>bt)throw new yt(n,e,bt);if(s>65535)throw new gt;return{time:n,counter:s,node:i.node}}function hi(i){let t=i.slice(0,Je),e=i.slice(Je,Je+On),n=i.slice(Je+On),r=parseInt(t,Ye),s=parseInt(e,Ye);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function vr(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function mi(i){return parseInt(i.slice(0,ht),36)}function gi(i,t){return mi(i)-mi(t)}function de(i){return i&&i["@@type"]==="file"}function bi(i){return{"@@type":"file",id:i}}var vt,wr=new Uint8Array(16);function Dn(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(wr)}var vi=/^(?:[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 Sr(i){return typeof i=="string"&&vi.test(i)}var wi=Sr;var X=[];for(wt=0;wt<256;++wt)X.push((wt+256).toString(16).substr(1));var wt;function xr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(X[i[t+0]]+X[i[t+1]]+X[i[t+2]]+X[i[t+3]]+"-"+X[i[t+4]]+X[i[t+5]]+"-"+X[i[t+6]]+X[i[t+7]]+"-"+X[i[t+8]]+X[i[t+9]]+"-"+X[i[t+10]]+X[i[t+11]]+X[i[t+12]]+X[i[t+13]]+X[i[t+14]]+X[i[t+15]]).toLowerCase();if(!wi(e))throw TypeError("Stringified UUID is invalid");return e}var Si=xr;function Or(i,t,e){i=i||{};var n=i.random||(i.rng||Dn)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return Si(n)}var Ge=Or;function ie(i){return te(i)||de(i)}function xi(i,t){return i===t?!0:!(!ie(i)||!ie(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Ci=dt(Di(),1);function Ir(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Cn(i){return JSON.stringify(i,Ir)}function ne(i,t=!0){if(N(i)||Array.isArray(i)){let e=oe(i),n;if(Array.isArray(i))n=i.map(r=>ne(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=ne(s,t)}return t&&e&&K(n,e),n}return i}function we(i){return(0,Ci.default)(i)}function N(i){return i&&typeof i=="object"}function Ei(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function St(i=16){return Ge().replace("-","").slice(0,i)}function _i(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Pi(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Ie="__@@oid_do_not_use",Se="@@id",Dr="/",It=":",_n=new WeakMap;function ue(i){let t=oe(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function oe(i){if(N(i))return _n.get(i)??i[Se]??i[Ie]}function K(i,t){return V(N(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Dt(i),_n.set(i,t),i}function Ze(i){return!!oe(i)}function Dt(i){return _n.delete(i),i}function Pn(i){return i===Se||i===Ie}function Tn(i,t,e){if(Ze(i))return ue(i);{let n=ge(t,e);return K(i,n),n}}function Ti(i,t,e){if(Ze(i)){let n=ue(i);if(Ct(n,t))return ue(i);{let r=ge(t,e);return K(i,r),r}}else{let n=ge(t,e);return K(i,n),n}}var En={".":"&dot;","/":"&slash;",":":"&colon;"};function Ai(i){return i.replace(/[/]/g,En["/"]).replace(/[:]/g,En[":"]).replace(/[.]/g,En["."])}function Bi(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,t,e){let n=Ai(i)+Dr+Ai(t);return e&&(n+=It+e),n}function ge(i,t=Ar){let{collection:e,id:n}=ae(i);return Z(e,n,t())}function ae(i){let[t,e]=i.split(It),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:Bi(n),id:Bi(s),subId:e}}function je(i,t){let e=ue(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],N(n)&&!ie(n)&&(Ti(n,e,t),je(n,t))}else if(N(i)&&!ie(i))for(let n of Object.keys(i))N(i[n])&&!ie(i[n])&&(Ti(i[n],e,t),je(i[n],t))}function Cr(i,t){return V(N(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),i[Se]=t,i}function Er(i){if(N(i))return i[Se]||i[Ie]}function _r(i){return N(i)&&(delete i[Ie],delete i[Se]),i}function Pr(i){let t=oe(i);t&&Cr(i,t)}function Le(i){if(Pr(i),Array.isArray(i))for(let t=0;t<i.length;t++)Le(i[t]);else if(N(i))for(let t of Object.keys(i))Le(i[t])}function Tr(i){let t=Er(i);t&&K(i,t)}function Xe(i){if(Tr(i),_r(i),Array.isArray(i))for(let t=0;t<i.length;t++)Xe(i[t]);else if(N(i))for(let t of Object.keys(i))Xe(i[t])}function xt(i){if(Dt(i),Array.isArray(i))for(let t=0;t<i.length;t++)xt(i[t]);else if(N(i))for(let t of Object.keys(i))xt(i[t])}function Ar(){return Ge().slice(0,8)}function be(i){return{"@@type":"ref",id:i}}function Ot(i,t=new Map){if(Array.isArray(i)){let e=ue(i),n=K([],e);for(let r=0;r<i.length;r++){let s=i[r];if(N(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(de(s)){n[r]=s;continue}else{let a=ue(s);n[r]=be(a),Ot(s,t)}}else n[r]=s}t.set(e,n)}else if(N(i)&&!ie(i)){let e=ue(i),n=K({},e);for(let r of Object.keys(i)){let s=i[r];if(N(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(de(s))n[r]=s;else{let a=ue(s);n[r]=be(a),Ot(s,t)}}else n[r]=s}t.set(e,n)}else ie(i);return t}function $(i){return i.split(".")[0].split(It)[0]}function An(i){let t=$(i);return[t,`${t}${It}\uFFFF`]}function Ct(i,t){return $(i)===$(t)}function te(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Bn(i){return N(i)&&!ie(i)}function Br(i,t){return i===t?!0:ie(i)&&ie(t)?xi(i,t):!1}function et(i,t,e,n,r=[],s={}){let a=ue(i);function d(h,m,C){if(!Bn(m))Br(m,C)||r.push({oid:a,timestamp:e(),data:{op:"set",name:h,value:m}});else{let P=oe(C),v=oe(m);v&&!Ct(a,v)?(m=ne(m,!1),v=ge(a,n),K(m,v)):s.mergeUnknownObjects?!v&&P?(K(m,P),v=P):v=Tn(m,a,n):v=Tn(m,a,n),V(!!v,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Ct(a,v),`Error: value OID ${v} is not related to parent OID ${a}. This is a bug in Verdant.`),C===void 0||v!==P?(xe(m,v,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:h,value:be(v)}}),P!==void 0&&r.push({oid:P,timestamp:e(),data:{op:"delete"}})):et(C,m,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let m=0;m<t.length;m++){let C=t[m],P=i[m];d(m,C,P)}let h=i.length-t.length;if(h>0){for(let m=t.length;m<i.length;m++){let C=i[m],P=oe(C);P&&r.push({oid:P,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:h}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Bn(i)&&Bn(t)){let h=new Set(Object.keys(i));for(let[m,C]of Object.entries(t)){if(C===void 0&&s.defaultUndefined||(h.delete(m),Pn(m)))continue;let P=i[m];d(m,C,P)}if(!s.defaultUndefined)for(let m of h)Pn(m)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:m}})}}return r}function xe(i,t,e,n,r=[]){K(i,t),je(i,n);let s=Ot(i);for(let a of s.keys()){let d=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Dt(d)}})}return r}function Fi(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function kn(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Fn(i){let t={};for(let e of i){let n=$(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function De(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${oe(i)})`),!1)}function Ce(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(d){e&&ie(d)&&e.push(d)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":De(i)&&i.push(t.value);break;case"list-delete":De(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":De(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(De(i))do{let d=t.value;t.only==="last"?te(d)?r=_i(i,h=>h.id===d.id):r=i.lastIndexOf(d):te(d)?r=i.findIndex(h=>h.id===d.id):r=i.indexOf(d),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":De(i)&&(i.some(h=>te(h)&&te(t.value)?h.id===t.value.id:h===t.value)||i.push(t.value));break;case"list-move-by-ref":De(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(De(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):N(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return ne(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Et(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=ki(r,t,e),N(i[n])&&Et(i[n],t,e)}else if(!de(i)){if(N(i)){V(oe(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=ki(i[n],t,e),N(i[n])&&Et(i[n],t,e)}}return e}function ki(i,t,e){if(te(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),K(n,i.id)}else return i}function Rn(i){return i.equals!==void 0}function Mn(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function kr(i){return!!i.match}function jn(i){return i.startsWith!==void 0}function Ri(i){return!Mn(i)&&!Rn(i)&&!kr(i)&&!jn(i)&&i.order}function Fr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function _e(i,t){for(let[e,n]of Object.entries(i.fields)){let r=Mi(n);(r!==void 0&&t[e]===void 0||!Fr(n)&&t[e]===null)&&(t[e]=r),t[e]&&Ee(t[e],n)}return t}function Ee(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=Mi(n);r!==void 0&&(i[e]=r)}Ee(i[e],n)}else if(t.type==="array")for(let e of i)Ee(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===Se||e===Ie||Ee(n,t.values)}function Mi(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function ji(i,t){for(let[e,n]of Object.entries(t))e===Se||e===Ie||(i.fields[e]?Ln(n,i.fields[e]):delete t[e]);return t}function Ln(i,t){if(N(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?Ln(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)Ln(e,t.items)}function Li(i){return i}function Vi(i){return i}var _t="\uFFFFFE",Rr="\0",Mr="\uFFFFFF";function ce(...i){let t=jr(i);return t.length===1?t[0]:t}function Pe(...i){return i.join(_t)+`${Mr}`}function Te(...i){return i.join(_t)+`${_t}${Rr}`}function jr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(_t))))}function Lr(i,t){let e={};for(let[n,r]of Object.entries(i.synthetics||{}))e[n]=ve(r.compute(t));return e}function Vr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=ce(...r.of.map(s=>t[s])),e),{})}function Pt(i,t){return Object.assign(t,Lr(i,t)),Object.assign(t,Vr(i,t)),t}var Ur="null";function ve(i){if(i===null)return Ur;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(ve);throw new Error(`Unsupported index value: ${i}`)}var Nr={version:0,collections:{}};function Tt(i,t,e){let n=typeof t=="function",r=n?Nr:i,s=n?i:t,a=n?t:e,d=Object.keys(s.collections).filter(I=>r.collections[I]&&Cn(r.collections[I])!==Cn(s.collections[I])),h=Object.keys(r.collections).filter(I=>!s.collections[I]),m=Object.keys(s.collections).filter(I=>!r.collections[I]),C=new Set;for(let I of d){let D=r.collections[I].fields,O=s.collections[I].fields;Object.keys(O).some(x=>!D[x]?.default&&O[x]?.default)&&C.add(I),Object.keys(D).some(x=>!O[x])&&C.add(I)}let P={},v={};for(let I of[...d,...m]){let D=Ui(r.collections[I]),O=Ui(s.collections[I]),x=O.filter(y=>!D.find(w=>w.name===y.name)),A=D.filter(y=>!O.find(w=>w.name===y.name));x.length>0&&(P[I]=x,d.includes(I)&&C.add(I)),A.length>0&&(v[I]=A,d.includes(I)&&C.add(I))}let T=(I,D)=>_e(s.collections[I],D),b=I=>D=>{let O=s.collections[I];return _e(O,ji(O,D))};return{version:s.version,migrate:async I=>{let D=[];if(await a({migrate:async(O,x)=>{let A=b(O),y=async w=>{let l=await x(w);return K(l,ue(w)),A(l)};await I.migrate(O,y),D.push(O),C.delete(O)},identity:O=>O,withDefaults:T,info:{changedCollections:d,addedCollections:m,removedCollections:h},queries:I.queries,mutations:I.mutations}),s.version>1){I.log("debug","auto-migrating collections with new defaults",C);for(let x of C)await I.migrate(x,b(x)),D.push(x);let O=d.filter(x=>!D.includes(x));O.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,O)}},removedCollections:h,addedIndexes:P,removedIndexes:v,allCollections:Object.keys(s.collections),changedCollections:d,addedCollections:m,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function Ui(i){return i?[...Object.keys(i.fields).filter(e=>i.fields[e].indexed).map(e=>({name:e,multiEntry:i.fields[e].type==="array",synthetic:!1,compound:!1})),...Object.keys(i.synthetics||{}).map(e=>({name:e,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.synthetics[e].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(e=>({name:e,multiEntry:i.compounds[e].of.some(n=>(i.fields[n]||i.synthetics[n]).type==="array"),synthetic:!1,compound:!0}))]:[]}function Vn(i,t){return Tt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}var At=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>xe(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!N(n)||ie(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:be(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(N(e)){let n=ge(t,this.createSubId);return[...xe(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:be(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>N(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:be(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(N(n)){let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:be(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var U=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=St(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function Ni(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=ne(t),s=[];for(let a of e){let d=Kr(i,r,a,n);s.unshift(...d),Ce(r,a.data)}return s}function Kr(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(d=>({oid:i,timestamp:n(),data:{op:"list-insert",index:d,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Ve=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush())}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new Un({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},Un=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let s=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():s&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function tt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),d=0,h=0;a.onsuccess=function(m){let C=a.result;C&&(d++,h=h+Ei(C.value),C.continue())},a.onerror=function(m){n(m)},r.oncomplete=function(m){e({count:d,size:h})},r.onabort=function(m){n(m)},r.onerror=function(m){n(m)}})}function Ki(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return W(s.getAll())});return Promise.all(n)}async function Ae(i){i.close(),await new Promise((t,e)=>{t()})}async function Bt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}function zi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function $i(i=window.indexedDB){return i.databases()}var pe=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),d=e(a);return W(d)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),d=e(a);return Promise.all(d.map(W))};this.iterate=async(t,e,n,r="readonly",s)=>{let d=(s||this.db.transaction(t,r)).objectStore(t),h=e(d);return new Promise((m,C)=>{h.onsuccess=P=>{let v=h.result;v?(n(v.value,d),v.continue()):m()},h.onerror=C})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var kt=class extends pe{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var Ft=class extends pe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let[d,h]=An(e);return a.openCursor(IDBKeyRange.bound(d,h,!1,!1))},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.map(a=>{let[d,h]=An(a);return s.getAll(IDBKeyRange.bound(d,h,!1,!1))}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var qi=dt(ft(),1);var Rt=class extends pe{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,qi.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var Mt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(d=>{r.push({data:d.data,oid:d.oid,timestamp:d.timestamp}),s.add($(d.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(d=>{r.push({data:d.data,oid:d.oid,timestamp:d.timestamp}),s.add($(d.oid))},{mode:"readwrite"});let a=[];return n||(a=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var jt=class extends pe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:d="readonly",transaction:h}={})=>{let C=(h||this.db.transaction("operations",d)).objectStore("operations"),P=C.index("d_t"),v=s||a,T=v?ce(e,v):Te(e),b=r?ce(e,r):Pe(e),I=IDBKeyRange.bound(T,b,!!a,!1),D=P.openCursor(I,"next");return new Promise((O,x)=>{let A;D.onsuccess=y=>{let w=D.result;if(w){let l=w.value;V(l.oid.startsWith(e)),V(A===void 0||A<=l.timestamp,`expected ${A} <= ${l.timestamp}`),n(l,C),A=l.timestamp,w.continue()}else O()},D.onerror=y=>{x(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:d})=>{let m=(d||this.db.transaction("operations",a)).objectStore("operations"),C=r?ce(e,r):Te(e),P=s?ce(e,s):Pe(e),v=IDBKeyRange.bound(C,P,!!r,!1),T=m.openCursor(v,"next");return new Promise((b,I)=>{let D;T.onsuccess=O=>{let x=T.result;if(x){let A=x.value;V(A.oid.startsWith(e)),V(D===void 0||D<=A.timestamp,`expected ${D} <= ${A.timestamp}`),n(A,m),D=A.timestamp,x.continue()}else b()},T.onerror=O=>{I(O)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let h=(a||this.db.transaction("operations",s)).objectStore("operations"),m=h.index("l_t"),C=r?ce(!0,r):Te(!0),P=n?ce(!0,n):Pe(!0),v=IDBKeyRange.bound(C,P,!!r,!0),T=m.openCursor(v,"next");return new Promise((b,I)=>{let D;T.onsuccess=O=>{let x=T.result;if(x){let A=x.value;V(D===void 0||D<=A.timestamp,`expected ${D} <= ${A.timestamp}`),e(A,h),D=A.timestamp,x.continue()}else b()},T.onerror=O=>{I(O)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",d=>{let h=a?Te(a):void 0,m=n?Pe(n):void 0,C=h&&m?IDBKeyRange.bound(h,m,!1,!0):h?IDBKeyRange.lowerBound(h,!1):m?IDBKeyRange.upperBound(m,!0):void 0;return d.index("timestamp").openCursor(C,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:ce(e.oid,e.timestamp),l_t:ce(e.isLocal,e.timestamp),d_t:ce($(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add($(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Lt=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await W(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(s)}}};var nt=class extends U{constructor({disableRebasing:e,context:n}){super();this.time=new mt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=$(e);V(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=$(e);V(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),d=new Map;for(let m of a)m.snapshot&&K(m.snapshot,m.oid),d.set(m.oid,m.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,m=>{let C=d.get(m.oid)||void 0,P=Ce(C,m.data);P&&K(P,m.oid),d.set(m.oid,P)},{transaction:s,to:n.to||this.now});let h=d.get(r);return h&&Et(h,d),h};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add($(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(h=>{r.add(h.oid),n=h.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let d=[];for(let h of r)d.push(await this.rebase(h,n||e,s));this.emit("rebase",d)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),d=await this.baselines.get(e,{transaction:a}),h=d?.snapshot||void 0,m=0,C=[];await this.operations.iterateOverAllOperationsForEntity(e,(v,T)=>{(!d||v.timestamp>d.timestamp)&&(h=Ce(h,v.data,C)),m++,T.delete(v.oid_timestamp)},{to:n,transaction:a}),h&&K(h,e);let P={oid:e,snapshot:h,timestamp:n};if(P.snapshot?await this.baselines.set(P,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",h,"and deleted",m,"operations"),C.length){let v=C.filter(de);v.length&&this.emit("filesDeleted",v)}return P};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
4
+ `)},_domwindow:function(){return p("domwindow")},_bigint:function(c){return p("bigint:"+c.toString())},_process:function(){return p("process")},_timer:function(){return p("timer")},_pipe:function(){return p("pipe")},_tcp:function(){return p("tcp")},_udp:function(){return p("udp")},_tty:function(){return p("tty")},_statwatcher:function(){return p("statwatcher")},_securecontext:function(){return p("securecontext")},_connection:function(){return p("connection")},_zlib:function(){return p("zlib")},_context:function(){return p("context")},_nodescript:function(){return p("nodescript")},_httpparser:function(){return p("httpparser")},_dataview:function(){return p("dataview")},_signal:function(){return p("signal")},_fsevent:function(){return p("fsevent")},_tlswrap:function(){return p("tlswrap")}}}function A(){return{buf:"",write:function(y){this.buf+=y},end:function(y){this.buf+=y},read:function(){return this.buf}}}e.writeToStream=function(y,I,d){return d===void 0&&(d=I,I={}),S(I=C(y,I),d).dispatch(y)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/fake_9a5aa49d.js","/")},{buffer:3,crypto:5,lYpoI2:11}],2:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){(function(b){"use strict";var P=typeof Uint8Array<"u"?Uint8Array:Array,g="+".charCodeAt(0),O="/".charCodeAt(0),C="0".charCodeAt(0),x="a".charCodeAt(0),S="A".charCodeAt(0),A="-".charCodeAt(0),y="_".charCodeAt(0);function I(d){return d=d.charCodeAt(0),d===g||d===A?62:d===O||d===y?63:d<C?-1:d<C+10?d-C+26+26:d<S+26?d-S:d<x+26?d-x+26:void 0}b.toByteArray=function(d){var p,c;if(0<d.length%4)throw new Error("Invalid string. Length must be a multiple of 4");var w=d.length,w=d.charAt(w-2)==="="?2:d.charAt(w-1)==="="?1:0,D=new P(3*d.length/4-w),F=0<w?d.length-4:d.length,R=0;function j(B){D[R++]=B}for(p=0;p<F;p+=4,0)j((16711680&(c=I(d.charAt(p))<<18|I(d.charAt(p+1))<<12|I(d.charAt(p+2))<<6|I(d.charAt(p+3))))>>16),j((65280&c)>>8),j(255&c);return w==2?j(255&(c=I(d.charAt(p))<<2|I(d.charAt(p+1))>>4)):w==1&&(j((c=I(d.charAt(p))<<10|I(d.charAt(p+1))<<4|I(d.charAt(p+2))>>2)>>8&255),j(255&c)),D},b.fromByteArray=function(d){var p,c,w,D,F=d.length%3,R="";function j(B){return"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(B)}for(p=0,w=d.length-F;p<w;p+=3)c=(d[p]<<16)+(d[p+1]<<8)+d[p+2],R+=j((D=c)>>18&63)+j(D>>12&63)+j(D>>6&63)+j(63&D);switch(F){case 1:R=(R+=j((c=d[d.length-1])>>2))+j(c<<4&63)+"==";break;case 2:R=(R=(R+=j((c=(d[d.length-2]<<8)+d[d.length-1])>>10))+j(c>>4&63))+j(c<<2&63)+"="}return R}})(e===void 0?this.base64js={}:e)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/base64-js/lib/b64.js","/node_modules/gulp-browserify/node_modules/base64-js/lib")},{buffer:3,lYpoI2:11}],3:[function(i,t,e){(function(n,r,g,a,l,f,h,v,E){var b=i("base64-js"),P=i("ieee754");function g(o,u,m){if(!(this instanceof g))return new g(o,u,m);var T,_,M,L,Q=typeof o;if(u==="base64"&&Q=="string")for(o=(L=o).trim?L.trim():L.replace(/^\s+|\s+$/g,"");o.length%4!=0;)o+="=";if(Q=="number")T=ee(o);else if(Q=="string")T=g.byteLength(o,u);else{if(Q!="object")throw new Error("First argument needs to be a number, array or string.");T=ee(o.length)}if(g._useTypedArrays?_=g._augment(new Uint8Array(T)):((_=this).length=T,_._isBuffer=!0),g._useTypedArrays&&typeof o.byteLength=="number")_._set(o);else if(H(L=o)||g.isBuffer(L)||L&&typeof L=="object"&&typeof L.length=="number")for(M=0;M<T;M++)g.isBuffer(o)?_[M]=o.readUInt8(M):_[M]=o[M];else if(Q=="string")_.write(o,0,u);else if(Q=="number"&&!g._useTypedArrays&&!m)for(M=0;M<T;M++)_[M]=0;return _}function O(o,u,m,T){return g._charsWritten=dt(function(_){for(var M=[],L=0;L<_.length;L++)M.push(255&_.charCodeAt(L));return M}(u),o,m,T)}function C(o,u,m,T){return g._charsWritten=dt(function(_){for(var M,L,Q=[],Y=0;Y<_.length;Y++)L=_.charCodeAt(Y),M=L>>8,L=L%256,Q.push(L),Q.push(M);return Q}(u),o,m,T)}function x(o,u,m){var T="";m=Math.min(o.length,m);for(var _=u;_<m;_++)T+=String.fromCharCode(o[_]);return T}function S(o,u,m,M){M||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+1<o.length,"Trying to read beyond buffer length"));var _,M=o.length;if(!(M<=u))return m?(_=o[u],u+1<M&&(_|=o[u+1]<<8)):(_=o[u]<<8,u+1<M&&(_|=o[u+1])),_}function A(o,u,m,M){M||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+3<o.length,"Trying to read beyond buffer length"));var _,M=o.length;if(!(M<=u))return m?(u+2<M&&(_=o[u+2]<<16),u+1<M&&(_|=o[u+1]<<8),_|=o[u],u+3<M&&(_+=o[u+3]<<24>>>0)):(u+1<M&&(_=o[u+1]<<16),u+2<M&&(_|=o[u+2]<<8),u+3<M&&(_|=o[u+3]),_+=o[u]<<24>>>0),_}function y(o,u,m,T){if(T||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+1<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=S(o,u,m,!0),32768&T?-1*(65535-T+1):T}function I(o,u,m,T){if(T||(k(typeof m=="boolean","missing or invalid endian"),k(u!=null,"missing offset"),k(u+3<o.length,"Trying to read beyond buffer length")),!(o.length<=u))return T=A(o,u,m,!0),2147483648&T?-1*(4294967295-T+1):T}function d(o,u,m,T){return T||(k(typeof m=="boolean","missing or invalid endian"),k(u+3<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,23,4)}function p(o,u,m,T){return T||(k(typeof m=="boolean","missing or invalid endian"),k(u+7<o.length,"Trying to read beyond buffer length")),P.read(o,u,m,52,8)}function c(o,u,m,T,_){if(_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+1<o.length,"trying to write beyond buffer length"),bn(u,65535)),_=o.length,!(_<=m))for(var M=0,L=Math.min(_-m,2);M<L;M++)o[m+M]=(u&255<<8*(T?M:1-M))>>>8*(T?M:1-M)}function w(o,u,m,T,_){if(_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"trying to write beyond buffer length"),bn(u,4294967295)),_=o.length,!(_<=m))for(var M=0,L=Math.min(_-m,4);M<L;M++)o[m+M]=u>>>8*(T?M:3-M)&255}function D(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+1<o.length,"Trying to write beyond buffer length"),wn(u,32767,-32768)),o.length<=m||c(o,0<=u?u:65535+u+1,m,T,_)}function F(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"Trying to write beyond buffer length"),wn(u,2147483647,-2147483648)),o.length<=m||w(o,0<=u?u:4294967295+u+1,m,T,_)}function R(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+3<o.length,"Trying to write beyond buffer length"),ii(u,34028234663852886e22,-34028234663852886e22)),o.length<=m||P.write(o,u,m,T,23,4)}function j(o,u,m,T,_){_||(k(u!=null,"missing value"),k(typeof T=="boolean","missing or invalid endian"),k(m!=null,"missing offset"),k(m+7<o.length,"Trying to write beyond buffer length"),ii(u,17976931348623157e292,-17976931348623157e292)),o.length<=m||P.write(o,u,m,T,52,8)}e.Buffer=g,e.SlowBuffer=g,e.INSPECT_MAX_BYTES=50,g.poolSize=8192,g._useTypedArrays=function(){try{var o=new ArrayBuffer(0),u=new Uint8Array(o);return u.foo=function(){return 42},u.foo()===42&&typeof u.subarray=="function"}catch{return!1}}(),g.isEncoding=function(o){switch(String(o).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"raw":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},g.isBuffer=function(o){return!(o==null||!o._isBuffer)},g.byteLength=function(o,u){var m;switch(o+="",u||"utf8"){case"hex":m=o.length/2;break;case"utf8":case"utf-8":m=be(o).length;break;case"ascii":case"binary":case"raw":m=o.length;break;case"base64":m=ti(o).length;break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":m=2*o.length;break;default:throw new Error("Unknown encoding")}return m},g.concat=function(o,u){if(k(H(o),`Usage: Buffer.concat(list, [totalLength])
5
+ list should be an Array.`),o.length===0)return new g(0);if(o.length===1)return o[0];if(typeof u!="number")for(_=u=0;_<o.length;_++)u+=o[_].length;for(var m=new g(u),T=0,_=0;_<o.length;_++){var M=o[_];M.copy(m,T),T+=M.length}return m},g.prototype.write=function(o,u,m,T){isFinite(u)?isFinite(m)||(T=m,m=void 0):(Y=T,T=u,u=m,m=Y),u=Number(u)||0;var _,M,L,Q,Y=this.length-u;switch((!m||Y<(m=Number(m)))&&(m=Y),T=String(T||"utf8").toLowerCase()){case"hex":_=function(he,ie,re,G){re=Number(re)||0;var J=he.length-re;(!G||J<(G=Number(G)))&&(G=J),k((J=ie.length)%2==0,"Invalid hex string"),J/2<G&&(G=J/2);for(var Fe=0;Fe<G;Fe++){var ri=parseInt(ie.substr(2*Fe,2),16);k(!isNaN(ri),"Invalid hex string"),he[re+Fe]=ri}return g._charsWritten=2*Fe,Fe}(this,o,u,m);break;case"utf8":case"utf-8":M=this,L=u,Q=m,_=g._charsWritten=dt(be(o),M,L,Q);break;case"ascii":case"binary":_=O(this,o,u,m);break;case"base64":M=this,L=u,Q=m,_=g._charsWritten=dt(ti(o),M,L,Q);break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":_=C(this,o,u,m);break;default:throw new Error("Unknown encoding")}return _},g.prototype.toString=function(o,u,m){var T,_,M,L,Q=this;if(o=String(o||"utf8").toLowerCase(),u=Number(u)||0,(m=m!==void 0?Number(m):Q.length)===u)return"";switch(o){case"hex":T=function(Y,he,ie){var re=Y.length;(!he||he<0)&&(he=0),(!ie||ie<0||re<ie)&&(ie=re);for(var G="",J=he;J<ie;J++)G+=$(Y[J]);return G}(Q,u,m);break;case"utf8":case"utf-8":T=function(Y,he,ie){var re="",G="";ie=Math.min(Y.length,ie);for(var J=he;J<ie;J++)Y[J]<=127?(re+=ni(G)+String.fromCharCode(Y[J]),G=""):G+="%"+Y[J].toString(16);return re+ni(G)}(Q,u,m);break;case"ascii":case"binary":T=x(Q,u,m);break;case"base64":_=Q,L=m,T=(M=u)===0&&L===_.length?b.fromByteArray(_):b.fromByteArray(_.slice(M,L));break;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":T=function(Y,he,ie){for(var re=Y.slice(he,ie),G="",J=0;J<re.length;J+=2)G+=String.fromCharCode(re[J]+256*re[J+1]);return G}(Q,u,m);break;default:throw new Error("Unknown encoding")}return T},g.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}},g.prototype.copy=function(o,u,m,T){if(u=u||0,(T=T||T===0?T:this.length)!==(m=m||0)&&o.length!==0&&this.length!==0){k(m<=T,"sourceEnd < sourceStart"),k(0<=u&&u<o.length,"targetStart out of bounds"),k(0<=m&&m<this.length,"sourceStart out of bounds"),k(0<=T&&T<=this.length,"sourceEnd out of bounds"),T>this.length&&(T=this.length);var _=(T=o.length-u<T-m?o.length-u+m:T)-m;if(_<100||!g._useTypedArrays)for(var M=0;M<_;M++)o[M+u]=this[M+m];else o._set(this.subarray(m,m+_),u)}},g.prototype.slice=function(o,u){var m=this.length;if(o=q(o,m,0),u=q(u,m,m),g._useTypedArrays)return g._augment(this.subarray(o,u));for(var T=u-o,_=new g(T,void 0,!0),M=0;M<T;M++)_[M]=this[M+o];return _},g.prototype.get=function(o){return console.log(".get() is deprecated. Access using array indexes instead."),this.readUInt8(o)},g.prototype.set=function(o,u){return console.log(".set() is deprecated. Access using array indexes instead."),this.writeUInt8(o,u)},g.prototype.readUInt8=function(o,u){if(u||(k(o!=null,"missing offset"),k(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return this[o]},g.prototype.readUInt16LE=function(o,u){return S(this,o,!0,u)},g.prototype.readUInt16BE=function(o,u){return S(this,o,!1,u)},g.prototype.readUInt32LE=function(o,u){return A(this,o,!0,u)},g.prototype.readUInt32BE=function(o,u){return A(this,o,!1,u)},g.prototype.readInt8=function(o,u){if(u||(k(o!=null,"missing offset"),k(o<this.length,"Trying to read beyond buffer length")),!(o>=this.length))return 128&this[o]?-1*(255-this[o]+1):this[o]},g.prototype.readInt16LE=function(o,u){return y(this,o,!0,u)},g.prototype.readInt16BE=function(o,u){return y(this,o,!1,u)},g.prototype.readInt32LE=function(o,u){return I(this,o,!0,u)},g.prototype.readInt32BE=function(o,u){return I(this,o,!1,u)},g.prototype.readFloatLE=function(o,u){return d(this,o,!0,u)},g.prototype.readFloatBE=function(o,u){return d(this,o,!1,u)},g.prototype.readDoubleLE=function(o,u){return p(this,o,!0,u)},g.prototype.readDoubleBE=function(o,u){return p(this,o,!1,u)},g.prototype.writeUInt8=function(o,u,m){m||(k(o!=null,"missing value"),k(u!=null,"missing offset"),k(u<this.length,"trying to write beyond buffer length"),bn(o,255)),u>=this.length||(this[u]=o)},g.prototype.writeUInt16LE=function(o,u,m){c(this,o,u,!0,m)},g.prototype.writeUInt16BE=function(o,u,m){c(this,o,u,!1,m)},g.prototype.writeUInt32LE=function(o,u,m){w(this,o,u,!0,m)},g.prototype.writeUInt32BE=function(o,u,m){w(this,o,u,!1,m)},g.prototype.writeInt8=function(o,u,m){m||(k(o!=null,"missing value"),k(u!=null,"missing offset"),k(u<this.length,"Trying to write beyond buffer length"),wn(o,127,-128)),u>=this.length||(0<=o?this.writeUInt8(o,u,m):this.writeUInt8(255+o+1,u,m))},g.prototype.writeInt16LE=function(o,u,m){D(this,o,u,!0,m)},g.prototype.writeInt16BE=function(o,u,m){D(this,o,u,!1,m)},g.prototype.writeInt32LE=function(o,u,m){F(this,o,u,!0,m)},g.prototype.writeInt32BE=function(o,u,m){F(this,o,u,!1,m)},g.prototype.writeFloatLE=function(o,u,m){R(this,o,u,!0,m)},g.prototype.writeFloatBE=function(o,u,m){R(this,o,u,!1,m)},g.prototype.writeDoubleLE=function(o,u,m){j(this,o,u,!0,m)},g.prototype.writeDoubleBE=function(o,u,m){j(this,o,u,!1,m)},g.prototype.fill=function(o,u,m){if(u=u||0,m=m||this.length,k(typeof(o=typeof(o=o||0)=="string"?o.charCodeAt(0):o)=="number"&&!isNaN(o),"value is not a number"),k(u<=m,"end < start"),m!==u&&this.length!==0){k(0<=u&&u<this.length,"start out of bounds"),k(0<=m&&m<=this.length,"end out of bounds");for(var T=u;T<m;T++)this[T]=o}},g.prototype.inspect=function(){for(var o=[],u=this.length,m=0;m<u;m++)if(o[m]=$(this[m]),m===e.INSPECT_MAX_BYTES){o[m+1]="...";break}return"<Buffer "+o.join(" ")+">"},g.prototype.toArrayBuffer=function(){if(typeof Uint8Array>"u")throw new Error("Buffer.toArrayBuffer not supported in this browser");if(g._useTypedArrays)return new g(this).buffer;for(var o=new Uint8Array(this.length),u=0,m=o.length;u<m;u+=1)o[u]=this[u];return o.buffer};var B=g.prototype;function q(o,u,m){return typeof o!="number"?m:u<=(o=~~o)?u:0<=o||0<=(o+=u)?o:0}function ee(o){return(o=~~Math.ceil(+o))<0?0:o}function H(o){return(Array.isArray||function(u){return Object.prototype.toString.call(u)==="[object Array]"})(o)}function $(o){return o<16?"0"+o.toString(16):o.toString(16)}function be(o){for(var u=[],m=0;m<o.length;m++){var T=o.charCodeAt(m);if(T<=127)u.push(o.charCodeAt(m));else for(var _=m,M=(55296<=T&&T<=57343&&m++,encodeURIComponent(o.slice(_,m+1)).substr(1).split("%")),L=0;L<M.length;L++)u.push(parseInt(M[L],16))}return u}function ti(o){return b.toByteArray(o)}function dt(o,u,m,T){for(var _=0;_<T&&!(_+m>=u.length||_>=o.length);_++)u[_+m]=o[_];return _}function ni(o){try{return decodeURIComponent(o)}catch{return String.fromCharCode(65533)}}function bn(o,u){k(typeof o=="number","cannot write a non-number as a number"),k(0<=o,"specified a negative value for writing an unsigned value"),k(o<=u,"value is larger than maximum value for type"),k(Math.floor(o)===o,"value has a fractional component")}function wn(o,u,m){k(typeof o=="number","cannot write a non-number as a number"),k(o<=u,"value larger than maximum allowed value"),k(m<=o,"value smaller than minimum allowed value"),k(Math.floor(o)===o,"value has a fractional component")}function ii(o,u,m){k(typeof o=="number","cannot write a non-number as a number"),k(o<=u,"value larger than maximum allowed value"),k(m<=o,"value smaller than minimum allowed value")}function k(o,u){if(!o)throw new Error(u||"Failed assertion")}g._augment=function(o){return o._isBuffer=!0,o._get=o.get,o._set=o.set,o.get=B.get,o.set=B.set,o.write=B.write,o.toString=B.toString,o.toLocaleString=B.toString,o.toJSON=B.toJSON,o.copy=B.copy,o.slice=B.slice,o.readUInt8=B.readUInt8,o.readUInt16LE=B.readUInt16LE,o.readUInt16BE=B.readUInt16BE,o.readUInt32LE=B.readUInt32LE,o.readUInt32BE=B.readUInt32BE,o.readInt8=B.readInt8,o.readInt16LE=B.readInt16LE,o.readInt16BE=B.readInt16BE,o.readInt32LE=B.readInt32LE,o.readInt32BE=B.readInt32BE,o.readFloatLE=B.readFloatLE,o.readFloatBE=B.readFloatBE,o.readDoubleLE=B.readDoubleLE,o.readDoubleBE=B.readDoubleBE,o.writeUInt8=B.writeUInt8,o.writeUInt16LE=B.writeUInt16LE,o.writeUInt16BE=B.writeUInt16BE,o.writeUInt32LE=B.writeUInt32LE,o.writeUInt32BE=B.writeUInt32BE,o.writeInt8=B.writeInt8,o.writeInt16LE=B.writeInt16LE,o.writeInt16BE=B.writeInt16BE,o.writeInt32LE=B.writeInt32LE,o.writeInt32BE=B.writeInt32BE,o.writeFloatLE=B.writeFloatLE,o.writeFloatBE=B.writeFloatBE,o.writeDoubleLE=B.writeDoubleLE,o.writeDoubleBE=B.writeDoubleBE,o.fill=B.fill,o.inspect=B.inspect,o.toArrayBuffer=B.toArrayBuffer,o}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/buffer/index.js","/node_modules/gulp-browserify/node_modules/buffer")},{"base64-js":2,buffer:3,ieee754:10,lYpoI2:11}],4:[function(i,t,e){(function(n,r,b,a,l,f,h,v,E){var b=i("buffer").Buffer,P=4,g=new b(P);g.fill(0),t.exports={hash:function(O,C,x,S){for(var A=C(function(c,w){c.length%P!=0&&(D=c.length+(P-c.length%P),c=b.concat([c,g],D));for(var D,F=[],R=w?c.readInt32BE:c.readInt32LE,j=0;j<c.length;j+=P)F.push(R.call(c,j));return F}(O=b.isBuffer(O)?O:new b(O),S),8*O.length),C=S,y=new b(x),I=C?y.writeInt32BE:y.writeInt32LE,d=0;d<A.length;d++)I.call(y,A[d],4*d,!0);return y}}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/helpers.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],5:[function(i,t,e){(function(n,r,b,a,l,f,h,v,E){var b=i("buffer").Buffer,P=i("./sha"),g=i("./sha256"),O=i("./rng"),C={sha1:P,sha256:g,md5:i("./md5")},x=64,S=new b(x);function A(c,w){var D=C[c=c||"sha1"],F=[];return D||y("algorithm:",c,"is not yet supported"),{update:function(R){return b.isBuffer(R)||(R=new b(R)),F.push(R),R.length,this},digest:function(R){var j=b.concat(F),j=w?function(B,q,ee){b.isBuffer(q)||(q=new b(q)),b.isBuffer(ee)||(ee=new b(ee)),q.length>x?q=B(q):q.length<x&&(q=b.concat([q,S],x));for(var H=new b(x),$=new b(x),be=0;be<x;be++)H[be]=54^q[be],$[be]=92^q[be];return ee=B(b.concat([H,ee])),B(b.concat([$,ee]))}(D,w,j):D(j);return F=null,R?j.toString(R):j}}}function y(){var c=[].slice.call(arguments).join(" ");throw new Error([c,"we accept pull requests","http://github.com/dominictarr/crypto-browserify"].join(`
6
+ `))}S.fill(0),e.createHash=function(c){return A(c)},e.createHmac=A,e.randomBytes=function(c,w){if(!w||!w.call)return new b(O(c));try{w.call(this,void 0,new b(O(c)))}catch(D){w(D)}};var I,d=["createCredentials","createCipher","createCipheriv","createDecipher","createDecipheriv","createSign","createVerify","createDiffieHellman","pbkdf2"],p=function(c){e[c]=function(){y("sorry,",c,"is not implemented yet")}};for(I in d)p(d[I],I)}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/index.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./md5":6,"./rng":7,"./sha":8,"./sha256":9,buffer:3,lYpoI2:11}],6:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){var b=i("./helpers");function P(y,I){y[I>>5]|=128<<I%32,y[14+(I+64>>>9<<4)]=I;for(var d=1732584193,p=-271733879,c=-1732584194,w=271733878,D=0;D<y.length;D+=16){var F=d,R=p,j=c,B=w,d=O(d,p,c,w,y[D+0],7,-680876936),w=O(w,d,p,c,y[D+1],12,-389564586),c=O(c,w,d,p,y[D+2],17,606105819),p=O(p,c,w,d,y[D+3],22,-1044525330);d=O(d,p,c,w,y[D+4],7,-176418897),w=O(w,d,p,c,y[D+5],12,1200080426),c=O(c,w,d,p,y[D+6],17,-1473231341),p=O(p,c,w,d,y[D+7],22,-45705983),d=O(d,p,c,w,y[D+8],7,1770035416),w=O(w,d,p,c,y[D+9],12,-1958414417),c=O(c,w,d,p,y[D+10],17,-42063),p=O(p,c,w,d,y[D+11],22,-1990404162),d=O(d,p,c,w,y[D+12],7,1804603682),w=O(w,d,p,c,y[D+13],12,-40341101),c=O(c,w,d,p,y[D+14],17,-1502002290),d=C(d,p=O(p,c,w,d,y[D+15],22,1236535329),c,w,y[D+1],5,-165796510),w=C(w,d,p,c,y[D+6],9,-1069501632),c=C(c,w,d,p,y[D+11],14,643717713),p=C(p,c,w,d,y[D+0],20,-373897302),d=C(d,p,c,w,y[D+5],5,-701558691),w=C(w,d,p,c,y[D+10],9,38016083),c=C(c,w,d,p,y[D+15],14,-660478335),p=C(p,c,w,d,y[D+4],20,-405537848),d=C(d,p,c,w,y[D+9],5,568446438),w=C(w,d,p,c,y[D+14],9,-1019803690),c=C(c,w,d,p,y[D+3],14,-187363961),p=C(p,c,w,d,y[D+8],20,1163531501),d=C(d,p,c,w,y[D+13],5,-1444681467),w=C(w,d,p,c,y[D+2],9,-51403784),c=C(c,w,d,p,y[D+7],14,1735328473),d=x(d,p=C(p,c,w,d,y[D+12],20,-1926607734),c,w,y[D+5],4,-378558),w=x(w,d,p,c,y[D+8],11,-2022574463),c=x(c,w,d,p,y[D+11],16,1839030562),p=x(p,c,w,d,y[D+14],23,-35309556),d=x(d,p,c,w,y[D+1],4,-1530992060),w=x(w,d,p,c,y[D+4],11,1272893353),c=x(c,w,d,p,y[D+7],16,-155497632),p=x(p,c,w,d,y[D+10],23,-1094730640),d=x(d,p,c,w,y[D+13],4,681279174),w=x(w,d,p,c,y[D+0],11,-358537222),c=x(c,w,d,p,y[D+3],16,-722521979),p=x(p,c,w,d,y[D+6],23,76029189),d=x(d,p,c,w,y[D+9],4,-640364487),w=x(w,d,p,c,y[D+12],11,-421815835),c=x(c,w,d,p,y[D+15],16,530742520),d=S(d,p=x(p,c,w,d,y[D+2],23,-995338651),c,w,y[D+0],6,-198630844),w=S(w,d,p,c,y[D+7],10,1126891415),c=S(c,w,d,p,y[D+14],15,-1416354905),p=S(p,c,w,d,y[D+5],21,-57434055),d=S(d,p,c,w,y[D+12],6,1700485571),w=S(w,d,p,c,y[D+3],10,-1894986606),c=S(c,w,d,p,y[D+10],15,-1051523),p=S(p,c,w,d,y[D+1],21,-2054922799),d=S(d,p,c,w,y[D+8],6,1873313359),w=S(w,d,p,c,y[D+15],10,-30611744),c=S(c,w,d,p,y[D+6],15,-1560198380),p=S(p,c,w,d,y[D+13],21,1309151649),d=S(d,p,c,w,y[D+4],6,-145523070),w=S(w,d,p,c,y[D+11],10,-1120210379),c=S(c,w,d,p,y[D+2],15,718787259),p=S(p,c,w,d,y[D+9],21,-343485551),d=A(d,F),p=A(p,R),c=A(c,j),w=A(w,B)}return Array(d,p,c,w)}function g(y,I,d,p,c,w){return A((I=A(A(I,y),A(p,w)))<<c|I>>>32-c,d)}function O(y,I,d,p,c,w,D){return g(I&d|~I&p,y,I,c,w,D)}function C(y,I,d,p,c,w,D){return g(I&p|d&~p,y,I,c,w,D)}function x(y,I,d,p,c,w,D){return g(I^d^p,y,I,c,w,D)}function S(y,I,d,p,c,w,D){return g(d^(I|~p),y,I,c,w,D)}function A(y,I){var d=(65535&y)+(65535&I);return(y>>16)+(I>>16)+(d>>16)<<16|65535&d}t.exports=function(y){return b.hash(y,P,16)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/md5.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],7:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){var b;t.exports=b||function(P){for(var g,O=new Array(P),C=0;C<P;C++)!(3&C)&&(g=4294967296*Math.random()),O[C]=g>>>((3&C)<<3)&255;return O}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/rng.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{buffer:3,lYpoI2:11}],8:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){var b=i("./helpers");function P(C,x){C[x>>5]|=128<<24-x%32,C[15+(x+64>>9<<4)]=x;for(var S,A,y,I=Array(80),d=1732584193,p=-271733879,c=-1732584194,w=271733878,D=-1009589776,F=0;F<C.length;F+=16){for(var R=d,j=p,B=c,q=w,ee=D,H=0;H<80;H++){I[H]=H<16?C[F+H]:O(I[H-3]^I[H-8]^I[H-14]^I[H-16],1);var $=g(g(O(d,5),($=p,A=c,y=w,(S=H)<20?$&A|~$&y:!(S<40)&&S<60?$&A|$&y|A&y:$^A^y)),g(g(D,I[H]),(S=H)<20?1518500249:S<40?1859775393:S<60?-1894007588:-899497514)),D=w,w=c,c=O(p,30),p=d,d=$}d=g(d,R),p=g(p,j),c=g(c,B),w=g(w,q),D=g(D,ee)}return Array(d,p,c,w,D)}function g(C,x){var S=(65535&C)+(65535&x);return(C>>16)+(x>>16)+(S>>16)<<16|65535&S}function O(C,x){return C<<x|C>>>32-x}t.exports=function(C){return b.hash(C,P,20,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],9:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){function b(x,S){var A=(65535&x)+(65535&S);return(x>>16)+(S>>16)+(A>>16)<<16|65535&A}function P(x,S){var A,y=new Array(1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298),I=new Array(1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225),d=new Array(64);x[S>>5]|=128<<24-S%32,x[15+(S+64>>9<<4)]=S;for(var p,c,w=0;w<x.length;w+=16){for(var D=I[0],F=I[1],R=I[2],j=I[3],B=I[4],q=I[5],ee=I[6],H=I[7],$=0;$<64;$++)d[$]=$<16?x[$+w]:b(b(b((c=d[$-2],O(c,17)^O(c,19)^C(c,10)),d[$-7]),(c=d[$-15],O(c,7)^O(c,18)^C(c,3))),d[$-16]),A=b(b(b(b(H,O(c=B,6)^O(c,11)^O(c,25)),B&q^~B&ee),y[$]),d[$]),p=b(O(p=D,2)^O(p,13)^O(p,22),D&F^D&R^F&R),H=ee,ee=q,q=B,B=b(j,A),j=R,R=F,F=D,D=b(A,p);I[0]=b(D,I[0]),I[1]=b(F,I[1]),I[2]=b(R,I[2]),I[3]=b(j,I[3]),I[4]=b(B,I[4]),I[5]=b(q,I[5]),I[6]=b(ee,I[6]),I[7]=b(H,I[7])}return I}var g=i("./helpers"),O=function(x,S){return x>>>S|x<<32-S},C=function(x,S){return x>>>S};t.exports=function(x){return g.hash(x,P,32,!0)}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/crypto-browserify/sha256.js","/node_modules/gulp-browserify/node_modules/crypto-browserify")},{"./helpers":4,buffer:3,lYpoI2:11}],10:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){e.read=function(b,P,g,O,w){var x,S,A=8*w-O-1,y=(1<<A)-1,I=y>>1,d=-7,p=g?w-1:0,c=g?-1:1,w=b[P+p];for(p+=c,x=w&(1<<-d)-1,w>>=-d,d+=A;0<d;x=256*x+b[P+p],p+=c,d-=8);for(S=x&(1<<-d)-1,x>>=-d,d+=O;0<d;S=256*S+b[P+p],p+=c,d-=8);if(x===0)x=1-I;else{if(x===y)return S?NaN:1/0*(w?-1:1);S+=Math.pow(2,O),x-=I}return(w?-1:1)*S*Math.pow(2,x-O)},e.write=function(b,P,g,O,C,D){var S,A,y=8*D-C-1,I=(1<<y)-1,d=I>>1,p=C===23?Math.pow(2,-24)-Math.pow(2,-77):0,c=O?0:D-1,w=O?1:-1,D=P<0||P===0&&1/P<0?1:0;for(P=Math.abs(P),isNaN(P)||P===1/0?(A=isNaN(P)?1:0,S=I):(S=Math.floor(Math.log(P)/Math.LN2),P*(O=Math.pow(2,-S))<1&&(S--,O*=2),2<=(P+=1<=S+d?p/O:p*Math.pow(2,1-d))*O&&(S++,O/=2),I<=S+d?(A=0,S=I):1<=S+d?(A=(P*O-1)*Math.pow(2,C),S+=d):(A=P*Math.pow(2,d-1)*Math.pow(2,C),S=0));8<=C;b[g+c]=255&A,c+=w,A/=256,C-=8);for(S=S<<C|A,y+=C;0<y;b[g+c]=255&S,c+=w,S/=256,y-=8);b[g+c-w]|=128*D}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/ieee754/index.js","/node_modules/gulp-browserify/node_modules/ieee754")},{buffer:3,lYpoI2:11}],11:[function(i,t,e){(function(n,r,s,a,l,f,h,v,E){var b,P,g;function O(){}(n=t.exports={}).nextTick=(P=typeof window<"u"&&window.setImmediate,g=typeof window<"u"&&window.postMessage&&window.addEventListener,P?function(C){return window.setImmediate(C)}:g?(b=[],window.addEventListener("message",function(C){var x=C.source;x!==window&&x!==null||C.data!=="process-tick"||(C.stopPropagation(),0<b.length&&b.shift()())},!0),function(C){b.push(C),window.postMessage("process-tick","*")}):function(C){setTimeout(C,0)}),n.title="browser",n.browser=!0,n.env={},n.argv=[],n.on=O,n.addListener=O,n.once=O,n.off=O,n.removeListener=O,n.removeAllListeners=O,n.emit=O,n.binding=function(C){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(C){throw new Error("process.chdir is not supported")}}).call(this,i("lYpoI2"),typeof self<"u"?self:typeof window<"u"?window:{},i("buffer").Buffer,arguments[3],arguments[4],arguments[5],arguments[6],"/node_modules/gulp-browserify/node_modules/process/browser.js","/node_modules/gulp-browserify/node_modules/process")},{buffer:3,lYpoI2:11}]},{},[1])(1)})});var ei={};pr(ei,{Client:()=>Re,ClientDescriptor:()=>gn,Entity:()=>ye,EntityFile:()=>Me,MigrationPathError:()=>Ve,ServerSync:()=>Ke,Storage:()=>Re,StorageDescriptor:()=>gn,collection:()=>Ki,createDefaultMigration:()=>zn,createMigration:()=>$n,migrate:()=>kt,schema:()=>zi});var Si=ut(ht(),1),mt=4,Qe=36;function yi(i){return i.toString(Qe).padStart(mt,"0")}function vr(i){return i.toString().padStart(6,"0")}var yt=class{constructor(){this.latest={time:Date.now(),counter:0,node:Sr()};this.zeroCounter=0;this.now=t=>(this.latest=bi(this.latest),this.get(t,this.latest));this.OLD_now=t=>(this.latest=bi(this.latest),vr(t)+Or(this.latest));this.timerState=()=>this.latest;this.update=t=>{let e=t.slice(mt);this.latest=xr(this.latest,wi(e))};this.get=(t,e)=>yi(t)+gi(e);this.zero=t=>yi(t)+gi({time:0,counter:this.zeroCounter++,node:this.latest.node});this.getWallClockTime=t=>wi(t.slice(mt)).time}},gt=class extends Error{constructor(...e){super();this.type="ClockDriftError",this.message=["maximum clock drift exceeded"].concat(e).join(" ")}},bt=class extends Error{constructor(){super();this.type="OverflowError",this.message="timestamp counter overflow"}},Dn=4,Cn=7,wt=60*1e3,He=9;function Sr(){return Si.default.slug().padStart(Cn,"0").slice(0,Cn)}function gi(i){let t=new Date(i.time).getTime().toString(Qe).padStart(He,"0"),e=i.counter.toString(Qe).padStart(Dn,"0"),n=i.node.padStart(Cn,"0");return`${t}${e}${n}`}function bi(i){let t=Date.now(),e=Math.max(i.time,t),n=i.time===e?i.counter+1:0;if(e-t>wt)throw new gt(e,t,wt);if(n>65535)throw new bt;return{time:e,counter:n,node:i.node}}function xr(i,t){let e=Date.now(),n=Math.max(e,Math.max(i.time,t.time)),r=Math.max(i.counter,t.counter),s;if(i.time===n&&t.time===n?s=r+1:i.time===n?s=i.counter+1:t.time===n?s=t.counter+1:s=0,n-e>wt)throw new gt(n,e,wt);if(s>65535)throw new bt;return{time:n,counter:s,node:i.node}}function wi(i){let t=i.slice(0,He),e=i.slice(He,He+Dn),n=i.slice(He+Dn),r=parseInt(t,Qe),s=parseInt(e,Qe);if(isNaN(r)||isNaN(s))throw new Error("invalid clock format");return{time:r,counter:s,node:n}}function Or(i){let t=new Date(i.time).toISOString(),e=i.counter.toString(16).toUpperCase().padStart(4,"0"),n=i.node.padStart(16,"0");return`${t}-${e}-${n}`}function vi(i){return parseInt(i.slice(0,mt),36)}function xi(i,t){return vi(i)-vi(t)}function se(i){return i&&i["@@type"]==="file"}function Oi(i){return{"@@type":"file",id:i}}var vt,Ir=new Uint8Array(16);function En(){if(!vt&&(vt=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||typeof msCrypto<"u"&&typeof msCrypto.getRandomValues=="function"&&msCrypto.getRandomValues.bind(msCrypto),!vt))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return vt(Ir)}var Ii=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Dr(i){return typeof i=="string"&&Ii.test(i)}var Di=Dr;var X=[];for(St=0;St<256;++St)X.push((St+256).toString(16).substr(1));var St;function Cr(i){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,e=(X[i[t+0]]+X[i[t+1]]+X[i[t+2]]+X[i[t+3]]+"-"+X[i[t+4]]+X[i[t+5]]+"-"+X[i[t+6]]+X[i[t+7]]+"-"+X[i[t+8]]+X[i[t+9]]+"-"+X[i[t+10]]+X[i[t+11]]+X[i[t+12]]+X[i[t+13]]+X[i[t+14]]+X[i[t+15]]).toLowerCase();if(!Di(e))throw TypeError("Stringified UUID is invalid");return e}var Ci=Cr;function Er(i,t,e){i=i||{};var n=i.random||(i.rng||En)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,t){e=e||0;for(var r=0;r<16;++r)t[e+r]=n[r];return t}return Ci(n)}var Je=Er;function ne(i){return te(i)||se(i)}function Ei(i,t){return i===t?!0:!(!ne(i)||!ne(t)||i["@@type"]!==t["@@type"]||i.id!==t.id)}var Ai=ut(Ti(),1);function Pr(i,t){return typeof t!="object"||t===null||Array.isArray(t)?t:Object.fromEntries(Object.entries(t).sort(([e],[n])=>e<n?-1:e>n?1:0))}function Ye(i){return JSON.stringify(i,Pr)}function oe(i,t=!0){if(z(i)||Array.isArray(i)){let e=ae(i),n;if(Array.isArray(i))n=i.map(r=>oe(r,t));else{n={};for(let[r,s]of Object.entries(i))n[r]=oe(s,t)}return t&&e&&U(n,e),n}return i}function Se(i){return(0,Ai.default)(i)}function z(i){return i&&typeof i=="object"}function ki(i){for(var t=[],e=[i],n=0;e.length;){var r=e.pop();if(typeof r=="boolean")n+=4;else if(typeof r=="string")n+=r.length*2;else if(typeof r=="number")n+=8;else if(typeof r=="object"&&t.indexOf(r)===-1){t.push(r);for(var s in r)e.push(r[s])}}return n}function V(i,t="assertion failed"){if(!i)throw new Error(t)}function xt(i=16){return Je().replace("-","").slice(0,i)}function Mi(i,t){for(let e=i.length-1;e>=0;e--)if(t(i[e]))return e;return-1}function Bi(i,t){let e;return function(...n){let r=this;clearTimeout(e),e=setTimeout(()=>i.apply(r,n),t)}}var Ie="__@@oid_do_not_use",De="@@id",_r="/",Xe=":",_n=new WeakMap;function ce(i){let t=ae(i);return V(!!t,`Object ${JSON.stringify(i)} does not have an OID assigned to it`),t}function ae(i){if(z(i))return _n.get(i)??i[De]??i[Ie]}function U(i,t){return V(z(i),`Only objects can be assigned OIDs, received ${JSON.stringify(i)}`),Ze(i)&&Dt(i),_n.set(i,t),i}function Ze(i){return!!ae(i)}function Dt(i){return _n.delete(i),i}function Tn(i){return i===De||i===Ie}function An(i,t,e){if(Ze(i))return ce(i);{let n=ge(t,e);return U(i,n),n}}function Ri(i,t,e){if(Ze(i)){let n=ce(i);if(Ct(n,t))return ce(i);{let r=ge(t,e);return U(i,r),r}}else{let n=ge(t,e);return U(i,n),n}}var Pn={".":"&dot;","/":"&slash;",":":"&colon;"};function Fi(i){return i.replace(/[/]/g,Pn["/"]).replace(/[:]/g,Pn[":"]).replace(/[.]/g,Pn["."])}function ji(i){return i.replace(/&slash;/g,"/").replace(/&colon;/g,":").replace(/&dot;/g,".")}function Z(i,t,e){let n=Fi(i)+_r+Fi(t);return e&&(n+=Xe+e),n}function ge(i,t=Mr){let{collection:e,id:n}=le(i);return Z(e,n,t())}function le(i){let[t,e]=i.split(Xe),[n,r]=t.split("/"),s;return r.includes(".")?s=r.slice(0,r.indexOf(".")):s=r,{collection:ji(n),id:ji(s),subId:e}}function je(i,t){let e=ce(i);if(Array.isArray(i)){let n;for(let r=0;r<i.length;r++)n=i[r],z(n)&&!ne(n)&&(Ri(n,e,t),je(n,t))}else if(z(i)&&!ne(i))for(let n of Object.keys(i))z(i[n])&&!ne(i[n])&&(Ri(i[n],e,t),je(i[n],t))}function Tr(i){if(z(i))return i[De]||i[Ie]}function Ar(i){return z(i)&&(delete i[Ie],delete i[De]),i}function kr(i){let t=Tr(i);t&&U(i,t)}function Ge(i){if(kr(i),Ar(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ge(i[t]);else if(z(i))for(let t of Object.keys(i))Ge(i[t])}function Ot(i){if(Dt(i),Array.isArray(i))for(let t=0;t<i.length;t++)Ot(i[t]);else if(z(i))for(let t of Object.keys(i))Ot(i[t])}function Mr(){return Je().slice(0,8)}function we(i){return{"@@type":"ref",id:i}}function It(i,t=new Map){if(Array.isArray(i)){let e=ce(i),n=U([],e);for(let r=0;r<i.length;r++){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s)){n[r]=s;continue}else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else if(z(i)&&!ne(i)){let e=ce(i),n=U({},e);for(let r of Object.keys(i)){let s=i[r];if(z(s)){if(te(s))throw new Error("An attempt was made to normalize an already normalized object! This is an error in verdant itself.");if(se(s))n[r]=s;else{let a=ce(s);n[r]=we(a),It(s,t)}}else n[r]=s}t.set(e,n)}else ne(i);return t}function K(i){return i.split(".")[0].split(Xe)[0]}function kn(i,t){let e=K(i),n=ge(e,()=>"\uFFFF");return t?[`${e}.`,n]:[`${e}${Xe}`,n]}function Ct(i,t){return K(i)===K(t)}function Mn(i){return i.split(Xe)[0].includes(".")}function te(i){return i&&typeof i=="object"&&i["@@type"]==="ref"}function Bn(i){return z(i)&&!ne(i)}function Br(i,t){return i===t?!0:ne(i)&&ne(t)?Ei(i,t):!1}function et(i,t,e,n,r=[],s={}){let a=ce(i);function l(f,h,v){if(!Bn(h))Br(h,v)||r.push({oid:a,timestamp:e(),data:{op:"set",name:f,value:h}});else{let E=ae(v),b=ae(h);b&&!Ct(a,b)?(h=oe(h,!1),b=ge(a,n),U(h,b)):s.mergeUnknownObjects?!b&&E?(U(h,E),b=E):b=An(h,a,n):b=An(h,a,n),V(!!b,"Error: no value OID was resolved during diff. This is a bug in Verdant."),V(Ct(a,b),`Error: value OID ${b} is not related to parent OID ${a}. This is a bug in Verdant.`),v===void 0||b!==E?(xe(h,b,e,n,r),r.push({oid:a,timestamp:e(),data:{op:"set",name:f,value:we(b)}}),E!==void 0&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})):et(v,h,e,n,r,s)}}if(Array.isArray(i)&&Array.isArray(t)){for(let h=0;h<t.length;h++){let v=t[h],E=i[h];l(h,v,E)}let f=i.length-t.length;if(f>0){for(let h=t.length;h<i.length;h++){let v=i[h],E=ae(v);E&&r.push({oid:E,timestamp:e(),data:{op:"delete"}})}r.push({oid:a,timestamp:e(),data:{op:"list-delete",index:t.length,count:f}})}}else{if(Array.isArray(i)||Array.isArray(t))throw new Error("Cannot diff an array with an object");if(Bn(i)&&Bn(t)){let f=new Set(Object.keys(i));for(let[h,v]of Object.entries(t)){if(v===void 0&&s.defaultUndefined||(f.delete(h),Tn(h)))continue;let E=i[h];l(h,v,E)}if(!s.defaultUndefined)for(let h of f)Tn(h)||r.push({oid:a,timestamp:e(),data:{op:"remove",name:h}})}}return r}function xe(i,t,e,n,r=[]){U(i,t),je(i,n);let s=It(i);for(let a of s.keys()){let l=s.get(a);r.push({oid:a,timestamp:e(),data:{op:"initialize",value:Dt(l)}})}return r}function Vi(i){let t={};for(let e of i)e.oid in t?t[e.oid].push(e):t[e.oid]=[e];return t}function Rn(i){let t={};for(let e of i){let n=K(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Fn(i){let t={};for(let e of i){let n=K(e.oid);n in t?t[n].push(e):t[n]=[e]}return t}function Ce(i){return Array.isArray(i)?!0:(console.error(`Cannot apply list patch; expected array, received ${JSON.stringify(i)}. This suggests your data is changing from a list to an object over time. (OID: ${ae(i)})`),!1)}function Ee(i,t,e){if(i==null&&t.op!=="initialize")return i;let n=i,r,s;function a(l){e&&ne(l)&&e.push(l)}switch(t.op){case"set":a(n[t.name]),n[t.name]=t.value;break;case"remove":a(n[t.name]),delete n[t.name];break;case"list-push":Ce(i)&&i.push(t.value);break;case"list-delete":Ce(i)&&(a(i[t.index]),i.splice(t.index,t.count));break;case"list-move-by-index":Ce(i)&&(s=i.splice(t.from,1),i.splice(t.to,0,s[0]));break;case"list-remove":if(Ce(i))do{let l=t.value;t.only==="last"?te(l)?r=Mi(i,f=>f.id===l.id):r=i.lastIndexOf(l):te(l)?r=i.findIndex(f=>f.id===l.id):r=i.indexOf(l),r!==-1&&(a(i[r]),i.splice(r,1))}while(!t.only&&r!==-1);break;case"list-add":Ce(i)&&(i.some(f=>te(f)&&te(t.value)?f.id===t.value.id:f===t.value)||i.push(t.value));break;case"list-move-by-ref":Ce(i)&&(r=i.indexOf(t.value),s=i.splice(r,1),i.splice(t.index,0,s[0]));break;case"list-insert":if(Ce(i)){if(!t.value&&!t.values)throw new Error(`Cannot apply list insert patch; expected value or values, received ${JSON.stringify(t)}`);t.value?i.splice(t.index,0,t.value):i.splice(t.index,0,...t.values)}break;case"delete":Array.isArray(i)?i.forEach(a):z(i)&&Object.values(i||{}).forEach(a);return;case"initialize":return oe(t.value);default:throw new Error(`Unsupported patch operation: ${t.op}`)}return i}function Et(i,t,e=[]){if(Array.isArray(i))for(let n=0;n<i.length;n++){let r=i[n];i[n]=Li(r,t,e),z(i[n])&&Et(i[n],t,e)}else if(!se(i)){if(z(i)){V(ae(i),`Object ${JSON.stringify(i)} must have an oid`);for(let n of Object.keys(i))i[n]=Li(i[n],t,e),z(i[n])&&Et(i[n],t,e)}}return e}function Li(i,t,e){if(te(i)){e.push(i.id);let n=t.get(i.id);return V(!!n,`No value was found in object map for ${i.id}`),U(n,i.id)}else return i}function Rr(i){return i.type==="any"?!0:i.type==="map"?!1:i.nullable}function Ln(i){return i?i.type==="map"||i.type==="array"?!0:i.type==="file"?!1:i.type==="object"?!0:i.default!==void 0:!1}function Pt(i){return i.type==="map"||i.type==="object"||i.type==="array"||i.type==="file"||i.type==="any"?!1:i.indexed}function ve(i,t){for(let[e,n]of Object.entries(i.fields)){let r=Ni(n);(r!==void 0&&t[e]===void 0||!Rr(n)&&t[e]===null)&&(t[e]=r),t[e]&&Pe(t[e],n)}return t}function Pe(i,t){if(i==null)return i;if(t.type==="object")for(let[e,n]of Object.entries(t.properties)){if(i[e]===void 0){let r=Ni(n);r!==void 0&&(i[e]=r)}Pe(i[e],n)}else if(t.type==="array")for(let e of i)Pe(e,t.items);else if(t.type==="map")for(let[e,n]of Object.entries(i))e===De||e===Ie||Pe(n,t.values)}function Ni(i){if(i.type==="string"||i.type==="number"||i.type==="boolean"||i.type==="any"){if(i.default&&typeof i.default=="function")return i.default();if(i.default!==void 0)return JSON.parse(JSON.stringify(i.default))}if(i.type==="array")return[];if(i.type==="map")return{};if(i.type!=="any"&&i.nullable)return null}function Vn(i,t){for(let[e,n]of Object.entries(t))e===De||e===Ie||(i.fields[e]?jn(n,i.fields[e]):delete t[e]);return t}function jn(i,t){if(z(i)&&t.type==="object")for(let[e,n]of Object.entries(i))t.properties[e]?jn(n,t.properties[e]):delete i[e];else if(Array.isArray(i)&&t.type==="array")for(let e of i)jn(e,t.items)}function Nn(i){return i.equals!==void 0}function Un(i){return i.gte!==void 0||i.lte!==void 0||i.gt!==void 0||i.lt!==void 0}function Fr(i){return!!i.match}function Kn(i){return i.startsWith!==void 0}function Ui(i){return!Un(i)&&!Nn(i)&&!Fr(i)&&!Kn(i)&&i.order}function Ki({synthetics:i,indexes:t,...e}){let n={...i,...t};for(let[r,s]of Object.entries(e.fields))Pt(s)&&(n[r]={field:r});return{...e,indexes:n}}function zi(i){return i}var _t="\uFFFFFE",jr="\0",Lr="\uFFFFFF";function de(...i){let t=Vr(i);return t.length===1?t[0]:t}function _e(...i){return i.join(_t)+`${Lr}`}function Te(...i){return i.join(_t)+`${_t}${jr}`}function Vr(i){let t=[[]];for(let e of i)if(Array.isArray(e)){let n=[];for(let r of t)for(let s of e)n.push(r.concat(s));t=n}else for(let n of t)n.push(`${e}`);return Array.from(new Set(t.map(e=>e.join(_t))))}function Nr(i){return!!i.field}function Ur(i,t){let e={};for(let[n,r]of Object.entries(i.indexes||{})){let s=r;Nr(s)?e[n]=me(t[s.field]):e[n]=me(s.compute(t))}return e}function Kr(i,t){return Object.entries(i.compounds||{}).reduce((e,[n,r])=>(e[n]=de(...r.of.map(s=>t[s])),e),{})}function zr(i,t){return Object.entries(i.fields).reduce((e,[n,r])=>(Pt(r)&&(e[n]=me(t[n])),e),{})}function Tt(i,t){return{[i.primaryKey]:t[i.primaryKey],...zr(i,t),...Ur(i,t),...Kr(i,t),"@@@snapshot":t}}var $r="null";function me(i){if(i===null)return $r;if(typeof i=="string"||typeof i=="number")return i;if(typeof i=="boolean"||i===null)return`${i}`;if(i===void 0)return"undefined";if(Array.isArray(i))return i.map(me);throw new Error(`Unsupported index value: ${i}`)}var $i={version:0,collections:{}};function kt(i,t,e){let n=typeof t=="function",r=n?$i:i,s=n?i:t,a=n?t:e,l=Object.keys(s.collections).filter(O=>r.collections[O]&&Ye(r.collections[O])!==Ye(s.collections[O])),f=Object.keys(r.collections).filter(O=>!s.collections[O]),h=Object.keys(s.collections).filter(O=>!r.collections[O]),v=new Set;for(let O of l){let C=r.collections[O].fields,x=s.collections[O].fields;Object.keys(x).some(S=>!C[S]?.default&&x[S]?.default)&&v.add(O),Object.keys(C).some(S=>!x[S])&&v.add(O)}let E={},b={};for(let O of[...l,...h]){let C=At(r.collections[O]),x=At(s.collections[O]),S=x.filter(y=>!C.find(I=>I.name===y.name)),A=C.filter(y=>!x.find(I=>I.name===y.name));S.length>0&&(E[O]=S,l.includes(O)&&v.add(O)),A.length>0&&(b[O]=A,l.includes(O)&&v.add(O))}let P=(O,C)=>ve(s.collections[O],C),g=O=>C=>{let x=s.collections[O];return ve(x,Vn(x,C))};return{version:s.version,migrate:async O=>{let C=[];if(await a({migrate:async(x,S)=>{let A=g(x),y=async I=>{let d=await S(I);return U(d,ce(I)),A(d)};await O.migrate(x,y),C.push(x),v.delete(x)},identity:x=>x,withDefaults:P,info:{changedCollections:l,addedCollections:h,removedCollections:f},queries:O.queries,mutations:O.mutations}),s.version>1){O.log("debug","auto-migrating collections with new defaults",v);for(let S of v)await O.migrate(S,g(S)),C.push(S);let x=l.filter(S=>!C.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:f,addedIndexes:E,removedIndexes:b,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:h,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function At(i){return i?[...Object.keys(i.indexes||{}).map(t=>({name:t,multiEntry:["array","string[]","number[]","boolean[]"].includes(i.indexes[t].type),synthetic:!0,compound:!1})),...Object.keys(i.compounds||{}).map(t=>({name:t,multiEntry:i.compounds[t].of.some(e=>(i.fields[e]||i.indexes[e]).type==="array"),synthetic:!1,compound:!0}))]:[]}function zn(i,t){return kt(t?i:{version:0,collections:{}},t||i,async({migrate:n,info:r})=>{if((t||i).version!==1)for(let s of r.changedCollections)await n(s,a=>a)})}function $n(i,t,e){let n=typeof t=="function"||t===void 0,r=n?$i:i,s=n?i:t,a=n?t:e;V(r,"Invalid arguments to createMigration"),V(s,"Invalid arguments to createMigration");let{changedCollections:l,addedCollections:f,removedCollections:h,addedIndexes:v,removedIndexes:E,autoMigratedCollections:b,autoMigration:P}=qr(r,s);return{version:s.version,migrate:async g=>{let O=[];if(await a?.({migrate:async(x,S)=>{let A=P(x),y=async I=>{let d=await S(I);return U(d,ce(I)),A(d)};await g.migrate(x,y),O.push(x),b.delete(x)},info:{changedCollections:l,addedCollections:f,removedCollections:h},queries:g.queries,mutations:g.mutations}),s.version>1){g.log("debug","auto-migrating collections with new defaults",b);for(let S of b)await g.migrate(S,P(S)),O.push(S);let x=l.filter(S=>!O.includes(S));x.length>0&&console.error(`Unmigrated changed collections from version ${r.version} to version ${s.version}:`,x)}},removedCollections:h,addedIndexes:v,removedIndexes:E,allCollections:Object.keys(s.collections),changedCollections:l,addedCollections:f,oldCollections:Object.keys(r.collections),oldSchema:r,newSchema:s}}function qr(i,t){let e=Object.keys(t.collections).filter(v=>i.collections[v]&&Ye(i.collections[v])!==Ye(t.collections[v])),n=Object.keys(i.collections).filter(v=>!t.collections[v]),r=Object.keys(t.collections).filter(v=>!i.collections[v]),s=new Set;for(let v of e){let E=i.collections[v].fields,b=t.collections[v].fields;Object.keys(b).some(P=>!Ln(E[P])&&Ln(b[P]))&&s.add(v),Object.keys(E).some(P=>!b[P])&&s.add(v)}let a={},l={};for(let v of[...e,...r]){let E=At(i.collections[v]),b=At(t.collections[v]),P=b.filter(O=>!E.find(C=>C.name===O.name)),g=E.filter(O=>!b.find(C=>C.name===O.name));P.length>0&&(a[v]=P,e.includes(v)&&s.add(v)),g.length>0&&(l[v]=g,e.includes(v)&&s.add(v))}return{changedCollections:e,addedCollections:r,removedCollections:n,addedIndexes:a,removedIndexes:l,autoMigratedCollections:s,withDefaults:(v,E)=>ve(t.collections[v],E),autoMigration:v=>E=>{let b=t.collections[v];return ve(b,Vn(b,E))}}}var Mt=class{constructor(t,e){this.getNow=t;this.createSubId=e;this.createDiff=(t,e,n={})=>et(t,e,this.getNow,this.createSubId,[],n);this.createInitialize=(t,e)=>xe(t,e,this.getNow,this.createSubId);this.createSet=(t,e,n)=>{if(!z(n)||ne(n))return[{oid:t,timestamp:this.getNow(),data:{op:"set",name:e,value:n}}];{let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"set",value:we(r),name:e}}]}};this.createRemove=(t,e)=>[{oid:t,timestamp:this.getNow(),data:{op:"remove",name:e}}];this.createListPush=(t,e)=>{if(z(e)){let n=ge(t,this.createSubId);return[...xe(e,n,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:we(n)}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-push",value:e}}]};this.createListAdd=(t,e)=>z(e)?[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:we(e)}}]:[{oid:t,timestamp:this.getNow(),data:{op:"list-add",value:e}}];this.createListInsert=(t,e,n)=>{if(z(n)){let r=ge(t,this.createSubId);return[...xe(n,r,this.getNow),{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:we(r),index:e}}]}else return[{oid:t,timestamp:this.getNow(),data:{op:"list-insert",value:n,index:e}}]};this.createListRemove=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-remove",value:e,only:n}}];this.createListDelete=(t,e,n=1)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-delete",index:e,count:n}}];this.createListMoveByRef=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-ref",value:e,index:n}}];this.createListMoveByIndex=(t,e,n)=>[{oid:t,timestamp:this.getNow(),data:{op:"list-move-by-index",from:e,to:n}}];this.createDelete=t=>[{oid:t,timestamp:this.getNow(),data:{op:"delete"}}];this.createDeleteAll=t=>t.map(e=>({oid:e,timestamp:this.getNow(),data:{op:"delete"}}))}};var N=class{constructor(t){this._onAllUnsubscribed=t;this.subscribers={};this.counts={};this._disabled=!1;this.subscriberCount=t=>this.counts[t]??0;this.totalSubscriberCount=()=>Object.values(this.counts).reduce((t,e)=>t+e,0);this.subscribe=(t,e)=>{let n=xt(),r=this.subscribers[t];return r||(r=this.subscribers[t]={}),r[n]=e,this.counts[t]=(this.counts[t]||0)+1,()=>{this.subscribers[t]&&(delete this.subscribers[t][n],this.counts[t]--,this.counts[t]===0&&(delete this.subscribers[t],delete this.counts[t],this._onAllUnsubscribed&&this._onAllUnsubscribed(t)))}};this.emit=(t,...e)=>{this._disabled||this.subscribers[t]&&Object.values(this.subscribers[t]).forEach(n=>n(...e))};this.dispose=()=>{let t=Object.keys(this.subscribers);this.subscribers={},this.counts={},t.forEach(e=>{this._onAllUnsubscribed&&this._onAllUnsubscribed(e)})};this.disable=()=>{this._disabled=!0}}get disabled(){return this._disabled}};function qi(i,t,e,n){if(t===void 0)return[{oid:i,timestamp:n(),data:{op:"delete"}}];let r=oe(t),s=[];for(let a of e){let l=Wr(i,r,a,n);s.unshift(...l),Ee(r,a.data)}return s}function Wr(i,t,e,n){let r=e.data;switch(r.op){case"set":case"remove":return[{oid:i,timestamp:n(),data:{op:"set",name:r.name,value:t[r.name]}}];case"list-insert":return[{oid:i,timestamp:n(),data:{op:"list-delete",index:r.index,count:1}}];case"list-delete":return[{oid:i,timestamp:n(),data:{op:"list-insert",index:r.index,values:t.slice(r.index,r.count)}}];case"list-move-by-ref":return[{oid:i,timestamp:n(),data:{op:"list-move-by-ref",value:r.value,index:t.indexOf(r.value)}}];case"list-move-by-index":return[{oid:i,timestamp:n(),data:{op:"list-move-by-index",from:r.to,to:r.from}}];case"delete":return[{oid:i,timestamp:n(),data:{op:"initialize",value:t}}];case"list-push":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"list-remove":if(r.only==="last"){let s=t.lastIndexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else if(r.only==="first"){let s=t.indexOf(r.value);return[{oid:i,timestamp:n(),data:{op:"list-insert",index:s,values:[r.value]}}]}else{let s=[],a=t.indexOf(r.value);for(;a!==-1;)s.push(a),a=t.indexOf(r.value,a+1);return s.map(l=>({oid:i,timestamp:n(),data:{op:"list-insert",index:l,value:r.value}}))}case"list-add":return[{oid:i,timestamp:n(),data:{op:"list-remove",value:r.value,only:"last"}}];case"initialize":return[{oid:i,timestamp:n(),data:{op:"delete"}}];default:throw new Error(`Cannot undo operation type: ${r.op}`)}}var Le=class{constructor(t){this.flusher=t;this.batches=new Map;this.flush=t=>{let e=this.batches.get(t);if(e)return e.flush()};this.discard=t=>{let e=this.batches.get(t);e&&(e.discard(),this.batches.delete(t))};this.flushAll=()=>[...this.batches.values()].map(t=>t.flush())}add({key:t,userData:e,items:n,max:r,timeout:s}){let a=this.batches.get(t);return a||(a=new qn({max:r||null,startedAt:Date.now(),userData:e,timeout:s||null,flusher:this.flusher,key:t}),this.batches.set(t,a)),a.update({items:n,max:r,timeout:s,userData:e}),a}},qn=class{constructor({max:t,startedAt:e,timeout:n,userData:r,flusher:s,key:a}){this.items=[];this.update=({items:t,max:e,timeout:n,userData:r})=>{this.items.push(...t),e!==void 0&&(this.max=e),n!==void 0&&(this.timeout=n),r&&(this.userData=r);let s=this.items.length!==0&&this.timeout!==null&&!this.flushTimeout;this.max!==null&&this.items.length>=this.max?this.flush():s&&this.timeout!==null&&(this.flushTimeout=setTimeout(this.flush,this.timeout))};this.flush=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0;let t=this.items;return this.items=[],this.flusher(t,this.key,this.userData)};this.discard=()=>{this.flushTimeout&&clearTimeout(this.flushTimeout),this.flushTimeout=void 0,this.items=[]};this.max=t,this.startedAt=e,this.timeout=n,this.userData=r,this.flusher=s,this.key=a}};function W(i){return new Promise((t,e)=>{i.onsuccess=()=>{t(i.result)},i.onerror=()=>{e(i.error)}})}function tt(i,t){return new Promise((e,n)=>{let r=i.transaction([t],"readonly"),a=r.objectStore(t).openCursor(),l=0,f=0;a.onsuccess=function(h){let v=a.result;v&&(l++,f=f+ki(v.value),v.continue())},a.onerror=function(h){n(h)},r.oncomplete=function(h){e({count:l,size:f})},r.onabort=function(h){n(h)},r.onerror=function(h){n(h)}})}function Wi(i,t){let e=i.transaction(t,"readonly"),n=t.map(r=>{let s=e.objectStore(r);return W(s.getAll())});return Promise.all(n)}async function Ae(i){i.close(),await new Promise((t,e)=>{t()})}async function Bt(i,t=window.indexedDB){let e=t.deleteDatabase([i,"meta"].join("_")),n=t.deleteDatabase([i,"collections"].join("_"));await Promise.all([new Promise((r,s)=>{e.onsuccess=r,e.onerror=s}),new Promise((r,s)=>{n.onsuccess=r,n.onerror=s})]),window.location.reload()}function Hi(i,t=window.indexedDB){return W(t.deleteDatabase(i))}async function Qi(i=window.indexedDB){return i.databases()}var pe=class{constructor(t){this.db=t;this.createTransaction=(t,e)=>this.db.transaction(t,e);this.run=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return W(l)};this.runAll=async(t,e,n="readonly",r)=>{let a=(r||this.db.transaction(t,n)).objectStore(t),l=e(a);return Promise.all(l.map(W))};this.iterate=async(t,e,n,r="readonly",s)=>{let l=(s||this.db.transaction(t,r)).objectStore(t),f=e(l);return Array.isArray(f)?Promise.all(f.map(h=>new Promise((v,E)=>{h.onsuccess=()=>{let b=h.result;b?(n(b.value,l),b.continue()):v()},h.onerror=E}))).then(()=>{}):new Promise((h,v)=>{f.onsuccess=()=>{let E=f.result;E?(n(E.value,l),E.continue()):h()},f.onerror=v})};this.clear=t=>this.run(t,e=>e.clear(),"readwrite")}};var Rt=class extends pe{constructor(){super(...arguments);this.getAckInfo=async()=>{let e=await this.run("info",n=>n.get("ack"));return e||{globalAckTimestamp:null,type:"ack"}};this.setGlobalAck=async e=>{await this.run("info",n=>n.put({type:"ack",globalAckTimestamp:e}),"readwrite")}}};var Ft=class extends pe{constructor(e){super(e);this.getAllForDocument=async(e,{mode:n="readonly",transaction:r}={})=>{let s=[];return await this.iterateOverAllForDocument(e,a=>{s.push(a)},{mode:n,transaction:r}),s};this.iterateOverAllForDocument=async(e,n,{mode:r="readonly",transaction:s}={})=>this.iterate("baselines",a=>{let l=K(e),f=Mn(e),[h,v]=kn(e,f);return[a.openCursor(IDBKeyRange.only(l)),a.openCursor(IDBKeyRange.bound(h,v,!1,!1))]},n,r,s);this.getAllForMultipleDocuments=async(e,{mode:n="readonly"}={})=>(await this.runAll("baselines",s=>e.flatMap(a=>{let l=K(a),f=Mn(a),[h,v]=kn(a,f);return[s.get(l),s.getAll(IDBKeyRange.bound(h,v,!1,!1))]}),n)).flat();this.getAllSince=async(e,{mode:n="readonly"}={})=>this.run("baselines",r=>{let s=e?IDBKeyRange.lowerBound(e,!0):void 0;return r.index("timestamp").getAll(s)},n);this.get=async(e,{transaction:n,mode:r="readonly"}={})=>this.run("baselines",s=>s.get(e),r,n);this.set=async(e,{transaction:n}={})=>{await this.run("baselines",r=>r.put(e),"readwrite",n)};this.setAll=async(e,{transaction:n}={})=>{await this.runAll("baselines",r=>e.map(s=>r.put(s)),"readwrite",n)};this.reset=()=>this.clear("baselines");this.delete=async(e,{transaction:n})=>{await this.run("baselines",r=>r.delete(e),"readwrite",n)}}};var Ji=ut(ht(),1);var jt=class extends pe{constructor(){super(...arguments);this.get=async({transaction:e}={})=>{if(this.cached)return this.cached;let n=await this.run("info",r=>r.get("localReplicaInfo"),void 0,e);if(!n){let s={type:"localReplicaInfo",id:(0,Ji.default)(),ackedLogicalTime:null,lastSyncedLogicalTime:null};return await this.run("info",a=>a.put(s),"readwrite"),this.cached=s,s}return this.cached=n,n};this.update=async(e,{transaction:n}={})=>{let r=await this.get({transaction:n});Object.assign(r,e),await this.run("info",s=>s.put(r),"readwrite"),this.cached=r};this.reset=async()=>{let e=await this.get();e.ackedLogicalTime=null,e.lastSyncedLogicalTime=null,await this.run("info",n=>n.put(e),"readwrite")}}};var Lt=class{constructor(t){this.meta=t;this.createOperation=async t=>{let e=await this.meta.localReplica.get();return{type:"op",timestamp:this.meta.now,replicaId:e.id,operations:t.operations.map(n=>({data:n.data,oid:n.oid,timestamp:n.timestamp}))}};this.createMigrationOperation=async({targetVersion:t,...e})=>{let n=await this.meta.localReplica.get();return{type:"op",operations:e.operations.map(r=>({...r,timestamp:this.meta.time.zero(t)})),timestamp:this.meta.time.zero(t),replicaId:n.id}};this.createSyncStep1=async t=>{let e=await this.meta.localReplica.get(),n=t===null?null:e.lastSyncedLogicalTime,r=[],s=new Set;n?await this.meta.operations.iterateOverAllLocalOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(K(l.oid))},{after:n,mode:"readwrite"}):await this.meta.operations.iterateOverAllOperations(l=>{r.push({data:l.data,oid:l.oid,timestamp:l.timestamp}),s.add(K(l.oid))},{mode:"readwrite"});let a=[];return n||(a=await this.meta.baselines.getAllSince("")),{type:"sync",schemaVersion:this.meta.schema.currentVersion,timestamp:this.meta.now,replicaId:e.id,resyncAll:!e.lastSyncedLogicalTime,operations:r,baselines:a,since:n}};this.createPresenceUpdate=async t=>{let e=await this.meta.localReplica.get();return{type:"presence-update",presence:t,replicaId:e.id}};this.createHeartbeat=async()=>{let t=await this.meta.localReplica.get();return{type:"heartbeat",timestamp:this.meta.now,replicaId:t.id}};this.createAck=async t=>{let e=await this.meta.localReplica.get();return{type:"ack",timestamp:this.meta.now,replicaId:e.id,nonce:t}}}};var Vt=class extends pe{constructor(){super(...arguments);this.iterateOverAllOperationsForDocument=async(e,n,{to:r,from:s,after:a,mode:l="readonly",transaction:f}={})=>{let v=(f||this.db.transaction("operations",l)).objectStore("operations"),E=v.index("d_t"),b=s||a,P=b?de(e,b):Te(e),g=r?de(e,r):_e(e),O=IDBKeyRange.bound(P,g,!!a,!1),C=E.openCursor(O,"next");return new Promise((x,S)=>{let A;C.onsuccess=y=>{let I=C.result;if(I){let d=I.value;V(d.oid.startsWith(e)),V(A===void 0||A<=d.timestamp,`expected ${A} <= ${d.timestamp}`),n(d,v),A=d.timestamp,I.continue()}else x()},C.onerror=y=>{S(y)}})};this.iterateOverAllOperationsForEntity=async(e,n,{after:r,to:s,mode:a,transaction:l})=>{let h=(l||this.db.transaction("operations",a)).objectStore("operations"),v=r?de(e,r):Te(e),E=s?de(e,s):_e(e),b=IDBKeyRange.bound(v,E,!!r,!1),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(A.oid.startsWith(e)),V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),n(A,h),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllLocalOperations=async(e,{before:n,after:r,mode:s="readonly",transaction:a})=>{let f=(a||this.db.transaction("operations",s)).objectStore("operations"),h=f.index("l_t"),v=r?de(!0,r):Te(!0),E=n?de(!0,n):_e(!0),b=IDBKeyRange.bound(v,E,!!r,!0),P=h.openCursor(b,"next");return new Promise((g,O)=>{let C;P.onsuccess=x=>{let S=P.result;if(S){let A=S.value;V(C===void 0||C<=A.timestamp,`expected ${C} <= ${A.timestamp}`),e(A,f),C=A.timestamp,S.continue()}else g()},P.onerror=x=>{O(x)}})};this.iterateOverAllOperations=async(e,{before:n,transaction:r,mode:s,from:a})=>{await this.iterate("operations",l=>{let f=a?Te(a):void 0,h=n?_e(n):void 0,v=f&&h?IDBKeyRange.bound(f,h,!1,!0):f?IDBKeyRange.lowerBound(f,!1):h?IDBKeyRange.upperBound(h,!0):void 0;return l.index("timestamp").openCursor(v,"next")},e,s,r)};this.addOperations=async(e,{transaction:n}={})=>this.insert(e.map(this.addCompoundIndexes),{transaction:n});this.addCompoundIndexes=e=>({...e,oid_timestamp:de(e.oid,e.timestamp),l_t:de(e.isLocal,e.timestamp),d_t:de(K(e.oid),e.timestamp)});this.insert=async(e,{transaction:n})=>{let r=new Set;return await this.runAll("operations",s=>e.map(a=>(r.add(K(a.oid)),s.put(a))),"readwrite",n),Array.from(r)};this.reset=()=>this.clear("operations")}};var Nt=class{constructor(t,e){this.db=t;this.currentVersion=e;this.cached=null;this.get=async()=>{if(this.cached)return this.cached;let r=this.db.transaction("info","readonly").objectStore("info").get("schema"),s=await W(r);return s?(this.cached=JSON.parse(s.schema),this.cached):null};this.set=async t=>{let s=this.db.transaction("info","readwrite").objectStore("info").put({type:"schema",schema:JSON.stringify(t)});this.cached=t,await W(s)}}};var nt=class extends N{constructor({disableRebasing:e,context:n}){super();this.time=new yt;this.disableRebasing=!1;this._closing=!1;this.setContext=e=>{this.context=e};this.close=()=>{this._closing=!0};this.createTransaction=e=>this.db.transaction(e,"readwrite");this.getAllDocumentRelatedOids=async e=>{let n=new Set,r=K(e);V(r===e,"Must be root document OID"),n.add(r);let s=this.db.transaction(["baselines","operations"],"readwrite");return await Promise.all([this.baselines.iterateOverAllForDocument(r,a=>{n.add(a.oid)},{transaction:s}),this.operations.iterateOverAllOperationsForDocument(r,a=>{n.add(a.oid)},{transaction:s})]),Array.from(n)};this.getDocumentSnapshot=async(e,n={})=>{let r=K(e);V(r===e,"Must be root document OID");let s=this.db.transaction(["baselines","operations"],"readwrite"),a=await this.baselines.getAllForDocument(r,{transaction:s}),l=new Map;for(let h of a)h.snapshot&&U(h.snapshot,h.oid),l.set(h.oid,h.snapshot);await this.operations.iterateOverAllOperationsForDocument(r,h=>{let v=l.get(h.oid)||void 0,E=Ee(v,h.data);E&&U(E,h.oid),l.set(h.oid,E)},{transaction:s,to:n.to||this.now});let f=l.get(r);return f&&Et(f,l),f};this.ack=async e=>{let n=await this.localReplica.get();e>this.now||(this.emit("message",{type:"ack",replicaId:n.id,timestamp:e}),!this._closing&&(!n.ackedLogicalTime||e>n.ackedLogicalTime)&&this.localReplica.update({ackedLogicalTime:e}))};this.insertLocalOperation=async e=>{if(e.length===0)return;this.log(`Inserting ${e.length} local operations`);for(let r of e)r.isLocal=!0;await this.operations.addOperations(e);let n=await this.messageCreator.createOperation({operations:e});this.emit("message",n),this.tryAutonomousRebase()};this.insertRemoteOperations=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote operations`);let n=await this.operations.addOperations(e.map(r=>({...r,isLocal:!1})));return this.ack(e[e.length-1].timestamp),n};this.insertRemoteBaselines=async e=>{if(e.length===0)return[];this.log(`Inserting ${e.length} remote baselines`),await this.baselines.setAll(e);let n=new Set;return e.forEach(r=>{n.add(K(r.oid))}),Array.from(n)};this.updateLastSynced=async e=>{if(!this._closing)return this.localReplica.update({lastSyncedLogicalTime:e})};this.lastSyncedTimestamp=async()=>(await this.localReplica.get()).lastSyncedLogicalTime;this.tryAutonomousRebase=async()=>{this.disableRebasing||(await this.localReplica.get()).lastSyncedLogicalTime||await this.runRebase(this.now)};this.runRebase=async e=>{if(this._closing)return;let n,r=new Set,s=this.db.transaction(["baselines","operations"],"readwrite"),a=0;if(await this.operations.iterateOverAllOperations(f=>{r.add(f.oid),n=f.timestamp,a++},{before:e,transaction:s}),!r.size){this.log("Cannot rebase, no operations prior to",e);return}if(this._closing)return;let l=[];for(let f of r)l.push(await this.rebase(f,n||e,s));this.emit("rebase",l)};this.rebase=async(e,n,r)=>{let s=(await this.localReplica.get()).id;this.log("[",s,"]","Rebasing",e,"up to",n);let a=r||this.db.transaction(["operations","baselines"],"readwrite"),l=await this.baselines.get(e,{transaction:a}),f=l?.snapshot||void 0,h=0,v=[];await this.operations.iterateOverAllOperationsForEntity(e,(b,P)=>{(!l||b.timestamp>l.timestamp)&&(f=Ee(f,b.data,v)),h++,P.delete(b.oid_timestamp)},{to:n,transaction:a}),f&&U(f,e);let E={oid:e,snapshot:f,timestamp:n};if(E.snapshot?await this.baselines.set(E,{transaction:a}):await this.baselines.delete(e,{transaction:a}),this.log("successfully rebased",e,"up to",n,":",f,"and deleted",h,"operations"),v.length){let b=v.filter(se);b.length&&this.emit("filesDeleted",b)}return E};this.reset=async()=>{await this.operations.reset(),await this.baselines.reset(),await this.localReplica.reset()};this.updateSchema=async(e,n)=>{let r=await this.schema.get();if(r&&n===r.version&&r.version===e.version&&JSON.stringify(r)!==JSON.stringify(e))throw console.error(`Schema mismatch for version ${e.version}
7
7
  ${JSON.stringify(r)}
8
- ${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Ki(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await W(r.objectStore("baselines").clear()),await W(r.objectStore("operations").clear()),await W(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await tt(e,"operations"),r=await tt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Lt(n.metaDb,n.schema.version),this.operations=new jt(this.db),this.baselines=new Ft(this.db),this.localReplica=new Rt(this.db),this.ackInfo=new kt(this.db),this.messageCreator=new Mt(this),this.patchCreator=new At(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var zr=[$r,qr,Wr,Hr];function Vt({indexedDB:i=window.indexedDB,namespace:t,log:e}){return new Promise((n,r)=>{let s=i.open(`${t}_meta`,4),a=!1;s.onupgradeneeded=async d=>{let h=s.result,m=s.transaction,C=zr.slice(d.oldVersion);for(let P of C)await P(h,m);d.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{n({db:s.result,wasInitialized:a})}})}async function Wi({wipNamespace:i,namespace:t,indexedDB:e,log:n}){let r=await Vt({namespace:i,indexedDB:e,log:n});if(!r.wasInitialized)return r;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await Vt({namespace:t,indexedDB:e,log:n}),a=s.transaction(["baselines","operations","info"],"readonly"),[d,h,m]=await Promise.all([W(a.objectStore("baselines").getAll()),W(a.objectStore("operations").getAll()),W(a.objectStore("info").getAll())]),C=r.db.transaction(["baselines","operations","info"],"readwrite"),P=C.objectStore("baselines"),v=C.objectStore("operations"),T=C.objectStore("info");for(let b of d)P.put(b);for(let b of h)v.put(b);for(let b of m)T.put(b);return await new Promise((b,I)=>{C.oncomplete=()=>{b()},C.onerror=D=>{I(D)},C.onabort=D=>{I(D)}}),await Ae(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",d.length,"baselines,",h.length,"operations"),r}async function $r(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function qr(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let{isLocal_timestamp:d,documentOid_timestamp:h,...m}=a.value;a.update({...m,l_t:d,d_t:h}),a.continue()}else n()},s.onerror=a=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Wr(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Hr(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var Qr=i=>IDBKeyRange.only(ve(i.equals)),Jr=i=>{},Yr=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(ve(t)):t?e?IDBKeyRange.bound(ve(t),ve(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(ve(t),!!i.gt):IDBKeyRange.upperBound(ve(e),!!i.lt)},Gr=(i,t,e)=>{let n=i.collections[t].compounds[e.where];V(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((h,m)=>n.of.indexOf(h)-n.of.indexOf(m));for(let h of r)if(n.of.indexOf(h)!==r.indexOf(h))throw new Error(`Compound index ${e.where} does not have ${h} at the start of its order`);let s=r.map(h=>e.match[h]);if(r.length===n.of.length)return IDBKeyRange.only(ce(...s));let a=Te(...s),d=Pe(...s);return IDBKeyRange.bound(a,d)};function Xr(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function Ut(i,t,e){if(e)return Mn(e)?Yr(e):Rn(e)?Qr(e):Ri(e)?Jr(e):jn(e)?Xr(e):Gr(i,t,e)}function Nn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function Nt({collection:i,index:t,context:e}){let n=Nn(e.documentDb,i),r=t?n.index(t.where):n,s=Ut(e.schema,i,t),a=t?.order==="desc"?"prev":"next",d=r.openCursor(s,a);return await new Promise((m,C)=>{d.onsuccess=()=>{let P=d.result;m(P?Z(i,P.primaryKey.toString()):null)},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",d.error),m(null)):C(d.error)}})}async function Kt({collection:i,index:t,context:e}){let n=Nn(e.documentDb,i),r=t?n.index(t.where):n,s=Ut(e.schema,i,t),a=t?.order==="desc"?"prev":"next",d=r.openCursor(s,a);return await new Promise((m,C)=>{let P=new Set;d.onsuccess=()=>{let v=d.result;v?(P.add(Z(i,v.primaryKey.toString())),v.continue()):m(Array.from(P))},d.onerror=()=>{d.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",d.error),m([])):C(d.error)}})}async function it({collection:i,index:t,context:e,limit:n,offset:r}){let s=Nn(e.documentDb,i),a=t?s.index(t.where):s,d=Ut(e.schema,i,t),h=t?.order==="desc"?"prev":"next",m=a.openCursor(d,h),C=!r,P=!1,v=0;return{result:await new Promise((b,I)=>{let D=new Set;m.onsuccess=()=>{v++;let O=m.result;O?r&&!C?(O.advance(r),C=!0):(n&&D.size<n&&D.add(Z(i,O.primaryKey.toString())),n&&v>n?(P=!0,b(Array.from(D))):O.continue()):b(Array.from(D))},m.onerror=()=>{m.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",m.error),b([])):I(m.error)}}),hasNextPage:P}}async function Kn(i,t,e,n){function r(d,h){let m,C,P=i.open([t,"collections"].join("_"),e);P.onupgradeneeded=async v=>{m=v.oldVersion;let T=P.transaction;C=P.result,T.abort()},P.onsuccess=v=>{d([P.result.version,P.result])},P.onblocked=v=>{n?.("Database blocked, waiting...")},P.onerror=v=>{d([m,C])}}let[s,a]=await new Promise(r);return await zt(a),s}async function zt(i){i.close(),await new Promise(t=>t())}async function Hi(i,t,e,n,r){function s(a,d){let h=i.open([t,"collections"].join("_"),e),m=!1;h.onupgradeneeded=C=>{let P=h.transaction;n(P,h.result,C),m=!0},h.onsuccess=C=>{h.result.close(),m?a():d(new Error("Database was not upgraded when a version change was expected"))},h.onerror=C=>{d(h.error||new Error("Unknown error"))},h.onblocked=C=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Qi(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function Be(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((s,a)=>{let d=i.open([t,"collections"].join("_"),e);d.onupgradeneeded=async h=>{d.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",d.result.version),a(d.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${d.result.version}`))},d.onsuccess=h=>{s(d.result)},d.onblocked=h=>{a(new Error("Migration error: database blocked"))},d.onerror=h=>{a(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var Ue=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function $t({currentVersion:i,targetVersion:t,migrations:e}){let n=Ji({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ue(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Ji({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let s=Ji({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var $n=typeof window<"u"?window.indexedDB:void 0;async function rt({version:i,indexedDB:t=$n,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await Kn(t,r.namespace,i,r.log);r.log("debug","Current database version:",s,"target version:",i);let a=$t({currentVersion:s,targetVersion:i,migrations:e});return a.length>0&&(r.log("debug","Migrations to run:",a.map(d=>d.version)),await zn({context:r,toRun:a,meta:n,indexedDB:t})),Be(t,r.namespace,i,r.log)}async function Yi({version:i,indexedDB:t=$n,migrations:e,meta:n,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let a=await Kn(t,s,i,r.log);if(a===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let d=$t({currentVersion:a,targetVersion:i-1,migrations:e});if(d.length>0){await zn({context:r,toRun:d,meta:n,indexedDB:t,namespace:s});let m=await Be(t,r.namespace,i-1,r.log),C=await Be(t,s,i-1,r.log),P=new Array;for(let O=0;O<m.objectStoreNames.length;O++)P.push(m.objectStoreNames[O]);let v=m.transaction(P,"readonly"),T=P.map(O=>v.objectStore(O)),b=await Promise.all(T.map(O=>W(O.getAll()))),I=C.transaction(P,"readwrite"),D=P.map(O=>I.objectStore(O));for(let O=0;O<D.length;O++)await Promise.all(b[O].map(x=>W(D[O].put(x))))}let h=$t({currentVersion:i-1,targetVersion:i,migrations:e});h.length>0&&await zn({context:r,toRun:h,meta:n,indexedDB:t,namespace:s})}return Be(t,s,i,r.log)}async function zn({context:i,toRun:t,meta:e,indexedDB:n=$n,namespace:r=i.namespace}){await Qi(r,async()=>{for(let s of t){let a;if(s.oldSchema.version===0)a=ts({meta:e,migration:s,context:i}),await s.migrate(a);else{let m=await Be(n,r,s.oldSchema.version,i.log);a=es({meta:e,migration:s,context:{...i,documentDb:m}});try{await s.migrate(a),await Promise.all(a.awaitables)}catch(C){throw i.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,C),C}await zt(m)}i.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Hi(n,r,s.newSchema.version,(m,C)=>{for(let P of s.addedCollections)C.createObjectStore(P,{keyPath:s.newSchema.collections[P].primaryKey,autoIncrement:!1});for(let P of s.allCollections){let v=m.objectStore(P);for(let T of s.addedIndexes[P]||[])v.createIndex(T.name,T.name,{multiEntry:T.multiEntry});for(let T of s.removedIndexes[P]||[])v.deleteIndex(T.name)}for(let P of s.removedCollections)m.objectStore(P).clear()},i.log);let d=await ss({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),h=await Be(n,r,s.newSchema.version,i.log);for(let m of s.allCollections){let P=h.transaction(m,"readwrite").objectStore(m),T=(await ns(P)).map(x=>Z(m,`${x}`));T.push(...a.newOids.filter(x=>ae(x).collection===m),...d.filter(x=>ae(x).collection===m));let I=(await Promise.all(T.map(async x=>{try{let A=await e.getDocumentSnapshot(x);return[x,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",x,"this document will not be preserved",A),null}}))).filter(x=>!!x).map(([x,A])=>{if(!A)return[x,void 0];let y=Pt(s.newSchema.collections[m],A);return Le(y),[x,y]}),O=h.transaction(m,"readwrite").objectStore(m);await Promise.all(I.map(([x,A])=>{if(A)return rs(O,A);{let{id:y}=ae(x);return is(O,y)}}))}await zt(h),i.log("debug",`Migration of ${r} complete.`),i.log(`
8
+ ${JSON.stringify(e)}`),new Error("Schema has changed without a version change! Any changes to your schema must be accompanied by a change in schema version and a migration routine.");await this.schema.set(e)};this.setGlobalAck=async e=>{this._closing||(await this.ackInfo.setGlobalAck(e),this.disableRebasing||await this.runRebase(e))};this.export=async()=>{let e=this.db,[n,r]=await Wi(e,["baselines","operations"]),s=await this.localReplica.get(),a=await this.schema.get();if(!a)throw new Error("Cannot export Client data before initializing");return{operations:r,baselines:n,localReplica:s,schema:a}};this.resetFrom=async e=>{let r=this.db.transaction(["baselines","operations","info"],"readwrite");await W(r.objectStore("baselines").clear()),await W(r.objectStore("operations").clear()),await W(r.objectStore("info").clear()),await this.localReplica.update({ackedLogicalTime:e.localReplica.ackedLogicalTime,lastSyncedLogicalTime:e.localReplica.lastSyncedLogicalTime},{transaction:r})};this.stats=async()=>{let e=this.db,n=await tt(e,"operations"),r=await tt(e,"baselines");return{operationsSize:n,baselinesSize:r}};this.context=n,this.schema=new Nt(n.metaDb,n.schema.version),this.operations=new Vt(this.db),this.baselines=new Ft(this.db),this.localReplica=new jt(this.db),this.ackInfo=new Rt(this.db),this.messageCreator=new Lt(this),this.patchCreator=new Mt(()=>this.now),e&&(this.disableRebasing=e)}get db(){return this.context.metaDb}get log(){return this.context.log}get now(){return this.time.now(this.schema.currentVersion)}};var Hr=[Qr,Jr,Yr,Gr];function Ut({indexedDB:i=window.indexedDB,namespace:t,log:e}){return new Promise((n,r)=>{let s=i.open(`${t}_meta`,4),a=!1;s.onupgradeneeded=async l=>{let f=s.result,h=s.transaction,v=Hr.slice(l.oldVersion);for(let E of v)await E(f,h);l.oldVersion||(a=!0)},s.onerror=()=>{console.error("Error opening database",s.error),r(s.error)},s.onsuccess=()=>{n({db:s.result,wasInitialized:a})}})}async function Yi({wipNamespace:i,namespace:t,indexedDB:e,log:n}){let r=await Ut({namespace:i,indexedDB:e,log:n});if(!r.wasInitialized)return r;n?.("debug","Beginning copy of production metadata database to WIP");let{db:s}=await Ut({namespace:t,indexedDB:e,log:n}),a=s.transaction(["baselines","operations","info"],"readonly"),[l,f,h]=await Promise.all([W(a.objectStore("baselines").getAll()),W(a.objectStore("operations").getAll()),W(a.objectStore("info").getAll())]),v=r.db.transaction(["baselines","operations","info"],"readwrite"),E=v.objectStore("baselines"),b=v.objectStore("operations"),P=v.objectStore("info");for(let g of l)E.put(g);for(let g of f)b.put(g);for(let g of h)P.put(g);return await new Promise((g,O)=>{v.oncomplete=()=>{g()},v.onerror=C=>{O(C)},v.onabort=C=>{O(C)}}),await Ae(s),n?.("debug","Finished copy of production metadata database to WIP. Copied:",l.length,"baselines,",f.length,"operations"),r}async function Qr(i,t){let e=i.createObjectStore("baselines",{keyPath:"oid"}),n=i.createObjectStore("operations",{keyPath:"oid_timestamp"}),r=i.createObjectStore("info",{keyPath:"type"});e.createIndex("timestamp","timestamp"),n.createIndex("isLocal_timestamp","isLocal_timestamp"),n.createIndex("documentOid_timestamp","documentOid_timestamp")}async function Jr(i,t){let e=t.objectStore("operations");await new Promise((n,r)=>{let s=e.openCursor();s.onsuccess=()=>{let a=s.result;if(a){let{isLocal_timestamp:l,documentOid_timestamp:f,...h}=a.value;a.update({...h,l_t:l,d_t:f}),a.continue()}else n()},s.onerror=a=>{r(s.error)}}),e.deleteIndex("isLocal_timestamp"),e.deleteIndex("documentOid_timestamp"),e.createIndex("l_t","l_t",{unique:!1}),e.createIndex("o_t","o_t",{unique:!1}),e.createIndex("d_t","d_t",{unique:!1})}async function Yr(i,t){t.objectStore("operations").createIndex("timestamp","timestamp")}async function Gr(i,t){let e=i.createObjectStore("files",{keyPath:"id"});e.createIndex("remote","remote"),e.createIndex("deletedAt","deletedAt")}var Xr=i=>IDBKeyRange.only(me(i.equals)),Zr=i=>{},es=i=>{let t=i.gte||i.gt,e=i.lte||i.lt;return t===e?IDBKeyRange.only(me(t)):t?e?IDBKeyRange.bound(me(t),me(e),!!i.gt,!!i.lt):IDBKeyRange.lowerBound(me(t),!!i.gt):IDBKeyRange.upperBound(me(e),!!i.lt)},ts=(i,t,e)=>{let n=i.collections[t].compounds[e.where];V(n,`Index ${e.where} does not exist on collection ${t}`);let r=Object.keys(e.match).sort((f,h)=>n.of.indexOf(f)-n.of.indexOf(h));for(let f of r)if(n.of.indexOf(f)!==r.indexOf(f))throw new Error(`Compound index ${e.where} does not have ${f} at the start of its order`);let s=r.map(f=>e.match[f]);if(r.length===n.of.length)return IDBKeyRange.only(de(...s));let a=Te(...s),l=_e(...s);return IDBKeyRange.bound(a,l)};function ns(i){let t=i.startsWith,e=i.startsWith+"\uFFFF";return IDBKeyRange.bound(t,e)}function Kt(i,t,e){if(e)return Un(e)?es(e):Nn(e)?Xr(e):Ui(e)?Zr(e):Kn(e)?ns(e):ts(i,t,e)}function Wn(i,t,e){return i.transaction(t,e?"readwrite":"readonly").objectStore(t)}async function zt({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{l.onsuccess=()=>{let E=l.result;h(E?Z(i,E.primaryKey.toString()):null)},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findOne query failed with InvalidStateError",l.error),h(null)):v(l.error)}})}async function $t({collection:i,index:t,context:e}){let n=Wn(e.documentDb,i),r=t?n.index(t.where):n,s=Kt(e.schema,i,t),a=t?.order==="desc"?"prev":"next",l=r.openCursor(s,a);return await new Promise((h,v)=>{let E=new Set;l.onsuccess=()=>{let b=l.result;b?(E.add(Z(i,b.primaryKey.toString())),b.continue()):h(Array.from(E))},l.onerror=()=>{l.error?.name==="InvalidStateError"?(e.log("error","findAll query failed with InvalidStateError",l.error),h([])):v(l.error)}})}async function it({collection:i,index:t,context:e,limit:n,offset:r}){let s=Wn(e.documentDb,i),a=t?s.index(t.where):s,l=Kt(e.schema,i,t),f=t?.order==="desc"?"prev":"next",h=a.openCursor(l,f),v=!r,E=!1,b=0;return{result:await new Promise((g,O)=>{let C=new Set;h.onsuccess=()=>{b++;let x=h.result;x?r&&!v?(x.advance(r),v=!0):(n&&C.size<n&&C.add(Z(i,x.primaryKey.toString())),n&&b>n?(E=!0,g(Array.from(C))):x.continue()):g(Array.from(C))},h.onerror=()=>{h.error?.name==="InvalidStateError"?(e.log("error","find query failed with InvalidStateError",h.error),g([])):O(h.error)}}),hasNextPage:E}}async function Hn(i,t,e,n){function r(l,f){let h,v,E=i.open([t,"collections"].join("_"),e);E.onupgradeneeded=async b=>{h=b.oldVersion;let P=E.transaction;v=E.result,P.abort()},E.onsuccess=b=>{l([E.result.version,E.result])},E.onblocked=b=>{n?.("Database blocked, waiting...")},E.onerror=b=>{l([h,v])}}let[s,a]=await new Promise(r);return await qt(a),s}async function qt(i){i.close(),await new Promise(t=>t())}async function Gi(i,t,e,n,r){function s(a,l){let f=i.open([t,"collections"].join("_"),e),h=!1;f.onupgradeneeded=v=>{let E=f.transaction;n(E,f.result,v),h=!0},f.onsuccess=v=>{f.result.close(),h?a():l(new Error("Database was not upgraded when a version change was expected"))},f.onerror=v=>{l(f.error||new Error("Unknown error"))},f.onblocked=v=>{r?.("Database upgrade blocked, waiting...")}}return new Promise(s)}async function Xi(i,t){typeof navigator<"u"&&navigator.locks?await navigator.locks.request(`verdant_migration_${i}`,t):await t()}async function ke(i,t,e,n){n?.("debug","Opening database",t,"at version",e);let r=await new Promise((s,a)=>{let l=i.open([t,"collections"].join("_"),e);l.onupgradeneeded=async f=>{l.transaction.abort(),n?.("error","Database upgrade needed, but not expected","Expected",e,"Got",l.result.version),a(l.error||new Error(`Migration error: database version changed unexpectedly when reading current data. Expected ${e}, got ${l.result.version}`))},l.onsuccess=f=>{s(l.result)},l.onblocked=f=>{a(new Error("Migration error: database blocked"))},l.onerror=f=>{a(new Error("Migration error: database error"))}});return r.addEventListener("versionchange",s=>{r.close()}),r}var Ve=class extends Error{constructor(e){super(e);this.message=e;this.name="MigrationPathError"}};function Wt({currentVersion:i,targetVersion:t,migrations:e}){let n=Zi({currentVersion:i,targetVersion:t,migrations:e});if(!n)throw new Ve(`No migration path found from ${i} to ${t}! This is a bug. If you're seeing this, contact the developer and provide them with the full contents of this message.`);return n}function Zi({currentVersion:i,targetVersion:t,migrations:e}){if(i===t)return[];let n=e.filter(r=>r.oldSchema.version===i).sort((r,s)=>s.newSchema.version-r.newSchema.version);for(;n.length>0;){let r=n.shift();if(r.newSchema.version>t)return null;if(r.newSchema.version===t)return[r];let s=Zi({currentVersion:r.newSchema.version,targetVersion:t,migrations:e});if(s)return[r,...s]}return null}var Jn=typeof window<"u"?window.indexedDB:void 0;async function rt({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r}){if(r.schema.wip)throw new Error("Cannot open a production client with a WIP schema!");let s=await Hn(t,r.namespace,i,r.log);r.log("debug","Current database version:",s,"target version:",i);let a=Wt({currentVersion:s,targetVersion:i,migrations:e});return a.length>0&&(r.log("debug","Migrations to run:",a.map(l=>l.version)),await Qn({context:r,toRun:a,meta:n,indexedDB:t})),ke(t,r.namespace,i,r.log)}async function er({version:i,indexedDB:t=Jn,migrations:e,meta:n,context:r,wipNamespace:s}){r.log("debug","Opening WIP database",s);let a=await Hn(t,s,i,r.log);if(a===i)r.log("info","WIP schema is up-to-date; not refreshing database");else{r.log("info","WIP schema is out-of-date; refreshing database");let l=Wt({currentVersion:a,targetVersion:i-1,migrations:e});if(l.length>0){await Qn({context:r,toRun:l,meta:n,indexedDB:t,namespace:s});let h=await ke(t,r.namespace,i-1,r.log),v=await ke(t,s,i-1,r.log),E=new Array;for(let x=0;x<h.objectStoreNames.length;x++)E.push(h.objectStoreNames[x]);let b=h.transaction(E,"readonly"),P=E.map(x=>b.objectStore(x)),g=await Promise.all(P.map(x=>W(x.getAll()))),O=v.transaction(E,"readwrite"),C=E.map(x=>O.objectStore(x));for(let x=0;x<C.length;x++)await Promise.all(g[x].map(S=>W(C[x].put(S))))}let f=Wt({currentVersion:i-1,targetVersion:i,migrations:e});f.length>0&&await Qn({context:r,toRun:f,meta:n,indexedDB:t,namespace:s})}return ke(t,s,i,r.log)}async function Qn({context:i,toRun:t,meta:e,indexedDB:n=Jn,namespace:r=i.namespace}){await Xi(r,async()=>{for(let s of t){let a;if(s.oldSchema.version===0)a=ss({meta:e,migration:s,context:i}),await s.migrate(a);else{let h=await ke(n,r,s.oldSchema.version,i.log);a=rs({meta:e,migration:s,context:{...i,documentDb:h}});try{await s.migrate(a),await Promise.all(a.awaitables)}catch(v){throw i.log("critical",`Migration failed (${s.oldSchema.version} -> ${s.newSchema.version})`,v),v}await qt(h)}i.log("debug","Upgrading database",r,"to version",s.newSchema.version),await Gi(n,r,s.newSchema.version,(h,v)=>{for(let E of s.addedCollections)v.createObjectStore(E,{keyPath:s.newSchema.collections[E].primaryKey,autoIncrement:!1});for(let E of s.allCollections){let b=h.objectStore(E);for(let P of s.addedIndexes[E]||[])b.createIndex(P.name,P.name,{multiEntry:P.multiEntry});for(let P of s.removedIndexes[E]||[])b.deleteIndex(P.name)}for(let E of s.removedCollections)h.objectStore(E).clear()},i.log);let l=await ls({meta:e,currentVersion:s.oldSchema.version,newVersion:s.newSchema.version}),f=await ke(n,r,s.newSchema.version,i.log);for(let h of s.allCollections){let E=f.transaction(h,"readwrite").objectStore(h),P=(await os(E)).map(S=>Z(h,`${S}`));P.push(...a.newOids.filter(S=>le(S).collection===h),...l.filter(S=>le(S).collection===h));let O=(await Promise.all(P.map(async S=>{try{let A=await e.getDocumentSnapshot(S);return[S,A]}catch(A){return i.log("error","Could not regenerate snapshot during migration for oid",S,"this document will not be preserved",A),null}}))).filter(S=>!!S).map(([S,A])=>{if(!A)return[S,void 0];let y=Tt(s.newSchema.collections[h],A);return[S,y]}),x=f.transaction(h,"readwrite").objectStore(h);await Promise.all(O.map(([S,A])=>{if(A)return cs(x,A).catch(y=>{throw y});{let{id:y}=le(S);return as(x,y)}}))}await qt(f),i.log("debug",`Migration of ${r} complete.`),i.log(`
9
9
  \u2B06\uFE0F v${s.newSchema.version} Migration complete. Here's the rundown:
10
10
  - Added collections: ${s.addedCollections.join(", ")}
11
11
  - Removed collections: ${s.removedCollections.join(", ")}
12
12
  - Changed collections: ${s.changedCollections.join(", ")}
13
- - New indexes: ${Object.keys(s.addedIndexes).map(m=>s.addedIndexes[m].map(C=>`${m}.${C.name}`)).flatMap(m=>m).join(", ")}
14
- - Removed indexes: ${Object.keys(s.removedIndexes).map(m=>s.removedIndexes[m].map(C=>`${m}.${C.name}`)).flatMap(m=>m).join(", ")}
15
- `)}})}function Gi({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{_e(i.newSchema.collections[s],a);let d=a[i.newSchema.collections[s].primaryKey],h=Z(s,d);return n.push(h),await t.insertLocalOperation(xe(a,h,e)),a},delete:a=>{let d=Z(s,a);return t.insertLocalOperation([{oid:d,timestamp:e(),data:{op:"delete"}}])}},r),{})}function Zr({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=Z(r,s);return await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await Nt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await Kt({collection:r,index:s,context:t});return await Promise.all(a.map(h=>e.getDocumentSnapshot(h,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function es({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=Zr({migration:t,context:e,meta:i}),a=Gi({migration:t,getMigrationNow:n,newOids:r,meta:i}),d=new Array;return{log:e.log,newOids:r,migrate:async(m,C)=>{let P=await s[m].findAll();await Promise.all(P.filter(Boolean).map(async v=>{V(Ze(v),`Document is missing an OID: ${JSON.stringify(v)}`);let T=ne(v),b=await C(v);if(b){Xe(T),Xe(b),je(b);let I=et(T,b,n,void 0,[],{mergeUnknownObjects:!0});I.length>0&&await i.insertLocalOperation(I)}}))},queries:s,mutations:a,awaitables:d}}function ts({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=Gi({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function ns(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function is(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function rs(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ss({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>$(r.oid))))}var st=class extends U{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var qt=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return V(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return _e(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var Ne=Symbol("entity-file-update"),ot=Symbol("entity-file-mark-failed"),os,as,ke=class extends U{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[os]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[as]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{os=Ne,as=ot}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var Xi=dt(ft(),1);function cs(i){return{id:(0,Xi.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Fe(i,t){if(typeof window<"u"&&i instanceof File){let e=cs(i);return t(e),bi(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=Fe(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=Fe(i[e],t);return i}return i}function Zi(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Wt=class extends pe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await Zi(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?ls(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function ls(i,t){return new Blob([i],{type:t})}function ds(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Ht=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ne](e);else{let n=new ke(e.id);n[Ne](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new ke(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[ot]();return}let n=await this.storage.getFile(t.id);if(n)t[Ne](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ne](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[ot](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[ot](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new Wt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:ds,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var Ke=class{constructor(t){this.value=t}deref(){return this.value}};var er="@@refresh",Qt="@@deepChange";function at(i,t){return i[er](t)}var us,ps,me=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[us]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[Qt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[ps]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Qt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return ne(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(te(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(de(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Qt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=ne(t,!1));let n=this.getChildFieldSchema(e);return n&&Ee(t,n),Fe(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>te(e)?this.getSubObject(e.id,n)?.getSnapshot():e);else{t={...this.value};for(let[e,n]of Object.entries(t))te(n)&&(t[e]=this.getSubObject(n.id,e)?.getSnapshot())}return K(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');for(let[s,a]of Object.entries(t)){let d=this.getChildFieldSchema(s);d&&Ee(a,d)}let r=Fe(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),K(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=oe(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(te(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>te(e)?e.id===oe(t):(de(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.oid=t;let{collection:d}=ae(t);this.collection=d,this.parent=s&&new Ke(s),this.store=e,this.fieldSchema=n,this.cache=r;let{view:h,deleted:m,lastTimestamp:C}=this.cache.computeView(t);if(this._current=h,this._deleted=m,this._updatedAt=C||null,this.cachedDeepUpdatedAt=null,this.events=new U(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");V(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}get length(){return this.value.length}[(us=er,ps=Qt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Jt=class{constructor(){let t,e;this.promise=new Promise((n,r)=>{t=n,e=r}),this._resolve=t,this._reject=e}resolve(t){this._resolve(t)}reject(t){this._reject(t)}};var Yt=class extends U{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Jt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(at(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],d=a.findIndex(m=>m.timestamp>=r.timestamp);if(d!==-1){if(a[d].timestamp===r.timestamp)continue;a.splice(d,0,r)}else a.push(r);this.operationsMap.set(s,a);let h=this.localOperationsMap.get(s);h&&this.localOperationsMap.set(s,h.filter(m=>m.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let d=this.operationsMap.get(s)||[];for(;d[0]?.timestamp<r.timestamp;)d.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let d of this.entities.values()){let h=d.deref();h&&at(h,a)}else for(let d of a.affectedOids){let m=this.entities.get(d)?.deref();m&&(at(m,a),this.emit(`change:${d}`),this.emit("change:*",d))}};this.applyOperations=(e,n,r,s)=>{let a,d=this.storeTools.now;for(let h of r)if(!(s&&h.timestamp<=s)){if(gi(h.timestamp,d)>0){a=h.timestamp;continue}h.data.op==="delete"?n=!0:(e=Ce(e,h.data),h.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{if(this.baselinesMap.size===0&&this.operationsMap.size===0&&this.localOperationsMap.size===0)return this.context.log("debug",`Entity ${e} accessed with no data at all`),{view:null,deleted:!0,lastTimestamp:null};let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&K(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=ne(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&K(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r)=>{let a=this.entities.get(e)?.deref();return a||(a=new me({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r}),this.entities.set(e,new Ke(a))),a};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=({operations:e,baselines:n,dropExistingUnconfirmed:r=!1,unconfirmedOperations:s,dropAll:a})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let d={isLocal:!1,affectedOids:new Set};a&&this.baselinesMap.clear(),this.insertBaselines(n,d),a&&this.operationsMap.clear(),this.insertOperations(e,d),(s||r)&&(this.localOperationsMap.clear(),s&&this.insertLocalOperations(s));for(let h of this.entities.keys()){let C=this.entities.get(h)?.deref();C&&(at(C,d),this.emit(`change:${h}`),this.emit("change:*",h))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}get initializedPromise(){return this._initialized.promise}};var Gt="@@default",Xt=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=Gt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=ae(t);return this.schema.collections[e]?{type:"object",properties:this.schema.collections[e].fields}:(this.log("warn",`Missing schema for collection: ${e}`),null)};this.refreshFamilyCache=async(t,e=!1,n=!1)=>{if(this._disposed){this.context.log("debug",`EntityStore is disposed, not refreshing ${t.oid} cache`);return}let r=this.meta.createTransaction(["baselines","operations"]),s=[],a=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,d=>{s.push(d)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,d=>{d.confirmed=!0,a.push(d)},{transaction:r,mode:"readwrite"})]),t.reset({operations:a,baselines:s,dropExistingUnconfirmed:e,dropAll:n})};this.openFamilyCache=async t=>{let e=$(t),n=this.documentFamilyCaches.get(e);return n||(this.context.log("debug","opening family cache for",e),n=new Yt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n),n.setInitialized()),await n.initializedPromise,n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=$(t),{id:n,collection:r}=ae(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let d=ne(a);Pt(this.schema.collections[r],d),Le(d);try{let m=this.db.transaction(r,"readwrite").objectStore(r);await W(m.put(d)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",d)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
16
- `,"Invalid data:",JSON.stringify(d))}}else{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let n=this.getDocumentSchema(t);return n?e.getEntity(t,n):null}return null};this.create=async(t,e,n)=>{xt(t);let r=Fe(t,this.files.add);K(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let d=this.getDocumentSchema(e);if(!d)throw new Error(`Cannot create a document in the ${ae(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,d)};this.addOperationsToOpenCaches=async(t,e)=>{let n=kn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Fn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Fn(t),a=kn(e),d=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let h of d){let m=this.documentFamilyCaches.get(h);m?(m.addData({operations:a[h]||[],baselines:s[h]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",h,a[h]?.length??0,"operations",s[h]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",h,"because it is not open")}return d};this.addData=async({operations:t,baselines:e,reset:n})=>{if(this._disposed){this.log("warn","EntityStore is disposed, not adding data");return}let r=t;for(let d of r)d.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(d=>$(d.oid)).concat(t.map(d=>$(d.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0,!0);for(let d of s)await this.writeDocumentToStorage(d);let a=Array.from(new Set(s.map(d=>ae(d).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=St(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:d=>(this.currentBatchKey=e,d(),this.currentBatchKey=Gt,a),flush:async()=>(await this.operationBatcher.flush(Gt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushAllBatches=async()=>{await Promise.all(this.operationBatcher.flushAll())};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>$(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>ae(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Fi(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let d=await this.openFamilyCache(s),{view:h,deleted:m}=d.computeConfirmedView(s),C=Ni(s,h,a,r);n.unshift(...C)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{V(t===$(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=async()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear(),await this.flushAllBatches()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await W(n.clear())}};this.refreshAllCaches=async(t=!1,e=!1)=>{for(let[n,r]of this.documentFamilyCaches)await this.refreshFamilyCache(r,t,e)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new Ve(this.flushOperations),this.operationBatcher.add({key:Gt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var qn=Symbol("handleMessage"),fs,ct=class extends U{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[fs]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,d]of Object.entries(n.peerPresence))this.isSelf(e,d)?(this._self=d,this._selfReplicaIds.add(d.replicaId),this.emit("selfChanged",d)):(r=!0,s.add(a),this._peers[a]=d,this.emit("peerChanged",a,d))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Ve(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{fs=qn}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 Zt=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var ze=class extends U{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var en=class extends U{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let d of a.messages)this.handleServerMessage(d);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new ze({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function Wn(i){this.message=i}Wn.prototype=new Error,Wn.prototype.name="InvalidCharacterError";var tr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Wn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function hs(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(tr(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return tr(t)}}function tn(i){this.message=i}function ms(i,t){if(typeof i!="string")throw new tn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(hs(i.split(".")[e]))}catch(n){throw new tn("Invalid token specified: "+n.message)}}tn.prototype=new Error,tn.prototype.name="InvalidTokenError";var nr=ms;var nn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(d=>{if(d.ok)return d.json();throw new Error(`Auth endpoint returned non-200 response: ${d.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=nr(t.accessToken);V(e.url,"No sync endpoint provided from auth endpoint"),V(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let d=new URL(r);d.pathname=d.pathname+"/files",a=d.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var rn=class extends U{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}},sn=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var on=class extends U{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new ze;this.reconnectScheduler=new rn(new sn(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e)};this.onMessage=async e=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var an=class extends U{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new ct({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},$e=class extends U{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:d,pullInterval:h,presenceUpdateBatchTimeout:m,defaultProfile:C,useBroadcastChannel:P},{meta:v,log:T,onData:b}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[qn](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=v,this.onData=b,this.log=T||(()=>{}),this.presence=new ct({initialPresence:r,defaultProfile:C,updateBatchTimeout:m}),this.endpointProvider=new nn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new on({endpointProvider:this.endpointProvider,meta:v,presence:this.presence,log:this.log}),this.pushPullSync=new en({endpointProvider:this.endpointProvider,meta:v,presence:this.presence,log:this.log,interval:h}),this.fileSync=new Zt({endpointProvider:this.endpointProvider,log:this.log}),P&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),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=()=>{D&&clearTimeout(D);let x=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;x&&this.mode==="pull"?this.setMode("realtime"):!x&&this.mode==="realtime"&&(D=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},D;this.presence.subscribe("peersChanged",I),s!=="peers-only"&&this.presence.subscribe("selfChanged",I)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var qe=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function gs(i){return i!==null}function Hn(i){return Array.isArray(i)?i.map(Hn).filter(gs):i instanceof me&&i.deleted?null:i}function Oe(i,t){return!i&&!t||i&&t&&we(i)===we(t)}var Qn=Symbol("ON_ALL_UNSUBSCRIBED"),le=Symbol("UPDATE"),bs,fe=class extends qe{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Hn(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof me&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof me&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error&&(e.name==="InvalidStateError"||e.name==="InvalidAccessError"))return this._value;throw e}),this._executionPromise);this[bs]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new U(h=>{h==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let d=a||(h=>h.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",h=>{d(h)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{bs=Qn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var cn=class extends fe{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var vs,ln=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await Nt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[vs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{vs=le}};var ws,dn=class extends fe{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[ws]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{ws=le}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ss,un=class extends fe{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ss]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Ss=le}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var xs,pn=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await Kt({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[xs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{xs=le}};var fn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?we(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new cn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new ln({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[le](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new pn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[le](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new dn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[le](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[le](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,this.context=r,this.documentManager=s,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var hn=class extends qe{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Qn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var Re=class extends U{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let m of e)n[m]=await tt(this.documentDb,m);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((m,{size:C})=>m+C,0),d=r.baselinesSize.size+r.operationsSize.size,h=d/a;return{collections:n,meta:r,storage:s,totalMetaSize:d,totalCollectionsSize:a,metaToDataRatio:h,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this.sync.stop(),this.sync.dispose(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ae(this.documentDb),await Ae(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Bt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ae(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((d,h)=>{s.onsuccess=d,s.onerror=h});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ae(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new $e(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new an,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new Ht({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new Xt({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new hn({context:n}),this._documentManager=new qt(this.meta,this.schema,this._entities);let s=Pi(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[a,d]of Object.entries(n.schema.collections)){let h=d,m=h.pluralName??h.name+"s";V(m===a,`The key of the collection in the schema must be the plural of the name (expected: "${m}")`),this[m]=new fn({collection:m,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var mn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let{db:e}=await Vt({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace}),n={namespace:this._namespace,metaDb:e,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new U,globalEvents:new U},r=new nt({context:n,disableRebasing:t.disableRebasing});await r.updateSchema(t.schema,t.overrideSchemaConflict);let s=await rt({context:n,version:t.schema.version,meta:r,migrations:t.migrations,indexedDB:t.indexedDb}),a=Object.assign(n,{documentDb:s});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},a,{meta:r})};this.initializeWIPDatabases=async t=>{let e=we(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Wi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),s={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new U,globalEvents:new U},a=new nt({context:s,disableRebasing:t.disableRebasing});await a.updateSchema(t.schema,t.overrideSchemaConflict);let d=await Yi({context:s,version:t.schema.version,meta:a,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),h=Object.assign(s,{documentDb:d});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},h,{meta:a})};this.cleanupWIPDatabases=async t=>{let r=(await $i(t.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${t.namespace}_${we(t.schema)}`));for(let s of r)await zi(s,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Bt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=Jn;
13
+ - New indexes: ${Object.keys(s.addedIndexes).map(h=>s.addedIndexes[h].map(v=>`${h}.${v.name}`)).flatMap(h=>h).join(", ")}
14
+ - Removed indexes: ${Object.keys(s.removedIndexes).map(h=>s.removedIndexes[h].map(v=>`${h}.${v.name}`)).flatMap(h=>h).join(", ")}
15
+ `)}})}function tr({migration:i,meta:t,getMigrationNow:e,newOids:n}){return i.allCollections.reduce((r,s)=>(r[s]={put:async a=>{ve(i.newSchema.collections[s],a);let l=a[i.newSchema.collections[s].primaryKey],f=Z(s,l);return n.push(f),await t.insertLocalOperation(xe(a,f,e)),a},delete:a=>{let l=Z(s,a);return t.insertLocalOperation([{oid:l,timestamp:e(),data:{op:"delete"}}])}},r),{})}function is({migration:i,context:t,meta:e}){return i.oldCollections.reduce((n,r)=>(n[r]={get:async s=>{let a=Z(r,s);return await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)})},findOne:async s=>{let a=await zt({collection:r,index:s,context:t});return a?await e.getDocumentSnapshot(a,{to:e.time.now(i.oldSchema.version)}):null},findAll:async s=>{let a=await $t({collection:r,index:s,context:t});return await Promise.all(a.map(f=>e.getDocumentSnapshot(f,{to:e.time.now(i.oldSchema.version)})))}},n),{})}function rs({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=is({migration:t,context:e,meta:i}),a=tr({migration:t,getMigrationNow:n,newOids:r,meta:i}),l=new Array;return{log:e.log,newOids:r,migrate:async(h,v)=>{let E=await s[h].findAll();await Promise.all(E.filter(Boolean).map(async b=>{V(Ze(b),`Document is missing an OID: ${JSON.stringify(b)}`);let P=oe(b),g=await v(b);if(g){Ge(P),Ge(g),je(g);let O=et(P,g,n,void 0,[],{mergeUnknownObjects:!0});O.length>0&&await i.insertLocalOperation(O)}}))},queries:s,mutations:a,awaitables:l}}function ss({meta:i,migration:t,context:e}){function n(){return i.time.zero(t.version)}let r=new Array,s=new Proxy({},{get(){throw new Error("Queries are not available in initial migrations; there is no database yet!")}}),a=tr({migration:t,getMigrationNow:n,newOids:r,meta:i});return{log:e.log,newOids:r,migrate:()=>{throw new Error("Calling migrate() in initial migrations is not supported! Use initial migrations to seed initial data using mutations.")},queries:s,mutations:a,awaitables:[]}}async function os(i){return new Promise((t,e)=>{let n=i.getAllKeys();n.onsuccess=r=>{t(n.result)},n.onerror=r=>{e(n.error)}})}async function as(i,t){let e=i.delete(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function cs(i,t){let e=i.put(t);return new Promise((n,r)=>{e.onsuccess=s=>{n()},e.onerror=s=>{r(e.error)}})}async function ls({meta:i,currentVersion:t,newVersion:e}){let n=[];return await i.operations.iterateOverAllOperations(r=>n.push(r),{from:i.time.zero(t+1)}),Array.from(new Set(n.map(r=>K(r.oid))))}var st=class extends N{constructor(){super(...arguments);this._undoable=[];this._undone=[];this.undo=async()=>{let e=this._undoable.pop();return e?(this._undone.push(await e()),this.emit("change"),!0):!1};this.redo=async()=>{let e=this._undone.pop();return e?(this._undoable.push(await e()),this.emit("change"),!0):!1};this.addUndo=e=>{this._undoable.push(e),this._undone=[],this.emit("change")};this.addRedo=e=>{this._undone.push(e),this.emit("change")};this.clear=()=>{this._undoable=[],this._undone=[],this.emit("change")}}get canUndo(){return this._undoable.length>0}get canRedo(){return this._undone.length>0}};var Ht=class{constructor(t,e,n){this.meta=t;this.schema=e;this.entities=n;this.getOid=(t,e)=>{let n=this.schema.collections[t].primaryKey,r=e[n];return V(r,`Document must have a primary key: ${n.toString()} (got: ${JSON.stringify(e)})`),Z(t,r)};this.addDefaults=(t,e)=>{let n=this.schema.collections[t];return ve(n,e)};this.create=async(t,e,n={})=>{let r=this.addDefaults(t,e),s=this.getOid(t,r);return this.entities.create(r,s,n)};this.delete=async(t,e,n={})=>{let r=Z(t,e);return this.entities.delete(r,n)};this.deleteAll=async(t,e={})=>this.entities.deleteAll(t.map(([n,r])=>Z(n,r)),e);this.deleteAllFromCollection=async(t,e,n={})=>this.entities.deleteAll(e.map(r=>Z(t,r)),n)}};var Ne=Symbol("entity-file-update"),ot=Symbol("entity-file-mark-failed"),ds,us,Me=class extends N{constructor(e,{downloadRemote:n=!1}={}){super();this.id=e;this._objectUrl=null;this._fileData=null;this._loading=!0;this._failed=!1;this._disposed=!1;this._downloadRemote=!1;this[ds]=e=>{this._loading=!1,this._failed=!1,this._disposed=!1,this._fileData=e,e.file&&(this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._objectUrl=URL.createObjectURL(e.file)),this.emit("change")};this[us]=()=>{this._failed=!0,this._loading=!1,this.emit("change")};this.dispose=()=>{this._objectUrl&&URL.revokeObjectURL(this._objectUrl),this._disposed=!0};this._downloadRemote=n}static{ds=Ne,us=ot}get downloadRemote(){return this._downloadRemote}get url(){return this.loading?null:this._objectUrl?this._objectUrl:this._fileData?.url??null}get name(){return this._fileData?.name??null}get type(){return this._fileData?.type??null}get loading(){return this._loading}get failed(){return this._failed}};var nr=ut(ht(),1);function ps(i){return{id:(0,nr.default)(),file:i,url:void 0,remote:!1,name:i.name,type:i.type}}function Be(i,t){if(typeof window<"u"&&i instanceof File){let e=ps(i);return t(e),Oi(e.id)}if(Array.isArray(i)){for(let e=0;e<i.length;e++)i[e]=Be(i[e],t);return i}if(typeof i=="object"){for(let e in i)i[e]=Be(i[e],t);return i}return i}function ir(i){return new Promise((t,e)=>{let n=new FileReader;n.onload=()=>{t(n.result)},n.onerror=e,n.readAsArrayBuffer(i)})}var Qt=class extends pe{constructor(){super(...arguments);this.addFile=async(e,{transaction:n,downloadRemote:r=!1}={})=>{let s=e.file?await ir(e.file):void 0;if(!s&&r&&e.url)try{s=await fetch(e.url,{method:"GET",credentials:"include"}).then(a=>a.arrayBuffer())}catch(a){console.error("Failed to download file to cache it locally. The file will still be available using its URL. Check the file server's CORS configuration.",a)}return this.run("files",a=>a.put({id:e.id,remote:e.remote?"true":"false",deletedAt:null,name:e.name,type:e.type,url:e.url,buffer:s}),"readwrite",n)};this.hydrateFileData=e=>{e.remote=e.remote==="true";let n=e.buffer;return delete e.buffer,e.file=n?fs(n,e.type):void 0,e};this.markUploaded=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,remote:"true"}),"readwrite",n)};this.getFileRaw=async(e,{transaction:n}={})=>{let r=await this.run("files",s=>s.get(e),"readonly",n);if(r)return r};this.getFile=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(r)return this.hydrateFileData(r)};this.markPendingDelete=async(e,{transaction:n}={})=>{let r=await this.getFileRaw(e,{transaction:n});if(!r)throw new Error("File is not in local database");return this.run("files",s=>s.put({...r,deletedAt:Date.now()}),"readwrite",n)};this.listUnsynced=async()=>(await this.run("files",n=>n.index("remote").getAll("false"),"readonly")).map(this.hydrateFileData);this.iterateOverPendingDelete=(e,n)=>this.iterate("files",r=>r.index("deletedAt").openCursor(IDBKeyRange.lowerBound(0,!0)),(r,s)=>{e(this.hydrateFileData(r),s)},"readwrite",n)}deleteFile(e,{transaction:n}={}){return this.run("files",r=>r.delete(e),"readwrite",n)}};function fs(i,t){return new Blob([i],{type:t})}function hs(i){return i.deletedAt!==null&&i.deletedAt<Date.now()-1e3*60*24*3}var Jt=class{constructor({db:t,sync:e,context:n,meta:r,config:s={}}){this.files=new Map;this.add=async t=>{let e=t;if(e.remote=!1,this.files.has(e.id))this.files.get(e.id)[Ne](e);else{let n=new Me(e.id);n[Ne](e),this.files.set(e.id,n)}await this.storage.addFile(e),e.file&&((await this.sync.uploadFile(e)).success?await this.storage.markUploaded(e.id):this.context.log("error","Failed to upload file"))};this.uploadFile=async(t,e=0)=>{let n=await this.sync.uploadFile(t);n.success?await this.storage.markUploaded(t.id):n.retry&&e<5?(this.context.log("error","Error uploading file, retrying..."),setTimeout(this.uploadFile,1e3,t,e+1)):this.context.log("error","Failed to upload file. Not retrying until next sync.")};this.get=t=>{if(this.files.has(t))return this.files.get(t);let e=new Me(t);return this.files.set(t,e),this.load(e),e};this.load=async(t,e=0)=>{if(e>5){t[ot]();return}let n=await this.storage.getFile(t.id);if(n)t[Ne](n);else try{let r=await this.sync.getFile(t.id);r.success?(t[Ne](r.data),await this.storage.addFile(r.data,{downloadRemote:t.downloadRemote})):(t[ot](),r.retry&&setTimeout(this.load,1e3,t,e+1))}catch(r){this.context.log("error","Failed to load file",r),t[ot](),setTimeout(this.load,1e3,t,e+1)}};this.listUnsynced=async()=>this.storage.listUnsynced();this.onOnlineChange=async t=>{if(t){let e=await this.listUnsynced();await Promise.all(e.map(this.uploadFile))}};this.tryCleanupDeletedFiles=async()=>{let t=0,e=0;await this.storage.iterateOverPendingDelete((n,r)=>{this.config.canCleanupDeletedFile(n)?(t++,r.delete(n.id)):e++}),this.context.log("info",`Cleaned up ${t} files, skipped ${e} files`)};this.handleFileRefsDeleted=async t=>{let e=this.storage.createTransaction(["files"],"readwrite");await Promise.all(t.map(async n=>{try{await this.storage.markPendingDelete(n.id,{transaction:e})}catch(r){this.context.log("error","Failed to mark file for deletion",r)}})),this.context.log("info",`Marked ${t.length} files as pending delete`)};this.storage=new Qt(t),this.sync=e,this.context=n,this.meta=r,this.config={canCleanupDeletedFile:hs,...s},this.sync.subscribe("onlineChange",this.onOnlineChange),this.meta.subscribe("filesDeleted",this.handleFileRefsDeleted),this.tryCleanupDeletedFiles()}};var rr="@@refresh",Yt="@@deepChange";function at(i,t){return i[rr](t)}var ms,ys,ye=class i{constructor({oid:t,store:e,fieldSchema:n,cache:r,parent:s,onAllUnsubscribed:a,readonlyKeys:l=[]}){this._current=null;this._deleted=!1;this.cachedSnapshot=null;this.cachedDestructure=null;this.cachedDeepUpdatedAt=null;this._updatedAt=null;this[ms]=t=>{let{view:e,deleted:n,lastTimestamp:r}=this.cache.computeView(this.oid);this._current=e;let s=this._deleted&&!n;this._deleted=n,this.cachedDestructure=null,this._updatedAt=r||null,this.cachedDeepUpdatedAt=null,this._deleted?this.events.emit("delete",t):(this.events.emit("change",t),this[Yt](this,t)),s&&(this.cachedSnapshot=null,this.events.emit("restore",t))};this[ys]=(t,e)=>{this.cachedSnapshot=null,this.cachedDeepUpdatedAt=null,this.events.emit("changeDeep",t,e);let n=this.parent?.deref();n&&n[Yt](t,e)};this.getChildFieldSchema=t=>{if(this.fieldSchema.type==="object")return this.fieldSchema.properties[t];if(this.fieldSchema.type==="array")return this.fieldSchema.items;if(this.fieldSchema.type==="map")return this.fieldSchema.values;if(this.fieldSchema.type==="any")return this.fieldSchema;throw new Error("Invalid field schema")};this.dispose=()=>{this.events.dispose()};this.subscribe=(t,e)=>this.events.subscribe(t,e);this.addPatches=t=>{this.store.addLocalOperations(t)};this.cloneCurrent=()=>{if(this._current!==void 0)return oe(this._current)};this.getSubObject=(t,e)=>{let n=this.getChildFieldSchema(e);return this.cache.getEntity(t,n,this)};this.wrapValue=(t,e)=>{if(te(t)){let n=t.id,r=this.getSubObject(n,e);if(r)return r;throw new Error(`CACHE MISS: Subobject ${n} does not exist on ${this.oid}`)}else if(se(t)){let n=this.store.getFile(t.id);if(n)return n.subscribe("change",()=>{this[Yt](this,{isLocal:!1})}),n}return t};this.processInputValue=(t,e)=>{t instanceof File||(t=oe(t,!1));let n=this.getChildFieldSchema(e);return n&&Pe(t,n),Be(t,this.store.addFile)};this.get=t=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");let e=this.value[t];return this.wrapValue(e,t)};this.getAll=()=>{if(this.value===void 0||this.value===null)throw new Error("Cannot access deleted entity");if(this.cachedDestructure)return this.cachedDestructure;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>this.wrapValue(e,n));else{t={};for(let e in this.value)t[e]=this.get(e)}return this.cachedDestructure=t,t};this.getSnapshot=()=>{if(!this.value||this.deleted)return null;if(this.cachedSnapshot)return this.cachedSnapshot;let t;if(Array.isArray(this.value))t=this.value.map((e,n)=>te(e)?this.getSubObject(e.id,n)?.getSnapshot():se(e)?this.getFileSnapshot(e):e);else{t={...this.value};for(let[e,n]of Object.entries(t))te(n)?t[e]=this.getSubObject(n.id,e)?.getSnapshot():se(n)&&(t[e]=this.getFileSnapshot(n))}return U(t,this.oid),this.cachedSnapshot=t,t};this.keys=()=>Object.keys(this.value||{});this.entries=()=>Object.entries(this.getAll());this.values=()=>Object.values(this.getAll());this.set=(t,e)=>{if(this.readonlyKeys.includes(t))throw new Error(`Cannot set readonly key ${t.toString()}`);this.addPatches(this.store.patchCreator.createSet(this.oid,t,this.processInputValue(e,t)))};this.delete=t=>{if(Array.isArray(this.value))this.addPatches(this.store.patchCreator.createListDelete(this.oid,t,1));else{let e=this.getDeleteMode(t);if(!e)throw new Error(`Cannot delete key ${t} - the property is not marked as optional in the schema`);e==="delete"?this.addPatches(this.store.patchCreator.createRemove(this.oid,t)):this.addPatches(this.store.patchCreator.createSet(this.oid,t,null))}};this.getDeleteMode=t=>{if(this.readonlyKeys.includes(t))return!1;if(this.fieldSchema.type==="any"||this.fieldSchema.type==="map")return"delete";if(this.fieldSchema.type==="object"){let e=this.fieldSchema.properties[t];if(!e||e.type==="any")return"delete";if(e.type==="map")return!1;if(e.nullable)return"null"}return!1};this.remove=this.delete.bind(this);this.update=(t,{replaceSubObjects:e=!1,merge:n=!0}={replaceSubObjects:!1,merge:!0})=>{if(!n&&this.fieldSchema.type!=="any"&&this.fieldSchema.type!=="map")throw new Error('Cannot use .update without merge if the field has a strict schema type. merge: false is only available on "any" or "map" types.');for(let[s,a]of Object.entries(t)){if(this.readonlyKeys.includes(s))throw new Error(`Cannot set readonly key ${s.toString()}`);let l=this.getChildFieldSchema(s);l&&Pe(a,l)}let r=Be(t,this.store.addFile);this.addPatches(this.store.patchCreator.createDiff(this.getSnapshot(),U(r,this.oid),{mergeUnknownObjects:!e,defaultUndefined:n}))};this.getItemRefValue=t=>{if(typeof t=="object"){let e=ae(t);if(!e||!this.cache.hasOid(e))throw new Error(`Cannot move object ${JSON.stringify(t)} which does not exist in this list`);return e}else return t};this.push=t=>{this.addPatches(this.store.patchCreator.createListPush(this.oid,this.processInputValue(t,this.value.length)))};this.insert=(t,e)=>{this.addPatches(this.store.patchCreator.createListInsert(this.oid,t,this.processInputValue(e,t)))};this.move=(t,e)=>{this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,t,e))};this.moveItem=(t,e)=>{let n=this.getItemRefValue(t);if(te(n))this.addPatches(this.store.patchCreator.createListMoveByRef(this.oid,n,e));else{let r=this.value.indexOf(n);this.addPatches(this.store.patchCreator.createListMoveByIndex(this.oid,r,e))}};this.removeAll=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t)))};this.removeFirst=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"first"))};this.removeLast=t=>{this.addPatches(this.store.patchCreator.createListRemove(this.oid,this.getItemRefValue(t),"last"))};this.add=t=>{this.addPatches(this.store.patchCreator.createListAdd(this.oid,this.processInputValue(t,this.value.length)))};this.has=t=>typeof t=="object"?this.value.some(e=>te(e)?e.id===ae(t):(se(e),!1)):this.value.includes(t);this.getAsWrapped=()=>{if(!this.isList)throw new Error("Cannot map items of a non-list");return this.value.map(this.wrapValue)};this.map=t=>this.getAsWrapped().map(t);this.filter=t=>this.getAsWrapped().filter((e,n)=>t(e,n));this.forEach=t=>{this.getAsWrapped().forEach(t)};this.some=t=>this.getAsWrapped().some(t);this.every=t=>this.getAsWrapped().every(t);this.find=t=>this.getAsWrapped().find(t);this.includes=t=>this.has(t);this.oid=t;let{collection:f}=le(t);this.collection=f,this.store=e,this.fieldSchema=n,this.readonlyKeys=l,this.cache=r,this.parent=s&&this.cache.weakRef(s);let{view:h,deleted:v,lastTimestamp:E}=this.cache.computeView(t);if(this._current=h,this._deleted=v,this._updatedAt=E||null,this.cachedDeepUpdatedAt=null,this.events=new N(()=>{this.hasSubscribers||a?.()}),this.oid.includes(".")&&!this.parent)throw new Error("Parent must be provided for sub entities");V(!!n,"Field schema must be provided")}hasSubscribersToDeepChanges(){return this.events.subscriberCount("changeDeep")>0}get hasSubscribers(){if(this.events.totalSubscriberCount()>0)return!0;let t=this.parent?.deref();for(;t;){if(t.hasSubscribersToDeepChanges())return!0;t=t.parent?.deref()}return!1}get deleted(){return this._deleted}get value(){return this._current}get isList(){return Array.isArray(this._current)}get updatedAt(){return this._updatedAt}get deepUpdatedAt(){if(this.cachedDeepUpdatedAt)return this.cachedDeepUpdatedAt;let t=this._updatedAt;return this.isList?this.forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}):this.values().forEach(e=>{if(e instanceof i){let n=e.deepUpdatedAt;n&&(!t||n>t)&&(t=n)}}),this.cachedDeepUpdatedAt=t,t}get uid(){return this.oid}getFileSnapshot(t){let e=this.store.getFile(t.id);return e.url?{id:t.id,url:e.url}:e.loading||e.failed?{id:t.id,url:void 0}:{id:t.id,url:null}}get length(){return this.value.length}[(ms=rr,ys=Yt,Symbol.iterator)](){let t=0;return{next:()=>t<this.value.length?{value:this.get(t++),done:!1}:{value:void 0,done:!0}}}};var Gt=class{constructor(){let t,e;this.promise=new Promise((n,r)=>{t=n,e=r}),this._resolve=t,this._reject=e}resolve(t){this._resolve(t)}reject(t){this._reject(t)}};var Xt=class extends N{constructor({oid:e,store:n,context:r}){super();this.entities=new Map;this._initialized=new Gt;this.setInitialized=()=>{this._initialized.resolve(!0)};this.insertLocalOperations=e=>{let n=new Set;for(let r of e){let{oid:s}=r;n.add(s);let a=this.localOperationsMap.get(s)||[];a.push(r),this.localOperationsMap.set(s,a)}for(let r of n){let a=this.entities.get(r)?.deref();a&&(at(a,{isLocal:!0}),this.emit(`change:${r}`),this.emit("change:*",r))}};this.insertOperations=(e,n)=>{for(let r of e){let{oid:s}=r;n.affectedOids?.add(s);let a=this.operationsMap.get(s)||[],l=a.findIndex(h=>h.timestamp>=r.timestamp);if(l!==-1){if(a[l].timestamp===r.timestamp)continue;a.splice(l,0,r)}else a.push(r);this.operationsMap.set(s,a);let f=this.localOperationsMap.get(s);f&&this.localOperationsMap.set(s,f.filter(h=>h.timestamp!==r.timestamp))}};this.insertBaselines=(e,{affectedOids:n})=>{for(let r of e){let{oid:s}=r,a=this.baselinesMap.get(s);if(a?.timestamp&&a.timestamp>=r.timestamp)continue;n?.add(s),this.baselinesMap.set(s,r);let l=this.operationsMap.get(s)||[];for(;l[0]?.timestamp<r.timestamp;)l.shift()}};this.addData=({operations:e,baselines:n,reset:r,isLocal:s})=>{r&&(this.operationsMap.clear(),this.baselinesMap.clear());let a={isLocal:s||!1,affectedOids:new Set};if(this.insertBaselines(n,a),this.insertOperations(e,a),r)for(let l of this.entities.values()){let f=l.deref();f&&at(f,a)}else for(let l of a.affectedOids){let h=this.entities.get(l)?.deref();h&&(at(h,a),this.emit(`change:${l}`),this.emit("change:*",l))}};this.applyOperations=(e,n,r,s)=>{let a,l=this.storeTools.now;for(let f of r)if(!(s&&f.timestamp<=s)){if(xi(f.timestamp,l)>0){a=f.timestamp;continue}f.data.op==="delete"?n=!0:(e=Ee(e,f.data),f.data.op==="initialize"&&(n=!1))}return a&&this.context.globalEvents.emit("futureSeen",a),{view:e,deleted:n,empty:!e&&!r.length}};this.computeView=e=>{if(this.baselinesMap.size===0&&this.operationsMap.size===0&&this.localOperationsMap.size===0)return this.context.log("debug",`Entity ${e} accessed with no data at all`),{view:null,deleted:!0,lastTimestamp:null};let n=this.computeConfirmedView(e),r=this.localOperationsMap.get(e)||[];if(n.empty&&!r.length)return this.context.log("debug",`Entity ${e} accessed with no local data at all`),{view:null,deleted:!0,lastTimestamp:null};let{view:s,deleted:a}=this.applyOperations(n.view,n.deleted,r);return s&&U(s,e),{view:s,deleted:a,lastTimestamp:this.getLastTimestamp(e)}};this.computeConfirmedView=e=>{let n=this.baselinesMap.get(e),r=this.operationsMap.get(e)||[],s=oe(n?.snapshot||void 0),a=this.applyOperations(s,!s,r,n?.timestamp);return a.view&&U(a.view,e),a.empty&&this.context.log("debug",`Entity ${e} accessed with no confirmed data`),a};this.getLastTimestamp=e=>{let n=this.localOperationsMap.get(e);n?.length||(n=this.operationsMap.get(e)||[]);let r=null;return n.length?r=n[n.length-1]?.timestamp:r=this.baselinesMap.get(e)?.timestamp??null,r?this.storeTools.time.getWallClockTime(r):null};this.getEntity=(e,n,r,s)=>{let l=this.entities.get(e)?.deref();return l||(l=new ye({oid:e,cache:this,fieldSchema:n,store:this.storeTools,parent:r,readonlyKeys:s}),this.entities.set(e,this.context.weakRef(l))),l};this.hasOid=e=>this.operationsMap.has(e)||this.baselinesMap.has(e);this.dispose=()=>{this.entities.forEach(e=>e.deref()?.dispose()),this.entities.clear()};this.reset=({operations:e,baselines:n,dropExistingUnconfirmed:r=!1,unconfirmedOperations:s,dropAll:a})=>{this.context.log("debug",`Resetting cache for ${this.oid} with ${e.length} ops and ${n.length} baselines, dropUnconfirmed=${r}`);let l={isLocal:!1,affectedOids:new Set};a&&this.baselinesMap.clear(),this.insertBaselines(n,l),a&&this.operationsMap.clear(),this.insertOperations(e,l),(s||r)&&(this.localOperationsMap.clear(),s&&this.insertLocalOperations(s));for(let f of this.entities.keys()){let v=this.entities.get(f)?.deref();v&&(at(v,l),this.emit(`change:${f}`),this.emit("change:*",f))}};this.oid=e,this.operationsMap=new Map,this.localOperationsMap=new Map,this.baselinesMap=new Map,this.storeTools={addLocalOperations:n.addLocalOperations,patchCreator:n.meta.patchCreator,addFile:n.files.add,getFile:n.files.get,time:n.meta.time,now:n.meta.now},this.context=r}get initializedPromise(){return this._initialized.promise}get weakRef(){return this.context.weakRef}};var Zt="@@default",en=class{constructor({context:t,meta:e,batchTimeout:n=200,files:r}){this.documentFamilyCaches=new Map;this.unsubscribes=[];this._disposed=!1;this.currentBatchKey=Zt;this.setContext=t=>{this.context=t};this.getDocumentSchema=t=>{let{collection:e}=le(t);if(!this.schema.collections[e])return this.log("warn",`Missing schema for collection: ${e}`),{schema:null,readonlyKeys:[]};let n=this.schema.collections[e];return{readonlyKeys:[n.primaryKey],schema:{type:"object",properties:n.fields}}};this.refreshFamilyCache=async(t,e=!1,n=!1)=>{if(this._disposed){this.context.log("debug",`EntityStore is disposed, not refreshing ${t.oid} cache`);return}let r=this.meta.createTransaction(["baselines","operations"]),s=[],a=[];await Promise.all([this.meta.baselines.iterateOverAllForDocument(t.oid,l=>{s.push(l)},{transaction:r,mode:"readwrite"}),this.meta.operations.iterateOverAllOperationsForDocument(t.oid,l=>{l.confirmed=!0,a.push(l)},{transaction:r,mode:"readwrite"})]),t.reset({operations:a,baselines:s,dropExistingUnconfirmed:e,dropAll:n})};this.openFamilyCache=async t=>{let e=K(t),n=this.documentFamilyCaches.get(e);return n||(this.context.log("debug","opening family cache for",e),n=new Xt({oid:e,store:this,context:this.context}),this.documentFamilyCaches.set(e,n),await this.refreshFamilyCache(n),n.setInitialized()),await n.initializedPromise,n};this.onEntityChange=async t=>{};this.writeDocumentToStorage=async t=>{if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let e=K(t),{id:n,collection:r}=le(e),s=await this.get(e);if(this._disposed){this.log("warn","EntityStore is disposed, not writing to storage");return}let a=s?.getSnapshot();if(a){let l=Tt(this.schema.collections[r],a);try{let h=this.db.transaction(r,"readwrite").objectStore(r);await W(h.put(l)),this.log("info","\u{1F4DD}","wrote",r,n,"to storage",l)}catch{this.log("\u26A0\uFE0F CRITICAL: possibly corrupt data couldn't be written to queryable storage. This is probably a bug in verdant! Please report at https://github.com/a-type/verdant/issues",`
16
+ `,"Invalid data:",JSON.stringify(l))}}else{let f=this.db.transaction(r,"readwrite").objectStore(r);await W(f.delete(n)),this.log("info","\u274C","deleted",r,n,"from storage")}};this.get=async t=>{let e=await this.openFamilyCache(t),{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null};this.getCached=t=>{let e=this.documentFamilyCaches.get(t);if(e){let{schema:n,readonlyKeys:r}=this.getDocumentSchema(t);return n?e.getEntity(t,n,void 0,r):null}return null};this.create=async(t,e,n)=>{Ot(t);let r=Be(t,this.files.add);U(r,e);let s=this.meta.patchCreator.createInitialize(r,e),a=await this.openFamilyCache(e);a.insertLocalOperations(s),await this.submitOperations(s,n);let{schema:l,readonlyKeys:f}=this.getDocumentSchema(e);if(!l)throw new Error(`Cannot create a document in the ${le(e).collection} collection; it is not defined in the current schema version.`);return a.getEntity(e,l,void 0,f)};this.addOperationsToOpenCaches=async(t,e)=>{let n=Rn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding",e.confirmed?"confirmed":"unconfirmed","operations to cache",s,n[s].length),e.isLocal?a.insertLocalOperations(n[s]):a.insertOperations(n[s],e))})};this.addBaselinesToOpenCaches=async(t,e)=>{let n=Fn(t);Object.keys(n).forEach(s=>{let a=this.documentFamilyCaches.get(s);a&&(this.log("adding","baselines to cache",s,n[s].length),a.insertBaselines(n[s],e))})};this.addDataToOpenCaches=({baselines:t,operations:e,reset:n,isLocal:r})=>{let s=Fn(t),a=Rn(e),l=Array.from(new Set(Object.keys(s).concat(Object.keys(a))));for(let f of l){let h=this.documentFamilyCaches.get(f);h?(h.addData({operations:a[f]||[],baselines:s[f]||[],reset:n,isLocal:r}),this.log("debug","Added data to cache for",f,a[f]?.length??0,"operations",s[f]?.length??0,"baselines")):this.log("debug","Could not add data to cache for",f,"because it is not open")}return l};this.addData=async({operations:t,baselines:e,reset:n})=>{if(this._disposed){this.log("warn","EntityStore is disposed, not adding data");return}let r=t;for(let l of r)l.confirmed=!1;let s=[];n?(this.log("Resetting local store to replicate remote synced data",e.length,"baselines, and",t.length,"operations"),await this.meta.reset(),await this.resetStoredDocuments(),s=Array.from(new Set(e.map(l=>K(l.oid)).concat(t.map(l=>K(l.oid)))))):s=this.addDataToOpenCaches({operations:r,baselines:e,reset:n}),await this.meta.insertRemoteBaselines(e),await this.meta.insertRemoteOperations(t),n&&await this.refreshAllCaches(!0,!0);for(let l of s)await this.writeDocumentToStorage(l);let a=Array.from(new Set(s.map(l=>le(l).collection)));this.context.log("changes to collections",a),this.context.entityEvents.emit("collectionsChanged",a)};this.addLocalOperations=async t=>{this.log("Adding local operations",t.length),this.addOperationsToOpenCaches(t,{isLocal:!0,confirmed:!1}),this.operationBatcher.add({key:this.currentBatchKey,items:t})};this.batch=({undoable:t=!0,batchName:e=xt(),max:n=null,timeout:r=this.defaultBatchTimeout}={})=>{let s=this.operationBatcher.add({key:e,max:n,timeout:r,items:[],userData:{undoable:t}}),a={run:l=>(this.currentBatchKey=e,l(),this.currentBatchKey=Zt,a),flush:async()=>(await this.operationBatcher.flush(Zt),s.flush()),discard:()=>{this.operationBatcher.discard(e)}};return a};this.flushPatches=async()=>{await this.operationBatcher.flush(this.currentBatchKey)};this.flushAllBatches=async()=>{await Promise.all(this.operationBatcher.flushAll())};this.flushOperations=async(t,e,n)=>{if(t.length){this.log("Flushing operations",t.length,"to storage / sync");for(let r of t)r.timestamp=this.meta.now;await this.submitOperations(t,n)}};this.submitOperations=async(t,{undoable:e=!0}={})=>{e&&this.undoHistory.addUndo(await this.createUndo(t)),await this.meta.insertLocalOperation(t),this.addDataToOpenCaches({operations:t,baselines:[]});let n=Array.from(new Set(t.map(s=>K(s.oid))));for(let s of n)await this.writeDocumentToStorage(s);let r=new Set(t.map(({oid:s})=>le(s).collection));this.context.log("changes to collections",r),this.context.entityEvents.emit("collectionsChanged",Array.from(r))};this.getInverseOperations=async t=>{let e=Vi(t),n=[],r=()=>this.meta.now;for(let[s,a]of Object.entries(e)){let l=await this.openFamilyCache(s),{view:f,deleted:h}=l.computeConfirmedView(s),v=qi(s,f,a,r);n.unshift(...v)}return n};this.createUndo=async t=>{let e=await this.getInverseOperations(t);return async()=>{let n=await this.createUndo(e);return await this.submitOperations(e.map(r=>(r.timestamp=this.meta.now,r)),{undoable:!1}),n}};this.delete=async(t,e)=>{V(t===K(t),"Only root documents may be deleted via client methods");let n=await this.meta.getAllDocumentRelatedOids(t),r=this.meta.patchCreator.createDeleteAll(n);await this.submitOperations(r,e)};this.deleteAll=async(t,e)=>{let n=await Promise.all(t.map(s=>this.meta.getAllDocumentRelatedOids(s))),r=this.meta.patchCreator.createDeleteAll(n.flat());await this.submitOperations(r,e)};this.reset=async()=>{this.context.log("warn","Resetting local database"),await this.resetStoredDocuments(),await this.refreshAllCaches(!0)};this.destroy=async()=>{this._disposed=!0;for(let t of this.unsubscribes)t();for(let t of this.documentFamilyCaches.values())t.dispose();this.documentFamilyCaches.clear(),await this.flushAllBatches()};this.handleRebase=t=>{this.log("debug","Reacting to rebases",t.length),this.addBaselinesToOpenCaches(t,{isLocal:!0})};this.resetStoredDocuments=async()=>{let t=this.db.transaction(Object.keys(this.schema.collections),"readwrite");for(let e of Object.keys(this.schema.collections)){let n=t.objectStore(e);await W(n.clear())}};this.refreshAllCaches=async(t=!1,e=!1)=>{for(let[n,r]of this.documentFamilyCaches)await this.refreshFamilyCache(r,t,e)};this.context=t,this.defaultBatchTimeout=n,this.meta=e,this.files=r,this.operationBatcher=new Le(this.flushOperations),this.operationBatcher.add({key:Zt,items:[],max:100,timeout:n,userData:{undoable:!0}}),this.unsubscribes.push(this.meta.subscribe("rebase",this.handleRebase))}get log(){return this.context.log}get db(){return this.context.documentDb}get undoHistory(){return this.context.undoHistory}get schema(){return this.context.schema}};var Yn=Symbol("handleMessage"),gs,ct=class extends N{constructor({initialPresence:e,updateBatchTimeout:n=200,defaultProfile:r}){super();this._peers={};this._self={profile:{}};this._selfReplicaIds=new Set;this._peerIds=new Array;this.isSelf=(e,n)=>e.id===n.replicaId||this._selfReplicaIds.has(n.replicaId)||this._self.id===n.id;this[gs]=async(e,n)=>{let r=!1,s=new Set(this.peerIds);if(n.type==="presence-changed")this.isSelf(e,n.userInfo)?(this._self=n.userInfo,this._selfReplicaIds.add(n.userInfo.replicaId),this.emit("selfChanged",n.userInfo)):(s.add(n.userInfo.id),this._peers[n.userInfo.id]=n.userInfo,r=!0,this.emit("peerChanged",n.userInfo.id,n.userInfo));else if(n.type==="sync-resp"){this._peers={},s.clear();for(let[a,l]of Object.entries(n.peerPresence))this.isSelf(e,l)?(this._self=l,this._selfReplicaIds.add(l.replicaId),this.emit("selfChanged",l)):(r=!0,s.add(a),this._peers[a]=l,this.emit("peerChanged",a,l))}else if(n.type==="presence-offline"){s.delete(n.userId),this._selfReplicaIds.delete(n.replicaId);let a=this._peers[n.userId];delete this._peers[n.userId],r=!0,this.emit("peerLeft",n.userId,a)}r&&(this._peerIds=Array.from(s),this.emit("peersChanged",this._peers))};this.update=async e=>{this._updateBatch.update({items:[e]}),this.self.presence={...this.self.presence,...e},this.emit("selfChanged",this.self)};this.flushPresenceUpdates=e=>{let n=e.reduce((r,s)=>({...r,...s}),this.self.presence);this.emit("update",n)};this.self.presence=e,this.self.profile=r,this._updateBatcher=new Le(this.flushPresenceUpdates),this._updateBatch=this._updateBatcher.add({max:25,timeout:n,items:[],key:"default"})}static{gs=Yn}get self(){return this._self}get peers(){return this._peers}get peerIds(){return this._peerIds}get everyone(){let e={...this._peers};return e[this.self.id]=this.self,e}get selfReplicaIds(){return this._selfReplicaIds}};var tn=class{constructor({endpointProvider:t,log:e}){this.uploadFile=async t=>{let e=t.file;if(!e)throw new Error("Cannot upload a non-local file");let{files:n,token:r}=await this.endpointProvider.getEndpoints(),s=new window.FormData;s.append("file",e);try{let a=await fetch(n+`/${t.id}`,{method:"POST",body:s,credentials:"include",headers:{Authorization:`Bearer ${r}`}});return a.ok?{success:!0,retry:!1}:(this.log("error","File upload failed",a.status,await a.text()),{success:!1,retry:a.status>=500})}catch(a){return this.log("error","File upload failed",a),{success:!1,retry:!0}}};this.getFile=async t=>{let{files:e,token:n}=await this.endpointProvider.getEndpoints();try{let r=await fetch(e+`/${t}`,{method:"GET",credentials:"include",headers:{"Content-Type":"application/json",Authorization:`Bearer ${n}`}});return r.ok?{success:!0,data:await r.json()}:(this.log("error","File information fetch failed",r.status,await r.text()),{success:!1,retry:r.status>=500||r.status===404})}catch(r){return this.log("error","File information fetch failed",r),{success:!1,retry:!0}}};this.endpointProvider=t,this.log=e}};var Ue=class extends N{constructor({interval:e=15*1e3,deadlineLength:n=3*1e3,restartOnTabFocus:r=!0}={}){super();this.nextBeat=null;this.deadline=null;this.keepAlive=()=>{this.deadline&&(clearTimeout(this.deadline),this.deadline=null,this.start())};this.start=(e=!1)=>{this.stop(),e?this.beat():this.nextBeat=setTimeout(this.beat,this._interval)};this.stop=()=>{this.nextBeat&&clearTimeout(this.nextBeat),this.deadline&&clearTimeout(this.deadline)};this.beat=async()=>{this.emit("beat"),this.deadline=setTimeout(this.onDeadline,this.deadlineLength)};this.onDeadline=()=>{this.deadline=null,this.emit("missed")};this.setInterval=e=>{this._interval=e};this._interval=e,this.deadlineLength=n,typeof window<"u"&&r&&window.addEventListener("pageshow",()=>this.start(!0))}get interval(){return this._interval}};var nn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,interval:s=15*1e3,log:a=()=>{}}){super();this.mode="pull";this._isConnected=!1;this._status="paused";this._hasSynced=!1;this.setInterval=e=>{this.heartbeat.setInterval(e)};this.sendRequest=async e=>{this.log("Sending sync request",e);try{let{http:n,token:r}=await this.endpointProvider.getEndpoints(),s=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify({messages:e}),credentials:"include"});if(s.ok){this.heartbeat.keepAlive();let a=await s.json();for(let l of a.messages)this.handleServerMessage(l);this._isConnected||(this._isConnected=!0,this.emit("onlineChange",!0))}else this.log("Sync request failed",s.status,await s.text()),this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),s.status>=500&&this.heartbeat.keepAlive()}catch(n){this._isConnected&&(this._isConnected=!1,this.emit("onlineChange",!1)),this.log(n),this.heartbeat.keepAlive()}};this.handleServerMessage=async e=>{e.type==="sync-resp"&&(e.ackThisNonce&&(this.log("Sending sync ack",e.ackThisNonce),this.sendRequest([await this.meta.messageCreator.createAck(e.ackThisNonce)])),this._hasSynced=!0),this.emit("message",e)};this.send=e=>{switch(e.type){case"presence-update":case"sync":case"heartbeat":return this.sendRequest([e]);case"op":if(this._hasSynced)return this.sendRequest([e]);break}};this.dispose=()=>{};this.onHeartbeat=async()=>{this.sendRequest([await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence),await this.meta.messageCreator.createSyncStep1()])};this.onHeartbeatMissed=async()=>{this.emit("onlineChange",!1),this.log("Missed heartbeat"),this._isConnected=!1};this.log=a,this.meta=n,this.presence=r,this.endpointProvider=e,this.heartbeat=new Ue({interval:s}),this.heartbeat.subscribe("beat",this.onHeartbeat),this.heartbeat.subscribe("missed",this.onHeartbeatMissed)}get interval(){return this.heartbeat.interval}start(){this.status!=="active"&&(this.heartbeat.start(!0),this._status="active")}stop(){this.heartbeat.stop(),this._status="paused"}reconnect(){this.heartbeat.start(!0)}get isConnected(){return this._isConnected}get status(){return this._status}};function Gn(i){this.message=i}Gn.prototype=new Error,Gn.prototype.name="InvalidCharacterError";var sr=typeof window<"u"&&window.atob&&window.atob.bind(window)||function(i){var t=String(i).replace(/=+$/,"");if(t.length%4==1)throw new Gn("'atob' failed: The string to be decoded is not correctly encoded.");for(var e,n,r=0,s=0,a="";n=t.charAt(s++);~n&&(e=r%4?64*e+n:n,r++%4)?a+=String.fromCharCode(255&e>>(-2*r&6)):0)n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(n);return a};function bs(i){var t=i.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(sr(e).replace(/(.)/g,function(n,r){var s=r.charCodeAt(0).toString(16).toUpperCase();return s.length<2&&(s="0"+s),"%"+s}))}(t)}catch{return sr(t)}}function rn(i){this.message=i}function ws(i,t){if(typeof i!="string")throw new rn("Invalid token specified");var e=(t=t||{}).header===!0?0:1;try{return JSON.parse(bs(i.split(".")[e]))}catch(n){throw new rn("Invalid token specified: "+n.message)}}rn.prototype=new Error,rn.prototype.name="InvalidTokenError";var or=ws;var sn=class{constructor(t){this.config=t;this.cached=null;this.type=0;this.getEndpoints=async()=>{if(this.cached)return this.cached;let t;this.config.fetchAuth?t=await this.config.fetchAuth():t=await fetch(this.config.authEndpoint,{credentials:"include"}).then(l=>{if(l.ok)return l.json();throw new Error(`Auth endpoint returned non-200 response: ${l.status}`)}),V(t.accessToken,"No access token provided from auth endpoint");let e=or(t.accessToken);V(e.url,"No sync endpoint provided from auth endpoint"),V(e.type!==void 0,"No replica type provided from auth endpoint"),this.type=parseInt(e.type+"");let n=new URL(e.url);n.protocol=n.protocol.replace("ws","http");let r=n.toString();n.protocol=n.protocol.replace("http","ws");let s=n.toString(),a=e.file;if(!a){let l=new URL(r);l.pathname=l.pathname+"/files",a=l.toString()}return this.cached={http:r,websocket:s,files:a,token:t.accessToken},this.cached};if(!t.authEndpoint&&!t.fetchAuth)throw new Error("Either authEndpoint or fetchAuth must be provided to ServerSyncEndpointProvider")}};var on=class extends N{constructor(e){super();this.timer=null;this.isScheduled=!1;this.next=()=>{this.isScheduled||(this.isScheduled=!0,this.timer=setTimeout(()=>{this.emit("trigger"),this.isScheduled=!1,this.backoff.next()},this.backoff.current))};this.reset=()=>{this.backoff.reset(),this.timer&&(clearTimeout(this.timer),this.timer=null)};this.backoff=e}},an=class{constructor(t,e){this.current=0;this.next=()=>{this.current=Math.min(this.max,this.current*this.factor)};this.reset=()=>{this.current=0};this.max=t,this.factor=e}};var cn=class extends N{constructor({endpointProvider:e,meta:n,presence:r,log:s}){super();this.socket=null;this.connectQueue=[];this.syncQueue=[];this._status="paused";this.synced=!1;this.hasStartedSync=!1;this.mode="realtime";this.log=(...e)=>{};this.heartbeat=new Ue;this.reconnectScheduler=new on(new an(60*1e3,1.5));this.onOpen=()=>{if(!this.socket)throw new Error("Invalid sync state: online but socket is null");if(this.synced=!1,this.connectQueue.length){for(let e of this.connectQueue)this.log("Sending queued message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e));this.connectQueue=[]}this.log("Sync connected"),this.onOnlineChange(!0),this.reconnectScheduler.reset()};this.onOnlineChange=async e=>{this.log("Socket online change",e),e?(this.log("Starting sync"),this.hasStartedSync=!0,this.synced=!1,this.send(await this.meta.messageCreator.createPresenceUpdate(this.presence.self.presence)),this.send(await this.meta.messageCreator.createSyncStep1()),this.heartbeat.start()):(this.hasStartedSync=!1,this.synced=!1,this.heartbeat.stop()),this.emit("onlineChange",e)};this.onMessage=async e=>{let n=JSON.parse(e.data);switch(n.type){case"sync-resp":if(n.ackThisNonce&&this.send(await this.meta.messageCreator.createAck(n.ackThisNonce)),this.hasStartedSync=!0,this.synced=!0,this.syncQueue.length){for(let r of this.syncQueue)this.send(r);this.syncQueue=[]}case"need-since":case"presence-changed":case"presence-offline":this.emit("message",n);break;case"op-re":if(!this.hasStartedSync){this.log("Skipping op-re message because sync hasn't started yet",n);break}this.emit("message",n);break;case"heartbeat-response":this.heartbeat.keepAlive(),this.emit("message",n);break;default:this.synced&&this.emit("message",n);break}};this.onError=e=>{this.log(e),this.reconnectScheduler.next(),this.log("Attempting reconnect to websocket sync")};this.onClose=e=>{this.log("Sync disconnected"),this.onOnlineChange(!1),this.onError(e)};this.initializeSocket=async()=>{let e=await this.endpointProvider.getEndpoints();return this.socket=new WebSocket(e.websocket,["Bearer",e.token]),this.socket.addEventListener("message",this.onMessage),this.socket.addEventListener("open",this.onOpen),this.socket.addEventListener("error",this.onError),this.socket.addEventListener("close",this.onClose),this.socket};this.sendHeartbeat=async()=>{this.send(await this.meta.messageCreator.createHeartbeat())};this.reconnect=()=>{this.stop(),this.start()};this.canSkipSyncWait=e=>e.type==="sync"||e.type==="presence-update"||e.type==="sync-ack"||e.type==="heartbeat";this.send=e=>{this.status==="active"&&(!this.hasStartedSync&&!this.canSkipSyncWait(e)||(this.canSkipSyncWait(e)?this.socket?.readyState===WebSocket.OPEN?(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):(this.log("Enqueueing message until socket is open",JSON.stringify(e,null,2)),this.connectQueue.push(e)):this.synced?this.socket?.readyState===WebSocket.OPEN&&(this.log("Sending message",JSON.stringify(e,null,2)),this.socket.send(JSON.stringify(e))):this.hasStartedSync&&(this.log("Enqueueing message until synced",JSON.stringify(e,null,2)),this.syncQueue.push(e))))};this.dispose=()=>{this.socket?.removeEventListener("message",this.onMessage),this.socket?.removeEventListener("close",this.onClose),this.socket?.close()};this.start=()=>{this.socket||(this.initializeSocket(),this._status="active")};this.stop=()=>{this.dispose(),this.socket=null,this._status="paused"};this.log=s||this.log,this.endpointProvider=e,this.meta=n,this.presence=r,this.reconnectScheduler.subscribe("trigger",this.initializeSocket),this.heartbeat.subscribe("beat",this.sendHeartbeat)}get isConnected(){return this.socket?.readyState===WebSocket.OPEN}get status(){return this._status}};var ln=class extends N{constructor(){super(...arguments);this.mode="pull";this.dispose=()=>{};this.isConnected=!1;this.status="paused";this.pullInterval=0;this.presence=new ct({initialPresence:{},defaultProfile:{}});this.uploadFile=async()=>({success:!1,retry:!1});this.getFile=async()=>({success:!1,retry:!1})}send(){}start(){}stop(){}reconnect(){}setMode(){}setPullInterval(){}},Ke=class extends N{constructor({authEndpoint:e,fetchAuth:n,initialPresence:r,automaticTransportSelection:s=!0,autoStart:a,initialTransport:l,pullInterval:f,presenceUpdateBatchTimeout:h,defaultProfile:v,useBroadcastChannel:E},{meta:b,log:P,onData:g}){super();this.broadcastChannel=null;this._activelySyncing=!1;this.handleBroadcastChannelMessage=e=>{e.data.type==="sync"&&this.handleMessage(e.data.message)};this.handleMessage=async e=>{if(e.type==="op-re"||e.type==="sync-resp")for(let n of e.operations)this.meta.time.update(n.timestamp);switch(this.log("sync message",JSON.stringify(e,null,2)),e.type){case"op-re":await this.onData({operations:e.operations,baselines:e.baselines}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp);break;case"global-ack":await this.meta.setGlobalAck(e.timestamp);break;case"sync-resp":this._activelySyncing=!0,this.emit("syncingChange",!0),await this.onData({operations:e.operations,baselines:e.baselines,reset:e.overwriteLocalData}),e.globalAckTimestamp&&await this.meta.setGlobalAck(e.globalAckTimestamp),await this.meta.updateLastSynced(e.ackedTimestamp),this._activelySyncing=!1,this.emit("syncingChange",!1);break;case"need-since":this.activeSync.send(await this.meta.messageCreator.createSyncStep1(e.since));break;case"server-ack":await this.meta.updateLastSynced(e.timestamp)}this.broadcastChannel?.postMessage({type:"sync",message:e}),this.presence[Yn](await this.meta.localReplica.get(),e)};this.handleOnlineChange=e=>{this.emit("onlineChange",e)};this.handlePresenceUpdate=async e=>{this.send(await this.meta.messageCreator.createPresenceUpdate(e))};this.setMode=e=>{if(e==="realtime"&&!this.canDoRealtime)throw new Error("Cannot switch to realtime mode, because the current auth token does not allow it");let n;e==="realtime"?n=this.webSocketSync:n=this.pushPullSync,n!==this.activeSync&&(this.log("switching to",e,"mode"),this.activeSync.status==="active"&&n.start(),this.activeSync.stop(),this.activeSync=n)};this.setPullInterval=e=>{this.pushPullSync.setInterval(e)};this.send=e=>{if(this.activeSync.status==="active")return this.activeSync.send(e)};this.uploadFile=async e=>this.activeSync.status==="active"?this.fileSync.uploadFile(e):{success:!1,retry:!1};this.getFile=async e=>{if(this.activeSync.status==="active")return this.fileSync.getFile(e);throw new Error("Offline, cannot retrieve remote file details")};this.start=()=>this.activeSync.start();this.stop=()=>this.activeSync.stop();this.dispose=()=>{this.webSocketSync.dispose(),this.pushPullSync.dispose()};this.reconnect=()=>this.activeSync.reconnect();if(this.meta=b,this.onData=g,this.log=P||(()=>{}),this.presence=new ct({initialPresence:r,defaultProfile:v,updateBatchTimeout:h}),this.endpointProvider=new sn({authEndpoint:e,fetchAuth:n}),this.webSocketSync=new cn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log}),this.pushPullSync=new nn({endpointProvider:this.endpointProvider,meta:b,presence:this.presence,log:this.log,interval:f}),this.fileSync=new tn({endpointProvider:this.endpointProvider,log:this.log}),E&&"BroadcastChannel"in window&&(this.broadcastChannel=new BroadcastChannel("verdant"),this.broadcastChannel.addEventListener("message",this.handleBroadcastChannelMessage)),l==="realtime"?this.activeSync=this.webSocketSync:this.activeSync=this.pushPullSync,this.presence.subscribe("update",this.handlePresenceUpdate),this.meta.subscribe("message",this.send),this.webSocketSync.subscribe("message",this.handleMessage),this.webSocketSync.subscribe("onlineChange",this.handleOnlineChange),this.pushPullSync.subscribe("message",this.handleMessage),this.pushPullSync.subscribe("onlineChange",this.handleOnlineChange),s&&this.canDoRealtime){let O=()=>{C&&clearTimeout(C);let S=Object.keys(this.presence.peers).length>0||s!=="peers-only"&&this.presence.selfReplicaIds.size>1;S&&this.mode==="pull"?this.setMode("realtime"):!S&&this.mode==="realtime"&&(C=setTimeout(()=>{Object.keys(this.presence.peers).length===0&&this.setMode("pull")},1e3))},C;this.presence.subscribe("peersChanged",O),s!=="peers-only"&&this.presence.subscribe("selfChanged",O)}a&&this.start()}get canDoRealtime(){return this.endpointProvider.type===0||this.endpointProvider.type===2||this.endpointProvider.type===5}get syncing(){return this._activelySyncing}get pullInterval(){return this.pushPullSync.interval}get isConnected(){return this.activeSync.isConnected}get status(){return this.activeSync.status}get mode(){return this.activeSync.mode}};var ze=class{constructor(){this._disposes=[];this.disposed=!1;this.dispose=()=>{this.disposed=!0,this._disposes.forEach(t=>t()),this._disposes=[]};this.addDispose=t=>{this._disposes.push(t)}}};function Ss(i){return i!==null}function Xn(i){return Array.isArray(i)?i.map(Xn).filter(Ss):i instanceof ye&&i.deleted?null:i}function Oe(i,t){return!i&&!t||i&&t&&Se(i)===Se(t)}var Zn=Symbol("ON_ALL_UNSUBSCRIBED"),ue=Symbol("UPDATE"),xs,fe=class extends ze{constructor({initial:e,context:n,collection:r,key:s,shouldUpdate:a}){super();this._internalUnsubscribes=[];this._status="initial";this._executionPromise=null;this.setValue=e=>{this._rawValue=e,this.subscribeToDeleteAndRestore(this._rawValue),this._value=Xn(e),this._status="ready",this._events.emit("change",this._value)};this.refreshValue=()=>{this.setValue(this._rawValue)};this.subscribeToDeleteAndRestore=e=>{for(;this._internalUnsubscribes.length;)this._internalUnsubscribes.pop()?.();Array.isArray(e)?e.forEach(n=>{n instanceof ye&&(this._internalUnsubscribes.push(n.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(n.subscribe("restore",this.refreshValue)))}):e instanceof ye&&(this._internalUnsubscribes.push(e.subscribe("delete",this.refreshValue)),this._internalUnsubscribes.push(e.subscribe("restore",()=>{this.refreshValue()})))};this.execute=()=>(this.context.log("debug","Executing query",this.key),this._status==="initial"?this._status="initializing":this._status==="ready"&&(this._status="revalidating"),this._executionPromise=this.run().then(()=>this._value).catch(e=>{if(e instanceof Error&&(e.name==="InvalidStateError"||e.name==="InvalidAccessError"))return this._value;throw e}),this._executionPromise);this[xs]=e=>{this._allUnsubscribedHandler=e};this._rawValue=e,this._value=e,this._events=new N(f=>{f==="change"&&this._allUnsubscribedHandler?.(this)}),this.context=n,this.key=s,this.collection=r;let l=a||(f=>f.includes(r));this.addDispose(this.context.entityEvents.subscribe("collectionsChanged",f=>{l(f)&&(this.context.log("info","Updating query",this.key),this.execute())}))}static{xs=Zn}get current(){return this._value}get resolved(){return this.status==="ready"?Promise.resolve(this._value):this._executionPromise??this.execute()}get subscribed(){return this._events.totalSubscriberCount()>0}get status(){return this._status}subscribe(e,n){if(n===void 0&&typeof e=="function")return this.resolved,this._events.subscribe("change",e);if(e==="change"&&n!==void 0)return this.resolved,this._events.subscribe("change",n);if(e==="statusChange"&&typeof n=="function")return this._events.subscribe(e,n);throw new Error("Invalid invocation of Query.subscribe")}};var dn=class extends fe{constructor({id:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await this.hydrate(this.oid);this.setValue(e)};this.oid=Z(r.collection,e),this.hydrate=n}};var Os,un=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:null,...r});this.run=async()=>{let e=await zt({collection:this.collection,index:this.index,context:this.context});this.setValue(e?await this.hydrate(e):null)};this[Os]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Os=ue}};var Is,pn=class extends fe{constructor({index:e,hydrate:n,pageSize:r,page:s,...a}){super({initial:[],...a});this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,index:this.index,context:this.context,limit:this._pageSize,offset:this._page*this._pageSize});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.nextPage=async()=>{this.hasNextPage&&(this._page++,await this.run())};this.previousPage=async()=>{this._page!==0&&(this._page--,await this.run())};this.setPage=async e=>{this._page=e,await this.run()};this[Is]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n,this._pageSize=r,this._page=s}static{Is=ue}get pageSize(){return this._pageSize}get page(){return this._page}get hasNextPage(){return this._hasNextPage}get hasPreviousPage(){return this._page>0}};var Ds,fn=class extends fe{constructor({hydrate:e,pageSize:n,index:r,...s}){super({initial:[],...s});this._upToPage=1;this._hasNextPage=!1;this.run=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize*this._upToPage,offset:0,index:this.index});this._hasNextPage=n,this.setValue(await Promise.all(e.map(this.hydrate)))};this.loadMore=async()=>{let{result:e,hasNextPage:n}=await it({collection:this.collection,context:this.context,limit:this._pageSize,offset:this._pageSize*this._upToPage,index:this.index});this._hasNextPage=n,this._upToPage++,this.setValue([...this.current,...await Promise.all(e.map(this.hydrate))])};this[Ds]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=r,this.hydrate=e,this._pageSize=n}static{Ds=ue}get pageSize(){return this._pageSize}get hasMore(){return this._hasNextPage}};var Cs,hn=class extends fe{constructor({index:e,hydrate:n,...r}){super({initial:[],...r});this.run=async()=>{let e=await $t({collection:this.collection,index:this.index,context:this.context});this.setValue(await Promise.all(e.map(this.hydrate)))};this[Cs]=e=>{Oe(this.index,e)||(this.index=e,this.execute())};this.index=e,this.hydrate=n}static{Cs=ue}};var mn=class{constructor({collection:t,cache:e,entities:n,context:r,documentManager:s}){this.serializeIndex=t=>t?Se(t):"";this.get=t=>{let e=`get:${this.collection}:${t}`;return this.cache.getOrSet(e,()=>new dn({id:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:e}))};this.findOne=({index:t,key:e}={})=>{let n=e||`findOne:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new un({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findAll=({index:t,key:e}={})=>{let n=e||`findAll:${this.collection}:${this.serializeIndex(t)}`;return this.cache.getOrSet(n,()=>new hn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:n}),r=>{r[ue](t)})};this.findPage=({index:t,pageSize:e,page:n,key:r})=>{let s=r||`findPage:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(s,()=>new pn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:s,pageSize:e,page:n}),a=>{a[ue](t)})};this.findAllInfinite=({index:t,pageSize:e,key:n})=>{let r=n||`findAllInfinite:${this.collection}:${this.serializeIndex(t)}:${e}`;return this.cache.getOrSet(r,()=>new fn({index:t,collection:this.collection,hydrate:this.hydrate,context:this.context,key:r,pageSize:e}),s=>{s[ue](t)})};this.cache=e,this.collection=t,this.hydrate=n.get,this.context=r,this.documentManager=s,this.put=this.documentManager.create.bind(this.documentManager,this.collection),this.delete=this.documentManager.delete.bind(this.documentManager,this.collection),this.deleteAll=this.documentManager.deleteAllFromCollection.bind(this.documentManager,this.collection)}};var yn=class extends ze{constructor({evictionTime:e=5*1e3,context:n}){super();this._cache=new Map;this.onQueryUnsubscribed=e=>{setTimeout(()=>{e.subscribed||this._cache.get(e.key)===e&&this._cache.delete(e.key)},this._evictionTime)};this._evictionTime=e,this.context=n}get(e){return this._cache.get(e)||null}set(e){return this._cache.set(e.key,e),e[Zn](this.onQueryUnsubscribed),e}getOrSet(e,n,r){let s=this.get(e);return s?(r?.(s),s):this.set(n())}};var Re=class extends N{constructor(e,n,r){super();this.config=e;this.context=n;this.addData=e=>this._entities.addData(e);this.stats=async()=>{let e=Object.keys(this.schema.collections),n={};for(let h of e)n[h]=await tt(this.documentDb,h);let r=await this.meta.stats(),s=typeof navigator<"u"&&typeof navigator.storage<"u"&&"estimate"in navigator.storage?await navigator.storage.estimate():void 0,a=Object.values(n).reduce((h,{size:v})=>h+v,0),l=r.baselinesSize.size+r.operationsSize.size,f=l/a;return{collections:n,meta:r,storage:s,totalMetaSize:l,totalCollectionsSize:a,metaToDataRatio:f,quotaUsage:s?.usage&&s?.quota?s.usage/s.quota:void 0}};this.close=async()=>{this.sync.stop(),this.sync.dispose(),await this._entities.destroy(),this.meta.close(),await new Promise(async e=>{await Ae(this.documentDb),await Ae(this.metaDb),e()}),this.context.log?.("Client closed")};this.__dangerous__resetLocal=async()=>{this.sync.stop(),await Bt(this.namespace,indexedDB)};this.export=async()=>{let e=await this.meta.export();return Buffer.from(JSON.stringify(e))};this.import=async e=>{this.context.log("Importing data..."),await Ae(this.context.documentDb);let n=JSON.parse(e.toString());await this.meta.resetFrom(n);let r=n.schema.version,s=indexedDB.deleteDatabase([this.namespace,"collections"].join("_"));await new Promise((l,f)=>{s.onsuccess=l,s.onerror=f});let a=this.context.schema;this.context.schema=n.schema,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:r}),this.context.log("Re-initializing data from imported data..."),await this._entities.addData({operations:n.operations,baselines:n.baselines,reset:!0}),await Ae(this.context.documentDb),this.context.log("Migrating up to latest schema..."),this.context.schema=a,this.context.documentDb=await rt({meta:this.meta,migrations:this.config.migrations,context:this.context,version:a.version})};this.meta=r.meta,this.collectionNames=Object.keys(n.schema.collections),this._sync=this.config.syncConfig&&!n.schema.wip?new Ke(this.config.syncConfig,{meta:this.meta,onData:this.addData,log:this.context.log}):new ln,n.schema.wip&&this.config.syncConfig&&n.log("warn","\u26A0\uFE0F\u26A0\uFE0F Sync is disabled for WIP schemas. Commit your schema changes to start syncing again. \u26A0\uFE0F\u26A0\uFE0F"),this._fileManager=new Jt({db:this.metaDb,sync:this.sync,context:this.context,config:this.config.files,meta:this.meta}),this._entities=new en({context:this.context,meta:this.meta,files:this._fileManager}),this._queryCache=new yn({context:n}),this._documentManager=new Ht(this.meta,this.schema,this._entities);let s=Bi(()=>{this.emit("futureSeen")},300);this.context.globalEvents.subscribe("futureSeen",s),this.documentDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.documentDb.close(),typeof window<"u"&&window.location.reload()}),this.metaDb.addEventListener("versionchange",()=>{this.context.log?.(`Another tab has requested a version change for ${this.namespace}`),this.metaDb.close(),typeof window<"u"&&window.location.reload()});for(let[a,l]of Object.entries(n.schema.collections)){let f=a;this[f]=new mn({collection:f,cache:this._queryCache,context:this.context,entities:this.entities,documentManager:this.documentManager})}}get sync(){return this._sync}get entities(){return this._entities}get documentManager(){return this._documentManager}get documentDb(){return this.context.documentDb}get metaDb(){return this.context.metaDb}get schema(){return this.context.schema}get namespace(){return this.context.namespace}get undoHistory(){return this.context.undoHistory}get presence(){return this.sync.presence}get batch(){return this.entities.batch}};var lt=class{constructor(t){this.value=t}deref(){return this.value}};var gn=class{constructor(t){this.init=t;this._initializing=!1;this.initialize=async t=>{if(typeof window>"u"&&!t.indexedDb)throw new Error("A verdant client was initialized in an environment without IndexedDB. If you are using verdant in a server-rendered framework, you must enforce that all clients are initialized on the client-side, or you must provide some mock interface of IDBFactory to the ClientDescriptor options.");if(this._initializing||this._resolvedValue)return this._readyPromise;this._initializing=!0;try{let e;return t.schema.wip?e=await this.initializeWIPDatabases(t):(e=await this.initializeDatabases(t),this.cleanupWIPDatabases(t)),this.resolveReady(e),this._resolvedValue=e,e}catch(e){throw this.rejectReady(e),e}finally{this._initializing=!1}};this.initializeDatabases=async t=>{let{db:e}=await Ut({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace}),n={namespace:this._namespace,metaDb:e,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:f=>t.EXPERIMENTAL_weakRefs?new WeakRef(f):new lt(f)},r=new nt({context:n,disableRebasing:t.disableRebasing});await r.updateSchema(t.schema,t.overrideSchemaConflict);let s=await rt({context:n,version:t.schema.version,meta:r,migrations:t.migrations,indexedDB:t.indexedDb}),a=Object.assign(n,{documentDb:s});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},a,{meta:r})};this.initializeWIPDatabases=async t=>{let e=Se(t.schema);console.info(`WIP schema in use. Opening database with hash ${e}`);let n=`@@wip_${t.namespace}_${e}`,{db:r}=await Yi({indexedDB:t.indexedDb,log:t.log,namespace:t.namespace,wipNamespace:n}),s={namespace:this._namespace,metaDb:r,schema:t.schema,log:t.log||(()=>{}),undoHistory:t.undoHistory||new st,entityEvents:new N,globalEvents:new N,weakRef:v=>t.EXPERIMENTAL_weakRefs?new WeakRef(v):new lt(v)},a=new nt({context:s,disableRebasing:t.disableRebasing});await a.updateSchema(t.schema,t.overrideSchemaConflict);let l=await er({context:s,version:t.schema.version,meta:a,migrations:t.migrations,indexedDB:t.indexedDb,wipNamespace:n}),f=Object.assign(s,{documentDb:l});return new Re({syncConfig:t.sync,migrations:t.migrations,files:t.files},f,{meta:a})};this.cleanupWIPDatabases=async t=>{let r=(await Qi(t.indexedDb)).filter(s=>s.name?.startsWith("@@wip_")).map(s=>s.name).filter(s=>!s.startsWith(`@@wip_${t.namespace}_${Se(t.schema)}`));for(let s of r)await Hi(s,t.indexedDb)};this.open=()=>this.initialize(this.init);this.close=async()=>{this._resolvedValue&&this._resolvedValue.close(),this._initializing&&(await this._readyPromise).close()};this.__dangerous__resetLocal=async()=>{await Bt(this.namespace)};this._readyPromise=new Promise((e,n)=>{this.resolveReady=e,this.rejectReady=n}),this._namespace=t.namespace}get namespace(){return this._namespace}get current(){return this._resolvedValue}get readyPromise(){return this._readyPromise}get schema(){return this.init.schema}};window.Verdant=ei;
17
17
  //# sourceMappingURL=index.js.map