dexie-cloud-addon 4.0.1-beta.32 → 4.0.1-beta.33

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.
@@ -8,7 +8,7 @@
8
8
  *
9
9
  * ==========================================================================
10
10
  *
11
- * Version 4.0.1-beta.32, Fri Mar 10 2023
11
+ * Version 4.0.1-beta.33, Sat Mar 11 2023
12
12
  *
13
13
  * https://dexie.org
14
14
  *
@@ -5962,7 +5962,7 @@ function dexieCloud(dexie) {
5962
5962
  currentUserEmitter.next(UNAUTHORIZED_USER);
5963
5963
  });
5964
5964
  dexie.cloud = {
5965
- version: '4.0.1-beta.32',
5965
+ version: '4.0.1-beta.33',
5966
5966
  options: Object.assign({}, DEFAULT_OPTIONS),
5967
5967
  schema: null,
5968
5968
  get currentUserId() {
@@ -6217,7 +6217,7 @@ function dexieCloud(dexie) {
6217
6217
  });
6218
6218
  }
6219
6219
  }
6220
- dexieCloud.version = '4.0.1-beta.32';
6220
+ dexieCloud.version = '4.0.1-beta.33';
6221
6221
  Dexie.Cloud = dexieCloud;
6222
6222
 
6223
6223
  export { dexieCloud as default, dexieCloud, getTiedObjectId, getTiedRealmId };
