dexie-cloud-addon 4.0.0-beta.17 → 4.0.0-beta.18

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