dexie-cloud-addon 4.0.0-beta.19 → 4.0.0-beta.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs")):"function"==typeof define&&define.amd?define(["dexie","rxjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);function o(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,c)}a((r=r.apply(e,t||[])).next())}))}const i={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(i),Object.freeze(i.claims)}catch(e){}const s={},c=self.document&&navigator.serviceWorker;c&&c.ready.then((e=>s.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class a{constructor(e){this.name=e}subscribe(e){if(!c)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 c.addEventListener("message",t),()=>c.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}))):s.registration&&(null===(t=s.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class u extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new a(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof a?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof a?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",Object.assign({},e),"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}function l(e){return"function"==typeof e}function d(e){return function(t){if(function(e){return l(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}var f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},f(e,t)};function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function h(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,c)}a((r=r.apply(e,t||[])).next())}))}function v(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function b(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function m(e,t){for(var n=0,r=t.length,o=e.length;n<r;n++,o++)e[o]=t[n];return e}function g(e){return this instanceof g?(this.v=e,this):new g(e)}function _(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof g?Promise.resolve(e.value.v).then(a,u):l(i[0][2],e)}(o[e](t))}catch(e){l(i[0][3],e)}}function a(e){c("next",e)}function u(e){c("throw",e)}function l(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}}function w(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=y(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}var S=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function k(e){return l(null==e?void 0:e.then)}function x(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var I=x((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function E(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var O=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._teardowns=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=y(i),c=s.next();!c.done;c=s.next()){c.value.remove(this)}}catch(t){e={error:t}}finally{try{c&&!c.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var a=this.initialTeardown;if(l(a))try{a()}catch(e){o=e instanceof I?e.errors:[e]}var u=this._teardowns;if(u){this._teardowns=null;try{for(var d=y(u),f=d.next();!f.done;f=d.next()){var p=f.value;try{C(p)}catch(e){o=null!=o?o:[],e instanceof I?o=m(m([],b(o)),b(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}}if(o)throw new I(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)C(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._teardowns=null!==(n=this._teardowns)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&E(t,e)},e.prototype.remove=function(t){var n=this._teardowns;n&&E(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function T(e){return e instanceof O||e&&"closed"in e&&l(e.remove)&&l(e.add)&&l(e.unsubscribe)}function C(e){l(e)?e():e.unsubscribe()}var A={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},j={setTimeout:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=j.delegate;return((null==n?void 0:n.setTimeout)||setTimeout).apply(void 0,m([],b(e)))},clearTimeout:function(e){var t=j.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function P(e){j.setTimeout((function(){throw e}))}function U(){}var D=$("C",void 0,void 0);function $(e,t,n){return{kind:e,value:t,error:n}}function R(e){0}var L=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,T(t)&&t.add(n)):n.destination=F,n}return p(t,e),t.create=function(e,t,n){return new N(e,t,n)},t.prototype.next=function(e){this.isStopped?M(function(e){return $("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?M($("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?M(D,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(O),N=function(e){function t(t,n,r){var o,i=e.call(this)||this;if(l(t))o=t;else if(t){var s;o=t.next,n=t.error,r=t.complete,i&&A.useDeprecatedNextContext?(s=Object.create(t)).unsubscribe=function(){return i.unsubscribe()}:s=t,o=null==o?void 0:o.bind(s),n=null==n?void 0:n.bind(s),r=null==r?void 0:r.bind(s)}return i.destination={next:o?W(o):U,error:W(null!=n?n:B),complete:r?W(r):U},i}return p(t,e),t}(L);function W(e,t){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{e.apply(void 0,m([],b(t)))}catch(e){A.useDeprecatedSynchronousErrorHandling?R():P(e)}}}function B(e){throw e}function M(e,t){var n=A.onStoppedNotification;n&&j.setTimeout((function(){return n(e,t)}))}var F={closed:!0,next:U,error:B,complete:U},H="function"==typeof Symbol&&Symbol.observable||"@@observable";function K(e){return e}function q(e){return 0===e.length?K:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var z=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,o=this,i=(r=e)&&r instanceof L||function(e){return e&&l(e.next)&&l(e.error)&&l(e.complete)}(r)&&T(r)?e:new N(e,t,n);return function(){var e=o,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=V(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),null==o||o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[H]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return q(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=V(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function V(e){var t;return null!==(t=null!=e?e:A.Promise)&&void 0!==t?t:Promise}function G(e){return l(e[H])}function J(e){return Symbol.asyncIterator&&l(null==e?void 0:e[Symbol.asyncIterator])}function Y(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var Q="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Z(e){return l(null==e?void 0:e[Q])}function X(e){return _(this,arguments,(function(){var t,n,r;return v(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,g(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,g(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,g(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function ee(e){return l(null==e?void 0:e.getReader)}function te(e){if(e instanceof z)return e;if(null!=e){if(G(e))return o=e,new z((function(e){var t=o[H]();if(l(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(S(e))return r=e,new z((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(k(e))return n=e,new z((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,P)}));if(J(e))return ne(e);if(Z(e))return t=e,new z((function(e){var n,r;try{for(var o=y(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()}));if(ee(e))return ne(X(e))}var t,n,r,o;throw Y(e)}function ne(e){return new z((function(t){(function(e,t){var n,r,o,i;return h(this,void 0,void 0,(function(){var s,c;return v(this,(function(a){switch(a.label){case 0:a.trys.push([0,5,6,11]),n=w(e),a.label=1;case 1:return[4,n.next()];case 2:if((r=a.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];a.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=a.sent(),o={error:c},[3,11];case 6:return a.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:a.sent(),a.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}var re=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.onFinalize=i,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return p(t,e),t.prototype.unsubscribe=function(){var t,n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))},t}(L),oe=function(e){function t(t,n){return e.call(this)||this}return p(t,e),t.prototype.schedule=function(e,t){return this},t}(O),ie={setInterval:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=ie.delegate;return((null==n?void 0:n.setInterval)||setInterval).apply(void 0,m([],b(e)))},clearInterval:function(e){var t=ie.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},se=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 p(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),ie.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;ie.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,E(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(oe),ce={now:function(){return(ce.delegate||Date).now()},delegate:void 0},ae=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=ce.now,e}(),ue=new(function(e){function t(t,n){void 0===n&&(n=ae.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return p(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(ae))(se),le=ue;function de(e){return e&&l(e.schedule)}function fe(e){return e instanceof Date&&!isNaN(e)}function pe(e){return de((t=e)[t.length-1])?e.pop():void 0;var t}function he(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var i=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(i),!o)return i}function ve(e){return d((function(t,n){var r,o=null,i=!1;o=t.subscribe(new re(n,void 0,void 0,(function(s){r=te(e(s,ve(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):i=!0}))),i&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function ye(e,t){return void 0===t&&(t=0),d((function(n,r){n.subscribe(new re(r,(function(n){return he(r,e,(function(){return r.next(n)}),t)}),(function(){return he(r,e,(function(){return r.complete()}),t)}),(function(n){return he(r,e,(function(){return r.error(n)}),t)})))}))}function be(e,t){return void 0===t&&(t=0),d((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function me(e,t){if(!e)throw new Error("Iterable cannot be null");return new z((function(n){he(n,t,(function(){var r=e[Symbol.asyncIterator]();he(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function ge(e,t){if(null!=e){if(G(e))return function(e,t){return te(e).pipe(be(t),ye(t))}(e,t);if(S(e))return function(e,t){return new z((function(n){var r=0;return t.schedule((function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())}))}))}(e,t);if(k(e))return function(e,t){return te(e).pipe(be(t),ye(t))}(e,t);if(J(e))return me(e,t);if(Z(e))return function(e,t){return new z((function(n){var r;return he(n,t,(function(){r=e[Q](),he(n,t,(function(){var e,t,o;try{t=(e=r.next()).value,o=e.done}catch(e){return void n.error(e)}o?n.complete():n.next(t)}),0,!0)})),function(){return l(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(ee(e))return function(e,t){return me(X(e),t)}(e,t)}throw Y(e)}function _e(e,t){return t?ge(e,t):te(e)}function we(e,t){return d((function(n,r){var o=0;n.subscribe(new re(r,(function(n){r.next(e.call(t,n,o++))})))}))}function Se(e,t,n){return void 0===n&&(n=1/0),l(t)?Se((function(n,r){return we((function(e,o){return t(n,e,r,o)}))(te(e(n,r)))}),n):("number"==typeof t&&(n=t),d((function(t,r){return function(e,t,n,r,o,i,s,c){var a=[],u=0,l=0,d=!1,f=function(){!d||a.length||u||t.complete()},p=function(e){return u<r?h(e):a.push(e)},h=function(e){i&&t.next(e),u++;var c=!1;te(n(e,l++)).subscribe(new re(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){c=!0}),void 0,(function(){if(c)try{u--;for(var e=function(){var e=a.shift();s?he(t,s,(function(){return h(e)})):h(e)};a.length&&u<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(new re(t,p,(function(){d=!0,f()}))),function(){null==c||c()}}(t,r,e,n)})))}function ke(){return void 0===(e=1)&&(e=1/0),Se(K,e);var e}function xe(e,t){return void 0===t&&(t=ue),d((function(n,r){var o=null,i=null,s=null,c=function(){if(o){o.unsubscribe(),o=null;var e=i;i=null,r.next(e)}};function a(){var n=s+e,i=t.now();if(i<n)return o=this.schedule(void 0,n-i),void r.add(o);c()}n.subscribe(new re(r,(function(n){i=n,s=t.now(),o||(o=t.schedule(a,e),r.add(o))}),(function(){c(),r.complete()}),void 0,(function(){i=o=null})))}))}function Ie(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ke()(_e(e,pe(e)))}var Ee=new z((function(e){return e.complete()}));function Oe(e){return e<=0?function(){return Ee}:d((function(t,n){var r=0;t.subscribe(new re(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Te(e,t){return t?function(n){return Ie(t.pipe(Oe(1),d((function(e,t){e.subscribe(new re(t,U))}))),n.pipe(Te(e)))}:Se((function(t,n){return e(t,n).pipe(Oe(1),function(e){return we((function(){return e}))}(t))}))}function Ce(e,t){void 0===t&&(t=ue);var n=function(e,t,n){void 0===e&&(e=0),void 0===n&&(n=le);var r=-1;return null!=t&&(de(t)?n=t:r=t),new z((function(t){var o=fe(e)?+e-n.now():e;o<0&&(o=0);var i=0;return n.schedule((function(){t.closed||(t.next(i++),0<=r?this.schedule(void 0,r):t.complete())}),o)}))}(e,t);return Te((function(){return n}))}function Ae(e,t){return e===t}function je(e,t){return d((function(n,r){var o=0;n.subscribe(new re(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function Pe(e){return je((function(t,n){return e<=n}))}function Ue(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=pe(e);return d((function(t,r){(n?Ie(e,t,n):Ie(e,t)).subscribe(r)}))}function De(e,t){return d((function(n,r){var o=null,i=0,s=!1,c=function(){return s&&!o&&r.complete()};n.subscribe(new re(r,(function(n){null==o||o.unsubscribe();var s=0,a=i++;te(e(n,a)).subscribe(o=new re(r,(function(e){return r.next(t?t(n,e,a,s++):e)}),(function(){o=null,c()})))}),(function(){s=!0,c()})))}))}function $e(e,t,n){var r=l(e)||t||n?{next:e,error:t,complete:n}:e;return r?d((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(new re(t,(function(e){var n;null===(n=r.next)||void 0===n||n.call(r,e),t.next(e)}),(function(){var e;o=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()}),(function(e){var n;o=!1,null===(n=r.error)||void 0===n||n.call(r,e),t.error(e)}),(function(){var e,t;o&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)})))})):K}var Re=x((function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}));function Le(e){throw new Re(e)}let Ne=!1;function We(e,t){return o(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){Ne||(console.debug("Dexie Cloud: Could not register sync event",e),Ne=!0)}}))}function Be(e,t){e.cloud.usingServiceWorker?We(e,t):e.localSyncEvent.next({purpose:t})}const Me="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},Fe="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 He({realms:e,inviteRealms:t}){return o(this,void 0,void 0,(function*(){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),o=yield crypto.subtle.digest("SHA-1",r);return Fe(o)}))}function Ke(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function qe(e){return`$${e}_mutations`}function ze(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const Ve=[].concat;function Ge(e){return Ve.apply([],e)}function Je(e,t,{since:n={},limit:r=1/0}={}){return o(this,void 0,void 0,(function*(){const t=Ge(yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){const t=ze(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return(yield i.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.ts-t.mut.ts)),i=[];let s=null,c=null;for(const{table:e,mut:n}of t)s&&s.table===e&&c===n.txid?s.muts.push(n):(s={table:e,muts:[n]},c=n.txid,i.push(s));return i}))}function Ye(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}const Qe=crypto.getRandomValues;function Ze(e){if(!e)throw new Error("Assertion Failed")}function Xe(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){Ze("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)Xe(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),c=t.substr(i+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var a=e[s];a||(a=e[s]={}),Xe(a,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const et="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Qe(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function tt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>tt(e)))&&e.every(nt))}function nt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(nt)}function rt(e,t,n){const r=e[t]||(e[t]={}),o=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":o.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":o.forEach(((e,t)=>{const o="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(o))Xe(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":o.forEach((e=>{r[e]={type:"del"}}))}return e}function ot(e,t){for(const{table:n,muts:r}of t)for(const t of r)rt(e,n,t)}function it(e,t){let n=!1;return new Promise(((o,i)=>{const s=Object.assign(Object.assign({},t),{onSubmit:t=>{e.next(void 0),n=!0,o(t)},onCancel:()=>{e.next(void 0),n=!0,i(new r.default.AbortError("User cancelled"))}});e.next(s)}))}function st(e,t,...n){return it(e,{type:"message-alert",title:t,alerts:n,fields:{}})}function ct(e,t,n){return o(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(yield it(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function at(e,t,n){return o(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:o}=yield it(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function ut(e,t,n,r,i){return o(this,void 0,void 0,(function*(){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?yield lt(e,t):yield function(e,t,n,r){return o(this,void 0,void 0,(function*(){const{privateKey:o,publicKey:i}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!o||!i)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=o;const s=function(e){const t=Fe(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=yield 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&&(yield it(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts})),e}catch(e){throw yield st(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem authenticating right now.",messageParams:{}}).catch((()=>{})),e}}))}(t,n,r,i)}))}function lt(e,t){return o(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",o=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=Fe(i),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},a=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==a.status)throw new Error(`RefreshToken: Status ${a.status} from ${e}/token`);const u=yield a.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}))}const{toString:dt}={};const ft={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function pt(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,o){const i=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 ft;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,dt.call(o).slice(8,-1)),c=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==c?void 0:c[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:ft),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o);return i},parse(e,n){const r=[];return JSON.parse(e,(function(e,o){const i=null==o?void 0:o.$t;if(i){const e=t[i];o=e?e.revive(o,n,t):o}let s=r[r.length-1];if(s&&s[0]===o){o={...o};for(const e of s[1])delete o[e];for(const[e,t]of Object.entries(s[2]))o[e]=t;r.pop()}if(void 0===o||"$"===e[0]&&"$t"!==e){let t,n;s=r[r.length-1],s&&s[0]===this?(t=s[1],n=s[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=o):n[e]=void 0}return o}))}}}const ht={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 vt={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 yt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var bt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},mt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},gt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const _t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var wt=["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=_t[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function St(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=It[e[n]];return t}(Fe(e))}function kt(e){return Me(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+=xt[e[n]];return t}(e))}const xt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},It={};for(const e of Object.keys(xt))It[xt[e]]=e;var Et={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:St(e)}),revive:({v:e})=>{const t=kt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ot{constructor(e,t){this.buf=e,this.type=t}}function Tt(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 Ct(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var At={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ot,replace:e=>({$t:"Blob",v:Fe(e instanceof Ot?e.buf:Ct(Tt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Me(t);return void 0!==typeof Blob?new Blob([n]):new Ot(n.buffer,e)}}};const jt={...vt,...yt,...bt,...mt,...gt,...wt,...Et,...At};function Pt(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 Ut={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Dt="bigint"==typeof BigInt(0);class $t{constructor(e){this.v=e}toString(){return this.v}}const Rt=Object.assign(Object.assign({},Ut),Dt?{}:{bigint:{test:e=>e instanceof $t,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new $t(e)}}),Lt=pt(jt,Rt),Nt=function(...e){const t=pt(jt,ht,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),o=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[o,r]},async parse(e,n){let r=0;const o=[],i=await Pt(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 Pt(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)}}}(Rt);class Wt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Bt(e,t,n){const o=[];for(let i of n){const{table:n,muts:s}=i,c=e.tables.find((e=>e.name===n));if(!c)throw new Error(`Internal error: table ${n} not found in DBCore schema`);const{primaryKey:a}=c;let u=i;s.forEach(((e,n)=>{const o=!a.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach(((e,s)=>{if(Array.isArray(e)){u===i&&(u=Mt(i,o));const t=u.muts[n],c=JSON.stringify(e);t.keys[s]=c,o&&r.default.setByKeyPath(t.values[s],a.keyPath,c)}else if("#"===e[0]){u===i&&(u=Mt(i,o));const c=u.muts[n];if(!t.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const l=`${e}:${t.userId}`;c.keys[s]=l,o&&r.default.setByKeyPath(c.values[s],a.keyPath,l)}}))})),o.push(u)}return o}function Mt(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}function Ft(e,t,n,r,i,s,c,a){return o(this,void 0,void 0,(function*(){const u={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},l=yield function(e){var t,n;return o(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:c,claims:a}=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==c?void 0:c.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield lt(e.cloud.options.databaseUrl,r);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}))}(r);l&&(u.Authorization=`Bearer ${l}`);const d={v:2,dbID:null==t?void 0:t.remoteDbId,clientIdentity:c,schema:s||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:Bt(r.dx.core.schema,a,e)};console.debug("Sync request",d),r.syncStateChangedEvent.next({phase:"pushing"});const f=yield fetch(`${i}/sync`,{method:"post",headers:u,body:Lt.stringify(d)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!f.ok)throw new Wt(f);if("application/x-bison"===f.headers.get("content-type"))return Nt.fromBinary(yield f.blob());{const e=yield f.text();return Lt.parse(e)}}))}function Ht(e){if(null==e?void 0:e.cancelled)throw new r.default.AbortError("Operation was cancelled")}let Kt=navigator.onLine;function qt(e,t,n,r){return o(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}))}function zt(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function Vt(t,n,i){return o(this,void 0,void 0,(function*(){const o=yield t.bulkGet(n),s=[],c=[];n.forEach(((n,a)=>{const u=o[a];if(u){for(const[o,s]of Object.entries(i[a]))if(o===t.schema.primKey.keyPath){if(0!==e.cmp(s,n))throw new Error("Cannot change primary key")}else r.default.setByKeyPath(u,o,s);s.push(n),c.push(u)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(c,s):t.bulkPut(c)}))}function Gt(e,t){return o(this,void 0,void 0,(function*(){console.debug("Applying server changes",e,r.default.currentTransaction);for(const{table:n,muts:o}of e){const e=t.table(n);if(!e)continue;const{primaryKey:i}=e.core.schema,s=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+t.cloud.currentUserId)?e.substr(0,e.length-t.cloud.currentUserId.length-1):e;default:return e}};for(const t of o){const n=t.keys.map(s);switch(t.type){case"insert":i.outbound?yield e.bulkAdd(t.values,n):(n.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),yield e.bulkAdd(t.values));break;case"upsert":i.outbound?yield e.bulkPut(t.values,n):(n.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),yield e.bulkPut(t.values));break;case"modify":1===n.length?yield e.update(n[0],t.changeSpec):yield e.where(":id").anyOf(n).modify(t.changeSpec);break;case"update":yield Vt(e,n,t.changeSpecs);break;case"delete":yield e.bulkDelete(n)}}}}))}self.addEventListener("online",(()=>Kt=!0)),self.addEventListener("offline",(()=>Kt=!1));function Jt(e,t,n,r){return Yt.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((i=>o(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):(console.debug("Error from _sync",{isOnline:Kt,syncOptions:r,error:i}),Kt&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise((e=>setTimeout(e,500))),yield Jt(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:Kt?"error":"offline",error:i}),Promise.reject(i)))}))))}function Yt(e,t,n,{isInitialSync:r,cancelToken:s,justCheckIfNeeded:c,purpose:a}={isInitialSync:!1}){var u;return o(this,void 0,void 0,(function*(){if(c||console.debug("SYNC STARTED",{isInitialSync:r,purpose:a}),!(null===(u=e.cloud.options)||void 0===u?void 0:u.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:l}=t,d=yield e.getCurrentUser(),f=d.isLoggedIn?Ke(e):[],p=f.map((t=>e.table(qe(t.name)))),h=yield e.getPersistedSyncState(),v=!r&&d.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Ke(e).filter((e=>!n.includes(e.name)))}(e,h):[];Ht(s);const y=v.length>0;if(y){if(c)return!0;yield e.transaction("rw",v,(e=>o(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return o(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==i.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==i.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==i.userId||(e.owner=t.userId),e.realmId&&e.realmId!==i.userId||(e.realmId=t.userId))})))}))}(v,d,null==h?void 0:h.realms)})))),Ht(s)}const[b,m,g]=yield e.transaction("r",e.tables,(()=>o(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield Je(p);if(Ht(s),y){const e=[...(null==h?void 0:h.realms)||[],...(null==h?void 0:h.inviteRealms)||[]],c=yield function(e,t,n,r){return o(this,void 0,void 0,(function*(){const i=`upload-${Ye(8)}`;if(t.isLoggedIn&&e.length>0){const s=new Set(r||[]);return(yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const o=n[e.name],c=(null==o?void 0:o.generatedGlobalId)?e.filter((e=>{const t=r(e);return!s.has(e.realmId||"")&&tt(t)})):e.filter((e=>{return r(e),!s.has(e.realmId||"")&&(t=r(e),!(n=null==o?void 0:o.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=yield c.toArray();if(a.length>0){const n={type:"upsert",values:a,keys:a.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(v,d,n,e);return Ht(s),i=i.concat(c),[i,t,r]}return[i,t,r]})))),_=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(c)return console.debug("Sync is needed:",_),_;if("push"===a&&!_)return!1;const w=zt(b,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||et(16);Ht(s);const k=yield Ft(b,m,g,e,l,n,S,d);console.debug("Sync response",k);const x=yield e.transaction("rw",e.tables,(t=>o(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))k.schema[e]&&(n[e]=k.schema[e]);yield e.$syncState.put(n,"schema");const r=yield Je(p,0,{since:w});for(const t of p){const n=ze(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(w[n]){const r=w[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}zt(r,w),yield qt(e,n,w,k.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return o(this,void 0,void 0,(function*(){const r=new Set,o=new Set,i=n?n.realms:[],s=n?n.inviteRealms:[],c=new Set(t.realms),a=new Set(t.realms.concat(t.inviteRealms));for(const e of i)c.has(e)||(o.add(e),a.has(e)||r.add(e));for(const e of s.concat(i))a.has(e)||r.add(e);if(r.size>0||o.size>0){const t=Ke(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:o;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}}))}(e,k,i);const s=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};s.syncedTables=f.map((e=>e.name)).concat(v.map((e=>e.name))),s.latestRevisions=w,s.remoteDbId=k.dbId,s.initiallySynced=!0,s.realms=k.realms,s.inviteRealms=k.inviteRealms,s.serverRevision=k.serverRevision,s.timestamp=new Date,delete s.error;const c=Qt(k.changes,r);return yield Gt(c,e),e.$syncState.put(s,"syncState"),0===r.length}))));return x?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),yield Yt(e,t,n,{isInitialSync:r,cancelToken:s}))}))}function Qt(e,t){const n={};ot(n,e);const r={};return ot(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,c]of Object.entries(s))switch(c.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(c.mod))Xe(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(c.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=et(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 Zt(e){const n=[],i=new t.BehaviorSubject(!0),s=new t.BehaviorSubject(null);let c=!1,a=0,u=[0,0,0,0,0,0,0,0,0,Date.now()];return s.subscribe((()=>o(this,void 0,void 0,(function*(){if(!c&&n.length>0){c=!0,u.shift(),u.push(Date.now()),i.next(!1);try{yield function(){var t,i,s;return o(this,void 0,void 0,(function*(){for(;n.length>0;){const c=n.shift();try{yield e.cloud.syncState.pipe(je((({phase:e})=>"in-sync"===e||"error"===e)),Oe(1)).toPromise(),console.debug("processing msg",c);const n=e.cloud.persistedSyncState.value;if(!c)continue;switch(c.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=e.cloud.currentUser.value,u=yield lt(e.cloud.options.databaseUrl,a);yield e.table("$logins").update(a.userId,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration});break;case"realm-added":case"realm-accepted":case"realms-changed":Be(e,"pull");break;case"realm-removed":(null===(t=null==n?void 0:n.realms)||void 0===t?void 0:t.includes(c.realm))||null===(i=null==n?void 0:n.inviteRealms)||void 0===i||i.includes(c.realm),Be(e,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(s=e.cloud.syncState.value)||void 0===s?void 0:s.phase)){Be(e,"pull");break}yield e.transaction("rw",e.dx.tables,(t=>o(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,o,i]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!n||!i)return void console.debug("required vars not present",{syncState:o,schema:n,currentUser:i});if(c.baseRev!==o.serverRevision)return console.debug(`baseRev (${c.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`),void("string"!=typeof c.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||Be(e,"pull"));const s=yield r.default.waitFor(He(o));if(console.debug("ourRealmSetHash",s),s!==c.realmSetHash)return console.debug("not same realmSetHash",c.realmSetHash),void Be(e,"pull");let a=[];if(i.isLoggedIn){const t=Ke(e).map((t=>e.table(qe(t.name))));a=yield Je(t),console.debug("msg queue: client changes",a)}if(c.changes.length>0){const t=Qt(c.changes,a);console.debug("applying filtered server changes",t),yield Gt(t,e)}o.latestRevisions=zt(a,o.latestRevisions),o.serverRevision=c.newRev,console.debug("Updating baseRefs",o.latestRevisions),yield qt(e,n,o.latestRevisions,c.newRev),console.debug("Updating syncState",o),yield e.$syncState.put(o,"syncState")})))),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}))}()}finally{u[u.length-1]-u[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,yield new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,yield new Promise((e=>setTimeout(e,1e4))))),c=!1,i.next(!0)}}})))),{enqueue:function(e){n.push(e),s.next(null)},readyToServe:i}}const Xt=new WeakMap,en={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let tn=0;function nn(e){"vip"in e&&(e=e.vip);let n=Xt.get(e.cloud);if(!n){const r=new t.Subject;let o=new u(`syncstatechanged-${e.name}`);r.id=++tn;let s=!1;n={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return s},localSyncEvent:r,get syncStateChangedEvent(){return o},dx:e};const c={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||i)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema"),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){o=new u(`syncstatechanged-${e.name}`)}};Object.assign(n,c),n.messageConsumer=Zt(n),Xt.set(e.cloud,n)}return n}const rn=new WeakMap;class on{constructor(e,t){rn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new on(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return o(this,void 0,void 0,(function*(){rn.get(this).table("$logins").put(this)}))}}function sn(e,t){return o(this,void 0,void 0,(function*(){if((yield e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new on(e,{claims:{},lastLogin:new Date(0)});yield ut(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function({public_key:n,hints:r}){var i;return o(this,void 0,void 0,(function*(){let o;const s=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!s)throw new Error("No database URL given.");o="demo"===(null==r?void 0:r.grant_type)?{demo_user:yield ct(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:yield ct(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const c=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==c.status){const e=yield c.text();throw yield st(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Wt(c,e)}const a=yield c.json();if("tokens"===a.type)return a;if("otp"===o.grant_type){if("otp-sent"!==a.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield at(t,o.email);o.otp=e||"",o.otp_id=a.otp_id;let n=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=yield n.text();o.otp=yield at(t,o.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=yield n.text();throw yield st(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Wt(n,e)}return yield n.json()}throw new Error(`Unexpected response from ${s}/token`)}))}}(e),e.cloud.userInteraction,t),yield n.save(),yield function(e,t){return o(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>o(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,yield t.save(),console.debug("Saved new user",t.email)})))),yield 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),Be(e,"pull")}))}const cn="undefined"!=typeof InstallTrigger,an="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),un=an?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,ln=an&&un<=605||cn;const dn="undefined"!=typeof self&&"clients"in self&&!self.document;function fn(){throw new r.default.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:pn}={};function hn(e){return pn.call(e).slice(8,-1)}function vn(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 yn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let bn=0;function mn(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();bn>=o?++bn:bn=o,r[0]=bn/1099511627776,r[1]=bn/4294967296,r[2]=bn/16777216,r[3]=bn/65536,r[4]=bn/256,r[5]=bn;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+St(new Uint8Array(n.buffer))+(t||"")}function gn(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:t=>Object.assign(Object.assign({},t),{table:n=>{const o=t.table(n);return Object.assign(Object.assign({},o),{mutate:t=>{var i,s;if(t.trans.disableChangeTracking)return o.mutate(t);if("add"===t.type||"put"===t.type){const c=null===(i=e.cloud.schema)||void 0===i?void 0:i[n];if(null==c?void 0:c.generatedGlobalId){if((null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!e.initiallySynced){const e=vn(o.schema.primaryKey,t);return o.getMany({keys:e,trans:t.trans,cache:"immutable"}).then((n=>{if(n.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(t)}))}return function(t,i){let s=null;const c=vn(o.schema.primaryKey,t);return c.forEach(((a,u)=>{if(void 0===a){const n=t.values[u].realmId||e.cloud.currentUserId,a=n.substr(n.length-3);c[u]=mn(i,a),o.schema.primaryKey.outbound||(s||(s=t.values.slice()),s[u]=r.default.deepClone(s[u]),r.default.setByKeyPath(s[u],o.schema.primaryKey.keyPath,c[u]))}else if("string"!=typeof a||!a.startsWith(i)&&!a.startsWith("#"+i))throw new r.default.ConstraintError(`The ID "${a}" is not valid for table "${n}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate(Object.assign(Object.assign({},t),{keys:c,values:s||t.values}))}(t,c.idPrefix)}if(null==c?void 0:c.markedForSync){vn(o.schema.primaryKey,t).forEach(((e,t)=>{if(!tt(e)){const t=Array.isArray(e)?e.map(hn).join(","):hn(e);throw new r.default.ConstraintError(`Invalid primary key type ${t} for table ${n}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(t)}})}})}}let _n=0;function wn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function Sn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const kn=new t.BehaviorSubject(new Set);function xn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){fn()}return Object.assign(Object.assign({},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=>qe(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=Ye(16),i.currentUser=e.value,kn.value.add(i),kn.next(kn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),kn.value.delete(i),kn.next(kn.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),We(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 r=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},r),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),r.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},r),{mutate:e=>r.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e))))}):r;const{schema:i}=r,s=o.get(e);return function(e){const t="$lock"+ ++_n;return Object.assign(Object.assign({},e),{count:wn(e.count,t),get:wn(e.get,t),getMany:wn(e.getMany,t),openCursor:wn(e.openCursor,t),query:wn(e.query,t),mutate:Sn(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,a;const u=n.trans;return u.txid?u.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(a=u.currentUser)||void 0===a?void 0:a.isLoggedIn)?"deleteRange"===n.type?r.query({query:{range:n.range,index:i.primaryKey},trans:n.trans,values:!1}).then((e=>c({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):c(n):r.mutate(n):r.mutate(n)}}));function c(e){const t=e.trans;t.mutationsAdded=!0;const{txid:n,currentUser:{userId:o}}=t,{type:i}=e;return r.mutate(e).then((r=>{const{numFailures:c,failures:a}=r;let u="delete"===i?e.keys:r.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];c&&(u=u.filter(((e,t)=>!a[t])),l=l.filter(((e,t)=>!a[t])),d=d.filter(((e,t)=>!a[t])));const f=Date.now(),p="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:n,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:n,userId:o}:e.changeSpecs?{type:"update",ts:f,keys:u,changeSpecs:d,txid:n,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:n,userId:o};return u.length>0||"criteria"in e&&e.criteria?s.mutate({type:"add",trans:t,values:[p]}).then((()=>r)):r}))}}})}}}function In(e,t){return function(n,r){const o=Object.assign(Object.assign({},en),n),i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(yn.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 En=new t.BehaviorSubject(!0),On=new t.BehaviorSubject(!0);var Tn,Cn;En.pipe(De((e=>e?t.of(!0):t.of(!1).pipe(Ce(2e4)))),(void 0===Cn&&(Cn=K),Tn=null!=Tn?Tn:Ae,d((function(e,t){var n,r=!0;e.subscribe(new re(t,(function(e){var o=Cn(e);!r&&Tn(n,o)||(r=!1,n=o,t.next(e))})))})))).subscribe(On);const An="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),jn=An.pipe(je((()=>"hidden"===document.visibilityState))),Pn=An.pipe(je((()=>"visible"===document.visibilityState))),Un="undefined"!=typeof window?t.merge(Pn,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),jn,Un).pipe(we((()=>"visible"===document.visibilityState)),$e((e=>{En.value!==e&&En.next(e)})),De((e=>e?t.of(0).pipe(Ce(16e4),$e((()=>En.next(!1)))):t.of(0)))).subscribe((()=>{}));class Dn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class $n extends t.Observable{constructor(e,t,n,r,o,i,s,c){super((a=>new Ln(e,t,n,r,s,c,a,o,i)))}}let Rn=0;class Ln extends t.Subscription{constructor(e,t,n,r,o,i,s,c,a){super((()=>this.teardown())),this.id=++Rn,this.reconnecting=!1,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=c,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(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return o(this,void 0,void 0,(function*(){if(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 Dn);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>o(this,void 0,void 0,(function*(){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=Lt.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{let e=!1;yield new Promise(((t,r)=>{n.onopen=n=>{console.debug("dexie-cloud WebSocket onopen"),e=!0,t(null)},n.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),r(e)}}})),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(Lt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}function Nn(e){return o(this,void 0,void 0,(function*(){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),yield(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),yield Un.pipe(Oe(1)).toPromise(),console.debug("someone did something!")}))}function Wn(e){var t;return o(this,void 0,void 0,(function*(){return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Jt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const Bn=Ye(16);function Mn(n,r,i,s,{awaitRemoteJob:c}={}){return o(this,void 0,void 0,(function*(){const a=n.table(i);if(yield function s(){return o(this,void 0,void 0,(function*(){if(yield n.transaction("rw!",i,(()=>o(this,void 0,void 0,(function*(){const e=yield a.get(r);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${r} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),yield a.put({nodeId:Bn,started:new Date,heartbeat:new Date},r),!0):(yield a.add({nodeId:Bn,started:new Date,heartbeat:new Date},r),!0)})))))return!0;if(c)try{const n=t.from(e.liveQuery((()=>a.get(r)))).pipe(function(e,t){var n=fe(e)?{first:e}:"number"==typeof e?{each:e}:e,r=n.first,o=n.each,i=n.with,s=void 0===i?Le:i,c=n.scheduler,a=void 0===c?null!=t?t:ue:c,u=n.meta,l=void 0===u?null:u;if(null==r&&null==o)throw new TypeError("No timeout provided.");return d((function(e,t){var n,i,c=null,u=0,d=function(e){i=he(t,a,(function(){try{n.unsubscribe(),te(s({meta:l,lastValue:c,seen:u})).subscribe(t)}catch(e){t.error(e)}}),e)};n=e.subscribe(new re(t,(function(e){null==i||i.unsubscribe(),u++,t.next(c=e),o>0&&d(o)}),void 0,void 0,(function(){(null==i?void 0:i.closed)||null==i||i.unsubscribe(),c=null}))),d(null!=r?"number"==typeof r?r:+r-a.now():o)}))}(6e4),je((e=>!e)));return yield n.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return yield s()}return!1}))}()){const e=setInterval((()=>{a.update(r,(e=>{e.nodeId===Bn&&(e.heartbeat=new Date)}))}),1e3);try{return yield s()}finally{clearInterval(e),yield n.transaction("rw!",i,(()=>o(this,void 0,void 0,(function*(){const e=yield a.get(r);e&&e.nodeId===Bn&&(yield a.delete(r))}))))}}}))}const Fn=new WeakMap;function Hn(e,t,n,r){const i=Fn.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),i.promise;{let o=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(o=!0)}));return i.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!o)return Hn(e,t,n,r)}))}}const s=function(){return o(this,void 0,void 0,(function*(){try{if(e.cloud.isServiceWorkerDB)yield Jt(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw Ze(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield Mn(e,"currentSyncWorker","$jobs",(()=>Jt(e,t,n,r)))}Fn.delete(e),console.debug("Done sync")}catch(t){throw Fn.delete(e),console.error("Failed to sync client changes",t),t}}))}();return Fn.set(e,{promise:s,pull:"push"!==(null==r?void 0:r.purpose)}),s}function Kn(e,t,n){let r=null,o={cancelled:!1};function i(r,c=1){setTimeout((()=>{Hn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():c<3&&setTimeout((()=>i(r,c+1)),6e4*[0,5,15][c])}))}),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 qn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var zn,Vn,Gn,Jn,Yn={},Qn=[],Zn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Xn(e,t){for(var n in t)e[n]=t[n];return e}function er(e){var t=e.parentNode;t&&t.removeChild(e)}function tr(e,t,n){var r,o,i,s=arguments,c={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:c[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(c.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===c[i]&&(c[i]=e.defaultProps[i]);return nr(e,c,r,o,null)}function nr(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++zn.__v:o};return null!=zn.vnode&&zn.vnode(i),i}function rr(e){return e.children}function or(e,t){this.props=e,this.context=t}function ir(e,t){if(null==t)return e.__?ir(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?ir(e):null}function sr(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return sr(e)}}function cr(e){(!e.__d&&(e.__d=!0)&&Vn.push(e)&&!ar.__r++||Jn!==zn.debounceRendering)&&((Jn=zn.debounceRendering)||Gn)(ar)}function ar(){for(var e;ar.__r=Vn.length;)e=Vn.sort((function(e,t){return e.__v.__b-t.__v.__b})),Vn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=Xn({},o)).__v=o.__v+1,yr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?ir(o):i,o.__h),br(n,o),o.__e!=i&&sr(o)))}))}function ur(e,t,n,r,o,i,s,c,a,u){var l,d,f,p,h,v,y,b=r&&r.__k||Qn,m=b.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(p=n.__k[l]=null==(p=t[l])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?nr(null,p,null,null,p):Array.isArray(p)?nr(rr,{children:p},null,null,null):p.__b>0?nr(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=b[l])||f&&p.key==f.key&&p.type===f.type)b[l]=void 0;else for(d=0;d<m;d++){if((f=b[d])&&p.key==f.key&&p.type===f.type){b[d]=void 0;break}f=null}yr(e,p,f=f||Yn,o,i,s,c,a,u),h=p.__e,(d=p.ref)&&f.ref!=d&&(y||(y=[]),f.ref&&y.push(f.ref,null,p),y.push(d,p.__c||h,p)),null!=h?(null==v&&(v=h),"function"==typeof p.type&&null!=p.__k&&p.__k===f.__k?p.__d=a=lr(p,a,e):a=dr(e,p,f,b,h,a),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=a):e.value=""):a&&f.__e==a&&a.parentNode!=e&&(a=ir(f))}for(n.__e=v,l=m;l--;)null!=b[l]&&("function"==typeof n.type&&null!=b[l].__e&&b[l].__e==n.__d&&(n.__d=ir(r,l+1)),_r(b[l],b[l]));if(y)for(l=0;l<y.length;l++)gr(y[l],y[++l],y[++l])}function lr(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?lr(o,t,n):dr(n,o,o,e.__k,o.__e,t));return t}function dr(e,t,n,r,o,i){var s,c,a;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(c=i,a=0;(c=c.nextSibling)&&a<r.length;a+=2)if(c==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function fr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Zn.test(t)?n:n+"px"}function pr(e,t,n,r,o){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||fr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||fr(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?vr:hr,i):e.removeEventListener(t,i?vr:hr,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 hr(e){this.l[e.type+!1](zn.event?zn.event(e):e)}function vr(e){this.l[e.type+!0](zn.event?zn.event(e):e)}function yr(e,t,n,r,o,i,s,c,a){var u,l,d,f,p,h,v,y,b,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(a=n.__h,c=t.__e=n.__e,t.__h=null,i=[c]),(u=zn.__b)&&u(t);try{e:if("function"==typeof _){if(y=t.props,b=(u=_.contextType)&&r[u.__c],m=u?b?b.props.value:u.__:r,n.__c?v=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(y,m):(t.__c=l=new or(y,m),l.constructor=_,l.render=wr),b&&b.sub(l),l.props=y,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=Xn({},l.__s)),Xn(l.__s,_.getDerivedStateFromProps(y,l.__s))),f=l.props,p=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&y!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(y,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(y,l.__s,m)||t.__v===n.__v){l.props=y,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(y,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,p,h)}))}l.context=m,l.props=y,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=Xn(Xn({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(h=l.getSnapshotBeforeUpdate(f,p)),g=null!=u&&u.type===rr&&null==u.key?u.props.children:u,ur(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,c,a),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),v&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=mr(n.__e,t,n,r,o,i,s,a);(u=zn.diffed)&&u(t)}catch(e){t.__v=null,(a||null!=i)&&(t.__e=c,t.__h=!!a,i[i.indexOf(c)]=null),zn.__e(e,t,n)}}function br(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 mr(e,t,n,r,o,i,s,c){var a,u,l,d,f=n.props,p=t.props,h=t.type,v=0;if("svg"===h&&(o=!0),null!=i)for(;v<i.length;v++)if((a=i[v])&&(a===e||(h?a.localName==h:3==a.nodeType))){e=a,i[v]=null;break}if(null==e){if(null===h)return document.createTextNode(p);e=o?document.createElementNS("http://www.w3.org/2000/svg",h):document.createElement(h,p.is&&p),i=null,c=!1}if(null===h)f===p||c&&e.data===p||(e.data=p);else{if(i=i&&Qn.slice.call(e.childNodes),u=(f=n.props||Yn).dangerouslySetInnerHTML,l=p.dangerouslySetInnerHTML,!c){if(null!=i)for(f={},d=0;d<e.attributes.length;d++)f[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||pr(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]||pr(e,i,t[i],n[i],r)}(e,p,f,o,c),l)t.__k=[];else if(v=t.props.children,ur(e,Array.isArray(v)?v:[v],t,n,r,o&&"foreignObject"!==h,i,s,e.firstChild,c),null!=i)for(v=i.length;v--;)null!=i[v]&&er(i[v]);c||("value"in p&&void 0!==(v=p.value)&&(v!==e.value||"progress"===h&&!v)&&pr(e,"value",v,f.value,!1),"checked"in p&&void 0!==(v=p.checked)&&v!==e.checked&&pr(e,"checked",v,f.checked,!1))}return e}function gr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){zn.__e(e,n)}}function _r(e,t,n){var r,o,i;if(zn.unmount&&zn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||gr(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){zn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&_r(r[i],t,n);null!=o&&er(o)}function wr(e,t,n){return this.constructor(e,n)}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},or.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Xn({},this.state),"function"==typeof e&&(e=e(Xn({},n),this.props)),e&&Xn(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),cr(this))},or.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),cr(this))},or.prototype.render=rr,Vn=[],Gn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ar.__r=0;const Sr={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function kr({children:e}){return tr("div",null,tr("div",{style:Sr.Darken}),tr("div",{style:Sr.DialogOuter},tr("div",{style:Sr.DialogInner},e)))}var xr,Ir,Er,Or=0,Tr=[],Cr=zn.__b,Ar=zn.__r,jr=zn.diffed,Pr=zn.__c,Ur=zn.unmount;function Dr(e,t){zn.__h&&zn.__h(Ir,e,Or||t),Or=0;var n=Ir.__H||(Ir.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function $r(e){return Or=1,function(e,t,n){var r=Dr(xr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Fr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Ir),r.__}(Fr,e)}function Rr(e){return Or=5,function(e,t){var n=Dr(xr++,7);return Mr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Lr(){Tr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Wr),e.__H.__h.forEach(Br),e.__H.__h=[]}catch(t){e.__H.__h=[],zn.__e(t,e.__v)}})),Tr=[]}zn.__b=function(e){Ir=null,Cr&&Cr(e)},zn.__r=function(e){Ar&&Ar(e),xr=0;var t=(Ir=e.__c).__H;t&&(t.__h.forEach(Wr),t.__h.forEach(Br),t.__h=[])},zn.diffed=function(e){jr&&jr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Tr.push(t)&&Er===zn.requestAnimationFrame||((Er=zn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Nr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Nr&&(t=requestAnimationFrame(n))})(Lr)),Ir=void 0},zn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Wr),e.__h=e.__h.filter((function(e){return!e.__||Br(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],zn.__e(n,e.__v)}})),Pr&&Pr(e,t)},zn.unmount=function(e){Ur&&Ur(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Wr)}catch(e){zn.__e(e,t.__v)}};var Nr="function"==typeof requestAnimationFrame;function Wr(e){var t=Ir;"function"==typeof e.__c&&e.__c(),Ir=t}function Br(e){var t=Ir;e.__c=e.__(),Ir=t}function Mr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Fr(e,t){return"function"==typeof t?t(e):t}function Hr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=$r({}),c=Rr();return function(e,t){var n=Dr(xr++,4);!zn.__s&&Mr(n.__H,t)&&(n.__=e,n.__H=t,Ir.__h.push(n))}((()=>{var e;return null===(e=c.current)||void 0===e?void 0:e.focus()}),[]),tr(kr,null,tr(rr,null,tr("h3",{style:Sr.WindowHeader},e),t.map((e=>tr("p",{style:Sr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),tr("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>tr("label",{style:Sr.Label},n?`${n}: `:"",tr("input",{ref:0===o?c:void 0,type:t,name:e,autoComplete:"on",style:Sr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s(Object.assign(Object.assign({},i),{[e]:Kr(t,null===(r=n.target)||void 0===r?void 0:r.value)}))}})))))),tr("div",{style:Sr.ButtonsDiv},tr("button",{type:"submit",style:Sr.Button,onClick:()=>o(i)},"Submit"),tr("button",{style:Sr.Button,onClick:r},"Cancel")))}function Kr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class qr extends or{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?tr(Hr,Object.assign({},t)):null}}function 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=[],yr(t,e=(!r&&n||t).__k=tr(rr,null,[e]),o||Yn,Yn,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?Qn.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),br(i,e)}(tr(qr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function Vr(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}function Gr(e,n){let r=n,o=t.from(e).pipe(t.map((e=>r=e)),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const i=new t.Observable((e=>{let t=!1;const n=o.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return i.getValue=()=>r,i}const Jr=Vr((t=>Gr(e.liveQuery((()=>t.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),Yr=Vr((e=>new t.BehaviorSubject(i))),Qr=Vr((t=>Gr(Yr(t._novip).pipe(De((n=>e.liveQuery((()=>t.transaction("r","realms","members",(()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}})));function Zr(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,o=t[e];t[e]=[...new Set([...o,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const Xr=Vr((e=>function(e,n){let r;const o=e.pipe(t.map((e=>r=n(e))));return o.getValue=()=>void 0!==r?r:r=n(e.getValue()),o}(Gr(t.combineLatest([Qr(e._novip),Jr(e._novip)]).pipe(we((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:i.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const o=t.map((t=>{const o=e.filter((e=>e.realmId===t.realmId)),i=o.map((e=>e.permissions)).filter((e=>e)),s=Ge(o.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:Zr(...i,...s)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return o}))));class eo{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const to=Vr((n=>{const r=Yr(n._novip).pipe(t.switchMap((t=>e.liveQuery((()=>n.members.where({email:t.email||""}).toArray()))))),o=Xr(n._novip),i=Qr(n._novip);return Gr(t.combineLatest([r,i,o]).pipe(t.map((([e,t,n])=>{const r=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:n[t.realmId]})}),o=e.reduce(r,{}),i=t.selfMembers.reduce(r,o);return Object.values(i).filter((e=>!e.accepted))}))),[])})),no={nameSuffix:!0};function ro(n){const s=n.name,c=Yr(n),a=[];let u=!1,l=null;n.on("ready",(n=>o(this,void 0,void 0,(function*(){try{yield function(n){var i,s,p,h,v,y,b;return o(this,void 0,void 0,(function*(){d=!1;const m=nn(n);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=m.cloud.options)||void 0===i?void 0:i.customLoginGui)||a.push(zr(n))),m.cloud.isServiceWorkerDB||a.push(function(e){let n=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(De((e=>{const r=n;n=e;const o=t.of(e);switch(e){case"disconnected":return En.value?o.pipe(xe(500)):o;case"connecting":return"not-started"===r||"error"===r?o:o.pipe(xe(4e3));default:return o}})));return t.combineLatest([r,e.syncStateChangedEvent.pipe(Ue({phase:"initial"})),On]).pipe(we((([t,n,r])=>{let{phase:o,error:i,progress:s}=n,c=t;return"error"===o&&(c="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(c="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(c="connecting"),r||(c="disconnected"),{phase:o,error:i,progress:s,status:Kt?c:"offline"}})))}(m).subscribe(n.cloud.syncState)),m.tables.every((e=>e.core))||fn();const g="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],_=yield m.transaction("rw",m.$syncState,(()=>o(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=m.cloud,[o,i,s]=yield Promise.all([m.getOptions(),m.getSchema(),m.getPersistedSyncState()]);if(u){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");yield m.$syncState.put(n,"options")}}else m.cloud.options=o||null;if((null===(e=m.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&g.length>0&&!ln?(console.debug("Dexie Cloud Addon: Using service worker"),m.cloud.usingServiceWorker=!0):((null===(t=m.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!m.cloud.isServiceWorkerDB&&console.debug("dexie-cloud-addon: Not using service worker.",0===g.length?"No SW registrations found.":"serviceWorker"in navigator&&ln?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),m.cloud.usingServiceWorker=!1),qn(r,m.cloud.options),qn(i,m.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield m.$syncState.put(e,"schema"),Object.assign(r,e)}}else m.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}))));_&&m.setInitiallySynced(!0),function(e){var t,n;for(const o of e.tables)if(null===(n=null===(t=e.cloud.schema)||void 0===t?void 0:t[o.name])||void 0===n?void 0:n.markedForSync){if(o.schema.primKey.auto)throw new r.default.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new r.default.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}}(m),(null===(s=m.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!_&&(yield function(e,t,n){return o(this,void 0,void 0,(function*(){console.debug("Performing initial sync"),yield Jt(e,t,n,{isInitialSync:!0}),console.debug("Done initial sync")}))}(m,m.cloud.options,m.cloud.schema),m.setInitiallySynced(!0)),f(),m.cloud.isServiceWorkerDB||(a.push(e.liveQuery((()=>m.getCurrentUser())).subscribe(c)),a.push(e.liveQuery((()=>m.getPersistedSyncState())).subscribe(m.cloud.persistedSyncState)),yield t.combineLatest([c.pipe(Pe(1),Oe(1)),m.cloud.persistedSyncState.pipe(Pe(1),Oe(1))]).toPromise()),(null===(p=m.cloud.options)||void 0===p?void 0:p.requireAuth)&&(yield sn(m)),l&&l.stop(),l=null,f(),m.cloud.usingServiceWorker&&(null===(h=m.cloud.options)||void 0===h?void 0:h.databaseUrl)?(We(m,"push").catch((()=>{})),function(e){var t;return o(this,void 0,void 0,(function*(){try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),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)}}))}(m).catch((()=>{}))):(null===(v=m.cloud.options)||void 0===v?void 0:v.databaseUrl)&&m.cloud.schema&&!m.cloud.isServiceWorkerDB&&(l=Kn(m,m.cloud.options,m.cloud.schema),l.start(),Be(m,"push")),f(),m.cloud.isServiceWorkerDB||a.push(t.fromEvent(self,"online").subscribe((()=>{console.debug("online!"),m.syncStateChangedEvent.next({phase:"not-in-sync"}),Be(m,"push")})),t.fromEvent(self,"offline").subscribe((()=>{console.debug("offline!"),m.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(y=m.cloud.options)||void 0===y?void 0:y.databaseUrl)||(null===(b=m.cloud.options)||void 0===b?void 0:b.disableWebSocket)||dn||a.push(function(e){var n;if(!(null===(n=e.cloud.options)||void 0===n?void 0:n.databaseUrl))throw new Error("No database URL to connect WebSocket to");const r=e.messageConsumer.readyToServe.pipe(je((e=>e)),De((()=>e.getPersistedSyncState())),je((e=>e&&e.serverRevision)),we((e=>({type:"ready",rev:e.serverRevision}))));return function n(){return e.cloud.persistedSyncState.pipe(je((e=>null==e?void 0:e.serverRevision)),Oe(1),De((t=>e.cloud.currentUser.pipe(we((e=>[e,t]))))),De((([e,t])=>On.pipe(we((n=>[n?e:null,t]))))),De((([e,t])=>o(this,void 0,void 0,(function*(){return[e,yield He(t)]})))),De((([n,o])=>n?new $n(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,o,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n.accessToken,n.accessTokenExpiration):t.from([]))),ve((r=>"TokenExpiredError"===(null==r?void 0:r.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),t.of(!0).pipe(De((()=>o(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield lt(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})))),De((()=>n())))):t.throwError(r))),ve((r=>(e.cloud.webSocketStatus.next("error"),t.from(Nn(r)).pipe(De((()=>n())))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(m))}))}(n)}catch(e){console.error(e)}}))),!0);let d=!1;function f(){if(d)throw new r.default.DatabaseClosedError}var p;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{a.forEach((e=>e.unsubscribe())),d=!0,l&&l.stop(),l=null,c.next(i)})),n.cloud={version:"4.0.0-beta.19",options:Object.assign({},no),schema:null,serverState:null,get currentUserId(){return c.value.userId||i.userId},currentUser:c,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return o(this,void 0,void 0,(function*(){const t=nn(n);yield t.cloud.sync(),yield sn(t,e)}))},invites:to(n),roles:Jr(n),configure(e){e=n.cloud.options=Object.assign(Object.assign({},n.cloud.options),e),u=!0,e.databaseUrl&&e.nameSuffix&&(n.name=`${s}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,nn(n).reconfigure()),qn(n.cloud.schema,n.cloud.options)},sync({wait:r,purpose:i}={wait:!0,purpose:"push"}){return o(this,void 0,void 0,(function*(){void 0===r&&(r=!0);const s=nn(n);if("pull"===i){const e=s.cloud.persistedSyncState.value;if(Be(s,i),r){const t=yield s.cloud.persistedSyncState.pipe(je((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))),Oe(1)).toPromise();if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield Wn(s)){const n=s.cloud.persistedSyncState.value;Be(s,i),r&&(console.debug("db.cloud.login() is waiting for sync completion..."),yield t.from(e.liveQuery((()=>o(this,void 0,void 0,(function*(){const e=yield Wn(s),t=yield s.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(je((e=>!e)),Oe(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}))},permissions:(e,t)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId:o}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const i=Xr(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new eo(i.permissions,n,o===e.cloud.currentUserId||r===e.cloud.currentUserId):new eo({},n,!r||r===e.cloud.currentUserId)},c=i.pipe(we(s));return c.getValue=()=>s(i.getValue()),c}(n._novip,e,t)},n.Version.prototype._parseStoresSpec=r.default.override(n.Version.prototype._parseStoresSpec,(e=>In(e,n))),n.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return mn(n.cloud.schema[this.name].idPrefix||"",t)},n.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},n.use(xn({currentUserObservable:n.cloud.currentUser,db:nn(n)})),n.use((p=nn(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,o,i,s;if(e.trans.disableChangeTracking)return n.mutate(e);const c=e.trans;if((null===(o=null===(r=p.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type))for(const t of e.values){t.owner||(t.owner=c.currentUser.userId),t.realmId||(t.realmId=c.currentUser.userId);const r=null===(s=(i=n.schema.primaryKey).extractKey)||void 0===s?void 0:s.call(i,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.changeSpecs,t.$ts=Date.now())}return n.mutate(e)}})}})})),n.use(gn(nn(n)))}ro.version="4.0.0-beta.19",r.default.Cloud=ro;const oo=new Map;function io(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const so=new Map;function co(e,t){let n=so.get(e+"/"+t);return n||(n=function e(t,n){var i;return o(this,void 0,void 0,(function*(){let o=oo.get(t);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const i=new r.default(t,{addons:[ro]});if(o=nn(i),o.cloud.isServiceWorkerDB=!0,i.on("versionchange",s),yield o.dx.open(),oo.get(t))return o.close(),yield e(t,n);oo.set(t,o)}if(null===(i=o.cloud.options)||void 0===i?void 0:i.databaseUrl)if(o.cloud.schema)try{console.debug("Dexie Cloud SW: Syncing"),yield Hn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(e){if(console.error("Dexie Cloud SW Error",e),s(),e.name!==r.default.errnames.NoSuchDatabase)throw e}else console.error("Dexie Cloud: No schema persisted");else console.error("Dexie Cloud: No databaseUrl configured");function s(){return o.dx.on.versionchange.unsubscribe(s),oo.get(o.name)===o&&oo.delete(o.name),console.debug(`Dexie Cloud SW: Closing Dexie instance for ${t}`),o.dx.close(),!1}}))}(e,t).then((()=>{so.delete(e+"/"+t)})).catch((n=>(so.delete(e+"/"+t),Promise.reject(n)))),so.set(e+"/"+t,n)),n}ln||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=io(e.tag);t&&e.waitUntil(co(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=io(e.tag);t&&e.waitUntil(co(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)=>co(t,e.data.purpose||"pull").catch((e=>o(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>console.error(e)))):n().catch((e=>console.error(e)))}})))}));
1
+ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs")):"function"==typeof define&&define.amd?define(["dexie","rxjs"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs)}(this,(function(e,t){"use strict";function n(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var r=n(e);function o(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,c)}a((r=r.apply(e,t||[])).next())}))}const i={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(i),Object.freeze(i.claims)}catch(e){}const s={},c=self.document&&navigator.serviceWorker;c&&c.ready.then((e=>s.registration=e)),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",(e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach((t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)}))}));class a{constructor(e){this.name=e}subscribe(e){if(!c)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 c.addEventListener("message",t),()=>c.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}))):s.registration&&(null===(t=s.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class u extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new a(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){console.debug("BroadcastedAndLocalEvent: onMessageEvent",e),n.next(e.data)}let i;return self.addEventListener(`lbc-${e}`,r),t instanceof a?i=t.subscribe((e=>n.next(e))):(console.debug("BroadcastedAndLocalEvent: bc.addEventListener()",e,"bc is a",t),t.addEventListener("message",o)),()=>{self.removeEventListener(`lbc-${e}`,r),t instanceof a?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){console.debug("BroadcastedAndLocalEvent: bc.postMessage()",Object.assign({},e),"bc is a",this.bc),this.bc.postMessage(e);const t=new CustomEvent(`lbc-${this.name}`,{detail:e});self.dispatchEvent(t)}}function l(e){return"function"==typeof e}function d(e){return function(t){if(function(e){return l(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}var f=function(e,t){return f=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},f(e,t)};function p(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function n(){this.constructor=e}f(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function h(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{a(r.next(e))}catch(e){i(e)}}function c(e){try{a(r.throw(e))}catch(e){i(e)}}function a(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,c)}a((r=r.apply(e,t||[])).next())}))}function v(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:c(0),throw:c(1),return:c(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function c(i){return function(c){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,c])}}}function y(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function b(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function m(e,t){for(var n=0,r=t.length,o=e.length;n<r;n++,o++)e[o]=t[n];return e}function g(e){return this instanceof g?(this.v=e,this):new g(e)}function _(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof g?Promise.resolve(e.value.v).then(a,u):l(i[0][2],e)}(o[e](t))}catch(e){l(i[0][3],e)}}function a(e){c("next",e)}function u(e){c("throw",e)}function l(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}}function w(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=y(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}var S=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function k(e){return l(null==e?void 0:e.then)}function x(e){var t=e((function(e){Error.call(e),e.stack=(new Error).stack}));return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var I=x((function(e){return function(t){e(this),this.message=t?t.length+" errors occurred during unsubscription:\n"+t.map((function(e,t){return t+1+") "+e.toString()})).join("\n "):"",this.name="UnsubscriptionError",this.errors=t}}));function E(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var O=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._teardowns=null}var t;return e.prototype.unsubscribe=function(){var e,t,n,r,o;if(!this.closed){this.closed=!0;var i=this._parentage;if(i)if(this._parentage=null,Array.isArray(i))try{for(var s=y(i),c=s.next();!c.done;c=s.next()){c.value.remove(this)}}catch(t){e={error:t}}finally{try{c&&!c.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var a=this.initialTeardown;if(l(a))try{a()}catch(e){o=e instanceof I?e.errors:[e]}var u=this._teardowns;if(u){this._teardowns=null;try{for(var d=y(u),f=d.next();!f.done;f=d.next()){var p=f.value;try{C(p)}catch(e){o=null!=o?o:[],e instanceof I?o=m(m([],b(o)),b(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{f&&!f.done&&(r=d.return)&&r.call(d)}finally{if(n)throw n.error}}}if(o)throw new I(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)C(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._teardowns=null!==(n=this._teardowns)&&void 0!==n?n:[]).push(t)}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&E(t,e)},e.prototype.remove=function(t){var n=this._teardowns;n&&E(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function T(e){return e instanceof O||e&&"closed"in e&&l(e.remove)&&l(e.add)&&l(e.unsubscribe)}function C(e){l(e)?e():e.unsubscribe()}var A={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},j={setTimeout:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=j.delegate;return((null==n?void 0:n.setTimeout)||setTimeout).apply(void 0,m([],b(e)))},clearTimeout:function(e){var t=j.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function P(e){j.setTimeout((function(){throw e}))}function U(){}var D=$("C",void 0,void 0);function $(e,t,n){return{kind:e,value:t,error:n}}function R(e){0}var L=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,T(t)&&t.add(n)):n.destination=F,n}return p(t,e),t.create=function(e,t,n){return new N(e,t,n)},t.prototype.next=function(e){this.isStopped?M(function(e){return $("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?M($("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?M(D,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(O),N=function(e){function t(t,n,r){var o,i=e.call(this)||this;if(l(t))o=t;else if(t){var s;o=t.next,n=t.error,r=t.complete,i&&A.useDeprecatedNextContext?(s=Object.create(t)).unsubscribe=function(){return i.unsubscribe()}:s=t,o=null==o?void 0:o.bind(s),n=null==n?void 0:n.bind(s),r=null==r?void 0:r.bind(s)}return i.destination={next:o?W(o):U,error:W(null!=n?n:B),complete:r?W(r):U},i}return p(t,e),t}(L);function W(e,t){return function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];try{e.apply(void 0,m([],b(t)))}catch(e){A.useDeprecatedSynchronousErrorHandling?R():P(e)}}}function B(e){throw e}function M(e,t){var n=A.onStoppedNotification;n&&j.setTimeout((function(){return n(e,t)}))}var F={closed:!0,next:U,error:B,complete:U},H="function"==typeof Symbol&&Symbol.observable||"@@observable";function K(e){return e}function q(e){return 0===e.length?K:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var V=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,o=this,i=(r=e)&&r instanceof L||function(e){return e&&l(e.next)&&l(e.error)&&l(e.complete)}(r)&&T(r)?e:new N(e,t,n);return function(){var e=o,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=z(t))((function(t,r){var o;o=n.subscribe((function(t){try{e(t)}catch(e){r(e),null==o||o.unsubscribe()}}),r,t)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[H]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return q(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=z(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 z(e){var t;return null!==(t=null!=e?e:A.Promise)&&void 0!==t?t:Promise}function G(e){return l(e[H])}function J(e){return Symbol.asyncIterator&&l(null==e?void 0:e[Symbol.asyncIterator])}function Y(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var Q="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function Z(e){return l(null==e?void 0:e[Q])}function X(e){return _(this,arguments,(function(){var t,n,r;return v(this,(function(o){switch(o.label){case 0:t=e.getReader(),o.label=1;case 1:o.trys.push([1,,9,10]),o.label=2;case 2:return[4,g(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,g(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,g(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function ee(e){return l(null==e?void 0:e.getReader)}function te(e){if(e instanceof V)return e;if(null!=e){if(G(e))return o=e,new V((function(e){var t=o[H]();if(l(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(S(e))return r=e,new V((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(k(e))return n=e,new V((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,P)}));if(J(e))return ne(e);if(Z(e))return t=e,new V((function(e){var n,r;try{for(var o=y(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()}));if(ee(e))return ne(X(e))}var t,n,r,o;throw Y(e)}function ne(e){return new V((function(t){(function(e,t){var n,r,o,i;return h(this,void 0,void 0,(function(){var s,c;return v(this,(function(a){switch(a.label){case 0:a.trys.push([0,5,6,11]),n=w(e),a.label=1;case 1:return[4,n.next()];case 2:if((r=a.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];a.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return c=a.sent(),o={error:c},[3,11];case 6:return a.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:a.sent(),a.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}var re=function(e){function t(t,n,r,o,i){var s=e.call(this,t)||this;return s.onFinalize=i,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return p(t,e),t.prototype.unsubscribe=function(){var t,n=this.closed;e.prototype.unsubscribe.call(this),!n&&(null===(t=this.onFinalize)||void 0===t||t.call(this))},t}(L),oe=function(e){function t(t,n){return e.call(this)||this}return p(t,e),t.prototype.schedule=function(e,t){return this},t}(O),ie={setInterval:function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=ie.delegate;return((null==n?void 0:n.setInterval)||setInterval).apply(void 0,m([],b(e)))},clearInterval:function(e){var t=ie.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},se=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 p(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),ie.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;ie.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return new Error("executing a cancelled action");this.pending=!1;var n=this._execute(e,t);if(n)return n;!1===this.pending&&null!=this.id&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n,r=!1;try{this.work(e)}catch(e){r=!0,n=e||new Error("Scheduled action threw falsy error")}if(r)return this.unsubscribe(),n},t.prototype.unsubscribe=function(){if(!this.closed){var t=this.id,n=this.scheduler,r=n.actions;this.work=this.state=this.scheduler=null,this.pending=!1,E(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(oe),ce={now:function(){return(ce.delegate||Date).now()},delegate:void 0},ae=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=ce.now,e}(),ue=new(function(e){function t(t,n){void 0===n&&(n=ae.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return p(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(ae))(se),le=ue;function de(e){return e&&l(e.schedule)}function fe(e){return e instanceof Date&&!isNaN(e)}function pe(e){return de((t=e)[t.length-1])?e.pop():void 0;var t}function he(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var i=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(i),!o)return i}function ve(e){return d((function(t,n){var r,o=null,i=!1;o=t.subscribe(new re(n,void 0,void 0,(function(s){r=te(e(s,ve(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):i=!0}))),i&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function ye(e,t){return void 0===t&&(t=0),d((function(n,r){n.subscribe(new re(r,(function(n){return he(r,e,(function(){return r.next(n)}),t)}),(function(){return he(r,e,(function(){return r.complete()}),t)}),(function(n){return he(r,e,(function(){return r.error(n)}),t)})))}))}function be(e,t){return void 0===t&&(t=0),d((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function me(e,t){if(!e)throw new Error("Iterable cannot be null");return new V((function(n){he(n,t,(function(){var r=e[Symbol.asyncIterator]();he(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function ge(e,t){if(null!=e){if(G(e))return function(e,t){return te(e).pipe(be(t),ye(t))}(e,t);if(S(e))return function(e,t){return new V((function(n){var r=0;return t.schedule((function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())}))}))}(e,t);if(k(e))return function(e,t){return te(e).pipe(be(t),ye(t))}(e,t);if(J(e))return me(e,t);if(Z(e))return function(e,t){return new V((function(n){var r;return he(n,t,(function(){r=e[Q](),he(n,t,(function(){var e,t,o;try{t=(e=r.next()).value,o=e.done}catch(e){return void n.error(e)}o?n.complete():n.next(t)}),0,!0)})),function(){return l(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(ee(e))return function(e,t){return me(X(e),t)}(e,t)}throw Y(e)}function _e(e,t){return t?ge(e,t):te(e)}function we(e,t){return d((function(n,r){var o=0;n.subscribe(new re(r,(function(n){r.next(e.call(t,n,o++))})))}))}function Se(e,t,n){return void 0===n&&(n=1/0),l(t)?Se((function(n,r){return we((function(e,o){return t(n,e,r,o)}))(te(e(n,r)))}),n):("number"==typeof t&&(n=t),d((function(t,r){return function(e,t,n,r,o,i,s,c){var a=[],u=0,l=0,d=!1,f=function(){!d||a.length||u||t.complete()},p=function(e){return u<r?h(e):a.push(e)},h=function(e){i&&t.next(e),u++;var c=!1;te(n(e,l++)).subscribe(new re(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){c=!0}),void 0,(function(){if(c)try{u--;for(var e=function(){var e=a.shift();s?he(t,s,(function(){return h(e)})):h(e)};a.length&&u<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(new re(t,p,(function(){d=!0,f()}))),function(){null==c||c()}}(t,r,e,n)})))}function ke(){return void 0===(e=1)&&(e=1/0),Se(K,e);var e}function xe(e,t){return void 0===t&&(t=ue),d((function(n,r){var o=null,i=null,s=null,c=function(){if(o){o.unsubscribe(),o=null;var e=i;i=null,r.next(e)}};function a(){var n=s+e,i=t.now();if(i<n)return o=this.schedule(void 0,n-i),void r.add(o);c()}n.subscribe(new re(r,(function(n){i=n,s=t.now(),o||(o=t.schedule(a,e),r.add(o))}),(function(){c(),r.complete()}),void 0,(function(){i=o=null})))}))}function Ie(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ke()(_e(e,pe(e)))}var Ee=new V((function(e){return e.complete()}));function Oe(e){return e<=0?function(){return Ee}:d((function(t,n){var r=0;t.subscribe(new re(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function Te(e,t){return t?function(n){return Ie(t.pipe(Oe(1),d((function(e,t){e.subscribe(new re(t,U))}))),n.pipe(Te(e)))}:Se((function(t,n){return e(t,n).pipe(Oe(1),function(e){return we((function(){return e}))}(t))}))}function Ce(e,t){void 0===t&&(t=ue);var n=function(e,t,n){void 0===e&&(e=0),void 0===n&&(n=le);var r=-1;return null!=t&&(de(t)?n=t:r=t),new V((function(t){var o=fe(e)?+e-n.now():e;o<0&&(o=0);var i=0;return n.schedule((function(){t.closed||(t.next(i++),0<=r?this.schedule(void 0,r):t.complete())}),o)}))}(e,t);return Te((function(){return n}))}function Ae(e,t){return e===t}function je(e,t){return d((function(n,r){var o=0;n.subscribe(new re(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function Pe(e){return je((function(t,n){return e<=n}))}function Ue(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=pe(e);return d((function(t,r){(n?Ie(e,t,n):Ie(e,t)).subscribe(r)}))}function De(e,t){return d((function(n,r){var o=null,i=0,s=!1,c=function(){return s&&!o&&r.complete()};n.subscribe(new re(r,(function(n){null==o||o.unsubscribe();var s=0,a=i++;te(e(n,a)).subscribe(o=new re(r,(function(e){return r.next(t?t(n,e,a,s++):e)}),(function(){o=null,c()})))}),(function(){s=!0,c()})))}))}function $e(e,t,n){var r=l(e)||t||n?{next:e,error:t,complete:n}:e;return r?d((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(new re(t,(function(e){var n;null===(n=r.next)||void 0===n||n.call(r,e),t.next(e)}),(function(){var e;o=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()}),(function(e){var n;o=!1,null===(n=r.error)||void 0===n||n.call(r,e),t.error(e)}),(function(){var e,t;o&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)})))})):K}var Re=x((function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}));function Le(e){throw new Re(e)}let Ne=!1;function We(e,t){return o(this,void 0,void 0,(function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){Ne||(console.debug("Dexie Cloud: Could not register sync event",e),Ne=!0)}}))}function Be(e,t){e.cloud.usingServiceWorker?We(e,t):e.localSyncEvent.next({purpose:t})}const Me="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},Fe="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,ArrayBuffer.isView(e)?e:new Uint8Array(e)));function He({realms:e,inviteRealms:t}){return o(this,void 0,void 0,(function*(){const n=JSON.stringify([...e.map((e=>({realmId:e,accepted:!0}))),...t.map((e=>({realmId:e,accepted:!1})))].sort(((e,t)=>e.realmId<t.realmId?-1:e.realmId>t.realmId?1:0))),r=(new TextEncoder).encode(n),o=yield crypto.subtle.digest("SHA-1",r);return Fe(o)}))}function Ke(e){return Object.entries(e.cloud.schema||{}).filter((([,{markedForSync:e}])=>e)).map((([t])=>e.tables.filter((({name:e})=>e===t))[0])).filter((e=>e))}function qe(e){return`$${e}_mutations`}function Ve(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const ze=[].concat;function Ge(e){return ze.apply([],e)}function Je(e,t,{since:n={},limit:r=1/0}={}){return o(this,void 0,void 0,(function*(){const t=Ge(yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){const t=Ve(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return(yield i.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.ts-t.mut.ts)),i=[];let s=null,c=null;for(const{table:e,mut:n}of t)s&&s.table===e&&c===n.txid?s.muts.push(n):(s={table:e,muts:[n]},c=n.txid,i.push(s));return i}))}function Ye(e){const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))}const Qe=crypto.getRandomValues;function Ze(e){if(!e)throw new Error("Assertion Failed")}function Xe(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){Ze("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)Xe(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),c=t.substr(i+1);if(""===c)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var a=e[s];a||(a=e[s]={}),Xe(a,c,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const et="undefined"==typeof self?e=>{const t=Buffer.alloc(e);return Qe(t),t.toString("base64")}:e=>{const t=new Uint8Array(e);return crypto.getRandomValues(t),btoa(String.fromCharCode.apply(null,t))};function tt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>tt(e)))&&e.every(nt))}function nt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(nt)}function rt(e,t,n){const r=e[t]||(e[t]={}),o=n.keys.map((e=>"string"==typeof e?e:JSON.stringify(e)));switch(n.type){case"insert":case"upsert":o.forEach(((e,t)=>{r[e]={type:"ups",val:n.values[t]}}));break;case"update":case"modify":o.forEach(((e,t)=>{const o="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(o))Xe(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":o.forEach((e=>{r[e]={type:"del"}}))}return e}function ot(e,t){for(const{table:n,muts:r}of t)for(const t of r)rt(e,n,t)}function it(e,t){let n=!1;return new Promise(((o,i)=>{const s=Object.assign(Object.assign({},t),{onSubmit:t=>{e.next(void 0),n=!0,o(t)},onCancel:()=>{e.next(void 0),n=!0,i(new r.default.AbortError("User cancelled"))}});e.next(s)}))}function st(e,t,...n){return it(e,{type:"message-alert",title:t,alerts:n,fields:{}})}function ct(e,t,n){return o(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(yield it(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r}))}function at(e,t,n){return o(this,void 0,void 0,(function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:o}=yield it(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function ut(e,t,n,r,i){return o(this,void 0,void 0,(function*(){return t.accessToken&&t.accessTokenExpiration.getTime()>Date.now()?t:t.refreshToken&&(!t.refreshTokenExpiration||t.refreshTokenExpiration.getTime()>Date.now())?yield lt(e,t):yield function(e,t,n,r){return o(this,void 0,void 0,(function*(){const{privateKey:o,publicKey:i}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!o||!i)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=o;const s=function(e){const t=Fe(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",i));e.publicKey=i;try{const o=yield 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&&(yield it(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts})),e}catch(e){throw yield st(n,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:"We're having a problem authenticating right now.",messageParams:{}}).catch((()=>{})),e}}))}(t,n,r,i)}))}function lt(e,t){return o(this,void 0,void 0,(function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",o=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,o),s=Fe(i),c={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},a=yield fetch(`${e}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==a.status)throw new Error(`RefreshToken: Status ${a.status} from ${e}/token`);const u=yield a.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}))}const{toString:dt}={};const ft={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function pt(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,o){const i=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 ft;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,dt.call(o).slice(8,-1)),c=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==c?void 0:c[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:ft),n.set(r,i),i}default:return t[r]}var o}(o);return i?i.replace(o,r,t):o}),o);return i},parse(e,n){const r=[];return JSON.parse(e,(function(e,o){const i=null==o?void 0:o.$t;if(i){const e=t[i];o=e?e.revive(o,n,t):o}let s=r[r.length-1];if(s&&s[0]===o){o={...o};for(const e of s[1])delete o[e];for(const[e,t]of Object.entries(s[2]))o[e]=t;r.pop()}if(void 0===o||"$"===e[0]&&"$t"!==e){let t,n;s=r[r.length-1],s&&s[0]===this?(t=s[1],n=s[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=o):n[e]=void 0}return o}))}}}const ht={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 vt={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 yt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var bt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},mt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},gt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const _t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var wt=["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=_t[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function St(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=It[e[n]];return t}(Fe(e))}function kt(e){return Me(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+=xt[e[n]];return t}(e))}const xt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},It={};for(const e of Object.keys(xt))It[xt[e]]=e;var Et={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:St(e)}),revive:({v:e})=>{const t=kt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ot{constructor(e,t){this.buf=e,this.type=t}}function Tt(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 Ct(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var At={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ot,replace:e=>({$t:"Blob",v:Fe(e instanceof Ot?e.buf:Ct(Tt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Me(t);return void 0!==typeof Blob?new Blob([n]):new Ot(n.buffer,e)}}};const jt={...vt,...yt,...bt,...mt,...gt,...wt,...Et,...At};function Pt(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 Ut={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Dt="bigint"==typeof BigInt(0);class $t{constructor(e){this.v=e}toString(){return this.v}}const Rt=Object.assign(Object.assign({},Ut),Dt?{}:{bigint:{test:e=>e instanceof $t,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new $t(e)}}),Lt=pt(jt,Rt),Nt=function(...e){const t=pt(jt,ht,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),o=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[o,r]},async parse(e,n){let r=0;const o=[],i=await Pt(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 Pt(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)}}}(Rt);class Wt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Bt(e,t,n){const o=[];for(let i of n){const{table:n,muts:s}=i,c=e.tables.find((e=>e.name===n));if(!c)throw new Error(`Internal error: table ${n} not found in DBCore schema`);const{primaryKey:a}=c;let u=i;s.forEach(((e,n)=>{const o=!a.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach(((e,s)=>{if(Array.isArray(e)){u===i&&(u=Mt(i,o));const t=u.muts[n],c=JSON.stringify(e);t.keys[s]=c,o&&r.default.setByKeyPath(t.values[s],a.keyPath,c)}else if("#"===e[0]){u===i&&(u=Mt(i,o));const c=u.muts[n];if(!t.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const l=`${e}:${t.userId}`;c.keys[s]=l,o&&r.default.setByKeyPath(c.values[s],a.keyPath,l)}}))})),o.push(u)}return o}function Mt(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()}))):e.muts.map((e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()})))})}function Ft(e,t,n,r,i,s,c,a){return o(this,void 0,void 0,(function*(){const u={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},l=yield function(e){var t,n;return o(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:c,claims:a}=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==c?void 0:c.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield lt(e.cloud.options.databaseUrl,r);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}))}(r);l&&(u.Authorization=`Bearer ${l}`);const d={v:2,dbID:null==t?void 0:t.remoteDbId,clientIdentity:c,schema:s||{},lastPull:t?{serverRevision:t.serverRevision,realms:t.realms,inviteRealms:t.inviteRealms}:void 0,baseRevs:n,changes:Bt(r.dx.core.schema,a,e)};console.debug("Sync request",d),r.syncStateChangedEvent.next({phase:"pushing"});const f=yield fetch(`${i}/sync`,{method:"post",headers:u,body:Lt.stringify(d)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!f.ok)throw new Wt(f);if("application/x-bison"===f.headers.get("content-type"))return Nt.fromBinary(yield f.blob());{const e=yield f.text();return Lt.parse(e)}}))}function Ht(e){if(null==e?void 0:e.cancelled)throw new r.default.AbortError("Operation was cancelled")}let Kt=navigator.onLine;function qt(e,t,n,r){return o(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))))}))}function Vt(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function zt(t,n,i){return o(this,void 0,void 0,(function*(){const o=yield t.bulkGet(n),s=[],c=[];n.forEach(((n,a)=>{const u=o[a];if(u){for(const[o,s]of Object.entries(i[a]))if(o===t.schema.primKey.keyPath){if(0!==e.cmp(s,n))throw new Error("Cannot change primary key")}else r.default.setByKeyPath(u,o,s);s.push(n),c.push(u)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(c,s):t.bulkPut(c)}))}function Gt(e,t){return o(this,void 0,void 0,(function*(){console.debug("Applying server changes",e,r.default.currentTransaction);for(const{table:n,muts:o}of e){const e=t.table(n);if(!e)continue;const{primaryKey:i}=e.core.schema,s=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+t.cloud.currentUserId)?e.substr(0,e.length-t.cloud.currentUserId.length-1):e;default:return e}};for(const t of o){const n=t.keys.map(s);switch(t.type){case"insert":i.outbound?yield e.bulkAdd(t.values,n):(n.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),yield e.bulkAdd(t.values));break;case"upsert":i.outbound?yield e.bulkPut(t.values,n):(n.forEach(((e,n)=>{r.default.setByKeyPath(t.values[n],i.keyPath,e)})),yield e.bulkPut(t.values));break;case"modify":1===n.length?yield e.update(n[0],t.changeSpec):yield e.where(":id").anyOf(n).modify(t.changeSpec);break;case"update":yield zt(e,n,t.changeSpecs);break;case"delete":yield e.bulkDelete(n)}}}}))}self.addEventListener("online",(()=>Kt=!0)),self.addEventListener("offline",(()=>Kt=!1));function Jt(e,t,n,r){return Yt.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((i=>o(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):(console.debug("Error from _sync",{isOnline:Kt,syncOptions:r,error:i}),Kt&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise((e=>setTimeout(e,500))),yield Jt(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:Kt?"error":"offline",error:i}),Promise.reject(i)))}))))}function Yt(e,t,n,{isInitialSync:r,cancelToken:s,justCheckIfNeeded:c,purpose:a}={isInitialSync:!1}){var u;return o(this,void 0,void 0,(function*(){if(c||console.debug("SYNC STARTED",{isInitialSync:r,purpose:a}),!(null===(u=e.cloud.options)||void 0===u?void 0:u.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:l}=t,d=yield e.getCurrentUser(),f=d.isLoggedIn?Ke(e):[],p=f.map((t=>e.table(qe(t.name)))),h=yield e.getPersistedSyncState(),v=!r&&d.isLoggedIn?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Ke(e).filter((e=>!n.includes(e.name)))}(e,h):[];Ht(s);const y=v.length>0;if(y){if(c)return!0;yield e.transaction("rw",v,(e=>o(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return o(this,void 0,void 0,(function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||e.userId&&e.userId!==i.userId||(e.userId=t.userId)})):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify((e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==i.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==i.userId||(e.owner=t.userId),e.realmId&&e.realmId!==i.userId||(e.realmId=t.userId))})))}))}(v,d,null==h?void 0:h.realms)})))),Ht(s)}const[b,m,g]=yield e.transaction("r",e.tables,(()=>o(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield Je(p);if(Ht(s),y){const e=[...(null==h?void 0:h.realms)||[],...(null==h?void 0:h.inviteRealms)||[]],c=yield function(e,t,n,r){return o(this,void 0,void 0,(function*(){const i=`upload-${Ye(8)}`;if(t.isLoggedIn&&e.length>0){const s=new Set(r||[]);return(yield Promise.all(e.map((e=>o(this,void 0,void 0,(function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const o=n[e.name],c=(null==o?void 0:o.generatedGlobalId)?e.filter((e=>{const t=r(e);return!s.has(e.realmId||"")&&tt(t)})):e.filter((e=>{return r(e),!s.has(e.realmId||"")&&(t=r(e),!(n=null==o?void 0:o.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n})),a=yield c.toArray();if(a.length>0){const n={type:"upsert",values:a,keys:a.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(v,d,n,e);return Ht(s),i=i.concat(c),[i,t,r]}return[i,t,r]})))),_=b.some((e=>e.muts.some((e=>e.keys.length>0))));if(c)return console.debug("Sync is needed:",_),_;if("push"===a&&!_)return!1;const w=Vt(b,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||et(16);Ht(s);const k=yield Ft(b,m,g,e,l,n,S,d);console.debug("Sync response",k);const x=yield e.transaction("rw",e.tables,(t=>o(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))k.schema[e]&&(n[e]=k.schema[e]);yield e.$syncState.put(n,"schema");const r=yield Je(p,0,{since:w});for(const t of p){const n=Ve(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(w[n]){const r=w[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}Vt(r,w),yield qt(e,n,w,k.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return o(this,void 0,void 0,(function*(){const r=new Set,o=new Set,i=n?n.realms:[],s=n?n.inviteRealms:[],c=new Set(t.realms),a=new Set(t.realms.concat(t.inviteRealms));for(const e of i)c.has(e)||(o.add(e),a.has(e)||r.add(e));for(const e of s.concat(i))a.has(e)||r.add(e);if(r.size>0||o.size>0){const t=Ke(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:o;0!==t.size&&(e.schema.indexes.some((e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0]))?yield e.where("realmId").anyOf([...t]).delete():yield e.filter((e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId))).delete())}}}))}(e,k,i);const s=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};s.syncedTables=f.map((e=>e.name)).concat(v.map((e=>e.name))),s.latestRevisions=w,s.remoteDbId=k.dbId,s.initiallySynced=!0,s.realms=k.realms,s.inviteRealms=k.inviteRealms,s.serverRevision=k.serverRevision,s.timestamp=new Date,delete s.error;const c=Qt(k.changes,r);return yield Gt(c,e),e.$syncState.put(s,"syncState"),0===r.length}))));return x?(console.debug("SYNC DONE",{isInitialSync:r}),!1):(console.debug("MORE SYNC NEEDED. Go for it again!"),yield Yt(e,t,n,{isInitialSync:r,cancelToken:s}))}))}function Qt(e,t){const n={};ot(n,e);const r={};return ot(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,c]of Object.entries(s))switch(c.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(c.mod))Xe(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(c.mod))delete n.mod[e]}break}}}(n,r),function(e){const t=et(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 Zt(e){const n=[],i=new t.BehaviorSubject(!0),s=new t.BehaviorSubject(null);let c=!1,a=0,u=[0,0,0,0,0,0,0,0,0,Date.now()];return s.subscribe((()=>o(this,void 0,void 0,(function*(){if(!c&&n.length>0){c=!0,u.shift(),u.push(Date.now()),i.next(!1);try{yield function(){var t,i,s;return o(this,void 0,void 0,(function*(){for(;n.length>0;){const c=n.shift();try{yield e.cloud.syncState.pipe(je((({phase:e})=>"in-sync"===e||"error"===e)),Oe(1)).toPromise(),console.debug("processing msg",c);const n=e.cloud.persistedSyncState.value;if(!c)continue;switch(c.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=e.cloud.currentUser.value,u=yield lt(e.cloud.options.databaseUrl,a);yield e.table("$logins").update(a.userId,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration});break;case"realm-added":case"realm-accepted":case"realms-changed":Be(e,"pull");break;case"realm-removed":(null===(t=null==n?void 0:n.realms)||void 0===t?void 0:t.includes(c.realm))||null===(i=null==n?void 0:n.inviteRealms)||void 0===i||i.includes(c.realm),Be(e,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(s=e.cloud.syncState.value)||void 0===s?void 0:s.phase)){Be(e,"pull");break}yield e.transaction("rw",e.dx.tables,(t=>o(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,o,i]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(console.debug("ws message queue: in transaction"),!o||!n||!i)return void console.debug("required vars not present",{syncState:o,schema:n,currentUser:i});if(c.baseRev!==o.serverRevision)return console.debug(`baseRev (${c.baseRev}) differs from our serverRevision in syncState (${o.serverRevision})`),void("string"!=typeof c.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||Be(e,"pull"));const s=yield r.default.waitFor(He(o));if(console.debug("ourRealmSetHash",s),s!==c.realmSetHash)return console.debug("not same realmSetHash",c.realmSetHash),void Be(e,"pull");let a=[];if(i.isLoggedIn){const t=Ke(e).map((t=>e.table(qe(t.name))));a=yield Je(t),console.debug("msg queue: client changes",a)}if(c.changes.length>0){const t=Qt(c.changes,a);console.debug("applying filtered server changes",t),yield Gt(t,e)}o.latestRevisions=Vt(a,o.latestRevisions),o.serverRevision=c.newRev,console.debug("Updating baseRefs",o.latestRevisions),yield qt(e,n,o.latestRevisions,c.newRev),console.debug("Updating syncState",o),yield e.$syncState.put(o,"syncState")})))),console.debug("msg queue: done with rw transaction")}}catch(e){console.error("Error in msg queue",e)}}}))}()}finally{u[u.length-1]-u[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,yield new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,yield new Promise((e=>setTimeout(e,1e4))))),c=!1,i.next(!0)}}})))),{enqueue:function(e){n.push(e),s.next(null)},readyToServe:i}}const Xt=new WeakMap,en={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let tn=0;function nn(e){"vip"in e&&(e=e.vip);let n=Xt.get(e.cloud);if(!n){const r=new t.Subject;let o=new u(`syncstatechanged-${e.name}`);r.id=++tn;let s=!1;n={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return s},localSyncEvent:r,get syncStateChangedEvent(){return o},dx:e};const c={getCurrentUser:()=>n.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||i)),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema"),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){s=e},reconfigure(){o=new u(`syncstatechanged-${e.name}`)}};Object.assign(n,c),n.messageConsumer=Zt(n),Xt.set(e.cloud,n)}return n}const rn=new WeakMap;class on{constructor(e,t){rn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new on(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return o(this,void 0,void 0,(function*(){rn.get(this).table("$logins").put(this)}))}}function sn(e,t){return o(this,void 0,void 0,(function*(){if((yield e.getCurrentUser()).isLoggedIn){if(t){if(t.email&&e.cloud.currentUser.value.email!==t.email)throw new Error("Must logout before changing user");if(t.userId&&e.cloud.currentUserId!==t.userId)throw new Error("Must logout before changing user")}return}const n=new on(e,{claims:{},lastLogin:new Date(0)});yield ut(e.cloud.options.databaseUrl,n,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function({public_key:n,hints:r}){var i;return o(this,void 0,void 0,(function*(){let o;const s=null===(i=e.cloud.options)||void 0===i?void 0:i.databaseUrl;if(!s)throw new Error("No database URL given.");o="demo"===(null==r?void 0:r.grant_type)?{demo_user:yield ct(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:yield ct(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const c=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==c.status){const e=yield c.text();throw yield st(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Wt(c,e)}const a=yield c.json();if("tokens"===a.type)return a;if("otp"===o.grant_type){if("otp-sent"!==a.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield at(t,o.email);o.otp=e||"",o.otp_id=a.otp_id;let n=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===n.status;){const e=yield n.text();o.otp=yield at(t,o.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),n=yield fetch(`${s}/token`,{body:JSON.stringify(o),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==n.status){const e=yield n.text();throw yield st(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Wt(n,e)}return yield n.json()}throw new Error(`Unexpected response from ${s}/token`)}))}}(e),e.cloud.userInteraction,t),yield n.save(),yield function(e,t){return o(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>o(this,void 0,void 0,(function*(){const e=yield n.toArray();yield Promise.all(e.filter((e=>e.userId!==t.userId&&e.isLoggedIn)).map((e=>(e.isLoggedIn=!1,n.put(e))))),t.isLoggedIn=!0,t.lastLogin=new Date,yield t.save(),console.debug("Saved new user",t.email)})))),yield 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),Be(e,"pull")}))}const cn="undefined"!=typeof InstallTrigger,an="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),un=an?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,ln=an&&un<=605||cn;const dn="undefined"!=typeof self&&"clients"in self&&!self.document;function fn(){throw new r.default.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:pn}={};function hn(e){return pn.call(e).slice(8,-1)}function vn(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 yn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let bn=0;function mn(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();bn>=o?++bn:bn=o,r[0]=bn/1099511627776,r[1]=bn/4294967296,r[2]=bn/16777216,r[3]=bn/65536,r[4]=bn/256,r[5]=bn;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+St(new Uint8Array(n.buffer))+(t||"")}function gn(e){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:t=>Object.assign(Object.assign({},t),{table:n=>{const o=t.table(n);return Object.assign(Object.assign({},o),{mutate:t=>{var i,s;if(t.trans.disableChangeTracking)return o.mutate(t);if("add"===t.type||"put"===t.type){const c=null===(i=e.cloud.schema)||void 0===i?void 0:i[n];if(null==c?void 0:c.generatedGlobalId){if((null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!e.initiallySynced){const e=vn(o.schema.primaryKey,t);return o.getMany({keys:e,trans:t.trans,cache:"immutable"}).then((n=>{if(n.length<e.length)throw new Error("Unable to create new objects without an initial sync having been performed.");return o.mutate(t)}))}return function(t,i){let s=null;const c=vn(o.schema.primaryKey,t);return c.forEach(((a,u)=>{if(void 0===a){const n=t.values[u].realmId||e.cloud.currentUserId,a=n.substr(n.length-3);c[u]=mn(i,a),o.schema.primaryKey.outbound||(s||(s=t.values.slice()),s[u]=r.default.deepClone(s[u]),r.default.setByKeyPath(s[u],o.schema.primaryKey.keyPath,c[u]))}else if("string"!=typeof a||!a.startsWith(i)&&!a.startsWith("#"+i))throw new r.default.ConstraintError(`The ID "${a}" is not valid for table "${n}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)})),o.mutate(Object.assign(Object.assign({},t),{keys:c,values:s||t.values}))}(t,c.idPrefix)}if(null==c?void 0:c.markedForSync){vn(o.schema.primaryKey,t).forEach(((e,t)=>{if(!tt(e)){const t=Array.isArray(e)?e.map(hn).join(","):hn(e);throw new r.default.ConstraintError(`Invalid primary key type ${t} for table ${n}. Tables marked for sync has primary keys of type string or Array of string (and optional numbers)`)}}))}}return o.mutate(t)}})}})}}let _n=0;function wn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=o.length,s=(i>0?o[i-1].then((()=>e(n)),(()=>e(n))):e(n)).finally((()=>r.splice(r.indexOf(s))));return r.push(s),s}}function Sn(e,t){return function(n){const{readers:r,writers:o}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(o.length>0?o[o.length-1].then((()=>e(n)),(()=>e(n))):r.length>0?(s=r,new Promise((e=>{0===s.length&&e([]);let t=s.length;const n=new Array(t);s.forEach(((r,o)=>Promise.resolve(r).then((e=>n[o]={status:"fulfilled",value:e}),(e=>n[o]={status:"rejected",reason:e})).then((()=>--t||e(n)))))}))).then((()=>e(n))):e(n)).finally((()=>o.shift()));var s;return o.push(i),i}}const kn=new t.BehaviorSubject(new Set);function xn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){fn()}return Object.assign(Object.assign({},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=>qe(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=Ye(16),i.currentUser=e.value,kn.value.add(i),kn.next(kn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),kn.value.delete(i),kn.next(kn.value)},r=()=>{var e;i.mutationsAdded&&(null===(e=t.cloud.options)||void 0===e?void 0:e.databaseUrl)&&(t.cloud.usingServiceWorker?(console.debug("registering sync event"),We(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 r=n.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},r),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),r.mutate(e))}):"$logins"===e?Object.assign(Object.assign({},r),{mutate:e=>r.mutate(e).then((t=>(e.trans.mutationsAdded=!0,t))).catch((e=>(console.debug("Failed mutation $logins",e),Promise.reject(e))))}):r;const{schema:i}=r,s=o.get(e);return function(e){const t="$lock"+ ++_n;return Object.assign(Object.assign({},e),{count:wn(e.count,t),get:wn(e.get,t),getMany:wn(e.getMany,t),openCursor:wn(e.openCursor,t),query:wn(e.query,t),mutate:Sn(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,a;const u=n.trans;return u.txid?u.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(a=u.currentUser)||void 0===a?void 0:a.isLoggedIn)?"deleteRange"===n.type?r.query({query:{range:n.range,index:i.primaryKey},trans:n.trans,values:!1}).then((e=>c({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):c(n):r.mutate(n):r.mutate(n)}}));function c(e){const t=e.trans;t.mutationsAdded=!0;const{txid:n,currentUser:{userId:o}}=t,{type:i}=e;return r.mutate(e).then((r=>{const{numFailures:c,failures:a}=r;let u="delete"===i?e.keys:r.results,l="values"in e?e.values:[],d="changeSpecs"in e?e.changeSpecs:[];c&&(u=u.filter(((e,t)=>!a[t])),l=l.filter(((e,t)=>!a[t])),d=d.filter(((e,t)=>!a[t])));const f=Date.now(),p="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:n,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:n,userId:o}:e.changeSpecs?{type:"update",ts:f,keys:u,changeSpecs:d,txid:n,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:n,userId:o};return u.length>0||"criteria"in e&&e.criteria?s.mutate({type:"add",trans:t,values:[p]}).then((()=>r)):r}))}}})}}}function In(e,t){return function(n,r){const o=Object.assign(Object.assign({},en),n),i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(yn.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 En=new t.BehaviorSubject(!0),On=new t.BehaviorSubject(!0);var Tn,Cn;En.pipe(De((e=>e?t.of(!0):t.of(!1).pipe(Ce(2e4)))),(void 0===Cn&&(Cn=K),Tn=null!=Tn?Tn:Ae,d((function(e,t){var n,r=!0;e.subscribe(new re(t,(function(e){var o=Cn(e);!r&&Tn(n,o)||(r=!1,n=o,t.next(e))})))})))).subscribe(On);const An="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),jn=An.pipe(je((()=>"hidden"===document.visibilityState))),Pn=An.pipe(je((()=>"visible"===document.visibilityState))),Un="undefined"!=typeof window?t.merge(Pn,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),jn,Un).pipe(we((()=>"visible"===document.visibilityState)),$e((e=>{En.value!==e&&En.next(e)})),De((e=>e?t.of(0).pipe(Ce(16e4),$e((()=>En.next(!1)))):t.of(0)))).subscribe((()=>{}));class Dn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class $n extends t.Observable{constructor(e,t,n,r,o,i,s,c){super((a=>new Ln(e,t,n,r,s,c,a,o,i)))}}let Rn=0;class Ln extends t.Subscription{constructor(e,t,n,r,o,i,s,c,a){super((()=>this.teardown())),this.id=++Rn,this.reconnecting=!1,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=c,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(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return o(this,void 0,void 0,(function*(){if(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 Dn);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>o(this,void 0,void 0,(function*(){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=Lt.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{let e=!1;yield new Promise(((t,r)=>{n.onopen=n=>{console.debug("dexie-cloud WebSocket onopen"),e=!0,t(null)},n.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),r(e)}}})),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(Lt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}function Nn(e){return o(this,void 0,void 0,(function*(){var t;console.error("WebSocket observable: error but revive when user does some active thing...",e),yield(t=3e3,new Promise((e=>setTimeout(e,t)))),console.debug("waiting for someone to do something"),yield Un.pipe(Oe(1)).toPromise(),console.debug("someone did something!")}))}function Wn(e){var t;return o(this,void 0,void 0,(function*(){return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Jt(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const Bn=Ye(16);function Mn(n,r,i,s,{awaitRemoteJob:c}={}){return o(this,void 0,void 0,(function*(){const a=n.table(i);if(yield function s(){return o(this,void 0,void 0,(function*(){if(yield n.transaction("rw!",i,(()=>o(this,void 0,void 0,(function*(){const e=yield a.get(r);return e?e.heartbeat.getTime()<Date.now()-6e4&&(console.warn(`Latest ${r} worker seem to have died.\n`,"The dead job started:",e.started,"\n","Last heart beat was:",e.heartbeat,"\n","We're now taking over!"),yield a.put({nodeId:Bn,started:new Date,heartbeat:new Date},r),!0):(yield a.add({nodeId:Bn,started:new Date,heartbeat:new Date},r),!0)})))))return!0;if(c)try{const n=t.from(e.liveQuery((()=>a.get(r)))).pipe(function(e,t){var n=fe(e)?{first:e}:"number"==typeof e?{each:e}:e,r=n.first,o=n.each,i=n.with,s=void 0===i?Le:i,c=n.scheduler,a=void 0===c?null!=t?t:ue:c,u=n.meta,l=void 0===u?null:u;if(null==r&&null==o)throw new TypeError("No timeout provided.");return d((function(e,t){var n,i,c=null,u=0,d=function(e){i=he(t,a,(function(){try{n.unsubscribe(),te(s({meta:l,lastValue:c,seen:u})).subscribe(t)}catch(e){t.error(e)}}),e)};n=e.subscribe(new re(t,(function(e){null==i||i.unsubscribe(),u++,t.next(c=e),o>0&&d(o)}),void 0,void 0,(function(){(null==i?void 0:i.closed)||null==i||i.unsubscribe(),c=null}))),d(null!=r?"number"==typeof r?r:+r-a.now():o)}))}(6e4),je((e=>!e)));return yield n.toPromise(),!1}catch(e){if("TimeoutError"!==e.name)throw e;return yield s()}return!1}))}()){const e=setInterval((()=>{a.update(r,(e=>{e.nodeId===Bn&&(e.heartbeat=new Date)}))}),1e3);try{return yield s()}finally{clearInterval(e),yield n.transaction("rw!",i,(()=>o(this,void 0,void 0,(function*(){const e=yield a.get(r);e&&e.nodeId===Bn&&(yield a.delete(r))}))))}}}))}const Fn=new WeakMap;function Hn(e,t,n,r){const i=Fn.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return console.debug("syncIfPossible(): returning the ongoing sync promise."),i.promise;{let o=!1;const s=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(o=!0)}));return i.promise.then((()=>{s.unsubscribe()})).catch((e=>(s.unsubscribe(),Promise.reject(e)))).then((()=>{if(!o)return Hn(e,t,n,r)}))}}const s=function(){return o(this,void 0,void 0,(function*(){try{if(e.cloud.isServiceWorkerDB)yield Jt(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw Ze(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield Mn(e,"currentSyncWorker","$jobs",(()=>Jt(e,t,n,r)))}Fn.delete(e),console.debug("Done sync")}catch(t){throw Fn.delete(e),console.error("Failed to sync client changes",t),t}}))}();return Fn.set(e,{promise:s,pull:"push"!==(null==r?void 0:r.purpose)}),s}function Kn(e,t,n){let r=null,o={cancelled:!1};function i(r,c=1){setTimeout((()=>{Hn(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():c<3&&setTimeout((()=>i(r,c+1)),6e4*[0,5,15][c])}))}),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 qn(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Vn,zn,Gn,Jn,Yn={},Qn=[],Zn=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Xn(e,t){for(var n in t)e[n]=t[n];return e}function er(e){var t=e.parentNode;t&&t.removeChild(e)}function tr(e,t,n){var r,o,i,s=arguments,c={};for(i in t)"key"==i?r=t[i]:"ref"==i?o=t[i]:c[i]=t[i];if(arguments.length>3)for(n=[n],i=3;i<arguments.length;i++)n.push(s[i]);if(null!=n&&(c.children=n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===c[i]&&(c[i]=e.defaultProps[i]);return nr(e,c,r,o,null)}function nr(e,t,n,r,o){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==o?++Vn.__v:o};return null!=Vn.vnode&&Vn.vnode(i),i}function rr(e){return e.children}function or(e,t){this.props=e,this.context=t}function ir(e,t){if(null==t)return e.__?ir(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?ir(e):null}function sr(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return sr(e)}}function cr(e){(!e.__d&&(e.__d=!0)&&zn.push(e)&&!ar.__r++||Jn!==Vn.debounceRendering)&&((Jn=Vn.debounceRendering)||Gn)(ar)}function ar(){for(var e;ar.__r=zn.length;)e=zn.sort((function(e,t){return e.__v.__b-t.__v.__b})),zn=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=Xn({},o)).__v=o.__v+1,yr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?ir(o):i,o.__h),br(n,o),o.__e!=i&&sr(o)))}))}function ur(e,t,n,r,o,i,s,c,a,u){var l,d,f,p,h,v,y,b=r&&r.__k||Qn,m=b.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(p=n.__k[l]=null==(p=t[l])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?nr(null,p,null,null,p):Array.isArray(p)?nr(rr,{children:p},null,null,null):p.__b>0?nr(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=b[l])||f&&p.key==f.key&&p.type===f.type)b[l]=void 0;else for(d=0;d<m;d++){if((f=b[d])&&p.key==f.key&&p.type===f.type){b[d]=void 0;break}f=null}yr(e,p,f=f||Yn,o,i,s,c,a,u),h=p.__e,(d=p.ref)&&f.ref!=d&&(y||(y=[]),f.ref&&y.push(f.ref,null,p),y.push(d,p.__c||h,p)),null!=h?(null==v&&(v=h),"function"==typeof p.type&&null!=p.__k&&p.__k===f.__k?p.__d=a=lr(p,a,e):a=dr(e,p,f,b,h,a),u||"option"!==n.type?"function"==typeof n.type&&(n.__d=a):e.value=""):a&&f.__e==a&&a.parentNode!=e&&(a=ir(f))}for(n.__e=v,l=m;l--;)null!=b[l]&&("function"==typeof n.type&&null!=b[l].__e&&b[l].__e==n.__d&&(n.__d=ir(r,l+1)),_r(b[l],b[l]));if(y)for(l=0;l<y.length;l++)gr(y[l],y[++l],y[++l])}function lr(e,t,n){var r,o;for(r=0;r<e.__k.length;r++)(o=e.__k[r])&&(o.__=e,t="function"==typeof o.type?lr(o,t,n):dr(n,o,o,e.__k,o.__e,t));return t}function dr(e,t,n,r,o,i){var s,c,a;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(c=i,a=0;(c=c.nextSibling)&&a<r.length;a+=2)if(c==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function fr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||Zn.test(t)?n:n+"px"}function pr(e,t,n,r,o){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||fr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||fr(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?vr:hr,i):e.removeEventListener(t,i?vr:hr,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 hr(e){this.l[e.type+!1](Vn.event?Vn.event(e):e)}function vr(e){this.l[e.type+!0](Vn.event?Vn.event(e):e)}function yr(e,t,n,r,o,i,s,c,a){var u,l,d,f,p,h,v,y,b,m,g,_=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(a=n.__h,c=t.__e=n.__e,t.__h=null,i=[c]),(u=Vn.__b)&&u(t);try{e:if("function"==typeof _){if(y=t.props,b=(u=_.contextType)&&r[u.__c],m=u?b?b.props.value:u.__:r,n.__c?v=(l=t.__c=n.__c).__=l.__E:("prototype"in _&&_.prototype.render?t.__c=l=new _(y,m):(t.__c=l=new or(y,m),l.constructor=_,l.render=wr),b&&b.sub(l),l.props=y,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=Xn({},l.__s)),Xn(l.__s,_.getDerivedStateFromProps(y,l.__s))),f=l.props,p=l.state,d)null==_.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==_.getDerivedStateFromProps&&y!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(y,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(y,l.__s,m)||t.__v===n.__v){l.props=y,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(y,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,p,h)}))}l.context=m,l.props=y,l.state=l.__s,(u=Vn.__r)&&u(t),l.__d=!1,l.__v=t,l.__P=e,u=l.render(l.props,l.state,l.context),l.state=l.__s,null!=l.getChildContext&&(r=Xn(Xn({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(h=l.getSnapshotBeforeUpdate(f,p)),g=null!=u&&u.type===rr&&null==u.key?u.props.children:u,ur(e,Array.isArray(g)?g:[g],t,n,r,o,i,s,c,a),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),v&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=mr(n.__e,t,n,r,o,i,s,a);(u=Vn.diffed)&&u(t)}catch(e){t.__v=null,(a||null!=i)&&(t.__e=c,t.__h=!!a,i[i.indexOf(c)]=null),Vn.__e(e,t,n)}}function br(e,t){Vn.__c&&Vn.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){Vn.__e(e,t.__v)}}))}function mr(e,t,n,r,o,i,s,c){var a,u,l,d,f=n.props,p=t.props,h=t.type,v=0;if("svg"===h&&(o=!0),null!=i)for(;v<i.length;v++)if((a=i[v])&&(a===e||(h?a.localName==h:3==a.nodeType))){e=a,i[v]=null;break}if(null==e){if(null===h)return document.createTextNode(p);e=o?document.createElementNS("http://www.w3.org/2000/svg",h):document.createElement(h,p.is&&p),i=null,c=!1}if(null===h)f===p||c&&e.data===p||(e.data=p);else{if(i=i&&Qn.slice.call(e.childNodes),u=(f=n.props||Yn).dangerouslySetInnerHTML,l=p.dangerouslySetInnerHTML,!c){if(null!=i)for(f={},d=0;d<e.attributes.length;d++)f[e.attributes[d].name]=e.attributes[d].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||pr(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]||pr(e,i,t[i],n[i],r)}(e,p,f,o,c),l)t.__k=[];else if(v=t.props.children,ur(e,Array.isArray(v)?v:[v],t,n,r,o&&"foreignObject"!==h,i,s,e.firstChild,c),null!=i)for(v=i.length;v--;)null!=i[v]&&er(i[v]);c||("value"in p&&void 0!==(v=p.value)&&(v!==e.value||"progress"===h&&!v)&&pr(e,"value",v,f.value,!1),"checked"in p&&void 0!==(v=p.checked)&&v!==e.checked&&pr(e,"checked",v,f.checked,!1))}return e}function gr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){Vn.__e(e,n)}}function _r(e,t,n){var r,o,i;if(Vn.unmount&&Vn.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||gr(r,null,t)),n||"function"==typeof e.type||(n=null!=(o=e.__e)),e.__e=e.__d=void 0,null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Vn.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(i=0;i<r.length;i++)r[i]&&_r(r[i],t,n);null!=o&&er(o)}function wr(e,t,n){return this.constructor(e,n)}Vn={__e:function(e,t){for(var n,r,o;t=t.__;)if((n=t.__c)&&!n.__)try{if((r=n.constructor)&&null!=r.getDerivedStateFromError&&(n.setState(r.getDerivedStateFromError(e)),o=n.__d),null!=n.componentDidCatch&&(n.componentDidCatch(e),o=n.__d),o)return n.__E=n}catch(t){e=t}throw e},__v:0},or.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Xn({},this.state),"function"==typeof e&&(e=e(Xn({},n),this.props)),e&&Xn(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),cr(this))},or.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),cr(this))},or.prototype.render=rr,zn=[],Gn="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,ar.__r=0;const Sr={Error:{color:"red"},Alert:{error:{color:"red"},warning:{color:"yellow"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"30px",marginBottom:"2em",maxWidth:"90%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",width:"auto"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function kr({children:e,className:t}){return tr("div",{className:t},tr("div",{style:Sr.Darken}),tr("div",{style:Sr.DialogOuter},tr("div",{style:Sr.DialogInner},e)))}var xr,Ir,Er,Or=0,Tr=[],Cr=Vn.__b,Ar=Vn.__r,jr=Vn.diffed,Pr=Vn.__c,Ur=Vn.unmount;function Dr(e,t){Vn.__h&&Vn.__h(Ir,e,Or||t),Or=0;var n=Ir.__H||(Ir.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function $r(e){return Or=1,function(e,t,n){var r=Dr(xr++,2);return r.t=e,r.__c||(r.__=[n?n(t):Fr(void 0,t),function(e){var t=r.t(r.__[0],e);r.__[0]!==t&&(r.__=[t,r.__[1]],r.__c.setState({}))}],r.__c=Ir),r.__}(Fr,e)}function Rr(e){return Or=5,function(e,t){var n=Dr(xr++,7);return Mr(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}((function(){return{current:e}}),[])}function Lr(){Tr.forEach((function(e){if(e.__P)try{e.__H.__h.forEach(Wr),e.__H.__h.forEach(Br),e.__H.__h=[]}catch(t){e.__H.__h=[],Vn.__e(t,e.__v)}})),Tr=[]}Vn.__b=function(e){Ir=null,Cr&&Cr(e)},Vn.__r=function(e){Ar&&Ar(e),xr=0;var t=(Ir=e.__c).__H;t&&(t.__h.forEach(Wr),t.__h.forEach(Br),t.__h=[])},Vn.diffed=function(e){jr&&jr(e);var t=e.__c;t&&t.__H&&t.__H.__h.length&&(1!==Tr.push(t)&&Er===Vn.requestAnimationFrame||((Er=Vn.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),Nr&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);Nr&&(t=requestAnimationFrame(n))})(Lr)),Ir=void 0},Vn.__c=function(e,t){t.some((function(e){try{e.__h.forEach(Wr),e.__h=e.__h.filter((function(e){return!e.__||Br(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],Vn.__e(n,e.__v)}})),Pr&&Pr(e,t)},Vn.unmount=function(e){Ur&&Ur(e);var t=e.__c;if(t&&t.__H)try{t.__H.__.forEach(Wr)}catch(e){Vn.__e(e,t.__v)}};var Nr="function"==typeof requestAnimationFrame;function Wr(e){var t=Ir;"function"==typeof e.__c&&e.__c(),Ir=t}function Br(e){var t=Ir;e.__c=e.__(),Ir=t}function Mr(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function Fr(e,t){return"function"==typeof t?t(e):t}function Hr({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=$r({}),c=Rr();return function(e,t){var n=Dr(xr++,4);!Vn.__s&&Mr(n.__H,t)&&(n.__=e,n.__H=t,Ir.__h.push(n))}((()=>{var e;return null===(e=c.current)||void 0===e?void 0:e.focus()}),[]),tr(kr,{className:"dxc-login-dlg"},tr(rr,null,tr("h3",{style:Sr.WindowHeader},e),t.map((e=>tr("p",{style:Sr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substr(1,e.length-2)]))}(e)))),tr("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>tr("label",{style:Sr.Label},n?`${n}: `:"",tr("input",{ref:0===o?c:void 0,type:t,name:e,autoComplete:"on",style:Sr.Input,autoFocus:!0,placeholder:r,value:i[e]||"",onInput:n=>{var r;return s(Object.assign(Object.assign({},i),{[e]:Kr(t,null===(r=n.target)||void 0===r?void 0:r.value)}))}})))))),tr("div",{style:Sr.ButtonsDiv},tr("button",{type:"submit",style:Sr.Button,onClick:()=>o(i)},"Submit"),tr("button",{style:Sr.Button,onClick:r},"Cancel")))}function Kr(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}class qr extends or{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?tr(Hr,Object.assign({},t)):null}}function Vr(e){const t=document.createElement("div");document.body.appendChild(t),function(e,t,n){var r,o,i;Vn.__&&Vn.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],yr(t,e=(!r&&n||t).__k=tr(rr,null,[e]),o||Yn,Yn,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?Qn.slice.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),br(i,e)}(tr(qr,{db:e.vip}),t);let n=!1;return{unsubscribe(){t.remove(),n=!0},get closed(){return n}}}function zr(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}function Gr(e,n){let r=n,o=t.from(e).pipe(t.map((e=>r=e)),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const i=new t.Observable((e=>{let t=!1;const n=o.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n}));return i.getValue=()=>r,i}const Jr=zr((t=>Gr(e.liveQuery((()=>t.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),Yr=zr((e=>new t.BehaviorSubject(i))),Qr=zr((t=>Gr(Yr(t._novip).pipe(De((n=>e.liveQuery((()=>t.transaction("r","realms","members",(()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}})));function Zr(...e){if(0===e.length)return{};const t=e.reduce(((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,o=t[e];t[e]=[...new Set([...o,...r])]}else if("object"==typeof r&&r&&"object"==typeof n[e]){const t=n[e];for(const[e,n]of Object.entries(r))"*"!==t[e]&&("*"===n?t[e]="*":Array.isArray(t[e])&&Array.isArray(n)&&(t[e]=[...new Set([...t[e],...n])]))}}else n[e]=t[e];return n}));return t}const Xr=zr((e=>function(e,n){let r;const o=e.pipe(t.map((e=>r=n(e))));return o.getValue=()=>void 0!==r?r:r=n(e.getValue()),o}(Gr(t.combineLatest([Qr(e._novip),Jr(e._novip)]).pipe(we((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:i.userId,globalRoles:{}}),(({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const o=t.map((t=>{const o=e.filter((e=>e.realmId===t.realmId)),i=o.map((e=>e.permissions)).filter((e=>e)),s=Ge(o.map((e=>e.roles)).filter((e=>e))).map((e=>r[e])).filter((e=>e)).map((e=>e.permissions));return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:Zr(...i,...s)})})).reduce(((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t})),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return o}))));class eo{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every((e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)}))))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every((e=>"owner"!==e));const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every((e=>"owner"!==e)):e.every((e=>null==r?void 0:r.some((t=>t===e||"*"===t&&"owner"!==e))))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const to=zr((n=>{const r=Yr(n._novip).pipe(t.switchMap((t=>e.liveQuery((()=>n.members.where({email:t.email||""}).toArray()))))),i=Xr(n._novip),s=Qr(n._novip);return Gr(t.combineLatest([r,s,i]).pipe(t.map((([e,t,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),s=e.reduce(i,{}),c=t.selfMembers.reduce(i,s);return Object.values(c).filter((e=>!e.accepted&&!e.rejected)).map((e=>Object.assign(Object.assign({},e),{accept(){return o(this,void 0,void 0,(function*(){yield n.members.update(e.id,{accepted:new Date})}))},reject(){return o(this,void 0,void 0,(function*(){yield n.members.update(e.id,{rejected:new Date})}))}})))}))),[])})),no={nameSuffix:!0};function ro(n){const s=n.name,c=Yr(n),a=[];let u=!1,l=null;n.on("ready",(n=>o(this,void 0,void 0,(function*(){try{yield function(n){var i,s,p,h,v,y,b;return o(this,void 0,void 0,(function*(){d=!1;const m=nn(n);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=m.cloud.options)||void 0===i?void 0:i.customLoginGui)||a.push(Vr(n))),m.cloud.isServiceWorkerDB||a.push(function(e){let n=e.cloud.webSocketStatus.value;const r=e.cloud.webSocketStatus.pipe(De((e=>{const r=n;n=e;const o=t.of(e);switch(e){case"disconnected":return En.value?o.pipe(xe(500)):o;case"connecting":return"not-started"===r||"error"===r?o:o.pipe(xe(4e3));default:return o}})));return t.combineLatest([r,e.syncStateChangedEvent.pipe(Ue({phase:"initial"})),On]).pipe(we((([t,n,r])=>{let{phase:o,error:i,progress:s}=n,c=t;return"error"===o&&(c="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(c="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(c="connecting"),r||(c="disconnected"),{phase:o,error:i,progress:s,status:Kt?c:"offline"}})))}(m).subscribe(n.cloud.syncState)),m.tables.every((e=>e.core))||fn();const g="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],_=yield m.transaction("rw",m.$syncState,(()=>o(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=m.cloud,[o,i,s]=yield Promise.all([m.getOptions(),m.getSchema(),m.getPersistedSyncState()]);if(u){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");yield m.$syncState.put(n,"options")}}else m.cloud.options=o||null;if((null===(e=m.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&g.length>0&&!ln?(console.debug("Dexie Cloud Addon: Using service worker"),m.cloud.usingServiceWorker=!0):((null===(t=m.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&!m.cloud.isServiceWorkerDB&&console.debug("dexie-cloud-addon: Not using service worker.",0===g.length?"No SW registrations found.":"serviceWorker"in navigator&&ln?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),m.cloud.usingServiceWorker=!1),qn(r,m.cloud.options),qn(i,m.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield m.$syncState.put(e,"schema"),Object.assign(r,e)}}else m.cloud.schema=i||null;return null==s?void 0:s.initiallySynced}))));_&&m.setInitiallySynced(!0),function(e){var t,n;for(const o of e.tables)if(null===(n=null===(t=e.cloud.schema)||void 0===t?void 0:t[o.name])||void 0===n?void 0:n.markedForSync){if(o.schema.primKey.auto)throw new r.default.SchemaError(`Table ${o.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`);if(!o.schema.primKey.keyPath)throw new r.default.SchemaError(`Table ${o.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(o.name)}]}) to blacklist it from sync`)}}(m),(null===(s=m.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!_&&(yield function(e,t,n){return o(this,void 0,void 0,(function*(){console.debug("Performing initial sync"),yield Jt(e,t,n,{isInitialSync:!0}),console.debug("Done initial sync")}))}(m,m.cloud.options,m.cloud.schema),m.setInitiallySynced(!0)),f(),m.cloud.isServiceWorkerDB||(a.push(e.liveQuery((()=>m.getCurrentUser())).subscribe(c)),a.push(e.liveQuery((()=>m.getPersistedSyncState())).subscribe(m.cloud.persistedSyncState)),yield t.combineLatest([c.pipe(Pe(1),Oe(1)),m.cloud.persistedSyncState.pipe(Pe(1),Oe(1))]).toPromise()),(null===(p=m.cloud.options)||void 0===p?void 0:p.requireAuth)&&(yield sn(m)),l&&l.stop(),l=null,f(),m.cloud.usingServiceWorker&&(null===(h=m.cloud.options)||void 0===h?void 0:h.databaseUrl)?(We(m,"push").catch((()=>{})),function(e){var t;return o(this,void 0,void 0,(function*(){try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync),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)}}))}(m).catch((()=>{}))):(null===(v=m.cloud.options)||void 0===v?void 0:v.databaseUrl)&&m.cloud.schema&&!m.cloud.isServiceWorkerDB&&(l=Kn(m,m.cloud.options,m.cloud.schema),l.start(),Be(m,"push")),f(),m.cloud.isServiceWorkerDB||a.push(t.fromEvent(self,"online").subscribe((()=>{console.debug("online!"),m.syncStateChangedEvent.next({phase:"not-in-sync"}),Be(m,"push")})),t.fromEvent(self,"offline").subscribe((()=>{console.debug("offline!"),m.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(y=m.cloud.options)||void 0===y?void 0:y.databaseUrl)||(null===(b=m.cloud.options)||void 0===b?void 0:b.disableWebSocket)||dn||a.push(function(e){var n;if(!(null===(n=e.cloud.options)||void 0===n?void 0:n.databaseUrl))throw new Error("No database URL to connect WebSocket to");const r=e.messageConsumer.readyToServe.pipe(je((e=>e)),De((()=>e.getPersistedSyncState())),je((e=>e&&e.serverRevision)),we((e=>({type:"ready",rev:e.serverRevision}))));return function n(){return e.cloud.persistedSyncState.pipe(je((e=>null==e?void 0:e.serverRevision)),Oe(1),De((t=>e.cloud.currentUser.pipe(we((e=>[e,t]))))),De((([e,t])=>On.pipe(we((n=>[n?e:null,t]))))),De((([e,t])=>o(this,void 0,void 0,(function*(){return[e,yield He(t)]})))),De((([n,o])=>n?new $n(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,o,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n.accessToken,n.accessTokenExpiration):t.from([]))),ve((r=>"TokenExpiredError"===(null==r?void 0:r.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),t.of(!0).pipe(De((()=>o(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield lt(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})))),De((()=>n())))):t.throwError(r))),ve((r=>(e.cloud.webSocketStatus.next("error"),t.from(Nn(r)).pipe(De((()=>n())))))))}().subscribe((t=>{t&&(console.debug("WS got message",t),e.messageConsumer.enqueue(t))}),(e=>{console.error("Oops! The main observable errored!",e)}),(()=>{console.error("Oops! The main observable completed!")}))}(m))}))}(n)}catch(e){console.error(e)}}))),!0);let d=!1;function f(){if(d)throw new r.default.DatabaseClosedError}var p;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(n,(()=>{a.forEach((e=>e.unsubscribe())),d=!0,l&&l.stop(),l=null,c.next(i)})),n.cloud={version:"4.0.0-beta.22",options:Object.assign({},no),schema:null,get currentUserId(){return c.value.userId||i.userId},currentUser:c,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return o(this,void 0,void 0,(function*(){const t=nn(n);yield t.cloud.sync(),yield sn(t,e)}))},invites:to(n),roles:Jr(n),configure(e){e=n.cloud.options=Object.assign(Object.assign({},n.cloud.options),e),u=!0,e.databaseUrl&&e.nameSuffix&&(n.name=`${s}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,nn(n).reconfigure()),qn(n.cloud.schema,n.cloud.options)},sync({wait:r,purpose:i}={wait:!0,purpose:"push"}){return o(this,void 0,void 0,(function*(){void 0===r&&(r=!0);const s=nn(n);if("pull"===i){const e=s.cloud.persistedSyncState.value;if(Be(s,i),r){const t=yield s.cloud.persistedSyncState.pipe(je((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))),Oe(1)).toPromise();if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield Wn(s)){const n=s.cloud.persistedSyncState.value;Be(s,i),r&&(console.debug("db.cloud.login() is waiting for sync completion..."),yield t.from(e.liveQuery((()=>o(this,void 0,void 0,(function*(){const e=yield Wn(s),t=yield s.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(je((e=>!e)),Oe(1)).toPromise(),console.debug("Done waiting for sync completion because we have nothing to push anymore"))}}))},permissions:(e,t)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:r,realmId:o}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const i=Xr(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new eo(i.permissions,n,o===e.cloud.currentUserId||r===e.cloud.currentUserId):new eo({},n,!r||r===e.cloud.currentUserId)},c=i.pipe(we(s));return c.getValue=()=>s(i.getValue()),c}(n._novip,e,t)},n.Version.prototype._parseStoresSpec=r.default.override(n.Version.prototype._parseStoresSpec,(e=>In(e,n))),n.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return mn(n.cloud.schema[this.name].idPrefix||"",t)},n.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},n.use(xn({currentUserObservable:n.cloud.currentUser,db:nn(n)})),n.use((p=nn(n),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,o,i,s;if(e.trans.disableChangeTracking)return n.mutate(e);const c=e.trans;if((null===(o=null===(r=p.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type))for(const t of e.values){t.owner||(t.owner=c.currentUser.userId),t.realmId||(t.realmId=c.currentUser.userId);const r=null===(s=(i=n.schema.primaryKey).extractKey)||void 0===s?void 0:s.call(i,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.changeSpecs,t.$ts=Date.now())}return n.mutate(e)}})}})})),n.use(gn(nn(n)))}ro.version="4.0.0-beta.22",r.default.Cloud=ro;const oo=new Map;function io(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const so=new Map;function co(e,t){let n=so.get(e+"/"+t);return n||(n=function e(t,n){var i;return o(this,void 0,void 0,(function*(){let o=oo.get(t);if(!o){console.debug("Dexie Cloud SW: Creating new Dexie instance for",t);const i=new r.default(t,{addons:[ro]});if(o=nn(i),o.cloud.isServiceWorkerDB=!0,i.on("versionchange",s),yield o.dx.open(),oo.get(t))return o.close(),yield e(t,n);oo.set(t,o)}if(null===(i=o.cloud.options)||void 0===i?void 0:i.databaseUrl)if(o.cloud.schema)try{console.debug("Dexie Cloud SW: Syncing"),yield Hn(o,o.cloud.options,o.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:n}),console.debug("Dexie Cloud SW: Done Syncing")}catch(e){if(console.error("Dexie Cloud SW Error",e),s(),e.name!==r.default.errnames.NoSuchDatabase)throw e}else console.error("Dexie Cloud: No schema persisted");else console.error("Dexie Cloud: No databaseUrl configured");function s(){return o.dx.on.versionchange.unsubscribe(s),oo.get(o.name)===o&&oo.delete(o.name),console.debug(`Dexie Cloud SW: Closing Dexie instance for ${t}`),o.dx.close(),!1}}))}(e,t).then((()=>{so.delete(e+"/"+t)})).catch((n=>(so.delete(e+"/"+t),Promise.reject(n)))),so.set(e+"/"+t,n)),n}ln||(self.addEventListener("sync",(e=>{console.debug('SW "sync" Event',e.tag);const t=io(e.tag);t&&e.waitUntil(co(t,"push"))})),self.addEventListener("periodicsync",(e=>{console.debug('SW "periodicsync" Event',e.tag);const t=io(e.tag);t&&e.waitUntil(co(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)=>co(t,e.data.purpose||"pull").catch((e=>o(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>console.error(e)))):n().catch((e=>console.error(e)))}})))}));