dexie-cloud-addon 4.2.0-alpha.1 → 4.2.0-alpha.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- import e,{PropModification as t,cmp as n,Dexie as r,liveQuery as i,RangeSet as s}from"dexie";import{firstValueFrom as o,from as c,filter as l,Observable as a,BehaviorSubject as u,Subject as d,fromEvent as h,of as f,merge as p,switchMap as g,tap as y,mergeMap as v,Subscription as m,throwError as b,combineLatest as w,map as _,share as k,timer as S,startWith as E}from"rxjs";var x=function(e,t){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},x(e,t)};function I(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}x(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function C(e,t,n,r){return new(n||(n=Promise))((function(i,s){function o(e){try{l(r.next(e))}catch(e){s(e)}}function c(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,c)}l((r=r.apply(e,t||[])).next())}))}function A(e,t){var n,r,i,s,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return s={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function c(s){return function(c){return function(s){if(n)throw new TypeError("Generator is already executing.");for(;o;)try{if(n=1,r&&(i=2&s[0]?r.return:s[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,s[1])).done)return i;switch(r=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{n=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function D(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,i,s=n.call(e),o=[];try{for(;(void 0===t||t-- >0)&&!(r=s.next()).done;)o.push(r.value)}catch(e){i={error:e}}finally{try{r&&!r.done&&(n=s.return)&&n.call(s)}finally{if(i)throw i.error}}return o}function T(e,t,n){if(n||2===arguments.length)for(var r,i=0,s=t.length;i<s;i++)!r&&i in t||(r||(r=Array.prototype.slice.call(t,0,i)),r[i]=t[i]);return e.concat(r||Array.prototype.slice.call(t))}function U(e){return this instanceof U?(this.v=e,this):new U(e)}function P(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,i=n.apply(e,t||[]),s=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(e){i[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof U?Promise.resolve(e.value.v).then(l,a):u(s[0][2],e)}(i[e](t))}catch(e){u(s[0][3],e)}}function l(e){c("next",e)}function a(e){c("throw",e)}function u(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}}function j(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=O(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,i){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,i,(t=e[n](t)).done,t.value)}))}}}const L={}.hasOwnProperty;function R(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,i=t.length;r<i;++r)R(e,t[r],n[r])}else{var s=t.indexOf(".");if(-1!==s){var o=t.substr(0,s),c=t.substr(s+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var l=e[o];l&&function(e,t){return L.call(e,t)}(e,o)||(l=e[o]={}),R(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const N="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=$)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function $(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function M(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>M(e)))&&e.every(B))}function B(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(B)}function F(e,t,n){const r=e[t]||(e[t]={}),i=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":i.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":i.forEach(((e,t)=>{const i="update"===n.type?n.changeSpecs[t]:n.changeSpec,s=r[e];if(s)switch(s.type){case"ups":for(const[e,t]of Object.entries(i))R(s.val,e,t);break;case"del":break;case"upd":Object.assign(s.mod,i)}else r[e]={type:"upd",mod:i}}));break;case"delete":i.forEach((e=>{r[e]={type:"del"}}))}return e}function W(e,t){for(const{table:n,muts:r}of t)for(const t of r)F(e,n,t)}const V=Math.floor,K=Math.abs,H=(e,t)=>e>t?e:t,z=128,J=127,q=Number.MAX_SAFE_INTEGER,Y=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&V(e)===e),G=Array.isArray,X="undefined"!=typeof TextEncoder?new TextEncoder:null,Z=X?e=>X.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let Q="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Q&&1===Q.decode(new Uint8Array).length&&(Q=null);let ee=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const te=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},ne=(e,t)=>{for(;t>J;)te(e,z|J&t),t=V(t/128);te(e,J&t)},re=new Uint8Array(3e4),ie=re.length/3,se=X&&X.encodeInto?(e,t)=>{if(t.length<ie){const n=X.encodeInto(t,re).written||0;ne(e,n);for(let t=0;t<n;t++)te(e,re[t])}else oe(e,Z(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;ne(e,r);for(let t=0;t<r;t++)te(e,n.codePointAt(t))},oe=(e,t)=>{ne(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,i=((e,t)=>e<t?e:t)(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(H(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)})(e,t)},ce=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*H(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},le=(e,t)=>ce(e,8).setBigUint64(0,t,!1),ae=new DataView(new ArrayBuffer(4)),ue=(e,t)=>{switch(typeof t){case"string":te(e,119),se(e,t);break;case"number":Y(t)&&K(t)<=2147483647?(te(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),te(e,(t>63?z:0)|(n?64:0)|63&t),t=V(t/64);t>0;)te(e,(t>J?z:0)|J&t),t=V(t/128)})(e,t)):(n=t,ae.setFloat32(0,n),ae.getFloat32(0)===n?(te(e,124),((e,t)=>{ce(e,4).setFloat32(0,t,!1)})(e,t)):(te(e,123),((e,t)=>{ce(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":te(e,122),((e,t)=>{ce(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)te(e,126);else if(G(t)){te(e,117),ne(e,t.length);for(let n=0;n<t.length;n++)ue(e,t[n])}else if(t instanceof Uint8Array)te(e,116),oe(e,t);else{te(e,118);const n=Object.keys(t);ne(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];se(e,i),ue(e,t[i])}}break;case"boolean":te(e,t?120:121);break;default:te(e,127)}var n};function de(e){const t=new ee;switch(se(t,e.type),"table"in e&&se(t,e.table),"prop"in e&&se(t,e.prop),e.type){case"u-ack":case"u-reject":le(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":se(t,e.yServerRev);break;default:switch(ue(t,e.k),e.type){case"aware":oe(t,e.u);break;case"doc-open":ue(t,e.serverRev),ue(t,e.sv);break;case"doc-close":break;case"sv":oe(t,e.sv);break;case"u-c":oe(t,e.u),le(t,BigInt(e.i));break;case"u-s":oe(t,e.u),se(t,e.r||"")}}return(e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const he=e=>new Error(e),fe=he("Unexpected end of array"),pe=he("Integer out of Range");let ge=class{constructor(e){this.arr=e,this.pos=0}};const ye=e=>e.pos!==e.arr.length,ve=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,be(e)),me=e=>e.arr[e.pos++],be=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&J)*n,n*=128,r<z)return t;if(t>q)throw pe}throw fe},we=Q?e=>Q.decode(ve(e)):e=>{let t=be(e);if(0===t)return"";{let n=String.fromCodePoint(me(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(me(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},_e=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ke=e=>_e(e,8).getBigUint64(0,!1),Se=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(64&t)>0?-1:1;if(0==(t&z))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&J)*r,r*=128,t<z)return i*n;if(n>q)throw pe}throw fe},e=>_e(e,4).getFloat32(0,!1),e=>_e(e,8).getFloat64(0,!1),e=>_e(e,8).getBigInt64(0,!1),e=>!1,e=>!0,we,e=>{const t=be(e),n={};for(let r=0;r<t;r++){n[we(e)]=Ee(e)}return n},e=>{const t=be(e),n=[];for(let r=0;r<t;r++)n.push(Ee(e));return n},ve],Ee=e=>Se[127-me(e)](e);function xe(e){return P(this,arguments,(function*(){var t,n,r,i;let s=0,o=new Uint8Array(4),c=0,l=[],a=0;try{for(var u,d=!0,h=j(e);!(t=(u=yield U(h.next())).done);d=!0){i=u.value,d=!1;const e=i,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(s){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===c)break;o[c++]=t,++n}if(c<4)break}else if(c>0&&c<4)for(const t of e.slice(n,n+4-c))o[c++]=t,++n;case 1:a=4===c?new DataView(o.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),c?c=0:n+=4;case 2:if(n>=e.byteLength){s=2;break}if(n+a>e.byteLength)l.push(e.slice(n)),a-=e.byteLength-n,s=2,n=e.byteLength;else{if(l.length>0){const t=new Uint8Array(l.reduce(((e,t)=>e+t.byteLength),a));let r=0;for(const e of l)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+a),r),l=[],yield yield U(t)}else yield yield U(e.slice(n,n+a));n+=a,s=0}}}}catch(e){n={error:e}}finally{try{d||t||!(r=h.return)||(yield U(r.call(h)))}finally{if(n)throw n.error}}}))}function Ie(e){return"function"==typeof e}function Ce(e){return function(t){if(function(e){return Ie(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}var Ae=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function Oe(e){return Ie(null==e?void 0:e.then)}var De,Te,Ue=(De=function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}},(Te=De((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),Te.prototype.constructor=Te,Te);function Pe(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var je=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var o=O(s),c=o.next();!c.done;c=o.next()){c.value.remove(this)}}catch(t){e={error:t}}finally{try{c&&!c.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else s.remove(this);var l=this.initialTeardown;if(Ie(l))try{l()}catch(e){i=e instanceof Ue?e.errors:[e]}var a=this._finalizers;if(a){this._finalizers=null;try{for(var u=O(a),d=u.next();!d.done;d=u.next()){var h=d.value;try{Re(h)}catch(e){i=null!=i?i:[],e instanceof Ue?i=T(T([],D(i)),D(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(i)throw new Ue(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)Re(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=null!==(n=this._finalizers)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&Pe(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&Pe(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function Le(e){return e instanceof je||e&&"closed"in e&&Ie(e.remove)&&Ie(e.add)&&Ie(e.unsubscribe)}function Re(e){Ie(e)?e():e.unsubscribe()}je.EMPTY;var Ne={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},$e={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=$e.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,T([e,t],D(n))):setTimeout.apply(void 0,T([e,t],D(n)))},clearTimeout:function(e){var t=$e.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function Me(e){$e.setTimeout((function(){throw e}))}function Be(){}var Fe=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,Le(t)&&t.add(n)):n.destination=Je,n}return I(t,e),t.create=function(e,t,n){return new He(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(je),We=Function.prototype.bind;function Ve(e,t){return We.call(e,t)}var Ke=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){ze(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ze(e)}else ze(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ze(e)}},e}(),He=function(e){function t(t,n,r){var i,s,o=e.call(this)||this;Ie(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&Ne.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&Ve(t.next,s),error:t.error&&Ve(t.error,s),complete:t.complete&&Ve(t.complete,s)}):i=t;return o.destination=new Ke(i),o}return I(t,e),t}(Fe);function ze(e){Me(e)}var Je={closed:!0,next:Be,error:function(e){throw e},complete:Be},qe="function"==typeof Symbol&&Symbol.observable||"@@observable";function Ye(e){return e}var Ge=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,i=this,s=(r=e)&&r instanceof Fe||function(e){return e&&Ie(e.next)&&Ie(e.error)&&Ie(e.complete)}(r)&&Le(r)?e:new He(e,t,n);return function(){var e=i,t=e.operator,n=e.source;s.add(t?t.call(s,n):n?i._subscribe(s):i._trySubscribe(s))}(),s},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=Xe(t))((function(t,r){var i=new He({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[qe]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return(0===(e=t).length?Ye:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=Xe(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function Xe(e){var t;return null!==(t=null!=e?e:Ne.Promise)&&void 0!==t?t:Promise}function Ze(e){return Ie(e[qe])}function Qe(e){return Symbol.asyncIterator&&Ie(null==e?void 0:e[Symbol.asyncIterator])}function et(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var tt="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function nt(e){return Ie(null==e?void 0:e[tt])}function rt(e){return P(this,arguments,(function(){var t,n,r;return A(this,(function(i){switch(i.label){case 0:t=e.getReader(),i.label=1;case 1:i.trys.push([1,,9,10]),i.label=2;case 2:return[4,U(t.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,U(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,U(r)];case 6:return[4,i.sent()];case 7:return i.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function it(e){return Ie(null==e?void 0:e.getReader)}function st(e){if(e instanceof Ge)return e;if(null!=e){if(Ze(e))return i=e,new Ge((function(e){var t=i[qe]();if(Ie(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(Ae(e))return r=e,new Ge((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(Oe(e))return n=e,new Ge((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,Me)}));if(Qe(e))return ot(e);if(nt(e))return t=e,new Ge((function(e){var n,r;try{for(var i=O(t),s=i.next();!s.done;s=i.next()){var o=s.value;if(e.next(o),e.closed)return}}catch(e){n={error:e}}finally{try{s&&!s.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}e.complete()}));if(it(e))return ot(rt(e))}var t,n,r,i;throw et(e)}function ot(e){return new Ge((function(t){(function(e,t){var n,r,i,s;return C(this,void 0,void 0,(function(){var o,c;return A(this,(function(l){switch(l.label){case 0:l.trys.push([0,5,6,11]),n=j(e),l.label=1;case 1:return[4,n.next()];case 2:if((r=l.sent()).done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];l.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=l.sent(),i={error:c},[3,11];case 6:return l.trys.push([6,,9,10]),r&&!r.done&&(s=n.return)?[4,s.call(n)]:[3,8];case 7:l.sent(),l.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function ct(e,t,n,r,i){return new lt(e,t,n,r,i)}var lt=function(e){function t(t,n,r,i,s,o){var c=e.call(this,t)||this;return c.onFinalize=s,c.shouldUnsubscribe=o,c._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,c._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,c._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,c}return I(t,e),t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))}},t}(Fe),at=function(e){function t(t,n){return e.call(this)||this}return I(t,e),t.prototype.schedule=function(e,t){return this},t}(je),ut={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=ut.delegate;return(null==i?void 0:i.setInterval)?i.setInterval.apply(i,T([e,t],D(n))):setInterval.apply(void 0,T([e,t],D(n)))},clearInterval:function(e){var t=ut.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},dt=function(e){function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return I(t,e),t.prototype.schedule=function(e,t){if(void 0===t&&(t=0),this.closed)return this;this.state=e;var n=this.id,r=this.scheduler;return null!=n&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=this.id||this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return void 0===n&&(n=0),ut.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(void 0===n&&(n=0),null!=n&&this.delay===n&&!1===this.pending)return t;ut.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,Pe(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(at),ht={now:function(){return(ht.delegate||Date).now()},delegate:void 0},ft=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=ht.now,e}(),pt=new(function(e){function t(t,n){void 0===n&&(n=ft.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return I(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(ft))(dt),gt=pt;function yt(e){return e&&Ie(e.schedule)}function vt(e,t,n){void 0===e&&(e=0),void 0===n&&(n=gt);var r=-1;return null!=t&&(yt(t)?n=t:r=t),new Ge((function(t){var i,s=(i=e)instanceof Date&&!isNaN(i)?+e-n.now():e;s<0&&(s=0);var o=0;return n.schedule((function(){t.closed||(t.next(o++),0<=r?this.schedule(void 0,r):t.complete())}),s)}))}function mt(e){return yt((t=e)[t.length-1])?e.pop():void 0;var t}function bt(e,t,n,r,i){void 0===r&&(r=0),void 0===i&&(i=!1);var s=t.schedule((function(){n(),i?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(s),!i)return s}function wt(e){return Ce((function(t,n){var r,i=null,s=!1;i=t.subscribe(ct(n,void 0,void 0,(function(o){r=st(e(o,wt(e)(t))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function _t(e,t){return void 0===t&&(t=0),Ce((function(n,r){n.subscribe(ct(r,(function(n){return bt(r,e,(function(){return r.next(n)}),t)}),(function(){return bt(r,e,(function(){return r.complete()}),t)}),(function(n){return bt(r,e,(function(){return r.error(n)}),t)})))}))}function kt(e,t){return void 0===t&&(t=0),Ce((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function St(e,t){if(!e)throw new Error("Iterable cannot be null");return new Ge((function(n){bt(n,t,(function(){var r=e[Symbol.asyncIterator]();bt(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Et(e,t){if(null!=e){if(Ze(e))return function(e,t){return st(e).pipe(kt(t),_t(t))}(e,t);if(Ae(e))return function(e,t){return new Ge((function(n){var r=0;return t.schedule((function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())}))}))}(e,t);if(Oe(e))return function(e,t){return st(e).pipe(kt(t),_t(t))}(e,t);if(Qe(e))return St(e,t);if(nt(e))return function(e,t){return new Ge((function(n){var r;return bt(n,t,(function(){r=e[tt](),bt(n,t,(function(){var e,t,i;try{t=(e=r.next()).value,i=e.done}catch(e){return void n.error(e)}i?n.complete():n.next(t)}),0,!0)})),function(){return Ie(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(it(e))return function(e,t){return St(rt(e),t)}(e,t)}throw et(e)}function xt(e,t){return Ce((function(n,r){var i=0;n.subscribe(ct(r,(function(n){r.next(e.call(t,n,i++))})))}))}function It(e,t,n){return void 0===n&&(n=1/0),Ie(t)?It((function(n,r){return xt((function(e,i){return t(n,e,r,i)}))(st(e(n,r)))}),n):("number"==typeof t&&(n=t),Ce((function(t,r){return function(e,t,n,r,i,s,o,c){var l=[],a=0,u=0,d=!1,h=function(){!d||l.length||a||t.complete()},f=function(e){return a<r?p(e):l.push(e)},p=function(e){s&&t.next(e),a++;var c=!1;st(n(e,u++)).subscribe(ct(t,(function(e){null==i||i(e),s?f(e):t.next(e)}),(function(){c=!0}),void 0,(function(){if(c)try{a--;for(var e=function(){var e=l.shift();o?bt(t,o,(function(){return p(e)})):p(e)};l.length&&a<r;)e();h()}catch(e){t.error(e)}})))};return e.subscribe(ct(t,f,(function(){d=!0,h()}))),function(){null==c||c()}}(t,r,e,n)})))}function Ct(){return void 0===(e=1)&&(e=1/0),It(Ye,e);var e}function At(e,t){return void 0===t&&(t=pt),Ce((function(n,r){var i=null,s=null,o=null,c=function(){if(i){i.unsubscribe(),i=null;var e=s;s=null,r.next(e)}};function l(){var n=o+e,s=t.now();if(s<n)return i=this.schedule(void 0,n-s),void r.add(i);c()}n.subscribe(ct(r,(function(n){s=n,o=t.now(),i||(i=t.schedule(l,e),r.add(i))}),(function(){c(),r.complete()}),void 0,(function(){s=i=null})))}))}function Ot(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return Ct()((e=n,(t=mt(n))?Et(e,t):st(e)))}var Dt=new Ge((function(e){return e.complete()}));function Tt(e){return e<=0?function(){return Dt}:Ce((function(t,n){var r=0;t.subscribe(ct(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Ut(e,t){return t?function(n){return Ot(t.pipe(Tt(1),Ce((function(e,t){e.subscribe(ct(t,Be))}))),n.pipe(Ut(e)))}:It((function(t,n){return e(t,n).pipe(Tt(1),function(e){return xt((function(){return e}))}(t))}))}function Pt(e,t){void 0===t&&(t=pt);var n=vt(e,t);return Ut((function(){return n}))}function jt(e,t){return void 0===t&&(t=Ye),e=null!=e?e:Lt,Ce((function(n,r){var i,s=!0;n.subscribe(ct(r,(function(n){var o=t(n);!s&&e(i,o)||(s=!1,i=o,r.next(n))})))}))}function Lt(e,t){return e===t}function Rt(e,t){return Ce((function(n,r){var i=0;n.subscribe(ct(r,(function(n){return e.call(t,n,i++)&&r.next(n)})))}))}function Nt(e){return Rt((function(t,n){return e<=n}))}function $t(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=mt(e);return Ce((function(t,r){(n?Ot(e,t,n):Ot(e,t)).subscribe(r)}))}function Mt(e,t){return Ce((function(n,r){var i=null,s=0,o=!1,c=function(){return o&&!i&&r.complete()};n.subscribe(ct(r,(function(n){null==i||i.unsubscribe();var o=0,l=s++;st(e(n,l)).subscribe(i=ct(r,(function(e){return r.next(t?t(n,e,l,o++):e)}),(function(){i=null,c()})))}),(function(){o=!0,c()})))}))}function Bt(e,t,n){var r=Ie(e)||t||n?{next:e,error:t,complete:n}:e;return r?Ce((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;e.subscribe(ct(t,(function(e){var n;null===(n=r.next)||void 0===n||n.call(r,e),t.next(e)}),(function(){var e;i=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()}),(function(e){var n;i=!1,null===(n=r.error)||void 0===n||n.call(r,e),t.error(e)}),(function(){var e,t;i&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)})))})):Ye}let Ft=!1;function Wt(e,t){return C(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){Ft||(Ft=!0)}}))}function Vt(e,t){e.cloud.usingServiceWorker?Wt(e,t):e.localSyncEvent.next({purpose:t})}const Kt="fromBase64"in Uint8Array,Ht="toBase64"in Uint8Array.prototype,zt="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):Kt?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var i=0;i<n;i++)r[i]=t.charCodeAt(i);return r},Jt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):Ht?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};class qt extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function Yt(t,n){return new Promise(((r,i)=>{const s=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),i(new e.AbortError("User cancelled"))}});t.next(s)}))}function Gt(e,t,...n){return Yt(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function Xt(e,t,n){return C(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield Yt(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function Zt(e,t,n){return C(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:i}=yield Yt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return i}))}function Qt(e){return C(this,void 0,void 0,(function*(){var t,n,r;const i=yield e.getCurrentUser(),{accessToken:s,accessTokenExpiration:o,refreshToken:c,refreshTokenExpiration:l,claims:a}=i;if(!s)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=i.license)||void 0===n?void 0:n.status)||"ok"))return i;if(!c)throw new Error("Refresh token missing");if((null!==(r=null==l?void 0:l.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield tn(e.cloud.options.databaseUrl,i);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license,data:u.data}),u}))}function en(t,n,r,i,s){return C(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield tn(t,n):yield function(t,n,r,i){return C(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:s,publicKey:o}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!s||!o)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=s;const c=function(e){const t=Jt(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",o));t.publicKey=o;try{const e=yield n({public_key:c,hints:i});if("error"===e.type)throw new qt(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield Yt(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof qt)throw yield Gt(r,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield Gt(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,i,s)}))}function tn(e,t){return C(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",i=(new TextEncoder).encode(t.refreshToken+n),s=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,i),o=Jt(s),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},l=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==l.status)throw new Error(`RefreshToken: Status ${l.status} from ${e}/token`);const a=yield l.json();if("error"===a.type)throw new qt(a);return t.accessToken=a.accessToken,t.accessTokenExpiration=a.accessTokenExpiration?new Date(a.accessTokenExpiration):void 0,t.claims=a.claims,t.license={type:a.userType,status:a.claims.license||"ok"},null!=a.evalDaysLeft&&(t.license.evalDaysLeft=a.evalDaysLeft),null!=a.userValidUntil&&(t.license.validUntil=new Date(a.userValidUntil)),a.data&&(t.data=a.data),t}))}const nn=new WeakMap;class rn{constructor(e,t){nn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new rn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return C(this,void 0,void 0,(function*(){nn.get(this).table("$logins").put(this)}))}}const sn={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(sn),Object.freeze(sn.claims)}catch(e){}function on(e,t){return o(c(e).pipe(l(t)))}function cn(e){return C(this,void 0,void 0,(function*(){const t=yield ln(e);if(t){if(!(yield function(e,t,n){return C(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield Yt(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield ln(e,{deleteUnsyncedData:!0})}}))}function ln(e){return C(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>C(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const i=n.storeNames.filter((e=>e.endsWith("_mutations"))),s=(yield Promise.all(i.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(s>0&&!t)return[s,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[s,!0]}))));return r&&(yield on(e.cloud.currentUser,(e=>e.userId===sn.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}class an extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function un(e,...t){globalThis.console[e](...t)}function dn(e,t){return C(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),i=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield Qt(e),!1}const s=new rn(e,{claims:{},lastLogin:new Date(0)});return yield en(e.cloud.options.databaseUrl,s,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return C(this,arguments,void 0,(function*({public_key:n,hints:r}){var i;let s;const o=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!o)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))s={demo_user:yield Xt(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n};else if((null==r?void 0:r.otpId)&&r.otp)s={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield Xt(t,"Enter email address",null==r?void 0:r.email);s=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}const c=yield fetch(`${o}/token`,{body:JSON.stringify(s),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==c.status){const e=yield c.text();throw yield Gt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new an(c,e)}const l=yield c.json();if("tokens"===l.type||"error"===l.type)return l;if("otp"===s.grant_type&&"email"in s){if("otp-sent"!==l.type)throw new Error(`Unexpected response from ${o}/token`);const e=yield Zt(t,s.email),r=Object.assign(Object.assign({},s),{otp:e||"",otp_id:l.otp_id,public_key:n});let i=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===i.status;){const e=yield i.text();r.otp=yield Zt(t,s.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),i=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==i.status){const e=yield i.text();throw new an(i,e)}return yield i.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==sn.userId&&s.userId!==i&&(yield cn(e)),yield function(e,t){return C(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>C(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(un("debug","Login context property names:",Object.keys(t)),un("debug","Login context property names:",Object.keys(t)),un("debug","Login context:",t),un("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield on(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,s),Vt(e,"pull"),s.userId!==i}))}const hn={},fn="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;fn&&fn.ready.then((e=>hn.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class pn{constructor(e){this.name=e}subscribe(e){if(!fn)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return fn.addEventListener("message",t),()=>fn.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):hn.registration&&(null===(t=hn.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const gn=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class yn extends a{constructor(e){const t="undefined"==typeof BroadcastChannel?new pn(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function i(e){n.next(e.data)}let s;!function(e,t){gn.has(e)?gn.get(e).push(t):gn.set(e,[t])}(`lbc-${e}`,r);try{t instanceof pn?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",i)}catch(e){}return()=>{!function(e,t){const n=gn.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof pn?s():t.removeEventListener("message",i)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=gn.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function vn(e){return C(this,arguments,void 0,(function*({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),i=yield crypto.subtle.digest("SHA-1",r);return Jt(i)}))}function mn(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function bn(e){return`$${e}_mutations`}function wn(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const _n=[].concat;function kn(e){return _n.apply([],e)}function Sn(e,t){return C(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const i=kn(yield Promise.all(e.map((e=>C(this,void 0,void 0,(function*(){const t=wn(e.name),i=n[t];let s=i?e.where("rev").above(i):e;r<1/0&&(s=s.limit(r));return(yield s.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts)),s=[];let o=null,c=null;for(const{table:e,mut:t}of i)o&&o.table===e&&c===t.txid?o.muts.push(t):(o={table:e,muts:[t]},c=t.txid,s.push(o));return s}))}function En(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:xn}={};const In={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function Cn(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,i){const s=JSON.stringify(e,(function(e){const i=this[e],s=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return In;let s=n.get(r);if(void 0!==s)return s;const o=(i=e,xn.call(i).slice(8,-1)),c=Object.entries(t).find((([t,n])=>{var r,i;return null!==(i=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==i?i:t===o}));return s=null==c?void 0:c[1],s||(s=Array.isArray(e)?null:"function"==typeof e?t.function||null:In),n.set(r,s),s}default:return t[r]}var i}(i);return s?s.replace(i,r,t):i}),i);return s},parse(e,n){const r=[];return JSON.parse(e,(function(e,i){const s=null==i?void 0:i.$t;if(s){const e=t[s];i=e?e.revive(i,n,t):i}let o=r[r.length-1];if(o&&o[0]===i){i={...i};for(const e of o[1])delete i[e];for(const[e,t]of Object.entries(o[2]))i[e]=t;r.pop()}if(void 0===i||"$"===e[0]&&"$t"!==e){let t,n;o=r[r.length-1],o&&o[0]===this?(t=o[1],n=o[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=i):n[e]=void 0}return i}))}}}const An={Blob:{test:(e,t)=>"Blob"===t,replace:(e,t)=>{const n=t.length;return t.push(e),{$t:"Blob",mimeType:e.type,i:n}},revive:({i:e,mimeType:t},n)=>new Blob([n[e]],{type:t})}};var On={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const Dn={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Tn={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Un={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Pn={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const jn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Ln=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const i=jn[t];return i&&new i(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Rn(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Mn[e[n]];return t}(Jt(e))}function Nn(e){return zt(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=$n[e[n]];return t}(e))}const $n={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},Mn={};for(const e of Object.keys($n))Mn[$n[e]]=e;var Bn={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Rn(e)}),revive:({v:e})=>{const t=Nn(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Fn{constructor(e,t){this.buf=e,this.type=t}}function Wn(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function Vn(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Kn={Blob:{test:(e,t)=>"Blob"===t||e instanceof Fn,replace:e=>({$t:"Blob",v:Jt(e instanceof Fn?e.buf:Vn(Wn(e))),type:e.type}),revive:({type:e,v:t})=>{const n=zt(t);return void 0!==typeof Blob?new Blob([n]):new Fn(n.buffer,e)}}};const Hn={...On,...Dn,...Tn,...Un,...Pn,...Ln,...Bn,...Kn};function zn(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsArrayBuffer(e)}))}var Jn={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},qn={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:Jt(Vn(Wn(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const i=zt(t);return new File([i],n,{type:e,lastModified:new Date(r).getTime()})}}};const Yn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Gn{toString(){return this.v}constructor(e){this.v=e}}const Xn=Yn?{}:{bigint:{test:e=>e instanceof Gn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Gn(e)}},Zn=Object.assign(Object.assign(Object.assign(Object.assign({},Jn),Xn),qn),{PropModification:{test:e=>e instanceof t,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]])}return n}(e,["$t"]);return new t(n)}}}),Qn=Cn(Hn,Zn),er=function(...e){const t=Cn(Hn,An,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),i=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[i,r]},async parse(e,n){let r=0;const i=[],s=await zn(n),o=new DataView(s);for(;r<s.byteLength;){const e=o.getUint32(r);r+=4;const t=s.slice(r,r+e);r+=e,i.push(t)}return t.parse(e,i)},async fromBinary(e){const t=new DataView(await zn(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(Zn);function tr(t,n,r){const i=[];for(let s of r){const{table:r,muts:o}=s,c=t.tables.find((e=>e.name===r));if(!c)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:l}=c;let a=s;o.forEach(((t,r)=>{const i=!l.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,o)=>{if(Array.isArray(t)){a===s&&(a=nr(s,i));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===s&&(a=nr(s,i));const c=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${t}:${n.userId}`;c.keys[o]=u,i&&e.setByKeyPath(c.values[o],l.keyPath,u)}}))})),i.push(a)}return i}function nr(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}let rr=new WeakMap;function ir(e){return C(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=rr.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function sr(e,t,n,r,i,s,o,c,l){return C(this,void 0,void 0,(function*(){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield Qt(i),d=null==u?void 0:u.accessToken;d&&(a.Authorization=`Bearer ${d}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:c,schema:o||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:tr(i.dx.core.schema,l,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=Qn.stringify(h),p=yield fetch(`${s}/sync`,{method:"post",headers:a,credentials:"include",body:f});if(i.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),i=t.headers.get("Ratelimit-Reset");if(n&&r&&i){const t=Number(n),s=Math.max(0,Number(r)),o=Number(i);if(s<t/2){const t=Math.ceil(o/(s+1));rr.set(e,new Date(Date.now()+1e3*t))}else rr.delete(e)}}(i,p),!p.ok)throw new an(p);if("application/x-bison"===p.headers.get("content-type"))return er.fromBinary(yield p.blob());{const e=yield p.text();return Qn.parse(e)}}))}function or(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let cr=!1;function lr(e,t,n,r){return C(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function ar(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function ur(t,r,i){return C(this,void 0,void 0,(function*(){const s=yield t.bulkGet(r),o=[],c=[];r.forEach(((r,l)=>{const a=s[l];if(a){for(const[s,o]of Object.entries(i[l]))if(s===t.schema.primKey.keyPath){if(0!==n(o,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(a,s,o);o.push(r),c.push(a)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(c,o):t.bulkPut(c)}))}function dr(t,n){return C(this,void 0,void 0,(function*(){for(const{table:r,muts:i}of t){if(!n.dx._allTables[r])continue;const t=n.table(r),{primaryKey:s}=t.core.schema,o=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of i){const r=n.keys.map(o);switch(n.type){case"insert":s.outbound?yield t.bulkAdd(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),yield t.bulkAdd(n.values));break;case"upsert":s.outbound?yield t.bulkPut(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),yield t.bulkPut(n.values));break;case"modify":1===r.length?yield t.update(r[0],n.changeSpec):yield t.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield ur(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(cr=navigator.onLine,self.addEventListener("online",(()=>cr=!0)),self.addEventListener("offline",(()=>cr=!1)));const hr="dexie-cloud-syncer";function fr(e,t){return e.where("i").between(t,1/0,!0).toArray()}const pr=()=>new Map,gr=e=>{const t=pr();return e.forEach(((e,n)=>{t.set(n,e)})),t},yr=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},vr=()=>new Set,mr=e=>e[e.length-1],br=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},wr=Array.from,_r=Array.isArray;class kr{constructor(){this._observers=pr()}on(e,t){return yr(this._observers,e,vr).add(t),t}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return wr((this._observers.get(e)||pr()).values()).forEach((e=>e(...t)))}destroy(){this._observers=pr()}}const Sr=Math.floor,Er=Math.abs,xr=(e,t)=>e<t?e:t,Ir=(e,t)=>e>t?e:t,Cr=e=>0!==e?e<0:1/e<0,Ar=64,Or=128,Dr=127,Tr=Number.MAX_SAFE_INTEGER,Ur=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&Sr(e)===e),Pr=/^\s*/g,jr=/([A-Z])/g,Lr=(e,t)=>(e=>e.replace(Pr,""))(e.replace(jr,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),Rr="undefined"!=typeof TextEncoder?new TextEncoder:null,Nr=Rr?e=>Rr.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let $r="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});$r&&1===$r.decode(new Uint8Array).length&&($r=null);class Mr{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Br=()=>new Mr,Fr=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Wr=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},Vr=Wr,Kr=(e,t)=>{for(;t>Dr;)Wr(e,Or|Dr&t),t=Sr(t/128);Wr(e,Dr&t)},Hr=(e,t)=>{const n=Cr(t);for(n&&(t=-t),Wr(e,(t>63?Or:0)|(n?Ar:0)|63&t),t=Sr(t/64);t>0;)Wr(e,(t>Dr?Or:0)|Dr&t),t=Sr(t/128)},zr=new Uint8Array(3e4),Jr=zr.length/3,qr=Rr&&Rr.encodeInto?(e,t)=>{if(t.length<Jr){const n=Rr.encodeInto(t,zr).written||0;Kr(e,n);for(let t=0;t<n;t++)Wr(e,zr[t])}else Gr(e,Nr(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;Kr(e,r);for(let t=0;t<r;t++)Wr(e,n.codePointAt(t))},Yr=(e,t)=>{const n=e.cbuf.length,r=e.cpos,i=xr(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Ir(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Gr=(e,t)=>{Kr(e,t.byteLength),Yr(e,t)},Xr=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*Ir(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Zr=new DataView(new ArrayBuffer(4)),Qr=(e,t)=>{switch(typeof t){case"string":Wr(e,119),qr(e,t);break;case"number":Ur(t)&&Er(t)<=2147483647?(Wr(e,125),Hr(e,t)):(n=t,Zr.setFloat32(0,n),Zr.getFloat32(0)===n?(Wr(e,124),((e,t)=>{Xr(e,4).setFloat32(0,t,!1)})(e,t)):(Wr(e,123),((e,t)=>{Xr(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":Wr(e,122),((e,t)=>{Xr(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Wr(e,126);else if(_r(t)){Wr(e,117),Kr(e,t.length);for(let n=0;n<t.length;n++)Qr(e,t[n])}else if(t instanceof Uint8Array)Wr(e,116),Gr(e,t);else{Wr(e,118);const n=Object.keys(t);Kr(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];qr(e,i),Qr(e,t[i])}}break;case"boolean":Wr(e,t?120:121);break;default:Wr(e,127)}var n};class ei extends Mr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Kr(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const ti=e=>{e.count>0&&(Hr(e.encoder,1===e.count?e.s:-e.s),e.count>1&&Kr(e.encoder,e.count-2))};class ni{constructor(){this.encoder=new Mr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(ti(this),this.count=1,this.s=e)}toUint8Array(){return ti(this),Fr(this.encoder)}}const ri=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);Hr(e.encoder,t),e.count>1&&Kr(e.encoder,e.count-2)}};class ii{constructor(){this.encoder=new Mr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(ri(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return ri(this),Fr(this.encoder)}}class si{constructor(){this.sarr=[],this.s="",this.lensE=new ni}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new Mr;return this.sarr.push(this.s),this.s="",qr(e,this.sarr.join("")),Yr(e,this.lensE.toUint8Array()),Fr(e)}}const oi=e=>new Error(e),ci=()=>{throw oi("Method unimplemented")},li=()=>{throw oi("Unexpected case")},ai=oi("Unexpected end of array"),ui=oi("Integer out of Range");class di{constructor(e){this.arr=e,this.pos=0}}const hi=e=>new di(e),fi=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,gi(e)),pi=e=>e.arr[e.pos++],gi=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Dr)*n,n*=128,r<Or)return t;if(t>Tr)throw ui}throw ai},yi=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(t&Ar)>0?-1:1;if(0==(t&Or))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&Dr)*r,r*=128,t<Or)return i*n;if(n>Tr)throw ui}throw ai},vi=$r?e=>$r.decode(fi(e)):e=>{let t=gi(e);if(0===t)return"";{let n=String.fromCodePoint(pi(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(pi(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},mi=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},bi=[e=>{},e=>null,yi,e=>mi(e,4).getFloat32(0,!1),e=>mi(e,8).getFloat64(0,!1),e=>mi(e,8).getBigInt64(0,!1),e=>!1,e=>!0,vi,e=>{const t=gi(e),n={};for(let r=0;r<t;r++){n[vi(e)]=wi(e)}return n},e=>{const t=gi(e),n=[];for(let r=0;r<t;r++)n.push(wi(e));return n},fi],wi=e=>bi[127-pi(e)](e);class _i extends di{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){var e;return 0===this.count&&(this.s=this.reader(this),(e=this).pos!==e.arr.length?this.count=gi(this)+1:this.count=-1),this.count--,this.s}}class ki extends di{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=yi(this);const e=Cr(this.s);this.count=1,e&&(this.s=-this.s,this.count=gi(this)+2)}return this.count--,this.s}}class Si extends di{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=yi(this),t=1&e;this.diff=Sr(e/2),this.count=1,t&&(this.count=gi(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ei{constructor(e){this.decoder=new ki(e),this.str=vi(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}const xi=crypto.getRandomValues.bind(crypto),Ii=()=>xi(new Uint32Array(1))[0],Ci=[1e7]+-1e3+-4e3+-8e3+-1e11,Ai=()=>Ci.replace(/[018]/g,(e=>(e^Ii()&15>>e/4).toString(16))),Oi=e=>new Promise(e);Promise.all.bind(Promise);const Di=e=>void 0===e?null:e;let Ti=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Ui=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Ti=localStorage,Ui=!1)}catch(Ma){}const Pi=Ti,ji=Object.assign,Li=Object.keys,Ri=e=>Li(e).length,Ni=(e,t)=>e===t||Ri(e)===Ri(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,((e,n)=>(void 0!==e||((e,t)=>Object.prototype.hasOwnProperty.call(e,t))(t,n))&&t[n]===e)),$i=Object.freeze,Mi=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Mi(e[t])}return $i(e)},Bi=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Bi(e,t,n+1)}},Fi="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Wi;const Vi=e=>(()=>{if(void 0===Wi)if(Fi){Wi=pr();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Wi.set(t,""),t=r):null!==t&&(Wi.set(t,r),t=null)}null!==t&&Wi.set(t,"")}else"object"==typeof location?(Wi=pr(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");Wi.set(`--${Lr(t,"-")}`,n),Wi.set(`-${Lr(t,"-")}`,n)}}))):Wi=pr();return Wi})().has(e),Ki=e=>Di(Fi?process.env[e.toUpperCase().replaceAll("-","_")]:Pi.getItem(e)),Hi=e=>Vi("--"+e)||null!==Ki(e);Hi("production");var zi;Fi&&(zi=process.env.FORCE_COLOR,["true","1","2"].includes(zi))||!Vi("--no-colors")&&!Hi("no-color")&&(!Fi||process.stdout.isTTY)&&(!Fi||Vi("--color")||null!==Ki("COLORTERM")||(Ki("TERM")||"").includes("color"));class Ji{constructor(e,t){this.left=e,this.right=t}}const qi=(e,t)=>new Ji(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const Yi=Symbol,Gi=Yi(),Xi=Yi(),Zi=Yi(),Qi=Yi(),es=Yi(),ts=Yi(),ns=Yi(),rs=Yi(),is=Yi(),ss=(qi("font-weight","bold"),qi("font-weight","normal"),qi("color","blue"),qi("color","green"),qi("color","grey"),qi("color","red"),qi("color","purple"),qi("color","orange"),qi("color","black"),vr()),os=e=>({[Symbol.iterator](){return this},next:e}),cs=(e,t)=>os((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class ls{constructor(e,t){this.clock=e,this.len=t}}class as{constructor(){this.clients=new Map}}const us=(e,t,n)=>t.clients.forEach(((t,r)=>{const i=e.doc.store.clients.get(r);if(null!=i){const r=i[i.length-1],s=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<s;o=t[++r])zs(e,i,o.clock,o.len,n)}})),ds=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=Sr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},hs=e=>{e.clients.forEach((e=>{let t,n;for(e.sort(((e,t)=>e.clock-t.clock)),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?r.len=Ir(r.len,i.clock+i.len-r.clock):(n<t&&(e[n]=i),n++)}e.length=n}))},fs=(e,t,n,r)=>{yr(e.clients,t,(()=>[])).push(new ls(n,r))},ps=(e,t)=>{Kr(e.restEncoder,t.clients.size),wr(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),Kr(e.restEncoder,t);const r=n.length;Kr(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},gs=(e,t,n)=>{const r=new as,i=gi(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=gi(e.restDecoder),s=gi(e.restDecoder),o=n.clients.get(i)||[],c=Ms(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&fs(r,i,c,s-c);let e=Fs(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,Ac(t,l,n-l.id.clock)),e++);e<o.length&&(l=o[e++],l.id.clock<s);)l.deleted||(s<l.id.clock+l.length&&o.splice(e,0,Ac(t,l,s-l.id.clock)),l.delete(t))}else fs(r,i,n,s-n)}}if(r.clients.size>0){const e=new Ss;return Kr(e.restEncoder,0),ps(e,r),e.toUint8Array()}return null},ys=Ii;class vs extends kr{constructor({guid:e=Ai(),collectionid:t=null,gc:n=!0,gcFilter:r=(()=>!0),meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=ys(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Ns,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Oi((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const c=()=>Oi((e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)}));this.on("sync",(e=>{!1===e&&this.isSynced&&(this.whenSynced=c()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])})),this.whenSynced=c()}load(){const e=this._item;null===e||this.shouldLoad||Zs(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(wr(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return Zs(this,e,t)}get(e,t=mo){const n=yr(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==mo&&r!==t){if(r===mo){const r=new t;r._map=n._map,n._map.forEach((e=>{for(;null!==e;e=e.left)e.parent=r})),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,Ro)}getText(e=""){return this.get(e,ec)}getMap(e=""){return this.get(e,$o)}getXmlElement(e=""){return this.get(e,rc)}getXmlFragment(e=""){return this.get(e,nc)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,wr(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new vs({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Zs(e.parent.doc,(n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)}),null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class ms{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=gi(this.restDecoder),this.dsCurrVal}readDsLen(){const e=gi(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class bs extends ms{constructor(e){super(e),this.keys=[],gi(e),this.keyClockDecoder=new Si(fi(e)),this.clientDecoder=new ki(fi(e)),this.leftClockDecoder=new Si(fi(e)),this.rightClockDecoder=new Si(fi(e)),this.infoDecoder=new _i(fi(e),pi),this.stringDecoder=new Ei(fi(e)),this.parentInfoDecoder=new _i(fi(e),pi),this.typeRefDecoder=new ki(fi(e)),this.lenDecoder=new ki(fi(e))}readLeftID(){return new Us(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Us(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return wi(this.restDecoder)}readBuf(){return fi(this.restDecoder)}readJSON(){return wi(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class ws{constructor(){this.restEncoder=Br()}toUint8Array(){return Fr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Kr(this.restEncoder,e)}writeDsLen(e){Kr(this.restEncoder,e)}}class _s extends ws{writeLeftID(e){Kr(this.restEncoder,e.client),Kr(this.restEncoder,e.clock)}writeRightID(e){Kr(this.restEncoder,e.client),Kr(this.restEncoder,e.clock)}writeClient(e){Kr(this.restEncoder,e)}writeInfo(e){Vr(this.restEncoder,e)}writeString(e){qr(this.restEncoder,e)}writeParentInfo(e){Kr(this.restEncoder,e?1:0)}writeTypeRef(e){Kr(this.restEncoder,e)}writeLen(e){Kr(this.restEncoder,e)}writeAny(e){Qr(this.restEncoder,e)}writeBuf(e){Gr(this.restEncoder,e)}writeJSON(e){qr(this.restEncoder,JSON.stringify(e))}writeKey(e){qr(this.restEncoder,e)}}class ks{constructor(){this.restEncoder=Br(),this.dsCurrVal=0}toUint8Array(){return Fr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,Kr(this.restEncoder,t)}writeDsLen(e){0===e&&li(),Kr(this.restEncoder,e-1),this.dsCurrVal+=e}}class Ss extends ks{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new ii,this.clientEncoder=new ni,this.leftClockEncoder=new ii,this.rightClockEncoder=new ii,this.infoEncoder=new ei(Vr),this.stringEncoder=new si,this.parentInfoEncoder=new ei(Vr),this.typeRefEncoder=new ni,this.lenEncoder=new ni}toUint8Array(){const e=Br();return Kr(e,0),Gr(e,this.keyClockEncoder.toUint8Array()),Gr(e,this.clientEncoder.toUint8Array()),Gr(e,this.leftClockEncoder.toUint8Array()),Gr(e,this.rightClockEncoder.toUint8Array()),Gr(e,Fr(this.infoEncoder)),Gr(e,this.stringEncoder.toUint8Array()),Gr(e,Fr(this.parentInfoEncoder)),Gr(e,this.typeRefEncoder.toUint8Array()),Gr(e,this.lenEncoder.toUint8Array()),Yr(e,Fr(this.restEncoder)),Fr(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Qr(this.restEncoder,e)}writeBuf(e){Gr(this.restEncoder,e)}writeJSON(e){Qr(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const Es=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{Ms(t,n)>e&&r.set(n,e)})),$s(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),Kr(e.restEncoder,r.size),wr(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=Ir(r,t[0].id.clock);const i=Fs(t,r);Kr(e.restEncoder,t.length-i),e.writeClient(n),Kr(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)}))},xs=(e,t,n,r=new bs(e))=>Zs(t,(e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=pr(),r=gi(e.restDecoder);for(let i=0;i<r;i++){const r=gi(e.restDecoder),i=new Array(r),s=e.readClient();let o=gi(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new lc(js(s,o),t),o+=t;break}case 10:{const t=gi(e.restDecoder);i[n]=new Uc(js(s,o),t),o+=t;break}default:{const c=0==(192&r),l=new Oc(js(s,o),null,(r&Or)===Or?e.readLeftID():null,null,(r&Ar)===Ar?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,c&&32==(32&r)?e.readString():null,Dc(e,r));i[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=wr(n.keys()).sort(((e,t)=>e-t));if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const c=new Ns,l=new Map,a=(e,t)=>{const n=l.get(e);(null==n||n>t)&&l.set(e,t)};let u=o.refs[o.i++];const d=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,c.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):c.clients.set(t,[e]),i=i.filter((e=>e!==t))}r.length=0};for(;;){if(u.constructor!==Uc){const i=yr(d,u.id.client,(()=>Ms(t,u.id.client)))-u.id.clock;if(i<0)r.push(u),a(u.id.client,u.id.clock-1),h();else{const s=u.getMissing(e,t);if(null!==s){r.push(u);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){u=e.refs[e.i++];continue}a(s,Ms(t,s)),h()}else(0===i||i<u.length)&&(u.integrate(e,i),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(null!==o&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=s(),null===o)break;u=o.refs[o.i++]}}if(c.clients.size>0){const e=new Ss;return Es(e,c,new Map),Kr(e.restEncoder,0),{missing:l,update:e.toUint8Array()}}return null})(e,i,s),c=i.pendingStructs;if(c){for(const[e,n]of c.missing)if(n<Ms(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=c.missing.get(e);(null==n||n>t)&&c.missing.set(e,t)}c.update=ro([c.update,o.update])}}else i.pendingStructs=o;const l=gs(r,e,i);if(i.pendingDs){const t=new bs(hi(i.pendingDs));gi(t.restDecoder);const n=gs(t,e,i);i.pendingDs=l&&n?ro([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,Is(e.doc,t)}}),n,!1),Is=(e,t,n,r=bs)=>{const i=hi(t);xs(i,e,n,new r(i))};class Cs{constructor(){this.l=[]}}const As=()=>new Cs,Os=(e,t)=>e.l.push(t),Ds=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},Ts=(e,t,n)=>Bi(e.l,[t,n]);class Us{constructor(e,t){this.client=e,this.clock=t}}const Ps=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,js=(e,t)=>new Us(e,t),Ls=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ds(t.ds,e.id),Rs=(e,t)=>{const n=yr(e.meta,Rs,vr),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<Ms(r,n)&&Ks(e,js(n,t))})),us(e,t.ds,(e=>{})),n.add(t))};class Ns{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const $s=e=>{const t=new Map;return e.clients.forEach(((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)})),t},Ms=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},Bs=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw li()}n.push(t)},Fs=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Sr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=Sr((n+r)/2)}throw li()},Ws=(e,t)=>{const n=e.clients.get(t.client);return n[Fs(n,t.clock)]},Vs=(e,t,n)=>{const r=Fs(t,n),i=t[r];return i.id.clock<n&&i instanceof Oc?(t.splice(r+1,0,Ac(e,i,n-i.id.clock)),r+1):r},Ks=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Vs(e,n,t.clock)]},Hs=(e,t,n)=>{const r=t.clients.get(n.client),i=Fs(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==lc&&r.splice(i+1,0,Ac(e,s,n.clock-s.id.clock+1)),s},zs=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,c=Vs(e,t,n);do{o=t[c++],s<o.id.clock+o.length&&Vs(e,t,s),i(o)}while(c<t.length&&t[c].id.clock<s)};class Js{constructor(e,t,n){this.doc=e,this.deleteSet=new as,this.beforeState=$s(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const qs=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1})(t.afterState,((e,n)=>t.beforeState.get(n)!==e)))&&(hs(t.deleteSet),((e,t)=>{Es(e,t.doc.store,t.beforeState)})(e,t),ps(e,t.deleteSet),!0),Ys=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&yr(e.changed,t,vr).add(n)},Gs=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--i-1])n instanceof Oc&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},Xs=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{hs(s),n.afterState=$s(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach(((t,r)=>e.push((()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})))),e.push((()=>{n.changedParentTypes.forEach(((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter((e=>null===e.target._item||!e.target._item.deleted))).forEach((e=>{e.currentTarget=t,e._path=null})),e.sort(((e,t)=>e.path.length-t.path.length)),Ts(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),Bi(e,[]),n._needFormattingCleanup&&Xo(n)}finally{r.gc&&((e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=Fs(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof Oc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}})(s,i,r.gcFilter),((e,t)=>{e.clients.forEach(((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=xr(r.length-1,1+Fs(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Gs(r,e)}}))})(s,i),n.afterState.forEach(((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=Ir(Fs(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Gs(e,t)}}));for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=Fs(r,n);s+1<r.length&&Gs(r,s+1)>1||s>0&&Gs(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{ss.forEach((t=>t.print(e)))})(rs,Gi,"[yjs] ",Xi,ts,"Changed the client-id because another client seems to be using it."),r.clientID=ys()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new _s;qs(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Ss;qs(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:c,subdocsLoaded:l,subdocsRemoved:a}=n;(c.size>0||a.size>0||l.size>0)&&(c.forEach((e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)})),a.forEach((e=>r.subdocs.delete(e))),r.emit("subdocs",[{loaded:l,added:c,removed:a},r,n]),a.forEach((e=>e.destroy()))),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Xs(e,t+1)}}},Zs=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new Js(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&Xs(i,0)}}return o};class Qs{constructor(e,t){this.gen=function*(e){const t=gi(e.restDecoder);for(let n=0;n<t;n++){const t=gi(e.restDecoder),n=e.readClient();let r=gi(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=gi(e.restDecoder);yield new Uc(js(n,r),t),r+=t}else if(0!=(31&t)){const i=0==(192&t),s=new Oc(js(n,r),null,(t&Or)===Or?e.readLeftID():null,null,(t&Ar)===Ar?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&32==(32&t)?e.readString():null,Dc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new lc(js(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===Uc);return this.curr}}class eo{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const to=(e,t=ks,n=bs)=>{const r=new t,i=new Qs(new n(hi(e)),!1);let s=i.curr;if(null!==s){let e=0,t=s.id.client,n=0!==s.id.clock,o=n?0:s.id.clock+s.length;for(;null!==s;s=i.next())t!==s.id.client&&(0!==o&&(e++,Kr(r.restEncoder,t),Kr(r.restEncoder,o)),t=s.id.client,o=0,n=0!==s.id.clock),s.constructor===Uc&&(n=!0),n||(o=s.id.clock+s.length);0!==o&&(e++,Kr(r.restEncoder,t),Kr(r.restEncoder,o));const c=Br();return Kr(c,e),((e,t)=>{Yr(e,Fr(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return Kr(r.restEncoder,0),r.toUint8Array()},no=(e,t)=>{if(e.constructor===lc){const{client:n,clock:r}=e.id;return new lc(js(n,r+t),e.length-t)}if(e.constructor===Uc){const{client:n,clock:r}=e.id;return new Uc(js(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new Oc(js(r,i+t),null,js(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},ro=(e,t=bs,n=Ss)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(hi(e))));let i=r.map((e=>new Qs(e,!0))),s=null;const o=new n,c=new eo(o);for(;i=i.filter((e=>null!==e.curr)),i.sort(((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Uc?1:-1:n}return t.curr.id.client-e.curr.id.client})),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)so(c,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===Uc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{so(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new Uc(js(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===Uc?s.struct.length-=t:n=no(n,t)),s.struct.mergeWith(n)||(so(c,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==Uc;n=e.next())so(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(so(c,s.struct,s.offset),s=null),oo(c);const l=r.map((e=>(e=>{const t=new as,n=gi(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=gi(e.restDecoder),r=gi(e.restDecoder);if(r>0){const i=yr(t.clients,n,(()=>[]));for(let t=0;t<r;t++)i.push(new ls(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new as;for(let n=0;n<e.length;n++)e[n].clients.forEach(((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)br(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}}));return hs(t),t})(l);return ps(o,a),o.toUint8Array()},io=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Fr(e.encoder.restEncoder)}),e.encoder.restEncoder=Br(),e.written=0)},so=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&io(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Kr(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},oo=e=>{io(e);const t=e.encoder.restEncoder;Kr(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];Kr(t,r.written),Yr(t,r.restEncoder)}},co="You must not compute changes after the event-handler fired.";class lo{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=ao(this.currentTarget,this.target))}deletes(e){return ds(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw oi(co);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=mr(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=mr(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=mr(r.content.getContent())}e.set(n,{action:i,oldValue:s})}})),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw oi(co);const t=this.target,n=vr(),r=vr(),i=[];e={added:n,deleted:r,delta:i,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}}const ao=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},uo=()=>{((...e)=>{e.unshift(rs),ss.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let ho=0;class fo{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ho++}}const po=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ho++},go=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce(((e,n)=>Er(t-e.index)<Er(t-n.index)?e:n));let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=ho++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&Er(n.index-i)<r.parent.length/80?(po(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return po(r,t,n),r}{const r=new fo(t,n);return e.push(r),r}})(e._searchMarker,r,i)},yo=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=Ir(t,i.index+n))}},vo=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;yr(i,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;Ts(r._eH,n,t)};class mo{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=As(),this._dEH=As(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw ci()}clone(){throw ci()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Os(this._eH,e)}observeDeep(e){Os(this._dEH,e)}unobserve(e){Ds(this._eH,e)}unobserveDeep(e){Ds(this._dEH,e)}toJSON(){}}const bo=(e,t,n)=>{e.doc??uo(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},wo=e=>{e.doc??uo();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},_o=(e,t)=>{let n=0,r=e._start;for(e.doc??uo();null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},ko=(e,t)=>{const n=[];return _o(e,((r,i)=>{n.push(t(r,i,e))})),n},So=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Eo=(e,t)=>{e.doc??uo();const n=go(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},xo=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,c=s.store,l=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(i=new Oc(js(o,Ms(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new vc(a)),i.integrate(e,0),a=[])};r.forEach((n=>{if(null===n)a.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(n);break;default:switch(u(),n.constructor){case Uint8Array:case ArrayBuffer:i=new Oc(js(o,Ms(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new ac(new Uint8Array(n))),i.integrate(e,0);break;case vs:i=new Oc(js(o,Ms(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new hc(n)),i.integrate(e,0);break;default:if(!(n instanceof mo))throw new Error("Unexpected content type in insert operation");i=new Oc(js(o,Ms(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Cc(n)),i.integrate(e,0)}}})),u()},Io=()=>oi("Length exceeded!"),Co=(e,t,n,r)=>{if(n>t._length)throw Io();if(0===n)return t._searchMarker&&yo(t._searchMarker,n,r.length),xo(e,t,null,r);const i=n,s=go(t,n);let o=t._start;for(null!==s&&(o=s.p,0===(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Ks(e,js(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&yo(t._searchMarker,i,r.length),xo(e,t,o,r)},Ao=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=go(t,n);let c=t._start;for(null!==o&&(c=o.p,n-=o.index);null!==c&&n>0;c=c.right)!c.deleted&&c.countable&&(n<c.length&&Ks(e,js(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&Ks(e,js(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw Io();t._searchMarker&&yo(t._searchMarker,i,-s+r)},Oo=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Do=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let c;if(null==r)c=new vc([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new vc([r]);break;case Uint8Array:c=new ac(r);break;case vs:c=new hc(r);break;default:if(!(r instanceof mo))throw new Error("Unexpected content type");c=new Cc(r)}new Oc(js(o,Ms(s.store,o)),i,i&&i.lastId,null,null,t,n,c).integrate(e,0)},To=(e,t)=>{e.doc??uo();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Uo=e=>{const t={};return e.doc??uo(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Po=(e,t)=>{e.doc??uo();const n=e._map.get(t);return void 0!==n&&!n.deleted},jo=e=>(e.doc??uo(),((e,t)=>os((()=>{let n;do{n=e.next()}while(!n.done&&!t(n.value));return n})))(e._map.entries(),(e=>!e[1].deleted)));class Lo extends lo{}class Ro extends mo{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Ro;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ro}clone(){const e=new Ro;return e.insert(0,this.toArray().map((e=>e instanceof mo?e.clone():e))),e}get length(){return this.doc??uo(),this._length}_callObserver(e,t){super._callObserver(e,t),vo(this,e,new Lo(this,e))}insert(e,t){null!==this.doc?Zs(this.doc,(n=>{Co(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Zs(this.doc,(t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce(((e,t)=>t.index>e.index?t:e),{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;xo(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Zs(this.doc,(n=>{Ao(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return Eo(this,e)}toArray(){return wo(this)}slice(e=0,t=this.length){return bo(this,e,t)}toJSON(){return this.map((e=>e instanceof mo?e.toJSON():e))}map(e){return ko(this,e)}forEach(e){_o(this,e)}[Symbol.iterator](){return So(this)}_write(e){e.writeTypeRef(wc)}}class No extends lo{constructor(e,t,n){super(e,t),this.keysChanged=n}}class $o extends mo{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach(((e,t)=>{this.set(t,e)})),this._prelimContent=null}_copy(){return new $o}clone(){const e=new $o;return this.forEach(((t,n)=>{e.set(n,t instanceof mo?t.clone():t)})),e}_callObserver(e,t){vo(this,e,new No(this,e,t))}toJSON(){this.doc??uo();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof mo?r.toJSON():r}})),e}get size(){return[...jo(this)].length}keys(){return cs(jo(this),(e=>e[0]))}values(){return cs(jo(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return cs(jo(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??uo(),this._map.forEach(((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)}))}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?Zs(this.doc,(t=>{Oo(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Zs(this.doc,(n=>{Do(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return To(this,e)}has(e){return Po(this,e)}clear(){null!==this.doc?Zs(this.doc,(e=>{this.forEach((function(t,n,r){Oo(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(_c)}}const Mo=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&Ni(e,t);class Bo{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&li(),this.right.content.constructor===pc)this.right.deleted||Ko(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const Fo=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===pc)t.right.deleted||Ko(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Ks(e,js(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},Wo=(e,t,n,r)=>{const i=new Map,s=r?go(t,n):null;if(s){const t=new Bo(s.p.left,s.p,s.index,i);return Fo(e,t,n-s.index)}{const r=new Bo(null,t._start,0,i);return Fo(e,r,n)}},Vo=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===pc&&Mo(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach(((r,o)=>{const c=n.left,l=n.right,a=new Oc(js(s,Ms(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new pc(o,r));a.integrate(e,0),n.right=a,n.forward()}))},Ko=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Ho=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===pc&&Mo(t[e.right.content.key]??null,e.right.content.value));)e.forward()},zo=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const c in r){const l=r[c],a=n.currentAttributes.get(c)??null;if(!Mo(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new Oc(js(s,Ms(i.store,s)),r,r&&r.lastId,u,u&&u.id,t,null,new pc(c,l)),n.right.integrate(e,0),n.forward()}}return o},Jo=(e,t,n,r,i)=>{n.currentAttributes.forEach(((e,t)=>{void 0===i[t]&&(i[t]=null)}));const s=e.doc,o=s.clientID;Ho(n,i);const c=zo(e,t,n,i),l=r.constructor===String?new mc(r):r instanceof mo?new Cc(r):new fc(r);let{left:a,right:u,index:d}=n;t._searchMarker&&yo(t._searchMarker,n.index,l.getLength()),u=new Oc(js(o,Ms(s.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,l),u.integrate(e,0),n.right=u,n.index=d,n.forward(),Vo(e,t,n,c)},qo=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;Ho(n,i);const c=zo(e,t,n,i);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===pc));){if(!n.right.deleted)switch(n.right.content.constructor){case pc:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(Mo(o,s))c.delete(t);else{if(0===r)break e;c.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&Ks(e,js(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new Oc(js(o,Ms(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new mc(i)),n.right.integrate(e,0),n.forward()}Vo(e,t,n,c)},Yo=(e,t,n,r,i)=>{let s=t;const o=pr();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===pc){const e=s.content;o.set(e.key,e)}s=s.right}let c=0,l=!1;for(;t!==s;){if(n===t&&(l=!0),!t.deleted){const n=t.content;switch(n.constructor){case pc:{const{key:s,value:a}=n,u=r.get(s)??null;o.get(s)===n&&u!==a||(t.delete(e),c++,l||(i.get(s)??null)!==a||u===a||(null===u?i.delete(s):i.set(s,u))),l||t.deleted||Ko(i,n);break}}}t=t.right}return c},Go=e=>{let t=0;return Zs(e.doc,(n=>{let r=e._start,i=e._start,s=pr();const o=gr(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===pc)Ko(o,i.content);else t+=Yo(n,r,i,s,o),s=gr(o),r=i;i=i.right}})),t},Xo=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&zs(e,n.store.clients.get(r),s,i,(e=>{e.deleted||e.content.constructor!==pc||e.constructor===lc||t.add(e.parent)}))}Zs(n,(n=>{us(e,e.deleteSet,(e=>{if(e instanceof lc||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===pc?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===pc){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)Go(e)}))},Zo=(e,t,n)=>{const r=n,i=gr(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Cc:case fc:case mc:n<t.right.length&&Ks(e,js(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&Yo(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&yo(o._searchMarker,t.index,-r+n),t};class Qo extends lo{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach((e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)}))}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];Zs(e,(e=>{const n=new Map,r=new Map;let i=this.target._start,s=null;const o={};let c="",l=0,a=0;const u=()=>{if(null!==s){let e=null;switch(s){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof c||c.length>0)&&(e={insert:c},n.size>0&&(e.attributes={},n.forEach(((t,n)=>{null!==t&&(e.attributes[n]=t)})))),c="";break;case"retain":l>0&&(e={retain:l},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=ji({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Cc:case fc:this.adds(i)?this.deletes(i)||(u(),s="insert",c=i.content.getContent()[0],u()):this.deletes(i)?("delete"!==s&&(u(),s="delete"),a+=1):i.deleted||("retain"!==s&&(u(),s="retain"),l+=1);break;case mc:this.adds(i)?this.deletes(i)||("insert"!==s&&(u(),s="insert"),c+=i.content.str):this.deletes(i)?("delete"!==s&&(u(),s="delete"),a+=i.length):i.deleted||("retain"!==s&&(u(),s="retain"),l+=i.length);break;case pc:{const{key:t,value:c}=i.content;if(this.adds(i)){if(!this.deletes(i)){const l=n.get(t)??null;Mo(l,c)?null!==c&&i.delete(e):("retain"===s&&u(),Mo(c,r.get(t)??null)?delete o[t]:o[t]=c)}}else if(this.deletes(i)){r.set(t,c);const e=n.get(t)??null;Mo(e,c)||("retain"===s&&u(),o[t]=e)}else if(!i.deleted){r.set(t,c);const n=o[t];void 0!==n&&(Mo(n,c)?null!==n&&i.delete(e):("retain"===s&&u(),null===c?delete o[t]:o[t]=c))}i.deleted||("insert"===s&&u(),Ko(n,i.content));break}}i=i.right}for(u();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}})),this._delta=t}return this._delta}}class ec extends mo{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??uo(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new ec}clone(){const e=new ec;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new Qo(this,e,t);vo(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??uo();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===mc&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Zs(this.doc,(n=>{const r=new Bo(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Jo(n,this,r,o,s.attributes||{})}else void 0!==s.retain?qo(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&Zo(n,r,s.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??uo();const r=[],i=new Map,s=this.doc;let o="",c=this._start;function l(){if(o.length>0){const e={};let t=!1;i.forEach(((n,r)=>{t=!0,e[r]=n}));const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==c;){if(Ls(c,e)||void 0!==t&&Ls(c,t))switch(c.content.constructor){case mc:{const r=i.get("ychange");void 0===e||Ls(c,e)?void 0===t||Ls(c,t)?void 0!==r&&(l(),i.delete("ychange")):void 0!==r&&r.user===c.id.client&&"added"===r.type||(l(),i.set("ychange",n?n("added",c.id):{type:"added"})):void 0!==r&&r.user===c.id.client&&"removed"===r.type||(l(),i.set("ychange",n?n("removed",c.id):{type:"removed"})),o+=c.content.str;break}case Cc:case fc:{l();const e={insert:c.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach(((e,n)=>{t[n]=e}))}r.push(e);break}case pc:Ls(c,e)&&(l(),Ko(i,c.content))}c=c.right}l()};return e||t?Zs(s,(n=>{e&&Rs(n,e),t&&Rs(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Zs(r,(r=>{const i=Wo(r,this,e,!n);n||(n={},i.currentAttributes.forEach(((e,t)=>{n[t]=e}))),Jo(r,this,i,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?Zs(r,(r=>{const i=Wo(r,this,e,!n);Jo(r,this,i,t,n||{})})):this._pending.push((()=>this.insertEmbed(e,t,n||{})))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?Zs(n,(n=>{Zo(n,Wo(n,this,e,!0),t)})):this._pending.push((()=>this.delete(e,t)))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?Zs(r,(r=>{const i=Wo(r,this,e,!1);null!==i.right&&qo(r,this,i,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?Zs(this.doc,(t=>{Oo(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?Zs(this.doc,(n=>{Do(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return To(this,e)}getAttributes(){return Uo(this)}_write(e){e.writeTypeRef(kc)}}class tc{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??uo()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==rc&&t.constructor!==nc||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class nc extends mo{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new nc}clone(){const e=new nc;return e.insert(0,this.toArray().map((e=>e instanceof mo?e.clone():e))),e}get length(){return this.doc??uo(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new tc(this,e)}querySelector(e){e=e.toUpperCase();const t=new tc(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),wr(new tc(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){vo(this,e,new ic(this,t,e))}toString(){return ko(this,(e=>e.toString())).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),_o(this,(i=>{r.insertBefore(i.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?Zs(this.doc,(n=>{Co(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Zs(this.doc,(n=>{const r=e&&e instanceof mo?e._item:e;xo(n,this,r,t)}));else{const n=this._prelimContent,r=null===e?0:n.findIndex((t=>t===e))+1;if(0===r&&null!==e)throw oi("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Zs(this.doc,(n=>{Ao(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return wo(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Eo(this,e)}slice(e=0,t=this.length){return bo(this,e,t)}forEach(e){_o(this,e)}_write(e){e.writeTypeRef(Ec)}}class rc extends nc{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach(((e,t)=>{this.setAttribute(t,e)})),this._prelimAttrs=null}_copy(){return new rc(this.nodeName)}clone(){const e=new rc(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),((t,n)=>{"string"==typeof t&&e.setAttribute(n,t)})),e.insert(0,this.toArray().map((e=>e instanceof mo?e.clone():e))),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let i=0;i<r;i++){const r=n[i];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?Zs(this.doc,(t=>{Oo(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Zs(this.doc,(n=>{Do(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return To(this,e)}hasAttribute(e){return Po(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach(((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&Ls(i,t)&&(n[r]=i.content.getContent()[i.length-1])})),n})(this,e):Uo(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const e in i){const t=i[e];"string"==typeof t&&r.setAttribute(e,t)}return _o(this,(i=>{r.appendChild(i.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Sc),e.writeKey(this.nodeName)}}class ic extends lo{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach((e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)}))}}class sc extends $o{constructor(e){super(),this.hookName=e}_copy(){return new sc(this.hookName)}clone(){const e=new sc(this.hookName);return this.forEach(((t,n)=>{e.set(n,t)})),e}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(xc),e.writeKey(this.hookName)}}class oc extends ec{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new oc}clone(){const e=new oc;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map((e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort(((e,t)=>e.key<t.key?-1:1)),t.push({nodeName:n,attrs:r})}t.sort(((e,t)=>e.nodeName<t.nodeName?-1:1));let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n})).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Ic)}}class cc{constructor(e,t){this.id=e,this.length=t}get deleted(){throw ci()}mergeWith(e){return!1}write(e,t,n){throw ci()}integrate(e,t){throw ci()}}class lc extends cc{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),Bs(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class ac{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ac(this.content)}splice(e){throw ci()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class uc{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new uc(this.len)}splice(e){const t=new uc(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){fs(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const dc=(e,t)=>new vs({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class hc{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new hc(dc(this.doc.guid,this.opts))}splice(e){throw ci()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class fc{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new fc(this.embed)}splice(e){throw ci()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class pc{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new pc(this.key,this.value)}splice(e){throw ci()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class gc{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new gc(this.arr)}splice(e){const t=new gc(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}const yc="development"===Ki("node_env");class vc{constructor(e){this.arr=e,yc&&Mi(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new vc(this.arr)}splice(e){const t=new vc(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class mc{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new mc(this.str)}splice(e){const t=new mc(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const bc=[e=>new Ro,e=>new $o,e=>new ec,e=>new rc(e.readKey()),e=>new nc,e=>new sc(e.readKey()),e=>new oc],wc=0,_c=1,kc=2,Sc=3,Ec=4,xc=5,Ic=6;class Cc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Cc(this.type._copy())}splice(e){throw ci()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach((t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)})),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach((t=>{for(;null!==t;)t.gc(e,!0),t=t.left})),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const Ac=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new Oc(js(r,i+n),t,js(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=js(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s};class Oc extends cc{constructor(e,t,n,r,i,s,o,c){super(e,c.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=c,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=Ms(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Ms(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Us&&this.id.client!==this.parent.client&&this.parent.clock>=Ms(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Hs(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Ks(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===lc||this.right&&this.right.constructor===lc)this.parent=null;else if(this.parent){if(this.parent.constructor===Us){const e=Ws(t,this.parent);e.constructor===lc?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===Oc?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Oc&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Hs(e,e.doc.store,js(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,i=new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),Ps(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Ps(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(Ws(e.doc.store,t.origin)))break;r.has(Ws(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),Bs(e.doc.store,this),this.content.integrate(e,this),Ys(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new lc(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:js(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Ps(e.origin,this.lastId)&&this.right===e&&Ps(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach((t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))})),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),fs(e.deleteSet,this.id.client,this.id.clock,this.length),Ys(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw li();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[Fs(r,t.id.clock)]=n})(e,this,new lc(this.id,this.length)):this.content=new uc(this.length)}write(e,t){const n=t>0?js(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:Or)|(null===r?0:Ar)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=(e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw li()})(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Us?(e.writeParentInfo(!1),e.writeLeftID(t)):li();null!==i&&e.writeString(i)}this.content.write(e,t)}}const Dc=(e,t)=>Tc[31&t](e),Tc=[()=>{li()},e=>new uc(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new gc(n)},e=>new ac(e.readBuf()),e=>new mc(e.readString()),e=>new fc(e.readJSON()),e=>new pc(e.readKey(),e.readJSON()),e=>new Cc(bc[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new vc(n)},e=>new hc(dc(e.readString(),e.readAny())),()=>{li()}];class Uc extends cc{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){li()}write(e,t){e.writeInfo(10),Kr(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Pc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},jc="__ $YJS$ __";function Lc(e,t,n){var r,i,s;if(!e.dx._allTables[t])return;const o=null===(s=null===(i=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===i?void 0:i.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}Pc[jc],Pc[jc]=!0;const Rc=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function Nc(e){var t,n;return null!==(t=(n=e._novip)._docCache)&&void 0!==t?t:n._docCache={cache:{},get size(){return Object.keys(this.cache).length},find(e,t,n){const r=Bc(e,t,n),i=this.cache[r];return i?i.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:i}=e.meta;if(!n||!i||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const s=Bc(n,r,i),o=null===(t=this.cache[s])||void 0===t?void 0:t.deref();o&&Rc.unregister(o),this.cache[s]=new WeakRef(e),Rc.register(e,{cache:this.cache,key:s},e)},delete(e){Rc.unregister(e);const t=Bc(e.meta.parentTable,e.meta.parentId,e.meta.parentProp),n=this.cache[t];(null==n?void 0:n.deref())===e&&delete this.cache[t]}}}const $c=new WeakSet;function Mc(e){if($c.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Bc(e,t,n){return`${e}[${t}].${n}`}let Fc=null;function Wc(e){Fc=e}function Vc(){}const Kc=new WeakMap;function Hc(){return r.Events(null,"load","sync","error")}class zc{static getOrCreateDocument(e,t,n,r){var i,s;const o=Nc(e),c=null===(s=null===(i=e.table(t).schema.yProps)||void 0===i?void 0:i.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;if(!c)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,i,s){let o=t.find(n,s,r);return o||(o=new vs({meta:{db:e,updatesTable:i,parentProp:r,parentTable:n,parentId:s}}),t.add(o),o.on("destroy",(()=>{$c.add(o),t.delete(o)})),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=Kc.get(e);return r?(++r.refCount,null!=(null==t?void 0:t.gracePeriod)&&r.graceTimeout<t.gracePeriod&&(r.graceTimeout=t.gracePeriod),r.graceTimer&&(clearTimeout(r.graceTimer),r.graceTimer=null)):(r=new zc(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Kc.set(e,r)),r}static release(e){if(!e||$c.has(e))return;const t=Kc.get(e);t?--t.refCount<=0&&(t.graceTimeout<0?t._release():t.graceTimer||(t.graceTimer=setTimeout((()=>{t.graceTimer=null,0===t.refCount&&t._release()}),t.graceTimeout))):e.destroy()}_release(){this.doc&&Promise.resolve(zc.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return Kc.get(e)}static get currentUpdateRow(){return Fc}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((e,t)=>{this.doc?this.doc.isLoaded?e():this._error?t(this._error):$c.has(this.doc)?t(new r.AbortError("Document was destroyed before loaded")):(this.on("load",e),this.on("error",t),this.doc.on("destroy",(()=>t(new r.AbortError("Document was destroyed before loaded"))))):t(new Error("No Y.Doc associated with this provider"))}))),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise(((e,t)=>{this.doc?this.doc.isSynced?e():this._error?t(this._error):$c.has(this.doc)?t(new r.AbortError("Document was destroyed before synced")):(this.on("sync",e),this.on("error",t),this.doc.on("destroy",(()=>t(new r.AbortError("Document was destroyed before synced"))))):t(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(e){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Hc(),this.doc=e,this.off=(e,t)=>{var n;return null===(n=this.on[e])||void 0===n?void 0:n.unsubscribe(t)},"dispose"in Symbol&&(this[Symbol.dispose]=()=>zc.release(e)),e.on("load",(()=>this.on("load").fire())),e.on("sync",(e=>!1!==e&&this.on("sync").fire())),e.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:t,parentTable:r,parentId:s,updatesTable:o}=e.meta||{};if(!t||!r||!o)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!t.table(r)||!t.table(o))throw new Error(`Table ${r} or ${o} not found in db`);Mc(e),this.stopObserving=function(e,t,r,s,o,c){let l=0,a=!0;const u=i((()=>{Mc(t);const e=r.table(o);return Promise.all([(l>0?e.where("i").between(l,1/0,!1).toArray().then((e=>e.filter((e=>0===n(e.k,c))))):e.where({k:c}).toArray()).then((e=>e)),r.table(s).where(":id").equals(c).toArray()])})).subscribe((([n,r])=>{n.length>0&&(l=n[n.length-1].i),0!==r.length?(Mc(t),n.length>0&&Zs(t,(()=>{n.forEach((e=>{try{Wc(e),Is(t,e.u)}finally{Wc(null)}}))}),e,!1),a&&(a=!1,t.emit("load",[t]))):t.destroy()}),(t=>{e.on("error").fire(t)})),d=(t,n)=>{n!==e&&r.table(o).add({k:c,u:t,f:1}).then((e=>{e===l-1&&++l})).catch((t=>{e.on("error").fire(t)}))},h=()=>{u.unsubscribe(),t.off("updateV2",d),t.off("destroy",h)};return t.on("updateV2",d),t.on("destroy",h),h}(this,e,t,r,o,s),zc.on("new").fire(this)}destroy(){var e;Kc.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Hc(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Jc(e,t){return C(this,void 0,void 0,(function*(){var r;const i={};let s,o=!1;for(const c of e)try{switch(c.type){case"u-s":{const e=Lc(t,c.table,c.prop);if(e){const t={k:c.k,u:c.u};c.r&&(t.r=c.r,s=c.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=Lc(t,c.table,c.prop);e&&(yield t.transaction("rw",e,(t=>C(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(hr);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:hr}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})))));break}case"u-reject":{const e=Lc(t,c.table,c.prop);if(!e)break;const i=null===(r=yield e.get(c.i))||void 0===r?void 0:r.k;if(null!=i){yield t.transaction("rw",e,(t=>(t.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(c.i).filter((e=>0===n(e.k,i)&&1==(1&(e.f||0)))).delete())));const r=zc.getDocCache(t.dx).find(c.table,i,c.prop);r&&r.destroy()}break}case"in-sync":{const e=zc.getDocCache(t.dx).find(c.table,c.k,c.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":s=c.yServerRev;break;case"outdated-server-rev":o=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:o,yServerRevision:s}}))}zc.on=r.Events(null,{new:[function(e,t){return e===Vc?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Vc?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,i=arguments.length,s=new Array(i);i--;)s[i]=arguments[i];return n.then((function(){return t.apply(r,s)}))}return t.apply(this,arguments)}}]}),zc.getDocCache=Nc,r.DexieYProvider=zc;const qc=1,Yc=2,Gc=3;function Xc(t,n,r){return C(this,arguments,void 0,(function*(t,n,{yDownloadedRealms:r,realms:i}){if(r&&i&&i.every((e=>"*"===r[e])))return;const s=yield Qt(t),o={"Content-Type":"application/json",Accept:"application/octet-stream"};s&&(o.Authorization=`Bearer ${s.accessToken}`);const c=yield fetch(`${n}/y/download`,{body:Qn.stringify({downloadedRealms:r||{}}),method:"POST",headers:o,credentials:"include"});if(!c.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${c.status}`);yield async function(e,...t){var n,r,i;let s=e();for(let e=0;e<t.length;e++)s=t[e](s);try{for(var o,c=!0,l=j(s);!(n=(o=await l.next()).done);c=!0)o.value,c=!1}catch(e){r={error:e}}finally{try{c||n||!(i=l.return)||await i.call(l)}finally{if(r)throw r.error}}}(function(e){return function(){return P(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield U(t.read());if(e)return yield U(void 0);yield yield U(n)}}finally{t.releaseLock()}}))}}(c),xe,(function(r){return P(this,arguments,(function*(){var i,s,o,c;let l=null,a=null,u=null,d=[];function h(e){return C(this,void 0,void 0,(function*(){const r=d[d.length-1];if(d.length>0){if(!l||!a||!u)throw new Error(`Protocol error from ${n}/y/download`);const e=Lc(t,a,u);e&&(yield e.bulkAdd(d)),d=[]}l&&(a&&u&&r||e)&&(yield t.$syncState.update("syncState",(t=>{const n=t.yDownloadedRealms||{};n[l]=e?"*":{tbl:a,prop:u,key:r.k},t.yDownloadedRealms=n})))}))}try{try{for(var f,p=!0,g=j(r);!(i=(f=yield U(g.next())).done);p=!0){c=f.value,p=!1;const e=new ge(c);for(;ye(e);)switch(me(e)){case qc:yield U(h(!0)),l=we(e);break;case Yc:yield U(h(!1)),a=we(e),u=we(e);break;case Gc:{const t=Ee(e),n=ve(e);d.push({k:t,u:n});break}}yield U(h(!1))}}catch(e){s={error:e}}finally{try{p||i||!(o=g.return)||(yield U(o.call(g)))}finally{if(s)throw s.error}}yield U(h(!0))}catch(t){throw t instanceof e.DexieError||(yield U(h(!1))),t}}))}))}))}const Zc="currentSyncWorker";function Qc(e,t,n,r){return el(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((i=>C(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):cr&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise((e=>setTimeout(e,500))),yield Qc(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:cr?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function el(e,t,n){return C(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:s,purpose:o}={isInitialSync:!1}){var c;if(!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:l}=t,a=yield e.getCurrentUser(),u=a.isLoggedIn?mn(e):[],d=u.map((t=>e.table(bn(t.name)))),h=yield e.getPersistedSyncState(),f=a.isLoggedIn,p=f?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return mn(e).filter((e=>!n.includes(e.name)))}(e,h):[];or(i);const g=p.length>0;if(g){if(s)return!0;yield e.transaction("rw",p,(e=>C(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return C(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==sn.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==sn.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==sn.userId||(e.owner=t.userId),e.realmId&&e.realmId!==sn.userId||(e.realmId=t.userId))})))}))}(p,a,null==h?void 0:h.realms)})))),or(i)}const[y,v,m,{yMessages:b,lastUpdateIds:w}]=yield e.transaction("r",e.tables,(()=>C(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>u.some((t=>t.name===e.tableName))));let s=yield Sn(d,e);const o=yield function(e,t){return C(this,void 0,void 0,(function*(){const n=[],r={};for(const i of t)if(i.schema.yProps)for(const t of i.schema.yProps){const s=e.table(t.updatesTable),o=yield s.get(hr),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield fr(s,a);u.length>0&&(r[s.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<c)continue;const n=JSON.stringify(e.k)+"/"+t;let r=d[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(d[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:s,i:o}of Object.values(d)){const c=1===s.length?s[0]:ro(s);if(r)n.push({type:"u-c",table:i.name,prop:t.prop,k:e,u:c,i:o});else{const r=to(c);n.push({type:"sv",table:i.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,u);if(or(i),g){const e=[...(null==h?void 0:h.realms)||[],...(null==h?void 0:h.inviteRealms)||[]],c=yield function(e,t,n,r){return C(this,void 0,void 0,(function*(){const i=`upload-${En(8)}`;if(t.isLoggedIn&&e.length>0){const s=new Set(r||[]);return(yield Promise.all(e.map((e=>C(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const o=n[e.name],c=(null==o?void 0:o.generatedGlobalId)?e.filter((e=>{return r(e),!s.has(e.realmId||"")&&(t=r(e),!(n=null==o?void 0:o.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})):e.filter((e=>{const t=r(e);return!s.has(e.realmId||"")&&M(t)})),l=yield c.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(p,a,n,e);return or(i),s=s.concat(c),[s,t,r,o]}return[s,t,r,o]})))),_=y.some((e=>e.muts.some((e=>e.keys.length>0))))||b.some((e=>"u-c"===e.type));if(s)return _;if("push"===o&&!_)return!1;const k=ar(y,null==v?void 0:v.latestRevisions),S=(null==v?void 0:v.clientIdentity)||N(16);or(i);const E=yield sr(y,b,v,m,e,l,n,S,a),{done:x,newSyncState:I}=yield e.transaction("rw",e.tables,(t=>C(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))E.schema[e]&&(n[e]=E.schema[e]);yield e.$syncState.put(n,"schema");const r=yield Sn(d,e,{since:k});for(const t of d){const n=wn(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(k[n]){const r=k[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}ar(r,k),yield lr(e,n,k,E.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return C(this,void 0,void 0,(function*(){const r=new Set,i=new Set,s=n?n.realms:[],o=n?n.inviteRealms:[],c=new Set(t.realms),l=new Set(t.realms.concat(t.inviteRealms));for(const e of s)c.has(e)||(i.add(e),l.has(e)||r.add(e));for(const e of o.concat(s))l.has(e)||r.add(e);if(r.size>0||i.size>0){const t=mn(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:i;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}if(i.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of i)delete n.yDownloadedRealms[e]}))}(e,E,i);const s=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};f&&(s.syncedTables=u.map((e=>e.name)).concat(p.map((e=>e.name)))),s.latestRevisions=k,s.remoteDbId=E.dbId,s.initiallySynced=!0,s.realms=E.realms,s.inviteRealms=E.inviteRealms,s.serverRevision=E.serverRevision,s.yServerRevision=E.serverRevision,s.timestamp=new Date,delete s.error;const o=tl(E.changes,r);if(yield dr(o,e),E.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield Jc(E.yMessages,e);r&&(s.yServerRevision=r),yield function(e,t,n){return C(this,void 0,void 0,(function*(){var r,i,s,o,c;const l={};for(const[t,n]of Object.entries(e))null!==(r=l[t])&&void 0!==r||(l[t]={}),l[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=l[e])&&void 0!==i||(l[e]={}),l[e].receivedUntil=n;const a=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of a){const t=l[e],r=null!==(s=null==t?void 0:t.unsentFrom)&&void 0!==s?s:1,i=null!==(c=null!==(o=null==t?void 0:t.receivedUntil)&&void 0!==o?o:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==c?c:0;yield n.transaction("rw",e,(()=>C(this,void 0,void 0,(function*(){const t=yield n.table(e).get(hr);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:hr,unsentFrom:r,receivedUntil:i})}))))}}))}(w,t,e),n&&(s.yDownloadedRealms={})}return e.$syncState.put(s,"syncState"),{done:0===r.length,newSyncState:s}}))));if(!x)return yield ir(e),yield el(e,t,n,{isInitialSync:r,cancelToken:i});const A=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),O=!!E.yMessages;if(A&&O)try{yield Xc(e,l,I)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function tl(e,t){const n={};W(n,e);const r={};return W(r,t),function(e,t){var n,r,i;for(const[s,o]of Object.entries(t))for(const[t,c]of Object.entries(o))switch(c.type){case"ups":{const r=null===(n=e[s])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[s][t]}}break;case"del":null===(r=e[s])||void 0===r||delete r[t];break;case"upd":{const n=null===(i=e[s])||void 0===i?void 0:i[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(c.mod))R(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(c.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=N(16));const n={};for(const[t,r]of Object.entries(e))for(const[e,i]of Object.entries(r)){const r=n[t]||(n[t]={});(r[i.type]||(r[i.type]=[])).push(Object.assign({key:e},i))}const r=[];for(const[e,i]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(i))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}const nl=10,rl=1e4,il=1e3;function sl(t){const n=[],r=new u(!0),i=new u(null);let s=!1,c=new Array(nl).fill(0);return i.subscribe((()=>C(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,c.shift(),c.push(Date.now()),r.next(!1);try{yield function(){return C(this,void 0,void 0,(function*(){for(var r,i,s,c,l,a;n.length>0;){const u=n.shift();try{yield o(t.cloud.syncState.pipe(Rt((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!u)continue;switch(u.type){case"token-expired":const o=t.cloud.currentUser.value,d=yield tn(t.cloud.options.databaseUrl,o);yield t.table("$logins").update(o.userId,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(u.realm))||(null===(i=null==n?void 0:n.inviteRealms)||void 0===i?void 0:i.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(s=null==n?void 0:n.realms)||void 0===s?void 0:s.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(c=null==n?void 0:n.realms)||void 0===c?void 0:c.includes(u.realm))||(null===(l=null==n?void 0:n.inviteRealms)||void 0===l?void 0:l.includes(u.realm)))&&(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield t.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(a=t.cloud.syncState.value)||void 0===a?void 0:a.phase)){Vt(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>C(this,void 0,void 0,(function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,i,s]=yield Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(!i||!r||!s)return;if(u.baseRev!==i.serverRevision)return void("string"!=typeof u.baseRev||"bigint"!=typeof i.serverRevision&&"object"!=typeof i.serverRevision||Vt(t,"pull"));if((yield e.waitFor(vn(i)))!==u.realmSetHash)return void Vt(t,"pull");let o=[];if(s.isLoggedIn){const e=mn(t).map((e=>t.table(bn(e.name))));o=yield Sn(e,t)}if(u.changes.length>0){const e=tl(u.changes,o);yield dr(e,t)}i.latestRevisions=ar(o,i.latestRevisions),i.serverRevision=u.newRev,yield lr(t,r,i.latestRevisions,u.newRev),yield t.$syncState.put(i,"syncState")}))))}}catch(e){}}}))}()}finally{c[c.length-1]-c[0]<rl&&(yield new Promise((e=>setTimeout(e,il)))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:r}}const ol=new WeakMap,cl={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let ll=0;function al(e){"vip"in e&&(e=e.vip);let t=ol.get(e.cloud);if(!t){const n=new d;let r=new yn(`syncstatechanged-${e.name}`),i=new yn(`synccomplete-${e.name}`);n.id=++ll;let s=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return s},localSyncEvent:n,get syncStateChangedEvent(){return r},get syncCompleteEvent(){return i},dx:e};const o={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||sn)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){r=new yn(`syncstatechanged-${e.name}`),i=new yn(`synccomplete-${e.name}`)}};Object.assign(t,o),t.messageConsumer=sl(t),t.messageProducer=new d,ol.set(e.cloud,t)}return t}const ul="undefined"!=typeof InstallTrigger,dl="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),hl=dl?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,fl=dl&&hl<=605||ul,pl="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:gl}={};function yl(e){return gl.call(e).slice(8,-1)}function vl(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const ml=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let bl=0;function wl(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),i=Date.now();bl>=i?++bl:bl=i,r[0]=bl/1099511627776,r[1]=bl/4294967296,r[2]=bl/16777216,r[3]=bl/65536,r[4]=bl/256,r[5]=bl;const s=new Uint8Array(n.buffer,6);crypto.getRandomValues(s);return e+Rn(new Uint8Array(n.buffer))+(t||"")}function _l(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const i=n.table(r);return Object.assign(Object.assign({},i),{mutate:n=>{var s,o;const c=n.trans;if("versionchange"===c.mode&&(c.disableChangeTracking=!0,c.disableAccessControl=!0),c.disableChangeTracking)return i.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!t.initiallySynced){const e=vl(i.schema.primaryKey,n);return i.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return i.mutate(n)}))}return function(n,s){let o=null;const c=vl(i.schema.primaryKey,n);return c.forEach(((l,a)=>{if(void 0===l){const r=n.values[a].realmId||t.cloud.currentUserId,l=r.substr(r.length-3);c[a]=wl(s,l),i.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=e.deepClone(o[a]),e.setByKeyPath(o[a],i.schema.primaryKey.keyPath,c[a]))}else if("string"!=typeof l||!l.startsWith(s)&&!l.startsWith("#"+s))throw new e.ConstraintError(`The ID "${l}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${s}" (or "#${s}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),i.mutate(Object.assign(Object.assign({},n),{keys:c,values:o||n.values}))}(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){vl(i.schema.primaryKey,n).forEach(((t,n)=>{if(!M(t)){const n=Array.isArray(t)?t.map(yl).join(","):yl(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return i.mutate(n)}})}})}}let kl=0;function Sl(e,t){return function(n){const{readers:r,writers:i}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),s=i.length,o=(s>0?i[s-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>{r.splice(r.indexOf(o))}));return r.push(o),o}}function El(e,t){return function(n){const{readers:r,writers:i}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let s=(i.length>0?i[i.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(o=r,new Promise((e=>{0===o.length&&e([]);let t=o.length;const n=new Array(t);o.forEach(((r,i)=>Promise.resolve(r).then((e=>n[i]={status:"fulfilled",value:e}),(e=>n[i]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>{i.shift()}));var o;return i.push(s),s}}const xl=new u(new Set);function Il(e){var t,n,r,i;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl)}function Cl({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=new Set(n.schema.tables.map((e=>e.name))),i=n.schema.tables.filter((e=>!/^\$/.test(e.name))),o=new Map;for(const e of i){const t=`$${e.name}_mutations`;r.has(t)&&o.set(e.name,n.table(t))}return Object.assign(Object.assign({},n),{transaction:(r,i)=>{let s;if("readwrite"===i){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>bn(e)));s=n.transaction([...r,...e],i)}else s=n.transaction(r,i);if("readwrite"===i){s.txid=En(16),s.opCount=0,s.currentUser=e.value,xl.value.add(s),xl.next(xl.value);const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",n),s.removeEventListener("abort",n),xl.value.delete(s),xl.next(xl.value)},r=()=>{s.mutationsAdded&&!Il(t)&&Vt(t,"push"),n()};s.addEventListener("complete",r),s.addEventListener("error",n),s.addEventListener("abort",n)}return s},table:e=>{const r=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},r),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),r.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},r),{mutate:e=>r.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):r;const{schema:i}=r,c=o.get(e);return c?function(e){const t="$lock"+ ++kl;return Object.assign(Object.assign({},e),{count:Sl(e.count,t),get:Sl(e.get,t),getMany:Sl(e.getMany,t),openCursor:Sl(e.openCursor,t),query:Sl(e.query,t),mutate:El(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var s,o,c;const a=n.trans;return a.txid?a.disableChangeTracking?r.mutate(n):(null===(o=null===(s=t.cloud.schema)||void 0===s?void 0:s[e])||void 0===o?void 0:o.markedForSync)&&(null===(c=a.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===n.type?r.query({query:{range:n.range,index:i.primaryKey},trans:n.trans,values:!1}).then((e=>l({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):l(n):r.mutate(n):r.mutate(n)}})):r;function l(n){var o,l;const a=n.trans,u=null===(l=null===(o=t.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===l?void 0:l[e],{txid:d,currentUser:{userId:h}}=a,{type:f}=n,p=++a.opCount;function g(e){if(!u)return e;let t=e;for(const n of Object.keys(e))u.some((e=>n===e||n.startsWith(e+".")))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return r.mutate(n).then((e=>{var t;const{numFailures:r,failures:o}=e;let l="delete"===f?n.keys:e.results,y="values"in n?n.values:[],v="changeSpec"in n?n.changeSpec:void 0,m="updates"in n?n.updates:void 0;if(r&&(l=l.filter(((e,t)=>!o[t])),y=y.filter(((e,t)=>!o[t]))),u){if(y=y.map((e=>{const t=Object.assign({},e);for(const e of u)delete t[e];return t})),v&&(v=g(v),0===Object.keys(v).length))return e;if(m){let e=m.changeSpecs.map(g),t={keys:[],changeSpecs:[]};const n=new s;let r=!1;for(let i=0,s=e.length;i<s;++i)Object.keys(e[i]).length>0?(t.keys.push(m.keys[i]),t.changeSpecs.push(e[i]),n.addKey(m.keys[i])):r=!0;if(m=t,r){let e=[],t=[];for(let r=0,i=l.length;r<i;++r)n.hasKey(l[r])&&(e.push(l[r]),t.push(y[r]));l=e,y=t}}}const b=Date.now();let w="criteria"in n&&n.criteria?Object.assign(Object.assign({},n.criteria),{index:n.criteria.index===i.primaryKey.keyPath?null:n.criteria.index}):void 0;if(u&&(null==w?void 0:w.index)){const e=null===(t=i.indexes.find((e=>e.name===w.index)))||void 0===t?void 0:t.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(w=void 0)}const _="delete"===n.type?{type:"delete",ts:b,opNo:p,keys:l,criteria:w,txid:d,userId:h}:"add"===n.type?{type:"insert",ts:b,opNo:p,keys:l,txid:d,userId:h,values:y}:w&&v?{type:"modify",ts:b,opNo:p,keys:l,criteria:w,changeSpec:v,txid:d,userId:h}:v?{type:"update",ts:b,opNo:p,keys:l,changeSpecs:l.map((()=>v)),txid:d,userId:h}:m?{type:"update",ts:b,opNo:p,keys:m.keys,changeSpecs:m.changeSpecs,txid:d,userId:h}:{type:"upsert",ts:b,opNo:p,keys:l,values:y,txid:d,userId:h};return"isAdditionalChunk"in n&&n.isAdditionalChunk&&(_.isAdditionalChunk=!0),l.length>0||w?c.mutate({type:"add",trans:a,values:[_]}).then((()=>(a.mutationsAdded=!0,e))):e}))}}})}}}function Al(e,t){return function(n,r){var i;const s=Object.assign(Object.assign({},cl),n);Object.keys(cl).forEach((e=>{const t=s[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),i=cl[e].split(",").map((e=>e.trim())),o=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==i[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(cl[e])}`);for(let t=1;t<i.length;++t){const n=i[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(s[e]+=`,${n}`)}}));const o=t.cloud.schema||(t.cloud.schema={}),c=new Set;Object.keys(s).forEach((e=>{const t=s[e],n=o[e]||(o[e]={});null!=t?(/^\@/.test(t)&&(s[e]=s[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,i=e.length;t<i&&n.length<3;++t)(ml.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,i,s;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)i=n,r=(1&(s=e)?i[0].toUpperCase():i[0].toLowerCase())+(2&s?i[1].toUpperCase():i[1].toLowerCase())+(4&s?i[2].toUpperCase():i[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,c),c.add(n.idPrefix)),/^\$/.test(e)||(s[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,s[`$${e}_mutations`]=null)}));const l=e.call(this,s,r);for(const[e,t]of Object.entries(r))if(null===(i=t.yProps)||void 0===i?void 0:i.length){const n=o[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return l}}function Ol(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const Dl=new u(!0),Tl=new u(!0);Dl.pipe(Mt((e=>e?f(!0):f(!1).pipe(Pt(2e4)))),jt()).subscribe(Tl);const Ul="undefined"!=typeof document?h(document,"visibilitychange"):f({}),Pl=Ul.pipe(Rt((()=>"hidden"===document.visibilityState))),jl=Ul.pipe(Rt((()=>"visible"===document.visibilityState))),Ll="undefined"!=typeof window?p(jl,h(window,"mousedown"),h(window,"mousemove"),h(window,"keydown"),h(window,"wheel"),h(window,"touchmove")):f({});"undefined"!=typeof document&&p(f(!0),Pl,Ll).pipe(xt((()=>"visible"===document.visibilityState)),Bt((e=>{Dl.value!==e&&Dl.next(e)})),Mt((e=>e?f(0).pipe(Pt(16e4),Bt((()=>Dl.next(!1)))):f(0)))).subscribe((()=>{}));class Rl extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function Nl(t){var n,r;if(!(null===(n=t.cloud.options)||void 0===n?void 0:n.awarenessProtocol))throw new e.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');return null===(r=t.cloud.options)||void 0===r?void 0:r.awarenessProtocol}const $l=new WeakMap,Ml=new WeakMap;function Bl(e){let t=Ml.get(e);return t||(t=new d,Ml.set(e,t)),t}class Fl extends a{constructor(e,t,n,r,i,s,o,c){super((l=>new Vl(e,t,n,r,i,c,l,s,o)))}}let Wl=0;class Vl extends m{constructor(e,t,n,r,i,s,o,c,l){super((()=>this.teardown())),this.id=++Wl,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=i,this.user=s,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=c,this.webSocketStatus=l,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return C(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new Rl);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>C(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else this.reconnect()}))),3e4);const t=new URL(this.databaseUrl);t.protocol="http:"===t.protocol?"ws":"wss";const n=new URLSearchParams;if(this.subscriber.closed)return;n.set("v","2"),this.rev&&n.set("rev",this.rev),this.yrev&&n.set("yrev",this.yrev),n.set("realmsHash",this.realmSetHash),n.set("clientId",this.clientIdentity),n.set("dxcv",this.db.cloud.version),this.user.accessToken&&n.set("token",this.user.accessToken);const r=this.ws=new WebSocket(`${t}/changes?${n}`);r.binaryType="arraybuffer",r.onclose=e=>{this.pinger&&this.reconnect()},r.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?Qn.parse(e.data):function(e){const t=new ge(e),n=we(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:we(t)};const r=we(t),i=we(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:i,i:Number(ke(t))};default:{const e=Ee(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:i,k:e};case"aware":return{type:n,table:r,prop:i,k:e,u:ve(t)};case"doc-open":return{type:n,table:r,prop:i,k:e,serverRev:Ee(t),sv:Ee(t)};case"sv":return{type:n,table:r,prop:i,k:e,sv:ve(t)};case"u-c":return{type:n,table:r,prop:i,k:e,u:ve(t),i:Number(ke(t))};case"u-s":return{type:n,table:r,prop:i,k:e,u:ve(t),r:t.pos<t.arr.length&&we(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=zc.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>$l.get(e))(e);if(n){Nl(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=zc.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&Bl(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?Jc([t],this.db).then((e=>C(this,[e],void 0,(function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=Lc(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(hr,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{r.onopen=n=>{e=!0,t(null)},r.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(Qn.stringify(e))):null===(n=this.ws)||void 0===n||n.send(de(e)))}))),this.user.isLoggedIn&&!Il(this.db)&&this.subscriptions.add(function(e){const t=kn(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return p(...t.map((({table:t,ydocProp:n,updatesTable:r})=>{const s=e.table(r);return c(s.get(hr)).pipe(g((e=>{let r=(null==e?void 0:e.unsentFrom)||1;return c(i((()=>C(this,void 0,void 0,(function*(){return(yield fr(s,r)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:t,prop:n,k:e.k,u:e.u,i:e.i})))}))))).pipe(y((e=>{e.length>0&&(r=e.at(-1).i+1)})))})))}))).pipe(v((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class Kl extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function Hl(e){return C(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield o(Ll)}))}function zl(e){return C(this,void 0,void 0,(function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Qc(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const Jl=new WeakMap;function ql(e,t,n,r){const i=Jl.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return i.promise;{let s=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(s=!0)}));return i.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!s)return ql(e,t,n,r)}))}}const s=function(){return C(this,void 0,void 0,(function*(){try{yield ir(e),yield Ol(e,Zc,(()=>Qc(e,t,n,r))),Jl.delete(e)}catch(t){throw Jl.delete(e),t}}))}();return Jl.set(e,{promise:s,pull:"push"!==(null==r?void 0:r.purpose)}),s}const Yl=1e3;function Gl(e,t,n){let r=null,i={cancelled:!1},s=0,o=0;function c(r=1){setTimeout((()=>{const h=l?"pull":"push";o=Date.now(),ql(e,t,n,{cancelToken:i,retryImmediatelyOnFetchError:!0,purpose:h}).then((()=>{if(i.cancelled)d();else if(l||a)return l=!1,a=!1,c();u=!1,s=0,o=0})).catch((e=>{if(i.cancelled)d(),u=!1,s=0,o=0;else if(r<5){const e=[0,20,40,300,900][r]*Yl;s=Date.now()+e,o=0,setTimeout((()=>c(r+1)),e)}else u=!1,s=0,o=0}))}),0)}let l=!1,a=!1,u=!1;const d=()=>{i.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{(e=>{i.cancelled||("pull"===e&&(l=!0),"push"===e&&(a=!0),u?s||o>0&&Date.now():(u=!0,c()))})(e||"pull")}))},stop:d}}function Xl(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Zl,Ql,ea,ta,na,ra={},ia=[],sa=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function oa(e,t){for(var n in t)e[n]=t[n];return e}function ca(e){var t=e.parentNode;t&&t.removeChild(e)}function la(e,t,n){var r,i,s,o={};for(s in t)"key"==s?r=t[s]:"ref"==s?i=t[s]:o[s]=t[s];if(arguments.length>2&&(o.children=arguments.length>3?Zl.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===o[s]&&(o[s]=e.defaultProps[s]);return aa(e,o,r,i,null)}function aa(e,t,n,r,i){var s={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==i?++ea:i};return null==i&&null!=Ql.vnode&&Ql.vnode(s),s}function ua(e){return e.children}function da(e,t){this.props=e,this.context=t}function ha(e,t){if(null==t)return e.__?ha(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?ha(e):null}function fa(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return fa(e)}}function pa(e){(!e.__d&&(e.__d=!0)&&ta.push(e)&&!ga.__r++||na!==Ql.debounceRendering)&&((na=Ql.debounceRendering)||setTimeout)(ga)}function ga(){for(var e;ga.__r=ta.length;)e=ta.sort((function(e,t){return e.__v.__b-t.__v.__b})),ta=[],e.some((function(e){var t,n,r,i,s,o;e.__d&&(s=(i=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=oa({},i)).__v=i.__v+1,Sa(o,i,r,t.__n,void 0!==o.ownerSVGElement,null!=i.__h?[s]:null,n,null==s?ha(i):s,i.__h),Ea(n,i),i.__e!=s&&fa(i)))}))}function ya(e,t,n,r,i,s,o,c,l,a){var u,d,h,f,p,g,y,v=r&&r.__k||ia,m=v.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(f=n.__k[u]=null==(f=t[u])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?aa(null,f,null,null,f):Array.isArray(f)?aa(ua,{children:f},null,null,null):f.__b>0?aa(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[u])||h&&f.key==h.key&&f.type===h.type)v[u]=void 0;else for(d=0;d<m;d++){if((h=v[d])&&f.key==h.key&&f.type===h.type){v[d]=void 0;break}h=null}Sa(e,f,h=h||ra,i,s,o,c,l,a),p=f.__e,(d=f.ref)&&h.ref!=d&&(y||(y=[]),h.ref&&y.push(h.ref,null,f),y.push(d,f.__c||p,f)),null!=p?(null==g&&(g=p),"function"==typeof f.type&&f.__k===h.__k?f.__d=l=va(f,l,e):l=ma(e,f,h,v,p,l),"function"==typeof n.type&&(n.__d=l)):l&&h.__e==l&&l.parentNode!=e&&(l=ha(h))}for(n.__e=g,u=m;u--;)null!=v[u]&&("function"==typeof n.type&&null!=v[u].__e&&v[u].__e==n.__d&&(n.__d=ha(r,u+1)),Ca(v[u],v[u]));if(y)for(u=0;u<y.length;u++)Ia(y[u],y[++u],y[++u])}function va(e,t,n){for(var r,i=e.__k,s=0;i&&s<i.length;s++)(r=i[s])&&(r.__=e,t="function"==typeof r.type?va(r,t,n):ma(n,r,r,i,r.__e,t));return t}function ma(e,t,n,r,i,s){var o,c,l;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||i!=s||null==i.parentNode)e:if(null==s||s.parentNode!==e)e.appendChild(i),o=null;else{for(c=s,l=0;(c=c.nextSibling)&&l<r.length;l+=2)if(c==i)break e;e.insertBefore(i,s),o=s}return void 0!==o?o:i.nextSibling}function ba(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||sa.test(t)?n:n+"px"}function wa(e,t,n,r,i){var s;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||ba(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||ba(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])s=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?r||e.addEventListener(t,s?ka:_a,s):e.removeEventListener(t,s?ka:_a,s);else if("dangerouslySetInnerHTML"!==t){if(i)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function _a(e){this.l[e.type+!1](Ql.event?Ql.event(e):e)}function ka(e){this.l[e.type+!0](Ql.event?Ql.event(e):e)}function Sa(e,t,n,r,i,s,o,c,l){var a,u,d,h,f,p,g,y,v,m,b,w,_,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(l=n.__h,c=t.__e=n.__e,t.__h=null,s=[c]),(a=Ql.__b)&&a(t);try{e:if("function"==typeof k){if(y=t.props,v=(a=k.contextType)&&r[a.__c],m=a?v?v.props.value:a.__:r,n.__c?g=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(y,m):(t.__c=u=new da(y,m),u.constructor=k,u.render=Aa),v&&v.sub(u),u.props=y,u.state||(u.state={}),u.context=m,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=oa({},u.__s)),oa(u.__s,k.getDerivedStateFromProps(y,u.__s))),h=u.props,f=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&y!==h&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(y,m),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(y,u.__s,m)||t.__v===n.__v){u.props=y,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(y,u.__s,m),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(h,f,p)}))}if(u.context=m,u.props=y,u.__v=t,u.__P=e,b=Ql.__r,w=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context);else do{u.__d=!1,b&&b(t),a=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++w<25);u.state=u.__s,null!=u.getChildContext&&(r=oa(oa({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===ua&&null==a.key?a.props.children:a,ya(e,Array.isArray(_)?_:[_],t,n,r,i,s,o,c,l),u.base=t.__e,t.__h=null,u.__h.length&&o.push(u),g&&(u.__E=u.__=null),u.__e=!1}else null==s&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=xa(n.__e,t,n,r,i,s,o,l);(a=Ql.diffed)&&a(t)}catch(e){t.__v=null,(l||null!=s)&&(t.__e=c,t.__h=!!l,s[s.indexOf(c)]=null),Ql.__e(e,t,n)}}function Ea(e,t){Ql.__c&&Ql.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Ql.__e(e,t.__v)}}))}function xa(e,t,n,r,i,s,o,c){var l,a,u,d=n.props,h=t.props,f=t.type,p=0;if("svg"===f&&(i=!0),null!=s)for(;p<s.length;p++)if((l=s[p])&&"setAttribute"in l==!!f&&(f?l.localName===f:3===l.nodeType)){e=l,s[p]=null;break}if(null==e){if(null===f)return document.createTextNode(h);e=i?document.createElementNS("http://www.w3.org/2000/svg",f):document.createElement(f,h.is&&h),s=null,c=!1}if(null===f)d===h||c&&e.data===h||(e.data=h);else{if(s=s&&Zl.call(e.childNodes),a=(d=n.props||ra).dangerouslySetInnerHTML,u=h.dangerouslySetInnerHTML,!c){if(null!=s)for(d={},p=0;p<e.attributes.length;p++)d[e.attributes[p].name]=e.attributes[p].value;(u||a)&&(u&&(a&&u.__html==a.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,i){var s;for(s in n)"children"===s||"key"===s||s in t||wa(e,s,null,n[s],r);for(s in t)i&&"function"!=typeof t[s]||"children"===s||"key"===s||"value"===s||"checked"===s||n[s]===t[s]||wa(e,s,t[s],n[s],r)}(e,h,d,i,c),u)t.__k=[];else if(p=t.props.children,ya(e,Array.isArray(p)?p:[p],t,n,r,i&&"foreignObject"!==f,s,o,s?s[0]:n.__k&&ha(n,0),c),null!=s)for(p=s.length;p--;)null!=s[p]&&ca(s[p]);c||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&wa(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&wa(e,"checked",p,d.checked,!1))}return e}function Ia(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Ql.__e(e,n)}}function Ca(e,t,n){var r,i;if(Ql.unmount&&Ql.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Ia(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Ql.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Ca(r[i],t,"function"!=typeof e.type);n||null==e.__e||ca(e.__e),e.__e=e.__d=void 0}function Aa(e,t,n){return this.constructor(e,n)}function Oa(e,t,n){var r,i,s;Ql.__&&Ql.__(e,t),i=(r="function"==typeof n)?null:n&&n.__k||t.__k,s=[],Sa(t,e=(!r&&n||t).__k=la(ua,null,[e]),i||ra,ra,void 0!==t.ownerSVGElement,!r&&n?[n]:i?null:t.firstChild?Zl.call(t.childNodes):null,s,!r&&n?n:i?i.__e:t.firstChild,r),Ea(s,e)}Zl=ia.slice,Ql={__e:function(e,t,n,r){for(var i,s,o;t=t.__;)if((i=t.__c)&&!i.__)try{if((s=i.constructor)&&null!=s.getDerivedStateFromError&&(i.setState(s.getDerivedStateFromError(e)),o=i.__d),null!=i.componentDidCatch&&(i.componentDidCatch(e,r||{}),o=i.__d),o)return i.__E=i}catch(t){e=t}throw e}},ea=0,da.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=oa({},this.state),"function"==typeof e&&(e=e(oa({},n),this.props)),e&&oa(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),pa(this))},da.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),pa(this))},da.prototype.render=ua,ta=[],ga.__r=0;const Da={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function Ta({children:e,className:t}){return la("div",{className:t},la("div",{style:Da.Darken}),la("div",{style:Da.DialogOuter},la("div",{style:Da.DialogInner},e)))}var Ua,Pa,ja,La,Ra=0,Na=[],$a=[],Ma=Ql.__b,Ba=Ql.__r,Fa=Ql.diffed,Wa=Ql.__c,Va=Ql.unmount;function Ka(e,t){Ql.__h&&Ql.__h(Pa,e,Ra||t),Ra=0;var n=Pa.__H||(Pa.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:$a}),n.__[e]}function Ha(e){return Ra=1,function(e,t,n){var r=Ka(Ua++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Za(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=Pa,!Pa.u)){Pa.u=!0;var i=Pa.shouldComponentUpdate;Pa.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var s=r.__c.__H.__.filter((function(e){return e.__c}));if(s.every((function(e){return!e.__N})))return!i||i.call(this,e,t,n);var o=!1;return s.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}})),!!o&&(!i||i.call(this,e,t,n))}}return r.__N||r.__}(Za,e)}function za(e){return Ra=5,function(e,t){var n=Ka(Ua++,7);return Xa(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function Ja(){for(var e;e=Na.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ya),e.__H.__h.forEach(Ga),e.__H.__h=[]}catch(t){e.__H.__h=[],Ql.__e(t,e.__v)}}Ql.__b=function(e){Pa=null,Ma&&Ma(e)},Ql.__r=function(e){Ba&&Ba(e),Ua=0;var t=(Pa=e.__c).__H;t&&(ja===Pa?(t.__h=[],Pa.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=$a,e.__N=e.i=void 0}))):(t.__h.forEach(Ya),t.__h.forEach(Ga),t.__h=[])),ja=Pa},Ql.diffed=function(e){Fa&&Fa(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Na.push(t)&&La===Ql.requestAnimationFrame||((La=Ql.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),qa&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);qa&&(t=requestAnimationFrame(n))})(Ja)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==$a&&(e.__=e.__V),e.i=void 0,e.__V=$a}))),ja=Pa=null},Ql.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Ya),e.__h=e.__h.filter((function(e){return!e.__||Ga(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Ql.__e(n,e.__v)}})),Wa&&Wa(e,t)},Ql.unmount=function(e){Va&&Va(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{Ya(e)}catch(e){t=e}})),t&&Ql.__e(t,n.__v))};var qa="function"==typeof requestAnimationFrame;function Ya(e){var t=Pa,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Pa=t}function Ga(e){var t=Pa;e.__c=e.__(),Pa=t}function Xa(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Za(e,t){return"function"==typeof t?t(e):t}function Qa({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}function eu({title:e,type:t,alerts:n,fields:r,submitLabel:i,cancelLabel:s,onCancel:o,onSubmit:c}){const[l,a]=Ha({}),u=za(null);return function(e,t){var n=Ka(Ua++,4);!Ql.__s&&Xa(n.__H,t)&&(n.__=e,n.i=t,Pa.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),la(Ta,{className:"dxc-login-dlg"},la(ua,null,la("h3",{style:Da.WindowHeader},e),n.map((e=>la("p",{style:Da.Alert[e.type]},Qa(e)))),la("form",{onSubmit:e=>{e.preventDefault(),c(l)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],i)=>la("label",{style:Da.Label,key:i},n?`${n}: `:"",la("input",{ref:0===i?u:void 0,type:t,name:e,autoComplete:"on",style:Da.Input,autoFocus:!0,placeholder:r,value:l[e]||"",onInput:n=>{var r;const i=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let s=Object.assign(Object.assign({},l),{[e]:i});a(s),"otp"===t&&8===(null==i?void 0:i.trim().length)&&c(s)}})))))),la("div",{style:Da.ButtonsDiv},la(ua,null,la("button",{type:"submit",style:Da.Button,onClick:()=>c(l)},i),s&&la("button",{style:Da.Button,onClick:o},s))))}class tu extends da{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=c(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?la(eu,Object.assign({},t)):null}}function nu(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const ru=nu((e=>new u(sn)));function iu(e,t){let n=t,r=c(e).pipe(_((e=>n=e)),k({resetOnRefCountZero:()=>S(1e3)}));const i=new a((e=>{let t=!1;const i=r.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||i.closed||e.next(n),i}));return i.getValue=()=>n,i}const su=nu((e=>iu(i((()=>e.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),ou=nu((e=>iu(ru(e._novip).pipe(Mt((t=>i((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:t.userId}).toArray(),e.realms.toArray(),t.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function cu(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,i=t[e];t[e]=[...new Set([...i,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const lu=nu((e=>function(e,t){let n;const r=e.pipe(_((e=>n=t(e))));return r.getValue=()=>void 0!==n?n:n=t(e.getValue()),r}(iu(w([ou(e._novip),su(e._novip)]).pipe(xt((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:sn.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const i=t.map((t=>{const i=e.filter((e=>e.realmId===t.realmId)),s=i.map((e=>e.permissions)).filter((e=>e)),o=kn(i.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:cu(...s,...o)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return i}))));class au{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const uu=nu((e=>{const t=ru(e._novip).pipe(Mt((t=>i((()=>e.members.where({email:t.email||""}).toArray()))))),n=lu(e._novip),r=ou(e._novip);return iu(w([t,r,n]).pipe(xt((([t,n,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),s=t.reduce(i,{}),o=n.selfMembers.reduce(i,s);return Object.values(o).filter((e=>!e.accepted)).map((t=>Object.assign(Object.assign({},t),{accept(){return C(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return C(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function du(e){return t=>{var r;const i=t.doc;if(!i)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:s}=i.meta||{};if(!(null===(r=e.cloud.schema)||void 0===r?void 0:r[s].markedForSync))return;let o;Object.defineProperty(t,"awareness",{get:()=>o||(o=function(e,t,r){const{parentTable:i,parentId:s,parentProp:o,updatesTable:c}=t.meta,l=Nl(e),a=new l.Awareness(t),u=Bl(t);return a.on("update",(({added:n,updated:s,removed:c},u)=>{const d=n.concat(s).concat(c),h=e.cloud.currentUser.value;if("server"!==u&&h.isLoggedIn&&!Il(e)){const n=l.encodeAwarenessUpdate(a,d);e.messageProducer.next({type:"aware",table:i,prop:o,k:t.meta.parentId,u:n}),r.destroyed&&e.messageProducer.next({type:"doc-close",table:i,prop:o,k:t.meta.parentId})}})),a.on("destroy",(()=>{l.removeAwarenessStates(a,[t.clientID],"provider destroyed")})),(()=>{C(this,void 0,void 0,(function*(){if(r.destroyed)return;let t=!1,l=1;const a=w([e.cloud.webSocketStatus,u.pipe(E(null))]).subscribe((([n])=>{if(r.destroyed)return;t="connected"===n;const i=e.cloud.currentUser.value;"connected"===n&&i.isLoggedIn&&!Il(e)&&(++l,d().catch((e=>{})))}));function d(){return C(this,void 0,void 0,(function*(){const a=l,u=e.table(c),d=e.$syncState,[h,f]=yield e.transaction("r",d,u,(()=>C(this,void 0,void 0,(function*(){const e=yield u.get(hr),t=yield d.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(r.destroyed||l!==a||!t)return;const p={type:"doc-open",table:i,prop:o,k:s,serverRev:f},g=yield u.where("i").between(h,1/0,!1).filter((e=>0===n(e.k,s)&&0==(1&(e.f||0)))).toArray();if(!r.destroyed&&l===a&&t){if(g.length>0){const e=ro(g.map((e=>e.u))),t=to(e);p.sv=t}e.messageProducer.next(p)}}))}r.addCleanupHandler(a)}))})(),a}(e,i,t),$l.set(i,o),o)})}}function hu(e){return"rlm~"+e}function fu(e){return e.startsWith("rlm~")?e.substr(4):null}const pu={},gu=new WeakMap,yu=mu("tx"),vu=mu("unload");function mu(e){let t=null,n=!1,r=new Map;return{name:e,run(){return C(this,void 0,void 0,(function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch((()=>{}))),setTimeout((()=>{n=!1;const e=r;r=new Map,t=function(e){return C(this,void 0,void 0,(function*(){for(const{db:t,parentId:n,triggers:r,parentTable:i,prop:s}of e.values()){const e=zc.getOrCreateDocument(t,i,s,n);try{const t=zc.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{zc.release(e)}}}))}(e).finally((()=>{t=null}))}),0))}))},enqueue(e,t,n,i,s){const o=`${e.name}:${t}:${n}:${i}`;let c=r.get(o);c||(c={db:e,parentTable:t,parentId:n,prop:i,triggers:new Set},r.set(o,c)),c.triggers.add(s)}}}function bu(){yu.run()}function wu(){vu.run()}function _u(e,t,n){var r,i;const o=null===(i=null===(r=e.schema.yProps)||void 0===r?void 0:r.find((e=>e.prop===t)))||void 0===i?void 0:i.updatesTable;if(!o)throw new Error(`Table ${e.name} does not have a Yjs property named ${t}`);pu[o]={trigger:n,parentTable:e.name,prop:t};const c=e.db._novip;let l=gu.get(c);l||(l=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:t=>Object.assign(Object.assign({},t),{transaction:(e,n,r)=>{const i=t.transaction(e,n,r);return"readonly"===n?i:e.some((e=>pu[e]))?(i.addEventListener("complete",bu),i):i},table:n=>{const r=t.table(n),i=pu[n];if(!i)return r;const{trigger:o,parentTable:c,prop:l}=i;return Object.assign(Object.assign({},r),{mutate(t){var n;switch(t.type){case"add":for(const r of t.values){if(null==r.k)continue;const t=r.k,i=zc.getDocCache(e).find(c,t,l);(i&&(null===(n=zc.for(i))||void 0===n?void 0:n.refCount)?vu:yu).enqueue(e,c,t,l,o)}break;case"delete":t.trans._rejecting_y_ypdate&&r.getMany({keys:t.keys,trans:t.trans,cache:"immutable"}).then((t=>{const n=new s;for(const{k:e}of t)null!=e&&n.addKey(e);for(const t of n)yu.enqueue(e,c,t.from,l,o)}))}return r.mutate(t)}})}})}))(c),gu.set(c,l)),c.use(l),zc.on("beforeunload",wu)}const ku={nameSuffix:!0};function Su(t){const n=t.name,r=ru(t),s=[];let l=!1,a=null;t.on("ready",(t=>C(this,void 0,void 0,(function*(){try{yield function(t){return C(this,void 0,void 0,(function*(){var n,d,m,_,k,S,E;g=!1;const x=al(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(n=x.cloud.options)||void 0===n?void 0:n.customLoginGui)||s.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Oa(la(tu,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Oa(la(tu,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),x.cloud.isServiceWorkerDB||s.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Mt((e=>{const n=t;t=e;const r=f(e);switch(e){case"disconnected":return Dl.value?r.pipe(At(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(At(4e3));default:return r}})));return w([n,e.syncStateChangedEvent.pipe($t({phase:"initial"})),ru(e.dx._novip),Tl]).pipe(xt((([t,n,r,i])=>{var s;if((null===(s=r.license)||void 0===s?void 0:s.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:c,progress:l}=n,a=t;return"error"===o&&(a="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(a="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(a="connecting"),i||(a="disconnected"),{phase:o,error:c,progress:l,status:cr?a:"offline",license:"ok"}})))}(x).subscribe(t.cloud.syncState)),s.push(x.syncCompleteEvent.subscribe(v)),x.tables.every((e=>e.core))||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const I="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[A,O]=yield x.transaction("rw",x.$syncState,(()=>C(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=x.cloud,[i,s,o]=yield Promise.all([x.getOptions(),x.getSchema(),x.getPersistedSyncState()]);if(l){if(!i||JSON.stringify(i)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield x.$syncState.put(e,"options")}}else x.cloud.options=i||null;if((null===(e=x.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&I.length>0&&!fl?x.cloud.usingServiceWorker=!0:((null===(t=x.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&x.cloud.isServiceWorkerDB,x.cloud.usingServiceWorker=!1),Xl(r,x.cloud.options),Xl(s,x.cloud.options),r){if(!s||JSON.stringify(s)!==JSON.stringify(r)){const e=s||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield x.$syncState.put(e,"schema"),Object.assign(r,e)}}else x.cloud.schema=s||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(A&&x.setInitiallySynced(!0),function(t){var n,r;for(const i of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[i.name])||void 0===r?void 0:r.markedForSync){if(i.schema.primKey.auto)throw new e.SchemaError(`Table ${i.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(i.name)}]}) to blacklist it from sync`);if(!i.schema.primKey.keyPath)throw new e.SchemaError(`Table ${i.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(i.name)}]}) to blacklist it from sync`)}}(x),y(),!x.cloud.isServiceWorkerDB){s.push(i((()=>x.getCurrentUser())).subscribe(r)),s.push(i((()=>x.getPersistedSyncState())).subscribe(x.cloud.persistedSyncState)),yield o(w([r.pipe(Nt(1),Tt(1)),x.cloud.persistedSyncState.pipe(Nt(1),Tt(1))]));const e=du(x);zc.on.new.subscribe(e),x.dx.once("close",(()=>{zc.on.new.unsubscribe(e)}))}let D=!1;const T=yield x.getCurrentUser(),U=null===(d=x.cloud.options)||void 0===d?void 0:d.requireAuth;U&&(x.cloud.isServiceWorkerDB?yield o(r.pipe(Rt((e=>!!e.isLoggedIn)),Tt(1))):"object"==typeof U?(!T.isLoggedIn||U.userId&&T.userId!==U.userId||U.email&&T.email!==U.email)&&(D=yield dn(x,U)):T.isLoggedIn||(D=yield dn(x))),!T.isLoggedIn||O&&O.includes(T.userId)||(D=!0),a&&a.stop(),a=null,y();const P=(null===(m=x.cloud.options)||void 0===m?void 0:m.databaseUrl)&&(!A||D);P&&(yield function(e,t,n){return C(this,void 0,void 0,(function*(){yield Ol(e,Zc,(()=>Qc(e,t,n,{isInitialSync:!0})))}))}(x,x.cloud.options,x.cloud.schema),x.setInitiallySynced(!0)),y(),x.cloud.usingServiceWorker&&(null===(_=x.cloud.options)||void 0===_?void 0:_.databaseUrl)?(P||Wt(x,"push").catch((()=>{})),function(e){return C(this,void 0,void 0,(function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}}))}(x).catch((()=>{}))):(null===(k=x.cloud.options)||void 0===k?void 0:k.databaseUrl)&&x.cloud.schema&&!x.cloud.isServiceWorkerDB&&(a=Gl(x,x.cloud.options,x.cloud.schema),a.start(),P||Vt(x,"push")),y(),x.cloud.isServiceWorkerDB||s.push(h(self,"online").subscribe((()=>{x.syncStateChangedEvent.next({phase:"not-in-sync"}),Il(x)||Vt(x,"push")})),h(self,"offline").subscribe((()=>{x.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(S=x.cloud.options)||void 0===S?void 0:S.databaseUrl)||(null===(E=x.cloud.options)||void 0===E?void 0:E.disableWebSocket)||pl||s.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const n=e.messageConsumer.readyToServe.pipe(Rt((e=>e)),Mt((()=>e.getPersistedSyncState())),Rt((e=>e&&e.serverRevision)),Mt((e=>C(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield vn(e)}}))))),r=p(n,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(Rt((e=>null==e?void 0:e.serverRevision)),Tt(1),Mt((t=>e.cloud.currentUser.pipe(xt((e=>[e,t]))))),Mt((([e,t])=>Tl.pipe(xt((n=>[n?e:null,t]))))),Mt((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(Rt((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),Tt(1),xt((e=>[t,e]))):new u([t,n]))),Mt((e=>C(this,[e],void 0,(function*([e,t]){return[e,yield vn(t)]})))),jt((([e,t],[n,r])=>e===n&&t===r)),Mt((([n,i])=>{var s;return(null===(s=e.cloud.persistedSyncState)||void 0===s?void 0:s.value)?n?new Fl(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,i,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n):c([]):t()})),wt((n=>"TokenExpiredError"===(null==n?void 0:n.name)?f(!0).pipe(Mt((()=>C(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield tn(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),Mt((()=>t()))):b((()=>n)))),wt((n=>(e.cloud.webSocketStatus.next("error"),n instanceof Kl?b((()=>n)):c(Hl()).pipe(Mt((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(x))}))}(t)}catch(e){}}))),!0);let g=!1;function y(){if(g)throw new e.DatabaseClosedError}t.once("close",(()=>{s.forEach((e=>e.unsubscribe())),s.splice(0,s.length),g=!0,a&&a.stop(),a=null,r.next(sn)}));const v=new d;var m;t.cloud={version:"4.2.0-alpha.1",options:Object.assign({},ku),schema:null,get currentUserId(){return r.value.userId||sn.userId},currentUser:r,syncState:new u({phase:"initial",status:"not-started"}),events:{syncComplete:v},persistedSyncState:new u(void 0),userInteraction:new u(void 0),webSocketStatus:new u("not-started"),login(e){return C(this,void 0,void 0,(function*(){const n=al(t);yield n.cloud.sync(),yield dn(n,e)}))},invites:uu(t),roles:su(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),l=!0,e.databaseUrl&&e.nameSuffix&&(t.name=`${n}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,al(t).reconfigure()),Xl(t.cloud.schema,t.cloud.options)},logout(){return C(this,arguments,void 0,(function*({force:e}={}){e?yield ln(al(t),{deleteUnsyncedData:!0}):yield cn(al(t))}))},sync(){return C(this,arguments,void 0,(function*({wait:e,purpose:n}={wait:!0,purpose:"push"}){var r;void 0===e&&(e=!0);const s=al(t);if("ok"!==((null===(r=s.cloud.currentUser.value.license)||void 0===r?void 0:r.status)||"ok")&&(yield Qt(s)),"pull"===n){const t=s.cloud.persistedSyncState.value;if(Vt(s,n),e){const e=yield o(s.cloud.persistedSyncState.pipe(Rt((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp)))));if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield zl(s)){const t=s.cloud.persistedSyncState.value;Vt(s,n),e&&(yield o(c(i((()=>C(this,void 0,void 0,(function*(){const e=yield zl(s),n=yield s.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==t?void 0:t.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return e}))))).pipe(Rt((e=>!e)))))}}))},permissions:(e,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId:i}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const s=lu(e),o=t=>{const s=t[i||e.cloud.currentUserId];return s?new au(s.permissions,n,void 0===i||i===e.cloud.currentUserId||r===e.cloud.currentUserId):new au({},n,!r||r===e.cloud.currentUserId)},c=s.pipe(xt(o));return c.getValue=()=>o(s.getValue()),c}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>Al(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return wl(t.cloud.schema[this.name].idPrefix||"",n)},t.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},t.use(Cl({currentUserObservable:t.cloud.currentUser,db:al(t)})),t.use((m=al(t),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,i,s,o,c,l;const a=e.trans;if(a.disableChangeTracking)return n.mutate(e);const u=null!==(i=null===(r=a.currentUser)||void 0===r?void 0:r.userId)&&void 0!==i?i:sn.userId;if((null===(o=null===(s=m.cloud.schema)||void 0===s?void 0:s[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(l=(c=n.schema.primaryKey).extractKey)||void 0===l?void 0:l.call(c,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),t.use(_l(al(t)))}Su.version="4.2.0-alpha.1",e.Cloud=Su;export{Su as default,_u as defineYDocTrigger,Su as dexieCloud,fu as getTiedObjectId,hu as getTiedRealmId,Qa as resolveText};
1
+ import e,{PropModification as t,cmp as n,RangeSet as r,liveQuery as o}from"dexie";import{Encoder as s,writeVarString as i,writeAny as a,writeVarUint8Array as l,writeBigUint64 as c,toUint8Array as u}from"lib0/encoding";import{Decoder as d,readVarString as f,readAny as p,readVarUint8Array as y,readBigUint64 as h,hasContent as v,readUint8 as m}from"lib0/decoding";import{firstValueFrom as b,from as g,filter as _,Observable as w,BehaviorSubject as k,Subject as S,of as x,fromEvent as I,merge as E,switchMap as O,tap as C,mergeMap as T,Subscription as j,throwError as U,combineLatest as A,map as P,share as $,timer as D,startWith as L}from"rxjs";import{filter as R,switchMap as N,delay as B,distinctUntilChanged as M,map as F,tap as W,take as K,catchError as V,debounceTime as H,startWith as q,skip as z}from"rxjs/operators";import*as J from"yjs";import{DexieYProvider as G}from"y-dexie";function Y(e,t,n,r){return new(n||(n=Promise))((function(o,s){function i(e){try{l(r.next(e))}catch(e){s(e)}}function a(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((r=r.apply(e,t||[])).next())}))}function Z(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function X(e){return this instanceof X?(this.v=e,this):new X(e)}function Q(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),s=[];return r={},i("next"),i("throw"),i("return"),r[Symbol.asyncIterator]=function(){return this},r;function i(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){s.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof X?Promise.resolve(e.value.v).then(l,c):u(s[0][2],e)}(o[e](t))}catch(e){u(s[0][3],e)}}function l(e){a("next",e)}function c(e){a("throw",e)}function u(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function ee(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=Z(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}const te={}.hasOwnProperty;function ne(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)ne(e,t[r],n[r])}else{var s=t.indexOf(".");if(-1!==s){var i=t.substr(0,s),a=t.substr(s+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(i))||e.splice(parseInt(i),1):delete e[i]:e[i]=n;else{var l=e[i];l&&function(e,t){return te.call(e,t)}(e,i)||(l=e[i]={}),ne(l,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const re="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=oe)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function oe(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function se(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>se(e)))&&e.every(ie))}function ie(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(ie)}function ae(e,t,n){const r=e[t]||(e[t]={}),o=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":o.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":o.forEach(((e,t)=>{const o="update"===n.type?n.changeSpecs[t]:n.changeSpec,s=r[e];if(s)switch(s.type){case"ups":for(const[e,t]of Object.entries(o))ne(s.val,e,t);break;case"del":break;case"upd":Object.assign(s.mod,o)}else r[e]={type:"upd",mod:o}}));break;case"delete":o.forEach((e=>{r[e]={type:"del"}}))}return e}function le(e,t){for(const{table:n,muts:r}of t)for(const t of r)ae(e,n,t)}function ce(e){return Q(this,arguments,(function*(){var t,n,r,o;let s=0,i=new Uint8Array(4),a=0,l=[],c=0;try{for(var u,d=!0,f=ee(e);!(t=(u=yield X(f.next())).done);d=!0){o=u.value,d=!1;const e=o,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(s){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===a)break;i[a++]=t,++n}if(a<4)break}else if(a>0&&a<4)for(const t of e.slice(n,n+4-a))i[a++]=t,++n;case 1:c=4===a?new DataView(i.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),a?a=0:n+=4;case 2:if(n>=e.byteLength){s=2;break}if(n+c>e.byteLength)l.push(e.slice(n)),c-=e.byteLength-n,s=2,n=e.byteLength;else{if(l.length>0){const t=new Uint8Array(l.reduce(((e,t)=>e+t.byteLength),c));let r=0;for(const e of l)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+c),r),l=[],yield yield X(t)}else yield yield X(e.slice(n,n+c));n+=c,s=0}}}}catch(e){n={error:e}}finally{try{d||t||!(r=f.return)||(yield X(r.call(f)))}finally{if(n)throw n.error}}}))}let ue=!1;function de(e,t){return Y(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){ue||(ue=!0)}}))}function fe(e,t){e.cloud.usingServiceWorker?de(e,t):e.localSyncEvent.next({purpose:t})}const pe="fromBase64"in Uint8Array,ye="toBase64"in Uint8Array.prototype,he="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):pe?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var o=0;o<n;o++)r[o]=t.charCodeAt(o);return r},ve="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):ye?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};class me extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function be(t,n){return new Promise(((r,o)=>{const s=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}});t.next(s)}))}function ge(e,t,...n){return be(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function _e(e,t,n){return Y(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield be(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function we(e,t,n){return Y(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:o}=yield be(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function ke(e){return Y(this,void 0,void 0,(function*(){var t,n,r;const o=yield e.getCurrentUser(),{accessToken:s,accessTokenExpiration:i,refreshToken:a,refreshTokenExpiration:l,claims:c}=o;if(!s)return null;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=o.license)||void 0===n?void 0:n.status)||"ok"))return o;if(!a)throw new Error("Refresh token missing");if((null!==(r=null==l?void 0:l.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield xe(e.cloud.options.databaseUrl,o);return yield e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license,data:u.data}),u}))}function Se(t,n,r,o,s){return Y(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield xe(t,n):yield function(t,n,r,o){return Y(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:s,publicKey:i}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!s||!i)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=s;const a=function(e){const t=ve(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",i));t.publicKey=i;try{const e=yield n({public_key:a,hints:o});if("error"===e.type)throw new me(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield be(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof me)throw yield ge(r,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield ge(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,o,s)}))}function xe(e,t){return Y(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",o=(new TextEncoder).encode(t.refreshToken+n),s=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,o),i=ve(s),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:i,signing_algorithm:r,time_stamp:n},l=yield fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==l.status)throw new Error(`RefreshToken: Status ${l.status} from ${e}/token`);const c=yield l.json();if("error"===c.type)throw new me(c);return t.accessToken=c.accessToken,t.accessTokenExpiration=c.accessTokenExpiration?new Date(c.accessTokenExpiration):void 0,t.claims=c.claims,t.license={type:c.userType,status:c.claims.license||"ok"},null!=c.evalDaysLeft&&(t.license.evalDaysLeft=c.evalDaysLeft),null!=c.userValidUntil&&(t.license.validUntil=new Date(c.userValidUntil)),c.data&&(t.data=c.data),t}))}const Ie=new WeakMap;class Ee{constructor(e,t){Ie.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new Ee(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return Y(this,void 0,void 0,(function*(){Ie.get(this).table("$logins").put(this)}))}}const Oe={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(Oe),Object.freeze(Oe.claims)}catch(e){}function Ce(e,t){return b(g(e).pipe(_(t)))}function Te(e){return Y(this,void 0,void 0,(function*(){const t=yield je(e);if(t){if(!(yield function(e,t,n){return Y(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield be(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield je(e,{deleteUnsyncedData:!0})}}))}function je(e){return Y(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>Y(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const o=n.storeNames.filter((e=>e.endsWith("_mutations"))),s=(yield Promise.all(o.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(s>0&&!t)return[s,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[s,!0]}))));return r&&(yield Ce(e.cloud.currentUser,(e=>e.userId===Oe.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}class Ue extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Ae(e,...t){globalThis.console[e](...t)}function Pe(e,t){return Y(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),o=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield ke(e),!1}const s=new Ee(e,{claims:{},lastLogin:new Date(0)});return yield Se(e.cloud.options.databaseUrl,s,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return Y(this,arguments,void 0,(function*({public_key:n,hints:r}){var o;let s;const i=null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!i)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))s={demo_user:yield _e(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n};else if((null==r?void 0:r.otpId)&&r.otp)s={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield _e(t,"Enter email address",null==r?void 0:r.email);s=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}const a=yield fetch(`${i}/token`,{body:JSON.stringify(s),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=yield a.text();throw yield ge(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Ue(a,e)}const l=yield a.json();if("tokens"===l.type||"error"===l.type)return l;if("otp"===s.grant_type&&"email"in s){if("otp-sent"!==l.type)throw new Error(`Unexpected response from ${i}/token`);const e=yield we(t,s.email),r=Object.assign(Object.assign({},s),{otp:e||"",otp_id:l.otp_id,public_key:n});let o=yield fetch(`${i}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===o.status;){const e=yield o.text();r.otp=yield we(t,s.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),o=yield fetch(`${i}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==o.status){const e=yield o.text();throw new Ue(o,e)}return yield o.json()}throw new Error(`Unexpected response from ${i}/token`)}))}}(e),e.cloud.userInteraction,t),o!==Oe.userId&&s.userId!==o&&(yield Te(e)),yield function(e,t){return Y(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>Y(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(Ae("debug","Login context property names:",Object.keys(t)),Ae("debug","Login context property names:",Object.keys(t)),Ae("debug","Login context:",t),Ae("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield Ce(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,s),fe(e,"pull"),s.userId!==o}))}const $e={},De="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;De&&De.ready.then((e=>$e.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class Le{constructor(e){this.name=e}subscribe(e){if(!De)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return De.addEventListener("message",t),()=>De.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):$e.registration&&(null===(t=$e.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const Re=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class Ne extends w{constructor(e){const t="undefined"==typeof BroadcastChannel?new Le(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){n.next(e.data)}let s;!function(e,t){Re.has(e)?Re.get(e).push(t):Re.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Le?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",o)}catch(e){}return()=>{!function(e,t){const n=Re.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Le?s():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=Re.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function Be(e){return Y(this,arguments,void 0,(function*({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),o=yield crypto.subtle.digest("SHA-1",r);return ve(o)}))}function Me(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function Fe(e){return`$${e}_mutations`}function We(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const Ke=[].concat;function Ve(e){return Ke.apply([],e)}function He(e,t){return Y(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const o=Ve(yield Promise.all(e.map((e=>Y(this,void 0,void 0,(function*(){const t=We(e.name),o=n[t];let s=o?e.where("rev").above(o):e;r<1/0&&(s=s.limit(r));return(yield s.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts)),s=[];let i=null,a=null;for(const{table:e,mut:t}of o)i&&i.table===e&&a===t.txid?i.muts.push(t):(i={table:e,muts:[t]},a=t.txid,s.push(i));return s}))}function qe(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:ze}={};const Je={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function Ge(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,o){const s=JSON.stringify(e,(function(e){const o=this[e],s=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return Je;let s=n.get(r);if(void 0!==s)return s;const i=(o=e,ze.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,i))&&void 0!==o?o:t===i}));return s=null==a?void 0:a[1],s||(s=Array.isArray(e)?null:"function"==typeof e?t.function||null:Je),n.set(r,s),s}default:return t[r]}var o}(o);return s?s.replace(o,r,t):o}),o);return s},parse(e,n){const r=[];return JSON.parse(e,(function(e,o){const s=null==o?void 0:o.$t;if(s){const e=t[s];o=e?e.revive(o,n,t):o}let i=r[r.length-1];if(i&&i[0]===o){o={...o};for(const e of i[1])delete o[e];for(const[e,t]of Object.entries(i[2]))o[e]=t;r.pop()}if(void 0===o||"$"===e[0]&&"$t"!==e){let t,n;i=r[r.length-1],i&&i[0]===this?(t=i[1],n=i[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=o):n[e]=void 0}return o}))}}}const Ye={Blob:{test:(e,t)=>"Blob"===t,replace:(e,t)=>{const n=t.length;return t.push(e),{$t:"Blob",mimeType:e.type,i:n}},revive:({i:e,mimeType:t},n)=>new Blob([n[e]],{type:t})}};var Ze={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const Xe={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Qe={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},et={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},tt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const nt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var rt=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=nt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function ot(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=at[e[n]];return t}(ve(e))}function st(e){return he(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=it[e[n]];return t}(e))}const it={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},at={};for(const e of Object.keys(it))at[it[e]]=e;var lt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:ot(e)}),revive:({v:e})=>{const t=st(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class ct{constructor(e,t){this.buf=e,this.type=t}}function ut(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function dt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var ft={Blob:{test:(e,t)=>"Blob"===t||e instanceof ct,replace:e=>({$t:"Blob",v:ve(e instanceof ct?e.buf:dt(ut(e))),type:e.type}),revive:({type:e,v:t})=>{const n=he(t);return void 0!==typeof Blob?new Blob([n]):new ct(n.buffer,e)}}};const pt={...Ze,...Xe,...Qe,...et,...tt,...rt,...lt,...ft};function yt(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsArrayBuffer(e)}))}var ht={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},vt={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:ve(dt(ut(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const o=he(t);return new File([o],n,{type:e,lastModified:new Date(r).getTime()})}}};const mt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class bt{toString(){return this.v}constructor(e){this.v=e}}const gt=mt?{}:{bigint:{test:e=>e instanceof bt,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new bt(e)}},_t=Object.assign(Object.assign(Object.assign(Object.assign({},ht),gt),vt),{PropModification:{test:e=>e instanceof t,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["$t"]);return new t(n)}}}),wt=Ge(pt,_t),kt=function(...e){const t=Ge(pt,Ye,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),o=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[o,r]},async parse(e,n){let r=0;const o=[],s=await yt(n),i=new DataView(s);for(;r<s.byteLength;){const e=i.getUint32(r);r+=4;const t=s.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await yt(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(_t);function St(t,n,r){const o=[];for(let s of r){const{table:r,muts:i}=s,a=t.tables.find((e=>e.name===r));if(!a)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:l}=a;let c=s;i.forEach(((t,r)=>{const o=!l.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,i)=>{if(Array.isArray(t)){c===s&&(c=xt(s,o));const e=c.muts[r],n=JSON.stringify(t);e.keys[i]=n}else if("#"===t[0]){c===s&&(c=xt(s,o));const a=c.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${t}:${n.userId}`;a.keys[i]=u,o&&e.setByKeyPath(a.values[i],l.keyPath,u)}}))})),o.push(c)}return o}function xt(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}let It=new WeakMap;function Et(e){return Y(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=It.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function Ot(e,t,n,r,o,s,i,a,l){return Y(this,void 0,void 0,(function*(){const c={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield ke(o),d=null==u?void 0:u.accessToken;d&&(c.Authorization=`Bearer ${d}`);const f={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:a,schema:i||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:St(o.dx.core.schema,l,e),y:t,dxcv:o.cloud.version};o.syncStateChangedEvent.next({phase:"pushing"});const p=wt.stringify(f),y=yield fetch(`${s}/sync`,{method:"post",headers:c,credentials:"include",body:p});if(o.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),o=t.headers.get("Ratelimit-Reset");if(n&&r&&o){const t=Number(n),s=Math.max(0,Number(r)),i=Number(o);if(s<t/2){const t=Math.ceil(i/(s+1));It.set(e,new Date(Date.now()+1e3*t))}else It.delete(e)}}(o,y),!y.ok)throw new Ue(y);if("application/x-bison"===y.headers.get("content-type"))return kt.fromBinary(yield y.blob());{const e=yield y.text();return wt.parse(e)}}))}function Ct(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Tt=!1;function jt(e,t,n,r){return Y(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function Ut(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function At(t,r,o){return Y(this,void 0,void 0,(function*(){const s=yield t.bulkGet(r),i=[],a=[];r.forEach(((r,l)=>{const c=s[l];if(c){for(const[s,i]of Object.entries(o[l]))if(s===t.schema.primKey.keyPath){if(0!==n(i,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(c,s,i);i.push(r),a.push(c)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(a,i):t.bulkPut(a)}))}function Pt(t,n){return Y(this,void 0,void 0,(function*(){for(const{table:r,muts:o}of t){if(!n.dx._allTables[r])continue;const t=n.table(r),{primaryKey:s}=t.core.schema,i=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of o){const r=n.keys.map(i);switch(n.type){case"insert":s.outbound?yield t.bulkAdd(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),yield t.bulkAdd(n.values));break;case"upsert":s.outbound?yield t.bulkPut(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],s.keyPath,t)})),yield t.bulkPut(n.values));break;case"modify":1===r.length?yield t.update(r[0],n.changeSpec):yield t.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield At(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Tt=navigator.onLine,self.addEventListener("online",(()=>Tt=!0)),self.addEventListener("offline",(()=>Tt=!1)));const $t="dexie-cloud-syncer";function Dt(e,t){return e.where("i").between(t,1/0,!0).toArray()}function Lt(e,t,n){var r,o,s;if(!e.dx._allTables[t])return;const i=null===(s=null===(o=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===o?void 0:o.find((e=>e.prop===n)))||void 0===s?void 0:s.updatesTable;return i&&e.dx._allTables[i]?e.table(i):void 0}function Rt(e,t){return Y(this,void 0,void 0,(function*(){var r;const o={};let s,i=!1;for(const a of e)try{switch(a.type){case"u-s":{const e=Lt(t,a.table,a.prop);if(e){const t={k:a.k,u:a.u};a.r&&(t.r=a.r,s=a.r),o[e.name]=yield e.add(t)}break}case"u-ack":{const e=Lt(t,a.table,a.prop);e&&(yield t.transaction("rw",e,(t=>Y(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get($t);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:$t}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,a.i+1)}))})))));break}case"u-reject":{const e=Lt(t,a.table,a.prop);if(!e)break;const o=null===(r=yield e.get(a.i))||void 0===r?void 0:r.k;if(null!=o){yield t.transaction("rw",e,(t=>(t.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(a.i).filter((e=>0===n(e.k,o)&&1==(1&(e.f||0)))).delete())));const r=G.getDocCache(t.dx).find(a.table,o,a.prop);r&&r.destroy()}break}case"in-sync":{const e=G.getDocCache(t.dx).find(a.table,a.k,a.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":s=a.yServerRev;break;case"outdated-server-rev":i=!0}}catch(e){}return{receivedUntils:o,resyncNeeded:i,yServerRevision:s}}))}const Nt=1,Bt=2,Mt=3;function Ft(t,n,r){return Y(this,arguments,void 0,(function*(t,n,{yDownloadedRealms:r,realms:o}){if(r&&o&&o.every((e=>"*"===r[e])))return;const s=yield ke(t),i={"Content-Type":"application/json",Accept:"application/octet-stream"};s&&(i.Authorization=`Bearer ${s.accessToken}`);const a=yield fetch(`${n}/y/download`,{body:wt.stringify({downloadedRealms:r||{}}),method:"POST",headers:i,credentials:"include"});if(!a.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${a.status}`);yield async function(e,...t){var n,r,o;let s=e();for(let e=0;e<t.length;e++)s=t[e](s);try{for(var i,a=!0,l=ee(s);!(n=(i=await l.next()).done);a=!0)i.value,a=!1}catch(e){r={error:e}}finally{try{a||n||!(o=l.return)||await o.call(l)}finally{if(r)throw r.error}}}(function(e){return function(){return Q(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield X(t.read());if(e)return yield X(void 0);yield yield X(n)}}finally{t.releaseLock()}}))}}(a),ce,(function(r){return Q(this,arguments,(function*(){var o,s,i,a;let l=null,c=null,u=null,h=[];function b(e){return Y(this,void 0,void 0,(function*(){const r=h[h.length-1];if(h.length>0){if(!l||!c||!u)throw new Error(`Protocol error from ${n}/y/download`);const e=Lt(t,c,u);e&&(yield e.bulkAdd(h)),h=[]}l&&(c&&u&&r||e)&&(yield t.$syncState.update("syncState",(t=>{const n=t.yDownloadedRealms||{};n[l]=e?"*":{tbl:c,prop:u,key:r.k},t.yDownloadedRealms=n})))}))}try{try{for(var g,_=!0,w=ee(r);!(o=(g=yield X(w.next())).done);_=!0){a=g.value,_=!1;const e=new d(a);for(;v(e);)switch(m(e)){case Nt:yield X(b(!0)),l=f(e);break;case Bt:yield X(b(!1)),c=f(e),u=f(e);break;case Mt:{const t=p(e),n=y(e);h.push({k:t,u:n});break}}yield X(b(!1))}}catch(e){s={error:e}}finally{try{_||o||!(i=w.return)||(yield X(i.call(w)))}finally{if(s)throw s.error}}yield X(b(!0))}catch(t){throw t instanceof e.DexieError||(yield X(b(!1))),t}}))}))}))}const Wt="currentSyncWorker";function Kt(e,t,n,r){return Vt(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((o=>Y(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):Tt&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),yield new Promise((e=>setTimeout(e,500))),yield Kt(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Tt?"error":"offline",error:new Error(""+(null==o?void 0:o.message)||o)}),Promise.reject(o))}))))}function Vt(e,t,n){return Y(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:s,purpose:i}={isInitialSync:!1}){var a;if(!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:l}=t,c=yield e.getCurrentUser(),u=c.isLoggedIn?Me(e):[],d=u.map((t=>e.table(Fe(t.name)))),f=yield e.getPersistedSyncState(),p=c.isLoggedIn,y=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Me(e).filter((e=>!n.includes(e.name)))}(e,f):[];Ct(o);const h=y.length>0;if(h){if(s)return!0;yield e.transaction("rw",y,(e=>Y(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return Y(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==Oe.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==Oe.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==Oe.userId||(e.owner=t.userId),e.realmId&&e.realmId!==Oe.userId||(e.realmId=t.userId))})))}))}(y,c,null==f?void 0:f.realms)})))),Ct(o)}const[v,m,b,{yMessages:g,lastUpdateIds:_}]=yield e.transaction("r",e.tables,(()=>Y(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>u.some((t=>t.name===e.tableName))));let s=yield He(d,e);const i=yield function(e,t){return Y(this,void 0,void 0,(function*(){const n=[],r={};for(const o of t)if(o.schema.yProps)for(const t of o.schema.yProps){const s=e.table(t.updatesTable),i=yield s.get($t),a=(null==i?void 0:i.unsentFrom)||1,l=(null==i?void 0:i.receivedUntil)||0,c=Math.min(a,l+1),u=yield Dt(s,c);u.length>0&&(r[s.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<a)continue;const n=JSON.stringify(e.k)+"/"+t;let r=d[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(d[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:s,i:i}of Object.values(d)){const a=1===s.length?s[0]:J.mergeUpdatesV2(s);if(r)n.push({type:"u-c",table:o.name,prop:t.prop,k:e,u:a,i:i});else{const r=J.encodeStateVectorFromUpdateV2(a);n.push({type:"sv",table:o.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,u);if(Ct(o),h){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],a=yield function(e,t,n,r){return Y(this,void 0,void 0,(function*(){const o=`upload-${qe(8)}`;if(t.isLoggedIn&&e.length>0){const s=new Set(r||[]);return(yield Promise.all(e.map((e=>Y(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const i=n[e.name],a=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>{return r(e),!s.has(e.realmId||"")&&(t=r(e),!(n=null==i?void 0:i.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})):e.filter((e=>{const t=r(e);return!s.has(e.realmId||"")&&se(t)})),l=yield a.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.map(r),userId:t.userId,txid:o};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(y,c,n,e);return Ct(o),s=s.concat(a),[s,t,r,i]}return[s,t,r,i]})))),w=v.some((e=>e.muts.some((e=>e.keys.length>0))))||g.some((e=>"u-c"===e.type));if(s)return w;if("push"===i&&!w)return!1;const k=Ut(v,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||re(16);Ct(o);const x=yield Ot(v,g,m,b,e,l,n,S,c),{done:I,newSyncState:E}=yield e.transaction("rw",e.tables,(t=>Y(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))x.schema[e]&&(n[e]=x.schema[e]);yield e.$syncState.put(n,"schema");const r=yield He(d,e,{since:k});for(const t of d){const n=We(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(k[n]){const r=k[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}Ut(r,k),yield jt(e,n,k,x.serverRevision);const o=yield e.getPersistedSyncState();yield function(e,t,n){return Y(this,void 0,void 0,(function*(){const r=new Set,o=new Set,s=n?n.realms:[],i=n?n.inviteRealms:[],a=new Set(t.realms),l=new Set(t.realms.concat(t.inviteRealms));for(const e of s)a.has(e)||(o.add(e),l.has(e)||r.add(e));for(const e of i.concat(s))l.has(e)||r.add(e);if(r.size>0||o.size>0){const t=Me(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:o;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}if(o.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of o)delete n.yDownloadedRealms[e]}))}(e,x,o);const s=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};p&&(s.syncedTables=u.map((e=>e.name)).concat(y.map((e=>e.name)))),s.latestRevisions=k,s.remoteDbId=x.dbId,s.initiallySynced=!0,s.realms=x.realms,s.inviteRealms=x.inviteRealms,s.serverRevision=x.serverRevision,s.yServerRevision=x.serverRevision,s.timestamp=new Date,delete s.error;const i=Ht(x.changes,r);if(yield Pt(i,e),x.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield Rt(x.yMessages,e);r&&(s.yServerRevision=r),yield function(e,t,n){return Y(this,void 0,void 0,(function*(){var r,o,s,i,a;const l={};for(const[t,n]of Object.entries(e))null!==(r=l[t])&&void 0!==r||(l[t]={}),l[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(o=l[e])&&void 0!==o||(l[e]={}),l[e].receivedUntil=n;const c=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of c){const t=l[e],r=null!==(s=null==t?void 0:t.unsentFrom)&&void 0!==s?s:1,o=null!==(a=null!==(i=null==t?void 0:t.receivedUntil)&&void 0!==i?i:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==a?a:0;yield n.transaction("rw",e,(()=>Y(this,void 0,void 0,(function*(){const t=yield n.table(e).get($t);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(o,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:$t,unsentFrom:r,receivedUntil:o})}))))}}))}(_,t,e),n&&(s.yDownloadedRealms={})}return e.$syncState.put(s,"syncState"),{done:0===r.length,newSyncState:s}}))));if(!I)return yield Et(e),yield Vt(e,t,n,{isInitialSync:r,cancelToken:o});const O=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),C=!!x.yMessages;if(O&&C)try{yield Ft(e,l,E)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function Ht(e,t){const n={};le(n,e);const r={};return le(r,t),function(e,t){var n,r,o;for(const[s,i]of Object.entries(t))for(const[t,a]of Object.entries(i))switch(a.type){case"ups":{const r=null===(n=e[s])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[s][t]}}break;case"del":null===(r=e[s])||void 0===r||delete r[t];break;case"upd":{const n=null===(o=e[s])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))ne(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=re(16));const n={};for(const[t,r]of Object.entries(e))for(const[e,o]of Object.entries(r)){const r=n[t]||(n[t]={});(r[o.type]||(r[o.type]=[])).push(Object.assign({key:e},o))}const r=[];for(const[e,o]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(o))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}const qt=10,zt=1e4,Jt=1e3;function Gt(t){const n=[],r=new k(!0),o=new k(null);let s=!1,i=new Array(qt).fill(0);return o.subscribe((()=>Y(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,i.shift(),i.push(Date.now()),r.next(!1);try{yield function(){return Y(this,void 0,void 0,(function*(){for(var r,o,s,i,a,l;n.length>0;){const c=n.shift();try{yield b(t.cloud.syncState.pipe(R((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!c)continue;switch(c.type){case"token-expired":const u=t.cloud.currentUser.value,d=yield xe(t.cloud.options.databaseUrl,u);yield t.table("$logins").update(u.userId,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(c.realm))||(null===(o=null==n?void 0:n.inviteRealms)||void 0===o?void 0:o.includes(c.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(s=null==n?void 0:n.realms)||void 0===s?void 0:s.includes(c.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(i=null==n?void 0:n.realms)||void 0===i?void 0:i.includes(c.realm))||(null===(a=null==n?void 0:n.inviteRealms)||void 0===a?void 0:a.includes(c.realm)))&&(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield t.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(l=t.cloud.syncState.value)||void 0===l?void 0:l.phase)){fe(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>Y(this,void 0,void 0,(function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,s]=yield Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(!o||!r||!s)return;if(c.baseRev!==o.serverRevision)return void("string"!=typeof c.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||fe(t,"pull"));if((yield e.waitFor(Be(o)))!==c.realmSetHash)return void fe(t,"pull");let i=[];if(s.isLoggedIn){const e=Me(t).map((e=>t.table(Fe(e.name))));i=yield He(e,t)}if(c.changes.length>0){const e=Ht(c.changes,i);yield Pt(e,t)}o.latestRevisions=Ut(i,o.latestRevisions),o.serverRevision=c.newRev,yield jt(t,r,o.latestRevisions,c.newRev),yield t.$syncState.put(o,"syncState")}))))}}catch(e){}}}))}()}finally{i[i.length-1]-i[0]<zt&&(yield new Promise((e=>setTimeout(e,Jt)))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),o.next(null)},readyToServe:r}}const Yt=new WeakMap,Zt={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Xt=0;function Qt(e){"vip"in e&&(e=e.vip);let t=Yt.get(e.cloud);if(!t){const n=new S;let r=new Ne(`syncstatechanged-${e.name}`),o=new Ne(`synccomplete-${e.name}`);n.id=++Xt;let s=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return s},localSyncEvent:n,get syncStateChangedEvent(){return r},get syncCompleteEvent(){return o},dx:e};const i={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||Oe)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){r=new Ne(`syncstatechanged-${e.name}`),o=new Ne(`synccomplete-${e.name}`)}};Object.assign(t,i),t.messageConsumer=Gt(t),t.messageProducer=new S,Yt.set(e.cloud,t)}return t}const en="undefined"!=typeof InstallTrigger,tn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),nn=tn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,rn=tn&&nn<=605||en,on="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:sn}={};function an(e){return sn.call(e).slice(8,-1)}function ln(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const cn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let un=0;function dn(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();un>=o?++un:un=o,r[0]=un/1099511627776,r[1]=un/4294967296,r[2]=un/16777216,r[3]=un/65536,r[4]=un/256,r[5]=un;const s=new Uint8Array(n.buffer,6);crypto.getRandomValues(s);return e+ot(new Uint8Array(n.buffer))+(t||"")}function fn(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const o=n.table(r);return Object.assign(Object.assign({},o),{mutate:n=>{var s,i;const a=n.trans;if("versionchange"===a.mode&&(a.disableChangeTracking=!0,a.disableAccessControl=!0),a.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const a=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==a?void 0:a.generatedGlobalId){if((null===(i=t.cloud.options)||void 0===i?void 0:i.databaseUrl)&&!t.initiallySynced){const e=ln(o.schema.primaryKey,n);return o.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(n)}))}return function(n,s){let i=null;const a=ln(o.schema.primaryKey,n);return a.forEach(((l,c)=>{if(void 0===l){const r=n.values[c].realmId||t.cloud.currentUserId,l=r.substr(r.length-3);a[c]=dn(s,l),o.schema.primaryKey.outbound||(i||(i=n.values.slice()),i[c]=e.deepClone(i[c]),e.setByKeyPath(i[c],o.schema.primaryKey.keyPath,a[c]))}else if("string"!=typeof l||!l.startsWith(s)&&!l.startsWith("#"+s))throw new e.ConstraintError(`The ID "${l}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${s}" (or "#${s}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate(Object.assign(Object.assign({},n),{keys:a,values:i||n.values}))}(n,a.idPrefix)}if(null==a?void 0:a.markedForSync){ln(o.schema.primaryKey,n).forEach(((t,n)=>{if(!se(t)){const n=Array.isArray(t)?t.map(an).join(","):an(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(n)}})}})}}let pn=0;function yn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),s=o.length,i=(s>0?o[s-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>{r.splice(r.indexOf(i))}));return r.push(i),i}}function hn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let s=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(i=r,new Promise((e=>{0===i.length&&e([]);let t=i.length;const n=new Array(t);i.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>{o.shift()}));var i;return o.push(s),s}}const vn=new k(new Set);function mn(e){var t,n,r,o;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)}function bn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const o=new Set(n.schema.tables.map((e=>e.name))),s=n.schema.tables.filter((e=>!/^\$/.test(e.name))),i=new Map;for(const e of s){const t=`$${e.name}_mutations`;o.has(t)&&i.set(e.name,n.table(t))}return Object.assign(Object.assign({},n),{transaction:(r,o)=>{let s;if("readwrite"===o){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>Fe(e)));s=n.transaction([...r,...e],o)}else s=n.transaction(r,o);if("readwrite"===o){s.txid=qe(16),s.opCount=0,s.currentUser=e.value,vn.value.add(s),vn.next(vn.value);const n=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",n),s.removeEventListener("abort",n),vn.value.delete(s),vn.next(vn.value)},r=()=>{s.mutationsAdded&&!mn(t)&&fe(t,"push"),n()};s.addEventListener("complete",r),s.addEventListener("error",n),s.addEventListener("abort",n)}return s},table:e=>{const o=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},o),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),o.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},o),{mutate:e=>o.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):o;const{schema:s}=o,a=i.get(e);return a?function(e){const t="$lock"+ ++pn;return Object.assign(Object.assign({},e),{count:yn(e.count,t),get:yn(e.get,t),getMany:yn(e.getMany,t),openCursor:yn(e.openCursor,t),query:yn(e.query,t),mutate:hn(e.mutate,t)})}(Object.assign(Object.assign({},o),{mutate:n=>{var r,i,a;const c=n.trans;return c.txid?c.disableChangeTracking?o.mutate(n):(null===(i=null===(r=t.cloud.schema)||void 0===r?void 0:r[e])||void 0===i?void 0:i.markedForSync)&&(null===(a=c.currentUser)||void 0===a?void 0:a.isLoggedIn)?"deleteRange"===n.type?o.query({query:{range:n.range,index:s.primaryKey},trans:n.trans,values:!1}).then((e=>l({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):l(n):o.mutate(n):o.mutate(n)}})):o;function l(n){var i,l;const c=n.trans,u=null===(l=null===(i=t.cloud.options)||void 0===i?void 0:i.unsyncedProperties)||void 0===l?void 0:l[e],{txid:d,currentUser:{userId:f}}=c,{type:p}=n,y=++c.opCount;function h(e){if(!u)return e;let t=e;for(const n of Object.keys(e))u.some((e=>n===e||n.startsWith(e+".")))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return o.mutate(n).then((e=>{var t;const{numFailures:o,failures:i}=e;let l="delete"===p?n.keys:e.results,v="values"in n?n.values:[],m="changeSpec"in n?n.changeSpec:void 0,b="updates"in n?n.updates:void 0;if(o&&(l=l.filter(((e,t)=>!i[t])),v=v.filter(((e,t)=>!i[t]))),u){if(v=v.map((e=>{const t=Object.assign({},e);for(const e of u)delete t[e];return t})),m&&(m=h(m),0===Object.keys(m).length))return e;if(b){let e=b.changeSpecs.map(h),t={keys:[],changeSpecs:[]};const n=new r;let o=!1;for(let r=0,s=e.length;r<s;++r)Object.keys(e[r]).length>0?(t.keys.push(b.keys[r]),t.changeSpecs.push(e[r]),n.addKey(b.keys[r])):o=!0;if(b=t,o){let e=[],t=[];for(let r=0,o=l.length;r<o;++r)n.hasKey(l[r])&&(e.push(l[r]),t.push(v[r]));l=e,v=t}}}const g=Date.now();let _="criteria"in n&&n.criteria?Object.assign(Object.assign({},n.criteria),{index:n.criteria.index===s.primaryKey.keyPath?null:n.criteria.index}):void 0;if(u&&(null==_?void 0:_.index)){const e=null===(t=s.indexes.find((e=>e.name===_.index)))||void 0===t?void 0:t.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(_=void 0)}const w="delete"===n.type?{type:"delete",ts:g,opNo:y,keys:l,criteria:_,txid:d,userId:f}:"add"===n.type?{type:"insert",ts:g,opNo:y,keys:l,txid:d,userId:f,values:v}:_&&m?{type:"modify",ts:g,opNo:y,keys:l,criteria:_,changeSpec:m,txid:d,userId:f}:m?{type:"update",ts:g,opNo:y,keys:l,changeSpecs:l.map((()=>m)),txid:d,userId:f}:b?{type:"update",ts:g,opNo:y,keys:b.keys,changeSpecs:b.changeSpecs,txid:d,userId:f}:{type:"upsert",ts:g,opNo:y,keys:l,values:v,txid:d,userId:f};return"isAdditionalChunk"in n&&n.isAdditionalChunk&&(w.isAdditionalChunk=!0),l.length>0||_?a.mutate({type:"add",trans:c,values:[w]}).then((()=>(c.mutationsAdded=!0,e))):e}))}}})}}}function gn(e,t){return function(n,r){var o;const s=Object.assign(Object.assign({},Zt),n);Object.keys(Zt).forEach((e=>{const t=s[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),o=Zt[e].split(",").map((e=>e.trim())),i=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==o[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(Zt[e])}`);for(let t=1;t<o.length;++t){const n=o[t];i.has(n.replace(/([&*]|\+\+)/g,""))||(s[e]+=`,${n}`)}}));const i=t.cloud.schema||(t.cloud.schema={}),a=new Set;Object.keys(s).forEach((e=>{const t=s[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(s[e]=s[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(cn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,s;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)o=n,r=(1&(s=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&s?o[1].toUpperCase():o[1].toLowerCase())+(4&s?o[2].toUpperCase():o[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,a),a.add(n.idPrefix)),/^\$/.test(e)||(s[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,s[`$${e}_mutations`]=null)}));const l=e.call(this,s,r);for(const[e,t]of Object.entries(r))if(null===(o=t.yProps)||void 0===o?void 0:o.length){const n=i[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return l}}function _n(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const wn=new k(!0),kn=new k(!0);wn.pipe(N((e=>e?x(!0):x(!1).pipe(B(2e4)))),M()).subscribe(kn);const Sn="undefined"!=typeof document?I(document,"visibilitychange"):x({}),xn=Sn.pipe(R((()=>"hidden"===document.visibilityState))),In=Sn.pipe(R((()=>"visible"===document.visibilityState))),En="undefined"!=typeof window?E(In,I(window,"mousedown"),I(window,"mousemove"),I(window,"keydown"),I(window,"wheel"),I(window,"touchmove")):x({});"undefined"!=typeof document&&E(x(!0),xn,En).pipe(F((()=>"visible"===document.visibilityState)),W((e=>{wn.value!==e&&wn.next(e)})),N((e=>e?x(0).pipe(B(16e4),W((()=>wn.next(!1)))):x(0)))).subscribe((()=>{}));class On extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function Cn(t){var n,r;if(!(null===(n=t.cloud.options)||void 0===n?void 0:n.awarenessProtocol))throw new e.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');return null===(r=t.cloud.options)||void 0===r?void 0:r.awarenessProtocol}const Tn=new WeakMap,jn=new WeakMap;function Un(e){let t=jn.get(e);return t||(t=new S,jn.set(e,t)),t}class An extends w{constructor(e,t,n,r,o,s,i,a){super((l=>new $n(e,t,n,r,o,a,l,s,i)))}}let Pn=0;class $n extends j{constructor(e,t,n,r,o,s,i,a,l){super((()=>this.teardown())),this.id=++Pn,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=o,this.user=s,this.subscriber=i,this.lastUserActivity=new Date,this.messageProducer=a,this.webSocketStatus=l,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return Y(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new On);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>Y(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else this.reconnect()}))),3e4);const t=new URL(this.databaseUrl);t.protocol="http:"===t.protocol?"ws":"wss";const n=new URLSearchParams;if(this.subscriber.closed)return;n.set("v","2"),this.rev&&n.set("rev",this.rev),this.yrev&&n.set("yrev",this.yrev),n.set("realmsHash",this.realmSetHash),n.set("clientId",this.clientIdentity),n.set("dxcv",this.db.cloud.version),this.user.accessToken&&n.set("token",this.user.accessToken);const r=this.ws=new WebSocket(`${t}/changes?${n}`);r.binaryType="arraybuffer",r.onclose=e=>{this.pinger&&this.reconnect()},r.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?wt.parse(e.data):function(e){const t=new d(e),n=f(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:f(t)};const r=f(t),o=f(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:o,i:Number(h(t))};default:{const e=p(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:o,k:e};case"aware":return{type:n,table:r,prop:o,k:e,u:y(t)};case"doc-open":return{type:n,table:r,prop:o,k:e,serverRev:p(t),sv:p(t)};case"sv":return{type:n,table:r,prop:o,k:e,sv:y(t)};case"u-c":return{type:n,table:r,prop:o,k:e,u:y(t),i:Number(h(t))};case"u-s":return{type:n,table:r,prop:o,k:e,u:y(t),r:t.pos<t.arr.length&&f(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=G.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Tn.get(e))(e);if(n){Cn(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=G.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&Un(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?Rt([t],this.db).then((e=>Y(this,[e],void 0,(function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=Lt(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update($t,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{r.onopen=n=>{e=!0,t(null)},r.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(wt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new s;switch(i(t,e.type),"table"in e&&i(t,e.table),"prop"in e&&i(t,e.prop),e.type){case"u-ack":case"u-reject":c(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":i(t,e.yServerRev);break;default:switch(a(t,e.k),e.type){case"aware":l(t,e.u);break;case"doc-open":a(t,e.serverRev),a(t,e.sv);break;case"doc-close":break;case"sv":l(t,e.sv);break;case"u-c":l(t,e.u),c(t,BigInt(e.i));break;case"u-s":l(t,e.u),i(t,e.r||"")}}return u(t)}(e)))}))),this.user.isLoggedIn&&!mn(this.db)&&this.subscriptions.add(function(e){const t=Ve(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return E(...t.map((({table:t,ydocProp:n,updatesTable:r})=>{const s=e.table(r);return g(s.get($t)).pipe(O((e=>{let r=(null==e?void 0:e.unsentFrom)||1;return g(o((()=>Y(this,void 0,void 0,(function*(){return(yield Dt(s,r)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:t,prop:n,k:e.k,u:e.u,i:e.i})))}))))).pipe(C((e=>{e.length>0&&(r=e.at(-1).i+1)})))})))}))).pipe(T((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class Dn extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function Ln(e){return Y(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield b(En)}))}function Rn(e){return Y(this,void 0,void 0,(function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Kt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const Nn=new WeakMap;function Bn(e,t,n,r){const o=Nn.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return o.promise;{let s=!1;const i=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(s=!0)}));return o.promise.then((()=>{i.unsubscribe()})).catch((e=>(i.unsubscribe(),Promise.reject(e)))).then((()=>{if(!s)return Bn(e,t,n,r)}))}}const s=function(){return Y(this,void 0,void 0,(function*(){try{yield Et(e),yield _n(e,Wt,(()=>Kt(e,t,n,r))),Nn.delete(e)}catch(t){throw Nn.delete(e),t}}))}();return Nn.set(e,{promise:s,pull:"push"!==(null==r?void 0:r.purpose)}),s}const Mn=1e3;function Fn(e,t,n){let r=null,o={cancelled:!1},s=0,i=0;function a(r=1){setTimeout((()=>{const f=l?"pull":"push";i=Date.now(),Bn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:f}).then((()=>{if(o.cancelled)d();else if(l||c)return l=!1,c=!1,a();u=!1,s=0,i=0})).catch((e=>{if(o.cancelled)d(),u=!1,s=0,i=0;else if(r<5){const e=[0,20,40,300,900][r]*Mn;s=Date.now()+e,i=0,setTimeout((()=>a(r+1)),e)}else u=!1,s=0,i=0}))}),0)}let l=!1,c=!1,u=!1;const d=()=>{o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{(e=>{o.cancelled||("pull"===e&&(l=!0),"push"===e&&(c=!0),u?s||i>0&&Date.now():(u=!0,a()))})(e||"pull")}))},stop:d}}function Wn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Kn,Vn,Hn,qn,zn,Jn={},Gn=[],Yn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Zn(e,t){for(var n in t)e[n]=t[n];return e}function Xn(e){var t=e.parentNode;t&&t.removeChild(e)}function Qn(e,t,n){var r,o,s,i={};for(s in t)"key"==s?r=t[s]:"ref"==s?o=t[s]:i[s]=t[s];if(arguments.length>2&&(i.children=arguments.length>3?Kn.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(s in e.defaultProps)void 0===i[s]&&(i[s]=e.defaultProps[s]);return er(e,i,r,o,null)}function er(e,t,n,r,o){var s={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++Hn:o};return null==o&&null!=Vn.vnode&&Vn.vnode(s),s}function tr(e){return e.children}function nr(e,t){this.props=e,this.context=t}function rr(e,t){if(null==t)return e.__?rr(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?rr(e):null}function or(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return or(e)}}function sr(e){(!e.__d&&(e.__d=!0)&&qn.push(e)&&!ir.__r++||zn!==Vn.debounceRendering)&&((zn=Vn.debounceRendering)||setTimeout)(ir)}function ir(){for(var e;ir.__r=qn.length;)e=qn.sort((function(e,t){return e.__v.__b-t.__v.__b})),qn=[],e.some((function(e){var t,n,r,o,s,i;e.__d&&(s=(o=(t=e).__v).__e,(i=t.__P)&&(n=[],(r=Zn({},o)).__v=o.__v+1,yr(i,o,r,t.__n,void 0!==i.ownerSVGElement,null!=o.__h?[s]:null,n,null==s?rr(o):s,o.__h),hr(n,o),o.__e!=s&&or(o)))}))}function ar(e,t,n,r,o,s,i,a,l,c){var u,d,f,p,y,h,v,m=r&&r.__k||Gn,b=m.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(p=n.__k[u]=null==(p=t[u])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?er(null,p,null,null,p):Array.isArray(p)?er(tr,{children:p},null,null,null):p.__b>0?er(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=m[u])||f&&p.key==f.key&&p.type===f.type)m[u]=void 0;else for(d=0;d<b;d++){if((f=m[d])&&p.key==f.key&&p.type===f.type){m[d]=void 0;break}f=null}yr(e,p,f=f||Jn,o,s,i,a,l,c),y=p.__e,(d=p.ref)&&f.ref!=d&&(v||(v=[]),f.ref&&v.push(f.ref,null,p),v.push(d,p.__c||y,p)),null!=y?(null==h&&(h=y),"function"==typeof p.type&&p.__k===f.__k?p.__d=l=lr(p,l,e):l=cr(e,p,f,m,y,l),"function"==typeof n.type&&(n.__d=l)):l&&f.__e==l&&l.parentNode!=e&&(l=rr(f))}for(n.__e=h,u=b;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=rr(r,u+1)),br(m[u],m[u]));if(v)for(u=0;u<v.length;u++)mr(v[u],v[++u],v[++u])}function lr(e,t,n){for(var r,o=e.__k,s=0;o&&s<o.length;s++)(r=o[s])&&(r.__=e,t="function"==typeof r.type?lr(r,t,n):cr(n,r,r,o,r.__e,t));return t}function cr(e,t,n,r,o,s){var i,a,l;if(void 0!==t.__d)i=t.__d,t.__d=void 0;else if(null==n||o!=s||null==o.parentNode)e:if(null==s||s.parentNode!==e)e.appendChild(o),i=null;else{for(a=s,l=0;(a=a.nextSibling)&&l<r.length;l+=2)if(a==o)break e;e.insertBefore(o,s),i=s}return void 0!==i?i:o.nextSibling}function ur(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Yn.test(t)?n:n+"px"}function dr(e,t,n,r,o){var s;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||ur(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||ur(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])s=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+s]=n,n?r||e.addEventListener(t,s?pr:fr,s):e.removeEventListener(t,s?pr:fr,s);else if("dangerouslySetInnerHTML"!==t){if(o)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function fr(e){this.l[e.type+!1](Vn.event?Vn.event(e):e)}function pr(e){this.l[e.type+!0](Vn.event?Vn.event(e):e)}function yr(e,t,n,r,o,s,i,a,l){var c,u,d,f,p,y,h,v,m,b,g,_,w,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(l=n.__h,a=t.__e=n.__e,t.__h=null,s=[a]),(c=Vn.__b)&&c(t);try{e:if("function"==typeof k){if(v=t.props,m=(c=k.contextType)&&r[c.__c],b=c?m?m.props.value:c.__:r,n.__c?h=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(v,b):(t.__c=u=new nr(v,b),u.constructor=k,u.render=gr),m&&m.sub(u),u.props=v,u.state||(u.state={}),u.context=b,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=Zn({},u.__s)),Zn(u.__s,k.getDerivedStateFromProps(v,u.__s))),f=u.props,p=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&v!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(v,b),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(v,u.__s,b)||t.__v===n.__v){u.props=v,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&i.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(v,u.__s,b),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(f,p,y)}))}if(u.context=b,u.props=v,u.__v=t,u.__P=e,g=Vn.__r,_=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,g&&g(t),c=u.render(u.props,u.state,u.context);else do{u.__d=!1,g&&g(t),c=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++_<25);u.state=u.__s,null!=u.getChildContext&&(r=Zn(Zn({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(y=u.getSnapshotBeforeUpdate(f,p)),w=null!=c&&c.type===tr&&null==c.key?c.props.children:c,ar(e,Array.isArray(w)?w:[w],t,n,r,o,s,i,a,l),u.base=t.__e,t.__h=null,u.__h.length&&i.push(u),h&&(u.__E=u.__=null),u.__e=!1}else null==s&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=vr(n.__e,t,n,r,o,s,i,l);(c=Vn.diffed)&&c(t)}catch(e){t.__v=null,(l||null!=s)&&(t.__e=a,t.__h=!!l,s[s.indexOf(a)]=null),Vn.__e(e,t,n)}}function hr(e,t){Vn.__c&&Vn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Vn.__e(e,t.__v)}}))}function vr(e,t,n,r,o,s,i,a){var l,c,u,d=n.props,f=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=s)for(;y<s.length;y++)if((l=s[y])&&"setAttribute"in l==!!p&&(p?l.localName===p:3===l.nodeType)){e=l,s[y]=null;break}if(null==e){if(null===p)return document.createTextNode(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),s=null,a=!1}if(null===p)d===f||a&&e.data===f||(e.data=f);else{if(s=s&&Kn.call(e.childNodes),c=(d=n.props||Jn).dangerouslySetInnerHTML,u=f.dangerouslySetInnerHTML,!a){if(null!=s)for(d={},y=0;y<e.attributes.length;y++)d[e.attributes[y].name]=e.attributes[y].value;(u||c)&&(u&&(c&&u.__html==c.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,o){var s;for(s in n)"children"===s||"key"===s||s in t||dr(e,s,null,n[s],r);for(s in t)o&&"function"!=typeof t[s]||"children"===s||"key"===s||"value"===s||"checked"===s||n[s]===t[s]||dr(e,s,t[s],n[s],r)}(e,f,d,o,a),u)t.__k=[];else if(y=t.props.children,ar(e,Array.isArray(y)?y:[y],t,n,r,o&&"foreignObject"!==p,s,i,s?s[0]:n.__k&&rr(n,0),a),null!=s)for(y=s.length;y--;)null!=s[y]&&Xn(s[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y||"option"===p&&y!==d.value)&&dr(e,"value",y,d.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&dr(e,"checked",y,d.checked,!1))}return e}function mr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Vn.__e(e,n)}}function br(e,t,n){var r,o;if(Vn.unmount&&Vn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||mr(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Vn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&br(r[o],t,"function"!=typeof e.type);n||null==e.__e||Xn(e.__e),e.__e=e.__d=void 0}function gr(e,t,n){return this.constructor(e,n)}function _r(e,t,n){var r,o,s;Vn.__&&Vn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,s=[],yr(t,e=(!r&&n||t).__k=Qn(tr,null,[e]),o||Jn,Jn,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?Kn.call(t.childNodes):null,s,!r&&n?n:o?o.__e:t.firstChild,r),hr(s,e)}Kn=Gn.slice,Vn={__e:function(e,t,n,r){for(var o,s,i;t=t.__;)if((o=t.__c)&&!o.__)try{if((s=o.constructor)&&null!=s.getDerivedStateFromError&&(o.setState(s.getDerivedStateFromError(e)),i=o.__d),null!=o.componentDidCatch&&(o.componentDidCatch(e,r||{}),i=o.__d),i)return o.__E=o}catch(t){e=t}throw e}},Hn=0,nr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Zn({},this.state),"function"==typeof e&&(e=e(Zn({},n),this.props)),e&&Zn(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),sr(this))},nr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),sr(this))},nr.prototype.render=tr,qn=[],ir.__r=0;const wr={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function kr({children:e,className:t}){return Qn("div",{className:t},Qn("div",{style:wr.Darken}),Qn("div",{style:wr.DialogOuter},Qn("div",{style:wr.DialogInner},e)))}var Sr,xr,Ir,Er,Or=0,Cr=[],Tr=[],jr=Vn.__b,Ur=Vn.__r,Ar=Vn.diffed,Pr=Vn.__c,$r=Vn.unmount;function Dr(e,t){Vn.__h&&Vn.__h(xr,e,Or||t),Or=0;var n=xr.__H||(xr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:Tr}),n.__[e]}function Lr(e){return Or=1,function(e,t,n){var r=Dr(Sr++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Kr(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=xr,!xr.u)){xr.u=!0;var o=xr.shouldComponentUpdate;xr.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var s=r.__c.__H.__.filter((function(e){return e.__c}));if(s.every((function(e){return!e.__N})))return!o||o.call(this,e,t,n);var i=!1;return s.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(i=!0)}})),!!i&&(!o||o.call(this,e,t,n))}}return r.__N||r.__}(Kr,e)}function Rr(e){return Or=5,function(e,t){var n=Dr(Sr++,7);return Wr(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function Nr(){for(var e;e=Cr.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Mr),e.__H.__h.forEach(Fr),e.__H.__h=[]}catch(t){e.__H.__h=[],Vn.__e(t,e.__v)}}Vn.__b=function(e){xr=null,jr&&jr(e)},Vn.__r=function(e){Ur&&Ur(e),Sr=0;var t=(xr=e.__c).__H;t&&(Ir===xr?(t.__h=[],xr.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Tr,e.__N=e.i=void 0}))):(t.__h.forEach(Mr),t.__h.forEach(Fr),t.__h=[])),Ir=xr},Vn.diffed=function(e){Ar&&Ar(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Cr.push(t)&&Er===Vn.requestAnimationFrame||((Er=Vn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Br&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Br&&(t=requestAnimationFrame(n))})(Nr)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Tr&&(e.__=e.__V),e.i=void 0,e.__V=Tr}))),Ir=xr=null},Vn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Mr),e.__h=e.__h.filter((function(e){return!e.__||Fr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Vn.__e(n,e.__v)}})),Pr&&Pr(e,t)},Vn.unmount=function(e){$r&&$r(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{Mr(e)}catch(e){t=e}})),t&&Vn.__e(t,n.__v))};var Br="function"==typeof requestAnimationFrame;function Mr(e){var t=xr,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),xr=t}function Fr(e){var t=xr;e.__c=e.__(),xr=t}function Wr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Kr(e,t){return"function"==typeof t?t(e):t}function Vr({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}function Hr({title:e,type:t,alerts:n,fields:r,submitLabel:o,cancelLabel:s,onCancel:i,onSubmit:a}){const[l,c]=Lr({}),u=Rr(null);return function(e,t){var n=Dr(Sr++,4);!Vn.__s&&Wr(n.__H,t)&&(n.__=e,n.i=t,xr.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Qn(kr,{className:"dxc-login-dlg"},Qn(tr,null,Qn("h3",{style:wr.WindowHeader},e),n.map((e=>Qn("p",{style:wr.Alert[e.type]},Vr(e)))),Qn("form",{onSubmit:e=>{e.preventDefault(),a(l)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],o)=>Qn("label",{style:wr.Label,key:o},n?`${n}: `:"",Qn("input",{ref:0===o?u:void 0,type:t,name:e,autoComplete:"on",style:wr.Input,autoFocus:!0,placeholder:r,value:l[e]||"",onInput:n=>{var r;const o=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let s=Object.assign(Object.assign({},l),{[e]:o});c(s),"otp"===t&&8===(null==o?void 0:o.trim().length)&&a(s)}})))))),Qn("div",{style:wr.ButtonsDiv},Qn(tr,null,Qn("button",{type:"submit",style:wr.Button,onClick:()=>a(l)},o),s&&Qn("button",{style:wr.Button,onClick:i},s))))}class qr extends nr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=g(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?Qn(Hr,Object.assign({},t)):null}}function zr(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const Jr=zr((e=>new k(Oe)));function Gr(e,t){let n=t,r=g(e).pipe(P((e=>n=e)),$({resetOnRefCountZero:()=>D(1e3)}));const o=new w((e=>{let t=!1;const o=r.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||o.closed||e.next(n),o}));return o.getValue=()=>n,o}const Yr=zr((e=>Gr(o((()=>e.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),Zr=zr((e=>Gr(Jr(e._novip).pipe(N((t=>o((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:t.userId}).toArray(),e.realms.toArray(),t.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function Xr(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,o=t[e];t[e]=[...new Set([...o,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const Qr=zr((e=>function(e,t){let n;const r=e.pipe(P((e=>n=t(e))));return r.getValue=()=>void 0!==n?n:n=t(e.getValue()),r}(Gr(A([Zr(e._novip),Yr(e._novip)]).pipe(F((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:Oe.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const o=t.map((t=>{const o=e.filter((e=>e.realmId===t.realmId)),s=o.map((e=>e.permissions)).filter((e=>e)),i=Ve(o.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:Xr(...s,...i)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return o}))));class eo{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const to=zr((e=>{const t=Jr(e._novip).pipe(N((t=>o((()=>e.members.where({email:t.email||""}).toArray()))))),n=Qr(e._novip),r=Zr(e._novip);return Gr(A([t,r,n]).pipe(F((([t,n,r])=>{const o=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),s=t.reduce(o,{}),i=n.selfMembers.reduce(o,s);return Object.values(i).filter((e=>!e.accepted)).map((t=>Object.assign(Object.assign({},t),{accept(){return Y(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return Y(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function no(e){return t=>{var r;const o=t.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:s}=o.meta||{};if(!(null===(r=e.cloud.schema)||void 0===r?void 0:r[s].markedForSync))return;let i;Object.defineProperty(t,"awareness",{get:()=>i||(i=function(e,t,r){const{parentTable:o,parentId:s,parentProp:i,updatesTable:a}=t.meta,l=Cn(e),c=new l.Awareness(t),u=Un(t);return c.on("update",(({added:n,updated:s,removed:a},u)=>{const d=n.concat(s).concat(a),f=e.cloud.currentUser.value;if("server"!==u&&f.isLoggedIn&&!mn(e)){const n=l.encodeAwarenessUpdate(c,d);e.messageProducer.next({type:"aware",table:o,prop:i,k:t.meta.parentId,u:n}),r.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:i,k:t.meta.parentId})}})),c.on("destroy",(()=>{l.removeAwarenessStates(c,[t.clientID],"provider destroyed")})),(()=>{Y(this,void 0,void 0,(function*(){if(r.destroyed)return;let t=!1,l=1;const c=A([e.cloud.webSocketStatus,u.pipe(L(null))]).subscribe((([n])=>{if(r.destroyed)return;t="connected"===n;const o=e.cloud.currentUser.value;"connected"===n&&o.isLoggedIn&&!mn(e)&&(++l,d().catch((e=>{})))}));function d(){return Y(this,void 0,void 0,(function*(){const c=l,u=e.table(a),d=e.$syncState,[f,p]=yield e.transaction("r",d,u,(()=>Y(this,void 0,void 0,(function*(){const e=yield u.get($t),t=yield d.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(r.destroyed||l!==c||!t)return;const y={type:"doc-open",table:o,prop:i,k:s,serverRev:p},h=yield u.where("i").between(f,1/0,!1).filter((e=>0===n(e.k,s)&&0==(1&(e.f||0)))).toArray();if(!r.destroyed&&l===c&&t){if(h.length>0){const e=J.mergeUpdatesV2(h.map((e=>e.u))),t=J.encodeStateVectorFromUpdateV2(e);y.sv=t}e.messageProducer.next(y)}}))}r.addCleanupHandler(c)}))})(),c}(e,o,t),Tn.set(o,i),i)})}}function ro(e){return"rlm~"+e}function oo(e){return e.startsWith("rlm~")?e.substr(4):null}const so={},io=new WeakMap,ao=co("tx"),lo=co("unload");function co(e){let t=null,n=!1,r=new Map;return{name:e,run(){return Y(this,void 0,void 0,(function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch((()=>{}))),setTimeout((()=>{n=!1;const e=r;r=new Map,t=function(e){return Y(this,void 0,void 0,(function*(){for(const{db:t,parentId:n,triggers:r,parentTable:o,prop:s}of e.values()){const e=G.getOrCreateDocument(t,o,s,n);try{const t=G.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{G.release(e)}}}))}(e).finally((()=>{t=null}))}),0))}))},enqueue(e,t,n,o,s){const i=`${e.name}:${t}:${n}:${o}`;let a=r.get(i);a||(a={db:e,parentTable:t,parentId:n,prop:o,triggers:new Set},r.set(i,a)),a.triggers.add(s)}}}function uo(){ao.run()}function fo(){lo.run()}function po(e,t,n){var o,s;const i=null===(s=null===(o=e.schema.yProps)||void 0===o?void 0:o.find((e=>e.prop===t)))||void 0===s?void 0:s.updatesTable;if(!i)throw new Error(`Table ${e.name} does not have a Yjs property named ${t}`);so[i]={trigger:n,parentTable:e.name,prop:t};const a=e.db._novip;let l=io.get(a);l||(l=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:t=>Object.assign(Object.assign({},t),{transaction:(e,n,r)=>{const o=t.transaction(e,n,r);return"readonly"===n?o:e.some((e=>so[e]))?(o.addEventListener("complete",uo),o):o},table:n=>{const o=t.table(n),s=so[n];if(!s)return o;const{trigger:i,parentTable:a,prop:l}=s;return Object.assign(Object.assign({},o),{mutate(t){var n;switch(t.type){case"add":for(const r of t.values){if(null==r.k)continue;const t=r.k,o=G.getDocCache(e).find(a,t,l);(o&&(null===(n=G.for(o))||void 0===n?void 0:n.refCount)?lo:ao).enqueue(e,a,t,l,i)}break;case"delete":t.trans._rejecting_y_ypdate&&o.getMany({keys:t.keys,trans:t.trans,cache:"immutable"}).then((t=>{const n=new r;for(const{k:e}of t)null!=e&&n.addKey(e);for(const t of n)ao.enqueue(e,a,t.from,l,i)}))}return o.mutate(t)}})}})}))(a),io.set(a,l)),a.use(l),G.on("beforeunload",fo)}const yo={nameSuffix:!0};function ho(t){const n=t.name,r=Jr(t),s=[];let i=!1,a=null;t.on("ready",(t=>Y(this,void 0,void 0,(function*(){try{yield function(t){return Y(this,void 0,void 0,(function*(){var n,d,f,p,y,h,v;l=!1;const m=Qt(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(n=m.cloud.options)||void 0===n?void 0:n.customLoginGui)||s.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),_r(Qn(qr,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),_r(Qn(qr,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),m.cloud.isServiceWorkerDB||s.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(N((e=>{const n=t;t=e;const r=x(e);switch(e){case"disconnected":return wn.value?r.pipe(H(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(H(4e3));default:return r}})));return A([n,e.syncStateChangedEvent.pipe(q({phase:"initial"})),Jr(e.dx._novip),kn]).pipe(F((([t,n,r,o])=>{var s;if((null===(s=r.license)||void 0===s?void 0:s.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:i,error:a,progress:l}=n,c=t;return"error"===i&&(c="error"),"not-started"===t&&("pushing"!==i&&"pulling"!==i||(c="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(c="connecting"),o||(c="disconnected"),{phase:i,error:a,progress:l,status:Tt?c:"offline",license:"ok"}})))}(m).subscribe(t.cloud.syncState)),s.push(m.syncCompleteEvent.subscribe(u)),m.tables.every((e=>e.core))||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const _="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[w,S]=yield m.transaction("rw",m.$syncState,(()=>Y(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=m.cloud,[o,s,a]=yield Promise.all([m.getOptions(),m.getSchema(),m.getPersistedSyncState()]);if(i){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield m.$syncState.put(e,"options")}}else m.cloud.options=o||null;if((null===(e=m.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!rn?m.cloud.usingServiceWorker=!0:((null===(t=m.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&m.cloud.isServiceWorkerDB,m.cloud.usingServiceWorker=!1),Wn(r,m.cloud.options),Wn(s,m.cloud.options),r){if(!s||JSON.stringify(s)!==JSON.stringify(r)){const e=s||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield m.$syncState.put(e,"schema"),Object.assign(r,e)}}else m.cloud.schema=s||null;return[null==a?void 0:a.initiallySynced,null==a?void 0:a.realms]}))));if(w&&m.setInitiallySynced(!0),function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}}(m),c(),!m.cloud.isServiceWorkerDB){s.push(o((()=>m.getCurrentUser())).subscribe(r)),s.push(o((()=>m.getPersistedSyncState())).subscribe(m.cloud.persistedSyncState)),yield b(A([r.pipe(z(1),K(1)),m.cloud.persistedSyncState.pipe(z(1),K(1))]));const e=no(m);G.on.new.subscribe(e),m.dx.once("close",(()=>{G.on.new.unsubscribe(e)}))}let O=!1;const C=yield m.getCurrentUser(),T=null===(d=m.cloud.options)||void 0===d?void 0:d.requireAuth;T&&(m.cloud.isServiceWorkerDB?yield b(r.pipe(R((e=>!!e.isLoggedIn)),K(1))):"object"==typeof T?(!C.isLoggedIn||T.userId&&C.userId!==T.userId||T.email&&C.email!==T.email)&&(O=yield Pe(m,T)):C.isLoggedIn||(O=yield Pe(m))),!C.isLoggedIn||S&&S.includes(C.userId)||(O=!0),a&&a.stop(),a=null,c();const j=(null===(f=m.cloud.options)||void 0===f?void 0:f.databaseUrl)&&(!w||O);j&&(yield function(e,t,n){return Y(this,void 0,void 0,(function*(){yield _n(e,Wt,(()=>Kt(e,t,n,{isInitialSync:!0})))}))}(m,m.cloud.options,m.cloud.schema),m.setInitiallySynced(!0)),c(),m.cloud.usingServiceWorker&&(null===(p=m.cloud.options)||void 0===p?void 0:p.databaseUrl)?(j||de(m,"push").catch((()=>{})),function(e){return Y(this,void 0,void 0,(function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}}))}(m).catch((()=>{}))):(null===(y=m.cloud.options)||void 0===y?void 0:y.databaseUrl)&&m.cloud.schema&&!m.cloud.isServiceWorkerDB&&(a=Fn(m,m.cloud.options,m.cloud.schema),a.start(),j||fe(m,"push")),c(),m.cloud.isServiceWorkerDB||s.push(I(self,"online").subscribe((()=>{m.syncStateChangedEvent.next({phase:"not-in-sync"}),mn(m)||fe(m,"push")})),I(self,"offline").subscribe((()=>{m.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(h=m.cloud.options)||void 0===h?void 0:h.databaseUrl)||(null===(v=m.cloud.options)||void 0===v?void 0:v.disableWebSocket)||on||s.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const n=e.messageConsumer.readyToServe.pipe(R((e=>e)),N((()=>e.getPersistedSyncState())),R((e=>e&&e.serverRevision)),N((e=>Y(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield Be(e)}}))))),r=E(n,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(R((e=>null==e?void 0:e.serverRevision)),K(1),N((t=>e.cloud.currentUser.pipe(F((e=>[e,t]))))),N((([e,t])=>kn.pipe(F((n=>[n?e:null,t]))))),N((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(R((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),K(1),F((e=>[t,e]))):new k([t,n]))),N((e=>Y(this,[e],void 0,(function*([e,t]){return[e,yield Be(t)]})))),M((([e,t],[n,r])=>e===n&&t===r)),N((([n,o])=>{var s;return(null===(s=e.cloud.persistedSyncState)||void 0===s?void 0:s.value)?n?new An(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,o,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n):g([]):t()})),V((n=>"TokenExpiredError"===(null==n?void 0:n.name)?x(!0).pipe(N((()=>Y(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield xe(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),N((()=>t()))):U((()=>n)))),V((n=>(e.cloud.webSocketStatus.next("error"),n instanceof Dn?U((()=>n)):g(Ln()).pipe(N((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(m))}))}(t)}catch(e){}}))),!0);let l=!1;function c(){if(l)throw new e.DatabaseClosedError}t.once("close",(()=>{s.forEach((e=>e.unsubscribe())),s.splice(0,s.length),l=!0,a&&a.stop(),a=null,r.next(Oe)}));const u=new S;var d;t.cloud={version:"4.2.0-alpha.3",options:Object.assign({},yo),schema:null,get currentUserId(){return r.value.userId||Oe.userId},currentUser:r,syncState:new k({phase:"initial",status:"not-started"}),events:{syncComplete:u},persistedSyncState:new k(void 0),userInteraction:new k(void 0),webSocketStatus:new k("not-started"),login(e){return Y(this,void 0,void 0,(function*(){const n=Qt(t);yield n.cloud.sync(),yield Pe(n,e)}))},invites:to(t),roles:Yr(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),i=!0,e.databaseUrl&&e.nameSuffix&&(t.name=`${n}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,Qt(t).reconfigure()),Wn(t.cloud.schema,t.cloud.options)},logout(){return Y(this,arguments,void 0,(function*({force:e}={}){e?yield je(Qt(t),{deleteUnsyncedData:!0}):yield Te(Qt(t))}))},sync(){return Y(this,arguments,void 0,(function*({wait:e,purpose:n}={wait:!0,purpose:"push"}){var r;void 0===e&&(e=!0);const s=Qt(t);if("ok"!==((null===(r=s.cloud.currentUser.value.license)||void 0===r?void 0:r.status)||"ok")&&(yield ke(s)),"pull"===n){const t=s.cloud.persistedSyncState.value;if(fe(s,n),e){const e=yield b(s.cloud.persistedSyncState.pipe(R((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp)))));if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield Rn(s)){const t=s.cloud.persistedSyncState.value;fe(s,n),e&&(yield b(g(o((()=>Y(this,void 0,void 0,(function*(){const e=yield Rn(s),n=yield s.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==t?void 0:t.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return e}))))).pipe(R((e=>!e)))))}}))},permissions:(e,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId:o}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const s=Qr(e),i=t=>{const s=t[o||e.cloud.currentUserId];return s?new eo(s.permissions,n,void 0===o||o===e.cloud.currentUserId||r===e.cloud.currentUserId):new eo({},n,!r||r===e.cloud.currentUserId)},a=s.pipe(F(i));return a.getValue=()=>i(s.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>gn(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return dn(t.cloud.schema[this.name].idPrefix||"",n)},t.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},t.use(bn({currentUserObservable:t.cloud.currentUser,db:Qt(t)})),t.use((d=Qt(t),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,o,s,i,a,l;const c=e.trans;if(c.disableChangeTracking)return n.mutate(e);const u=null!==(o=null===(r=c.currentUser)||void 0===r?void 0:r.userId)&&void 0!==o?o:Oe.userId;if((null===(i=null===(s=d.cloud.schema)||void 0===s?void 0:s[t])||void 0===i?void 0:i.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(l=(a=n.schema.primaryKey).extractKey)||void 0===l?void 0:l.call(a,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),t.use(fn(Qt(t)))}ho.version="4.2.0-alpha.3",e.Cloud=ho;export{ho as default,po as defineYDocTrigger,ho as dexieCloud,oo as getTiedObjectId,ro as getTiedRealmId,Vr as resolveText};
2
2
  //# sourceMappingURL=dexie-cloud-addon.min.js.map