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