@@ -1,2 +1,2 @@
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 a,merge as c,Subscription as u,from as l,throwError as d,combineLatest as f,map as p,share as h,timer as y}from"rxjs";var v=function(e,t){return v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},v(e,t)};function b(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}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function m(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function g(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function _(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 w(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 S(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 k(e){return this instanceof k?(this.v=e,this):new k(e)}function x(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof k?Promise.resolve(e.value.v).then(c,u):l(i[0][2],e)}(o[e](t))}catch(e){l(i[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function I(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=_(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)}))}}}function E(e){if(!e)throw new Error("Assertion Failed")}const O={}.hasOwnProperty;function T(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){E("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)T(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c&&function(e,t){return O.call(e,t)}(e,s)||(c=e[s]={}),T(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const A="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=C)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function C(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function P(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>P(e)))&&e.every(j))}function j(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(j)}function U(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))T(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 $(e,t){for(const{table:n,muts:r}of t)for(const t of r)U(e,n,t)}function D(e){return"function"==typeof e}function R(e){return function(t){if(function(e){return D(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 N=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function L(e){return D(null==e?void 0:e.then)}function B(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 W=B((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 M(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var F=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=_(i),a=s.next();!a.done;a=s.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var c=this.initialTeardown;if(D(c))try{c()}catch(e){o=e instanceof W?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=_(u),d=l.next();!d.done;d=l.next()){var f=d.value;try{H(f)}catch(e){o=null!=o?o:[],e instanceof W?o=S(S([],w(o)),w(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}if(o)throw new W(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)H(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)&&M(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&M(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function K(e){return e instanceof F||e&&"closed"in e&&D(e.remove)&&D(e.add)&&D(e.unsubscribe)}function H(e){D(e)?e():e.unsubscribe()}F.EMPTY;var V={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},z={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=z.delegate;return(null==o?void 0:o.setTimeout)?o.setTimeout.apply(o,S([e,t],w(n))):setTimeout.apply(void 0,S([e,t],w(n)))},clearTimeout:function(e){var t=z.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function q(e){z.setTimeout((function(){var t=V.onUnhandledError;if(!t)throw e;t(e)}))}function G(){}var J=Y("C",void 0,void 0);function Y(e,t,n){return{kind:e,value:t,error:n}}var Z=null;var X=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,K(t)&&t.add(n)):n.destination=ie,n}return b(t,e),t.create=function(e,t,n){return new ne(e,t,n)},t.prototype.next=function(e){this.isStopped?oe(function(e){return Y("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?oe(Y("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?oe(J,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}(F),Q=Function.prototype.bind;function ee(e,t){return Q.call(e,t)}var te=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){re(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){re(e)}else re(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){re(e)}},e}(),ne=function(e){function t(t,n,r){var o,i,s=e.call(this)||this;D(t)||!t?o={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:s&&V.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&ee(t.next,i),error:t.error&&ee(t.error,i),complete:t.complete&&ee(t.complete,i)}):o=t;return s.destination=new te(o),s}return b(t,e),t}(X);function re(e){q(e)}function oe(e,t){var n=V.onStoppedNotification;n&&z.setTimeout((function(){return n(e,t)}))}var ie={closed:!0,next:G,error:function(e){throw e},complete:G},se="function"==typeof Symbol&&Symbol.observable||"@@observable";function ae(e){return e}function ce(e){return 0===e.length?ae:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var ue=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 X||function(e){return e&&D(e.next)&&D(e.error)&&D(e.complete)}(r)&&K(r)?e:new ne(e,t,n);return function(e){if(V.useDeprecatedSynchronousErrorHandling){var t=!Z;if(t&&(Z={errorThrown:!1,error:null}),e(),t){var n=Z,r=n.errorThrown,o=n.error;if(Z=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=le(t))((function(t,r){var o=new ne({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[se]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ce(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=le(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 le(e){var t;return null!==(t=null!=e?e:V.Promise)&&void 0!==t?t:Promise}function de(e){return D(e[se])}function fe(e){return Symbol.asyncIterator&&D(null==e?void 0:e[Symbol.asyncIterator])}function pe(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 he="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ye(e){return D(null==e?void 0:e[he])}function ve(e){return x(this,arguments,(function(){var t,n,r;return g(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,k(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,k(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,k(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 be(e){return D(null==e?void 0:e.getReader)}function me(e){if(e instanceof ue)return e;if(null!=e){if(de(e))return o=e,new ue((function(e){var t=o[se]();if(D(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(N(e))return r=e,new ue((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(L(e))return n=e,new ue((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,q)}));if(fe(e))return ge(e);if(ye(e))return t=e,new ue((function(e){var n,r;try{for(var o=_(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(be(e))return ge(ve(e))}var t,n,r,o;throw pe(e)}function ge(e){return new ue((function(t){(function(e,t){var n,r,o,i;return m(this,void 0,void 0,(function(){var s,a;return g(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=I(e),c.label=1;case 1:return[4,n.next()];case 2:if((r=c.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function _e(e,t,n,r,o){return new we(e,t,n,r,o)}var we=function(e){function t(t,n,r,o,i,s){var a=e.call(this,t)||this;return a.onFinalize=i,a.shouldUnsubscribe=s,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return b(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}(X),Se=function(e){function t(t,n){return e.call(this)||this}return b(t,e),t.prototype.schedule=function(e,t){return this},t}(F),ke={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=ke.delegate;return(null==o?void 0:o.setInterval)?o.setInterval.apply(o,S([e,t],w(n))):setInterval.apply(void 0,S([e,t],w(n)))},clearInterval:function(e){var t=ke.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},xe=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 b(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),ke.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;ke.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,M(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Se),Ie={now:function(){return(Ie.delegate||Date).now()},delegate:void 0},Ee=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=Ie.now,e}(),Oe=new(function(e){function t(t,n){void 0===n&&(n=Ee.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return b(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}(Ee))(xe),Te=Oe;function Ae(e){return e&&D(e.schedule)}function Ce(e){return e instanceof Date&&!isNaN(e)}function Pe(e){return Ae((t=e)[t.length-1])?e.pop():void 0;var t}function je(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 Ue(e){return R((function(t,n){var r,o=null,i=!1;o=t.subscribe(_e(n,void 0,void 0,(function(s){r=me(e(s,Ue(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):i=!0}))),i&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function $e(e,t){return void 0===t&&(t=0),R((function(n,r){n.subscribe(_e(r,(function(n){return je(r,e,(function(){return r.next(n)}),t)}),(function(){return je(r,e,(function(){return r.complete()}),t)}),(function(n){return je(r,e,(function(){return r.error(n)}),t)})))}))}function De(e,t){return void 0===t&&(t=0),R((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function Re(e,t){if(!e)throw new Error("Iterable cannot be null");return new ue((function(n){je(n,t,(function(){var r=e[Symbol.asyncIterator]();je(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Ne(e,t){if(null!=e){if(de(e))return function(e,t){return me(e).pipe(De(t),$e(t))}(e,t);if(N(e))return function(e,t){return new ue((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(L(e))return function(e,t){return me(e).pipe(De(t),$e(t))}(e,t);if(fe(e))return Re(e,t);if(ye(e))return function(e,t){return new ue((function(n){var r;return je(n,t,(function(){r=e[he](),je(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 D(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(be(e))return function(e,t){return Re(ve(e),t)}(e,t)}throw pe(e)}function Le(e,t){return t?Ne(e,t):me(e)}function Be(e,t){return R((function(n,r){var o=0;n.subscribe(_e(r,(function(n){r.next(e.call(t,n,o++))})))}))}function We(e,t,n){return void 0===n&&(n=1/0),D(t)?We((function(n,r){return Be((function(e,o){return t(n,e,r,o)}))(me(e(n,r)))}),n):("number"==typeof t&&(n=t),R((function(t,r){return function(e,t,n,r,o,i,s,a){var c=[],u=0,l=0,d=!1,f=function(){!d||c.length||u||t.complete()},p=function(e){return u<r?h(e):c.push(e)},h=function(e){i&&t.next(e),u++;var a=!1;me(n(e,l++)).subscribe(_e(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){a=!0}),void 0,(function(){if(a)try{u--;for(var e=function(){var e=c.shift();s?je(t,s,(function(){return h(e)})):h(e)};c.length&&u<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(_e(t,p,(function(){d=!0,f()}))),function(){null==a||a()}}(t,r,e,n)})))}function Me(){return void 0===(e=1)&&(e=1/0),We(ae,e);var e}function Fe(e,t){return void 0===t&&(t=Oe),R((function(n,r){var o=null,i=null,s=null,a=function(){if(o){o.unsubscribe(),o=null;var e=i;i=null,r.next(e)}};function c(){var n=s+e,i=t.now();if(i<n)return o=this.schedule(void 0,n-i),void r.add(o);a()}n.subscribe(_e(r,(function(n){i=n,s=t.now(),o||(o=t.schedule(c,e),r.add(o))}),(function(){a(),r.complete()}),void 0,(function(){i=o=null})))}))}function Ke(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Me()(Le(e,Pe(e)))}var He=new ue((function(e){return e.complete()}));function Ve(e){return e<=0?function(){return He}:R((function(t,n){var r=0;t.subscribe(_e(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function ze(e,t){return t?function(n){return Ke(t.pipe(Ve(1),R((function(e,t){e.subscribe(_e(t,G))}))),n.pipe(ze(e)))}:We((function(t,n){return e(t,n).pipe(Ve(1),function(e){return Be((function(){return e}))}(t))}))}function qe(e,t){void 0===t&&(t=Oe);var n=function(e,t,n){void 0===e&&(e=0),void 0===n&&(n=Te);var r=-1;return null!=t&&(Ae(t)?n=t:r=t),new ue((function(t){var o=Ce(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 ze((function(){return n}))}function Ge(e,t){return e===t}function Je(e,t){return R((function(n,r){var o=0;n.subscribe(_e(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function Ye(e){return Je((function(t,n){return e<=n}))}function Ze(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Pe(e);return R((function(t,r){(n?Ke(e,t,n):Ke(e,t)).subscribe(r)}))}function Xe(e,t){return R((function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(_e(r,(function(n){null==o||o.unsubscribe();var s=0,c=i++;me(e(n,c)).subscribe(o=_e(r,(function(e){return r.next(t?t(n,e,c,s++):e)}),(function(){o=null,a()})))}),(function(){s=!0,a()})))}))}function Qe(e,t,n){var r=D(e)||t||n?{next:e,error:t,complete:n}:e;return r?R((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(_e(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)})))})):ae}var et=B((function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}));function tt(e){throw new et(e)}let nt=!1;function rt(e,t){return m(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){nt||(console.debug("Dexie Cloud: Could not register sync event",e),nt=!0)}}))}function ot(e,t){e.cloud.usingServiceWorker?rt(e,t):e.localSyncEvent.next({purpose:t})}const it="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},st="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 at(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 ct(e,t,...n){return at(e,{type:"message-alert",title:t,alerts:n,fields:{}})}function ut(e,t,n){return m(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(yield at(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 lt(e,t,n){return m(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 at(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function dt(e,t,n,r,o){return m(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 ft(e,t):yield function(e,t,n,r){return m(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=st(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 at(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts})),e}catch(e){throw yield ct(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 ft(e,t){return m(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=st(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=yield c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}))}const pt=new WeakMap;class ht{constructor(e,t){pt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new ht(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return m(this,void 0,void 0,(function*(){pt.get(this).table("$logins").put(this)}))}}class yt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function vt(e,t){return m(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 ht(e,{claims:{},lastLogin:new Date(0)});yield dt(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 m(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 ut(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 ut(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=yield fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=yield a.text();throw yield ct(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new yt(a,e)}const c=yield a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield lt(t,i.email);i.otp=e||"",i.otp_id=c.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 lt(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 ct(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new yt(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 m(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>m(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),ot(e,"pull")}))}const bt={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(bt),Object.freeze(bt.claims)}catch(e){}const mt={},gt="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;gt&&gt.ready.then((e=>mt.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 _t{constructor(e){this.name=e}subscribe(e){if(!gt)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 gt.addEventListener("message",t),()=>gt.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}))):mt.registration&&(null===(t=mt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class wt extends r{constructor(e){const t="undefined"==typeof BroadcastChannel?new _t(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 _t?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 _t?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 St({realms:e,inviteRealms:t}){return m(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 st(o)}))}function kt(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 xt(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 Et=[].concat;function Ot(e){return Et.apply([],e)}function Tt(e,t,{since:n={},limit:r=1/0}={}){return m(this,void 0,void 0,(function*(){const t=Ot(yield Promise.all(e.map((e=>m(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 At(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:Ct}={};const Pt={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 jt(...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 Pt;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,Ct.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:Pt),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 Ut={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 $t={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 Dt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Rt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Nt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Lt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Bt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var Wt=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=Bt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Mt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Ht[e[n]];return t}(st(e))}function Ft(e){return it(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=Kt[e[n]];return t}(e))}const Kt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},Ht={};for(const e of Object.keys(Kt))Ht[Kt[e]]=e;var Vt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Mt(e)}),revive:({v:e})=>{const t=Ft(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class zt{constructor(e,t){this.buf=e,this.type=t}}function qt(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 Gt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Jt={Blob:{test:(e,t)=>"Blob"===t||e instanceof zt,replace:e=>({$t:"Blob",v:st(e instanceof zt?e.buf:Gt(qt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=it(t);return void 0!==typeof Blob?new Blob([n]):new zt(n.buffer,e)}}};const Yt={...$t,...Dt,...Rt,...Nt,...Lt,...Wt,...Vt,...Jt};function Zt(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 Xt={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Qt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class en{toString(){return this.v}constructor(e){this.v=e}}const tn=Object.assign(Object.assign({},Xt),Qt?{}:{bigint:{test:e=>e instanceof en,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new en(e)}}),nn=jt(Yt,tn),rn=function(...e){const t=jt(Yt,Ut,...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 Zt(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 Zt(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)}}}(tn);function on(t,n,r){const o=[];for(let i of r){const{table:r,muts:s}=i,a=t.tables.find((e=>e.name===r));if(!a)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=a;let u=i;s.forEach(((t,r)=>{const o=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,s)=>{if(Array.isArray(t)){u===i&&(u=sn(i,o));const n=u.muts[r],a=JSON.stringify(t);n.keys[s]=a,o&&e.setByKeyPath(n.values[s],c.keyPath,a)}else if("#"===t[0]){u===i&&(u=sn(i,o));const a=u.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const l=`${t}:${n.userId}`;a.keys[s]=l,o&&e.setByKeyPath(a.values[s],c.keyPath,l)}}))})),o.push(u)}return o}function sn(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 an(e,t,n,r,o,i,s,a){return m(this,void 0,void 0,(function*(){const c={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield function(e){var t,n;return m(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield ft(e.cloud.options.databaseUrl,r);return yield e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}))}(r);u&&(c.Authorization=`Bearer ${u}`);const l={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:on(r.dx.core.schema,a,e)};console.debug("Sync request",l),r.syncStateChangedEvent.next({phase:"pushing"});const d=yield fetch(`${o}/sync`,{method:"post",headers:c,body:nn.stringify(l)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!d.ok)throw new yt(d);if("application/x-bison"===d.headers.get("content-type"))return rn.fromBinary(yield d.blob());{const e=yield d.text();return nn.parse(e)}}))}function cn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let un=!1;function ln(e,t,n,r){return m(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 dn(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 fn(n,r,o){return m(this,void 0,void 0,(function*(){const i=yield n.bulkGet(r),s=[],a=[];r.forEach(((r,c)=>{const u=i[c];if(u){for(const[i,s]of Object.entries(o[c]))if(i===n.schema.primKey.keyPath){if(0!==t(s,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(u,i,s);s.push(r),a.push(u)}})),yield null==n.schema.primKey.keyPath?n.bulkPut(a,s):n.bulkPut(a)}))}function pn(t,n){return m(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 fn(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(un=navigator.onLine,self.addEventListener("online",(()=>un=!0)),self.addEventListener("offline",(()=>un=!1)));function hn(e,t,n,r){return yn.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((o=>m(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:un,syncOptions:r,error:o}),un&&(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 hn(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:un?"error":"offline",error:o}),Promise.reject(o)))}))))}function yn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;return m(this,void 0,void 0,(function*(){if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=yield e.getCurrentUser(),l=u.isLoggedIn?kt(e):[],d=l.map((t=>e.table(xt(t.name)))),f=yield e.getPersistedSyncState(),p=!r&&u.isLoggedIn,h=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return kt(e).filter((e=>!n.includes(e.name)))}(e,f):[];cn(o);const y=h.length>0;if(y){if(i)return!0;yield e.transaction("rw",h,(e=>m(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return m(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!==bt.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!==bt.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==bt.userId||(e.owner=t.userId),e.realmId&&e.realmId!==bt.userId||(e.realmId=t.userId))})))}))}(h,u,null==f?void 0:f.realms)})))),cn(o)}const[v,b,g]=yield e.transaction("r",e.tables,(()=>m(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield Tt(d);if(cn(o),y){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],s=yield function(e,t,n,r){return m(this,void 0,void 0,(function*(){const o=`upload-${At(8)}`;if(t.isLoggedIn&&e.length>0){const i=new Set(r||[]);return(yield Promise.all(e.map((e=>m(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],a=(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||"")&&P(t)})),c=yield a.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.map(r),userId:t.userId,txid:o};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(h,u,n,e);return cn(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=dn(v,null==b?void 0:b.latestRevisions),S=(null==b?void 0:b.clientIdentity)||A(16);cn(o);const k=yield an(v,b,g,e,c,n,S,u);console.debug("Sync response",k);const x=yield e.transaction("rw",e.tables,(t=>m(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 Tt(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()])}dn(r,w),yield ln(e,n,w,k.serverRevision);const o=yield e.getPersistedSyncState();yield function(e,t,n){return m(this,void 0,void 0,(function*(){const r=new Set,o=new Set,i=n?n.realms:[],s=n?n.inviteRealms:[],a=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)a.has(e)||(o.add(e),c.has(e)||r.add(e));for(const e of s.concat(i))c.has(e)||r.add(e);if(r.size>0||o.size>0){const t=kt(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=l.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=vn(k.changes,r);return yield pn(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 yn(e,t,n,{isInitialSync:r,cancelToken:o}))}))}function vn(e,t){const n={};$(n,e);const r={};return $(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))T(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=A(16));const 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 bn(t){const n=[],r=new o(!0),i=new o(null);let s=!1,a=0,c=[0,0,0,0,0,0,0,0,0,Date.now()];return i.subscribe((()=>m(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,c.shift(),c.push(Date.now()),r.next(!1);try{yield function(){var r,o,i;return m(this,void 0,void 0,(function*(){for(;n.length>0;){const s=n.shift();try{yield t.cloud.syncState.pipe(Je((({phase:e})=>"in-sync"===e||"error"===e)),Ve(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=yield ft(t.cloud.options.databaseUrl,a);yield t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"realm-added":case"realm-accepted":case"realms-changed":ot(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),ot(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){ot(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>m(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||ot(t,"pull"));const a=yield e.waitFor(St(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void ot(t,"pull");let c=[];if(i.isLoggedIn){const e=kt(t).map((e=>t.table(xt(e.name))));c=yield Tt(e),console.debug("msg queue: client changes",c)}if(s.changes.length>0){const e=vn(s.changes,c);console.debug("applying filtered server changes",e),yield pn(e,t)}o.latestRevisions=dn(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),yield ln(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{c[c.length-1]-c[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,yield new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,yield new Promise((e=>setTimeout(e,1e4))))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:r}}const mn=new WeakMap,gn={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let _n=0;function wn(e){"vip"in e&&(e=e.vip);let t=mn.get(e.cloud);if(!t){const n=new i;let r=new wt(`syncstatechanged-${e.name}`);n.id=++_n;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))||bt)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){r=new wt(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=bn(t),mn.set(e.cloud,t)}return t}const Sn="undefined"!=typeof InstallTrigger,kn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),xn=kn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,In=kn&&xn<=605||Sn;const En="undefined"!=typeof self&&"clients"in self&&!self.document;function On(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:Tn}={};function An(e){return Tn.call(e).slice(8,-1)}function Cn(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const Pn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let jn=0;function Un(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();jn>=o?++jn:jn=o,r[0]=jn/1099511627776,r[1]=jn/4294967296,r[2]=jn/16777216,r[3]=jn/65536,r[4]=jn/256,r[5]=jn;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+Mt(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 a=null===(i=t.cloud.schema)||void 0===i?void 0:i[r];if(null==a?void 0:a.generatedGlobalId){if((null===(s=t.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!t.initiallySynced){const e=Cn(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 a=Cn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=Un(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (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:a,values:s||n.values}))}(n,a.idPrefix)}if(null==a?void 0:a.markedForSync){Cn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!P(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 Dn=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 Nn(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 Ln=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){On()}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=>xt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=At(16),i.currentUser=e.value,Ln.value.add(i),Ln.next(Ln.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),Ln.value.delete(i),Ln.next(Ln.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"),rt(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"+ ++Dn;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:Nn(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,c;const u=n.trans;return u.txid?u.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(c=u.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===n.type?r.query({query:{range:n.range,index:i.primaryKey},trans:n.trans,values:!1}).then((e=>a({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):a(n):r.mutate(n):r.mutate(n)}}));function a(e){const t=e.trans;t.mutationsAdded=!0;const{txid:n,currentUser:{userId:o}}=t,{type:i}=e;return r.mutate(e).then((r=>{const{numFailures:a,failures:c}=r;let u="delete"===i?e.keys:r.results,l="values"in e?e.values:[],d="updates"in e&&e.updates;a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])));const f=Date.now(),p="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:n,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:n,userId:o}:d?{type:"update",ts:f,keys:d.keys,changeSpecs:d.changeSpecs,txid:n,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:n,userId:o};return u.length>0||"criteria"in e&&e.criteria?s.mutate({type:"add",trans:t,values:[p]}).then((()=>r)):r}))}}})}}}function Wn(e,t){return function(n,r){const o=Object.assign(Object.assign({},gn),n),i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(Pn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,i;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const Mn=new o(!0),Fn=new o(!0);var Kn,Hn;Mn.pipe(Xe((e=>e?a(!0):a(!1).pipe(qe(2e4)))),(void 0===Hn&&(Hn=ae),Kn=null!=Kn?Kn:Ge,R((function(e,t){var n,r=!0;e.subscribe(_e(t,(function(e){var o=Hn(e);!r&&Kn(n,o)||(r=!1,n=o,t.next(e))})))})))).subscribe(Fn);const Vn="undefined"!=typeof document?s(document,"visibilitychange"):a({}),zn=Vn.pipe(Je((()=>"hidden"===document.visibilityState))),qn=Vn.pipe(Je((()=>"visible"===document.visibilityState))),Gn="undefined"!=typeof window?c(qn,s(window,"mousedown"),s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),zn,Gn).pipe(Be((()=>"visible"===document.visibilityState)),Qe((e=>{Mn.value!==e&&Mn.next(e)})),Xe((e=>e?a(0).pipe(qe(16e4),Qe((()=>Mn.next(!1)))):a(0)))).subscribe((()=>{}));class Jn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Yn extends r{constructor(e,t,n,r,o,i,s,a){super((c=>new Xn(e,t,n,r,s,a,c,o,i)))}}let Zn=0;class Xn extends u{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++Zn,this.reconnecting=!1,console.debug("New WebSocket Connection",this.id,o?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.realmSetHash=n,this.clientIdentity=r,this.token=o,this.tokenExpiration=i,this.subscriber=s,this.lastUserActivity=new Date,this.messageProducer=a,this.messageProducerSubscription=null,this.webSocketStatus=c,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return m(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 Jn);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>m(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=nn.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(nn.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}function Qn(e){return m(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 Gn.pipe(Ve(1)).toPromise(),console.debug("someone did something!")}))}function er(e){var t;return m(this,void 0,void 0,(function*(){return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield hn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const tr=At(16);function nr(e,t,r,o,{awaitRemoteJob:i}={}){return m(this,void 0,void 0,(function*(){const s=e.table(r);if(yield function o(){return m(this,void 0,void 0,(function*(){if(yield e.transaction("rw!",r,(()=>m(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:tr,started:new Date,heartbeat:new Date},t),!0):(yield s.add({nodeId:tr,started:new Date,heartbeat:new Date},t),!0)})))))return!0;if(i)try{const e=l(n((()=>s.get(t)))).pipe(function(e,t){var n=Ce(e)?{first:e}:"number"==typeof e?{each:e}:e,r=n.first,o=n.each,i=n.with,s=void 0===i?tt:i,a=n.scheduler,c=void 0===a?null!=t?t:Oe:a,u=n.meta,l=void 0===u?null:u;if(null==r&&null==o)throw new TypeError("No timeout provided.");return R((function(e,t){var n,i,a=null,u=0,d=function(e){i=je(t,c,(function(){try{n.unsubscribe(),me(s({meta:l,lastValue:a,seen:u})).subscribe(t)}catch(e){t.error(e)}}),e)};n=e.subscribe(_e(t,(function(e){null==i||i.unsubscribe(),u++,t.next(a=e),o>0&&d(o)}),void 0,void 0,(function(){(null==i?void 0:i.closed)||null==i||i.unsubscribe(),a=null}))),!u&&d(null!=r?"number"==typeof r?r:+r-c.now():o)}))}(6e4),Je((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===tr&&(e.heartbeat=new Date)}))}),1e3);try{return yield o()}finally{clearInterval(n),yield e.transaction("rw!",r,(()=>m(this,void 0,void 0,(function*(){const e=yield s.get(t);e&&e.nodeId===tr&&(yield s.delete(t))}))))}}}))}const rr=new WeakMap;function or(e,t,n,r){const o=rr.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 or(e,t,n,r)}))}}const i=function(){return m(this,void 0,void 0,(function*(){try{if(e.cloud.isServiceWorkerDB)yield hn(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw E(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield nr(e,"currentSyncWorker","$jobs",(()=>hn(e,t,n,r)))}rr.delete(e),console.debug("Done sync")}catch(t){throw rr.delete(e),console.error("Failed to sync client changes",t),t}}))}();return rr.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function ir(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){setTimeout((()=>{or(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}),0)}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function sr(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var ar,cr,ur,lr,dr,fr={},pr=[],hr=/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 vr(e){var t=e.parentNode;t&&t.removeChild(e)}function br(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 mr(e,s,r,o,null)}function mr(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!=cr.vnode&&cr.vnode(i),i}function gr(e){return e.children}function _r(e,t){this.props=e,this.context=t}function wr(e,t){if(null==t)return e.__?wr(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?wr(e):null}function Sr(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return Sr(e)}}function kr(e){(!e.__d&&(e.__d=!0)&&lr.push(e)&&!xr.__r++||dr!==cr.debounceRendering)&&((dr=cr.debounceRendering)||setTimeout)(xr)}function xr(){for(var e;xr.__r=lr.length;)e=lr.sort((function(e,t){return e.__v.__b-t.__v.__b})),lr=[],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,jr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?wr(o):i,o.__h),Ur(n,o),o.__e!=i&&Sr(o)))}))}function Ir(e,t,n,r,o,i,s,a,c,u){var l,d,f,p,h,y,v,b=r&&r.__k||pr,m=b.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(p=n.__k[l]=null==(p=t[l])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?mr(null,p,null,null,p):Array.isArray(p)?mr(gr,{children:p},null,null,null):p.__b>0?mr(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=b[l])||f&&p.key==f.key&&p.type===f.type)b[l]=void 0;else for(d=0;d<m;d++){if((f=b[d])&&p.key==f.key&&p.type===f.type){b[d]=void 0;break}f=null}jr(e,p,f=f||fr,o,i,s,a,c,u),h=p.__e,(d=p.ref)&&f.ref!=d&&(v||(v=[]),f.ref&&v.push(f.ref,null,p),v.push(d,p.__c||h,p)),null!=h?(null==y&&(y=h),"function"==typeof p.type&&p.__k===f.__k?p.__d=c=Er(p,c,e):c=Or(e,p,f,b,h,c),"function"==typeof n.type&&(n.__d=c)):c&&f.__e==c&&c.parentNode!=e&&(c=wr(f))}for(n.__e=y,l=m;l--;)null!=b[l]&&("function"==typeof n.type&&null!=b[l].__e&&b[l].__e==n.__d&&(n.__d=wr(r,l+1)),Rr(b[l],b[l]));if(v)for(l=0;l<v.length;l++)Dr(v[l],v[++l],v[++l])}function Er(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?Er(r,t,n):Or(n,r,r,o,r.__e,t));return t}function Or(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function Tr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||hr.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||Tr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Tr(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?Pr:Cr,i):e.removeEventListener(t,i?Pr:Cr,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 Cr(e){this.l[e.type+!1](cr.event?cr.event(e):e)}function Pr(e){this.l[e.type+!0](cr.event?cr.event(e):e)}function jr(e,t,n,r,o,i,s,a,c){var u,l,d,f,p,h,y,v,b,m,g,_,w,S=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=cr.__b)&&u(t);try{e:if("function"==typeof S){if(v=t.props,b=(u=S.contextType)&&r[u.__c],m=u?b?b.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in S&&S.prototype.render?t.__c=l=new S(v,m):(t.__c=l=new _r(v,m),l.constructor=S,l.render=Nr),b&&b.sub(l),l.props=v,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=S.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=yr({},l.__s)),yr(l.__s,S.getDerivedStateFromProps(v,l.__s))),f=l.props,p=l.state,d)null==S.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==S.getDerivedStateFromProps&&v!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(v,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(v,l.__s,m)||t.__v===n.__v){l.props=v,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(v,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,p,h)}))}if(l.context=m,l.props=v,l.__v=t,l.__P=e,g=cr.__r,_=0,"prototype"in S&&S.prototype.render)l.state=l.__s,l.__d=!1,g&&g(t),u=l.render(l.props,l.state,l.context);else do{l.__d=!1,g&&g(t),u=l.render(l.props,l.state,l.context),l.state=l.__s}while(l.__d&&++_<25);l.state=l.__s,null!=l.getChildContext&&(r=yr(yr({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(h=l.getSnapshotBeforeUpdate(f,p)),w=null!=u&&u.type===gr&&null==u.key?u.props.children:u,Ir(e,Array.isArray(w)?w:[w],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=$r(n.__e,t,n,r,o,i,s,c);(u=cr.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),cr.__e(e,t,n)}}function Ur(e,t){cr.__c&&cr.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){cr.__e(e,t.__v)}}))}function $r(e,t,n,r,o,i,s,a){var c,u,l,d=n.props,f=t.props,p=t.type,h=0;if("svg"===p&&(o=!0),null!=i)for(;h<i.length;h++)if((c=i[h])&&"setAttribute"in c==!!p&&(p?c.localName===p:3===c.nodeType)){e=c,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,a=!1}if(null===p)d===f||a&&e.data===f||(e.data=f);else{if(i=i&&ar.call(e.childNodes),u=(d=n.props||fr).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(d={},h=0;h<e.attributes.length;h++)d[e.attributes[h].name]=e.attributes[h].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||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,a),l)t.__k=[];else if(h=t.props.children,Ir(e,Array.isArray(h)?h:[h],t,n,r,o&&"foreignObject"!==p,i,s,i?i[0]:n.__k&&wr(n,0),a),null!=i)for(h=i.length;h--;)null!=i[h]&&vr(i[h]);a||("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 Dr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){cr.__e(e,n)}}function Rr(e,t,n){var r,o;if(cr.unmount&&cr.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Dr(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){cr.__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||vr(e.__e),e.__e=e.__d=void 0}function Nr(e,t,n){return this.constructor(e,n)}function Lr(e,t,n){var r,o,i;cr.__&&cr.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],jr(t,e=(!r&&n||t).__k=br(gr,null,[e]),o||fr,fr,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),Ur(i,e)}ar=pr.slice,cr={__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,_r.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),kr(this))},_r.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),kr(this))},_r.prototype.render=gr,lr=[],xr.__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 Wr({children:e,className:t}){return br("div",{className:t},br("div",{style:Br.Darken}),br("div",{style:Br.DialogOuter},br("div",{style:Br.DialogInner},e)))}var Mr,Fr,Kr,Hr,Vr=0,zr=[],qr=[],Gr=cr.__b,Jr=cr.__r,Yr=cr.diffed,Zr=cr.__c,Xr=cr.unmount;function Qr(e,t){cr.__h&&cr.__h(Fr,e,Vr||t),Vr=0;var n=Fr.__H||(Fr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:qr}),n.__[e]}function eo(e){return Vr=1,function(e,t,n){var r=Qr(Mr++,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=Fr,!Fr.u)){Fr.u=!0;var o=Fr.shouldComponentUpdate;Fr.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 to(e){return Vr=5,function(e,t){var n=Qr(Mr++,7);return so(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function no(){for(var e;e=zr.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(oo),e.__H.__h.forEach(io),e.__H.__h=[]}catch(t){e.__H.__h=[],cr.__e(t,e.__v)}}cr.__b=function(e){Fr=null,Gr&&Gr(e)},cr.__r=function(e){Jr&&Jr(e),Mr=0;var t=(Fr=e.__c).__H;t&&(Kr===Fr?(t.__h=[],Fr.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=qr,e.__N=e.i=void 0}))):(t.__h.forEach(oo),t.__h.forEach(io),t.__h=[])),Kr=Fr},cr.diffed=function(e){Yr&&Yr(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==zr.push(t)&&Hr===cr.requestAnimationFrame||((Hr=cr.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),ro&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);ro&&(t=requestAnimationFrame(n))})(no)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==qr&&(e.__=e.__V),e.i=void 0,e.__V=qr}))),Kr=Fr=null},cr.__c=function(e,t){t.some((function(e){try{e.__h.forEach(oo),e.__h=e.__h.filter((function(e){return!e.__||io(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],cr.__e(n,e.__v)}})),Zr&&Zr(e,t)},cr.unmount=function(e){Xr&&Xr(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{oo(e)}catch(e){t=e}})),t&&cr.__e(t,n.__v))};var ro="function"==typeof requestAnimationFrame;function oo(e){var t=Fr,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Fr=t}function io(e){var t=Fr;e.__c=e.__(),Fr=t}function so(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 co({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=eo({}),a=to(null);return function(e,t){var n=Qr(Mr++,4);!cr.__s&&so(n.__H,t)&&(n.__=e,n.i=t,Fr.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),br(Wr,{className:"dxc-login-dlg"},br(gr,null,br("h3",{style:Br.WindowHeader},e),t.map((e=>br("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)))),br("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>br("label",{style:Br.Label},n?`${n}: `:"",br("input",{ref:0===o?a: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)}))}})))))),br("div",{style:Br.ButtonsDiv},br("button",{type:"submit",style:Br.Button,onClick:()=>o(i)},"Submit"),br("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 lo extends _r{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=l(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?br(co,Object.assign({},t)):null}}function fo(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}function po(e,t){let n=t,o=l(e).pipe(p((e=>n=e)),h({resetOnRefCountZero:()=>y(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 ho=fo((e=>po(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=fo((e=>new o(bt))),vo=fo((e=>po(yo(e._novip).pipe(Xe((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 bo(...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 mo=fo((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}(po(f([vo(e._novip),ho(e._novip)]).pipe(Be((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:bt.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=Ot(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:"*"}:bo(...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 go{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 _o=fo((e=>{const t=yo(e._novip).pipe(Xe((t=>n((()=>e.members.where({email:t.email||""}).toArray()))))),r=mo(e._novip),o=vo(e._novip);return po(f([t,o,r]).pipe(Be((([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 m(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return m(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function wo(e){return"rlm~"+e}function So(e){return e.startsWith("rlm~")?e.substr(4):null}const ko={nameSuffix:!0};function xo(t){const r=t.name,i=yo(t),c=[];let u=!1,p=null;t.on("ready",(t=>m(this,void 0,void 0,(function*(){try{yield function(t){var r,o,v,b,g,_,w;return m(this,void 0,void 0,(function*(){h=!1;const S=wn(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(r=S.cloud.options)||void 0===r?void 0:r.customLoginGui)||c.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Lr(br(lo,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Lr(br(lo,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),S.cloud.isServiceWorkerDB||c.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Xe((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return Mn.value?r.pipe(Fe(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(Fe(4e3));default:return r}})));return f([n,e.syncStateChangedEvent.pipe(Ze({phase:"initial"})),Fn]).pipe(Be((([t,n,r])=>{let{phase:o,error:i,progress:s}=n,a=t;return"error"===o&&(a="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(a="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(a="connecting"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:un?a:"offline"}})))}(S).subscribe(t.cloud.syncState)),S.tables.every((e=>e.core))||On();const k="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],x=yield S.transaction("rw",S.$syncState,(()=>m(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(u){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,yield S.$syncState.put(e,"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&&!In?(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&&In?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),S.cloud.usingServiceWorker=!1),sr(r,S.cloud.options),sr(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 m(this,void 0,void 0,(function*(){console.debug("Performing initial sync"),yield hn(e,t,n,{isInitialSync:!0}),console.debug("Done initial sync")}))}(S,S.cloud.options,S.cloud.schema),S.setInitiallySynced(!0)),y(),S.cloud.isServiceWorkerDB||(c.push(n((()=>S.getCurrentUser())).subscribe(i)),c.push(n((()=>S.getPersistedSyncState())).subscribe(S.cloud.persistedSyncState)),yield f([i.pipe(Ye(1),Ve(1)),S.cloud.persistedSyncState.pipe(Ye(1),Ve(1))]).toPromise()),(null===(v=S.cloud.options)||void 0===v?void 0:v.requireAuth)&&(yield vt(S)),p&&p.stop(),p=null,y(),S.cloud.usingServiceWorker&&(null===(b=S.cloud.options)||void 0===b?void 0:b.databaseUrl)?(rt(S,"push").catch((()=>{})),function(e){var t;return m(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=ir(S,S.cloud.options,S.cloud.schema),p.start(),ot(S,"push")),y(),S.cloud.isServiceWorkerDB||c.push(s(self,"online").subscribe((()=>{console.debug("online!"),S.syncStateChangedEvent.next({phase:"not-in-sync"}),ot(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)||En||c.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(Je((e=>e)),Xe((()=>e.getPersistedSyncState())),Je((e=>e&&e.serverRevision)),Be((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Je((e=>null==e?void 0:e.serverRevision)),Ve(1),Xe((t=>e.cloud.currentUser.pipe(Be((e=>[e,t]))))),Xe((([e,t])=>Fn.pipe(Be((n=>[n?e:null,t]))))),Xe((([e,t])=>m(this,void 0,void 0,(function*(){return[e,yield St(t)]})))),Xe((([t,r])=>t?new Yn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,r,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):l([]))),Ue((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Xe((()=>m(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield ft(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})))),Xe((()=>t())))):d(n))),Ue((n=>(e.cloud.webSocketStatus.next("error"),l(Qn(n)).pipe(Xe((()=>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 y(){if(h)throw new e.DatabaseClosedError}var v;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(t,(()=>{c.forEach((e=>e.unsubscribe())),h=!0,p&&p.stop(),p=null,i.next(bt)})),t.cloud={version:"4.0.1-beta.32",options:Object.assign({},ko),schema:null,get currentUserId(){return i.value.userId||bt.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 m(this,void 0,void 0,(function*(){const n=wn(t);yield n.cloud.sync(),yield vt(n,e)}))},invites:_o(t),roles:ho(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),u=!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)}`,wn(t).reconfigure()),sr(t.cloud.schema,t.cloud.options)},sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){return m(this,void 0,void 0,(function*(){void 0===e&&(e=!0);const o=wn(t);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(ot(o,r),e){const e=yield o.cloud.persistedSyncState.pipe(Je((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),Ve(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield er(o)){const t=o.cloud.persistedSyncState.value;ot(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),yield l(n((()=>m(this,void 0,void 0,(function*(){const e=yield er(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(Je((e=>!e)),Ve(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=mo(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new go(i.permissions,n,o===e.cloud.currentUserId||r===e.cloud.currentUserId):new go({},n,!r||r===e.cloud.currentUserId)},a=i.pipe(Be(s));return a.getValue=()=>s(i.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>Wn(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return Un(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:wn(t)})),t.use((v=wn(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 a=e.trans;if((null===(o=null===(r=v.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type))for(const t of e.values){t.owner||(t.owner=a.currentUser.userId),t.realmId||(t.realmId=a.currentUser.userId);const r=null===(s=(i=n.schema.primaryKey).extractKey)||void 0===s?void 0:s.call(i,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}return n.mutate(e)}})}})})),t.use($n(wn(t)))}xo.version="4.0.1-beta.32",e.Cloud=xo;export{xo as default,xo as dexieCloud,So as getTiedObjectId,wo as getTiedRealmId};
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 a,merge as c,Subscription as u,from as l,throwError as d,combineLatest as f,map as p,share as h,timer as y}from"rxjs";var v=function(e,t){return v=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},v(e,t)};function b(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}v(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function m(e,t,n,r){return new(n||(n=Promise))((function(o,i){function s(e){try{c(r.next(e))}catch(e){i(e)}}function a(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(s,a)}c((r=r.apply(e,t||[])).next())}))}function g(e,t){var n,r,o,i,s={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:a(0),throw:a(1),return:a(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function a(i){return function(a){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return s.label++,{value:i[1],done:!1};case 5:s.label++,r=i[1],i=[0];continue;case 7:i=s.ops.pop(),s.trys.pop();continue;default:if(!(o=s.trys,(o=o.length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){s=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){s.label=i[1];break}if(6===i[0]&&s.label<o[1]){s.label=o[1],o=i;break}if(o&&s.label<o[2]){s.label=o[2],s.ops.push(i);break}o[2]&&s.ops.pop(),s.trys.pop();continue}i=t.call(e,s)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,a])}}}function _(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 w(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 S(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 k(e){return this instanceof k?(this.v=e,this):new k(e)}function x(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,o=n.apply(e,t||[]),i=[];return r={},s("next"),s("throw"),s("return"),r[Symbol.asyncIterator]=function(){return this},r;function s(e){o[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||a(e,t)}))})}function a(e,t){try{!function(e){e.value instanceof k?Promise.resolve(e.value.v).then(c,u):l(i[0][2],e)}(o[e](t))}catch(e){l(i[0][3],e)}}function c(e){a("next",e)}function u(e){a("throw",e)}function l(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function I(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=_(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)}))}}}function E(e){if(!e)throw new Error("Assertion Failed")}const O={}.hasOwnProperty;function T(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){E("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)T(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var s=t.substr(0,i),a=t.substr(i+1);if(""===a)void 0===n?Array.isArray(e)?isNaN(parseInt(s))||e.splice(parseInt(s),1):delete e[s]:e[s]=n;else{var c=e[s];c&&function(e,t){return O.call(e,t)}(e,s)||(c=e[s]={}),T(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const A="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=C)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function C(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function P(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>P(e)))&&e.every(j))}function j(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(j)}function U(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))T(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 $(e,t){for(const{table:n,muts:r}of t)for(const t of r)U(e,n,t)}function D(e){return"function"==typeof e}function R(e){return function(t){if(function(e){return D(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 N=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function L(e){return D(null==e?void 0:e.then)}function B(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 W=B((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 M(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var F=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=_(i),a=s.next();!a.done;a=s.next()){a.value.remove(this)}}catch(t){e={error:t}}finally{try{a&&!a.done&&(t=s.return)&&t.call(s)}finally{if(e)throw e.error}}else i.remove(this);var c=this.initialTeardown;if(D(c))try{c()}catch(e){o=e instanceof W?e.errors:[e]}var u=this._finalizers;if(u){this._finalizers=null;try{for(var l=_(u),d=l.next();!d.done;d=l.next()){var f=d.value;try{H(f)}catch(e){o=null!=o?o:[],e instanceof W?o=S(S([],w(o)),w(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=l.return)&&r.call(l)}finally{if(n)throw n.error}}}if(o)throw new W(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)H(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)&&M(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&M(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function K(e){return e instanceof F||e&&"closed"in e&&D(e.remove)&&D(e.add)&&D(e.unsubscribe)}function H(e){D(e)?e():e.unsubscribe()}F.EMPTY;var V={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},z={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=z.delegate;return(null==o?void 0:o.setTimeout)?o.setTimeout.apply(o,S([e,t],w(n))):setTimeout.apply(void 0,S([e,t],w(n)))},clearTimeout:function(e){var t=z.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function q(e){z.setTimeout((function(){var t=V.onUnhandledError;if(!t)throw e;t(e)}))}function G(){}var J=Y("C",void 0,void 0);function Y(e,t,n){return{kind:e,value:t,error:n}}var Z=null;var X=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,K(t)&&t.add(n)):n.destination=ie,n}return b(t,e),t.create=function(e,t,n){return new ne(e,t,n)},t.prototype.next=function(e){this.isStopped?oe(function(e){return Y("N",e,void 0)}(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?oe(Y("E",void 0,e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?oe(J,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}(F),Q=Function.prototype.bind;function ee(e,t){return Q.call(e,t)}var te=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){re(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){re(e)}else re(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){re(e)}},e}(),ne=function(e){function t(t,n,r){var o,i,s=e.call(this)||this;D(t)||!t?o={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:s&&V.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&ee(t.next,i),error:t.error&&ee(t.error,i),complete:t.complete&&ee(t.complete,i)}):o=t;return s.destination=new te(o),s}return b(t,e),t}(X);function re(e){q(e)}function oe(e,t){var n=V.onStoppedNotification;n&&z.setTimeout((function(){return n(e,t)}))}var ie={closed:!0,next:G,error:function(e){throw e},complete:G},se="function"==typeof Symbol&&Symbol.observable||"@@observable";function ae(e){return e}function ce(e){return 0===e.length?ae:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)}}var ue=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 X||function(e){return e&&D(e.next)&&D(e.error)&&D(e.complete)}(r)&&K(r)?e:new ne(e,t,n);return function(e){if(V.useDeprecatedSynchronousErrorHandling){var t=!Z;if(t&&(Z={errorThrown:!1,error:null}),e(),t){var n=Z,r=n.errorThrown,o=n.error;if(Z=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=le(t))((function(t,r){var o=new ne({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[se]=function(){return this},e.prototype.pipe=function(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return ce(e)(this)},e.prototype.toPromise=function(e){var t=this;return new(e=le(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 le(e){var t;return null!==(t=null!=e?e:V.Promise)&&void 0!==t?t:Promise}function de(e){return D(e[se])}function fe(e){return Symbol.asyncIterator&&D(null==e?void 0:e[Symbol.asyncIterator])}function pe(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 he="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function ye(e){return D(null==e?void 0:e[he])}function ve(e){return x(this,arguments,(function(){var t,n,r;return g(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,k(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,k(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,k(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 be(e){return D(null==e?void 0:e.getReader)}function me(e){if(e instanceof ue)return e;if(null!=e){if(de(e))return o=e,new ue((function(e){var t=o[se]();if(D(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(N(e))return r=e,new ue((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(L(e))return n=e,new ue((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,q)}));if(fe(e))return ge(e);if(ye(e))return t=e,new ue((function(e){var n,r;try{for(var o=_(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(be(e))return ge(ve(e))}var t,n,r,o;throw pe(e)}function ge(e){return new ue((function(t){(function(e,t){var n,r,o,i;return m(this,void 0,void 0,(function(){var s,a;return g(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=I(e),c.label=1;case 1:return[4,n.next()];case 2:if((r=c.sent()).done)return[3,4];if(s=r.value,t.next(s),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return a=c.sent(),o={error:a},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(i=n.return)?[4,i.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(o)throw o.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}}))}))})(e,t).catch((function(e){return t.error(e)}))}))}function _e(e,t,n,r,o){return new we(e,t,n,r,o)}var we=function(e){function t(t,n,r,o,i,s){var a=e.call(this,t)||this;return a.onFinalize=i,a.shouldUnsubscribe=s,a._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,a._error=o?function(e){try{o(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,a._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,a}return b(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}(X),Se=function(e){function t(t,n){return e.call(this)||this}return b(t,e),t.prototype.schedule=function(e,t){return this},t}(F),ke={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=ke.delegate;return(null==o?void 0:o.setInterval)?o.setInterval.apply(o,S([e,t],w(n))):setInterval.apply(void 0,S([e,t],w(n)))},clearInterval:function(e){var t=ke.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},xe=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 b(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),ke.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;ke.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,M(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(Se),Ie={now:function(){return(Ie.delegate||Date).now()},delegate:void 0},Ee=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=Ie.now,e}(),Oe=new(function(e){function t(t,n){void 0===n&&(n=Ee.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return b(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}(Ee))(xe),Te=Oe;function Ae(e){return e&&D(e.schedule)}function Ce(e){return e instanceof Date&&!isNaN(e)}function Pe(e){return Ae((t=e)[t.length-1])?e.pop():void 0;var t}function je(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 Ue(e){return R((function(t,n){var r,o=null,i=!1;o=t.subscribe(_e(n,void 0,void 0,(function(s){r=me(e(s,Ue(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):i=!0}))),i&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function $e(e,t){return void 0===t&&(t=0),R((function(n,r){n.subscribe(_e(r,(function(n){return je(r,e,(function(){return r.next(n)}),t)}),(function(){return je(r,e,(function(){return r.complete()}),t)}),(function(n){return je(r,e,(function(){return r.error(n)}),t)})))}))}function De(e,t){return void 0===t&&(t=0),R((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function Re(e,t){if(!e)throw new Error("Iterable cannot be null");return new ue((function(n){je(n,t,(function(){var r=e[Symbol.asyncIterator]();je(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Ne(e,t){if(null!=e){if(de(e))return function(e,t){return me(e).pipe(De(t),$e(t))}(e,t);if(N(e))return function(e,t){return new ue((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(L(e))return function(e,t){return me(e).pipe(De(t),$e(t))}(e,t);if(fe(e))return Re(e,t);if(ye(e))return function(e,t){return new ue((function(n){var r;return je(n,t,(function(){r=e[he](),je(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 D(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(be(e))return function(e,t){return Re(ve(e),t)}(e,t)}throw pe(e)}function Le(e,t){return t?Ne(e,t):me(e)}function Be(e,t){return R((function(n,r){var o=0;n.subscribe(_e(r,(function(n){r.next(e.call(t,n,o++))})))}))}function We(e,t,n){return void 0===n&&(n=1/0),D(t)?We((function(n,r){return Be((function(e,o){return t(n,e,r,o)}))(me(e(n,r)))}),n):("number"==typeof t&&(n=t),R((function(t,r){return function(e,t,n,r,o,i,s,a){var c=[],u=0,l=0,d=!1,f=function(){!d||c.length||u||t.complete()},p=function(e){return u<r?h(e):c.push(e)},h=function(e){i&&t.next(e),u++;var a=!1;me(n(e,l++)).subscribe(_e(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){a=!0}),void 0,(function(){if(a)try{u--;for(var e=function(){var e=c.shift();s?je(t,s,(function(){return h(e)})):h(e)};c.length&&u<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(_e(t,p,(function(){d=!0,f()}))),function(){null==a||a()}}(t,r,e,n)})))}function Me(){return void 0===(e=1)&&(e=1/0),We(ae,e);var e}function Fe(e,t){return void 0===t&&(t=Oe),R((function(n,r){var o=null,i=null,s=null,a=function(){if(o){o.unsubscribe(),o=null;var e=i;i=null,r.next(e)}};function c(){var n=s+e,i=t.now();if(i<n)return o=this.schedule(void 0,n-i),void r.add(o);a()}n.subscribe(_e(r,(function(n){i=n,s=t.now(),o||(o=t.schedule(c,e),r.add(o))}),(function(){a(),r.complete()}),void 0,(function(){i=o=null})))}))}function Ke(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];return Me()(Le(e,Pe(e)))}var He=new ue((function(e){return e.complete()}));function Ve(e){return e<=0?function(){return He}:R((function(t,n){var r=0;t.subscribe(_e(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function ze(e,t){return t?function(n){return Ke(t.pipe(Ve(1),R((function(e,t){e.subscribe(_e(t,G))}))),n.pipe(ze(e)))}:We((function(t,n){return e(t,n).pipe(Ve(1),function(e){return Be((function(){return e}))}(t))}))}function qe(e,t){void 0===t&&(t=Oe);var n=function(e,t,n){void 0===e&&(e=0),void 0===n&&(n=Te);var r=-1;return null!=t&&(Ae(t)?n=t:r=t),new ue((function(t){var o=Ce(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 ze((function(){return n}))}function Ge(e,t){return e===t}function Je(e,t){return R((function(n,r){var o=0;n.subscribe(_e(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function Ye(e){return Je((function(t,n){return e<=n}))}function Ze(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Pe(e);return R((function(t,r){(n?Ke(e,t,n):Ke(e,t)).subscribe(r)}))}function Xe(e,t){return R((function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(_e(r,(function(n){null==o||o.unsubscribe();var s=0,c=i++;me(e(n,c)).subscribe(o=_e(r,(function(e){return r.next(t?t(n,e,c,s++):e)}),(function(){o=null,a()})))}),(function(){s=!0,a()})))}))}function Qe(e,t,n){var r=D(e)||t||n?{next:e,error:t,complete:n}:e;return r?R((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(_e(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)})))})):ae}var et=B((function(e){return function(t){void 0===t&&(t=null),e(this),this.message="Timeout has occurred",this.name="TimeoutError",this.info=t}}));function tt(e){throw new et(e)}let nt=!1;function rt(e,t){return m(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){nt||(console.debug("Dexie Cloud: Could not register sync event",e),nt=!0)}}))}function ot(e,t){e.cloud.usingServiceWorker?rt(e,t):e.localSyncEvent.next({purpose:t})}const it="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},st="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 at(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 ct(e,t,...n){return at(e,{type:"message-alert",title:t,alerts:n,fields:{}})}function ut(e,t,n){return m(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-\.]+@([\w-]+\.)+[\w-]{2,10}$/.test(r);)r=(yield at(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 lt(e,t,n){return m(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 at(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function dt(e,t,n,r,o){return m(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 ft(e,t):yield function(e,t,n,r){return m(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=st(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 at(n,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:o.alerts})),e}catch(e){throw yield ct(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 ft(e,t){return m(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=st(i),a={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:s,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(a),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const u=yield c.json();return t.accessToken=u.accessToken,t.accessTokenExpiration=u.accessTokenExpiration?new Date(u.accessTokenExpiration):void 0,t}))}const pt=new WeakMap;class ht{constructor(e,t){pt.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new ht(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return m(this,void 0,void 0,(function*(){pt.get(this).table("$logins").put(this)}))}}class yt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function vt(e,t){return m(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 ht(e,{claims:{},lastLogin:new Date(0)});yield dt(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 m(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 ut(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 ut(t,"Enter email address",null==r?void 0:r.email),grant_type:"otp",scopes:["ACCESS_DB"],public_key:n};const a=yield fetch(`${s}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==a.status){const e=yield a.text();throw yield ct(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new yt(a,e)}const c=yield a.json();if("tokens"===c.type)return c;if("otp"===i.grant_type){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield lt(t,i.email);i.otp=e||"",i.otp_id=c.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 lt(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 ct(t,"OTP Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new yt(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 m(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>m(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),ot(e,"pull")}))}const bt={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(bt),Object.freeze(bt.claims)}catch(e){}const mt={},gt="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;gt&&gt.ready.then((e=>mt.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 _t{constructor(e){this.name=e}subscribe(e){if(!gt)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 gt.addEventListener("message",t),()=>gt.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}))):mt.registration&&(null===(t=mt.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}class wt extends r{constructor(e){const t="undefined"==typeof BroadcastChannel?new _t(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 _t?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 _t?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 St({realms:e,inviteRealms:t}){return m(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 st(o)}))}function kt(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 xt(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 Et=[].concat;function Ot(e){return Et.apply([],e)}function Tt(e,t,{since:n={},limit:r=1/0}={}){return m(this,void 0,void 0,(function*(){const t=Ot(yield Promise.all(e.map((e=>m(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 At(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:Ct}={};const Pt={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 jt(...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 Pt;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,Ct.call(o).slice(8,-1)),a=Object.entries(t).find((([t,n])=>{var r,o;return null!==(o=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,s))&&void 0!==o?o:t===s}));return i=null==a?void 0:a[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:Pt),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 Ut={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 $t={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 Dt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Rt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Nt={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Lt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Bt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"==typeof global?global:void 0;var Wt=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce(((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const o=Bt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Mt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Ht[e[n]];return t}(st(e))}function Ft(e){return it(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=Kt[e[n]];return t}(e))}const Kt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},Ht={};for(const e of Object.keys(Kt))Ht[Kt[e]]=e;var Vt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Mt(e)}),revive:({v:e})=>{const t=Ft(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class zt{constructor(e,t){this.buf=e,this.type=t}}function qt(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 Gt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Jt={Blob:{test:(e,t)=>"Blob"===t||e instanceof zt,replace:e=>({$t:"Blob",v:st(e instanceof zt?e.buf:Gt(qt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=it(t);return void 0!==typeof Blob?new Blob([n]):new zt(n.buffer,e)}}};const Yt={...$t,...Dt,...Rt,...Nt,...Lt,...Wt,...Vt,...Jt};function Zt(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 Xt={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Qt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class en{toString(){return this.v}constructor(e){this.v=e}}const tn=Object.assign(Object.assign({},Xt),Qt?{}:{bigint:{test:e=>e instanceof en,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new en(e)}}),nn=jt(Yt,tn),rn=function(...e){const t=jt(Yt,Ut,...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 Zt(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 Zt(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)}}}(tn);function on(t,n,r){const o=[];for(let i of r){const{table:r,muts:s}=i,a=t.tables.find((e=>e.name===r));if(!a)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=a;let u=i;s.forEach(((t,r)=>{const o=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,s)=>{if(Array.isArray(t)){u===i&&(u=sn(i,o));const n=u.muts[r],a=JSON.stringify(t);n.keys[s]=a,o&&e.setByKeyPath(n.values[s],c.keyPath,a)}else if("#"===t[0]){u===i&&(u=sn(i,o));const a=u.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const l=`${t}:${n.userId}`;a.keys[s]=l,o&&e.setByKeyPath(a.values[s],c.keyPath,l)}}))})),o.push(u)}return o}function sn(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 an(e,t,n,r,o,i,s,a){return m(this,void 0,void 0,(function*(){const c={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield function(e){var t,n;return m(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),{accessToken:o,accessTokenExpiration:i,refreshToken:s,refreshTokenExpiration:a,claims:c}=r;if(!o)return;if((null!==(t=null==i?void 0:i.getTime())&&void 0!==t?t:1/0)>Date.now())return o;if(!s)throw new Error("Refresh token missing");if((null!==(n=null==a?void 0:a.getTime())&&void 0!==n?n:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield ft(e.cloud.options.databaseUrl,r);return yield e.table("$logins").update(c.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration}),u.accessToken}))}(r);u&&(c.Authorization=`Bearer ${u}`);const l={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:on(r.dx.core.schema,a,e)};console.debug("Sync request",l),r.syncStateChangedEvent.next({phase:"pushing"});const d=yield fetch(`${o}/sync`,{method:"post",headers:c,body:nn.stringify(l)});if(r.syncStateChangedEvent.next({phase:"pulling"}),!d.ok)throw new yt(d);if("application/x-bison"===d.headers.get("content-type"))return rn.fromBinary(yield d.blob());{const e=yield d.text();return nn.parse(e)}}))}function cn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let un=!1;function ln(e,t,n,r){return m(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 dn(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 fn(n,r,o){return m(this,void 0,void 0,(function*(){const i=yield n.bulkGet(r),s=[],a=[];r.forEach(((r,c)=>{const u=i[c];if(u){for(const[i,s]of Object.entries(o[c]))if(i===n.schema.primKey.keyPath){if(0!==t(s,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(u,i,s);s.push(r),a.push(u)}})),yield null==n.schema.primKey.keyPath?n.bulkPut(a,s):n.bulkPut(a)}))}function pn(t,n){return m(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 fn(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(un=navigator.onLine,self.addEventListener("online",(()=>un=!0)),self.addEventListener("offline",(()=>un=!1)));function hn(e,t,n,r){return yn.apply(this,arguments).then((()=>{(null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"})})).catch((o=>m(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):(console.debug("Error from _sync",{isOnline:un,syncOptions:r,error:o}),un&&(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 hn(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:un?"error":"offline",error:o}),Promise.reject(o)))}))))}function yn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;return m(this,void 0,void 0,(function*(){if(i||console.debug("SYNC STARTED",{isInitialSync:r,purpose:s}),!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:c}=t,u=yield e.getCurrentUser(),l=u.isLoggedIn?kt(e):[],d=l.map((t=>e.table(xt(t.name)))),f=yield e.getPersistedSyncState(),p=!r&&u.isLoggedIn,h=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return kt(e).filter((e=>!n.includes(e.name)))}(e,f):[];cn(o);const y=h.length>0;if(y){if(i)return!0;yield e.transaction("rw",h,(e=>m(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return m(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!==bt.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!==bt.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==bt.userId||(e.owner=t.userId),e.realmId&&e.realmId!==bt.userId||(e.realmId=t.userId))})))}))}(h,u,null==f?void 0:f.realms)})))),cn(o)}const[v,b,g]=yield e.transaction("r",e.tables,(()=>m(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield Tt(d);if(cn(o),y){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],s=yield function(e,t,n,r){return m(this,void 0,void 0,(function*(){const o=`upload-${At(8)}`;if(t.isLoggedIn&&e.length>0){const i=new Set(r||[]);return(yield Promise.all(e.map((e=>m(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],a=(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||"")&&P(t)})),c=yield a.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.map(r),userId:t.userId,txid:o};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))))).filter((e=>e.muts.length>0))}return[]}))}(h,u,n,e);return cn(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=dn(v,null==b?void 0:b.latestRevisions),S=(null==b?void 0:b.clientIdentity)||A(16);cn(o);const k=yield an(v,b,g,e,c,n,S,u);console.debug("Sync response",k);const x=yield e.transaction("rw",e.tables,(t=>m(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 Tt(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()])}dn(r,w),yield ln(e,n,w,k.serverRevision);const o=yield e.getPersistedSyncState();yield function(e,t,n){return m(this,void 0,void 0,(function*(){const r=new Set,o=new Set,i=n?n.realms:[],s=n?n.inviteRealms:[],a=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)a.has(e)||(o.add(e),c.has(e)||r.add(e));for(const e of s.concat(i))c.has(e)||r.add(e);if(r.size>0||o.size>0){const t=kt(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=l.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=vn(k.changes,r);return yield pn(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 yn(e,t,n,{isInitialSync:r,cancelToken:o}))}))}function vn(e,t){const n={};$(n,e);const r={};return $(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(o=e[i])||void 0===o?void 0:o[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(a.mod))T(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(a.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=A(16));const 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 bn(t){const n=[],r=new o(!0),i=new o(null);let s=!1,a=0,c=[0,0,0,0,0,0,0,0,0,Date.now()];return i.subscribe((()=>m(this,void 0,void 0,(function*(){if(!s&&n.length>0){s=!0,c.shift(),c.push(Date.now()),r.next(!1);try{yield function(){var r,o,i;return m(this,void 0,void 0,(function*(){for(;n.length>0;){const s=n.shift();try{yield t.cloud.syncState.pipe(Je((({phase:e})=>"in-sync"===e||"error"===e)),Ve(1)).toPromise(),console.debug("processing msg",s);const n=t.cloud.persistedSyncState.value;if(!s)continue;switch(s.type){case"token-expired":console.debug("WebSocket observable: Token expired. Refreshing token...");const a=t.cloud.currentUser.value,c=yield ft(t.cloud.options.databaseUrl,a);yield t.table("$logins").update(a.userId,{accessToken:c.accessToken,accessTokenExpiration:c.accessTokenExpiration});break;case"realm-added":case"realm-accepted":case"realms-changed":ot(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),ot(t,"pull");break;case"changes":if(console.debug("changes"),"error"===(null===(i=t.cloud.syncState.value)||void 0===i?void 0:i.phase)){ot(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>m(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||ot(t,"pull"));const a=yield e.waitFor(St(o));if(console.debug("ourRealmSetHash",a),a!==s.realmSetHash)return console.debug("not same realmSetHash",s.realmSetHash),void ot(t,"pull");let c=[];if(i.isLoggedIn){const e=kt(t).map((e=>t.table(xt(e.name))));c=yield Tt(e),console.debug("msg queue: client changes",c)}if(s.changes.length>0){const e=vn(s.changes,c);console.debug("applying filtered server changes",e),yield pn(e,t)}o.latestRevisions=dn(c,o.latestRevisions),o.serverRevision=s.newRev,console.debug("Updating baseRefs",o.latestRevisions),yield ln(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{c[c.length-1]-c[0]<1e4&&(Date.now()-a<5e3?(console.warn("Slowing down websocket loop for one minute"),a=Date.now()+6e4,yield new Promise((e=>setTimeout(e,6e4)))):(console.warn("Slowing down websocket loop for 10 seconds"),a=Date.now()+1e4,yield new Promise((e=>setTimeout(e,1e4))))),s=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),i.next(null)},readyToServe:r}}const mn=new WeakMap,gn={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let _n=0;function wn(e){"vip"in e&&(e=e.vip);let t=mn.get(e.cloud);if(!t){const n=new i;let r=new wt(`syncstatechanged-${e.name}`);n.id=++_n;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))||bt)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){r=new wt(`syncstatechanged-${e.name}`)}};Object.assign(t,s),t.messageConsumer=bn(t),mn.set(e.cloud,t)}return t}const Sn="undefined"!=typeof InstallTrigger,kn="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),xn=kn?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,In=kn&&xn<=605||Sn;const En="undefined"!=typeof self&&"clients"in self&&!self.document;function On(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:Tn}={};function An(e){return Tn.call(e).slice(8,-1)}function Cn(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const Pn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let jn=0;function Un(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();jn>=o?++jn:jn=o,r[0]=jn/1099511627776,r[1]=jn/4294967296,r[2]=jn/16777216,r[3]=jn/65536,r[4]=jn/256,r[5]=jn;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+Mt(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 a=null===(i=t.cloud.schema)||void 0===i?void 0:i[r];if(null==a?void 0:a.generatedGlobalId){if((null===(s=t.cloud.options)||void 0===s?void 0:s.databaseUrl)&&!t.initiallySynced){const e=Cn(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 a=Cn(o.schema.primaryKey,n);return a.forEach(((c,u)=>{if(void 0===c){const r=n.values[u].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[u]=Un(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[u]=e.deepClone(s[u]),e.setByKeyPath(s[u],o.schema.primaryKey.keyPath,a[u]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (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:a,values:s||n.values}))}(n,a.idPrefix)}if(null==a?void 0:a.markedForSync){Cn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!P(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 Dn=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 Nn(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 Ln=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){On()}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=>xt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=At(16),i.currentUser=e.value,Ln.value.add(i),Ln.next(Ln.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),Ln.value.delete(i),Ln.next(Ln.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"),rt(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"+ ++Dn;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:Nn(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,c;const u=n.trans;return u.txid?u.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(c=u.currentUser)||void 0===c?void 0:c.isLoggedIn)?"deleteRange"===n.type?r.query({query:{range:n.range,index:i.primaryKey},trans:n.trans,values:!1}).then((e=>a({type:"delete",keys:e.result,trans:n.trans,criteria:{index:null,range:n.range}}))):a(n):r.mutate(n):r.mutate(n)}}));function a(e){const t=e.trans;t.mutationsAdded=!0;const{txid:n,currentUser:{userId:o}}=t,{type:i}=e;return r.mutate(e).then((r=>{const{numFailures:a,failures:c}=r;let u="delete"===i?e.keys:r.results,l="values"in e?e.values:[],d="updates"in e&&e.updates;a&&(u=u.filter(((e,t)=>!c[t])),l=l.filter(((e,t)=>!c[t])));const f=Date.now(),p="delete"===e.type?{type:"delete",ts:f,keys:u,criteria:e.criteria,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:f,keys:u,txid:n,userId:o,values:l}:e.criteria&&e.changeSpec?{type:"modify",ts:f,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:n,userId:o}:d?{type:"update",ts:f,keys:d.keys,changeSpecs:d.changeSpecs,txid:n,userId:o}:{type:"upsert",ts:f,keys:u,values:l,txid:n,userId:o};return u.length>0||"criteria"in e&&e.criteria?s.mutate({type:"add",trans:t,values:[p]}).then((()=>r)):r}))}}})}}}function Wn(e,t){return function(n,r){const o=Object.assign(Object.assign({},gn),n),i=t.cloud.schema||(t.cloud.schema={}),s=new Set;Object.keys(o).forEach((e=>{const t=o[e],n=i[e]||(i[e]={});null!=t?(/^\@/.test(t)&&(o[e]=o[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,o=e.length;t<o&&n.length<3;++t)(Pn.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,o,i;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)o=n,r=(1&(i=e)?o[0].toUpperCase():o[0].toLowerCase())+(2&i?o[1].toUpperCase():o[1].toLowerCase())+(4&i?o[2].toUpperCase():o[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,s),s.add(n.idPrefix)),/^\$/.test(e)||(o[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,o[`$${e}_mutations`]=null)}));return e.call(this,o,r)}}const Mn=new o(!0),Fn=new o(!0);var Kn,Hn;Mn.pipe(Xe((e=>e?a(!0):a(!1).pipe(qe(2e4)))),(void 0===Hn&&(Hn=ae),Kn=null!=Kn?Kn:Ge,R((function(e,t){var n,r=!0;e.subscribe(_e(t,(function(e){var o=Hn(e);!r&&Kn(n,o)||(r=!1,n=o,t.next(e))})))})))).subscribe(Fn);const Vn="undefined"!=typeof document?s(document,"visibilitychange"):a({}),zn=Vn.pipe(Je((()=>"hidden"===document.visibilityState))),qn=Vn.pipe(Je((()=>"visible"===document.visibilityState))),Gn="undefined"!=typeof window?c(qn,s(window,"mousedown"),s(window,"mousemove"),s(window,"keydown"),s(window,"wheel"),s(window,"touchmove")):a({});"undefined"!=typeof document&&c(a(!0),zn,Gn).pipe(Be((()=>"visible"===document.visibilityState)),Qe((e=>{Mn.value!==e&&Mn.next(e)})),Xe((e=>e?a(0).pipe(qe(16e4),Qe((()=>Mn.next(!1)))):a(0)))).subscribe((()=>{}));class Jn extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class Yn extends r{constructor(e,t,n,r,o,i,s,a){super((c=>new Xn(e,t,n,r,s,a,c,o,i)))}}let Zn=0;class Xn extends u{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++Zn,this.reconnecting=!1,console.debug("New WebSocket Connection",this.id,o?"authorized":"unauthorized"),this.databaseUrl=e,this.rev=t,this.realmSetHash=n,this.clientIdentity=r,this.token=o,this.tokenExpiration=i,this.subscriber=s,this.lastUserActivity=new Date,this.messageProducer=a,this.messageProducerSubscription=null,this.webSocketStatus=c,this.connect()}teardown(){console.debug("Teardown WebSocket Connection",this.id),this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null,this.messageProducerSubscription&&(this.messageProducerSubscription.unsubscribe(),this.messageProducerSubscription=null)}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return m(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 Jn);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>m(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=nn.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(nn.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}function Qn(e){return m(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 Gn.pipe(Ve(1)).toPromise(),console.debug("someone did something!")}))}function er(e){var t;return m(this,void 0,void 0,(function*(){return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield hn(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const tr=At(16);function nr(e,t,r,o,{awaitRemoteJob:i}={}){return m(this,void 0,void 0,(function*(){const s=e.table(r);if(yield function o(){return m(this,void 0,void 0,(function*(){if(yield e.transaction("rw!",r,(()=>m(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:tr,started:new Date,heartbeat:new Date},t),!0):(yield s.add({nodeId:tr,started:new Date,heartbeat:new Date},t),!0)})))))return!0;if(i)try{const e=l(n((()=>s.get(t)))).pipe(function(e,t){var n=Ce(e)?{first:e}:"number"==typeof e?{each:e}:e,r=n.first,o=n.each,i=n.with,s=void 0===i?tt:i,a=n.scheduler,c=void 0===a?null!=t?t:Oe:a,u=n.meta,l=void 0===u?null:u;if(null==r&&null==o)throw new TypeError("No timeout provided.");return R((function(e,t){var n,i,a=null,u=0,d=function(e){i=je(t,c,(function(){try{n.unsubscribe(),me(s({meta:l,lastValue:a,seen:u})).subscribe(t)}catch(e){t.error(e)}}),e)};n=e.subscribe(_e(t,(function(e){null==i||i.unsubscribe(),u++,t.next(a=e),o>0&&d(o)}),void 0,void 0,(function(){(null==i?void 0:i.closed)||null==i||i.unsubscribe(),a=null}))),!u&&d(null!=r?"number"==typeof r?r:+r-c.now():o)}))}(6e4),Je((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===tr&&(e.heartbeat=new Date)}))}),1e3);try{return yield o()}finally{clearInterval(n),yield e.transaction("rw!",r,(()=>m(this,void 0,void 0,(function*(){const e=yield s.get(t);e&&e.nodeId===tr&&(yield s.delete(t))}))))}}}))}const rr=new WeakMap;function or(e,t,n,r){const o=rr.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 or(e,t,n,r)}))}}const i=function(){return m(this,void 0,void 0,(function*(){try{if(e.cloud.isServiceWorkerDB)yield hn(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw E(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield nr(e,"currentSyncWorker","$jobs",(()=>hn(e,t,n,r)))}rr.delete(e),console.debug("Done sync")}catch(t){throw rr.delete(e),console.error("Failed to sync client changes",t),t}}))}();return rr.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}function ir(e,t,n){let r=null,o={cancelled:!1};function i(r,a=1){setTimeout((()=>{or(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:r}).catch((e=>{console.error("error in syncIfPossible()",e),o.cancelled?s():a<3&&setTimeout((()=>i(r,a+1)),6e4*[0,5,15][a])}))}),0)}const s=()=>{console.debug("Stopping LocalSyncWorker"),o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{console.debug("Starting LocalSyncWorker",e.localSyncEvent.id),r=e.localSyncEvent.subscribe((({purpose:e})=>{try{i(e||"pull")}catch(e){console.error("What-the....",e)}}))},stop:s}}function sr(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var ar,cr,ur,lr,dr,fr={},pr=[],hr=/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 vr(e){var t=e.parentNode;t&&t.removeChild(e)}function br(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 mr(e,s,r,o,null)}function mr(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!=cr.vnode&&cr.vnode(i),i}function gr(e){return e.children}function _r(e,t){this.props=e,this.context=t}function wr(e,t){if(null==t)return e.__?wr(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?wr(e):null}function Sr(e){var t,n;if(null!=(e=e.__)&&null!=e.__c){for(e.__e=e.__c.base=null,t=0;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e){e.__e=e.__c.base=n.__e;break}return Sr(e)}}function kr(e){(!e.__d&&(e.__d=!0)&&lr.push(e)&&!xr.__r++||dr!==cr.debounceRendering)&&((dr=cr.debounceRendering)||setTimeout)(xr)}function xr(){for(var e;xr.__r=lr.length;)e=lr.sort((function(e,t){return e.__v.__b-t.__v.__b})),lr=[],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,jr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?wr(o):i,o.__h),Ur(n,o),o.__e!=i&&Sr(o)))}))}function Ir(e,t,n,r,o,i,s,a,c,u){var l,d,f,p,h,y,v,b=r&&r.__k||pr,m=b.length;for(n.__k=[],l=0;l<t.length;l++)if(null!=(p=n.__k[l]=null==(p=t[l])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?mr(null,p,null,null,p):Array.isArray(p)?mr(gr,{children:p},null,null,null):p.__b>0?mr(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=b[l])||f&&p.key==f.key&&p.type===f.type)b[l]=void 0;else for(d=0;d<m;d++){if((f=b[d])&&p.key==f.key&&p.type===f.type){b[d]=void 0;break}f=null}jr(e,p,f=f||fr,o,i,s,a,c,u),h=p.__e,(d=p.ref)&&f.ref!=d&&(v||(v=[]),f.ref&&v.push(f.ref,null,p),v.push(d,p.__c||h,p)),null!=h?(null==y&&(y=h),"function"==typeof p.type&&p.__k===f.__k?p.__d=c=Er(p,c,e):c=Or(e,p,f,b,h,c),"function"==typeof n.type&&(n.__d=c)):c&&f.__e==c&&c.parentNode!=e&&(c=wr(f))}for(n.__e=y,l=m;l--;)null!=b[l]&&("function"==typeof n.type&&null!=b[l].__e&&b[l].__e==n.__d&&(n.__d=wr(r,l+1)),Rr(b[l],b[l]));if(v)for(l=0;l<v.length;l++)Dr(v[l],v[++l],v[++l])}function Er(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?Er(r,t,n):Or(n,r,r,o,r.__e,t));return t}function Or(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function Tr(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||hr.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||Tr(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Tr(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?Pr:Cr,i):e.removeEventListener(t,i?Pr:Cr,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 Cr(e){this.l[e.type+!1](cr.event?cr.event(e):e)}function Pr(e){this.l[e.type+!0](cr.event?cr.event(e):e)}function jr(e,t,n,r,o,i,s,a,c){var u,l,d,f,p,h,y,v,b,m,g,_,w,S=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,a=t.__e=n.__e,t.__h=null,i=[a]),(u=cr.__b)&&u(t);try{e:if("function"==typeof S){if(v=t.props,b=(u=S.contextType)&&r[u.__c],m=u?b?b.props.value:u.__:r,n.__c?y=(l=t.__c=n.__c).__=l.__E:("prototype"in S&&S.prototype.render?t.__c=l=new S(v,m):(t.__c=l=new _r(v,m),l.constructor=S,l.render=Nr),b&&b.sub(l),l.props=v,l.state||(l.state={}),l.context=m,l.__n=r,d=l.__d=!0,l.__h=[]),null==l.__s&&(l.__s=l.state),null!=S.getDerivedStateFromProps&&(l.__s==l.state&&(l.__s=yr({},l.__s)),yr(l.__s,S.getDerivedStateFromProps(v,l.__s))),f=l.props,p=l.state,d)null==S.getDerivedStateFromProps&&null!=l.componentWillMount&&l.componentWillMount(),null!=l.componentDidMount&&l.__h.push(l.componentDidMount);else{if(null==S.getDerivedStateFromProps&&v!==f&&null!=l.componentWillReceiveProps&&l.componentWillReceiveProps(v,m),!l.__e&&null!=l.shouldComponentUpdate&&!1===l.shouldComponentUpdate(v,l.__s,m)||t.__v===n.__v){l.props=v,l.state=l.__s,t.__v!==n.__v&&(l.__d=!1),l.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),l.__h.length&&s.push(l);break e}null!=l.componentWillUpdate&&l.componentWillUpdate(v,l.__s,m),null!=l.componentDidUpdate&&l.__h.push((function(){l.componentDidUpdate(f,p,h)}))}if(l.context=m,l.props=v,l.__v=t,l.__P=e,g=cr.__r,_=0,"prototype"in S&&S.prototype.render)l.state=l.__s,l.__d=!1,g&&g(t),u=l.render(l.props,l.state,l.context);else do{l.__d=!1,g&&g(t),u=l.render(l.props,l.state,l.context),l.state=l.__s}while(l.__d&&++_<25);l.state=l.__s,null!=l.getChildContext&&(r=yr(yr({},r),l.getChildContext())),d||null==l.getSnapshotBeforeUpdate||(h=l.getSnapshotBeforeUpdate(f,p)),w=null!=u&&u.type===gr&&null==u.key?u.props.children:u,Ir(e,Array.isArray(w)?w:[w],t,n,r,o,i,s,a,c),l.base=t.__e,t.__h=null,l.__h.length&&s.push(l),y&&(l.__E=l.__=null),l.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=$r(n.__e,t,n,r,o,i,s,c);(u=cr.diffed)&&u(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),cr.__e(e,t,n)}}function Ur(e,t){cr.__c&&cr.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){cr.__e(e,t.__v)}}))}function $r(e,t,n,r,o,i,s,a){var c,u,l,d=n.props,f=t.props,p=t.type,h=0;if("svg"===p&&(o=!0),null!=i)for(;h<i.length;h++)if((c=i[h])&&"setAttribute"in c==!!p&&(p?c.localName===p:3===c.nodeType)){e=c,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,a=!1}if(null===p)d===f||a&&e.data===f||(e.data=f);else{if(i=i&&ar.call(e.childNodes),u=(d=n.props||fr).dangerouslySetInnerHTML,l=f.dangerouslySetInnerHTML,!a){if(null!=i)for(d={},h=0;h<e.attributes.length;h++)d[e.attributes[h].name]=e.attributes[h].value;(l||u)&&(l&&(u&&l.__html==u.__html||l.__html===e.innerHTML)||(e.innerHTML=l&&l.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||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,a),l)t.__k=[];else if(h=t.props.children,Ir(e,Array.isArray(h)?h:[h],t,n,r,o&&"foreignObject"!==p,i,s,i?i[0]:n.__k&&wr(n,0),a),null!=i)for(h=i.length;h--;)null!=i[h]&&vr(i[h]);a||("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 Dr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){cr.__e(e,n)}}function Rr(e,t,n){var r,o;if(cr.unmount&&cr.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Dr(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){cr.__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||vr(e.__e),e.__e=e.__d=void 0}function Nr(e,t,n){return this.constructor(e,n)}function Lr(e,t,n){var r,o,i;cr.__&&cr.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],jr(t,e=(!r&&n||t).__k=br(gr,null,[e]),o||fr,fr,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),Ur(i,e)}ar=pr.slice,cr={__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,_r.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),kr(this))},_r.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),kr(this))},_r.prototype.render=gr,lr=[],xr.__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 Wr({children:e,className:t}){return br("div",{className:t},br("div",{style:Br.Darken}),br("div",{style:Br.DialogOuter},br("div",{style:Br.DialogInner},e)))}var Mr,Fr,Kr,Hr,Vr=0,zr=[],qr=[],Gr=cr.__b,Jr=cr.__r,Yr=cr.diffed,Zr=cr.__c,Xr=cr.unmount;function Qr(e,t){cr.__h&&cr.__h(Fr,e,Vr||t),Vr=0;var n=Fr.__H||(Fr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:qr}),n.__[e]}function eo(e){return Vr=1,function(e,t,n){var r=Qr(Mr++,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=Fr,!Fr.u)){Fr.u=!0;var o=Fr.shouldComponentUpdate;Fr.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 to(e){return Vr=5,function(e,t){var n=Qr(Mr++,7);return so(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function no(){for(var e;e=zr.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(oo),e.__H.__h.forEach(io),e.__H.__h=[]}catch(t){e.__H.__h=[],cr.__e(t,e.__v)}}cr.__b=function(e){Fr=null,Gr&&Gr(e)},cr.__r=function(e){Jr&&Jr(e),Mr=0;var t=(Fr=e.__c).__H;t&&(Kr===Fr?(t.__h=[],Fr.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=qr,e.__N=e.i=void 0}))):(t.__h.forEach(oo),t.__h.forEach(io),t.__h=[])),Kr=Fr},cr.diffed=function(e){Yr&&Yr(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==zr.push(t)&&Hr===cr.requestAnimationFrame||((Hr=cr.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),ro&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);ro&&(t=requestAnimationFrame(n))})(no)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==qr&&(e.__=e.__V),e.i=void 0,e.__V=qr}))),Kr=Fr=null},cr.__c=function(e,t){t.some((function(e){try{e.__h.forEach(oo),e.__h=e.__h.filter((function(e){return!e.__||io(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],cr.__e(n,e.__v)}})),Zr&&Zr(e,t)},cr.unmount=function(e){Xr&&Xr(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{oo(e)}catch(e){t=e}})),t&&cr.__e(t,n.__v))};var ro="function"==typeof requestAnimationFrame;function oo(e){var t=Fr,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Fr=t}function io(e){var t=Fr;e.__c=e.__(),Fr=t}function so(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 co({title:e,alerts:t,fields:n,onCancel:r,onSubmit:o}){const[i,s]=eo({}),a=to(null);return function(e,t){var n=Qr(Mr++,4);!cr.__s&&so(n.__H,t)&&(n.__=e,n.i=t,Fr.__h.push(n))}((()=>{var e;return null===(e=a.current)||void 0===e?void 0:e.focus()}),[]),br(Wr,{className:"dxc-login-dlg"},br(gr,null,br("h3",{style:Br.WindowHeader},e),t.map((e=>br("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)))),br("form",{onSubmit:e=>{e.preventDefault(),o(i)}},Object.entries(n).map((([e,{type:t,label:n,placeholder:r}],o)=>br("label",{style:Br.Label},n?`${n}: `:"",br("input",{ref:0===o?a: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)}))}})))))),br("div",{style:Br.ButtonsDiv},br("button",{type:"submit",style:Br.Button,onClick:()=>o(i)},"Submit"),br("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 lo extends _r{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=l(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?br(co,Object.assign({},t)):null}}function fo(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}function po(e,t){let n=t,o=l(e).pipe(p((e=>n=e)),h({resetOnRefCountZero:()=>y(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 ho=fo((e=>po(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=fo((e=>new o(bt))),vo=fo((e=>po(yo(e._novip).pipe(Xe((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 bo(...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 mo=fo((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}(po(f([vo(e._novip),ho(e._novip)]).pipe(Be((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:bt.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=Ot(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:"*"}:bo(...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 go{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 _o=fo((e=>{const t=yo(e._novip).pipe(Xe((t=>n((()=>e.members.where({email:t.email||""}).toArray()))))),r=mo(e._novip),o=vo(e._novip);return po(f([t,o,r]).pipe(Be((([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 m(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return m(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function wo(e){return"rlm~"+e}function So(e){return e.startsWith("rlm~")?e.substr(4):null}const ko={nameSuffix:!0};function xo(t){const r=t.name,i=yo(t),c=[];let u=!1,p=null;t.on("ready",(t=>m(this,void 0,void 0,(function*(){try{yield function(t){var r,o,v,b,g,_,w;return m(this,void 0,void 0,(function*(){h=!1;const S=wn(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(r=S.cloud.options)||void 0===r?void 0:r.customLoginGui)||c.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Lr(br(lo,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Lr(br(lo,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),S.cloud.isServiceWorkerDB||c.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Xe((e=>{const n=t;t=e;const r=a(e);switch(e){case"disconnected":return Mn.value?r.pipe(Fe(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(Fe(4e3));default:return r}})));return f([n,e.syncStateChangedEvent.pipe(Ze({phase:"initial"})),Fn]).pipe(Be((([t,n,r])=>{let{phase:o,error:i,progress:s}=n,a=t;return"error"===o&&(a="error"),"not-started"===t&&("pushing"!==o&&"pulling"!==o||(a="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(a="connecting"),r||(a="disconnected"),{phase:o,error:i,progress:s,status:un?a:"offline"}})))}(S).subscribe(t.cloud.syncState)),S.tables.every((e=>e.core))||On();const k="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],x=yield S.transaction("rw",S.$syncState,(()=>m(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(u){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,yield S.$syncState.put(e,"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&&!In?(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&&In?"Avoiding SW background sync and SW periodic bg sync for this browser due to browser bugs.":"navigator.serviceWorker not present"),S.cloud.usingServiceWorker=!1),sr(r,S.cloud.options),sr(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 m(this,void 0,void 0,(function*(){console.debug("Performing initial sync"),yield hn(e,t,n,{isInitialSync:!0}),console.debug("Done initial sync")}))}(S,S.cloud.options,S.cloud.schema),S.setInitiallySynced(!0)),y(),S.cloud.isServiceWorkerDB||(c.push(n((()=>S.getCurrentUser())).subscribe(i)),c.push(n((()=>S.getPersistedSyncState())).subscribe(S.cloud.persistedSyncState)),yield f([i.pipe(Ye(1),Ve(1)),S.cloud.persistedSyncState.pipe(Ye(1),Ve(1))]).toPromise()),(null===(v=S.cloud.options)||void 0===v?void 0:v.requireAuth)&&(yield vt(S)),p&&p.stop(),p=null,y(),S.cloud.usingServiceWorker&&(null===(b=S.cloud.options)||void 0===b?void 0:b.databaseUrl)?(rt(S,"push").catch((()=>{})),function(e){var t;return m(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=ir(S,S.cloud.options,S.cloud.schema),p.start(),ot(S,"push")),y(),S.cloud.isServiceWorkerDB||c.push(s(self,"online").subscribe((()=>{console.debug("online!"),S.syncStateChangedEvent.next({phase:"not-in-sync"}),ot(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)||En||c.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(Je((e=>e)),Xe((()=>e.getPersistedSyncState())),Je((e=>e&&e.serverRevision)),Be((e=>({type:"ready",rev:e.serverRevision}))));return function t(){return e.cloud.persistedSyncState.pipe(Je((e=>null==e?void 0:e.serverRevision)),Ve(1),Xe((t=>e.cloud.currentUser.pipe(Be((e=>[e,t]))))),Xe((([e,t])=>Fn.pipe(Be((n=>[n?e:null,t]))))),Xe((([e,t])=>m(this,void 0,void 0,(function*(){return[e,yield St(t)]})))),Xe((([t,r])=>t?new Yn(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,r,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,t.accessToken,t.accessTokenExpiration):l([]))),Ue((n=>"TokenExpiredError"===(null==n?void 0:n.name)?(console.debug("WebSocket observable: Token expired. Refreshing token..."),a(!0).pipe(Xe((()=>m(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield ft(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration})})))),Xe((()=>t())))):d(n))),Ue((n=>(e.cloud.webSocketStatus.next("error"),l(Qn(n)).pipe(Xe((()=>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 y(){if(h)throw new e.DatabaseClosedError}var v;!function(e,t){e.on.close.subscribe(t);const n=e.close;e.close=function(){n.call(this),t()}}(t,(()=>{c.forEach((e=>e.unsubscribe())),h=!0,p&&p.stop(),p=null,i.next(bt)})),t.cloud={version:"4.0.1-beta.33",options:Object.assign({},ko),schema:null,get currentUserId(){return i.value.userId||bt.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 m(this,void 0,void 0,(function*(){const n=wn(t);yield n.cloud.sync(),yield vt(n,e)}))},invites:_o(t),roles:ho(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),u=!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)}`,wn(t).reconfigure()),sr(t.cloud.schema,t.cloud.options)},sync({wait:e,purpose:r}={wait:!0,purpose:"push"}){return m(this,void 0,void 0,(function*(){void 0===e&&(e=!0);const o=wn(t);if("pull"===r){const t=o.cloud.persistedSyncState.value;if(ot(o,r),e){const e=yield o.cloud.persistedSyncState.pipe(Je((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp))),Ve(1)).toPromise();if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield er(o)){const t=o.cloud.persistedSyncState.value;ot(o,r),e&&(console.debug("db.cloud.login() is waiting for sync completion..."),yield l(n((()=>m(this,void 0,void 0,(function*(){const e=yield er(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(Je((e=>!e)),Ve(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=mo(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new go(i.permissions,n,o===e.cloud.currentUserId||r===e.cloud.currentUserId):new go({},n,!r||r===e.cloud.currentUserId)},a=i.pipe(Be(s));return a.getValue=()=>s(i.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>Wn(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return Un(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:wn(t)})),t.use((v=wn(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 a=e.trans;if((null===(o=null===(r=v.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type))for(const t of e.values){t.owner||(t.owner=a.currentUser.userId),t.realmId||(t.realmId=a.currentUser.userId);const r=null===(s=(i=n.schema.primaryKey).extractKey)||void 0===s?void 0:s.call(i,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,delete e.updates,t.$ts=Date.now())}return n.mutate(e)}})}})})),t.use($n(wn(t)))}xo.version="4.0.1-beta.33",e.Cloud=xo;export{xo as default,xo as dexieCloud,So as getTiedObjectId,wo as getTiedRealmId};
2
2
  //# sourceMappingURL=dexie-cloud-addon.min.js.map
@@ -5937,7 +5937,7 @@ function dexieCloud(dexie) {
5937
5937
  currentUserEmitter.next(UNAUTHORIZED_USER);
5938
5938
  });
5939
5939
  dexie.cloud = {
5940
- version: '4.0.1-beta.32',
5940
+ version: '4.0.1-beta.33',
5941
5941
  options: Object.assign({}, DEFAULT_OPTIONS),
5942
5942
  schema: null,
5943
5943
  get currentUserId() {
@@ -6192,7 +6192,7 @@ function dexieCloud(dexie) {
6192
6192
  });
6193
6193
  }
6194
6194
  }
6195
- dexieCloud.version = '4.0.1-beta.32';
6195
+ dexieCloud.version = '4.0.1-beta.33';
6196
6196
  Dexie.Cloud = dexieCloud;
6197
6197
 
6198
6198
  // In case the SW lives for a while, let it reuse already opened connections: