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.
Files changed (34) hide show
  1. package/dist/modern/dexie-cloud-addon.js +189 -158
  2. package/dist/modern/dexie-cloud-addon.js.map +1 -1
  3. package/dist/modern/dexie-cloud-addon.min.js +1 -1
  4. package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
  5. package/dist/modern/service-worker.js +1208 -1176
  6. package/dist/modern/service-worker.js.map +1 -1
  7. package/dist/modern/service-worker.min.js +1 -1
  8. package/dist/modern/service-worker.min.js.map +1 -1
  9. package/dist/module-es5/dexie-cloud-addon.js +259 -207
  10. package/dist/module-es5/dexie-cloud-addon.js.map +1 -1
  11. package/dist/module-es5/dexie-cloud-addon.min.js +1 -1
  12. package/dist/module-es5/dexie-cloud-addon.min.js.map +1 -1
  13. package/dist/types/WSObservable.d.ts +11 -6
  14. package/dist/types/WebSocketStatus.d.ts +1 -0
  15. package/dist/types/helpers/BroadcastedLocalEvent.d.ts +8 -0
  16. package/dist/types/helpers/visibleState.d.ts +1 -0
  17. package/dist/types/sync/syncServerToClientOnly.d.ts +3 -0
  18. package/dist/types/types/CloudConnectionStatus.d.ts +0 -0
  19. package/dist/types/types/ConnectionStatus.d.ts +0 -0
  20. package/dist/types/types/LoginState.d.ts +41 -0
  21. package/dist/types/types/SyncConnectionStatus.d.ts +1 -0
  22. package/dist/types/types/SyncFlowStatus.d.ts +6 -0
  23. package/dist/types/types/SyncStatus.d.ts +6 -0
  24. package/dist/umd/dexie-cloud-addon.js +259 -207
  25. package/dist/umd/dexie-cloud-addon.js.map +1 -1
  26. package/dist/umd/dexie-cloud-addon.min.js +1 -1
  27. package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
  28. package/dist/umd/service-worker.js +1208 -1176
  29. package/dist/umd/service-worker.js.map +1 -1
  30. package/dist/umd/service-worker.min.js +1 -1
  31. package/dist/umd/service-worker.min.js.map +1 -1
  32. package/dist/umd-modern/dexie-cloud-addon.js +188 -157
  33. package/dist/umd-modern/dexie-cloud-addon.js.map +1 -1
  34. package/package.json +2 -2
