dexie-cloud-addon 4.2.0-alpha.1 → 4.2.0-alpha.4
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 +11 -15
- 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
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs")):"function"==typeof define&&define.amd?define(["dexie","rxjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs)}(this,(function(e,t){"use strict";var n=function(e,t){return n=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])},n(e,t)};function r(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}n(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function i(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 s(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 c(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 l(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 a(e){return this instanceof a?(this.v=e,this):new a(e)}function u(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 a?Promise.resolve(e.value.v).then(l,u):d(s[0][2],e)}(i[e](t))}catch(e){d(s[0][3],e)}}function l(e){c("next",e)}function u(e){c("throw",e)}function d(e,t){e(t),s.shift(),s.length&&c(s[0][0],s[0][1])}}function d(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 h={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(h),Object.freeze(h.claims)}catch(e){}const f={},p="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;p&&p.ready.then((e=>f.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 g{constructor(e){this.name=e}subscribe(e){if(!p)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 p.addEventListener("message",t),()=>p.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}))):f.registration&&(null===(t=f.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const y=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class v extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new g(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){y.has(e)?y.get(e).push(t):y.set(e,[t])}(`lbc-${e}`,r);try{t instanceof g?s=t.subscribe((e=>n.next(e))):t.addEventListener("message",i)}catch(e){}return()=>{!function(e,t){const n=y.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof g?s():t.removeEventListener("message",i)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=y.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function m(e){return"function"==typeof e}function b(e){return function(t){if(function(e){return m(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 w=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function _(e){return m(null==e?void 0:e.then)}var k,S,E=(k=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}},(S=k((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),S.prototype.constructor=S,S);function x(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var I=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 a=o(s),u=a.next();!u.done;u=a.next()){u.value.remove(this)}}catch(t){e={error:t}}finally{try{u&&!u.done&&(t=a.return)&&t.call(a)}finally{if(e)throw e.error}}else s.remove(this);var d=this.initialTeardown;if(m(d))try{d()}catch(e){i=e instanceof E?e.errors:[e]}var h=this._finalizers;if(h){this._finalizers=null;try{for(var f=o(h),p=f.next();!p.done;p=f.next()){var g=p.value;try{A(g)}catch(e){i=null!=i?i:[],e instanceof E?i=l(l([],c(i)),c(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{p&&!p.done&&(r=f.return)&&r.call(f)}finally{if(n)throw n.error}}}if(i)throw new E(i)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)A(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)&&x(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&x(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function C(e){return e instanceof I||e&&"closed"in e&&m(e.remove)&&m(e.add)&&m(e.unsubscribe)}function A(e){m(e)?e():e.unsubscribe()}I.EMPTY;var O={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},D={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=D.delegate;return(null==i?void 0:i.setTimeout)?i.setTimeout.apply(i,l([e,t],c(n))):setTimeout.apply(void 0,l([e,t],c(n)))},clearTimeout:function(e){var t=D.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function T(e){D.setTimeout((function(){throw e}))}function U(){}var j=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,C(t)&&t.add(n)):n.destination=M,n}return r(t,e),t.create=function(e,t,n){return new N(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}(I),P=Function.prototype.bind;function L(e,t){return P.call(e,t)}var R=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){$(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){$(e)}else $(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){$(e)}},e}(),N=function(e){function t(t,n,r){var i,s,o=e.call(this)||this;m(t)||!t?i={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:o&&O.useDeprecatedNextContext?((s=Object.create(t)).unsubscribe=function(){return o.unsubscribe()},i={next:t.next&&L(t.next,s),error:t.error&&L(t.error,s),complete:t.complete&&L(t.complete,s)}):i=t;return o.destination=new R(i),o}return r(t,e),t}(j);function $(e){T(e)}var M={closed:!0,next:U,error:function(e){throw e},complete:U},B="function"==typeof Symbol&&Symbol.observable||"@@observable";function F(e){return e}var W=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 j||function(e){return e&&m(e.next)&&m(e.error)&&m(e.complete)}(r)&&C(r)?e:new N(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=V(t))((function(t,r){var i=new N({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[B]=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?F: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=V(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 V(e){var t;return null!==(t=null!=e?e:O.Promise)&&void 0!==t?t:Promise}function K(e){return m(e[B])}function H(e){return Symbol.asyncIterator&&m(null==e?void 0:e[Symbol.asyncIterator])}function z(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 J="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function q(e){return m(null==e?void 0:e[J])}function Y(e){return u(this,arguments,(function(){var t,n,r;return s(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,a(t.read())];case 3:return n=i.sent(),r=n.value,n.done?[4,a(void 0)]:[3,5];case 4:return[2,i.sent()];case 5:return[4,a(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 G(e){return m(null==e?void 0:e.getReader)}function Q(e){if(e instanceof W)return e;if(null!=e){if(K(e))return i=e,new W((function(e){var t=i[B]();if(m(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(w(e))return r=e,new W((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(_(e))return n=e,new W((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,T)}));if(H(e))return X(e);if(q(e))return t=e,new W((function(e){var n,r;try{for(var i=o(t),s=i.next();!s.done;s=i.next()){var c=s.value;if(e.next(c),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(G(e))return X(Y(e))}var t,n,r,i;throw z(e)}function X(e){return new W((function(t){(function(e,t){var n,r,o,c;return i(this,void 0,void 0,(function(){var i,l;return s(this,(function(s){switch(s.label){case 0:s.trys.push([0,5,6,11]),n=d(e),s.label=1;case 1:return[4,n.next()];case 2:if((r=s.sent()).done)return[3,4];if(i=r.value,t.next(i),t.closed)return[2];s.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return l=s.sent(),o={error:l},[3,11];case 6:return s.trys.push([6,,9,10]),r&&!r.done&&(c=n.return)?[4,c.call(n)]:[3,8];case 7:s.sent(),s.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function Z(e,t,n,r,i){return new ee(e,t,n,r,i)}var ee=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 r(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}(j),te=function(e){function t(t,n){return e.call(this)||this}return r(t,e),t.prototype.schedule=function(e,t){return this},t}(I),ne={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var i=ne.delegate;return(null==i?void 0:i.setInterval)?i.setInterval.apply(i,l([e,t],c(n))):setInterval.apply(void 0,l([e,t],c(n)))},clearInterval:function(e){var t=ne.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},re=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 r(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),ne.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;ne.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,x(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(te),ie={now:function(){return(ie.delegate||Date).now()},delegate:void 0},se=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=ie.now,e}(),oe=new(function(e){function t(t,n){void 0===n&&(n=se.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return r(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}(se))(re),ce=oe;function le(e){return e&&m(e.schedule)}function ae(e,t,n){void 0===e&&(e=0),void 0===n&&(n=ce);var r=-1;return null!=t&&(le(t)?n=t:r=t),new W((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 ue(e){return le((t=e)[t.length-1])?e.pop():void 0;var t}function de(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 he(e){return b((function(t,n){var r,i=null,s=!1;i=t.subscribe(Z(n,void 0,void 0,(function(o){r=Q(e(o,he(e)(t))),i?(i.unsubscribe(),i=null,r.subscribe(n)):s=!0}))),s&&(i.unsubscribe(),i=null,r.subscribe(n))}))}function fe(e,t){return void 0===t&&(t=0),b((function(n,r){n.subscribe(Z(r,(function(n){return de(r,e,(function(){return r.next(n)}),t)}),(function(){return de(r,e,(function(){return r.complete()}),t)}),(function(n){return de(r,e,(function(){return r.error(n)}),t)})))}))}function pe(e,t){return void 0===t&&(t=0),b((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function ge(e,t){if(!e)throw new Error("Iterable cannot be null");return new W((function(n){de(n,t,(function(){var r=e[Symbol.asyncIterator]();de(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function ye(e,t){if(null!=e){if(K(e))return function(e,t){return Q(e).pipe(pe(t),fe(t))}(e,t);if(w(e))return function(e,t){return new W((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(_(e))return function(e,t){return Q(e).pipe(pe(t),fe(t))}(e,t);if(H(e))return ge(e,t);if(q(e))return function(e,t){return new W((function(n){var r;return de(n,t,(function(){r=e[J](),de(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 m(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(G(e))return function(e,t){return ge(Y(e),t)}(e,t)}throw z(e)}function ve(e,t){return b((function(n,r){var i=0;n.subscribe(Z(r,(function(n){r.next(e.call(t,n,i++))})))}))}function me(e,t,n){return void 0===n&&(n=1/0),m(t)?me((function(n,r){return ve((function(e,i){return t(n,e,r,i)}))(Q(e(n,r)))}),n):("number"==typeof t&&(n=t),b((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;Q(n(e,u++)).subscribe(Z(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?de(t,o,(function(){return p(e)})):p(e)};l.length&&a<r;)e();h()}catch(e){t.error(e)}})))};return e.subscribe(Z(t,f,(function(){d=!0,h()}))),function(){null==c||c()}}(t,r,e,n)})))}function be(){return void 0===(e=1)&&(e=1/0),me(F,e);var e}function we(e,t){return void 0===t&&(t=oe),b((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(Z(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 _e(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return be()((e=n,(t=ue(n))?ye(e,t):Q(e)))}var ke=new W((function(e){return e.complete()}));function Se(e){return e<=0?function(){return ke}:b((function(t,n){var r=0;t.subscribe(Z(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Ee(e,t){return t?function(n){return _e(t.pipe(Se(1),b((function(e,t){e.subscribe(Z(t,U))}))),n.pipe(Ee(e)))}:me((function(t,n){return e(t,n).pipe(Se(1),function(e){return ve((function(){return e}))}(t))}))}function xe(e,t){void 0===t&&(t=oe);var n=ae(e,t);return Ee((function(){return n}))}function Ie(e,t){return void 0===t&&(t=F),e=null!=e?e:Ce,b((function(n,r){var i,s=!0;n.subscribe(Z(r,(function(n){var o=t(n);!s&&e(i,o)||(s=!1,i=o,r.next(n))})))}))}function Ce(e,t){return e===t}function Ae(e,t){return b((function(n,r){var i=0;n.subscribe(Z(r,(function(n){return e.call(t,n,i++)&&r.next(n)})))}))}function Oe(e){return Ae((function(t,n){return e<=n}))}function De(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=ue(e);return b((function(t,r){(n?_e(e,t,n):_e(e,t)).subscribe(r)}))}function Te(e,t){return b((function(n,r){var i=null,s=0,o=!1,c=function(){return o&&!i&&r.complete()};n.subscribe(Z(r,(function(n){null==i||i.unsubscribe();var o=0,l=s++;Q(e(n,l)).subscribe(i=Z(r,(function(e){return r.next(t?t(n,e,l,o++):e)}),(function(){i=null,c()})))}),(function(){o=!0,c()})))}))}function Ue(e,t,n){var r=m(e)||t||n?{next:e,error:t,complete:n}:e;return r?b((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var i=!0;e.subscribe(Z(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)})))})):F}let je=!1;function Pe(e,t){return i(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){je||(je=!0)}}))}function Le(e,t){e.cloud.usingServiceWorker?Pe(e,t):e.localSyncEvent.next({purpose:t})}const Re="fromBase64"in Uint8Array,Ne="toBase64"in Uint8Array.prototype,$e="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):Re?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},Me="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):Ne?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 Be(e){return i(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 Me(i)}))}function Fe(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 We(e){return`$${e}_mutations`}function Ve(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const Ke=[].concat;function He(e){return Ke.apply([],e)}function ze(e,t){return i(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const s=He(yield Promise.all(e.map((e=>i(this,void 0,void 0,(function*(){const t=Ve(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)),o=[];let c=null,l=null;for(const{table:e,mut:t}of s)c&&c.table===e&&l===t.txid?c.muts.push(t):(c={table:e,muts:[t]},l=t.txid,o.push(c));return o}))}function Je(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 qe={}.hasOwnProperty;function Ye(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)Ye(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 qe.call(e,t)}(e,o)||(l=e[o]={}),Ye(l,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const Ge="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=Qe)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function Qe(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function Xe(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>Xe(e)))&&e.every(Ze))}function Ze(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(Ze)}function et(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))Ye(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 tt(e,t){for(const{table:n,muts:r}of t)for(const t of r)et(e,n,t)}const nt=Math.floor,rt=Math.abs,it=(e,t)=>e>t?e:t,st=128,ot=127,ct=Number.MAX_SAFE_INTEGER,lt=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&nt(e)===e),at=Array.isArray,ut="undefined"!=typeof TextEncoder?new TextEncoder:null,dt=ut?e=>ut.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 ht="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});ht&&1===ht.decode(new Uint8Array).length&&(ht=null);let ft=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const pt=(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},gt=(e,t)=>{for(;t>ot;)pt(e,st|ot&t),t=nt(t/128);pt(e,ot&t)},yt=new Uint8Array(3e4),vt=yt.length/3,mt=ut&&ut.encodeInto?(e,t)=>{if(t.length<vt){const n=ut.encodeInto(t,yt).written||0;gt(e,n);for(let t=0;t<n;t++)pt(e,yt[t])}else bt(e,dt(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;gt(e,r);for(let t=0;t<r;t++)pt(e,n.codePointAt(t))},bt=(e,t)=>{gt(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(it(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)})(e,t)},wt=(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*it(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},_t=(e,t)=>wt(e,8).setBigUint64(0,t,!1),kt=new DataView(new ArrayBuffer(4)),St=(e,t)=>{switch(typeof t){case"string":pt(e,119),mt(e,t);break;case"number":lt(t)&&rt(t)<=2147483647?(pt(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),pt(e,(t>63?st:0)|(n?64:0)|63&t),t=nt(t/64);t>0;)pt(e,(t>ot?st:0)|ot&t),t=nt(t/128)})(e,t)):(n=t,kt.setFloat32(0,n),kt.getFloat32(0)===n?(pt(e,124),((e,t)=>{wt(e,4).setFloat32(0,t,!1)})(e,t)):(pt(e,123),((e,t)=>{wt(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":pt(e,122),((e,t)=>{wt(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)pt(e,126);else if(at(t)){pt(e,117),gt(e,t.length);for(let n=0;n<t.length;n++)St(e,t[n])}else if(t instanceof Uint8Array)pt(e,116),bt(e,t);else{pt(e,118);const n=Object.keys(t);gt(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];mt(e,i),St(e,t[i])}}break;case"boolean":pt(e,t?120:121);break;default:pt(e,127)}var n};function Et(e){const t=new ft;switch(mt(t,e.type),"table"in e&&mt(t,e.table),"prop"in e&&mt(t,e.prop),e.type){case"u-ack":case"u-reject":_t(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":mt(t,e.yServerRev);break;default:switch(St(t,e.k),e.type){case"aware":bt(t,e.u);break;case"doc-open":St(t,e.serverRev),St(t,e.sv);break;case"doc-close":break;case"sv":bt(t,e.sv);break;case"u-c":bt(t,e.u),_t(t,BigInt(e.i));break;case"u-s":bt(t,e.u),mt(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 xt=e=>new Error(e),It=xt("Unexpected end of array"),Ct=xt("Integer out of Range");let At=class{constructor(e){this.arr=e,this.pos=0}};const Ot=e=>e.pos!==e.arr.length,Dt=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Ut(e)),Tt=e=>e.arr[e.pos++],Ut=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<st)return t;if(t>ct)throw Ct}throw It},jt=ht?e=>ht.decode(Dt(e)):e=>{let t=Ut(e);if(0===t)return"";{let n=String.fromCodePoint(Tt(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Tt(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))}},Pt=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Lt=e=>Pt(e,8).getBigUint64(0,!1),Rt=[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&st))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<st)return i*n;if(n>ct)throw Ct}throw It},e=>Pt(e,4).getFloat32(0,!1),e=>Pt(e,8).getFloat64(0,!1),e=>Pt(e,8).getBigInt64(0,!1),e=>!1,e=>!0,jt,e=>{const t=Ut(e),n={};for(let r=0;r<t;r++){n[jt(e)]=Nt(e)}return n},e=>{const t=Ut(e),n=[];for(let r=0;r<t;r++)n.push(Nt(e));return n},Dt],Nt=e=>Rt[127-Tt(e)](e);function $t(e){return u(this,arguments,(function*(){var t,n,r,i;let s=0,o=new Uint8Array(4),c=0,l=[],u=0;try{for(var h,f=!0,p=d(e);!(t=(h=yield a(p.next())).done);f=!0){i=h.value,f=!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:u=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+u>e.byteLength)l.push(e.slice(n)),u-=e.byteLength-n,s=2,n=e.byteLength;else{if(l.length>0){const t=new Uint8Array(l.reduce(((e,t)=>e+t.byteLength),u));let r=0;for(const e of l)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+u),r),l=[],yield yield a(t)}else yield yield a(e.slice(n,n+u));n+=u,s=0}}}}catch(e){n={error:e}}finally{try{f||t||!(r=p.return)||(yield a(r.call(p)))}finally{if(n)throw n.error}}}))}class Mt 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 Bt(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 Ft(e,t,...n){return Bt(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function Wt(e,t,n){return i(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 Bt(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 Vt(e,t,n){return i(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 Bt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return i}))}function Kt(e){return i(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 zt(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 Ht(t,n,r,s,o){return i(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 zt(t,n):yield function(t,n,r,s){return i(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:i,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(!i||!o)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=i;const c=function(e){const t=Me(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:s});if("error"===e.type)throw new Mt(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 Bt(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof Mt)throw yield Ft(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 Ft(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,s,o)}))}function zt(e,t){return i(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=Me(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 Mt(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:Jt}={};const qt={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 Yt(...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 qt;let s=n.get(r);if(void 0!==s)return s;const o=(i=e,Jt.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:qt),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 Gt={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 Qt={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 Xt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Zt={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)}},tn={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const nn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var rn=["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=nn[t];return i&&new i(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function sn(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=ln[e[n]];return t}(Me(e))}function on(e){return $e(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+=cn[e[n]];return t}(e))}const cn={"-":"=",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:"+","|":"/"},ln={};for(const e of Object.keys(cn))ln[cn[e]]=e;var an={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:sn(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 un{constructor(e,t){this.buf=e,this.type=t}}function dn(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 hn(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var fn={Blob:{test:(e,t)=>"Blob"===t||e instanceof un,replace:e=>({$t:"Blob",v:Me(e instanceof un?e.buf:hn(dn(e))),type:e.type}),revive:({type:e,v:t})=>{const n=$e(t);return void 0!==typeof Blob?new Blob([n]):new un(n.buffer,e)}}};const pn={...Qt,...Xt,...Zt,...en,...tn,...rn,...an,...fn};function gn(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 yn={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},vn={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:Me(hn(dn(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const i=$e(t);return new File([i],n,{type:e,lastModified:new Date(r).getTime()})}}};const mn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class bn{toString(){return this.v}constructor(e){this.v=e}}const wn=mn?{}:{bigint:{test:e=>e instanceof bn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new bn(e)}},_n=Object.assign(Object.assign(Object.assign(Object.assign({},yn),wn),vn),{PropModification:{test:t=>t instanceof e.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:t=>{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}(t,["$t"]);return new e.PropModification(n)}}}),kn=Yt(pn,_n),Sn=function(...e){const t=Yt(pn,Gt,...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 gn(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 gn(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)}}}(_n);class En extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function xn(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=In(s,i));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===s&&(a=In(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 In(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 Cn=new WeakMap;function An(e){return i(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=Cn.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 On(e,t,n,r,s,o,c,l,a){return i(this,void 0,void 0,(function*(){const i={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield Kt(s),d=null==u?void 0:u.accessToken;d&&(i.Authorization=`Bearer ${d}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:l,schema:c||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:xn(s.dx.core.schema,a,e),y:t,dxcv:s.cloud.version};s.syncStateChangedEvent.next({phase:"pushing"});const f=kn.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:i,credentials:"include",body:f});if(s.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));Cn.set(e,new Date(Date.now()+1e3*t))}else Cn.delete(e)}}(s,p),!p.ok)throw new En(p);if("application/x-bison"===p.headers.get("content-type"))return Sn.fromBinary(yield p.blob());{const e=yield p.text();return kn.parse(e)}}))}function Dn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Tn=!1;function Un(e,t,n,r){return i(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 jn(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 Pn(t,n,r){return i(this,void 0,void 0,(function*(){const i=yield t.bulkGet(n),s=[],o=[];n.forEach(((n,c)=>{const l=i[c];if(l){for(const[i,s]of Object.entries(r[c]))if(i===t.schema.primKey.keyPath){if(0!==e.cmp(s,n))throw new Error("Cannot change primary key")}else e.setByKeyPath(l,i,s);s.push(n),o.push(l)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(o,s):t.bulkPut(o)}))}function Ln(t,n){return i(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 Pn(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Tn=navigator.onLine,self.addEventListener("online",(()=>Tn=!0)),self.addEventListener("offline",(()=>Tn=!1)));const Rn="dexie-cloud-syncer";function Nn(e,t){return e.where("i").between(t,1/0,!0).toArray()}const $n=()=>new Map,Mn=e=>{const t=$n();return e.forEach(((e,n)=>{t.set(n,e)})),t},Bn=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},Fn=()=>new Set,Wn=e=>e[e.length-1],Vn=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Kn=Array.from,Hn=Array.isArray;class zn{constructor(){this._observers=$n()}on(e,t){return Bn(this._observers,e,Fn).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 Kn((this._observers.get(e)||$n()).values()).forEach((e=>e(...t)))}destroy(){this._observers=$n()}}const Jn=Math.floor,qn=Math.abs,Yn=(e,t)=>e<t?e:t,Gn=(e,t)=>e>t?e:t,Qn=e=>0!==e?e<0:1/e<0,Xn=64,Zn=128,er=127,tr=Number.MAX_SAFE_INTEGER,nr=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&Jn(e)===e),rr=/^\s*/g,ir=/([A-Z])/g,sr=(e,t)=>(e=>e.replace(rr,""))(e.replace(ir,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),or="undefined"!=typeof TextEncoder?new TextEncoder:null,cr=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 lr="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});lr&&1===lr.decode(new Uint8Array).length&&(lr=null);class ar{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const ur=()=>new ar,dr=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},hr=(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},fr=hr,pr=(e,t)=>{for(;t>er;)hr(e,Zn|er&t),t=Jn(t/128);hr(e,er&t)},gr=(e,t)=>{const n=Qn(t);for(n&&(t=-t),hr(e,(t>63?Zn:0)|(n?Xn:0)|63&t),t=Jn(t/64);t>0;)hr(e,(t>er?Zn:0)|er&t),t=Jn(t/128)},yr=new Uint8Array(3e4),vr=yr.length/3,mr=or&&or.encodeInto?(e,t)=>{if(t.length<vr){const n=or.encodeInto(t,yr).written||0;pr(e,n);for(let t=0;t<n;t++)hr(e,yr[t])}else wr(e,cr(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;pr(e,r);for(let t=0;t<r;t++)hr(e,n.codePointAt(t))},br=(e,t)=>{const n=e.cbuf.length,r=e.cpos,i=Yn(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(Gn(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},wr=(e,t)=>{pr(e,t.byteLength),br(e,t)},_r=(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*Gn(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},kr=new DataView(new ArrayBuffer(4)),Sr=(e,t)=>{switch(typeof t){case"string":hr(e,119),mr(e,t);break;case"number":nr(t)&&qn(t)<=2147483647?(hr(e,125),gr(e,t)):(n=t,kr.setFloat32(0,n),kr.getFloat32(0)===n?(hr(e,124),((e,t)=>{_r(e,4).setFloat32(0,t,!1)})(e,t)):(hr(e,123),((e,t)=>{_r(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":hr(e,122),((e,t)=>{_r(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)hr(e,126);else if(Hn(t)){hr(e,117),pr(e,t.length);for(let n=0;n<t.length;n++)Sr(e,t[n])}else if(t instanceof Uint8Array)hr(e,116),wr(e,t);else{hr(e,118);const n=Object.keys(t);pr(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];mr(e,i),Sr(e,t[i])}}break;case"boolean":hr(e,t?120:121);break;default:hr(e,127)}var n};class Er extends ar{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&pr(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const xr=e=>{e.count>0&&(gr(e.encoder,1===e.count?e.s:-e.s),e.count>1&&pr(e.encoder,e.count-2))};class Ir{constructor(){this.encoder=new ar,this.s=0,this.count=0}write(e){this.s===e?this.count++:(xr(this),this.count=1,this.s=e)}toUint8Array(){return xr(this),dr(this.encoder)}}const Cr=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);gr(e.encoder,t),e.count>1&&pr(e.encoder,e.count-2)}};class Ar{constructor(){this.encoder=new ar,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Cr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Cr(this),dr(this.encoder)}}class Or{constructor(){this.sarr=[],this.s="",this.lensE=new Ir}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 ar;return this.sarr.push(this.s),this.s="",mr(e,this.sarr.join("")),br(e,this.lensE.toUint8Array()),dr(e)}}const Dr=e=>new Error(e),Tr=()=>{throw Dr("Method unimplemented")},Ur=()=>{throw Dr("Unexpected case")},jr=Dr("Unexpected end of array"),Pr=Dr("Integer out of Range");class Lr{constructor(e){this.arr=e,this.pos=0}}const Rr=e=>new Lr(e),Nr=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Mr(e)),$r=e=>e.arr[e.pos++],Mr=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&er)*n,n*=128,r<Zn)return t;if(t>tr)throw Pr}throw jr},Br=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(t&Xn)>0?-1:1;if(0==(t&Zn))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&er)*r,r*=128,t<Zn)return i*n;if(n>tr)throw Pr}throw jr},Fr=lr?e=>lr.decode(Nr(e)):e=>{let t=Mr(e);if(0===t)return"";{let n=String.fromCodePoint($r(e));if(--t<100)for(;t--;)n+=String.fromCodePoint($r(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))}},Wr=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Vr=[e=>{},e=>null,Br,e=>Wr(e,4).getFloat32(0,!1),e=>Wr(e,8).getFloat64(0,!1),e=>Wr(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Fr,e=>{const t=Mr(e),n={};for(let r=0;r<t;r++){n[Fr(e)]=Kr(e)}return n},e=>{const t=Mr(e),n=[];for(let r=0;r<t;r++)n.push(Kr(e));return n},Nr],Kr=e=>Vr[127-$r(e)](e);class Hr extends Lr{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=Mr(this)+1:this.count=-1),this.count--,this.s}}class zr extends Lr{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=Br(this);const e=Qn(this.s);this.count=1,e&&(this.s=-this.s,this.count=Mr(this)+2)}return this.count--,this.s}}class Jr extends Lr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=Br(this),t=1&e;this.diff=Jn(e/2),this.count=1,t&&(this.count=Mr(this)+2)}return this.s+=this.diff,this.count--,this.s}}class qr{constructor(e){this.decoder=new zr(e),this.str=Fr(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 Yr=crypto.getRandomValues.bind(crypto),Gr=()=>Yr(new Uint32Array(1))[0],Qr=[1e7]+-1e3+-4e3+-8e3+-1e11,Xr=()=>Qr.replace(/[018]/g,(e=>(e^Gr()&15>>e/4).toString(16))),Zr=e=>new Promise(e);Promise.all.bind(Promise);const ei=e=>void 0===e?null:e;let ti=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},ni=!0;try{"undefined"!=typeof localStorage&&localStorage&&(ti=localStorage,ni=!1)}catch(ya){}const ri=ti,ii=Object.assign,si=Object.keys,oi=e=>si(e).length,ci=(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)),li=Object.freeze,ai=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||ai(e[t])}return li(e)},ui=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&ui(e,t,n+1)}},di="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let hi;const fi=e=>(()=>{if(void 0===hi)if(di){hi=$n();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&hi.set(t,""),t=r):null!==t&&(hi.set(t,r),t=null)}null!==t&&hi.set(t,"")}else"object"==typeof location?(hi=$n(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");hi.set(`--${sr(t,"-")}`,n),hi.set(`-${sr(t,"-")}`,n)}}))):hi=$n();return hi})().has(e),pi=e=>ei(di?process.env[e.toUpperCase().replaceAll("-","_")]:ri.getItem(e)),gi=e=>fi("--"+e)||null!==pi(e);gi("production");var yi;di&&(yi=process.env.FORCE_COLOR,["true","1","2"].includes(yi))||!fi("--no-colors")&&!gi("no-color")&&(!di||process.stdout.isTTY)&&(!di||fi("--color")||null!==pi("COLORTERM")||(pi("TERM")||"").includes("color"));class vi{constructor(e,t){this.left=e,this.right=t}}const mi=(e,t)=>new vi(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const bi=Symbol,wi=bi(),_i=bi(),ki=bi(),Si=bi(),Ei=bi(),xi=bi(),Ii=bi(),Ci=bi(),Ai=bi(),Oi=(mi("font-weight","bold"),mi("font-weight","normal"),mi("color","blue"),mi("color","green"),mi("color","grey"),mi("color","red"),mi("color","purple"),mi("color","orange"),mi("color","black"),Fn()),Di=e=>({[Symbol.iterator](){return this},next:e}),Ti=(e,t)=>Di((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class Ui{constructor(e,t){this.clock=e,this.len=t}}class ji{constructor(){this.clients=new Map}}const Pi=(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])ys(e,i,o.clock,o.len,n)}})),Li=(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=Jn((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)},Ri=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=Gn(r.len,i.clock+i.len-r.clock):(n<t&&(e[n]=i),n++)}e.length=n}))},Ni=(e,t,n,r)=>{Bn(e.clients,t,(()=>[])).push(new Ui(n,r))},$i=(e,t)=>{pr(e.restEncoder,t.clients.size),Kn(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),pr(e.restEncoder,t);const r=n.length;pr(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},Mi=(e,t,n)=>{const r=new ji,i=Mr(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=Mr(e.restDecoder),s=Mr(e.restDecoder),o=n.clients.get(i)||[],c=as(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<c){c<s&&Ni(r,i,c,s-c);let e=ds(o,n),l=o[e];for(!l.deleted&&l.id.clock<n&&(o.splice(e+1,0,Xo(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,Xo(t,l,s-l.id.clock)),l.delete(t))}else Ni(r,i,n,s-n)}}if(r.clients.size>0){const e=new Ji;return pr(e.restEncoder,0),$i(e,r),e.toUint8Array()}return null},Bi=Gr;class Fi extends zn{constructor({guid:e=Xr(),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=Bi(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new cs,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=Zr((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const c=()=>Zr((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||ks(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Kn(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return ks(this,e,t)}get(e,t=Fs){const n=Bn(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==Fs&&r!==t){if(r===Fs){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,so)}getText(e=""){return this.get(e,Eo)}getMap(e=""){return this.get(e,co)}getXmlElement(e=""){return this.get(e,Co)}getXmlFragment(e=""){return this.get(e,Io)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,Kn(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Fi({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,ks(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 Wi{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Mr(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Mr(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Vi extends Wi{constructor(e){super(e),this.keys=[],Mr(e),this.keyClockDecoder=new Jr(Nr(e)),this.clientDecoder=new zr(Nr(e)),this.leftClockDecoder=new Jr(Nr(e)),this.rightClockDecoder=new Jr(Nr(e)),this.infoDecoder=new Hr(Nr(e),$r),this.stringDecoder=new qr(Nr(e)),this.parentInfoDecoder=new Hr(Nr(e),$r),this.typeRefDecoder=new zr(Nr(e)),this.lenDecoder=new zr(Nr(e))}readLeftID(){return new ns(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new ns(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 Kr(this.restDecoder)}readBuf(){return Nr(this.restDecoder)}readJSON(){return Kr(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 Ki{constructor(){this.restEncoder=ur()}toUint8Array(){return dr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){pr(this.restEncoder,e)}writeDsLen(e){pr(this.restEncoder,e)}}class Hi extends Ki{writeLeftID(e){pr(this.restEncoder,e.client),pr(this.restEncoder,e.clock)}writeRightID(e){pr(this.restEncoder,e.client),pr(this.restEncoder,e.clock)}writeClient(e){pr(this.restEncoder,e)}writeInfo(e){fr(this.restEncoder,e)}writeString(e){mr(this.restEncoder,e)}writeParentInfo(e){pr(this.restEncoder,e?1:0)}writeTypeRef(e){pr(this.restEncoder,e)}writeLen(e){pr(this.restEncoder,e)}writeAny(e){Sr(this.restEncoder,e)}writeBuf(e){wr(this.restEncoder,e)}writeJSON(e){mr(this.restEncoder,JSON.stringify(e))}writeKey(e){mr(this.restEncoder,e)}}class zi{constructor(){this.restEncoder=ur(),this.dsCurrVal=0}toUint8Array(){return dr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,pr(this.restEncoder,t)}writeDsLen(e){0===e&&Ur(),pr(this.restEncoder,e-1),this.dsCurrVal+=e}}class Ji extends zi{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Ar,this.clientEncoder=new Ir,this.leftClockEncoder=new Ar,this.rightClockEncoder=new Ar,this.infoEncoder=new Er(fr),this.stringEncoder=new Or,this.parentInfoEncoder=new Er(fr),this.typeRefEncoder=new Ir,this.lenEncoder=new Ir}toUint8Array(){const e=ur();return pr(e,0),wr(e,this.keyClockEncoder.toUint8Array()),wr(e,this.clientEncoder.toUint8Array()),wr(e,this.leftClockEncoder.toUint8Array()),wr(e,this.rightClockEncoder.toUint8Array()),wr(e,dr(this.infoEncoder)),wr(e,this.stringEncoder.toUint8Array()),wr(e,dr(this.parentInfoEncoder)),wr(e,this.typeRefEncoder.toUint8Array()),wr(e,this.lenEncoder.toUint8Array()),br(e,dr(this.restEncoder)),dr(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){Sr(this.restEncoder,e)}writeBuf(e){wr(this.restEncoder,e)}writeJSON(e){Sr(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 qi=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{as(t,n)>e&&r.set(n,e)})),ls(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),pr(e.restEncoder,r.size),Kn(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=Gn(r,t[0].id.clock);const i=ds(t,r);pr(e.restEncoder,t.length-i),e.writeClient(n),pr(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)}))},Yi=(e,t,n,r=new Vi(e))=>ks(t,(e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=$n(),r=Mr(e.restDecoder);for(let i=0;i<r;i++){const r=Mr(e.restDecoder),i=new Array(r),s=e.readClient();let o=Mr(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 Uo(is(s,o),t),o+=t;break}case 10:{const t=Mr(e.restDecoder);i[n]=new nc(is(s,o),t),o+=t;break}default:{const c=0==(192&r),l=new Zo(is(s,o),null,(r&Zn)===Zn?e.readLeftID():null,null,(r&Xn)===Xn?e.readRightID():null,c?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,c&&32==(32&r)?e.readString():null,ec(e,r));i[n]=l,o+=l.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=Kn(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 cs,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!==nc){const i=Bn(d,u.id.client,(()=>as(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,as(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 Ji;return qi(e,c,new Map),pr(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<as(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=Cs([c.update,o.update])}}else i.pendingStructs=o;const l=Mi(r,e,i);if(i.pendingDs){const t=new Vi(Rr(i.pendingDs));Mr(t.restDecoder);const n=Mi(t,e,i);i.pendingDs=l&&n?Cs([l,n]):l||n}else i.pendingDs=l;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,Gi(e.doc,t)}}),n,!1),Gi=(e,t,n,r=Vi)=>{const i=Rr(t);Yi(i,e,n,new r(i))};class Qi{constructor(){this.l=[]}}const Xi=()=>new Qi,Zi=(e,t)=>e.l.push(t),es=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},ts=(e,t,n)=>ui(e.l,[t,n]);class ns{constructor(e,t){this.client=e,this.clock=t}}const rs=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,is=(e,t)=>new ns(e,t),ss=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Li(t.ds,e.id),os=(e,t)=>{const n=Bn(e.meta,os,Fn),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<as(r,n)&&ps(e,is(n,t))})),Pi(e,t.ds,(e=>{})),n.add(t))};class cs{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ls=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},as=(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},us=(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 Ur()}n.push(t)},ds=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=Jn(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=Jn((n+r)/2)}throw Ur()},hs=(e,t)=>{const n=e.clients.get(t.client);return n[ds(n,t.clock)]},fs=(e,t,n)=>{const r=ds(t,n),i=t[r];return i.id.clock<n&&i instanceof Zo?(t.splice(r+1,0,Xo(e,i,n-i.id.clock)),r+1):r},ps=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[fs(e,n,t.clock)]},gs=(e,t,n)=>{const r=t.clients.get(n.client),i=ds(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==Uo&&r.splice(i+1,0,Xo(e,s,n.clock-s.id.clock+1)),s},ys=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,c=fs(e,t,n);do{o=t[c++],s<o.id.clock+o.length&&fs(e,t,s),i(o)}while(c<t.length&&t[c].id.clock<s)};class vs{constructor(e,t,n){this.doc=e,this.deleteSet=new ji,this.beforeState=ls(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 ms=(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)))&&(Ri(t.deleteSet),((e,t)=>{qi(e,t.doc.store,t.beforeState)})(e,t),$i(e,t.deleteSet),!0),bs=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Bn(e.changed,t,Fn).add(n)},ws=(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 Zo&&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},_s=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{Ri(s),n.afterState=ls(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach(((t,r)=>e.push((()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})))),e.push((()=>{n.changedParentTypes.forEach(((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter((e=>null===e.target._item||!e.target._item.deleted))).forEach((e=>{e.currentTarget=t,e._path=null})),e.sort(((e,t)=>e.path.length-t.path.length)),ts(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),ui(e,[]),n._needFormattingCleanup&&_o(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=ds(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 Zo&&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=Yn(r.length-1,1+ds(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+ws(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=Gn(ds(e,r),1);for(let t=e.length-1;t>=n;)t-=1+ws(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=ds(r,n);s+1<r.length&&ws(r,s+1)>1||s>0&&ws(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Oi.forEach((t=>t.print(e)))})(Ci,wi,"[yjs] ",_i,xi,"Changed the client-id because another client seems to be using it."),r.clientID=Bi()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Hi;ms(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Ji;ms(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])):_s(e,t+1)}}},ks=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new vs(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&&_s(i,0)}}return o};class Ss{constructor(e,t){this.gen=function*(e){const t=Mr(e.restDecoder);for(let n=0;n<t;n++){const t=Mr(e.restDecoder),n=e.readClient();let r=Mr(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=Mr(e.restDecoder);yield new nc(is(n,r),t),r+=t}else if(0!=(31&t)){const i=0==(192&t),s=new Zo(is(n,r),null,(t&Zn)===Zn?e.readLeftID():null,null,(t&Xn)===Xn?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&32==(32&t)?e.readString():null,ec(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new Uo(is(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===nc);return this.curr}}class Es{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const xs=(e,t=zi,n=Vi)=>{const r=new t,i=new Ss(new n(Rr(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++,pr(r.restEncoder,t),pr(r.restEncoder,o)),t=s.id.client,o=0,n=0!==s.id.clock),s.constructor===nc&&(n=!0),n||(o=s.id.clock+s.length);0!==o&&(e++,pr(r.restEncoder,t),pr(r.restEncoder,o));const c=ur();return pr(c,e),((e,t)=>{br(e,dr(t))})(c,r.restEncoder),r.restEncoder=c,r.toUint8Array()}return pr(r.restEncoder,0),r.toUint8Array()},Is=(e,t)=>{if(e.constructor===Uo){const{client:n,clock:r}=e.id;return new Uo(is(n,r+t),e.length-t)}if(e.constructor===nc){const{client:n,clock:r}=e.id;return new nc(is(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new Zo(is(r,i+t),null,is(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Cs=(e,t=Vi,n=Ji)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(Rr(e))));let i=r.map((e=>new Ss(e,!0))),s=null;const o=new n,c=new Es(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===nc?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)Os(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===nc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{Os(c,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new nc(is(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===nc?s.struct.length-=t:n=Is(n,t)),s.struct.mergeWith(n)||(Os(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!==nc;n=e.next())Os(c,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(Os(c,s.struct,s.offset),s=null),Ds(c);const l=r.map((e=>(e=>{const t=new ji,n=Mr(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Mr(e.restDecoder),r=Mr(e.restDecoder);if(r>0){const i=Bn(t.clients,n,(()=>[]));for(let t=0;t<r;t++)i.push(new Ui(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new ji;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++)Vn(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}}));return Ri(t),t})(l);return $i(o,a),o.toUint8Array()},As=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:dr(e.encoder.restEncoder)}),e.encoder.restEncoder=ur(),e.written=0)},Os=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&As(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),pr(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ds=e=>{As(e);const t=e.encoder.restEncoder;pr(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];pr(t,r.written),br(t,r.restEncoder)}},Ts="You must not compute changes after the event-handler fired.";class Us{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=js(this.currentTarget,this.target))}deletes(e){return Li(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Dr(Ts);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=Wn(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=Wn(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=Wn(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 Dr(Ts);const t=this.target,n=Fn(),r=Fn(),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 js=(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},Ps=()=>{((...e)=>{e.unshift(Ci),Oi.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let Ls=0;class Rs{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Ls++}}const Ns=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ls++},$s=(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)=>qn(t-e.index)<qn(t-n.index)?e:n));let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=Ls++})(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&&qn(n.index-i)<r.parent.length/80?(Ns(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return Ns(r,t,n),r}{const r=new Rs(t,n);return e.push(r),r}})(e._searchMarker,r,i)},Ms=(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=Gn(t,i.index+n))}},Bs=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;Bn(i,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;ts(r._eH,n,t)};class Fs{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Xi(),this._dEH=Xi(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Tr()}clone(){throw Tr()}_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){Zi(this._eH,e)}observeDeep(e){Zi(this._dEH,e)}unobserve(e){es(this._eH,e)}unobserveDeep(e){es(this._dEH,e)}toJSON(){}}const Ws=(e,t,n)=>{e.doc??Ps(),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},Vs=e=>{e.doc??Ps();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},Ks=(e,t)=>{let n=0,r=e._start;for(e.doc??Ps();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}},Hs=(e,t)=>{const n=[];return Ks(e,((r,i)=>{n.push(t(r,i,e))})),n},zs=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}}}},Js=(e,t)=>{e.doc??Ps();const n=$s(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}},qs=(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 Zo(is(o,as(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Fo(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 Zo(is(o,as(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new jo(new Uint8Array(n))),i.integrate(e,0);break;case Fi:i=new Zo(is(o,as(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Ro(n)),i.integrate(e,0);break;default:if(!(n instanceof Fs))throw new Error("Unexpected content type in insert operation");i=new Zo(is(o,as(c,o)),i,i&&i.lastId,l,l&&l.id,t,null,new Qo(n)),i.integrate(e,0)}}})),u()},Ys=()=>Dr("Length exceeded!"),Gs=(e,t,n,r)=>{if(n>t._length)throw Ys();if(0===n)return t._searchMarker&&Ms(t._searchMarker,n,r.length),qs(e,t,null,r);const i=n,s=$s(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&&ps(e,is(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Ms(t._searchMarker,i,r.length),qs(e,t,o,r)},Qs=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=$s(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&&ps(e,is(c.id.client,c.id.clock+n)),n-=c.length);for(;r>0&&null!==c;)c.deleted||(r<c.length&&ps(e,is(c.id.client,c.id.clock+r)),c.delete(e),r-=c.length),c=c.right;if(r>0)throw Ys();t._searchMarker&&Ms(t._searchMarker,i,-s+r)},Xs=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Zs=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let c;if(null==r)c=new Fo([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:c=new Fo([r]);break;case Uint8Array:c=new jo(r);break;case Fi:c=new Ro(r);break;default:if(!(r instanceof Fs))throw new Error("Unexpected content type");c=new Qo(r)}new Zo(is(o,as(s.store,o)),i,i&&i.lastId,null,null,t,n,c).integrate(e,0)},eo=(e,t)=>{e.doc??Ps();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},to=e=>{const t={};return e.doc??Ps(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},no=(e,t)=>{e.doc??Ps();const n=e._map.get(t);return void 0!==n&&!n.deleted},ro=e=>(e.doc??Ps(),((e,t)=>Di((()=>{let n;do{n=e.next()}while(!n.done&&!t(n.value));return n})))(e._map.entries(),(e=>!e[1].deleted)));class io extends Us{}class so extends Fs{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new so;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new so}clone(){const e=new so;return e.insert(0,this.toArray().map((e=>e instanceof Fs?e.clone():e))),e}get length(){return this.doc??Ps(),this._length}_callObserver(e,t){super._callObserver(e,t),Bs(this,e,new io(this,e))}insert(e,t){null!==this.doc?ks(this.doc,(n=>{Gs(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?ks(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;qs(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?ks(this.doc,(n=>{Qs(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return Js(this,e)}toArray(){return Vs(this)}slice(e=0,t=this.length){return Ws(this,e,t)}toJSON(){return this.map((e=>e instanceof Fs?e.toJSON():e))}map(e){return Hs(this,e)}forEach(e){Ks(this,e)}[Symbol.iterator](){return zs(this)}_write(e){e.writeTypeRef(Ko)}}class oo extends Us{constructor(e,t,n){super(e,t),this.keysChanged=n}}class co extends Fs{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 co}clone(){const e=new co;return this.forEach(((t,n)=>{e.set(n,t instanceof Fs?t.clone():t)})),e}_callObserver(e,t){Bs(this,e,new oo(this,e,t))}toJSON(){this.doc??Ps();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Fs?r.toJSON():r}})),e}get size(){return[...ro(this)].length}keys(){return Ti(ro(this),(e=>e[0]))}values(){return Ti(ro(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return Ti(ro(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??Ps(),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?ks(this.doc,(t=>{Xs(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?ks(this.doc,(n=>{Zs(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return eo(this,e)}has(e){return no(this,e)}clear(){null!==this.doc?ks(this.doc,(e=>{this.forEach((function(t,n,r){Xs(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(Ho)}}const lo=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&ci(e,t);class ao{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Ur(),this.right.content.constructor===$o)this.right.deleted||po(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const uo=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===$o)t.right.deleted||po(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&ps(e,is(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},ho=(e,t,n,r)=>{const i=new Map,s=r?$s(t,n):null;if(s){const t=new ao(s.p.left,s.p,s.index,i);return uo(e,t,n-s.index)}{const r=new ao(null,t._start,0,i);return uo(e,r,n)}},fo=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===$o&&lo(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 Zo(is(s,as(i.store,s)),c,c&&c.lastId,l,l&&l.id,t,null,new $o(o,r));a.integrate(e,0),n.right=a,n.forward()}))},po=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},go=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===$o&&lo(t[e.right.content.key]??null,e.right.content.value));)e.forward()},yo=(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(!lo(a,l)){o.set(c,a);const{left:r,right:u}=n;n.right=new Zo(is(s,as(i.store,s)),r,r&&r.lastId,u,u&&u.id,t,null,new $o(c,l)),n.right.integrate(e,0),n.forward()}}return o},vo=(e,t,n,r,i)=>{n.currentAttributes.forEach(((e,t)=>{void 0===i[t]&&(i[t]=null)}));const s=e.doc,o=s.clientID;go(n,i);const c=yo(e,t,n,i),l=r.constructor===String?new Wo(r):r instanceof Fs?new Qo(r):new No(r);let{left:a,right:u,index:d}=n;t._searchMarker&&Ms(t._searchMarker,n.index,l.getLength()),u=new Zo(is(o,as(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(),fo(e,t,n,c)},mo=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;go(n,i);const c=yo(e,t,n,i);e:for(;null!==n.right&&(r>0||c.size>0&&(n.right.deleted||n.right.content.constructor===$o));){if(!n.right.deleted)switch(n.right.content.constructor){case $o:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(lo(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&&ps(e,is(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 Zo(is(o,as(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Wo(i)),n.right.integrate(e,0),n.forward()}fo(e,t,n,c)},bo=(e,t,n,r,i)=>{let s=t;const o=$n();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===$o){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 $o:{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||po(i,n);break}}}t=t.right}return c},wo=e=>{let t=0;return ks(e.doc,(n=>{let r=e._start,i=e._start,s=$n();const o=Mn(s);for(;i;){if(!1===i.deleted)if(i.content.constructor===$o)po(o,i.content);else t+=bo(n,r,i,s,o),s=Mn(o),r=i;i=i.right}})),t},_o=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&&ys(e,n.store.clients.get(r),s,i,(e=>{e.deleted||e.content.constructor!==$o||e.constructor===Uo||t.add(e.parent)}))}ks(n,(n=>{Pi(e,e.deleteSet,(e=>{if(e instanceof Uo||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===$o?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===$o){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)wo(e)}))},ko=(e,t,n)=>{const r=n,i=Mn(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Qo:case No:case Wo:n<t.right.length&&ps(e,is(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&bo(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Ms(o._searchMarker,t.index,-r+n),t};class So extends Us{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=[];ks(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=ii({},o))),l=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Qo:case No: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 Wo: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 $o:{const{key:t,value:c}=i.content;if(this.adds(i)){if(!this.deletes(i)){const l=n.get(t)??null;lo(l,c)?null!==c&&i.delete(e):("retain"===s&&u(),lo(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;lo(e,c)||("retain"===s&&u(),o[t]=e)}else if(!i.deleted){r.set(t,c);const n=o[t];void 0!==n&&(lo(n,c)?null!==n&&i.delete(e):("retain"===s&&u(),null===c?delete o[t]:o[t]=c))}i.deleted||("insert"===s&&u(),po(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 Eo extends Fs{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Ps(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new Eo}clone(){const e=new Eo;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new So(this,e,t);Bs(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Ps();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Wo&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?ks(this.doc,(n=>{const r=new ao(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)&&vo(n,this,r,o,s.attributes||{})}else void 0!==s.retain?mo(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&ko(n,r,s.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??Ps();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(ss(c,e)||void 0!==t&&ss(c,t))switch(c.content.constructor){case Wo:{const r=i.get("ychange");void 0===e||ss(c,e)?void 0===t||ss(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 Qo:case No:{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 $o:ss(c,e)&&(l(),po(i,c.content))}c=c.right}l()};return e||t?ks(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?ks(r,(r=>{const i=ho(r,this,e,!n);n||(n={},i.currentAttributes.forEach(((e,t)=>{n[t]=e}))),vo(r,this,i,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?ks(r,(r=>{const i=ho(r,this,e,!n);vo(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?ks(n,(n=>{ko(n,ho(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?ks(r,(r=>{const i=ho(r,this,e,!1);null!==i.right&&mo(r,this,i,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?ks(this.doc,(t=>{Xs(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?ks(this.doc,(n=>{Zs(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return eo(this,e)}getAttributes(){return to(this)}_write(e){e.writeTypeRef(zo)}}class xo{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Ps()}[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!==Co&&t.constructor!==Io||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 Io extends Fs{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 Io}clone(){const e=new Io;return e.insert(0,this.toArray().map((e=>e instanceof Fs?e.clone():e))),e}get length(){return this.doc??Ps(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new xo(this,e)}querySelector(e){e=e.toUpperCase();const t=new xo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Kn(new xo(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){Bs(this,e,new Ao(this,t,e))}toString(){return Hs(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),Ks(this,(i=>{r.insertBefore(i.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?ks(this.doc,(n=>{Gs(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)ks(this.doc,(n=>{const r=e&&e instanceof Fs?e._item:e;qs(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 Dr("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?ks(this.doc,(n=>{Qs(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return Vs(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Js(this,e)}slice(e=0,t=this.length){return Ws(this,e,t)}forEach(e){Ks(this,e)}_write(e){e.writeTypeRef(qo)}}class Co extends Io{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 Co(this.nodeName)}clone(){const e=new Co(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 Fs?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?ks(this.doc,(t=>{Xs(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?ks(this.doc,(n=>{Zs(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return eo(this,e)}hasAttribute(e){return no(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&&ss(i,t)&&(n[r]=i.content.getContent()[i.length-1])})),n})(this,e):to(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 Ks(this,(i=>{r.appendChild(i.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Jo),e.writeKey(this.nodeName)}}class Ao extends Us{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 Oo extends co{constructor(e){super(),this.hookName=e}_copy(){return new Oo(this.hookName)}clone(){const e=new Oo(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(Yo),e.writeKey(this.hookName)}}class Do extends Eo{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 Do}clone(){const e=new Do;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(Go)}}class To{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Tr()}mergeWith(e){return!1}write(e,t,n){throw Tr()}integrate(e,t){throw Tr()}}class Uo extends To{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),us(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class jo{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new jo(this.content)}splice(e){throw Tr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class Po{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Po(this.len)}splice(e){const t=new Po(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Ni(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 Lo=(e,t)=>new Fi({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Ro{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 Ro(Lo(this.doc.guid,this.opts))}splice(e){throw Tr()}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 No{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new No(this.embed)}splice(e){throw Tr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class $o{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new $o(this.key,this.value)}splice(e){throw Tr()}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 Mo{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Mo(this.arr)}splice(e){const t=new Mo(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 Bo="development"===pi("node_env");class Fo{constructor(e){this.arr=e,Bo&&ai(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Fo(this.arr)}splice(e){const t=new Fo(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 Wo{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Wo(this.str)}splice(e){const t=new Wo(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 Vo=[e=>new so,e=>new co,e=>new Eo,e=>new Co(e.readKey()),e=>new Io,e=>new Oo(e.readKey()),e=>new Do],Ko=0,Ho=1,zo=2,Jo=3,qo=4,Yo=5,Go=6;class Qo{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Qo(this.type._copy())}splice(e){throw Tr()}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 Xo=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new Zo(is(r,i+n),t,is(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=is(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 Zo extends To{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>=as(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=as(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===ns&&this.id.client!==this.parent.client&&this.parent.clock>=as(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=gs(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ps(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Uo||this.right&&this.right.constructor===Uo)this.parent=null;else if(this.parent){if(this.parent.constructor===ns){const e=hs(t,this.parent);e.constructor===Uo?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===Zo?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===Zo&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=gs(e,e.doc.store,is(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),rs(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(rs(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(hs(e.doc.store,t.origin)))break;r.has(hs(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),us(e.doc.store,this),this.content.integrate(e,this),bs(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Uo(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:is(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&rs(e.origin,this.lastId)&&this.right===e&&rs(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(),Ni(e.deleteSet,this.id.client,this.id.clock,this.length),bs(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Ur();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[ds(r,t.id.clock)]=n})(e,this,new Uo(this.id,this.length)):this.content=new Po(this.length)}write(e,t){const n=t>0?is(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:Zn)|(null===r?0:Xn)|(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 Ur()})(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===ns?(e.writeParentInfo(!1),e.writeLeftID(t)):Ur();null!==i&&e.writeString(i)}this.content.write(e,t)}}const ec=(e,t)=>tc[31&t](e),tc=[()=>{Ur()},e=>new Po(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 Mo(n)},e=>new jo(e.readBuf()),e=>new Wo(e.readString()),e=>new No(e.readJSON()),e=>new $o(e.readKey(),e.readJSON()),e=>new Qo(Vo[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Fo(n)},e=>new Ro(Lo(e.readString(),e.readAny())),()=>{Ur()}];class nc extends To{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Ur()}write(e,t){e.writeInfo(10),pr(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const rc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},ic="__ $YJS$ __";function sc(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}rc[ic],rc[ic]=!0;const oc=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function cc(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=uc(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=uc(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=uc(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 lc=new WeakSet;function ac(e){if(lc.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function uc(e,t,n){return`${e}[${t}].${n}`}let dc=null;function hc(e){dc=e}function fc(){}const pc=new WeakMap;function gc(){return e.Dexie.Events(null,"load","sync","error")}class yc{static getOrCreateDocument(e,t,n,r){var i,s;const o=cc(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 Fi({meta:{db:e,updatesTable:i,parentProp:r,parentTable:n,parentId:s}}),t.add(o),o.on("destroy",(()=>{lc.add(o),t.delete(o)})),o)}(e,o,t,n,c,r)}static load(e,t){var n;let r=pc.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 yc(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,pc.set(e,r)),r}static release(e){if(!e||lc.has(e))return;const t=pc.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(yc.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return pc.get(e)}static get currentUpdateRow(){return dc}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((t,n)=>{this.doc?this.doc.isLoaded?t():this._error?n(this._error):lc.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",t),this.on("error",n),this.doc.on("destroy",(()=>n(new e.Dexie.AbortError("Document was destroyed before loaded"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise(((t,n)=>{this.doc?this.doc.isSynced?t():this._error?n(this._error):lc.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",t),this.on("error",n),this.doc.on("destroy",(()=>n(new e.Dexie.AbortError("Document was destroyed before synced"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(t){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=gc(),this.doc=t,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]=()=>yc.release(t)),t.on("load",(()=>this.on("load").fire())),t.on("sync",(e=>!1!==e&&this.on("sync").fire())),t.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:n,parentTable:r,parentId:i,updatesTable:s}=t.meta||{};if(!n||!r||!s)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(s))throw new Error(`Table ${r} or ${s} not found in db`);ac(t),this.stopObserving=function(t,n,r,i,s,o){let c=0,l=!0;const a=e.liveQuery((()=>{ac(n);const t=r.table(s);return Promise.all([(c>0?t.where("i").between(c,1/0,!1).toArray().then((t=>t.filter((t=>0===e.cmp(t.k,o))))):t.where({k:o}).toArray()).then((e=>e)),r.table(i).where(":id").equals(o).toArray()])})).subscribe((([e,r])=>{e.length>0&&(c=e[e.length-1].i),0!==r.length?(ac(n),e.length>0&&ks(n,(()=>{e.forEach((e=>{try{hc(e),Gi(n,e.u)}finally{hc(null)}}))}),t,!1),l&&(l=!1,n.emit("load",[n]))):n.destroy()}),(e=>{t.on("error").fire(e)})),u=(e,n)=>{n!==t&&r.table(s).add({k:o,u:e,f:1}).then((e=>{e===c-1&&++c})).catch((e=>{t.on("error").fire(e)}))},d=()=>{a.unsubscribe(),n.off("updateV2",u),n.off("destroy",d)};return n.on("updateV2",u),n.on("destroy",d),d}(this,t,n,r,s,i),yc.on("new").fire(this)}destroy(){var e;pc.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=gc(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function vc(t,n){return i(this,void 0,void 0,(function*(){var r;const s={};let o,c=!1;for(const l of t)try{switch(l.type){case"u-s":{const e=sc(n,l.table,l.prop);if(e){const t={k:l.k,u:l.u};l.r&&(t.r=l.r,o=l.r),s[e.name]=yield e.add(t)}break}case"u-ack":{const e=sc(n,l.table,l.prop);e&&(yield n.transaction("rw",e,(t=>i(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(Rn);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:Rn}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,l.i+1)}))})))));break}case"u-reject":{const t=sc(n,l.table,l.prop);if(!t)break;const i=null===(r=yield t.get(l.i))||void 0===r?void 0:r.k;if(null!=i){yield n.transaction("rw",t,(n=>(n.idbtrans._rejecting_y_ypdate=!0,t.where("i").aboveOrEqual(l.i).filter((t=>0===e.cmp(t.k,i)&&1==(1&(t.f||0)))).delete())));const r=yc.getDocCache(n.dx).find(l.table,i,l.prop);r&&r.destroy()}break}case"in-sync":{const e=yc.getDocCache(n.dx).find(l.table,l.k,l.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=l.yServerRev;break;case"outdated-server-rev":c=!0}}catch(e){}return{receivedUntils:s,resyncNeeded:c,yServerRevision:o}}))}yc.on=e.Dexie.Events(null,{new:[function(e,t){return e===fc?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===fc?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)}}]}),yc.getDocCache=cc,e.Dexie.DexieYProvider=yc;const mc=1,bc=2,wc=3;function _c(t,n,r){return i(this,arguments,void 0,(function*(t,n,{yDownloadedRealms:r,realms:s}){if(r&&s&&s.every((e=>"*"===r[e])))return;const o=yield Kt(t),c={"Content-Type":"application/json",Accept:"application/octet-stream"};o&&(c.Authorization=`Bearer ${o.accessToken}`);const l=yield fetch(`${n}/y/download`,{body:kn.stringify({downloadedRealms:r||{}}),method:"POST",headers:c,credentials:"include"});if(!l.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${l.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=d(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 u(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 a(t.read());if(e)return yield a(void 0);yield yield a(n)}}finally{t.releaseLock()}}))}}(l),$t,(function(r){return u(this,arguments,(function*(){var s,o,c,l;let u=null,h=null,f=null,p=[];function g(e){return i(this,void 0,void 0,(function*(){const r=p[p.length-1];if(p.length>0){if(!u||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const e=sc(t,h,f);e&&(yield e.bulkAdd(p)),p=[]}u&&(h&&f&&r||e)&&(yield t.$syncState.update("syncState",(t=>{const n=t.yDownloadedRealms||{};n[u]=e?"*":{tbl:h,prop:f,key:r.k},t.yDownloadedRealms=n})))}))}try{try{for(var y,v=!0,m=d(r);!(s=(y=yield a(m.next())).done);v=!0){l=y.value,v=!1;const e=new At(l);for(;Ot(e);)switch(Tt(e)){case mc:yield a(g(!0)),u=jt(e);break;case bc:yield a(g(!1)),h=jt(e),f=jt(e);break;case wc:{const t=Nt(e),n=Dt(e);p.push({k:t,u:n});break}}yield a(g(!1))}}catch(e){o={error:e}}finally{try{v||s||!(c=m.return)||(yield a(c.call(m)))}finally{if(o)throw o.error}}yield a(g(!0))}catch(t){throw t instanceof e.DexieError||(yield a(g(!1))),t}}))}))}))}const kc="currentSyncWorker";function Sc(e,t,n,r){return Ec(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((s=>i(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(s):Tn&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==s?void 0:s.name)&&/fetch/.test(null==s?void 0:s.message)?(e.syncStateChangedEvent.next({phase:"error",error:s}),yield new Promise((e=>setTimeout(e,500))),yield Sc(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+s}),e.syncStateChangedEvent.next({phase:Tn?"error":"offline",error:new Error(""+(null==s?void 0:s.message)||s)}),Promise.reject(s))}))))}function Ec(e,t,n){return i(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:s,justCheckIfNeeded:o,purpose:c}={isInitialSync:!1}){var l;if(!(null===(l=e.cloud.options)||void 0===l?void 0:l.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,u=yield e.getCurrentUser(),d=u.isLoggedIn?Fe(e):[],f=d.map((t=>e.table(We(t.name)))),p=yield e.getPersistedSyncState(),g=u.isLoggedIn,y=g?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Fe(e).filter((e=>!n.includes(e.name)))}(e,p):[];Dn(s);const v=y.length>0;if(v){if(o)return!0;yield e.transaction("rw",y,(e=>i(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return i(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!==h.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!==h.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==h.userId||(e.owner=t.userId),e.realmId&&e.realmId!==h.userId||(e.realmId=t.userId))})))}))}(y,u,null==p?void 0:p.realms)})))),Dn(s)}const[m,b,w,{yMessages:_,lastUpdateIds:k}]=yield e.transaction("r",e.tables,(()=>i(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>d.some((t=>t.name===e.tableName))));let o=yield ze(f,e);const c=yield function(e,t){return i(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(Rn),c=(null==o?void 0:o.unsentFrom)||1,l=(null==o?void 0:o.receivedUntil)||0,a=Math.min(c,l+1),u=yield Nn(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]:Cs(s);if(r)n.push({type:"u-c",table:i.name,prop:t.prop,k:e,u:c,i:o});else{const r=xs(c);n.push({type:"sv",table:i.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,d);if(Dn(s),v){const e=[...(null==p?void 0:p.realms)||[],...(null==p?void 0:p.inviteRealms)||[]],l=yield function(e,t,n,r){return i(this,void 0,void 0,(function*(){const s=`upload-${Je(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(yield Promise.all(e.map((e=>i(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],c=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>{return r(e),!o.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!o.has(e.realmId||"")&&Xe(t)})),l=yield c.toArray();if(l.length>0){const n={type:"upsert",values:l,keys:l.map(r),userId:t.userId,txid:s};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(y,u,n,e);return Dn(s),o=o.concat(l),[o,t,r,c]}return[o,t,r,c]})))),S=m.some((e=>e.muts.some((e=>e.keys.length>0))))||_.some((e=>"u-c"===e.type));if(o)return S;if("push"===c&&!S)return!1;const E=jn(m,null==b?void 0:b.latestRevisions),x=(null==b?void 0:b.clientIdentity)||Ge(16);Dn(s);const I=yield On(m,_,b,w,e,a,n,x,u),{done:C,newSyncState:A}=yield e.transaction("rw",e.tables,(t=>i(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))I.schema[e]&&(n[e]=I.schema[e]);yield e.$syncState.put(n,"schema");const r=yield ze(f,e,{since:E});for(const t of f){const n=Ve(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(E[n]){const r=E[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()])}jn(r,E),yield Un(e,n,E,I.serverRevision);const s=yield e.getPersistedSyncState();yield function(e,t,n){return i(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=Fe(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,I,s);const o=s||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:x};g&&(o.syncedTables=d.map((e=>e.name)).concat(y.map((e=>e.name)))),o.latestRevisions=E,o.remoteDbId=I.dbId,o.initiallySynced=!0,o.realms=I.realms,o.inviteRealms=I.inviteRealms,o.serverRevision=I.serverRevision,o.yServerRevision=I.serverRevision,o.timestamp=new Date,delete o.error;const c=xc(I.changes,r);if(yield Ln(c,e),I.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield vc(I.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return i(this,void 0,void 0,(function*(){var r,s,o,c,l;const a={};for(const[t,n]of Object.entries(e))null!==(r=a[t])&&void 0!==r||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(s=a[e])&&void 0!==s||(a[e]={}),a[e].receivedUntil=n;const u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=a[e],r=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,s=null!==(l=null!==(c=null==t?void 0:t.receivedUntil)&&void 0!==c?c:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==l?l:0;yield n.transaction("rw",e,(()=>i(this,void 0,void 0,(function*(){const t=yield n.table(e).get(Rn);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(s,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:Rn,unsentFrom:r,receivedUntil:s})}))))}}))}(k,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}))));if(!C)return yield An(e),yield Ec(e,t,n,{isInitialSync:r,cancelToken:s});const O=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),D=!!I.yMessages;if(O&&D)try{yield _c(e,a,A)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function xc(e,t){const n={};tt(n,e);const r={};return tt(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))Ye(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=Ge(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 Ic=10,Cc=1e4,Ac=1e3;function Oc(n){const r=[],s=new t.BehaviorSubject(!0),o=new t.BehaviorSubject(null);let c=!1,l=new Array(Ic).fill(0);return o.subscribe((()=>i(this,void 0,void 0,(function*(){if(!c&&r.length>0){c=!0,l.shift(),l.push(Date.now()),s.next(!1);try{yield function(){return i(this,void 0,void 0,(function*(){for(var s,o,c,l,a,u;r.length>0;){const d=r.shift();try{yield t.firstValueFrom(n.cloud.syncState.pipe(Ae((({phase:e})=>"in-sync"===e||"error"===e))));const r=n.cloud.persistedSyncState.value;if(!d)continue;switch(d.type){case"token-expired":const t=n.cloud.currentUser.value,h=yield zt(n.cloud.options.databaseUrl,t);yield n.table("$logins").update(t.userId,{accessToken:h.accessToken,accessTokenExpiration:h.accessTokenExpiration,claims:h.claims,license:h.license,data:h.data});break;case"realm-added":(null===(s=null==r?void 0:r.realms)||void 0===s?void 0:s.includes(d.realm))||(null===(o=null==r?void 0:r.inviteRealms)||void 0===o?void 0:o.includes(d.realm))||(yield n.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==r?void 0:r.realms)||void 0===c?void 0:c.includes(d.realm))||(yield n.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(l=null==r?void 0:r.realms)||void 0===l?void 0:l.includes(d.realm))||(null===(a=null==r?void 0:r.inviteRealms)||void 0===a?void 0:a.includes(d.realm)))&&(yield n.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield n.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(u=n.cloud.syncState.value)||void 0===u?void 0:u.phase)){Le(n,"pull");break}yield n.transaction("rw",n.dx.tables,(t=>i(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[r,i,s]=yield Promise.all([n.getSchema(),n.getPersistedSyncState(),n.getCurrentUser()]);if(!i||!r||!s)return;if(d.baseRev!==i.serverRevision)return void("string"!=typeof d.baseRev||"bigint"!=typeof i.serverRevision&&"object"!=typeof i.serverRevision||Le(n,"pull"));if((yield e.waitFor(Be(i)))!==d.realmSetHash)return void Le(n,"pull");let o=[];if(s.isLoggedIn){const e=Fe(n).map((e=>n.table(We(e.name))));o=yield ze(e,n)}if(d.changes.length>0){const e=xc(d.changes,o);yield Ln(e,n)}i.latestRevisions=jn(o,i.latestRevisions),i.serverRevision=d.newRev,yield Un(n,r,i.latestRevisions,d.newRev),yield n.$syncState.put(i,"syncState")}))))}}catch(e){}}}))}()}finally{l[l.length-1]-l[0]<Cc&&(yield new Promise((e=>setTimeout(e,Ac)))),c=!1,s.next(!0)}}})))),{enqueue:function(e){r.push(e),o.next(null)},readyToServe:s}}const Dc=new WeakMap,Tc={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Uc=0;function jc(e){"vip"in e&&(e=e.vip);let n=Dc.get(e.cloud);if(!n){const r=new t.Subject;let i=new v(`syncstatechanged-${e.name}`),s=new v(`synccomplete-${e.name}`);r.id=++Uc;let o=!1;n={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 o},localSyncEvent:r,get syncStateChangedEvent(){return i},get syncCompleteEvent(){return s},dx:e};const c={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||h)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema").then((e=>{if(e)for(const r of n.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(t=r.schema.primKey.keyPath)?t:t?"["+[].join.call(t,"+")+"]":"");var t;return e})),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){i=new v(`syncstatechanged-${e.name}`),s=new v(`synccomplete-${e.name}`)}};Object.assign(n,c),n.messageConsumer=Oc(n),n.messageProducer=new t.Subject,Dc.set(e.cloud,n)}return n}const Pc=new WeakMap;class Lc{constructor(e,t){Pc.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new Lc(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return i(this,void 0,void 0,(function*(){Pc.get(this).table("$logins").put(this)}))}}function Rc(e,n){return t.firstValueFrom(t.from(e).pipe(t.filter(n)))}function Nc(e){return i(this,void 0,void 0,(function*(){const t=yield $c(e);if(t){if(!(yield function(e,t,n){return i(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 Bt(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 $c(e,{deleteUnsyncedData:!0})}}))}function $c(e){return i(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>i(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 Rc(e.cloud.currentUser,(e=>e.userId===h.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function Mc(e,...t){globalThis.console[e](...t)}function Bc(e,t){return i(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),s=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 Kt(e),!1}const o=new Lc(e,{claims:{},lastLogin:new Date(0)});return yield Ht(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return i(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 Wt(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 Wt(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 Ft(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new En(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 Vt(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 Vt(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 En(i,e)}return yield i.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),s!==h.userId&&o.userId!==s&&(yield Nc(e)),yield function(e,t){return i(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>i(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&&(Mc("debug","Login context property names:",Object.keys(t)),Mc("debug","Login context property names:",Object.keys(t)),Mc("debug","Login context:",t),Mc("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield Rc(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,o),Le(e,"pull"),o.userId!==s}))}const Fc="undefined"!=typeof InstallTrigger,Wc="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Vc=Wc?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Kc=Wc&&Vc<=605||Fc,Hc="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:zc}={};function Jc(e){return zc.call(e).slice(8,-1)}function qc(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 Yc=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Gc=0;function Qc(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),i=Date.now();Gc>=i?++Gc:Gc=i,r[0]=Gc/1099511627776,r[1]=Gc/4294967296,r[2]=Gc/16777216,r[3]=Gc/65536,r[4]=Gc/256,r[5]=Gc;const s=new Uint8Array(n.buffer,6);crypto.getRandomValues(s);return e+sn(new Uint8Array(n.buffer))+(t||"")}function Xc(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=qc(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=qc(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]=Qc(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){qc(i.schema.primaryKey,n).forEach(((t,n)=>{if(!Xe(t)){const n=Array.isArray(t)?t.map(Jc).join(","):Jc(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 Zc=0;function el(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 tl(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 nl=new t.BehaviorSubject(new Set);function rl(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 il({currentUserObservable:t,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const i=new Set(r.schema.tables.map((e=>e.name))),s=r.schema.tables.filter((e=>!/^\$/.test(e.name))),o=new Map;for(const e of s){const t=`$${e.name}_mutations`;i.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(e,i)=>{let s;if("readwrite"===i){const t=e.filter((e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync})).map((e=>We(e)));s=r.transaction([...e,...t],i)}else s=r.transaction(e,i);if("readwrite"===i){s.txid=Je(16),s.opCount=0,s.currentUser=t.value,nl.value.add(s),nl.next(nl.value);const e=()=>{s.removeEventListener("complete",r),s.removeEventListener("error",e),s.removeEventListener("abort",e),nl.value.delete(s),nl.next(nl.value)},r=()=>{s.mutationsAdded&&!rl(n)&&Le(n,"push"),e()};s.addEventListener("complete",r),s.addEventListener("error",e),s.addEventListener("abort",e)}return s},table:t=>{const i=r.table(t);if(/^\$/.test(t))return t.endsWith("_mutations")?Object.assign(Object.assign({},i),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),i.mutate(e))}):"$logins"===t?Object.assign(Object.assign({},i),{mutate:e=>i.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):i;const{schema:s}=i,c=o.get(t);return c?function(e){const t="$lock"+ ++Zc;return Object.assign(Object.assign({},e),{count:el(e.count,t),get:el(e.get,t),getMany:el(e.getMany,t),openCursor:el(e.openCursor,t),query:el(e.query,t),mutate:tl(e.mutate,t)})}(Object.assign(Object.assign({},i),{mutate:e=>{var r,o,c;const a=e.trans;return a.txid?a.disableChangeTracking?i.mutate(e):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(c=a.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===e.type?i.query({query:{range:e.range,index:s.primaryKey},trans:e.trans,values:!1}).then((t=>l({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):l(e):i.mutate(e):i.mutate(e)}})):i;function l(r){var o,l;const a=r.trans,u=null===(l=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===l?void 0:l[t],{txid:d,currentUser:{userId:h}}=a,{type:f}=r,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 i.mutate(r).then((t=>{var n;const{numFailures:i,failures:o}=t;let l="delete"===f?r.keys:t.results,y="values"in r?r.values:[],v="changeSpec"in r?r.changeSpec:void 0,m="updates"in r?r.updates:void 0;if(i&&(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 t;if(m){let t=m.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new e.RangeSet;let i=!1;for(let e=0,s=t.length;e<s;++e)Object.keys(t[e]).length>0?(n.keys.push(m.keys[e]),n.changeSpecs.push(t[e]),r.addKey(m.keys[e])):i=!0;if(m=n,i){let e=[],t=[];for(let n=0,i=l.length;n<i;++n)r.hasKey(l[n])&&(e.push(l[n]),t.push(y[n]));l=e,y=t}}}const b=Date.now();let w="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===s.primaryKey.keyPath?null:r.criteria.index}):void 0;if(u&&(null==w?void 0:w.index)){const e=null===(n=s.indexes.find((e=>e.name===w.index)))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(w=void 0)}const _="delete"===r.type?{type:"delete",ts:b,opNo:p,keys:l,criteria:w,txid:d,userId:h}:"add"===r.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 r&&r.isAdditionalChunk&&(_.isAdditionalChunk=!0),l.length>0||w?c.mutate({type:"add",trans:a,values:[_]}).then((()=>(a.mutationsAdded=!0,t))):t}))}}})}}}function sl(e,t){return function(n,r){var i;const s=Object.assign(Object.assign({},Tc),n);Object.keys(Tc).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=Tc[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(Tc[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)(Yc.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 cl=new t.BehaviorSubject(!0),ll=new t.BehaviorSubject(!0);cl.pipe(Te((e=>e?t.of(!0):t.of(!1).pipe(xe(2e4)))),Ie()).subscribe(ll);const al="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),ul=al.pipe(Ae((()=>"hidden"===document.visibilityState))),dl=al.pipe(Ae((()=>"visible"===document.visibilityState))),hl="undefined"!=typeof window?t.merge(dl,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),ul,hl).pipe(ve((()=>"visible"===document.visibilityState)),Ue((e=>{cl.value!==e&&cl.next(e)})),Te((e=>e?t.of(0).pipe(xe(16e4),Ue((()=>cl.next(!1)))):t.of(0)))).subscribe((()=>{}));class fl extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function pl(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 gl=new WeakMap,yl=new WeakMap;function vl(e){let n=yl.get(e);return n||(n=new t.Subject,yl.set(e,n)),n}class ml extends t.Observable{constructor(e,t,n,r,i,s,o,c){super((l=>new wl(e,t,n,r,i,c,l,s,o)))}}let bl=0;class wl extends t.Subscription{constructor(e,t,n,r,i,s,o,c,l){super((()=>this.teardown())),this.id=++bl,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 i(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 n=this.user.accessTokenExpiration;if(n&&n<new Date)return void this.subscriber.error(new fl);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>i(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 r=new URL(this.databaseUrl);r.protocol="http:"===r.protocol?"ws":"wss";const s=new URLSearchParams;if(this.subscriber.closed)return;s.set("v","2"),this.rev&&s.set("rev",this.rev),this.yrev&&s.set("yrev",this.yrev),s.set("realmsHash",this.realmSetHash),s.set("clientId",this.clientIdentity),s.set("dxcv",this.db.cloud.version),this.user.accessToken&&s.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${r}/changes?${s}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?kn.parse(e.data):function(e){const t=new At(e),n=jt(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:jt(t)};const r=jt(t),i=jt(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:i,i:Number(Lt(t))};default:{const e=Nt(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:Dt(t)};case"doc-open":return{type:n,table:r,prop:i,k:e,serverRev:Nt(t),sv:Nt(t)};case"sv":return{type:n,table:r,prop:i,k:e,sv:Dt(t)};case"u-c":return{type:n,table:r,prop:i,k:e,u:Dt(t),i:Number(Lt(t))};case"u-s":return{type:n,table:r,prop:i,k:e,u:Dt(t),r:t.pos<t.arr.length&&jt(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=yc.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>gl.get(e))(e);if(n){pl(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=yc.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&vl(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?vc([t],this.db).then((e=>i(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=sc(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(Rn,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let n=!1;yield new Promise(((e,t)=>{o.onopen=t=>{n=!0,e(null)},o.onerror=e=>{if(n)this.reconnect();else{const n=e.error||new Error("WebSocket Error");this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}}})),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(kn.stringify(e))):null===(n=this.ws)||void 0===n||n.send(Et(e)))}))),this.user.isLoggedIn&&!rl(this.db)&&this.subscriptions.add(function(n){const r=He(n.tables.filter((e=>{var t,r;return(null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e.name])||void 0===r?void 0:r.markedForSync)&&e.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return t.merge(...r.map((({table:r,ydocProp:s,updatesTable:o})=>{const c=n.table(o);return t.from(c.get(Rn)).pipe(t.switchMap((n=>{let o=(null==n?void 0:n.unsentFrom)||1;return t.from(e.liveQuery((()=>i(this,void 0,void 0,(function*(){return(yield Nn(c,o)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:r,prop:s,k:e.k,u:e.u,i:e.i})))}))))).pipe(t.tap((e=>{e.length>0&&(o=e.at(-1).i+1)})))})))}))).pipe(t.mergeMap((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class _l extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function kl(e){return i(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield t.firstValueFrom(hl)}))}function Sl(e){return i(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 Sc(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const El=new WeakMap;function xl(e,t,n,r){const s=El.get(e);if(s){if(s.pull||"push"===(null==r?void 0:r.purpose))return s.promise;{let i=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(i=!0)}));return s.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!i)return xl(e,t,n,r)}))}}const o=function(){return i(this,void 0,void 0,(function*(){try{yield An(e),yield ol(e,kc,(()=>Sc(e,t,n,r))),El.delete(e)}catch(t){throw El.delete(e),t}}))}();return El.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}const Il=1e3;function Cl(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(),xl(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]*Il;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 Al(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Ol,Dl,Tl,Ul,jl,Pl={},Ll=[],Rl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Nl(e,t){for(var n in t)e[n]=t[n];return e}function $l(e){var t=e.parentNode;t&&t.removeChild(e)}function Ml(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?Ol.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 Bl(e,o,r,i,null)}function Bl(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?++Tl:i};return null==i&&null!=Dl.vnode&&Dl.vnode(s),s}function Fl(e){return e.children}function Wl(e,t){this.props=e,this.context=t}function Vl(e,t){if(null==t)return e.__?Vl(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?Vl(e):null}function Kl(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 Kl(e)}}function Hl(e){(!e.__d&&(e.__d=!0)&&Ul.push(e)&&!zl.__r++||jl!==Dl.debounceRendering)&&((jl=Dl.debounceRendering)||setTimeout)(zl)}function zl(){for(var e;zl.__r=Ul.length;)e=Ul.sort((function(e,t){return e.__v.__b-t.__v.__b})),Ul=[],e.some((function(e){var t,n,r,i,s,o;e.__d&&(s=(i=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=Nl({},i)).__v=i.__v+1,ea(o,i,r,t.__n,void 0!==o.ownerSVGElement,null!=i.__h?[s]:null,n,null==s?Vl(i):s,i.__h),ta(n,i),i.__e!=s&&Kl(i)))}))}function Jl(e,t,n,r,i,s,o,c,l,a){var u,d,h,f,p,g,y,v=r&&r.__k||Ll,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?Bl(null,f,null,null,f):Array.isArray(f)?Bl(Fl,{children:f},null,null,null):f.__b>0?Bl(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}ea(e,f,h=h||Pl,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=ql(f,l,e):l=Yl(e,f,h,v,p,l),"function"==typeof n.type&&(n.__d=l)):l&&h.__e==l&&l.parentNode!=e&&(l=Vl(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=Vl(r,u+1)),ia(v[u],v[u]));if(y)for(u=0;u<y.length;u++)ra(y[u],y[++u],y[++u])}function ql(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?ql(r,t,n):Yl(n,r,r,i,r.__e,t));return t}function Yl(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 Gl(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Rl.test(t)?n:n+"px"}function Ql(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||Gl(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Gl(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?Zl:Xl,s):e.removeEventListener(t,s?Zl:Xl,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 Xl(e){this.l[e.type+!1](Dl.event?Dl.event(e):e)}function Zl(e){this.l[e.type+!0](Dl.event?Dl.event(e):e)}function ea(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=Dl.__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 Wl(y,m),u.constructor=k,u.render=sa),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=Nl({},u.__s)),Nl(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=Dl.__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=Nl(Nl({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===Fl&&null==a.key?a.props.children:a,Jl(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=na(n.__e,t,n,r,i,s,o,l);(a=Dl.diffed)&&a(t)}catch(e){t.__v=null,(l||null!=s)&&(t.__e=c,t.__h=!!l,s[s.indexOf(c)]=null),Dl.__e(e,t,n)}}function ta(e,t){Dl.__c&&Dl.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Dl.__e(e,t.__v)}}))}function na(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&&Ol.call(e.childNodes),a=(d=n.props||Pl).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||Ql(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]||Ql(e,s,t[s],n[s],r)}(e,h,d,i,c),u)t.__k=[];else if(p=t.props.children,Jl(e,Array.isArray(p)?p:[p],t,n,r,i&&"foreignObject"!==f,s,o,s?s[0]:n.__k&&Vl(n,0),c),null!=s)for(p=s.length;p--;)null!=s[p]&&$l(s[p]);c||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&Ql(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&Ql(e,"checked",p,d.checked,!1))}return e}function ra(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Dl.__e(e,n)}}function ia(e,t,n){var r,i;if(Dl.unmount&&Dl.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||ra(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Dl.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&ia(r[i],t,"function"!=typeof e.type);n||null==e.__e||$l(e.__e),e.__e=e.__d=void 0}function sa(e,t,n){return this.constructor(e,n)}function oa(e,t,n){var r,i,s;Dl.__&&Dl.__(e,t),i=(r="function"==typeof n)?null:n&&n.__k||t.__k,s=[],ea(t,e=(!r&&n||t).__k=Ml(Fl,null,[e]),i||Pl,Pl,void 0!==t.ownerSVGElement,!r&&n?[n]:i?null:t.firstChild?Ol.call(t.childNodes):null,s,!r&&n?n:i?i.__e:t.firstChild,r),ta(s,e)}Ol=Ll.slice,Dl={__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}},Tl=0,Wl.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Nl({},this.state),"function"==typeof e&&(e=e(Nl({},n),this.props)),e&&Nl(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Hl(this))},Wl.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Hl(this))},Wl.prototype.render=Fl,Ul=[],zl.__r=0;const ca={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 la({children:e,className:t}){return Ml("div",{className:t},Ml("div",{style:ca.Darken}),Ml("div",{style:ca.DialogOuter},Ml("div",{style:ca.DialogInner},e)))}var aa,ua,da,ha,fa=0,pa=[],ga=[],ya=Dl.__b,va=Dl.__r,ma=Dl.diffed,ba=Dl.__c,wa=Dl.unmount;function _a(e,t){Dl.__h&&Dl.__h(ua,e,fa||t),fa=0;var n=ua.__H||(ua.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:ga}),n.__[e]}function ka(e){return fa=1,function(e,t,n){var r=_a(aa++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):Oa(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=ua,!ua.u)){ua.u=!0;var i=ua.shouldComponentUpdate;ua.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.__}(Oa,e)}function Sa(e){return fa=5,function(e,t){var n=_a(aa++,7);return Aa(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function Ea(){for(var e;e=pa.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ia),e.__H.__h.forEach(Ca),e.__H.__h=[]}catch(t){e.__H.__h=[],Dl.__e(t,e.__v)}}Dl.__b=function(e){ua=null,ya&&ya(e)},Dl.__r=function(e){va&&va(e),aa=0;var t=(ua=e.__c).__H;t&&(da===ua?(t.__h=[],ua.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=ga,e.__N=e.i=void 0}))):(t.__h.forEach(Ia),t.__h.forEach(Ca),t.__h=[])),da=ua},Dl.diffed=function(e){ma&&ma(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==pa.push(t)&&ha===Dl.requestAnimationFrame||((ha=Dl.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),xa&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);xa&&(t=requestAnimationFrame(n))})(Ea)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==ga&&(e.__=e.__V),e.i=void 0,e.__V=ga}))),da=ua=null},Dl.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Ia),e.__h=e.__h.filter((function(e){return!e.__||Ca(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Dl.__e(n,e.__v)}})),ba&&ba(e,t)},Dl.unmount=function(e){wa&&wa(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{Ia(e)}catch(e){t=e}})),t&&Dl.__e(t,n.__v))};var xa="function"==typeof requestAnimationFrame;function Ia(e){var t=ua,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),ua=t}function Ca(e){var t=ua;e.__c=e.__(),ua=t}function Aa(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Oa(e,t){return"function"==typeof t?t(e):t}function Da({title:e,type:t,alerts:n,fields:r,submitLabel:i,cancelLabel:s,onCancel:o,onSubmit:c}){const[l,a]=ka({}),u=Sa(null);return function(e,t){var n=_a(aa++,4);!Dl.__s&&Aa(n.__H,t)&&(n.__=e,n.i=t,ua.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Ml(la,{className:"dxc-login-dlg"},Ml(Fl,null,Ml("h3",{style:ca.WindowHeader},e),n.map((e=>Ml("p",{style:ca.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(e)))),Ml("form",{onSubmit:e=>{e.preventDefault(),c(l)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],i)=>Ml("label",{style:ca.Label,key:i},n?`${n}: `:"",Ml("input",{ref:0===i?u:void 0,type:t,name:e,autoComplete:"on",style:ca.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)}})))))),Ml("div",{style:ca.ButtonsDiv},Ml(Fl,null,Ml("button",{type:"submit",style:ca.Button,onClick:()=>c(l)},i),s&&Ml("button",{style:ca.Button,onClick:o},s))))}class Ta extends Wl{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?Ml(Da,Object.assign({},t)):null}}function Ua(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const ja=Ua((e=>new t.BehaviorSubject(h)));function Pa(e,n){let r=n,i=t.from(e).pipe(t.map((e=>r=e)),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const s=new t.Observable((e=>{let t=!1;const n=i.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return s.getValue=()=>r,s}const La=Ua((t=>Pa(e.liveQuery((()=>t.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})))),{}))),Ra=Ua((t=>Pa(ja(t._novip).pipe(Te((n=>e.liveQuery((()=>t.transaction("r","realms","members",(()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}})));function Na(...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 $a=Ua((e=>function(e,n){let r;const i=e.pipe(t.map((e=>r=n(e))));return i.getValue=()=>void 0!==r?r:r=n(e.getValue()),i}(Pa(t.combineLatest([Ra(e._novip),La(e._novip)]).pipe(ve((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:h.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=He(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:"*"}:Na(...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 Ma{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 Ba=Ua((n=>{const r=ja(n._novip).pipe(Te((t=>e.liveQuery((()=>n.members.where({email:t.email||""}).toArray()))))),s=$a(n._novip),o=Ra(n._novip);return Pa(t.combineLatest([r,o,s]).pipe(ve((([e,t,r])=>{const s=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),o=e.reduce(s,{}),c=t.selfMembers.reduce(s,o);return Object.values(c).filter((e=>!e.accepted)).map((e=>Object.assign(Object.assign({},e),{accept(){return i(this,void 0,void 0,(function*(){yield n.members.update(e.id,{accepted:new Date})}))},reject(){return i(this,void 0,void 0,(function*(){yield n.members.update(e.id,{rejected:new Date})}))}})))}))),[])}));function Fa(n){return r=>{var s;const o=r.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:c}=o.meta||{};if(!(null===(s=n.cloud.schema)||void 0===s?void 0:s[c].markedForSync))return;let l;Object.defineProperty(r,"awareness",{get:()=>l||(l=function(n,r,s){const{parentTable:o,parentId:c,parentProp:l,updatesTable:a}=r.meta,u=pl(n),d=new u.Awareness(r),h=vl(r);return d.on("update",(({added:e,updated:t,removed:i},c)=>{const a=e.concat(t).concat(i),h=n.cloud.currentUser.value;if("server"!==c&&h.isLoggedIn&&!rl(n)){const e=u.encodeAwarenessUpdate(d,a);n.messageProducer.next({type:"aware",table:o,prop:l,k:r.meta.parentId,u:e}),s.destroyed&&n.messageProducer.next({type:"doc-close",table:o,prop:l,k:r.meta.parentId})}})),d.on("destroy",(()=>{u.removeAwarenessStates(d,[r.clientID],"provider destroyed")})),(()=>{i(this,void 0,void 0,(function*(){if(s.destroyed)return;let r=!1,u=1;const d=t.combineLatest([n.cloud.webSocketStatus,h.pipe(t.startWith(null))]).subscribe((([e])=>{if(s.destroyed)return;r="connected"===e;const t=n.cloud.currentUser.value;"connected"===e&&t.isLoggedIn&&!rl(n)&&(++u,f().catch((e=>{})))}));function f(){return i(this,void 0,void 0,(function*(){const t=u,d=n.table(a),h=n.$syncState,[f,p]=yield n.transaction("r",h,d,(()=>i(this,void 0,void 0,(function*(){const e=yield d.get(Rn),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(s.destroyed||u!==t||!r)return;const g={type:"doc-open",table:o,prop:l,k:c,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter((t=>0===e.cmp(t.k,c)&&0==(1&(t.f||0)))).toArray();if(!s.destroyed&&u===t&&r){if(y.length>0){const e=Cs(y.map((e=>e.u))),t=xs(e);g.sv=t}n.messageProducer.next(g)}}))}s.addCleanupHandler(d)}))})(),d}(n,o,r),gl.set(o,l),l)})}}const Wa={nameSuffix:!0};function Va(n){const r=n.name,s=ja(n),o=[];let c=!1,l=null;n.on("ready",(n=>i(this,void 0,void 0,(function*(){try{yield function(n){return i(this,void 0,void 0,(function*(){var r,h,f,p,g,y,v;a=!1;const m=jc(n);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(r=m.cloud.options)||void 0===r?void 0:r.customLoginGui)||o.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),oa(Ml(Ta,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),oa(Ml(Ta,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(n))),m.cloud.isServiceWorkerDB||o.push(function(e){let n=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(Te((e=>{const r=n;n=e;const i=t.of(e);switch(e){case"disconnected":return cl.value?i.pipe(we(500)):i;case"connecting":return"not-started"===r||"error"===r?i:i.pipe(we(4e3));default:return i}})));return t.combineLatest([r,e.syncStateChangedEvent.pipe(De({phase:"initial"})),ja(e.dx._novip),ll]).pipe(ve((([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:Tn?a:"offline",license:"ok"}})))}(m).subscribe(n.cloud.syncState)),o.push(m.syncCompleteEvent.subscribe(d)),m.tables.every((e=>e.core))||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const b="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[w,_]=yield m.transaction("rw",m.$syncState,(()=>i(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=m.cloud,[i,s,o]=yield Promise.all([m.getOptions(),m.getSchema(),m.getPersistedSyncState()]);if(c){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 m.$syncState.put(e,"options")}}else m.cloud.options=i||null;if((null===(e=m.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&b.length>0&&!Kc?m.cloud.usingServiceWorker=!0:((null===(t=m.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&m.cloud.isServiceWorkerDB,m.cloud.usingServiceWorker=!1),Al(r,m.cloud.options),Al(s,m.cloud.options),r){if(!s||JSON.stringify(s)!==JSON.stringify(r)){const e=s||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield m.$syncState.put(e,"schema"),Object.assign(r,e)}}else m.cloud.schema=s||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(w&&m.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`)}}(m),u(),!m.cloud.isServiceWorkerDB){o.push(e.liveQuery((()=>m.getCurrentUser())).subscribe(s)),o.push(e.liveQuery((()=>m.getPersistedSyncState())).subscribe(m.cloud.persistedSyncState)),yield t.firstValueFrom(t.combineLatest([s.pipe(Oe(1),Se(1)),m.cloud.persistedSyncState.pipe(Oe(1),Se(1))]));const n=Fa(m);yc.on.new.subscribe(n),m.dx.once("close",(()=>{yc.on.new.unsubscribe(n)}))}let k=!1;const S=yield m.getCurrentUser(),E=null===(h=m.cloud.options)||void 0===h?void 0:h.requireAuth;E&&(m.cloud.isServiceWorkerDB?yield t.firstValueFrom(s.pipe(Ae((e=>!!e.isLoggedIn)),Se(1))):"object"==typeof E?(!S.isLoggedIn||E.userId&&S.userId!==E.userId||E.email&&S.email!==E.email)&&(k=yield Bc(m,E)):S.isLoggedIn||(k=yield Bc(m))),!S.isLoggedIn||_&&_.includes(S.userId)||(k=!0),l&&l.stop(),l=null,u();const x=(null===(f=m.cloud.options)||void 0===f?void 0:f.databaseUrl)&&(!w||k);x&&(yield function(e,t,n){return i(this,void 0,void 0,(function*(){yield ol(e,kc,(()=>Sc(e,t,n,{isInitialSync:!0})))}))}(m,m.cloud.options,m.cloud.schema),m.setInitiallySynced(!0)),u(),m.cloud.usingServiceWorker&&(null===(p=m.cloud.options)||void 0===p?void 0:p.databaseUrl)?(x||Pe(m,"push").catch((()=>{})),function(e){return i(this,void 0,void 0,(function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}}))}(m).catch((()=>{}))):(null===(g=m.cloud.options)||void 0===g?void 0:g.databaseUrl)&&m.cloud.schema&&!m.cloud.isServiceWorkerDB&&(l=Cl(m,m.cloud.options,m.cloud.schema),l.start(),x||Le(m,"push")),u(),m.cloud.isServiceWorkerDB||o.push(t.fromEvent(self,"online").subscribe((()=>{m.syncStateChangedEvent.next({phase:"not-in-sync"}),rl(m)||Le(m,"push")})),t.fromEvent(self,"offline").subscribe((()=>{m.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(y=m.cloud.options)||void 0===y?void 0:y.databaseUrl)||(null===(v=m.cloud.options)||void 0===v?void 0:v.disableWebSocket)||Hc||o.push(function(e){var n;if(!(null===(n=e.cloud.options)||void 0===n?void 0:n.databaseUrl))throw new Error("No database URL to connect WebSocket to");const r=e.messageConsumer.readyToServe.pipe(Ae((e=>e)),Te((()=>e.getPersistedSyncState())),Ae((e=>e&&e.serverRevision)),Te((e=>i(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield Be(e)}}))))),s=t.merge(r,e.messageProducer);return function n(){return e.cloud.persistedSyncState.pipe(Ae((e=>null==e?void 0:e.serverRevision)),Se(1),Te((t=>e.cloud.currentUser.pipe(ve((e=>[e,t]))))),Te((([e,t])=>ll.pipe(ve((n=>[n?e:null,t]))))),Te((([n,r])=>(null==n?void 0:n.isLoggedIn)&&!(null==r?void 0:r.realms.includes(n.userId))?e.cloud.persistedSyncState.pipe(Ae((e=>(null==e?void 0:e.realms.includes(n.userId))||!1)),Se(1),ve((e=>[n,e]))):new t.BehaviorSubject([n,r]))),Te((e=>i(this,[e],void 0,(function*([e,t]){return[e,yield Be(t)]})))),Ie((([e,t],[n,r])=>e===n&&t===r)),Te((([r,i])=>{var o;return(null===(o=e.cloud.persistedSyncState)||void 0===o?void 0:o.value)?r?new ml(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,i,e.cloud.persistedSyncState.value.clientIdentity,s,e.cloud.webSocketStatus,r):t.from([]):n()})),he((r=>"TokenExpiredError"===(null==r?void 0:r.name)?t.of(!0).pipe(Te((()=>i(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield zt(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})})))),Te((()=>n()))):t.throwError((()=>r)))),he((r=>(e.cloud.webSocketStatus.next("error"),r instanceof _l?t.throwError((()=>r)):t.from(kl()).pipe(Te((()=>n())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(m))}))}(n)}catch(e){}}))),!0);let a=!1;function u(){if(a)throw new e.DatabaseClosedError}n.once("close",(()=>{o.forEach((e=>e.unsubscribe())),o.splice(0,o.length),a=!0,l&&l.stop(),l=null,s.next(h)}));const d=new t.Subject;var f;n.cloud={version:"4.2.0-alpha.1",options:Object.assign({},Wa),schema:null,get currentUserId(){return s.value.userId||h.userId},currentUser:s,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:d},persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return i(this,void 0,void 0,(function*(){const t=jc(n);yield t.cloud.sync(),yield Bc(t,e)}))},invites:Ba(n),roles:La(n),configure(e){e=n.cloud.options=Object.assign(Object.assign({},n.cloud.options),e),c=!0,e.databaseUrl&&e.nameSuffix&&(n.name=`${r}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,jc(n).reconfigure()),Al(n.cloud.schema,n.cloud.options)},logout(){return i(this,arguments,void 0,(function*({force:e}={}){e?yield $c(jc(n),{deleteUnsyncedData:!0}):yield Nc(jc(n))}))},sync(){return i(this,arguments,void 0,(function*({wait:r,purpose:s}={wait:!0,purpose:"push"}){var o;void 0===r&&(r=!0);const c=jc(n);if("ok"!==((null===(o=c.cloud.currentUser.value.license)||void 0===o?void 0:o.status)||"ok")&&(yield Kt(c)),"pull"===s){const e=c.cloud.persistedSyncState.value;if(Le(c,s),r){const n=yield t.firstValueFrom(c.cloud.persistedSyncState.pipe(Ae((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp)))));if(null==n?void 0:n.error)throw new Error("Sync error: "+n.error)}}else if(yield Sl(c)){const n=c.cloud.persistedSyncState.value;Le(c,s),r&&(yield t.firstValueFrom(t.from(e.liveQuery((()=>i(this,void 0,void 0,(function*(){const e=yield Sl(c),t=yield c.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==n?void 0:n.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))))).pipe(Ae((e=>!e)))))}}))},permissions:(e,t)=>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=$a(e),o=t=>{const s=t[i||e.cloud.currentUserId];return s?new Ma(s.permissions,n,void 0===i||i===e.cloud.currentUserId||r===e.cloud.currentUserId):new Ma({},n,!r||r===e.cloud.currentUserId)},c=s.pipe(ve(o));return c.getValue=()=>o(s.getValue()),c}(n._novip,e,t)},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>sl(e,n))),n.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return Qc(n.cloud.schema[this.name].idPrefix||"",t)},n.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)||""},n.use(il({currentUserObservable:n.cloud.currentUser,db:jc(n)})),n.use((f=jc(n),{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:h.userId;if((null===(o=null===(s=f.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)}})}})})),n.use(Xc(jc(n)))}Va.version="4.2.0-alpha.1",e.Cloud=Va;const Ka=new Map;function Ha(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const za=new Map;function Ja(t,n){let r=za.get(t+"/"+n);return r||(r=function t(n,r){return i(this,void 0,void 0,(function*(){var i;let s=Ka.get(n);if(!s){const i=new e(n,{addons:[Va]});if(s=jc(i),s.cloud.isServiceWorkerDB=!0,i.on("versionchange",o),yield s.dx.open(),Ka.get(n))return s.close(),yield t(n,r);Ka.set(n,s)}if((null===(i=s.cloud.options)||void 0===i?void 0:i.databaseUrl)&&s.cloud.schema)try{yield xl(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),Ka.get(s.name)===s&&Ka.delete(s.name),s.dx.close(),!1}}))}(t,n).then((()=>{za.delete(t+"/"+n)})).catch((e=>(za.delete(t+"/"+n),Promise.reject(e)))),za.set(t+"/"+n,r)),r}Kc||(self.addEventListener("sync",(e=>{const t=Ha(e.tag);t&&e.waitUntil(Ja(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=Ha(e.tag);t&&e.waitUntil(Ja(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>Ja(t,e.data.purpose||"pull").catch((e=>i(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
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs,e.rxjs.operators)}(this,(function(e,t,n){"use strict";function r(e,t,n,r){return new(n||(n=Promise))((function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(o,l)}c((r=r.apply(e,t||[])).next())}))}function s(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 i(e){return this instanceof i?(this.v=e,this):new i(e)}function o(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),o=[];return r={},l("next"),l("throw"),l("return"),r[Symbol.asyncIterator]=function(){return this},r;function l(e){s[e]&&(r[e]=function(t){return new Promise((function(n,r){o.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof i?Promise.resolve(e.value.v).then(a,u):d(o[0][2],e)}(s[e](t))}catch(e){d(o[0][3],e)}}function a(e){c("next",e)}function u(e){c("throw",e)}function d(e,t){e(t),o.shift(),o.length&&c(o[0][0],o[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=s(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,s){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,s,(t=e[n](t)).done,t.value)}))}}}const c={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(c),Object.freeze(c.claims)}catch(e){}const a={},u="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;u&&u.ready.then((e=>a.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 d{constructor(e){this.name=e}subscribe(e){if(!u)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 u.addEventListener("message",t),()=>u.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}))):a.registration&&(null===(t=a.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const h=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class f extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new d(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function s(e){n.next(e.data)}let i;!function(e,t){h.has(e)?h.get(e).push(t):h.set(e,[t])}(`lbc-${e}`,r);try{t instanceof d?i=t.subscribe((e=>n.next(e))):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=h.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof d?i():t.removeEventListener("message",s)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=h.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}let p=!1;function g(e,t){return r(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){p||(p=!0)}}))}function y(e,t){e.cloud.usingServiceWorker?g(e,t):e.localSyncEvent.next({purpose:t})}const m="fromBase64"in Uint8Array,v="toBase64"in Uint8Array.prototype,b="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):m?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var s=0;s<n;s++)r[s]=t.charCodeAt(s);return r},w="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):v?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 _(e){return r(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),s=yield crypto.subtle.digest("SHA-1",r);return w(s)}))}function k(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 S(e){return`$${e}_mutations`}function E(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 x=[].concat;function C(e){return x.apply([],e)}function I(e,t){return r(this,arguments,void 0,(function*(e,t,{since:n={},limit:s=1/0}={}){const i=C(yield Promise.all(e.map((e=>r(this,void 0,void 0,(function*(){const t=E(e.name),r=n[t];let i=r?e.where("rev").above(r):e;s<1/0&&(i=i.limit(s));return(yield i.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)),o=[];let l=null,c=null;for(const{table:e,mut:t}of i)l&&l.table===e&&c===t.txid?l.muts.push(t):(l={table:e,muts:[t]},c=t.txid,o.push(l));return o}))}function A(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 D={}.hasOwnProperty;function O(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,s=t.length;r<s;++r)O(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),l=t.substr(i+1);if(""===l)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var c=e[o];c&&function(e,t){return D.call(e,t)}(e,o)||(c=e[o]={}),O(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const T="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=U)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function U(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function j(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>j(e)))&&e.every(L))}function L(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(L)}function P(e,t,n){const r=e[t]||(e[t]={}),s=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":s.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":s.forEach(((e,t)=>{const s="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(s))O(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,s)}else r[e]={type:"upd",mod:s}}));break;case"delete":s.forEach((e=>{r[e]={type:"del"}}))}return e}function R(e,t){for(const{table:n,muts:r}of t)for(const t of r)P(e,n,t)}const M=Math.floor,N=Math.abs,$=(e,t)=>e>t?e:t,B=128,F=127,W=Number.MAX_SAFE_INTEGER,V=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&M(e)===e),K=Array.isArray,H="undefined"!=typeof TextEncoder?new TextEncoder:null,J=H?e=>H.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 z="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});z&&1===z.decode(new Uint8Array).length&&(z=null);let q=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const Y=(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},G=(e,t)=>{for(;t>F;)Y(e,B|F&t),t=M(t/128);Y(e,F&t)},Q=new Uint8Array(3e4),X=Q.length/3,Z=H&&H.encodeInto?(e,t)=>{if(t.length<X){const n=H.encodeInto(t,Q).written||0;G(e,n);for(let t=0;t<n;t++)Y(e,Q[t])}else ee(e,J(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;G(e,r);for(let t=0;t<r;t++)Y(e,n.codePointAt(t))},ee=(e,t)=>{G(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,s=((e,t)=>e<t?e:t)(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array($(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)})(e,t)},te=(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*$(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},ne=(e,t)=>te(e,8).setBigUint64(0,t,!1),re=new DataView(new ArrayBuffer(4)),se=(e,t)=>{switch(typeof t){case"string":Y(e,119),Z(e,t);break;case"number":V(t)&&N(t)<=2147483647?(Y(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),Y(e,(t>63?B:0)|(n?64:0)|63&t),t=M(t/64);t>0;)Y(e,(t>F?B:0)|F&t),t=M(t/128)})(e,t)):(n=t,re.setFloat32(0,n),re.getFloat32(0)===n?(Y(e,124),((e,t)=>{te(e,4).setFloat32(0,t,!1)})(e,t)):(Y(e,123),((e,t)=>{te(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":Y(e,122),((e,t)=>{te(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Y(e,126);else if(K(t)){Y(e,117),G(e,t.length);for(let n=0;n<t.length;n++)se(e,t[n])}else if(t instanceof Uint8Array)Y(e,116),ee(e,t);else{Y(e,118);const n=Object.keys(t);G(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];Z(e,s),se(e,t[s])}}break;case"boolean":Y(e,t?120:121);break;default:Y(e,127)}var n};function ie(e){const t=new q;switch(Z(t,e.type),"table"in e&&Z(t,e.table),"prop"in e&&Z(t,e.prop),e.type){case"u-ack":case"u-reject":ne(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":Z(t,e.yServerRev);break;default:switch(se(t,e.k),e.type){case"aware":ee(t,e.u);break;case"doc-open":se(t,e.serverRev),se(t,e.sv);break;case"doc-close":break;case"sv":ee(t,e.sv);break;case"u-c":ee(t,e.u),ne(t,BigInt(e.i));break;case"u-s":ee(t,e.u),Z(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 s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const oe=e=>new Error(e),le=oe("Unexpected end of array"),ce=oe("Integer out of Range");let ae=class{constructor(e){this.arr=e,this.pos=0}};const ue=e=>e.pos!==e.arr.length,de=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,fe(e)),he=e=>e.arr[e.pos++],fe=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&F)*n,n*=128,r<B)return t;if(t>W)throw ce}throw le},pe=z?e=>z.decode(de(e)):e=>{let t=fe(e);if(0===t)return"";{let n=String.fromCodePoint(he(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(he(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},ge=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ye=e=>ge(e,8).getBigUint64(0,!1),me=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(64&t)>0?-1:1;if(0==(t&B))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&F)*r,r*=128,t<B)return s*n;if(n>W)throw ce}throw le},e=>ge(e,4).getFloat32(0,!1),e=>ge(e,8).getFloat64(0,!1),e=>ge(e,8).getBigInt64(0,!1),e=>!1,e=>!0,pe,e=>{const t=fe(e),n={};for(let r=0;r<t;r++){n[pe(e)]=ve(e)}return n},e=>{const t=fe(e),n=[];for(let r=0;r<t;r++)n.push(ve(e));return n},de],ve=e=>me[127-he(e)](e);function be(e){return o(this,arguments,(function*(){var t,n,r,s;let o=0,c=new Uint8Array(4),a=0,u=[],d=0;try{for(var h,f=!0,p=l(e);!(t=(h=yield i(p.next())).done);f=!0){s=h.value,f=!1;const e=s,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(o){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===a)break;c[a++]=t,++n}if(a<4)break}else if(a>0&&a<4)for(const t of e.slice(n,n+4-a))c[a++]=t,++n;case 1:d=4===a?new DataView(c.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),a?a=0:n+=4;case 2:if(n>=e.byteLength){o=2;break}if(n+d>e.byteLength)u.push(e.slice(n)),d-=e.byteLength-n,o=2,n=e.byteLength;else{if(u.length>0){const t=new Uint8Array(u.reduce(((e,t)=>e+t.byteLength),d));let r=0;for(const e of u)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+d),r),u=[],yield yield i(t)}else yield yield i(e.slice(n,n+d));n+=d,o=0}}}}catch(e){n={error:e}}finally{try{f||t||!(r=p.return)||(yield i(r.call(p)))}finally{if(n)throw n.error}}}))}class we 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 _e(t,n){return new Promise(((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),s(new e.AbortError("User cancelled"))}});t.next(i)}))}function ke(e,t,...n){return _e(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function Se(e,t,n){return r(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 _e(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 Ee(e,t,n){return r(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:s}=yield _e(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s}))}function xe(e){return r(this,void 0,void 0,(function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:l,refreshTokenExpiration:c,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!l)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield Ie(e.cloud.options.databaseUrl,s);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 Ce(t,n,s,i,o){return r(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 Ie(t,n):yield function(t,n,s,i){return r(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:r,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(!r||!o)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=r;const l=function(e){const t=w(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:l,hints:i});if("error"===e.type)throw new we(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 _e(s,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof we)throw yield ke(s,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 ke(s,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,s,i,o)}))}function Ie(e,t){return r(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",s=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,s),o=w(i),l={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(l),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const a=yield c.json();if("error"===a.type)throw new we(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:Ae}={};const De={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 Oe(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,s){const i=JSON.stringify(e,(function(e){const s=this[e],i=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 De;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,Ae.call(s).slice(8,-1)),l=Object.entries(t).find((([t,n])=>{var r,s;return null!==(s=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==s?s:t===o}));return i=null==l?void 0:l[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:De),n.set(r,i),i}default:return t[r]}var s}(s);return i?i.replace(s,r,t):s}),s);return i},parse(e,n){const r=[];return JSON.parse(e,(function(e,s){const i=null==s?void 0:s.$t;if(i){const e=t[i];s=e?e.revive(s,n,t):s}let o=r[r.length-1];if(o&&o[0]===s){s={...s};for(const e of o[1])delete s[e];for(const[e,t]of Object.entries(o[2]))s[e]=t;r.pop()}if(void 0===s||"$"===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)]=s):n[e]=void 0}return s}))}}}const Te={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 Ue={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 je={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Le={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Pe={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Re={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Me="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Ne=["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 s=Me[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function $e(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=We[e[n]];return t}(w(e))}function Be(e){return b(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+=Fe[e[n]];return t}(e))}const Fe={"-":"=",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:"+","|":"/"},We={};for(const e of Object.keys(Fe))We[Fe[e]]=e;var Ve={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:$e(e)}),revive:({v:e})=>{const t=Be(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ke{constructor(e,t){this.buf=e,this.type=t}}function He(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 Je(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var ze={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ke,replace:e=>({$t:"Blob",v:w(e instanceof Ke?e.buf:Je(He(e))),type:e.type}),revive:({type:e,v:t})=>{const n=b(t);return void 0!==typeof Blob?new Blob([n]):new Ke(n.buffer,e)}}};const qe={...Ue,...je,...Le,...Pe,...Re,...Ne,...Ve,...ze};function Ye(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 Ge={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},Qe={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:w(Je(He(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=b(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const Xe="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Ze{toString(){return this.v}constructor(e){this.v=e}}const et=Xe?{}:{bigint:{test:e=>e instanceof Ze,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Ze(e)}},tt=Object.assign(Object.assign(Object.assign(Object.assign({},Ge),et),Qe),{PropModification:{test:t=>t instanceof e.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:t=>{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 s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(t,["$t"]);return new e.PropModification(n)}}}),nt=Oe(qe,tt),rt=function(...e){const t=Oe(qe,Te,...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),s=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[s,r]},async parse(e,n){let r=0;const s=[],i=await Ye(n),o=new DataView(i);for(;r<i.byteLength;){const e=o.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,s.push(t)}return t.parse(e,s)},async fromBinary(e){const t=new DataView(await Ye(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)}}}(tt);class st extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function it(t,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=t.tables.find((e=>e.name===r));if(!l)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=l;let a=i;o.forEach(((t,r)=>{const s=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,o)=>{if(Array.isArray(t)){a===i&&(a=ot(i,s));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===i&&(a=ot(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${t}:${n.userId}`;l.keys[o]=u,s&&e.setByKeyPath(l.values[o],c.keyPath,u)}}))})),s.push(a)}return s}function ot(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 lt=new WeakMap;function ct(e){return r(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=lt.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 at(e,t,n,s,i,o,l,c,a){return r(this,void 0,void 0,(function*(){const r={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield xe(i),d=null==u?void 0:u.accessToken;d&&(r.Authorization=`Bearer ${d}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:c,schema:l||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:s,changes:it(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=nt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:r,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"),s=t.headers.get("Ratelimit-Reset");if(n&&r&&s){const t=Number(n),i=Math.max(0,Number(r)),o=Number(s);if(i<t/2){const t=Math.ceil(o/(i+1));lt.set(e,new Date(Date.now()+1e3*t))}else lt.delete(e)}}(i,p),!p.ok)throw new st(p);if("application/x-bison"===p.headers.get("content-type"))return rt.fromBinary(yield p.blob());{const e=yield p.text();return nt.parse(e)}}))}function ut(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let dt=!1;function ht(e,t,n,s){return r(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:s})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function ft(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 pt(t,n,s){return r(this,void 0,void 0,(function*(){const r=yield t.bulkGet(n),i=[],o=[];n.forEach(((n,l)=>{const c=r[l];if(c){for(const[r,i]of Object.entries(s[l]))if(r===t.schema.primKey.keyPath){if(0!==e.cmp(i,n))throw new Error("Cannot change primary key")}else e.setByKeyPath(c,r,i);i.push(n),o.push(c)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(o,i):t.bulkPut(o)}))}function gt(t,n){return r(this,void 0,void 0,(function*(){for(const{table:r,muts:s}of t){if(!n.dx._allTables[r])continue;const t=n.table(r),{primaryKey:i}=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 s){const r=n.keys.map(o);switch(n.type){case"insert":i.outbound?yield t.bulkAdd(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),yield t.bulkAdd(n.values));break;case"upsert":i.outbound?yield t.bulkPut(n.values,r):(r.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.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 pt(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(dt=navigator.onLine,self.addEventListener("online",(()=>dt=!0)),self.addEventListener("offline",(()=>dt=!1)));const yt="dexie-cloud-syncer";function mt(e,t){return e.where("i").between(t,1/0,!0).toArray()}const vt=()=>new Map,bt=e=>{const t=vt();return e.forEach(((e,n)=>{t.set(n,e)})),t},wt=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},_t=()=>new Set,kt=e=>e[e.length-1],St=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Et=Array.from,xt=Array.isArray;class Ct{constructor(){this._observers=vt()}on(e,t){return wt(this._observers,e,_t).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 Et((this._observers.get(e)||vt()).values()).forEach((e=>e(...t)))}destroy(){this._observers=vt()}}const It=Math.floor,At=Math.abs,Dt=(e,t)=>e<t?e:t,Ot=(e,t)=>e>t?e:t,Tt=e=>0!==e?e<0:1/e<0,Ut=64,jt=128,Lt=127,Pt=Number.MAX_SAFE_INTEGER,Rt=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&It(e)===e),Mt=/^\s*/g,Nt=/([A-Z])/g,$t=(e,t)=>(e=>e.replace(Mt,""))(e.replace(Nt,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),Bt="undefined"!=typeof TextEncoder?new TextEncoder:null,Ft=Bt?e=>Bt.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 Wt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Wt&&1===Wt.decode(new Uint8Array).length&&(Wt=null);class Vt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Kt=()=>new Vt,Ht=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 s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Jt=(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},zt=Jt,qt=(e,t)=>{for(;t>Lt;)Jt(e,jt|Lt&t),t=It(t/128);Jt(e,Lt&t)},Yt=(e,t)=>{const n=Tt(t);for(n&&(t=-t),Jt(e,(t>63?jt:0)|(n?Ut:0)|63&t),t=It(t/64);t>0;)Jt(e,(t>Lt?jt:0)|Lt&t),t=It(t/128)},Gt=new Uint8Array(3e4),Qt=Gt.length/3,Xt=Bt&&Bt.encodeInto?(e,t)=>{if(t.length<Qt){const n=Bt.encodeInto(t,Gt).written||0;qt(e,n);for(let t=0;t<n;t++)Jt(e,Gt[t])}else en(e,Ft(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;qt(e,r);for(let t=0;t<r;t++)Jt(e,n.codePointAt(t))},Zt=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=Dt(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(Ot(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},en=(e,t)=>{qt(e,t.byteLength),Zt(e,t)},tn=(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*Ot(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},nn=new DataView(new ArrayBuffer(4)),rn=(e,t)=>{switch(typeof t){case"string":Jt(e,119),Xt(e,t);break;case"number":Rt(t)&&At(t)<=2147483647?(Jt(e,125),Yt(e,t)):(n=t,nn.setFloat32(0,n),nn.getFloat32(0)===n?(Jt(e,124),((e,t)=>{tn(e,4).setFloat32(0,t,!1)})(e,t)):(Jt(e,123),((e,t)=>{tn(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":Jt(e,122),((e,t)=>{tn(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Jt(e,126);else if(xt(t)){Jt(e,117),qt(e,t.length);for(let n=0;n<t.length;n++)rn(e,t[n])}else if(t instanceof Uint8Array)Jt(e,116),en(e,t);else{Jt(e,118);const n=Object.keys(t);qt(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];Xt(e,s),rn(e,t[s])}}break;case"boolean":Jt(e,t?120:121);break;default:Jt(e,127)}var n};class sn extends Vt{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&qt(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const on=e=>{e.count>0&&(Yt(e.encoder,1===e.count?e.s:-e.s),e.count>1&&qt(e.encoder,e.count-2))};class ln{constructor(){this.encoder=new Vt,this.s=0,this.count=0}write(e){this.s===e?this.count++:(on(this),this.count=1,this.s=e)}toUint8Array(){return on(this),Ht(this.encoder)}}const cn=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);Yt(e.encoder,t),e.count>1&&qt(e.encoder,e.count-2)}};class an{constructor(){this.encoder=new Vt,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(cn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return cn(this),Ht(this.encoder)}}class un{constructor(){this.sarr=[],this.s="",this.lensE=new ln}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 Vt;return this.sarr.push(this.s),this.s="",Xt(e,this.sarr.join("")),Zt(e,this.lensE.toUint8Array()),Ht(e)}}const dn=e=>new Error(e),hn=()=>{throw dn("Method unimplemented")},fn=()=>{throw dn("Unexpected case")},pn=dn("Unexpected end of array"),gn=dn("Integer out of Range");class yn{constructor(e){this.arr=e,this.pos=0}}const mn=e=>new yn(e),vn=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,wn(e)),bn=e=>e.arr[e.pos++],wn=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Lt)*n,n*=128,r<jt)return t;if(t>Pt)throw gn}throw pn},_n=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&Ut)>0?-1:1;if(0==(t&jt))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&Lt)*r,r*=128,t<jt)return s*n;if(n>Pt)throw gn}throw pn},kn=Wt?e=>Wt.decode(vn(e)):e=>{let t=wn(e);if(0===t)return"";{let n=String.fromCodePoint(bn(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(bn(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},Sn=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},En=[e=>{},e=>null,_n,e=>Sn(e,4).getFloat32(0,!1),e=>Sn(e,8).getFloat64(0,!1),e=>Sn(e,8).getBigInt64(0,!1),e=>!1,e=>!0,kn,e=>{const t=wn(e),n={};for(let r=0;r<t;r++){n[kn(e)]=xn(e)}return n},e=>{const t=wn(e),n=[];for(let r=0;r<t;r++)n.push(xn(e));return n},vn],xn=e=>En[127-bn(e)](e);class Cn extends yn{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=wn(this)+1:this.count=-1),this.count--,this.s}}class In extends yn{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=_n(this);const e=Tt(this.s);this.count=1,e&&(this.s=-this.s,this.count=wn(this)+2)}return this.count--,this.s}}class An extends yn{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=_n(this),t=1&e;this.diff=It(e/2),this.count=1,t&&(this.count=wn(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Dn{constructor(e){this.decoder=new In(e),this.str=kn(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 On=crypto.getRandomValues.bind(crypto),Tn=()=>On(new Uint32Array(1))[0],Un=[1e7]+-1e3+-4e3+-8e3+-1e11,jn=()=>Un.replace(/[018]/g,(e=>(e^Tn()&15>>e/4).toString(16))),Ln=e=>new Promise(e);Promise.all.bind(Promise);const Pn=e=>void 0===e?null:e;let Rn=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Mn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Rn=localStorage,Mn=!1)}catch(Ql){}const Nn=Rn,$n=Object.assign,Bn=Object.keys,Fn=e=>Bn(e).length,Wn=(e,t)=>e===t||Fn(e)===Fn(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)),Vn=Object.freeze,Kn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Kn(e[t])}return Vn(e)},Hn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Hn(e,t,n+1)}},Jn="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let zn;const qn=e=>(()=>{if(void 0===zn)if(Jn){zn=vt();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&zn.set(t,""),t=r):null!==t&&(zn.set(t,r),t=null)}null!==t&&zn.set(t,"")}else"object"==typeof location?(zn=vt(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");zn.set(`--${$t(t,"-")}`,n),zn.set(`-${$t(t,"-")}`,n)}}))):zn=vt();return zn})().has(e),Yn=e=>Pn(Jn?process.env[e.toUpperCase().replaceAll("-","_")]:Nn.getItem(e)),Gn=e=>qn("--"+e)||null!==Yn(e);Gn("production");var Qn;Jn&&(Qn=process.env.FORCE_COLOR,["true","1","2"].includes(Qn))||!qn("--no-colors")&&!Gn("no-color")&&(!Jn||process.stdout.isTTY)&&(!Jn||qn("--color")||null!==Yn("COLORTERM")||(Yn("TERM")||"").includes("color"));class Xn{constructor(e,t){this.left=e,this.right=t}}const Zn=(e,t)=>new Xn(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const er=Symbol,tr=er(),nr=er(),rr=er(),sr=er(),ir=er(),or=er(),lr=er(),cr=er(),ar=er(),ur=(Zn("font-weight","bold"),Zn("font-weight","normal"),Zn("color","blue"),Zn("color","green"),Zn("color","grey"),Zn("color","red"),Zn("color","purple"),Zn("color","orange"),Zn("color","black"),_t()),dr=e=>({[Symbol.iterator](){return this},next:e}),hr=(e,t)=>dr((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class fr{constructor(e,t){this.clock=e,this.len=t}}class pr{constructor(){this.clients=new Map}}const gr=(e,t,n)=>t.clients.forEach(((t,r)=>{const s=e.doc.store.clients.get(r);if(null!=s){const r=s[s.length-1],i=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<i;o=t[++r])Qr(e,s,o.clock,o.len,n)}})),yr=(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 s=It((n+r)/2),i=e[s],o=i.clock;if(o<=t){if(t<o+i.len)return s;n=s+1}else r=s-1}return null})(n,t.clock)},mr=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],s=e[t];r.clock+r.len>=s.clock?r.len=Ot(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n}))},vr=(e,t,n,r)=>{wt(e.clients,t,(()=>[])).push(new fr(n,r))},br=(e,t)=>{qt(e.restEncoder,t.clients.size),Et(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),qt(e.restEncoder,t);const r=n.length;qt(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},wr=(e,t,n)=>{const r=new pr,s=wn(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=wn(e.restDecoder),i=wn(e.restDecoder),o=n.clients.get(s)||[],l=Kr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&vr(r,s,l,i-l);let e=Jr(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Ui(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<i);)c.deleted||(i<c.id.clock+c.length&&o.splice(e,0,Ui(t,c,i-c.id.clock)),c.delete(t))}else vr(r,s,n,i-n)}}if(r.clients.size>0){const e=new Ar;return qt(e.restEncoder,0),br(e,r),e.toUint8Array()}return null},_r=Tn;class kr extends Ct{constructor({guid:e=jn(),collectionid:t=null,gc:n=!0,gcFilter:r=(()=>!0),meta:s=null,autoLoad:i=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=_r(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Wr,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=i,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=Ln((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const l=()=>Ln((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=l()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])})),this.whenSynced=l()}load(){const e=this._item;null===e||this.shouldLoad||rs(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Et(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return rs(this,e,t)}get(e,t=ks){const n=wt(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==ks&&r!==t){if(r===ks){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,Bs)}getText(e=""){return this.get(e,si)}getMap(e=""){return this.get(e,Ws)}getXmlElement(e=""){return this.get(e,li)}getXmlFragment(e=""){return this.get(e,oi)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,Et(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new kr({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,rs(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 Sr{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=wn(this.restDecoder),this.dsCurrVal}readDsLen(){const e=wn(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Er extends Sr{constructor(e){super(e),this.keys=[],wn(e),this.keyClockDecoder=new An(vn(e)),this.clientDecoder=new In(vn(e)),this.leftClockDecoder=new An(vn(e)),this.rightClockDecoder=new An(vn(e)),this.infoDecoder=new Cn(vn(e),bn),this.stringDecoder=new Dn(vn(e)),this.parentInfoDecoder=new Cn(vn(e),bn),this.typeRefDecoder=new In(vn(e)),this.lenDecoder=new In(vn(e))}readLeftID(){return new Mr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Mr(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 xn(this.restDecoder)}readBuf(){return vn(this.restDecoder)}readJSON(){return xn(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 xr{constructor(){this.restEncoder=Kt()}toUint8Array(){return Ht(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){qt(this.restEncoder,e)}writeDsLen(e){qt(this.restEncoder,e)}}class Cr extends xr{writeLeftID(e){qt(this.restEncoder,e.client),qt(this.restEncoder,e.clock)}writeRightID(e){qt(this.restEncoder,e.client),qt(this.restEncoder,e.clock)}writeClient(e){qt(this.restEncoder,e)}writeInfo(e){zt(this.restEncoder,e)}writeString(e){Xt(this.restEncoder,e)}writeParentInfo(e){qt(this.restEncoder,e?1:0)}writeTypeRef(e){qt(this.restEncoder,e)}writeLen(e){qt(this.restEncoder,e)}writeAny(e){rn(this.restEncoder,e)}writeBuf(e){en(this.restEncoder,e)}writeJSON(e){Xt(this.restEncoder,JSON.stringify(e))}writeKey(e){Xt(this.restEncoder,e)}}class Ir{constructor(){this.restEncoder=Kt(),this.dsCurrVal=0}toUint8Array(){return Ht(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,qt(this.restEncoder,t)}writeDsLen(e){0===e&&fn(),qt(this.restEncoder,e-1),this.dsCurrVal+=e}}class Ar extends Ir{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new an,this.clientEncoder=new ln,this.leftClockEncoder=new an,this.rightClockEncoder=new an,this.infoEncoder=new sn(zt),this.stringEncoder=new un,this.parentInfoEncoder=new sn(zt),this.typeRefEncoder=new ln,this.lenEncoder=new ln}toUint8Array(){const e=Kt();return qt(e,0),en(e,this.keyClockEncoder.toUint8Array()),en(e,this.clientEncoder.toUint8Array()),en(e,this.leftClockEncoder.toUint8Array()),en(e,this.rightClockEncoder.toUint8Array()),en(e,Ht(this.infoEncoder)),en(e,this.stringEncoder.toUint8Array()),en(e,Ht(this.parentInfoEncoder)),en(e,this.typeRefEncoder.toUint8Array()),en(e,this.lenEncoder.toUint8Array()),Zt(e,Ht(this.restEncoder)),Ht(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){rn(this.restEncoder,e)}writeBuf(e){en(this.restEncoder,e)}writeJSON(e){rn(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 Dr=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{Kr(t,n)>e&&r.set(n,e)})),Vr(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),qt(e.restEncoder,r.size),Et(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=Ot(r,t[0].id.clock);const s=Jr(t,r);qt(e.restEncoder,t.length-s),e.writeClient(n),qt(e.restEncoder,r);const i=t[s];i.write(e,r-i.id.clock);for(let n=s+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)}))},Or=(e,t,n,r=new Er(e))=>rs(t,(e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=vt(),r=wn(e.restDecoder);for(let s=0;s<r;s++){const r=wn(e.restDecoder),s=new Array(r),i=e.readClient();let o=wn(e.restDecoder);n.set(i,{i:0,refs:s});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();s[n]=new hi($r(i,o),t),o+=t;break}case 10:{const t=wn(e.restDecoder);s[n]=new Ri($r(i,o),t),o+=t;break}default:{const l=0==(192&r),c=new ji($r(i,o),null,(r&jt)===jt?e.readLeftID():null,null,(r&Ut)===Ut?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,l&&32==(32&r)?e.readString():null,Li(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=Et(n.keys()).sort(((e,t)=>e-t));if(0===s.length)return null;const i=()=>{if(0===s.length)return null;let e=n.get(s[s.length-1]);for(;e.refs.length===e.i;){if(s.pop(),!(s.length>0))return null;e=n.get(s[s.length-1])}return e};let o=i();if(null===o)return null;const l=new Wr,c=new Map,a=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.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--,l.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):l.clients.set(t,[e]),s=s.filter((e=>e!==t))}r.length=0};for(;;){if(u.constructor!==Ri){const s=wt(d,u.id.client,(()=>Kr(t,u.id.client)))-u.id.clock;if(s<0)r.push(u),a(u.id.client,u.id.clock-1),h();else{const i=u.getMissing(e,t);if(null!==i){r.push(u);const e=n.get(i)||{refs:[],i:0};if(e.refs.length!==e.i){u=e.refs[e.i++];continue}a(i,Kr(t,i)),h()}else(0===s||s<u.length)&&(u.integrate(e,s),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=i(),null===o)break;u=o.refs[o.i++]}}if(l.clients.size>0){const e=new Ar;return Dr(e,l,new Map),qt(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,s,i),l=s.pendingStructs;if(l){for(const[e,n]of l.missing)if(n<Kr(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=l.missing.get(e);(null==n||n>t)&&l.missing.set(e,t)}l.update=cs([l.update,o.update])}}else s.pendingStructs=o;const c=wr(r,e,s);if(s.pendingDs){const t=new Er(mn(s.pendingDs));wn(t.restDecoder);const n=wr(t,e,s);s.pendingDs=c&&n?cs([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,Tr(e.doc,t)}}),n,!1),Tr=(e,t,n,r=Er)=>{const s=mn(t);Or(s,e,n,new r(s))};class Ur{constructor(){this.l=[]}}const jr=()=>new Ur,Lr=(e,t)=>e.l.push(t),Pr=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},Rr=(e,t,n)=>Hn(e.l,[t,n]);class Mr{constructor(e,t){this.client=e,this.clock=t}}const Nr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,$r=(e,t)=>new Mr(e,t),Br=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!yr(t.ds,e.id),Fr=(e,t)=>{const n=wt(e.meta,Fr,_t),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<Kr(r,n)&&Yr(e,$r(n,t))})),gr(e,t.ds,(e=>{})),n.add(t))};class Wr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Vr=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},Kr=(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},Hr=(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 fn()}n.push(t)},Jr=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=It(t/(i+s.length-1)*r);for(;n<=r;){if(s=e[o],i=s.id.clock,i<=t){if(t<i+s.length)return o;n=o+1}else r=o-1;o=It((n+r)/2)}throw fn()},zr=(e,t)=>{const n=e.clients.get(t.client);return n[Jr(n,t.clock)]},qr=(e,t,n)=>{const r=Jr(t,n),s=t[r];return s.id.clock<n&&s instanceof ji?(t.splice(r+1,0,Ui(e,s,n-s.id.clock)),r+1):r},Yr=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[qr(e,n,t.clock)]},Gr=(e,t,n)=>{const r=t.clients.get(n.client),s=Jr(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==hi&&r.splice(s+1,0,Ui(e,i,n.clock-i.id.clock+1)),i},Qr=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=qr(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&qr(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class Xr{constructor(e,t,n){this.doc=e,this.deleteSet=new pr,this.beforeState=Vr(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 Zr=(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)))&&(mr(t.deleteSet),((e,t)=>{Dr(e,t.doc.store,t.beforeState)})(e,t),br(e,t.deleteSet),!0),es=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&wt(e.changed,t,_t).add(n)},ts=(e,t)=>{let n=e[t],r=e[t-1],s=t;for(;s>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--s-1])n instanceof ji&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const i=t-s;return i&&e.splice(t+1-i,i),i},ns=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{mr(i),n.afterState=Vr(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)),Rr(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),Hn(e,[]),n._needFormattingCleanup&&ti(n)}finally{r.gc&&((e,t,n)=>{for(const[r,s]of e.clients.entries()){const e=t.clients.get(r);for(let r=s.length-1;r>=0;r--){const i=s[r],o=i.clock+i.len;for(let r=Jr(e,i.clock),s=e[r];r<e.length&&s.id.clock<o;s=e[++r]){const s=e[r];if(i.clock+i.len<=s.id.clock)break;s instanceof ji&&s.deleted&&!s.keep&&n(s)&&s.gc(t,!1)}}}})(i,s,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=Dt(r.length-1,1+Jr(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+ts(r,e)}}))})(i,s),n.afterState.forEach(((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=s.clients.get(t),n=Ot(Jr(e,r),1);for(let t=e.length-1;t>=n;)t-=1+ts(e,t)}}));for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=s.clients.get(t),i=Jr(r,n);i+1<r.length&&ts(r,i+1)>1||i>0&&ts(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{ur.forEach((t=>t.print(e)))})(cr,tr,"[yjs] ",nr,or,"Changed the client-id because another client seems to be using it."),r.clientID=_r()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Cr;Zr(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Ar;Zr(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.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:c,added:l,removed:a},r,n]),a.forEach((e=>e.destroy()))),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):ns(e,t+1)}}},rs=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new Xr(e,n,r),s.push(e._transaction),1===s.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const t=e._transaction===s[0];e._transaction=null,t&&ns(s,0)}}return o};class ss{constructor(e,t){this.gen=function*(e){const t=wn(e.restDecoder);for(let n=0;n<t;n++){const t=wn(e.restDecoder),n=e.readClient();let r=wn(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=wn(e.restDecoder);yield new Ri($r(n,r),t),r+=t}else if(0!=(31&t)){const s=0==(192&t),i=new ji($r(n,r),null,(t&jt)===jt?e.readLeftID():null,null,(t&Ut)===Ut?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,s&&32==(32&t)?e.readString():null,Li(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new hi($r(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===Ri);return this.curr}}class is{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const os=(e,t=Ir,n=Er)=>{const r=new t,s=new ss(new n(mn(e)),!1);let i=s.curr;if(null!==i){let e=0,t=i.id.client,n=0!==i.id.clock,o=n?0:i.id.clock+i.length;for(;null!==i;i=s.next())t!==i.id.client&&(0!==o&&(e++,qt(r.restEncoder,t),qt(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===Ri&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,qt(r.restEncoder,t),qt(r.restEncoder,o));const l=Kt();return qt(l,e),((e,t)=>{Zt(e,Ht(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return qt(r.restEncoder,0),r.toUint8Array()},ls=(e,t)=>{if(e.constructor===hi){const{client:n,clock:r}=e.id;return new hi($r(n,r+t),e.length-t)}if(e.constructor===Ri){const{client:n,clock:r}=e.id;return new Ri($r(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new ji($r(r,s+t),null,$r(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},cs=(e,t=Er,n=Ar)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(mn(e))));let s=r.map((e=>new ss(e,!0))),i=null;const o=new n,l=new is(o);for(;s=s.filter((e=>null!==e.curr)),s.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===Ri?1:-1:n}return t.curr.id.client-e.curr.id.client})),0!==s.length;){const e=s[0],t=e.curr.id.client;if(null!==i){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=i.struct.id.clock+i.struct.length&&n.id.client>=i.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>i.struct.id.clock+i.struct.length)continue;if(t!==i.struct.id.client)us(l,i.struct,i.offset),i={struct:n,offset:0},e.next();else if(i.struct.id.clock+i.struct.length<n.id.clock)if(i.struct.constructor===Ri)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{us(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Ri($r(t,i.struct.id.clock+i.struct.length),e),offset:0}}else{const t=i.struct.id.clock+i.struct.length-n.id.clock;t>0&&(i.struct.constructor===Ri?i.struct.length-=t:n=ls(n,t)),i.struct.mergeWith(n)||(us(l,i.struct,i.offset),i={struct:n,offset:0},e.next())}}else i={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===i.struct.id.clock+i.struct.length&&n.constructor!==Ri;n=e.next())us(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(us(l,i.struct,i.offset),i=null),ds(l);const c=r.map((e=>(e=>{const t=new pr,n=wn(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=wn(e.restDecoder),r=wn(e.restDecoder);if(r>0){const s=wt(t.clients,n,(()=>[]));for(let t=0;t<r;t++)s.push(new fr(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new pr;for(let n=0;n<e.length;n++)e[n].clients.forEach(((r,s)=>{if(!t.clients.has(s)){const i=r.slice();for(let t=n+1;t<e.length;t++)St(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}}));return mr(t),t})(c);return br(o,a),o.toUint8Array()},as=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Ht(e.encoder.restEncoder)}),e.encoder.restEncoder=Kt(),e.written=0)},us=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&as(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),qt(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ds=e=>{as(e);const t=e.encoder.restEncoder;qt(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];qt(t,r.written),Zt(t,r.restEncoder)}},hs="You must not compute changes after the event-handler fired.";class fs{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=ps(this.currentTarget,this.target))}deletes(e){return yr(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw dn(hs);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n=>{if(null!==n){const r=t._map.get(n);let s,i;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;s="delete",i=kt(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=kt(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=kt(r.content.getContent())}e.set(n,{action:s,oldValue:i})}})),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 dn(hs);const t=this.target,n=_t(),r=_t(),s=[];e={added:n,deleted:r,delta:s,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const i=()=>{e&&s.push(e)};for(let s=t._start;null!==s;s=s.right)s.deleted?this.deletes(s)&&!this.adds(s)&&(null!==e&&void 0!==e.delete||(i(),e={delete:0}),e.delete+=s.length,r.add(s)):this.adds(s)?(null!==e&&void 0!==e.insert||(i(),e={insert:[]}),e.insert=e.insert.concat(s.content.getContent()),n.add(s)):(null!==e&&void 0!==e.retain||(i(),e={retain:0}),e.retain+=s.length);null!==e&&void 0===e.retain&&i()}this._changes=e}return e}}const ps=(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},gs=()=>{((...e)=>{e.unshift(cr),ur.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let ys=0;class ms{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=ys++}}const vs=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=ys++},bs=(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)=>At(t-e.index)<At(t-n.index)?e:n));let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=ys++})(n));null!==r.right&&s<t;){if(!r.deleted&&r.countable){if(t<s+r.length)break;s+=r.length}r=r.right}for(;null!==r.left&&s>t;)r=r.left,!r.deleted&&r.countable&&(s-=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&&(s-=r.length);return null!==n&&At(n.index-s)<r.parent.length/80?(vs(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return vs(r,t,n),r}{const r=new ms(t,n);return e.push(r),r}})(e._searchMarker,r,s)},ws=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const s=e[r];if(n>0){let t=s.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(s.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}s.p=t,t.marker=!0}(t<s.index||n>0&&t===s.index)&&(s.index=Ot(t,s.index+n))}},_s=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;wt(s,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;Rr(r._eH,n,t)};class ks{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=jr(),this._dEH=jr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw hn()}clone(){throw hn()}_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){Lr(this._eH,e)}observeDeep(e){Lr(this._dEH,e)}unobserve(e){Pr(this._eH,e)}unobserveDeep(e){Pr(this._dEH,e)}toJSON(){}}const Ss=(e,t,n)=>{e.doc??gs(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const s=[];let i=e._start;for(;null!==i&&r>0;){if(i.countable&&!i.deleted){const e=i.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)s.push(e[n]),r--;t=0}}i=i.right}return s},Es=e=>{e.doc??gs();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},xs=(e,t)=>{let n=0,r=e._start;for(e.doc??gs();null!==r;){if(r.countable&&!r.deleted){const s=r.content.getContent();for(let r=0;r<s.length;r++)t(s[r],n++,e)}r=r.right}},Cs=(e,t)=>{const n=[];return xs(e,((r,s)=>{n.push(t(r,s,e))})),n},Is=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}}}},As=(e,t)=>{e.doc??gs();const n=bs(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}},Ds=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,l=i.store,c=null===n?t._start:n.right;let a=[];const u=()=>{a.length>0&&(s=new ji($r(o,Kr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new _i(a)),s.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:s=new ji($r(o,Kr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new fi(new Uint8Array(n))),s.integrate(e,0);break;case kr:s=new ji($r(o,Kr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new yi(n)),s.integrate(e,0);break;default:if(!(n instanceof ks))throw new Error("Unexpected content type in insert operation");s=new ji($r(o,Kr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ti(n)),s.integrate(e,0)}}})),u()},Os=()=>dn("Length exceeded!"),Ts=(e,t,n,r)=>{if(n>t._length)throw Os();if(0===n)return t._searchMarker&&ws(t._searchMarker,n,r.length),Ds(e,t,null,r);const s=n,i=bs(t,n);let o=t._start;for(null!==i&&(o=i.p,0===(n-=i.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&&Yr(e,$r(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ws(t._searchMarker,s,r.length),Ds(e,t,o,r)},Us=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=bs(t,n);let l=t._start;for(null!==o&&(l=o.p,n-=o.index);null!==l&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&Yr(e,$r(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&Yr(e,$r(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw Os();t._searchMarker&&ws(t._searchMarker,s,-i+r)},js=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Ls=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new _i([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new _i([r]);break;case Uint8Array:l=new fi(r);break;case kr:l=new yi(r);break;default:if(!(r instanceof ks))throw new Error("Unexpected content type");l=new Ti(r)}new ji($r(o,Kr(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},Ps=(e,t)=>{e.doc??gs();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Rs=e=>{const t={};return e.doc??gs(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Ms=(e,t)=>{e.doc??gs();const n=e._map.get(t);return void 0!==n&&!n.deleted},Ns=e=>{return e.doc??gs(),t=e._map.entries(),n=e=>!e[1].deleted,dr((()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e}));var t,n};class $s extends fs{}class Bs extends ks{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Bs;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Bs}clone(){const e=new Bs;return e.insert(0,this.toArray().map((e=>e instanceof ks?e.clone():e))),e}get length(){return this.doc??gs(),this._length}_callObserver(e,t){super._callObserver(e,t),_s(this,e,new $s(this,e))}insert(e,t){null!==this.doc?rs(this.doc,(n=>{Ts(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?rs(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;Ds(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?rs(this.doc,(n=>{Us(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return As(this,e)}toArray(){return Es(this)}slice(e=0,t=this.length){return Ss(this,e,t)}toJSON(){return this.map((e=>e instanceof ks?e.toJSON():e))}map(e){return Cs(this,e)}forEach(e){xs(this,e)}[Symbol.iterator](){return Is(this)}_write(e){e.writeTypeRef(Ei)}}class Fs extends fs{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ws extends ks{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 Ws}clone(){const e=new Ws;return this.forEach(((t,n)=>{e.set(n,t instanceof ks?t.clone():t)})),e}_callObserver(e,t){_s(this,e,new Fs(this,e,t))}toJSON(){this.doc??gs();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof ks?r.toJSON():r}})),e}get size(){return[...Ns(this)].length}keys(){return hr(Ns(this),(e=>e[0]))}values(){return hr(Ns(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return hr(Ns(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??gs(),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?rs(this.doc,(t=>{js(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?rs(this.doc,(n=>{Ls(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return Ps(this,e)}has(e){return Ms(this,e)}clear(){null!==this.doc?rs(this.doc,(e=>{this.forEach((function(t,n,r){js(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(xi)}}const Vs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&Wn(e,t);class Ks{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&fn(),this.right.content.constructor===vi)this.right.deleted||qs(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const Hs=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===vi)t.right.deleted||qs(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Yr(e,$r(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},Js=(e,t,n,r)=>{const s=new Map,i=r?bs(t,n):null;if(i){const t=new Ks(i.p.left,i.p,i.index,s);return Hs(e,t,n-i.index)}{const r=new Ks(null,t._start,0,s);return Hs(e,r,n)}},zs=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===vi&&Vs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach(((r,o)=>{const l=n.left,c=n.right,a=new ji($r(i,Kr(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new vi(o,r));a.integrate(e,0),n.right=a,n.forward()}))},qs=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Ys=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===vi&&Vs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Gs=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const l in r){const c=r[l],a=n.currentAttributes.get(l)??null;if(!Vs(a,c)){o.set(l,a);const{left:r,right:u}=n;n.right=new ji($r(i,Kr(s.store,i)),r,r&&r.lastId,u,u&&u.id,t,null,new vi(l,c)),n.right.integrate(e,0),n.forward()}}return o},Qs=(e,t,n,r,s)=>{n.currentAttributes.forEach(((e,t)=>{void 0===s[t]&&(s[t]=null)}));const i=e.doc,o=i.clientID;Ys(n,s);const l=Gs(e,t,n,s),c=r.constructor===String?new ki(r):r instanceof ks?new Ti(r):new mi(r);let{left:a,right:u,index:d}=n;t._searchMarker&&ws(t._searchMarker,n.index,c.getLength()),u=new ji($r(o,Kr(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),zs(e,t,n,l)},Xs=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Ys(n,s);const l=Gs(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===vi));){if(!n.right.deleted)switch(n.right.content.constructor){case vi:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(Vs(o,i))l.delete(t);else{if(0===r)break e;l.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&Yr(e,$r(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let s="";for(;r>0;r--)s+="\n";n.right=new ji($r(o,Kr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ki(s)),n.right.integrate(e,0),n.forward()}zs(e,t,n,l)},Zs=(e,t,n,r,s)=>{let i=t;const o=vt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===vi){const e=i.content;o.set(e.key,e)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case vi:{const{key:i,value:a}=n,u=r.get(i)??null;o.get(i)===n&&u!==a||(t.delete(e),l++,c||(s.get(i)??null)!==a||u===a||(null===u?s.delete(i):s.set(i,u))),c||t.deleted||qs(s,n);break}}}t=t.right}return l},ei=e=>{let t=0;return rs(e.doc,(n=>{let r=e._start,s=e._start,i=vt();const o=bt(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===vi)qs(o,s.content);else t+=Zs(n,r,s,i,o),i=bt(o),r=s;s=s.right}})),t},ti=e=>{const t=new Set,n=e.doc;for(const[r,s]of e.afterState.entries()){const i=e.beforeState.get(r)||0;s!==i&&Qr(e,n.store.clients.get(r),i,s,(e=>{e.deleted||e.content.constructor!==vi||e.constructor===hi||t.add(e.parent)}))}rs(n,(n=>{gr(e,e.deleteSet,(e=>{if(e instanceof hi||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===vi?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===vi){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)ei(e)}))},ni=(e,t,n)=>{const r=n,s=bt(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Ti:case mi:case ki:n<t.right.length&&Yr(e,$r(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&Zs(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&ws(o._searchMarker,t.index,-r+n),t};class ri extends fs{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=[];rs(e,(e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let l="",c=0,a=0;const u=()=>{if(null!==i){let e=null;switch(i){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof l||l.length>0)&&(e={insert:l},n.size>0&&(e.attributes={},n.forEach(((t,n)=>{null!==t&&(e.attributes[n]=t)})))),l="";break;case"retain":c>0&&(e={retain:c},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=$n({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case Ti:case mi:this.adds(s)?this.deletes(s)||(u(),i="insert",l=s.content.getContent()[0],u()):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=1):s.deleted||("retain"!==i&&(u(),i="retain"),c+=1);break;case ki:this.adds(s)?this.deletes(s)||("insert"!==i&&(u(),i="insert"),l+=s.content.str):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(u(),i="retain"),c+=s.length);break;case vi:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;Vs(c,l)?null!==l&&s.delete(e):("retain"===i&&u(),Vs(l,r.get(t)??null)?delete o[t]:o[t]=l)}}else if(this.deletes(s)){r.set(t,l);const e=n.get(t)??null;Vs(e,l)||("retain"===i&&u(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(Vs(n,l)?null!==n&&s.delete(e):("retain"===i&&u(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&u(),qs(n,s.content));break}}s=s.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 si extends ks{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??gs(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new si}clone(){const e=new si;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new ri(this,e,t);_s(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??gs();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===ki&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?rs(this.doc,(n=>{const r=new Ks(null,this._start,0,new Map);for(let s=0;s<e.length;s++){const i=e[s];if(void 0!==i.insert){const o=t||"string"!=typeof i.insert||s!==e.length-1||null!==r.right||"\n"!==i.insert.slice(-1)?i.insert:i.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Qs(n,this,r,o,i.attributes||{})}else void 0!==i.retain?Xs(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&ni(n,r,i.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??gs();const r=[],s=new Map,i=this.doc;let o="",l=this._start;function c(){if(o.length>0){const e={};let t=!1;s.forEach(((n,r)=>{t=!0,e[r]=n}));const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==l;){if(Br(l,e)||void 0!==t&&Br(l,t))switch(l.content.constructor){case ki:{const r=s.get("ychange");void 0===e||Br(l,e)?void 0===t||Br(l,t)?void 0!==r&&(c(),s.delete("ychange")):void 0!==r&&r.user===l.id.client&&"added"===r.type||(c(),s.set("ychange",n?n("added",l.id):{type:"added"})):void 0!==r&&r.user===l.id.client&&"removed"===r.type||(c(),s.set("ychange",n?n("removed",l.id):{type:"removed"})),o+=l.content.str;break}case Ti:case mi:{c();const e={insert:l.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach(((e,n)=>{t[n]=e}))}r.push(e);break}case vi:Br(l,e)&&(c(),qs(s,l.content))}l=l.right}c()};return e||t?rs(i,(n=>{e&&Fr(n,e),t&&Fr(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?rs(r,(r=>{const s=Js(r,this,e,!n);n||(n={},s.currentAttributes.forEach(((e,t)=>{n[t]=e}))),Qs(r,this,s,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?rs(r,(r=>{const s=Js(r,this,e,!n);Qs(r,this,s,t,n||{})})):this._pending.push((()=>this.insertEmbed(e,t,n||{})))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?rs(n,(n=>{ni(n,Js(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?rs(r,(r=>{const s=Js(r,this,e,!1);null!==s.right&&Xs(r,this,s,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?rs(this.doc,(t=>{js(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?rs(this.doc,(n=>{Ls(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return Ps(this,e)}getAttributes(){return Rs(this)}_write(e){e.writeTypeRef(Ci)}}class ii{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??gs()}[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!==li&&t.constructor!==oi||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 oi extends ks{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 oi}clone(){const e=new oi;return e.insert(0,this.toArray().map((e=>e instanceof ks?e.clone():e))),e}get length(){return this.doc??gs(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new ii(this,e)}querySelector(e){e=e.toUpperCase();const t=new ii(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Et(new ii(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){_s(this,e,new ci(this,t,e))}toString(){return Cs(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),xs(this,(s=>{r.insertBefore(s.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?rs(this.doc,(n=>{Ts(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)rs(this.doc,(n=>{const r=e&&e instanceof ks?e._item:e;Ds(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 dn("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?rs(this.doc,(n=>{Us(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return Es(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return As(this,e)}slice(e=0,t=this.length){return Ss(this,e,t)}forEach(e){xs(this,e)}_write(e){e.writeTypeRef(Ai)}}class li extends oi{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 li(this.nodeName)}clone(){const e=new li(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 ks?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 s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const s=this.nodeName.toLocaleLowerCase();return`<${s}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${s}>`}removeAttribute(e){null!==this.doc?rs(this.doc,(t=>{js(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?rs(this.doc,(n=>{Ls(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return Ps(this,e)}hasAttribute(e){return Ms(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach(((e,r)=>{let s=e;for(;null!==s&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;null!==s&&Br(s,t)&&(n[r]=s.content.getContent()[s.length-1])})),n})(this,e):Rs(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),s=this.getAttributes();for(const e in s){const t=s[e];"string"==typeof t&&r.setAttribute(e,t)}return xs(this,(s=>{r.appendChild(s.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Ii),e.writeKey(this.nodeName)}}class ci extends fs{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 ai extends Ws{constructor(e){super(),this.hookName=e}_copy(){return new ai(this.hookName)}clone(){const e=new ai(this.hookName);return this.forEach(((t,n)=>{e.set(n,t)})),e}toDOM(e=document,t={},n){const r=t[this.hookName];let s;return s=void 0!==r?r.createDom(this):document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(Di),e.writeKey(this.hookName)}}class ui extends si{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 ui}clone(){const e=new ui;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(Oi)}}class di{constructor(e,t){this.id=e,this.length=t}get deleted(){throw hn()}mergeWith(e){return!1}write(e,t,n){throw hn()}integrate(e,t){throw hn()}}class hi extends di{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),Hr(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class fi{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new fi(this.content)}splice(e){throw hn()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class pi{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new pi(this.len)}splice(e){const t=new pi(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){vr(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 gi=(e,t)=>new kr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class yi{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 yi(gi(this.doc.guid,this.opts))}splice(e){throw hn()}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 mi{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new mi(this.embed)}splice(e){throw hn()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class vi{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new vi(this.key,this.value)}splice(e){throw hn()}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 bi{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new bi(this.arr)}splice(e){const t=new bi(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 wi="development"===Yn("node_env");class _i{constructor(e){this.arr=e,wi&&Kn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new _i(this.arr)}splice(e){const t=new _i(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 ki{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new ki(this.str)}splice(e){const t=new ki(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 Si=[e=>new Bs,e=>new Ws,e=>new si,e=>new li(e.readKey()),e=>new oi,e=>new ai(e.readKey()),e=>new ui],Ei=0,xi=1,Ci=2,Ii=3,Ai=4,Di=5,Oi=6;class Ti{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Ti(this.type._copy())}splice(e){throw hn()}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 Ui=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new ji($r(r,s+n),t,$r(r,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),null!==t.redone&&(i.redone=$r(t.redone.client,t.redone.clock+n)),t.right=i,null!==i.right&&(i.right.left=i),e._mergeStructs.push(i),null!==i.parentSub&&null===i.right&&i.parent._map.set(i.parentSub,i),t.length=n,i};class ji extends di{constructor(e,t,n,r,s,i,o,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=l,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>=Kr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Kr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Mr&&this.id.client!==this.parent.client&&this.parent.clock>=Kr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Gr(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Yr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===hi||this.right&&this.right.constructor===hi)this.parent=null;else if(this.parent){if(this.parent.constructor===Mr){const e=zr(t,this.parent);e.constructor===hi?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===ji?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===ji&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Gr(e,e.doc.store,$r(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,s=new Set;for(;null!==t&&t!==this.right;){if(s.add(t),r.add(t),Nr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Nr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(zr(e.doc.store,t.origin)))break;r.has(zr(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),Hr(e.doc.store,this),this.content.integrate(e,this),es(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new hi(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:$r(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Nr(e.origin,this.lastId)&&this.right===e&&Nr(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(),vr(e.deleteSet,this.id.client,this.id.clock,this.length),es(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw fn();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[Jr(r,t.id.clock)]=n})(e,this,new hi(this.id,this.length)):this.content=new pi(this.length)}write(e,t){const n=t>0?$r(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:jt)|(null===r?0:Ut)|(null===s?0:32);if(e.writeInfo(i),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 fn()})(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===Mr?(e.writeParentInfo(!1),e.writeLeftID(t)):fn();null!==s&&e.writeString(s)}this.content.write(e,t)}}const Li=(e,t)=>Pi[31&t](e),Pi=[()=>{fn()},e=>new pi(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 bi(n)},e=>new fi(e.readBuf()),e=>new ki(e.readString()),e=>new mi(e.readJSON()),e=>new vi(e.readKey(),e.readJSON()),e=>new Ti(Si[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new _i(n)},e=>new yi(gi(e.readString(),e.readAny())),()=>{fn()}];class Ri extends di{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){fn()}write(e,t){e.writeInfo(10),qt(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Mi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Ni="__ $YJS$ __";function $i(e,t,n){var r,s,i;if(!e.dx._allTables[t])return;const o=null===(i=null===(s=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}Mi[Ni],Mi[Ni]=!0;const Bi=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function Fi(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=Ki(e,t,n),s=this.cache[r];return s?s.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:s}=e.meta;if(!n||!s||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const i=Ki(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&Bi.unregister(o),this.cache[i]=new WeakRef(e),Bi.register(e,{cache:this.cache,key:i},e)},delete(e){Bi.unregister(e);const t=Ki(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 Wi=new WeakSet;function Vi(e){if(Wi.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Ki(e,t,n){return`${e}[${t}].${n}`}let Hi=null;function Ji(e){Hi=e}function zi(){}const qi=new WeakMap;function Yi(){return e.Dexie.Events(null,"load","sync","error")}class Gi{static getOrCreateDocument(e,t,n,r){var s,i;const o=Fi(e),l=null===(i=null===(s=e.table(t).schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;if(!l)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,s,i){let o=t.find(n,i,r);return o||(o=new kr({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",(()=>{Wi.add(o),t.delete(o)})),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=qi.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 Gi(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,qi.set(e,r)),r}static release(e){if(!e||Wi.has(e))return;const t=qi.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(Gi.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return qi.get(e)}static get currentUpdateRow(){return Hi}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((t,n)=>{this.doc?this.doc.isLoaded?t():this._error?n(this._error):Wi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",t),this.on("error",n),this.doc.on("destroy",(()=>n(new e.Dexie.AbortError("Document was destroyed before loaded"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise(((t,n)=>{this.doc?this.doc.isSynced?t():this._error?n(this._error):Wi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",t),this.on("error",n),this.doc.on("destroy",(()=>n(new e.Dexie.AbortError("Document was destroyed before synced"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(t){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Yi(),this.doc=t,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]=()=>Gi.release(t)),t.on("load",(()=>this.on("load").fire())),t.on("sync",(e=>!1!==e&&this.on("sync").fire())),t.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:n,parentTable:r,parentId:s,updatesTable:i}=t.meta||{};if(!n||!r||!i)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(i))throw new Error(`Table ${r} or ${i} not found in db`);Vi(t),this.stopObserving=function(t,n,r,s,i,o){let l=0,c=!0;const a=e.liveQuery((()=>{Vi(n);const t=r.table(i);return Promise.all([(l>0?t.where("i").between(l,1/0,!1).toArray().then((t=>t.filter((t=>0===e.cmp(t.k,o))))):t.where({k:o}).toArray()).then((e=>e)),r.table(s).where(":id").equals(o).toArray()])})).subscribe((([e,r])=>{e.length>0&&(l=e[e.length-1].i),0!==r.length?(Vi(n),e.length>0&&rs(n,(()=>{e.forEach((e=>{try{Ji(e),Tr(n,e.u)}finally{Ji(null)}}))}),t,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()}),(e=>{t.on("error").fire(e)})),u=(e,n)=>{n!==t&&r.table(i).add({k:o,u:e,f:1}).then((e=>{e===l-1&&++l})).catch((e=>{t.on("error").fire(e)}))},d=()=>{a.unsubscribe(),n.off("updateV2",u),n.off("destroy",d)};return n.on("updateV2",u),n.on("destroy",d),d}(this,t,n,r,i,s),Gi.on("new").fire(this)}destroy(){var e;qi.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Yi(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Qi(t,n){return r(this,void 0,void 0,(function*(){var s;const i={};let o,l=!1;for(const c of t)try{switch(c.type){case"u-s":{const e=$i(n,c.table,c.prop);if(e){const t={k:c.k,u:c.u};c.r&&(t.r=c.r,o=c.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=$i(n,c.table,c.prop);e&&(yield n.transaction("rw",e,(t=>r(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(yt);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:yt}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})))));break}case"u-reject":{const t=$i(n,c.table,c.prop);if(!t)break;const r=null===(s=yield t.get(c.i))||void 0===s?void 0:s.k;if(null!=r){yield n.transaction("rw",t,(n=>(n.idbtrans._rejecting_y_ypdate=!0,t.where("i").aboveOrEqual(c.i).filter((t=>0===e.cmp(t.k,r)&&1==(1&(t.f||0)))).delete())));const s=Gi.getDocCache(n.dx).find(c.table,r,c.prop);s&&s.destroy()}break}case"in-sync":{const e=Gi.getDocCache(n.dx).find(c.table,c.k,c.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=c.yServerRev;break;case"outdated-server-rev":l=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:l,yServerRevision:o}}))}Gi.on=e.Dexie.Events(null,{new:[function(e,t){return e===zi?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===zi?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then((function(){return t.apply(r,i)}))}return t.apply(this,arguments)}}]}),Gi.getDocCache=Fi,e.Dexie.DexieYProvider?Gi=e.Dexie.DexieYProvider||Gi:e.Dexie.DexieYProvider=Gi;const Xi=1,Zi=2,eo=3;function to(t,n,s){return r(this,arguments,void 0,(function*(t,n,{yDownloadedRealms:s,realms:c}){if(s&&c&&c.every((e=>"*"===s[e])))return;const a=yield xe(t),u={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(u.Authorization=`Bearer ${a.accessToken}`);const d=yield fetch(`${n}/y/download`,{body:nt.stringify({downloadedRealms:s||{}}),method:"POST",headers:u,credentials:"include"});if(!d.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${d.status}`);yield async function(e,...t){var n,r,s;let i=e();for(let e=0;e<t.length;e++)i=t[e](i);try{for(var o,c=!0,a=l(i);!(n=(o=await a.next()).done);c=!0)o.value,c=!1}catch(e){r={error:e}}finally{try{c||n||!(s=a.return)||await s.call(a)}finally{if(r)throw r.error}}}(function(e){return function(){return o(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 i(t.read());if(e)return yield i(void 0);yield yield i(n)}}finally{t.releaseLock()}}))}}(d),be,(function(s){return o(this,arguments,(function*(){var o,c,a,u;let d=null,h=null,f=null,p=[];function g(e){return r(this,void 0,void 0,(function*(){const r=p[p.length-1];if(p.length>0){if(!d||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const e=$i(t,h,f);e&&(yield e.bulkAdd(p)),p=[]}d&&(h&&f&&r||e)&&(yield t.$syncState.update("syncState",(t=>{const n=t.yDownloadedRealms||{};n[d]=e?"*":{tbl:h,prop:f,key:r.k},t.yDownloadedRealms=n})))}))}try{try{for(var y,m=!0,v=l(s);!(o=(y=yield i(v.next())).done);m=!0){u=y.value,m=!1;const e=new ae(u);for(;ue(e);)switch(he(e)){case Xi:yield i(g(!0)),d=pe(e);break;case Zi:yield i(g(!1)),h=pe(e),f=pe(e);break;case eo:{const t=ve(e),n=de(e);p.push({k:t,u:n});break}}yield i(g(!1))}}catch(e){c={error:e}}finally{try{m||o||!(a=v.return)||(yield i(a.call(v)))}finally{if(c)throw c.error}}yield i(g(!0))}catch(t){throw t instanceof e.DexieError||(yield i(g(!1))),t}}))}))}))}const no="currentSyncWorker";function ro(e,t,n,s){return so(e,t,n,s).then((t=>((null==s?void 0:s.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((i=>r(this,void 0,void 0,(function*(){return(null==s?void 0:s.justCheckIfNeeded)?Promise.reject(i):dt&&(null==s?void 0:s.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 ro(e,t,n,Object.assign(Object.assign({},s),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:dt?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function so(e,t,n){return r(this,arguments,void 0,(function*(e,t,n,{isInitialSync:s,cancelToken:i,justCheckIfNeeded:o,purpose:l}={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:u}=t,d=yield e.getCurrentUser(),h=d.isLoggedIn?k(e):[],f=h.map((t=>e.table(S(t.name)))),p=yield e.getPersistedSyncState(),g=d.isLoggedIn,y=g?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return k(e).filter((e=>!n.includes(e.name)))}(e,p):[];ut(i);const m=y.length>0;if(m){if(o)return!0;yield e.transaction("rw",y,(e=>r(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return r(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!==c.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!==c.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==c.userId||(e.owner=t.userId),e.realmId&&e.realmId!==c.userId||(e.realmId=t.userId))})))}))}(y,d,null==p?void 0:p.realms)})))),ut(i)}const[v,b,w,{yMessages:_,lastUpdateIds:x}]=yield e.transaction("r",e.tables,(()=>r(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let s=yield e.$baseRevs.toArray();s=s.filter((e=>h.some((t=>t.name===e.tableName))));let o=yield I(f,e);const l=yield function(e,t){return r(this,void 0,void 0,(function*(){const n=[],r={};for(const s of t)if(s.schema.yProps)for(const t of s.schema.yProps){const i=e.table(t.updatesTable),o=yield i.get(yt),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),u=yield mt(i,a);u.length>0&&(r[i.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<l)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:i,i:o}of Object.values(d)){const l=1===i.length?i[0]:cs(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=os(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,h);if(ut(i),m){const e=[...(null==p?void 0:p.realms)||[],...(null==p?void 0:p.inviteRealms)||[]],c=yield function(e,t,n,s){return r(this,void 0,void 0,(function*(){const i=`upload-${A(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(s||[]);return(yield Promise.all(e.map((e=>r(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const s=n[e.name],l=(null==s?void 0:s.generatedGlobalId)?e.filter((e=>{return r(e),!o.has(e.realmId||"")&&(t=r(e),!(n=null==s?void 0:s.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})):e.filter((e=>{const t=r(e);return!o.has(e.realmId||"")&&j(t)})),c=yield l.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.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[]}))}(y,d,n,e);return ut(i),o=o.concat(c),[o,t,s,l]}return[o,t,s,l]})))),C=v.some((e=>e.muts.some((e=>e.keys.length>0))))||_.some((e=>"u-c"===e.type));if(o)return C;if("push"===l&&!C)return!1;const D=ft(v,null==b?void 0:b.latestRevisions),O=(null==b?void 0:b.clientIdentity)||T(16);ut(i);const U=yield at(v,_,b,w,e,u,n,O,d),{done:L,newSyncState:P}=yield e.transaction("rw",e.tables,(t=>r(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))U.schema[e]&&(n[e]=U.schema[e]);yield e.$syncState.put(n,"schema");const s=yield I(f,e,{since:D});for(const t of f){const n=E(t.name);if(s.some((e=>e.table===n&&e.muts.length>0))){if(D[n]){const r=D[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()])}ft(s,D),yield ht(e,n,D,U.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return r(this,void 0,void 0,(function*(){const r=new Set,s=new Set,i=n?n.realms:[],o=n?n.inviteRealms:[],l=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)l.has(e)||(s.add(e),c.has(e)||r.add(e));for(const e of o.concat(i))c.has(e)||r.add(e);if(r.size>0||s.size>0){const t=k(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:s;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(s.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of s)delete n.yDownloadedRealms[e]}))}(e,U,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:O};g&&(o.syncedTables=h.map((e=>e.name)).concat(y.map((e=>e.name)))),o.latestRevisions=D,o.remoteDbId=U.dbId,o.initiallySynced=!0,o.realms=U.realms,o.inviteRealms=U.inviteRealms,o.serverRevision=U.serverRevision,o.yServerRevision=U.serverRevision,o.timestamp=new Date,delete o.error;const l=io(U.changes,s);if(yield gt(l,e),U.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:s}=yield Qi(U.yMessages,e);s&&(o.yServerRevision=s),yield function(e,t,n){return r(this,void 0,void 0,(function*(){var s,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(s=a[t])&&void 0!==s||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=a[e])&&void 0!==i||(a[e]={}),a[e].receivedUntil=n;const u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=a[e],s=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,i=null!==(c=null!==(l=null==t?void 0:t.receivedUntil)&&void 0!==l?l:(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,(()=>r(this,void 0,void 0,(function*(){const t=yield n.table(e).get(yt);t?(t.unsentFrom=Math.max(s,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:yt,unsentFrom:s,receivedUntil:i})}))))}}))}(x,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===s.length,newSyncState:o}}))));if(!L)return yield ct(e),yield so(e,t,n,{isInitialSync:s,cancelToken:i});const R=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),M=!!U.yMessages;if(R&&M)try{yield to(e,u,P)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function io(e,t){const n={};R(n,e);const r={};return R(r,t),function(e,t){var n,r,s;for(const[i,o]of Object.entries(t))for(const[t,l]of Object.entries(o))switch(l.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(s=e[i])||void 0===s?void 0:s[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(l.mod))O(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(l.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=T(16));const n={};for(const[t,r]of Object.entries(e))for(const[e,s]of Object.entries(r)){const r=n[t]||(n[t]={});(r[s.type]||(r[s.type]=[])).push(Object.assign({key:e},s))}const r=[];for(const[e,s]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(s))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 oo=10,lo=1e4,co=1e3;function ao(s){const i=[],o=new t.BehaviorSubject(!0),l=new t.BehaviorSubject(null);let c=!1,a=new Array(oo).fill(0);return l.subscribe((()=>r(this,void 0,void 0,(function*(){if(!c&&i.length>0){c=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return r(this,void 0,void 0,(function*(){for(var o,l,c,a,u,d;i.length>0;){const h=i.shift();try{yield t.firstValueFrom(s.cloud.syncState.pipe(n.filter((({phase:e})=>"in-sync"===e||"error"===e))));const i=s.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const t=s.cloud.currentUser.value,n=yield Ie(s.cloud.options.databaseUrl,t);yield s.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data});break;case"realm-added":(null===(o=null==i?void 0:i.realms)||void 0===o?void 0:o.includes(h.realm))||(null===(l=null==i?void 0:i.inviteRealms)||void 0===l?void 0:l.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==i?void 0:i.realms)||void 0===c?void 0:c.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(a=null==i?void 0:i.realms)||void 0===a?void 0:a.includes(h.realm))||(null===(u=null==i?void 0:i.inviteRealms)||void 0===u?void 0:u.includes(h.realm)))&&(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield s.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(d=s.cloud.syncState.value)||void 0===d?void 0:d.phase)){y(s,"pull");break}yield s.transaction("rw",s.dx.tables,(t=>r(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,r,i]=yield Promise.all([s.getSchema(),s.getPersistedSyncState(),s.getCurrentUser()]);if(!r||!n||!i)return;if(h.baseRev!==r.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof r.serverRevision&&"object"!=typeof r.serverRevision||y(s,"pull"));if((yield e.waitFor(_(r)))!==h.realmSetHash)return void y(s,"pull");let o=[];if(i.isLoggedIn){const e=k(s).map((e=>s.table(S(e.name))));o=yield I(e,s)}if(h.changes.length>0){const e=io(h.changes,o);yield gt(e,s)}r.latestRevisions=ft(o,r.latestRevisions),r.serverRevision=h.newRev,yield ht(s,n,r.latestRevisions,h.newRev),yield s.$syncState.put(r,"syncState")}))))}}catch(e){}}}))}()}finally{a[a.length-1]-a[0]<lo&&(yield new Promise((e=>setTimeout(e,co)))),c=!1,o.next(!0)}}})))),{enqueue:function(e){i.push(e),l.next(null)},readyToServe:o}}const uo=new WeakMap,ho={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let fo=0;function po(e){"vip"in e&&(e=e.vip);let n=uo.get(e.cloud);if(!n){const r=new t.Subject;let s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`);r.id=++fo;let o=!1;n={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 o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||c)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema").then((e=>{if(e)for(const r of n.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(t=r.schema.primKey.keyPath)?t:t?"["+[].join.call(t,"+")+"]":"");var t;return e})),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`)}};Object.assign(n,l),n.messageConsumer=ao(n),n.messageProducer=new t.Subject,uo.set(e.cloud,n)}return n}const go=new WeakMap;class yo{constructor(e,t){go.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new yo(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return r(this,void 0,void 0,(function*(){go.get(this).table("$logins").put(this)}))}}function mo(e,n){return t.firstValueFrom(t.from(e).pipe(t.filter(n)))}function vo(e){return r(this,void 0,void 0,(function*(){const t=yield bo(e);if(t){if(!(yield function(e,t,n){return r(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 _e(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 bo(e,{deleteUnsyncedData:!0})}}))}function bo(e){return r(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,s]=yield e.dx.transaction("rw",e.dx.tables,(n=>r(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const s=n.storeNames.filter((e=>e.endsWith("_mutations"))),i=(yield Promise.all(s.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}))));return s&&(yield mo(e.cloud.currentUser,(e=>e.userId===c.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function wo(e,...t){globalThis.console[e](...t)}function _o(e,t){return r(this,void 0,void 0,(function*(){var n;const s=yield e.getCurrentUser(),i=s.userId;if(s.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok")&&s.accessToken&&(!s.accessTokenExpiration||s.accessTokenExpiration.getTime()>Date.now()))return!1;if(s.refreshToken&&(!s.refreshTokenExpiration||s.refreshTokenExpiration.getTime()>Date.now()))return yield xe(e),!1}const o=new yo(e,{claims:{},lastLogin:new Date(0)});return yield Ce(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return r(this,arguments,void 0,(function*({public_key:n,hints:r}){var s;let i;const o=null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl;if(!o)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))i={demo_user:yield Se(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)i={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield Se(t,"Enter email address",null==r?void 0:r.email);i=/@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 l=yield fetch(`${o}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==l.status){const e=yield l.text();throw yield ke(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new st(l,e)}const c=yield l.json();if("tokens"===c.type||"error"===c.type)return c;if("otp"===i.grant_type&&"email"in i){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${o}/token`);const e=yield Ee(t,i.email),r=Object.assign(Object.assign({},i),{otp:e||"",otp_id:c.otp_id,public_key:n});let s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===s.status;){const e=yield s.text();r.otp=yield Ee(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield s.text();throw new st(s,e)}return yield s.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==c.userId&&o.userId!==i&&(yield vo(e)),yield function(e,t){return r(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>r(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&&(wo("debug","Login context property names:",Object.keys(t)),wo("debug","Login context property names:",Object.keys(t)),wo("debug","Login context:",t),wo("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield mo(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,o),y(e,"pull"),o.userId!==i}))}const ko="undefined"!=typeof InstallTrigger,So="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Eo=So?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,xo=So&&Eo<=605||ko,Co="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:Io}={};function Ao(e){return Io.call(e).slice(8,-1)}function Do(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 Oo=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let To=0;function Uo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();To>=s?++To:To=s,r[0]=To/1099511627776,r[1]=To/4294967296,r[2]=To/16777216,r[3]=To/65536,r[4]=To/256,r[5]=To;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+$e(new Uint8Array(n.buffer))+(t||"")}function jo(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const s=n.table(r);return Object.assign(Object.assign({},s),{mutate:n=>{var i,o;const l=n.trans;if("versionchange"===l.mode&&(l.disableChangeTracking=!0,l.disableAccessControl=!0),l.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const l=null===(i=t.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!t.initiallySynced){const e=Do(s.schema.primaryKey,n);return s.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 s.mutate(n)}))}return function(n,i){let o=null;const l=Do(s.schema.primaryKey,n);return l.forEach(((c,a)=>{if(void 0===c){const r=n.values[a].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);l[a]=Uo(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=e.deepClone(o[a]),e.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\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.`)})),s.mutate(Object.assign(Object.assign({},n),{keys:l,values:o||n.values}))}(n,l.idPrefix)}if(null==l?void 0:l.markedForSync){Do(s.schema.primaryKey,n).forEach(((t,n)=>{if(!j(t)){const n=Array.isArray(t)?t.map(Ao).join(","):Ao(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 s.mutate(n)}})}})}}let Lo=0;function Po(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=s.length,o=(i>0?s[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>{r.splice(r.indexOf(o))}));return r.push(o),o}}function Ro(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(s.length>0?s[s.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,s)=>Promise.resolve(r).then((e=>n[s]={status:"fulfilled",value:e}),(e=>n[s]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>{s.shift()}));var o;return s.push(i),i}}const Mo=new t.BehaviorSubject(new Set);function No(e){var t,n,r,s;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===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)}function $o({currentUserObservable:t,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const s=new Set(r.schema.tables.map((e=>e.name))),i=r.schema.tables.filter((e=>!/^\$/.test(e.name))),o=new Map;for(const e of i){const t=`$${e.name}_mutations`;s.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(e,s)=>{let i;if("readwrite"===s){const t=e.filter((e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync})).map((e=>S(e)));i=r.transaction([...e,...t],s)}else i=r.transaction(e,s);if("readwrite"===s){i.txid=A(16),i.opCount=0,i.currentUser=t.value,Mo.value.add(i),Mo.next(Mo.value);const e=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",e),i.removeEventListener("abort",e),Mo.value.delete(i),Mo.next(Mo.value)},r=()=>{i.mutationsAdded&&!No(n)&&y(n,"push"),e()};i.addEventListener("complete",r),i.addEventListener("error",e),i.addEventListener("abort",e)}return i},table:t=>{const s=r.table(t);if(/^\$/.test(t))return t.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===t?Object.assign(Object.assign({},s),{mutate:e=>s.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>Promise.reject(e)))}):s;const{schema:i}=s,l=o.get(t);return l?function(e){const t="$lock"+ ++Lo;return Object.assign(Object.assign({},e),{count:Po(e.count,t),get:Po(e.get,t),getMany:Po(e.getMany,t),openCursor:Po(e.openCursor,t),query:Po(e.query,t),mutate:Ro(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:e=>{var r,o,l;const a=e.trans;return a.txid?a.disableChangeTracking?s.mutate(e):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===e.type?s.query({query:{range:e.range,index:i.primaryKey},trans:e.trans,values:!1}).then((t=>c({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):c(e):s.mutate(e):s.mutate(e)}})):s;function c(r){var o,c;const a=r.trans,u=null===(c=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===c?void 0:c[t],{txid:d,currentUser:{userId:h}}=a,{type:f}=r,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 s.mutate(r).then((t=>{var n;const{numFailures:s,failures:o}=t;let c="delete"===f?r.keys:t.results,y="values"in r?r.values:[],m="changeSpec"in r?r.changeSpec:void 0,v="updates"in r?r.updates:void 0;if(s&&(c=c.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})),m&&(m=g(m),0===Object.keys(m).length))return t;if(v){let t=v.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new e.RangeSet;let s=!1;for(let e=0,i=t.length;e<i;++e)Object.keys(t[e]).length>0?(n.keys.push(v.keys[e]),n.changeSpecs.push(t[e]),r.addKey(v.keys[e])):s=!0;if(v=n,s){let e=[],t=[];for(let n=0,s=c.length;n<s;++n)r.hasKey(c[n])&&(e.push(c[n]),t.push(y[n]));c=e,y=t}}}const b=Date.now();let w="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===i.primaryKey.keyPath?null:r.criteria.index}):void 0;if(u&&(null==w?void 0:w.index)){const e=null===(n=i.indexes.find((e=>e.name===w.index)))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some((e=>null==u?void 0:u.includes(e)))&&(w=void 0)}const _="delete"===r.type?{type:"delete",ts:b,opNo:p,keys:c,criteria:w,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:b,opNo:p,keys:c,txid:d,userId:h,values:y}:w&&m?{type:"modify",ts:b,opNo:p,keys:c,criteria:w,changeSpec:m,txid:d,userId:h}:m?{type:"update",ts:b,opNo:p,keys:c,changeSpecs:c.map((()=>m)),txid:d,userId:h}:v?{type:"update",ts:b,opNo:p,keys:v.keys,changeSpecs:v.changeSpecs,txid:d,userId:h}:{type:"upsert",ts:b,opNo:p,keys:c,values:y,txid:d,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(_.isAdditionalChunk=!0),c.length>0||w?l.mutate({type:"add",trans:a,values:[_]}).then((()=>(a.mutationsAdded=!0,t))):t}))}}})}}}function Bo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},ho),n);Object.keys(ho).forEach((e=>{const t=i[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())),s=ho[e].split(",").map((e=>e.trim())),o=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==s[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(ho[e])}`);for(let t=1;t<s.length;++t){const n=s[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(i[e]+=`,${n}`)}}));const o=t.cloud.schema||(t.cloud.schema={}),l=new Set;Object.keys(i).forEach((e=>{const t=i[e],n=o[e]||(o[e]={});null!=t?(/^\@/.test(t)&&(i[e]=i[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,s=e.length;t<s&&n.length<3;++t)(Oo.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,s,i;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;)s=n,r=(1&(i=e)?s[0].toUpperCase():s[0].toLowerCase())+(2&i?s[1].toUpperCase():s[1].toLowerCase())+(4&i?s[2].toUpperCase():s[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,l),l.add(n.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,i[`$${e}_mutations`]=null)}));const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(s=t.yProps)||void 0===s?void 0:s.length){const n=o[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return c}}function Fo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const Wo=new t.BehaviorSubject(!0),Vo=new t.BehaviorSubject(!0);Wo.pipe(n.switchMap((e=>e?t.of(!0):t.of(!1).pipe(n.delay(2e4)))),n.distinctUntilChanged()).subscribe(Vo);const Ko="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),Ho=Ko.pipe(n.filter((()=>"hidden"===document.visibilityState))),Jo=Ko.pipe(n.filter((()=>"visible"===document.visibilityState))),zo="undefined"!=typeof window?t.merge(Jo,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),Ho,zo).pipe(n.map((()=>"visible"===document.visibilityState)),n.tap((e=>{Wo.value!==e&&Wo.next(e)})),n.switchMap((e=>e?t.of(0).pipe(n.delay(16e4),n.tap((()=>Wo.next(!1)))):t.of(0)))).subscribe((()=>{}));class qo extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function Yo(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 Go=new WeakMap,Qo=new WeakMap;function Xo(e){let n=Qo.get(e);return n||(n=new t.Subject,Qo.set(e,n)),n}class Zo extends t.Observable{constructor(e,t,n,r,s,i,o,l){super((c=>new tl(e,t,n,r,s,l,c,i,o)))}}let el=0;class tl extends t.Subscription{constructor(e,t,n,r,s,i,o,l,c){super((()=>this.teardown())),this.id=++el,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=s,this.user=i,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=l,this.webSocketStatus=c,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 r(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 n=this.user.accessTokenExpiration;if(n&&n<new Date)return void this.subscriber.error(new qo);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>r(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 s=new URL(this.databaseUrl);s.protocol="http:"===s.protocol?"ws":"wss";const i=new URLSearchParams;if(this.subscriber.closed)return;i.set("v","2"),this.rev&&i.set("rev",this.rev),this.yrev&&i.set("yrev",this.yrev),i.set("realmsHash",this.realmSetHash),i.set("clientId",this.clientIdentity),i.set("dxcv",this.db.cloud.version),this.user.accessToken&&i.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${s}/changes?${i}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?nt.parse(e.data):function(e){const t=new ae(e),n=pe(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:pe(t)};const r=pe(t),s=pe(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(ye(t))};default:{const e=ve(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:s,k:e};case"aware":return{type:n,table:r,prop:s,k:e,u:de(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:ve(t),sv:ve(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:de(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:de(t),i:Number(ye(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:de(t),r:t.pos<t.arr.length&&pe(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=Gi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Go.get(e))(e);if(n){Yo(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Gi.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&Xo(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?Qi([t],this.db).then((e=>r(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=$i(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(yt,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let n=!1;yield new Promise(((e,t)=>{o.onopen=t=>{n=!0,e(null)},o.onerror=e=>{if(n)this.reconnect();else{const n=e.error||new Error("WebSocket Error");this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}}})),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(nt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(ie(e)))}))),this.user.isLoggedIn&&!No(this.db)&&this.subscriptions.add(function(n){const s=C(n.tables.filter((e=>{var t,r;return(null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e.name])||void 0===r?void 0:r.markedForSync)&&e.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return t.merge(...s.map((({table:s,ydocProp:i,updatesTable:o})=>{const l=n.table(o);return t.from(l.get(yt)).pipe(t.switchMap((n=>{let o=(null==n?void 0:n.unsentFrom)||1;return t.from(e.liveQuery((()=>r(this,void 0,void 0,(function*(){return(yield mt(l,o)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:s,prop:i,k:e.k,u:e.u,i:e.i})))}))))).pipe(t.tap((e=>{e.length>0&&(o=e.at(-1).i+1)})))})))}))).pipe(t.mergeMap((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class nl extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function rl(e){return r(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield t.firstValueFrom(zo)}))}function sl(e){return r(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 ro(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const il=new WeakMap;function ol(e,t,n,s){const i=il.get(e);if(i){if(i.pull||"push"===(null==s?void 0:s.purpose))return i.promise;{let r=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(r=!0)}));return i.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!r)return ol(e,t,n,s)}))}}const o=function(){return r(this,void 0,void 0,(function*(){try{yield ct(e),yield Fo(e,no,(()=>ro(e,t,n,s))),il.delete(e)}catch(t){throw il.delete(e),t}}))}();return il.set(e,{promise:o,pull:"push"!==(null==s?void 0:s.purpose)}),o}const ll=1e3;function cl(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout((()=>{const d=c?"pull":"push";o=Date.now(),ol(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:d}).then((()=>{if(s.cancelled)h();else if(c||a)return c=!1,a=!1,l();u=!1,i=0,o=0})).catch((e=>{if(s.cancelled)h(),u=!1,i=0,o=0;else if(r<5){const e=[0,20,40,300,900][r]*ll;i=Date.now()+e,o=0,setTimeout((()=>l(r+1)),e)}else u=!1,i=0,o=0}))}),0)}let c=!1,a=!1,u=!1;const d=e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),u?i||o>0&&Date.now():(u=!0,l()))},h=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{d(e||"pull")}))},stop:h}}function al(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var ul,dl,hl,fl,pl,gl={},yl=[],ml=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function vl(e,t){for(var n in t)e[n]=t[n];return e}function bl(e){var t=e.parentNode;t&&t.removeChild(e)}function wl(e,t,n){var r,s,i,o={};for(i in t)"key"==i?r=t[i]:"ref"==i?s=t[i]:o[i]=t[i];if(arguments.length>2&&(o.children=arguments.length>3?ul.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===o[i]&&(o[i]=e.defaultProps[i]);return _l(e,o,r,s,null)}function _l(e,t,n,r,s){var i={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==s?++hl:s};return null==s&&null!=dl.vnode&&dl.vnode(i),i}function kl(e){return e.children}function Sl(e,t){this.props=e,this.context=t}function El(e,t){if(null==t)return e.__?El(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?El(e):null}function xl(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 xl(e)}}function Cl(e){(!e.__d&&(e.__d=!0)&&fl.push(e)&&!Il.__r++||pl!==dl.debounceRendering)&&((pl=dl.debounceRendering)||setTimeout)(Il)}function Il(){for(var e;Il.__r=fl.length;)e=fl.sort((function(e,t){return e.__v.__b-t.__v.__b})),fl=[],e.some((function(e){var t,n,r,s,i,o;e.__d&&(i=(s=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=vl({},s)).__v=s.__v+1,Pl(o,s,r,t.__n,void 0!==o.ownerSVGElement,null!=s.__h?[i]:null,n,null==i?El(s):i,s.__h),Rl(n,s),s.__e!=i&&xl(s)))}))}function Al(e,t,n,r,s,i,o,l,c,a){var u,d,h,f,p,g,y,m=r&&r.__k||yl,v=m.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?_l(null,f,null,null,f):Array.isArray(f)?_l(kl,{children:f},null,null,null):f.__b>0?_l(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=m[u])||h&&f.key==h.key&&f.type===h.type)m[u]=void 0;else for(d=0;d<v;d++){if((h=m[d])&&f.key==h.key&&f.type===h.type){m[d]=void 0;break}h=null}Pl(e,f,h=h||gl,s,i,o,l,c,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=c=Dl(f,c,e):c=Ol(e,f,h,m,p,c),"function"==typeof n.type&&(n.__d=c)):c&&h.__e==c&&c.parentNode!=e&&(c=El(h))}for(n.__e=g,u=v;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=El(r,u+1)),$l(m[u],m[u]));if(y)for(u=0;u<y.length;u++)Nl(y[u],y[++u],y[++u])}function Dl(e,t,n){for(var r,s=e.__k,i=0;s&&i<s.length;i++)(r=s[i])&&(r.__=e,t="function"==typeof r.type?Dl(r,t,n):Ol(n,r,r,s,r.__e,t));return t}function Ol(e,t,n,r,s,i){var o,l,c;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||s!=i||null==s.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(s),o=null;else{for(l=i,c=0;(l=l.nextSibling)&&c<r.length;c+=2)if(l==s)break e;e.insertBefore(s,i),o=i}return void 0!==o?o:s.nextSibling}function Tl(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||ml.test(t)?n:n+"px"}function Ul(e,t,n,r,s){var i;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||Tl(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Tl(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?Ll:jl,i):e.removeEventListener(t,i?Ll:jl,i);else if("dangerouslySetInnerHTML"!==t){if(s)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 jl(e){this.l[e.type+!1](dl.event?dl.event(e):e)}function Ll(e){this.l[e.type+!0](dl.event?dl.event(e):e)}function Pl(e,t,n,r,s,i,o,l,c){var a,u,d,h,f,p,g,y,m,v,b,w,_,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,l=t.__e=n.__e,t.__h=null,i=[l]),(a=dl.__b)&&a(t);try{e:if("function"==typeof k){if(y=t.props,m=(a=k.contextType)&&r[a.__c],v=a?m?m.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,v):(t.__c=u=new Sl(y,v),u.constructor=k,u.render=Bl),m&&m.sub(u),u.props=y,u.state||(u.state={}),u.context=v,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=vl({},u.__s)),vl(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,v),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(y,u.__s,v)||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,v),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(h,f,p)}))}if(u.context=v,u.props=y,u.__v=t,u.__P=e,b=dl.__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=vl(vl({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===kl&&null==a.key?a.props.children:a,Al(e,Array.isArray(_)?_:[_],t,n,r,s,i,o,l,c),u.base=t.__e,t.__h=null,u.__h.length&&o.push(u),g&&(u.__E=u.__=null),u.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=Ml(n.__e,t,n,r,s,i,o,c);(a=dl.diffed)&&a(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=l,t.__h=!!c,i[i.indexOf(l)]=null),dl.__e(e,t,n)}}function Rl(e,t){dl.__c&&dl.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){dl.__e(e,t.__v)}}))}function Ml(e,t,n,r,s,i,o,l){var c,a,u,d=n.props,h=t.props,f=t.type,p=0;if("svg"===f&&(s=!0),null!=i)for(;p<i.length;p++)if((c=i[p])&&"setAttribute"in c==!!f&&(f?c.localName===f:3===c.nodeType)){e=c,i[p]=null;break}if(null==e){if(null===f)return document.createTextNode(h);e=s?document.createElementNS("http://www.w3.org/2000/svg",f):document.createElement(f,h.is&&h),i=null,l=!1}if(null===f)d===h||l&&e.data===h||(e.data=h);else{if(i=i&&ul.call(e.childNodes),a=(d=n.props||gl).dangerouslySetInnerHTML,u=h.dangerouslySetInnerHTML,!l){if(null!=i)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,s){var i;for(i in n)"children"===i||"key"===i||i in t||Ul(e,i,null,n[i],r);for(i in t)s&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||Ul(e,i,t[i],n[i],r)}(e,h,d,s,l),u)t.__k=[];else if(p=t.props.children,Al(e,Array.isArray(p)?p:[p],t,n,r,s&&"foreignObject"!==f,i,o,i?i[0]:n.__k&&El(n,0),l),null!=i)for(p=i.length;p--;)null!=i[p]&&bl(i[p]);l||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&Ul(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&Ul(e,"checked",p,d.checked,!1))}return e}function Nl(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){dl.__e(e,n)}}function $l(e,t,n){var r,s;if(dl.unmount&&dl.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Nl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){dl.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&$l(r[s],t,"function"!=typeof e.type);n||null==e.__e||bl(e.__e),e.__e=e.__d=void 0}function Bl(e,t,n){return this.constructor(e,n)}function Fl(e,t,n){var r,s,i;dl.__&&dl.__(e,t),s=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Pl(t,e=(!r&&n||t).__k=wl(kl,null,[e]),s||gl,gl,void 0!==t.ownerSVGElement,!r&&n?[n]:s?null:t.firstChild?ul.call(t.childNodes):null,i,!r&&n?n:s?s.__e:t.firstChild,r),Rl(i,e)}ul=yl.slice,dl={__e:function(e,t,n,r){for(var s,i,o;t=t.__;)if((s=t.__c)&&!s.__)try{if((i=s.constructor)&&null!=i.getDerivedStateFromError&&(s.setState(i.getDerivedStateFromError(e)),o=s.__d),null!=s.componentDidCatch&&(s.componentDidCatch(e,r||{}),o=s.__d),o)return s.__E=s}catch(t){e=t}throw e}},hl=0,Sl.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=vl({},this.state),"function"==typeof e&&(e=e(vl({},n),this.props)),e&&vl(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Cl(this))},Sl.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Cl(this))},Sl.prototype.render=kl,fl=[],Il.__r=0;const Wl={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 Vl({children:e,className:t}){return wl("div",{className:t},wl("div",{style:Wl.Darken}),wl("div",{style:Wl.DialogOuter},wl("div",{style:Wl.DialogInner},e)))}var Kl,Hl,Jl,zl,ql=0,Yl=[],Gl=[],Ql=dl.__b,Xl=dl.__r,Zl=dl.diffed,ec=dl.__c,tc=dl.unmount;function nc(e,t){dl.__h&&dl.__h(Hl,e,ql||t),ql=0;var n=Hl.__H||(Hl.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:Gl}),n.__[e]}function rc(e){return ql=1,function(e,t,n){var r=nc(Kl++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):uc(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=Hl,!Hl.u)){Hl.u=!0;var s=Hl.shouldComponentUpdate;Hl.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var i=r.__c.__H.__.filter((function(e){return e.__c}));if(i.every((function(e){return!e.__N})))return!s||s.call(this,e,t,n);var o=!1;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}})),!!o&&(!s||s.call(this,e,t,n))}}return r.__N||r.__}(uc,e)}function sc(e){return ql=5,function(e,t){var n=nc(Kl++,7);return ac(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function ic(){for(var e;e=Yl.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(lc),e.__H.__h.forEach(cc),e.__H.__h=[]}catch(t){e.__H.__h=[],dl.__e(t,e.__v)}}dl.__b=function(e){Hl=null,Ql&&Ql(e)},dl.__r=function(e){Xl&&Xl(e),Kl=0;var t=(Hl=e.__c).__H;t&&(Jl===Hl?(t.__h=[],Hl.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Gl,e.__N=e.i=void 0}))):(t.__h.forEach(lc),t.__h.forEach(cc),t.__h=[])),Jl=Hl},dl.diffed=function(e){Zl&&Zl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Yl.push(t)&&zl===dl.requestAnimationFrame||((zl=dl.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),oc&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);oc&&(t=requestAnimationFrame(n))})(ic)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Gl&&(e.__=e.__V),e.i=void 0,e.__V=Gl}))),Jl=Hl=null},dl.__c=function(e,t){t.some((function(e){try{e.__h.forEach(lc),e.__h=e.__h.filter((function(e){return!e.__||cc(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],dl.__e(n,e.__v)}})),ec&&ec(e,t)},dl.unmount=function(e){tc&&tc(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{lc(e)}catch(e){t=e}})),t&&dl.__e(t,n.__v))};var oc="function"==typeof requestAnimationFrame;function lc(e){var t=Hl,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Hl=t}function cc(e){var t=Hl;e.__c=e.__(),Hl=t}function ac(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function uc(e,t){return"function"==typeof t?t(e):t}function dc({title:e,type:t,alerts:n,fields:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=rc({}),u=sc(null);return function(e,t){var n=nc(Kl++,4);!dl.__s&&ac(n.__H,t)&&(n.__=e,n.i=t,Hl.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),wl(Vl,{className:"dxc-login-dlg"},wl(kl,null,wl("h3",{style:Wl.WindowHeader},e),n.map((e=>wl("p",{style:Wl.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(e)))),wl("form",{onSubmit:e=>{e.preventDefault(),l(c)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],s)=>wl("label",{style:Wl.Label,key:s},n?`${n}: `:"",wl("input",{ref:0===s?u:void 0,type:t,name:e,autoComplete:"on",style:Wl.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const s=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 i=Object.assign(Object.assign({},c),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&l(i)}})))))),wl("div",{style:Wl.ButtonsDiv},wl(kl,null,wl("button",{type:"submit",style:Wl.Button,onClick:()=>l(c)},s),i&&wl("button",{style:Wl.Button,onClick:o},i))))}class hc extends Sl{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?wl(dc,Object.assign({},t)):null}}function fc(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const pc=fc((e=>new t.BehaviorSubject(c)));function gc(e,n){let r=n,s=t.from(e).pipe(t.map((e=>r=e)),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const i=new t.Observable((e=>{let t=!1;const n=s.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return i.getValue=()=>r,i}const yc=fc((t=>gc(e.liveQuery((()=>t.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})))),{}))),mc=fc((t=>gc(pc(t._novip).pipe(n.switchMap((n=>e.liveQuery((()=>t.transaction("r","realms","members",(()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}})));function vc(...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,s=t[e];t[e]=[...new Set([...s,...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 bc=fc((e=>function(e,n){let r;const s=e.pipe(t.map((e=>r=n(e))));return s.getValue=()=>void 0!==r?r:r=n(e.getValue()),s}(gc(t.combineLatest([mc(e._novip),yc(e._novip)]).pipe(n.map((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:c.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const s=t.map((t=>{const s=e.filter((e=>e.realmId===t.realmId)),i=s.map((e=>e.permissions)).filter((e=>e)),o=C(s.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:"*"}:vc(...i,...o)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return s}))));class wc{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 _c=fc((s=>{const i=pc(s._novip).pipe(n.switchMap((t=>e.liveQuery((()=>s.members.where({email:t.email||""}).toArray()))))),o=bc(s._novip),l=mc(s._novip);return gc(t.combineLatest([i,l,o]).pipe(n.map((([e,t,n])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:n[t.realmId]})}),o=e.reduce(i,{}),l=t.selfMembers.reduce(i,o);return Object.values(l).filter((e=>!e.accepted)).map((e=>Object.assign(Object.assign({},e),{accept(){return r(this,void 0,void 0,(function*(){yield s.members.update(e.id,{accepted:new Date})}))},reject(){return r(this,void 0,void 0,(function*(){yield s.members.update(e.id,{rejected:new Date})}))}})))}))),[])}));function kc(n){return s=>{var i;const o=s.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:l}=o.meta||{};if(!(null===(i=n.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(s,"awareness",{get:()=>c||(c=function(n,s,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=s.meta,u=Yo(n),d=new u.Awareness(s),h=Xo(s);return d.on("update",(({added:e,updated:t,removed:r},l)=>{const a=e.concat(t).concat(r),h=n.cloud.currentUser.value;if("server"!==l&&h.isLoggedIn&&!No(n)){const e=u.encodeAwarenessUpdate(d,a);n.messageProducer.next({type:"aware",table:o,prop:c,k:s.meta.parentId,u:e}),i.destroyed&&n.messageProducer.next({type:"doc-close",table:o,prop:c,k:s.meta.parentId})}})),d.on("destroy",(()=>{u.removeAwarenessStates(d,[s.clientID],"provider destroyed")})),(()=>{r(this,void 0,void 0,(function*(){if(i.destroyed)return;let s=!1,u=1;const d=t.combineLatest([n.cloud.webSocketStatus,h.pipe(t.startWith(null))]).subscribe((([e])=>{if(i.destroyed)return;s="connected"===e;const t=n.cloud.currentUser.value;"connected"===e&&t.isLoggedIn&&!No(n)&&(++u,f().catch((e=>{})))}));function f(){return r(this,void 0,void 0,(function*(){const t=u,d=n.table(a),h=n.$syncState,[f,p]=yield n.transaction("r",h,d,(()=>r(this,void 0,void 0,(function*(){const e=yield d.get(yt),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}))));if(i.destroyed||u!==t||!s)return;const g={type:"doc-open",table:o,prop:c,k:l,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter((t=>0===e.cmp(t.k,l)&&0==(1&(t.f||0)))).toArray();if(!i.destroyed&&u===t&&s){if(y.length>0){const e=cs(y.map((e=>e.u))),t=os(e);g.sv=t}n.messageProducer.next(g)}}))}i.addCleanupHandler(d)}))})(),d}(n,o,s),Go.set(o,c),c)})}}const Sc={nameSuffix:!0};function Ec(s){const i=s.name,o=pc(s),l=[];let a=!1,u=null;s.on("ready",(s=>r(this,void 0,void 0,(function*(){try{yield function(s){return r(this,void 0,void 0,(function*(){var i,c,p,m,v,b,w;d=!1;const k=po(s);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=k.cloud.options)||void 0===i?void 0:i.customLoginGui)||l.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Fl(wl(hc,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Fl(wl(hc,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(s))),k.cloud.isServiceWorkerDB||l.push(function(e){let r=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(n.switchMap((e=>{const s=r;r=e;const i=t.of(e);switch(e){case"disconnected":return Wo.value?i.pipe(n.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(n.debounceTime(4e3));default:return i}})));return t.combineLatest([s,e.syncStateChangedEvent.pipe(n.startWith({phase:"initial"})),pc(e.dx._novip),Vo]).pipe(n.map((([t,n,r,s])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:l,progress:c}=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"),s||(a="disconnected"),{phase:o,error:l,progress:c,status:dt?a:"offline",license:"ok"}})))}(k).subscribe(s.cloud.syncState)),l.push(k.syncCompleteEvent.subscribe(f)),k.tables.every((e=>e.core))||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const S="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[E,x]=yield k.transaction("rw",k.$syncState,(()=>r(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=k.cloud,[s,i,o]=yield Promise.all([k.getOptions(),k.getSchema(),k.getPersistedSyncState()]);if(a){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield k.$syncState.put(e,"options")}}else k.cloud.options=s||null;if((null===(e=k.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&S.length>0&&!xo?k.cloud.usingServiceWorker=!0:((null===(t=k.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&k.cloud.isServiceWorkerDB,k.cloud.usingServiceWorker=!1),al(r,k.cloud.options),al(i,k.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};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 k.$syncState.put(e,"schema"),Object.assign(r,e)}}else k.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(E&&k.setInitiallySynced(!0),function(t){var n,r;for(const s of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new e.SchemaError(`Table ${s.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`);if(!s.schema.primKey.keyPath)throw new e.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(k),h(),!k.cloud.isServiceWorkerDB){l.push(e.liveQuery((()=>k.getCurrentUser())).subscribe(o)),l.push(e.liveQuery((()=>k.getPersistedSyncState())).subscribe(k.cloud.persistedSyncState)),yield t.firstValueFrom(t.combineLatest([o.pipe(n.skip(1),n.take(1)),k.cloud.persistedSyncState.pipe(n.skip(1),n.take(1))]));const r=kc(k);Gi.on.new.subscribe(r),k.dx.once("close",(()=>{Gi.on.new.unsubscribe(r)}))}let C=!1;const I=yield k.getCurrentUser(),A=null===(c=k.cloud.options)||void 0===c?void 0:c.requireAuth;A&&(k.cloud.isServiceWorkerDB?yield t.firstValueFrom(o.pipe(n.filter((e=>!!e.isLoggedIn)),n.take(1))):"object"==typeof A?(!I.isLoggedIn||A.userId&&I.userId!==A.userId||A.email&&I.email!==A.email)&&(C=yield _o(k,A)):I.isLoggedIn||(C=yield _o(k))),!I.isLoggedIn||x&&x.includes(I.userId)||(C=!0),u&&u.stop(),u=null,h();const D=(null===(p=k.cloud.options)||void 0===p?void 0:p.databaseUrl)&&(!E||C);D&&(yield function(e,t,n){return r(this,void 0,void 0,(function*(){yield Fo(e,no,(()=>ro(e,t,n,{isInitialSync:!0})))}))}(k,k.cloud.options,k.cloud.schema),k.setInitiallySynced(!0)),h(),k.cloud.usingServiceWorker&&(null===(m=k.cloud.options)||void 0===m?void 0:m.databaseUrl)?(D||g(k,"push").catch((()=>{})),function(e){return r(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){}}))}(k).catch((()=>{}))):(null===(v=k.cloud.options)||void 0===v?void 0:v.databaseUrl)&&k.cloud.schema&&!k.cloud.isServiceWorkerDB&&(u=cl(k,k.cloud.options,k.cloud.schema),u.start(),D||y(k,"push")),h(),k.cloud.isServiceWorkerDB||l.push(t.fromEvent(self,"online").subscribe((()=>{k.syncStateChangedEvent.next({phase:"not-in-sync"}),No(k)||y(k,"push")})),t.fromEvent(self,"offline").subscribe((()=>{k.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(b=k.cloud.options)||void 0===b?void 0:b.databaseUrl)||(null===(w=k.cloud.options)||void 0===w?void 0:w.disableWebSocket)||Co||l.push(function(e){var s;if(!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(n.filter((e=>e)),n.switchMap((()=>e.getPersistedSyncState())),n.filter((e=>e&&e.serverRevision)),n.switchMap((e=>r(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield _(e)}}))))),o=t.merge(i,e.messageProducer);return function s(){return e.cloud.persistedSyncState.pipe(n.filter((e=>null==e?void 0:e.serverRevision)),n.take(1),n.switchMap((t=>e.cloud.currentUser.pipe(n.map((e=>[e,t]))))),n.switchMap((([e,t])=>Vo.pipe(n.map((n=>[n?e:null,t]))))),n.switchMap((([r,s])=>(null==r?void 0:r.isLoggedIn)&&!(null==s?void 0:s.realms.includes(r.userId))?e.cloud.persistedSyncState.pipe(n.filter((e=>(null==e?void 0:e.realms.includes(r.userId))||!1)),n.take(1),n.map((e=>[r,e]))):new t.BehaviorSubject([r,s]))),n.switchMap((e=>r(this,[e],void 0,(function*([e,t]){return[e,yield _(t)]})))),n.distinctUntilChanged((([e,t],[n,r])=>e===n&&t===r)),n.switchMap((([n,r])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?n?new Zo(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,r,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,n):t.from([]):s()})),n.catchError((i=>"TokenExpiredError"===(null==i?void 0:i.name)?t.of(!0).pipe(n.switchMap((()=>r(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield Ie(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),n.switchMap((()=>s()))):t.throwError((()=>i)))),n.catchError((r=>(e.cloud.webSocketStatus.next("error"),r instanceof nl?t.throwError((()=>r)):t.from(rl()).pipe(n.switchMap((()=>s())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(k))}))}(s)}catch(e){}}))),!0);let d=!1;function h(){if(d)throw new e.DatabaseClosedError}s.once("close",(()=>{l.forEach((e=>e.unsubscribe())),l.splice(0,l.length),d=!0,u&&u.stop(),u=null,o.next(c)}));const f=new t.Subject;var p;s.cloud={version:"4.2.0-alpha.4",options:Object.assign({},Sc),schema:null,get currentUserId(){return o.value.userId||c.userId},currentUser:o,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:f},persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return r(this,void 0,void 0,(function*(){const t=po(s);yield t.cloud.sync(),yield _o(t,e)}))},invites:_c(s),roles:yc(s),configure(e){e=s.cloud.options=Object.assign(Object.assign({},s.cloud.options),e),a=!0,e.databaseUrl&&e.nameSuffix&&(s.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,po(s).reconfigure()),al(s.cloud.schema,s.cloud.options)},logout(){return r(this,arguments,void 0,(function*({force:e}={}){e?yield bo(po(s),{deleteUnsyncedData:!0}):yield vo(po(s))}))},sync(){return r(this,arguments,void 0,(function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=po(s);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield xe(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(y(c,o),i){const r=yield t.firstValueFrom(c.cloud.persistedSyncState.pipe(n.filter((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp)))));if(null==r?void 0:r.error)throw new Error("Sync error: "+r.error)}}else if(yield sl(c)){const s=c.cloud.persistedSyncState.value;y(c,o),i&&(yield t.firstValueFrom(t.from(e.liveQuery((()=>r(this,void 0,void 0,(function*(){const e=yield sl(c),t=yield c.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==s?void 0:s.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))))).pipe(n.filter((e=>!e)))))}}))},permissions:(e,t)=>function(e,t,r){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!r){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");r=t.table()}const o=bc(e),l=t=>{const n=t[i||e.cloud.currentUserId];return n?new wc(n.permissions,r,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new wc({},r,!s||s===e.cloud.currentUserId)},c=o.pipe(n.map(l));return c.getValue=()=>l(o.getValue()),c}(s._novip,e,t)},s.Version.prototype._parseStoresSpec=e.override(s.Version.prototype._parseStoresSpec,(e=>Bo(e,s))),s.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return Uo(s.cloud.schema[this.name].idPrefix||"",t)},s.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)||""},s.use($o({currentUserObservable:s.cloud.currentUser,db:po(s)})),s.use((p=po(s),{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,s,i,o,l,a;const u=e.trans;if(u.disableChangeTracking)return n.mutate(e);const d=null!==(s=null===(r=u.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:c.userId;if((null===(o=null===(i=p.cloud.schema)||void 0===i?void 0:i[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=d),t.realmId||(t.realmId=d);const r=null===(a=(l=n.schema.primaryKey).extractKey)||void 0===a?void 0:a.call(l,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)}})}})})),s.use(jo(po(s)))}Ec.version="4.2.0-alpha.4",e.Cloud=Ec;const xc=new Map;function Cc(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const Ic=new Map;function Ac(t,n){let s=Ic.get(t+"/"+n);return s||(s=function t(n,s){return r(this,void 0,void 0,(function*(){var r;let i=xc.get(n);if(!i){const r=new e(n,{addons:[Ec]});if(i=po(r),i.cloud.isServiceWorkerDB=!0,r.on("versionchange",o),yield i.dx.open(),xc.get(n))return i.close(),yield t(n,s);xc.set(n,i)}if((null===(r=i.cloud.options)||void 0===r?void 0:r.databaseUrl)&&i.cloud.schema)try{yield ol(i,i.cloud.options,i.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:s})}catch(t){if(o(),t.name!==e.errnames.NoSuchDatabase)throw t}function o(){return i.dx.on.versionchange.unsubscribe(o),xc.get(i.name)===i&&xc.delete(i.name),i.dx.close(),!1}}))}(t,n).then((()=>{Ic.delete(t+"/"+n)})).catch((e=>(Ic.delete(t+"/"+n),Promise.reject(e)))),Ic.set(t+"/"+n,s)),s}xo||(self.addEventListener("sync",(e=>{const t=Cc(e.tag);t&&e.waitUntil(Ac(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=Cc(e.tag);t&&e.waitUntil(Ac(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(s=1)=>Ac(t,e.data.purpose||"pull").catch((e=>r(void 0,void 0,void 0,(function*(){if(3===s)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(s+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>{}))):n().catch((e=>{}))}})))}));
|
|
2
2
|
//# sourceMappingURL=service-worker.min.js.map
|