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