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.
- package/dist/modern/dexie-cloud-addon.js +1893 -14966
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.gz +0 -0
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/service-worker.js +1969 -15042
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/yjs/reopenDocSignal.d.ts +2 -2
- package/dist/umd/dexie-cloud-addon.js +200 -1677
- package/dist/umd/dexie-cloud-addon.js.gz +0 -0
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.gz +0 -0
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +61 -1538
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/dist/umd/yjs/reopenDocSignal.d.ts +2 -2
- package/package.json +3 -3
- package/dist/modern/helpers/dbOnClosed.d.ts +0 -2
- package/dist/modern/yjs/Y.d.ts +0 -3
- package/dist/modern/yjs/importDexieYProvider.d.ts +0 -1
- package/dist/umd/helpers/dbOnClosed.d.ts +0 -2
- package/dist/umd/yjs/Y.d.ts +0 -3
- package/dist/umd/yjs/importDexieYProvider.d.ts +0 -1
|
@@ -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{Observable as o,BehaviorSubject as c,firstValueFrom as l,Subject as a,from as u,filter 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 L(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 j={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(j),Object.freeze(j.claims)}catch(e){}const R={},N="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;N&&N.ready.then((e=>R.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 ${constructor(e){this.name=e}subscribe(e){if(!N)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 N.addEventListener("message",t),()=>N.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}))):R.registration&&(null===(t=R.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const M=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class B extends o{constructor(e){const t="undefined"==typeof BroadcastChannel?new $(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){M.has(e)?M.get(e).push(t):M.set(e,[t])}(`lbc-${e}`,r);try{t instanceof $?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",i)}catch(e){}return()=>{!function(e,t){const n=M.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof $?s():t.removeEventListener("message",i)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=M.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function F(e){return"function"==typeof e}function W(e){return function(t){if(function(e){return F(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 V=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function K(e){return F(null==e?void 0:e.then)}var H,z,J=(H=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}},(z=H((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),z.prototype.constructor=z,z);function q(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var Y=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(F(l))try{l()}catch(e){i=e instanceof J?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{X(h)}catch(e){i=null!=i?i:[],e instanceof J?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 J(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)X(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)&&q(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&q(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function G(e){return e instanceof Y||e&&"closed"in e&&F(e.remove)&&F(e.add)&&F(e.unsubscribe)}function X(e){F(e)?e():e.unsubscribe()}Y.EMPTY;var Z={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},Q={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=Q.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=Q.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function ee(e){Q.setTimeout((function(){throw e}))}function te(){}var ne=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,G(t)&&t.add(n)):n.destination=le,n}return I(t,e),t.create=function(e,t,n){return new oe(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}(Y),re=Function.prototype.bind;function ie(e,t){return re.call(e,t)}var se=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){ce(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ce(e)}else ce(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ce(e)}},e}(),oe=function(e){function t(t,n,r){var i,s,o=e.call(this)||this;F(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&Z.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&ie(t.next,s),error:t.error&&ie(t.error,s),complete:t.complete&&ie(t.complete,s)}):i=t;return o.destination=new se(i),o}return I(t,e),t}(ne);function ce(e){ee(e)}var le={closed:!0,next:te,error:function(e){throw e},complete:te},ae="function"==typeof Symbol&&Symbol.observable||"@@observable";function ue(e){return e}var de=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 ne||function(e){return e&&F(e.next)&&F(e.error)&&F(e.complete)}(r)&&G(r)?e:new oe(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=he(t))((function(t,r){var i=new oe({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[ae]=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?ue: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=he(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 he(e){var t;return null!==(t=null!=e?e:Z.Promise)&&void 0!==t?t:Promise}function fe(e){return F(e[ae])}function pe(e){return Symbol.asyncIterator&&F(null==e?void 0:e[Symbol.asyncIterator])}function ge(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 ye="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ve(e){return F(null==e?void 0:e[ye])}function me(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 be(e){return F(null==e?void 0:e.getReader)}function we(e){if(e instanceof de)return e;if(null!=e){if(fe(e))return i=e,new de((function(e){var t=i[ae]();if(F(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(V(e))return r=e,new de((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(K(e))return n=e,new de((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,ee)}));if(pe(e))return _e(e);if(ve(e))return t=e,new de((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(be(e))return _e(me(e))}var t,n,r,i;throw ge(e)}function _e(e){return new de((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=L(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 ke(e,t,n,r,i){return new Se(e,t,n,r,i)}var Se=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}(ne),Ee=function(e){function t(t,n){return e.call(this)||this}return I(t,e),t.prototype.schedule=function(e,t){return this},t}(Y),xe={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=xe.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=xe.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},Ie=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),xe.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;xe.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,q(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Ee),Ce={now:function(){return(Ce.delegate||Date).now()},delegate:void 0},Ae=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=Ce.now,e}(),Oe=new(function(e){function t(t,n){void 0===n&&(n=Ae.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}(Ae))(Ie),De=Oe;function Te(e){return e&&F(e.schedule)}function Ue(e,t,n){void 0===e&&(e=0),void 0===n&&(n=De);var r=-1;return null!=t&&(Te(t)?n=t:r=t),new de((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 Pe(e){return Te((t=e)[t.length-1])?e.pop():void 0;var t}function Le(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 je(e){return W((function(t,n){var r,i=null,s=!1;i=t.subscribe(ke(n,void 0,void 0,(function(o){r=we(e(o,je(e)(t))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function Re(e,t){return void 0===t&&(t=0),W((function(n,r){n.subscribe(ke(r,(function(n){return Le(r,e,(function(){return r.next(n)}),t)}),(function(){return Le(r,e,(function(){return r.complete()}),t)}),(function(n){return Le(r,e,(function(){return r.error(n)}),t)})))}))}function Ne(e,t){return void 0===t&&(t=0),W((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function $e(e,t){if(!e)throw new Error("Iterable cannot be null");return new de((function(n){Le(n,t,(function(){var r=e[Symbol.asyncIterator]();Le(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Me(e,t){if(null!=e){if(fe(e))return function(e,t){return we(e).pipe(Ne(t),Re(t))}(e,t);if(V(e))return function(e,t){return new de((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(K(e))return function(e,t){return we(e).pipe(Ne(t),Re(t))}(e,t);if(pe(e))return $e(e,t);if(ve(e))return function(e,t){return new de((function(n){var r;return Le(n,t,(function(){r=e[ye](),Le(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 F(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(be(e))return function(e,t){return $e(me(e),t)}(e,t)}throw ge(e)}function Be(e,t){return W((function(n,r){var i=0;n.subscribe(ke(r,(function(n){r.next(e.call(t,n,i++))})))}))}function Fe(e,t,n){return void 0===n&&(n=1/0),F(t)?Fe((function(n,r){return Be((function(e,i){return t(n,e,r,i)}))(we(e(n,r)))}),n):("number"==typeof t&&(n=t),W((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;we(n(e,u++)).subscribe(ke(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?Le(t,o,(function(){return p(e)})):p(e)};l.length&&a<r;)e();h()}catch(e){t.error(e)}})))};return e.subscribe(ke(t,f,(function(){d=!0,h()}))),function(){null==c||c()}}(t,r,e,n)})))}function We(){return void 0===(e=1)&&(e=1/0),Fe(ue,e);var e}function Ve(e,t){return void 0===t&&(t=Oe),W((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(ke(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 Ke(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return We()((e=n,(t=Pe(n))?Me(e,t):we(e)))}var He=new de((function(e){return e.complete()}));function ze(e){return e<=0?function(){return He}:W((function(t,n){var r=0;t.subscribe(ke(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Je(e,t){return t?function(n){return Ke(t.pipe(ze(1),W((function(e,t){e.subscribe(ke(t,te))}))),n.pipe(Je(e)))}:Fe((function(t,n){return e(t,n).pipe(ze(1),function(e){return Be((function(){return e}))}(t))}))}function qe(e,t){void 0===t&&(t=Oe);var n=Ue(e,t);return Je((function(){return n}))}function Ye(e,t){return void 0===t&&(t=ue),e=null!=e?e:Ge,W((function(n,r){var i,s=!0;n.subscribe(ke(r,(function(n){var o=t(n);!s&&e(i,o)||(s=!1,i=o,r.next(n))})))}))}function Ge(e,t){return e===t}function Xe(e,t){return W((function(n,r){var i=0;n.subscribe(ke(r,(function(n){return e.call(t,n,i++)&&r.next(n)})))}))}function Ze(e){return Xe((function(t,n){return e<=n}))}function Qe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Pe(e);return W((function(t,r){(n?Ke(e,t,n):Ke(e,t)).subscribe(r)}))}function et(e,t){return W((function(n,r){var i=null,s=0,o=!1,c=function(){return o&&!i&&r.complete()};n.subscribe(ke(r,(function(n){null==i||i.unsubscribe();var o=0,l=s++;we(e(n,l)).subscribe(i=ke(r,(function(e){return r.next(t?t(n,e,l,o++):e)}),(function(){i=null,c()})))}),(function(){o=!0,c()})))}))}function tt(e,t,n){var r=F(e)||t||n?{next:e,error:t,complete:n}:e;return r?W((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;e.subscribe(ke(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)})))})):ue}let nt=!1;function rt(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){nt||(nt=!0)}}))}function it(e,t){e.cloud.usingServiceWorker?rt(e,t):e.localSyncEvent.next({purpose:t})}const st="fromBase64"in Uint8Array,ot="toBase64"in Uint8Array.prototype,ct="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):st?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},lt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):ot?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(""))};function at(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 lt(i)}))}function ut(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 dt(e){return`$${e}_mutations`}function ht(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 ft=[].concat;function pt(e){return ft.apply([],e)}function gt(e,t){return C(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const i=pt(yield Promise.all(e.map((e=>C(this,void 0,void 0,(function*(){const t=ht(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 yt(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 vt={}.hasOwnProperty;function mt(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)mt(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 vt.call(e,t)}(e,o)||(l=e[o]={}),mt(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const bt="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=wt)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function wt(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function _t(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>_t(e)))&&e.every(kt))}function kt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(kt)}function St(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))mt(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 Et(e,t){for(const{table:n,muts:r}of t)for(const t of r)St(e,n,t)}const xt=Math.floor,It=Math.abs,Ct=(e,t)=>e>t?e:t,At=128,Ot=127,Dt=Number.MAX_SAFE_INTEGER,Tt=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&xt(e)===e),Ut=Array.isArray,Pt="undefined"!=typeof TextEncoder?new TextEncoder:null,Lt=Pt?e=>Pt.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 jt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});jt&&1===jt.decode(new Uint8Array).length&&(jt=null);let Rt=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Nt=(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},$t=(e,t)=>{for(;t>Ot;)Nt(e,At|Ot&t),t=xt(t/128);Nt(e,Ot&t)},Mt=new Uint8Array(3e4),Bt=Mt.length/3,Ft=Pt&&Pt.encodeInto?(e,t)=>{if(t.length<Bt){const n=Pt.encodeInto(t,Mt).written||0;$t(e,n);for(let t=0;t<n;t++)Nt(e,Mt[t])}else Wt(e,Lt(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;$t(e,r);for(let t=0;t<r;t++)Nt(e,n.codePointAt(t))},Wt=(e,t)=>{$t(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(Ct(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)})(e,t)},Vt=(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*Ct(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Kt=(e,t)=>Vt(e,8).setBigUint64(0,t,!1),Ht=new DataView(new ArrayBuffer(4)),zt=(e,t)=>{switch(typeof t){case"string":Nt(e,119),Ft(e,t);break;case"number":Tt(t)&&It(t)<=2147483647?(Nt(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),Nt(e,(t>63?At:0)|(n?64:0)|63&t),t=xt(t/64);t>0;)Nt(e,(t>Ot?At:0)|Ot&t),t=xt(t/128)})(e,t)):(n=t,Ht.setFloat32(0,n),Ht.getFloat32(0)===n?(Nt(e,124),((e,t)=>{Vt(e,4).setFloat32(0,t,!1)})(e,t)):(Nt(e,123),((e,t)=>{Vt(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":Nt(e,122),((e,t)=>{Vt(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Nt(e,126);else if(Ut(t)){Nt(e,117),$t(e,t.length);for(let n=0;n<t.length;n++)zt(e,t[n])}else if(t instanceof Uint8Array)Nt(e,116),Wt(e,t);else{Nt(e,118);const n=Object.keys(t);$t(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];Ft(e,i),zt(e,t[i])}}break;case"boolean":Nt(e,t?120:121);break;default:Nt(e,127)}var n};function Jt(e){const t=new Rt;switch(Ft(t,e.type),"table"in e&&Ft(t,e.table),"prop"in e&&Ft(t,e.prop),e.type){case"u-ack":case"u-reject":Kt(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":Ft(t,e.yServerRev);break;default:switch(zt(t,e.k),e.type){case"aware":Wt(t,e.u);break;case"doc-open":zt(t,e.serverRev),zt(t,e.sv);break;case"doc-close":break;case"sv":Wt(t,e.sv);break;case"u-c":Wt(t,e.u),Kt(t,BigInt(e.i));break;case"u-s":Wt(t,e.u),Ft(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 qt=e=>new Error(e),Yt=qt("Unexpected end of array"),Gt=qt("Integer out of Range");let Xt=class{constructor(e){this.arr=e,this.pos=0}};const Zt=e=>e.pos!==e.arr.length,Qt=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,tn(e)),en=e=>e.arr[e.pos++],tn=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Ot)*n,n*=128,r<At)return t;if(t>Dt)throw Gt}throw Yt},nn=jt?e=>jt.decode(Qt(e)):e=>{let t=tn(e);if(0===t)return"";{let n=String.fromCodePoint(en(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(en(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))}},rn=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},sn=e=>rn(e,8).getBigUint64(0,!1),on=[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&At))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&Ot)*r,r*=128,t<At)return i*n;if(n>Dt)throw Gt}throw Yt},e=>rn(e,4).getFloat32(0,!1),e=>rn(e,8).getFloat64(0,!1),e=>rn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,nn,e=>{const t=tn(e),n={};for(let r=0;r<t;r++){n[nn(e)]=cn(e)}return n},e=>{const t=tn(e),n=[];for(let r=0;r<t;r++)n.push(cn(e));return n},Qt],cn=e=>on[127-en(e)](e);function ln(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=L(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}}}))}class an 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 un(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 dn(e,t,...n){return un(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function hn(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 un(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 fn(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 un(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return i}))}function pn(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 yn(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 gn(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 yn(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=lt(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 an(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 un(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof an)throw yield dn(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 dn(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,i,s)}))}function yn(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=lt(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 an(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{toString:vn}={};const mn={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 bn(...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 mn;let s=n.get(r);if(void 0!==s)return s;const o=(i=e,vn.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:mn),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 wn={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 _n={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 kn={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Sn={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},En={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},xn={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const In="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Cn=["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=In[t];return i&&new i(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function An(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Tn[e[n]];return t}(lt(e))}function On(e){return ct(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+=Dn[e[n]];return t}(e))}const Dn={"-":"=",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:"+","|":"/"},Tn={};for(const e of Object.keys(Dn))Tn[Dn[e]]=e;var Un={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:An(e)}),revive:({v:e})=>{const t=On(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Pn{constructor(e,t){this.buf=e,this.type=t}}function Ln(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 jn(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Rn={Blob:{test:(e,t)=>"Blob"===t||e instanceof Pn,replace:e=>({$t:"Blob",v:lt(e instanceof Pn?e.buf:jn(Ln(e))),type:e.type}),revive:({type:e,v:t})=>{const n=ct(t);return void 0!==typeof Blob?new Blob([n]):new Pn(n.buffer,e)}}};const Nn={..._n,...kn,...Sn,...En,...xn,...Cn,...Un,...Rn};function $n(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 Mn={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},Bn={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:lt(jn(Ln(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const i=ct(t);return new File([i],n,{type:e,lastModified:new Date(r).getTime()})}}};const Fn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Wn{toString(){return this.v}constructor(e){this.v=e}}const Vn=Fn?{}:{bigint:{test:e=>e instanceof Wn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Wn(e)}},Kn=Object.assign(Object.assign(Object.assign(Object.assign({},Mn),Vn),Bn),{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)}}}),Hn=bn(Nn,Kn),zn=function(...e){const t=bn(Nn,wn,...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 $n(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 $n(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)}}}(Kn);class Jn extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function qn(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=Yn(s,i));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===s&&(a=Yn(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 Yn(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 Gn=new WeakMap;function Xn(e){return C(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=Gn.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 Zn(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 pn(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:qn(i.dx.core.schema,l,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=Hn.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));Gn.set(e,new Date(Date.now()+1e3*t))}else Gn.delete(e)}}(i,p),!p.ok)throw new Jn(p);if("application/x-bison"===p.headers.get("content-type"))return zn.fromBinary(yield p.blob());{const e=yield p.text();return Hn.parse(e)}}))}function Qn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let er=!1;function tr(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 nr(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 rr(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 ir(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 rr(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(er=navigator.onLine,self.addEventListener("online",(()=>er=!0)),self.addEventListener("offline",(()=>er=!1)));const sr="dexie-cloud-syncer";function or(e,t){return e.where("i").between(t,1/0,!0).toArray()}const cr=()=>new Map,lr=e=>{const t=cr();return e.forEach(((e,n)=>{t.set(n,e)})),t},ar=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},ur=()=>new Set,dr=e=>e[e.length-1],hr=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},fr=Array.from,pr=Array.isArray;class gr{constructor(){this._observers=cr()}on(e,t){return ar(this._observers,e,ur).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 fr((this._observers.get(e)||cr()).values()).forEach((e=>e(...t)))}destroy(){this._observers=cr()}}const yr=Math.floor,vr=Math.abs,mr=(e,t)=>e<t?e:t,br=(e,t)=>e>t?e:t,wr=e=>0!==e?e<0:1/e<0,_r=64,kr=128,Sr=127,Er=Number.MAX_SAFE_INTEGER,xr=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&yr(e)===e),Ir=/^\s*/g,Cr=/([A-Z])/g,Ar=(e,t)=>(e=>e.replace(Ir,""))(e.replace(Cr,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),Or="undefined"!=typeof TextEncoder?new TextEncoder:null,Dr=Or?e=>Or.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 Tr="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Tr&&1===Tr.decode(new Uint8Array).length&&(Tr=null);class Ur{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Pr=()=>new Ur,Lr=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},jr=(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},Rr=jr,Nr=(e,t)=>{for(;t>Sr;)jr(e,kr|Sr&t),t=yr(t/128);jr(e,Sr&t)},$r=(e,t)=>{const n=wr(t);for(n&&(t=-t),jr(e,(t>63?kr:0)|(n?_r:0)|63&t),t=yr(t/64);t>0;)jr(e,(t>Sr?kr:0)|Sr&t),t=yr(t/128)},Mr=new Uint8Array(3e4),Br=Mr.length/3,Fr=Or&&Or.encodeInto?(e,t)=>{if(t.length<Br){const n=Or.encodeInto(t,Mr).written||0;Nr(e,n);for(let t=0;t<n;t++)jr(e,Mr[t])}else Vr(e,Dr(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;Nr(e,r);for(let t=0;t<r;t++)jr(e,n.codePointAt(t))},Wr=(e,t)=>{const n=e.cbuf.length,r=e.cpos,i=mr(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(br(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Vr=(e,t)=>{Nr(e,t.byteLength),Wr(e,t)},Kr=(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*br(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Hr=new DataView(new ArrayBuffer(4)),zr=(e,t)=>{switch(typeof t){case"string":jr(e,119),Fr(e,t);break;case"number":xr(t)&&vr(t)<=2147483647?(jr(e,125),$r(e,t)):(n=t,Hr.setFloat32(0,n),Hr.getFloat32(0)===n?(jr(e,124),((e,t)=>{Kr(e,4).setFloat32(0,t,!1)})(e,t)):(jr(e,123),((e,t)=>{Kr(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":jr(e,122),((e,t)=>{Kr(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)jr(e,126);else if(pr(t)){jr(e,117),Nr(e,t.length);for(let n=0;n<t.length;n++)zr(e,t[n])}else if(t instanceof Uint8Array)jr(e,116),Vr(e,t);else{jr(e,118);const n=Object.keys(t);Nr(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];Fr(e,i),zr(e,t[i])}}break;case"boolean":jr(e,t?120:121);break;default:jr(e,127)}var n};class Jr extends Ur{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Nr(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const qr=e=>{e.count>0&&($r(e.encoder,1===e.count?e.s:-e.s),e.count>1&&Nr(e.encoder,e.count-2))};class Yr{constructor(){this.encoder=new Ur,this.s=0,this.count=0}write(e){this.s===e?this.count++:(qr(this),this.count=1,this.s=e)}toUint8Array(){return qr(this),Lr(this.encoder)}}const Gr=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);$r(e.encoder,t),e.count>1&&Nr(e.encoder,e.count-2)}};class Xr{constructor(){this.encoder=new Ur,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Gr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Gr(this),Lr(this.encoder)}}class Zr{constructor(){this.sarr=[],this.s="",this.lensE=new Yr}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 Ur;return this.sarr.push(this.s),this.s="",Fr(e,this.sarr.join("")),Wr(e,this.lensE.toUint8Array()),Lr(e)}}const Qr=e=>new Error(e),ei=()=>{throw Qr("Method unimplemented")},ti=()=>{throw Qr("Unexpected case")},ni=Qr("Unexpected end of array"),ri=Qr("Integer out of Range");class ii{constructor(e){this.arr=e,this.pos=0}}const si=e=>new ii(e),oi=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,li(e)),ci=e=>e.arr[e.pos++],li=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Sr)*n,n*=128,r<kr)return t;if(t>Er)throw ri}throw ni},ai=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(t&_r)>0?-1:1;if(0==(t&kr))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&Sr)*r,r*=128,t<kr)return i*n;if(n>Er)throw ri}throw ni},ui=Tr?e=>Tr.decode(oi(e)):e=>{let t=li(e);if(0===t)return"";{let n=String.fromCodePoint(ci(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ci(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))}},di=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},hi=[e=>{},e=>null,ai,e=>di(e,4).getFloat32(0,!1),e=>di(e,8).getFloat64(0,!1),e=>di(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ui,e=>{const t=li(e),n={};for(let r=0;r<t;r++){n[ui(e)]=fi(e)}return n},e=>{const t=li(e),n=[];for(let r=0;r<t;r++)n.push(fi(e));return n},oi],fi=e=>hi[127-ci(e)](e);class pi extends ii{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=li(this)+1:this.count=-1),this.count--,this.s}}class gi extends ii{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=ai(this);const e=wr(this.s);this.count=1,e&&(this.s=-this.s,this.count=li(this)+2)}return this.count--,this.s}}class yi extends ii{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=ai(this),t=1&e;this.diff=yr(e/2),this.count=1,t&&(this.count=li(this)+2)}return this.s+=this.diff,this.count--,this.s}}class vi{constructor(e){this.decoder=new gi(e),this.str=ui(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 mi=crypto.getRandomValues.bind(crypto),bi=()=>mi(new Uint32Array(1))[0],wi=[1e7]+-1e3+-4e3+-8e3+-1e11,_i=()=>wi.replace(/[018]/g,(e=>(e^bi()&15>>e/4).toString(16))),ki=e=>new Promise(e);Promise.all.bind(Promise);const Si=e=>void 0===e?null:e;let Ei=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},xi=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Ei=localStorage,xi=!1)}catch(Ma){}const Ii=Ei,Ci=Object.assign,Ai=Object.keys,Oi=e=>Ai(e).length,Di=(e,t)=>e===t||Oi(e)===Oi(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)),Ti=Object.freeze,Ui=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Ui(e[t])}return Ti(e)},Pi=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Pi(e,t,n+1)}},Li="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let ji;const Ri=e=>(()=>{if(void 0===ji)if(Li){ji=cr();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&ji.set(t,""),t=r):null!==t&&(ji.set(t,r),t=null)}null!==t&&ji.set(t,"")}else"object"==typeof location?(ji=cr(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");ji.set(`--${Ar(t,"-")}`,n),ji.set(`-${Ar(t,"-")}`,n)}}))):ji=cr();return ji})().has(e),Ni=e=>Si(Li?process.env[e.toUpperCase().replaceAll("-","_")]:Ii.getItem(e)),$i=e=>Ri("--"+e)||null!==Ni(e);$i("production");var Mi;Li&&(Mi=process.env.FORCE_COLOR,["true","1","2"].includes(Mi))||!Ri("--no-colors")&&!$i("no-color")&&(!Li||process.stdout.isTTY)&&(!Li||Ri("--color")||null!==Ni("COLORTERM")||(Ni("TERM")||"").includes("color"));class Bi{constructor(e,t){this.left=e,this.right=t}}const Fi=(e,t)=>new Bi(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const Wi=Symbol,Vi=Wi(),Ki=Wi(),Hi=Wi(),zi=Wi(),Ji=Wi(),qi=Wi(),Yi=Wi(),Gi=Wi(),Xi=Wi(),Zi=(Fi("font-weight","bold"),Fi("font-weight","normal"),Fi("color","blue"),Fi("color","green"),Fi("color","grey"),Fi("color","red"),Fi("color","purple"),Fi("color","orange"),Fi("color","black"),ur()),Qi=e=>({[Symbol.iterator](){return this},next:e}),es=(e,t)=>Qi((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class ts{constructor(e,t){this.clock=e,this.len=t}}class ns{constructor(){this.clients=new Map}}const rs=(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])Ms(e,i,o.clock,o.len,n)}})),is=(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=yr((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)},ss=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=br(r.len,i.clock+i.len-r.clock):(n<t&&(e[n]=i),n++)}e.length=n}))},os=(e,t,n,r)=>{ar(e.clients,t,(()=>[])).push(new ts(n,r))},cs=(e,t)=>{Nr(e.restEncoder,t.clients.size),fr(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),Nr(e.restEncoder,t);const r=n.length;Nr(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},ls=(e,t,n)=>{const r=new ns,i=li(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=li(e.restDecoder),s=li(e.restDecoder),o=n.clients.get(i)||[],c=Us(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&os(r,i,c,s-c);let e=Ls(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,_c(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,_c(t,l,s-l.id.clock)),l.delete(t))}else os(r,i,n,s-n)}}if(r.clients.size>0){const e=new ys;return Nr(e.restEncoder,0),cs(e,r),e.toUint8Array()}return null},as=bi;class us extends gr{constructor({guid:e=_i(),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=as(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Ds,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=ki((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const c=()=>ki((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||Hs(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(fr(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return Hs(this,e,t)}get(e,t=uo){const n=ar(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==uo&&r!==t){if(r===uo){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,Oo)}getText(e=""){return this.get(e,Jo)}getMap(e=""){return this.get(e,To)}getXmlElement(e=""){return this.get(e,Go)}getXmlFragment(e=""){return this.get(e,Yo)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,fr(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new us({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Hs(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 ds{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=li(this.restDecoder),this.dsCurrVal}readDsLen(){const e=li(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class hs extends ds{constructor(e){super(e),this.keys=[],li(e),this.keyClockDecoder=new yi(oi(e)),this.clientDecoder=new gi(oi(e)),this.leftClockDecoder=new yi(oi(e)),this.rightClockDecoder=new yi(oi(e)),this.infoDecoder=new pi(oi(e),ci),this.stringDecoder=new vi(oi(e)),this.parentInfoDecoder=new pi(oi(e),ci),this.typeRefDecoder=new gi(oi(e)),this.lenDecoder=new gi(oi(e))}readLeftID(){return new xs(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new xs(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 fi(this.restDecoder)}readBuf(){return oi(this.restDecoder)}readJSON(){return fi(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 fs{constructor(){this.restEncoder=Pr()}toUint8Array(){return Lr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Nr(this.restEncoder,e)}writeDsLen(e){Nr(this.restEncoder,e)}}class ps extends fs{writeLeftID(e){Nr(this.restEncoder,e.client),Nr(this.restEncoder,e.clock)}writeRightID(e){Nr(this.restEncoder,e.client),Nr(this.restEncoder,e.clock)}writeClient(e){Nr(this.restEncoder,e)}writeInfo(e){Rr(this.restEncoder,e)}writeString(e){Fr(this.restEncoder,e)}writeParentInfo(e){Nr(this.restEncoder,e?1:0)}writeTypeRef(e){Nr(this.restEncoder,e)}writeLen(e){Nr(this.restEncoder,e)}writeAny(e){zr(this.restEncoder,e)}writeBuf(e){Vr(this.restEncoder,e)}writeJSON(e){Fr(this.restEncoder,JSON.stringify(e))}writeKey(e){Fr(this.restEncoder,e)}}class gs{constructor(){this.restEncoder=Pr(),this.dsCurrVal=0}toUint8Array(){return Lr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,Nr(this.restEncoder,t)}writeDsLen(e){0===e&&ti(),Nr(this.restEncoder,e-1),this.dsCurrVal+=e}}class ys extends gs{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Xr,this.clientEncoder=new Yr,this.leftClockEncoder=new Xr,this.rightClockEncoder=new Xr,this.infoEncoder=new Jr(Rr),this.stringEncoder=new Zr,this.parentInfoEncoder=new Jr(Rr),this.typeRefEncoder=new Yr,this.lenEncoder=new Yr}toUint8Array(){const e=Pr();return Nr(e,0),Vr(e,this.keyClockEncoder.toUint8Array()),Vr(e,this.clientEncoder.toUint8Array()),Vr(e,this.leftClockEncoder.toUint8Array()),Vr(e,this.rightClockEncoder.toUint8Array()),Vr(e,Lr(this.infoEncoder)),Vr(e,this.stringEncoder.toUint8Array()),Vr(e,Lr(this.parentInfoEncoder)),Vr(e,this.typeRefEncoder.toUint8Array()),Vr(e,this.lenEncoder.toUint8Array()),Wr(e,Lr(this.restEncoder)),Lr(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){zr(this.restEncoder,e)}writeBuf(e){Vr(this.restEncoder,e)}writeJSON(e){zr(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 vs=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{Us(t,n)>e&&r.set(n,e)})),Ts(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),Nr(e.restEncoder,r.size),fr(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=br(r,t[0].id.clock);const i=Ls(t,r);Nr(e.restEncoder,t.length-i),e.writeClient(n),Nr(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)}))},ms=(e,t,n,r=new hs(e))=>Hs(t,(e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=cr(),r=li(e.restDecoder);for(let i=0;i<r;i++){const r=li(e.restDecoder),i=new Array(r),s=e.readClient();let o=li(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 tc(Cs(s,o),t),o+=t;break}case 10:{const t=li(e.restDecoder);i[n]=new xc(Cs(s,o),t),o+=t;break}default:{const c=0==(192&r),l=new kc(Cs(s,o),null,(r&kr)===kr?e.readLeftID():null,null,(r&_r)===_r?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,c&&32==(32&r)?e.readString():null,Sc(e,r));i[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=fr(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 Ds,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!==xc){const i=ar(d,u.id.client,(()=>Us(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,Us(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 ys;return vs(e,c,new Map),Nr(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<Us(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=Gs([c.update,o.update])}}else i.pendingStructs=o;const l=ls(r,e,i);if(i.pendingDs){const t=new hs(si(i.pendingDs));li(t.restDecoder);const n=ls(t,e,i);i.pendingDs=l&&n?Gs([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,bs(e.doc,t)}}),n,!1),bs=(e,t,n,r=hs)=>{const i=si(t);ms(i,e,n,new r(i))};class ws{constructor(){this.l=[]}}const _s=()=>new ws,ks=(e,t)=>e.l.push(t),Ss=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},Es=(e,t,n)=>Pi(e.l,[t,n]);class xs{constructor(e,t){this.client=e,this.clock=t}}const Is=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Cs=(e,t)=>new xs(e,t),As=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!is(t.ds,e.id),Os=(e,t)=>{const n=ar(e.meta,Os,ur),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<Us(r,n)&&Ns(e,Cs(n,t))})),rs(e,t.ds,(e=>{})),n.add(t))};class Ds{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Ts=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},Us=(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},Ps=(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 ti()}n.push(t)},Ls=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=yr(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=yr((n+r)/2)}throw ti()},js=(e,t)=>{const n=e.clients.get(t.client);return n[Ls(n,t.clock)]},Rs=(e,t,n)=>{const r=Ls(t,n),i=t[r];return i.id.clock<n&&i instanceof kc?(t.splice(r+1,0,_c(e,i,n-i.id.clock)),r+1):r},Ns=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Rs(e,n,t.clock)]},$s=(e,t,n)=>{const r=t.clients.get(n.client),i=Ls(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==tc&&r.splice(i+1,0,_c(e,s,n.clock-s.id.clock+1)),s},Ms=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,c=Rs(e,t,n);do{o=t[c++],s<o.id.clock+o.length&&Rs(e,t,s),i(o)}while(c<t.length&&t[c].id.clock<s)};class Bs{constructor(e,t,n){this.doc=e,this.deleteSet=new ns,this.beforeState=Ts(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 Fs=(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)))&&(ss(t.deleteSet),((e,t)=>{vs(e,t.doc.store,t.beforeState)})(e,t),cs(e,t.deleteSet),!0),Ws=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&ar(e.changed,t,ur).add(n)},Vs=(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 kc&&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},Ks=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{ss(s),n.afterState=Ts(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)),Es(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),Pi(e,[]),n._needFormattingCleanup&&Ko(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=Ls(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 kc&&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=mr(r.length-1,1+Ls(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Vs(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=br(Ls(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Vs(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=Ls(r,n);s+1<r.length&&Vs(r,s+1)>1||s>0&&Vs(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Zi.forEach((t=>t.print(e)))})(Gi,Vi,"[yjs] ",Ki,qi,"Changed the client-id because another client seems to be using it."),r.clientID=as()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new ps;Fs(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new ys;Fs(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])):Ks(e,t+1)}}},Hs=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new Bs(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&&Ks(i,0)}}return o};class zs{constructor(e,t){this.gen=function*(e){const t=li(e.restDecoder);for(let n=0;n<t;n++){const t=li(e.restDecoder),n=e.readClient();let r=li(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=li(e.restDecoder);yield new xc(Cs(n,r),t),r+=t}else if(0!=(31&t)){const i=0==(192&t),s=new kc(Cs(n,r),null,(t&kr)===kr?e.readLeftID():null,null,(t&_r)===_r?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&32==(32&t)?e.readString():null,Sc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new tc(Cs(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===xc);return this.curr}}class Js{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const qs=(e,t=gs,n=hs)=>{const r=new t,i=new zs(new n(si(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++,Nr(r.restEncoder,t),Nr(r.restEncoder,o)),t=s.id.client,o=0,n=0!==s.id.clock),s.constructor===xc&&(n=!0),n||(o=s.id.clock+s.length);0!==o&&(e++,Nr(r.restEncoder,t),Nr(r.restEncoder,o));const c=Pr();return Nr(c,e),((e,t)=>{Wr(e,Lr(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return Nr(r.restEncoder,0),r.toUint8Array()},Ys=(e,t)=>{if(e.constructor===tc){const{client:n,clock:r}=e.id;return new tc(Cs(n,r+t),e.length-t)}if(e.constructor===xc){const{client:n,clock:r}=e.id;return new xc(Cs(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new kc(Cs(r,i+t),null,Cs(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Gs=(e,t=hs,n=ys)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(si(e))));let i=r.map((e=>new zs(e,!0))),s=null;const o=new n,c=new Js(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===xc?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)Zs(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===xc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{Zs(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new xc(Cs(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===xc?s.struct.length-=t:n=Ys(n,t)),s.struct.mergeWith(n)||(Zs(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!==xc;n=e.next())Zs(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(Zs(c,s.struct,s.offset),s=null),Qs(c);const l=r.map((e=>(e=>{const t=new ns,n=li(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=li(e.restDecoder),r=li(e.restDecoder);if(r>0){const i=ar(t.clients,n,(()=>[]));for(let t=0;t<r;t++)i.push(new ts(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new ns;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++)hr(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}}));return ss(t),t})(l);return cs(o,a),o.toUint8Array()},Xs=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Lr(e.encoder.restEncoder)}),e.encoder.restEncoder=Pr(),e.written=0)},Zs=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Xs(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Nr(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Qs=e=>{Xs(e);const t=e.encoder.restEncoder;Nr(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];Nr(t,r.written),Wr(t,r.restEncoder)}},eo="You must not compute changes after the event-handler fired.";class to{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=no(this.currentTarget,this.target))}deletes(e){return is(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Qr(eo);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=dr(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=dr(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=dr(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 Qr(eo);const t=this.target,n=ur(),r=ur(),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 no=(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},ro=()=>{((...e)=>{e.unshift(Gi),Zi.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let io=0;class so{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=io++}}const oo=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=io++},co=(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)=>vr(t-e.index)<vr(t-n.index)?e:n));let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=io++})(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&&vr(n.index-i)<r.parent.length/80?(oo(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return oo(r,t,n),r}{const r=new so(t,n);return e.push(r),r}})(e._searchMarker,r,i)},lo=(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=br(t,i.index+n))}},ao=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;ar(i,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;Es(r._eH,n,t)};class uo{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=_s(),this._dEH=_s(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw ei()}clone(){throw ei()}_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){ks(this._eH,e)}observeDeep(e){ks(this._dEH,e)}unobserve(e){Ss(this._eH,e)}unobserveDeep(e){Ss(this._dEH,e)}toJSON(){}}const ho=(e,t,n)=>{e.doc??ro(),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},fo=e=>{e.doc??ro();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},po=(e,t)=>{let n=0,r=e._start;for(e.doc??ro();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}},go=(e,t)=>{const n=[];return po(e,((r,i)=>{n.push(t(r,i,e))})),n},yo=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}}}},vo=(e,t)=>{e.doc??ro();const n=co(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}},mo=(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 kc(Cs(o,Us(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new uc(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 kc(Cs(o,Us(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new nc(new Uint8Array(n))),i.integrate(e,0);break;case us:i=new kc(Cs(o,Us(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new sc(n)),i.integrate(e,0);break;default:if(!(n instanceof uo))throw new Error("Unexpected content type in insert operation");i=new kc(Cs(o,Us(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new wc(n)),i.integrate(e,0)}}})),u()},bo=()=>Qr("Length exceeded!"),wo=(e,t,n,r)=>{if(n>t._length)throw bo();if(0===n)return t._searchMarker&&lo(t._searchMarker,n,r.length),mo(e,t,null,r);const i=n,s=co(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&&Ns(e,Cs(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&lo(t._searchMarker,i,r.length),mo(e,t,o,r)},_o=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=co(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&&Ns(e,Cs(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&Ns(e,Cs(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw bo();t._searchMarker&&lo(t._searchMarker,i,-s+r)},ko=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},So=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let c;if(null==r)c=new uc([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new uc([r]);break;case Uint8Array:c=new nc(r);break;case us:c=new sc(r);break;default:if(!(r instanceof uo))throw new Error("Unexpected content type");c=new wc(r)}new kc(Cs(o,Us(s.store,o)),i,i&&i.lastId,null,null,t,n,c).integrate(e,0)},Eo=(e,t)=>{e.doc??ro();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},xo=e=>{const t={};return e.doc??ro(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Io=(e,t)=>{e.doc??ro();const n=e._map.get(t);return void 0!==n&&!n.deleted},Co=e=>(e.doc??ro(),((e,t)=>Qi((()=>{let n;do{n=e.next()}while(!n.done&&!t(n.value));return n})))(e._map.entries(),(e=>!e[1].deleted)));class Ao extends to{}class Oo extends uo{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Oo;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Oo}clone(){const e=new Oo;return e.insert(0,this.toArray().map((e=>e instanceof uo?e.clone():e))),e}get length(){return this.doc??ro(),this._length}_callObserver(e,t){super._callObserver(e,t),ao(this,e,new Ao(this,e))}insert(e,t){null!==this.doc?Hs(this.doc,(n=>{wo(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Hs(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;mo(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Hs(this.doc,(n=>{_o(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return vo(this,e)}toArray(){return fo(this)}slice(e=0,t=this.length){return ho(this,e,t)}toJSON(){return this.map((e=>e instanceof uo?e.toJSON():e))}map(e){return go(this,e)}forEach(e){po(this,e)}[Symbol.iterator](){return yo(this)}_write(e){e.writeTypeRef(fc)}}class Do extends to{constructor(e,t,n){super(e,t),this.keysChanged=n}}class To extends uo{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 To}clone(){const e=new To;return this.forEach(((t,n)=>{e.set(n,t instanceof uo?t.clone():t)})),e}_callObserver(e,t){ao(this,e,new Do(this,e,t))}toJSON(){this.doc??ro();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof uo?r.toJSON():r}})),e}get size(){return[...Co(this)].length}keys(){return es(Co(this),(e=>e[0]))}values(){return es(Co(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return es(Co(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??ro(),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?Hs(this.doc,(t=>{ko(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Hs(this.doc,(n=>{So(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return Eo(this,e)}has(e){return Io(this,e)}clear(){null!==this.doc?Hs(this.doc,(e=>{this.forEach((function(t,n,r){ko(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(pc)}}const Uo=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&Di(e,t);class Po{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&ti(),this.right.content.constructor===cc)this.right.deleted||No(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const Lo=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===cc)t.right.deleted||No(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Ns(e,Cs(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},jo=(e,t,n,r)=>{const i=new Map,s=r?co(t,n):null;if(s){const t=new Po(s.p.left,s.p,s.index,i);return Lo(e,t,n-s.index)}{const r=new Po(null,t._start,0,i);return Lo(e,r,n)}},Ro=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===cc&&Uo(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 kc(Cs(s,Us(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new cc(o,r));a.integrate(e,0),n.right=a,n.forward()}))},No=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},$o=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===cc&&Uo(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Mo=(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(!Uo(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new kc(Cs(s,Us(i.store,s)),r,r&&r.lastId,u,u&&u.id,t,null,new cc(c,l)),n.right.integrate(e,0),n.forward()}}return o},Bo=(e,t,n,r,i)=>{n.currentAttributes.forEach(((e,t)=>{void 0===i[t]&&(i[t]=null)}));const s=e.doc,o=s.clientID;$o(n,i);const c=Mo(e,t,n,i),l=r.constructor===String?new dc(r):r instanceof uo?new wc(r):new oc(r);let{left:a,right:u,index:d}=n;t._searchMarker&&lo(t._searchMarker,n.index,l.getLength()),u=new kc(Cs(o,Us(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(),Ro(e,t,n,c)},Fo=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;$o(n,i);const c=Mo(e,t,n,i);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===cc));){if(!n.right.deleted)switch(n.right.content.constructor){case cc:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(Uo(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&&Ns(e,Cs(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 kc(Cs(o,Us(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new dc(i)),n.right.integrate(e,0),n.forward()}Ro(e,t,n,c)},Wo=(e,t,n,r,i)=>{let s=t;const o=cr();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===cc){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 cc:{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||No(i,n);break}}}t=t.right}return c},Vo=e=>{let t=0;return Hs(e.doc,(n=>{let r=e._start,i=e._start,s=cr();const o=lr(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===cc)No(o,i.content);else t+=Wo(n,r,i,s,o),s=lr(o),r=i;i=i.right}})),t},Ko=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&&Ms(e,n.store.clients.get(r),s,i,(e=>{e.deleted||e.content.constructor!==cc||e.constructor===tc||t.add(e.parent)}))}Hs(n,(n=>{rs(e,e.deleteSet,(e=>{if(e instanceof tc||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===cc?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===cc){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)Vo(e)}))},Ho=(e,t,n)=>{const r=n,i=lr(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case wc:case oc:case dc:n<t.right.length&&Ns(e,Cs(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&Wo(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&lo(o._searchMarker,t.index,-r+n),t};class zo extends to{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=[];Hs(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=Ci({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case wc:case oc: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 dc: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 cc:{const{key:t,value:c}=i.content;if(this.adds(i)){if(!this.deletes(i)){const l=n.get(t)??null;Uo(l,c)?null!==c&&i.delete(e):("retain"===s&&u(),Uo(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;Uo(e,c)||("retain"===s&&u(),o[t]=e)}else if(!i.deleted){r.set(t,c);const n=o[t];void 0!==n&&(Uo(n,c)?null!==n&&i.delete(e):("retain"===s&&u(),null===c?delete o[t]:o[t]=c))}i.deleted||("insert"===s&&u(),No(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 Jo extends uo{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ro(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new Jo}clone(){const e=new Jo;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new zo(this,e,t);ao(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ro();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===dc&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Hs(this.doc,(n=>{const r=new Po(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)&&Bo(n,this,r,o,s.attributes||{})}else void 0!==s.retain?Fo(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&Ho(n,r,s.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??ro();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(As(c,e)||void 0!==t&&As(c,t))switch(c.content.constructor){case dc:{const r=i.get("ychange");void 0===e||As(c,e)?void 0===t||As(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 wc:case oc:{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 cc:As(c,e)&&(l(),No(i,c.content))}c=c.right}l()};return e||t?Hs(s,(n=>{e&&Os(n,e),t&&Os(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Hs(r,(r=>{const i=jo(r,this,e,!n);n||(n={},i.currentAttributes.forEach(((e,t)=>{n[t]=e}))),Bo(r,this,i,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?Hs(r,(r=>{const i=jo(r,this,e,!n);Bo(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?Hs(n,(n=>{Ho(n,jo(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?Hs(r,(r=>{const i=jo(r,this,e,!1);null!==i.right&&Fo(r,this,i,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?Hs(this.doc,(t=>{ko(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?Hs(this.doc,(n=>{So(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return Eo(this,e)}getAttributes(){return xo(this)}_write(e){e.writeTypeRef(gc)}}class qo{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ro()}[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!==Go&&t.constructor!==Yo||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 Yo extends uo{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 Yo}clone(){const e=new Yo;return e.insert(0,this.toArray().map((e=>e instanceof uo?e.clone():e))),e}get length(){return this.doc??ro(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new qo(this,e)}querySelector(e){e=e.toUpperCase();const t=new qo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),fr(new qo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){ao(this,e,new Xo(this,t,e))}toString(){return go(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),po(this,(i=>{r.insertBefore(i.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?Hs(this.doc,(n=>{wo(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Hs(this.doc,(n=>{const r=e&&e instanceof uo?e._item:e;mo(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 Qr("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Hs(this.doc,(n=>{_o(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return fo(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return vo(this,e)}slice(e=0,t=this.length){return ho(this,e,t)}forEach(e){po(this,e)}_write(e){e.writeTypeRef(vc)}}class Go extends Yo{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 Go(this.nodeName)}clone(){const e=new Go(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 uo?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?Hs(this.doc,(t=>{ko(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Hs(this.doc,(n=>{So(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return Eo(this,e)}hasAttribute(e){return Io(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&&As(i,t)&&(n[r]=i.content.getContent()[i.length-1])})),n})(this,e):xo(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 po(this,(i=>{r.appendChild(i.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(yc),e.writeKey(this.nodeName)}}class Xo extends to{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 Zo extends To{constructor(e){super(),this.hookName=e}_copy(){return new Zo(this.hookName)}clone(){const e=new Zo(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(mc),e.writeKey(this.hookName)}}class Qo extends Jo{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 Qo}clone(){const e=new Qo;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(bc)}}class ec{constructor(e,t){this.id=e,this.length=t}get deleted(){throw ei()}mergeWith(e){return!1}write(e,t,n){throw ei()}integrate(e,t){throw ei()}}class tc extends ec{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),Ps(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class nc{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new nc(this.content)}splice(e){throw ei()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class rc{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new rc(this.len)}splice(e){const t=new rc(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){os(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 ic=(e,t)=>new us({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class sc{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 sc(ic(this.doc.guid,this.opts))}splice(e){throw ei()}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 oc{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new oc(this.embed)}splice(e){throw ei()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class cc{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new cc(this.key,this.value)}splice(e){throw ei()}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 lc{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new lc(this.arr)}splice(e){const t=new lc(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 ac="development"===Ni("node_env");class uc{constructor(e){this.arr=e,ac&&Ui(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new uc(this.arr)}splice(e){const t=new uc(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 dc{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new dc(this.str)}splice(e){const t=new dc(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 hc=[e=>new Oo,e=>new To,e=>new Jo,e=>new Go(e.readKey()),e=>new Yo,e=>new Zo(e.readKey()),e=>new Qo],fc=0,pc=1,gc=2,yc=3,vc=4,mc=5,bc=6;class wc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new wc(this.type._copy())}splice(e){throw ei()}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 _c=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new kc(Cs(r,i+n),t,Cs(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=Cs(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 kc extends ec{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>=Us(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Us(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===xs&&this.id.client!==this.parent.client&&this.parent.clock>=Us(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=$s(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Ns(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===tc||this.right&&this.right.constructor===tc)this.parent=null;else if(this.parent){if(this.parent.constructor===xs){const e=js(t,this.parent);e.constructor===tc?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===kc?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===kc&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=$s(e,e.doc.store,Cs(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),Is(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Is(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(js(e.doc.store,t.origin)))break;r.has(js(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),Ps(e.doc.store,this),this.content.integrate(e,this),Ws(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new tc(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:Cs(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Is(e.origin,this.lastId)&&this.right===e&&Is(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(),os(e.deleteSet,this.id.client,this.id.clock,this.length),Ws(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw ti();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[Ls(r,t.id.clock)]=n})(e,this,new tc(this.id,this.length)):this.content=new rc(this.length)}write(e,t){const n=t>0?Cs(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:kr)|(null===r?0:_r)|(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 ti()})(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===xs?(e.writeParentInfo(!1),e.writeLeftID(t)):ti();null!==i&&e.writeString(i)}this.content.write(e,t)}}const Sc=(e,t)=>Ec[31&t](e),Ec=[()=>{ti()},e=>new rc(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 lc(n)},e=>new nc(e.readBuf()),e=>new dc(e.readString()),e=>new oc(e.readJSON()),e=>new cc(e.readKey(),e.readJSON()),e=>new wc(hc[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new uc(n)},e=>new sc(ic(e.readString(),e.readAny())),()=>{ti()}];class xc extends ec{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){ti()}write(e,t){e.writeInfo(10),Nr(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Ic="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Cc="__ $YJS$ __";function Ac(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}Ic[Cc],Ic[Cc]=!0;const Oc=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function Dc(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=Pc(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=Pc(n,r,i),o=null===(t=this.cache[s])||void 0===t?void 0:t.deref();o&&Oc.unregister(o),this.cache[s]=new WeakRef(e),Oc.register(e,{cache:this.cache,key:s},e)},delete(e){Oc.unregister(e);const t=Pc(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 Tc=new WeakSet;function Uc(e){if(Tc.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Pc(e,t,n){return`${e}[${t}].${n}`}let Lc=null;function jc(e){Lc=e}function Rc(){}const Nc=new WeakMap;function $c(){return r.Events(null,"load","sync","error")}class Mc{static getOrCreateDocument(e,t,n,r){var i,s;const o=Dc(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 us({meta:{db:e,updatesTable:i,parentProp:r,parentTable:n,parentId:s}}),t.add(o),o.on("destroy",(()=>{Tc.add(o),t.delete(o)})),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=Nc.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 Mc(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Nc.set(e,r)),r}static release(e){if(!e||Tc.has(e))return;const t=Nc.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(Mc.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return Nc.get(e)}static get currentUpdateRow(){return Lc}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((e,t)=>{this.doc?this.doc.isLoaded?e():this._error?t(this._error):Tc.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):Tc.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=$c(),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]=()=>Mc.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`);Uc(e),this.stopObserving=function(e,t,r,s,o,c){let l=0,a=!0;const u=i((()=>{Uc(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?(Uc(t),n.length>0&&Hs(t,(()=>{n.forEach((e=>{try{jc(e),bs(t,e.u)}finally{jc(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),Mc.on("new").fire(this)}destroy(){var e;Nc.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=$c(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Bc(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=Ac(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=Ac(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(sr);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:sr}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})))));break}case"u-reject":{const e=Ac(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=Mc.getDocCache(t.dx).find(c.table,i,c.prop);r&&r.destroy()}break}case"in-sync":{const e=Mc.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}}))}Mc.on=r.Events(null,{new:[function(e,t){return e===Rc?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Rc?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)}}]}),Mc.getDocCache=Dc,r.DexieYProvider=Mc;const Fc=1,Wc=2,Vc=3;function Kc(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 pn(t),o={"Content-Type":"application/json",Accept:"application/octet-stream"};s&&(o.Authorization=`Bearer ${s.accessToken}`);const c=yield fetch(`${n}/y/download`,{body:Hn.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=L(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),ln,(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=Ac(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=L(r);!(i=(f=yield U(g.next())).done);p=!0){c=f.value,p=!1;const e=new Xt(c);for(;Zt(e);)switch(en(e)){case Fc:yield U(h(!0)),l=nn(e);break;case Wc:yield U(h(!1)),a=nn(e),u=nn(e);break;case Vc:{const t=cn(e),n=Qt(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 Hc="currentSyncWorker";function zc(e,t,n,r){return Jc(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):er&&(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 zc(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:er?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function Jc(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?ut(e):[],d=u.map((t=>e.table(dt(t.name)))),h=yield e.getPersistedSyncState(),f=a.isLoggedIn,p=f?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return ut(e).filter((e=>!n.includes(e.name)))}(e,h):[];Qn(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!==j.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!==j.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==j.userId||(e.owner=t.userId),e.realmId&&e.realmId!==j.userId||(e.realmId=t.userId))})))}))}(p,a,null==h?void 0:h.realms)})))),Qn(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 gt(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(sr),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield or(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]:Gs(s);if(r)n.push({type:"u-c",table:i.name,prop:t.prop,k:e,u:c,i:o});else{const r=qs(c);n.push({type:"sv",table:i.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,u);if(Qn(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-${yt(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||"")&&_t(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 Qn(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=nr(y,null==v?void 0:v.latestRevisions),S=(null==v?void 0:v.clientIdentity)||bt(16);Qn(i);const E=yield Zn(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 gt(d,e,{since:k});for(const t of d){const n=ht(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()])}nr(r,k),yield tr(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=ut(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=qc(E.changes,r);if(yield ir(o,e),E.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield Bc(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(sr);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:sr,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 Xn(e),yield Jc(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 Kc(e,l,I)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function qc(e,t){const n={};Et(n,e);const r={};return Et(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))mt(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=bt(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 Yc=10,Gc=1e4,Xc=1e3;function Zc(t){const n=[],r=new c(!0),i=new c(null);let s=!1,o=new Array(Yc).fill(0);return i.subscribe((()=>C(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,o.shift(),o.push(Date.now()),r.next(!1);try{yield function(){return C(this,void 0,void 0,(function*(){for(var r,i,s,o,c,a;n.length>0;){const u=n.shift();try{yield l(t.cloud.syncState.pipe(Xe((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!u)continue;switch(u.type){case"token-expired":const l=t.cloud.currentUser.value,d=yield yn(t.cloud.options.databaseUrl,l);yield t.table("$logins").update(l.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===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(u.realm))||(null===(c=null==n?void 0:n.inviteRealms)||void 0===c?void 0:c.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)){it(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||it(t,"pull"));if((yield e.waitFor(at(i)))!==u.realmSetHash)return void it(t,"pull");let o=[];if(s.isLoggedIn){const e=ut(t).map((e=>t.table(dt(e.name))));o=yield gt(e,t)}if(u.changes.length>0){const e=qc(u.changes,o);yield ir(e,t)}i.latestRevisions=nr(o,i.latestRevisions),i.serverRevision=u.newRev,yield tr(t,r,i.latestRevisions,u.newRev),yield t.$syncState.put(i,"syncState")}))))}}catch(e){}}}))}()}finally{o[o.length-1]-o[0]<Gc&&(yield new Promise((e=>setTimeout(e,Xc)))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:r}}const Qc=new WeakMap,el={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let tl=0;function nl(e){"vip"in e&&(e=e.vip);let t=Qc.get(e.cloud);if(!t){const n=new a;let r=new B(`syncstatechanged-${e.name}`),i=new B(`synccomplete-${e.name}`);n.id=++tl;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))||j)),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 B(`syncstatechanged-${e.name}`),i=new B(`synccomplete-${e.name}`)}};Object.assign(t,o),t.messageConsumer=Zc(t),t.messageProducer=new a,Qc.set(e.cloud,t)}return t}const rl=new WeakMap;class il{constructor(e,t){rl.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new il(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return C(this,void 0,void 0,(function*(){rl.get(this).table("$logins").put(this)}))}}function sl(e,t){return l(u(e).pipe(d(t)))}function ol(e){return C(this,void 0,void 0,(function*(){const t=yield cl(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 un(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 cl(e,{deleteUnsyncedData:!0})}}))}function cl(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 sl(e.cloud.currentUser,(e=>e.userId===j.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function ll(e,...t){globalThis.console[e](...t)}function al(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 pn(e),!1}const s=new il(e,{claims:{},lastLogin:new Date(0)});return yield gn(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 hn(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 hn(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 dn(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Jn(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 fn(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 fn(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 Jn(i,e)}return yield i.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==j.userId&&s.userId!==i&&(yield ol(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&&(ll("debug","Login context property names:",Object.keys(t)),ll("debug","Login context property names:",Object.keys(t)),ll("debug","Login context:",t),ll("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield sl(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,s),it(e,"pull"),s.userId!==i}))}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+An(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(!_t(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 c(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=>dt(e)));s=n.transaction([...r,...e],i)}else s=n.transaction(r,i);if("readwrite"===i){s.txid=yt(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)&&it(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({},el),n);Object.keys(el).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=el[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(el[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 c(!0),Tl=new c(!0);Dl.pipe(et((e=>e?f(!0):f(!1).pipe(qe(2e4)))),Ye()).subscribe(Tl);const Ul="undefined"!=typeof document?h(document,"visibilitychange"):f({}),Pl=Ul.pipe(Xe((()=>"hidden"===document.visibilityState))),Ll=Ul.pipe(Xe((()=>"visible"===document.visibilityState))),jl="undefined"!=typeof window?p(Ll,h(window,"mousedown"),h(window,"mousemove"),h(window,"keydown"),h(window,"wheel"),h(window,"touchmove")):f({});"undefined"!=typeof document&&p(f(!0),Pl,jl).pipe(Be((()=>"visible"===document.visibilityState)),tt((e=>{Dl.value!==e&&Dl.next(e)})),et((e=>e?f(0).pipe(qe(16e4),tt((()=>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 a,Ml.set(e,t)),t}class Fl extends o{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?Hn.parse(e.data):function(e){const t=new Xt(e),n=nn(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:nn(t)};const r=nn(t),i=nn(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:i,i:Number(sn(t))};default:{const e=cn(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:Qt(t)};case"doc-open":return{type:n,table:r,prop:i,k:e,serverRev:cn(t),sv:cn(t)};case"sv":return{type:n,table:r,prop:i,k:e,sv:Qt(t)};case"u-c":return{type:n,table:r,prop:i,k:e,u:Qt(t),i:Number(sn(t))};case"u-s":return{type:n,table:r,prop:i,k:e,u:Qt(t),r:t.pos<t.arr.length&&nn(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=Mc.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=Mc.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?Bc([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=Ac(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(sr,{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(Hn.stringify(e))):null===(n=this.ws)||void 0===n||n.send(Jt(e)))}))),this.user.isLoggedIn&&!Il(this.db)&&this.subscriptions.add(function(e){const t=pt(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 u(s.get(sr)).pipe(g((e=>{let r=(null==e?void 0:e.unsentFrom)||1;return u(i((()=>C(this,void 0,void 0,(function*(){return(yield or(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 l(jl)}))}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 zc(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 Xn(e),yield Ol(e,Hc,(()=>zc(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 d=l?"pull":"push";o=Date.now(),ql(e,t,n,{cancelToken:i,retryImmediatelyOnFetchError:!0,purpose:d}).then((()=>{if(i.cancelled)h();else if(l||a)return l=!1,a=!1,c();u=!1,s=0,o=0})).catch((e=>{if(i.cancelled)h(),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=e=>{i.cancelled||("pull"===e&&(l=!0),"push"===e&&(a=!0),u?s||o>0&&Date.now():(u=!0,c()))},h=()=>{i.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{d(e||"pull")}))},stop:h}}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,La,ja,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&&(La===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=[])),La=Pa},Ql.diffed=function(e){Fa&&Fa(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Na.push(t)&&ja===Ql.requestAnimationFrame||((ja=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}))),La=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({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]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(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 eu extends da{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=u(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?la(Qa,Object.assign({},t)):null}}function tu(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const nu=tu((e=>new c(j)));function ru(e,t){let n=t,r=u(e).pipe(_((e=>n=e)),k({resetOnRefCountZero:()=>S(1e3)}));const i=new o((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 iu=tu((e=>ru(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})))),{}))),su=tu((e=>ru(nu(e._novip).pipe(et((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 ou(...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 cu=tu((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}(ru(w([su(e._novip),iu(e._novip)]).pipe(Be((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:j.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=pt(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:"*"}:ou(...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 lu{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 au=tu((e=>{const t=nu(e._novip).pipe(et((t=>i((()=>e.members.where({email:t.email||""}).toArray()))))),n=cu(e._novip),r=su(e._novip);return ru(w([t,r,n]).pipe(Be((([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 uu(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(sr),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=Gs(g.map((e=>e.u))),t=qs(e);p.sv=t}e.messageProducer.next(p)}}))}r.addCleanupHandler(a)}))})(),a}(e,i,t),$l.set(i,o),o)})}}const du={nameSuffix:!0};function hu(t){const n=t.name,r=nu(t),s=[];let o=!1,d=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,a,m,_,k,S,E;g=!1;const x=nl(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(eu,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Oa(la(eu,{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(et((e=>{const n=t;t=e;const r=f(e);switch(e){case"disconnected":return Dl.value?r.pipe(Ve(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(Ve(4e3));default:return r}})));return w([n,e.syncStateChangedEvent.pipe(Qe({phase:"initial"})),nu(e.dx._novip),Tl]).pipe(Be((([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:er?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,c]=yield Promise.all([x.getOptions(),x.getSchema(),x.getPersistedSyncState()]);if(o){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==c?void 0:c.initiallySynced,null==c?void 0:c.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 l(w([r.pipe(Ze(1),ze(1)),x.cloud.persistedSyncState.pipe(Ze(1),ze(1))]));const e=uu(x);Mc.on.new.subscribe(e),x.dx.once("close",(()=>{Mc.on.new.unsubscribe(e)}))}let D=!1;const T=yield x.getCurrentUser(),U=null===(a=x.cloud.options)||void 0===a?void 0:a.requireAuth;U&&(x.cloud.isServiceWorkerDB?yield l(r.pipe(Xe((e=>!!e.isLoggedIn)),ze(1))):"object"==typeof U?(!T.isLoggedIn||U.userId&&T.userId!==U.userId||U.email&&T.email!==U.email)&&(D=yield al(x,U)):T.isLoggedIn||(D=yield al(x))),!T.isLoggedIn||O&&O.includes(T.userId)||(D=!0),d&&d.stop(),d=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,Hc,(()=>zc(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||rt(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&&(d=Gl(x,x.cloud.options,x.cloud.schema),d.start(),P||it(x,"push")),y(),x.cloud.isServiceWorkerDB||s.push(h(self,"online").subscribe((()=>{x.syncStateChangedEvent.next({phase:"not-in-sync"}),Il(x)||it(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(Xe((e=>e)),et((()=>e.getPersistedSyncState())),Xe((e=>e&&e.serverRevision)),et((e=>C(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield at(e)}}))))),r=p(n,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(Xe((e=>null==e?void 0:e.serverRevision)),ze(1),et((t=>e.cloud.currentUser.pipe(Be((e=>[e,t]))))),et((([e,t])=>Tl.pipe(Be((n=>[n?e:null,t]))))),et((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(Xe((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),ze(1),Be((e=>[t,e]))):new c([t,n]))),et((e=>C(this,[e],void 0,(function*([e,t]){return[e,yield at(t)]})))),Ye((([e,t],[n,r])=>e===n&&t===r)),et((([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):u([]):t()})),je((n=>"TokenExpiredError"===(null==n?void 0:n.name)?f(!0).pipe(et((()=>C(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield yn(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})})))),et((()=>t()))):b((()=>n)))),je((n=>(e.cloud.webSocketStatus.next("error"),n instanceof Kl?b((()=>n)):u(Hl()).pipe(et((()=>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,d&&d.stop(),d=null,r.next(j)}));const v=new a;var m;t.cloud={version:"4.2.0-alpha.1",options:Object.assign({},du),schema:null,get currentUserId(){return r.value.userId||j.userId},currentUser:r,syncState:new c({phase:"initial",status:"not-started"}),events:{syncComplete:v},persistedSyncState:new c(void 0),userInteraction:new c(void 0),webSocketStatus:new c("not-started"),login(e){return C(this,void 0,void 0,(function*(){const n=nl(t);yield n.cloud.sync(),yield al(n,e)}))},invites:au(t),roles:iu(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),o=!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)}`,nl(t).reconfigure()),Xl(t.cloud.schema,t.cloud.options)},logout(){return C(this,arguments,void 0,(function*({force:e}={}){e?yield cl(nl(t),{deleteUnsyncedData:!0}):yield ol(nl(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=nl(t);if("ok"!==((null===(r=s.cloud.currentUser.value.license)||void 0===r?void 0:r.status)||"ok")&&(yield pn(s)),"pull"===n){const t=s.cloud.persistedSyncState.value;if(it(s,n),e){const e=yield l(s.cloud.persistedSyncState.pipe(Xe((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;it(s,n),e&&(yield l(u(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(Xe((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=cu(e),o=t=>{const s=t[i||e.cloud.currentUserId];return s?new lu(s.permissions,n,void 0===i||i===e.cloud.currentUserId||r===e.cloud.currentUserId):new lu({},n,!r||r===e.cloud.currentUserId)},c=s.pipe(Be(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:nl(t)})),t.use((m=nl(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:j.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(nl(t)))}hu.version="4.2.0-alpha.1",e.Cloud=hu;const fu=new Map;function pu(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const gu=new Map;function yu(t,n){let r=gu.get(t+"/"+n);return r||(r=function t(n,r){return C(this,void 0,void 0,(function*(){var i;let s=fu.get(n);if(!s){const i=new e(n,{addons:[hu]});if(s=nl(i),s.cloud.isServiceWorkerDB=!0,i.on("versionchange",o),yield s.dx.open(),fu.get(n))return s.close(),yield t(n,r);fu.set(n,s)}if((null===(i=s.cloud.options)||void 0===i?void 0:i.databaseUrl)&&s.cloud.schema)try{yield ql(s,s.cloud.options,s.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:r})}catch(t){if(o(),t.name!==e.errnames.NoSuchDatabase)throw t}function o(){return s.dx.on.versionchange.unsubscribe(o),fu.get(s.name)===s&&fu.delete(s.name),s.dx.close(),!1}}))}(t,n).then((()=>{gu.delete(t+"/"+n)})).catch((e=>(gu.delete(t+"/"+n),Promise.reject(e)))),gu.set(t+"/"+n,r)),r}fl||(self.addEventListener("sync",(e=>{const t=pu(e.tag);t&&e.waitUntil(yu(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=pu(e.tag);t&&e.waitUntil(yu(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>yu(t,e.data.purpose||"pull").catch((e=>C(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>{}))):n().catch((e=>{}))}})));
|
|
1
|
+
import e,{PropModification as t,cmp as n,RangeSet as r,liveQuery as o}from"dexie";import{Observable as s,BehaviorSubject as i,firstValueFrom as a,Subject as l,from as c,filter as u,of as d,fromEvent as f,merge as p,switchMap as y,tap as h,mergeMap as v,Subscription as m,throwError as b,combineLatest as g,map as _,share as w,timer as k,startWith as S}from"rxjs";import{filter as x,switchMap as I,delay as E,distinctUntilChanged as O,map as C,tap as T,take as j,catchError as U,debounceTime as A,startWith as P,skip as $}from"rxjs/operators";import{Encoder as D,writeVarString as L,writeAny as R,writeVarUint8Array as N,writeBigUint64 as B,toUint8Array as M}from"lib0/encoding";import{Decoder as F,readVarString as W,readAny as K,readVarUint8Array as V,readBigUint64 as H,hasContent as J,readUint8 as q}from"lib0/decoding";import*as z 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={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(te),Object.freeze(te.claims)}catch(e){}const ne={},re="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;re&&re.ready.then((e=>ne.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 oe{constructor(e){this.name=e}subscribe(e){if(!re)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 re.addEventListener("message",t),()=>re.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}))):ne.registration&&(null===(t=ne.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const se=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class ie extends s{constructor(e){const t="undefined"==typeof BroadcastChannel?new oe(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){se.has(e)?se.get(e).push(t):se.set(e,[t])}(`lbc-${e}`,r);try{t instanceof oe?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",o)}catch(e){}return()=>{!function(e,t){const n=se.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof oe?s():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=se.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}let ae=!1;function le(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){ae||(ae=!0)}}))}function ce(e,t){e.cloud.usingServiceWorker?le(e,t):e.localSyncEvent.next({purpose:t})}const ue="fromBase64"in Uint8Array,de="toBase64"in Uint8Array.prototype,fe="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):ue?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},pe="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):de?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(""))};function ye(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 pe(o)}))}function he(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 ve(e){return`$${e}_mutations`}function me(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 be=[].concat;function ge(e){return be.apply([],e)}function _e(e,t){return Y(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const o=ge(yield Promise.all(e.map((e=>Y(this,void 0,void 0,(function*(){const t=me(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 we(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 ke={}.hasOwnProperty;function Se(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)Se(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 ke.call(e,t)}(e,i)||(l=e[i]={}),Se(l,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const xe="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=Ie)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function Ie(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function Ee(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>Ee(e)))&&e.every(Oe))}function Oe(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(Oe)}function Ce(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))Se(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 Te(e,t){for(const{table:n,muts:r}of t)for(const t of r)Ce(e,n,t)}function je(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}}}))}class Ue 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 Ae(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 Pe(e,t,...n){return Ae(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 Ae(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 De(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 Ae(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function Le(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 Ne(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 Re(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 Ne(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=pe(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 Ue(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 Ae(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof Ue)throw yield Pe(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 Pe(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,o,s)}))}function Ne(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=pe(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 Ue(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{toString:Be}={};const Me={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 Fe(...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 Me;let s=n.get(r);if(void 0!==s)return s;const i=(o=e,Be.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:Me),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 We={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 Ke={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 Ve={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var He={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Je={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},qe={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const ze="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Ge=["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=ze[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Ye(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Qe[e[n]];return t}(pe(e))}function Ze(e){return fe(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+=Xe[e[n]];return t}(e))}const Xe={"-":"=",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:"+","|":"/"},Qe={};for(const e of Object.keys(Xe))Qe[Xe[e]]=e;var et={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Ye(e)}),revive:({v:e})=>{const t=Ze(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class tt{constructor(e,t){this.buf=e,this.type=t}}function nt(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 rt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var ot={Blob:{test:(e,t)=>"Blob"===t||e instanceof tt,replace:e=>({$t:"Blob",v:pe(e instanceof tt?e.buf:rt(nt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=fe(t);return void 0!==typeof Blob?new Blob([n]):new tt(n.buffer,e)}}};const st={...Ke,...Ve,...He,...Je,...qe,...Ge,...et,...ot};function it(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 at={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},lt={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:pe(rt(nt(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const o=fe(t);return new File([o],n,{type:e,lastModified:new Date(r).getTime()})}}};const ct="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class ut{toString(){return this.v}constructor(e){this.v=e}}const dt=ct?{}:{bigint:{test:e=>e instanceof ut,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new ut(e)}},ft=Object.assign(Object.assign(Object.assign(Object.assign({},at),dt),lt),{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)}}}),pt=Fe(st,ft),yt=function(...e){const t=Fe(st,We,...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 it(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 it(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)}}}(ft);class ht extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function vt(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=mt(s,o));const e=c.muts[r],n=JSON.stringify(t);e.keys[i]=n}else if("#"===t[0]){c===s&&(c=mt(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 mt(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 bt=new WeakMap;function gt(e){return Y(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=bt.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 _t(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 Le(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:vt(o.dx.core.schema,l,e),y:t,dxcv:o.cloud.version};o.syncStateChangedEvent.next({phase:"pushing"});const p=pt.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));bt.set(e,new Date(Date.now()+1e3*t))}else bt.delete(e)}}(o,y),!y.ok)throw new ht(y);if("application/x-bison"===y.headers.get("content-type"))return yt.fromBinary(yield y.blob());{const e=yield y.text();return pt.parse(e)}}))}function wt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let kt=!1;function St(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 xt(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 It(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 Et(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 It(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(kt=navigator.onLine,self.addEventListener("online",(()=>kt=!0)),self.addEventListener("offline",(()=>kt=!1)));const Ot="dexie-cloud-syncer";function Ct(e,t){return e.where("i").between(t,1/0,!0).toArray()}function Tt(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 jt(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=Tt(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=Tt(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(Ot);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:Ot}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,a.i+1)}))})))));break}case"u-reject":{const e=Tt(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 Ut=1,At=2,Pt=3;function $t(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 Le(t),i={"Content-Type":"application/json",Accept:"application/octet-stream"};s&&(i.Authorization=`Bearer ${s.accessToken}`);const a=yield fetch(`${n}/y/download`,{body:pt.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),je,(function(r){return Q(this,arguments,(function*(){var o,s,i,a;let l=null,c=null,u=null,d=[];function f(e){return Y(this,void 0,void 0,(function*(){const r=d[d.length-1];if(d.length>0){if(!l||!c||!u)throw new Error(`Protocol error from ${n}/y/download`);const e=Tt(t,c,u);e&&(yield e.bulkAdd(d)),d=[]}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 p,y=!0,h=ee(r);!(o=(p=yield X(h.next())).done);y=!0){a=p.value,y=!1;const e=new F(a);for(;J(e);)switch(q(e)){case Ut:yield X(f(!0)),l=W(e);break;case At:yield X(f(!1)),c=W(e),u=W(e);break;case Pt:{const t=K(e),n=V(e);d.push({k:t,u:n});break}}yield X(f(!1))}}catch(e){s={error:e}}finally{try{y||o||!(i=h.return)||(yield X(i.call(h)))}finally{if(s)throw s.error}}yield X(f(!0))}catch(t){throw t instanceof e.DexieError||(yield X(f(!1))),t}}))}))}))}const Dt="currentSyncWorker";function Lt(e,t,n,r){return Rt(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):kt&&(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 Lt(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:kt?"error":"offline",error:new Error(""+(null==o?void 0:o.message)||o)}),Promise.reject(o))}))))}function Rt(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?he(e):[],d=u.map((t=>e.table(ve(t.name)))),f=yield e.getPersistedSyncState(),p=c.isLoggedIn,y=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return he(e).filter((e=>!n.includes(e.name)))}(e,f):[];wt(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!==te.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!==te.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==te.userId||(e.owner=t.userId),e.realmId&&e.realmId!==te.userId||(e.realmId=t.userId))})))}))}(y,c,null==f?void 0:f.realms)})))),wt(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 _e(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(Ot),a=(null==i?void 0:i.unsentFrom)||1,l=(null==i?void 0:i.receivedUntil)||0,c=Math.min(a,l+1),u=yield Ct(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]:z.mergeUpdatesV2(s);if(r)n.push({type:"u-c",table:o.name,prop:t.prop,k:e,u:a,i:i});else{const r=z.encodeStateVectorFromUpdateV2(a);n.push({type:"sv",table:o.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,u);if(wt(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-${we(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||"")&&Ee(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 wt(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=xt(v,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||xe(16);wt(o);const x=yield _t(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 _e(d,e,{since:k});for(const t of d){const n=me(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()])}xt(r,k),yield St(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=he(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=Nt(x.changes,r);if(yield Et(i,e),x.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield jt(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(Ot);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:Ot,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 gt(e),yield Rt(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 $t(e,l,E)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function Nt(e,t){const n={};Te(n,e);const r={};return Te(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))Se(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=xe(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 Bt=10,Mt=1e4,Ft=1e3;function Wt(t){const n=[],r=new i(!0),o=new i(null);let s=!1,l=new Array(Bt).fill(0);return o.subscribe((()=>Y(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,l.shift(),l.push(Date.now()),r.next(!1);try{yield function(){return Y(this,void 0,void 0,(function*(){for(var r,o,s,i,l,c;n.length>0;){const u=n.shift();try{yield a(t.cloud.syncState.pipe(x((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!u)continue;switch(u.type){case"token-expired":const a=t.cloud.currentUser.value,d=yield Ne(t.cloud.options.databaseUrl,a);yield t.table("$logins").update(a.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===(o=null==n?void 0:n.inviteRealms)||void 0===o?void 0:o.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===(i=null==n?void 0:n.realms)||void 0===i?void 0:i.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===(c=t.cloud.syncState.value)||void 0===c?void 0:c.phase)){ce(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(u.baseRev!==o.serverRevision)return void("string"!=typeof u.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||ce(t,"pull"));if((yield e.waitFor(ye(o)))!==u.realmSetHash)return void ce(t,"pull");let i=[];if(s.isLoggedIn){const e=he(t).map((e=>t.table(ve(e.name))));i=yield _e(e,t)}if(u.changes.length>0){const e=Nt(u.changes,i);yield Et(e,t)}o.latestRevisions=xt(i,o.latestRevisions),o.serverRevision=u.newRev,yield St(t,r,o.latestRevisions,u.newRev),yield t.$syncState.put(o,"syncState")}))))}}catch(e){}}}))}()}finally{l[l.length-1]-l[0]<Mt&&(yield new Promise((e=>setTimeout(e,Ft)))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),o.next(null)},readyToServe:r}}const Kt=new WeakMap,Vt={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Ht=0;function Jt(e){"vip"in e&&(e=e.vip);let t=Kt.get(e.cloud);if(!t){const n=new l;let r=new ie(`syncstatechanged-${e.name}`),o=new ie(`synccomplete-${e.name}`);n.id=++Ht;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))||te)),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 ie(`syncstatechanged-${e.name}`),o=new ie(`synccomplete-${e.name}`)}};Object.assign(t,i),t.messageConsumer=Wt(t),t.messageProducer=new l,Kt.set(e.cloud,t)}return t}const qt=new WeakMap;class zt{constructor(e,t){qt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new zt(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return Y(this,void 0,void 0,(function*(){qt.get(this).table("$logins").put(this)}))}}function Gt(e,t){return a(c(e).pipe(u(t)))}function Yt(e){return Y(this,void 0,void 0,(function*(){const t=yield Zt(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 Ae(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 Zt(e,{deleteUnsyncedData:!0})}}))}function Zt(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 Gt(e.cloud.currentUser,(e=>e.userId===te.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function Xt(e,...t){globalThis.console[e](...t)}function Qt(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 Le(e),!1}const s=new zt(e,{claims:{},lastLogin:new Date(0)});return yield Re(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 Pe(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new ht(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 De(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 De(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 ht(o,e)}return yield o.json()}throw new Error(`Unexpected response from ${i}/token`)}))}}(e),e.cloud.userInteraction,t),o!==te.userId&&s.userId!==o&&(yield Yt(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&&(Xt("debug","Login context property names:",Object.keys(t)),Xt("debug","Login context property names:",Object.keys(t)),Xt("debug","Login context:",t),Xt("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield Gt(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,s),ce(e,"pull"),s.userId!==o}))}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+Ye(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(!Ee(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 i(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=>ve(e)));s=n.transaction([...r,...e],o)}else s=n.transaction(r,o);if("readwrite"===o){s.txid=we(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)&&ce(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({},Vt),n);Object.keys(Vt).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=Vt[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(Vt[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 i(!0),kn=new i(!0);wn.pipe(I((e=>e?d(!0):d(!1).pipe(E(2e4)))),O()).subscribe(kn);const Sn="undefined"!=typeof document?f(document,"visibilitychange"):d({}),xn=Sn.pipe(x((()=>"hidden"===document.visibilityState))),In=Sn.pipe(x((()=>"visible"===document.visibilityState))),En="undefined"!=typeof window?p(In,f(window,"mousedown"),f(window,"mousemove"),f(window,"keydown"),f(window,"wheel"),f(window,"touchmove")):d({});"undefined"!=typeof document&&p(d(!0),xn,En).pipe(C((()=>"visible"===document.visibilityState)),T((e=>{wn.value!==e&&wn.next(e)})),I((e=>e?d(0).pipe(E(16e4),T((()=>wn.next(!1)))):d(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 l,jn.set(e,t)),t}class An extends s{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 m{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?pt.parse(e.data):function(e){const t=new F(e),n=W(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:W(t)};const r=W(t),o=W(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:o,i:Number(H(t))};default:{const e=K(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:V(t)};case"doc-open":return{type:n,table:r,prop:o,k:e,serverRev:K(t),sv:K(t)};case"sv":return{type:n,table:r,prop:o,k:e,sv:V(t)};case"u-c":return{type:n,table:r,prop:o,k:e,u:V(t),i:Number(H(t))};case"u-s":return{type:n,table:r,prop:o,k:e,u:V(t),r:t.pos<t.arr.length&&W(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?jt([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=Tt(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(Ot,{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(pt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new D;switch(L(t,e.type),"table"in e&&L(t,e.table),"prop"in e&&L(t,e.prop),e.type){case"u-ack":case"u-reject":B(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":L(t,e.yServerRev);break;default:switch(R(t,e.k),e.type){case"aware":N(t,e.u);break;case"doc-open":R(t,e.serverRev),R(t,e.sv);break;case"doc-close":break;case"sv":N(t,e.sv);break;case"u-c":N(t,e.u),B(t,BigInt(e.i));break;case"u-s":N(t,e.u),L(t,e.r||"")}}return M(t)}(e)))}))),this.user.isLoggedIn&&!mn(this.db)&&this.subscriptions.add(function(e){const t=ge(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(Ot)).pipe(y((e=>{let r=(null==e?void 0:e.unsentFrom)||1;return c(o((()=>Y(this,void 0,void 0,(function*(){return(yield Ct(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(h((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 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 a(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 Lt(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 gt(e),yield _n(e,Dt,(()=>Lt(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 d=l?"pull":"push";i=Date.now(),Bn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:d}).then((()=>{if(o.cancelled)f();else if(l||c)return l=!1,c=!1,a();u=!1,s=0,i=0})).catch((e=>{if(o.cancelled)f(),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=e=>{o.cancelled||("pull"===e&&(l=!0),"push"===e&&(c=!0),u?s||i>0&&Date.now():(u=!0,a()))},f=()=>{o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{d(e||"pull")}))},stop:f}}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,Jn,qn,zn={},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)&&Jn.push(e)&&!ir.__r++||qn!==Vn.debounceRendering)&&((qn=Vn.debounceRendering)||setTimeout)(ir)}function ir(){for(var e;ir.__r=Jn.length;)e=Jn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Jn=[],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||zn,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||zn).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||zn,zn,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,Jn=[],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({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]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(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 Hr extends nr{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?Qn(Vr,Object.assign({},t)):null}}function Jr(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const qr=Jr((e=>new i(te)));function zr(e,t){let n=t,r=c(e).pipe(_((e=>n=e)),w({resetOnRefCountZero:()=>k(1e3)}));const o=new s((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 Gr=Jr((e=>zr(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})))),{}))),Yr=Jr((e=>zr(qr(e._novip).pipe(I((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 Zr(...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 Xr=Jr((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}(zr(g([Yr(e._novip),Gr(e._novip)]).pipe(C((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:te.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=ge(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:"*"}:Zr(...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 Qr{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 eo=Jr((e=>{const t=qr(e._novip).pipe(I((t=>o((()=>e.members.where({email:t.email||""}).toArray()))))),n=Xr(e._novip),r=Yr(e._novip);return zr(g([t,r,n]).pipe(C((([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 to(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=g([e.cloud.webSocketStatus,u.pipe(S(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(Ot),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=z.mergeUpdatesV2(h.map((e=>e.u))),t=z.encodeStateVectorFromUpdateV2(e);y.sv=t}e.messageProducer.next(y)}}))}r.addCleanupHandler(c)}))})(),c}(e,o,t),Tn.set(o,i),i)})}}const no={nameSuffix:!0};function ro(t){const n=t.name,r=qr(t),s=[];let u=!1,y=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,l,_,w,k,S,E;h=!1;const T=Jt(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(n=T.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(Hr,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),_r(Qn(Hr,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),T.cloud.isServiceWorkerDB||s.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(I((e=>{const n=t;t=e;const r=d(e);switch(e){case"disconnected":return wn.value?r.pipe(A(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(A(4e3));default:return r}})));return g([n,e.syncStateChangedEvent.pipe(P({phase:"initial"})),qr(e.dx._novip),kn]).pipe(C((([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:kt?c:"offline",license:"ok"}})))}(T).subscribe(t.cloud.syncState)),s.push(T.syncCompleteEvent.subscribe(m)),T.tables.every((e=>e.core))||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const D="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[L,R]=yield T.transaction("rw",T.$syncState,(()=>Y(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=T.cloud,[o,s,i]=yield Promise.all([T.getOptions(),T.getSchema(),T.getPersistedSyncState()]);if(u){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 T.$syncState.put(e,"options")}}else T.cloud.options=o||null;if((null===(e=T.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&D.length>0&&!rn?T.cloud.usingServiceWorker=!0:((null===(t=T.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&T.cloud.isServiceWorkerDB,T.cloud.usingServiceWorker=!1),Wn(r,T.cloud.options),Wn(s,T.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 T.$syncState.put(e,"schema"),Object.assign(r,e)}}else T.cloud.schema=s||null;return[null==i?void 0:i.initiallySynced,null==i?void 0:i.realms]}))));if(L&&T.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`)}}(T),v(),!T.cloud.isServiceWorkerDB){s.push(o((()=>T.getCurrentUser())).subscribe(r)),s.push(o((()=>T.getPersistedSyncState())).subscribe(T.cloud.persistedSyncState)),yield a(g([r.pipe($(1),j(1)),T.cloud.persistedSyncState.pipe($(1),j(1))]));const e=to(T);G.on.new.subscribe(e),T.dx.once("close",(()=>{G.on.new.unsubscribe(e)}))}let N=!1;const B=yield T.getCurrentUser(),M=null===(l=T.cloud.options)||void 0===l?void 0:l.requireAuth;M&&(T.cloud.isServiceWorkerDB?yield a(r.pipe(x((e=>!!e.isLoggedIn)),j(1))):"object"==typeof M?(!B.isLoggedIn||M.userId&&B.userId!==M.userId||M.email&&B.email!==M.email)&&(N=yield Qt(T,M)):B.isLoggedIn||(N=yield Qt(T))),!B.isLoggedIn||R&&R.includes(B.userId)||(N=!0),y&&y.stop(),y=null,v();const F=(null===(_=T.cloud.options)||void 0===_?void 0:_.databaseUrl)&&(!L||N);F&&(yield function(e,t,n){return Y(this,void 0,void 0,(function*(){yield _n(e,Dt,(()=>Lt(e,t,n,{isInitialSync:!0})))}))}(T,T.cloud.options,T.cloud.schema),T.setInitiallySynced(!0)),v(),T.cloud.usingServiceWorker&&(null===(w=T.cloud.options)||void 0===w?void 0:w.databaseUrl)?(F||le(T,"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){}}))}(T).catch((()=>{}))):(null===(k=T.cloud.options)||void 0===k?void 0:k.databaseUrl)&&T.cloud.schema&&!T.cloud.isServiceWorkerDB&&(y=Fn(T,T.cloud.options,T.cloud.schema),y.start(),F||ce(T,"push")),v(),T.cloud.isServiceWorkerDB||s.push(f(self,"online").subscribe((()=>{T.syncStateChangedEvent.next({phase:"not-in-sync"}),mn(T)||ce(T,"push")})),f(self,"offline").subscribe((()=>{T.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(S=T.cloud.options)||void 0===S?void 0:S.databaseUrl)||(null===(E=T.cloud.options)||void 0===E?void 0:E.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(x((e=>e)),I((()=>e.getPersistedSyncState())),x((e=>e&&e.serverRevision)),I((e=>Y(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield ye(e)}}))))),r=p(n,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(x((e=>null==e?void 0:e.serverRevision)),j(1),I((t=>e.cloud.currentUser.pipe(C((e=>[e,t]))))),I((([e,t])=>kn.pipe(C((n=>[n?e:null,t]))))),I((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(x((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),j(1),C((e=>[t,e]))):new i([t,n]))),I((e=>Y(this,[e],void 0,(function*([e,t]){return[e,yield ye(t)]})))),O((([e,t],[n,r])=>e===n&&t===r)),I((([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):c([]):t()})),U((n=>"TokenExpiredError"===(null==n?void 0:n.name)?d(!0).pipe(I((()=>Y(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield Ne(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})})))),I((()=>t()))):b((()=>n)))),U((n=>(e.cloud.webSocketStatus.next("error"),n instanceof Dn?b((()=>n)):c(Ln()).pipe(I((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(T))}))}(t)}catch(e){}}))),!0);let h=!1;function v(){if(h)throw new e.DatabaseClosedError}t.once("close",(()=>{s.forEach((e=>e.unsubscribe())),s.splice(0,s.length),h=!0,y&&y.stop(),y=null,r.next(te)}));const m=new l;var _;t.cloud={version:"4.2.0-alpha.3",options:Object.assign({},no),schema:null,get currentUserId(){return r.value.userId||te.userId},currentUser:r,syncState:new i({phase:"initial",status:"not-started"}),events:{syncComplete:m},persistedSyncState:new i(void 0),userInteraction:new i(void 0),webSocketStatus:new i("not-started"),login(e){return Y(this,void 0,void 0,(function*(){const n=Jt(t);yield n.cloud.sync(),yield Qt(n,e)}))},invites:eo(t),roles:Gr(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),u=!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)}`,Jt(t).reconfigure()),Wn(t.cloud.schema,t.cloud.options)},logout(){return Y(this,arguments,void 0,(function*({force:e}={}){e?yield Zt(Jt(t),{deleteUnsyncedData:!0}):yield Yt(Jt(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=Jt(t);if("ok"!==((null===(r=s.cloud.currentUser.value.license)||void 0===r?void 0:r.status)||"ok")&&(yield Le(s)),"pull"===n){const t=s.cloud.persistedSyncState.value;if(ce(s,n),e){const e=yield a(s.cloud.persistedSyncState.pipe(x((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;ce(s,n),e&&(yield a(c(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(x((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=Xr(e),i=t=>{const s=t[o||e.cloud.currentUserId];return s?new Qr(s.permissions,n,void 0===o||o===e.cloud.currentUserId||r===e.cloud.currentUserId):new Qr({},n,!r||r===e.cloud.currentUserId)},a=s.pipe(C(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:Jt(t)})),t.use((_=Jt(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:te.userId;if((null===(i=null===(s=_.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(Jt(t)))}ro.version="4.2.0-alpha.3",e.Cloud=ro;const oo=new Map;function so(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const io=new Map;function ao(t,n){let r=io.get(t+"/"+n);return r||(r=function t(n,r){return Y(this,void 0,void 0,(function*(){var o;let s=oo.get(n);if(!s){const o=new e(n,{addons:[ro]});if(s=Jt(o),s.cloud.isServiceWorkerDB=!0,o.on("versionchange",i),yield s.dx.open(),oo.get(n))return s.close(),yield t(n,r);oo.set(n,s)}if((null===(o=s.cloud.options)||void 0===o?void 0:o.databaseUrl)&&s.cloud.schema)try{yield Bn(s,s.cloud.options,s.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:r})}catch(t){if(i(),t.name!==e.errnames.NoSuchDatabase)throw t}function i(){return s.dx.on.versionchange.unsubscribe(i),oo.get(s.name)===s&&oo.delete(s.name),s.dx.close(),!1}}))}(t,n).then((()=>{io.delete(t+"/"+n)})).catch((e=>(io.delete(t+"/"+n),Promise.reject(e)))),io.set(t+"/"+n,r)),r}rn||(self.addEventListener("sync",(e=>{const t=so(e.tag);t&&e.waitUntil(ao(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=so(e.tag);t&&e.waitUntil(ao(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>ao(t,e.data.purpose||"pull").catch((e=>Y(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>{}))):n().catch((e=>{}))}})));
|
|
2
2
|
//# sourceMappingURL=service-worker.min.js.map
|