dexie-cloud-addon 4.0.7 → 4.1.0-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/modern/DexieCloudOptions.d.ts +4 -2
- package/dist/modern/WSObservable.d.ts +9 -6
- package/dist/modern/db/DexieCloudDB.d.ts +2 -0
- package/dist/modern/db/entities/PersistedSyncState.d.ts +7 -0
- package/dist/modern/dexie-cloud-addon.js +1752 -79
- package/dist/modern/dexie-cloud-addon.js.map +1 -1
- package/dist/modern/dexie-cloud-addon.min.js +1 -1
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/service-worker.js +1752 -79
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/sync/DEXIE_CLOUD_SYNCER_ID.d.ts +1 -0
- package/dist/modern/sync/syncWithServer.d.ts +2 -2
- package/dist/modern/yjs/Y.d.ts +3 -0
- package/dist/modern/yjs/YDexieCloudSyncState.d.ts +4 -0
- package/dist/modern/yjs/YTable.d.ts +2 -0
- package/dist/modern/yjs/applyYMessages.d.ts +5 -0
- package/dist/modern/yjs/awareness.d.ts +4 -0
- package/dist/modern/yjs/createYClientUpdateObservable.d.ts +4 -0
- package/dist/modern/yjs/createYHandler.d.ts +5 -0
- package/dist/modern/yjs/downloadYDocsFromServer.d.ts +3 -0
- package/dist/modern/yjs/getUpdatesTable.d.ts +3 -0
- package/dist/modern/yjs/listUpdatesSince.d.ts +2 -0
- package/dist/modern/yjs/listYClientMessagesAndStateVector.d.ts +26 -0
- package/dist/modern/yjs/updateYSyncStates.d.ts +6 -0
- package/dist/umd/DexieCloudOptions.d.ts +4 -2
- package/dist/umd/WSObservable.d.ts +9 -6
- package/dist/umd/db/DexieCloudDB.d.ts +2 -0
- package/dist/umd/db/entities/PersistedSyncState.d.ts +7 -0
- package/dist/umd/dexie-cloud-addon.js +1750 -77
- package/dist/umd/dexie-cloud-addon.js.map +1 -1
- package/dist/umd/dexie-cloud-addon.min.js +1 -1
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +1750 -77
- package/dist/umd/service-worker.js.map +1 -1
- package/dist/umd/service-worker.min.js +1 -1
- package/dist/umd/service-worker.min.js.map +1 -1
- package/dist/umd/sync/DEXIE_CLOUD_SYNCER_ID.d.ts +1 -0
- package/dist/umd/sync/syncWithServer.d.ts +2 -2
- package/dist/umd/yjs/Y.d.ts +3 -0
- package/dist/umd/yjs/YDexieCloudSyncState.d.ts +4 -0
- package/dist/umd/yjs/YTable.d.ts +2 -0
- package/dist/umd/yjs/applyYMessages.d.ts +5 -0
- package/dist/umd/yjs/awareness.d.ts +4 -0
- package/dist/umd/yjs/createYClientUpdateObservable.d.ts +4 -0
- package/dist/umd/yjs/createYHandler.d.ts +5 -0
- package/dist/umd/yjs/downloadYDocsFromServer.d.ts +3 -0
- package/dist/umd/yjs/getUpdatesTable.d.ts +3 -0
- package/dist/umd/yjs/listUpdatesSince.d.ts +2 -0
- package/dist/umd/yjs/listYClientMessagesAndStateVector.d.ts +26 -0
- package/dist/umd/yjs/updateYSyncStates.d.ts +6 -0
- package/package.json +5 -4
- package/dist/modern/helpers/dbOnClosed.d.ts +0 -2
- package/dist/umd/helpers/dbOnClosed.d.ts +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import e,{PropModification as t,cmp as n,liveQuery as r}from"dexie";import{Observable as o,BehaviorSubject as i,firstValueFrom as s,Subject as a,from as c,filter as l,fromEvent as u,of as d,merge as f,Subscription as p,throwError as h,combineLatest as y,map as v,share as m,timer as b}from"rxjs";var g=function(e,t){return g=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])},g(e,t)};function _(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}g(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function w(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 k(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 S(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 x(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 I(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 E(e){return this instanceof E?(this.v=e,this):new E(e)}function O(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 E?Promise.resolve(e.value.v).then(c,l):u(i[0][2],e)}(o[e](t))}catch(e){u(i[0][3],e)}}function c(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function C(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=S(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}const T={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(T),Object.freeze(T.claims)}catch(e){}const A={},j="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;j&&j.ready.then((e=>A.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 P{constructor(e){this.name=e}subscribe(e){if(!j)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 j.addEventListener("message",t),()=>j.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}))):A.registration&&(null===(t=A.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const U=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class $ extends o{constructor(e){const t="undefined"==typeof BroadcastChannel?new P(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){n.next(e.data)}let i;!function(e,t){U.has(e)?U.get(e).push(t):U.set(e,[t])}(`lbc-${e}`,r);try{t instanceof P?i=t.subscribe((e=>n.next(e))):t.addEventListener("message",o)}catch(e){}return()=>{!function(e,t){const n=U.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof P?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=U.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function D(e){return"function"==typeof e}function L(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 R(e){return D(null==e?void 0:e.then)}var B,M,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}},(M=B((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),M.prototype.constructor=M,M);function F(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var K=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=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 l=this._finalizers;if(l){this._finalizers=null;try{for(var u=S(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{V(f)}catch(e){o=null!=o?o:[],e instanceof W?o=I(I([],x(o)),x(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(o)throw new W(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)V(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)&&F(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&F(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function H(e){return e instanceof K||e&&"closed"in e&&D(e.remove)&&D(e.add)&&D(e.unsubscribe)}function V(e){D(e)?e():e.unsubscribe()}K.EMPTY;var z={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},q={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=q.delegate;return(null==o?void 0:o.setTimeout)?o.setTimeout.apply(o,I([e,t],x(n))):setTimeout.apply(void 0,I([e,t],x(n)))},clearTimeout:function(e){var t=q.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function J(e){q.setTimeout((function(){throw e}))}function G(){}var Y=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,H(t)&&t.add(n)):n.destination=ne,n}return _(t,e),t.create=function(e,t,n){return new ee(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),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}(K),Z=Function.prototype.bind;function X(e,t){return Z.call(e,t)}var Q=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){te(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){te(e)}else te(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){te(e)}},e}(),ee=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&&z.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&X(t.next,i),error:t.error&&X(t.error,i),complete:t.complete&&X(t.complete,i)}):o=t;return s.destination=new Q(o),s}return _(t,e),t}(Y);function te(e){J(e)}var ne={closed:!0,next:G,error:function(e){throw e},complete:G},re="function"==typeof Symbol&&Symbol.observable||"@@observable";function oe(e){return e}var ie=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r,o=this,i=(r=e)&&r instanceof Y||function(e){return e&&D(e.next)&&D(e.error)&&D(e.complete)}(r)&&H(r)?e:new ee(e,t,n);return function(){var e=o,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=se(t))((function(t,r){var o=new ee({next:function(t){try{e(t)}catch(e){r(e),o.unsubscribe()}},error:r,complete:t});n.subscribe(o)}))},e.prototype._subscribe=function(e){var t;return null===(t=this.source)||void 0===t?void 0:t.subscribe(e)},e.prototype[re]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return(0===(e=t).length?oe:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=se(e))((function(e,n){var r;t.subscribe((function(e){return r=e}),(function(e){return n(e)}),(function(){return e(r)}))}))},e.create=function(t){return new e(t)},e}();function se(e){var t;return null!==(t=null!=e?e:z.Promise)&&void 0!==t?t:Promise}function ae(e){return D(e[re])}function ce(e){return Symbol.asyncIterator&&D(null==e?void 0:e[Symbol.asyncIterator])}function le(e){return new TypeError("You provided "+(null!==e&&"object"==typeof e?"an invalid object":"'"+e+"'")+" where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.")}var ue="function"==typeof Symbol&&Symbol.iterator?Symbol.iterator:"@@iterator";function de(e){return D(null==e?void 0:e[ue])}function fe(e){return O(this,arguments,(function(){var t,n,r;return k(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,E(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,E(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,E(r)];case 6:return[4,o.sent()];case 7:return o.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}}))}))}function pe(e){return D(null==e?void 0:e.getReader)}function he(e){if(e instanceof ie)return e;if(null!=e){if(ae(e))return o=e,new ie((function(e){var t=o[re]();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 ie((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(R(e))return n=e,new ie((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,J)}));if(ce(e))return ye(e);if(de(e))return t=e,new ie((function(e){var n,r;try{for(var o=S(t),i=o.next();!i.done;i=o.next()){var s=i.value;if(e.next(s),e.closed)return}}catch(e){n={error:e}}finally{try{i&&!i.done&&(r=o.return)&&r.call(o)}finally{if(n)throw n.error}}e.complete()}));if(pe(e))return ye(fe(e))}var t,n,r,o;throw le(e)}function ye(e){return new ie((function(t){(function(e,t){var n,r,o,i;return w(this,void 0,void 0,(function(){var s,a;return k(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=C(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 ve(e,t,n,r,o){return new me(e,t,n,r,o)}var me=function(e){function t(t,n,r,o,i,s){var 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 _(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}(Y),be=function(e){function t(t,n){return e.call(this)||this}return _(t,e),t.prototype.schedule=function(e,t){return this},t}(K),ge={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=ge.delegate;return(null==o?void 0:o.setInterval)?o.setInterval.apply(o,I([e,t],x(n))):setInterval.apply(void 0,I([e,t],x(n)))},clearInterval:function(e){var t=ge.delegate;return((null==t?void 0:t.clearInterval)||clearInterval)(e)},delegate:void 0},_e=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 _(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),ge.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;ge.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,F(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(be),we={now:function(){return(we.delegate||Date).now()},delegate:void 0},ke=function(){function e(t,n){void 0===n&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return void 0===t&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=we.now,e}(),Se=new(function(e){function t(t,n){void 0===n&&(n=ke.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r._scheduled=void 0,r}return _(t,e),t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do{if(n=e.execute(e.state,e.delay))break}while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(ke))(_e),xe=Se;function Ie(e){return e&&D(e.schedule)}function Ee(e,t,n){void 0===e&&(e=0),void 0===n&&(n=xe);var r=-1;return null!=t&&(Ie(t)?n=t:r=t),new ie((function(t){var o,i=(o=e)instanceof Date&&!isNaN(o)?+e-n.now():e;i<0&&(i=0);var s=0;return n.schedule((function(){t.closed||(t.next(s++),0<=r?this.schedule(void 0,r):t.complete())}),i)}))}function Oe(e){return Ie((t=e)[t.length-1])?e.pop():void 0;var t}function Ce(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var i=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(i),!o)return i}function Te(e){return L((function(t,n){var r,o=null,i=!1;o=t.subscribe(ve(n,void 0,void 0,(function(s){r=he(e(s,Te(e)(t))),o?(o.unsubscribe(),o=null,r.subscribe(n)):i=!0}))),i&&(o.unsubscribe(),o=null,r.subscribe(n))}))}function Ae(e,t){return void 0===t&&(t=0),L((function(n,r){n.subscribe(ve(r,(function(n){return Ce(r,e,(function(){return r.next(n)}),t)}),(function(){return Ce(r,e,(function(){return r.complete()}),t)}),(function(n){return Ce(r,e,(function(){return r.error(n)}),t)})))}))}function je(e,t){return void 0===t&&(t=0),L((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function Pe(e,t){if(!e)throw new Error("Iterable cannot be null");return new ie((function(n){Ce(n,t,(function(){var r=e[Symbol.asyncIterator]();Ce(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Ue(e,t){if(null!=e){if(ae(e))return function(e,t){return he(e).pipe(je(t),Ae(t))}(e,t);if(N(e))return function(e,t){return new ie((function(n){var r=0;return t.schedule((function(){r===e.length?n.complete():(n.next(e[r++]),n.closed||this.schedule())}))}))}(e,t);if(R(e))return function(e,t){return he(e).pipe(je(t),Ae(t))}(e,t);if(ce(e))return Pe(e,t);if(de(e))return function(e,t){return new ie((function(n){var r;return Ce(n,t,(function(){r=e[ue](),Ce(n,t,(function(){var e,t,o;try{t=(e=r.next()).value,o=e.done}catch(e){return void n.error(e)}o?n.complete():n.next(t)}),0,!0)})),function(){return D(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(pe(e))return function(e,t){return Pe(fe(e),t)}(e,t)}throw le(e)}function $e(e,t){return L((function(n,r){var o=0;n.subscribe(ve(r,(function(n){r.next(e.call(t,n,o++))})))}))}function De(e,t,n){return void 0===n&&(n=1/0),D(t)?De((function(n,r){return $e((function(e,o){return t(n,e,r,o)}))(he(e(n,r)))}),n):("number"==typeof t&&(n=t),L((function(t,r){return function(e,t,n,r,o,i,s,a){var c=[],l=0,u=0,d=!1,f=function(){!d||c.length||l||t.complete()},p=function(e){return l<r?h(e):c.push(e)},h=function(e){i&&t.next(e),l++;var a=!1;he(n(e,u++)).subscribe(ve(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){a=!0}),void 0,(function(){if(a)try{l--;for(var e=function(){var e=c.shift();s?Ce(t,s,(function(){return h(e)})):h(e)};c.length&&l<r;)e();f()}catch(e){t.error(e)}})))};return e.subscribe(ve(t,p,(function(){d=!0,f()}))),function(){null==a||a()}}(t,r,e,n)})))}function Le(){return void 0===(e=1)&&(e=1/0),De(oe,e);var e}function Ne(e,t){return void 0===t&&(t=Se),L((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(ve(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 Re(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return Le()((e=n,(t=Oe(n))?Ue(e,t):he(e)))}var Be=new ie((function(e){return e.complete()}));function Me(e){return e<=0?function(){return Be}:L((function(t,n){var r=0;t.subscribe(ve(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function We(e,t){return t?function(n){return Re(t.pipe(Me(1),L((function(e,t){e.subscribe(ve(t,G))}))),n.pipe(We(e)))}:De((function(t,n){return e(t,n).pipe(Me(1),function(e){return $e((function(){return e}))}(t))}))}function Fe(e,t){void 0===t&&(t=Se);var n=Ee(e,t);return We((function(){return n}))}function Ke(e,t){return void 0===t&&(t=oe),e=null!=e?e:He,L((function(n,r){var o,i=!0;n.subscribe(ve(r,(function(n){var s=t(n);!i&&e(o,s)||(i=!1,o=s,r.next(n))})))}))}function He(e,t){return e===t}function Ve(e,t){return L((function(n,r){var o=0;n.subscribe(ve(r,(function(n){return e.call(t,n,o++)&&r.next(n)})))}))}function ze(e){return Ve((function(t,n){return e<=n}))}function qe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Oe(e);return L((function(t,r){(n?Re(e,t,n):Re(e,t)).subscribe(r)}))}function Je(e,t){return L((function(n,r){var o=null,i=0,s=!1,a=function(){return s&&!o&&r.complete()};n.subscribe(ve(r,(function(n){null==o||o.unsubscribe();var s=0,c=i++;he(e(n,c)).subscribe(o=ve(r,(function(e){return r.next(t?t(n,e,c,s++):e)}),(function(){o=null,a()})))}),(function(){s=!0,a()})))}))}function Ge(e,t,n){var r=D(e)||t||n?{next:e,error:t,complete:n}:e;return r?L((function(e,t){var n;null===(n=r.subscribe)||void 0===n||n.call(r);var o=!0;e.subscribe(ve(t,(function(e){var n;null===(n=r.next)||void 0===n||n.call(r,e),t.next(e)}),(function(){var e;o=!1,null===(e=r.complete)||void 0===e||e.call(r),t.complete()}),(function(e){var n;o=!1,null===(n=r.error)||void 0===n||n.call(r,e),t.error(e)}),(function(){var e,t;o&&(null===(e=r.unsubscribe)||void 0===e||e.call(r)),null===(t=r.finalize)||void 0===t||t.call(r)})))})):oe}let Ye=!1;function Ze(e,t){return w(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){Ye||(Ye=!0)}}))}function Xe(e,t){e.cloud.usingServiceWorker?Ze(e,t):e.localSyncEvent.next({purpose:t})}const Qe="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},et="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};function tt({realms:e,inviteRealms:t}){return w(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 et(o)}))}function nt(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 rt(e){return`$${e}_mutations`}function ot(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 it=[].concat;function st(e){return it.apply([],e)}function at(e,t,{since:n={},limit:r=1/0}={}){return w(this,void 0,void 0,(function*(){const t=st(yield Promise.all(e.map((e=>w(this,void 0,void 0,(function*(){const t=ot(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.txid===t.mut.txid?e.mut.opNo-t.mut.opNo: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 ct(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")}function lt(e){if(!e)throw new Error("Assertion Failed")}const ut={}.hasOwnProperty;function dt(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){lt("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)dt(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 ut.call(e,t)}(e,s)||(c=e[s]={}),dt(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const ft="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=pt)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function pt(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function ht(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>ht(e)))&&e.every(yt))}function yt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(yt)}function vt(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))dt(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 mt(e,t){for(const{table:n,muts:r}of t)for(const t of r)vt(e,n,t)}class bt extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function gt(t,n){return new Promise(((r,o)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}});t.next(i)}))}function _t(e,t,...n){return gt(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function wt(e,t,n){return w(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield gt(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 kt(e,t,n){return w(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 gt(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function St(e){var t,n,r;return w(this,void 0,void 0,(function*(){const o=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:s,refreshToken:a,refreshTokenExpiration:c,claims:l}=o;if(!i)return null;if((null!==(t=null==s?void 0:s.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=o.license)||void 0===n?void 0:n.status)||"ok"))return o;if(!a)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield It(e.cloud.options.databaseUrl,o);return yield e.table("$logins").update(l.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license}),u}))}function xt(t,n,r,o,i){return w(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield It(t,n):yield function(t,n,r,o){return w(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:i,publicKey:s}=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(!i||!s)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=i;const a=function(e){const t=et(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",s));t.publicKey=s;try{const e=yield n({public_key:a,hints:o});if("error"===e.type)throw new bt(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield gt(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof bt)throw yield _t(r,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield _t(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,o,i)}))}function It(e,t){return w(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=et(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 l=yield c.json();if("error"===l.type)throw new bt(l);return t.accessToken=l.accessToken,t.accessTokenExpiration=l.accessTokenExpiration?new Date(l.accessTokenExpiration):void 0,t.claims=l.claims,t.license={type:l.userType,status:l.claims.license||"ok"},null!=l.evalDaysLeft&&(t.license.evalDaysLeft=l.evalDaysLeft),null!=l.userValidUntil&&(t.license.validUntil=new Date(l.userValidUntil)),l.data&&(t.data=l.data),t}))}const{toString:Et}={};const Ot={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function Ct(...e){const t=e.reduce(((e,t)=>({...e,...t})),e.reduce(((e,t)=>({...t,...e})),{})),n=new WeakMap;return{stringify(e,r,o){const i=JSON.stringify(e,(function(e){const o=this[e],i=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return Ot;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,Et.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:Ot),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 Tt={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 At={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const jt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Pt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Ut={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},$t={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Dt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Lt=["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=Dt[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function Nt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Mt[e[n]];return t}(et(e))}function Rt(e){return Qe(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=Bt[e[n]];return t}(e))}const Bt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},Mt={};for(const e of Object.keys(Bt))Mt[Bt[e]]=e;var Wt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Nt(e)}),revive:({v:e})=>{const t=Rt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ft{constructor(e,t){this.buf=e,this.type=t}}function Kt(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function Ht(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Vt={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ft,replace:e=>({$t:"Blob",v:et(e instanceof Ft?e.buf:Ht(Kt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Qe(t);return void 0!==typeof Blob?new Blob([n]):new Ft(n.buffer,e)}}};const zt={...At,...jt,...Pt,...Ut,...$t,...Lt,...Wt,...Vt};function qt(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsArrayBuffer(e)}))}var Jt={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Gt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Yt{toString(){return this.v}constructor(e){this.v=e}}const Zt=Object.assign(Object.assign(Object.assign({},Jt),Gt?{}:{bigint:{test:e=>e instanceof Yt,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Yt(e)}}),{PropModification:{test:e=>e instanceof t,replace:e=>Object.assign({$t:"PropModification"},e),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["$t"]);return new t(n)}}}),Xt=Ct(zt,Zt),Qt=function(...e){const t=Ct(zt,Tt,...e);return{toBinary(e){const[t,n]=this.stringify(e),r=new ArrayBuffer(4);return new DataView(r).setUint32(0,t.size),new Blob([r,t,n])},stringify(e){const n=[],r=t.stringify(e,n),o=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[o,r]},async parse(e,n){let r=0;const o=[],i=await qt(n),s=new DataView(i);for(;r<i.byteLength;){const e=s.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,o.push(t)}return t.parse(e,o)},async fromBinary(e){const t=new DataView(await qt(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise(((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)}))}(e.slice(t+4));return await this.parse(r,n)}}}(Zt);class en extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function tn(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 l=i;s.forEach(((t,r)=>{const o=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,s)=>{if(Array.isArray(t)){l===i&&(l=nn(i,o));const e=l.muts[r],n=JSON.stringify(t);e.keys[s]=n}else if("#"===t[0]){l===i&&(l=nn(i,o));const a=l.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${t}:${n.userId}`;a.keys[s]=u,o&&e.setByKeyPath(a.values[s],c.keyPath,u)}}))})),o.push(l)}return o}function nn(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):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()})))})}let rn=new WeakMap;function on(e){var t,n;return w(this,void 0,void 0,(function*(){const r=(null!==(n=null===(t=rn.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function sn(e,t,n,r,o,i,s,a){return w(this,void 0,void 0,(function*(){const c={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},l=yield St(r),u=null==l?void 0:l.accessToken;u&&(c.Authorization=`Bearer ${u}`);const d={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:tn(r.dx.core.schema,a,e)};r.syncStateChangedEvent.next({phase:"pushing"});const f=yield fetch(`${o}/sync`,{method:"post",headers:c,credentials:"include",body:Xt.stringify(d)});if(r.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),o=t.headers.get("Ratelimit-Reset");if(n&&r&&o){const t=Number(n),i=Math.max(0,Number(r)),s=Number(o);if(i<t/2){const t=Math.ceil(s/(i+1));rn.set(e,new Date(Date.now()+1e3*t))}else rn.delete(e)}}(r,f),!f.ok)throw new en(f);if("application/x-bison"===f.headers.get("content-type"))return Qt.fromBinary(yield f.blob());{const e=yield f.text();return Xt.parse(e)}}))}function an(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let cn=!1;function ln(e,t,n,r){return w(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 un(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 dn(t,r,o){return w(this,void 0,void 0,(function*(){const i=yield t.bulkGet(r),s=[],a=[];r.forEach(((r,c)=>{const l=i[c];if(l){for(const[i,s]of Object.entries(o[c]))if(i===t.schema.primKey.keyPath){if(0!==n(s,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(l,i,s);s.push(r),a.push(l)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(a,s):t.bulkPut(a)}))}function fn(t,n){return w(this,void 0,void 0,(function*(){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 dn(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(cn=navigator.onLine,self.addEventListener("online",(()=>cn=!0)),self.addEventListener("offline",(()=>cn=!1)));const pn="currentSyncWorker";function hn(e,t,n,r){return yn.apply(this,arguments).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((o=>w(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):cn&&(null==r?void 0:r.retryImmediatelyOnFetchError)&&"TypeError"===(null==o?void 0:o.name)&&/fetch/.test(null==o?void 0:o.message)?(e.syncStateChangedEvent.next({phase:"error",error:o}),yield new Promise((e=>setTimeout(e,500))),yield 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:cn?"error":"offline",error:new Error(""+(null==o?void 0:o.message)||o)}),Promise.reject(o))}))))}function yn(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;return w(this,void 0,void 0,(function*(){if(!(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,l=yield e.getCurrentUser(),u=l.isLoggedIn?nt(e):[],d=u.map((t=>e.table(rt(t.name)))),f=yield e.getPersistedSyncState(),p=!r&&l.isLoggedIn,h=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return nt(e).filter((e=>!n.includes(e.name)))}(e,f):[];an(o);const y=h.length>0;if(y){if(i)return!0;yield e.transaction("rw",h,(e=>w(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return w(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!==T.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!==T.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==T.userId||(e.owner=t.userId),e.realmId&&e.realmId!==T.userId||(e.realmId=t.userId))})))}))}(h,l,null==f?void 0:f.realms)})))),an(o)}const[v,m,b]=yield e.transaction("r",e.tables,(()=>w(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield at(d);if(an(o),y){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],s=yield function(e,t,n,r){return w(this,void 0,void 0,(function*(){const o=`upload-${ct(8)}`;if(t.isLoggedIn&&e.length>0){const i=new Set(r||[]);return(yield Promise.all(e.map((e=>w(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||"")&&ht(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,l,n,e);return an(o),i=i.concat(s),[i,t,r]}return[i,t,r]})))),g=v.some((e=>e.muts.some((e=>e.keys.length>0))));if(i)return g;if("push"===s&&!g)return!1;const _=un(v,null==m?void 0:m.latestRevisions),k=(null==m?void 0:m.clientIdentity)||ft(16);an(o);const S=yield sn(v,m,b,e,c,n,k,l),x=yield e.transaction("rw",e.tables,(t=>w(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))S.schema[e]&&(n[e]=S.schema[e]);yield e.$syncState.put(n,"schema");const r=yield at(d,0,{since:_});for(const t of d){const n=ot(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(_[n]){const r=_[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()])}un(r,_),yield ln(e,n,_,S.serverRevision);const o=yield e.getPersistedSyncState();yield function(e,t,n){return w(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=nt(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,S,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:k};p&&(i.syncedTables=u.map((e=>e.name)).concat(h.map((e=>e.name)))),i.latestRevisions=_,i.remoteDbId=S.dbId,i.initiallySynced=!0,i.realms=S.realms,i.inviteRealms=S.inviteRealms,i.serverRevision=S.serverRevision,i.timestamp=new Date,delete i.error;const s=vn(S.changes,r);return yield fn(s,e),e.$syncState.put(i,"syncState"),0===r.length}))));return x?(e.syncCompleteEvent.next(),!1):(yield on(e),yield yn(e,t,n,{isInitialSync:r,cancelToken:o}))}))}function vn(e,t){const n={};mt(n,e);const r={};return mt(r,t),function(e,t){var n,r,o;for(const[i,s]of Object.entries(t))for(const[t,a]of Object.entries(s))switch(a.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":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))dt(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=ft(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 mn(t){const n=[],r=new i(!0),o=new i(null);let a=!1,c=0,l=[0,0,0,0,0,0,0,0,0,Date.now()];return o.subscribe((()=>w(this,void 0,void 0,(function*(){if(!a&&n.length>0){a=!0,l.shift(),l.push(Date.now()),r.next(!1);try{yield function(){var r,o,i,a,c,l;return w(this,void 0,void 0,(function*(){for(;n.length>0;){const u=n.shift();try{yield s(t.cloud.syncState.pipe(Ve((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!u)continue;switch(u.type){case"token-expired":const s=t.cloud.currentUser.value,d=yield It(t.cloud.options.databaseUrl,s);yield t.table("$logins").update(s.userId,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(u.realm))||(null===(o=null==n?void 0:n.inviteRealms)||void 0===o?void 0:o.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(i=null==n?void 0:n.realms)||void 0===i?void 0:i.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(a=null==n?void 0:n.realms)||void 0===a?void 0:a.includes(u.realm))||(null===(c=null==n?void 0:n.inviteRealms)||void 0===c?void 0:c.includes(u.realm)))&&(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield t.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(l=t.cloud.syncState.value)||void 0===l?void 0:l.phase)){Xe(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>w(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(!o||!r||!i)return;if(u.baseRev!==o.serverRevision)return void("string"!=typeof u.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||Xe(t,"pull"));if((yield e.waitFor(tt(o)))!==u.realmSetHash)return void Xe(t,"pull");let s=[];if(i.isLoggedIn){const e=nt(t).map((e=>t.table(rt(e.name))));s=yield at(e)}if(u.changes.length>0){const e=vn(u.changes,s);yield fn(e,t)}o.latestRevisions=un(s,o.latestRevisions),o.serverRevision=u.newRev,yield ln(t,r,o.latestRevisions,u.newRev),yield t.$syncState.put(o,"syncState")}))))}}catch(e){}}}))}()}finally{l[l.length-1]-l[0]<1e4&&(Date.now()-c<5e3?(c=Date.now()+6e4,yield new Promise((e=>setTimeout(e,6e4)))):(c=Date.now()+1e4,yield new Promise((e=>setTimeout(e,1e4))))),a=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),o.next(null)},readyToServe:r}}const bn=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=bn.get(e.cloud);if(!t){const n=new a;let r=new $(`syncstatechanged-${e.name}`),o=new $(`synccomplete-${e.name}`);n.id=++_n;let i=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return i},localSyncEvent:n,get syncStateChangedEvent(){return r},get syncCompleteEvent(){return o},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||T)),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){i=e},reconfigure(){r=new $(`syncstatechanged-${e.name}`),o=new $(`synccomplete-${e.name}`)}};Object.assign(t,s),t.messageConsumer=mn(t),bn.set(e.cloud,t)}return t}const kn=new WeakMap;class Sn{constructor(e,t){kn.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new Sn(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return w(this,void 0,void 0,(function*(){kn.get(this).table("$logins").put(this)}))}}function xn(e,t){return s(c(e).pipe(l(t)))}function In(e){return w(this,void 0,void 0,(function*(){const t=yield En(e);if(t){if(!(yield function(e,t,n){return w(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield gt(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield En(e,{deleteUnsyncedData:!0})}}))}function En(e,{deleteUnsyncedData:t=!1}={}){return w(this,void 0,void 0,(function*(){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>w(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const o=n.storeNames.filter((e=>e.endsWith("_mutations"))),i=(yield Promise.all(o.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}))));return r&&(yield xn(e.cloud.currentUser,(e=>e.userId===T.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function On(e,...t){globalThis.console[e](...t)}function Cn(e,t){var n;return w(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),o=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield St(e),!1}const i=new Sn(e,{claims:{},lastLogin:new Date(0)});return yield xt(e.cloud.options.databaseUrl,i,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function({public_key:n,hints:r}){var o;return w(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.");if("demo"===(null==r?void 0:r.grant_type))i={demo_user:yield wt(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};else if((null==r?void 0:r.otpId)&&r.otp)i={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield wt(t,"Enter email address",null==r?void 0:r.email);i=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}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 _t(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new en(a,e)}const c=yield a.json();if("tokens"===c.type||"error"===c.type)return c;if("otp"===i.grant_type&&"email"in i){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield kt(t,i.email),r=Object.assign(Object.assign({},i),{otp:e||"",otp_id:c.otp_id,public_key:n});let o=yield fetch(`${s}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===o.status;){const e=yield o.text();r.otp=yield kt(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),o=yield fetch(`${s}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==o.status){const e=yield o.text();throw new en(o,e)}return yield o.json()}throw new Error(`Unexpected response from ${s}/token`)}))}}(e),e.cloud.userInteraction,t),o!==T.userId&&i.userId!==o&&(yield In(e)),yield function(e,t){return w(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>w(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;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(On("debug","Login context property names:",Object.keys(t)),On("debug","Login context property names:",Object.keys(t)),On("debug","Login context:",t),On("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield xn(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,i),Xe(e,"pull"),i.userId!==o}))}const Tn="undefined"!=typeof InstallTrigger,An="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),jn=An?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Pn=An&&jn<=605||Tn;const Un="undefined"!=typeof self&&"clients"in self&&!self.document;function $n(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:Dn}={};function Ln(e){return Dn.call(e).slice(8,-1)}function Nn(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 Rn=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Bn=0;function Mn(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();Bn>=o?++Bn:Bn=o,r[0]=Bn/1099511627776,r[1]=Bn/4294967296,r[2]=Bn/16777216,r[3]=Bn/65536,r[4]=Bn/256,r[5]=Bn;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+Nt(new Uint8Array(n.buffer))+(t||"")}function Wn(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=Nn(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=Nn(o.schema.primaryKey,n);return a.forEach(((c,l)=>{if(void 0===c){const r=n.values[l].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[l]=Mn(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[l]=e.deepClone(s[l]),e.setByKeyPath(s[l],o.schema.primaryKey.keyPath,a[l]))}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){Nn(o.schema.primaryKey,n).forEach(((t,n)=>{if(!ht(t)){const n=Array.isArray(t)?t.map(Ln).join(","):Ln(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 Fn=0;function Kn(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 Hn(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 Vn=new i(new Set);function zn(e){var t,n,r,o;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)}function qn({currentUserObservable:e,db:t}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:n=>{const r=n.schema.tables.filter((e=>!/^\$/.test(e.name)));let o;try{o=new Map(r.map((e=>[e.name,n.table(`$${e.name}_mutations`)])))}catch(e){$n()}return 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=>rt(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=ct(16),i.opCount=0,i.currentUser=e.value,Vn.value.add(i),Vn.next(Vn.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),Vn.value.delete(i),Vn.next(Vn.value)},r=()=>{i.mutationsAdded&&!zn(t)&&Xe(t,"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=>Promise.reject(e)))}):r;const{schema:i}=r,s=o.get(e);return function(e){const t="$lock"+ ++Fn;return Object.assign(Object.assign({},e),{count:Kn(e.count,t),get:Kn(e.get,t),getMany:Kn(e.getMany,t),openCursor:Kn(e.openCursor,t),query:Kn(e.query,t),mutate:Hn(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,c;const l=n.trans;return l.txid?l.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(c=l.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,a=++t.opCount;return r.mutate(e).then((r=>{const{numFailures:c,failures:l}=r;let u="delete"===i?e.keys:r.results,d="values"in e?e.values:[],f="updates"in e&&e.updates;c&&(u=u.filter(((e,t)=>!l[t])),d=d.filter(((e,t)=>!l[t])));const p=Date.now(),h="delete"===e.type?{type:"delete",ts:p,opNo:a,keys:u,criteria:e.criteria,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:p,opNo:a,keys:u,txid:n,userId:o,values:d}:e.criteria&&e.changeSpec?{type:"modify",ts:p,opNo:a,keys:u,criteria:e.criteria,changeSpec:e.changeSpec,txid:n,userId:o}:f?{type:"update",ts:p,opNo:a,keys:f.keys,changeSpecs:f.changeSpecs,txid:n,userId:o}:{type:"upsert",ts:p,opNo:a,keys:u,values:d,txid:n,userId:o};return"isAdditionalChunk"in e&&e.isAdditionalChunk&&(h.isAdditionalChunk=!0),u.length>0||"criteria"in e&&e.criteria?s.mutate({type:"add",trans:t,values:[h]}).then((()=>r)):r}))}}})}}}function Jn(e,t){return function(n,r){const o=Object.assign(Object.assign({},gn),n);Object.keys(gn).forEach((e=>{const t=o[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),i=gn[e].split(",").map((e=>e.trim())),s=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==i[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(gn[e])}`);for(let t=1;t<i.length;++t){const n=i[t];s.has(n.replace(/([&*]|\+\+)/g,""))||(o[e]+=`,${n}`)}}));const 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)(Rn.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 Gn=new i(!0),Yn=new i(!0);Gn.pipe(Je((e=>e?d(!0):d(!1).pipe(Fe(2e4)))),Ke()).subscribe(Yn);const Zn="undefined"!=typeof document?u(document,"visibilitychange"):d({}),Xn=Zn.pipe(Ve((()=>"hidden"===document.visibilityState))),Qn=Zn.pipe(Ve((()=>"visible"===document.visibilityState))),er="undefined"!=typeof window?f(Qn,u(window,"mousedown"),u(window,"mousemove"),u(window,"keydown"),u(window,"wheel"),u(window,"touchmove")):d({});"undefined"!=typeof document&&f(d(!0),Xn,er).pipe($e((()=>"visible"===document.visibilityState)),Ge((e=>{Gn.value!==e&&Gn.next(e)})),Je((e=>e?d(0).pipe(Fe(16e4),Ge((()=>Gn.next(!1)))):d(0)))).subscribe((()=>{}));class tr extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}class nr extends o{constructor(e,t,n,r,o,i,s,a){super((c=>new or(e,t,n,r,s,a,c,o,i)))}}let rr=0;class or extends p{constructor(e,t,n,r,o,i,s,a,c){super((()=>this.teardown())),this.id=++rr,this.reconnecting=!1,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(){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 w(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;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 tr);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>w(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else 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);const n=this.ws=new WebSocket(`${e}/changes?${t}`);n.onclose=e=>{this.pinger&&this.reconnect()},n.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t=Xt.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=>{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(Xt.stringify(e)))}))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class ir extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function sr(e){return w(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield s(er)}))}function ar(e){var t;return w(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 cr=new WeakMap;function lr(e,t,n,r){const o=cr.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return 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 lr(e,t,n,r)}))}}const i=function(){return w(this,void 0,void 0,(function*(){try{if(yield on(e),e.cloud.isServiceWorkerDB)yield hn(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw lt(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield function(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}(e,pn,(()=>hn(e,t,n,r)))}cr.delete(e)}catch(t){throw cr.delete(e),t}}))}();return cr.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}const ur=6e4;function dr(e,t,n){let r=null,o={cancelled:!1},i=null,s=null;function a(r,l=1){setTimeout((()=>{i&&clearTimeout(i);const u="pull"===s?"pull":r;i=null,s=null,lr(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:u}).catch((e=>{if(o.cancelled)c();else if(l<3){const e=s&&"pull"===s?"pull":r,t=setTimeout((()=>a(e,l+1)),[0,5,15][l]*ur);i&&clearTimeout(i),i=t,s=e}}))}),0)}const c=()=>{o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{try{a(e||"pull")}catch(e){}}))},stop:c}}function fr(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var pr,hr,yr,vr,mr,br={},gr=[],_r=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function wr(e,t){for(var n in t)e[n]=t[n];return e}function kr(e){var t=e.parentNode;t&&t.removeChild(e)}function Sr(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?pr.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 xr(e,s,r,o,null)}function xr(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?++yr:o};return null==o&&null!=hr.vnode&&hr.vnode(i),i}function Ir(e){return e.children}function Er(e,t){this.props=e,this.context=t}function Or(e,t){if(null==t)return e.__?Or(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?Or(e):null}function Cr(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 Cr(e)}}function Tr(e){(!e.__d&&(e.__d=!0)&&vr.push(e)&&!Ar.__r++||mr!==hr.debounceRendering)&&((mr=hr.debounceRendering)||setTimeout)(Ar)}function Ar(){for(var e;Ar.__r=vr.length;)e=vr.sort((function(e,t){return e.__v.__b-t.__v.__b})),vr=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=wr({},o)).__v=o.__v+1,Rr(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?Or(o):i,o.__h),Br(n,o),o.__e!=i&&Cr(o)))}))}function jr(e,t,n,r,o,i,s,a,c,l){var u,d,f,p,h,y,v,m=r&&r.__k||gr,b=m.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(p=n.__k[u]=null==(p=t[u])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?xr(null,p,null,null,p):Array.isArray(p)?xr(Ir,{children:p},null,null,null):p.__b>0?xr(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=m[u])||f&&p.key==f.key&&p.type===f.type)m[u]=void 0;else for(d=0;d<b;d++){if((f=m[d])&&p.key==f.key&&p.type===f.type){m[d]=void 0;break}f=null}Rr(e,p,f=f||br,o,i,s,a,c,l),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=Pr(p,c,e):c=Ur(e,p,f,m,h,c),"function"==typeof n.type&&(n.__d=c)):c&&f.__e==c&&c.parentNode!=e&&(c=Or(f))}for(n.__e=y,u=b;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=Or(r,u+1)),Fr(m[u],m[u]));if(v)for(u=0;u<v.length;u++)Wr(v[u],v[++u],v[++u])}function Pr(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?Pr(r,t,n):Ur(n,r,r,o,r.__e,t));return t}function Ur(e,t,n,r,o,i){var s,a,c;if(void 0!==t.__d)s=t.__d,t.__d=void 0;else if(null==n||o!=i||null==o.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(o),s=null;else{for(a=i,c=0;(a=a.nextSibling)&&c<r.length;c+=2)if(a==o)break e;e.insertBefore(o,i),s=i}return void 0!==s?s:o.nextSibling}function $r(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||_r.test(t)?n:n+"px"}function Dr(e,t,n,r,o){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||$r(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||$r(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?Nr:Lr,i):e.removeEventListener(t,i?Nr:Lr,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 Lr(e){this.l[e.type+!1](hr.event?hr.event(e):e)}function Nr(e){this.l[e.type+!0](hr.event?hr.event(e):e)}function Rr(e,t,n,r,o,i,s,a,c){var l,u,d,f,p,h,y,v,m,b,g,_,w,k=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]),(l=hr.__b)&&l(t);try{e:if("function"==typeof k){if(v=t.props,m=(l=k.contextType)&&r[l.__c],b=l?m?m.props.value:l.__:r,n.__c?y=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(v,b):(t.__c=u=new Er(v,b),u.constructor=k,u.render=Kr),m&&m.sub(u),u.props=v,u.state||(u.state={}),u.context=b,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=wr({},u.__s)),wr(u.__s,k.getDerivedStateFromProps(v,u.__s))),f=u.props,p=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&v!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(v,b),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(v,u.__s,b)||t.__v===n.__v){u.props=v,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&s.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(v,u.__s,b),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(f,p,h)}))}if(u.context=b,u.props=v,u.__v=t,u.__P=e,g=hr.__r,_=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,g&&g(t),l=u.render(u.props,u.state,u.context);else do{u.__d=!1,g&&g(t),l=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++_<25);u.state=u.__s,null!=u.getChildContext&&(r=wr(wr({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(h=u.getSnapshotBeforeUpdate(f,p)),w=null!=l&&l.type===Ir&&null==l.key?l.props.children:l,jr(e,Array.isArray(w)?w:[w],t,n,r,o,i,s,a,c),u.base=t.__e,t.__h=null,u.__h.length&&s.push(u),y&&(u.__E=u.__=null),u.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=Mr(n.__e,t,n,r,o,i,s,c);(l=hr.diffed)&&l(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),hr.__e(e,t,n)}}function Br(e,t){hr.__c&&hr.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){hr.__e(e,t.__v)}}))}function Mr(e,t,n,r,o,i,s,a){var c,l,u,d=n.props,f=t.props,p=t.type,h=0;if("svg"===p&&(o=!0),null!=i)for(;h<i.length;h++)if((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&&pr.call(e.childNodes),l=(d=n.props||br).dangerouslySetInnerHTML,u=f.dangerouslySetInnerHTML,!a){if(null!=i)for(d={},h=0;h<e.attributes.length;h++)d[e.attributes[h].name]=e.attributes[h].value;(u||l)&&(u&&(l&&u.__html==l.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||Dr(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]||Dr(e,i,t[i],n[i],r)}(e,f,d,o,a),u)t.__k=[];else if(h=t.props.children,jr(e,Array.isArray(h)?h:[h],t,n,r,o&&"foreignObject"!==p,i,s,i?i[0]:n.__k&&Or(n,0),a),null!=i)for(h=i.length;h--;)null!=i[h]&&kr(i[h]);a||("value"in f&&void 0!==(h=f.value)&&(h!==e.value||"progress"===p&&!h||"option"===p&&h!==d.value)&&Dr(e,"value",h,d.value,!1),"checked"in f&&void 0!==(h=f.checked)&&h!==e.checked&&Dr(e,"checked",h,d.checked,!1))}return e}function Wr(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){hr.__e(e,n)}}function Fr(e,t,n){var r,o;if(hr.unmount&&hr.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Wr(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){hr.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Fr(r[o],t,"function"!=typeof e.type);n||null==e.__e||kr(e.__e),e.__e=e.__d=void 0}function Kr(e,t,n){return this.constructor(e,n)}function Hr(e,t,n){var r,o,i;hr.__&&hr.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Rr(t,e=(!r&&n||t).__k=Sr(Ir,null,[e]),o||br,br,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?pr.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),Br(i,e)}pr=gr.slice,hr={__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}},yr=0,Er.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=wr({},this.state),"function"==typeof e&&(e=e(wr({},n),this.props)),e&&wr(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Tr(this))},Er.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Tr(this))},Er.prototype.render=Ir,vr=[],Ar.__r=0;const Vr={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},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",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function zr({children:e,className:t}){return Sr("div",{className:t},Sr("div",{style:Vr.Darken}),Sr("div",{style:Vr.DialogOuter},Sr("div",{style:Vr.DialogInner},e)))}var qr,Jr,Gr,Yr,Zr=0,Xr=[],Qr=[],eo=hr.__b,to=hr.__r,no=hr.diffed,ro=hr.__c,oo=hr.unmount;function io(e,t){hr.__h&&hr.__h(Jr,e,Zr||t),Zr=0;var n=Jr.__H||(Jr.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:Qr}),n.__[e]}function so(e){return Zr=1,function(e,t,n){var r=io(qr++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):ho(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=Jr,!Jr.u)){Jr.u=!0;var o=Jr.shouldComponentUpdate;Jr.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.__}(ho,e)}function ao(e){return Zr=5,function(e,t){var n=io(qr++,7);return po(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function co(){for(var e;e=Xr.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(uo),e.__H.__h.forEach(fo),e.__H.__h=[]}catch(t){e.__H.__h=[],hr.__e(t,e.__v)}}hr.__b=function(e){Jr=null,eo&&eo(e)},hr.__r=function(e){to&&to(e),qr=0;var t=(Jr=e.__c).__H;t&&(Gr===Jr?(t.__h=[],Jr.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=Qr,e.__N=e.i=void 0}))):(t.__h.forEach(uo),t.__h.forEach(fo),t.__h=[])),Gr=Jr},hr.diffed=function(e){no&&no(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Xr.push(t)&&Yr===hr.requestAnimationFrame||((Yr=hr.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),lo&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);lo&&(t=requestAnimationFrame(n))})(co)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==Qr&&(e.__=e.__V),e.i=void 0,e.__V=Qr}))),Gr=Jr=null},hr.__c=function(e,t){t.some((function(e){try{e.__h.forEach(uo),e.__h=e.__h.filter((function(e){return!e.__||fo(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],hr.__e(n,e.__v)}})),ro&&ro(e,t)},hr.unmount=function(e){oo&&oo(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{uo(e)}catch(e){t=e}})),t&&hr.__e(t,n.__v))};var lo="function"==typeof requestAnimationFrame;function uo(e){var t=Jr,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Jr=t}function fo(e){var t=Jr;e.__c=e.__(),Jr=t}function po(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function ho(e,t){return"function"==typeof t?t(e):t}function yo({title:e,type:t,alerts:n,fields:r,submitLabel:o,cancelLabel:i,onCancel:s,onSubmit:a}){const[c,l]=so({}),u=ao(null);return function(e,t){var n=io(qr++,4);!hr.__s&&po(n.__H,t)&&(n.__=e,n.i=t,Jr.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Sr(zr,{className:"dxc-login-dlg"},Sr(Ir,null,Sr("h3",{style:Vr.WindowHeader},e),n.map((e=>Sr("p",{style:Vr.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(e)))),Sr("form",{onSubmit:e=>{e.preventDefault(),a(c)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],o)=>Sr("label",{style:Vr.Label,key:o},n?`${n}: `:"",Sr("input",{ref:0===o?u:void 0,type:t,name:e,autoComplete:"on",style:Vr.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const o=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let i=Object.assign(Object.assign({},c),{[e]:o});l(i),"otp"===t&&8===(null==o?void 0:o.trim().length)&&a(i)}})))))),Sr("div",{style:Vr.ButtonsDiv},Sr(Ir,null,Sr("button",{type:"submit",style:Vr.Button,onClick:()=>a(c)},o),i&&Sr("button",{style:Vr.Button,onClick:s},i))))}class vo extends Er{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=c(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?Sr(yo,Object.assign({},t)):null}}function mo(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const bo=mo((e=>new i(T)));function go(e,t){let n=t,r=c(e).pipe(v((e=>n=e)),m({resetOnRefCountZero:()=>b(1e3)}));const i=new o((e=>{let t=!1;const o=r.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||o.closed||e.next(n),o}));return i.getValue=()=>n,i}const _o=mo((e=>go(r((()=>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})))),{}))),wo=mo((e=>go(bo(e._novip).pipe(Je((t=>r((()=>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 ko(...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 So=mo((e=>function(e,t){let n;const r=e.pipe(v((e=>n=t(e))));return r.getValue=()=>void 0!==n?n:n=t(e.getValue()),r}(go(y([wo(e._novip),_o(e._novip)]).pipe($e((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:T.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=st(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:"*"}:ko(...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 xo{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 Io=mo((e=>{const t=bo(e._novip).pipe(Je((t=>r((()=>e.members.where({email:t.email||""}).toArray()))))),n=So(e._novip),o=wo(e._novip);return go(y([t,o,n]).pipe($e((([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)).map((t=>Object.assign(Object.assign({},t),{accept(){return w(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return w(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])})),Eo={nameSuffix:!0};function Oo(t){const n=t.name,o=bo(t),l=[];let f=!1,p=null;t.on("ready",(t=>w(this,void 0,void 0,(function*(){try{yield function(t){var n,a,g,_,k,S,x;return w(this,void 0,void 0,(function*(){v=!1;const I=wn(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(n=I.cloud.options)||void 0===n?void 0:n.customLoginGui)||l.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Hr(Sr(vo,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Hr(Sr(vo,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),I.cloud.isServiceWorkerDB||l.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Je((e=>{const n=t;t=e;const r=d(e);switch(e){case"disconnected":return Gn.value?r.pipe(Ne(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(Ne(4e3));default:return r}})));return y([n,e.syncStateChangedEvent.pipe(qe({phase:"initial"})),bo(e.dx._novip),Yn]).pipe($e((([t,n,r,o])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:s,error:a,progress:c}=n,l=t;return"error"===s&&(l="error"),"not-started"===t&&("pushing"!==s&&"pulling"!==s||(l="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(l="connecting"),o||(l="disconnected"),{phase:s,error:a,progress:c,status:cn?l:"offline",license:"ok"}})))}(I).subscribe(t.cloud.syncState)),l.push(I.syncCompleteEvent.subscribe(b)),I.tables.every((e=>e.core))||$n();const E="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[O,C]=yield I.transaction("rw",I.$syncState,(()=>w(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=I.cloud,[o,i,s]=yield Promise.all([I.getOptions(),I.getSchema(),I.getPersistedSyncState()]);if(f){if(!o||JSON.stringify(o)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,yield I.$syncState.put(e,"options")}}else I.cloud.options=o||null;if((null===(e=I.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&E.length>0&&!Pn?I.cloud.usingServiceWorker=!0:((null===(t=I.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&I.cloud.isServiceWorkerDB,I.cloud.usingServiceWorker=!1),fr(r,I.cloud.options),fr(i,I.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 I.$syncState.put(e,"schema"),Object.assign(r,e)}}else I.cloud.schema=i||null;return[null==s?void 0:s.initiallySynced,null==s?void 0:s.realms]}))));O&&I.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`)}}(I),(null===(a=I.cloud.options)||void 0===a?void 0:a.databaseUrl)&&!O&&(yield function(e,t,n){return w(this,void 0,void 0,(function*(){yield hn(e,t,n,{isInitialSync:!0})}))}(I,I.cloud.options,I.cloud.schema),I.setInitiallySynced(!0)),m(),I.cloud.isServiceWorkerDB||(l.push(r((()=>I.getCurrentUser())).subscribe(o)),l.push(r((()=>I.getPersistedSyncState())).subscribe(I.cloud.persistedSyncState)),yield s(y([o.pipe(ze(1),Me(1)),I.cloud.persistedSyncState.pipe(ze(1),Me(1))])));let T=!1;const A=yield I.getCurrentUser();(null===(g=I.cloud.options)||void 0===g?void 0:g.requireAuth)&&(A.isLoggedIn||(T=yield Cn(I))),!A.isLoggedIn||C&&C.includes(A.userId)||(T=!0),p&&p.stop(),p=null,m(),I.cloud.usingServiceWorker&&(null===(_=I.cloud.options)||void 0===_?void 0:_.databaseUrl)?(Ze(I,T?"pull":"push").catch((()=>{})),function(e){var t;return w(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)}catch(e){}}catch(e){}}))}(I).catch((()=>{}))):(null===(k=I.cloud.options)||void 0===k?void 0:k.databaseUrl)&&I.cloud.schema&&!I.cloud.isServiceWorkerDB&&(p=dr(I,I.cloud.options,I.cloud.schema),p.start(),Xe(I,T?"pull":"push")),m(),I.cloud.isServiceWorkerDB||l.push(u(self,"online").subscribe((()=>{I.syncStateChangedEvent.next({phase:"not-in-sync"}),zn(I)||Xe(I,"push")})),u(self,"offline").subscribe((()=>{I.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(S=I.cloud.options)||void 0===S?void 0:S.databaseUrl)||(null===(x=I.cloud.options)||void 0===x?void 0:x.disableWebSocket)||Un||l.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(Ve((e=>e)),Je((()=>e.getPersistedSyncState())),Ve((e=>e&&e.serverRevision)),Je((e=>w(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield tt(e)}})))));return function t(){return e.cloud.persistedSyncState.pipe(Ve((e=>null==e?void 0:e.serverRevision)),Me(1),Je((t=>e.cloud.currentUser.pipe($e((e=>[e,t]))))),Je((([e,t])=>Yn.pipe($e((n=>[n?e:null,t]))))),Je((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(Ve((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),Me(1),$e((e=>[t,e]))):new i([t,n]))),Je((([e,t])=>w(this,void 0,void 0,(function*(){return[e,yield tt(t)]})))),Ke((([e,t],[n,r])=>e===n&&t===r)),Je((([r,o])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?r?new nr(e.cloud.options.databaseUrl,e.cloud.persistedSyncState.value.serverRevision,o,e.cloud.persistedSyncState.value.clientIdentity,n,e.cloud.webSocketStatus,r.accessToken,r.accessTokenExpiration):c([]):t()})),Te((n=>"TokenExpiredError"===(null==n?void 0:n.name)?d(!0).pipe(Je((()=>w(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield It(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),Je((()=>t()))):h((()=>n)))),Te((n=>(e.cloud.webSocketStatus.next("error"),n instanceof ir?h((()=>n)):c(sr()).pipe(Je((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(I))}))}(t)}catch(e){}}))),!0);let v=!1;function m(){if(v)throw new e.DatabaseClosedError}!function(e,t){e.on.close.subscribe(t);const n=e._close;e._close=function(){n.call(this),t()}}(t,(()=>{l.forEach((e=>e.unsubscribe())),v=!0,p&&p.stop(),p=null,o.next(T)}));const b=new a;var g;t.cloud={version:"4.0.7",options:Object.assign({},Eo),schema:null,get currentUserId(){return o.value.userId||T.userId},currentUser:o,syncState:new i({phase:"initial",status:"not-started"}),events:{syncComplete:b},persistedSyncState:new i(void 0),userInteraction:new i(void 0),webSocketStatus:new i("not-started"),login(e){return w(this,void 0,void 0,(function*(){const n=wn(t);yield n.cloud.sync(),yield Cn(n,e)}))},invites:Io(t),roles:_o(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),f=!0,e.databaseUrl&&e.nameSuffix&&(t.name=`${n}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,wn(t).reconfigure()),fr(t.cloud.schema,t.cloud.options)},logout({force:e}={}){return w(this,void 0,void 0,(function*(){e?yield En(wn(t),{deleteUnsyncedData:!0}):yield In(wn(t))}))},sync({wait:e,purpose:n}={wait:!0,purpose:"push"}){var o;return w(this,void 0,void 0,(function*(){void 0===e&&(e=!0);const i=wn(t);if("ok"!==((null===(o=i.cloud.currentUser.value.license)||void 0===o?void 0:o.status)||"ok")&&(yield St(i)),"pull"===n){const t=i.cloud.persistedSyncState.value;if(Xe(i,n),e){const e=yield s(i.cloud.persistedSyncState.pipe(Ve((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp)))));if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield ar(i)){const t=i.cloud.persistedSyncState.value;Xe(i,n),e&&(yield s(c(r((()=>w(this,void 0,void 0,(function*(){const e=yield ar(i),n=yield i.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(Ve((e=>!e)))))}}))},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=So(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new xo(i.permissions,n,void 0===o||o===e.cloud.currentUserId||r===e.cloud.currentUserId):new xo({},n,!r||r===e.cloud.currentUserId)},a=i.pipe($e(s));return a.getValue=()=>s(i.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>Jn(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return Mn(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(qn({currentUserObservable:t.cloud.currentUser,db:wn(t)})),t.use((g=wn(t),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:t=>Object.assign(Object.assign({},t),{table:n=>{const r=t.table(n);return Object.assign(Object.assign({},r),{mutate:t=>{var o,i,s,a;if(t.trans.disableChangeTracking)return r.mutate(t);const c=t.trans;if(null===(i=null===(o=g.cloud.schema)||void 0===o?void 0:o[n])||void 0===i?void 0:i.markedForSync){if("versionchange"===c.mode)return Promise.reject(new e.UpgradeError(`Dexie Cloud Addon: Cannot upgrade or populate synced table "${n}". See https://dexie.org/cloud/docs/best-practices`));if("add"===t.type||"put"===t.type){if("members"===n)for(const e of t.values)"string"==typeof e.email&&(e.email=e.email.trim().toLowerCase());for(const e of t.values){e.owner||(e.owner=c.currentUser.userId),e.realmId||(e.realmId=c.currentUser.userId);const n=null===(a=(s=r.schema.primaryKey).extractKey)||void 0===a?void 0:a.call(s,e);"string"==typeof n&&"#"===n[0]&&"put"===t.type&&(delete t.criteria,delete t.changeSpec,delete t.updates,e.$ts=Date.now())}}}return r.mutate(t)}})}})})),t.use(Wn(wn(t)))}Oo.version="4.0.7",e.Cloud=Oo;const Co=new Map;function To(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const Ao=new Map;function jo(t,n){let r=Ao.get(t+"/"+n);return r||(r=function t(n,r){var o;return w(this,void 0,void 0,(function*(){let i=Co.get(n);if(!i){const o=new e(n,{addons:[Oo]});if(i=wn(o),i.cloud.isServiceWorkerDB=!0,o.on("versionchange",s),yield i.dx.open(),Co.get(n))return i.close(),yield t(n,r);Co.set(n,i)}if((null===(o=i.cloud.options)||void 0===o?void 0:o.databaseUrl)&&i.cloud.schema)try{yield lr(i,i.cloud.options,i.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:r})}catch(t){if(s(),t.name!==e.errnames.NoSuchDatabase)throw t}function s(){return i.dx.on.versionchange.unsubscribe(s),Co.get(i.name)===i&&Co.delete(i.name),i.dx.close(),!1}}))}(t,n).then((()=>{Ao.delete(t+"/"+n)})).catch((e=>(Ao.delete(t+"/"+n),Promise.reject(e)))),Ao.set(t+"/"+n,r)),r}Pn||(self.addEventListener("sync",(e=>{const t=To(e.tag);t&&e.waitUntil(jo(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=To(e.tag);t&&e.waitUntil(jo(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>jo(t,e.data.purpose||"pull").catch((e=>w(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>{}))):n().catch((e=>{}))}})));
|
|
1
|
+
import e,{PropModification as t,cmp as n,DexieYProvider as r,liveQuery as o}from"dexie";import{Observable as i,BehaviorSubject as s,firstValueFrom as a,Subject as c,from as l,filter as u,fromEvent as d,of as f,merge as p,switchMap as h,tap as y,mergeMap as v,Subscription as m,throwError as b,combineLatest as g,map as _,share as w,timer as k}from"rxjs";var S=function(e,t){return S=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])},S(e,t)};function x(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}S(e,t),e.prototype=null===t?Object.create(t):(n.prototype=t.prototype,new n)}function I(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 E(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 O(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function A(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),s=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)s.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return s}function T(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 U(e){return this instanceof U?(this.v=e,this):new U(e)}function C(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 U?Promise.resolve(e.value.v).then(c,l):u(i[0][2],e)}(o[e](t))}catch(e){u(i[0][3],e)}}function c(e){a("next",e)}function l(e){a("throw",e)}function u(e,t){e(t),i.shift(),i.length&&a(i[0][0],i[0][1])}}function P(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=O(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise((function(r,o){(function(e,t,n,r){Promise.resolve(r).then((function(t){e({value:t,done:n})}),t)})(r,o,(t=e[n](t)).done,t.value)}))}}}const j={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(j),Object.freeze(j.claims)}catch(e){}const $={},D="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;D&&D.ready.then((e=>$.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 L{constructor(e){this.name=e}subscribe(e){if(!D)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 D.addEventListener("message",t),()=>D.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}))):$.registration&&(null===(t=$.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const N=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class R extends i{constructor(e){const t="undefined"==typeof BroadcastChannel?new L(e):new BroadcastChannel(e);super((n=>{function r(e){n.next(e.detail)}function o(e){n.next(e.data)}let i;!function(e,t){N.has(e)?N.get(e).push(t):N.set(e,[t])}(`lbc-${e}`,r);try{t instanceof L?i=t.subscribe((e=>n.next(e))):t.addEventListener("message",o)}catch(e){}return()=>{!function(e,t){const n=N.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof L?i():t.removeEventListener("message",o)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=N.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function B(e){return"function"==typeof e}function M(e){return function(t){if(function(e){return B(null==e?void 0:e.lift)}(t))return t.lift((function(t){try{return e(t,this)}catch(e){this.error(e)}}));throw new TypeError("Unable to lift unknown Observable type")}}var F=function(e){return e&&"number"==typeof e.length&&"function"!=typeof e};function W(e){return B(null==e?void 0:e.then)}var V,K,H=(V=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}},(K=V((function(e){Error.call(e),e.stack=(new Error).stack}))).prototype=Object.create(Error.prototype),K.prototype.constructor=K,K);function z(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var q=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=O(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(B(c))try{c()}catch(e){o=e instanceof H?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=O(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{G(f)}catch(e){o=null!=o?o:[],e instanceof H?o=T(T([],A(o)),A(e.errors)):o.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(o)throw new H(o)}},e.prototype.add=function(t){var n;if(t&&t!==this)if(this.closed)G(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)&&z(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&z(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=((t=new e).closed=!0,t),e}();function J(e){return e instanceof q||e&&"closed"in e&&B(e.remove)&&B(e.add)&&B(e.unsubscribe)}function G(e){B(e)?e():e.unsubscribe()}q.EMPTY;var Y={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},X={setTimeout:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=X.delegate;return(null==o?void 0:o.setTimeout)?o.setTimeout.apply(o,T([e,t],A(n))):setTimeout.apply(void 0,T([e,t],A(n)))},clearTimeout:function(e){var t=X.delegate;return((null==t?void 0:t.clearTimeout)||clearTimeout)(e)},delegate:void 0};function Z(e){X.setTimeout((function(){throw e}))}function Q(){}var ee=function(e){function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,J(t)&&t.add(n)):n.destination=se,n}return x(t,e),t.create=function(e,t,n){return new oe(e,t,n)},t.prototype.next=function(e){this.isStopped||this._next(e)},t.prototype.error=function(e){this.isStopped||(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped||(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),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}(q),te=Function.prototype.bind;function ne(e,t){return te.call(e,t)}var re=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){ie(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){ie(e)}else ie(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){ie(e)}},e}(),oe=function(e){function t(t,n,r){var o,i,s=e.call(this)||this;B(t)||!t?o={next:null!=t?t:void 0,error:null!=n?n:void 0,complete:null!=r?r:void 0}:s&&Y.useDeprecatedNextContext?((i=Object.create(t)).unsubscribe=function(){return s.unsubscribe()},o={next:t.next&&ne(t.next,i),error:t.error&&ne(t.error,i),complete:t.complete&&ne(t.complete,i)}):o=t;return s.destination=new re(o),s}return x(t,e),t}(ee);function ie(e){Z(e)}var se={closed:!0,next:Q,error:function(e){throw e},complete:Q},ae="function"==typeof Symbol&&Symbol.observable||"@@observable";function ce(e){return e}var le=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 ee||function(e){return e&&B(e.next)&&B(e.error)&&B(e.complete)}(r)&&J(r)?e:new oe(e,t,n);return function(){var e=o,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?o._subscribe(i):o._trySubscribe(i))}(),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return new(t=ue(t))((function(t,r){var o=new oe({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[ae]=function(){return this},e.prototype.pipe=function(){for(var e,t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return(0===(e=t).length?ce:1===e.length?e[0]:function(t){return e.reduce((function(e,t){return t(e)}),t)})(this)},e.prototype.toPromise=function(e){var t=this;return new(e=ue(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 ue(e){var t;return null!==(t=null!=e?e:Y.Promise)&&void 0!==t?t:Promise}function de(e){return B(e[ae])}function fe(e){return Symbol.asyncIterator&&B(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 B(null==e?void 0:e[he])}function ve(e){return C(this,arguments,(function(){var t,n,r;return E(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,U(t.read())];case 3:return n=o.sent(),r=n.value,n.done?[4,U(void 0)]:[3,5];case 4:return[2,o.sent()];case 5:return[4,U(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 me(e){return B(null==e?void 0:e.getReader)}function be(e){if(e instanceof le)return e;if(null!=e){if(de(e))return o=e,new le((function(e){var t=o[ae]();if(B(t.subscribe))return t.subscribe(e);throw new TypeError("Provided object does not correctly implement Symbol.observable")}));if(F(e))return r=e,new le((function(e){for(var t=0;t<r.length&&!e.closed;t++)e.next(r[t]);e.complete()}));if(W(e))return n=e,new le((function(e){n.then((function(t){e.closed||(e.next(t),e.complete())}),(function(t){return e.error(t)})).then(null,Z)}));if(fe(e))return ge(e);if(ye(e))return t=e,new le((function(e){var n,r;try{for(var o=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(me(e))return ge(ve(e))}var t,n,r,o;throw pe(e)}function ge(e){return new le((function(t){(function(e,t){var n,r,o,i;return I(this,void 0,void 0,(function(){var s,a;return E(this,(function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=P(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 x(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}(ee),ke=function(e){function t(t,n){return e.call(this)||this}return x(t,e),t.prototype.schedule=function(e,t){return this},t}(q),Se={setInterval:function(e,t){for(var n=[],r=2;r<arguments.length;r++)n[r-2]=arguments[r];var o=Se.delegate;return(null==o?void 0:o.setInterval)?o.setInterval.apply(o,T([e,t],A(n))):setInterval.apply(void 0,T([e,t],A(n)))},clearInterval:function(e){var t=Se.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 x(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),Se.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;Se.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,z(r,this),null!=t&&(this.id=this.recycleAsyncId(n,t,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(ke),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 x(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),Ae=Oe;function Te(e){return e&&B(e.schedule)}function Ue(e,t,n){void 0===e&&(e=0),void 0===n&&(n=Ae);var r=-1;return null!=t&&(Te(t)?n=t:r=t),new le((function(t){var o,i=(o=e)instanceof Date&&!isNaN(o)?+e-n.now():e;i<0&&(i=0);var s=0;return n.schedule((function(){t.closed||(t.next(s++),0<=r?this.schedule(void 0,r):t.complete())}),i)}))}function Ce(e){return Te((t=e)[t.length-1])?e.pop():void 0;var t}function Pe(e,t,n,r,o){void 0===r&&(r=0),void 0===o&&(o=!1);var i=t.schedule((function(){n(),o?e.add(this.schedule(null,r)):this.unsubscribe()}),r);if(e.add(i),!o)return i}function je(e){return M((function(t,n){var r,o=null,i=!1;o=t.subscribe(_e(n,void 0,void 0,(function(s){r=be(e(s,je(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),M((function(n,r){n.subscribe(_e(r,(function(n){return Pe(r,e,(function(){return r.next(n)}),t)}),(function(){return Pe(r,e,(function(){return r.complete()}),t)}),(function(n){return Pe(r,e,(function(){return r.error(n)}),t)})))}))}function De(e,t){return void 0===t&&(t=0),M((function(n,r){r.add(e.schedule((function(){return n.subscribe(r)}),t))}))}function Le(e,t){if(!e)throw new Error("Iterable cannot be null");return new le((function(n){Pe(n,t,(function(){var r=e[Symbol.asyncIterator]();Pe(n,t,(function(){r.next().then((function(e){e.done?n.complete():n.next(e.value)}))}),0,!0)}))}))}function Ne(e,t){if(null!=e){if(de(e))return function(e,t){return be(e).pipe(De(t),$e(t))}(e,t);if(F(e))return function(e,t){return new le((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(W(e))return function(e,t){return be(e).pipe(De(t),$e(t))}(e,t);if(fe(e))return Le(e,t);if(ye(e))return function(e,t){return new le((function(n){var r;return Pe(n,t,(function(){r=e[he](),Pe(n,t,(function(){var e,t,o;try{t=(e=r.next()).value,o=e.done}catch(e){return void n.error(e)}o?n.complete():n.next(t)}),0,!0)})),function(){return B(null==r?void 0:r.return)&&r.return()}}))}(e,t);if(me(e))return function(e,t){return Le(ve(e),t)}(e,t)}throw pe(e)}function Re(e,t){return M((function(n,r){var o=0;n.subscribe(_e(r,(function(n){r.next(e.call(t,n,o++))})))}))}function Be(e,t,n){return void 0===n&&(n=1/0),B(t)?Be((function(n,r){return Re((function(e,o){return t(n,e,r,o)}))(be(e(n,r)))}),n):("number"==typeof t&&(n=t),M((function(t,r){return function(e,t,n,r,o,i,s,a){var c=[],l=0,u=0,d=!1,f=function(){!d||c.length||l||t.complete()},p=function(e){return l<r?h(e):c.push(e)},h=function(e){i&&t.next(e),l++;var a=!1;be(n(e,u++)).subscribe(_e(t,(function(e){null==o||o(e),i?p(e):t.next(e)}),(function(){a=!0}),void 0,(function(){if(a)try{l--;for(var e=function(){var e=c.shift();s?Pe(t,s,(function(){return h(e)})):h(e)};c.length&&l<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),Be(ce,e);var e}function Fe(e,t){return void 0===t&&(t=Oe),M((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 We(){for(var e,t,n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];return Me()((e=n,(t=Ce(n))?Ne(e,t):be(e)))}var Ve=new le((function(e){return e.complete()}));function Ke(e){return e<=0?function(){return Ve}:M((function(t,n){var r=0;t.subscribe(_e(n,(function(t){++r<=e&&(n.next(t),e<=r&&n.complete())})))}))}function He(e,t){return t?function(n){return We(t.pipe(Ke(1),M((function(e,t){e.subscribe(_e(t,Q))}))),n.pipe(He(e)))}:Be((function(t,n){return e(t,n).pipe(Ke(1),function(e){return Re((function(){return e}))}(t))}))}function ze(e,t){void 0===t&&(t=Oe);var n=Ue(e,t);return He((function(){return n}))}function qe(e,t){return void 0===t&&(t=ce),e=null!=e?e:Je,M((function(n,r){var o,i=!0;n.subscribe(_e(r,(function(n){var s=t(n);!i&&e(o,s)||(i=!1,o=s,r.next(n))})))}))}function Je(e,t){return e===t}function Ge(e,t){return M((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 Ge((function(t,n){return e<=n}))}function Xe(){for(var e=[],t=0;t<arguments.length;t++)e[t]=arguments[t];var n=Ce(e);return M((function(t,r){(n?We(e,t,n):We(e,t)).subscribe(r)}))}function Ze(e,t){return M((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++;be(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=B(e)||t||n?{next:e,error:t,complete:n}:e;return r?M((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)})))})):ce}let et=!1;function tt(e,t){return I(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){et||(et=!0)}}))}function nt(e,t){e.cloud.usingServiceWorker?tt(e,t):e.localSyncEvent.next({purpose:t})}const rt="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},ot="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};function it({realms:e,inviteRealms:t}){return I(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 ot(o)}))}function st(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 at(e){return`$${e}_mutations`}function ct(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const lt=[].concat;function ut(e){return lt.apply([],e)}function dt(e,t,{since:n={},limit:r=1/0}={}){return I(this,void 0,void 0,(function*(){const t=ut(yield Promise.all(e.map((e=>I(this,void 0,void 0,(function*(){const t=ct(e.name),o=n[t];let i=o?e.where("rev").above(o):e;r<1/0&&(i=i.limit(r));return(yield i.toArray()).map((e=>({table:t,mut:e})))})))))).sort(((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo: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 ft(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")}function pt(e){if(!e)throw new Error("Assertion Failed")}const ht={}.hasOwnProperty;function yt(e,t,n){if(e&&void 0!==t&&(!("isFrozen"in Object)||!Object.isFrozen(e)))if("string"!=typeof t&&"length"in t){pt("string"!=typeof n&&"length"in n);for(var r=0,o=t.length;r<o;++r)yt(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 ht.call(e,t)}(e,s)||(c=e[s]={}),yt(c,a,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const vt="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=mt)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function mt(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function bt(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>bt(e)))&&e.every(gt))}function gt(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(gt)}function _t(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))yt(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 wt(e,t){for(const{table:n,muts:r}of t)for(const t of r)_t(e,n,t)}const kt=Math.floor,St=Math.abs,xt=(e,t)=>e>t?e:t,It=128,Et=127,Ot=Number.MAX_SAFE_INTEGER,At=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&kt(e)===e),Tt=Array.isArray,Ut="undefined"!=typeof TextEncoder?new TextEncoder:null,Ct=Ut?e=>Ut.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let Pt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Pt&&1===Pt.decode(new Uint8Array).length&&(Pt=null);class jt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const $t=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},Dt=(e,t)=>{for(;t>Et;)$t(e,It|Et&t),t=kt(t/128);$t(e,Et&t)},Lt=new Uint8Array(3e4),Nt=Lt.length/3,Rt=Ut&&Ut.encodeInto?(e,t)=>{if(t.length<Nt){const n=Ut.encodeInto(t,Lt).written||0;Dt(e,n);for(let t=0;t<n;t++)$t(e,Lt[t])}else Bt(e,Ct(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;Dt(e,r);for(let t=0;t<r;t++)$t(e,n.codePointAt(t))},Bt=(e,t)=>{Dt(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,o=((e,t)=>e<t?e:t)(n-r,t.length),i=t.length-o;e.cbuf.set(t.subarray(0,o),r),e.cpos+=o,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(xt(2*n,i)),e.cbuf.set(t.subarray(o)),e.cpos=i)})(e,t)},Mt=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*xt(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ft=(e,t)=>Mt(e,8).setBigUint64(0,t,!1),Wt=new DataView(new ArrayBuffer(4)),Vt=(e,t)=>{switch(typeof t){case"string":$t(e,119),Rt(e,t);break;case"number":At(t)&&St(t)<=2147483647?($t(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),$t(e,(t>63?It:0)|(n?64:0)|63&t),t=kt(t/64);t>0;)$t(e,(t>Et?It:0)|Et&t),t=kt(t/128)})(e,t)):(n=t,Wt.setFloat32(0,n),Wt.getFloat32(0)===n?($t(e,124),((e,t)=>{Mt(e,4).setFloat32(0,t,!1)})(e,t)):($t(e,123),((e,t)=>{Mt(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":$t(e,122),((e,t)=>{Mt(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)$t(e,126);else if(Tt(t)){$t(e,117),Dt(e,t.length);for(let n=0;n<t.length;n++)Vt(e,t[n])}else if(t instanceof Uint8Array)$t(e,116),Bt(e,t);else{$t(e,118);const n=Object.keys(t);Dt(e,n.length);for(let r=0;r<n.length;r++){const o=n[r];Rt(e,o),Vt(e,t[o])}}break;case"boolean":$t(e,t?120:121);break;default:$t(e,127)}var n};function Kt(e){const t=new jt;switch(Rt(t,e.type),Rt(t,e.table),Rt(t,e.prop),e.type){case"u-ack":case"u-reject":Ft(t,BigInt(e.i));break;default:switch(Vt(t,e.k),e.type){case"aware":case"u-s":Bt(t,e.u);break;case"doc-open":Vt(t,e.serverRev),Vt(t,e.sv);break;case"doc-close":break;case"sv":Bt(t,e.sv);break;case"u-c":Bt(t,e.u),Ft(t,BigInt(e.i))}}return(e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const o=e.bufs[r];t.set(o,n),n+=o.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const Ht=e=>new Error(e),zt=Ht("Unexpected end of array"),qt=Ht("Integer out of Range");class Jt{constructor(e){this.arr=e,this.pos=0}}const Gt=e=>e.pos!==e.arr.length,Yt=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Zt(e)),Xt=e=>e.arr[e.pos++],Zt=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Et)*n,n*=128,r<It)return t;if(t>Ot)throw qt}throw zt},Qt=Pt?e=>Pt.decode(Yt(e)):e=>{let t=Zt(e);if(0===t)return"";{let n=String.fromCodePoint(Xt(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Xt(e));else for(;t>0;){const r=t<1e4?t:1e4,o=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,o),t-=r}return decodeURIComponent(escape(n))}},en=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},tn=e=>en(e,8).getBigUint64(0,!1),nn=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const o=(64&t)>0?-1:1;if(0==(t&It))return o*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&Et)*r,r*=128,t<It)return o*n;if(n>Ot)throw qt}throw zt},e=>en(e,4).getFloat32(0,!1),e=>en(e,8).getFloat64(0,!1),e=>en(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Qt,e=>{const t=Zt(e),n={};for(let r=0;r<t;r++){n[Qt(e)]=rn(e)}return n},e=>{const t=Zt(e),n=[];for(let r=0;r<t;r++)n.push(rn(e));return n},Yt],rn=e=>nn[127-Xt(e)](e);function on(e){return C(this,arguments,(function*(){var t,n,r,o;let i=0,s=new Uint8Array(4),a=0,c=[],l=0;try{for(var u,d=!0,f=P(e);!(t=(u=yield U(f.next())).done);d=!0){o=u.value,d=!1;const e=o,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(i){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===a)break;s[a++]=t,++n}if(a<4)break}else if(a>0&&a<4)for(const t of e.slice(n,n+4-a))s[a++]=t,++n;case 1:l=4===a?new DataView(s.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),a?a=0:n+=4;case 2:if(n>=e.byteLength){i=2;break}if(n+l>e.byteLength)c.push(e.slice(n)),l-=e.byteLength-n,i=2,n=e.byteLength;else{if(c.length>0){const t=new Uint8Array(c.reduce(((e,t)=>e+t.byteLength),l));let r=0;for(const e of c)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+l),r),c=[],yield yield U(t)}else yield yield U(e.slice(n,n+l));n+=l,i=0}}}}catch(e){n={error:e}}finally{try{d||t||!(r=f.return)||(yield U(r.call(f)))}finally{if(n)throw n.error}}}))}class sn extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function an(t,n){return new Promise(((r,o)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),o(new e.AbortError("User cancelled"))}});t.next(i)}))}function cn(e,t,...n){return an(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function ln(e,t,n){return I(this,void 0,void 0,(function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield an(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 un(e,t,n){return I(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 an(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return o}))}function dn(e){var t,n,r;return I(this,void 0,void 0,(function*(){const o=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:s,refreshToken:a,refreshTokenExpiration:c,claims:l}=o;if(!i)return null;if((null!==(t=null==s?void 0:s.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=o.license)||void 0===n?void 0:n.status)||"ok"))return o;if(!a)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const u=yield pn(e.cloud.options.databaseUrl,o);return yield e.table("$logins").update(l.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license}),u}))}function fn(t,n,r,o,i){return I(this,void 0,void 0,(function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield pn(t,n):yield function(t,n,r,o){return I(this,void 0,void 0,(function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:i,publicKey:s}=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(!i||!s)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=i;const a=function(e){const t=ot(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",s));t.publicKey=s;try{const e=yield n({public_key:a,hints:o});if("error"===e.type)throw new sn(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield an(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof sn)throw yield cn(r,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield cn(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw t}}))}(n,r,o,i)}))}function pn(e,t){return I(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=ot(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 l=yield c.json();if("error"===l.type)throw new sn(l);return t.accessToken=l.accessToken,t.accessTokenExpiration=l.accessTokenExpiration?new Date(l.accessTokenExpiration):void 0,t.claims=l.claims,t.license={type:l.userType,status:l.claims.license||"ok"},null!=l.evalDaysLeft&&(t.license.evalDaysLeft=l.evalDaysLeft),null!=l.userValidUntil&&(t.license.validUntil=new Date(l.userValidUntil)),l.data&&(t.data=l.data),t}))}const{toString:hn}={};const yn={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 vn(...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 yn;let i=n.get(r);if(void 0!==i)return i;const s=(o=e,hn.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:yn),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 mn={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 bn={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 gn={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var _n={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},wn={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},kn={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const Sn="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var xn=["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=Sn[t];return o&&new o(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function In(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=An[e[n]];return t}(ot(e))}function En(e){return rt(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+=On[e[n]];return t}(e))}const On={"-":"=",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:"+","|":"/"},An={};for(const e of Object.keys(On))An[On[e]]=e;var Tn={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:In(e)}),revive:({v:e})=>{const t=En(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Un{constructor(e,t){this.buf=e,this.type=t}}function Cn(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 Pn(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var jn={Blob:{test:(e,t)=>"Blob"===t||e instanceof Un,replace:e=>({$t:"Blob",v:ot(e instanceof Un?e.buf:Pn(Cn(e))),type:e.type}),revive:({type:e,v:t})=>{const n=rt(t);return void 0!==typeof Blob?new Blob([n]):new Un(n.buffer,e)}}};const $n={...bn,...gn,..._n,...wn,...kn,...xn,...Tn,...jn};function Dn(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 Ln={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}};const Nn="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Rn{toString(){return this.v}constructor(e){this.v=e}}const Bn=Object.assign(Object.assign(Object.assign({},Ln),Nn?{}:{bigint:{test:e=>e instanceof Rn,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Rn(e)}}),{PropModification:{test:e=>e instanceof t,replace:e=>Object.assign({$t:"PropModification"},e),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var o=0;for(r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]])}return n}(e,["$t"]);return new t(n)}}}),Mn=vn($n,Bn),Fn=function(...e){const t=vn($n,mn,...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 Dn(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 Dn(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)}}}(Bn);class Wn extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Vn(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 l=i;s.forEach(((t,r)=>{const o=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach(((t,s)=>{if(Array.isArray(t)){l===i&&(l=Kn(i,o));const e=l.muts[r],n=JSON.stringify(t);e.keys[s]=n}else if("#"===t[0]){l===i&&(l=Kn(i,o));const a=l.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${t}:${n.userId}`;a.keys[s]=u,o&&e.setByKeyPath(a.values[s],c.keyPath,u)}}))})),o.push(l)}return o}function Kn(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map((e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):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()})))})}let Hn=new WeakMap;function zn(e){var t,n;return I(this,void 0,void 0,(function*(){const r=(null!==(n=null===(t=Hn.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise((e=>setTimeout(e,r))))}))}function qn(e,t,n,r,o,i,s,a,c){return I(this,void 0,void 0,(function*(){const l={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield dn(o),d=null==u?void 0:u.accessToken;d&&(l.Authorization=`Bearer ${d}`);const f={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:a,schema:s||{},lastPull:n?{serverRevision:n.serverRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:r,changes:Vn(o.dx.core.schema,c,e),y:t};o.syncStateChangedEvent.next({phase:"pushing"});const p=yield fetch(`${i}/sync`,{method:"post",headers:l,credentials:"include",body:Mn.stringify(f)});if(o.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),o=t.headers.get("Ratelimit-Reset");if(n&&r&&o){const t=Number(n),i=Math.max(0,Number(r)),s=Number(o);if(i<t/2){const t=Math.ceil(s/(i+1));Hn.set(e,new Date(Date.now()+1e3*t))}else Hn.delete(e)}}(o,p),!p.ok)throw new Wn(p);if("application/x-bison"===p.headers.get("content-type"))return Fn.fromBinary(yield p.blob());{const e=yield p.text();return Mn.parse(e)}}))}function Jn(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Gn=!1;function Yn(e,t,n,r){return I(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 Xn(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 Zn(t,r,o){return I(this,void 0,void 0,(function*(){const i=yield t.bulkGet(r),s=[],a=[];r.forEach(((r,c)=>{const l=i[c];if(l){for(const[i,s]of Object.entries(o[c]))if(i===t.schema.primKey.keyPath){if(0!==n(s,r))throw new Error("Cannot change primary key")}else e.setByKeyPath(l,i,s);s.push(r),a.push(l)}})),yield null==t.schema.primKey.keyPath?t.bulkPut(a,s):t.bulkPut(a)}))}function Qn(t,n){return I(this,void 0,void 0,(function*(){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 Zn(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Gn=navigator.onLine,self.addEventListener("online",(()=>Gn=!0)),self.addEventListener("offline",(()=>Gn=!1)));const er="dexie-cloud-syncer";function tr(e,t){return e.where("i").between(t,1/0,!0).toArray()}function nr(e){const t=e.dx._options.Y;if(!t)throw new Error("Y library not supplied to Dexie constructor");return t}function rr(e,t,n){var r,o,i;const s=null===(i=null===(o=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===o?void 0:o.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;if(!s)throw new Error(`No updatesTable found for ${t}.${n}`);return e.table(s)}function or(e,t){return I(this,void 0,void 0,(function*(){const n={};for(const o of e)switch(o.type){case"u-s":{const e=rr(t,o.table,o.prop);n[e.name]=yield e.add({k:o.k,u:o.u});break}case"u-ack":{const e=rr(t,o.table,o.prop);yield t.transaction("rw",e,(t=>I(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(er);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:er}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,o.i+1)}))}))));break}case"u-reject":{const e=rr(t,o.table,o.prop);yield e.delete(o.i);break}case"in-sync":{const e=r.getDocCache(t.dx).find(o.table,o.k,o.prop);e&&!e.isSynced&&e.emit("sync",[!0]);break}}return n}))}const ir=1,sr=2,ar=3;function cr(t,n,{yDownloadedRealms:r,realms:o}){return I(this,void 0,void 0,(function*(){if(r&&o&&o.every((e=>"*"===r[e])))return;const i=yield dn(t),s={"Content-Type":"application/json",Accept:"application/octet-stream"};i&&(s.Authorization=`Bearer ${i.accessToken}`);const a=yield fetch(`${n}/y/download`,{body:Mn.stringify({downloadedRealms:r||{}}),method:"POST",headers:s,credentials:"include"});if(!a.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${a.status}`);yield async function(e,...t){var n,r,o;let i=e();for(let e=0;e<t.length;e++)i=t[e](i);try{for(var s,a=!0,c=P(i);!(n=(s=await c.next()).done);a=!0)s.value,a=!1}catch(e){r={error:e}}finally{try{a||n||!(o=c.return)||await o.call(c)}finally{if(r)throw r.error}}}(function(e){return function(){return C(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield U(t.read());if(e)return yield U(void 0);yield yield U(n)}}finally{t.releaseLock()}}))}}(a),on,(function(r){return C(this,arguments,(function*(){var o,i,s,a;let c=null,l=null,u=null,d=[];function f(e){return I(this,void 0,void 0,(function*(){const r=d[d.length-1];if(d.length>0){if(!c||!l||!u)throw new Error(`Protocol error from ${n}/y/download`);const e=rr(t,l,u);yield e.bulkAdd(d),d=[]}c&&(l&&u&&r||e)&&(yield t.$syncState.update("syncState",(t=>{const n=t.yDownloadedRealms||{};n[c]=e?"*":{tbl:l,prop:u,key:r.k},t.yDownloadedRealms=n})))}))}try{try{for(var p,h=!0,y=P(r);!(o=(p=yield U(y.next())).done);h=!0){a=p.value,h=!1;const e=new Jt(a);for(;Gt(e);)switch(Xt(e)){case ir:yield U(f(!0)),c=Qt(e);break;case sr:yield U(f(!1)),l=Qt(e),u=Qt(e);break;case ar:{const t=rn(e),n=Yt(e);d.push({k:t,u:n});break}}yield U(f(!1))}}catch(e){i={error:e}}finally{try{h||o||!(s=y.return)||(yield U(s.call(y)))}finally{if(i)throw i.error}}yield U(f(!0))}catch(t){throw t instanceof e.DexieError||(yield U(f(!1))),t}}))}))}))}const lr="currentSyncWorker";function ur(e,t,n,r){return dr.apply(this,arguments).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((o=>I(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(o):Gn&&(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 ur(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+o}),e.syncStateChangedEvent.next({phase:Gn?"error":"offline",error:new Error(""+(null==o?void 0:o.message)||o)}),Promise.reject(o))}))))}function dr(e,t,n,{isInitialSync:r,cancelToken:o,justCheckIfNeeded:i,purpose:s}={isInitialSync:!1}){var a;return I(this,void 0,void 0,(function*(){if(!(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,l=yield e.getCurrentUser(),u=l.isLoggedIn?st(e):[],d=u.map((t=>e.table(at(t.name)))),f=yield e.getPersistedSyncState(),p=!r&&l.isLoggedIn,h=p?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return st(e).filter((e=>!n.includes(e.name)))}(e,f):[];Jn(o);const y=h.length>0;if(y){if(i)return!0;yield e.transaction("rw",h,(e=>I(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return I(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!==j.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!==j.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==j.userId||(e.owner=t.userId),e.realmId&&e.realmId!==j.userId||(e.realmId=t.userId))})))}))}(h,l,null==f?void 0:f.realms)})))),Jn(o)}const[v,m,b,{yMessages:g,lastUpdateIds:_}]=yield e.transaction("r",e.tables,(()=>I(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState(),r=yield e.$baseRevs.toArray();let i=yield dt(d);const s=yield function(e,t){return I(this,void 0,void 0,(function*(){const n=[],r={};for(const o of t)if(o.schema.yProps)for(const t of o.schema.yProps){const i=nr(e),s=e.table(t.updatesTable),a=yield s.get(er),c=(null==a?void 0:a.unsentFrom)||1,l=(null==a?void 0:a.receivedUntil)||0,u=Math.min(c,l+1),d=yield tr(s,u);d.length>0&&(r[s.name]=d[d.length-1].i);const f={};for(const e of d){const t=1==(1&(e.f||0));if(t&&e.i<c)continue;const n=JSON.stringify(e.k)+"/"+t;let r=f[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(f[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:s,i:a}of Object.values(f)){const c=1===s.length?s[0]:i.mergeUpdatesV2(s);if(r)n.push({type:"u-c",table:o.name,prop:t.prop,k:e,u:c,i:a});else{const r=i.encodeStateVectorFromUpdateV2(c);n.push({type:"sv",table:o.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,u);if(Jn(o),y){const e=[...(null==f?void 0:f.realms)||[],...(null==f?void 0:f.inviteRealms)||[]],a=yield function(e,t,n,r){return I(this,void 0,void 0,(function*(){const o=`upload-${ft(8)}`;if(t.isLoggedIn&&e.length>0){const i=new Set(r||[]);return(yield Promise.all(e.map((e=>I(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||"")&&bt(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,l,n,e);return Jn(o),i=i.concat(a),[i,t,r,s]}return[i,t,r,s]})))),w=v.some((e=>e.muts.some((e=>e.keys.length>0))))||g.some((e=>"u-c"===e.type));if(i)return w;if("push"===s&&!w)return!1;const k=Xn(v,null==m?void 0:m.latestRevisions),S=(null==m?void 0:m.clientIdentity)||vt(16);Jn(o);const x=yield qn(v,g,m,b,e,c,n,S,l),{done:E,newSyncState:O}=yield e.transaction("rw",e.tables,(t=>I(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))x.schema[e]&&(n[e]=x.schema[e]);yield e.$syncState.put(n,"schema");const r=yield dt(d,0,{since:k});for(const t of d){const n=ct(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(k[n]){const r=k[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()])}Xn(r,k),yield Yn(e,n,k,x.serverRevision);const o=yield e.getPersistedSyncState();yield function(e,t,n){return I(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=st(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())}}if(o.size>0){const t={};for(const e of o)t[`yDownloadedRealms.${e}`]=void 0;yield e.$syncState.update("syncState",t)}}))}(e,x,o);const i=o||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:S};p&&(i.syncedTables=u.map((e=>e.name)).concat(h.map((e=>e.name)))),i.latestRevisions=k,i.remoteDbId=x.dbId,i.initiallySynced=!0,i.realms=x.realms,i.inviteRealms=x.inviteRealms,i.serverRevision=x.serverRevision,i.timestamp=new Date,delete i.error;const s=fr(x.changes,r);if(yield Qn(s,e),x.yMessages){const t=yield or(x.yMessages,e);yield function(e,t,n,r){var o,i,s,a,c;return I(this,void 0,void 0,(function*(){const l={};for(const[t,n]of Object.entries(e))null!==(o=l[t])&&void 0!==o||(l[t]={}),l[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=l[e])&&void 0!==i||(l[e]={}),l[e].receivedUntil=n;const u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=l[e],o=null!==(s=null==t?void 0:t.unsentFrom)&&void 0!==s?s:1,i=null!==(c=null!==(a=null==t?void 0:t.receivedUntil)&&void 0!==a?a:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==c?c:0;yield n.transaction("rw",e,(()=>I(this,void 0,void 0,(function*(){const t=yield n.table(e).get(er);t?(t.unsentFrom=Math.max(o,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),t.serverRev=r,yield n.table(e).put(t)):yield n.table(e).add({i:er,unsentFrom:o,receivedUntil:i,serverRev:r})}))))}}))}(_,t,e,x.serverRevision)}return e.$syncState.put(i,"syncState"),{done:0===r.length,newSyncState:i}}))));if(!E)return yield zn(e),yield dr(e,t,n,{isInitialSync:r,cancelToken:o});const A=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),T=!!x.yMessages;return A&&T&&(yield cr(e,c,O)),e.syncCompleteEvent.next(),!1}))}function fr(e,t){const n={};wt(n,e);const r={};return wt(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))yt(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=vt(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)}const pr=10,hr=1e4,yr=1e3;function vr(t){const n=[],r=new s(!0),o=new s(null);let i=!1,c=new Array(pr).fill(0);return o.subscribe((()=>I(this,void 0,void 0,(function*(){if(!i&&n.length>0){i=!0,c.shift(),c.push(Date.now()),r.next(!1);try{yield function(){var r,o,i,s,c,l;return I(this,void 0,void 0,(function*(){for(;n.length>0;){const u=n.shift();try{yield a(t.cloud.syncState.pipe(Ge((({phase:e})=>"in-sync"===e||"error"===e))));const n=t.cloud.persistedSyncState.value;if(!u)continue;switch(u.type){case"token-expired":const a=t.cloud.currentUser.value,d=yield pn(t.cloud.options.databaseUrl,a);yield t.table("$logins").update(a.userId,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data});break;case"realm-added":(null===(r=null==n?void 0:n.realms)||void 0===r?void 0:r.includes(u.realm))||(null===(o=null==n?void 0:n.inviteRealms)||void 0===o?void 0:o.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(i=null==n?void 0:n.realms)||void 0===i?void 0:i.includes(u.realm))||(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(s=null==n?void 0:n.realms)||void 0===s?void 0:s.includes(u.realm))||(null===(c=null==n?void 0:n.inviteRealms)||void 0===c?void 0:c.includes(u.realm)))&&(yield t.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield t.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(l=t.cloud.syncState.value)||void 0===l?void 0:l.phase)){nt(t,"pull");break}yield t.transaction("rw",t.dx.tables,(n=>I(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(!o||!r||!i)return;if(u.baseRev!==o.serverRevision)return void("string"!=typeof u.baseRev||"bigint"!=typeof o.serverRevision&&"object"!=typeof o.serverRevision||nt(t,"pull"));if((yield e.waitFor(it(o)))!==u.realmSetHash)return void nt(t,"pull");let s=[];if(i.isLoggedIn){const e=st(t).map((e=>t.table(at(e.name))));s=yield dt(e)}if(u.changes.length>0){const e=fr(u.changes,s);yield Qn(e,t)}o.latestRevisions=Xn(s,o.latestRevisions),o.serverRevision=u.newRev,yield Yn(t,r,o.latestRevisions,u.newRev),yield t.$syncState.put(o,"syncState")}))))}}catch(e){}}}))}()}finally{c[c.length-1]-c[0]<hr&&(yield new Promise((e=>setTimeout(e,yr)))),i=!1,r.next(!0)}}})))),{enqueue:function(e){n.push(e),o.next(null)},readyToServe:r}}const mr=new WeakMap,br={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let gr=0;function _r(e){"vip"in e&&(e=e.vip);let t=mr.get(e.cloud);if(!t){const n=new c;let r=new R(`syncstatechanged-${e.name}`),o=new R(`synccomplete-${e.name}`);n.id=++gr;let i=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return i},localSyncEvent:n,get syncStateChangedEvent(){return r},get syncCompleteEvent(){return o},dx:e};const s={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||j)),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){i=e},reconfigure(){r=new R(`syncstatechanged-${e.name}`),o=new R(`synccomplete-${e.name}`)}};Object.assign(t,s),t.messageConsumer=vr(t),t.messageProducer=new c,mr.set(e.cloud,t)}return t}const wr=new WeakMap;class kr{constructor(e,t){wr.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new kr(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return I(this,void 0,void 0,(function*(){wr.get(this).table("$logins").put(this)}))}}function Sr(e,t){return a(l(e).pipe(u(t)))}function xr(e){return I(this,void 0,void 0,(function*(){const t=yield Ir(e);if(t){if(!(yield function(e,t,n){return I(this,void 0,void 0,(function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield an(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then((()=>!0)).catch((()=>!1))}))}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield Ir(e,{deleteUnsyncedData:!0})}}))}function Ir(e,{deleteUnsyncedData:t=!1}={}){return I(this,void 0,void 0,(function*(){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>I(this,void 0,void 0,(function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const o=n.storeNames.filter((e=>e.endsWith("_mutations"))),i=(yield Promise.all(o.map((e=>n.table(e).count())))).reduce(((e,t)=>e+t),0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}))));return r&&(yield Sr(e.cloud.currentUser,(e=>e.userId===j.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}function Er(e,...t){globalThis.console[e](...t)}function Or(e,t){var n;return I(this,void 0,void 0,(function*(){const r=yield e.getCurrentUser(),o=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield dn(e),!1}const i=new kr(e,{claims:{},lastLogin:new Date(0)});return yield fn(e.cloud.options.databaseUrl,i,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function({public_key:n,hints:r}){var o;return I(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.");if("demo"===(null==r?void 0:r.grant_type))i={demo_user:yield ln(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};else if((null==r?void 0:r.otpId)&&r.otp)i={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield ln(t,"Enter email address",null==r?void 0:r.email);i=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}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 cn(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new Wn(a,e)}const c=yield a.json();if("tokens"===c.type||"error"===c.type)return c;if("otp"===i.grant_type&&"email"in i){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${s}/token`);const e=yield un(t,i.email),r=Object.assign(Object.assign({},i),{otp:e||"",otp_id:c.otp_id,public_key:n});let o=yield fetch(`${s}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===o.status;){const e=yield o.text();r.otp=yield un(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),o=yield fetch(`${s}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==o.status){const e=yield o.text();throw new Wn(o,e)}return yield o.json()}throw new Error(`Unexpected response from ${s}/token`)}))}}(e),e.cloud.userInteraction,t),o!==j.userId&&i.userId!==o&&(yield xr(e)),yield function(e,t){return I(this,void 0,void 0,(function*(){if(t.userId===e.cloud.currentUserId)return;const n=e.table("$logins");yield e.transaction("rw",n,(e=>I(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;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(Er("debug","Login context property names:",Object.keys(t)),Er("debug","Login context property names:",Object.keys(t)),Er("debug","Login context:",t),Er("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield Sr(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,i),nt(e,"pull"),i.userId!==o}))}const Ar="undefined"!=typeof InstallTrigger,Tr="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Ur=Tr?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Cr=Tr&&Ur<=605||Ar,Pr="undefined"!=typeof self&&"clients"in self&&!self.document;function jr(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}const{toString:$r}={};function Dr(e){return $r.call(e).slice(8,-1)}function Lr(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 Nr=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Rr=0;function Br(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),o=Date.now();Rr>=o?++Rr:Rr=o,r[0]=Rr/1099511627776,r[1]=Rr/4294967296,r[2]=Rr/16777216,r[3]=Rr/65536,r[4]=Rr/256,r[5]=Rr;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+In(new Uint8Array(n.buffer))+(t||"")}function Mr(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=Lr(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=Lr(o.schema.primaryKey,n);return a.forEach(((c,l)=>{if(void 0===c){const r=n.values[l].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);a[l]=Br(i,c),o.schema.primaryKey.outbound||(s||(s=n.values.slice()),s[l]=e.deepClone(s[l]),e.setByKeyPath(s[l],o.schema.primaryKey.keyPath,a[l]))}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){Lr(o.schema.primaryKey,n).forEach(((t,n)=>{if(!bt(t)){const n=Array.isArray(t)?t.map(Dr).join(","):Dr(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 Fr=0;function Wr(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 Vr(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 Kr=new s(new Set);function Hr(e){var t,n,r,o;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)}function zr({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){jr()}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=>at(e)));i=n.transaction([...r,...e],o)}else i=n.transaction(r,o);if("readwrite"===o){i.txid=ft(16),i.opCount=0,i.currentUser=e.value,Kr.value.add(i),Kr.next(Kr.value);const n=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",n),i.removeEventListener("abort",n),Kr.value.delete(i),Kr.next(Kr.value)},r=()=>{i.mutationsAdded&&!Hr(t)&&nt(t,"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=>Promise.reject(e)))}):r;const{schema:i}=r,s=o.get(e);return function(e){const t="$lock"+ ++Fr;return Object.assign(Object.assign({},e),{count:Wr(e.count,t),get:Wr(e.get,t),getMany:Wr(e.getMany,t),openCursor:Wr(e.openCursor,t),query:Wr(e.query,t),mutate:Vr(e.mutate,t)})}(Object.assign(Object.assign({},r),{mutate:n=>{var o,s,c;const l=n.trans;return l.txid?l.disableChangeTracking?r.mutate(n):(null===(s=null===(o=t.cloud.schema)||void 0===o?void 0:o[e])||void 0===s?void 0:s.markedForSync)&&(null===(c=l.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:a}=e,c=++t.opCount;return r.mutate(e).then((r=>{const{numFailures:l,failures:u}=r;let d="delete"===a?e.keys:r.results,f="values"in e?e.values:[],p="updates"in e&&e.updates;l&&(d=d.filter(((e,t)=>!u[t])),f=f.filter(((e,t)=>!u[t])));const h=Date.now(),y="criteria"in e&&e.criteria?Object.assign(Object.assign({},e.criteria),{index:e.criteria.index===i.primaryKey.keyPath?null:e.criteria.index}):void 0,v="delete"===e.type?{type:"delete",ts:h,opNo:c,keys:d,criteria:y,txid:n,userId:o}:"add"===e.type?{type:"insert",ts:h,opNo:c,keys:d,txid:n,userId:o,values:f}:y&&e.changeSpec?{type:"modify",ts:h,opNo:c,keys:d,criteria:y,changeSpec:e.changeSpec,txid:n,userId:o}:p?{type:"update",ts:h,opNo:c,keys:p.keys,changeSpecs:p.changeSpecs,txid:n,userId:o}:{type:"upsert",ts:h,opNo:c,keys:d,values:f,txid:n,userId:o};return"isAdditionalChunk"in e&&e.isAdditionalChunk&&(v.isAdditionalChunk=!0),d.length>0||y?s.mutate({type:"add",trans:t,values:[v]}).then((()=>r)):r}))}}})}}}function qr(e,t){return function(n,r){var o;const i=Object.assign(Object.assign({},br),n);Object.keys(br).forEach((e=>{const t=i[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map((e=>e.trim())),o=br[e].split(",").map((e=>e.trim())),s=new Set(r.map((e=>e.replace(/([&*]|\+\+)/g,""))));if(r[0]!==o[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(br[e])}`);for(let t=1;t<o.length;++t){const n=o[t];s.has(n.replace(/([&*]|\+\+)/g,""))||(i[e]+=`,${n}`)}}));const s=t.cloud.schema||(t.cloud.schema={}),a=new Set;Object.keys(i).forEach((e=>{const t=i[e],n=s[e]||(s[e]={});null!=t?(/^\@/.test(t)&&(i[e]=i[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)(Nr.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,a),a.add(n.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,i[`$${e}_mutations`]=null)}));const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(o=t.yProps)||void 0===o?void 0:o.length){const n=s[e];n&&(n.yProps=t.yProps.map((e=>e.prop)))}return c}}const Jr=new s(!0),Gr=new s(!0);Jr.pipe(Ze((e=>e?f(!0):f(!1).pipe(ze(2e4)))),qe()).subscribe(Gr);const Yr="undefined"!=typeof document?d(document,"visibilitychange"):f({}),Xr=Yr.pipe(Ge((()=>"hidden"===document.visibilityState))),Zr=Yr.pipe(Ge((()=>"visible"===document.visibilityState))),Qr="undefined"!=typeof window?p(Zr,d(window,"mousedown"),d(window,"mousemove"),d(window,"keydown"),d(window,"wheel"),d(window,"touchmove")):f({});"undefined"!=typeof document&&p(f(!0),Xr,Qr).pipe(Re((()=>"visible"===document.visibilityState)),Qe((e=>{Jr.value!==e&&Jr.next(e)})),Ze((e=>e?f(0).pipe(ze(16e4),Qe((()=>Jr.next(!1)))):f(0)))).subscribe((()=>{}));class eo extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}function to(t){var n,r;if(!(null===(n=t.cloud.options)||void 0===n?void 0:n.awarenessProtocol))throw new e.MissingAPIError('awarenessProtocol was not provided to db.cloud.configure(). Please import * as awarenessProtocol from "y-protocols/awareness".');return null===(r=t.cloud.options)||void 0===r?void 0:r.awarenessProtocol}const no=new WeakMap;class ro extends i{constructor(e,t,n,r,o,i,s){super((a=>new io(e,t,n,r,s,a,o,i)))}}let oo=0;class io extends m{constructor(e,t,n,r,o,i,s,a){super((()=>this.teardown())),this.id=++oo,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.realmSetHash=n,this.clientIdentity=r,this.user=o,this.subscriber=i,this.lastUserActivity=new Date,this.messageProducer=s,this.webSocketStatus=a,this.connect()}teardown(){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;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch((()=>{})).then((()=>this.reconnecting=!1))}}connect(){return I(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;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;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new eo);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>I(this,void 0,void 0,(function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout((()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())}),2e4)}catch(e){this.reconnect()}else this.reconnect()}))),3e4);const t=new URL(this.databaseUrl);t.protocol="http:"===t.protocol?"ws":"wss";const n=new URLSearchParams;if(this.subscriber.closed)return;n.set("v","2"),n.set("rev",this.rev),n.set("realmsHash",this.realmSetHash),n.set("clientId",this.clientIdentity),this.user.accessToken&&n.set("token",this.user.accessToken);const i=this.ws=new WebSocket(`${t}/changes?${n}`);i.binaryType="arraybuffer",i.onclose=e=>{this.pinger&&this.reconnect()},i.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?Mn.parse(e.data):function(e){const t=new Jt(e),n=Qt(t),r=Qt(t),o=Qt(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:o,i:Number(tn(t))};default:{const e=rn(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:o,k:e};case"aware":case"u-s":return{type:n,table:r,prop:o,k:e,u:Yt(t)};case"doc-open":return{type:n,table:r,prop:o,k:e,serverRev:rn(t),sv:rn(t)};case"sv":return{type:n,table:r,prop:o,k:e,sv:Yt(t)};case"u-c":return{type:n,table:r,prop:o,k:e,u:Yt(t),i:Number(tn(t))};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("rev"===t.type)this.rev=t.rev;else if("aware"===t.type){const e=r.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>no.get(e))(e);if(n){to(this.db).applyAwarenessUpdate(n,t.u,"server")}}}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type?or([t],this.db):"pong"!==t.type&&this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{i.onopen=n=>{e=!0,t(null)},i.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?null===(t=this.ws)||void 0===t||t.send(Mn.stringify(e)):null===(n=this.ws)||void 0===n||n.send(Kt(e)))}))),this.user.isLoggedIn&&!Hr(this.db)&&this.subscriptions.add(function(e){const t=ut(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return p(...t.map((({table:t,ydocProp:n,updatesTable:r})=>{const i=e.table(r);return l(i.get(er)).pipe(h((e=>{let r=(null==e?void 0:e.unsentFrom)||1;return l(o((()=>I(this,void 0,void 0,(function*(){return(yield tr(i,r)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:t,prop:n,k:e.k,u:e.u,i:e.i})))}))))).pipe(y((e=>{e.length>0&&(r=e.at(-1).i+1)})))})))}))).pipe(v((e=>e)),y((e=>{})))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class so extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function ao(e){return I(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield a(Qr)}))}function co(e){var t;return I(this,void 0,void 0,(function*(){return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield ur(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const lo=new WeakMap;function uo(e,t,n,r){const o=lo.get(e);if(o){if(o.pull||"push"===(null==r?void 0:r.purpose))return 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 uo(e,t,n,r)}))}}const i=function(){return I(this,void 0,void 0,(function*(){try{if(yield zn(e),e.cloud.isServiceWorkerDB)yield ur(e,t,n,r);else{if(e.cloud.usingServiceWorker)throw pt(!1),new Error("Internal _syncIfPossible() - invalid precondition - should not have been called.");yield function(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}(e,lr,(()=>ur(e,t,n,r)))}lo.delete(e)}catch(t){throw lo.delete(e),t}}))}();return lo.set(e,{promise:i,pull:"push"!==(null==r?void 0:r.purpose)}),i}const fo=6e4;function po(e,t,n){let r=null,o={cancelled:!1},i=null,s=null;function a(r,l=1){setTimeout((()=>{i&&clearTimeout(i);const u="pull"===s?"pull":r;i=null,s=null,uo(e,t,n,{cancelToken:o,retryImmediatelyOnFetchError:!0,purpose:u}).catch((e=>{if(o.cancelled)c();else if(l<3){const e=s&&"pull"===s?"pull":r,t=setTimeout((()=>a(e,l+1)),[0,5,15][l]*fo);i&&clearTimeout(i),i=t,s=e}}))}),0)}const c=()=>{o.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{try{a(e||"pull")}catch(e){}}))},stop:c}}function ho(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var yo,vo,mo,bo,go,_o={},wo=[],ko=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function So(e,t){for(var n in t)e[n]=t[n];return e}function xo(e){var t=e.parentNode;t&&t.removeChild(e)}function Io(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?yo.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 Eo(e,s,r,o,null)}function Eo(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?++mo:o};return null==o&&null!=vo.vnode&&vo.vnode(i),i}function Oo(e){return e.children}function Ao(e,t){this.props=e,this.context=t}function To(e,t){if(null==t)return e.__?To(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?To(e):null}function Uo(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 Uo(e)}}function Co(e){(!e.__d&&(e.__d=!0)&&bo.push(e)&&!Po.__r++||go!==vo.debounceRendering)&&((go=vo.debounceRendering)||setTimeout)(Po)}function Po(){for(var e;Po.__r=bo.length;)e=bo.sort((function(e,t){return e.__v.__b-t.__v.__b})),bo=[],e.some((function(e){var t,n,r,o,i,s;e.__d&&(i=(o=(t=e).__v).__e,(s=t.__P)&&(n=[],(r=So({},o)).__v=o.__v+1,Mo(s,o,r,t.__n,void 0!==s.ownerSVGElement,null!=o.__h?[i]:null,n,null==i?To(o):i,o.__h),Fo(n,o),o.__e!=i&&Uo(o)))}))}function jo(e,t,n,r,o,i,s,a,c,l){var u,d,f,p,h,y,v,m=r&&r.__k||wo,b=m.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(p=n.__k[u]=null==(p=t[u])||"boolean"==typeof p?null:"string"==typeof p||"number"==typeof p||"bigint"==typeof p?Eo(null,p,null,null,p):Array.isArray(p)?Eo(Oo,{children:p},null,null,null):p.__b>0?Eo(p.type,p.props,p.key,null,p.__v):p)){if(p.__=n,p.__b=n.__b+1,null===(f=m[u])||f&&p.key==f.key&&p.type===f.type)m[u]=void 0;else for(d=0;d<b;d++){if((f=m[d])&&p.key==f.key&&p.type===f.type){m[d]=void 0;break}f=null}Mo(e,p,f=f||_o,o,i,s,a,c,l),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=$o(p,c,e):c=Do(e,p,f,m,h,c),"function"==typeof n.type&&(n.__d=c)):c&&f.__e==c&&c.parentNode!=e&&(c=To(f))}for(n.__e=y,u=b;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=To(r,u+1)),Ko(m[u],m[u]));if(v)for(u=0;u<v.length;u++)Vo(v[u],v[++u],v[++u])}function $o(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?$o(r,t,n):Do(n,r,r,o,r.__e,t));return t}function Do(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 Lo(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||ko.test(t)?n:n+"px"}function No(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||Lo(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||Lo(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?Bo:Ro,i):e.removeEventListener(t,i?Bo:Ro,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 Ro(e){this.l[e.type+!1](vo.event?vo.event(e):e)}function Bo(e){this.l[e.type+!0](vo.event?vo.event(e):e)}function Mo(e,t,n,r,o,i,s,a,c){var l,u,d,f,p,h,y,v,m,b,g,_,w,k=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]),(l=vo.__b)&&l(t);try{e:if("function"==typeof k){if(v=t.props,m=(l=k.contextType)&&r[l.__c],b=l?m?m.props.value:l.__:r,n.__c?y=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(v,b):(t.__c=u=new Ao(v,b),u.constructor=k,u.render=Ho),m&&m.sub(u),u.props=v,u.state||(u.state={}),u.context=b,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=So({},u.__s)),So(u.__s,k.getDerivedStateFromProps(v,u.__s))),f=u.props,p=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&v!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(v,b),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(v,u.__s,b)||t.__v===n.__v){u.props=v,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&s.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(v,u.__s,b),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(f,p,h)}))}if(u.context=b,u.props=v,u.__v=t,u.__P=e,g=vo.__r,_=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,g&&g(t),l=u.render(u.props,u.state,u.context);else do{u.__d=!1,g&&g(t),l=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++_<25);u.state=u.__s,null!=u.getChildContext&&(r=So(So({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(h=u.getSnapshotBeforeUpdate(f,p)),w=null!=l&&l.type===Oo&&null==l.key?l.props.children:l,jo(e,Array.isArray(w)?w:[w],t,n,r,o,i,s,a,c),u.base=t.__e,t.__h=null,u.__h.length&&s.push(u),y&&(u.__E=u.__=null),u.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=Wo(n.__e,t,n,r,o,i,s,c);(l=vo.diffed)&&l(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=a,t.__h=!!c,i[i.indexOf(a)]=null),vo.__e(e,t,n)}}function Fo(e,t){vo.__c&&vo.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){vo.__e(e,t.__v)}}))}function Wo(e,t,n,r,o,i,s,a){var c,l,u,d=n.props,f=t.props,p=t.type,h=0;if("svg"===p&&(o=!0),null!=i)for(;h<i.length;h++)if((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&&yo.call(e.childNodes),l=(d=n.props||_o).dangerouslySetInnerHTML,u=f.dangerouslySetInnerHTML,!a){if(null!=i)for(d={},h=0;h<e.attributes.length;h++)d[e.attributes[h].name]=e.attributes[h].value;(u||l)&&(u&&(l&&u.__html==l.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,o){var i;for(i in n)"children"===i||"key"===i||i in t||No(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]||No(e,i,t[i],n[i],r)}(e,f,d,o,a),u)t.__k=[];else if(h=t.props.children,jo(e,Array.isArray(h)?h:[h],t,n,r,o&&"foreignObject"!==p,i,s,i?i[0]:n.__k&&To(n,0),a),null!=i)for(h=i.length;h--;)null!=i[h]&&xo(i[h]);a||("value"in f&&void 0!==(h=f.value)&&(h!==e.value||"progress"===p&&!h||"option"===p&&h!==d.value)&&No(e,"value",h,d.value,!1),"checked"in f&&void 0!==(h=f.checked)&&h!==e.checked&&No(e,"checked",h,d.checked,!1))}return e}function Vo(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){vo.__e(e,n)}}function Ko(e,t,n){var r,o;if(vo.unmount&&vo.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Vo(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){vo.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(o=0;o<r.length;o++)r[o]&&Ko(r[o],t,"function"!=typeof e.type);n||null==e.__e||xo(e.__e),e.__e=e.__d=void 0}function Ho(e,t,n){return this.constructor(e,n)}function zo(e,t,n){var r,o,i;vo.__&&vo.__(e,t),o=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Mo(t,e=(!r&&n||t).__k=Io(Oo,null,[e]),o||_o,_o,void 0!==t.ownerSVGElement,!r&&n?[n]:o?null:t.firstChild?yo.call(t.childNodes):null,i,!r&&n?n:o?o.__e:t.firstChild,r),Fo(i,e)}yo=wo.slice,vo={__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}},mo=0,Ao.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=So({},this.state),"function"==typeof e&&(e=e(So({},n),this.props)),e&&So(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Co(this))},Ao.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Co(this))},Ao.prototype.render=Oo,bo=[],Po.__r=0;const qo={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},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",fontFamily:"sans-serif"},Input:{height:"35px",width:"17em",borderColor:"#ccf4",outline:"none",fontSize:"17pt",padding:"8px"}};function Jo({children:e,className:t}){return Io("div",{className:t},Io("div",{style:qo.Darken}),Io("div",{style:qo.DialogOuter},Io("div",{style:qo.DialogInner},e)))}var Go,Yo,Xo,Zo,Qo=0,ei=[],ti=[],ni=vo.__b,ri=vo.__r,oi=vo.diffed,ii=vo.__c,si=vo.unmount;function ai(e,t){vo.__h&&vo.__h(Yo,e,Qo||t),Qo=0;var n=Yo.__H||(Yo.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:ti}),n.__[e]}function ci(e){return Qo=1,function(e,t,n){var r=ai(Go++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):yi(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=Yo,!Yo.u)){Yo.u=!0;var o=Yo.shouldComponentUpdate;Yo.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.__}(yi,e)}function li(e){return Qo=5,function(e,t){var n=ai(Go++,7);return hi(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function ui(){for(var e;e=ei.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(fi),e.__H.__h.forEach(pi),e.__H.__h=[]}catch(t){e.__H.__h=[],vo.__e(t,e.__v)}}vo.__b=function(e){Yo=null,ni&&ni(e)},vo.__r=function(e){ri&&ri(e),Go=0;var t=(Yo=e.__c).__H;t&&(Xo===Yo?(t.__h=[],Yo.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=ti,e.__N=e.i=void 0}))):(t.__h.forEach(fi),t.__h.forEach(pi),t.__h=[])),Xo=Yo},vo.diffed=function(e){oi&&oi(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==ei.push(t)&&Zo===vo.requestAnimationFrame||((Zo=vo.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),di&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);di&&(t=requestAnimationFrame(n))})(ui)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==ti&&(e.__=e.__V),e.i=void 0,e.__V=ti}))),Xo=Yo=null},vo.__c=function(e,t){t.some((function(e){try{e.__h.forEach(fi),e.__h=e.__h.filter((function(e){return!e.__||pi(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],vo.__e(n,e.__v)}})),ii&&ii(e,t)},vo.unmount=function(e){si&&si(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{fi(e)}catch(e){t=e}})),t&&vo.__e(t,n.__v))};var di="function"==typeof requestAnimationFrame;function fi(e){var t=Yo,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Yo=t}function pi(e){var t=Yo;e.__c=e.__(),Yo=t}function hi(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function yi(e,t){return"function"==typeof t?t(e):t}function vi({title:e,type:t,alerts:n,fields:r,submitLabel:o,cancelLabel:i,onCancel:s,onSubmit:a}){const[c,l]=ci({}),u=li(null);return function(e,t){var n=ai(Go++,4);!vo.__s&&hi(n.__H,t)&&(n.__=e,n.i=t,Yo.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Io(Jo,{className:"dxc-login-dlg"},Io(Oo,null,Io("h3",{style:qo.WindowHeader},e),n.map((e=>Io("p",{style:qo.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}(e)))),Io("form",{onSubmit:e=>{e.preventDefault(),a(c)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],o)=>Io("label",{style:qo.Label,key:o},n?`${n}: `:"",Io("input",{ref:0===o?u:void 0,type:t,name:e,autoComplete:"on",style:qo.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const o=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let i=Object.assign(Object.assign({},c),{[e]:o});l(i),"otp"===t&&8===(null==o?void 0:o.trim().length)&&a(i)}})))))),Io("div",{style:qo.ButtonsDiv},Io(Oo,null,Io("button",{type:"submit",style:qo.Button,onClick:()=>a(c)},o),i&&Io("button",{style:qo.Button,onClick:s},i))))}class mi extends Ao{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?Io(vi,Object.assign({},t)):null}}function bi(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const gi=bi((e=>new s(j)));function _i(e,t){let n=t,r=l(e).pipe(_((e=>n=e)),w({resetOnRefCountZero:()=>k(1e3)}));const o=new i((e=>{let t=!1;const o=r.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||o.closed||e.next(n),o}));return o.getValue=()=>n,o}const wi=bi((e=>_i(o((()=>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})))),{}))),ki=bi((e=>_i(gi(e._novip).pipe(Ze((t=>o((()=>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 Si(...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 xi=bi((e=>function(e,t){let n;const r=e.pipe(_((e=>n=t(e))));return r.getValue=()=>void 0!==n?n:n=t(e.getValue()),r}(_i(g([ki(e._novip),wi(e._novip)]).pipe(Re((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:j.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=ut(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:"*"}:Si(...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 Ii{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 Ei=bi((e=>{const t=gi(e._novip).pipe(Ze((t=>o((()=>e.members.where({email:t.email||""}).toArray()))))),n=xi(e._novip),r=ki(e._novip);return _i(g([t,r,n]).pipe(Re((([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)).map((t=>Object.assign(Object.assign({},t),{accept(){return I(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return I(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function Oi(e){return t=>{var r;const o=to(e),i=t.doc,{parentTable:s,parentId:a,parentProp:c,updatesTable:l}=i.meta;if(!(null===(r=e.cloud.schema)||void 0===r?void 0:r[s].markedForSync))return;let u=new o.Awareness(i);no.set(i,u),t.awareness=u,u.on("update",(({added:n,updated:r,removed:a},l)=>{const d=n.concat(r).concat(a),f=e.cloud.currentUser.value;if("server"!==l&&f.isLoggedIn&&!Hr(e)){const n=o.encodeAwarenessUpdate(u,d);e.messageProducer.next({type:"aware",table:s,prop:c,k:i.meta.parentId,u:n}),t.destroyed&&e.messageProducer.next({type:"doc-close",table:s,prop:c,k:i.meta.parentId})}})),u.on("destroy",(()=>{o.removeAwarenessStates(u,[i.clientID],"provider destroyed")})),t.on("load",(()=>I(this,void 0,void 0,(function*(){if(t.destroyed)return;let r=!1,o=1;const i=e.cloud.webSocketStatus.subscribe((i=>{if(t.destroyed)return;r="connected"===i;const u=e.cloud.currentUser.value;"connected"===i&&u.isLoggedIn&&!Hr(e)&&(++o,function(i){return I(this,void 0,void 0,(function*(){const i=o,u=e.table(l),d=yield u.get(er);if(t.destroyed||o!==i||!r)return;const f=(null==d?void 0:d.receivedUntil)||0,p={type:"doc-open",table:s,prop:c,k:a,serverRev:null==d?void 0:d.serverRev},h=yield u.where("i").between(f,1/0,!1).filter((e=>0===n(e.k,a)&&0==(1&(e.f||0)))).toArray();if(!t.destroyed&&o===i&&r){if(h.length>0){const t=nr(e),n=t.mergeUpdatesV2(h.map((e=>e.u))),r=t.encodeStateVectorFromUpdateV2(n);p.sv=r}e.messageProducer.next(p)}}))}().catch((e=>{})))}));t.addCleanupHandler(i)}))))}}const Ai={nameSuffix:!0};function Ti(t){const n=t.name,r=gi(t),i=[];let u=!1,h=null;t.on("ready",(t=>I(this,void 0,void 0,(function*(){try{yield function(t){var n,c,_,w,k,S,x;return I(this,void 0,void 0,(function*(){y=!1;const E=_r(t);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(n=E.cloud.options)||void 0===n?void 0:n.customLoginGui)||i.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),zo(Io(mi,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),zo(Io(mi,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(t))),E.cloud.isServiceWorkerDB||i.push(function(e){let t=e.cloud.webSocketStatus.value;const n=e.cloud.webSocketStatus.pipe(Ze((e=>{const n=t;t=e;const r=f(e);switch(e){case"disconnected":return Jr.value?r.pipe(Fe(500)):r;case"connecting":return"not-started"===n||"error"===n?r:r.pipe(Fe(4e3));default:return r}})));return g([n,e.syncStateChangedEvent.pipe(Xe({phase:"initial"})),gi(e.dx._novip),Gr]).pipe(Re((([t,n,r,o])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:s,error:a,progress:c}=n,l=t;return"error"===s&&(l="error"),"not-started"===t&&("pushing"!==s&&"pulling"!==s||(l="connecting")),"error"!==e.cloud.syncState.value.phase||"pushing"!==n.phase&&"pulling"!==n.phase||(l="connecting"),o||(l="disconnected"),{phase:s,error:a,progress:c,status:Gn?l:"offline",license:"ok"}})))}(E).subscribe(t.cloud.syncState)),i.push(E.syncCompleteEvent.subscribe(m)),E.tables.every((e=>e.core))||jr();const O="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[A,T]=yield E.transaction("rw",E.$syncState,(()=>I(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=E.cloud,[o,i,s]=yield Promise.all([E.getOptions(),E.getSchema(),E.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,delete e.awarenessProtocol,yield E.$syncState.put(e,"options")}}else E.cloud.options=o||null;if((null===(e=E.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&O.length>0&&!Cr?E.cloud.usingServiceWorker=!0:((null===(t=E.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&E.cloud.isServiceWorkerDB,E.cloud.usingServiceWorker=!1),ho(r,E.cloud.options),ho(i,E.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 E.$syncState.put(e,"schema"),Object.assign(r,e)}}else E.cloud.schema=i||null;return[null==s?void 0:s.initiallySynced,null==s?void 0:s.realms]}))));if(A&&E.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`)}}(E),(null===(c=E.cloud.options)||void 0===c?void 0:c.databaseUrl)&&!A&&(yield function(e,t,n){return I(this,void 0,void 0,(function*(){yield ur(e,t,n,{isInitialSync:!0})}))}(E,E.cloud.options,E.cloud.schema),E.setInitiallySynced(!0)),v(),!E.cloud.isServiceWorkerDB){i.push(o((()=>E.getCurrentUser())).subscribe(r)),i.push(o((()=>E.getPersistedSyncState())).subscribe(E.cloud.persistedSyncState)),yield a(g([r.pipe(Ye(1),Ke(1)),E.cloud.persistedSyncState.pipe(Ye(1),Ke(1))]));const e=Oi(E);E.dx.on("y",e),E.dx.once("close",(()=>{var t;null===(t=E.dx.on.y)||void 0===t||t.unsubscribe(e)}))}let U=!1;const C=yield E.getCurrentUser(),P=null===(_=E.cloud.options)||void 0===_?void 0:_.requireAuth;P&&("object"==typeof P?(!C.isLoggedIn||P.userId&&C.userId!==P.userId||P.email&&C.email!==P.email)&&(U=yield Or(E,P)):C.isLoggedIn||(U=yield Or(E))),!C.isLoggedIn||T&&T.includes(C.userId)||(U=!0),h&&h.stop(),h=null,v(),E.cloud.usingServiceWorker&&(null===(w=E.cloud.options)||void 0===w?void 0:w.databaseUrl)?(tt(E,U?"pull":"push").catch((()=>{})),function(e){var t;return I(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)}catch(e){}}catch(e){}}))}(E).catch((()=>{}))):(null===(k=E.cloud.options)||void 0===k?void 0:k.databaseUrl)&&E.cloud.schema&&!E.cloud.isServiceWorkerDB&&(h=po(E,E.cloud.options,E.cloud.schema),h.start(),nt(E,U?"pull":"push")),v(),E.cloud.isServiceWorkerDB||i.push(d(self,"online").subscribe((()=>{E.syncStateChangedEvent.next({phase:"not-in-sync"}),Hr(E)||nt(E,"push")})),d(self,"offline").subscribe((()=>{E.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(S=E.cloud.options)||void 0===S?void 0:S.databaseUrl)||(null===(x=E.cloud.options)||void 0===x?void 0:x.disableWebSocket)||Pr||i.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(Ge((e=>e)),Ze((()=>e.getPersistedSyncState())),Ge((e=>e&&e.serverRevision)),Ze((e=>I(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield it(e)}}))))),r=p(n,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(Ge((e=>null==e?void 0:e.serverRevision)),Ke(1),Ze((t=>e.cloud.currentUser.pipe(Re((e=>[e,t]))))),Ze((([e,t])=>Gr.pipe(Re((n=>[n?e:null,t]))))),Ze((([t,n])=>(null==t?void 0:t.isLoggedIn)&&!(null==n?void 0:n.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(Ge((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),Ke(1),Re((e=>[t,e]))):new s([t,n]))),Ze((([e,t])=>I(this,void 0,void 0,(function*(){return[e,yield it(t)]})))),qe((([e,t],[n,r])=>e===n&&t===r)),Ze((([n,o])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?n?new ro(e,e.cloud.persistedSyncState.value.serverRevision,o,e.cloud.persistedSyncState.value.clientIdentity,r,e.cloud.webSocketStatus,n):l([]):t()})),je((n=>"TokenExpiredError"===(null==n?void 0:n.name)?f(!0).pipe(Ze((()=>I(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield pn(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})))),Ze((()=>t()))):b((()=>n)))),je((n=>(e.cloud.webSocketStatus.next("error"),n instanceof so?b((()=>n)):l(ao()).pipe(Ze((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(E))}))}(t)}catch(e){}}))),!0);let y=!1;function v(){if(y)throw new e.DatabaseClosedError}t.once("close",(()=>{i.forEach((e=>e.unsubscribe())),i.splice(0,i.length),y=!0,h&&h.stop(),h=null,r.next(j)}));const m=new c;var _;t.cloud={version:"4.1.0-alpha.10",options:Object.assign({},Ai),schema:null,get currentUserId(){return r.value.userId||j.userId},currentUser:r,syncState:new s({phase:"initial",status:"not-started"}),events:{syncComplete:m},persistedSyncState:new s(void 0),userInteraction:new s(void 0),webSocketStatus:new s("not-started"),login(e){return I(this,void 0,void 0,(function*(){const n=_r(t);yield n.cloud.sync(),yield Or(n,e)}))},invites:Ei(t),roles:wi(t),configure(e){e=t.cloud.options=Object.assign(Object.assign({},t.cloud.options),e),u=!0,e.databaseUrl&&e.nameSuffix&&(t.name=`${n}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,_r(t).reconfigure()),ho(t.cloud.schema,t.cloud.options)},logout({force:e}={}){return I(this,void 0,void 0,(function*(){e?yield Ir(_r(t),{deleteUnsyncedData:!0}):yield xr(_r(t))}))},sync({wait:e,purpose:n}={wait:!0,purpose:"push"}){var r;return I(this,void 0,void 0,(function*(){void 0===e&&(e=!0);const i=_r(t);if("ok"!==((null===(r=i.cloud.currentUser.value.license)||void 0===r?void 0:r.status)||"ok")&&(yield dn(i)),"pull"===n){const t=i.cloud.persistedSyncState.value;if(nt(i,n),e){const e=yield a(i.cloud.persistedSyncState.pipe(Ge((e=>null!=(null==e?void 0:e.timestamp)&&(!t||e.timestamp>t.timestamp)))));if(null==e?void 0:e.error)throw new Error("Sync error: "+e.error)}}else if(yield co(i)){const t=i.cloud.persistedSyncState.value;nt(i,n),e&&(yield a(l(o((()=>I(this,void 0,void 0,(function*(){const e=yield co(i),n=yield i.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(Ge((e=>!e)))))}}))},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=xi(e),s=t=>{const i=t[o||e.cloud.currentUserId];return i?new Ii(i.permissions,n,void 0===o||o===e.cloud.currentUserId||r===e.cloud.currentUserId):new Ii({},n,!r||r===e.cloud.currentUserId)},a=i.pipe(Re(s));return a.getValue=()=>s(i.getValue()),a}(t._novip,e,n)},t.Version.prototype._parseStoresSpec=e.override(t.Version.prototype._parseStoresSpec,(e=>qr(e,t))),t.Table.prototype.newId=function({colocateWith:e}={}){const n=e&&e.substr(e.length-3);return Br(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(zr({currentUserObservable:t.cloud.currentUser,db:_r(t)})),t.use((_=_r(t),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:t=>Object.assign(Object.assign({},t),{table:n=>{const r=t.table(n);return Object.assign(Object.assign({},r),{mutate:t=>{var o,i,s,a;if(t.trans.disableChangeTracking)return r.mutate(t);const c=t.trans;if(null===(i=null===(o=_.cloud.schema)||void 0===o?void 0:o[n])||void 0===i?void 0:i.markedForSync){if("versionchange"===c.mode)return Promise.reject(new e.UpgradeError(`Dexie Cloud Addon: Cannot upgrade or populate synced table "${n}". See https://dexie.org/cloud/docs/best-practices`));if("add"===t.type||"put"===t.type){if("members"===n)for(const e of t.values)"string"==typeof e.email&&(e.email=e.email.trim().toLowerCase());for(const e of t.values){e.owner||(e.owner=c.currentUser.userId),e.realmId||(e.realmId=c.currentUser.userId);const n=null===(a=(s=r.schema.primaryKey).extractKey)||void 0===a?void 0:a.call(s,e);"string"==typeof n&&"#"===n[0]&&"put"===t.type&&(delete t.criteria,delete t.changeSpec,delete t.updates,e.$ts=Date.now())}}}return r.mutate(t)}})}})})),t.use(Mr(_r(t)))}Ti.version="4.1.0-alpha.10",e.Cloud=Ti;const Ui=new Map;function Ci(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const Pi=new Map;function ji(t,n){let r=Pi.get(t+"/"+n);return r||(r=function t(n,r){var o;return I(this,void 0,void 0,(function*(){let i=Ui.get(n);if(!i){const o=new e(n,{addons:[Ti]});if(i=_r(o),i.cloud.isServiceWorkerDB=!0,o.on("versionchange",s),yield i.dx.open(),Ui.get(n))return i.close(),yield t(n,r);Ui.set(n,i)}if((null===(o=i.cloud.options)||void 0===o?void 0:o.databaseUrl)&&i.cloud.schema)try{yield uo(i,i.cloud.options,i.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:r})}catch(t){if(s(),t.name!==e.errnames.NoSuchDatabase)throw t}function s(){return i.dx.on.versionchange.unsubscribe(s),Ui.get(i.name)===i&&Ui.delete(i.name),i.dx.close(),!1}}))}(t,n).then((()=>{Pi.delete(t+"/"+n)})).catch((e=>(Pi.delete(t+"/"+n),Promise.reject(e)))),Pi.set(t+"/"+n,r)),r}Cr||(self.addEventListener("sync",(e=>{const t=Ci(e.tag);t&&e.waitUntil(ji(t,"push"))})),self.addEventListener("periodicsync",(e=>{const t=Ci(e.tag);t&&e.waitUntil(ji(t,"pull"))})),self.addEventListener("message",(e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(r=1)=>ji(t,e.data.purpose||"pull").catch((e=>I(void 0,void 0,void 0,(function*(){if(3===r)throw e;var t;yield(t=6e4,new Promise((e=>setTimeout(e,t)))),n(r+1)}))));"waitUntil"in e?e.waitUntil(n().catch((e=>{}))):n().catch((e=>{}))}})));
|
|
2
2
|
//# sourceMappingURL=service-worker.min.js.map
|