dexie-cloud-addon 1.0.0-beta.10 → 1.0.0-beta.11
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 +189 -158
- 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.map +1 -1
- package/dist/modern/service-worker.js +1208 -1176
- 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/module-es5/dexie-cloud-addon.js +259 -207
- package/dist/module-es5/dexie-cloud-addon.js.map +1 -1
- package/dist/module-es5/dexie-cloud-addon.min.js +1 -1
- package/dist/module-es5/dexie-cloud-addon.min.js.map +1 -1
- package/dist/types/WSObservable.d.ts +11 -6
- package/dist/types/WebSocketStatus.d.ts +1 -0
- package/dist/types/helpers/BroadcastedLocalEvent.d.ts +8 -0
- package/dist/types/helpers/visibleState.d.ts +1 -0
- package/dist/types/sync/syncServerToClientOnly.d.ts +3 -0
- package/dist/types/types/CloudConnectionStatus.d.ts +0 -0
- package/dist/types/types/ConnectionStatus.d.ts +0 -0
- package/dist/types/types/LoginState.d.ts +41 -0
- package/dist/types/types/SyncConnectionStatus.d.ts +1 -0
- package/dist/types/types/SyncFlowStatus.d.ts +6 -0
- package/dist/types/types/SyncStatus.d.ts +6 -0
- package/dist/umd/dexie-cloud-addon.js +259 -207
- 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.map +1 -1
- package/dist/umd/service-worker.js +1208 -1176
- 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-modern/dexie-cloud-addon.js +188 -157
- package/dist/umd-modern/dexie-cloud-addon.js.map +1 -1
- package/package.json +2 -2
|
@@ -1 +1 @@
|
|
|
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";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);const o={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(o),Object.freeze(o.claims)}catch(e){}const i={},s=self.document&&navigator.serviceWorker;s&&s.ready.then((e=>i.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 a{constructor(e){this.name=e}subscribe(e){if(!s)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 s.addEventListener("message",t),()=>s.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}))):i.registration&&(null===(t=i.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class c extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new a(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof a?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof a?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",{...e},"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}var u=function(e,t){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function l(e,t){function n(){this.constructor=e}u(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function d(e){return"function"==typeof e}var f=!1,h={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;f=e},get useDeprecatedSynchronousErrorHandling(){return f}};function p(e){setTimeout((function(){throw e}),0)}var y={closed:!0,next:function(e){},error:function(e){if(h.useDeprecatedSynchronousErrorHandling)throw e;p(e)},complete:function(){}},b=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function v(e){return null!==e&&"object"==typeof e}var m=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),g=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,o=n._ctorUnsubscribe,i=n._unsubscribe,s=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var a=0;a<r.length;++a){r[a].remove(this)}if(d(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof m?_(e.errors):[e]}}if(b(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(v(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof m?t=t.concat(_(e.errors)):t.push(e)}}}if(t)throw new m(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var o=n._parentOrParents;if(null===o)n._parentOrParents=this;else if(o instanceof e){if(o===this)return n;n._parentOrParents=[o,this]}else{if(-1!==o.indexOf(this))return n;o.push(this)}var i=this._subscriptions;return null===i?this._subscriptions=[n]:i.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function _(e){return e.reduce((function(e,t){return e.concat(t instanceof m?t.errors:t)}),[])}var w=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),S=function(e){function t(n,r,o){var i=e.call(this)||this;switch(i.syncErrorValue=null,i.syncErrorThrown=!1,i.syncErrorThrowable=!1,i.isStopped=!1,arguments.length){case 0:i.destination=y;break;case 1:if(!n){i.destination=y;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new k(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new k(i,n,r,o)}return i}return l(t,e),t.prototype[w]=function(){return this},t.create=function(e,n,r){var o=new t(e,n,r);return o.syncErrorThrowable=!1,o},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))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(g),k=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return d(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==y&&(d((a=Object.create(n)).unsubscribe)&&s.add(a.unsubscribe.bind(a)),a.unsubscribe=s.unsubscribe.bind(s))),s._context=a,s._next=i,s._error=r,s._complete=o,s}return l(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=h.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):p(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;p(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),h.useDeprecatedSynchronousErrorHandling)throw e;p(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!h.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return h.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(p(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(S);var x=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function E(e){return e}function I(e){return 0===e.length?E:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var T=function(){function e(e){this._isScalar=!1,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=this.operator,o=function(e,t,n){if(e){if(e instanceof S)return e;if(e[w])return e[w]()}return e||t||n?new S(e,t,n):new S(y)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||h.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),h.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){h.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),!function(e){for(;e;){var t=e,n=t.closed,r=t.destination,o=t.isStopped;if(n||o)return!1;e=r&&r instanceof S?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=C(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),o&&o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[x]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?this:I(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=C(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 C(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var A=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function P(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var O=P(),U=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function D(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var $=function(e){if(e&&"function"==typeof e[x])return r=e,function(e){var t=r[x]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(U(e))return A(e);if(D(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,p),e};if(e&&"function"==typeof e[O])return t=e,function(e){for(var n=t[O]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,o=v(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+o+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},N=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(S),j=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(S);function R(e,t){if(!t.closed){if(e instanceof T)return e.subscribe(t);var n;try{n=$(e)(t)}catch(e){t.error(e)}return n}}var L=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 l(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),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;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=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,n){return e.call(this)||this}return l(t,e),t.prototype.schedule=function(e,t){return this},t}(g)),B=function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=function(){return Date.now()},e}(),W=new(function(e){function t(n,r){void 0===r&&(r=B.now);var o=e.call(this,n,(function(){return t.delegate&&t.delegate!==o?t.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return l(t,e),t.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),t.delegate&&t.delegate!==this?t.delegate.schedule(n,r,o):e.prototype.schedule.call(this,n,r,o)},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}(B))(L);function F(e){return e&&"function"==typeof e.schedule}function M(e){return function(t){var n=new H(e),r=t.lift(n);return n.caught=r}}var H=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new V(e,this.selector,this.caught))},e}(),V=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return l(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var r=new N(this);this.add(r);var o=R(n,r);o!==r&&this.add(o)}},t}(j);function K(e,t){return new T((function(n){var r=new g,o=0;return r.add(t.schedule((function(){o!==e.length?(n.next(e[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function q(e,t){return t?K(e,t):new T(A(e))}function z(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[x]}(e))return function(e,t){return new T((function(n){var r=new g;return r.add(t.schedule((function(){var o=e[x]();r.add(o.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(D(e))return function(e,t){return new T((function(n){var r=new g;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(U(e))return K(e,t);if(function(e){return e&&"function"==typeof e[O]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new T((function(n){var r,o=new g;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[O](),o.add(t.schedule((function(){if(!n.closed){var e,t;try{var o=r.next();e=o.value,t=o.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),o}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}function G(e,t){return t?z(e,t):e instanceof T?e:new T($(e))}function J(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return F(n)?(e.pop(),K(e,n)):q(e)}function Y(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new Q(e,t))}}var Q=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new X(e,this.project,this.thisArg))},e}(),X=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return l(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(S);function Z(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(Z((function(n,r){return G(e(n,r)).pipe(Y((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new ee(e,n))})}var ee=function(){function e(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.project=e,this.concurrent=t}return e.prototype.call=function(e,t){return t.subscribe(new te(e,this.project,this.concurrent))},e}(),te=function(e){function t(t,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=e.call(this,t)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return l(t,e),t.prototype._next=function(e){this.active<this.concurrent?this._tryNext(e):this.buffer.push(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this.active++,this._innerSub(t)},t.prototype._innerSub=function(e){var t=new N(this),n=this.destination;n.add(t);var r=R(e,t);r!==t&&n.add(r)},t.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyComplete=function(){var e=this.buffer;this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(j);function ne(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),Z(E,e)}function re(){return ne(1)}function oe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return re()(J.apply(void 0,e))}function ie(e,t){return void 0===t&&(t=W),function(n){return n.lift(new se(e,t))}}var se=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ae(e,this.dueTime,this.scheduler))},e}(),ae=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.dueTime=n,o.scheduler=r,o.debouncedSubscription=null,o.lastValue=null,o.hasValue=!1,o}return l(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(ce,this.dueTime,this))},t.prototype._complete=function(){this.debouncedNext(),this.destination.complete()},t.prototype.debouncedNext=function(){if(this.clearDebounce(),this.hasValue){var e=this.lastValue;this.lastValue=null,this.hasValue=!1,this.destination.next(e)}},t.prototype.clearDebounce=function(){var e=this.debouncedSubscription;null!==e&&(this.remove(e),e.unsubscribe(),this.debouncedSubscription=null)},t}(S);function ce(e){e.debouncedNext()}function ue(e){return e instanceof Date&&!isNaN(+e)}var le=new T((function(e){return e.complete()}));function de(e){return e?function(e){return new T((function(t){return e.schedule((function(){return t.complete()}))}))}(e):le}function fe(e,t){return new T(t?function(n){return t.schedule(he,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function he(e){var t=e.error;e.subscriber.error(t)}var pe=function(){function e(e,t,n){this.kind=e,this.value=t,this.error=n,this.hasValue="N"===e}return e.prototype.observe=function(e){switch(this.kind){case"N":return e.next&&e.next(this.value);case"E":return e.error&&e.error(this.error);case"C":return e.complete&&e.complete()}},e.prototype.do=function(e,t,n){switch(this.kind){case"N":return e&&e(this.value);case"E":return t&&t(this.error);case"C":return n&&n()}},e.prototype.accept=function(e,t,n){return e&&"function"==typeof e.next?this.observe(e):this.do(e,t,n)},e.prototype.toObservable=function(){switch(this.kind){case"N":return J(this.value);case"E":return fe(this.error);case"C":return de()}throw new Error("unexpected notification kind value")},e.createNext=function(t){return void 0!==t?new e("N",t):e.undefinedValueNotification},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e.undefinedValueNotification=new e("N",void 0),e}();function ye(e,t){void 0===t&&(t=W);var n=ue(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new be(n,t))}}var be=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ve(e,this.delay,this.scheduler))},e}(),ve=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return l(t,e),t.dispatch=function(e){for(var t=e.source,n=t.queue,r=e.scheduler,o=e.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(e,i)}else this.unsubscribe(),t.active=!1},t.prototype._schedule=function(e){this.active=!0,this.destination.add(e.schedule(t.dispatch,this.delay,{source:this,destination:this.destination,scheduler:e}))},t.prototype.scheduleNotification=function(e){if(!0!==this.errored){var t=this.scheduler,n=new me(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(pe.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(pe.createComplete()),this.unsubscribe()},t}(S),me=function(){return function(e,t){this.time=e,this.notification=t}}();var ge=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new _e(e,this.compare,this.keySelector))},e}(),_e=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return l(t,e),t.prototype.compare=function(e,t){return e===t},t.prototype._next=function(e){var t;try{var n=this.keySelector;t=n?n(e):e}catch(e){return this.destination.error(e)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,t)}catch(e){return this.destination.error(e)}else this.hasKey=!0;r||(this.key=t,this.destination.next(e))},t}(S),we=function(){function e(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return e.prototype=Object.create(Error.prototype),e}();function Se(e,t){return function(n){return n.lift(new ke(e,t))}}var ke=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new xe(e,this.predicate,this.thisArg))},e}(),xe=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return l(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(S);function Ee(e){return function(t){return 0===e?de():t.lift(new Ie(e))}}var Ie=function(){function e(e){if(this.total=e,this.total<0)throw new we}return e.prototype.call=function(e,t){return t.subscribe(new Te(e,this.total))},e}(),Te=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return l(t,e),t.prototype._next=function(e){var t=this.total,n=++this.count;n<=t&&(this.destination.next(e),n===t&&(this.destination.complete(),this.unsubscribe()))},t}(S);function Ce(e){return function(t){return t.lift(new Ae(e))}}var Ae=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new Pe(e,this.total))},e}(),Pe=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return l(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(S);function Oe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return F(n)?(e.pop(),function(t){return oe(e,t,n)}):function(t){return oe(e,t)}}function Ue(e,t){return"function"==typeof t?function(n){return n.pipe(Ue((function(n,r){return G(e(n,r)).pipe(Y((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new De(e))}}var De=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new $e(e,this.project))},e}(),$e=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return l(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new N(this),r=this.destination;r.add(n),this.innerSubscription=R(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(j);function Ne(){}function je(e,t,n){return function(r){return r.lift(new Re(e,t,n))}}var Re=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new Le(e,this.nextOrObserver,this.error,this.complete))},e}(),Le=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=Ne,i._tapError=Ne,i._tapComplete=Ne,i._tapError=r||Ne,i._tapComplete=o||Ne,d(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||Ne,i._tapError=n.error||Ne,i._tapComplete=n.complete||Ne),i}return l(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(S),Be=function(){function e(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return e.prototype=Object.create(Error.prototype),e}();var We=function(){function e(e,t,n,r){this.waitFor=e,this.absoluteTimeout=t,this.withObservable=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Fe(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Fe=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.absoluteTimeout=n,s.waitFor=r,s.withObservable=o,s.scheduler=i,s.scheduleTimeout(),s}return l(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(R(t,new N(e)))},t.prototype.scheduleTimeout=function(){var e=this.action;e?this.action=e.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(t.dispatchTimeout,this.waitFor,this))},t.prototype._next=function(t){this.absoluteTimeout||this.scheduleTimeout(),e.prototype._next.call(this,t)},t.prototype._unsubscribe=function(){this.action=void 0,this.scheduler=null,this.withObservable=null},t}(j);function Me(e,t){return void 0===t&&(t=W),function(e,t,n){return void 0===n&&(n=W),function(r){var o=ue(e),i=o?+e-n.now():Math.abs(e);return r.lift(new We(i,o,t,n))}}(e,fe(new Be),t)}const{toString:He}={};const Ve={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 t of n)delete r[t],r["$"+t]=e[t];return r}};function Ke(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify:(e,r,o)=>JSON.stringify(e,(function(e){const o=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 Ve;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,He.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:Ve),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o),parse(e,n){let r=null,o=[];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}if(i===r){if(o.length>0){i={...i};for(const e of o)i[e.substr(1)]=i[e],delete i[e]}return o=[],i}return"$"===e[0]&&"$t"!==e&&(r=this,o.push(e)),i}))}}}const qe={Blob:{test:(e,t)=>"Blob"===t,replace:(e,t)=>{const n=t.length;return t.push(e),{$t:"Blob",mimeType:e.type,i:n}},revive:({i:e,mimeType:t},n)=>new Blob([n[e]],{type:t})}};var ze={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const Ge={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Je={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Ye={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Qe={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Xe="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var Ze=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=Xe[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});const et="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var o=0;o<n;o++)r[o]=t.charCodeAt(o);return r},tt="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>btoa(String.fromCharCode.apply(null,e));function nt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=it[e[n]];return t}(tt(e))}function rt(e){return et(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+=ot[e[n]];return t}(e))}const ot={"-":"=",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:"+","|":"/"},it={};for(const e of Object.keys(ot))it[ot[e]]=e;var st={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:nt(e)}),revive:({v:e})=>{const t=rt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class at{constructor(e,t){this.buf=e,this.type=t}}function ct(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 ut(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const lt={...ze,...Ge,...Je,...Ye,...Qe,...Ze,...st,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof at,replace:e=>({$t:"Blob",v:tt(e instanceof at?e.buf:ut(ct(e))),type:e.type}),revive:({type:e,v:t})=>{const n=et(t);return void 0!==typeof Blob?new Blob([n]):new at(n.buffer,e)}}}};function dt(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 ft={undefined:{replace:()=>{},revive:()=>{}}};const ht="bigint"==typeof BigInt(0);function pt(e){return"bigint"==typeof e?e:ht?"string"==typeof e?BigInt(e):BigInt(e.v):Number("string"==typeof e?e:e.v)}function yt(e,t){const n=pt(e),r=pt(t);return n<r?-1:n>r?1:0}class bt{constructor(e){this.v=e}toString(){return this.v}}const vt={...ft,...ht?{}:{bigint:{test:e=>e instanceof bt,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new bt(e)}}},mt=Ke(lt,vt),gt=function(...e){const t=Ke(lt,qe,...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);return[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])}))),r]},async parse(e,n){let r=0;const o=[],i=await dt(n),s=new DataView(i);for(;r<i.byteLength;){const e=s.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await dt(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)}}}(vt);let _t=!1;async function wt(e,t){try{const n=await navigator.serviceWorker.ready;return"push"===t&&n.sync&&await n.sync.register(`dexie-cloud:${e.name}`),void(n.active?n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t}):console.error("Dexie Cloud: There's no active service worker. Can this ever happen??"))}catch(e){_t||(console.debug("Dexie Cloud: Could not register sync event",e),_t=!0)}}function St(e,t){e.cloud.usingServiceWorker?wt(e,t):e.localSyncEvent.next({purpose:t})}async function kt({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),o=await crypto.subtle.digest("SHA-1",r);return tt(o)}function xt(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function Et(e){return`$${e}_mutations`}function It(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}async function Tt(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=It(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return{table:t,muts:await i.toArray()}})))).filter((({muts:e})=>e.length>0))}const Ct=crypto.getRandomValues;function At(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)At(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c||(c=e[s]={}),At(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const Pt="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Ct(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function Ot(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>Ot(e)))&&e.every(Ut))}function Ut(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(Ut)}function Dt(e,t,n){const r=e[t]||(e[t]={});switch(n.type){case"insert":case"upsert":n.keys.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":n.keys.forEach(((e,t)=>{const o="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(o))At(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,o)}else r[e]={type:"upd",mod:o}}));break;case"delete":n.keys.forEach((e=>{r[e]={type:"del"}}))}return e}function $t(e,t){for(const{table:n,muts:r}of t)for(const t of r)Dt(e,n,t)}function Nt(e,t){return new Promise(((n,o)=>{const i={...t,onSubmit:t=>{e.next(void 0),n(t)},onCancel:()=>{e.next(void 0),o(new r.default.AbortError("User cancelled"))}};e.next(i)}))}function jt(e,t,...n){return Nt(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function Rt(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await Nt(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}async function Lt(e,t,n){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:o}=await Nt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function Bt(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await Wt(e,t):await async function(e,t,n,r){const{privateKey:o,publicKey:i}=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);e.nonExportablePrivateKey=o;const s=function(e){const t=tt(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)}(await crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=await t({public_key:s,hints:r});if("tokens"!==o.type)throw new Error(`Unexpected response type from token endpoint: ${o.type}`);return e.accessToken=o.accessToken,e.accessTokenExpiration=new Date(o.accessTokenExpiration),e.refreshToken=o.refreshToken,o.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(o.refreshTokenExpiration)),e.userId=o.claims.sub,e.email=o.claims.email,e.name=o.claims.name,e.claims=o.claims,o.alerts&&o.alerts.length>0&&await Nt(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await jt(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem to authenticate rigth now.",messageParams:{}}).catch((()=>{})),e}}(t,n,r,o)}async function Wt(e,t){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",o=(new TextEncoder).encode(t.refreshToken+n),i=await crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=tt(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=await fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=await c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}class Ft extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function Mt(e,t,n,r,o,i,s){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},c=await async function(e){var t,n;const r=await e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=await Wt(e.cloud.options.databaseUrl,r);return await e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}(r);c&&(a.Authorization=`Bearer ${c}`);const u={dbID:null==t?void 0:t.remoteDbId,clientIdentity:s,schema:i||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:e};console.debug("Sync request",u),r.syncStateChangedEvent.next({phase:"pushing"});const l=await fetch(`${o}/sync`,{method:"post",headers:a,body:mt.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new Ft(l);switch(l.headers.get("content-type")){case"application/x-bison":return gt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return mt.parse(e)}}}async function Ht(e,t,n){const o=await e.bulkGet(t),i=[],s=[];t.forEach(((t,a)=>{const c=o[a];if(c){for(const[t,o]of Object.entries(n[a])){if(t===e.schema.primKey.keyPath)throw new Error("Cannot change primary key");r.default.setByKeyPath(c,t,o)}i.push(t),s.push(c)}})),await(null==e.schema.primKey.keyPath?e.bulkPut(s,i):e.bulkPut(s))}function Vt(e){if(null==e?void 0:e.cancelled)throw new r.default.AbortError("Operation was cancelled")}let Kt=navigator.onLine;async function qt(e,t,n,r){await e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}function zt(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0&&r[r.length-1].rev||0;t[n]=e}return t}self.addEventListener("online",(()=>Kt=!0)),self.addEventListener("offline",(()=>Kt=!1));function Gt(e,t,n,r){return Jt.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((async o=>(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:Kt,syncOptions:r,error:o}),Kt&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),await new Promise((e=>setTimeout(e,500))),await Gt(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Kt?"error":"offline",error:o}),Promise.reject(o)))))}async function Jt(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:s,purpose:a}={isInitialSync:!1}){var c;if(s||console.debug("SYNC STARTED",{isInitialSync:r,purpose:a}),!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:u}=t,l=await e.getCurrentUser(),d=l.isLoggedIn?xt(e):[],f=d.map((t=>e.table(Et(t.name)))),h=await e.getPersistedSyncState(),p=!r&&l.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return xt(e).filter((e=>!n.includes(e.name)))}(e,h):[];Vt(i);const y=p.length>0;if(y){if(s)return!0;console.debug("sync doSyncify is true"),await e.transaction("rw",p,(async e=>{e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,await async function(e,t,n){const r=new Set(n||[]);for(const n of e)"members"===n.name?await n.toCollection().modify((e=>{r.has(e.realmId)||e.userId!==o.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==o.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==o.userId||(e.owner=t.userId),e.realmId&&e.realmId!==o.userId||(e.realmId=t.userId))})))}(p,l,null==h?void 0:h.realms)})),Vt(i)}const[b,v,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let o=await Tt(f);if(Vt(i),y){const e=await async function(e,t,n,r){if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(await Promise.all(e.map((async e=>{const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const i=n[e.name],s=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>!o.has(e.realmId||"")&&Ot(r(e)))):e.filter((e=>{return!o.has(e.realmId||"")&&(t=r(e),!(n=null==i?void 0:i.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=await s.toArray();if(a.length>0){const n={type:"insert",values:a,keys:a.map(r),userId:t.userId};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter((e=>e.muts.length>0))}return[]}(p,l,n,null==h?void 0:h.realms);return Vt(i),o=o.concat(e),[o,t,r]}return[o,t,r]})),g=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(s)return console.debug("Sync is needed:",g),g;if("push"===a&&!g)return!1;const _=zt(b,null==v?void 0:v.latestRevisions),w=(null==v?void 0:v.clientIdentity)||Pt(16);Vt(i);const S=await Mt(b,v,m,e,u,n,w);console.debug("Sync response",S);return await e.transaction("rw",e.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))S.schema[e]&&(n[e]=S.schema[e]);await e.$syncState.put(n,"schema");const r=await Tt(f,0,{since:_});for(const t of f){const n=It(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(_[t.name]){const r=_[t.name]||0;await 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 await Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}zt(r,_),await qt(e,n,_,S.serverRevision);const o=await e.getPersistedSyncState();await async function(e,t,n){const r=[],o=n?n.realms.concat(n.inviteRealms):[],i=new Set([...t.realms,...t.inviteRealms]);for(const e of o)i.has(e)||r.push(e);if(r.length>0){const t=new Set(r),n=xt(e);for(const e of n)e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?await e.where("realmId").anyOf(r).delete():await e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete()}}(e,S,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:w};i.syncedTables=d.map((e=>e.name)).concat(p.map((e=>e.name))),i.latestRevisions=_,i.remoteDbId=S.dbId,i.initiallySynced=!0,i.realms=S.realms,i.inviteRealms=S.inviteRealms,i.serverRevision=S.serverRevision,i.timestamp=new Date,delete i.error;const s=Qt(S.changes,r);return await Yt(s,e),e.$syncState.put(i,"syncState"),0===r.length}))?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),await Jt(e,t,n,{isInitialSync:r,cancelToken:i}))}async function Yt(e,t){console.debug("Applying server changes",e,r.default.currentTransaction);for(const{table:n,muts:o}of e){const e=t.table(n);if(!e)continue;const{primaryKey:i}=e.core.schema;for(const t of o)switch(t.type){case"insert":i.outbound?await e.bulkAdd(t.values,t.keys):(t.keys.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),await e.bulkAdd(t.values));break;case"upsert":i.outbound?await e.bulkPut(t.values,t.keys):(t.keys.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),await e.bulkPut(t.values));break;case"modify":1===t.keys.length?await e.update(t.keys[0],t.changeSpec):await e.where(":id").anyOf(t.keys).modify(t.changeSpec);break;case"update":await Ht(e,t.keys,t.changeSpecs);break;case"delete":await e.bulkDelete(t.keys)}}}function Qt(e,t){const n={};$t(n,e);const r={};return $t(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":delete e[i][t];break;case"del":break;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===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))At(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=Pt(16),n={};for(const[t,r]of Object.entries(e))for(const[e,o]of Object.entries(r)){const r=n[t]||(n[t]={});(r[o.type]||(r[o.type]=[])).push(Object.assign({key:e},o))}const r=[];for(const[e,o]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(o))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}function Xt(e){const n=[],o=new t.BehaviorSubject(!0),i=new t.BehaviorSubject(null);let s=!1;return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,o.next(!1);try{await async function(){var t,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await e.cloud.syncState.pipe(Se((({phase:e})=>"in-sync"===e||"error"===e)),Ee(1)).toPromise(),console.debug("processing msg",s);const n=e.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=e.cloud.currentUser.value,c=await Wt(e.cloud.options.databaseUrl,a);await e.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"rev":(!(null==n?void 0:n.serverRevision)||yt(n.serverRevision,s.rev)<0)&&St(e,"pull");break;case"realm-added":(null===(t=null==n?void 0:n.realms)||void 0===t?void 0:t.includes(s.realm))||St(e,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&St(e,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=e.cloud.syncState.value)||void 0===i?void 0:i.phase)){St(e,"pull");break}await e.transaction("rw",e.dx.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,o,i]=await Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!n||!i)return void console.debug("required vars not present",{syncState:o,schema:n,currentUser:i});if(0!==yt(s.baseRev,o.serverRevision))return void console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`);const a=await r.default.waitFor(kt(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void St(e,"pull");let c=[];if(i.isLoggedIn){const t=xt(e).map((t=>e.table(Et(t.name))));c=await Tt(t),console.debug("msg queue: client changes",c)}const u=Qt(s.changes,c);console.debug("applying filtered server changes",u),await Yt(u,e),o.latestRevisions=zt(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await qt(e,n,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await e.$syncState.put(o,"syncState")})),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}()}finally{s=!1,o.next(!0)}}})),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:o}}const Zt=new WeakMap,en={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let tn=0;function nn(e){"vip"in e&&(e=e.vip);let n=Zt.get(e.cloud);if(!n){const r=new t.Subject;let i=new c(`syncstatechanged-${e.name}`);r.id=++tn;let s=!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 s},localSyncEvent:r,get syncStateChangedEvent(){return i},dx:e};const a={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||o)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema"),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){i=new c(`syncstatechanged-${e.name}`)}};Object.assign(n,a),n.messageConsumer=Xt(n),Zt.set(e.cloud,n)}return n}const rn=new WeakMap;class on{constructor(e,t){rn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new on(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){rn.get(this).table("$logins").put(this)}}async function sn(e,t){if((await e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new on(e,{claims:{},lastLogin:new Date(0)});await Bt(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return async function({public_key:n,hints:r}){var o;let i;const s=null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!s)throw new Error("No database URL given.");i="demo"===(null==r?void 0:r.grant_type)?{demo_user:await Rt(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}:{email:await Rt(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=await a.text();throw await jt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Ft(a,e)}const c=await a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=await Lt(t,i.email);i.otp=e||"",i.otp_id=c.otp_id;let n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=await n.text();i.otp=await Lt(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=await n.text();throw await jt(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Ft(n,e)}return await n.json()}throw new Error(`Unexpected response from ${s}/token`)}}(e),e.cloud.userInteraction,t),await n.save(),await async function(e,t){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");await e.transaction("rw",n,(async e=>{const r=await n.toArray();await Promise.all(r.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,await t.save(),console.debug("Saved new user",t.email)})),await new Promise((n=>{if(e.cloud.currentUserId===t.userId)n(null);else{const r=e.cloud.currentUser.subscribe((e=>{e.userId===t.userId&&(r.unsubscribe(),n(null))}))}}))}(e,n),St(e,"pull")}const an="undefined"!=typeof InstallTrigger,cn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),un=cn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,ln=cn&&un<=605||an;const dn="undefined"!=typeof self&&"clients"in self&&!self.document;function fn(){throw new r.default.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:hn}={};function pn(e){return hn.call(e).slice(8,-1)}function yn(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 bn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let vn=0;function mn(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:t=>({...t,table:n=>{const o=t.table(n);function i(t,i){let s=null;const a=yn(o.schema.primaryKey,t);return a.forEach(((c,u)=>{if(void 0===c){const n=t.values[u].realmId||e.cloud.currentUserId,c=n.substr(n.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();vn>=o?++vn:vn=o,r[0]=vn/1099511627776,r[1]=vn/4294967296,r[2]=vn/16777216,r[3]=vn/65536,r[4]=vn/256,r[5]=vn;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+nt(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=t.values.slice()),s[u]=r.default.deepClone(s[u]),r.default.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new r.default.ConstraintError(`The ID "${c}" is not valid for table "${n}". Primary '@' keys requires the key to be prefixed with "${i}.\n"If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate({...t,keys:a,values:s||t.values})}return{...o,mutate:t=>{var s,a;if(t.trans.disableChangeTracking)return o.mutate(t);if("add"===t.type||"put"===t.type){const c=null===(s=e.cloud.schema)||void 0===s?void 0:s[n];if(null==c?void 0:c.generatedGlobalId){if((null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!e.initiallySynced){const e=yn(o.schema.primaryKey,t);return o.getMany({keys:e,trans:t.trans,cache:"immutable"}).then((n=>{if(n.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(t)}))}return i(t,c.idPrefix)}if(null==c?void 0:c.markedForSync){yn(o.schema.primaryKey,t).forEach(((e,t)=>{if(!Ot(e)){const t=Array.isArray(e)?e.map(pn).join(","):pn(e);throw new r.default.ConstraintError(`Invalid primary key type ${t} for table ${n}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(t)}}}})}}function gn(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let _n=0;function wn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function Sn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const kn=new t.BehaviorSubject(new Set);function xn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){fn()}return{...n,transaction:(r,o)=>{let i;if("readwrite"===o){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>Et(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=gn(16),i.currentUser=e.value,kn.value.add(i),kn.next(kn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),kn.value.delete(i),kn.next(kn.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),wt(t,"push")):t.localSyncEvent.next({purpose:"push"})),n()};i.addEventListener("complete",r),i.addEventListener("error",n),i.addEventListener("abort",n)}return i},table:e=>{const t=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?{...t,mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),t.mutate(e))}:"$logins"===e?{...t,mutate:e=>(console.debug("Mutating $logins table",e),t.mutate(e).then((t=>(console.debug("Mutating $logins"),e.trans.mutationsAdded=!0,console.debug("$logins mutated"),t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e)))))}:t;const{schema:r}=t,i=o.get(e);return function(e){const t="$lock"+ ++_n;return{...e,count:wn(e.count,t),get:wn(e.get,t),getMany:wn(e.getMany,t),openCursor:wn(e.openCursor,t),query:wn(e.query,t),mutate:Sn(e.mutate,t)}}({...t,mutate:e=>{var n;const o=e.trans;return o.txid?o.disableChangeTracking?t.mutate(e):(null===(n=o.currentUser)||void 0===n?void 0:n.isLoggedIn)?"deleteRange"===e.type?t.query({query:{range:e.range,index:r.primaryKey},trans:e.trans,values:!1}).then((t=>s({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):s(e):t.mutate(e):t.mutate(e)}});function s(e){const n=e.trans;n.mutationsAdded=!0;const{txid:r,currentUser:{userId:o}}=n,{type:s}=e;return t.mutate(e).then((t=>{const{numFailures:a,failures:c}=t;let u="delete"===s?e.keys:t.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])),d=d.filter(((e,t)=>!c[t])));const f=Date.now(),h="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:f,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[h]}).then((()=>t)):t}))}}}}}}function En(e,t){return function(n,r){const o={...en,...n},i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(bn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,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;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const In=gn(16);async function Tn(n,r,o,i,{awaitRemoteJob:s}={}){const a=n.table(o);if(await async function i(){if(await n.transaction("rw!",o,(async()=>{const e=await a.get(r);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${r} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),await a.put({nodeId:In,started:new Date,heartbeat:new Date},r),!0):(await a.add({nodeId:In,started:new Date,heartbeat:new Date},r),!0)})))return!0;if(s)try{const n=t.from(e.liveQuery((()=>a.get(r)))).pipe(Me(6e4),Se((e=>!e)));return await n.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await i()}return!1}()){const e=setInterval((()=>{a.update(r,(e=>e.nodeId===In&&(e.heartbeat=new Date)))}),1e3);try{return await i()}finally{clearInterval(e),await n.transaction("rw!",o,(async()=>{const e=await a.get(r);e&&e.nodeId===In&&a.delete(r)}))}}}const Cn=new t.BehaviorSubject(!0),An=new t.BehaviorSubject(!0);var Pn,On;Cn.pipe(Ue((e=>e?t.of(!0):t.of(!1).pipe(ye(2e4)))),(function(e){return e.lift(new ge(Pn,On))})).subscribe(An);const Un="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),Dn=Un.pipe(Se((()=>"hidden"===document.visibilityState))),$n=Un.pipe(Se((()=>"visible"===document.visibilityState))),Nn="undefined"!=typeof window?t.merge($n,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),Dn,Nn).pipe(Y((()=>"visible"===document.visibilityState)),je((e=>{Cn.value!==e&&Cn.next(e)})),Ue((e=>e?t.of(0).pipe(ye(28e4),je((()=>Cn.next(!1)))):t.of(0)))).subscribe((()=>{}));class jn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Rn extends t.Observable{constructor(e,t,n,r,o,i,s){super((a=>new Bn(e,t,n,i,s,a,r,o)))}}let Ln=0;class Bn extends t.Subscription{constructor(e,t,n,r,o,i,s,a){super((()=>this.teardown())),this.id=++Ln,console.debug("New WebSocket Connection",this.id,r?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.clientIdentity=n,this.token=r,this.tokenExpiration=o,this.subscriber=i,this.lastUserActivity=new Date,this.messageProducer=s,this.messageProducerSubscription=null,this.webSocketStatus=a,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),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,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){this.disconnect(),this.connect()}async connect(){if(this.webSocketStatus.next("connecting"),this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return void console.debug("WS not reconnecting just yet",{id:this.id,pauseUntil:this.pauseUntil});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;if(this.tokenExpiration&&this.tokenExpiration<new Date)return void this.subscriber.error(new jn);this.pinger=setInterval((async()=>{if(this.closed)return console.debug("pinger check",this.id,"CLOSED."),void this.teardown();if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{if(console.debug("pinger setTimeout",this.id,this.pinger?"alive":"dead"),this.pinger)return this.closed?(console.debug("pinger setTimeout",this.id,"subscription is closed"),void this.teardown()):void(this.lastServerActivity<new Date(Date.now()-2e4)?(console.debug("pinger: server is inactive"),console.debug("pinger reconnecting"),this.reconnect()):console.debug("pinger: server still active"))}),2e4)}catch(e){console.debug("pinger catch error",this.id,"reconnecting"),this.reconnect()}else console.debug("pinger",this.id,"reconnecting"),this.reconnect()}),3e4);const e=new URL(this.databaseUrl);e.protocol="http:"===e.protocol?"ws":"wss";const t=new URLSearchParams;if(this.subscriber.closed)return;t.set("rev",this.rev),t.set("clientId",this.clientIdentity),this.token&&t.set("token",this.token),console.debug("dexie-cloud WebSocket create");const n=this.ws=new WebSocket(`${e}/changes?${t}`);n.onclose=e=>{this.pinger&&(console.debug("dexie-cloud WebSocket onclosed",this.id),this.reconnect())},n.onmessage=e=>{if(this.pinger){console.debug("dexie-cloud WebSocket onmessage",e.data),this.lastServerActivity=new Date;try{const t=mt.parse(e.data);if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);"rev"===t.type&&(this.rev=t.rev),"pong"!==t.type&&this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{await new Promise(((e,t)=>{n.onopen=t=>{console.debug("dexie-cloud WebSocket onopen"),e(null)},n.onerror=e=>{const n=e.error||new Error("WebSocket Error");this.disconnect(),this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}})),this.messageProducerSubscription=this.messageProducer.subscribe((e=>{var t;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),null===(t=this.ws)||void 0===t||t.send(mt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Wn(e){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),await(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),await Nn.pipe(Ee(1)).toPromise(),console.debug("someone did something!")}async function Fn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await Gt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Mn=new WeakMap;function Hn(e,t,n,r){const o=Mn.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),o.promise;{let i=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(i=!0)}));return o.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!i)return Hn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?dn&&await Gt(e,t,n,r):await Tn(e,"currentSyncWorker","$jobs",(()=>Gt(e,t,n,r))),Mn.delete(e),console.debug("Done sync")}catch(t){throw Mn.delete(e),console.error("Failed to sync client changes",t),t}}();return Mn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Vn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){Hn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function Kn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var qn,zn,Gn,Jn,Yn={},Qn=[],Xn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Zn(e,t){for(var n in t)e[n]=t[n];return e}function er(e){var t=e.parentNode;t&&t.removeChild(e)}function tr(e,t,n){var r,o,i,s=arguments,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:a[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(a.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return nr(e,a,r,o,null)}function nr(e,t,n,r,o){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==o?++qn.__v:o};return null!=qn.vnode&&qn.vnode(i),i}function rr(e){return e.children}function or(e,t){this.props=e,this.context=t}function ir(e,t){if(null==t)return e.__?ir(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?ir(e):null}function sr(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 sr(e)}}function ar(e){(!e.__d&&(e.__d=!0)&&zn.push(e)&&!cr.__r++||Jn!==qn.debounceRendering)&&((Jn=qn.debounceRendering)||Gn)(cr)}function cr(){for(var e;cr.__r=zn.length;)e=zn.sort((function(e,t){return e.__v.__b-t.__v.__b})),zn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=Zn({},o)).__v=o.__v+1,br(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?ir(o):i,o.__h),vr(n,o),o.__e!=i&&sr(o)))}))}function ur(e,t,n,r,o,i,s,a,c,u){var l,d,f,h,p,y,b,v=r&&r.__k||Qn,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(h=n.__k[l]=null==(h=t[l])||"boolean"==typeof h?null:"string"==typeof h||"number"==typeof h||"bigint"==typeof h?nr(null,h,null,null,h):Array.isArray(h)?nr(rr,{children:h},null,null,null):h.__b>0?nr(h.type,h.props,h.key,null,h.__v):h)){if(h.__=n,h.__b=n.__b+1,null===(f=v[l])||f&&h.key==f.key&&h.type===f.type)v[l]=void 0;else for(d=0;d<m;d++){if((f=v[d])&&h.key==f.key&&h.type===f.type){v[d]=void 0;break}f=null}br(e,h,f=f||Yn,o,i,s,a,c,u),p=h.__e,(d=h.ref)&&f.ref!=d&&(b||(b=[]),f.ref&&b.push(f.ref,null,h),b.push(d,h.__c||p,h)),null!=p?(null==y&&(y=p),"function"==typeof h.type&&null!=h.__k&&h.__k===f.__k?h.__d=c=lr(h,c,e):c=dr(e,h,f,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&f.__e==c&&c.parentNode!=e&&(c=ir(f))}for(n.__e=y,l=m;l--;)null!=v[l]&&("function"==typeof n.type&&null!=v[l].__e&&v[l].__e==n.__d&&(n.__d=ir(r,l+1)),_r(v[l],v[l]));if(b)for(l=0;l<b.length;l++)gr(b[l],b[++l],b[++l])}function lr(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?lr(o,t,n):dr(n,o,o,e.__k,o.__e,t));return t}function dr(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function fr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Xn.test(t)?n:n+"px"}function hr(e,t,n,r,o){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||fr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||fr(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?yr:pr,i):e.removeEventListener(t,i?yr:pr,i);else if("dangerouslySetInnerHTML"!==t){if(o)t=t.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function pr(e){this.l[e.type+!1](qn.event?qn.event(e):e)}function yr(e){this.l[e.type+!0](qn.event?qn.event(e):e)}function br(e,t,n,r,o,i,s,a,c){var u,l,d,f,h,p,y,b,v,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=qn.__b)&&u(t);try{e:if("function"==typeof _){if(b=t.props,v=(u=_.contextType)&&r[u.__c],m=u?v?v.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(b,m):(t.__c=l=new or(b,m),l.constructor=_,l.render=wr),v&&v.sub(l),l.props=b,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=_.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=Zn({},l.__s)),Zn(l.__s,_.getDerivedStateFromProps(b,l.__s))),f=l.props,h=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(b,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(b,l.__s,m)||t.__v===n.__v){l.props=b,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(b,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,h,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=qn.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=Zn(Zn({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(f,h)),g=null!=u&&u.type===rr&&null==u.key?u.props.children:u,ur(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=mr(n.__e,t,n,r,o,i,s,c);(u=qn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),qn.__e(e,t,n)}}function vr(e,t){qn.__c&&qn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){qn.__e(e,t.__v)}}))}function mr(e,t,n,r,o,i,s,a){var c,u,l,d,f=n.props,h=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=i)for(;y<i.length;y++)if((c=i[y])&&(c===e||(p?c.localName==p:3==c.nodeType))){e=c,i[y]=null;break}if(null==e){if(null===p)return document.createTextNode(h);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,h.is&&h),i=null,a=!1}if(null===p)f===h||a&&e.data===h||(e.data=h);else{if(i=i&&Qn.slice.call(e.childNodes),u=(f=n.props||Yn).dangerouslySetInnerHTML,l=h.dangerouslySetInnerHTML,!a){if(null!=i)for(f={},d=0;d<e.attributes.length;d++)f[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||hr(e,i,null,n[i],r);for(i in t)o&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||hr(e,i,t[i],n[i],r)}(e,h,f,o,a),l)t.__k=[];else if(y=t.props.children,ur(e,Array.isArray(y)?y:[y],t,n,r,o&&"foreignObject"!==p,i,s,e.firstChild,a),null!=i)for(y=i.length;y--;)null!=i[y]&&er(i[y]);a||("value"in h&&void 0!==(y=h.value)&&(y!==e.value||"progress"===p&&!y)&&hr(e,"value",y,f.value,!1),"checked"in h&&void 0!==(y=h.checked)&&y!==e.checked&&hr(e,"checked",y,f.checked,!1))}return e}function gr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){qn.__e(e,n)}}function _r(e,t,n){var r,o,i;if(qn.unmount&&qn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||gr(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){qn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&_r(r[i],t,n);null!=o&&er(o)}function wr(e,t,n){return this.constructor(e,n)}qn={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},or.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Zn({},this.state),"function"==typeof e&&(e=e(Zn({},n),this.props)),e&&Zn(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),ar(this))},or.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),ar(this))},or.prototype.render=rr,zn=[],Gn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,cr.__r=0;const Sr={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},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"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function kr({children:e}){return tr("div",null,tr("div",{style:Sr.Darken}),tr("div",{style:Sr.DialogOuter},tr("div",{style:Sr.DialogInner},e)))}var xr,Er,Ir,Tr=0,Cr=[],Ar=qn.__b,Pr=qn.__r,Or=qn.diffed,Ur=qn.__c,Dr=qn.unmount;function $r(e,t){qn.__h&&qn.__h(Er,e,Tr||t),Tr=0;var n=Er.__H||(Er.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Nr(e){return Tr=1,function(e,t,n){var r=$r(xr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Mr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Er),r.__}(Mr,e)}function jr(e){return Tr=5,function(e,t){var n=$r(xr++,7);return Fr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Rr(){Cr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Br),e.__H.__h.forEach(Wr),e.__H.__h=[]}catch(t){e.__H.__h=[],qn.__e(t,e.__v)}})),Cr=[]}qn.__b=function(e){Er=null,Ar&&Ar(e)},qn.__r=function(e){Pr&&Pr(e),xr=0;var t=(Er=e.__c).__H;t&&(t.__h.forEach(Br),t.__h.forEach(Wr),t.__h=[])},qn.diffed=function(e){Or&&Or(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Cr.push(t)&&Ir===qn.requestAnimationFrame||((Ir=qn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Lr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Lr&&(t=requestAnimationFrame(n))})(Rr)),Er=void 0},qn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Br),e.__h=e.__h.filter((function(e){return!e.__||Wr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],qn.__e(n,e.__v)}})),Ur&&Ur(e,t)},qn.unmount=function(e){Dr&&Dr(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Br)}catch(e){qn.__e(e,t.__v)}};var Lr="function"==typeof requestAnimationFrame;function Br(e){var t=Er;"function"==typeof e.__c&&e.__c(),Er=t}function Wr(e){var t=Er;e.__c=e.__(),Er=t}function Fr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Mr(e,t){return"function"==typeof t?t(e):t}function Hr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Nr({}),a=jr();return function(e,t){var n=$r(xr++,4);!qn.__s&&Fr(n.__H,t)&&(n.__=e,n.__H=t,Er.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),tr(kr,null,tr(rr,null,tr("h3",{style:Sr.WindowHeader},e),t.map((e=>tr("p",{style:Sr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),tr("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>tr("label",{style:Sr.Label},n?`${n}: `:"",tr("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Sr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Vr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),tr("div",{style:Sr.ButtonsDiv},tr("button",{type:"submit",style:Sr.Button,onClick:()=>o(i)},"Submit"),tr("button",{style:Sr.Button,onClick:r},"Cancel")))}function Vr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Kr extends or{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?tr(Hr,Object.assign({},t)):null}}function qr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;qn.__&&qn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],br(t,e=(!r&&n||t).__k=tr(rr,null,[e]),o||Yn,Yn,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?Qn.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),vr(i,e)}(tr(Kr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function zr(n){const i=n.name,s=new t.BehaviorSubject(o),a=[];let c=null;n.on("ready",(async n=>{try{await async function(n){var o,i,d,f,h,p;u=!1;const y=nn(n);dn||((null===(o=y.cloud.options)||void 0===o?void 0:o.customLoginGui)||a.push(qr(n)),a.push(function(e){let n=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(Ue((e=>{const r=n;n=e;const o=t.of(e);switch(e){case"disconnected":return Cn.value?o.pipe(ie(500)):o;case"connecting":return"not-started"===r||"error"===r?o:o.pipe(ie(4e3));default:return o}})));return t.combineLatest([r,e.syncStateChangedEvent.pipe(Oe({phase:"initial"})),An]).pipe(Y((([t,n,r])=>{let{phase:o,error:i,progress:s}=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"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:Kt?a:"offline"}})))}(y).subscribe(n.cloud.syncState)));y.tables.every((e=>e.core))||fn();const b="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],v=await y.transaction("rw",y.$syncState,(async()=>{var e,t;const{options:n,schema:r}=y.cloud,[o,i,s]=await Promise.all([y.getOptions(),y.getSchema(),y.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await y.$syncState.put(n,"options"):y.cloud.options=o||null,(null===(e=y.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&b.length>0&&!ln?(console.debug("Dexie Cloud Addon: Using service worker"),y.cloud.usingServiceWorker=!0):((null===(t=y.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!dn&&console.debug("dexie-cloud-addon: Not using service worker.",0===b.length?"No SW registrations found.":"serviceWorker"in navigator&&ln?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),y.cloud.usingServiceWorker=!1),Kn(r,y.cloud.options),Kn(i,y.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]={...n}}await y.$syncState.put(e,"schema"),Object.assign(r,e)}}else y.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));v&&y.setInitiallySynced(!0);(function(e){var t,n;for(const o of e.tables)if(null===(n=null===(t=e.cloud.schema)||void 0===t?void 0:t[o.name])||void 0===n?void 0:n.markedForSync){if(o.schema.primKey.auto)throw new r.default.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new r.default.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(y),(null===(i=y.cloud.options)||void 0===i?void 0:i.databaseUrl)&&!v&&(await async function(e,t,n){console.debug("Performing initial sync"),await Tn(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await Gt(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(y,y.cloud.options,y.cloud.schema),y.setInitiallySynced(!0));l(),dn||(a.push(e.liveQuery((()=>y.getCurrentUser())).subscribe(s)),a.push(e.liveQuery((()=>y.getPersistedSyncState())).subscribe(y.cloud.persistedSyncState)),await t.combineLatest([s.pipe(Ce(1),Ee(1)),y.cloud.persistedSyncState.pipe(Ce(1),Ee(1))]).toPromise());(null===(d=y.cloud.options)||void 0===d?void 0:d.requireAuth)&&await sn(y);c&&c.stop();c=null,l(),y.cloud.usingServiceWorker&&(null===(f=y.cloud.options)||void 0===f?void 0:f.databaseUrl)?(wt(y,"push").catch((()=>{})),async function(e){var t;try{const{periodicSync:n}=await navigator.serviceWorker.ready;if(n)try{await n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${e.name}`)}catch(e){console.debug("Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.",e)}else console.debug("Dexie Cloud: periodicSync not supported.")}catch(t){console.debug(`Dexie Cloud: Could not register periodicSync for ${e.name}`,t)}}(y).catch((()=>{}))):(null===(h=y.cloud.options)||void 0===h?void 0:h.databaseUrl)&&y.cloud.schema&&!dn&&(c=Vn(y,y.cloud.options,y.cloud.schema),c.start(),St(y,"push"));l(),dn||a.push(t.fromEvent(self,"online").subscribe((()=>{console.debug("online!"),y.syncStateChangedEvent.next({phase:"not-in-sync"}),St(y,"push")})),t.fromEvent(self,"offline").subscribe((()=>{console.debug("offline!"),y.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!dn&&(null===(p=y.cloud.options)||void 0===p?void 0:p.databaseUrl)&&a.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(Se((e=>e)),Ue((()=>e.getPersistedSyncState())),Se((e=>e&&e.serverRevision)),Y((e=>({type:"ready",rev:e.serverRevision}))));return function n(){return e.cloud.persistedSyncState.pipe(Se((e=>null==e?void 0:e.serverRevision)),Ee(1),Ue((()=>e.cloud.currentUser)),Ue((e=>An.pipe(Y((t=>t?e:null))))),Ue((n=>n?new Rn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n.accessToken,n.accessTokenExpiration):t.from([]))),M((r=>"TokenExpiredError"===(null==r?void 0:r.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),t.of(!0).pipe(Ue((async()=>{const t=await e.getCurrentUser(),n=await Wt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Ue((()=>n())))):t.throwError(r))),M((e=>t.from(Wn(e)).pipe(Ue((()=>n()))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(y))}(n)}catch(e){console.error(e)}}),!0);let u=!1;function l(){if(u)throw new r.default.DatabaseClosedError}var d;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{a.forEach((e=>e.unsubscribe())),u=!0,c&&c.stop(),c=null,s.next(o)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return s.value.userId||o.userId},currentUser:s,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),async login(e){const t=nn(n);await t.cloud.sync(),await sn(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,nn(n).reconfigure()),Kn(n.cloud.schema,n.cloud.options)},async sync({wait:r,purpose:o}={wait:!0,purpose:"push"}){void 0===r&&(r=!0);const i=nn(n);if("pull"===o){const e=i.cloud.persistedSyncState.value;if(St(i,o),r){const t=await i.cloud.persistedSyncState.pipe(Se((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))),Ee(1)).toPromise();if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(await Fn(i)){const n=i.cloud.persistedSyncState.value;St(i,o),r&&(console.debug("db.cloud.login() is waiting for sync completion..."),await t.from(e.liveQuery((async()=>{const e=await Fn(i),t=await i.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(Se((e=>!e)),Ee(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=r.default.override(n.Version.prototype._parseStoresSpec,(e=>En(e,n))),n.use(xn({currentUserObservable:n.cloud.currentUser,db:nn(n)})),n.use((d=nn(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>({...e,table:t=>{const n=e.table(t);return{...n,mutate:e=>{var r,o,i;const s=e.trans;if((null===(o=null===(r=d.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(i=s.currentUser)||void 0===i?void 0:i.isLoggedIn)&&("add"===e.type||"put"===e.type))for(const t of e.values)"owner"in t||(t.owner=s.currentUser.userId),"realmId"in t||(t.realmId=s.currentUser.userId);return n.mutate(e)}}}})})),n.use(mn(nn(n)))}zr.version="1.0.0-beta.10",r.default.Cloud=zr;const Gr=new Map;function Jr(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const Yr=new Map;function Qr(e,t){let n=Yr.get(e+"/"+t);return n||(n=async function(e,t){var n;let o=Gr.get(e);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",e);const t=new r.default(e,{addons:[zr]});o=nn(t),t.on("versionchange",i),await o.dx.open(),Gr.get(e)||Gr.set(e,o)}if(!(null===(n=o.cloud.options)||void 0===n?void 0:n.databaseUrl))return void console.error("Dexie Cloud: No databaseUrl configured");if(!o.cloud.schema)return void console.error("Dexie Cloud: No schema persisted");function i(){return o.dx.on.versionchange.unsubscribe(i),Gr.get(o.name)===o&&Gr.delete(o.name),o.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await Hn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:t}),console.debug("Dexie Cloud SW: Done Syncing")}catch(e){if(console.error("Dexie Cloud SW Error",e),i(),e.name!==r.default.errnames.NoSuchDatabase)throw e}}(e,t).then((()=>{Yr.delete(e+"/"+t)})).catch((n=>(Yr.delete(e+"/"+t),Promise.reject(n)))),Yr.set(e+"/"+t,n)),n}ln||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=Jr(e.tag);t&&e.waitUntil(Qr(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=Jr(e.tag);t&&e.waitUntil(Qr(t,"pull"))})),self.addEventListener("message",(e=>{if(console.debug('SW "message" Event',e.data),"dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>Qr(t,e.data.purpuse||"pull").catch((async e=>{if(3===r)throw e;var t;await(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}));"waitUntil"in e?e.waitUntil(n().catch((e=>console.error(e)))):n().catch((e=>console.error(e)))}})))}));
|
|
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";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);const o={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(o),Object.freeze(o.claims)}catch(e){}const i={},s=self.document&&navigator.serviceWorker;s&&s.ready.then((e=>i.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 a{constructor(e){this.name=e}subscribe(e){if(!s)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 s.addEventListener("message",t),()=>s.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}))):i.registration&&(null===(t=i.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class c extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new a(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof a?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof a?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",{...e},"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}var u=function(e,t){return(u=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])})(e,t)};function l(e,t){function n(){this.constructor=e}u(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function d(e){return"function"==typeof e}var f=!1,h={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;f=e},get useDeprecatedSynchronousErrorHandling(){return f}};function p(e){setTimeout((function(){throw e}),0)}var y={closed:!0,next:function(e){},error:function(e){if(h.useDeprecatedSynchronousErrorHandling)throw e;p(e)},complete:function(){}},b=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function v(e){return null!==e&&"object"==typeof e}var m=function(){function e(e){return Error.call(this),this.message=e?e.length+" errors occurred during unsubscription:\n"+e.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=e,this}return e.prototype=Object.create(Error.prototype),e}(),g=function(){function e(e){this.closed=!1,this._parentOrParents=null,this._subscriptions=null,e&&(this._ctorUnsubscribe=!0,this._unsubscribe=e)}return e.prototype.unsubscribe=function(){var t;if(!this.closed){var n=this,r=n._parentOrParents,o=n._ctorUnsubscribe,i=n._unsubscribe,s=n._subscriptions;if(this.closed=!0,this._parentOrParents=null,this._subscriptions=null,r instanceof e)r.remove(this);else if(null!==r)for(var a=0;a<r.length;++a){r[a].remove(this)}if(d(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof m?_(e.errors):[e]}}if(b(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(v(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof m?t=t.concat(_(e.errors)):t.push(e)}}}if(t)throw new m(t)}},e.prototype.add=function(t){var n=t;if(!t)return e.EMPTY;switch(typeof t){case"function":n=new e(t);case"object":if(n===this||n.closed||"function"!=typeof n.unsubscribe)return n;if(this.closed)return n.unsubscribe(),n;if(!(n instanceof e)){var r=n;(n=new e)._subscriptions=[r]}break;default:throw new Error("unrecognized teardown "+t+" added to Subscription.")}var o=n._parentOrParents;if(null===o)n._parentOrParents=this;else if(o instanceof e){if(o===this)return n;n._parentOrParents=[o,this]}else{if(-1!==o.indexOf(this))return n;o.push(this)}var i=this._subscriptions;return null===i?this._subscriptions=[n]:i.push(n),n},e.prototype.remove=function(e){var t=this._subscriptions;if(t){var n=t.indexOf(e);-1!==n&&t.splice(n,1)}},e.EMPTY=function(e){return e.closed=!0,e}(new e),e}();function _(e){return e.reduce((function(e,t){return e.concat(t instanceof m?t.errors:t)}),[])}var w=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),S=function(e){function t(n,r,o){var i=e.call(this)||this;switch(i.syncErrorValue=null,i.syncErrorThrown=!1,i.syncErrorThrowable=!1,i.isStopped=!1,arguments.length){case 0:i.destination=y;break;case 1:if(!n){i.destination=y;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new k(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new k(i,n,r,o)}return i}return l(t,e),t.prototype[w]=function(){return this},t.create=function(e,n,r){var o=new t(e,n,r);return o.syncErrorThrowable=!1,o},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))},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.destination.complete(),this.unsubscribe()},t.prototype._unsubscribeAndRecycle=function(){var e=this._parentOrParents;return this._parentOrParents=null,this.unsubscribe(),this.closed=!1,this.isStopped=!1,this._parentOrParents=e,this},t}(g),k=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return d(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==y&&(d((a=Object.create(n)).unsubscribe)&&s.add(a.unsubscribe.bind(a)),a.unsubscribe=s.unsubscribe.bind(s))),s._context=a,s._next=i,s._error=r,s._complete=o,s}return l(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?this.__tryOrSetError(t,this._next,e)&&this.unsubscribe():this.__tryOrUnsub(this._next,e)}},t.prototype.error=function(e){if(!this.isStopped){var t=this._parentSubscriber,n=h.useDeprecatedSynchronousErrorHandling;if(this._error)n&&t.syncErrorThrowable?(this.__tryOrSetError(t,this._error,e),this.unsubscribe()):(this.__tryOrUnsub(this._error,e),this.unsubscribe());else if(t.syncErrorThrowable)n?(t.syncErrorValue=e,t.syncErrorThrown=!0):p(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;p(e)}}},t.prototype.complete=function(){var e=this;if(!this.isStopped){var t=this._parentSubscriber;if(this._complete){var n=function(){return e._complete.call(e._context)};h.useDeprecatedSynchronousErrorHandling&&t.syncErrorThrowable?(this.__tryOrSetError(t,n),this.unsubscribe()):(this.__tryOrUnsub(n),this.unsubscribe())}else this.unsubscribe()}},t.prototype.__tryOrUnsub=function(e,t){try{e.call(this._context,t)}catch(e){if(this.unsubscribe(),h.useDeprecatedSynchronousErrorHandling)throw e;p(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!h.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return h.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(p(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(S);var x=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function E(e){return e}function I(e){return 0===e.length?E:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var T=function(){function e(e){this._isScalar=!1,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=this.operator,o=function(e,t,n){if(e){if(e instanceof S)return e;if(e[w])return e[w]()}return e||t||n?new S(e,t,n):new S(y)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||h.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),h.useDeprecatedSynchronousErrorHandling&&o.syncErrorThrowable&&(o.syncErrorThrowable=!1,o.syncErrorThrown))throw o.syncErrorValue;return o},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){h.useDeprecatedSynchronousErrorHandling&&(e.syncErrorThrown=!0,e.syncErrorValue=t),!function(e){for(;e;){var t=e,n=t.closed,r=t.destination,o=t.isStopped;if(n||o)return!1;e=r&&r instanceof S?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=C(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),o&&o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t=this.source;return t&&t.subscribe(e)},e.prototype[x]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return 0===e.length?this:I(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=C(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 C(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var A=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function P(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var O=P(),U=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function D(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var $=function(e){if(e&&"function"==typeof e[x])return r=e,function(e){var t=r[x]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(U(e))return A(e);if(D(e))return n=e,function(e){return n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,p),e};if(e&&"function"==typeof e[O])return t=e,function(e){for(var n=t[O]();;){var r=void 0;try{r=n.next()}catch(t){return e.error(t),e}if(r.done){e.complete();break}if(e.next(r.value),e.closed)break}return"function"==typeof n.return&&e.add((function(){n.return&&n.return()})),e};var t,n,r,o=v(e)?"an invalid object":"'"+e+"'";throw new TypeError("You provided "+o+" where a stream was expected. You can provide an Observable, Promise, Array, or Iterable.")},N=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return l(t,e),t.prototype._next=function(e){this.parent.notifyNext(e)},t.prototype._error=function(e){this.parent.notifyError(e),this.unsubscribe()},t.prototype._complete=function(){this.parent.notifyComplete(),this.unsubscribe()},t}(S),j=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return l(t,e),t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyError=function(e){this.destination.error(e)},t.prototype.notifyComplete=function(){this.destination.complete()},t}(S);function R(e,t){if(!t.closed){if(e instanceof T)return e.subscribe(t);var n;try{n=$(e)(t)}catch(e){t.error(e)}return n}}var L=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 l(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),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;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=!1,r=void 0;try{this.work(e)}catch(e){n=!0,r=!!e&&e||new Error(e)}if(n)return this.unsubscribe(),r},t.prototype._unsubscribe=function(){var e=this.id,t=this.scheduler,n=t.actions,r=n.indexOf(this);this.work=null,this.state=null,this.pending=!1,this.scheduler=null,-1!==r&&n.splice(r,1),null!=e&&(this.id=this.recycleAsyncId(t,e,null)),this.delay=null},t}(function(e){function t(t,n){return e.call(this)||this}return l(t,e),t.prototype.schedule=function(e,t){return this},t}(g)),B=function(){function e(t,n){void 0===n&&(n=e.now),this.SchedulerAction=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.SchedulerAction(this,e).schedule(n,t)},e.now=function(){return Date.now()},e}(),W=new(function(e){function t(n,r){void 0===r&&(r=B.now);var o=e.call(this,n,(function(){return t.delegate&&t.delegate!==o?t.delegate.now():r()}))||this;return o.actions=[],o.active=!1,o.scheduled=void 0,o}return l(t,e),t.prototype.schedule=function(n,r,o){return void 0===r&&(r=0),t.delegate&&t.delegate!==this?t.delegate.schedule(n,r,o):e.prototype.schedule.call(this,n,r,o)},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}(B))(L);function F(e){return e&&"function"==typeof e.schedule}function M(e){return function(t){var n=new H(e),r=t.lift(n);return n.caught=r}}var H=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new V(e,this.selector,this.caught))},e}(),V=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return l(t,e),t.prototype.error=function(t){if(!this.isStopped){var n=void 0;try{n=this.selector(t,this.caught)}catch(t){return void e.prototype.error.call(this,t)}this._unsubscribeAndRecycle();var r=new N(this);this.add(r);var o=R(n,r);o!==r&&this.add(o)}},t}(j);function K(e,t){return new T((function(n){var r=new g,o=0;return r.add(t.schedule((function(){o!==e.length?(n.next(e[o++]),n.closed||r.add(this.schedule())):n.complete()}))),r}))}function q(e,t){return t?K(e,t):new T(A(e))}function z(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[x]}(e))return function(e,t){return new T((function(n){var r=new g;return r.add(t.schedule((function(){var o=e[x]();r.add(o.subscribe({next:function(e){r.add(t.schedule((function(){return n.next(e)})))},error:function(e){r.add(t.schedule((function(){return n.error(e)})))},complete:function(){r.add(t.schedule((function(){return n.complete()})))}}))}))),r}))}(e,t);if(D(e))return function(e,t){return new T((function(n){var r=new g;return r.add(t.schedule((function(){return e.then((function(e){r.add(t.schedule((function(){n.next(e),r.add(t.schedule((function(){return n.complete()})))})))}),(function(e){r.add(t.schedule((function(){return n.error(e)})))}))}))),r}))}(e,t);if(U(e))return K(e,t);if(function(e){return e&&"function"==typeof e[O]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new T((function(n){var r,o=new g;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[O](),o.add(t.schedule((function(){if(!n.closed){var e,t;try{var o=r.next();e=o.value,t=o.done}catch(e){return void n.error(e)}t?n.complete():(n.next(e),this.schedule())}})))}))),o}))}(e,t)}throw new TypeError((null!==e&&typeof e||e)+" is not observable")}function G(e,t){return t?z(e,t):e instanceof T?e:new T($(e))}function J(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return F(n)?(e.pop(),K(e,n)):q(e)}function Y(e,t){return function(n){if("function"!=typeof e)throw new TypeError("argument is not a function. Are you looking for `mapTo()`?");return n.lift(new Q(e,t))}}var Q=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new X(e,this.project,this.thisArg))},e}(),X=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.project=n,o.count=0,o.thisArg=r||o,o}return l(t,e),t.prototype._next=function(e){var t;try{t=this.project.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}this.destination.next(t)},t}(S);function Z(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(Z((function(n,r){return G(e(n,r)).pipe(Y((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new ee(e,n))})}var ee=function(){function e(e,t){void 0===t&&(t=Number.POSITIVE_INFINITY),this.project=e,this.concurrent=t}return e.prototype.call=function(e,t){return t.subscribe(new te(e,this.project,this.concurrent))},e}(),te=function(e){function t(t,n,r){void 0===r&&(r=Number.POSITIVE_INFINITY);var o=e.call(this,t)||this;return o.project=n,o.concurrent=r,o.hasCompleted=!1,o.buffer=[],o.active=0,o.index=0,o}return l(t,e),t.prototype._next=function(e){this.active<this.concurrent?this._tryNext(e):this.buffer.push(e)},t.prototype._tryNext=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this.active++,this._innerSub(t)},t.prototype._innerSub=function(e){var t=new N(this),n=this.destination;n.add(t);var r=R(e,t);r!==t&&n.add(r)},t.prototype._complete=function(){this.hasCompleted=!0,0===this.active&&0===this.buffer.length&&this.destination.complete(),this.unsubscribe()},t.prototype.notifyNext=function(e){this.destination.next(e)},t.prototype.notifyComplete=function(){var e=this.buffer;this.active--,e.length>0?this._next(e.shift()):0===this.active&&this.hasCompleted&&this.destination.complete()},t}(j);function ne(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),Z(E,e)}function re(){return ne(1)}function oe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return re()(J.apply(void 0,e))}function ie(e,t){return void 0===t&&(t=W),function(n){return n.lift(new se(e,t))}}var se=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ae(e,this.dueTime,this.scheduler))},e}(),ae=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.dueTime=n,o.scheduler=r,o.debouncedSubscription=null,o.lastValue=null,o.hasValue=!1,o}return l(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(ce,this.dueTime,this))},t.prototype._complete=function(){this.debouncedNext(),this.destination.complete()},t.prototype.debouncedNext=function(){if(this.clearDebounce(),this.hasValue){var e=this.lastValue;this.lastValue=null,this.hasValue=!1,this.destination.next(e)}},t.prototype.clearDebounce=function(){var e=this.debouncedSubscription;null!==e&&(this.remove(e),e.unsubscribe(),this.debouncedSubscription=null)},t}(S);function ce(e){e.debouncedNext()}function ue(e){return e instanceof Date&&!isNaN(+e)}var le=new T((function(e){return e.complete()}));function de(e){return e?function(e){return new T((function(t){return e.schedule((function(){return t.complete()}))}))}(e):le}function fe(e,t){return new T(t?function(n){return t.schedule(he,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function he(e){var t=e.error;e.subscriber.error(t)}var pe=function(){function e(e,t,n){this.kind=e,this.value=t,this.error=n,this.hasValue="N"===e}return e.prototype.observe=function(e){switch(this.kind){case"N":return e.next&&e.next(this.value);case"E":return e.error&&e.error(this.error);case"C":return e.complete&&e.complete()}},e.prototype.do=function(e,t,n){switch(this.kind){case"N":return e&&e(this.value);case"E":return t&&t(this.error);case"C":return n&&n()}},e.prototype.accept=function(e,t,n){return e&&"function"==typeof e.next?this.observe(e):this.do(e,t,n)},e.prototype.toObservable=function(){switch(this.kind){case"N":return J(this.value);case"E":return fe(this.error);case"C":return de()}throw new Error("unexpected notification kind value")},e.createNext=function(t){return void 0!==t?new e("N",t):e.undefinedValueNotification},e.createError=function(t){return new e("E",void 0,t)},e.createComplete=function(){return e.completeNotification},e.completeNotification=new e("C"),e.undefinedValueNotification=new e("N",void 0),e}();function ye(e,t){void 0===t&&(t=W);var n=ue(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new be(n,t))}}var be=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ve(e,this.delay,this.scheduler))},e}(),ve=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.delay=n,o.scheduler=r,o.queue=[],o.active=!1,o.errored=!1,o}return l(t,e),t.dispatch=function(e){for(var t=e.source,n=t.queue,r=e.scheduler,o=e.destination;n.length>0&&n[0].time-r.now()<=0;)n.shift().notification.observe(o);if(n.length>0){var i=Math.max(0,n[0].time-r.now());this.schedule(e,i)}else this.unsubscribe(),t.active=!1},t.prototype._schedule=function(e){this.active=!0,this.destination.add(e.schedule(t.dispatch,this.delay,{source:this,destination:this.destination,scheduler:e}))},t.prototype.scheduleNotification=function(e){if(!0!==this.errored){var t=this.scheduler,n=new me(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(pe.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(pe.createComplete()),this.unsubscribe()},t}(S),me=function(){return function(e,t){this.time=e,this.notification=t}}();var ge=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new _e(e,this.compare,this.keySelector))},e}(),_e=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.keySelector=r,o.hasKey=!1,"function"==typeof n&&(o.compare=n),o}return l(t,e),t.prototype.compare=function(e,t){return e===t},t.prototype._next=function(e){var t;try{var n=this.keySelector;t=n?n(e):e}catch(e){return this.destination.error(e)}var r=!1;if(this.hasKey)try{r=(0,this.compare)(this.key,t)}catch(e){return this.destination.error(e)}else this.hasKey=!0;r||(this.key=t,this.destination.next(e))},t}(S),we=function(){function e(){return Error.call(this),this.message="argument out of range",this.name="ArgumentOutOfRangeError",this}return e.prototype=Object.create(Error.prototype),e}();function Se(e,t){return function(n){return n.lift(new ke(e,t))}}var ke=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new xe(e,this.predicate,this.thisArg))},e}(),xe=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.predicate=n,o.thisArg=r,o.count=0,o}return l(t,e),t.prototype._next=function(e){var t;try{t=this.predicate.call(this.thisArg,e,this.count++)}catch(e){return void this.destination.error(e)}t&&this.destination.next(e)},t}(S);function Ee(e){return function(t){return 0===e?de():t.lift(new Ie(e))}}var Ie=function(){function e(e){if(this.total=e,this.total<0)throw new we}return e.prototype.call=function(e,t){return t.subscribe(new Te(e,this.total))},e}(),Te=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return l(t,e),t.prototype._next=function(e){var t=this.total,n=++this.count;n<=t&&(this.destination.next(e),n===t&&(this.destination.complete(),this.unsubscribe()))},t}(S);function Ce(e){return function(t){return t.lift(new Ae(e))}}var Ae=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new Pe(e,this.total))},e}(),Pe=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return l(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(S);function Oe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return F(n)?(e.pop(),function(t){return oe(e,t,n)}):function(t){return oe(e,t)}}function Ue(e,t){return"function"==typeof t?function(n){return n.pipe(Ue((function(n,r){return G(e(n,r)).pipe(Y((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new De(e))}}var De=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new $e(e,this.project))},e}(),$e=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return l(t,e),t.prototype._next=function(e){var t,n=this.index++;try{t=this.project(e,n)}catch(e){return void this.destination.error(e)}this._innerSub(t)},t.prototype._innerSub=function(e){var t=this.innerSubscription;t&&t.unsubscribe();var n=new N(this),r=this.destination;r.add(n),this.innerSubscription=R(e,n),this.innerSubscription!==n&&r.add(this.innerSubscription)},t.prototype._complete=function(){var t=this.innerSubscription;t&&!t.closed||e.prototype._complete.call(this),this.unsubscribe()},t.prototype._unsubscribe=function(){this.innerSubscription=void 0},t.prototype.notifyComplete=function(){this.innerSubscription=void 0,this.isStopped&&e.prototype._complete.call(this)},t.prototype.notifyNext=function(e){this.destination.next(e)},t}(j);function Ne(){}function je(e,t,n){return function(r){return r.lift(new Re(e,t,n))}}var Re=function(){function e(e,t,n){this.nextOrObserver=e,this.error=t,this.complete=n}return e.prototype.call=function(e,t){return t.subscribe(new Le(e,this.nextOrObserver,this.error,this.complete))},e}(),Le=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=Ne,i._tapError=Ne,i._tapComplete=Ne,i._tapError=r||Ne,i._tapComplete=o||Ne,d(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||Ne,i._tapError=n.error||Ne,i._tapComplete=n.complete||Ne),i}return l(t,e),t.prototype._next=function(e){try{this._tapNext.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.next(e)},t.prototype._error=function(e){try{this._tapError.call(this._context,e)}catch(e){return void this.destination.error(e)}this.destination.error(e)},t.prototype._complete=function(){try{this._tapComplete.call(this._context)}catch(e){return void this.destination.error(e)}return this.destination.complete()},t}(S),Be=function(){function e(){return Error.call(this),this.message="Timeout has occurred",this.name="TimeoutError",this}return e.prototype=Object.create(Error.prototype),e}();var We=function(){function e(e,t,n,r){this.waitFor=e,this.absoluteTimeout=t,this.withObservable=n,this.scheduler=r}return e.prototype.call=function(e,t){return t.subscribe(new Fe(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Fe=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.absoluteTimeout=n,s.waitFor=r,s.withObservable=o,s.scheduler=i,s.scheduleTimeout(),s}return l(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(R(t,new N(e)))},t.prototype.scheduleTimeout=function(){var e=this.action;e?this.action=e.schedule(this,this.waitFor):this.add(this.action=this.scheduler.schedule(t.dispatchTimeout,this.waitFor,this))},t.prototype._next=function(t){this.absoluteTimeout||this.scheduleTimeout(),e.prototype._next.call(this,t)},t.prototype._unsubscribe=function(){this.action=void 0,this.scheduler=null,this.withObservable=null},t}(j);function Me(e,t){return void 0===t&&(t=W),function(e,t,n){return void 0===n&&(n=W),function(r){var o=ue(e),i=o?+e-n.now():Math.abs(e);return r.lift(new We(i,o,t,n))}}(e,fe(new Be),t)}let He=!1;async function Ve(e,t){try{const n=await navigator.serviceWorker.ready;return"push"===t&&n.sync&&await n.sync.register(`dexie-cloud:${e.name}`),void(n.active?n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t}):console.error("Dexie Cloud: There's no active service worker. Can this ever happen??"))}catch(e){He||(console.debug("Dexie Cloud: Could not register sync event",e),He=!0)}}function Ke(e,t){e.cloud.usingServiceWorker?Ve(e,t):e.localSyncEvent.next({purpose:t})}const qe="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var o=0;o<n;o++)r[o]=t.charCodeAt(o);return r},ze="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>btoa(String.fromCharCode.apply(null,e));async function Ge({realms:e,inviteRealms:t}){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),o=await crypto.subtle.digest("SHA-1",r);return ze(o)}function Je(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function Ye(e){return`$${e}_mutations`}function Qe(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}async function Xe(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=Qe(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return{table:t,muts:await i.toArray()}})))).filter((({muts:e})=>e.length>0))}const Ze=crypto.getRandomValues;function et(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){!function(e){if(!e)throw new Error("Assertion Failed")}("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)et(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c||(c=e[s]={}),et(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const tt="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Ze(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function nt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>nt(e)))&&e.every(rt))}function rt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(rt)}function ot(e,t,n){const r=e[t]||(e[t]={});switch(n.type){case"insert":case"upsert":n.keys.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":n.keys.forEach(((e,t)=>{const o="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(o))et(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,o)}else r[e]={type:"upd",mod:o}}));break;case"delete":n.keys.forEach((e=>{r[e]={type:"del"}}))}return e}function it(e,t){for(const{table:n,muts:r}of t)for(const t of r)ot(e,n,t)}function st(e,t){return new Promise(((n,o)=>{const i={...t,onSubmit:t=>{e.next(void 0),n(t)},onCancel:()=>{e.next(void 0),o(new r.default.AbortError("User cancelled"))}};e.next(i)}))}function at(e,t,...n){return st(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function ct(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await st(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}async function ut(e,t,n){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:o}=await st(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function lt(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await dt(e,t):await async function(e,t,n,r){const{privateKey:o,publicKey:i}=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);e.nonExportablePrivateKey=o;const s=function(e){const t=ze(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)}(await crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=await t({public_key:s,hints:r});if("tokens"!==o.type)throw new Error(`Unexpected response type from token endpoint: ${o.type}`);return e.accessToken=o.accessToken,e.accessTokenExpiration=new Date(o.accessTokenExpiration),e.refreshToken=o.refreshToken,o.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(o.refreshTokenExpiration)),e.userId=o.claims.sub,e.email=o.claims.email,e.name=o.claims.name,e.claims=o.claims,o.alerts&&o.alerts.length>0&&await st(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await at(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem to authenticate rigth now.",messageParams:{}}).catch((()=>{})),e}}(t,n,r,o)}async function dt(e,t){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",o=(new TextEncoder).encode(t.refreshToken+n),i=await crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=ze(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=await fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=await c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}const{toString:ft}={};const ht={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 t of n)delete r[t],r["$"+t]=e[t];return r}};function pt(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify:(e,r,o)=>JSON.stringify(e,(function(e){const o=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 ht;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,ft.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:ht),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o),parse(e,n){let r=null,o=[];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}if(i===r){if(o.length>0){i={...i};for(const e of o)i[e.substr(1)]=i[e],delete i[e]}return o=[],i}return"$"===e[0]&&"$t"!==e&&(r=this,o.push(e)),i}))}}}const yt={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 bt={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 vt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var mt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},gt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},_t={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const wt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var St=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=wt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function kt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=It[e[n]];return t}(ze(e))}function xt(e){return qe(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+=Et[e[n]];return t}(e))}const Et={"-":"=",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:"+","|":"/"},It={};for(const e of Object.keys(Et))It[Et[e]]=e;var Tt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:kt(e)}),revive:({v:e})=>{const t=xt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ct{constructor(e,t){this.buf=e,this.type=t}}function At(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 Pt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const Ot={...bt,...vt,...mt,...gt,..._t,...St,...Tt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof Ct,replace:e=>({$t:"Blob",v:ze(e instanceof Ct?e.buf:Pt(At(e))),type:e.type}),revive:({type:e,v:t})=>{const n=qe(t);return void 0!==typeof Blob?new Blob([n]):new Ct(n.buffer,e)}}}};function Ut(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 Dt={undefined:{replace:()=>{},revive:()=>{}}};const $t="bigint"==typeof BigInt(0);class Nt{constructor(e){this.v=e}toString(){return this.v}}const jt={...Dt,...$t?{}:{bigint:{test:e=>e instanceof Nt,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new Nt(e)}}},Rt=pt(Ot,jt),Lt=function(...e){const t=pt(Ot,yt,...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);return[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])}))),r]},async parse(e,n){let r=0;const o=[],i=await Ut(n),s=new DataView(i);for(;r<i.byteLength;){const e=s.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await Ut(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)}}}(jt);class Bt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function Wt(e,t,n,r,o,i,s){const a={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},c=await async function(e){var t,n;const r=await e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=await dt(e.cloud.options.databaseUrl,r);return await e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}(r);c&&(a.Authorization=`Bearer ${c}`);const u={v:2,dbID:null==t?void 0:t.remoteDbId,clientIdentity:s,schema:i||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:e};console.debug("Sync request",u),r.syncStateChangedEvent.next({phase:"pushing"});const l=await fetch(`${o}/sync`,{method:"post",headers:a,body:Rt.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new Bt(l);switch(l.headers.get("content-type")){case"application/x-bison":return Lt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return Rt.parse(e)}}}async function Ft(e,t,n){const o=await e.bulkGet(t),i=[],s=[];t.forEach(((t,a)=>{const c=o[a];if(c){for(const[t,o]of Object.entries(n[a])){if(t===e.schema.primKey.keyPath)throw new Error("Cannot change primary key");r.default.setByKeyPath(c,t,o)}i.push(t),s.push(c)}})),await(null==e.schema.primKey.keyPath?e.bulkPut(s,i):e.bulkPut(s))}function Mt(e){if(null==e?void 0:e.cancelled)throw new r.default.AbortError("Operation was cancelled")}let Ht=navigator.onLine;async function Vt(e,t,n,r){await e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}function Kt(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}self.addEventListener("online",(()=>Ht=!0)),self.addEventListener("offline",(()=>Ht=!1));function qt(e,t,n,r){return zt.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((async o=>(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:Ht,syncOptions:r,error:o}),Ht&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),await new Promise((e=>setTimeout(e,500))),await qt(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Ht?"error":"offline",error:o}),Promise.reject(o)))))}async function zt(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:s,purpose:a}={isInitialSync:!1}){var c;if(s||console.debug("SYNC STARTED",{isInitialSync:r,purpose:a}),!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:u}=t,l=await e.getCurrentUser(),d=l.isLoggedIn?Je(e):[],f=d.map((t=>e.table(Ye(t.name)))),h=await e.getPersistedSyncState(),p=!r&&l.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Je(e).filter((e=>!n.includes(e.name)))}(e,h):[];Mt(i);const y=p.length>0;if(y){if(s)return!0;console.debug("sync doSyncify is true"),await e.transaction("rw",p,(async e=>{e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,await async function(e,t,n){const r=new Set(n||[]);for(const n of e)"members"===n.name?await n.toCollection().modify((e=>{r.has(e.realmId)||e.userId!==o.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==o.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==o.userId||(e.owner=t.userId),e.realmId&&e.realmId!==o.userId||(e.realmId=t.userId))})))}(p,l,null==h?void 0:h.realms)})),Mt(i)}const[b,v,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let o=await Xe(f);if(Mt(i),y){const e=await async function(e,t,n,r){if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(await Promise.all(e.map((async e=>{const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const i=n[e.name],s=(null==i?void 0:i.generatedGlobalId)?e.filter((e=>!o.has(e.realmId||"")&&nt(r(e)))):e.filter((e=>{return!o.has(e.realmId||"")&&(t=r(e),!(n=null==i?void 0:i.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=await s.toArray();if(a.length>0){const n={type:"insert",values:a,keys:a.map(r),userId:t.userId};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter((e=>e.muts.length>0))}return[]}(p,l,n,null==h?void 0:h.realms);return Mt(i),o=o.concat(e),[o,t,r]}return[o,t,r]})),g=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(s)return console.debug("Sync is needed:",g),g;if("push"===a&&!g)return!1;const _=Kt(b,null==v?void 0:v.latestRevisions),w=(null==v?void 0:v.clientIdentity)||tt(16);Mt(i);const S=await Wt(b,v,m,e,u,n,w);console.debug("Sync response",S);return await e.transaction("rw",e.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))S.schema[e]&&(n[e]=S.schema[e]);await e.$syncState.put(n,"schema");const r=await Xe(f,0,{since:_});for(const t of f){const n=Qe(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(_[t.name]){const r=_[t.name]||0;await 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 await Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}Kt(r,_),await Vt(e,n,_,S.serverRevision);const o=await e.getPersistedSyncState();await async function(e,t,n){const r=[],o=n?n.realms.concat(n.inviteRealms):[],i=new Set([...t.realms,...t.inviteRealms]);for(const e of o)i.has(e)||r.push(e);if(r.length>0){const t=new Set(r),n=Je(e);for(const e of n)e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?await e.where("realmId").anyOf(r).delete():await e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete()}}(e,S,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:w};i.syncedTables=d.map((e=>e.name)).concat(p.map((e=>e.name))),i.latestRevisions=_,i.remoteDbId=S.dbId,i.initiallySynced=!0,i.realms=S.realms,i.inviteRealms=S.inviteRealms,i.serverRevision=S.serverRevision,i.timestamp=new Date,delete i.error;const s=Jt(S.changes,r);return await Gt(s,e),e.$syncState.put(i,"syncState"),0===r.length}))?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),await zt(e,t,n,{isInitialSync:r,cancelToken:i}))}async function Gt(e,t){console.debug("Applying server changes",e,r.default.currentTransaction);for(const{table:n,muts:o}of e){const e=t.table(n);if(!e)continue;const{primaryKey:i}=e.core.schema;for(const t of o)switch(t.type){case"insert":i.outbound?await e.bulkAdd(t.values,t.keys):(t.keys.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),await e.bulkAdd(t.values));break;case"upsert":i.outbound?await e.bulkPut(t.values,t.keys):(t.keys.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),await e.bulkPut(t.values));break;case"modify":1===t.keys.length?await e.update(t.keys[0],t.changeSpec):await e.where(":id").anyOf(t.keys).modify(t.changeSpec);break;case"update":await Ft(e,t.keys,t.changeSpecs);break;case"delete":await e.bulkDelete(t.keys)}}}function Jt(e,t){const n={};it(n,e);const r={};return it(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":delete e[i][t];break;case"del":break;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===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))et(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=tt(16),n={};for(const[t,r]of Object.entries(e))for(const[e,o]of Object.entries(r)){const r=n[t]||(n[t]={});(r[o.type]||(r[o.type]=[])).push(Object.assign({key:e},o))}const r=[];for(const[e,o]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(o))switch(e){case"ups":{const e={type:"upsert",keys:r.map((e=>e.key)),values:r.map((e=>e.val)),txid:t};n.muts.push(e);break}case"upd":{const e={type:"update",keys:r.map((e=>e.key)),changeSpecs:r.map((e=>e.mod)),txid:t};n.muts.push(e);break}case"del":{const e={type:"delete",keys:r.map((e=>e.key)),txid:t};n.muts.push(e);break}}r.push(n)}return r}(n)}function Yt(e){const n=[],o=new t.BehaviorSubject(!0),i=new t.BehaviorSubject(null);let s=!1,a=0,c=[0,0,0,0,0,0,0,0,0,Date.now()];return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,c.shift(),c.push(Date.now()),o.next(!1);try{await async function(){var t,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await e.cloud.syncState.pipe(Se((({phase:e})=>"in-sync"===e||"error"===e)),Ee(1)).toPromise(),console.debug("processing msg",s);const n=e.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=e.cloud.currentUser.value,c=await dt(e.cloud.options.databaseUrl,a);await e.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"realm-added":(null===(t=null==n?void 0:n.realms)||void 0===t?void 0:t.includes(s.realm))||Ke(e,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&Ke(e,"pull");break;case"realms-changed":Ke(e,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=e.cloud.syncState.value)||void 0===i?void 0:i.phase)){Ke(e,"pull");break}await e.transaction("rw",e.dx.tables,(async t=>{t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,o,i]=await Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!n||!i)return void console.debug("required vars not present",{syncState:o,schema:n,currentUser:i});if(s.baseRev!==o.serverRevision)return console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`),void("string"!=typeof s.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||Ke(e,"pull"));const a=await r.default.waitFor(Ge(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void Ke(e,"pull");let c=[];if(i.isLoggedIn){const t=Je(e).map((t=>e.table(Ye(t.name))));c=await Xe(t),console.debug("msg queue: client changes",c)}if(s.changes.length>0){const t=Jt(s.changes,c);console.debug("applying filtered server changes",t),await Gt(t,e)}o.latestRevisions=Kt(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await Vt(e,n,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await e.$syncState.put(o,"syncState")})),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}()}finally{c[c.length-1]-c[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,await new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,await new Promise((e=>setTimeout(e,1e4))))),s=!1,o.next(!0)}}})),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:o}}const Qt=new WeakMap,Xt={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Zt=0;function en(e){"vip"in e&&(e=e.vip);let n=Qt.get(e.cloud);if(!n){const r=new t.Subject;let i=new c(`syncstatechanged-${e.name}`);r.id=++Zt;let s=!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 s},localSyncEvent:r,get syncStateChangedEvent(){return i},dx:e};const a={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||o)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema"),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){i=new c(`syncstatechanged-${e.name}`)}};Object.assign(n,a),n.messageConsumer=Yt(n),Qt.set(e.cloud,n)}return n}const tn=new WeakMap;class nn{constructor(e,t){tn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new nn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){tn.get(this).table("$logins").put(this)}}async function rn(e,t){if((await e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new nn(e,{claims:{},lastLogin:new Date(0)});await lt(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return async function({public_key:n,hints:r}){var o;let i;const s=null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!s)throw new Error("No database URL given.");i="demo"===(null==r?void 0:r.grant_type)?{demo_user:await ct(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}:{email:await ct(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=await a.text();throw await at(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Bt(a,e)}const c=await a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=await ut(t,i.email);i.otp=e||"",i.otp_id=c.otp_id;let n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=await n.text();i.otp=await ut(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=await fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=await n.text();throw await at(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Bt(n,e)}return await n.json()}throw new Error(`Unexpected response from ${s}/token`)}}(e),e.cloud.userInteraction,t),await n.save(),await async function(e,t){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");await e.transaction("rw",n,(async e=>{const r=await n.toArray();await Promise.all(r.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,await t.save(),console.debug("Saved new user",t.email)})),await new Promise((n=>{if(e.cloud.currentUserId===t.userId)n(null);else{const r=e.cloud.currentUser.subscribe((e=>{e.userId===t.userId&&(r.unsubscribe(),n(null))}))}}))}(e,n),Ke(e,"pull")}const on="undefined"!=typeof InstallTrigger,sn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),an=sn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,cn=sn&&an<=605||on;const un="undefined"!=typeof self&&"clients"in self&&!self.document;function ln(){throw new r.default.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:dn}={};function fn(e){return dn.call(e).slice(8,-1)}function hn(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 pn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let yn=0;function bn(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:t=>({...t,table:n=>{const o=t.table(n);function i(t,i){let s=null;const a=hn(o.schema.primaryKey,t);return a.forEach(((c,u)=>{if(void 0===c){const n=t.values[u].realmId||e.cloud.currentUserId,c=n.substr(n.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();yn>=o?++yn:yn=o,r[0]=yn/1099511627776,r[1]=yn/4294967296,r[2]=yn/16777216,r[3]=yn/65536,r[4]=yn/256,r[5]=yn;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+kt(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=t.values.slice()),s[u]=r.default.deepClone(s[u]),r.default.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new r.default.ConstraintError(`The ID "${c}" is not valid for table "${n}". Primary '@' keys requires the key to be prefixed with "${i}.\n"If you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate({...t,keys:a,values:s||t.values})}return{...o,mutate:t=>{var s,a;if(t.trans.disableChangeTracking)return o.mutate(t);if("add"===t.type||"put"===t.type){const c=null===(s=e.cloud.schema)||void 0===s?void 0:s[n];if(null==c?void 0:c.generatedGlobalId){if((null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!e.initiallySynced){const e=hn(o.schema.primaryKey,t);return o.getMany({keys:e,trans:t.trans,cache:"immutable"}).then((n=>{if(n.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(t)}))}return i(t,c.idPrefix)}if(null==c?void 0:c.markedForSync){hn(o.schema.primaryKey,t).forEach(((e,t)=>{if(!nt(e)){const t=Array.isArray(e)?e.map(fn).join(","):fn(e);throw new r.default.ConstraintError(`Invalid primary key type ${t} for table ${n}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(t)}}}})}}function vn(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let mn=0;function gn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function _n(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const wn=new t.BehaviorSubject(new Set);function Sn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){ln()}return{...n,transaction:(r,o)=>{let i;if("readwrite"===o){const e=r.filter((e=>{var n,r;return null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[e])||void 0===r?void 0:r.markedForSync})).map((e=>Ye(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=vn(16),i.currentUser=e.value,wn.value.add(i),wn.next(wn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),wn.value.delete(i),wn.next(wn.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),Ve(t,"push")):t.localSyncEvent.next({purpose:"push"})),n()};i.addEventListener("complete",r),i.addEventListener("error",n),i.addEventListener("abort",n)}return i},table:e=>{const t=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?{...t,mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),t.mutate(e))}:"$logins"===e?{...t,mutate:e=>(console.debug("Mutating $logins table",e),t.mutate(e).then((t=>(console.debug("Mutating $logins"),e.trans.mutationsAdded=!0,console.debug("$logins mutated"),t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e)))))}:t;const{schema:r}=t,i=o.get(e);return function(e){const t="$lock"+ ++mn;return{...e,count:gn(e.count,t),get:gn(e.get,t),getMany:gn(e.getMany,t),openCursor:gn(e.openCursor,t),query:gn(e.query,t),mutate:_n(e.mutate,t)}}({...t,mutate:e=>{var n;const o=e.trans;return o.txid?o.disableChangeTracking?t.mutate(e):(null===(n=o.currentUser)||void 0===n?void 0:n.isLoggedIn)?"deleteRange"===e.type?t.query({query:{range:e.range,index:r.primaryKey},trans:e.trans,values:!1}).then((t=>s({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}}))):s(e):t.mutate(e):t.mutate(e)}});function s(e){const n=e.trans;n.mutationsAdded=!0;const{txid:r,currentUser:{userId:o}}=n,{type:s}=e;return t.mutate(e).then((t=>{const{numFailures:a,failures:c}=t;let u="delete"===s?e.keys:t.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])),d=d.filter(((e,t)=>!c[t])));const f=Date.now(),h="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:f,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[h]}).then((()=>t)):t}))}}}}}}function kn(e,t){return function(n,r){const o={...Xt,...n},i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(pn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,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;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const xn=vn(16);async function En(n,r,o,i,{awaitRemoteJob:s}={}){const a=n.table(o);if(await async function i(){if(await n.transaction("rw!",o,(async()=>{const e=await a.get(r);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${r} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),await a.put({nodeId:xn,started:new Date,heartbeat:new Date},r),!0):(await a.add({nodeId:xn,started:new Date,heartbeat:new Date},r),!0)})))return!0;if(s)try{const n=t.from(e.liveQuery((()=>a.get(r)))).pipe(Me(6e4),Se((e=>!e)));return await n.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await i()}return!1}()){const e=setInterval((()=>{a.update(r,(e=>e.nodeId===xn&&(e.heartbeat=new Date)))}),1e3);try{return await i()}finally{clearInterval(e),await n.transaction("rw!",o,(async()=>{const e=await a.get(r);e&&e.nodeId===xn&&a.delete(r)}))}}}const In=new t.BehaviorSubject(!0),Tn=new t.BehaviorSubject(!0);var Cn,An;In.pipe(Ue((e=>e?t.of(!0):t.of(!1).pipe(ye(2e4)))),(function(e){return e.lift(new ge(Cn,An))})).subscribe(Tn);const Pn="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),On=Pn.pipe(Se((()=>"hidden"===document.visibilityState))),Un=Pn.pipe(Se((()=>"visible"===document.visibilityState))),Dn="undefined"!=typeof window?t.merge(Un,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),On,Dn).pipe(Y((()=>"visible"===document.visibilityState)),je((e=>{In.value!==e&&In.next(e)})),Ue((e=>e?t.of(0).pipe(ye(28e4),je((()=>In.next(!1)))):t.of(0)))).subscribe((()=>{}));class $n extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Nn extends t.Observable{constructor(e,t,n,r,o,i,s,a){super((c=>new Rn(e,t,n,r,s,a,c,o,i)))}}let jn=0;class Rn extends t.Subscription{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++jn,console.debug("New WebSocket Connection",this.id,o?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.realmSetHash=n,this.clientIdentity=r,this.token=o,this.tokenExpiration=i,this.subscriber=s,this.lastUserActivity=new Date,this.messageProducer=a,this.messageProducerSubscription=null,this.webSocketStatus=c,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),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,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){this.disconnect(),this.connect()}async connect(){if(this.webSocketStatus.next("connecting"),this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return void console.debug("WS not reconnecting just yet",{id:this.id,pauseUntil:this.pauseUntil});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;if(this.tokenExpiration&&this.tokenExpiration<new Date)return void this.subscriber.error(new $n);this.pinger=setInterval((async()=>{if(this.closed)return console.debug("pinger check",this.id,"CLOSED."),void this.teardown();if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{if(console.debug("pinger setTimeout",this.id,this.pinger?"alive":"dead"),this.pinger)return this.closed?(console.debug("pinger setTimeout",this.id,"subscription is closed"),void this.teardown()):void(this.lastServerActivity<new Date(Date.now()-2e4)?(console.debug("pinger: server is inactive"),console.debug("pinger reconnecting"),this.reconnect()):console.debug("pinger: server still active"))}),2e4)}catch(e){console.debug("pinger catch error",this.id,"reconnecting"),this.reconnect()}else console.debug("pinger",this.id,"reconnecting"),this.reconnect()}),3e4);const e=new URL(this.databaseUrl);e.protocol="http:"===e.protocol?"ws":"wss";const t=new URLSearchParams;if(this.subscriber.closed)return;t.set("v","2"),t.set("rev",this.rev),t.set("realmsHash",this.realmSetHash),t.set("clientId",this.clientIdentity),this.token&&t.set("token",this.token),console.debug("dexie-cloud WebSocket create");const n=this.ws=new WebSocket(`${e}/changes?${t}`);n.onclose=e=>{this.pinger&&(console.debug("dexie-cloud WebSocket onclosed",this.id),this.reconnect())},n.onmessage=e=>{if(this.pinger){console.debug("dexie-cloud WebSocket onmessage",e.data),this.lastServerActivity=new Date;try{const t=Rt.parse(e.data);if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);"rev"===t.type&&(this.rev=t.rev),"pong"!==t.type&&this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{await new Promise(((e,t)=>{n.onopen=t=>{console.debug("dexie-cloud WebSocket onopen"),e(null)},n.onerror=e=>{const n=e.error||new Error("WebSocket Error");this.disconnect(),this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}})),this.messageProducerSubscription=this.messageProducer.subscribe((e=>{var t;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),null===(t=this.ws)||void 0===t||t.send(Rt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Ln(e){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),await(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),await Dn.pipe(Ee(1)).toPromise(),console.debug("someone did something!")}async function Bn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await qt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Wn=new WeakMap;function Fn(e,t,n,r){const o=Wn.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),o.promise;{let i=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(i=!0)}));return o.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!i)return Fn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?un&&await qt(e,t,n,r):await En(e,"currentSyncWorker","$jobs",(()=>qt(e,t,n,r))),Wn.delete(e),console.debug("Done sync")}catch(t){throw Wn.delete(e),console.error("Failed to sync client changes",t),t}}();return Wn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Mn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){setTimeout((()=>{Fn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}),0)}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function Hn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Vn,Kn,qn,zn,Gn={},Jn=[],Yn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Qn(e,t){for(var n in t)e[n]=t[n];return e}function Xn(e){var t=e.parentNode;t&&t.removeChild(e)}function Zn(e,t,n){var r,o,i,s=arguments,a={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:a[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(a.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===a[i]&&(a[i]=e.defaultProps[i]);return er(e,a,r,o,null)}function er(e,t,n,r,o){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==o?++Vn.__v:o};return null!=Vn.vnode&&Vn.vnode(i),i}function tr(e){return e.children}function nr(e,t){this.props=e,this.context=t}function rr(e,t){if(null==t)return e.__?rr(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?rr(e):null}function or(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return or(e)}}function ir(e){(!e.__d&&(e.__d=!0)&&Kn.push(e)&&!sr.__r++||zn!==Vn.debounceRendering)&&((zn=Vn.debounceRendering)||qn)(sr)}function sr(){for(var e;sr.__r=Kn.length;)e=Kn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Kn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=Qn({},o)).__v=o.__v+1,pr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?rr(o):i,o.__h),yr(n,o),o.__e!=i&&or(o)))}))}function ar(e,t,n,r,o,i,s,a,c,u){var l,d,f,h,p,y,b,v=r&&r.__k||Jn,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(h=n.__k[l]=null==(h=t[l])||"boolean"==typeof h?null:"string"==typeof h||"number"==typeof h||"bigint"==typeof h?er(null,h,null,null,h):Array.isArray(h)?er(tr,{children:h},null,null,null):h.__b>0?er(h.type,h.props,h.key,null,h.__v):h)){if(h.__=n,h.__b=n.__b+1,null===(f=v[l])||f&&h.key==f.key&&h.type===f.type)v[l]=void 0;else for(d=0;d<m;d++){if((f=v[d])&&h.key==f.key&&h.type===f.type){v[d]=void 0;break}f=null}pr(e,h,f=f||Gn,o,i,s,a,c,u),p=h.__e,(d=h.ref)&&f.ref!=d&&(b||(b=[]),f.ref&&b.push(f.ref,null,h),b.push(d,h.__c||p,h)),null!=p?(null==y&&(y=p),"function"==typeof h.type&&null!=h.__k&&h.__k===f.__k?h.__d=c=cr(h,c,e):c=ur(e,h,f,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&f.__e==c&&c.parentNode!=e&&(c=rr(f))}for(n.__e=y,l=m;l--;)null!=v[l]&&("function"==typeof n.type&&null!=v[l].__e&&v[l].__e==n.__d&&(n.__d=rr(r,l+1)),mr(v[l],v[l]));if(b)for(l=0;l<b.length;l++)vr(b[l],b[++l],b[++l])}function cr(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?cr(o,t,n):ur(n,o,o,e.__k,o.__e,t));return t}function ur(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function lr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Yn.test(t)?n:n+"px"}function dr(e,t,n,r,o){var 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||lr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||lr(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?hr:fr,i):e.removeEventListener(t,i?hr:fr,i);else if("dangerouslySetInnerHTML"!==t){if(o)t=t.replace(/xlink[H:h]/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function fr(e){this.l[e.type+!1](Vn.event?Vn.event(e):e)}function hr(e){this.l[e.type+!0](Vn.event?Vn.event(e):e)}function pr(e,t,n,r,o,i,s,a,c){var u,l,d,f,h,p,y,b,v,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=Vn.__b)&&u(t);try{e:if("function"==typeof _){if(b=t.props,v=(u=_.contextType)&&r[u.__c],m=u?v?v.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(b,m):(t.__c=l=new nr(b,m),l.constructor=_,l.render=gr),v&&v.sub(l),l.props=b,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=_.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=Qn({},l.__s)),Qn(l.__s,_.getDerivedStateFromProps(b,l.__s))),f=l.props,h=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(b,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(b,l.__s,m)||t.__v===n.__v){l.props=b,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(b,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,h,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=Vn.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=Qn(Qn({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(f,h)),g=null!=u&&u.type===tr&&null==u.key?u.props.children:u,ar(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=br(n.__e,t,n,r,o,i,s,c);(u=Vn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),Vn.__e(e,t,n)}}function yr(e,t){Vn.__c&&Vn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Vn.__e(e,t.__v)}}))}function br(e,t,n,r,o,i,s,a){var c,u,l,d,f=n.props,h=t.props,p=t.type,y=0;if("svg"===p&&(o=!0),null!=i)for(;y<i.length;y++)if((c=i[y])&&(c===e||(p?c.localName==p:3==c.nodeType))){e=c,i[y]=null;break}if(null==e){if(null===p)return document.createTextNode(h);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,h.is&&h),i=null,a=!1}if(null===p)f===h||a&&e.data===h||(e.data=h);else{if(i=i&&Jn.slice.call(e.childNodes),u=(f=n.props||Gn).dangerouslySetInnerHTML,l=h.dangerouslySetInnerHTML,!a){if(null!=i)for(f={},d=0;d<e.attributes.length;d++)f[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||dr(e,i,null,n[i],r);for(i in t)o&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||dr(e,i,t[i],n[i],r)}(e,h,f,o,a),l)t.__k=[];else if(y=t.props.children,ar(e,Array.isArray(y)?y:[y],t,n,r,o&&"foreignObject"!==p,i,s,e.firstChild,a),null!=i)for(y=i.length;y--;)null!=i[y]&&Xn(i[y]);a||("value"in h&&void 0!==(y=h.value)&&(y!==e.value||"progress"===p&&!y)&&dr(e,"value",y,f.value,!1),"checked"in h&&void 0!==(y=h.checked)&&y!==e.checked&&dr(e,"checked",y,f.checked,!1))}return e}function vr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Vn.__e(e,n)}}function mr(e,t,n){var r,o,i;if(Vn.unmount&&Vn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||vr(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Vn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&mr(r[i],t,n);null!=o&&Xn(o)}function gr(e,t,n){return this.constructor(e,n)}Vn={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},nr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Qn({},this.state),"function"==typeof e&&(e=e(Qn({},n),this.props)),e&&Qn(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),ir(this))},nr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),ir(this))},nr.prototype.render=tr,Kn=[],qn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,sr.__r=0;const _r={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},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"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function wr({children:e}){return Zn("div",null,Zn("div",{style:_r.Darken}),Zn("div",{style:_r.DialogOuter},Zn("div",{style:_r.DialogInner},e)))}var Sr,kr,xr,Er=0,Ir=[],Tr=Vn.__b,Cr=Vn.__r,Ar=Vn.diffed,Pr=Vn.__c,Or=Vn.unmount;function Ur(e,t){Vn.__h&&Vn.__h(kr,e,Er||t),Er=0;var n=kr.__H||(kr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Dr(e){return Er=1,function(e,t,n){var r=Ur(Sr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Wr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=kr),r.__}(Wr,e)}function $r(e){return Er=5,function(e,t){var n=Ur(Sr++,7);return Br(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Nr(){Ir.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Rr),e.__H.__h.forEach(Lr),e.__H.__h=[]}catch(t){e.__H.__h=[],Vn.__e(t,e.__v)}})),Ir=[]}Vn.__b=function(e){kr=null,Tr&&Tr(e)},Vn.__r=function(e){Cr&&Cr(e),Sr=0;var t=(kr=e.__c).__H;t&&(t.__h.forEach(Rr),t.__h.forEach(Lr),t.__h=[])},Vn.diffed=function(e){Ar&&Ar(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Ir.push(t)&&xr===Vn.requestAnimationFrame||((xr=Vn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),jr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);jr&&(t=requestAnimationFrame(n))})(Nr)),kr=void 0},Vn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Rr),e.__h=e.__h.filter((function(e){return!e.__||Lr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Vn.__e(n,e.__v)}})),Pr&&Pr(e,t)},Vn.unmount=function(e){Or&&Or(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Rr)}catch(e){Vn.__e(e,t.__v)}};var jr="function"==typeof requestAnimationFrame;function Rr(e){var t=kr;"function"==typeof e.__c&&e.__c(),kr=t}function Lr(e){var t=kr;e.__c=e.__(),kr=t}function Br(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Wr(e,t){return"function"==typeof t?t(e):t}function Fr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Dr({}),a=$r();return function(e,t){var n=Ur(Sr++,4);!Vn.__s&&Br(n.__H,t)&&(n.__=e,n.__H=t,kr.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),Zn(wr,null,Zn(tr,null,Zn("h3",{style:_r.WindowHeader},e),t.map((e=>Zn("p",{style:_r.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),Zn("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>Zn("label",{style:_r.Label},n?`${n}: `:"",Zn("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:_r.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Mr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),Zn("div",{style:_r.ButtonsDiv},Zn("button",{type:"submit",style:_r.Button,onClick:()=>o(i)},"Submit"),Zn("button",{style:_r.Button,onClick:r},"Cancel")))}function Mr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Hr extends nr{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?Zn(Fr,Object.assign({},t)):null}}function Vr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;Vn.__&&Vn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],pr(t,e=(!r&&n||t).__k=Zn(tr,null,[e]),o||Gn,Gn,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?Jn.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),yr(i,e)}(Zn(Hr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function Kr(n){const i=n.name,s=new t.BehaviorSubject(o),a=[];let c=null;n.on("ready",(async n=>{try{await async function(n){var o,i,d,f,h,p;u=!1;const y=en(n);un||((null===(o=y.cloud.options)||void 0===o?void 0:o.customLoginGui)||a.push(Vr(n)),a.push(function(e){let n=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(Ue((e=>{const r=n;n=e;const o=t.of(e);switch(e){case"disconnected":return In.value?o.pipe(ie(500)):o;case"connecting":return"not-started"===r||"error"===r?o:o.pipe(ie(4e3));default:return o}})));return t.combineLatest([r,e.syncStateChangedEvent.pipe(Oe({phase:"initial"})),Tn]).pipe(Y((([t,n,r])=>{let{phase:o,error:i,progress:s}=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"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:Ht?a:"offline"}})))}(y).subscribe(n.cloud.syncState)));y.tables.every((e=>e.core))||ln();const b="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],v=await y.transaction("rw",y.$syncState,(async()=>{var e,t;const{options:n,schema:r}=y.cloud,[o,i,s]=await Promise.all([y.getOptions(),y.getSchema(),y.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await y.$syncState.put(n,"options"):y.cloud.options=o||null,(null===(e=y.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&b.length>0&&!cn?(console.debug("Dexie Cloud Addon: Using service worker"),y.cloud.usingServiceWorker=!0):((null===(t=y.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!un&&console.debug("dexie-cloud-addon: Not using service worker.",0===b.length?"No SW registrations found.":"serviceWorker"in navigator&&cn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),y.cloud.usingServiceWorker=!1),Hn(r,y.cloud.options),Hn(i,y.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]={...n}}await y.$syncState.put(e,"schema"),Object.assign(r,e)}}else y.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));v&&y.setInitiallySynced(!0);(function(e){var t,n;for(const o of e.tables)if(null===(n=null===(t=e.cloud.schema)||void 0===t?void 0:t[o.name])||void 0===n?void 0:n.markedForSync){if(o.schema.primKey.auto)throw new r.default.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new r.default.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(y),(null===(i=y.cloud.options)||void 0===i?void 0:i.databaseUrl)&&!v&&(await async function(e,t,n){console.debug("Performing initial sync"),await En(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await qt(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(y,y.cloud.options,y.cloud.schema),y.setInitiallySynced(!0));l(),un||(a.push(e.liveQuery((()=>y.getCurrentUser())).subscribe(s)),a.push(e.liveQuery((()=>y.getPersistedSyncState())).subscribe(y.cloud.persistedSyncState)),await t.combineLatest([s.pipe(Ce(1),Ee(1)),y.cloud.persistedSyncState.pipe(Ce(1),Ee(1))]).toPromise());(null===(d=y.cloud.options)||void 0===d?void 0:d.requireAuth)&&await rn(y);c&&c.stop();c=null,l(),y.cloud.usingServiceWorker&&(null===(f=y.cloud.options)||void 0===f?void 0:f.databaseUrl)?(Ve(y,"push").catch((()=>{})),async function(e){var t;try{const{periodicSync:n}=await navigator.serviceWorker.ready;if(n)try{await n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),console.debug(`Dexie Cloud: Successfully registered periodicsync event for ${e.name}`)}catch(e){console.debug("Dexie Cloud: Failed to register periodic sync. Your PWA must be installed to allow background sync.",e)}else console.debug("Dexie Cloud: periodicSync not supported.")}catch(t){console.debug(`Dexie Cloud: Could not register periodicSync for ${e.name}`,t)}}(y).catch((()=>{}))):(null===(h=y.cloud.options)||void 0===h?void 0:h.databaseUrl)&&y.cloud.schema&&!un&&(c=Mn(y,y.cloud.options,y.cloud.schema),c.start(),Ke(y,"push"));l(),un||a.push(t.fromEvent(self,"online").subscribe((()=>{console.debug("online!"),y.syncStateChangedEvent.next({phase:"not-in-sync"}),Ke(y,"push")})),t.fromEvent(self,"offline").subscribe((()=>{console.debug("offline!"),y.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!un&&(null===(p=y.cloud.options)||void 0===p?void 0:p.databaseUrl)&&a.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(Se((e=>e)),Ue((()=>e.getPersistedSyncState())),Se((e=>e&&e.serverRevision)),Y((e=>({type:"ready",rev:e.serverRevision}))));return function n(){return e.cloud.persistedSyncState.pipe(Se((e=>null==e?void 0:e.serverRevision)),Ee(1),Ue((t=>e.cloud.currentUser.pipe(Y((e=>[e,t]))))),Ue((([e,t])=>Tn.pipe(Y((n=>[n?e:null,t]))))),Ue((async([e,t])=>[e,await Ge(t)])),Ue((([n,o])=>n?new Nn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,o,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n.accessToken,n.accessTokenExpiration):t.from([]))),M((r=>"TokenExpiredError"===(null==r?void 0:r.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),t.of(!0).pipe(Ue((async()=>{const t=await e.getCurrentUser(),n=await dt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Ue((()=>n())))):t.throwError(r))),M((e=>t.from(Ln(e)).pipe(Ue((()=>n()))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(y))}(n)}catch(e){console.error(e)}}),!0);let u=!1;function l(){if(u)throw new r.default.DatabaseClosedError}var d;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{a.forEach((e=>e.unsubscribe())),u=!0,c&&c.stop(),c=null,s.next(o)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return s.value.userId||o.userId},currentUser:s,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),async login(e){const t=en(n);await t.cloud.sync(),await rn(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,en(n).reconfigure()),Hn(n.cloud.schema,n.cloud.options)},async sync({wait:r,purpose:o}={wait:!0,purpose:"push"}){void 0===r&&(r=!0);const i=en(n);if("pull"===o){const e=i.cloud.persistedSyncState.value;if(Ke(i,o),r){const t=await i.cloud.persistedSyncState.pipe(Se((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))),Ee(1)).toPromise();if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(await Bn(i)){const n=i.cloud.persistedSyncState.value;Ke(i,o),r&&(console.debug("db.cloud.login() is waiting for sync completion..."),await t.from(e.liveQuery((async()=>{const e=await Bn(i),t=await i.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(Se((e=>!e)),Ee(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=r.default.override(n.Version.prototype._parseStoresSpec,(e=>kn(e,n))),n.use(Sn({currentUserObservable:n.cloud.currentUser,db:en(n)})),n.use((d=en(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>({...e,table:t=>{const n=e.table(t);return{...n,mutate:e=>{var r,o,i;const s=e.trans;if((null===(o=null===(r=d.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(i=s.currentUser)||void 0===i?void 0:i.isLoggedIn)&&("add"===e.type||"put"===e.type))for(const t of e.values)"owner"in t||(t.owner=s.currentUser.userId),"realmId"in t||(t.realmId=s.currentUser.userId);return n.mutate(e)}}}})})),n.use(bn(en(n)))}Kr.version="1.0.0-beta.10",r.default.Cloud=Kr;const qr=new Map;function zr(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const Gr=new Map;function Jr(e,t){let n=Gr.get(e+"/"+t);return n||(n=async function(e,t){var n;let o=qr.get(e);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",e);const t=new r.default(e,{addons:[Kr]});o=en(t),t.on("versionchange",i),await o.dx.open(),qr.get(e)||qr.set(e,o)}if(!(null===(n=o.cloud.options)||void 0===n?void 0:n.databaseUrl))return void console.error("Dexie Cloud: No databaseUrl configured");if(!o.cloud.schema)return void console.error("Dexie Cloud: No schema persisted");function i(){return o.dx.on.versionchange.unsubscribe(i),qr.get(o.name)===o&&qr.delete(o.name),console.debug(`Dexie Cloud SW: Closing Dexie instance for ${e}`),o.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await Fn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:t}),console.debug("Dexie Cloud SW: Done Syncing")}catch(e){if(console.error("Dexie Cloud SW Error",e),i(),e.name!==r.default.errnames.NoSuchDatabase)throw e}}(e,t).then((()=>{Gr.delete(e+"/"+t)})).catch((n=>(Gr.delete(e+"/"+t),Promise.reject(n)))),Gr.set(e+"/"+t,n)),n}cn||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=zr(e.tag);t&&e.waitUntil(Jr(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=zr(e.tag);t&&e.waitUntil(Jr(t,"pull"))})),self.addEventListener("message",(e=>{if(console.debug('SW "message" Event',e.data),"dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>Jr(t,e.data.purpose||"pull").catch((async e=>{if(3===r)throw e;var t;await(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}));"waitUntil"in e?e.waitUntil(n().catch((e=>console.error(e)))):n().catch((e=>console.error(e)))}})))}));
|