@@ -1 +1 @@
1
- import e,{liveQuery as t}from"dexie";import{Observable as n,BehaviorSubject as r,Subject as o,from as i,fromEvent as s,of as a,merge as c,Subscription as u,throwError as l,combineLatest as d}from"rxjs";const h={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(h),Object.freeze(h.claims)}catch(e){}const f={},p=self.document&&navigator.serviceWorker;p&&p.ready.then((e=>f.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class y{constructor(e){this.name=e}subscribe(e){if(!p)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return p.addEventListener("message",t),()=>p.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):f.registration&&(null===(t=f.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class b extends n{constructor(e){const t="undefined"==typeof BroadcastChannel?new y(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 y?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 y?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 v=function(e,t){return(v=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 m(e,t){function n(){this.constructor=e}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function g(e){return"function"==typeof e}var _=!1,w={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;_=e},get useDeprecatedSynchronousErrorHandling(){return _}};function S(e){setTimeout((function(){throw e}),0)}var k={closed:!0,next:function(e){},error:function(e){if(w.useDeprecatedSynchronousErrorHandling)throw e;S(e)},complete:function(){}},x=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function E(e){return null!==e&&"object"==typeof e}var I=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}(),T=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(g(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof I?C(e.errors):[e]}}if(x(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(E(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof I?t=t.concat(C(e.errors)):t.push(e)}}}if(t)throw new I(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 C(e){return e.reduce((function(e,t){return e.concat(t instanceof I?t.errors:t)}),[])}var A=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),P=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=k;break;case 1:if(!n){i.destination=k;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new O(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new O(i,n,r,o)}return i}return m(t,e),t.prototype[A]=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}(T),O=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return g(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==k&&(g((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 m(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;w.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=w.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):S(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;S(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)};w.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(),w.useDeprecatedSynchronousErrorHandling)throw e;S(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!w.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return w.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(S(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(P);var U=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function D(e){return e}function $(e){return 0===e.length?D:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var N=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 P)return e;if(e[A])return e[A]()}return e||t||n?new P(e,t,n):new P(k)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||w.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),w.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){w.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 P?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=R(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[U]=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:$(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=R(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 R(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var j=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function L(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var W=L(),B=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function F(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var M=function(e){if(e&&"function"==typeof e[U])return r=e,function(e){var t=r[U]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(B(e))return j(e);if(F(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,S),e};if(e&&"function"==typeof e[W])return t=e,function(e){for(var n=t[W]();;){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=E(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.")},H=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return m(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}(P),V=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(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}(P);function K(e,t){if(!t.closed){if(e instanceof N)return e.subscribe(t);var n;try{n=M(e)(t)}catch(e){t.error(e)}return n}}var q=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 m(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 m(t,e),t.prototype.schedule=function(e,t){return this},t}(T)),z=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}(),G=new(function(e){function t(n,r){void 0===r&&(r=z.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 m(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}(z))(q);function J(e){return e&&"function"==typeof e.schedule}function Y(e){return function(t){var n=new X(e),r=t.lift(n);return n.caught=r}}var X=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Z(e,this.selector,this.caught))},e}(),Z=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return m(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 H(this);this.add(r);var o=K(n,r);o!==r&&this.add(o)}},t}(V);function Q(e,t){return new N((function(n){var r=new T,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 ee(e,t){return t?Q(e,t):new N(j(e))}function te(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[U]}(e))return function(e,t){return new N((function(n){var r=new T;return r.add(t.schedule((function(){var o=e[U]();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(F(e))return function(e,t){return new N((function(n){var r=new T;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(B(e))return Q(e,t);if(function(e){return e&&"function"==typeof e[W]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new N((function(n){var r,o=new T;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[W](),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 ne(e,t){return t?te(e,t):e instanceof N?e:new N(M(e))}function re(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return J(n)?(e.pop(),Q(e,n)):ee(e)}function oe(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 ie(e,t))}}var ie=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new se(e,this.project,this.thisArg))},e}(),se=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 m(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}(P);function ae(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(ae((function(n,r){return ne(e(n,r)).pipe(oe((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new ce(e,n))})}var ce=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 ue(e,this.project,this.concurrent))},e}(),ue=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 m(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 H(this),n=this.destination;n.add(t);var r=K(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}(V);function le(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),ae(D,e)}function de(){return le(1)}function he(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return de()(re.apply(void 0,e))}function fe(e,t){return void 0===t&&(t=G),function(n){return n.lift(new pe(e,t))}}var pe=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ye(e,this.dueTime,this.scheduler))},e}(),ye=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 m(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(be,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}(P);function be(e){e.debouncedNext()}function ve(e){return e instanceof Date&&!isNaN(+e)}var me=new N((function(e){return e.complete()}));function ge(e){return e?function(e){return new N((function(t){return e.schedule((function(){return t.complete()}))}))}(e):me}function _e(e,t){return new N(t?function(n){return t.schedule(we,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function we(e){var t=e.error;e.subscriber.error(t)}var Se=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 re(this.value);case"E":return _e(this.error);case"C":return ge()}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 ke(e,t){void 0===t&&(t=G);var n=ve(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new xe(n,t))}}var xe=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new Ee(e,this.delay,this.scheduler))},e}(),Ee=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 m(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 Ie(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(Se.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(Se.createComplete()),this.unsubscribe()},t}(P),Ie=function(){return function(e,t){this.time=e,this.notification=t}}();var Te=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Ce(e,this.compare,this.keySelector))},e}(),Ce=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 m(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}(P),Ae=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 Pe(e,t){return function(n){return n.lift(new Oe(e,t))}}var Oe=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ue(e,this.predicate,this.thisArg))},e}(),Ue=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 m(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}(P);function De(e){return function(t){return 0===e?ge():t.lift(new $e(e))}}var $e=function(){function e(e){if(this.total=e,this.total<0)throw new Ae}return e.prototype.call=function(e,t){return t.subscribe(new Ne(e,this.total))},e}(),Ne=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return m(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}(P);function Re(e){return function(t){return t.lift(new je(e))}}var je=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new Le(e,this.total))},e}(),Le=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return m(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(P);function We(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return J(n)?(e.pop(),function(t){return he(e,t,n)}):function(t){return he(e,t)}}function Be(e,t){return"function"==typeof t?function(n){return n.pipe(Be((function(n,r){return ne(e(n,r)).pipe(oe((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new Fe(e))}}var Fe=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Me(e,this.project))},e}(),Me=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return m(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 H(this),r=this.destination;r.add(n),this.innerSubscription=K(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}(V);function He(){}function Ve(e,t,n){return function(r){return r.lift(new Ke(e,t,n))}}var Ke=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 qe(e,this.nextOrObserver,this.error,this.complete))},e}(),qe=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=He,i._tapError=He,i._tapComplete=He,i._tapError=r||He,i._tapComplete=o||He,g(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||He,i._tapError=n.error||He,i._tapComplete=n.complete||He),i}return m(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}(P),ze=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 Ge=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 Je(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Je=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 m(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(K(t,new H(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}(V);function Ye(e,t){return void 0===t&&(t=G),function(e,t,n){return void 0===n&&(n=G),function(r){var o=ve(e),i=o?+e-n.now():Math.abs(e);return r.lift(new Ge(i,o,t,n))}}(e,_e(new ze),t)}const{toString:Xe}={};const Ze={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 Qe(...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 Ze;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,Xe.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:Ze),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 et={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 tt={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 nt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var rt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},ot={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},it={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const st="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var at=["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=st[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});const ct="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},ut="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 lt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=ft[e[n]];return t}(ut(e))}function dt(e){return ct(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=ht[e[n]];return t}(e))}const ht={"-":"=",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:"+","|":"/"},ft={};for(const e of Object.keys(ht))ft[ht[e]]=e;var pt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:lt(e)}),revive:({v:e})=>{const t=dt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class yt{constructor(e,t){this.buf=e,this.type=t}}function bt(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 vt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const mt={...tt,...nt,...rt,...ot,...it,...at,...pt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof yt,replace:e=>({$t:"Blob",v:ut(e instanceof yt?e.buf:vt(bt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=ct(t);return void 0!==typeof Blob?new Blob([n]):new yt(n.buffer,e)}}}};function gt(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 _t={undefined:{replace:()=>{},revive:()=>{}}};const wt="bigint"==typeof BigInt(0);function St(e){return"bigint"==typeof e?e:wt?"string"==typeof e?BigInt(e):BigInt(e.v):Number("string"==typeof e?e:e.v)}function kt(e,t){const n=St(e),r=St(t);return n<r?-1:n>r?1:0}class xt{constructor(e){this.v=e}toString(){return this.v}}const Et={..._t,...wt?{}:{bigint:{test:e=>e instanceof xt,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new xt(e)}}},It=Qe(mt,Et),Tt=function(...e){const t=Qe(mt,et,...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 gt(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 gt(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)}}}(Et);let Ct=!1;async function At(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){Ct||(console.debug("Dexie Cloud: Could not register sync event",e),Ct=!0)}}function Pt(e,t){e.cloud.usingServiceWorker?At(e,t):e.localSyncEvent.next({purpose:t})}async function Ot({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 ut(o)}function Ut(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function Dt(e){return`$${e}_mutations`}function $t(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 Nt(e,t,{since:n={},limit:r=1/0}={}){return(await Promise.all(e.map((async e=>{const t=$t(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 Rt=crypto.getRandomValues;function jt(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)jt(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]={}),jt(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const Lt="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Rt(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function Wt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>Wt(e)))&&e.every(Bt))}function Bt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(Bt)}function Ft(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))jt(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 Mt(e,t){for(const{table:n,muts:r}of t)for(const t of r)Ft(e,n,t)}function Ht(t,n){return new Promise(((r,o)=>{const i={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(i)}))}function Vt(e,t,...n){return Ht(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function Kt(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await Ht(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 qt(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 Ht(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function zt(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await Gt(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=ut(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 Ht(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await Vt(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 Gt(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=ut(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 Jt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function Yt(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 Gt(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:It.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new Jt(l);switch(l.headers.get("content-type")){case"application/x-bison":return Tt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return It.parse(e)}}}async function Xt(t,n,r){const o=await t.bulkGet(n),i=[],s=[];n.forEach(((n,a)=>{const c=o[a];if(c){for(const[n,o]of Object.entries(r[a])){if(n===t.schema.primKey.keyPath)throw new Error("Cannot change primary key");e.setByKeyPath(c,n,o)}i.push(n),s.push(c)}})),await(null==t.schema.primKey.keyPath?t.bulkPut(s,i):t.bulkPut(s))}function Zt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Qt=navigator.onLine;async function en(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 tn(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",(()=>Qt=!0)),self.addEventListener("offline",(()=>Qt=!1));function nn(e,t,n,r){return rn.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:Qt,syncOptions:r,error:o}),Qt&&(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 nn(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Qt?"error":"offline",error:o}),Promise.reject(o)))))}async function rn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=await e.getCurrentUser(),l=u.isLoggedIn?Ut(e):[],d=l.map((t=>e.table(Dt(t.name)))),f=await e.getPersistedSyncState(),p=!r&&u.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Ut(e).filter((e=>!n.includes(e.name)))}(e,f):[];Zt(o);const y=p.length>0;if(y){if(i)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!==h.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==h.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==h.userId||(e.owner=t.userId),e.realmId&&e.realmId!==h.userId||(e.realmId=t.userId))})))}(p,u,null==f?void 0:f.realms)})),Zt(o)}const[b,v,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let i=await Nt(d);if(Zt(o),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||"")&&Wt(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,u,n,null==f?void 0:f.realms);return Zt(o),i=i.concat(e),[i,t,r]}return[i,t,r]})),g=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return console.debug("Sync is needed:",g),g;if("push"===s&&!g)return!1;const _=tn(b,null==v?void 0:v.latestRevisions),w=(null==v?void 0:v.clientIdentity)||Lt(16);Zt(o);const S=await Yt(b,v,m,e,c,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 Nt(d,0,{since:_});for(const t of d){const n=$t(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()])}tn(r,_),await en(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=Ut(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=l.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=sn(S.changes,r);return await on(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 rn(e,t,n,{isInitialSync:r,cancelToken:o}))}async function on(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:i}=t.core.schema;for(const n of o)switch(n.type){case"insert":i.outbound?await t.bulkAdd(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":i.outbound?await t.bulkPut(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===n.keys.length?await t.update(n.keys[0],n.changeSpec):await t.where(":id").anyOf(n.keys).modify(n.changeSpec);break;case"update":await Xt(t,n.keys,n.changeSpecs);break;case"delete":await t.bulkDelete(n.keys)}}}function sn(e,t){const n={};Mt(n,e);const r={};return Mt(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))jt(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=Lt(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 an(t){const n=[],o=new r(!0),i=new r(null);let s=!1;return i.subscribe((async()=>{if(!s&&n.length>0){s=!0,o.next(!1);try{await async function(){var r,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await t.cloud.syncState.pipe(Pe((({phase:e})=>"in-sync"===e||"error"===e)),De(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=await Gt(t.cloud.options.databaseUrl,a);await t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"rev":(!(null==n?void 0:n.serverRevision)||kt(n.serverRevision,s.rev)<0)&&Pt(t,"pull");break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(s.realm))||Pt(t,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&Pt(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){Pt(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!r||!i)return void console.debug("required vars not present",{syncState:o,schema:r,currentUser:i});if(0!==kt(s.baseRev,o.serverRevision))return void console.debug(`baseRev (${s.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`);const a=await e.waitFor(Ot(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void Pt(t,"pull");let c=[];if(i.isLoggedIn){const e=Ut(t).map((e=>t.table(Dt(e.name))));c=await Nt(e),console.debug("msg queue: client changes",c)}const u=sn(s.changes,c);console.debug("applying filtered server changes",u),await on(u,t),o.latestRevisions=tn(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await en(t,r,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await t.$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 cn=new WeakMap,un={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let ln=0;function dn(e){"vip"in e&&(e=e.vip);let t=cn.get(e.cloud);if(!t){const n=new o;let r=new b(`syncstatechanged-${e.name}`);n.id=++ln;let i=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return i},localSyncEvent:n,get syncStateChangedEvent(){return r},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||h)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){i=e},reconfigure(){r=new b(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=an(t),cn.set(e.cloud,t)}return t}const hn=new WeakMap;class fn{constructor(e,t){hn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new fn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){hn.get(this).table("$logins").put(this)}}async function pn(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 fn(e,{claims:{},lastLogin:new Date(0)});await zt(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 Kt(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 Kt(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 Vt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Jt(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 qt(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 qt(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 Vt(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Jt(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),Pt(e,"pull")}const yn="undefined"!=typeof InstallTrigger,bn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),vn=bn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,mn=bn&&vn<=605||yn;const gn="undefined"!=typeof self&&"clients"in self&&!self.document;function _n(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:wn}={};function Sn(e){return wn.call(e).slice(8,-1)}function kn(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 xn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let En=0;function In(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);function i(n,i){let s=null;const a=kn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();En>=o?++En:En=o,r[0]=En/1099511627776,r[1]=En/4294967296,r[2]=En/16777216,r[3]=En/65536,r[4]=En/256,r[5]=En;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+lt(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}.\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({...n,keys:a,values:s||n.values})}return{...o,mutate:n=>{var s,a;if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(a=t.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!t.initiallySynced){const e=kn(o.schema.primaryKey,n);return o.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(n)}))}return i(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){kn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!Wt(t)){const n=Array.isArray(t)?t.map(Sn).join(","):Sn(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(n)}}}})}}function Tn(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let Cn=0;function An(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 Pn(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 On=new r(new Set);function Un({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){_n()}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=>Dt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=Tn(16),i.currentUser=e.value,On.value.add(i),On.next(On.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),On.value.delete(i),On.next(On.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"),At(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"+ ++Cn;return{...e,count:An(e.count,t),get:An(e.get,t),getMany:An(e.getMany,t),openCursor:An(e.openCursor,t),query:An(e.query,t),mutate:Pn(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 h=Date.now(),f="delete"===e.type?{type:"delete",ts:h,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:h,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:h,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:h,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:h,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[f]}).then((()=>t)):t}))}}}}}}function Dn(e,t){return function(n,r){const o={...un,...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)(xn.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 $n=Tn(16);async function Nn(e,n,r,o,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function o(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(n);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${n} 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:$n,started:new Date,heartbeat:new Date},n),!0):(await a.add({nodeId:$n,started:new Date,heartbeat:new Date},n),!0)})))return!0;if(s)try{const e=i(t((()=>a.get(n)))).pipe(Ye(6e4),Pe((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await o()}return!1}()){const t=setInterval((()=>{a.update(n,(e=>e.nodeId===$n&&(e.heartbeat=new Date)))}),1e3);try{return await o()}finally{clearInterval(t),await e.transaction("rw!",r,(async()=>{const e=await a.get(n);e&&e.nodeId===$n&&a.delete(n)}))}}}const Rn=new r(!0),jn=new r(!0);var Ln,Wn;Rn.pipe(Be((e=>e?a(!0):a(!1).pipe(ke(2e4)))),(function(e){return e.lift(new Te(Ln,Wn))})).subscribe(jn);const Bn="undefined"!=typeof document?s(document,"visibilitychange"):a({}),Fn=Bn.pipe(Pe((()=>"hidden"===document.visibilityState))),Mn=Bn.pipe(Pe((()=>"visible"===document.visibilityState))),Hn="undefined"!=typeof window?c(Mn,s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),Fn,Hn).pipe(oe((()=>"visible"===document.visibilityState)),Ve((e=>{Rn.value!==e&&Rn.next(e)})),Be((e=>e?a(0).pipe(ke(28e4),Ve((()=>Rn.next(!1)))):a(0)))).subscribe((()=>{}));class Vn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Kn extends n{constructor(e,t,n,r,o,i,s){super((a=>new zn(e,t,n,i,s,a,r,o)))}}let qn=0;class zn extends u{constructor(e,t,n,r,o,i,s,a){super((()=>this.teardown())),this.id=++qn,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 Vn);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=It.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(It.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function Gn(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 Hn.pipe(De(1)).toPromise(),console.debug("someone did something!")}async function Jn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await nn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Yn=new WeakMap;function Xn(e,t,n,r){const o=Yn.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 Xn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?gn&&await nn(e,t,n,r):await Nn(e,"currentSyncWorker","$jobs",(()=>nn(e,t,n,r))),Yn.delete(e),console.debug("Done sync")}catch(t){throw Yn.delete(e),console.error("Failed to sync client changes",t),t}}();return Yn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Zn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){Xn(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 Qn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var er,tr,nr,rr,or={},ir=[],sr=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function ar(e,t){for(var n in t)e[n]=t[n];return e}function cr(e){var t=e.parentNode;t&&t.removeChild(e)}function ur(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 lr(e,a,r,o,null)}function lr(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?++er.__v:o};return null!=er.vnode&&er.vnode(i),i}function dr(e){return e.children}function hr(e,t){this.props=e,this.context=t}function fr(e,t){if(null==t)return e.__?fr(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?fr(e):null}function pr(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 pr(e)}}function yr(e){(!e.__d&&(e.__d=!0)&&tr.push(e)&&!br.__r++||rr!==er.debounceRendering)&&((rr=er.debounceRendering)||nr)(br)}function br(){for(var e;br.__r=tr.length;)e=tr.sort((function(e,t){return e.__v.__b-t.__v.__b})),tr=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=ar({},o)).__v=o.__v+1,xr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?fr(o):i,o.__h),Er(n,o),o.__e!=i&&pr(o)))}))}function vr(e,t,n,r,o,i,s,a,c,u){var l,d,h,f,p,y,b,v=r&&r.__k||ir,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(f=n.__k[l]=null==(f=t[l])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?lr(null,f,null,null,f):Array.isArray(f)?lr(dr,{children:f},null,null,null):f.__b>0?lr(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[l])||h&&f.key==h.key&&f.type===h.type)v[l]=void 0;else for(d=0;d<m;d++){if((h=v[d])&&f.key==h.key&&f.type===h.type){v[d]=void 0;break}h=null}xr(e,f,h=h||or,o,i,s,a,c,u),p=f.__e,(d=f.ref)&&h.ref!=d&&(b||(b=[]),h.ref&&b.push(h.ref,null,f),b.push(d,f.__c||p,f)),null!=p?(null==y&&(y=p),"function"==typeof f.type&&null!=f.__k&&f.__k===h.__k?f.__d=c=mr(f,c,e):c=gr(e,f,h,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&h.__e==c&&c.parentNode!=e&&(c=fr(h))}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=fr(r,l+1)),Cr(v[l],v[l]));if(b)for(l=0;l<b.length;l++)Tr(b[l],b[++l],b[++l])}function mr(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?mr(o,t,n):gr(n,o,o,e.__k,o.__e,t));return t}function gr(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 _r(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||sr.test(t)?n:n+"px"}function wr(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||_r(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||_r(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?kr:Sr,i):e.removeEventListener(t,i?kr:Sr,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 Sr(e){this.l[e.type+!1](er.event?er.event(e):e)}function kr(e){this.l[e.type+!0](er.event?er.event(e):e)}function xr(e,t,n,r,o,i,s,a,c){var u,l,d,h,f,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=er.__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 hr(b,m),l.constructor=_,l.render=Ar),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=ar({},l.__s)),ar(l.__s,_.getDerivedStateFromProps(b,l.__s))),h=l.props,f=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==h&&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(h,f,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=er.__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=ar(ar({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(h,f)),g=null!=u&&u.type===dr&&null==u.key?u.props.children:u,vr(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=Ir(n.__e,t,n,r,o,i,s,c);(u=er.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),er.__e(e,t,n)}}function Er(e,t){er.__c&&er.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){er.__e(e,t.__v)}}))}function Ir(e,t,n,r,o,i,s,a){var c,u,l,d,h=n.props,f=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(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,a=!1}if(null===p)h===f||a&&e.data===f||(e.data=f);else{if(i=i&&ir.slice.call(e.childNodes),u=(h=n.props||or).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(h={},d=0;d<e.attributes.length;d++)h[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||wr(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]||wr(e,i,t[i],n[i],r)}(e,f,h,o,a),l)t.__k=[];else if(y=t.props.children,vr(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]&&cr(i[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y)&&wr(e,"value",y,h.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&wr(e,"checked",y,h.checked,!1))}return e}function Tr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){er.__e(e,n)}}function Cr(e,t,n){var r,o,i;if(er.unmount&&er.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Tr(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){er.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Cr(r[i],t,n);null!=o&&cr(o)}function Ar(e,t,n){return this.constructor(e,n)}er={__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},hr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=ar({},this.state),"function"==typeof e&&(e=e(ar({},n),this.props)),e&&ar(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),yr(this))},hr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),yr(this))},hr.prototype.render=dr,tr=[],nr="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,br.__r=0;const Pr={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 Or({children:e}){return ur("div",null,ur("div",{style:Pr.Darken}),ur("div",{style:Pr.DialogOuter},ur("div",{style:Pr.DialogInner},e)))}var Ur,Dr,$r,Nr=0,Rr=[],jr=er.__b,Lr=er.__r,Wr=er.diffed,Br=er.__c,Fr=er.unmount;function Mr(e,t){er.__h&&er.__h(Dr,e,Nr||t),Nr=0;var n=Dr.__H||(Dr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Hr(e){return Nr=1,function(e,t,n){var r=Mr(Ur++,2);return r.t=e,r.__c||(r.__=[n?n(t):Yr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Dr),r.__}(Yr,e)}function Vr(e){return Nr=5,function(e,t){var n=Mr(Ur++,7);return Jr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Kr(){Rr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(zr),e.__H.__h.forEach(Gr),e.__H.__h=[]}catch(t){e.__H.__h=[],er.__e(t,e.__v)}})),Rr=[]}er.__b=function(e){Dr=null,jr&&jr(e)},er.__r=function(e){Lr&&Lr(e),Ur=0;var t=(Dr=e.__c).__H;t&&(t.__h.forEach(zr),t.__h.forEach(Gr),t.__h=[])},er.diffed=function(e){Wr&&Wr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Rr.push(t)&&$r===er.requestAnimationFrame||(($r=er.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),qr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);qr&&(t=requestAnimationFrame(n))})(Kr)),Dr=void 0},er.__c=function(e,t){t.some((function(e){try{e.__h.forEach(zr),e.__h=e.__h.filter((function(e){return!e.__||Gr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],er.__e(n,e.__v)}})),Br&&Br(e,t)},er.unmount=function(e){Fr&&Fr(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(zr)}catch(e){er.__e(e,t.__v)}};var qr="function"==typeof requestAnimationFrame;function zr(e){var t=Dr;"function"==typeof e.__c&&e.__c(),Dr=t}function Gr(e){var t=Dr;e.__c=e.__(),Dr=t}function Jr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Yr(e,t){return"function"==typeof t?t(e):t}function Xr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Hr({}),a=Vr();return function(e,t){var n=Mr(Ur++,4);!er.__s&&Jr(n.__H,t)&&(n.__=e,n.__H=t,Dr.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),ur(Or,null,ur(dr,null,ur("h3",{style:Pr.WindowHeader},e),t.map((e=>ur("p",{style:Pr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),ur("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>ur("label",{style:Pr.Label},n?`${n}: `:"",ur("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Pr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Zr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),ur("div",{style:Pr.ButtonsDiv},ur("button",{type:"submit",style:Pr.Button,onClick:()=>o(i)},"Submit"),ur("button",{style:Pr.Button,onClick:r},"Cancel")))}function Zr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Qr extends hr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=i(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ur(Xr,Object.assign({},t)):null}}function eo(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;er.__&&er.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],xr(t,e=(!r&&n||t).__k=ur(dr,null,[e]),o||or,or,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?ir.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),Er(i,e)}(ur(Qr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function to(n){const o=n.name,c=new r(h),u=[];let f=null;n.on("ready",(async n=>{try{await async function(n){var r,o,h,b,v,m;p=!1;const g=dn(n);gn||((null===(r=g.cloud.options)||void 0===r?void 0:r.customLoginGui)||u.push(eo(n)),u.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Be((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return Rn.value?r.pipe(fe(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(fe(4e3));default:return r}})));return d([n,e.syncStateChangedEvent.pipe(We({phase:"initial"})),jn]).pipe(oe((([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:Qt?a:"offline"}})))}(g).subscribe(n.cloud.syncState)));g.tables.every((e=>e.core))||_n();const _="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],w=await g.transaction("rw",g.$syncState,(async()=>{var e,t;const{options:n,schema:r}=g.cloud,[o,i,s]=await Promise.all([g.getOptions(),g.getSchema(),g.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await g.$syncState.put(n,"options"):g.cloud.options=o||null,(null===(e=g.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!mn?(console.debug("Dexie Cloud Addon: Using service worker"),g.cloud.usingServiceWorker=!0):((null===(t=g.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!gn&&console.debug("dexie-cloud-addon: Not using service worker.",0===_.length?"No SW registrations found.":"serviceWorker"in navigator&&mn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),g.cloud.usingServiceWorker=!1),Qn(r,g.cloud.options),Qn(i,g.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 g.$syncState.put(e,"schema"),Object.assign(r,e)}}else g.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));w&&g.setInitiallySynced(!0);(function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(g),(null===(o=g.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!w&&(await async function(e,t,n){console.debug("Performing initial sync"),await Nn(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await nn(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(g,g.cloud.options,g.cloud.schema),g.setInitiallySynced(!0));y(),gn||(u.push(t((()=>g.getCurrentUser())).subscribe(c)),u.push(t((()=>g.getPersistedSyncState())).subscribe(g.cloud.persistedSyncState)),await d([c.pipe(Re(1),De(1)),g.cloud.persistedSyncState.pipe(Re(1),De(1))]).toPromise());(null===(h=g.cloud.options)||void 0===h?void 0:h.requireAuth)&&await pn(g);f&&f.stop();f=null,y(),g.cloud.usingServiceWorker&&(null===(b=g.cloud.options)||void 0===b?void 0:b.databaseUrl)?(At(g,"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)}}(g).catch((()=>{}))):(null===(v=g.cloud.options)||void 0===v?void 0:v.databaseUrl)&&g.cloud.schema&&!gn&&(f=Zn(g,g.cloud.options,g.cloud.schema),f.start(),Pt(g,"push"));y(),gn||u.push(s(self,"online").subscribe((()=>{console.debug("online!"),g.syncStateChangedEvent.next({phase:"not-in-sync"}),Pt(g,"push")})),s(self,"offline").subscribe((()=>{console.debug("offline!"),g.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!gn&&(null===(m=g.cloud.options)||void 0===m?void 0:m.databaseUrl)&&u.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const n=e.messageConsumer.readyToServe.pipe(Pe((e=>e)),Be((()=>e.getPersistedSyncState())),Pe((e=>e&&e.serverRevision)),oe((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Pe((e=>null==e?void 0:e.serverRevision)),De(1),Be((()=>e.cloud.currentUser)),Be((e=>jn.pipe(oe((t=>t?e:null))))),Be((t=>t?new Kn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):i([]))),Y((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Be((async()=>{const t=await e.getCurrentUser(),n=await Gt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Be((()=>t())))):l(n))),Y((e=>i(Gn(e)).pipe(Be((()=>t()))))))}().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!")}))}(g))}(n)}catch(e){console.error(e)}}),!0);let p=!1;function y(){if(p)throw new e.DatabaseClosedError}var b;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{u.forEach((e=>e.unsubscribe())),p=!0,f&&f.stop(),f=null,c.next(h)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return c.value.userId||h.userId},currentUser:c,syncState:new r({phase:"initial",status:"not-started"}),persistedSyncState:new r(void 0),userInteraction:new r(void 0),webSocketStatus:new r("not-started"),async login(e){const t=dn(n);await t.cloud.sync(),await pn(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${o}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,dn(n).reconfigure()),Qn(n.cloud.schema,n.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const o=dn(n);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(Pt(o,r),e){const e=await o.cloud.persistedSyncState.pipe(Pe((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),De(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(await Jn(o)){const n=o.cloud.persistedSyncState.value;Pt(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await i(t((async()=>{const e=await Jn(o),t=await o.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(Pe((e=>!e)),De(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>Dn(e,n))),n.use(Un({currentUserObservable:n.cloud.currentUser,db:dn(n)})),n.use((b=dn(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=b.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(In(dn(n)))}to.version="1.0.0-beta.10",e.Cloud=to;const no=new Map;function ro(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const oo=new Map;function io(t,n){let r=oo.get(t+"/"+n);return r||(r=async function(t,n){var r;let o=no.get(t);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const n=new e(t,{addons:[to]});o=dn(n),n.on("versionchange",i),await o.dx.open(),no.get(t)||no.set(t,o)}if(!(null===(r=o.cloud.options)||void 0===r?void 0:r.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),no.get(o.name)===o&&no.delete(o.name),o.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await Xn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(t){if(console.error("Dexie Cloud SW Error",t),i(),t.name!==e.errnames.NoSuchDatabase)throw t}}(t,n).then((()=>{oo.delete(t+"/"+n)})).catch((e=>(oo.delete(t+"/"+n),Promise.reject(e)))),oo.set(t+"/"+n,r)),r}mn||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=ro(e.tag);t&&e.waitUntil(io(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=ro(e.tag);t&&e.waitUntil(io(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)=>io(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
+ import e,{liveQuery as t}from"dexie";import{Observable as n,BehaviorSubject as r,Subject as o,from as i,fromEvent as s,of as a,merge as c,Subscription as u,throwError as l,combineLatest as d}from"rxjs";const h={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(h),Object.freeze(h.claims)}catch(e){}const f={},p=self.document&&navigator.serviceWorker;p&&p.ready.then((e=>f.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class y{constructor(e){this.name=e}subscribe(e){if(!p)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return p.addEventListener("message",t),()=>p.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))):f.registration&&(null===(t=f.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class b extends n{constructor(e){const t="undefined"==typeof BroadcastChannel?new y(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 y?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 y?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 v=function(e,t){return(v=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 m(e,t){function n(){this.constructor=e}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function g(e){return"function"==typeof e}var _=!1,w={Promise:void 0,set useDeprecatedSynchronousErrorHandling(e){e&&(new Error).stack;_=e},get useDeprecatedSynchronousErrorHandling(){return _}};function S(e){setTimeout((function(){throw e}),0)}var k={closed:!0,next:function(e){},error:function(e){if(w.useDeprecatedSynchronousErrorHandling)throw e;S(e)},complete:function(){}},x=function(){return Array.isArray||function(e){return e&&"number"==typeof e.length}}();function E(e){return null!==e&&"object"==typeof e}var I=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}(),T=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(g(i)){o&&(this._unsubscribe=void 0);try{i.call(this)}catch(e){t=e instanceof I?C(e.errors):[e]}}if(x(s)){a=-1;for(var c=s.length;++a<c;){var u=s[a];if(E(u))try{u.unsubscribe()}catch(e){t=t||[],e instanceof I?t=t.concat(C(e.errors)):t.push(e)}}}if(t)throw new I(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 C(e){return e.reduce((function(e,t){return e.concat(t instanceof I?t.errors:t)}),[])}var A=function(){return"function"==typeof Symbol?Symbol("rxSubscriber"):"@@rxSubscriber_"+Math.random()}(),P=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=k;break;case 1:if(!n){i.destination=k;break}if("object"==typeof n){n instanceof t?(i.syncErrorThrowable=n.syncErrorThrowable,i.destination=n,n.add(i)):(i.syncErrorThrowable=!0,i.destination=new O(i,n));break}default:i.syncErrorThrowable=!0,i.destination=new O(i,n,r,o)}return i}return m(t,e),t.prototype[A]=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}(T),O=function(e){function t(t,n,r,o){var i,s=e.call(this)||this;s._parentSubscriber=t;var a=s;return g(n)?i=n:n&&(i=n.next,r=n.error,o=n.complete,n!==k&&(g((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 m(t,e),t.prototype.next=function(e){if(!this.isStopped&&this._next){var t=this._parentSubscriber;w.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=w.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):S(e),this.unsubscribe();else{if(this.unsubscribe(),n)throw e;S(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)};w.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(),w.useDeprecatedSynchronousErrorHandling)throw e;S(e)}},t.prototype.__tryOrSetError=function(e,t,n){if(!w.useDeprecatedSynchronousErrorHandling)throw new Error("bad call");try{t.call(this._context,n)}catch(t){return w.useDeprecatedSynchronousErrorHandling?(e.syncErrorValue=t,e.syncErrorThrown=!0,!0):(S(t),!0)}return!1},t.prototype._unsubscribe=function(){var e=this._parentSubscriber;this._context=null,this._parentSubscriber=null,e.unsubscribe()},t}(P);var U=function(){return"function"==typeof Symbol&&Symbol.observable||"@@observable"}();function D(e){return e}function $(e){return 0===e.length?D:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var N=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 P)return e;if(e[A])return e[A]()}return e||t||n?new P(e,t,n):new P(k)}(e,t,n);if(r?o.add(r.call(o,this.source)):o.add(this.source||w.useDeprecatedSynchronousErrorHandling&&!o.syncErrorThrowable?this._subscribe(o):this._trySubscribe(o)),w.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){w.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 P?r:null}return!0}(e)?console.warn(t):e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=R(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[U]=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:$(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=R(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 R(e){if(e||(e=Promise),!e)throw new Error("no Promise impl found");return e}var j=function(e){return function(t){for(var n=0,r=e.length;n<r&&!t.closed;n++)t.next(e[n]);t.complete()}};function L(){return"function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator"}var W=L(),B=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function F(e){return!!e&&"function"!=typeof e.subscribe&&"function"==typeof e.then}var M=function(e){if(e&&"function"==typeof e[U])return r=e,function(e){var t=r[U]();if("function"!=typeof t.subscribe)throw new TypeError("Provided object does not correctly implement Symbol.observable");return t.subscribe(e)};if(B(e))return j(e);if(F(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,S),e};if(e&&"function"==typeof e[W])return t=e,function(e){for(var n=t[W]();;){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=E(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.")},H=function(e){function t(t){var n=e.call(this)||this;return n.parent=t,n}return m(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}(P),V=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return m(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}(P);function K(e,t){if(!t.closed){if(e instanceof N)return e.subscribe(t);var n;try{n=M(e)(t)}catch(e){t.error(e)}return n}}var q=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 m(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 m(t,e),t.prototype.schedule=function(e,t){return this},t}(T)),z=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}(),G=new(function(e){function t(n,r){void 0===r&&(r=z.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 m(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}(z))(q);function J(e){return e&&"function"==typeof e.schedule}function Y(e){return function(t){var n=new X(e),r=t.lift(n);return n.caught=r}}var X=function(){function e(e){this.selector=e}return e.prototype.call=function(e,t){return t.subscribe(new Z(e,this.selector,this.caught))},e}(),Z=function(e){function t(t,n,r){var o=e.call(this,t)||this;return o.selector=n,o.caught=r,o}return m(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 H(this);this.add(r);var o=K(n,r);o!==r&&this.add(o)}},t}(V);function Q(e,t){return new N((function(n){var r=new T,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 ee(e,t){return t?Q(e,t):new N(j(e))}function te(e,t){if(null!=e){if(function(e){return e&&"function"==typeof e[U]}(e))return function(e,t){return new N((function(n){var r=new T;return r.add(t.schedule((function(){var o=e[U]();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(F(e))return function(e,t){return new N((function(n){var r=new T;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(B(e))return Q(e,t);if(function(e){return e&&"function"==typeof e[W]}(e)||"string"==typeof e)return function(e,t){if(!e)throw new Error("Iterable cannot be null");return new N((function(n){var r,o=new T;return o.add((function(){r&&"function"==typeof r.return&&r.return()})),o.add(t.schedule((function(){r=e[W](),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 ne(e,t){return t?te(e,t):e instanceof N?e:new N(M(e))}function re(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return J(n)?(e.pop(),Q(e,n)):ee(e)}function oe(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 ie(e,t))}}var ie=function(){function e(e,t){this.project=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new se(e,this.project,this.thisArg))},e}(),se=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 m(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}(P);function ae(e,t,n){return void 0===n&&(n=Number.POSITIVE_INFINITY),"function"==typeof t?function(r){return r.pipe(ae((function(n,r){return ne(e(n,r)).pipe(oe((function(e,o){return t(n,e,r,o)})))}),n))}:("number"==typeof t&&(n=t),function(t){return t.lift(new ce(e,n))})}var ce=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 ue(e,this.project,this.concurrent))},e}(),ue=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 m(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 H(this),n=this.destination;n.add(t);var r=K(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}(V);function le(e){return void 0===e&&(e=Number.POSITIVE_INFINITY),ae(D,e)}function de(){return le(1)}function he(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return de()(re.apply(void 0,e))}function fe(e,t){return void 0===t&&(t=G),function(n){return n.lift(new pe(e,t))}}var pe=function(){function e(e,t){this.dueTime=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new ye(e,this.dueTime,this.scheduler))},e}(),ye=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 m(t,e),t.prototype._next=function(e){this.clearDebounce(),this.lastValue=e,this.hasValue=!0,this.add(this.debouncedSubscription=this.scheduler.schedule(be,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}(P);function be(e){e.debouncedNext()}function ve(e){return e instanceof Date&&!isNaN(+e)}var me=new N((function(e){return e.complete()}));function ge(e){return e?function(e){return new N((function(t){return e.schedule((function(){return t.complete()}))}))}(e):me}function _e(e,t){return new N(t?function(n){return t.schedule(we,0,{error:e,subscriber:n})}:function(t){return t.error(e)})}function we(e){var t=e.error;e.subscriber.error(t)}var Se=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 re(this.value);case"E":return _e(this.error);case"C":return ge()}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 ke(e,t){void 0===t&&(t=G);var n=ve(e)?+e-t.now():Math.abs(e);return function(e){return e.lift(new xe(n,t))}}var xe=function(){function e(e,t){this.delay=e,this.scheduler=t}return e.prototype.call=function(e,t){return t.subscribe(new Ee(e,this.delay,this.scheduler))},e}(),Ee=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 m(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 Ie(t.now()+this.delay,e);this.queue.push(n),!1===this.active&&this._schedule(t)}},t.prototype._next=function(e){this.scheduleNotification(Se.createNext(e))},t.prototype._error=function(e){this.errored=!0,this.queue=[],this.destination.error(e),this.unsubscribe()},t.prototype._complete=function(){this.scheduleNotification(Se.createComplete()),this.unsubscribe()},t}(P),Ie=function(){return function(e,t){this.time=e,this.notification=t}}();var Te=function(){function e(e,t){this.compare=e,this.keySelector=t}return e.prototype.call=function(e,t){return t.subscribe(new Ce(e,this.compare,this.keySelector))},e}(),Ce=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 m(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}(P),Ae=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 Pe(e,t){return function(n){return n.lift(new Oe(e,t))}}var Oe=function(){function e(e,t){this.predicate=e,this.thisArg=t}return e.prototype.call=function(e,t){return t.subscribe(new Ue(e,this.predicate,this.thisArg))},e}(),Ue=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 m(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}(P);function De(e){return function(t){return 0===e?ge():t.lift(new $e(e))}}var $e=function(){function e(e){if(this.total=e,this.total<0)throw new Ae}return e.prototype.call=function(e,t){return t.subscribe(new Ne(e,this.total))},e}(),Ne=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return m(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}(P);function Re(e){return function(t){return t.lift(new je(e))}}var je=function(){function e(e){this.total=e}return e.prototype.call=function(e,t){return t.subscribe(new Le(e,this.total))},e}(),Le=function(e){function t(t,n){var r=e.call(this,t)||this;return r.total=n,r.count=0,r}return m(t,e),t.prototype._next=function(e){++this.count>this.total&&this.destination.next(e)},t}(P);function We(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=e[e.length-1];return J(n)?(e.pop(),function(t){return he(e,t,n)}):function(t){return he(e,t)}}function Be(e,t){return"function"==typeof t?function(n){return n.pipe(Be((function(n,r){return ne(e(n,r)).pipe(oe((function(e,o){return t(n,e,r,o)})))})))}:function(t){return t.lift(new Fe(e))}}var Fe=function(){function e(e){this.project=e}return e.prototype.call=function(e,t){return t.subscribe(new Me(e,this.project))},e}(),Me=function(e){function t(t,n){var r=e.call(this,t)||this;return r.project=n,r.index=0,r}return m(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 H(this),r=this.destination;r.add(n),this.innerSubscription=K(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}(V);function He(){}function Ve(e,t,n){return function(r){return r.lift(new Ke(e,t,n))}}var Ke=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 qe(e,this.nextOrObserver,this.error,this.complete))},e}(),qe=function(e){function t(t,n,r,o){var i=e.call(this,t)||this;return i._tapNext=He,i._tapError=He,i._tapComplete=He,i._tapError=r||He,i._tapComplete=o||He,g(n)?(i._context=i,i._tapNext=n):n&&(i._context=n,i._tapNext=n.next||He,i._tapError=n.error||He,i._tapComplete=n.complete||He),i}return m(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}(P),ze=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 Ge=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 Je(e,this.absoluteTimeout,this.waitFor,this.withObservable,this.scheduler))},e}(),Je=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 m(t,e),t.dispatchTimeout=function(e){var t=e.withObservable;e._unsubscribeAndRecycle(),e.add(K(t,new H(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}(V);function Ye(e,t){return void 0===t&&(t=G),function(e,t,n){return void 0===n&&(n=G),function(r){var o=ve(e),i=o?+e-n.now():Math.abs(e);return r.lift(new Ge(i,o,t,n))}}(e,_e(new ze),t)}let Xe=!1;async function Ze(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){Xe||(console.debug("Dexie Cloud: Could not register sync event",e),Xe=!0)}}function Qe(e,t){e.cloud.usingServiceWorker?Ze(e,t):e.localSyncEvent.next({purpose:t})}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));async function nt({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 rt(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.table(t)))}function ot(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 st(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 at=crypto.getRandomValues;function ct(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)ct(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]={}),ct(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const ut="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return at(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function lt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>lt(e)))&&e.every(dt))}function dt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(dt)}function ht(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))ct(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 ft(e,t){for(const{table:n,muts:r}of t)for(const t of r)ht(e,n,t)}function pt(t,n){return new Promise(((r,o)=>{const i={...n,onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}};t.next(i)}))}function yt(e,t,...n){return pt(e,{type:"message-alert",title:t,alerts:n,fields:{}})}async function bt(e,t,n){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(await pt(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 vt(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 pt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}async function mt(e,t,n,r,o){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?await gt(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 pt(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts}),e}catch(e){throw await yt(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 gt(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}const{toString:_t}={};const wt={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 St(...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 wt;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,_t.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:wt),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 kt={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 xt={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 Et={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var It={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Tt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Ct={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var Pt=["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=At[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Ot(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=$t[e[n]];return t}(tt(e))}function Ut(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+=Dt[e[n]];return t}(e))}const Dt={"-":"=",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:"+","|":"/"},$t={};for(const e of Object.keys(Dt))$t[Dt[e]]=e;var Nt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Ot(e)}),revive:({v:e})=>{const t=Ut(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Rt{constructor(e,t){this.buf=e,this.type=t}}function jt(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 Lt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}const Wt={...xt,...Et,...It,...Tt,...Ct,...Pt,...Nt,...{Blob:{test:(e,t)=>"Blob"===t||e instanceof Rt,replace:e=>({$t:"Blob",v:tt(e instanceof Rt?e.buf:Lt(jt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=et(t);return void 0!==typeof Blob?new Blob([n]):new Rt(n.buffer,e)}}}};function Bt(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 Mt="bigint"==typeof BigInt(0);class Ht{constructor(e){this.v=e}toString(){return this.v}}const Vt={...Ft,...Mt?{}:{bigint:{test:e=>e instanceof Ht,replace:e=>({$t:"bigint",...e}),revive:({v:e})=>new Ht(e)}}},Kt=St(Wt,Vt),qt=function(...e){const t=St(Wt,kt,...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 Bt(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 Bt(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);class zt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}async function Gt(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 gt(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:Kt.stringify(u)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!l.ok)throw new zt(l);switch(l.headers.get("content-type")){case"application/x-bison":return qt.fromBinary(await l.blob());case"application/x-bison-stream":default:case"application/json":{const e=await l.text();return Kt.parse(e)}}}async function Jt(t,n,r){const o=await t.bulkGet(n),i=[],s=[];n.forEach(((n,a)=>{const c=o[a];if(c){for(const[n,o]of Object.entries(r[a])){if(n===t.schema.primKey.keyPath)throw new Error("Cannot change primary key");e.setByKeyPath(c,n,o)}i.push(n),s.push(c)}})),await(null==t.schema.primKey.keyPath?t.bulkPut(s,i):t.bulkPut(s))}function Yt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Xt=navigator.onLine;async function Zt(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 Qt(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",(()=>Xt=!0)),self.addEventListener("offline",(()=>Xt=!1));function en(e,t,n,r){return tn.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:Xt,syncOptions:r,error:o}),Xt&&(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 en(e,t,n,{...r,retryImmediatelyOnFetchError:!1})):(await e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Xt?"error":"offline",error:o}),Promise.reject(o)))))}async function tn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=await e.getCurrentUser(),l=u.isLoggedIn?rt(e):[],d=l.map((t=>e.table(ot(t.name)))),f=await e.getPersistedSyncState(),p=!r&&u.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return rt(e).filter((e=>!n.includes(e.name)))}(e,f):[];Yt(o);const y=p.length>0;if(y){if(i)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!==h.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?await n.toCollection().modify((e=>{(r.has(e.realmId)||e.owner)&&e.owner!==h.userId||(e.owner=t.userId)})):await n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==h.userId||(e.owner=t.userId),e.realmId&&e.realmId!==h.userId||(e.realmId=t.userId))})))}(p,u,null==f?void 0:f.realms)})),Yt(o)}const[b,v,m]=await e.transaction("r",e.tables,(async()=>{const t=await e.getPersistedSyncState(),r=await e.$baseRevs.toArray();let i=await st(d);if(Yt(o),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||"")&&lt(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,u,n,null==f?void 0:f.realms);return Yt(o),i=i.concat(e),[i,t,r]}return[i,t,r]})),g=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return console.debug("Sync is needed:",g),g;if("push"===s&&!g)return!1;const _=Qt(b,null==v?void 0:v.latestRevisions),w=(null==v?void 0:v.clientIdentity)||ut(16);Yt(o);const S=await Gt(b,v,m,e,c,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 st(d,0,{since:_});for(const t of d){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()])}Qt(r,_),await Zt(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=rt(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=l.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=rn(S.changes,r);return await nn(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 tn(e,t,n,{isInitialSync:r,cancelToken:o}))}async function nn(t,n){console.debug("Applying server changes",t,e.currentTransaction);for(const{table:r,muts:o}of t){const t=n.table(r);if(!t)continue;const{primaryKey:i}=t.core.schema;for(const n of o)switch(n.type){case"insert":i.outbound?await t.bulkAdd(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkAdd(n.values));break;case"upsert":i.outbound?await t.bulkPut(n.values,n.keys):(n.keys.forEach(((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)})),await t.bulkPut(n.values));break;case"modify":1===n.keys.length?await t.update(n.keys[0],n.changeSpec):await t.where(":id").anyOf(n.keys).modify(n.changeSpec);break;case"update":await Jt(t,n.keys,n.changeSpecs);break;case"delete":await t.bulkDelete(n.keys)}}}function rn(e,t){const n={};ft(n,e);const r={};return ft(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))ct(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=ut(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 on(t){const n=[],o=new r(!0),i=new r(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 r,o,i;for(;n.length>0;){const s=n.shift();try{console.debug("processing msg",s),await t.cloud.syncState.pipe(Pe((({phase:e})=>"in-sync"===e||"error"===e)),De(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=await gt(t.cloud.options.databaseUrl,a);await t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(s.realm))||Qe(t,"pull");break;case"realm-removed":(null===(o=null==n?void 0:n.realms)||void 0===o?void 0:o.includes(s.realm))&&Qe(t,"pull");break;case"realms-changed":Qe(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){Qe(t,"pull");break}await t.transaction("rw",t.dx.tables,(async n=>{n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,o,i]=await Promise.all([t.getSchema(),t.getPersistedSyncState(),t.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!r||!i)return void console.debug("required vars not present",{syncState:o,schema:r,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||Qe(t,"pull"));const a=await e.waitFor(nt(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void Qe(t,"pull");let c=[];if(i.isLoggedIn){const e=rt(t).map((e=>t.table(ot(e.name))));c=await st(e),console.debug("msg queue: client changes",c)}if(s.changes.length>0){const e=rn(s.changes,c);console.debug("applying filtered server changes",e),await nn(e,t)}o.latestRevisions=Qt(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),await Zt(t,r,o.latestRevisions,s.newRev),console.debug("Updating syncState",o),await t.$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 sn=new WeakMap,an={realms:"@realmId",members:"@id",roles:"[realmId+name]",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let cn=0;function un(e){"vip"in e&&(e=e.vip);let t=sn.get(e.cloud);if(!t){const n=new o;let r=new b(`syncstatechanged-${e.name}`);n.id=++cn;let i=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return i},localSyncEvent:n,get syncStateChangedEvent(){return r},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||h)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema"),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){i=e},reconfigure(){r=new b(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=on(t),sn.set(e.cloud,t)}return t}const ln=new WeakMap;class dn{constructor(e,t){ln.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new dn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}async save(){ln.get(this).table("$logins").put(this)}}async function hn(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 dn(e,{claims:{},lastLogin:new Date(0)});await mt(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 bt(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 bt(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 yt(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new zt(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 vt(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 vt(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 yt(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new zt(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),Qe(e,"pull")}const fn="undefined"!=typeof InstallTrigger,pn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),yn=pn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,bn=pn&&yn<=605||fn;const vn="undefined"!=typeof self&&"clients"in self&&!self.document;function mn(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:gn}={};function _n(e){return gn.call(e).slice(8,-1)}function wn(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 Sn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let kn=0;function xn(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>({...n,table:r=>{const o=n.table(r);function i(n,i){let s=null;const a=wn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=function(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();kn>=o?++kn:kn=o,r[0]=kn/1099511627776,r[1]=kn/4294967296,r[2]=kn/16777216,r[3]=kn/65536,r[4]=kn/256,r[5]=kn;const i=new Uint8Array(n.buffer,6);return crypto.getRandomValues(i),e+Ot(new Uint8Array(n.buffer))+(t||"")}(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}.\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({...n,keys:a,values:s||n.values})}return{...o,mutate:n=>{var s,a;if(n.trans.disableChangeTracking)return o.mutate(n);if("add"===n.type||"put"===n.type){const c=null===(s=t.cloud.schema)||void 0===s?void 0:s[r];if(null==c?void 0:c.generatedGlobalId){if((null===(a=t.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!t.initiallySynced){const e=wn(o.schema.primaryKey,n);return o.getMany({keys:e,trans:n.trans,cache:"immutable"}).then((t=>{if(t.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(n)}))}return i(n,c.idPrefix)}if(null==c?void 0:c.markedForSync){wn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!lt(t)){const n=Array.isArray(t)?t.map(_n).join(","):_n(t);throw new e.ConstraintError(`Invalid primary key type ${n} for table ${r}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(n)}}}})}}function En(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}let In=0;function Tn(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 Cn(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 An=new r(new Set);function Pn({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){mn()}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=>ot(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=En(16),i.currentUser=e.value,An.value.add(i),An.next(An.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),An.value.delete(i),An.next(An.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"),Ze(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"+ ++In;return{...e,count:Tn(e.count,t),get:Tn(e.get,t),getMany:Tn(e.getMany,t),openCursor:Tn(e.openCursor,t),query:Tn(e.query,t),mutate:Cn(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 h=Date.now(),f="delete"===e.type?{type:"delete",ts:h,keys:u,criteria:e.criteria,txid:r,userId:o}:"add"===e.type?{type:"insert",ts:h,keys:u,txid:r,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:h,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:r,userId:o}:e.changeSpecs?{type:"update",ts:h,keys:u,changeSpecs:d,txid:r,userId:o}:{type:"upsert",ts:h,keys:u,values:l,txid:r,userId:o};return u.length>0||"criteria"in e&&e.criteria?i.mutate({type:"add",trans:n,values:[f]}).then((()=>t)):t}))}}}}}}function On(e,t){return function(n,r){const o={...an,...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)(Sn.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 Un=En(16);async function Dn(e,n,r,o,{awaitRemoteJob:s}={}){const a=e.table(r);if(await async function o(){if(await e.transaction("rw!",r,(async()=>{const e=await a.get(n);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${n} 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:Un,started:new Date,heartbeat:new Date},n),!0):(await a.add({nodeId:Un,started:new Date,heartbeat:new Date},n),!0)})))return!0;if(s)try{const e=i(t((()=>a.get(n)))).pipe(Ye(6e4),Pe((e=>!e)));return await e.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return await o()}return!1}()){const t=setInterval((()=>{a.update(n,(e=>e.nodeId===Un&&(e.heartbeat=new Date)))}),1e3);try{return await o()}finally{clearInterval(t),await e.transaction("rw!",r,(async()=>{const e=await a.get(n);e&&e.nodeId===Un&&a.delete(n)}))}}}const $n=new r(!0),Nn=new r(!0);var Rn,jn;$n.pipe(Be((e=>e?a(!0):a(!1).pipe(ke(2e4)))),(function(e){return e.lift(new Te(Rn,jn))})).subscribe(Nn);const Ln="undefined"!=typeof document?s(document,"visibilitychange"):a({}),Wn=Ln.pipe(Pe((()=>"hidden"===document.visibilityState))),Bn=Ln.pipe(Pe((()=>"visible"===document.visibilityState))),Fn="undefined"!=typeof window?c(Bn,s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),Wn,Fn).pipe(oe((()=>"visible"===document.visibilityState)),Ve((e=>{$n.value!==e&&$n.next(e)})),Be((e=>e?a(0).pipe(ke(28e4),Ve((()=>$n.next(!1)))):a(0)))).subscribe((()=>{}));class Mn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Hn extends n{constructor(e,t,n,r,o,i,s,a){super((c=>new Kn(e,t,n,r,s,a,c,o,i)))}}let Vn=0;class Kn extends u{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++Vn,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 Mn);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=Kt.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(Kt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}}async function qn(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 Fn.pipe(De(1)).toPromise(),console.debug("someone did something!")}async function zn(e){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&await en(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0})}const Gn=new WeakMap;function Jn(e,t,n,r){const o=Gn.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 Jn(e,t,n,r)}))}}const i=async function(){try{e.cloud.usingServiceWorker?vn&&await en(e,t,n,r):await Dn(e,"currentSyncWorker","$jobs",(()=>en(e,t,n,r))),Gn.delete(e),console.debug("Done sync")}catch(t){throw Gn.delete(e),console.error("Failed to sync client changes",t),t}}();return Gn.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function Yn(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){setTimeout((()=>{Jn(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 Xn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Zn,Qn,er,tr,nr={},rr=[],or=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function ir(e,t){for(var n in t)e[n]=t[n];return e}function sr(e){var t=e.parentNode;t&&t.removeChild(e)}function ar(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 cr(e,a,r,o,null)}function cr(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?++Zn.__v:o};return null!=Zn.vnode&&Zn.vnode(i),i}function ur(e){return e.children}function lr(e,t){this.props=e,this.context=t}function dr(e,t){if(null==t)return e.__?dr(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?dr(e):null}function hr(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 hr(e)}}function fr(e){(!e.__d&&(e.__d=!0)&&Qn.push(e)&&!pr.__r++||tr!==Zn.debounceRendering)&&((tr=Zn.debounceRendering)||er)(pr)}function pr(){for(var e;pr.__r=Qn.length;)e=Qn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Qn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=ir({},o)).__v=o.__v+1,Sr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?dr(o):i,o.__h),kr(n,o),o.__e!=i&&hr(o)))}))}function yr(e,t,n,r,o,i,s,a,c,u){var l,d,h,f,p,y,b,v=r&&r.__k||rr,m=v.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(f=n.__k[l]=null==(f=t[l])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?cr(null,f,null,null,f):Array.isArray(f)?cr(ur,{children:f},null,null,null):f.__b>0?cr(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=v[l])||h&&f.key==h.key&&f.type===h.type)v[l]=void 0;else for(d=0;d<m;d++){if((h=v[d])&&f.key==h.key&&f.type===h.type){v[d]=void 0;break}h=null}Sr(e,f,h=h||nr,o,i,s,a,c,u),p=f.__e,(d=f.ref)&&h.ref!=d&&(b||(b=[]),h.ref&&b.push(h.ref,null,f),b.push(d,f.__c||p,f)),null!=p?(null==y&&(y=p),"function"==typeof f.type&&null!=f.__k&&f.__k===h.__k?f.__d=c=br(f,c,e):c=vr(e,f,h,v,p,c),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=c):e.value=""):c&&h.__e==c&&c.parentNode!=e&&(c=dr(h))}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=dr(r,l+1)),Ir(v[l],v[l]));if(b)for(l=0;l<b.length;l++)Er(b[l],b[++l],b[++l])}function br(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?br(o,t,n):vr(n,o,o,e.__k,o.__e,t));return t}function vr(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 mr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||or.test(t)?n:n+"px"}function gr(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||mr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||mr(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?wr:_r,i):e.removeEventListener(t,i?wr:_r,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 _r(e){this.l[e.type+!1](Zn.event?Zn.event(e):e)}function wr(e){this.l[e.type+!0](Zn.event?Zn.event(e):e)}function Sr(e,t,n,r,o,i,s,a,c){var u,l,d,h,f,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=Zn.__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 lr(b,m),l.constructor=_,l.render=Tr),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=ir({},l.__s)),ir(l.__s,_.getDerivedStateFromProps(b,l.__s))),h=l.props,f=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&b!==h&&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(h,f,p)}))}l.context=m,l.props=b,l.state=l.__s,(u=Zn.__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=ir(ir({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(p=l.getSnapshotBeforeUpdate(h,f)),g=null!=u&&u.type===ur&&null==u.key?u.props.children:u,yr(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=xr(n.__e,t,n,r,o,i,s,c);(u=Zn.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),Zn.__e(e,t,n)}}function kr(e,t){Zn.__c&&Zn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Zn.__e(e,t.__v)}}))}function xr(e,t,n,r,o,i,s,a){var c,u,l,d,h=n.props,f=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(f);e=o?document.createElementNS("http://www.w3.org/2000/svg",p):document.createElement(p,f.is&&f),i=null,a=!1}if(null===p)h===f||a&&e.data===f||(e.data=f);else{if(i=i&&rr.slice.call(e.childNodes),u=(h=n.props||nr).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(h={},d=0;d<e.attributes.length;d++)h[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||gr(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]||gr(e,i,t[i],n[i],r)}(e,f,h,o,a),l)t.__k=[];else if(y=t.props.children,yr(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]&&sr(i[y]);a||("value"in f&&void 0!==(y=f.value)&&(y!==e.value||"progress"===p&&!y)&&gr(e,"value",y,h.value,!1),"checked"in f&&void 0!==(y=f.checked)&&y!==e.checked&&gr(e,"checked",y,h.checked,!1))}return e}function Er(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Zn.__e(e,n)}}function Ir(e,t,n){var r,o,i;if(Zn.unmount&&Zn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Er(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){Zn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&Ir(r[i],t,n);null!=o&&sr(o)}function Tr(e,t,n){return this.constructor(e,n)}Zn={__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},lr.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=ir({},this.state),"function"==typeof e&&(e=e(ir({},n),this.props)),e&&ir(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),fr(this))},lr.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),fr(this))},lr.prototype.render=ur,Qn=[],er="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,pr.__r=0;const Cr={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 Ar({children:e}){return ar("div",null,ar("div",{style:Cr.Darken}),ar("div",{style:Cr.DialogOuter},ar("div",{style:Cr.DialogInner},e)))}var Pr,Or,Ur,Dr=0,$r=[],Nr=Zn.__b,Rr=Zn.__r,jr=Zn.diffed,Lr=Zn.__c,Wr=Zn.unmount;function Br(e,t){Zn.__h&&Zn.__h(Or,e,Dr||t),Dr=0;var n=Or.__H||(Or.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Fr(e){return Dr=1,function(e,t,n){var r=Br(Pr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Gr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Or),r.__}(Gr,e)}function Mr(e){return Dr=5,function(e,t){var n=Br(Pr++,7);return zr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Hr(){$r.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Kr),e.__H.__h.forEach(qr),e.__H.__h=[]}catch(t){e.__H.__h=[],Zn.__e(t,e.__v)}})),$r=[]}Zn.__b=function(e){Or=null,Nr&&Nr(e)},Zn.__r=function(e){Rr&&Rr(e),Pr=0;var t=(Or=e.__c).__H;t&&(t.__h.forEach(Kr),t.__h.forEach(qr),t.__h=[])},Zn.diffed=function(e){jr&&jr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==$r.push(t)&&Ur===Zn.requestAnimationFrame||((Ur=Zn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Vr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Vr&&(t=requestAnimationFrame(n))})(Hr)),Or=void 0},Zn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Kr),e.__h=e.__h.filter((function(e){return!e.__||qr(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Zn.__e(n,e.__v)}})),Lr&&Lr(e,t)},Zn.unmount=function(e){Wr&&Wr(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Kr)}catch(e){Zn.__e(e,t.__v)}};var Vr="function"==typeof requestAnimationFrame;function Kr(e){var t=Or;"function"==typeof e.__c&&e.__c(),Or=t}function qr(e){var t=Or;e.__c=e.__(),Or=t}function zr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Gr(e,t){return"function"==typeof t?t(e):t}function Jr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=Fr({}),a=Mr();return function(e,t){var n=Br(Pr++,4);!Zn.__s&&zr(n.__H,t)&&(n.__=e,n.__H=t,Or.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),ar(Ar,null,ar(ur,null,ar("h3",{style:Cr.WindowHeader},e),t.map((e=>ar("p",{style:Cr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),ar("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>ar("label",{style:Cr.Label},n?`${n}: `:"",ar("input",{ref:0===o?a:void 0,type:t,name:e,autoComplete:"on",style:Cr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s({...i,[e]:Yr(t,null===(r=n.target)||void 0===r?void 0:r.value)})}})))))),ar("div",{style:Cr.ButtonsDiv},ar("button",{type:"submit",style:Cr.Button,onClick:()=>o(i)},"Submit"),ar("button",{style:Cr.Button,onClick:r},"Cancel")))}function Yr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class Xr extends lr{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=i(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ar(Jr,Object.assign({},t)):null}}function Zr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;Zn.__&&Zn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Sr(t,e=(!r&&n||t).__k=ar(ur,null,[e]),o||nr,nr,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?rr.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),kr(i,e)}(ar(Xr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function Qr(n){const o=n.name,c=new r(h),u=[];let f=null;n.on("ready",(async n=>{try{await async function(n){var r,o,h,b,v,m;p=!1;const g=un(n);vn||((null===(r=g.cloud.options)||void 0===r?void 0:r.customLoginGui)||u.push(Zr(n)),u.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Be((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return $n.value?r.pipe(fe(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(fe(4e3));default:return r}})));return d([n,e.syncStateChangedEvent.pipe(We({phase:"initial"})),Nn]).pipe(oe((([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:Xt?a:"offline"}})))}(g).subscribe(n.cloud.syncState)));g.tables.every((e=>e.core))||mn();const _="serviceWorker"in navigator?await navigator.serviceWorker.getRegistrations():[],w=await g.transaction("rw",g.$syncState,(async()=>{var e,t;const{options:n,schema:r}=g.cloud,[o,i,s]=await Promise.all([g.getOptions(),g.getSchema(),g.getPersistedSyncState()]);if(n?o&&JSON.stringify(o)===JSON.stringify(n)||await g.$syncState.put(n,"options"):g.cloud.options=o||null,(null===(e=g.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&_.length>0&&!bn?(console.debug("Dexie Cloud Addon: Using service worker"),g.cloud.usingServiceWorker=!0):((null===(t=g.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!vn&&console.debug("dexie-cloud-addon: Not using service worker.",0===_.length?"No SW registrations found.":"serviceWorker"in navigator&&bn?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),g.cloud.usingServiceWorker=!1),Xn(r,g.cloud.options),Xn(i,g.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 g.$syncState.put(e,"schema"),Object.assign(r,e)}}else g.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}));w&&g.setInitiallySynced(!0);(function(t){var n,r;for(const o of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[o.name])||void 0===r?void 0:r.markedForSync){if(o.schema.primKey.auto)throw new e.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new e.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}})(g),(null===(o=g.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!w&&(await async function(e,t,n){console.debug("Performing initial sync"),await Dn(e,"initialSync","$jobs",(async()=>{const r=await e.getPersistedSyncState();(null==r?void 0:r.initiallySynced)||await en(e,t,n,{isInitialSync:!0})}),{awaitRemoteJob:!0}),console.debug("Done initial sync")}(g,g.cloud.options,g.cloud.schema),g.setInitiallySynced(!0));y(),vn||(u.push(t((()=>g.getCurrentUser())).subscribe(c)),u.push(t((()=>g.getPersistedSyncState())).subscribe(g.cloud.persistedSyncState)),await d([c.pipe(Re(1),De(1)),g.cloud.persistedSyncState.pipe(Re(1),De(1))]).toPromise());(null===(h=g.cloud.options)||void 0===h?void 0:h.requireAuth)&&await hn(g);f&&f.stop();f=null,y(),g.cloud.usingServiceWorker&&(null===(b=g.cloud.options)||void 0===b?void 0:b.databaseUrl)?(Ze(g,"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)}}(g).catch((()=>{}))):(null===(v=g.cloud.options)||void 0===v?void 0:v.databaseUrl)&&g.cloud.schema&&!vn&&(f=Yn(g,g.cloud.options,g.cloud.schema),f.start(),Qe(g,"push"));y(),vn||u.push(s(self,"online").subscribe((()=>{console.debug("online!"),g.syncStateChangedEvent.next({phase:"not-in-sync"}),Qe(g,"push")})),s(self,"offline").subscribe((()=>{console.debug("offline!"),g.syncStateChangedEvent.next({phase:"offline"})})));"undefined"!=typeof window&&!vn&&(null===(m=g.cloud.options)||void 0===m?void 0:m.databaseUrl)&&u.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const n=e.messageConsumer.readyToServe.pipe(Pe((e=>e)),Be((()=>e.getPersistedSyncState())),Pe((e=>e&&e.serverRevision)),oe((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Pe((e=>null==e?void 0:e.serverRevision)),De(1),Be((t=>e.cloud.currentUser.pipe(oe((e=>[e,t]))))),Be((([e,t])=>Nn.pipe(oe((n=>[n?e:null,t]))))),Be((async([e,t])=>[e,await nt(t)])),Be((([t,r])=>t?new Hn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,r,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):i([]))),Y((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Be((async()=>{const t=await e.getCurrentUser(),n=await gt(e.cloud.options.databaseUrl,t);await e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})),Be((()=>t())))):l(n))),Y((e=>i(qn(e)).pipe(Be((()=>t()))))))}().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!")}))}(g))}(n)}catch(e){console.error(e)}}),!0);let p=!1;function y(){if(p)throw new e.DatabaseClosedError}var b;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{u.forEach((e=>e.unsubscribe())),p=!0,f&&f.stop(),f=null,c.next(h)})),n.cloud={version:"1.0.0-beta.10",options:null,schema:null,serverState:null,get currentUserId(){return c.value.userId||h.userId},currentUser:c,syncState:new r({phase:"initial",status:"not-started"}),persistedSyncState:new r(void 0),userInteraction:new r(void 0),webSocketStatus:new r("not-started"),async login(e){const t=un(n);await t.cloud.sync(),await hn(t,e)},configure(e){n.cloud.options=e,e.databaseUrl&&(n.name=`${o}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,un(n).reconfigure()),Xn(n.cloud.schema,n.cloud.options)},async sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){void 0===e&&(e=!0);const o=un(n);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(Qe(o,r),e){const e=await o.cloud.persistedSyncState.pipe(Pe((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),De(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(await zn(o)){const n=o.cloud.persistedSyncState.value;Qe(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),await i(t((async()=>{const e=await zn(o),t=await o.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(Pe((e=>!e)),De(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}},n.Version.prototype._parseStoresSpec=e.override(n.Version.prototype._parseStoresSpec,(e=>On(e,n))),n.use(Pn({currentUserObservable:n.cloud.currentUser,db:un(n)})),n.use((b=un(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=b.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(xn(un(n)))}Qr.version="1.0.0-beta.10",e.Cloud=Qr;const eo=new Map;function to(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const no=new Map;function ro(t,n){let r=no.get(t+"/"+n);return r||(r=async function(t,n){var r;let o=eo.get(t);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const n=new e(t,{addons:[Qr]});o=un(n),n.on("versionchange",i),await o.dx.open(),eo.get(t)||eo.set(t,o)}if(!(null===(r=o.cloud.options)||void 0===r?void 0:r.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),eo.get(o.name)===o&&eo.delete(o.name),console.debug(`Dexie Cloud SW: Closing Dexie instance for ${t}`),o.dx.close(),!1}try{console.debug("Dexie Cloud SW: Syncing"),await Jn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(t){if(console.error("Dexie Cloud SW Error",t),i(),t.name!==e.errnames.NoSuchDatabase)throw t}}(t,n).then((()=>{no.delete(t+"/"+n)})).catch((e=>(no.delete(t+"/"+n),Promise.reject(e)))),no.set(t+"/"+n,r)),r}bn||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=to(e.tag);t&&e.waitUntil(ro(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=to(e.tag);t&&e.waitUntil(ro(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)=>ro(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)))}})));