dexie-cloud-addon 4.3.2 → 4.3.3
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 +58 -10
- 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/errors/OAuthRedirectError.d.ts +11 -0
- package/dist/modern/service-worker.js +58 -10
- 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/umd/dexie-cloud-addon.js +58 -10
- 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 +58 -10
- 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/package.json +1 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs,e.rxjs.operators)}(this,function(e,t,n){"use strict";function r(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,l)}c((r=r.apply(e,t||[])).next())})}function s(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function i(e){return this instanceof i?(this.v=e,this):new i(e)}function o(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),o=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),l("next"),l("throw"),l("return",function(e){return function(t){return Promise.resolve(t).then(e,d)}}),r[Symbol.asyncIterator]=function(){return this},r;function l(e,t){s[e]&&(r[e]=function(t){return new Promise(function(n,r){o.push([e,t,n,r])>1||c(e,t)})},t&&(r[e]=t(r[e])))}function c(e,t){try{!function(e){e.value instanceof i?Promise.resolve(e.value.v).then(a,d):u(o[0][2],e)}(s[e](t))}catch(e){u(o[0][3],e)}}function a(e){c("next",e)}function d(e){c("throw",e)}function u(e,t){e(t),o.shift(),o.length&&c(o[0][0],o[0][1])}}function l(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=s(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,s){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,s,(t=e[n](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;const c={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(c),Object.freeze(c.claims)}catch(e){}const a={},d="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;d&&d.ready.then(e=>a.registration=e),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)})});class u{constructor(e){this.name=e}subscribe(e){if(!d)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return d.addEventListener("message",t),()=>d.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach(t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e})):a.registration&&(null===(t=a.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const h=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class f extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new u(e):new BroadcastChannel(e);super(n=>{function r(e){n.next(e.detail)}function s(e){n.next(e.data)}let i;!function(e,t){h.has(e)?h.get(e).push(t):h.set(e,[t])}(`lbc-${e}`,r);try{t instanceof u?i=t.subscribe(e=>n.next(e)):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=h.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof u?i():t.removeEventListener("message",s)}}),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=h.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){}})}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}let p=!1;function g(e,t){return r(this,void 0,void 0,function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){p||(p=!0)}})}function y(e,t){e.cloud.usingServiceWorker?g(e,t):e.localSyncEvent.next({purpose:t})}const m="fromBase64"in Uint8Array,v="toBase64"in Uint8Array.prototype,b="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):m?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var s=0;s<n;s++)r[s]=t.charCodeAt(s);return r},w="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):v?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};function _(e){return r(this,arguments,void 0,function*({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),s=yield crypto.subtle.digest("SHA-1",r);return w(s)})}function k(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 S(e){return`$${e}_mutations`}function x(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const E=[].concat;function C(e){return E.apply([],e)}function I(e,t){return r(this,arguments,void 0,function*(e,t,{since:n={},limit:s=1/0}={}){const i=yield Promise.all(e.map(e=>r(this,void 0,void 0,function*(){const t=x(e.name),r=n[t];let i=r?e.where("rev").above(r):e;s<1/0&&(i=i.limit(s));let o=yield i.toArray();o=function(e){return e=e.map(e=>{if("modify"===e.type&&null===e.criteria.index){const t=Object.assign(Object.assign({},e),{criteria:void 0,changeSpec:void 0,type:"update",keys:e.keys,changeSpecs:[e.changeSpec]});return delete t.criteria,delete t.changeSpec,t}return e}),e}(o),o=function(e){const t=new Map;for(const n of e)if("update"===n.type){if(1!==n.keys.length||1!==n.changeSpecs.length)continue;const e=""+n.keys[0],r=n.changeSpecs[0];if(Object.values(r).some(e=>"object"==typeof e&&e&&"@@propmod"in e))continue;let s=t.get(e);s?s.push({txid:n.txid,updateSpec:r}):t.set(e,[{txid:n.txid,updateSpec:r}])}return e=e.filter(e=>{if("update"!==e.type)return!0;if(1!==e.keys.length||1!==e.changeSpecs.length)return!0;const n=e.changeSpecs[0];if(Object.values(n).some(e=>"object"==typeof e&&e&&"@@propmod"in e))return!0;const r=new Set(Object.keys(e.changeSpecs[0])),s=""+e.keys[0],i=t.get(s);if(!i)return!0;for(let t=i.length-1;t>=0;--t){const{txid:n,updateSpec:s}=i[t];if(n===e.txid)break;for(const e of Object.keys(s))r.delete(e)}return 0!==r.size}),e}(o);return o.map(e=>({table:t,mut:e}))}))),o=C(i).sort((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts),l=[];let c=null,a=null;for(const{table:e,mut:t}of o)c&&c.table===e&&a===t.txid?c.muts.push(t):(c={table:e,muts:[t]},a=t.txid,l.push(c));return l})}function O(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const D={}.hasOwnProperty;function A(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,s=t.length;r<s;++r)A(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),l=t.substr(i+1);if(""===l)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var c=e[o];c&&function(e,t){return D.call(e,t)}(e,o)||(c=e[o]={}),A(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const T="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=U)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function U(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function j(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some(e=>j(e))&&e.every(L))}function L(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(L)}function P(e,t,n){const r=e[t]||(e[t]={}),s=n.keys.map(e=>"string"==typeof e?e:JSON.stringify(e));switch(n.type){case"insert":case"upsert":s.forEach((e,t)=>{r[e]={type:"ups",val:n.values[t]}});break;case"update":case"modify":s.forEach((e,t)=>{const s="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(s))A(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,s)}else r[e]={type:"upd",mod:s}});break;case"delete":s.forEach(e=>{r[e]={type:"del"}})}return e}function M(e,t){for(const{table:n,muts:r}of t)for(const t of r)P(e,n,t)}const $=Math.floor,R=Math.abs,N=(e,t)=>e<t?e:t,B=(e,t)=>e>t?e:t,F=e=>0!==e?e<0:1/e<0,W=64,H=128,V=127,z=Number.MAX_SAFE_INTEGER,K=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&$(e)===e),J=()=>new Set,q=e=>e[e.length-1],G=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Y=Array.from,Q=Array.isArray,X=/^\s*/g,Z=/([A-Z])/g,ee=(e,t)=>(e=>e.replace(X,""))(e.replace(Z,e=>`${t}${(e=>e.toLowerCase())(e)}`)),te="undefined"!=typeof TextEncoder?new TextEncoder:null,ne=te?e=>te.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let re="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});re&&1===re.decode(new Uint8Array).length&&(re=null);class se{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const ie=()=>new se,oe=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},le=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},ce=le,ae=(e,t)=>{for(;t>V;)le(e,H|V&t),t=$(t/128);le(e,V&t)},de=(e,t)=>{const n=F(t);for(n&&(t=-t),le(e,(t>63?H:0)|(n?W:0)|63&t),t=$(t/64);t>0;)le(e,(t>V?H:0)|V&t),t=$(t/128)},ue=new Uint8Array(3e4),he=ue.length/3,fe=te&&te.encodeInto?(e,t)=>{if(t.length<he){const n=te.encodeInto(t,ue).written||0;ae(e,n);for(let t=0;t<n;t++)le(e,ue[t])}else ge(e,ne(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;ae(e,r);for(let t=0;t<r;t++)le(e,n.codePointAt(t))},pe=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=N(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(B(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},ge=(e,t)=>{ae(e,t.byteLength),pe(e,t)},ye=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*B(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},me=(e,t)=>ye(e,8).setBigUint64(0,t,!1),ve=new DataView(new ArrayBuffer(4)),be=(e,t)=>{switch(typeof t){case"string":le(e,119),fe(e,t);break;case"number":K(t)&&R(t)<=2147483647?(le(e,125),de(e,t)):(n=t,ve.setFloat32(0,n),ve.getFloat32(0)===n?(le(e,124),((e,t)=>{ye(e,4).setFloat32(0,t,!1)})(e,t)):(le(e,123),((e,t)=>{ye(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":le(e,122),((e,t)=>{ye(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)le(e,126);else if(Q(t)){le(e,117),ae(e,t.length);for(let n=0;n<t.length;n++)be(e,t[n])}else if(t instanceof Uint8Array)le(e,116),ge(e,t);else{le(e,118);const n=Object.keys(t);ae(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];fe(e,s),be(e,t[s])}}break;case"boolean":le(e,t?120:121);break;default:le(e,127)}var n};class we extends se{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ae(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const _e=e=>{e.count>0&&(de(e.encoder,1===e.count?e.s:-e.s),e.count>1&&ae(e.encoder,e.count-2))};class ke{constructor(){this.encoder=new se,this.s=0,this.count=0}write(e){this.s===e?this.count++:(_e(this),this.count=1,this.s=e)}toUint8Array(){return _e(this),oe(this.encoder)}}const Se=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);de(e.encoder,t),e.count>1&&ae(e.encoder,e.count-2)}};class xe{constructor(){this.encoder=new se,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Se(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Se(this),oe(this.encoder)}}class Ee{constructor(){this.sarr=[],this.s="",this.lensE=new ke}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new se;return this.sarr.push(this.s),this.s="",fe(e,this.sarr.join("")),pe(e,this.lensE.toUint8Array()),oe(e)}}const Ce=e=>new Error(e),Ie=()=>{throw Ce("Method unimplemented")},Oe=()=>{throw Ce("Unexpected case")},De=Ce("Unexpected end of array"),Ae=Ce("Integer out of Range");class Te{constructor(e){this.arr=e,this.pos=0}}const Ue=e=>new Te(e),je=e=>e.pos!==e.arr.length,Le=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Me(e)),Pe=e=>e.arr[e.pos++],Me=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&V)*n,n*=128,r<H)return t;if(t>z)throw Ae}throw De},$e=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&W)>0?-1:1;if(0===(t&H))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&V)*r,r*=128,t<H)return s*n;if(n>z)throw Ae}throw De},Re=re?e=>re.decode(Le(e)):e=>{let t=Me(e);if(0===t)return"";{let n=String.fromCodePoint(Pe(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Pe(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},Ne=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Be=e=>Ne(e,8).getBigUint64(0,!1),Fe=[e=>{},e=>null,$e,e=>Ne(e,4).getFloat32(0,!1),e=>Ne(e,8).getFloat64(0,!1),e=>Ne(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Re,e=>{const t=Me(e),n={};for(let r=0;r<t;r++){n[Re(e)]=We(e)}return n},e=>{const t=Me(e),n=[];for(let r=0;r<t;r++)n.push(We(e));return n},Le],We=e=>Fe[127-Pe(e)](e);class He extends Te{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return 0===this.count&&(this.s=this.reader(this),je(this)?this.count=Me(this)+1:this.count=-1),this.count--,this.s}}class Ve extends Te{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=$e(this);const e=F(this.s);this.count=1,e&&(this.s=-this.s,this.count=Me(this)+2)}return this.count--,this.s}}class ze extends Te{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=$e(this),t=1&e;this.diff=$(e/2),this.count=1,t&&(this.count=Me(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ke{constructor(e){this.decoder=new Ve(e),this.str=Re(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}async function*Je(e){let t=0,n=new Uint8Array(4),r=0,s=[],i=0;for await(const o of e){const e=new DataView(o.buffer,o.byteOffset,o.byteLength);let l=0;for(;l<o.byteLength;)switch(t){case 0:if(l+4>o.byteLength){for(const e of o.slice(l)){if(4===r)break;n[r++]=e,++l}if(r<4)break}else if(r>0&&r<4)for(const e of o.slice(l,l+4-r))n[r++]=e,++l;case 1:i=4===r?new DataView(n.buffer,0,4).getUint32(0,!1):e.getUint32(l,!1),r?r=0:l+=4;case 2:if(l>=o.byteLength){t=2;break}if(l+i>o.byteLength)s.push(o.slice(l)),i-=o.byteLength-l,t=2,l=o.byteLength;else{if(s.length>0){const e=new Uint8Array(s.reduce((e,t)=>e+t.byteLength,i));let t=0;for(const n of s)e.set(n,t),t+=n.byteLength;e.set(o.slice(l,l+i),t),s=[],yield e}else yield o.slice(l,l+i);l+=i,t=0}}}}class qe extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}const Ge={},Ye={google:'<svg viewBox="0 0 24 24" width="20" height="20"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>',github:'<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>',microsoft:'<svg viewBox="0 0 24 24" width="20" height="20"><rect fill="#F25022" x="1" y="1" width="10" height="10"/><rect fill="#00A4EF" x="1" y="13" width="10" height="10"/><rect fill="#7FBA00" x="13" y="1" width="10" height="10"/><rect fill="#FFB900" x="13" y="13" width="10" height="10"/></svg>',apple:'<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/></svg>'};function Qe(e){return r(this,void 0,void 0,function*(){var t;let n;if(Ye[e.type])n=Ye[e.type];else if(null===(t=e.iconUrl)||void 0===t?void 0:t.toLowerCase().endsWith(".svg")){const t=yield function(e){return r(this,void 0,void 0,function*(){if(Ge[e])return Ge[e];try{const t=yield fetch(e);if(t.ok){const n=yield t.text();if(n.includes("<svg"))return Ge[e]=n,n}}catch(e){}return null})}(e.iconUrl);t&&(n=t)}return{name:"provider",value:e.name,displayName:`Continue with ${e.displayName}`,iconSvg:n,iconUrl:!n&&e.iconUrl?e.iconUrl:void 0,styleHint:e.type}})}function Xe(t,n){return new Promise((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),s(new e.AbortError("User cancelled"))}});t.next(i)})}function Ze(e,t,...n){return Xe(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function et(e,t,n){return r(this,void 0,void 0,function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield Xe(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r})}function tt(e,t,n){return r(this,void 0,void 0,function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:s}=yield Xe(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s})}function nt(e){return r(this,void 0,void 0,function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:l,refreshTokenExpiration:c,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!l)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const d=yield st(e.cloud.options.databaseUrl,s);return yield e.table("$logins").update(a.sub,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data}),d})}function rt(t,n,s,i,o){return r(this,void 0,void 0,function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield st(t,n):yield function(t,n,s,i){return r(this,void 0,void 0,function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:r,publicKey:o}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!r||!o)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=r;const l=function(e){const t=w(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",o));t.publicKey=o;try{const e=yield n({public_key:l,hints:i});if("error"===e.type)throw new qe(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield Xe(s,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof qe)throw yield Ze(s,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield Ze(s,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch(()=>{})}throw t}})}(n,s,i,o)})}function st(e,t){return r(this,void 0,void 0,function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",s=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,s),o=w(i),l={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(l),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const a=yield c.json();if("error"===a.type)throw new qe(a);return t.accessToken=a.accessToken,t.accessTokenExpiration=a.accessTokenExpiration?new Date(a.accessTokenExpiration):void 0,t.claims=a.claims,t.license={type:a.userType,status:a.claims.license||"ok"},null!=a.evalDaysLeft&&(t.license.evalDaysLeft=a.evalDaysLeft),null!=a.userValidUntil&&(t.license.validUntil=new Date(a.userValidUntil)),a.data&&(t.data=a.data),t})}const{toString:it}={};const ot={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function lt(...e){const t=e.reduce((e,t)=>({...e,...t}),e.reduce((e,t)=>({...t,...e}),{})),n=new WeakMap;return{stringify(e,r,s){const i=JSON.stringify(e,function(e){const s=this[e],i=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return ot;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,it.call(s).slice(8,-1)),l=Object.entries(t).find(([t,n])=>{var r,s;return null!==(s=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==s?s:t===o});return i=null==l?void 0:l[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:ot),n.set(r,i),i}default:return t[r]}var s}(s);return i?i.replace(s,r,t):s},s);return i},parse(e,n){const r=[];return JSON.parse(e,function(e,s){const i=null==s?void 0:s.$t;if(i){const e=t[i];s=e?e.revive(s,n,t):s}let o=r[r.length-1];if(o&&o[0]===s){s={...s};for(const e of o[1])delete s[e];for(const[e,t]of Object.entries(o[2]))s[e]=t;r.pop()}if(void 0===s||"$"===e[0]&&"$t"!==e){let t,n;o=r[r.length-1],o&&o[0]===this?(t=o[1],n=o[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=s):n[e]=void 0}return s})}}}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 at={number:{replace:e=>{switch(!0){case isNaN(e):return{$t:"number",v:"NaN"};case e===1/0:return{$t:"number",v:"Infinity"};case e===-1/0:return{$t:"number",v:"-Infinity"};default:return e}},revive:({v:e})=>Number(e)}};const dt={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var ut={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},ht={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},ft={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const pt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var gt=["Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","DataView","BigInt64Array","BigUint64Array"].reduce((e,t)=>({...e,[t]:{replace:(e,n,r)=>({$t:t,v:r.ArrayBuffer.replace(0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength),n,r).v}),revive:({v:e},n,r)=>{const s=pt[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}}),{});function yt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=bt[e[n]];return t}(w(e))}function mt(e){return b(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+=vt[e[n]];return t}(e))}const vt={"-":"=",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(vt))bt[vt[e]]=e;var wt={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:yt(e)}),revive:({v:e})=>{const t=mt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class _t{constructor(e,t){this.buf=e,this.type=t}}function kt(e){const t=new XMLHttpRequest;if(t.overrideMimeType("text/plain; charset=x-user-defined"),t.open("GET",URL.createObjectURL(e),!1),t.send(),200!==t.status&&0!==t.status)throw new Error("Bad Blob access: "+t.status);return t.responseText}function St(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var xt={Blob:{test:(e,t)=>"Blob"===t||e instanceof _t,replace:e=>({$t:"Blob",v:w(e instanceof _t?e.buf:St(kt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=b(t);return void 0!==typeof Blob?new Blob([n]):new _t(n.buffer,e)}}};const Et={...at,...dt,...ut,...ht,...ft,...gt,...wt,...xt};function Ct(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 It={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},Ot={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:w(St(kt(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=b(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const Dt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class At{toString(){return this.v}constructor(e){this.v=e}}const Tt=Dt?{}:{bigint:{test:e=>e instanceof At,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new At(e)}},Ut=Object.assign(Object.assign(Object.assign(Object.assign({},It),Tt),Ot),{PropModification:{test:t=>t instanceof e.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:t=>{var{$t:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(t,["$t"]);return new e.PropModification(r)}}}),jt=lt(Et,Ut),Lt=function(...e){const t=lt(Et,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);return[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])})),r]},async parse(e,n){let r=0;const s=[],i=await Ct(n),o=new DataView(i);for(;r<i.byteLength;){const e=o.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,s.push(t)}return t.parse(e,s)},async fromBinary(e){const t=new DataView(await Ct(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)}}}(Ut);class Pt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Mt(t,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=t.tables.find(e=>e.name===r);if(!l)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=l;let a=i;o.forEach((t,r)=>{const s=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach((t,o)=>{if(Array.isArray(t)){a===i&&(a=$t(i,s));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===i&&(a=$t(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const d=`${t}:${n.userId}`;l.keys[o]=d,s&&e.setByKeyPath(l.values[o],c.keyPath,d)}})}),s.push(a)}return s}function $t(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map(e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()})):e.muts.map(e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()}))})}let Rt=new WeakMap;function Nt(e){return r(this,void 0,void 0,function*(){var t,n;const r=(null!==(n=null===(t=Rt.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise(e=>setTimeout(e,r)))})}function Bt(e,t,n,s,i,o,l,c,a){return r(this,void 0,void 0,function*(){const r={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},d=yield nt(i),u=null==d?void 0:d.accessToken;u&&(r.Authorization=`Bearer ${u}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:c,schema:l||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:s,changes:Mt(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=jt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:r,credentials:"include",body:f});if(i.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),s=t.headers.get("Ratelimit-Reset");if(n&&r&&s){const t=Number(n),i=Math.max(0,Number(r)),o=Number(s);if(i<t/2){const t=Math.ceil(o/(i+1));Rt.set(e,new Date(Date.now()+1e3*t))}else Rt.delete(e)}}(i,p),!p.ok)throw new Pt(p);if("application/x-bison"===p.headers.get("content-type"))return Lt.fromBinary(yield p.blob());{const e=yield p.text();return jt.parse(e)}})}function Ft(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Wt=!1;function Ht(e,t,n,s){return r(this,void 0,void 0,function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter(e=>t[e].markedForSync).map(e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:s}))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter(e=>t[e].markedForSync)).delete()})}function Vt(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function zt(t,n,s){return r(this,void 0,void 0,function*(){const r=yield t.bulkGet(n),i=[],o=[];n.forEach((n,l)=>{const c=r[l];if(c){for(const[r,i]of Object.entries(s[l]))if(r===t.schema.primKey.keyPath){if(0!==e.cmp(i,n))throw new Error("Cannot change primary key")}else e.setByKeyPath(c,r,i);i.push(n),o.push(c)}}),yield null==t.schema.primKey.keyPath?t.bulkPut(o,i):t.bulkPut(o)})}function Kt(t,n){return r(this,void 0,void 0,function*(){for(const{table:r,muts:s}of t){if(!n.dx._allTables[r])continue;const t=n.table(r),{primaryKey:i}=t.core.schema,o=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of s){const r=n.keys.map(o);switch(n.type){case"insert":i.outbound?yield t.bulkAdd(n.values,r):(r.forEach((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)}),yield t.bulkAdd(n.values));break;case"upsert":i.outbound?yield t.bulkPut(n.values,r):(r.forEach((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)}),yield t.bulkPut(n.values));break;case"modify":1===r.length?yield t.update(r[0],n.changeSpec):yield t.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield zt(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}})}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Wt=navigator.onLine,self.addEventListener("online",()=>Wt=!0),self.addEventListener("offline",()=>Wt=!1));const Jt="dexie-cloud-syncer";function qt(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Gt=()=>new Map,Yt=e=>{const t=Gt();return e.forEach((e,n)=>{t.set(n,e)}),t},Qt=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};class Xt{constructor(){this._observers=Gt()}on(e,t){return Qt(this._observers,e,J).add(t),t}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Y((this._observers.get(e)||Gt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Gt()}}class Zt{constructor(){this._observers=Gt()}on(e,t){Qt(this._observers,e,J).add(t)}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Y((this._observers.get(e)||Gt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Gt()}}const en=crypto.getRandomValues.bind(crypto),tn=()=>en(new Uint32Array(1))[0],nn=[1e7]+-1e3+-4e3+-8e3+-1e11,rn=()=>nn.replace(/[018]/g,e=>(e^tn()&15>>e/4).toString(16)),sn=Date.now,on=e=>new Promise(e);Promise.all.bind(Promise);const ln=e=>void 0===e?null:e;let cn=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},an=!0;try{"undefined"!=typeof localStorage&&localStorage&&(cn=localStorage,an=!1)}catch(Nl){}const dn=cn,un=Object.assign,hn=Object.keys,fn=e=>hn(e).length,pn=e=>hn(e).length,gn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),yn=Object.freeze,mn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||mn(e[t])}return yn(e)},vn=Symbol("Equality"),bn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&bn(e,t,n+1)}},wn=(e,t)=>{if(e===t)return!0;if(null==e||null==t||e.constructor!==t.constructor)return!1;if(null!=e[vn])return e[vn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(const n of e.keys())if(!t.has(n)||!wn(e.get(n),t.get(n)))return!1;break;case Object:if(fn(e)!==fn(t))return!1;for(const n in e)if(!gn(e,n)||!wn(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!wn(e[n],t[n]))return!1;break;default:return!1}return!0},_n="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let kn;const Sn=e=>(()=>{if(void 0===kn)if(_n){kn=Gt();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&kn.set(t,""),t=r):null!==t&&(kn.set(t,r),t=null)}null!==t&&kn.set(t,"")}else"object"==typeof location?(kn=Gt(),(location.search||"?").slice(1).split("&").forEach(e=>{if(0!==e.length){const[t,n]=e.split("=");kn.set(`--${ee(t,"-")}`,n),kn.set(`-${ee(t,"-")}`,n)}})):kn=Gt();return kn})().has(e),xn=e=>ln(_n?process.env[e.toUpperCase().replaceAll("-","_")]:dn.getItem(e)),En=e=>Sn("--"+e)||null!==xn(e);En("production");var Cn;_n&&(Cn=process.env.FORCE_COLOR,["true","1","2"].includes(Cn))||!Sn("--no-colors")&&!En("no-color")&&(!_n||process.stdout.isTTY)&&(!_n||Sn("--color")||null!==xn("COLORTERM")||(xn("TERM")||"").includes("color"));class In{constructor(e,t){this.left=e,this.right=t}}const On=(e,t)=>new In(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const Dn=Symbol,An=Dn(),Tn=Dn(),Un=Dn(),jn=Dn(),Ln=Dn(),Pn=Dn(),Mn=Dn(),$n=Dn(),Rn=Dn(),Nn=(On("font-weight","bold"),On("font-weight","normal"),On("color","blue"),On("color","green"),On("color","grey"),On("color","red"),On("color","purple"),On("color","orange"),On("color","black"),J()),Bn=e=>({[Symbol.iterator](){return this},next:e}),Fn=(e,t)=>Bn(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class Wn{constructor(e,t){this.clock=e,this.len=t}}class Hn{constructor(){this.clients=new Map}}const Vn=(e,t,n)=>t.clients.forEach((t,r)=>{const s=e.doc.store.clients.get(r);if(null!=s){const r=s[s.length-1],i=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<i;o=t[++r])Cr(e,s,o.clock,o.len,n)}}),zn=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const s=$((n+r)/2),i=e[s],o=i.clock;if(o<=t){if(t<o+i.len)return s;n=s+1}else r=s-1}return null})(n,t.clock)},Kn=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],s=e[t];r.clock+r.len>=s.clock?r.len=B(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n})},Jn=(e,t,n,r)=>{Qt(e.clients,t,()=>[]).push(new Wn(n,r))},qn=(e,t)=>{ae(e.restEncoder,t.clients.size),Y(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),ae(e.restEncoder,t);const r=n.length;ae(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Gn=(e,t,n)=>{const r=new Hn,s=Me(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=Me(e.restDecoder),i=Me(e.restDecoder),o=n.clients.get(s)||[],l=br(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&Jn(r,s,l,i-l);let e=_r(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,li(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<i);)c.deleted||(i<c.id.clock+c.length&&o.splice(e,0,li(t,c,i-c.id.clock)),c.delete(t))}else Jn(r,s,n,i-n)}}if(r.clients.size>0){const e=new rr;return ae(e.restEncoder,0),qn(e,r),e.toUint8Array()}return null},Yn=tn;class Qn extends Xt{constructor({guid:e=rn(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:s=null,autoLoad:i=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Yn(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new mr,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=i,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=on(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const l=()=>on(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=l()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;null===e||this.shouldLoad||Ur(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Y(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Ur(this,e,t)}get(e,t=Qr){const n=Qt(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Qr&&r!==t){if(r===Qr){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,gs)}getText(e=""){return this.get(e,js)}getMap(e=""){return this.get(e,ms)}getXmlElement(e=""){return this.get(e,Ms)}getXmlFragment(e=""){return this.get(e,Ps)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Y(this.subdocs).forEach(e=>e.destroy());const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Qn({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Ur(e.parent.doc,n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Xn{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Me(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Me(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Zn extends Xn{constructor(e){super(e),this.keys=[],Me(e),this.keyClockDecoder=new ze(Le(e)),this.clientDecoder=new Ve(Le(e)),this.leftClockDecoder=new ze(Le(e)),this.rightClockDecoder=new ze(Le(e)),this.infoDecoder=new He(Le(e),Pe),this.stringDecoder=new Ke(Le(e)),this.parentInfoDecoder=new He(Le(e),Pe),this.typeRefDecoder=new Ve(Le(e)),this.lenDecoder=new Ve(Le(e))}readLeftID(){return new hr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new hr(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return We(this.restDecoder)}readBuf(){return Le(this.restDecoder)}readJSON(){return We(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class er{constructor(){this.restEncoder=ie()}toUint8Array(){return oe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ae(this.restEncoder,e)}writeDsLen(e){ae(this.restEncoder,e)}}class tr extends er{writeLeftID(e){ae(this.restEncoder,e.client),ae(this.restEncoder,e.clock)}writeRightID(e){ae(this.restEncoder,e.client),ae(this.restEncoder,e.clock)}writeClient(e){ae(this.restEncoder,e)}writeInfo(e){ce(this.restEncoder,e)}writeString(e){fe(this.restEncoder,e)}writeParentInfo(e){ae(this.restEncoder,e?1:0)}writeTypeRef(e){ae(this.restEncoder,e)}writeLen(e){ae(this.restEncoder,e)}writeAny(e){be(this.restEncoder,e)}writeBuf(e){ge(this.restEncoder,e)}writeJSON(e){fe(this.restEncoder,JSON.stringify(e))}writeKey(e){fe(this.restEncoder,e)}}class nr{constructor(){this.restEncoder=ie(),this.dsCurrVal=0}toUint8Array(){return oe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,ae(this.restEncoder,t)}writeDsLen(e){0===e&&Oe(),ae(this.restEncoder,e-1),this.dsCurrVal+=e}}class rr extends nr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new xe,this.clientEncoder=new ke,this.leftClockEncoder=new xe,this.rightClockEncoder=new xe,this.infoEncoder=new we(ce),this.stringEncoder=new Ee,this.parentInfoEncoder=new we(ce),this.typeRefEncoder=new ke,this.lenEncoder=new ke}toUint8Array(){const e=ie();return ae(e,0),ge(e,this.keyClockEncoder.toUint8Array()),ge(e,this.clientEncoder.toUint8Array()),ge(e,this.leftClockEncoder.toUint8Array()),ge(e,this.rightClockEncoder.toUint8Array()),ge(e,oe(this.infoEncoder)),ge(e,this.stringEncoder.toUint8Array()),ge(e,oe(this.parentInfoEncoder)),ge(e,this.typeRefEncoder.toUint8Array()),ge(e,this.lenEncoder.toUint8Array()),pe(e,oe(this.restEncoder)),oe(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){be(this.restEncoder,e)}writeBuf(e){ge(this.restEncoder,e)}writeJSON(e){be(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const sr=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{br(t,n)>e&&r.set(n,e)}),vr(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),ae(e.restEncoder,r.size),Y(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=B(r,t[0].id.clock);const s=_r(t,r);ae(e.restEncoder,t.length-s),e.writeClient(n),ae(e.restEncoder,r);const i=t[s];i.write(e,r-i.id.clock);for(let n=s+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)})},ir=(e,t,n,r=new Zn(e))=>Ur(t,e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Gt(),r=Me(e.restDecoder);for(let s=0;s<r;s++){const r=Me(e.restDecoder),s=new Array(r),i=e.readClient();let o=Me(e.restDecoder);n.set(i,{i:0,refs:s});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();s[n]=new Fs(pr(i,o),t),o+=t;break}case 10:{const t=Me(e.restDecoder);s[n]=new ui(pr(i,o),t),o+=t;break}default:{const l=!(192&r),c=new ci(pr(i,o),null,(r&H)===H?e.readLeftID():null,null,(r&W)===W?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!l||32&~r?null:e.readString(),ai(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=Y(n.keys()).sort((e,t)=>e-t);if(0===s.length)return null;const i=()=>{if(0===s.length)return null;let e=n.get(s[s.length-1]);for(;e.refs.length===e.i;){if(s.pop(),!(s.length>0))return null;e=n.get(s[s.length-1])}return e};let o=i();if(null===o)return null;const l=new mr,c=new Map,a=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let d=o.refs[o.i++];const u=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,l.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):l.clients.set(t,[e]),s=s.filter(e=>e!==t)}r.length=0};for(;;){if(d.constructor!==ui){const s=Qt(u,d.id.client,()=>br(t,d.id.client))-d.id.clock;if(s<0)r.push(d),a(d.id.client,d.id.clock-1),h();else{const i=d.getMissing(e,t);if(null!==i){r.push(d);const e=n.get(i)||{refs:[],i:0};if(e.refs.length!==e.i){d=e.refs[e.i++];continue}a(i,br(t,i)),h()}else(0===s||s<d.length)&&(d.integrate(e,s),u.set(d.id.client,d.id.clock+d.length))}}if(r.length>0)d=r.pop();else if(null!==o&&o.i<o.refs.length)d=o.refs[o.i++];else{if(o=i(),null===o)break;d=o.refs[o.i++]}}if(l.clients.size>0){const e=new rr;return sr(e,l,new Map),ae(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,s,i),l=s.pendingStructs;if(l){for(const[e,n]of l.missing)if(n<br(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=l.missing.get(e);(null==n||n>t)&&l.missing.set(e,t)}l.update=$r([l.update,o.update])}}else s.pendingStructs=o;const c=Gn(r,e,s);if(s.pendingDs){const t=new Zn(Ue(s.pendingDs));Me(t.restDecoder);const n=Gn(t,e,s);s.pendingDs=c&&n?$r([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,or(e.doc,t)}},n,!1),or=(e,t,n,r=Zn)=>{const s=Ue(t);ir(s,e,n,new r(s))};class lr{constructor(){this.l=[]}}const cr=()=>new lr,ar=(e,t)=>e.l.push(t),dr=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},ur=(e,t,n)=>bn(e.l,[t,n]);class hr{constructor(e,t){this.client=e,this.clock=t}}const fr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,pr=(e,t)=>new hr(e,t),gr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!zn(t.ds,e.id),yr=(e,t)=>{const n=Qt(e.meta,yr,J),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<br(r,n)&&xr(e,pr(n,t))}),Vn(e,t.ds,e=>{}),n.add(t))};class mr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const vr=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},br=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},wr=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Oe()}n.push(t)},_r=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=$(t/(i+s.length-1)*r);for(;n<=r;){if(s=e[o],i=s.id.clock,i<=t){if(t<i+s.length)return o;n=o+1}else r=o-1;o=$((n+r)/2)}throw Oe()},kr=(e,t)=>{const n=e.clients.get(t.client);return n[_r(n,t.clock)]},Sr=(e,t,n)=>{const r=_r(t,n),s=t[r];return s.id.clock<n&&s instanceof ci?(t.splice(r+1,0,li(e,s,n-s.id.clock)),r+1):r},xr=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Sr(e,n,t.clock)]},Er=(e,t,n)=>{const r=t.clients.get(n.client),s=_r(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Fs&&r.splice(s+1,0,li(e,i,n.clock-i.id.clock+1)),i},Cr=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=Sr(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&Sr(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class Ir{constructor(e,t,n){this.doc=e,this.deleteSet=new Hn,this.beforeState=vr(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Or=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1})(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&(Kn(t.deleteSet),((e,t)=>{sr(e,t.doc.store,t.beforeState)})(e,t),qn(e,t.deleteSet),!0),Dr=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Qt(e.changed,t,J).add(n)},Ar=(e,t)=>{let n=e[t],r=e[t-1],s=t;for(;s>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--s-1])n instanceof ci&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const i=t-s;return i&&e.splice(t+1-i,i),i},Tr=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{Kn(i),n.afterState=vr(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=t,e._path=null}),e.sort((e,t)=>e.path.length-t.path.length),ur(t._dEH,e,n))})}),e.push(()=>r.emit("afterTransaction",[n,r])),bn(e,[]),n._needFormattingCleanup&&As(n)}finally{r.gc&&((e,t,n)=>{for(const[r,s]of e.clients.entries()){const e=t.clients.get(r);for(let r=s.length-1;r>=0;r--){const i=s[r],o=i.clock+i.len;for(let r=_r(e,i.clock),s=e[r];r<e.length&&s.id.clock<o;s=e[++r]){const s=e[r];if(i.clock+i.len<=s.id.clock)break;s instanceof ci&&s.deleted&&!s.keep&&n(s)&&s.gc(t,!1)}}}})(i,s,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=N(r.length-1,1+_r(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Ar(r,e)}})})(i,s),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=s.clients.get(t),n=B(_r(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Ar(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=s.clients.get(t),i=_r(r,n);i+1<r.length&&Ar(r,i+1)>1||i>0&&Ar(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Nn.forEach(t=>t.print(e))})($n,An,"[yjs] ",Tn,Pn,"Changed the client-id because another client seems to be using it."),r.clientID=Yn()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new tr;Or(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new rr;Or(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),a.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:c,added:l,removed:a},r,n]),a.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Tr(e,t+1)}}},Ur=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new Ir(e,n,r),s.push(e._transaction),1===s.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const t=e._transaction===s[0];e._transaction=null,t&&Tr(s,0)}}return o};class jr{constructor(e,t){this.gen=function*(e){const t=Me(e.restDecoder);for(let n=0;n<t;n++){const t=Me(e.restDecoder),n=e.readClient();let r=Me(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=Me(e.restDecoder);yield new ui(pr(n,r),t),r+=t}else if(31&t){const s=!(192&t),i=new ci(pr(n,r),null,(t&H)===H?e.readLeftID():null,null,(t&W)===W?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,!s||32&~t?null:e.readString(),ai(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new Fs(pr(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===ui);return this.curr}}class Lr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Pr=(e,t=nr,n=Zn)=>{const r=new t,s=new jr(new n(Ue(e)),!1);let i=s.curr;if(null!==i){let e=0,t=i.id.client,n=0!==i.id.clock,o=n?0:i.id.clock+i.length;for(;null!==i;i=s.next())t!==i.id.client&&(0!==o&&(e++,ae(r.restEncoder,t),ae(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===ui&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,ae(r.restEncoder,t),ae(r.restEncoder,o));const l=ie();return ae(l,e),((e,t)=>{pe(e,oe(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return ae(r.restEncoder,0),r.toUint8Array()},Mr=(e,t)=>{if(e.constructor===Fs){const{client:n,clock:r}=e.id;return new Fs(pr(n,r+t),e.length-t)}if(e.constructor===ui){const{client:n,clock:r}=e.id;return new ui(pr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new ci(pr(r,s+t),null,pr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},$r=(e,t=Zn,n=rr)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(Ue(e)));let s=r.map(e=>new jr(e,!0)),i=null;const o=new n,l=new Lr(o);for(;s=s.filter(e=>null!==e.curr),s.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===ui?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==s.length;){const e=s[0],t=e.curr.id.client;if(null!==i){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=i.struct.id.clock+i.struct.length&&n.id.client>=i.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>i.struct.id.clock+i.struct.length)continue;if(t!==i.struct.id.client)Nr(l,i.struct,i.offset),i={struct:n,offset:0},e.next();else if(i.struct.id.clock+i.struct.length<n.id.clock)if(i.struct.constructor===ui)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{Nr(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new ui(pr(t,i.struct.id.clock+i.struct.length),e),offset:0}}else{const t=i.struct.id.clock+i.struct.length-n.id.clock;t>0&&(i.struct.constructor===ui?i.struct.length-=t:n=Mr(n,t)),i.struct.mergeWith(n)||(Nr(l,i.struct,i.offset),i={struct:n,offset:0},e.next())}}else i={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===i.struct.id.clock+i.struct.length&&n.constructor!==ui;n=e.next())Nr(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(Nr(l,i.struct,i.offset),i=null),Br(l);const c=r.map(e=>(e=>{const t=new Hn,n=Me(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Me(e.restDecoder),r=Me(e.restDecoder);if(r>0){const s=Qt(t.clients,n,()=>[]);for(let t=0;t<r;t++)s.push(new Wn(e.readDsClock(),e.readDsLen()))}}return t})(e)),a=(e=>{const t=new Hn;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,s)=>{if(!t.clients.has(s)){const i=r.slice();for(let t=n+1;t<e.length;t++)G(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}});return Kn(t),t})(c);return qn(o,a),o.toUint8Array()},Rr=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:oe(e.encoder.restEncoder)}),e.encoder.restEncoder=ie(),e.written=0)},Nr=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Rr(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ae(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Br=e=>{Rr(e);const t=e.encoder.restEncoder;ae(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];ae(t,r.written),pe(t,r.restEncoder)}},Fr="You must not compute changes after the event-handler fired.";class Wr{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Hr(this.currentTarget,this.target))}deletes(e){return zn(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Ce(Fr);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let s,i;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;s="delete",i=q(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=q(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=q(r.content.getContent())}e.set(n,{action:s,oldValue:i})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw Ce(Fr);const t=this.target,n=J(),r=J(),s=[];e={added:n,deleted:r,delta:s,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const i=()=>{e&&s.push(e)};for(let s=t._start;null!==s;s=s.right)s.deleted?this.deletes(s)&&!this.adds(s)&&(null!==e&&void 0!==e.delete||(i(),e={delete:0}),e.delete+=s.length,r.add(s)):this.adds(s)?(null!==e&&void 0!==e.insert||(i(),e={insert:[]}),e.insert=e.insert.concat(s.content.getContent()),n.add(s)):(null!==e&&void 0!==e.retain||(i(),e={retain:0}),e.retain+=s.length);null!==e&&void 0===e.retain&&i()}this._changes=e}return e}}const Hr=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},Vr=()=>{((...e)=>{e.unshift($n),Nn.forEach(t=>t.print(e))})("Invalid access: Add Yjs type to a document before reading data.")};let zr=0;class Kr{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=zr++}}const Jr=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=zr++},qr=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>R(t-e.index)<R(t-n.index)?e:n);let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=zr++})(n));null!==r.right&&s<t;){if(!r.deleted&&r.countable){if(t<s+r.length)break;s+=r.length}r=r.right}for(;null!==r.left&&s>t;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return null!==n&&R(n.index-s)<r.parent.length/80?(Jr(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return Jr(r,t,n),r}{const r=new Kr(t,n);return e.push(r),r}})(e._searchMarker,r,s)},Gr=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const s=e[r];if(n>0){let t=s.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(s.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}s.p=t,t.marker=!0}(t<s.index||n>0&&t===s.index)&&(s.index=B(t,s.index+n))}},Yr=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;Qt(s,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;ur(r._eH,n,t)};class Qr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=cr(),this._dEH=cr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Ie()}clone(){throw Ie()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){ar(this._eH,e)}observeDeep(e){ar(this._dEH,e)}unobserve(e){dr(this._eH,e)}unobserveDeep(e){dr(this._dEH,e)}toJSON(){}}const Xr=(e,t,n)=>{e.doc??Vr(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const s=[];let i=e._start;for(;null!==i&&r>0;){if(i.countable&&!i.deleted){const e=i.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)s.push(e[n]),r--;t=0}}i=i.right}return s},Zr=e=>{e.doc??Vr();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},es=(e,t)=>{let n=0,r=e._start;for(e.doc??Vr();null!==r;){if(r.countable&&!r.deleted){const s=r.content.getContent();for(let r=0;r<s.length;r++)t(s[r],n++,e)}r=r.right}},ts=(e,t)=>{const n=[];return es(e,(r,s)=>{n.push(t(r,s,e))}),n},ns=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},rs=(e,t)=>{e.doc??Vr();const n=qr(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},ss=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,l=i.store,c=null===n?t._start:n.right;let a=[];const d=()=>{a.length>0&&(s=new ci(pr(o,br(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ys(a)),s.integrate(e,0),a=[])};r.forEach(n=>{if(null===n)a.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(n);break;default:switch(d(),n.constructor){case Uint8Array:case ArrayBuffer:s=new ci(pr(o,br(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ws(new Uint8Array(n))),s.integrate(e,0);break;case Qn:s=new ci(pr(o,br(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new zs(n)),s.integrate(e,0);break;default:if(!(n instanceof Qr))throw new Error("Unexpected content type in insert operation");s=new ci(pr(o,br(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new oi(n)),s.integrate(e,0)}}}),d()},is=()=>Ce("Length exceeded!"),os=(e,t,n,r)=>{if(n>t._length)throw is();if(0===n)return t._searchMarker&&Gr(t._searchMarker,n,r.length),ss(e,t,null,r);const s=n,i=qr(t,n);let o=t._start;for(null!==i&&(o=i.p,0===(n-=i.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&xr(e,pr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Gr(t._searchMarker,s,r.length),ss(e,t,o,r)},ls=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=qr(t,n);let l=t._start;for(null!==o&&(l=o.p,n-=o.index);null!==l&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&xr(e,pr(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&xr(e,pr(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw is();t._searchMarker&&Gr(t._searchMarker,s,-i+r)},cs=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},as=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new Ys([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Ys([r]);break;case Uint8Array:l=new Ws(r);break;case Qn:l=new zs(r);break;default:if(!(r instanceof Qr))throw new Error("Unexpected content type");l=new oi(r)}new ci(pr(o,br(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},ds=(e,t)=>{e.doc??Vr();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},us=e=>{const t={};return e.doc??Vr(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},hs=(e,t)=>{e.doc??Vr();const n=e._map.get(t);return void 0!==n&&!n.deleted},fs=e=>{return e.doc??Vr(),t=e._map.entries(),n=e=>!e[1].deleted,Bn(()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e});var t,n};class ps extends Wr{}class gs extends Qr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new gs;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new gs}clone(){const e=new gs;return e.insert(0,this.toArray().map(e=>e instanceof Qr?e.clone():e)),e}get length(){return this.doc??Vr(),this._length}_callObserver(e,t){super._callObserver(e,t),Yr(this,e,new ps(this,e))}insert(e,t){null!==this.doc?Ur(this.doc,n=>{os(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Ur(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;ss(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Ur(this.doc,n=>{ls(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return rs(this,e)}toArray(){return Zr(this)}slice(e=0,t=this.length){return Xr(this,e,t)}toJSON(){return this.map(e=>e instanceof Qr?e.toJSON():e)}map(e){return ts(this,e)}forEach(e){es(this,e)}[Symbol.iterator](){return ns(this)}_write(e){e.writeTypeRef(Zs)}}class ys extends Wr{constructor(e,t,n){super(e,t),this.keysChanged=n}}class ms extends Qr{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new ms}clone(){const e=new ms;return this.forEach((t,n)=>{e.set(n,t instanceof Qr?t.clone():t)}),e}_callObserver(e,t){Yr(this,e,new ys(this,e,t))}toJSON(){this.doc??Vr();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Qr?r.toJSON():r}}),e}get size(){return[...fs(this)].length}keys(){return Fn(fs(this),e=>e[0])}values(){return Fn(fs(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Fn(fs(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??Vr(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?Ur(this.doc,t=>{cs(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Ur(this.doc,n=>{as(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return ds(this,e)}has(e){return hs(this,e)}clear(){null!==this.doc?Ur(this.doc,e=>{this.forEach(function(t,n,r){cs(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(ei)}}const vs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||pn(e)===pn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,(e,n)=>(void 0!==e||gn(t,n))&&t[n]===e))(e,t);class bs{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Oe(),this.right.content.constructor===Js)this.right.deleted||Ss(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const ws=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Js)t.right.deleted||Ss(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&xr(e,pr(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},_s=(e,t,n,r)=>{const s=new Map,i=r?qr(t,n):null;if(i){const t=new bs(i.p.left,i.p,i.index,s);return ws(e,t,n-i.index)}{const r=new bs(null,t._start,0,s);return ws(e,r,n)}},ks=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Js&&vs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach((r,o)=>{const l=n.left,c=n.right,a=new ci(pr(i,br(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new Js(o,r));a.integrate(e,0),n.right=a,n.forward()})},Ss=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},xs=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Js&&vs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Es=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const l in r){const c=r[l],a=n.currentAttributes.get(l)??null;if(!vs(a,c)){o.set(l,a);const{left:r,right:d}=n;n.right=new ci(pr(i,br(s.store,i)),r,r&&r.lastId,d,d&&d.id,t,null,new Js(l,c)),n.right.integrate(e,0),n.forward()}}return o},Cs=(e,t,n,r,s)=>{n.currentAttributes.forEach((e,t)=>{void 0===s[t]&&(s[t]=null)});const i=e.doc,o=i.clientID;xs(n,s);const l=Es(e,t,n,s),c=r.constructor===String?new Qs(r):r instanceof Qr?new oi(r):new Ks(r);let{left:a,right:d,index:u}=n;t._searchMarker&&Gr(t._searchMarker,n.index,c.getLength()),d=new ci(pr(o,br(i.store,o)),a,a&&a.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=u,n.forward(),ks(e,t,n,l)},Is=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;xs(n,s);const l=Es(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Js));){if(!n.right.deleted)switch(n.right.content.constructor){case Js:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(vs(o,i))l.delete(t);else{if(0===r)break e;l.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&xr(e,pr(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let s="";for(;r>0;r--)s+="\n";n.right=new ci(pr(o,br(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Qs(s)),n.right.integrate(e,0),n.forward()}ks(e,t,n,l)},Os=(e,t,n,r,s)=>{let i=t;const o=Gt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Js){const e=i.content;o.set(e.key,e)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case Js:{const{key:i,value:a}=n,d=r.get(i)??null;o.get(i)===n&&d!==a||(t.delete(e),l++,c||(s.get(i)??null)!==a||d===a||(null===d?s.delete(i):s.set(i,d))),c||t.deleted||Ss(s,n);break}}}t=t.right}return l},Ds=e=>{let t=0;return Ur(e.doc,n=>{let r=e._start,s=e._start,i=Gt();const o=Yt(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===Js)Ss(o,s.content);else t+=Os(n,r,s,i,o),i=Yt(o),r=s;s=s.right}}),t},As=e=>{const t=new Set,n=e.doc;for(const[r,s]of e.afterState.entries()){const i=e.beforeState.get(r)||0;s!==i&&Cr(e,n.store.clients.get(r),i,s,e=>{e.deleted||e.content.constructor!==Js||e.constructor===Fs||t.add(e.parent)})}Ur(n,n=>{Vn(e,e.deleteSet,e=>{if(e instanceof Fs||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Js?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===Js){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)Ds(e)})},Ts=(e,t,n)=>{const r=n,s=Yt(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case oi:case Ks:case Qs:n<t.right.length&&xr(e,pr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&Os(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Gr(o._searchMarker,t.index,-r+n),t};class Us extends Wr{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];Ur(e,e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let l="",c=0,a=0;const d=()=>{if(null!==i){let e=null;switch(i){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof l||l.length>0)&&(e={insert:l},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),l="";break;case"retain":c>0&&(e={retain:c},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=un({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case oi:case Ks:this.adds(s)?this.deletes(s)||(d(),i="insert",l=s.content.getContent()[0],d()):this.deletes(s)?("delete"!==i&&(d(),i="delete"),a+=1):s.deleted||("retain"!==i&&(d(),i="retain"),c+=1);break;case Qs:this.adds(s)?this.deletes(s)||("insert"!==i&&(d(),i="insert"),l+=s.content.str):this.deletes(s)?("delete"!==i&&(d(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(d(),i="retain"),c+=s.length);break;case Js:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;vs(c,l)?null!==l&&s.delete(e):("retain"===i&&d(),vs(l,r.get(t)??null)?delete o[t]:o[t]=l)}}else if(this.deletes(s)){r.set(t,l);const e=n.get(t)??null;vs(e,l)||("retain"===i&&d(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(vs(n,l)?null!==n&&s.delete(e):("retain"===i&&d(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&d(),Ss(n,s.content));break}}s=s.right}for(d();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}}class js extends Qr{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Vr(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){}this._pending=null}_copy(){return new js}clone(){const e=new js;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new Us(this,e,t);Yr(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Vr();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Qs&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Ur(this.doc,n=>{const r=new bs(null,this._start,0,new Map);for(let s=0;s<e.length;s++){const i=e[s];if(void 0!==i.insert){const o=t||"string"!=typeof i.insert||s!==e.length-1||null!==r.right||"\n"!==i.insert.slice(-1)?i.insert:i.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Cs(n,this,r,o,i.attributes||{})}else void 0!==i.retain?Is(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&Ts(n,r,i.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??Vr();const r=[],s=new Map,i=this.doc;let o="",l=this._start;function c(){if(o.length>0){const e={};let t=!1;s.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==l;){if(gr(l,e)||void 0!==t&&gr(l,t))switch(l.content.constructor){case Qs:{const r=s.get("ychange");void 0===e||gr(l,e)?void 0===t||gr(l,t)?void 0!==r&&(c(),s.delete("ychange")):void 0!==r&&r.user===l.id.client&&"added"===r.type||(c(),s.set("ychange",n?n("added",l.id):{type:"added"})):void 0!==r&&r.user===l.id.client&&"removed"===r.type||(c(),s.set("ychange",n?n("removed",l.id):{type:"removed"})),o+=l.content.str;break}case oi:case Ks:{c();const e={insert:l.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach((e,n)=>{t[n]=e})}r.push(e);break}case Js:gr(l,e)&&(c(),Ss(s,l.content))}l=l.right}c()};return e||t?Ur(i,n=>{e&&yr(n,e),t&&yr(n,t),a()},"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Ur(r,r=>{const s=_s(r,this,e,!n);n||(n={},s.currentAttributes.forEach((e,t)=>{n[t]=e})),Cs(r,this,s,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?Ur(r,r=>{const s=_s(r,this,e,!n);Cs(r,this,s,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?Ur(n,n=>{Ts(n,_s(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?Ur(r,r=>{const s=_s(r,this,e,!1);null!==s.right&&Is(r,this,s,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?Ur(this.doc,t=>{cs(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?Ur(this.doc,n=>{as(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return ds(this,e)}getAttributes(){return us(this)}_write(e){e.writeTypeRef(ti)}}class Ls{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Vr()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==Ms&&t.constructor!==Ps||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Ps extends Qr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ps}clone(){const e=new Ps;return e.insert(0,this.toArray().map(e=>e instanceof Qr?e.clone():e)),e}get length(){return this.doc??Vr(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new Ls(this,e)}querySelector(e){e=e.toUpperCase();const t=new Ls(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Y(new Ls(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Yr(this,e,new $s(this,t,e))}toString(){return ts(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),es(this,s=>{r.insertBefore(s.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?Ur(this.doc,n=>{os(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Ur(this.doc,n=>{const r=e&&e instanceof Qr?e._item:e;ss(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw Ce("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Ur(this.doc,n=>{ls(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return Zr(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return rs(this,e)}slice(e=0,t=this.length){return Xr(this,e,t)}forEach(e){es(this,e)}_write(e){e.writeTypeRef(ri)}}class Ms extends Ps{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new Ms(this.nodeName)}clone(){const e=new Ms(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),(t,n)=>{"string"==typeof t&&e.setAttribute(n,t)}),e.insert(0,this.toArray().map(e=>e instanceof Qr?e.clone():e)),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const s=this.nodeName.toLocaleLowerCase();return`<${s}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${s}>`}removeAttribute(e){null!==this.doc?Ur(this.doc,t=>{cs(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Ur(this.doc,n=>{as(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return ds(this,e)}hasAttribute(e){return hs(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let s=e;for(;null!==s&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;null!==s&&gr(s,t)&&(n[r]=s.content.getContent()[s.length-1])}),n})(this,e):us(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),s=this.getAttributes();for(const e in s){const t=s[e];"string"==typeof t&&r.setAttribute(e,t)}return es(this,s=>{r.appendChild(s.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(ni),e.writeKey(this.nodeName)}}class $s extends Wr{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}}class Rs extends ms{constructor(e){super(),this.hookName=e}_copy(){return new Rs(this.hookName)}clone(){const e=new Rs(this.hookName);return this.forEach((t,n)=>{e.set(n,t)}),e}toDOM(e=document,t={},n){const r=t[this.hookName];let s;return s=void 0!==r?r.createDom(this):document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(si),e.writeKey(this.hookName)}}class Ns extends js{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new Ns}clone(){const e=new Ns;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(ii)}}class Bs{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Ie()}mergeWith(e){return!1}write(e,t,n){throw Ie()}integrate(e,t){throw Ie()}}class Fs extends Bs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),wr(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class Ws{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ws(this.content)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class Hs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Hs(this.len)}splice(e){const t=new Hs(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Jn(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const Vs=(e,t)=>new Qn({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class zs{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new zs(Vs(this.doc.guid,this.opts))}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class Ks{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ks(this.embed)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class Js{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Js(this.key,this.value)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class qs{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new qs(this.arr)}splice(e){const t=new qs(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}const Gs="development"===xn("node_env");class Ys{constructor(e){this.arr=e,Gs&&mn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ys(this.arr)}splice(e){const t=new Ys(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class Qs{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Qs(this.str)}splice(e){const t=new Qs(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const Xs=[e=>new gs,e=>new ms,e=>new js,e=>new Ms(e.readKey()),e=>new Ps,e=>new Rs(e.readKey()),e=>new Ns],Zs=0,ei=1,ti=2,ni=3,ri=4,si=5,ii=6;class oi{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new oi(this.type._copy())}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const li=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new ci(pr(r,s+n),t,pr(r,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),null!==t.redone&&(i.redone=pr(t.redone.client,t.redone.clock+n)),t.right=i,null!==i.right&&(i.right.left=i),e._mergeStructs.push(i),null!==i.parentSub&&null===i.right&&i.parent._map.set(i.parentSub,i),t.length=n,i};class ci extends Bs{constructor(e,t,n,r,s,i,o,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=l,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=br(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=br(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===hr&&this.id.client!==this.parent.client&&this.parent.clock>=br(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Er(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=xr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Fs||this.right&&this.right.constructor===Fs)this.parent=null;else if(this.parent){if(this.parent.constructor===hr){const e=kr(t,this.parent);e.constructor===Fs?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===ci?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===ci&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Er(e,e.doc.store,pr(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,s=new Set;for(;null!==t&&t!==this.right;){if(s.add(t),r.add(t),fr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(fr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(kr(e.doc.store,t.origin)))break;r.has(kr(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),wr(e.doc.store,this),this.content.integrate(e,this),Dr(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Fs(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:pr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&fr(e.origin,this.lastId)&&this.right===e&&fr(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),Jn(e.deleteSet,this.id.client,this.id.clock,this.length),Dr(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Oe();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[_r(r,t.id.clock)]=n})(e,this,new Fs(this.id,this.length)):this.content=new Hs(this.length)}write(e,t){const n=t>0?pr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:H)|(null===r?0:W)|(null===s?0:32);if(e.writeInfo(i),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=(e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Oe()})(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===hr?(e.writeParentInfo(!1),e.writeLeftID(t)):Oe();null!==s&&e.writeString(s)}this.content.write(e,t)}}const ai=(e,t)=>di[31&t](e),di=[()=>{Oe()},e=>new Hs(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new qs(n)},e=>new Ws(e.readBuf()),e=>new Qs(e.readString()),e=>new Ks(e.readJSON()),e=>new Js(e.readKey(),e.readJSON()),e=>new oi(Xs[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Ys(n)},e=>new zs(Vs(e.readString(),e.readAny())),()=>{Oe()}];class ui extends Bs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Oe()}write(e,t){e.writeInfo(10),ae(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const hi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},fi="__ $YJS$ __";function pi(e,t,n){var r,s,i;if(!e.dx._allTables[t])return;const o=null===(i=null===(s=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===s?void 0:s.find(e=>e.prop===n))||void 0===i?void 0:i.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}hi[fi],hi[fi]=!0;const gi=new FinalizationRegistry(({cache:e,key:t})=>{delete e[t]});function yi(e){var t,n;return null!==(t=(n=e._novip)._docCache)&&void 0!==t?t:n._docCache={cache:{},get size(){return Object.keys(this.cache).length},find(e,t,n){const r=bi(e,t,n),s=this.cache[r];return s?s.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:s}=e.meta;if(!n||!s||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const i=bi(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&gi.unregister(o),this.cache[i]=new WeakRef(e),gi.register(e,{cache:this.cache,key:i},e)},delete(e){gi.unregister(e);const t=bi(e.meta.parentTable,e.meta.parentId,e.meta.parentProp),n=this.cache[t];(null==n?void 0:n.deref())===e&&delete this.cache[t]}}}const mi=new WeakSet;function vi(e){if(mi.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function bi(e,t,n){return`${e}[${t}].${n}`}const{getByKeyPath:wi}=e.Dexie;let _i=null;function ki(e){_i=e}function Si(){}const xi=new WeakMap;function Ei(){return e.Dexie.Events(null,"load","sync","error")}class Ci{static getOrCreateDocument(e,t,n,r){var s,i;const o=yi(e),l=null===(i=null===(s=e.table(t).schema.yProps)||void 0===s?void 0:s.find(e=>e.prop===n))||void 0===i?void 0:i.updatesTable;if(!l)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,s,i){let o=t.find(n,i,r);return o||(o=new Qn({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",()=>{mi.add(o),t.delete(o)}),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=xi.get(e);return r?(++r.refCount,null!=(null==t?void 0:t.gracePeriod)&&r.graceTimeout<t.gracePeriod&&(r.graceTimeout=t.gracePeriod),r.graceTimer&&(clearTimeout(r.graceTimer),r.graceTimer=null)):(r=new Ci(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,xi.set(e,r)),r}static release(e){if(!e||mi.has(e))return;const t=xi.get(e);t?--t.refCount<=0&&(t.graceTimeout<0?t._release():t.graceTimer||(t.graceTimer=setTimeout(()=>{t.graceTimer=null,0===t.refCount&&t._release()},t.graceTimeout))):e.destroy()}_release(){this.doc&&Promise.resolve(Ci.on("beforeunload").fire(this)).finally(()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())})}static for(e){return xi.get(e)}static get currentUpdateRow(){return _i}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise((t,n)=>{this.doc?this.doc.isLoaded?t():this._error?n(this._error):mi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",t),this.on("error",n),this.doc.on("destroy",()=>n(new e.Dexie.AbortError("Document was destroyed before loaded")))):n(new Error("No Y.Doc associated with this provider"))})),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise((t,n)=>{this.doc?this.doc.isSynced?t():this._error?n(this._error):mi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",t),this.on("error",n),this.doc.on("destroy",()=>n(new e.Dexie.AbortError("Document was destroyed before synced")))):n(new Error("No Y.Doc associated with this provider"))})),this._whenSynced}constructor(t){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Ei(),this.doc=t,this.off=(e,t)=>{var n;return null===(n=this.on[e])||void 0===n?void 0:n.unsubscribe(t)},"dispose"in Symbol&&(this[Symbol.dispose]=()=>Ci.release(t)),t.on("load",()=>this.on("load").fire()),t.on("sync",e=>!1!==e&&this.on("sync").fire()),t.on("destroy",this.destroy.bind(this)),this.on("error",e=>{this._error=e});const{db:n,parentTable:r,parentId:s,updatesTable:i}=t.meta||{};if(!n||!r||!i)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(i))throw new Error(`Table ${r} or ${i} not found in db`);vi(t),this.stopObserving=function(t,n,r,s,i,o){let l=0,c=!0;const a=e.liveQuery(()=>{vi(n);const t=r.table(i);return Promise.all([(l>0?t.where("i").between(l,1/0,!1).toArray().then(t=>t.filter(t=>0===e.cmp(t.k,o))):t.where({k:o}).toArray()).then(e=>e),r.table(s).where(":id").equals(o).toArray()])}).subscribe(([e,r])=>{e.length>0&&(l=e[e.length-1].i),0!==r.length?(vi(n),e.length>0&&Ur(n,()=>{e.forEach(e=>{try{ki(e),or(n,e.u)}finally{ki(null)}})},t,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()},e=>{t.on("error").fire(e)}),d=(e,n)=>{n!==t&&r.table(i).add({k:o,u:e,f:1}).then(e=>{e===l-1&&++l}).catch(e=>{t.on("error").fire(e)})},u=()=>{a.unsubscribe(),n.off("updateV2",d),n.off("destroy",u)};return n.on("updateV2",d),n.on("destroy",u),u}(this,t,n,r,i,s),Ci.on("new").fire(this)}destroy(){var e;xi.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Ei(),this.cleanupHandlers.forEach(e=>e())}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Ii(t,n){return r(this,void 0,void 0,function*(){var s;const i={};let o,l=!1;for(const c of t)try{switch(c.type){case"u-s":{const e=pi(n,c.table,c.prop);if(e){const t={k:c.k,u:c.u};c.r&&(t.r=c.r,o=c.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=pi(n,c.table,c.prop);e&&(yield n.transaction("rw",e,t=>r(this,void 0,void 0,function*(){let n=yield t.table(e.name).get(Jt);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:Jt}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})));break}case"u-reject":{const t=pi(n,c.table,c.prop);if(!t)break;const r=null===(s=yield t.get(c.i))||void 0===s?void 0:s.k;if(null!=r){yield n.transaction("rw",t,n=>(n.idbtrans._rejecting_y_ypdate=!0,t.where("i").aboveOrEqual(c.i).filter(t=>0===e.cmp(t.k,r)&&!(1&~(t.f||0))).delete()));const s=Ci.getDocCache(n.dx).find(c.table,r,c.prop);s&&s.destroy()}break}case"in-sync":{const e=Ci.getDocCache(n.dx).find(c.table,c.k,c.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=c.yServerRev;break;case"outdated-server-rev":l=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:l,yServerRevision:o}})}Ci.on=e.Dexie.Events(null,{new:[function(e,t){return e===Si?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Si?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then(function(){return t.apply(r,i)})}return t.apply(this,arguments)}}]}),Ci.getDocCache=yi,e.Dexie.DexieYProvider?Ci=e.Dexie.DexieYProvider||Ci:e.Dexie.DexieYProvider=Ci;function Oi(t,n,s){return r(this,arguments,void 0,function*(t,n,{yDownloadedRealms:s,realms:c}){if(s&&c&&c.every(e=>"*"===s[e]))return;const a=yield nt(t),d={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(d.Authorization=`Bearer ${a.accessToken}`);const u=yield fetch(`${n}/y/download`,{body:jt.stringify({downloadedRealms:s||{}}),method:"POST",headers:d,credentials:"include"});if(!u.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${u.status}`);yield async function(e,...t){let n=e();for(let e=0;e<t.length;e++)n=t[e](n);for await(const e of n);}(function(e){return async function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}}}(u),Je,function(s){return o(this,arguments,function*(){var o,c,a,d;let u=null,h=null,f=null,p=[];function g(e){return r(this,void 0,void 0,function*(){const r=p[p.length-1];if(p.length>0){if(!u||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const e=pi(t,h,f);e&&(yield e.bulkAdd(p)),p=[]}u&&(h&&f&&r||e)&&(yield t.$syncState.update("syncState",t=>{const n=t.yDownloadedRealms||{};n[u]=e?"*":{tbl:h,prop:f,key:r.k},t.yDownloadedRealms=n}))})}try{try{for(var y,m=!0,v=l(s);!(o=(y=yield i(v.next())).done);m=!0){d=y.value,m=!1;const e=new Te(d);for(;je(e);)switch(Pe(e)){case 1:yield i(g(!0)),u=Re(e);break;case 2:yield i(g(!1)),h=Re(e),f=Re(e);break;case 3:{const t=We(e),n=Le(e);p.push({k:t,u:n});break}}yield i(g(!1))}}catch(e){c={error:e}}finally{try{m||o||!(a=v.return)||(yield i(a.call(v)))}finally{if(c)throw c.error}}yield i(g(!0))}catch(t){throw t instanceof e.DexieError||(yield i(g(!1))),t}})})})}const Di="currentSyncWorker";function Ai(e,t,n,s){return Ti(e,t,n,s).then(t=>((null==s?void 0:s.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t)).catch(i=>r(this,void 0,void 0,function*(){return(null==s?void 0:s.justCheckIfNeeded)?Promise.reject(i):Wt&&(null==s?void 0:s.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise(e=>setTimeout(e,500)),yield Ai(e,t,n,Object.assign(Object.assign({},s),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:Wt?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))}function Ti(e,t,n){return r(this,arguments,void 0,function*(e,t,n,{isInitialSync:s,cancelToken:i,justCheckIfNeeded:o,purpose:l}={isInitialSync:!1}){var a;if(!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:d}=t,u=yield e.getCurrentUser(),h=u.isLoggedIn?k(e):[],f=h.map(t=>e.table(S(t.name))),p=yield e.getPersistedSyncState(),g=u.isLoggedIn,y=g?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return k(e).filter(e=>!n.includes(e.name))}(e,p):[];Ft(i);const m=y.length>0;if(m){if(o)return!0;yield e.transaction("rw",y,e=>r(this,void 0,void 0,function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify(e=>{r.has(e.realmId)||e.userId&&e.userId!==c.userId||(e.userId=t.userId)}):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify(e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==c.userId||(e.owner=t.userId)}):yield n.toCollection().modify(e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==c.userId||(e.owner=t.userId),e.realmId&&e.realmId!==c.userId||(e.realmId=t.userId))}))})}(y,u,null==p?void 0:p.realms)})),Ft(i)}const[v,b,w,{yMessages:_,lastUpdateIds:E}]=yield e.transaction("r",e.tables,()=>r(this,void 0,void 0,function*(){const t=yield e.getPersistedSyncState();let s=yield e.$baseRevs.toArray();s=s.filter(e=>h.some(t=>t.name===e.tableName));let o=yield I(f,e);const l=yield function(e,t){return r(this,void 0,void 0,function*(){const n=[],r={};for(const s of t)if(s.schema.yProps)for(const t of s.schema.yProps){const i=e.table(t.updatesTable),o=yield i.get(Jt),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),d=yield qt(i,a);d.length>0&&(r[i.name]=d[d.length-1].i);const u={};for(const e of d){const t=!(1&~(e.f||0));if(t&&e.i<l)continue;const n=JSON.stringify(e.k)+"/"+t;let r=u[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(u[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:i,i:o}of Object.values(u)){const l=1===i.length?i[0]:$r(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=Pr(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}})}(e,h);if(Ft(i),m){const e=[...(null==p?void 0:p.realms)||[],...(null==p?void 0:p.inviteRealms)||[]],c=yield function(e,t,n,s){return r(this,void 0,void 0,function*(){const i=`upload-${O(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(s||[]);return(yield Promise.all(e.map(e=>r(this,void 0,void 0,function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const s=n[e.name],l=(null==s?void 0:s.generatedGlobalId)?e.filter(e=>{return r(e),!o.has(e.realmId||"")&&(t=r(e),!(n=null==s?void 0:s.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n}):e.filter(e=>{const t=r(e);return!o.has(e.realmId||"")&&j(t)}),c=yield l.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter(e=>e.muts.length>0)}return[]})}(y,u,n,e);return Ft(i),o=o.concat(c),[o,t,s,l]}return[o,t,s,l]})),C=v.some(e=>e.muts.some(e=>e.keys.length>0))||_.some(e=>"u-c"===e.type);if(o)return C;if("push"===l&&!C)return!1;const D=Vt(v,null==b?void 0:b.latestRevisions),A=(null==b?void 0:b.clientIdentity)||T(16);Ft(i);const U=yield Bt(v,_,b,w,e,d,n,A,u),{done:L,newSyncState:P}=yield e.transaction("rw",e.tables,t=>r(this,void 0,void 0,function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))U.schema[e]&&(n[e]=U.schema[e]);yield e.$syncState.put(n,"schema");const s=yield I(f,e,{since:D});for(const t of f){const n=x(t.name);if(s.some(e=>e.table===n&&e.muts.length>0)){if(D[n]){const r=D[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}Vt(s,D),yield Ht(e,n,D,U.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=new Set,s=new Set,i=n?n.realms:[],o=n?n.inviteRealms:[],l=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)l.has(e)||(s.add(e),c.has(e)||r.add(e));for(const e of o.concat(i))c.has(e)||r.add(e);if(r.size>0||s.size>0){const t=k(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:s;0!==t.size&&(e.schema.indexes.some(e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0])?yield e.where("realmId").anyOf([...t]).delete():yield e.filter(e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId)).delete())}}if(s.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of s)delete n.yDownloadedRealms[e]})}(e,U,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:A};g&&(o.syncedTables=h.map(e=>e.name).concat(y.map(e=>e.name))),o.latestRevisions=D,o.remoteDbId=U.dbId,o.initiallySynced=!0,o.realms=U.realms,o.inviteRealms=U.inviteRealms,o.serverRevision=U.serverRevision,o.yServerRevision=U.serverRevision,o.timestamp=new Date,delete o.error;const l=Ui(U.changes,s);if(yield Kt(l,e),U.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:s}=yield Ii(U.yMessages,e);s&&(o.yServerRevision=s),yield function(e,t,n){return r(this,void 0,void 0,function*(){var s,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(s=a[t])&&void 0!==s||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=a[e])&&void 0!==i||(a[e]={}),a[e].receivedUntil=n;const d=Object.values(n.dx._dbSchema).filter(e=>e.yProps).map(e=>e.yProps.map(e=>e.updatesTable)).flat();for(const e of d){const t=a[e],s=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,i=null!==(c=null!==(l=null==t?void 0:t.receivedUntil)&&void 0!==l?l:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==c?c:0;yield n.transaction("rw",e,()=>r(this,void 0,void 0,function*(){const t=yield n.table(e).get(Jt);t?(t.unsentFrom=Math.max(s,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:Jt,unsentFrom:s,receivedUntil:i})}))}})}(E,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===s.length,newSyncState:o}}));if(!L)return yield Nt(e),yield Ti(e,t,n,{isInitialSync:s,cancelToken:i});const M=Object.values(n).some(e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length}),$=!!U.yMessages;if(M&&$)try{yield Oi(e,d,P)}catch(e){}return e.syncCompleteEvent.next(),!1})}function Ui(e,t){const n={};M(n,e);const r={};return M(r,t),function(e,t){for(const[n,r]of Object.entries(t))for(const[t,s]of Object.entries(r))switch(s.type){case"ups":{const r=e[n]?.[t];if(r)switch(r.type){case"ups":case"upd":delete e[n][t]}}break;case"del":delete e[n]?.[t];break;case"upd":{const r=e[n]?.[t];if(r)switch(r.type){case"ups":for(const[e,t]of Object.entries(s.mod))A(r.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(s.mod))delete r.mod[e]}break}}}(n,r),function(e,t){const n={};for(const[t,r]of Object.entries(e))for(const[e,s]of Object.entries(r)){const r=n[t]||(n[t]={});(r[s.type]||(r[s.type]=[])).push({key:e,...s})}const r=[];for(const[e,s]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(s))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 ji(s){const i=[],o=new t.BehaviorSubject(!0),l=new t.BehaviorSubject(null);let c=!1,a=new Array(10).fill(0);return l.subscribe(()=>r(this,void 0,void 0,function*(){if(!c&&i.length>0){c=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return r(this,void 0,void 0,function*(){for(var o,l,c,a,d,u;i.length>0;){const h=i.shift();try{yield t.firstValueFrom(s.cloud.syncState.pipe(n.filter(({phase:e})=>"in-sync"===e||"error"===e)));const i=s.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const t=s.cloud.currentUser.value,n=yield st(s.cloud.options.databaseUrl,t);yield s.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data});break;case"realm-added":(null===(o=null==i?void 0:i.realms)||void 0===o?void 0:o.includes(h.realm))||(null===(l=null==i?void 0:i.inviteRealms)||void 0===l?void 0:l.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==i?void 0:i.realms)||void 0===c?void 0:c.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(a=null==i?void 0:i.realms)||void 0===a?void 0:a.includes(h.realm))||(null===(d=null==i?void 0:i.inviteRealms)||void 0===d?void 0:d.includes(h.realm)))&&(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield s.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(u=s.cloud.syncState.value)||void 0===u?void 0:u.phase)){y(s,"pull");break}yield s.transaction("rw",s.dx.tables,t=>r(this,void 0,void 0,function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,r,i]=yield Promise.all([s.getSchema(),s.getPersistedSyncState(),s.getCurrentUser()]);if(!r||!n||!i)return;if(h.baseRev!==r.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof r.serverRevision&&"object"!=typeof r.serverRevision||y(s,"pull"));if((yield e.waitFor(_(r)))!==h.realmSetHash)return void y(s,"pull");let o=[];if(i.isLoggedIn){const e=k(s).map(e=>s.table(S(e.name)));o=yield I(e,s)}if(h.changes.length>0){const e=Ui(h.changes,o);yield Kt(e,s)}r.latestRevisions=Vt(o,r.latestRevisions),r.serverRevision=h.newRev,yield Ht(s,n,r.latestRevisions,h.newRev),yield s.$syncState.put(r,"syncState")}))}}catch(e){}}})}()}finally{a[a.length-1]-a[0]<1e4&&(yield new Promise(e=>setTimeout(e,1e3))),c=!1,o.next(!0)}}})),{enqueue:function(e){i.push(e),l.next(null)},readyToServe:o}}const Li=new WeakMap,Pi={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Mi=0;function $i(e){"vip"in e&&(e=e.vip);let n=Li.get(e.cloud);if(!n){const r=new t.Subject;let s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`);r.id=++Mi;let o=!1;n={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>n.$logins.toArray().then(e=>e.find(e=>e.isLoggedIn)||c),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema").then(e=>{if(e)for(const t of n.tables)t.schema.primKey&&t.schema.primKey.keyPath&&e[t.name]&&(e[t.name].primaryKey=Ri(t.schema.primKey.keyPath));return e}),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`)}};Object.assign(n,l),n.messageConsumer=ji(n),n.messageProducer=new t.Subject,Li.set(e.cloud,n)}return n}function Ri(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}const Ni=new WeakMap;class Bi{constructor(e,t){Ni.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then(n=>new Bi(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)}))}save(){return r(this,void 0,void 0,function*(){Ni.get(this).table("$logins").put(this)})}}function Fi(e,n){return t.firstValueFrom(t.from(e).pipe(t.filter(n)))}function Wi(e){return r(this,void 0,void 0,function*(){const t=yield Hi(e);if(t){if(!(yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield Xe(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then(()=>!0).catch(()=>!1)})}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield Hi(e,{deleteUnsyncedData:!0})}})}function Hi(e){return r(this,arguments,void 0,function*(e,{deleteUnsyncedData:t=!1}={}){const[n,s]=yield e.dx.transaction("rw",e.dx.tables,n=>r(this,void 0,void 0,function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const s=n.storeNames.filter(e=>e.endsWith("_mutations")),i=(yield Promise.all(s.map(e=>n.table(e).count()))).reduce((e,t)=>e+t,0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}));return s&&(yield Fi(e.cloud.currentUser,e=>e.userId===c.userId),yield e.cloud.sync({purpose:"pull",wait:!0})),n})}const Vi={access_denied:"Access was denied by the authentication provider.",invalid_state:"The authentication response could not be verified. Please try again.",email_not_verified:"Your email address must be verified before you can log in.",expired_code:"The authentication code has expired. Please try again.",provider_error:"An error occurred with the authentication provider.",network_error:"A network error occurred during authentication. Please check your connection and try again."};class zi extends Error{constructor(e,t,n){super(n||Vi[e]),this.name="OAuthError",this.code=e,this.provider=t}get userMessage(){return Vi[this.code]||this.message}}const Ki={providers:[],otpEnabled:!0};function Ji(e){"undefined"!=typeof sessionStorage&&sessionStorage.setItem("dexie-cloud-oauth-provider",e.provider);const t=function(e){const t=new URL(`${e.databaseUrl}/oauth/login/${e.provider}`),n=e.redirectUri||("undefined"!=typeof window?window.location.href:"");return n&&t.searchParams.set("redirect_uri",n),t.toString()}(e);window.location.href=t}function qi(t){const{userInteraction:n}=t.cloud;return function(s){return r(this,arguments,void 0,function*({public_key:s,hints:i}){var o,l;let c;const a=null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!a)throw new Error("No database URL given.");if((null==i?void 0:i.oauthCode)&&i.provider)return yield function(e){return r(this,void 0,void 0,function*(){const{databaseUrl:t,code:n,publicKey:r,scopes:s=["ACCESS_DB"]}=e,i={grant_type:"authorization_code",code:n,public_key:r,scopes:s};try{const e=yield fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),mode:"cors"});if(!e.ok){if(400===e.status||401===e.status)try{const t=yield e.json();if("error"===t.type){if("INVALID_OTP"===t.messageCode)throw new zi("expired_code",void 0,t.message);throw new qe(t)}}catch(e){if(e instanceof zi||e instanceof qe)throw e}const t=yield e.text().catch(()=>e.statusText);throw new zi("provider_error",void 0,`Token exchange failed: ${e.status} ${t}`)}const n=yield e.json();if("error"===n.type)throw new qe(n);if("tokens"!==n.type)throw new zi("provider_error",void 0,`Unexpected response type: ${n.type}`);return n}catch(e){if(e instanceof zi||e instanceof qe)throw e;if(e instanceof TypeError)throw new zi("network_error");throw e}})}({databaseUrl:a,code:i.oauthCode,publicKey:s,scopes:["ACCESS_DB"]});if(null==i?void 0:i.provider)throw Gi(t,i.provider),new Error("OAuth redirect initiated");if("demo"===(null==i?void 0:i.grant_type)){c={demo_user:yield et(n,"Enter a demo user email",(null==i?void 0:i.email)||(null==i?void 0:i.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:s}}else if((null==i?void 0:i.otpId)&&i.otp)c={grant_type:"otp",otp_id:i.otpId,otp:i.otp,scopes:["ACCESS_DB"],public_key:s};else{const o=!1!==(null===(l=t.cloud.options)||void 0===l?void 0:l.socialAuth),d=yield function(e){return r(this,arguments,void 0,function*(e,t=!0){if(!t)return Ki;try{const t=yield fetch(`${e}/auth-providers`,{method:"GET",headers:{Accept:"application/json"},mode:"cors"});return 404===t.status?Ki:t.ok?yield t.json():Ki}catch(e){return Ki}})}(a,o);if(d.providers.length>0){const s=yield function(t,n,s){return r(this,arguments,void 0,function*(t,n,r,s="Choose login method",i=[]){const o=[...yield Promise.all(n.map(Qe))];return r&&o.push({name:"otp",value:"email",displayName:"Continue with email",iconSvg:'<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6L12 13 2 6"/></svg>',styleHint:"otp"}),new Promise((n,r)=>{const l={type:"generic",title:s,alerts:i,options:o,fields:{},submitLabel:"",cancelLabel:"Cancel",onSubmit:e=>{t.next(void 0),n("otp"in e?{type:"otp"}:"provider"in e?{type:"provider",provider:e.provider}:{type:"otp"})},onCancel:()=>{t.next(void 0),r(new e.AbortError("User cancelled"))}};t.next(l)})})}(n,d.providers,d.otpEnabled,"Sign in");if("provider"===s.type)throw Gi(t,s.provider),new Error("OAuth redirect initiated")}const u=yield et(n,"Enter email address",null==i?void 0:i.email);c=/@demo.local$/.test(u)?{demo_user:u,grant_type:"demo",scopes:["ACCESS_DB"],public_key:s}:{email:u,grant_type:"otp",scopes:["ACCESS_DB"]}}const d=yield fetch(`${a}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==d.status){const e=yield d.text();throw yield Ze(n,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch(()=>{}),new Pt(d,e)}const u=yield d.json();if("tokens"===u.type||"error"===u.type)return u;if("otp"===c.grant_type&&"email"in c){if("otp-sent"!==u.type)throw new Error(`Unexpected response from ${a}/token`);const e=yield tt(n,c.email),t=Object.assign(Object.assign({},c),{otp:e||"",otp_id:u.otp_id,public_key:s});let r=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===r.status;){const e=yield r.text();t.otp=yield tt(n,c.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),r=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==r.status){const e=yield r.text();throw new Pt(r,e)}return yield r.json()}throw new Error(`Unexpected response from ${a}/token`)})}}function Gi(e,t){var n,r;const s=null===(n=e.cloud.options)||void 0===n?void 0:n.databaseUrl;if(!s)throw new Error("No database URL given.");Ji({databaseUrl:s,provider:t,redirectUri:(null===(r=e.cloud.options)||void 0===r?void 0:r.oauthRedirectUri)||("undefined"!=typeof window?window.location.href:void 0)})}function Yi(e,...t){globalThis.console[e](...t)}function Qi(e,t){return r(this,void 0,void 0,function*(){var n;const s=yield e.getCurrentUser(),i=s.userId;if(s.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok")&&s.accessToken&&(!s.accessTokenExpiration||s.accessTokenExpiration.getTime()>Date.now()))return!1;if(s.refreshToken&&(!s.refreshTokenExpiration||s.refreshTokenExpiration.getTime()>Date.now()))return yield nt(e),!1}const o=new Bi(e,{claims:{},lastLogin:new Date(0)});return yield rt(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||qi(e),e.cloud.userInteraction,t),i!==c.userId&&o.userId!==i&&(yield Wi(e)),yield function(e,t){return r(this,void 0,void 0,function*(){const n=e.table("$logins");yield e.transaction("rw",n,e=>r(this,void 0,void 0,function*(){const e=yield n.toArray();yield Promise.all(e.filter(e=>e.userId!==t.userId&&e.isLoggedIn).map(e=>(e.isLoggedIn=!1,n.put(e)))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(Yi("debug","Login context property names:",Object.keys(t)),Yi("debug","Login context property names:",Object.keys(t)),Yi("debug","Login context:",t),Yi("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})),yield Fi(e.cloud.currentUser,e=>e.userId===t.userId)})}(e,o),y(e,"pull"),o.userId!==i})}const Xi="undefined"!=typeof InstallTrigger,Zi="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),eo=Zi?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,to=Zi&&eo<=605||Xi,no="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:ro}={};function so(e){return ro.call(e).slice(8,-1)}function io(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}function oo(e,t){return(1&t?e[0].toUpperCase():e[0].toLowerCase())+(2&t?e[1].toUpperCase():e[1].toLowerCase())+(4&t?e[2].toUpperCase():e[2].toLowerCase())}const lo=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;function co(e){return e>="A"&&e<="Z"}let ao=0;function uo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();ao>=s?++ao:ao=s,r[0]=ao/1099511627776,r[1]=ao/4294967296,r[2]=ao/16777216,r[3]=ao/65536,r[4]=ao/256,r[5]=ao;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+yt(new Uint8Array(n.buffer))+(t||"")}function ho(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const s=n.table(r);return Object.assign(Object.assign({},s),{mutate:n=>{var i,o;const l=n.trans;if("versionchange"===l.mode&&(l.disableChangeTracking=!0,l.disableAccessControl=!0),l.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const l=null===(i=t.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!t.initiallySynced){const e=io(s.schema.primaryKey,n);return s.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 s.mutate(n)})}return function(n,i){let o=null;const l=io(s.schema.primaryKey,n);return l.forEach((c,a)=>{if(void 0===c){const r=n.values[a].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);l[a]=uo(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=e.deepClone(o[a]),e.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)}),s.mutate(Object.assign(Object.assign({},n),{keys:l,values:o||n.values}))}(n,l.idPrefix)}if(null==l?void 0:l.markedForSync){io(s.schema.primaryKey,n).forEach((t,n)=>{if(!j(t)){const n=Array.isArray(t)?t.map(so).join(","):so(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 s.mutate(n)}})}})}}let fo=0;function po(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=s.length,o=(i>0?s[i-1].then(()=>e(n),()=>e(n)):e(n)).finally(()=>{r.splice(r.indexOf(o))});return r.push(o),o}}function go(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(s.length>0?s[s.length-1].then(()=>e(n),()=>e(n)):r.length>0?(o=r,new Promise(e=>{0===o.length&&e([]);let t=o.length;const n=new Array(t);o.forEach((r,s)=>Promise.resolve(r).then(e=>n[s]={status:"fulfilled",value:e},e=>n[s]={status:"rejected",reason:e}).then(()=>--t||e(n)))})).then(()=>e(n)):e(n)).finally(()=>{s.shift()});var o;return s.push(i),i}}const yo=new t.BehaviorSubject(new Set);function mo(e){var t,n,r,s;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)}function vo({currentUserObservable:t,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const s=new Set(r.schema.tables.map(e=>e.name)),i=r.schema.tables.filter(e=>!/^\$/.test(e.name)),o=new Map;for(const e of i){const t=`$${e.name}_mutations`;s.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(e,s)=>{let i;if("readwrite"===s){const t=e.filter(e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync}).map(e=>S(e));i=r.transaction([...e,...t],s)}else i=r.transaction(e,s);if("readwrite"===s){i.txid=O(16),i.opCount=0,i.currentUser=t.value,yo.value.add(i),yo.next(yo.value);const e=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",e),i.removeEventListener("abort",e),yo.value.delete(i),yo.next(yo.value)},r=()=>{i.mutationsAdded&&!mo(n)&&y(n,"push"),e()};i.addEventListener("complete",r),i.addEventListener("error",e),i.addEventListener("abort",e)}return i},table:t=>{const s=r.table(t);if(/^\$/.test(t))return t.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===t?Object.assign(Object.assign({},s),{mutate:e=>s.mutate(e).then(t=>(e.trans.mutationsAdded=!0,t)).catch(e=>Promise.reject(e))}):s;const{schema:i}=s,l=o.get(t);return l?function(e){const t="$lock"+ ++fo;return Object.assign(Object.assign({},e),{count:po(e.count,t),get:po(e.get,t),getMany:po(e.getMany,t),openCursor:po(e.openCursor,t),query:po(e.query,t),mutate:go(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:e=>{var r,o,l;const a=e.trans;return a.txid?a.disableChangeTracking?s.mutate(e):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===e.type?s.query({query:{range:e.range,index:i.primaryKey},trans:e.trans,values:!1}).then(t=>c({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}})):c(e):s.mutate(e):s.mutate(e)}})):s;function c(r){var o,c;const a=r.trans,d=null===(c=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===c?void 0:c[t],{txid:u,currentUser:{userId:h}}=a,{type:f}=r,p=++a.opCount;function g(e){if(!d)return e;let t=e;for(const n of Object.keys(e))d.some(e=>n===e||n.startsWith(e+"."))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return s.mutate(r).then(t=>{var n;const{numFailures:s,failures:o}=t;let c="delete"===f?r.keys:t.results,y="values"in r?r.values:[],m="changeSpec"in r?r.changeSpec:void 0,v="updates"in r?r.updates:void 0,b=!(!v||!("upsert"in r))&&r.upsert;if(s&&(c=c.filter((e,t)=>!o[t]),y=y.filter((e,t)=>!o[t])),d){if(y=y.map(e=>{const t=Object.assign({},e);for(const e of d)delete t[e];return t}),m&&(m=g(m),0===Object.keys(m).length))return t;if(v){let t=v.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new e.RangeSet;let s=!1;if(!b){for(let e=0,i=t.length;e<i;++e)Object.keys(t[e]).length>0?(n.keys.push(v.keys[e]),n.changeSpecs.push(t[e]),r.addKey(v.keys[e])):s=!0;if(v=n,s){let e=[],t=[];for(let n=0,s=c.length;n<s;++n)r.hasKey(c[n])&&(e.push(c[n]),t.push(y[n]));c=e,y=t}}}}const w=Date.now();let _="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===i.primaryKey.keyPath?null:r.criteria.index}):void 0;if(d&&(null==_?void 0:_.index)){const e=null===(n=i.indexes.find(e=>e.name===_.index))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some(e=>null==d?void 0:d.includes(e))&&(_=void 0)}const k="delete"===r.type?{type:"delete",ts:w,opNo:p,keys:c,criteria:_,txid:u,userId:h}:"add"===r.type?{type:"insert",ts:w,opNo:p,keys:c,txid:u,userId:h,values:y}:b&&v?{type:"upsert",ts:w,opNo:p,keys:c,values:y,changeSpecs:v.changeSpecs.filter((e,t)=>!o[t]),txid:u,userId:h}:_&&m?{type:"modify",ts:w,opNo:p,keys:c,criteria:_,changeSpec:m,txid:u,userId:h}:m?{type:"update",ts:w,opNo:p,keys:c,changeSpecs:c.map(()=>m),txid:u,userId:h}:v?{type:"update",ts:w,opNo:p,keys:v.keys,changeSpecs:v.changeSpecs,txid:u,userId:h}:{type:"upsert",ts:w,opNo:p,keys:c,values:y,txid:u,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(k.isAdditionalChunk=!0),c.length>0||_?l.mutate({type:"add",trans:a,values:[k]}).then(()=>(a.mutationsAdded=!0,t)):t})}}})}}}function bo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},Pi),n);Object.keys(Pi).forEach(e=>{const t=i[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map(e=>e.trim()),s=Pi[e].split(",").map(e=>e.trim()),o=new Set(r.map(e=>e.replace(/([&*]|\+\+)/g,"")));if(r[0]!==s[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(Pi[e])}`);for(let t=1;t<s.length;++t){const n=s[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(i[e]+=`,${n}`)}});const o=t.cloud.schema||(t.cloud.schema={}),l=new Set;Object.keys(i).forEach(e=>{var t;const n=null===(t=i[e])||void 0===t?void 0:t.trim(),r=o[e]||(o[e]={});null!=n?(/^\@/.test(n)&&(i[e]=i[e].substr(1),r.generatedGlobalId=!0,r.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,r=e.length;t<r&&n.length<3;++t)(lo.test(e[t])||co(e[t]))&&(n+=e[t].toLowerCase());for(;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;)r=oo(n,e),++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,l),l.add(r.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",r.markedForSync=!0),r.deleted&&(r.deleted=!1)):(r.deleted=!0,r.markedForSync=!1,i[`$${e}_mutations`]=null)});const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(s=t.yProps)||void 0===s?void 0:s.length){const n=o[e];n&&(n.yProps=t.yProps.map(e=>e.prop))}return c}}function wo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,n):n()}const _o=new t.BehaviorSubject(!0),ko=new t.BehaviorSubject(!0);_o.pipe(n.switchMap(e=>e?t.of(!0):t.of(!1).pipe(n.delay(2e4))),n.distinctUntilChanged()).subscribe(ko);const So="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),xo=So.pipe(n.filter(()=>"hidden"===document.visibilityState)),Eo=So.pipe(n.filter(()=>"visible"===document.visibilityState)),Co="undefined"!=typeof window?t.merge(Eo,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),xo,Co).pipe(n.map(()=>"visible"===document.visibilityState),n.tap(e=>{_o.value!==e&&_o.next(e)}),n.switchMap(e=>e?t.of(0).pipe(n.delay(16e4),n.tap(()=>_o.next(!1))):t.of(0))).subscribe(()=>{});class Io extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const Oo=new WeakMap,Do=3e4;class Ao extends Zt{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=sn();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&Do<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&To(this,t,"timeout")},$(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,s=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:sn()});const i=[],o=[],l=[],c=[];null===e?c.push(t):null==s?null!=e&&i.push(t):(o.push(t),wn(s,e)||l.push(t)),(i.length>0||l.length>0||c.length>0)&&this.emit("change",[{added:i,updated:l,removed:c},"local"]),this.emit("update",[{added:i,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const To=(e,t,n)=>{const r=[];for(let n=0;n<t.length;n++){const s=t[n];if(e.states.has(s)){if(e.states.delete(s),s===e.clientID){const t=e.meta.get(s);e.meta.set(s,{clock:t.clock+1,lastUpdated:sn()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},Uo=new WeakMap;function jo(e){let n=Uo.get(e);return n||(n=new t.Subject,Uo.set(e,n)),n}class Lo extends t.Observable{constructor(e,t,n,r,s,i,o,l){super(c=>new Mo(e,t,n,r,s,l,c,i,o))}}let Po=0;class Mo extends t.Subscription{constructor(e,t,n,r,s,i,o,l,c){super(()=>this.teardown()),this.id=++Po,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=s,this.user=i,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=l,this.webSocketStatus=c,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch(()=>{}).then(()=>this.reconnecting=!1)}}connect(){return r(this,void 0,void 0,function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const n=this.user.accessTokenExpiration;if(n&&n<new Date)return void this.subscriber.error(new Io);this.webSocketStatus.next("connecting"),this.pinger=setInterval(()=>r(this,void 0,void 0,function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout(()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())},2e4)}catch(e){this.reconnect()}else this.reconnect()}),3e4);const s=new URL(this.databaseUrl);s.protocol="http:"===s.protocol?"ws":"wss";const i=new URLSearchParams;if(this.subscriber.closed)return;i.set("v","2"),this.rev&&i.set("rev",this.rev),this.yrev&&i.set("yrev",this.yrev),i.set("realmsHash",this.realmSetHash),i.set("clientId",this.clientIdentity),i.set("dxcv",this.db.cloud.version),this.user.accessToken&&i.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${s}/changes?${i}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?jt.parse(e.data):function(e){const t=new Te(e),n=Re(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:Re(t)};const r=Re(t),s=Re(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(Be(t))};default:{const e=We(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:s,k:e};case"aware":return{type:n,table:r,prop:s,k:e,u:Le(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:We(t),sv:We(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:Le(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:Le(t),i:Number(Be(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:Le(t),r:t.pos<t.arr.length&&Re(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=Ci.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Oo.get(e))(e);n&&((e,t,n)=>{const r=Ue(t),s=sn(),i=[],o=[],l=[],c=[],a=Me(r);for(let t=0;t<a;t++){const t=Me(r);let n=Me(r);const a=JSON.parse(Re(r)),d=e.meta.get(t),u=e.states.get(t),h=void 0===d?0:d.clock;(h<n||h===n&&null===a&&e.states.has(t))&&(null===a?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,a),e.meta.set(t,{clock:n,lastUpdated:s}),void 0===d&&null!==a?i.push(t):void 0!==d&&null===a?c.push(t):null!==a&&(wn(a,u)||l.push(t),o.push(t)))}(i.length>0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])})(n,t.u,"server")}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Ci.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&jo(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?Ii([t],this.db).then(e=>r(this,[e],void 0,function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=pi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(Jt,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let n=!1;yield new Promise((e,t)=>{o.onopen=t=>{n=!0,e(null)},o.onerror=e=>{if(n)this.reconnect();else{const n=e.error||new Error("WebSocket Error");this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}}}),this.subscriptions.add(this.messageProducer.subscribe(e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(jt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new se;switch(fe(t,e.type),"table"in e&&fe(t,e.table),"prop"in e&&fe(t,e.prop),e.type){case"u-ack":case"u-reject":me(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":fe(t,e.yServerRev);break;default:switch(be(t,e.k),e.type){case"aware":ge(t,e.u);break;case"doc-open":be(t,e.serverRev),be(t,e.sv);break;case"doc-close":break;case"sv":ge(t,e.sv);break;case"u-c":ge(t,e.u),me(t,BigInt(e.i));break;case"u-s":ge(t,e.u),fe(t,e.r||"")}}return oe(t)}(e)))})),this.user.isLoggedIn&&!mo(this.db)&&this.subscriptions.add(function(n){const s=C(n.tables.filter(e=>{var t,r;return(null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e.name])||void 0===r?void 0:r.markedForSync)&&e.schema.yProps}).map(e=>e.schema.yProps.map(t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))));return t.merge(...s.map(({table:s,ydocProp:i,updatesTable:o})=>{const l=n.table(o);return t.from(l.get(Jt)).pipe(t.switchMap(n=>{let o=(null==n?void 0:n.unsentFrom)||1;return t.from(e.liveQuery(()=>r(this,void 0,void 0,function*(){return(yield qt(l,o)).filter(e=>e.f&&1&e.f).map(e=>({type:"u-c",table:s,prop:i,k:e.k,u:e.u,i:e.i}))}))).pipe(t.tap(e=>{e.length>0&&(o=e.at(-1).i+1)}))}))})).pipe(t.mergeMap(e=>e))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}})}}class $o extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function Ro(e){return r(this,void 0,void 0,function*(){var e;yield(e=3e3,new Promise(t=>setTimeout(t,e))),yield t.firstValueFrom(Co)})}function No(e){return r(this,void 0,void 0,function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Ai(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))})}const Bo=new WeakMap;function Fo(e,t,n,s){const i=Bo.get(e);if(i){if(i.pull||"push"===(null==s?void 0:s.purpose))return i.promise;{let r=!1;const o=e.cloud.syncState.subscribe(e=>{"pulling"===e.phase&&(r=!0)});return i.promise.then(()=>{o.unsubscribe()}).catch(e=>(o.unsubscribe(),Promise.reject(e))).then(()=>{if(!r)return Fo(e,t,n,s)})}}const o=function(){return r(this,void 0,void 0,function*(){try{yield Nt(e),yield wo(e,Di,()=>Ai(e,t,n,s)),Bo.delete(e)}catch(t){throw Bo.delete(e),t}})}();return Bo.set(e,{promise:o,pull:"push"!==(null==s?void 0:s.purpose)}),o}function Wo(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout(()=>{const u=c?"pull":"push";o=Date.now(),Fo(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:u}).then(()=>{if(s.cancelled)h();else if(c||a)return c=!1,a=!1,l();d=!1,i=0,o=0}).catch(e=>{if(s.cancelled)h(),d=!1,i=0,o=0;else if(r<5){const e=1e3*[0,20,40,300,900][r];i=Date.now()+e,o=0,setTimeout(()=>l(r+1),e)}else d=!1,i=0,o=0})},0)}let c=!1,a=!1,d=!1;const u=e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),d?i||o>0&&Date.now():(d=!0,l()))},h=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe(({purpose:e})=>{u(e||"pull")})},stop:h}}function Ho(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Vo,zo,Ko,Jo,qo,Go,Yo,Qo,Xo,Zo,el,tl={},nl=[],rl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,sl=Array.isArray;function il(e,t){for(var n in t)e[n]=t[n];return e}function ol(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function ll(e,t,n){var r,s,i,o={};for(i in t)"key"==i?r=t[i]:"ref"==i?s=t[i]:o[i]=t[i];if(arguments.length>2&&(o.children=arguments.length>3?Vo.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===o[i]&&(o[i]=e.defaultProps[i]);return cl(e,o,r,s,null)}function cl(e,t,n,r,s){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==s?++Ko:s,__i:-1,__u:0};return null==s&&null!=zo.vnode&&zo.vnode(i),i}function al(e){return e.children}function dl(e,t){this.props=e,this.context=t}function ul(e,t){if(null==t)return e.__?ul(e.__,e.__i+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?ul(e):null}function hl(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 hl(e)}}function fl(e){(!e.__d&&(e.__d=!0)&&Jo.push(e)&&!pl.__r++||qo!=zo.debounceRendering)&&((qo=zo.debounceRendering)||Go)(pl)}function pl(){for(var e,t,n,r,s,i,o,l=1;Jo.length;)Jo.length>l&&Jo.sort(Yo),e=Jo.shift(),l=Jo.length,e.__d&&(n=void 0,r=void 0,s=(r=(t=e).__v).__e,i=[],o=[],t.__P&&((n=il({},r)).__v=r.__v+1,zo.vnode&&zo.vnode(n),_l(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[s]:null,i,null==s?ul(r):s,!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,Sl(i,n,o),r.__e=r.__=null,n.__e!=s&&hl(n)));pl.__r=0}function gl(e,t,n,r,s,i,o,l,c,a,d){var u,h,f,p,g,y,m,v=r&&r.__k||nl,b=t.length;for(c=function(e,t,n,r,s){var i,o,l,c,a,d=n.length,u=d,h=0;for(e.__k=new Array(s),i=0;i<s;i++)null!=(o=t[i])&&"boolean"!=typeof o&&"function"!=typeof o?("string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?o=e.__k[i]=cl(null,o,null,null,null):sl(o)?o=e.__k[i]=cl(al,{children:o},null,null,null):null==o.constructor&&o.__b>0?o=e.__k[i]=cl(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[i]=o,c=i+h,o.__=e,o.__b=e.__b+1,-1!=(a=o.__i=ml(o,n,c,u))&&(u--,(l=n[a])&&(l.__u|=2)),null==l||null==l.__v?(-1==a&&(s>d?h--:s<d&&h++),"function"!=typeof o.type&&(o.__u|=4)):a!=c&&(a==c-1?h--:a==c+1?h++:(a>c?h--:h++,o.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<d;i++)null!=(l=n[i])&&!(2&l.__u)&&(l.__e==r&&(r=ul(l)),Il(l,l));return r}(n,t,v,c,b),u=0;u<b;u++)null!=(f=n.__k[u])&&(h=-1==f.__i?tl:v[f.__i]||tl,f.__i=u,y=_l(e,f,h,s,i,o,l,c,a,d),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Cl(h.ref,null,f),d.push(f.ref,f.__c||p,f)),null==g&&null!=p&&(g=p),(m=!!(4&f.__u))||h.__k===f.__k?c=yl(f,c,e,m):"function"==typeof f.type&&void 0!==y?c=y:p&&(c=p.nextSibling),f.__u&=-7);return n.__e=g,c}function yl(e,t,n,r){var s,i;if("function"==typeof e.type){for(s=e.__k,i=0;s&&i<s.length;i++)s[i]&&(s[i].__=e,t=yl(s[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=ul(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function ml(e,t,n,r){var s,i,o,l=e.key,c=e.type,a=t[n],d=null!=a&&!(2&a.__u);if(null===a&&null==l||d&&l==a.key&&c==a.type)return n;if(r>(d?1:0))for(s=n-1,i=n+1;s>=0||i<t.length;)if(null!=(a=t[o=s>=0?s--:i++])&&!(2&a.__u)&&l==a.key&&c==a.type)return o;return-1}function vl(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||rl.test(t)?n:n+"px"}function bl(e,t,n,r,s){var i,o;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||vl(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||vl(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])i=t!=(t=t.replace(Qo,"$1")),o=t.toLowerCase(),t=o in e||"onFocusOut"==t||"onFocusIn"==t?o.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n.u=r.u:(n.u=Xo,e.addEventListener(t,i?el:Zo,i)):e.removeEventListener(t,i?el:Zo,i);else{if("http://www.w3.org/2000/svg"==s)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function wl(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=Xo++;else if(t.t<n.u)return;return n(zo.event?zo.event(t):t)}}}function _l(e,t,n,r,s,i,o,l,c,a){var d,u,h,f,p,g,y,m,v,b,w,_,k,S,x,E,C,I=t.type;if(null!=t.constructor)return null;128&n.__u&&(c=!!(32&n.__u),i=[l=t.__e=n.__e]),(d=zo.__b)&&d(t);e:if("function"==typeof I)try{if(m=t.props,v="prototype"in I&&I.prototype.render,b=(d=I.contextType)&&r[d.__c],w=d?b?b.props.value:d.__:r,n.__c?y=(u=t.__c=n.__c).__=u.__E:(v?t.__c=u=new I(m,w):(t.__c=u=new dl(m,w),u.constructor=I,u.render=Ol),b&&b.sub(u),u.state||(u.state={}),u.__n=r,h=u.__d=!0,u.__h=[],u._sb=[]),v&&null==u.__s&&(u.__s=u.state),v&&null!=I.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=il({},u.__s)),il(u.__s,I.getDerivedStateFromProps(m,u.__s))),f=u.props,p=u.state,u.__v=t,h)v&&null==I.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),v&&null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(v&&null==I.getDerivedStateFromProps&&m!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(m,w),t.__v==n.__v||!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(m,u.__s,w)){for(t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),_=0;_<u._sb.length;_++)u.__h.push(u._sb[_]);u._sb=[],u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(m,u.__s,w),v&&null!=u.componentDidUpdate&&u.__h.push(function(){u.componentDidUpdate(f,p,g)})}if(u.context=w,u.props=m,u.__P=e,u.__e=!1,k=zo.__r,S=0,v){for(u.state=u.__s,u.__d=!1,k&&k(t),d=u.render(u.props,u.state,u.context),x=0;x<u._sb.length;x++)u.__h.push(u._sb[x]);u._sb=[]}else do{u.__d=!1,k&&k(t),d=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++S<25);u.state=u.__s,null!=u.getChildContext&&(r=il(il({},r),u.getChildContext())),v&&!h&&null!=u.getSnapshotBeforeUpdate&&(g=u.getSnapshotBeforeUpdate(f,p)),E=d,null!=d&&d.type===al&&null==d.key&&(E=xl(d.props.children)),l=gl(e,sl(E)?E:[E],t,n,r,s,i,o,l,c,a),u.base=t.__e,t.__u&=-161,u.__h.length&&o.push(u),y&&(u.__E=u.__=null)}catch(e){if(t.__v=null,c||null!=i)if(e.then){for(t.__u|=c?160:128;l&&8==l.nodeType&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,t.__e=l}else{for(C=i.length;C--;)ol(i[C]);kl(t)}else t.__e=n.__e,t.__k=n.__k,e.then||kl(t);zo.__e(e,t,n)}else null==i&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=El(n.__e,t,n,r,s,i,o,c,a);return(d=zo.diffed)&&d(t),128&t.__u?void 0:l}function kl(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(kl)}function Sl(e,t,n){for(var r=0;r<n.length;r++)Cl(n[r],n[++r],n[++r]);zo.__c&&zo.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){zo.__e(e,t.__v)}})}function xl(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:sl(e)?e.map(xl):il({},e)}function El(e,t,n,r,s,i,o,l,c){var a,d,u,h,f,p,g,y=n.props||tl,m=t.props,v=t.type;if("svg"==v?s="http://www.w3.org/2000/svg":"math"==v?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),null!=i)for(a=0;a<i.length;a++)if((f=i[a])&&"setAttribute"in f==!!v&&(v?f.localName==v:3==f.nodeType)){e=f,i[a]=null;break}if(null==e){if(null==v)return document.createTextNode(m);e=document.createElementNS(s,v,m.is&&m),l&&(zo.__m&&zo.__m(t,i),l=!1),i=null}if(null==v)y===m||l&&e.data==m||(e.data=m);else{if(i=i&&Vo.call(e.childNodes),!l&&null!=i)for(y={},a=0;a<e.attributes.length;a++)y[(f=e.attributes[a]).name]=f.value;for(a in y)if(f=y[a],"children"==a);else if("dangerouslySetInnerHTML"==a)u=f;else if(!(a in m)){if("value"==a&&"defaultValue"in m||"checked"==a&&"defaultChecked"in m)continue;bl(e,a,null,f,s)}for(a in m)f=m[a],"children"==a?h=f:"dangerouslySetInnerHTML"==a?d=f:"value"==a?p=f:"checked"==a?g=f:l&&"function"!=typeof f||y[a]===f||bl(e,a,f,y[a],s);if(d)l||u&&(d.__html==u.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(u&&(e.innerHTML=""),gl("template"==t.type?e.content:e,sl(h)?h:[h],t,n,r,"foreignObject"==v?"http://www.w3.org/1999/xhtml":s,i,o,i?i[0]:n.__k&&ul(n,0),l,c),null!=i)for(a=i.length;a--;)ol(i[a]);l||(a="value","progress"==v&&null==p?e.removeAttribute("value"):null!=p&&(p!==e[a]||"progress"==v&&!p||"option"==v&&p!=y[a])&&bl(e,a,p,y[a],s),a="checked",null!=g&&g!=e[a]&&bl(e,a,g,y[a],s))}return e}function Cl(e,t,n){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==t||(e.__u=e(t))}else e.current=t}catch(e){zo.__e(e,n)}}function Il(e,t,n){var r,s;if(zo.unmount&&zo.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Cl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){zo.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Il(r[s],t,n||"function"!=typeof e.type);n||ol(e.__e),e.__c=e.__=e.__e=void 0}function Ol(e,t,n){return this.constructor(e,n)}function Dl(e,t,n){var r,s,i;t==document&&(t=document.documentElement),zo.__&&zo.__(e,t),r=!1?null:t.__k,s=[],i=[],_l(t,e=t.__k=ll(al,null,[e]),r||tl,tl,t.namespaceURI,r?null:t.firstChild?Vo.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,i),Sl(s,e,i)}Vo=nl.slice,zo={__e:function(e,t,n,r){for(var s,i,o;t=t.__;)if((s=t.__c)&&!s.__)try{if((i=s.constructor)&&null!=i.getDerivedStateFromError&&(s.setState(i.getDerivedStateFromError(e)),o=s.__d),null!=s.componentDidCatch&&(s.componentDidCatch(e,r||{}),o=s.__d),o)return s.__E=s}catch(t){e=t}throw e}},Ko=0,dl.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=il({},this.state),"function"==typeof e&&(e=e(il({},n),this.props)),e&&il(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),fl(this))},dl.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),fl(this))},dl.prototype.render=al,Jo=[],Go="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Yo=function(e,t){return e.__v.__b-t.__v.__b},pl.__r=0,Qo=/(PointerCapture)$|Capture$/i,Xo=0,Zo=wl(!1),el=wl(!0);const Al={Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center",padding:"16px",boxSizing:"border-box"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"24px",marginBottom:"2em",maxWidth:"400px",width:"100%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",fontFamily:"sans-serif",boxSizing:"border-box"},Input:{height:"35px",width:"100%",maxWidth:"100%",borderColor:"#ccf4",outline:"none",fontSize:"16px",padding:"8px",boxSizing:"border-box",backgroundColor:"#f9f9f9",borderRadius:"4px",border:"1px solid #ccc",marginTop:"6px",fontFamily:"inherit"},Button:{padding:"10px 20px",margin:"0 4px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease"},PrimaryButton:{padding:"10px 20px",margin:"0 4px",border:"1px solid #3b82f6",borderRadius:"6px",backgroundColor:"#3b82f6",color:"white",cursor:"pointer",fontSize:"14px",fontWeight:"500",transition:"all 0.2s ease"},ButtonsDiv:{display:"flex",justifyContent:"flex-end",gap:"12px",marginTop:"24px",paddingTop:"20px"},Label:{display:"block",marginBottom:"12px",fontSize:"14px",fontWeight:"500",color:"#333"},WindowHeader:{margin:"0 0 20px 0",fontSize:"18px",fontWeight:"600",color:"#333",borderBottom:"1px solid #eee",paddingBottom:"10px"},ProviderButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",marginBottom:"10px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"},ProviderButtonIcon:{width:"20px",height:"20px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},ProviderButtonText:{flex:1,textAlign:"left"},ProviderGoogle:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#3c4043"},ProviderGitHub:{backgroundColor:"#24292e",border:"1px solid #24292e",color:"#ffffff"},ProviderMicrosoft:{backgroundColor:"#ffffff",border:"1px solid #8c8c8c",color:"#5e5e5e"},ProviderApple:{backgroundColor:"#000000",border:"1px solid #000000",color:"#ffffff"},ProviderCustom:{backgroundColor:"#4f46e5",border:"1px solid #4f46e5",color:"#ffffff"},Divider:{display:"flex",alignItems:"center",margin:"20px 0",color:"#6b7280",fontSize:"13px"},DividerLine:{flex:1,height:"1px",backgroundColor:"#e5e7eb"},DividerText:{padding:"0 12px",color:"#9ca3af"},OtpButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#f9fafb",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"}};function Tl({children:e,className:t}){return ll("div",{className:`dexie-dialog ${t||""}`},ll("div",{style:Al.Darken}),ll("div",{style:Al.DialogOuter},ll("div",{style:Al.DialogInner},e)))}var Ul,jl,Ll,Pl,Ml=0,$l=[],Rl=zo,Nl=Rl.__b,Bl=Rl.__r,Fl=Rl.diffed,Wl=Rl.__c,Hl=Rl.unmount,Vl=Rl.__;function zl(e,t){Rl.__h&&Rl.__h(jl,e,Ml||t),Ml=0;var n=jl.__H||(jl.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Kl(e){return Ml=1,function(e,t){var n=zl(Ul++,2);if(n.t=e,!n.__c&&(n.__=[ec(void 0,t),function(e){var t=n.__N?n.__N[0]:n.__[0],r=n.t(t,e);t!==r&&(n.__N=[r,n.__[1]],n.__c.setState({}))}],n.__c=jl,!jl.__f)){var r=function(e,t,r){if(!n.__c.__H)return!0;var i=n.__c.__H.__.filter(function(e){return!!e.__c});if(i.every(function(e){return!e.__N}))return!s||s.call(this,e,t,r);var o=n.__c.props!==e;return i.forEach(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),s&&s.call(this,e,t,r)||o};jl.__f=!0;var s=jl.shouldComponentUpdate,i=jl.componentWillUpdate;jl.componentWillUpdate=function(e,t,n){if(this.__e){var o=s;s=void 0,r(e,t,n),s=o}i&&i.call(this,e,t,n)},jl.shouldComponentUpdate=r}return n.__N||n.__}(ec,e)}function Jl(e){return Ml=5,function(e,t){var n=zl(Ul++,7);return Zl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}(function(){return{current:e}},[])}function ql(){for(var e;e=$l.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Ql),e.__H.__h.forEach(Xl),e.__H.__h=[]}catch(t){e.__H.__h=[],Rl.__e(t,e.__v)}}Rl.__b=function(e){jl=null,Nl&&Nl(e)},Rl.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Vl&&Vl(e,t)},Rl.__r=function(e){Bl&&Bl(e),Ul=0;var t=(jl=e.__c).__H;t&&(Ll===jl?(t.__h=[],jl.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Ql),t.__h.forEach(Xl),t.__h=[],Ul=0)),Ll=jl},Rl.diffed=function(e){Fl&&Fl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==$l.push(t)&&Pl===Rl.requestAnimationFrame||((Pl=Rl.requestAnimationFrame)||Yl)(ql)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),Ll=jl=null},Rl.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Ql),e.__h=e.__h.filter(function(e){return!e.__||Xl(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],Rl.__e(n,e.__v)}}),Wl&&Wl(e,t)},Rl.unmount=function(e){Hl&&Hl(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Ql(e)}catch(e){t=e}}),n.__H=void 0,t&&Rl.__e(t,n.__v))};var Gl="function"==typeof requestAnimationFrame;function Yl(e){var t,n=function(){clearTimeout(r),Gl&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Gl&&(t=requestAnimationFrame(n))}function Ql(e){var t=jl,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),jl=t}function Xl(e){var t=jl;e.__c=e.__(),jl=t}function Zl(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function ec(e,t){return"function"==typeof t?t(e):t}function tc({option:e,onClick:t}){const{displayName:n,iconUrl:r,iconSvg:s,styleHint:i,value:o}=e,l=function(e){const t=Object.assign({},Al.ProviderButton);if(!e)return t;switch(e){case"google":return Object.assign(Object.assign({},t),Al.ProviderGoogle);case"github":return Object.assign(Object.assign({},t),Al.ProviderGitHub);case"microsoft":return Object.assign(Object.assign({},t),Al.ProviderMicrosoft);case"apple":return Object.assign(Object.assign({},t),Al.ProviderApple);case"otp":return Object.assign({},Al.OtpButton);case"custom-oauth2":return Object.assign(Object.assign({},t),Al.ProviderCustom);default:return t}}(i),c=l.color||"#000000",a=s?s.replace(/fill="currentColor"/gi,`fill="${c}"`).replace(/fill='currentColor'/gi,`fill='${c}'`).replace(/stroke="currentColor"/gi,`stroke="${c}"`).replace(/stroke='currentColor'/gi,`stroke='${c}'`):null;return ll("button",{type:"button",style:l,onClick:t,class:"dxc-option-btn"+(i?` dxc-option-${i}`:""),"aria-label":n},a?ll("span",{style:Al.ProviderButtonIcon,"aria-hidden":"true",dangerouslySetInnerHTML:{__html:a}}):r?ll("img",{src:r,alt:"",style:Al.ProviderButtonIcon,"aria-hidden":"true"}):null,ll("span",{style:Al.ProviderButtonText},n))}function nc(){return ll("div",{style:Al.Divider},ll("div",{style:Al.DividerLine}),ll("span",{style:Al.DividerText},"or"),ll("div",{style:Al.DividerLine}))}function rc({title:e,alerts:t,fields:n,options:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=Kl({}),d=Jl(null);!function(e,t){var n=zl(Ul++,4);!Rl.__s&&Zl(n.__H,t)&&(n.__=e,n.u=t,jl.__h.push(n))}(()=>{var e;return null===(e=d.current)||void 0===e?void 0:e.focus()},[]);const u=Object.entries(n||{}),h=u.length>0,f=r&&r.length>0,p=new Map;if(r)for(const e of r){const t=p.get(e.name)||[];t.push(e),p.set(e.name,t)}const g=p.size>1,y=e=>{l({[e.name]:e.value})};return ll(Tl,{className:"dxc-login-dlg"},ll(al,null,ll("h3",{style:Al.WindowHeader},e),t.map((e,t)=>ll("p",{key:t,style:Al.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,e=>n[e.substring(1,e.length-1)])}(e))),f&&ll("div",{class:"dxc-options"},g?Array.from(p.entries()).map(([e,t],n)=>ll(al,{key:e},n>0&&ll(nc,null),t.map(e=>ll(tc,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)})))):r.map(e=>ll(tc,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)}))),f&&h&&ll(nc,null),h&&ll("form",{onSubmit:e=>{e.preventDefault(),l(c)}},u.map(([e,{type:t,label:n,placeholder:r}],s)=>ll("label",{style:Al.Label,key:s},n?`${n}: `:"",ll("input",{ref:0===s?d:void 0,type:t,name:e,autoComplete:"on",style:Al.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const s=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let i=Object.assign(Object.assign({},c),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&l(i)}}))))),ll("div",{style:Al.ButtonsDiv},ll(al,null,h&&s&&ll("button",{type:"submit",style:Al.PrimaryButton,onClick:()=>l(c)},s),i&&ll("button",{style:Al.Button,onClick:o},i))))}class sc extends dl{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?ll(rc,Object.assign({},t)):null}}function ic(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const oc=ic(e=>new t.BehaviorSubject(c));function lc(e,n){let r=n,s=t.from(e).pipe(t.map(e=>r=e),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const i=new t.Observable(e=>{let t=!1;const n=s.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n});return i.getValue=()=>r,i}const cc=ic(t=>lc(e.liveQuery(()=>t.roles.where({realmId:"rlm-public"}).toArray().then(e=>{const t={};for(const n of e.slice().sort((e,t)=>(e.sortOrder||0)-(t.sortOrder||0)))t[n.name]=n;return t})),{})),ac=ic(t=>lc(oc(t._novip).pipe(n.switchMap(n=>e.liveQuery(()=>t.transaction("r","realms","members",()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then(([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}}));function dc(...e){if(0===e.length)return{};const t=e.reduce((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,s=t[e];t[e]=[...new Set([...s,...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 uc=ic(e=>function(e,n){let r;const s=e.pipe(t.map(e=>r=n(e)));return s.getValue=()=>void 0!==r?r:r=n(e.getValue()),s}(lc(t.combineLatest([ac(e._novip),cc(e._novip)]).pipe(n.map(([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r}))),{selfMembers:[],realms:[],userId:c.userId,globalRoles:{}}),({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const s=t.map(t=>{const s=e.filter(e=>e.realmId===t.realmId),i=s.map(e=>e.permissions).filter(e=>e),o=C(s.map(e=>e.roles).filter(e=>e)).map(e=>r[e]).filter(e=>e).map(e=>e.permissions);return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:dc(...i,...o)})}).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t}),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return s}));class hc{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every(e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)})))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every(e=>"owner"!==e);const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every(e=>"owner"!==e):e.every(e=>null==r?void 0:r.some(t=>t===e||"*"===t&&"owner"!==e))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const fc=ic(s=>{const i=oc(s._novip).pipe(n.switchMap(t=>e.liveQuery(()=>s.members.where({email:t.email||""}).toArray()))),o=uc(s._novip),l=ac(s._novip);return lc(t.combineLatest([i,l,o]).pipe(n.map(([e,t,n])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:n[t.realmId]})}),o=e.reduce(i,{}),l=t.selfMembers.reduce(i,o);return Object.values(l).filter(e=>!e.accepted).map(e=>Object.assign(Object.assign({},e),{accept(){return r(this,void 0,void 0,function*(){yield s.members.update(e.id,{accepted:new Date})})},reject(){return r(this,void 0,void 0,function*(){yield s.members.update(e.id,{rejected:new Date})})}}))})),[])});function pc(n){return s=>{var i;const o=s.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:l}=o.meta||{};if(!(null===(i=n.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(s,"awareness",{get:()=>c||(c=function(n,s,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=s.meta,d=new Ao(s),u=jo(s);return d.on("update",({added:e,updated:t,removed:r},l)=>{const a=e.concat(t).concat(r),u=n.cloud.currentUser.value;if("server"!==l&&u.isLoggedIn&&!mo(n)){const e=((e,t,n=e.states)=>{const r=t.length,s=ie();ae(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,l=e.meta.get(r).clock;ae(s,r),ae(s,l),fe(s,JSON.stringify(o))}return oe(s)})(d,a);n.messageProducer.next({type:"aware",table:o,prop:c,k:s.meta.parentId,u:e}),i.destroyed&&n.messageProducer.next({type:"doc-close",table:o,prop:c,k:s.meta.parentId})}}),d.on("destroy",()=>{To(d,[s.clientID],"provider destroyed")}),(()=>{r(this,void 0,void 0,function*(){if(i.destroyed)return;let s=!1,d=1;const h=t.combineLatest([n.cloud.webSocketStatus,u.pipe(t.startWith(null))]).subscribe(([e])=>{if(i.destroyed)return;s="connected"===e;const t=n.cloud.currentUser.value;"connected"===e&&t.isLoggedIn&&!mo(n)&&(++d,f().catch(e=>{}))});function f(){return r(this,void 0,void 0,function*(){const t=d,u=n.table(a),h=n.$syncState,[f,p]=yield n.transaction("r",h,u,()=>r(this,void 0,void 0,function*(){const e=yield u.get(Jt),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}));if(i.destroyed||d!==t||!s)return;const g={type:"doc-open",table:o,prop:c,k:l,serverRev:p},y=yield u.where("i").between(f,1/0,!1).filter(t=>0===e.cmp(t.k,l)&&!(1&(t.f||0))).toArray();if(!i.destroyed&&d===t&&s){if(y.length>0){const e=$r(y.map(e=>e.u)),t=Pr(e);g.sv=t}n.messageProducer.next(g)}})}i.addCleanupHandler(h)})})(),d}(n,o,s),Oo.set(o,c),c)})}}function gc(e){const t="undefined"!=typeof window?window.location.href:"";if(!t)return null;const n=new URL(t).searchParams.get("dxc-auth");if(!n)return null;let r;try{const e=function(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return atob(t)}(n);r=JSON.parse(e)}catch(e){return null}const{code:s,provider:i,state:o,error:l}=r;if(l){if(l.toLowerCase().includes("access_denied")||l.toLowerCase().includes("access denied"))throw new zi("access_denied",i,l);if(l.toLowerCase().includes("email")&&l.toLowerCase().includes("verif"))throw new zi("email_not_verified",i,l);throw new zi("provider_error",i,l)}return s&&i&&o?{code:s,provider:i,state:o}:null}function yc(){var e;if("undefined"==typeof window||!(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const t=new URL(window.location.href);if(!t.searchParams.has("dxc-auth"))return;t.searchParams.delete("dxc-auth");const n=t.pathname+(t.searchParams.toString()?`?${t.searchParams.toString()}`:"")+t.hash;window.history.replaceState(null,"",n)}const mc={nameSuffix:!0};function vc(s){const i=s.name,o=oc(s),l=[];let a=!1,d=null,u=null;s.on("ready",s=>r(this,void 0,void 0,function*(){try{yield function(s){return r(this,void 0,void 0,function*(){var i,c,m,v,b,w,k;h=!1;const S=$i(s);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=S.cloud.options)||void 0===i?void 0:i.customLoginGui)||l.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Dl(ll(sc,{db:e.vip}),n)):addEventListener("DOMContentLoaded",()=>{t||(document.body.appendChild(n),Dl(ll(sc,{db:e.vip}),n))}),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(s))),S.cloud.isServiceWorkerDB||l.push(function(e){let r=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(n.switchMap(e=>{const s=r;r=e;const i=t.of(e);switch(e){case"disconnected":return _o.value?i.pipe(n.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(n.debounceTime(4e3));default:return i}}));return t.combineLatest([s,e.syncStateChangedEvent.pipe(n.startWith({phase:"initial"})),oc(e.dx._novip),ko]).pipe(n.map(([t,n,r,s])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:l,progress:c}=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"),s||(a="disconnected"),{phase:o,error:l,progress:c,status:Wt?a:"offline",license:"ok"}}))}(S).subscribe(s.cloud.syncState)),l.push(S.syncCompleteEvent.subscribe(p)),S.tables.every(e=>e.core)||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const x="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[E,C]=yield S.transaction("rw",S.$syncState,()=>r(this,void 0,void 0,function*(){var e,t;const{options:n,schema:r}=S.cloud,[s,i,o]=yield Promise.all([S.getOptions(),S.getSchema(),S.getPersistedSyncState()]);if(a){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield S.$syncState.put(e,"options")}}else S.cloud.options=s||null;if((null===(e=S.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&x.length>0&&!to?S.cloud.usingServiceWorker=!0:((null===(t=S.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&S.cloud.isServiceWorkerDB,S.cloud.usingServiceWorker=!1),Ho(r,S.cloud.options),Ho(i,S.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield S.$syncState.put(e,"schema"),Object.assign(r,e)}}else S.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}));if(E&&S.setInitiallySynced(!0),function(t){var n,r;for(const s of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new e.SchemaError(`Table ${s.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`);if(!s.schema.primKey.keyPath)throw new e.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(S),f(),!S.cloud.isServiceWorkerDB){l.push(e.liveQuery(()=>S.getCurrentUser()).subscribe(o)),l.push(e.liveQuery(()=>S.getPersistedSyncState()).subscribe(S.cloud.persistedSyncState)),yield t.firstValueFrom(t.combineLatest([o.pipe(n.skip(1),n.take(1)),S.cloud.persistedSyncState.pipe(n.skip(1),n.take(1))]));const r=pc(S);Ci.on.new.subscribe(r),S.dx.once("close",()=>{Ci.on.new.unsubscribe(r)})}let I=!1;const O=yield S.getCurrentUser();if(d&&!S.cloud.isServiceWorkerDB){const{code:e,provider:t}=d;d=null;try{I=yield Qi(S,{oauthCode:e,provider:t})}catch(e){}}const D=null===(c=S.cloud.options)||void 0===c?void 0:c.requireAuth;D&&(S.cloud.isServiceWorkerDB?yield t.firstValueFrom(o.pipe(n.filter(e=>!!e.isLoggedIn),n.take(1))):"object"==typeof D?(!O.isLoggedIn||D.userId&&O.userId!==D.userId||D.email&&O.email!==D.email)&&(I=yield Qi(S,D)):O.isLoggedIn||(I=yield Qi(S))),!O.isLoggedIn||C&&C.includes(O.userId)||(I=!0),u&&u.stop(),u=null,f();const A=(null===(m=S.cloud.options)||void 0===m?void 0:m.databaseUrl)&&(!E||I);A&&(yield function(e,t,n){return r(this,void 0,void 0,function*(){yield wo(e,Di,()=>Ai(e,t,n,{isInitialSync:!0}))})}(S,S.cloud.options,S.cloud.schema),S.setInitiallySynced(!0)),f(),S.cloud.usingServiceWorker&&(null===(v=S.cloud.options)||void 0===v?void 0:v.databaseUrl)?(A||g(S,"push").catch(()=>{}),function(e){return r(this,void 0,void 0,function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}})}(S).catch(()=>{})):(null===(b=S.cloud.options)||void 0===b?void 0:b.databaseUrl)&&S.cloud.schema&&!S.cloud.isServiceWorkerDB&&(u=Wo(S,S.cloud.options,S.cloud.schema),u.start(),A||y(S,"push")),f(),S.cloud.isServiceWorkerDB||l.push(t.fromEvent(self,"online").subscribe(()=>{S.syncStateChangedEvent.next({phase:"not-in-sync"}),mo(S)||y(S,"push")}),t.fromEvent(self,"offline").subscribe(()=>{S.syncStateChangedEvent.next({phase:"offline"})})),!(null===(w=S.cloud.options)||void 0===w?void 0:w.databaseUrl)||(null===(k=S.cloud.options)||void 0===k?void 0:k.disableWebSocket)||no||l.push(function(e){var s;if(!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(n.filter(e=>e),n.switchMap(()=>e.getPersistedSyncState()),n.filter(e=>e&&e.serverRevision),n.switchMap(e=>r(this,void 0,void 0,function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield _(e)}}))),o=t.merge(i,e.messageProducer);return function s(){return e.cloud.persistedSyncState.pipe(n.filter(e=>null==e?void 0:e.serverRevision),n.take(1),n.switchMap(t=>e.cloud.currentUser.pipe(n.map(e=>[e,t]))),n.switchMap(([e,t])=>ko.pipe(n.map(n=>[n?e:null,t]))),n.switchMap(([r,s])=>(null==r?void 0:r.isLoggedIn)&&!(null==s?void 0:s.realms.includes(r.userId))?e.cloud.persistedSyncState.pipe(n.filter(e=>(null==e?void 0:e.realms.includes(r.userId))||!1),n.take(1),n.map(e=>[r,e])):new t.BehaviorSubject([r,s])),n.switchMap(e=>r(this,[e],void 0,function*([e,t]){return[e,yield _(t)]})),n.distinctUntilChanged(([e,t],[n,r])=>e===n&&t===r),n.switchMap(([n,r])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?n?new Lo(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,r,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,n):t.from([]):s()}),n.catchError(i=>"TokenExpiredError"===(null==i?void 0:i.name)?t.of(!0).pipe(n.switchMap(()=>r(this,void 0,void 0,function*(){const t=yield e.getCurrentUser(),n=yield st(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})),n.switchMap(()=>s())):t.throwError(()=>i)),n.catchError(r=>(e.cloud.webSocketStatus.next("error"),r instanceof $o?t.throwError(()=>r):t.from(Ro()).pipe(n.switchMap(()=>s())))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(S))})}(s)}catch(e){}}),!0);let h=!1;function f(){if(h)throw new e.DatabaseClosedError}s.once("close",()=>{l.forEach(e=>e.unsubscribe()),l.splice(0,l.length),h=!0,u&&u.stop(),u=null,o.next(c)});const p=new t.Subject;var m;s.cloud={version:"4.3.2",options:Object.assign({},mc),schema:null,get currentUserId(){return o.value.userId||c.userId},currentUser:o,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:p},persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return r(this,void 0,void 0,function*(){const t=$i(s);yield t.cloud.sync(),yield Qi(t,e)})},invites:fc(s),roles:cc(s),configure(e){if(e=s.cloud.options=Object.assign(Object.assign({},s.cloud.options),e),a=!0,e.databaseUrl&&e.nameSuffix&&(s.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,$i(s).reconfigure()),Ho(s.cloud.schema,s.cloud.options),"undefined"!=typeof window&&window.location)try{const e=gc();e&&(yc(),d={code:e.code,provider:e.provider})}catch(e){yc()}},logout(){return r(this,arguments,void 0,function*({force:e}={}){e?yield Hi($i(s),{deleteUnsyncedData:!0}):yield Wi($i(s))})},sync(){return r(this,arguments,void 0,function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=$i(s);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield nt(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(y(c,o),i){const r=yield t.firstValueFrom(c.cloud.persistedSyncState.pipe(n.filter(t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))));if(null==r?void 0:r.error)throw new Error("Sync error: "+r.error)}}else if(yield No(c)){const s=c.cloud.persistedSyncState.value;y(c,o),i&&(yield t.firstValueFrom(t.from(e.liveQuery(()=>r(this,void 0,void 0,function*(){const e=yield No(c),t=yield c.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==s?void 0:s.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))).pipe(n.filter(e=>!e))))}})},permissions:(e,t)=>function(e,t,r){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!r){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");r=t.table()}const o=uc(e),l=t=>{const n=t[i||e.cloud.currentUserId];return n?new hc(n.permissions,r,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new hc({},r,!s||s===e.cloud.currentUserId)},c=o.pipe(n.map(l));return c.getValue=()=>l(o.getValue()),c}(s._novip,e,t)},s.Version.prototype._parseStoresSpec=e.override(s.Version.prototype._parseStoresSpec,e=>bo(e,s)),s.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return uo(s.cloud.schema[this.name].idPrefix||"",t)},s.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},s.use(vo({currentUserObservable:s.cloud.currentUser,db:$i(s)})),s.use((m=$i(s),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,s,i,o,l,a;const d=e.trans;if(d.disableChangeTracking)return n.mutate(e);const u=null!==(s=null===(r=d.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:c.userId;if((null===(o=null===(i=m.cloud.schema)||void 0===i?void 0:i[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(a=(l=n.schema.primaryKey).extractKey)||void 0===a?void 0:a.call(l,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,e.upsert||delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),s.use(ho($i(s)))}vc.version="4.3.2",e.Cloud=vc;const bc=new Map;function wc(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const _c=new Map;function kc(t,n){let s=_c.get(t+"/"+n);return s||(s=function t(n,s){return r(this,void 0,void 0,function*(){var r;let i=bc.get(n);if(!i){const r=new e(n,{addons:[vc]});if(i=$i(r),i.cloud.isServiceWorkerDB=!0,r.on("versionchange",o),yield i.dx.open(),bc.get(n))return i.close(),yield t(n,s);bc.set(n,i)}if((null===(r=i.cloud.options)||void 0===r?void 0:r.databaseUrl)&&i.cloud.schema)try{yield Fo(i,i.cloud.options,i.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:s})}catch(t){if(o(),t.name!==e.errnames.NoSuchDatabase)throw t}function o(){return i.dx.on.versionchange.unsubscribe(o),bc.get(i.name)===i&&bc.delete(i.name),i.dx.close(),!1}})}(t,n).then(()=>{_c.delete(t+"/"+n)}).catch(e=>(_c.delete(t+"/"+n),Promise.reject(e))),_c.set(t+"/"+n,s)),s}to||(self.addEventListener("sync",e=>{const t=wc(e.tag);t&&e.waitUntil(kc(t,"push"))}),self.addEventListener("periodicsync",e=>{const t=wc(e.tag);t&&e.waitUntil(kc(t,"pull"))}),self.addEventListener("message",e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(s=1)=>kc(t,e.data.purpose||"pull").catch(e=>r(void 0,void 0,void 0,function*(){if(3===s)throw e;var t;yield(t=6e4,new Promise(e=>setTimeout(e,t))),n(s+1)}));"waitUntil"in e?e.waitUntil(n().catch(e=>{})):n().catch(e=>{})}}))});
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).Dexie,e.rxjs,e.rxjs.operators)}(this,function(e,t,n){"use strict";function r(e,t,n,r){return new(n||(n=Promise))(function(s,i){function o(e){try{c(r.next(e))}catch(e){i(e)}}function l(e){try{c(r.throw(e))}catch(e){i(e)}}function c(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,l)}c((r=r.apply(e,t||[])).next())})}function s(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function i(e){return this instanceof i?(this.v=e,this):new i(e)}function o(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),o=[];return r=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),l("next"),l("throw"),l("return",function(e){return function(t){return Promise.resolve(t).then(e,d)}}),r[Symbol.asyncIterator]=function(){return this},r;function l(e,t){s[e]&&(r[e]=function(t){return new Promise(function(n,r){o.push([e,t,n,r])>1||c(e,t)})},t&&(r[e]=t(r[e])))}function c(e,t){try{!function(e){e.value instanceof i?Promise.resolve(e.value.v).then(a,d):u(o[0][2],e)}(s[e](t))}catch(e){u(o[0][3],e)}}function a(e){c("next",e)}function d(e){c("throw",e)}function u(e,t){e(t),o.shift(),o.length&&c(o[0][0],o[0][1])}}function l(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=s(e),t={},r("next"),r("throw"),r("return"),t[Symbol.asyncIterator]=function(){return this},t);function r(n){t[n]=e[n]&&function(t){return new Promise(function(r,s){(function(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)})(r,s,(t=e[n](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;const c={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(c),Object.freeze(c.claims)}catch(e){}const a={},d="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;d&&d.ready.then(e=>a.registration=e),"undefined"!=typeof self&&"clients"in self&&!self.document&&addEventListener("message",e=>{var t,n;(null===(n=null===(t=e.data)||void 0===t?void 0:t.type)||void 0===n?void 0:n.startsWith("sw-broadcast-"))&&[...self.clients.matchAll({includeUncontrolled:!0})].forEach(t=>{var n;return t.id!==(null===(n=e.source)||void 0===n?void 0:n.id)&&t.postMessage(e.data)})});class u{constructor(e){this.name=e}subscribe(e){if(!d)return()=>{};const t=t=>{var n;(null===(n=t.data)||void 0===n?void 0:n.type)===`sw-broadcast-${this.name}`&&e(t.data.message)};return d.addEventListener("message",t),()=>d.removeEventListener("message",t)}postMessage(e){var t;"object"==typeof self.clients?[...self.clients.matchAll({includeUncontrolled:!0})].forEach(t=>t.postMessage({type:`sw-broadcast-${this.name}`,message:e})):a.registration&&(null===(t=a.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const h=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class f extends t.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new u(e):new BroadcastChannel(e);super(n=>{function r(e){n.next(e.detail)}function s(e){n.next(e.data)}let i;!function(e,t){h.has(e)?h.get(e).push(t):h.set(e,[t])}(`lbc-${e}`,r);try{t instanceof u?i=t.subscribe(e=>n.next(e)):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=h.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof u?i():t.removeEventListener("message",s)}}),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=h.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){}})}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}let p=!1;function g(e,t){return r(this,void 0,void 0,function*(){try{const n=yield navigator.serviceWorker.ready;if("push"===t&&n.sync&&(yield n.sync.register(`dexie-cloud:${e.name}`)),!n.active)throw new Error("Failed to trigger sync - there's no active service worker");return void n.active.postMessage({type:"dexie-cloud-sync",dbName:e.name,purpose:t})}catch(e){p||(p=!0)}})}function y(e,t){e.cloud.usingServiceWorker?g(e,t):e.localSyncEvent.next({purpose:t})}const m="fromBase64"in Uint8Array,v="toBase64"in Uint8Array.prototype,b="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):m?e=>Uint8Array.fromBase64(e):e=>{const t=atob(e),n=t.length,r=new Uint8Array(n);for(var s=0;s<n;s++)r[s]=t.charCodeAt(s);return r},w="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):v?e=>(ArrayBuffer.isView(e)?e:new Uint8Array(e)).toBase64():e=>{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e),n=[];for(let e=0,r=t.length;e<r;e+=4096){const r=t.subarray(e,e+4096);n.push(String.fromCharCode.apply(null,r))}return btoa(n.join(""))};function _(e){return r(this,arguments,void 0,function*({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),s=yield crypto.subtle.digest("SHA-1",r);return w(s)})}function k(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 S(e){return`$${e}_mutations`}function x(e){var t;const n=null===(t=/^\$(.*)_mutations$/.exec(e))||void 0===t?void 0:t[1];if(!n)throw new Error(`Given mutationTable ${e} is not correct`);return n}const E=[].concat;function C(e){return E.apply([],e)}function I(e,t){return r(this,arguments,void 0,function*(e,t,{since:n={},limit:s=1/0}={}){const i=yield Promise.all(e.map(e=>r(this,void 0,void 0,function*(){const t=x(e.name),r=n[t];let i=r?e.where("rev").above(r):e;s<1/0&&(i=i.limit(s));let o=yield i.toArray();o=function(e){return e=e.map(e=>{if("modify"===e.type&&null===e.criteria.index){const t=Object.assign(Object.assign({},e),{criteria:void 0,changeSpec:void 0,type:"update",keys:e.keys,changeSpecs:[e.changeSpec]});return delete t.criteria,delete t.changeSpec,t}return e}),e}(o),o=function(e){const t=new Map;for(const n of e)if("update"===n.type){if(1!==n.keys.length||1!==n.changeSpecs.length)continue;const e=""+n.keys[0],r=n.changeSpecs[0];if(Object.values(r).some(e=>"object"==typeof e&&e&&"@@propmod"in e))continue;let s=t.get(e);s?s.push({txid:n.txid,updateSpec:r}):t.set(e,[{txid:n.txid,updateSpec:r}])}return e=e.filter(e=>{if("update"!==e.type)return!0;if(1!==e.keys.length||1!==e.changeSpecs.length)return!0;const n=e.changeSpecs[0];if(Object.values(n).some(e=>"object"==typeof e&&e&&"@@propmod"in e))return!0;const r=new Set(Object.keys(e.changeSpecs[0])),s=""+e.keys[0],i=t.get(s);if(!i)return!0;for(let t=i.length-1;t>=0;--t){const{txid:n,updateSpec:s}=i[t];if(n===e.txid)break;for(const e of Object.keys(s))r.delete(e)}return 0!==r.size}),e}(o);return o.map(e=>({table:t,mut:e}))}))),o=C(i).sort((e,t)=>e.mut.txid===t.mut.txid?e.mut.opNo-t.mut.opNo:e.mut.ts-t.mut.ts),l=[];let c=null,a=null;for(const{table:e,mut:t}of o)c&&c.table===e&&a===t.txid?c.muts.push(t):(c={table:e,muts:[t]},a=t.txid,l.push(c));return l})}function O(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const D={}.hasOwnProperty;function A(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,s=t.length;r<s;++r)A(e,t[r],n[r])}else{var i=t.indexOf(".");if(-1!==i){var o=t.substr(0,i),l=t.substr(i+1);if(""===l)void 0===n?Array.isArray(e)?isNaN(parseInt(o))||e.splice(parseInt(o),1):delete e[o]:e[o]=n;else{var c=e[o];c&&function(e,t){return D.call(e,t)}(e,o)||(c=e[o]={}),A(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const T="undefined"!=typeof self&&"undefined"!=typeof crypto?(e,t=crypto.getRandomValues.bind(crypto))=>{const n=new Uint8Array(e);return t(n),self.btoa(String.fromCharCode.apply(null,n))}:"undefined"!=typeof Buffer?(e,t=U)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function U(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function j(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some(e=>j(e))&&e.every(L))}function L(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(L)}function P(e,t,n){const r=e[t]||(e[t]={}),s=n.keys.map(e=>"string"==typeof e?e:JSON.stringify(e));switch(n.type){case"insert":case"upsert":s.forEach((e,t)=>{r[e]={type:"ups",val:n.values[t]}});break;case"update":case"modify":s.forEach((e,t)=>{const s="update"===n.type?n.changeSpecs[t]:n.changeSpec,i=r[e];if(i)switch(i.type){case"ups":for(const[e,t]of Object.entries(s))A(i.val,e,t);break;case"del":break;case"upd":Object.assign(i.mod,s)}else r[e]={type:"upd",mod:s}});break;case"delete":s.forEach(e=>{r[e]={type:"del"}})}return e}function R(e,t){for(const{table:n,muts:r}of t)for(const t of r)P(e,n,t)}const M=Math.floor,$=Math.abs,N=(e,t)=>e<t?e:t,B=(e,t)=>e>t?e:t,F=e=>0!==e?e<0:1/e<0,W=64,H=128,V=127,z=Number.MAX_SAFE_INTEGER,K=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&M(e)===e),J=()=>new Set,q=e=>e[e.length-1],G=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Y=Array.from,Q=Array.isArray,X=/^\s*/g,Z=/([A-Z])/g,ee=(e,t)=>(e=>e.replace(X,""))(e.replace(Z,e=>`${t}${(e=>e.toLowerCase())(e)}`)),te="undefined"!=typeof TextEncoder?new TextEncoder:null,ne=te?e=>te.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let re="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});re&&1===re.decode(new Uint8Array).length&&(re=null);class se{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const ie=()=>new se,oe=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},le=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},ce=le,ae=(e,t)=>{for(;t>V;)le(e,H|V&t),t=M(t/128);le(e,V&t)},de=(e,t)=>{const n=F(t);for(n&&(t=-t),le(e,(t>63?H:0)|(n?W:0)|63&t),t=M(t/64);t>0;)le(e,(t>V?H:0)|V&t),t=M(t/128)},ue=new Uint8Array(3e4),he=ue.length/3,fe=te&&te.encodeInto?(e,t)=>{if(t.length<he){const n=te.encodeInto(t,ue).written||0;ae(e,n);for(let t=0;t<n;t++)le(e,ue[t])}else ge(e,ne(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;ae(e,r);for(let t=0;t<r;t++)le(e,n.codePointAt(t))},pe=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=N(n-r,t.length),i=t.length-s;e.cbuf.set(t.subarray(0,s),r),e.cpos+=s,i>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(B(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},ge=(e,t)=>{ae(e,t.byteLength),pe(e,t)},ye=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*B(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},me=(e,t)=>ye(e,8).setBigUint64(0,t,!1),ve=new DataView(new ArrayBuffer(4)),be=(e,t)=>{switch(typeof t){case"string":le(e,119),fe(e,t);break;case"number":K(t)&&$(t)<=2147483647?(le(e,125),de(e,t)):(n=t,ve.setFloat32(0,n),ve.getFloat32(0)===n?(le(e,124),((e,t)=>{ye(e,4).setFloat32(0,t,!1)})(e,t)):(le(e,123),((e,t)=>{ye(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":le(e,122),((e,t)=>{ye(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)le(e,126);else if(Q(t)){le(e,117),ae(e,t.length);for(let n=0;n<t.length;n++)be(e,t[n])}else if(t instanceof Uint8Array)le(e,116),ge(e,t);else{le(e,118);const n=Object.keys(t);ae(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];fe(e,s),be(e,t[s])}}break;case"boolean":le(e,t?120:121);break;default:le(e,127)}var n};class we extends se{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&ae(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const _e=e=>{e.count>0&&(de(e.encoder,1===e.count?e.s:-e.s),e.count>1&&ae(e.encoder,e.count-2))};class ke{constructor(){this.encoder=new se,this.s=0,this.count=0}write(e){this.s===e?this.count++:(_e(this),this.count=1,this.s=e)}toUint8Array(){return _e(this),oe(this.encoder)}}const Se=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);de(e.encoder,t),e.count>1&&ae(e.encoder,e.count-2)}};class xe{constructor(){this.encoder=new se,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Se(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Se(this),oe(this.encoder)}}class Ee{constructor(){this.sarr=[],this.s="",this.lensE=new ke}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new se;return this.sarr.push(this.s),this.s="",fe(e,this.sarr.join("")),pe(e,this.lensE.toUint8Array()),oe(e)}}const Ce=e=>new Error(e),Ie=()=>{throw Ce("Method unimplemented")},Oe=()=>{throw Ce("Unexpected case")},De=Ce("Unexpected end of array"),Ae=Ce("Integer out of Range");class Te{constructor(e){this.arr=e,this.pos=0}}const Ue=e=>new Te(e),je=e=>e.pos!==e.arr.length,Le=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Re(e)),Pe=e=>e.arr[e.pos++],Re=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&V)*n,n*=128,r<H)return t;if(t>z)throw Ae}throw De},Me=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&W)>0?-1:1;if(0===(t&H))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&V)*r,r*=128,t<H)return s*n;if(n>z)throw Ae}throw De},$e=re?e=>re.decode(Le(e)):e=>{let t=Re(e);if(0===t)return"";{let n=String.fromCodePoint(Pe(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Pe(e));else for(;t>0;){const r=t<1e4?t:1e4,s=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,s),t-=r}return decodeURIComponent(escape(n))}},Ne=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Be=e=>Ne(e,8).getBigUint64(0,!1),Fe=[e=>{},e=>null,Me,e=>Ne(e,4).getFloat32(0,!1),e=>Ne(e,8).getFloat64(0,!1),e=>Ne(e,8).getBigInt64(0,!1),e=>!1,e=>!0,$e,e=>{const t=Re(e),n={};for(let r=0;r<t;r++){n[$e(e)]=We(e)}return n},e=>{const t=Re(e),n=[];for(let r=0;r<t;r++)n.push(We(e));return n},Le],We=e=>Fe[127-Pe(e)](e);class He extends Te{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return 0===this.count&&(this.s=this.reader(this),je(this)?this.count=Re(this)+1:this.count=-1),this.count--,this.s}}class Ve extends Te{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=Me(this);const e=F(this.s);this.count=1,e&&(this.s=-this.s,this.count=Re(this)+2)}return this.count--,this.s}}class ze extends Te{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=Me(this),t=1&e;this.diff=M(e/2),this.count=1,t&&(this.count=Re(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ke{constructor(e){this.decoder=new Ve(e),this.str=$e(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}async function*Je(e){let t=0,n=new Uint8Array(4),r=0,s=[],i=0;for await(const o of e){const e=new DataView(o.buffer,o.byteOffset,o.byteLength);let l=0;for(;l<o.byteLength;)switch(t){case 0:if(l+4>o.byteLength){for(const e of o.slice(l)){if(4===r)break;n[r++]=e,++l}if(r<4)break}else if(r>0&&r<4)for(const e of o.slice(l,l+4-r))n[r++]=e,++l;case 1:i=4===r?new DataView(n.buffer,0,4).getUint32(0,!1):e.getUint32(l,!1),r?r=0:l+=4;case 2:if(l>=o.byteLength){t=2;break}if(l+i>o.byteLength)s.push(o.slice(l)),i-=o.byteLength-l,t=2,l=o.byteLength;else{if(s.length>0){const e=new Uint8Array(s.reduce((e,t)=>e+t.byteLength,i));let t=0;for(const n of s)e.set(n,t),t+=n.byteLength;e.set(o.slice(l,l+i),t),s=[],yield e}else yield o.slice(l,l+i);l+=i,t=0}}}}class qe extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}const Ge={},Ye={google:'<svg viewBox="0 0 24 24" width="20" height="20"><path fill="#4285F4" d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"/><path fill="#34A853" d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"/><path fill="#FBBC05" d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"/><path fill="#EA4335" d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"/></svg>',github:'<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M12 0C5.37 0 0 5.37 0 12c0 5.31 3.435 9.795 8.205 11.385.6.105.825-.255.825-.57 0-.285-.015-1.23-.015-2.235-3.015.555-3.795-.735-4.035-1.41-.135-.345-.72-1.41-1.23-1.695-.42-.225-1.02-.78-.015-.795.945-.015 1.62.87 1.845 1.23 1.08 1.815 2.805 1.305 3.495.99.105-.78.42-1.305.765-1.605-2.67-.3-5.46-1.335-5.46-5.925 0-1.305.465-2.385 1.23-3.225-.12-.3-.54-1.53.12-3.18 0 0 1.005-.315 3.3 1.23.96-.27 1.98-.405 3-.405s2.04.135 3 .405c2.295-1.56 3.3-1.23 3.3-1.23.66 1.65.24 2.88.12 3.18.765.84 1.23 1.905 1.23 3.225 0 4.605-2.805 5.625-5.475 5.925.435.375.81 1.095.81 2.22 0 1.605-.015 2.895-.015 3.3 0 .315.225.69.825.57A12.02 12.02 0 0024 12c0-6.63-5.37-12-12-12z"/></svg>',microsoft:'<svg viewBox="0 0 24 24" width="20" height="20"><rect fill="#F25022" x="1" y="1" width="10" height="10"/><rect fill="#00A4EF" x="1" y="13" width="10" height="10"/><rect fill="#7FBA00" x="13" y="1" width="10" height="10"/><rect fill="#FFB900" x="13" y="13" width="10" height="10"/></svg>',apple:'<svg viewBox="0 0 24 24" width="20" height="20" fill="currentColor"><path d="M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"/></svg>'};function Qe(e){return r(this,void 0,void 0,function*(){var t;let n;if(Ye[e.type])n=Ye[e.type];else if(null===(t=e.iconUrl)||void 0===t?void 0:t.toLowerCase().endsWith(".svg")){const t=yield function(e){return r(this,void 0,void 0,function*(){if(Ge[e])return Ge[e];try{const t=yield fetch(e);if(t.ok){const n=yield t.text();if(n.includes("<svg"))return Ge[e]=n,n}}catch(e){}return null})}(e.iconUrl);t&&(n=t)}return{name:"provider",value:e.name,displayName:`Continue with ${e.displayName}`,iconSvg:n,iconUrl:!n&&e.iconUrl?e.iconUrl:void 0,styleHint:e.type}})}function Xe(t,n){return new Promise((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:e=>{t.next(void 0),r(e)},onCancel:()=>{t.next(void 0),s(new e.AbortError("User cancelled"))}});t.next(i)})}function Ze(e,t,...n){return Xe(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function et(e,t,n){return r(this,void 0,void 0,function*(){let r=n||"";for(;!r||!/^[\w-+.]+@([\w-]+\.)+[\w-]{2,10}(\sas\s[\w-+.]+@([\w-]+\.)+[\w-]{2,10})?$/.test(r);)r=(yield Xe(e,{type:"email",title:t,alerts:r?[{type:"error",messageCode:"INVALID_EMAIL",message:"Please enter a valid email address",messageParams:{}}]:[],fields:{email:{type:"email",placeholder:"you@somedomain.com"}}})).email;return r})}function tt(e,t,n){return r(this,void 0,void 0,function*(){const r=[{type:"info",messageCode:"OTP_SENT",message:"A One-Time password has been sent to {email}",messageParams:{email:t}}];n&&r.push(n);const{otp:s}=yield Xe(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s})}class nt extends Error{constructor(e){super(`OAuth redirect initiated for provider: ${e}`),this.name="OAuthRedirectError",this.provider=e}}function rt(e){return r(this,void 0,void 0,function*(){var t,n,r;const s=yield e.getCurrentUser(),{accessToken:i,accessTokenExpiration:o,refreshToken:l,refreshTokenExpiration:c,claims:a}=s;if(!i)return null;if((null!==(t=null==o?void 0:o.getTime())&&void 0!==t?t:1/0)>Date.now()&&"ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok"))return s;if(!l)throw new Error("Refresh token missing");if((null!==(r=null==c?void 0:c.getTime())&&void 0!==r?r:1/0)<=Date.now())throw new Error("Refresh token has expired");const d=yield it(e.cloud.options.databaseUrl,s);return yield e.table("$logins").update(a.sub,{accessToken:d.accessToken,accessTokenExpiration:d.accessTokenExpiration,claims:d.claims,license:d.license,data:d.data}),d})}function st(t,n,s,i,o){return r(this,void 0,void 0,function*(){return n.accessToken&&n.accessTokenExpiration.getTime()>Date.now()?n:n.refreshToken&&(!n.refreshTokenExpiration||n.refreshTokenExpiration.getTime()>Date.now())?yield it(t,n):yield function(t,n,s,i){return r(this,void 0,void 0,function*(){if(!crypto.subtle)throw"undefined"!=typeof location&&"http:"===location.protocol?new Error("Dexie Cloud Addon needs to use WebCrypto, but your browser has disabled it due to being served from an insecure location. Please serve it from https or http://localhost:<port> (See https://stackoverflow.com/questions/46670556/how-to-enable-crypto-subtle-for-unsecure-origins-in-chrome/46671627#46671627)"):new Error("This browser does not support WebCrypto.");const{privateKey:r,publicKey:o}=yield crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!1,["sign","verify"]);if(!r||!o)throw new Error("Could not generate RSA keypair");t.nonExportablePrivateKey=r;const l=function(e){const t=w(e);return function(e){let t="-----BEGIN PUBLIC KEY-----\n";for(;e.length>0;)t+=e.substring(0,64)+"\n",e=e.substring(64);return t+="-----END PUBLIC KEY-----",t}(t)}(yield crypto.subtle.exportKey("spki",o));t.publicKey=o;try{const e=yield n({public_key:l,hints:i});if("error"===e.type)throw new qe(e);if("tokens"!==e.type)throw new Error(`Unexpected response type from token endpoint: ${e.type}`);return t.accessToken=e.accessToken,t.accessTokenExpiration=new Date(e.accessTokenExpiration),t.refreshToken=e.refreshToken,e.refreshTokenExpiration&&(t.refreshTokenExpiration=new Date(e.refreshTokenExpiration)),t.userId=e.claims.sub,t.email=e.claims.email,t.name=e.claims.name,t.claims=e.claims,t.license={type:e.userType,status:e.claims.license||"ok"},t.data=e.data,null!=e.evalDaysLeft&&(t.license.evalDaysLeft=e.evalDaysLeft),null!=e.userValidUntil&&(t.license.validUntil=new Date(e.userValidUntil)),e.alerts&&e.alerts.length>0&&(yield Xe(s,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:e.alerts})),t}catch(t){if(t instanceof nt||"OAuthRedirectError"===(null==t?void 0:t.name))throw t;if(t instanceof qe)throw yield Ze(s,t.title,{type:"error",messageCode:t.messageCode,message:t.message,messageParams:{}}),t;let n="We're having a problem authenticating right now.";if(t instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":e.debug||"undefined"!=typeof location&&("localhost"===location.hostname||"127.0.0.1"===location.hostname)?`Could not connect to server. Please verify that your origin '${location.origin}' is whitelisted using \`npx dexie-cloud whitelist\``:"Could not connect to server. Please verify the connection.",yield Ze(s,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch(()=>{})}throw t}})}(n,s,i,o)})}function it(e,t){return r(this,void 0,void 0,function*(){if(!t.refreshToken)throw new Error("Cannot refresh token - refresh token is missing.");if(!t.nonExportablePrivateKey)throw new Error("login.nonExportablePrivateKey is missing - cannot sign refresh token without a private key.");const n=Date.now(),r="RSASSA-PKCS1-v1_5",s=(new TextEncoder).encode(t.refreshToken+n),i=yield crypto.subtle.sign(r,t.nonExportablePrivateKey,s),o=w(i),l={grant_type:"refresh_token",refresh_token:t.refreshToken,scopes:["ACCESS_DB"],signature:o,signing_algorithm:r,time_stamp:n},c=yield fetch(`${e}/token`,{body:JSON.stringify(l),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});if(200!==c.status)throw new Error(`RefreshToken: Status ${c.status} from ${e}/token`);const a=yield c.json();if("error"===a.type)throw new qe(a);return t.accessToken=a.accessToken,t.accessTokenExpiration=a.accessTokenExpiration?new Date(a.accessTokenExpiration):void 0,t.claims=a.claims,t.license={type:a.userType,status:a.claims.license||"ok"},null!=a.evalDaysLeft&&(t.license.evalDaysLeft=a.evalDaysLeft),null!=a.userValidUntil&&(t.license.validUntil=new Date(a.userValidUntil)),a.data&&(t.data=a.data),t})}const{toString:ot}={};const lt={replace:function(e){const t=Object.keys(e);let n=null;for(let e=0,r=t.length;e<r;++e)"$"===t[e][0]&&(n=n||[],n.push(t[e]));if(!n)return e;const r={...e};for(const e of n)delete r[e];for(const t of n)r["$"+t]=e[t];return r}};function ct(...e){const t=e.reduce((e,t)=>({...e,...t}),e.reduce((e,t)=>({...t,...e}),{})),n=new WeakMap;return{stringify(e,r,s){const i=JSON.stringify(e,function(e){const s=this[e],i=function(e){const r=typeof e;switch(typeof e){case"object":case"function":{if(null===e)return null;const r=Object.getPrototypeOf(e);if(!r)return lt;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,ot.call(s).slice(8,-1)),l=Object.entries(t).find(([t,n])=>{var r,s;return null!==(s=null===(r=null==n?void 0:n.test)||void 0===r?void 0:r.call(n,e,o))&&void 0!==s?s:t===o});return i=null==l?void 0:l[1],i||(i=Array.isArray(e)?null:"function"==typeof e?t.function||null:lt),n.set(r,i),i}default:return t[r]}var s}(s);return i?i.replace(s,r,t):s},s);return i},parse(e,n){const r=[];return JSON.parse(e,function(e,s){const i=null==s?void 0:s.$t;if(i){const e=t[i];s=e?e.revive(s,n,t):s}let o=r[r.length-1];if(o&&o[0]===s){s={...s};for(const e of o[1])delete s[e];for(const[e,t]of Object.entries(o[2]))s[e]=t;r.pop()}if(void 0===s||"$"===e[0]&&"$t"!==e){let t,n;o=r[r.length-1],o&&o[0]===this?(t=o[1],n=o[2]):r.push([this,t=[],n={}]),"$"===e[0]&&"$t"!==e?(t.push(e),n[e.substr(1)]=s):n[e]=void 0}return s})}}}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 dt={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 ht={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},ft={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},pt={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const gt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var yt=["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 s=gt[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}}),{});function mt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=wt[e[n]];return t}(w(e))}function vt(e){return b(function(e){if("string"!=typeof e)throw new Error("invalid decoder input: "+e);for(var t="",n=0,r=e.length;n<r;n++)t+=bt[e[n]];return t}(e))}const bt={"-":"=",0:"A",1:"B",2:"C",3:"D",4:"E",5:"F",6:"G",7:"H",8:"I",9:"J",A:"K",B:"L",C:"M",D:"N",E:"O",F:"P",G:"Q",H:"R",I:"S",J:"T",K:"U",L:"V",M:"W",N:"X",O:"Y",P:"Z",Q:"a",R:"b",S:"c",T:"d",U:"e",V:"f",W:"g",X:"h",Y:"i",Z:"j",_:"k",a:"l",b:"m",c:"n",d:"o",e:"p",f:"q",g:"r",h:"s",i:"t",j:"u",k:"v",l:"w",m:"x",n:"y",o:"z",p:"0",q:"1",r:"2",s:"3",t:"4",u:"5",v:"6",w:"7",x:"8",y:"9",z:"+","|":"/"},wt={};for(const e of Object.keys(bt))wt[bt[e]]=e;var _t={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:mt(e)}),revive:({v:e})=>{const t=vt(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class kt{constructor(e,t){this.buf=e,this.type=t}}function St(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 xt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Et={Blob:{test:(e,t)=>"Blob"===t||e instanceof kt,replace:e=>({$t:"Blob",v:w(e instanceof kt?e.buf:xt(St(e))),type:e.type}),revive:({type:e,v:t})=>{const n=b(t);return void 0!==typeof Blob?new Blob([n]):new kt(n.buffer,e)}}};const Ct={...dt,...ut,...ht,...ft,...pt,...yt,..._t,...Et};function It(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 Ot={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},Dt={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:w(xt(St(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=b(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const At="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Tt{toString(){return this.v}constructor(e){this.v=e}}const Ut=At?{}:{bigint:{test:e=>e instanceof Tt,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Tt(e)}},jt=Object.assign(Object.assign(Object.assign(Object.assign({},Ot),Ut),Dt),{PropModification:{test:t=>t instanceof e.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:t=>{var{$t:n}=t,r=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(r=Object.getOwnPropertySymbols(e);s<r.length;s++)t.indexOf(r[s])<0&&Object.prototype.propertyIsEnumerable.call(e,r[s])&&(n[r[s]]=e[r[s]])}return n}(t,["$t"]);return new e.PropModification(r)}}}),Lt=ct(Ct,jt),Pt=function(...e){const t=ct(Ct,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);return[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])})),r]},async parse(e,n){let r=0;const s=[],i=await It(n),o=new DataView(i);for(;r<i.byteLength;){const e=o.getUint32(r);r+=4;const t=i.slice(r,r+e);r+=e,s.push(t)}return t.parse(e,s)},async fromBinary(e){const t=new DataView(await It(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)})}(e.slice(t+4));return await this.parse(r,n)}}}(jt);class Rt extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function Mt(t,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=t.tables.find(e=>e.name===r);if(!l)throw new Error(`Internal error: table ${r} not found in DBCore schema`);const{primaryKey:c}=l;let a=i;o.forEach((t,r)=>{const s=!c.outbound&&("upsert"===t.type||"insert"===t.type);t.keys.forEach((t,o)=>{if(Array.isArray(t)){a===i&&(a=$t(i,s));const e=a.muts[r],n=JSON.stringify(t);e.keys[o]=n}else if("#"===t[0]){a===i&&(a=$t(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const d=`${t}:${n.userId}`;l.keys[o]=d,s&&e.setByKeyPath(l.values[o],c.keyPath,d)}})}),s.push(a)}return s}function $t(e,t){return Object.assign(Object.assign({},e),{muts:t?e.muts.map(e=>"insert"!==e.type&&"upsert"!==e.type||!e.values?Object.assign(Object.assign({},e),{keys:e.keys.slice()}):Object.assign(Object.assign({},e),{keys:e.keys.slice(),values:e.values.slice()})):e.muts.map(e=>Object.assign(Object.assign({},e),{keys:e.keys.slice()}))})}let Nt=new WeakMap;function Bt(e){return r(this,void 0,void 0,function*(){var t,n;const r=(null!==(n=null===(t=Nt.get(e))||void 0===t?void 0:t.getTime())&&void 0!==n?n:0)-Date.now();r>0&&(yield new Promise(e=>setTimeout(e,r)))})}function Ft(e,t,n,s,i,o,l,c,a){return r(this,void 0,void 0,function*(){const r={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},d=yield rt(i),u=null==d?void 0:d.accessToken;u&&(r.Authorization=`Bearer ${u}`);const h={v:2,dbID:null==n?void 0:n.remoteDbId,clientIdentity:c,schema:l||{},lastPull:n?{serverRevision:n.serverRevision,yServerRevision:n.yServerRevision,realms:n.realms,inviteRealms:n.inviteRealms}:void 0,baseRevs:s,changes:Mt(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=Lt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:r,credentials:"include",body:f});if(i.syncStateChangedEvent.next({phase:"pulling"}),function(e,t){const n=t.headers.get("Ratelimit-Limit"),r=t.headers.get("Ratelimit-Remaining"),s=t.headers.get("Ratelimit-Reset");if(n&&r&&s){const t=Number(n),i=Math.max(0,Number(r)),o=Number(s);if(i<t/2){const t=Math.ceil(o/(i+1));Nt.set(e,new Date(Date.now()+1e3*t))}else Nt.delete(e)}}(i,p),!p.ok)throw new Rt(p);if("application/x-bison"===p.headers.get("content-type"))return Pt.fromBinary(yield p.blob());{const e=yield p.text();return Lt.parse(e)}})}function Wt(t){if(null==t?void 0:t.cancelled)throw new e.AbortError("Operation was cancelled")}let Ht=!1;function Vt(e,t,n,s){return r(this,void 0,void 0,function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter(e=>t[e].markedForSync).map(e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:s}))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter(e=>t[e].markedForSync)).delete()})}function zt(e,t={}){for(const{table:n,muts:r}of e){const e=r.length>0?r[r.length-1].rev:null;t[n]=e||t[n]||0}return t}function Kt(t,n,s){return r(this,void 0,void 0,function*(){const r=yield t.bulkGet(n),i=[],o=[];n.forEach((n,l)=>{const c=r[l];if(c){for(const[r,i]of Object.entries(s[l]))if(r===t.schema.primKey.keyPath){if(0!==e.cmp(i,n))throw new Error("Cannot change primary key")}else e.setByKeyPath(c,r,i);i.push(n),o.push(c)}}),yield null==t.schema.primKey.keyPath?t.bulkPut(o,i):t.bulkPut(o)})}function Jt(t,n){return r(this,void 0,void 0,function*(){for(const{table:r,muts:s}of t){if(!n.dx._allTables[r])continue;const t=n.table(r),{primaryKey:i}=t.core.schema,o=e=>{switch(e[0]){case"[":if(e.endsWith("]"))try{return JSON.parse(e)}catch(e){}return e;case"#":return e.endsWith(":"+n.cloud.currentUserId)?e.substr(0,e.length-n.cloud.currentUserId.length-1):e;default:return e}};for(const n of s){const r=n.keys.map(o);switch(n.type){case"insert":i.outbound?yield t.bulkAdd(n.values,r):(r.forEach((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)}),yield t.bulkAdd(n.values));break;case"upsert":i.outbound?yield t.bulkPut(n.values,r):(r.forEach((t,r)=>{e.setByKeyPath(n.values[r],i.keyPath,t)}),yield t.bulkPut(n.values));break;case"modify":1===r.length?yield t.update(r[0],n.changeSpec):yield t.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield Kt(t,r,n.changeSpecs);break;case"delete":yield t.bulkDelete(r)}}}})}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(Ht=navigator.onLine,self.addEventListener("online",()=>Ht=!0),self.addEventListener("offline",()=>Ht=!1));const qt="dexie-cloud-syncer";function Gt(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Yt=()=>new Map,Qt=e=>{const t=Yt();return e.forEach((e,n)=>{t.set(n,e)}),t},Xt=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};class Zt{constructor(){this._observers=Yt()}on(e,t){return Xt(this._observers,e,J).add(t),t}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Y((this._observers.get(e)||Yt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Yt()}}class en{constructor(){this._observers=Yt()}on(e,t){Xt(this._observers,e,J).add(t)}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Y((this._observers.get(e)||Yt()).values()).forEach(e=>e(...t))}destroy(){this._observers=Yt()}}const tn=crypto.getRandomValues.bind(crypto),nn=()=>tn(new Uint32Array(1))[0],rn=[1e7]+-1e3+-4e3+-8e3+-1e11,sn=()=>rn.replace(/[018]/g,e=>(e^nn()&15>>e/4).toString(16)),on=Date.now,ln=e=>new Promise(e);Promise.all.bind(Promise);const cn=e=>void 0===e?null:e;let an=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},dn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(an=localStorage,dn=!1)}catch(Bl){}const un=an,hn=Object.assign,fn=Object.keys,pn=e=>fn(e).length,gn=e=>fn(e).length,yn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),mn=Object.freeze,vn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||vn(e[t])}return mn(e)},bn=Symbol("Equality"),wn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&wn(e,t,n+1)}},_n=(e,t)=>{if(e===t)return!0;if(null==e||null==t||e.constructor!==t.constructor)return!1;if(null!=e[bn])return e[bn](t);switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(const n of e.keys())if(!t.has(n)||!_n(e.get(n),t.get(n)))return!1;break;case Object:if(pn(e)!==pn(t))return!1;for(const n in e)if(!yn(e,n)||!_n(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!_n(e[n],t[n]))return!1;break;default:return!1}return!0},kn="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Sn;const xn=e=>(()=>{if(void 0===Sn)if(kn){Sn=Yt();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Sn.set(t,""),t=r):null!==t&&(Sn.set(t,r),t=null)}null!==t&&Sn.set(t,"")}else"object"==typeof location?(Sn=Yt(),(location.search||"?").slice(1).split("&").forEach(e=>{if(0!==e.length){const[t,n]=e.split("=");Sn.set(`--${ee(t,"-")}`,n),Sn.set(`-${ee(t,"-")}`,n)}})):Sn=Yt();return Sn})().has(e),En=e=>cn(kn?process.env[e.toUpperCase().replaceAll("-","_")]:un.getItem(e)),Cn=e=>xn("--"+e)||null!==En(e);Cn("production");var In;kn&&(In=process.env.FORCE_COLOR,["true","1","2"].includes(In))||!xn("--no-colors")&&!Cn("no-color")&&(!kn||process.stdout.isTTY)&&(!kn||xn("--color")||null!==En("COLORTERM")||(En("TERM")||"").includes("color"));class On{constructor(e,t){this.left=e,this.right=t}}const Dn=(e,t)=>new On(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const An=Symbol,Tn=An(),Un=An(),jn=An(),Ln=An(),Pn=An(),Rn=An(),Mn=An(),$n=An(),Nn=An(),Bn=(Dn("font-weight","bold"),Dn("font-weight","normal"),Dn("color","blue"),Dn("color","green"),Dn("color","grey"),Dn("color","red"),Dn("color","purple"),Dn("color","orange"),Dn("color","black"),J()),Fn=e=>({[Symbol.iterator](){return this},next:e}),Wn=(e,t)=>Fn(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class Hn{constructor(e,t){this.clock=e,this.len=t}}class Vn{constructor(){this.clients=new Map}}const zn=(e,t,n)=>t.clients.forEach((t,r)=>{const s=e.doc.store.clients.get(r);if(null!=s){const r=s[s.length-1],i=r.id.clock+r.length;for(let r=0,o=t[r];r<t.length&&o.clock<i;o=t[++r])Ir(e,s,o.clock,o.len,n)}}),Kn=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const s=M((n+r)/2),i=e[s],o=i.clock;if(o<=t){if(t<o+i.len)return s;n=s+1}else r=s-1}return null})(n,t.clock)},Jn=e=>{e.clients.forEach(e=>{let t,n;for(e.sort((e,t)=>e.clock-t.clock),t=1,n=1;t<e.length;t++){const r=e[n-1],s=e[t];r.clock+r.len>=s.clock?r.len=B(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n})},qn=(e,t,n,r)=>{Xt(e.clients,t,()=>[]).push(new Hn(n,r))},Gn=(e,t)=>{ae(e.restEncoder,t.clients.size),Y(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),ae(e.restEncoder,t);const r=n.length;ae(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},Yn=(e,t,n)=>{const r=new Vn,s=Re(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=Re(e.restDecoder),i=Re(e.restDecoder),o=n.clients.get(s)||[],l=wr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&qn(r,s,l,i-l);let e=kr(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,ci(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<i);)c.deleted||(i<c.id.clock+c.length&&o.splice(e,0,ci(t,c,i-c.id.clock)),c.delete(t))}else qn(r,s,n,i-n)}}if(r.clients.size>0){const e=new sr;return ae(e.restEncoder,0),Gn(e,r),e.toUint8Array()}return null},Qn=nn;class Xn extends Zt{constructor({guid:e=sn(),collectionid:t=null,gc:n=!0,gcFilter:r=()=>!0,meta:s=null,autoLoad:i=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=Qn(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new vr,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=i,this.meta=s,this.isLoaded=!1,this.isSynced=!1,this.isDestroyed=!1,this.whenLoaded=ln(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const l=()=>ln(e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)});this.on("sync",e=>{!1===e&&this.isSynced&&(this.whenSynced=l()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[this])}),this.whenSynced=l()}load(){const e=this._item;null===e||this.shouldLoad||jr(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Y(this.subdocs).map(e=>e.guid))}transact(e,t=null){return jr(this,e,t)}get(e,t=Xr){const n=Xt(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==Xr&&r!==t){if(r===Xr){const r=new t;r._map=n._map,n._map.forEach(e=>{for(;null!==e;e=e.left)e.parent=r}),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,ys)}getText(e=""){return this.get(e,Ls)}getMap(e=""){return this.get(e,vs)}getXmlElement(e=""){return this.get(e,Ms)}getXmlFragment(e=""){return this.get(e,Rs)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,Y(this.subdocs).forEach(e=>e.destroy());const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Xn({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,jr(e.parent.doc,n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)},null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}}class Zn{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Re(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Re(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class er extends Zn{constructor(e){super(e),this.keys=[],Re(e),this.keyClockDecoder=new ze(Le(e)),this.clientDecoder=new Ve(Le(e)),this.leftClockDecoder=new ze(Le(e)),this.rightClockDecoder=new ze(Le(e)),this.infoDecoder=new He(Le(e),Pe),this.stringDecoder=new Ke(Le(e)),this.parentInfoDecoder=new He(Le(e),Pe),this.typeRefDecoder=new Ve(Le(e)),this.lenDecoder=new Ve(Le(e))}readLeftID(){return new fr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new fr(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return We(this.restDecoder)}readBuf(){return Le(this.restDecoder)}readJSON(){return We(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class tr{constructor(){this.restEncoder=ie()}toUint8Array(){return oe(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){ae(this.restEncoder,e)}writeDsLen(e){ae(this.restEncoder,e)}}class nr extends tr{writeLeftID(e){ae(this.restEncoder,e.client),ae(this.restEncoder,e.clock)}writeRightID(e){ae(this.restEncoder,e.client),ae(this.restEncoder,e.clock)}writeClient(e){ae(this.restEncoder,e)}writeInfo(e){ce(this.restEncoder,e)}writeString(e){fe(this.restEncoder,e)}writeParentInfo(e){ae(this.restEncoder,e?1:0)}writeTypeRef(e){ae(this.restEncoder,e)}writeLen(e){ae(this.restEncoder,e)}writeAny(e){be(this.restEncoder,e)}writeBuf(e){ge(this.restEncoder,e)}writeJSON(e){fe(this.restEncoder,JSON.stringify(e))}writeKey(e){fe(this.restEncoder,e)}}class rr{constructor(){this.restEncoder=ie(),this.dsCurrVal=0}toUint8Array(){return oe(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,ae(this.restEncoder,t)}writeDsLen(e){0===e&&Oe(),ae(this.restEncoder,e-1),this.dsCurrVal+=e}}class sr extends rr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new xe,this.clientEncoder=new ke,this.leftClockEncoder=new xe,this.rightClockEncoder=new xe,this.infoEncoder=new we(ce),this.stringEncoder=new Ee,this.parentInfoEncoder=new we(ce),this.typeRefEncoder=new ke,this.lenEncoder=new ke}toUint8Array(){const e=ie();return ae(e,0),ge(e,this.keyClockEncoder.toUint8Array()),ge(e,this.clientEncoder.toUint8Array()),ge(e,this.leftClockEncoder.toUint8Array()),ge(e,this.rightClockEncoder.toUint8Array()),ge(e,oe(this.infoEncoder)),ge(e,this.stringEncoder.toUint8Array()),ge(e,oe(this.parentInfoEncoder)),ge(e,this.typeRefEncoder.toUint8Array()),ge(e,this.lenEncoder.toUint8Array()),pe(e,oe(this.restEncoder)),oe(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){be(this.restEncoder,e)}writeBuf(e){ge(this.restEncoder,e)}writeJSON(e){be(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const ir=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{wr(t,n)>e&&r.set(n,e)}),br(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),ae(e.restEncoder,r.size),Y(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=B(r,t[0].id.clock);const s=kr(t,r);ae(e.restEncoder,t.length-s),e.writeClient(n),ae(e.restEncoder,r);const i=t[s];i.write(e,r-i.id.clock);for(let n=s+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)})},or=(e,t,n,r=new er(e))=>jr(t,e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Yt(),r=Re(e.restDecoder);for(let s=0;s<r;s++){const r=Re(e.restDecoder),s=new Array(r),i=e.readClient();let o=Re(e.restDecoder);n.set(i,{i:0,refs:s});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();s[n]=new Ws(gr(i,o),t),o+=t;break}case 10:{const t=Re(e.restDecoder);s[n]=new hi(gr(i,o),t),o+=t;break}default:{const l=!(192&r),c=new ai(gr(i,o),null,(r&H)===H?e.readLeftID():null,null,(r&W)===W?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!l||32&~r?null:e.readString(),di(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=Y(n.keys()).sort((e,t)=>e-t);if(0===s.length)return null;const i=()=>{if(0===s.length)return null;let e=n.get(s[s.length-1]);for(;e.refs.length===e.i;){if(s.pop(),!(s.length>0))return null;e=n.get(s[s.length-1])}return e};let o=i();if(null===o)return null;const l=new vr,c=new Map,a=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let d=o.refs[o.i++];const u=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,l.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):l.clients.set(t,[e]),s=s.filter(e=>e!==t)}r.length=0};for(;;){if(d.constructor!==hi){const s=Xt(u,d.id.client,()=>wr(t,d.id.client))-d.id.clock;if(s<0)r.push(d),a(d.id.client,d.id.clock-1),h();else{const i=d.getMissing(e,t);if(null!==i){r.push(d);const e=n.get(i)||{refs:[],i:0};if(e.refs.length!==e.i){d=e.refs[e.i++];continue}a(i,wr(t,i)),h()}else(0===s||s<d.length)&&(d.integrate(e,s),u.set(d.id.client,d.id.clock+d.length))}}if(r.length>0)d=r.pop();else if(null!==o&&o.i<o.refs.length)d=o.refs[o.i++];else{if(o=i(),null===o)break;d=o.refs[o.i++]}}if(l.clients.size>0){const e=new sr;return ir(e,l,new Map),ae(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,s,i),l=s.pendingStructs;if(l){for(const[e,n]of l.missing)if(n<wr(s,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=l.missing.get(e);(null==n||n>t)&&l.missing.set(e,t)}l.update=$r([l.update,o.update])}}else s.pendingStructs=o;const c=Yn(r,e,s);if(s.pendingDs){const t=new er(Ue(s.pendingDs));Re(t.restDecoder);const n=Yn(t,e,s);s.pendingDs=c&&n?$r([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,lr(e.doc,t)}},n,!1),lr=(e,t,n,r=er)=>{const s=Ue(t);or(s,e,n,new r(s))};class cr{constructor(){this.l=[]}}const ar=()=>new cr,dr=(e,t)=>e.l.push(t),ur=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},hr=(e,t,n)=>wn(e.l,[t,n]);class fr{constructor(e,t){this.client=e,this.clock=t}}const pr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,gr=(e,t)=>new fr(e,t),yr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Kn(t.ds,e.id),mr=(e,t)=>{const n=Xt(e.meta,mr,J),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<wr(r,n)&&Er(e,gr(n,t))}),zn(e,t.ds,e=>{}),n.add(t))};class vr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const br=e=>{const t=new Map;return e.clients.forEach((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)}),t},wr=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},_r=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Oe()}n.push(t)},kr=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=M(t/(i+s.length-1)*r);for(;n<=r;){if(s=e[o],i=s.id.clock,i<=t){if(t<i+s.length)return o;n=o+1}else r=o-1;o=M((n+r)/2)}throw Oe()},Sr=(e,t)=>{const n=e.clients.get(t.client);return n[kr(n,t.clock)]},xr=(e,t,n)=>{const r=kr(t,n),s=t[r];return s.id.clock<n&&s instanceof ai?(t.splice(r+1,0,ci(e,s,n-s.id.clock)),r+1):r},Er=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[xr(e,n,t.clock)]},Cr=(e,t,n)=>{const r=t.clients.get(n.client),s=kr(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Ws&&r.splice(s+1,0,ci(e,i,n.clock-i.id.clock+1)),i},Ir=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=xr(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&xr(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class Or{constructor(e,t,n){this.doc=e,this.deleteSet=new Vn,this.beforeState=br(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const Dr=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,t)=>{for(const[n,r]of e)if(t(r,n))return!0;return!1})(t.afterState,(e,n)=>t.beforeState.get(n)!==e))&&(Jn(t.deleteSet),((e,t)=>{ir(e,t.doc.store,t.beforeState)})(e,t),Gn(e,t.deleteSet),!0),Ar=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Xt(e.changed,t,J).add(n)},Tr=(e,t)=>{let n=e[t],r=e[t-1],s=t;for(;s>0&&(r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n));n=r,r=e[--s-1])n instanceof ai&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const i=t-s;return i&&e.splice(t+1-i,i),i},Ur=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{Jn(i),n.afterState=br(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach((t,r)=>e.push(()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})),e.push(()=>{n.changedParentTypes.forEach((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter(e=>null===e.target._item||!e.target._item.deleted)).forEach(e=>{e.currentTarget=t,e._path=null}),e.sort((e,t)=>e.path.length-t.path.length),hr(t._dEH,e,n))})}),e.push(()=>r.emit("afterTransaction",[n,r])),wn(e,[]),n._needFormattingCleanup&&Ts(n)}finally{r.gc&&((e,t,n)=>{for(const[r,s]of e.clients.entries()){const e=t.clients.get(r);for(let r=s.length-1;r>=0;r--){const i=s[r],o=i.clock+i.len;for(let r=kr(e,i.clock),s=e[r];r<e.length&&s.id.clock<o;s=e[++r]){const s=e[r];if(i.clock+i.len<=s.id.clock)break;s instanceof ai&&s.deleted&&!s.keep&&n(s)&&s.gc(t,!1)}}}})(i,s,r.gcFilter),((e,t)=>{e.clients.forEach((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=N(r.length-1,1+kr(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Tr(r,e)}})})(i,s),n.afterState.forEach((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=s.clients.get(t),n=B(kr(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Tr(e,t)}});for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=s.clients.get(t),i=kr(r,n);i+1<r.length&&Tr(r,i+1)>1||i>0&&Tr(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Bn.forEach(t=>t.print(e))})($n,Tn,"[yjs] ",Un,Rn,"Changed the client-id because another client seems to be using it."),r.clientID=Qn()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new nr;Dr(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new sr;Dr(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:l,subdocsLoaded:c,subdocsRemoved:a}=n;(l.size>0||a.size>0||c.size>0)&&(l.forEach(e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)}),a.forEach(e=>r.subdocs.delete(e)),r.emit("subdocs",[{loaded:c,added:l,removed:a},r,n]),a.forEach(e=>e.destroy())),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Ur(e,t+1)}}},jr=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new Or(e,n,r),s.push(e._transaction),1===s.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(i){const t=e._transaction===s[0];e._transaction=null,t&&Ur(s,0)}}return o};class Lr{constructor(e,t){this.gen=function*(e){const t=Re(e.restDecoder);for(let n=0;n<t;n++){const t=Re(e.restDecoder),n=e.readClient();let r=Re(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=Re(e.restDecoder);yield new hi(gr(n,r),t),r+=t}else if(31&t){const s=!(192&t),i=new ai(gr(n,r),null,(t&H)===H?e.readLeftID():null,null,(t&W)===W?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,!s||32&~t?null:e.readString(),di(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new Ws(gr(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===hi);return this.curr}}class Pr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Rr=(e,t=rr,n=er)=>{const r=new t,s=new Lr(new n(Ue(e)),!1);let i=s.curr;if(null!==i){let e=0,t=i.id.client,n=0!==i.id.clock,o=n?0:i.id.clock+i.length;for(;null!==i;i=s.next())t!==i.id.client&&(0!==o&&(e++,ae(r.restEncoder,t),ae(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===hi&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,ae(r.restEncoder,t),ae(r.restEncoder,o));const l=ie();return ae(l,e),((e,t)=>{pe(e,oe(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return ae(r.restEncoder,0),r.toUint8Array()},Mr=(e,t)=>{if(e.constructor===Ws){const{client:n,clock:r}=e.id;return new Ws(gr(n,r+t),e.length-t)}if(e.constructor===hi){const{client:n,clock:r}=e.id;return new hi(gr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new ai(gr(r,s+t),null,gr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},$r=(e,t=er,n=sr)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(Ue(e)));let s=r.map(e=>new Lr(e,!0)),i=null;const o=new n,l=new Pr(o);for(;s=s.filter(e=>null!==e.curr),s.sort((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===hi?1:-1:n}return t.curr.id.client-e.curr.id.client}),0!==s.length;){const e=s[0],t=e.curr.id.client;if(null!==i){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=i.struct.id.clock+i.struct.length&&n.id.client>=i.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>i.struct.id.clock+i.struct.length)continue;if(t!==i.struct.id.client)Br(l,i.struct,i.offset),i={struct:n,offset:0},e.next();else if(i.struct.id.clock+i.struct.length<n.id.clock)if(i.struct.constructor===hi)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{Br(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new hi(gr(t,i.struct.id.clock+i.struct.length),e),offset:0}}else{const t=i.struct.id.clock+i.struct.length-n.id.clock;t>0&&(i.struct.constructor===hi?i.struct.length-=t:n=Mr(n,t)),i.struct.mergeWith(n)||(Br(l,i.struct,i.offset),i={struct:n,offset:0},e.next())}}else i={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===i.struct.id.clock+i.struct.length&&n.constructor!==hi;n=e.next())Br(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(Br(l,i.struct,i.offset),i=null),Fr(l);const c=r.map(e=>(e=>{const t=new Vn,n=Re(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Re(e.restDecoder),r=Re(e.restDecoder);if(r>0){const s=Xt(t.clients,n,()=>[]);for(let t=0;t<r;t++)s.push(new Hn(e.readDsClock(),e.readDsLen()))}}return t})(e)),a=(e=>{const t=new Vn;for(let n=0;n<e.length;n++)e[n].clients.forEach((r,s)=>{if(!t.clients.has(s)){const i=r.slice();for(let t=n+1;t<e.length;t++)G(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}});return Jn(t),t})(c);return Gn(o,a),o.toUint8Array()},Nr=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:oe(e.encoder.restEncoder)}),e.encoder.restEncoder=ie(),e.written=0)},Br=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Nr(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),ae(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Fr=e=>{Nr(e);const t=e.encoder.restEncoder;ae(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];ae(t,r.written),pe(t,r.restEncoder)}},Wr="You must not compute changes after the event-handler fired.";class Hr{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=Vr(this.currentTarget,this.target))}deletes(e){return Kn(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw Ce(Wr);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach(n=>{if(null!==n){const r=t._map.get(n);let s,i;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;s="delete",i=q(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=q(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=q(r.content.getContent())}e.set(n,{action:s,oldValue:i})}}),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw Ce(Wr);const t=this.target,n=J(),r=J(),s=[];e={added:n,deleted:r,delta:s,keys:this.keys};if(this.transaction.changed.get(t).has(null)){let e=null;const i=()=>{e&&s.push(e)};for(let s=t._start;null!==s;s=s.right)s.deleted?this.deletes(s)&&!this.adds(s)&&(null!==e&&void 0!==e.delete||(i(),e={delete:0}),e.delete+=s.length,r.add(s)):this.adds(s)?(null!==e&&void 0!==e.insert||(i(),e={insert:[]}),e.insert=e.insert.concat(s.content.getContent()),n.add(s)):(null!==e&&void 0!==e.retain||(i(),e={retain:0}),e.retain+=s.length);null!==e&&void 0===e.retain&&i()}this._changes=e}return e}}const Vr=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)!r.deleted&&r.countable&&(e+=r.length),r=r.right;n.unshift(e)}t=t._item.parent}return n},zr=()=>{((...e)=>{e.unshift($n),Bn.forEach(t=>t.print(e))})("Invalid access: Add Yjs type to a document before reading data.")};let Kr=0;class Jr{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Kr++}}const qr=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Kr++},Gr=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce((e,n)=>$(t-e.index)<$(t-n.index)?e:n);let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=Kr++})(n));null!==r.right&&s<t;){if(!r.deleted&&r.countable){if(t<s+r.length)break;s+=r.length}r=r.right}for(;null!==r.left&&s>t;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(s-=r.length);return null!==n&&$(n.index-s)<r.parent.length/80?(qr(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return qr(r,t,n),r}{const r=new Jr(t,n);return e.push(r),r}})(e._searchMarker,r,s)},Yr=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const s=e[r];if(n>0){let t=s.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(s.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}s.p=t,t.marker=!0}(t<s.index||n>0&&t===s.index)&&(s.index=B(t,s.index+n))}},Qr=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;Xt(s,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;hr(r._eH,n,t)};class Xr{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=ar(),this._dEH=ar(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Ie()}clone(){throw Ie()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){dr(this._eH,e)}observeDeep(e){dr(this._dEH,e)}unobserve(e){ur(this._eH,e)}unobserveDeep(e){ur(this._dEH,e)}toJSON(){}}const Zr=(e,t,n)=>{e.doc??zr(),t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const s=[];let i=e._start;for(;null!==i&&r>0;){if(i.countable&&!i.deleted){const e=i.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)s.push(e[n]),r--;t=0}}i=i.right}return s},es=e=>{e.doc??zr();const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},ts=(e,t)=>{let n=0,r=e._start;for(e.doc??zr();null!==r;){if(r.countable&&!r.deleted){const s=r.content.getContent();for(let r=0;r<s.length;r++)t(s[r],n++,e)}r=r.right}},ns=(e,t)=>{const n=[];return ts(e,(r,s)=>{n.push(t(r,s,e))}),n},rs=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},ss=(e,t)=>{e.doc??zr();const n=Gr(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},is=(e,t,n,r)=>{let s=n;const i=e.doc,o=i.clientID,l=i.store,c=null===n?t._start:n.right;let a=[];const d=()=>{a.length>0&&(s=new ai(gr(o,wr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Qs(a)),s.integrate(e,0),a=[])};r.forEach(n=>{if(null===n)a.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:a.push(n);break;default:switch(d(),n.constructor){case Uint8Array:case ArrayBuffer:s=new ai(gr(o,wr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Hs(new Uint8Array(n))),s.integrate(e,0);break;case Xn:s=new ai(gr(o,wr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ks(n)),s.integrate(e,0);break;default:if(!(n instanceof Xr))throw new Error("Unexpected content type in insert operation");s=new ai(gr(o,wr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new li(n)),s.integrate(e,0)}}}),d()},os=()=>Ce("Length exceeded!"),ls=(e,t,n,r)=>{if(n>t._length)throw os();if(0===n)return t._searchMarker&&Yr(t._searchMarker,n,r.length),is(e,t,null,r);const s=n,i=Gr(t,n);let o=t._start;for(null!==i&&(o=i.p,0===(n-=i.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Er(e,gr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Yr(t._searchMarker,s,r.length),is(e,t,o,r)},cs=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=Gr(t,n);let l=t._start;for(null!==o&&(l=o.p,n-=o.index);null!==l&&n>0;l=l.right)!l.deleted&&l.countable&&(n<l.length&&Er(e,gr(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&Er(e,gr(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw os();t._searchMarker&&Yr(t._searchMarker,s,-i+r)},as=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},ds=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new Qs([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new Qs([r]);break;case Uint8Array:l=new Hs(r);break;case Xn:l=new Ks(r);break;default:if(!(r instanceof Xr))throw new Error("Unexpected content type");l=new li(r)}new ai(gr(o,wr(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},us=(e,t)=>{e.doc??zr();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},hs=e=>{const t={};return e.doc??zr(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},fs=(e,t)=>{e.doc??zr();const n=e._map.get(t);return void 0!==n&&!n.deleted},ps=e=>{return e.doc??zr(),t=e._map.entries(),n=e=>!e[1].deleted,Fn(()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e});var t,n};class gs extends Hr{}class ys extends Xr{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new ys;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ys}clone(){const e=new ys;return e.insert(0,this.toArray().map(e=>e instanceof Xr?e.clone():e)),e}get length(){return this.doc??zr(),this._length}_callObserver(e,t){super._callObserver(e,t),Qr(this,e,new gs(this,e))}insert(e,t){null!==this.doc?jr(this.doc,n=>{ls(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?jr(this.doc,t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce((e,t)=>t.index>e.index?t:e,{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;is(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?jr(this.doc,n=>{cs(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return ss(this,e)}toArray(){return es(this)}slice(e=0,t=this.length){return Zr(this,e,t)}toJSON(){return this.map(e=>e instanceof Xr?e.toJSON():e)}map(e){return ns(this,e)}forEach(e){ts(this,e)}[Symbol.iterator](){return rs(this)}_write(e){e.writeTypeRef(ei)}}class ms extends Hr{constructor(e,t,n){super(e,t),this.keysChanged=n}}class vs extends Xr{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach((e,t)=>{this.set(t,e)}),this._prelimContent=null}_copy(){return new vs}clone(){const e=new vs;return this.forEach((t,n)=>{e.set(n,t instanceof Xr?t.clone():t)}),e}_callObserver(e,t){Qr(this,e,new ms(this,e,t))}toJSON(){this.doc??zr();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Xr?r.toJSON():r}}),e}get size(){return[...ps(this)].length}keys(){return Wn(ps(this),e=>e[0])}values(){return Wn(ps(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Wn(ps(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??zr(),this._map.forEach((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)})}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?jr(this.doc,t=>{as(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?jr(this.doc,n=>{ds(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return us(this,e)}has(e){return fs(this,e)}clear(){null!==this.doc?jr(this.doc,e=>{this.forEach(function(t,n,r){as(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(ti)}}const bs=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||gn(e)===gn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,(e,n)=>(void 0!==e||yn(t,n))&&t[n]===e))(e,t);class ws{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&Oe(),this.right.content.constructor===qs)this.right.deleted||xs(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const _s=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===qs)t.right.deleted||xs(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Er(e,gr(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length);t.left=t.right,t.right=t.right.right}return t},ks=(e,t,n,r)=>{const s=new Map,i=r?Gr(t,n):null;if(i){const t=new ws(i.p.left,i.p,i.index,s);return _s(e,t,n-i.index)}{const r=new ws(null,t._start,0,s);return _s(e,r,n)}},Ss=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===qs&&bs(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const s=e.doc,i=s.clientID;r.forEach((r,o)=>{const l=n.left,c=n.right,a=new ai(gr(i,wr(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new qs(o,r));a.integrate(e,0),n.right=a,n.forward()})},xs=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Es=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===qs&&bs(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Cs=(e,t,n,r)=>{const s=e.doc,i=s.clientID,o=new Map;for(const l in r){const c=r[l],a=n.currentAttributes.get(l)??null;if(!bs(a,c)){o.set(l,a);const{left:r,right:d}=n;n.right=new ai(gr(i,wr(s.store,i)),r,r&&r.lastId,d,d&&d.id,t,null,new qs(l,c)),n.right.integrate(e,0),n.forward()}}return o},Is=(e,t,n,r,s)=>{n.currentAttributes.forEach((e,t)=>{void 0===s[t]&&(s[t]=null)});const i=e.doc,o=i.clientID;Es(n,s);const l=Cs(e,t,n,s),c=r.constructor===String?new Xs(r):r instanceof Xr?new li(r):new Js(r);let{left:a,right:d,index:u}=n;t._searchMarker&&Yr(t._searchMarker,n.index,c.getLength()),d=new ai(gr(o,wr(i.store,o)),a,a&&a.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=u,n.forward(),Ss(e,t,n,l)},Os=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Es(n,s);const l=Cs(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===qs));){if(!n.right.deleted)switch(n.right.content.constructor){case qs:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(bs(o,i))l.delete(t);else{if(0===r)break e;l.set(t,i)}n.right.delete(e)}else n.currentAttributes.set(t,i);break}default:r<n.right.length&&Er(e,gr(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let s="";for(;r>0;r--)s+="\n";n.right=new ai(gr(o,wr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Xs(s)),n.right.integrate(e,0),n.forward()}Ss(e,t,n,l)},Ds=(e,t,n,r,s)=>{let i=t;const o=Yt();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===qs){const e=i.content;o.set(e.key,e)}i=i.right}let l=0,c=!1;for(;t!==i;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case qs:{const{key:i,value:a}=n,d=r.get(i)??null;o.get(i)===n&&d!==a||(t.delete(e),l++,c||(s.get(i)??null)!==a||d===a||(null===d?s.delete(i):s.set(i,d))),c||t.deleted||xs(s,n);break}}}t=t.right}return l},As=e=>{let t=0;return jr(e.doc,n=>{let r=e._start,s=e._start,i=Yt();const o=Qt(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===qs)xs(o,s.content);else t+=Ds(n,r,s,i,o),i=Qt(o),r=s;s=s.right}}),t},Ts=e=>{const t=new Set,n=e.doc;for(const[r,s]of e.afterState.entries()){const i=e.beforeState.get(r)||0;s!==i&&Ir(e,n.store.clients.get(r),i,s,e=>{e.deleted||e.content.constructor!==qs||e.constructor===Ws||t.add(e.parent)})}jr(n,n=>{zn(e,e.deleteSet,e=>{if(e instanceof Ws||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===qs?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===qs){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)As(e)})},Us=(e,t,n)=>{const r=n,s=Qt(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case li:case Js:case Xs:n<t.right.length&&Er(e,gr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&Ds(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Yr(o._searchMarker,t.index,-r+n),t};class js extends Hr{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach(e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)})}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];jr(e,e=>{const n=new Map,r=new Map;let s=this.target._start,i=null;const o={};let l="",c=0,a=0;const d=()=>{if(null!==i){let e=null;switch(i){case"delete":a>0&&(e={delete:a}),a=0;break;case"insert":("object"==typeof l||l.length>0)&&(e={insert:l},n.size>0&&(e.attributes={},n.forEach((t,n)=>{null!==t&&(e.attributes[n]=t)}))),l="";break;case"retain":c>0&&(e={retain:c},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=hn({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case li:case Js:this.adds(s)?this.deletes(s)||(d(),i="insert",l=s.content.getContent()[0],d()):this.deletes(s)?("delete"!==i&&(d(),i="delete"),a+=1):s.deleted||("retain"!==i&&(d(),i="retain"),c+=1);break;case Xs:this.adds(s)?this.deletes(s)||("insert"!==i&&(d(),i="insert"),l+=s.content.str):this.deletes(s)?("delete"!==i&&(d(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(d(),i="retain"),c+=s.length);break;case qs:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;bs(c,l)?null!==l&&s.delete(e):("retain"===i&&d(),bs(l,r.get(t)??null)?delete o[t]:o[t]=l)}}else if(this.deletes(s)){r.set(t,l);const e=n.get(t)??null;bs(e,l)||("retain"===i&&d(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(bs(n,l)?null!==n&&s.delete(e):("retain"===i&&d(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&d(),xs(n,s.content));break}}s=s.right}for(d();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}}),this._delta=t}return this._delta}}class Ls extends Xr{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??zr(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){}this._pending=null}_copy(){return new Ls}clone(){const e=new Ls;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new js(this,e,t);Qr(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??zr();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Xs&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?jr(this.doc,n=>{const r=new ws(null,this._start,0,new Map);for(let s=0;s<e.length;s++){const i=e[s];if(void 0!==i.insert){const o=t||"string"!=typeof i.insert||s!==e.length-1||null!==r.right||"\n"!==i.insert.slice(-1)?i.insert:i.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Is(n,this,r,o,i.attributes||{})}else void 0!==i.retain?Os(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&Us(n,r,i.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??zr();const r=[],s=new Map,i=this.doc;let o="",l=this._start;function c(){if(o.length>0){const e={};let t=!1;s.forEach((n,r)=>{t=!0,e[r]=n});const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const a=()=>{for(;null!==l;){if(yr(l,e)||void 0!==t&&yr(l,t))switch(l.content.constructor){case Xs:{const r=s.get("ychange");void 0===e||yr(l,e)?void 0===t||yr(l,t)?void 0!==r&&(c(),s.delete("ychange")):void 0!==r&&r.user===l.id.client&&"added"===r.type||(c(),s.set("ychange",n?n("added",l.id):{type:"added"})):void 0!==r&&r.user===l.id.client&&"removed"===r.type||(c(),s.set("ychange",n?n("removed",l.id):{type:"removed"})),o+=l.content.str;break}case li:case Js:{c();const e={insert:l.content.getContent()[0]};if(s.size>0){const t={};e.attributes=t,s.forEach((e,n)=>{t[n]=e})}r.push(e);break}case qs:yr(l,e)&&(c(),xs(s,l.content))}l=l.right}c()};return e||t?jr(i,n=>{e&&mr(n,e),t&&mr(n,t),a()},"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?jr(r,r=>{const s=ks(r,this,e,!n);n||(n={},s.currentAttributes.forEach((e,t)=>{n[t]=e})),Is(r,this,s,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?jr(r,r=>{const s=ks(r,this,e,!n);Is(r,this,s,t,n||{})}):this._pending.push(()=>this.insertEmbed(e,t,n||{}))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?jr(n,n=>{Us(n,ks(n,this,e,!0),t)}):this._pending.push(()=>this.delete(e,t))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?jr(r,r=>{const s=ks(r,this,e,!1);null!==s.right&&Os(r,this,s,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?jr(this.doc,t=>{as(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?jr(this.doc,n=>{ds(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return us(this,e)}getAttributes(){return hs(this)}_write(e){e.writeTypeRef(ni)}}class Ps{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??zr()}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==Ms&&t.constructor!==Rs||null===t._start)for(;null!==e;){const t=e.next;if(null!==t){e=t;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class Rs extends Xr{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Rs}clone(){const e=new Rs;return e.insert(0,this.toArray().map(e=>e instanceof Xr?e.clone():e)),e}get length(){return this.doc??zr(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new Ps(this,e)}querySelector(e){e=e.toUpperCase();const t=new Ps(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Y(new Ps(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){Qr(this,e,new $s(this,t,e))}toString(){return ns(this,e=>e.toString()).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),ts(this,s=>{r.insertBefore(s.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?jr(this.doc,n=>{ls(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)jr(this.doc,n=>{const r=e&&e instanceof Xr?e._item:e;is(n,this,r,t)});else{const n=this._prelimContent,r=null===e?0:n.findIndex(t=>t===e)+1;if(0===r&&null!==e)throw Ce("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?jr(this.doc,n=>{cs(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return es(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return ss(this,e)}slice(e=0,t=this.length){return Zr(this,e,t)}forEach(e){ts(this,e)}_write(e){e.writeTypeRef(si)}}class Ms extends Rs{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach((e,t)=>{this.setAttribute(t,e)}),this._prelimAttrs=null}_copy(){return new Ms(this.nodeName)}clone(){const e=new Ms(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),(t,n)=>{"string"==typeof t&&e.setAttribute(n,t)}),e.insert(0,this.toArray().map(e=>e instanceof Xr?e.clone():e)),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let s=0;s<r;s++){const r=n[s];t.push(r+'="'+e[r]+'"')}const s=this.nodeName.toLocaleLowerCase();return`<${s}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${s}>`}removeAttribute(e){null!==this.doc?jr(this.doc,t=>{as(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?jr(this.doc,n=>{ds(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return us(this,e)}hasAttribute(e){return fs(this,e)}getAttributes(e){return e?((e,t)=>{const n={};return e._map.forEach((e,r)=>{let s=e;for(;null!==s&&(!t.sv.has(s.id.client)||s.id.clock>=(t.sv.get(s.id.client)||0));)s=s.left;null!==s&&yr(s,t)&&(n[r]=s.content.getContent()[s.length-1])}),n})(this,e):hs(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),s=this.getAttributes();for(const e in s){const t=s[e];"string"==typeof t&&r.setAttribute(e,t)}return ts(this,s=>{r.appendChild(s.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(ri),e.writeKey(this.nodeName)}}class $s extends Hr{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach(e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)})}}class Ns extends vs{constructor(e){super(),this.hookName=e}_copy(){return new Ns(this.hookName)}clone(){const e=new Ns(this.hookName);return this.forEach((t,n)=>{e.set(n,t)}),e}toDOM(e=document,t={},n){const r=t[this.hookName];let s;return s=void 0!==r?r.createDom(this):document.createElement(this.hookName),s.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(s,this),s}_write(e){e.writeTypeRef(ii),e.writeKey(this.hookName)}}class Bs extends Ls{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new Bs}clone(){const e=new Bs;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map(e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort((e,t)=>e.key<t.key?-1:1),t.push({nodeName:n,attrs:r})}t.sort((e,t)=>e.nodeName<t.nodeName?-1:1);let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n}).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(oi)}}class Fs{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Ie()}mergeWith(e){return!1}write(e,t,n){throw Ie()}integrate(e,t){throw Ie()}}class Ws extends Fs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),_r(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class Hs{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Hs(this.content)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class Vs{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Vs(this.len)}splice(e){const t=new Vs(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){qn(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const zs=(e,t)=>new Xn({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Ks{constructor(e){e._item,this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new Ks(zs(this.doc.guid,this.opts))}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class Js{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Js(this.embed)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class qs{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new qs(this.key,this.value)}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class Gs{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Gs(this.arr)}splice(e){const t=new Gs(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}const Ys="development"===En("node_env");class Qs{constructor(e){this.arr=e,Ys&&vn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Qs(this.arr)}splice(e){const t=new Qs(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class Xs{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Xs(this.str)}splice(e){const t=new Xs(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"�",t.str="�"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const Zs=[e=>new ys,e=>new vs,e=>new Ls,e=>new Ms(e.readKey()),e=>new Rs,e=>new Ns(e.readKey()),e=>new Bs],ei=0,ti=1,ni=2,ri=3,si=4,ii=5,oi=6;class li{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new li(this.type._copy())}splice(e){throw Ie()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach(t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)}),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach(t=>{for(;null!==t;)t.gc(e,!0),t=t.left}),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const ci=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new ai(gr(r,s+n),t,gr(r,s+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&i.markDeleted(),t.keep&&(i.keep=!0),null!==t.redone&&(i.redone=gr(t.redone.client,t.redone.clock+n)),t.right=i,null!==i.right&&(i.right.left=i),e._mergeStructs.push(i),null!==i.parentSub&&null===i.right&&i.parent._map.set(i.parentSub,i),t.length=n,i};class ai extends Fs{constructor(e,t,n,r,s,i,o,l){super(e,l.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=s,this.parent=i,this.parentSub=o,this.redone=null,this.content=l,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=wr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=wr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===fr&&this.id.client!==this.parent.client&&this.parent.clock>=wr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Cr(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Er(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Ws||this.right&&this.right.constructor===Ws)this.parent=null;else if(this.parent){if(this.parent.constructor===fr){const e=Sr(t,this.parent);e.constructor===Ws?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===ai?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===ai&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Cr(e,e.doc.store,gr(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,s=new Set;for(;null!==t&&t!==this.right;){if(s.add(t),r.add(t),pr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(pr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(Sr(e.doc.store,t.origin)))break;r.has(Sr(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),_r(e.doc.store,this),this.content.integrate(e,this),Ar(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Ws(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:gr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&pr(e.origin,this.lastId)&&this.right===e&&pr(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach(t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))}),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),qn(e.deleteSet,this.id.client,this.id.clock,this.length),Ar(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Oe();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[kr(r,t.id.clock)]=n})(e,this,new Ws(this.id,this.length)):this.content=new Vs(this.length)}write(e,t){const n=t>0?gr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:H)|(null===r?0:W)|(null===s?0:32);if(e.writeInfo(i),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=(e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Oe()})(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===fr?(e.writeParentInfo(!1),e.writeLeftID(t)):Oe();null!==s&&e.writeString(s)}this.content.write(e,t)}}const di=(e,t)=>ui[31&t](e),ui=[()=>{Oe()},e=>new Vs(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new Gs(n)},e=>new Hs(e.readBuf()),e=>new Xs(e.readString()),e=>new Js(e.readJSON()),e=>new qs(e.readKey(),e.readJSON()),e=>new li(Zs[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Qs(n)},e=>new Ks(zs(e.readString(),e.readAny())),()=>{Oe()}];class hi extends Fs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Oe()}write(e,t){e.writeInfo(10),ae(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const fi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},pi="__ $YJS$ __";function gi(e,t,n){var r,s,i;if(!e.dx._allTables[t])return;const o=null===(i=null===(s=null===(r=e.table(t))||void 0===r?void 0:r.schema.yProps)||void 0===s?void 0:s.find(e=>e.prop===n))||void 0===i?void 0:i.updatesTable;return o&&e.dx._allTables[o]?e.table(o):void 0}fi[pi],fi[pi]=!0;const yi=new FinalizationRegistry(({cache:e,key:t})=>{delete e[t]});function mi(e){var t,n;return null!==(t=(n=e._novip)._docCache)&&void 0!==t?t:n._docCache={cache:{},get size(){return Object.keys(this.cache).length},find(e,t,n){const r=wi(e,t,n),s=this.cache[r];return s?s.deref():void 0},add(e){var t;const{parentTable:n,parentId:r,parentProp:s}=e.meta;if(!n||!s||null==r)throw new Error("Missing Dexie-related metadata in Y.Doc");const i=wi(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&yi.unregister(o),this.cache[i]=new WeakRef(e),yi.register(e,{cache:this.cache,key:i},e)},delete(e){yi.unregister(e);const t=wi(e.meta.parentTable,e.meta.parentId,e.meta.parentProp),n=this.cache[t];(null==n?void 0:n.deref())===e&&delete this.cache[t]}}}const vi=new WeakSet;function bi(e){if(vi.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function wi(e,t,n){return`${e}[${t}].${n}`}const{getByKeyPath:_i}=e.Dexie;let ki=null;function Si(e){ki=e}function xi(){}const Ei=new WeakMap;function Ci(){return e.Dexie.Events(null,"load","sync","error")}class Ii{static getOrCreateDocument(e,t,n,r){var s,i;const o=mi(e),l=null===(i=null===(s=e.table(t).schema.yProps)||void 0===s?void 0:s.find(e=>e.prop===n))||void 0===i?void 0:i.updatesTable;if(!l)throw new Error(`Updates table for ${t}.${n} not found`);return function(e,t,n,r,s,i){let o=t.find(n,i,r);return o||(o=new Xn({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",()=>{vi.add(o),t.delete(o)}),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=Ei.get(e);return r?(++r.refCount,null!=(null==t?void 0:t.gracePeriod)&&r.graceTimeout<t.gracePeriod&&(r.graceTimeout=t.gracePeriod),r.graceTimer&&(clearTimeout(r.graceTimer),r.graceTimer=null)):(r=new Ii(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Ei.set(e,r)),r}static release(e){if(!e||vi.has(e))return;const t=Ei.get(e);t?--t.refCount<=0&&(t.graceTimeout<0?t._release():t.graceTimer||(t.graceTimer=setTimeout(()=>{t.graceTimer=null,0===t.refCount&&t._release()},t.graceTimeout))):e.destroy()}_release(){this.doc&&Promise.resolve(Ii.on("beforeunload").fire(this)).finally(()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())})}static for(e){return Ei.get(e)}static get currentUpdateRow(){return ki}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise((t,n)=>{this.doc?this.doc.isLoaded?t():this._error?n(this._error):vi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",t),this.on("error",n),this.doc.on("destroy",()=>n(new e.Dexie.AbortError("Document was destroyed before loaded")))):n(new Error("No Y.Doc associated with this provider"))})),this._whenLoaded}get whenSynced(){return this._whenSynced||(this._whenSynced=new Promise((t,n)=>{this.doc?this.doc.isSynced?t():this._error?n(this._error):vi.has(this.doc)?n(new e.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",t),this.on("error",n),this.doc.on("destroy",()=>n(new e.Dexie.AbortError("Document was destroyed before synced")))):n(new Error("No Y.Doc associated with this provider"))})),this._whenSynced}constructor(t){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Ci(),this.doc=t,this.off=(e,t)=>{var n;return null===(n=this.on[e])||void 0===n?void 0:n.unsubscribe(t)},"dispose"in Symbol&&(this[Symbol.dispose]=()=>Ii.release(t)),t.on("load",()=>this.on("load").fire()),t.on("sync",e=>!1!==e&&this.on("sync").fire()),t.on("destroy",this.destroy.bind(this)),this.on("error",e=>{this._error=e});const{db:n,parentTable:r,parentId:s,updatesTable:i}=t.meta||{};if(!n||!r||!i)throw new Error("Missing Dexie-related metadata in Y.Doc. Documents need to be obtained through Y.Doc properties from dexie queries.");if(!n.table(r)||!n.table(i))throw new Error(`Table ${r} or ${i} not found in db`);bi(t),this.stopObserving=function(t,n,r,s,i,o){let l=0,c=!0;const a=e.liveQuery(()=>{bi(n);const t=r.table(i);return Promise.all([(l>0?t.where("i").between(l,1/0,!1).toArray().then(t=>t.filter(t=>0===e.cmp(t.k,o))):t.where({k:o}).toArray()).then(e=>e),r.table(s).where(":id").equals(o).toArray()])}).subscribe(([e,r])=>{e.length>0&&(l=e[e.length-1].i),0!==r.length?(bi(n),e.length>0&&jr(n,()=>{e.forEach(e=>{try{Si(e),lr(n,e.u)}finally{Si(null)}})},t,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()},e=>{t.on("error").fire(e)}),d=(e,n)=>{n!==t&&r.table(i).add({k:o,u:e,f:1}).then(e=>{e===l-1&&++l}).catch(e=>{t.on("error").fire(e)})},u=()=>{a.unsubscribe(),n.off("updateV2",d),n.off("destroy",u)};return n.on("updateV2",d),n.on("destroy",u),u}(this,t,n,r,i,s),Ii.on("new").fire(this)}destroy(){var e;Ei.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Ci(),this.cleanupHandlers.forEach(e=>e())}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Oi(t,n){return r(this,void 0,void 0,function*(){var s;const i={};let o,l=!1;for(const c of t)try{switch(c.type){case"u-s":{const e=gi(n,c.table,c.prop);if(e){const t={k:c.k,u:c.u};c.r&&(t.r=c.r,o=c.r),i[e.name]=yield e.add(t)}break}case"u-ack":{const e=gi(n,c.table,c.prop);e&&(yield n.transaction("rw",e,t=>r(this,void 0,void 0,function*(){let n=yield t.table(e.name).get(qt);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:qt}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})));break}case"u-reject":{const t=gi(n,c.table,c.prop);if(!t)break;const r=null===(s=yield t.get(c.i))||void 0===s?void 0:s.k;if(null!=r){yield n.transaction("rw",t,n=>(n.idbtrans._rejecting_y_ypdate=!0,t.where("i").aboveOrEqual(c.i).filter(t=>0===e.cmp(t.k,r)&&!(1&~(t.f||0))).delete()));const s=Ii.getDocCache(n.dx).find(c.table,r,c.prop);s&&s.destroy()}break}case"in-sync":{const e=Ii.getDocCache(n.dx).find(c.table,c.k,c.prop);e&&!e.isSynced&&e.emit("sync",[!0,e]);break}case"y-complete-sync-done":o=c.yServerRev;break;case"outdated-server-rev":l=!0}}catch(e){}return{receivedUntils:i,resyncNeeded:l,yServerRevision:o}})}Ii.on=e.Dexie.Events(null,{new:[function(e,t){return e===xi?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===xi?t:function(){var n=e.apply(this,arguments);if(n&&"function"==typeof n.then){for(var r=this,s=arguments.length,i=new Array(s);s--;)i[s]=arguments[s];return n.then(function(){return t.apply(r,i)})}return t.apply(this,arguments)}}]}),Ii.getDocCache=mi,e.Dexie.DexieYProvider?Ii=e.Dexie.DexieYProvider||Ii:e.Dexie.DexieYProvider=Ii;function Di(t,n,s){return r(this,arguments,void 0,function*(t,n,{yDownloadedRealms:s,realms:c}){if(s&&c&&c.every(e=>"*"===s[e]))return;const a=yield rt(t),d={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(d.Authorization=`Bearer ${a.accessToken}`);const u=yield fetch(`${n}/y/download`,{body:Lt.stringify({downloadedRealms:s||{}}),method:"POST",headers:d,credentials:"include"});if(!u.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${u.status}`);yield async function(e,...t){let n=e();for(let e=0;e<t.length;e++)n=t[e](n);for await(const e of n);}(function(e){return async function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=await t.read();if(e)return;yield n}}finally{t.releaseLock()}}}(u),Je,function(s){return o(this,arguments,function*(){var o,c,a,d;let u=null,h=null,f=null,p=[];function g(e){return r(this,void 0,void 0,function*(){const r=p[p.length-1];if(p.length>0){if(!u||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const e=gi(t,h,f);e&&(yield e.bulkAdd(p)),p=[]}u&&(h&&f&&r||e)&&(yield t.$syncState.update("syncState",t=>{const n=t.yDownloadedRealms||{};n[u]=e?"*":{tbl:h,prop:f,key:r.k},t.yDownloadedRealms=n}))})}try{try{for(var y,m=!0,v=l(s);!(o=(y=yield i(v.next())).done);m=!0){d=y.value,m=!1;const e=new Te(d);for(;je(e);)switch(Pe(e)){case 1:yield i(g(!0)),u=$e(e);break;case 2:yield i(g(!1)),h=$e(e),f=$e(e);break;case 3:{const t=We(e),n=Le(e);p.push({k:t,u:n});break}}yield i(g(!1))}}catch(e){c={error:e}}finally{try{m||o||!(a=v.return)||(yield i(a.call(v)))}finally{if(c)throw c.error}}yield i(g(!0))}catch(t){throw t instanceof e.DexieError||(yield i(g(!1))),t}})})})}const Ai="currentSyncWorker";function Ti(e,t,n,s){return Ui(e,t,n,s).then(t=>((null==s?void 0:s.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t)).catch(i=>r(this,void 0,void 0,function*(){return(null==s?void 0:s.justCheckIfNeeded)?Promise.reject(i):Ht&&(null==s?void 0:s.retryImmediatelyOnFetchError)&&"TypeError"===(null==i?void 0:i.name)&&/fetch/.test(null==i?void 0:i.message)?(e.syncStateChangedEvent.next({phase:"error",error:i}),yield new Promise(e=>setTimeout(e,500)),yield Ti(e,t,n,Object.assign(Object.assign({},s),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:Ht?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))}function Ui(e,t,n){return r(this,arguments,void 0,function*(e,t,n,{isInitialSync:s,cancelToken:i,justCheckIfNeeded:o,purpose:l}={isInitialSync:!1}){var a;if(!(null===(a=e.cloud.options)||void 0===a?void 0:a.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:d}=t,u=yield e.getCurrentUser(),h=u.isLoggedIn?k(e):[],f=h.map(t=>e.table(S(t.name))),p=yield e.getPersistedSyncState(),g=u.isLoggedIn,y=g?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return k(e).filter(e=>!n.includes(e.name))}(e,p):[];Wt(i);const m=y.length>0;if(m){if(o)return!0;yield e.transaction("rw",y,e=>r(this,void 0,void 0,function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=new Set(n||[]);for(const n of e)"members"===n.name?yield n.toCollection().modify(e=>{r.has(e.realmId)||e.userId&&e.userId!==c.userId||(e.userId=t.userId)}):"roles"===n.name||("realms"===n.name?yield n.toCollection().modify(e=>{r.has(e.realmId)||void 0!==e.owner&&e.owner!==c.userId||(e.owner=t.userId)}):yield n.toCollection().modify(e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==c.userId||(e.owner=t.userId),e.realmId&&e.realmId!==c.userId||(e.realmId=t.userId))}))})}(y,u,null==p?void 0:p.realms)})),Wt(i)}const[v,b,w,{yMessages:_,lastUpdateIds:E}]=yield e.transaction("r",e.tables,()=>r(this,void 0,void 0,function*(){const t=yield e.getPersistedSyncState();let s=yield e.$baseRevs.toArray();s=s.filter(e=>h.some(t=>t.name===e.tableName));let o=yield I(f,e);const l=yield function(e,t){return r(this,void 0,void 0,function*(){const n=[],r={};for(const s of t)if(s.schema.yProps)for(const t of s.schema.yProps){const i=e.table(t.updatesTable),o=yield i.get(qt),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),d=yield Gt(i,a);d.length>0&&(r[i.name]=d[d.length-1].i);const u={};for(const e of d){const t=!(1&~(e.f||0));if(t&&e.i<l)continue;const n=JSON.stringify(e.k)+"/"+t;let r=u[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(u[n]=r={i:e.i,k:e.k,isLocal:t,u:[]},r.u.push(e.u))}for(const{k:e,isLocal:r,u:i,i:o}of Object.values(u)){const l=1===i.length?i[0]:$r(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=Rr(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}})}(e,h);if(Wt(i),m){const e=[...(null==p?void 0:p.realms)||[],...(null==p?void 0:p.inviteRealms)||[]],c=yield function(e,t,n,s){return r(this,void 0,void 0,function*(){const i=`upload-${O(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(s||[]);return(yield Promise.all(e.map(e=>r(this,void 0,void 0,function*(){const{extractKey:r}=e.core.schema.primaryKey;if(!r)return{table:e.name,muts:[]};const s=n[e.name],l=(null==s?void 0:s.generatedGlobalId)?e.filter(e=>{return r(e),!o.has(e.realmId||"")&&(t=r(e),!(n=null==s?void 0:s.idPrefix)||"string"==typeof t&&t.startsWith(n));var t,n}):e.filter(e=>{const t=r(e);return!o.has(e.realmId||"")&&j(t)}),c=yield l.toArray();if(c.length>0){const n={type:"upsert",values:c,keys:c.map(r),userId:t.userId,txid:i};return{table:e.name,muts:[n]}}return{table:e.name,muts:[]}})))).filter(e=>e.muts.length>0)}return[]})}(y,u,n,e);return Wt(i),o=o.concat(c),[o,t,s,l]}return[o,t,s,l]})),C=v.some(e=>e.muts.some(e=>e.keys.length>0))||_.some(e=>"u-c"===e.type);if(o)return C;if("push"===l&&!C)return!1;const D=zt(v,null==b?void 0:b.latestRevisions),A=(null==b?void 0:b.clientIdentity)||T(16);Wt(i);const U=yield Ft(v,_,b,w,e,d,n,A,u),{done:L,newSyncState:P}=yield e.transaction("rw",e.tables,t=>r(this,void 0,void 0,function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))U.schema[e]&&(n[e]=U.schema[e]);yield e.$syncState.put(n,"schema");const s=yield I(f,e,{since:D});for(const t of f){const n=x(t.name);if(s.some(e=>e.table===n&&e.muts.length>0)){if(D[n]){const r=D[n]||0;yield Promise.all([t.where("rev").belowOrEqual(r).delete(),e.$baseRevs.where(":id").between([n,-1/0],[n,r+1],!0,!0).reverse().offset(1).delete()])}}else yield Promise.all([t.clear(),e.$baseRevs.where({tableName:n}).delete()])}zt(s,D),yield Vt(e,n,D,U.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=new Set,s=new Set,i=n?n.realms:[],o=n?n.inviteRealms:[],l=new Set(t.realms),c=new Set(t.realms.concat(t.inviteRealms));for(const e of i)l.has(e)||(s.add(e),c.has(e)||r.add(e));for(const e of o.concat(i))c.has(e)||r.add(e);if(r.size>0||s.size>0){const t=k(e);for(const e of t){let t=["realms","members","roles"].includes(e.name)?r:s;0!==t.size&&(e.schema.indexes.some(e=>"realmId"===e.keyPath||Array.isArray(e.keyPath)&&"realmId"===e.keyPath[0])?yield e.where("realmId").anyOf([...t]).delete():yield e.filter(e=>!!(null==e?void 0:e.realmId)&&t.has(e.realmId)).delete())}}if(s.size>0&&(null==n?void 0:n.yDownloadedRealms))for(const e of s)delete n.yDownloadedRealms[e]})}(e,U,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:A};g&&(o.syncedTables=h.map(e=>e.name).concat(y.map(e=>e.name))),o.latestRevisions=D,o.remoteDbId=U.dbId,o.initiallySynced=!0,o.realms=U.realms,o.inviteRealms=U.inviteRealms,o.serverRevision=U.serverRevision,o.yServerRevision=U.serverRevision,o.timestamp=new Date,delete o.error;const l=ji(U.changes,s);if(yield Jt(l,e),U.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:s}=yield Oi(U.yMessages,e);s&&(o.yServerRevision=s),yield function(e,t,n){return r(this,void 0,void 0,function*(){var s,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(s=a[t])&&void 0!==s||(a[t]={}),a[t].unsentFrom=n+1;for(const[e,n]of Object.entries(t))null!==(i=a[e])&&void 0!==i||(a[e]={}),a[e].receivedUntil=n;const d=Object.values(n.dx._dbSchema).filter(e=>e.yProps).map(e=>e.yProps.map(e=>e.updatesTable)).flat();for(const e of d){const t=a[e],s=null!==(o=null==t?void 0:t.unsentFrom)&&void 0!==o?o:1,i=null!==(c=null!==(l=null==t?void 0:t.receivedUntil)&&void 0!==l?l:(yield n.table(e).where("i").between(1,1/0).reverse().limit(1).primaryKeys())[0])&&void 0!==c?c:0;yield n.transaction("rw",e,()=>r(this,void 0,void 0,function*(){const t=yield n.table(e).get(qt);t?(t.unsentFrom=Math.max(s,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:qt,unsentFrom:s,receivedUntil:i})}))}})}(E,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===s.length,newSyncState:o}}));if(!L)return yield Bt(e),yield Ui(e,t,n,{isInitialSync:s,cancelToken:i});const R=Object.values(n).some(e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length}),M=!!U.yMessages;if(R&&M)try{yield Di(e,d,P)}catch(e){}return e.syncCompleteEvent.next(),!1})}function ji(e,t){const n={};R(n,e);const r={};return R(r,t),function(e,t){for(const[n,r]of Object.entries(t))for(const[t,s]of Object.entries(r))switch(s.type){case"ups":{const r=e[n]?.[t];if(r)switch(r.type){case"ups":case"upd":delete e[n][t]}}break;case"del":delete e[n]?.[t];break;case"upd":{const r=e[n]?.[t];if(r)switch(r.type){case"ups":for(const[e,t]of Object.entries(s.mod))A(r.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(s.mod))delete r.mod[e]}break}}}(n,r),function(e,t){const n={};for(const[t,r]of Object.entries(e))for(const[e,s]of Object.entries(r)){const r=n[t]||(n[t]={});(r[s.type]||(r[s.type]=[])).push({key:e,...s})}const r=[];for(const[e,s]of Object.entries(n)){const n={table:e,muts:[]};for(const[e,r]of Object.entries(s))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 Li(s){const i=[],o=new t.BehaviorSubject(!0),l=new t.BehaviorSubject(null);let c=!1,a=new Array(10).fill(0);return l.subscribe(()=>r(this,void 0,void 0,function*(){if(!c&&i.length>0){c=!0,a.shift(),a.push(Date.now()),o.next(!1);try{yield function(){return r(this,void 0,void 0,function*(){for(var o,l,c,a,d,u;i.length>0;){const h=i.shift();try{yield t.firstValueFrom(s.cloud.syncState.pipe(n.filter(({phase:e})=>"in-sync"===e||"error"===e)));const i=s.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const t=s.cloud.currentUser.value,n=yield it(s.cloud.options.databaseUrl,t);yield s.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data});break;case"realm-added":(null===(o=null==i?void 0:i.realms)||void 0===o?void 0:o.includes(h.realm))||(null===(l=null==i?void 0:i.inviteRealms)||void 0===l?void 0:l.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-accepted":(null===(c=null==i?void 0:i.realms)||void 0===c?void 0:c.includes(h.realm))||(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realm-removed":((null===(a=null==i?void 0:i.realms)||void 0===a?void 0:a.includes(h.realm))||(null===(d=null==i?void 0:i.inviteRealms)||void 0===d?void 0:d.includes(h.realm)))&&(yield s.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield s.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(u=s.cloud.syncState.value)||void 0===u?void 0:u.phase)){y(s,"pull");break}yield s.transaction("rw",s.dx.tables,t=>r(this,void 0,void 0,function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;const[n,r,i]=yield Promise.all([s.getSchema(),s.getPersistedSyncState(),s.getCurrentUser()]);if(!r||!n||!i)return;if(h.baseRev!==r.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof r.serverRevision&&"object"!=typeof r.serverRevision||y(s,"pull"));if((yield e.waitFor(_(r)))!==h.realmSetHash)return void y(s,"pull");let o=[];if(i.isLoggedIn){const e=k(s).map(e=>s.table(S(e.name)));o=yield I(e,s)}if(h.changes.length>0){const e=ji(h.changes,o);yield Jt(e,s)}r.latestRevisions=zt(o,r.latestRevisions),r.serverRevision=h.newRev,yield Vt(s,n,r.latestRevisions,h.newRev),yield s.$syncState.put(r,"syncState")}))}}catch(e){}}})}()}finally{a[a.length-1]-a[0]<1e4&&(yield new Promise(e=>setTimeout(e,1e3))),c=!1,o.next(!0)}}})),{enqueue:function(e){i.push(e),l.next(null)},readyToServe:o}}const Pi=new WeakMap,Ri={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Mi=0;function $i(e){"vip"in e&&(e=e.vip);let n=Pi.get(e.cloud);if(!n){const r=new t.Subject;let s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`);r.id=++Mi;let o=!1;n={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>n.$logins.toArray().then(e=>e.find(e=>e.isLoggedIn)||c),getPersistedSyncState:()=>n.$syncState.get("syncState"),getSchema:()=>n.$syncState.get("schema").then(e=>{if(e)for(const t of n.tables)t.schema.primKey&&t.schema.primKey.keyPath&&e[t.name]&&(e[t.name].primaryKey=Ni(t.schema.primKey.keyPath));return e}),getOptions:()=>n.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new f(`syncstatechanged-${e.name}`),i=new f(`synccomplete-${e.name}`)}};Object.assign(n,l),n.messageConsumer=Li(n),n.messageProducer=new t.Subject,Pi.set(e.cloud,n)}return n}function Ni(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}const Bi=new WeakMap;class Fi{constructor(e,t){Bi.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then(n=>new Fi(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)}))}save(){return r(this,void 0,void 0,function*(){Bi.get(this).table("$logins").put(this)})}}function Wi(e,n){return t.firstValueFrom(t.from(e).pipe(t.filter(n)))}function Hi(e){return r(this,void 0,void 0,function*(){const t=yield Vi(e);if(t){if(!(yield function(e,t,n){return r(this,void 0,void 0,function*(){const r=[{type:"warning",messageCode:"LOGOUT_CONFIRMATION",message:"{numUnsyncedChanges} unsynced changes will get lost!\n Logout anyway?",messageParams:{currentUserId:t,numUnsyncedChanges:n.toString()}}];return yield Xe(e,{type:"logout-confirmation",title:"Confirm Logout",alerts:r,fields:{},submitLabel:"Confirm logout",cancelLabel:"Cancel"}).then(()=>!0).catch(()=>!1)})}(e.cloud.userInteraction,e.cloud.currentUserId,t)))throw new Error("User cancelled logout due to unsynced changes");yield Vi(e,{deleteUnsyncedData:!0})}})}function Vi(e){return r(this,arguments,void 0,function*(e,{deleteUnsyncedData:t=!1}={}){const[n,s]=yield e.dx.transaction("rw",e.dx.tables,n=>r(this,void 0,void 0,function*(){const r=n.idbtrans;r.disableChangeTracking=!0,r.disableAccessControl=!0;const s=n.storeNames.filter(e=>e.endsWith("_mutations")),i=(yield Promise.all(s.map(e=>n.table(e).count()))).reduce((e,t)=>e+t,0);if(i>0&&!t)return[i,!1];e.$syncState.delete("syncState");for(const t of e.dx.tables)"$jobs"!==t.name&&"$syncState"!==t.name&&t.clear();return[i,!0]}));return s&&(yield Wi(e.cloud.currentUser,e=>e.userId===c.userId),yield e.cloud.sync({purpose:"pull",wait:!0})),n})}const zi={access_denied:"Access was denied by the authentication provider.",invalid_state:"The authentication response could not be verified. Please try again.",email_not_verified:"Your email address must be verified before you can log in.",expired_code:"The authentication code has expired. Please try again.",provider_error:"An error occurred with the authentication provider.",network_error:"A network error occurred during authentication. Please check your connection and try again."};class Ki extends Error{constructor(e,t,n){super(n||zi[e]),this.name="OAuthError",this.code=e,this.provider=t}get userMessage(){return zi[this.code]||this.message}}const Ji={providers:[],otpEnabled:!0};function qi(e){"undefined"!=typeof sessionStorage&&sessionStorage.setItem("dexie-cloud-oauth-provider",e.provider);const t=function(e){const t=new URL(`${e.databaseUrl}/oauth/login/${e.provider}`),n=e.redirectUri||("undefined"!=typeof window?window.location.href:"");return n&&t.searchParams.set("redirect_uri",n),t.toString()}(e);window.location.href=t}function Gi(t){const{userInteraction:n}=t.cloud;return function(s){return r(this,arguments,void 0,function*({public_key:s,hints:i}){var o,l;let c;const a=null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl;if(!a)throw new Error("No database URL given.");if((null==i?void 0:i.oauthCode)&&i.provider)return yield function(e){return r(this,void 0,void 0,function*(){const{databaseUrl:t,code:n,publicKey:r,scopes:s=["ACCESS_DB"]}=e,i={grant_type:"authorization_code",code:n,public_key:r,scopes:s};try{const e=yield fetch(`${t}/token`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i),mode:"cors"});if(!e.ok){if(400===e.status||401===e.status)try{const t=yield e.json();if("error"===t.type){if("INVALID_OTP"===t.messageCode)throw new Ki("expired_code",void 0,t.message);throw new qe(t)}}catch(e){if(e instanceof Ki||e instanceof qe)throw e}const t=yield e.text().catch(()=>e.statusText);throw new Ki("provider_error",void 0,`Token exchange failed: ${e.status} ${t}`)}const n=yield e.json();if("error"===n.type)throw new qe(n);if("tokens"!==n.type)throw new Ki("provider_error",void 0,`Unexpected response type: ${n.type}`);return n}catch(e){if(e instanceof Ki||e instanceof qe)throw e;if(e instanceof TypeError)throw new Ki("network_error");throw e}})}({databaseUrl:a,code:i.oauthCode,publicKey:s,scopes:["ACCESS_DB"]});if(null==i?void 0:i.provider)throw Yi(t,i.provider),new nt(i.provider);if("demo"===(null==i?void 0:i.grant_type)){c={demo_user:yield et(n,"Enter a demo user email",(null==i?void 0:i.email)||(null==i?void 0:i.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:s}}else if((null==i?void 0:i.otpId)&&i.otp)c={grant_type:"otp",otp_id:i.otpId,otp:i.otp,scopes:["ACCESS_DB"],public_key:s};else{const o=!1!==(null===(l=t.cloud.options)||void 0===l?void 0:l.socialAuth),d=yield function(e){return r(this,arguments,void 0,function*(e,t=!0){if(!t)return Ji;try{const t=yield fetch(`${e}/auth-providers`,{method:"GET",headers:{Accept:"application/json"},mode:"cors"});return 404===t.status?Ji:t.ok?yield t.json():Ji}catch(e){return Ji}})}(a,o);if(d.providers.length>0){const s=yield function(t,n,s){return r(this,arguments,void 0,function*(t,n,r,s="Choose login method",i=[]){const o=[...yield Promise.all(n.map(Qe))];return r&&o.push({name:"otp",value:"email",displayName:"Continue with email",iconSvg:'<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2"><rect x="2" y="4" width="20" height="16" rx="2"/><path d="M22 6L12 13 2 6"/></svg>',styleHint:"otp"}),new Promise((n,r)=>{const l={type:"generic",title:s,alerts:i,options:o,fields:{},submitLabel:"",cancelLabel:"Cancel",onSubmit:e=>{t.next(void 0),n("otp"in e?{type:"otp"}:"provider"in e?{type:"provider",provider:e.provider}:{type:"otp"})},onCancel:()=>{t.next(void 0),r(new e.AbortError("User cancelled"))}};t.next(l)})})}(n,d.providers,d.otpEnabled,"Sign in");if("provider"===s.type)throw Yi(t,s.provider),new nt(s.provider)}const u=yield et(n,"Enter email address",null==i?void 0:i.email);c=/@demo.local$/.test(u)?{demo_user:u,grant_type:"demo",scopes:["ACCESS_DB"],public_key:s}:{email:u,grant_type:"otp",scopes:["ACCESS_DB"]}}const d=yield fetch(`${a}/token`,{body:JSON.stringify(c),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==d.status){const e=yield d.text();throw yield Ze(n,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch(()=>{}),new Rt(d,e)}const u=yield d.json();if("tokens"===u.type||"error"===u.type)return u;if("otp"===c.grant_type&&"email"in c){if("otp-sent"!==u.type)throw new Error(`Unexpected response from ${a}/token`);const e=yield tt(n,c.email),t=Object.assign(Object.assign({},c),{otp:e||"",otp_id:u.otp_id,public_key:s});let r=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===r.status;){const e=yield r.text();t.otp=yield tt(n,c.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),r=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==r.status){const e=yield r.text();throw new Rt(r,e)}return yield r.json()}throw new Error(`Unexpected response from ${a}/token`)})}}function Yi(e,t){var n,r;const s=null===(n=e.cloud.options)||void 0===n?void 0:n.databaseUrl;if(!s)throw new Error("No database URL given.");qi({databaseUrl:s,provider:t,redirectUri:(null===(r=e.cloud.options)||void 0===r?void 0:r.oauthRedirectUri)||("undefined"!=typeof window?window.location.href:void 0)})}function Qi(e,...t){globalThis.console[e](...t)}function Xi(e,t){return r(this,void 0,void 0,function*(){var n;const s=yield e.getCurrentUser(),i=s.userId;if(s.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=s.license)||void 0===n?void 0:n.status)||"ok")&&s.accessToken&&(!s.accessTokenExpiration||s.accessTokenExpiration.getTime()>Date.now()))return!1;if(s.refreshToken&&(!s.refreshTokenExpiration||s.refreshTokenExpiration.getTime()>Date.now()))return yield rt(e),!1}const o=new Fi(e,{claims:{},lastLogin:new Date(0)});try{yield st(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||Gi(e),e.cloud.userInteraction,t)}catch(e){if("OAuthRedirectError"===e.name)return!1;throw e}return i!==c.userId&&o.userId!==i&&(yield Hi(e)),yield function(e,t){return r(this,void 0,void 0,function*(){const n=e.table("$logins");yield e.transaction("rw",n,e=>r(this,void 0,void 0,function*(){const e=yield n.toArray();yield Promise.all(e.filter(e=>e.userId!==t.userId&&e.isLoggedIn).map(e=>(e.isLoggedIn=!1,n.put(e)))),t.isLoggedIn=!0,t.lastLogin=new Date;try{yield t.save()}catch(e){try{"DataCloneError"===e.name&&(Qi("debug","Login context property names:",Object.keys(t)),Qi("debug","Login context property names:",Object.keys(t)),Qi("debug","Login context:",t),Qi("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})),yield Wi(e.cloud.currentUser,e=>e.userId===t.userId)})}(e,o),y(e,"pull"),o.userId!==i})}const Zi="undefined"!=typeof InstallTrigger,eo="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),to=eo?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,no=eo&&to<=605||Zi,ro="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:so}={};function io(e){return so.call(e).slice(8,-1)}function oo(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}function lo(e,t){return(1&t?e[0].toUpperCase():e[0].toLowerCase())+(2&t?e[1].toUpperCase():e[1].toLowerCase())+(4&t?e[2].toUpperCase():e[2].toLowerCase())}const co=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;function ao(e){return e>="A"&&e<="Z"}let uo=0;function ho(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();uo>=s?++uo:uo=s,r[0]=uo/1099511627776,r[1]=uo/4294967296,r[2]=uo/16777216,r[3]=uo/65536,r[4]=uo/256,r[5]=uo;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+mt(new Uint8Array(n.buffer))+(t||"")}function fo(t){return{stack:"dbcore",name:"idGenerationMiddleware",level:1,create:n=>Object.assign(Object.assign({},n),{table:r=>{const s=n.table(r);return Object.assign(Object.assign({},s),{mutate:n=>{var i,o;const l=n.trans;if("versionchange"===l.mode&&(l.disableChangeTracking=!0,l.disableAccessControl=!0),l.disableChangeTracking)return s.mutate(n);if("add"===n.type||"put"===n.type){const l=null===(i=t.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=t.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!t.initiallySynced){const e=oo(s.schema.primaryKey,n);return s.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 s.mutate(n)})}return function(n,i){let o=null;const l=oo(s.schema.primaryKey,n);return l.forEach((c,a)=>{if(void 0===c){const r=n.values[a].realmId||t.cloud.currentUserId,c=r.substr(r.length-3);l[a]=ho(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=e.deepClone(o[a]),e.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new e.ConstraintError(`The ID "${c}" is not valid for table "${r}". Primary '@' keys requires the key to be prefixed with "${i}" (or "#${i}).\nIf you want to generate IDs programmatically, remove '@' from the schema to get rid of this constraint. Dexie Cloud supports custom IDs as long as they are random and globally unique.`)}),s.mutate(Object.assign(Object.assign({},n),{keys:l,values:o||n.values}))}(n,l.idPrefix)}if(null==l?void 0:l.markedForSync){oo(s.schema.primaryKey,n).forEach((t,n)=>{if(!j(t)){const n=Array.isArray(t)?t.map(io).join(","):io(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 s.mutate(n)}})}})}}let po=0;function go(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]}),i=s.length,o=(i>0?s[i-1].then(()=>e(n),()=>e(n)):e(n)).finally(()=>{r.splice(r.indexOf(o))});return r.push(o),o}}function yo(e,t){return function(n){const{readers:r,writers:s}=n.trans[t]||(n.trans[t]={writers:[],readers:[]});let i=(s.length>0?s[s.length-1].then(()=>e(n),()=>e(n)):r.length>0?(o=r,new Promise(e=>{0===o.length&&e([]);let t=o.length;const n=new Array(t);o.forEach((r,s)=>Promise.resolve(r).then(e=>n[s]={status:"fulfilled",value:e},e=>n[s]={status:"rejected",reason:e}).then(()=>--t||e(n)))})).then(()=>e(n)):e(n)).finally(()=>{s.shift()});var o;return s.push(i),i}}const mo=new t.BehaviorSubject(new Set);function vo(e){var t,n,r,s;return(null===(t=e.cloud.options)||void 0===t?void 0:t.disableEagerSync)||"ok"!==(null===(r=null===(n=e.cloud.currentUser.value)||void 0===n?void 0:n.license)||void 0===r?void 0:r.status)||!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl)}function bo({currentUserObservable:t,db:n}){return{stack:"dbcore",name:"MutationTrackingMiddleware",level:1,create:r=>{const s=new Set(r.schema.tables.map(e=>e.name)),i=r.schema.tables.filter(e=>!/^\$/.test(e.name)),o=new Map;for(const e of i){const t=`$${e.name}_mutations`;s.has(t)&&o.set(e.name,r.table(t))}return Object.assign(Object.assign({},r),{transaction:(e,s)=>{let i;if("readwrite"===s){const t=e.filter(e=>{var t,r;return null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e])||void 0===r?void 0:r.markedForSync}).map(e=>S(e));i=r.transaction([...e,...t],s)}else i=r.transaction(e,s);if("readwrite"===s){i.txid=O(16),i.opCount=0,i.currentUser=t.value,mo.value.add(i),mo.next(mo.value);const e=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",e),i.removeEventListener("abort",e),mo.value.delete(i),mo.next(mo.value)},r=()=>{i.mutationsAdded&&!vo(n)&&y(n,"push"),e()};i.addEventListener("complete",r),i.addEventListener("error",e),i.addEventListener("abort",e)}return i},table:t=>{const s=r.table(t);if(/^\$/.test(t))return t.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===t?Object.assign(Object.assign({},s),{mutate:e=>s.mutate(e).then(t=>(e.trans.mutationsAdded=!0,t)).catch(e=>Promise.reject(e))}):s;const{schema:i}=s,l=o.get(t);return l?function(e){const t="$lock"+ ++po;return Object.assign(Object.assign({},e),{count:go(e.count,t),get:go(e.get,t),getMany:go(e.getMany,t),openCursor:go(e.openCursor,t),query:go(e.query,t),mutate:yo(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:e=>{var r,o,l;const a=e.trans;return a.txid?a.disableChangeTracking?s.mutate(e):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[t])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===e.type?s.query({query:{range:e.range,index:i.primaryKey},trans:e.trans,values:!1}).then(t=>c({type:"delete",keys:t.result,trans:e.trans,criteria:{index:null,range:e.range}})):c(e):s.mutate(e):s.mutate(e)}})):s;function c(r){var o,c;const a=r.trans,d=null===(c=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===c?void 0:c[t],{txid:u,currentUser:{userId:h}}=a,{type:f}=r,p=++a.opCount;function g(e){if(!d)return e;let t=e;for(const n of Object.keys(e))d.some(e=>n===e||n.startsWith(e+"."))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return s.mutate(r).then(t=>{var n;const{numFailures:s,failures:o}=t;let c="delete"===f?r.keys:t.results,y="values"in r?r.values:[],m="changeSpec"in r?r.changeSpec:void 0,v="updates"in r?r.updates:void 0,b=!(!v||!("upsert"in r))&&r.upsert;if(s&&(c=c.filter((e,t)=>!o[t]),y=y.filter((e,t)=>!o[t])),d){if(y=y.map(e=>{const t=Object.assign({},e);for(const e of d)delete t[e];return t}),m&&(m=g(m),0===Object.keys(m).length))return t;if(v){let t=v.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new e.RangeSet;let s=!1;if(!b){for(let e=0,i=t.length;e<i;++e)Object.keys(t[e]).length>0?(n.keys.push(v.keys[e]),n.changeSpecs.push(t[e]),r.addKey(v.keys[e])):s=!0;if(v=n,s){let e=[],t=[];for(let n=0,s=c.length;n<s;++n)r.hasKey(c[n])&&(e.push(c[n]),t.push(y[n]));c=e,y=t}}}}const w=Date.now();let _="criteria"in r&&r.criteria?Object.assign(Object.assign({},r.criteria),{index:r.criteria.index===i.primaryKey.keyPath?null:r.criteria.index}):void 0;if(d&&(null==_?void 0:_.index)){const e=null===(n=i.indexes.find(e=>e.name===_.index))||void 0===n?void 0:n.keyPath;(e?"string"==typeof e?[e]:e:[]).some(e=>null==d?void 0:d.includes(e))&&(_=void 0)}const k="delete"===r.type?{type:"delete",ts:w,opNo:p,keys:c,criteria:_,txid:u,userId:h}:"add"===r.type?{type:"insert",ts:w,opNo:p,keys:c,txid:u,userId:h,values:y}:b&&v?{type:"upsert",ts:w,opNo:p,keys:c,values:y,changeSpecs:v.changeSpecs.filter((e,t)=>!o[t]),txid:u,userId:h}:_&&m?{type:"modify",ts:w,opNo:p,keys:c,criteria:_,changeSpec:m,txid:u,userId:h}:m?{type:"update",ts:w,opNo:p,keys:c,changeSpecs:c.map(()=>m),txid:u,userId:h}:v?{type:"update",ts:w,opNo:p,keys:v.keys,changeSpecs:v.changeSpecs,txid:u,userId:h}:{type:"upsert",ts:w,opNo:p,keys:c,values:y,txid:u,userId:h};return"isAdditionalChunk"in r&&r.isAdditionalChunk&&(k.isAdditionalChunk=!0),c.length>0||_?l.mutate({type:"add",trans:a,values:[k]}).then(()=>(a.mutationsAdded=!0,t)):t})}}})}}}function wo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},Ri),n);Object.keys(Ri).forEach(e=>{const t=i[e];if(null==t)throw new Error(`Cannot delete table ${e} as it is needed for access control of Dexie Cloud`);if(!n[e])return;const r=t.split(",").map(e=>e.trim()),s=Ri[e].split(",").map(e=>e.trim()),o=new Set(r.map(e=>e.replace(/([&*]|\+\+)/g,"")));if(r[0]!==s[0])throw new Error(`Cannot override primary key of table ${e}. Please declare it as {${e}: ${JSON.stringify(Ri[e])}`);for(let t=1;t<s.length;++t){const n=s[t];o.has(n.replace(/([&*]|\+\+)/g,""))||(i[e]+=`,${n}`)}});const o=t.cloud.schema||(t.cloud.schema={}),l=new Set;Object.keys(i).forEach(e=>{var t;const n=null===(t=i[e])||void 0===t?void 0:t.trim(),r=o[e]||(o[e]={});null!=n?(/^\@/.test(n)&&(i[e]=i[e].substr(1),r.generatedGlobalId=!0,r.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,r=e.length;t<r&&n.length<3;++t)(co.test(e[t])||ao(e[t]))&&(n+=e[t].toLowerCase());for(;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;)r=lo(n,e),++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,l),l.add(r.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",r.markedForSync=!0),r.deleted&&(r.deleted=!1)):(r.deleted=!0,r.markedForSync=!1,i[`$${e}_mutations`]=null)});const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(s=t.yProps)||void 0===s?void 0:s.length){const n=o[e];n&&(n.yProps=t.yProps.map(e=>e.prop))}return c}}function _o(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,n):n()}const ko=new t.BehaviorSubject(!0),So=new t.BehaviorSubject(!0);ko.pipe(n.switchMap(e=>e?t.of(!0):t.of(!1).pipe(n.delay(2e4))),n.distinctUntilChanged()).subscribe(So);const xo="undefined"!=typeof document?t.fromEvent(document,"visibilitychange"):t.of({}),Eo=xo.pipe(n.filter(()=>"hidden"===document.visibilityState)),Co=xo.pipe(n.filter(()=>"visible"===document.visibilityState)),Io="undefined"!=typeof window?t.merge(Co,t.fromEvent(window,"mousedown"),t.fromEvent(window,"mousemove"),t.fromEvent(window,"keydown"),t.fromEvent(window,"wheel"),t.fromEvent(window,"touchmove")):t.of({});"undefined"!=typeof document&&t.merge(t.of(!0),Eo,Io).pipe(n.map(()=>"visible"===document.visibilityState),n.tap(e=>{ko.value!==e&&ko.next(e)}),n.switchMap(e=>e?t.of(0).pipe(n.delay(16e4),n.tap(()=>ko.next(!1))):t.of(0))).subscribe(()=>{});class Oo extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const Do=new WeakMap,Ao=3e4;class To extends en{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=on();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach((n,r)=>{r!==this.clientID&&Ao<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Uo(this,t,"timeout")},M(3e3)),e.on("destroy",()=>{this.destroy()}),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,s=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:on()});const i=[],o=[],l=[],c=[];null===e?c.push(t):null==s?null!=e&&i.push(t):(o.push(t),_n(s,e)||l.push(t)),(i.length>0||l.length>0||c.length>0)&&this.emit("change",[{added:i,updated:l,removed:c},"local"]),this.emit("update",[{added:i,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const Uo=(e,t,n)=>{const r=[];for(let n=0;n<t.length;n++){const s=t[n];if(e.states.has(s)){if(e.states.delete(s),s===e.clientID){const t=e.meta.get(s);e.meta.set(s,{clock:t.clock+1,lastUpdated:on()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},jo=new WeakMap;function Lo(e){let n=jo.get(e);return n||(n=new t.Subject,jo.set(e,n)),n}class Po extends t.Observable{constructor(e,t,n,r,s,i,o,l){super(c=>new Mo(e,t,n,r,s,l,c,i,o))}}let Ro=0;class Mo extends t.Subscription{constructor(e,t,n,r,s,i,o,l,c){super(()=>this.teardown()),this.id=++Ro,this.subscriptions=new Set,this.reconnecting=!1,this.db=e,this.databaseUrl=e.cloud.options.databaseUrl,this.rev=t,this.yrev=n,this.realmSetHash=r,this.clientIdentity=s,this.user=i,this.subscriber=o,this.lastUserActivity=new Date,this.messageProducer=l,this.webSocketStatus=c,this.connect()}teardown(){this.disconnect()}disconnect(){if(this.webSocketStatus.next("disconnected"),this.pinger&&(clearInterval(this.pinger),this.pinger=null),this.ws)try{this.ws.close()}catch(e){}this.ws=null;for(const e of this.subscriptions)e.unsubscribe();this.subscriptions.clear()}reconnect(){if(!this.reconnecting){this.reconnecting=!0;try{this.disconnect()}catch(e){}this.connect().catch(()=>{}).then(()=>this.reconnecting=!1)}}connect(){return r(this,void 0,void 0,function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const n=this.user.accessTokenExpiration;if(n&&n<new Date)return void this.subscriber.error(new Oo);this.webSocketStatus.next("connecting"),this.pinger=setInterval(()=>r(this,void 0,void 0,function*(){if(this.closed)this.teardown();else if(this.ws)try{this.ws.send(JSON.stringify({type:"ping"})),setTimeout(()=>{this.pinger&&(this.closed?this.teardown():this.lastServerActivity<new Date(Date.now()-2e4)&&this.reconnect())},2e4)}catch(e){this.reconnect()}else this.reconnect()}),3e4);const s=new URL(this.databaseUrl);s.protocol="http:"===s.protocol?"ws":"wss";const i=new URLSearchParams;if(this.subscriber.closed)return;i.set("v","2"),this.rev&&i.set("rev",this.rev),this.yrev&&i.set("yrev",this.yrev),i.set("realmsHash",this.realmSetHash),i.set("clientId",this.clientIdentity),i.set("dxcv",this.db.cloud.version),this.user.accessToken&&i.set("token",this.user.accessToken);const o=this.ws=new WebSocket(`${s}/changes?${i}`);o.binaryType="arraybuffer",o.onclose=e=>{this.pinger&&this.reconnect()},o.onmessage=e=>{if(this.pinger){this.lastServerActivity=new Date;try{const t="string"==typeof e.data?Lt.parse(e.data):function(e){const t=new Te(e),n=$e(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:$e(t)};const r=$e(t),s=$e(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(Be(t))};default:{const e=We(t);switch(n){case"in-sync":case"doc-close":return{type:n,table:r,prop:s,k:e};case"aware":return{type:n,table:r,prop:s,k:e,u:Le(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:We(t),sv:We(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:Le(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:Le(t),i:Number(Be(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:Le(t),r:t.pos<t.arr.length&&$e(t)||void 0};default:throw new TypeError(`Unknown message type: ${n}`)}}}}(new Uint8Array(e.data));if("error"===t.type)throw new Error(`Error message from dexie-cloud: ${t.error}`);if("aware"===t.type){const e=Ii.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Do.get(e))(e);n&&((e,t,n)=>{const r=Ue(t),s=on(),i=[],o=[],l=[],c=[],a=Re(r);for(let t=0;t<a;t++){const t=Re(r);let n=Re(r);const a=JSON.parse($e(r)),d=e.meta.get(t),u=e.states.get(t),h=void 0===d?0:d.clock;(h<n||h===n&&null===a&&e.states.has(t))&&(null===a?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,a),e.meta.set(t,{clock:n,lastUpdated:s}),void 0===d&&null!==a?i.push(t):void 0!==d&&null===a?c.push(t):null!==a&&(_n(a,u)||l.push(t),o.push(t)))}(i.length>0||l.length>0||c.length>0)&&e.emit("change",[{added:i,updated:l,removed:c},n]),(i.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:i,updated:o,removed:c},n])})(n,t.u,"server")}}else if("pong"===t.type);else if("doc-open"===t.type){const e=Ii.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&Lo(e).next()}else"u-ack"===t.type||"u-reject"===t.type||"u-s"===t.type||"in-sync"===t.type||"outdated-server-rev"===t.type||"y-complete-sync-done"===t.type?Oi([t],this.db).then(e=>r(this,[e],void 0,function*({resyncNeeded:e,yServerRevision:n,receivedUntils:r}){if(n&&(yield this.db.$syncState.update("syncState",{yServerRevision:n})),"u-s"===t.type&&r){const e=gi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(qt,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let n=!1;yield new Promise((e,t)=>{o.onopen=t=>{n=!0,e(null)},o.onerror=e=>{if(n)this.reconnect();else{const n=e.error||new Error("WebSocket Error");this.subscriber.error(n),this.webSocketStatus.next("error"),t(n)}}}),this.subscriptions.add(this.messageProducer.subscribe(e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(Lt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new se;switch(fe(t,e.type),"table"in e&&fe(t,e.table),"prop"in e&&fe(t,e.prop),e.type){case"u-ack":case"u-reject":me(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":fe(t,e.yServerRev);break;default:switch(be(t,e.k),e.type){case"aware":ge(t,e.u);break;case"doc-open":be(t,e.serverRev),be(t,e.sv);break;case"doc-close":break;case"sv":ge(t,e.sv);break;case"u-c":ge(t,e.u),me(t,BigInt(e.i));break;case"u-s":ge(t,e.u),fe(t,e.r||"")}}return oe(t)}(e)))})),this.user.isLoggedIn&&!vo(this.db)&&this.subscriptions.add(function(n){const s=C(n.tables.filter(e=>{var t,r;return(null===(r=null===(t=n.cloud.schema)||void 0===t?void 0:t[e.name])||void 0===r?void 0:r.markedForSync)&&e.schema.yProps}).map(e=>e.schema.yProps.map(t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))));return t.merge(...s.map(({table:s,ydocProp:i,updatesTable:o})=>{const l=n.table(o);return t.from(l.get(qt)).pipe(t.switchMap(n=>{let o=(null==n?void 0:n.unsentFrom)||1;return t.from(e.liveQuery(()=>r(this,void 0,void 0,function*(){return(yield Gt(l,o)).filter(e=>e.f&&1&e.f).map(e=>({type:"u-c",table:s,prop:i,k:e.k,u:e.u,i:e.i}))}))).pipe(t.tap(e=>{e.length>0&&(o=e.at(-1).i+1)}))}))})).pipe(t.mergeMap(e=>e))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}})}}class $o extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function No(e){return r(this,void 0,void 0,function*(){var e;yield(e=3e3,new Promise(t=>setTimeout(t,e))),yield t.firstValueFrom(Io)})}function Bo(e){return r(this,void 0,void 0,function*(){var t;return!(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl)||!e.cloud.schema)&&(yield Ti(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))})}const Fo=new WeakMap;function Wo(e,t,n,s){const i=Fo.get(e);if(i){if(i.pull||"push"===(null==s?void 0:s.purpose))return i.promise;{let r=!1;const o=e.cloud.syncState.subscribe(e=>{"pulling"===e.phase&&(r=!0)});return i.promise.then(()=>{o.unsubscribe()}).catch(e=>(o.unsubscribe(),Promise.reject(e))).then(()=>{if(!r)return Wo(e,t,n,s)})}}const o=function(){return r(this,void 0,void 0,function*(){try{yield Bt(e),yield _o(e,Ai,()=>Ti(e,t,n,s)),Fo.delete(e)}catch(t){throw Fo.delete(e),t}})}();return Fo.set(e,{promise:o,pull:"push"!==(null==s?void 0:s.purpose)}),o}function Ho(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout(()=>{const u=c?"pull":"push";o=Date.now(),Wo(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:u}).then(()=>{if(s.cancelled)h();else if(c||a)return c=!1,a=!1,l();d=!1,i=0,o=0}).catch(e=>{if(s.cancelled)h(),d=!1,i=0,o=0;else if(r<5){const e=1e3*[0,20,40,300,900][r];i=Date.now()+e,o=0,setTimeout(()=>l(r+1),e)}else d=!1,i=0,o=0})},0)}let c=!1,a=!1,d=!1;const u=e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),d?i||o>0&&Date.now():(d=!0,l()))},h=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe(({purpose:e})=>{u(e||"pull")})},stop:h}}function Vo(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var zo,Ko,Jo,qo,Go,Yo,Qo,Xo,Zo,el,tl,nl={},rl=[],sl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,il=Array.isArray;function ol(e,t){for(var n in t)e[n]=t[n];return e}function ll(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function cl(e,t,n){var r,s,i,o={};for(i in t)"key"==i?r=t[i]:"ref"==i?s=t[i]:o[i]=t[i];if(arguments.length>2&&(o.children=arguments.length>3?zo.call(arguments,2):n),"function"==typeof e&&null!=e.defaultProps)for(i in e.defaultProps)void 0===o[i]&&(o[i]=e.defaultProps[i]);return al(e,o,r,s,null)}function al(e,t,n,r,s){var i={type:e,props:t,key:n,ref:r,__k:null,__:null,__b:0,__e:null,__c:null,constructor:void 0,__v:null==s?++Jo:s,__i:-1,__u:0};return null==s&&null!=Ko.vnode&&Ko.vnode(i),i}function dl(e){return e.children}function ul(e,t){this.props=e,this.context=t}function hl(e,t){if(null==t)return e.__?hl(e.__,e.__i+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?hl(e):null}function fl(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 fl(e)}}function pl(e){(!e.__d&&(e.__d=!0)&&qo.push(e)&&!gl.__r++||Go!=Ko.debounceRendering)&&((Go=Ko.debounceRendering)||Yo)(gl)}function gl(){for(var e,t,n,r,s,i,o,l=1;qo.length;)qo.length>l&&qo.sort(Qo),e=qo.shift(),l=qo.length,e.__d&&(n=void 0,r=void 0,s=(r=(t=e).__v).__e,i=[],o=[],t.__P&&((n=ol({},r)).__v=r.__v+1,Ko.vnode&&Ko.vnode(n),kl(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[s]:null,i,null==s?hl(r):s,!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,xl(i,n,o),r.__e=r.__=null,n.__e!=s&&fl(n)));gl.__r=0}function yl(e,t,n,r,s,i,o,l,c,a,d){var u,h,f,p,g,y,m,v=r&&r.__k||rl,b=t.length;for(c=function(e,t,n,r,s){var i,o,l,c,a,d=n.length,u=d,h=0;for(e.__k=new Array(s),i=0;i<s;i++)null!=(o=t[i])&&"boolean"!=typeof o&&"function"!=typeof o?("string"==typeof o||"number"==typeof o||"bigint"==typeof o||o.constructor==String?o=e.__k[i]=al(null,o,null,null,null):il(o)?o=e.__k[i]=al(dl,{children:o},null,null,null):null==o.constructor&&o.__b>0?o=e.__k[i]=al(o.type,o.props,o.key,o.ref?o.ref:null,o.__v):e.__k[i]=o,c=i+h,o.__=e,o.__b=e.__b+1,-1!=(a=o.__i=vl(o,n,c,u))&&(u--,(l=n[a])&&(l.__u|=2)),null==l||null==l.__v?(-1==a&&(s>d?h--:s<d&&h++),"function"!=typeof o.type&&(o.__u|=4)):a!=c&&(a==c-1?h--:a==c+1?h++:(a>c?h--:h++,o.__u|=4))):e.__k[i]=null;if(u)for(i=0;i<d;i++)null!=(l=n[i])&&!(2&l.__u)&&(l.__e==r&&(r=hl(l)),Ol(l,l));return r}(n,t,v,c,b),u=0;u<b;u++)null!=(f=n.__k[u])&&(h=-1==f.__i?nl:v[f.__i]||nl,f.__i=u,y=kl(e,f,h,s,i,o,l,c,a,d),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&Il(h.ref,null,f),d.push(f.ref,f.__c||p,f)),null==g&&null!=p&&(g=p),(m=!!(4&f.__u))||h.__k===f.__k?c=ml(f,c,e,m):"function"==typeof f.type&&void 0!==y?c=y:p&&(c=p.nextSibling),f.__u&=-7);return n.__e=g,c}function ml(e,t,n,r){var s,i;if("function"==typeof e.type){for(s=e.__k,i=0;s&&i<s.length;i++)s[i]&&(s[i].__=e,t=ml(s[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=hl(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function vl(e,t,n,r){var s,i,o,l=e.key,c=e.type,a=t[n],d=null!=a&&!(2&a.__u);if(null===a&&null==l||d&&l==a.key&&c==a.type)return n;if(r>(d?1:0))for(s=n-1,i=n+1;s>=0||i<t.length;)if(null!=(a=t[o=s>=0?s--:i++])&&!(2&a.__u)&&l==a.key&&c==a.type)return o;return-1}function bl(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||sl.test(t)?n:n+"px"}function wl(e,t,n,r,s){var i,o;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||bl(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||bl(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])i=t!=(t=t.replace(Xo,"$1")),o=t.toLowerCase(),t=o in e||"onFocusOut"==t||"onFocusIn"==t?o.slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r?n.u=r.u:(n.u=Zo,e.addEventListener(t,i?tl:el,i)):e.removeEventListener(t,i?tl:el,i);else{if("http://www.w3.org/2000/svg"==s)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("width"!=t&&"height"!=t&&"href"!=t&&"list"!=t&&"form"!=t&&"tabIndex"!=t&&"download"!=t&&"rowSpan"!=t&&"colSpan"!=t&&"role"!=t&&"popover"!=t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null==n||!1===n&&"-"!=t[4]?e.removeAttribute(t):e.setAttribute(t,"popover"==t&&1==n?"":n))}}function _l(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=Zo++;else if(t.t<n.u)return;return n(Ko.event?Ko.event(t):t)}}}function kl(e,t,n,r,s,i,o,l,c,a){var d,u,h,f,p,g,y,m,v,b,w,_,k,S,x,E,C,I=t.type;if(null!=t.constructor)return null;128&n.__u&&(c=!!(32&n.__u),i=[l=t.__e=n.__e]),(d=Ko.__b)&&d(t);e:if("function"==typeof I)try{if(m=t.props,v="prototype"in I&&I.prototype.render,b=(d=I.contextType)&&r[d.__c],w=d?b?b.props.value:d.__:r,n.__c?y=(u=t.__c=n.__c).__=u.__E:(v?t.__c=u=new I(m,w):(t.__c=u=new ul(m,w),u.constructor=I,u.render=Dl),b&&b.sub(u),u.state||(u.state={}),u.__n=r,h=u.__d=!0,u.__h=[],u._sb=[]),v&&null==u.__s&&(u.__s=u.state),v&&null!=I.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=ol({},u.__s)),ol(u.__s,I.getDerivedStateFromProps(m,u.__s))),f=u.props,p=u.state,u.__v=t,h)v&&null==I.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),v&&null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(v&&null==I.getDerivedStateFromProps&&m!==f&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(m,w),t.__v==n.__v||!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(m,u.__s,w)){for(t.__v!=n.__v&&(u.props=m,u.state=u.__s,u.__d=!1),t.__e=n.__e,t.__k=n.__k,t.__k.some(function(e){e&&(e.__=t)}),_=0;_<u._sb.length;_++)u.__h.push(u._sb[_]);u._sb=[],u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(m,u.__s,w),v&&null!=u.componentDidUpdate&&u.__h.push(function(){u.componentDidUpdate(f,p,g)})}if(u.context=w,u.props=m,u.__P=e,u.__e=!1,k=Ko.__r,S=0,v){for(u.state=u.__s,u.__d=!1,k&&k(t),d=u.render(u.props,u.state,u.context),x=0;x<u._sb.length;x++)u.__h.push(u._sb[x]);u._sb=[]}else do{u.__d=!1,k&&k(t),d=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++S<25);u.state=u.__s,null!=u.getChildContext&&(r=ol(ol({},r),u.getChildContext())),v&&!h&&null!=u.getSnapshotBeforeUpdate&&(g=u.getSnapshotBeforeUpdate(f,p)),E=d,null!=d&&d.type===dl&&null==d.key&&(E=El(d.props.children)),l=yl(e,il(E)?E:[E],t,n,r,s,i,o,l,c,a),u.base=t.__e,t.__u&=-161,u.__h.length&&o.push(u),y&&(u.__E=u.__=null)}catch(e){if(t.__v=null,c||null!=i)if(e.then){for(t.__u|=c?160:128;l&&8==l.nodeType&&l.nextSibling;)l=l.nextSibling;i[i.indexOf(l)]=null,t.__e=l}else{for(C=i.length;C--;)ll(i[C]);Sl(t)}else t.__e=n.__e,t.__k=n.__k,e.then||Sl(t);Ko.__e(e,t,n)}else null==i&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=Cl(n.__e,t,n,r,s,i,o,c,a);return(d=Ko.diffed)&&d(t),128&t.__u?void 0:l}function Sl(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(Sl)}function xl(e,t,n){for(var r=0;r<n.length;r++)Il(n[r],n[++r],n[++r]);Ko.__c&&Ko.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){Ko.__e(e,t.__v)}})}function El(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:il(e)?e.map(El):ol({},e)}function Cl(e,t,n,r,s,i,o,l,c){var a,d,u,h,f,p,g,y=n.props||nl,m=t.props,v=t.type;if("svg"==v?s="http://www.w3.org/2000/svg":"math"==v?s="http://www.w3.org/1998/Math/MathML":s||(s="http://www.w3.org/1999/xhtml"),null!=i)for(a=0;a<i.length;a++)if((f=i[a])&&"setAttribute"in f==!!v&&(v?f.localName==v:3==f.nodeType)){e=f,i[a]=null;break}if(null==e){if(null==v)return document.createTextNode(m);e=document.createElementNS(s,v,m.is&&m),l&&(Ko.__m&&Ko.__m(t,i),l=!1),i=null}if(null==v)y===m||l&&e.data==m||(e.data=m);else{if(i=i&&zo.call(e.childNodes),!l&&null!=i)for(y={},a=0;a<e.attributes.length;a++)y[(f=e.attributes[a]).name]=f.value;for(a in y)if(f=y[a],"children"==a);else if("dangerouslySetInnerHTML"==a)u=f;else if(!(a in m)){if("value"==a&&"defaultValue"in m||"checked"==a&&"defaultChecked"in m)continue;wl(e,a,null,f,s)}for(a in m)f=m[a],"children"==a?h=f:"dangerouslySetInnerHTML"==a?d=f:"value"==a?p=f:"checked"==a?g=f:l&&"function"!=typeof f||y[a]===f||wl(e,a,f,y[a],s);if(d)l||u&&(d.__html==u.__html||d.__html==e.innerHTML)||(e.innerHTML=d.__html),t.__k=[];else if(u&&(e.innerHTML=""),yl("template"==t.type?e.content:e,il(h)?h:[h],t,n,r,"foreignObject"==v?"http://www.w3.org/1999/xhtml":s,i,o,i?i[0]:n.__k&&hl(n,0),l,c),null!=i)for(a=i.length;a--;)ll(i[a]);l||(a="value","progress"==v&&null==p?e.removeAttribute("value"):null!=p&&(p!==e[a]||"progress"==v&&!p||"option"==v&&p!=y[a])&&wl(e,a,p,y[a],s),a="checked",null!=g&&g!=e[a]&&wl(e,a,g,y[a],s))}return e}function Il(e,t,n){try{if("function"==typeof e){var r="function"==typeof e.__u;r&&e.__u(),r&&null==t||(e.__u=e(t))}else e.current=t}catch(e){Ko.__e(e,n)}}function Ol(e,t,n){var r,s;if(Ko.unmount&&Ko.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||Il(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Ko.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Ol(r[s],t,n||"function"!=typeof e.type);n||ll(e.__e),e.__c=e.__=e.__e=void 0}function Dl(e,t,n){return this.constructor(e,n)}function Al(e,t,n){var r,s,i;t==document&&(t=document.documentElement),Ko.__&&Ko.__(e,t),r=!1?null:t.__k,s=[],i=[],kl(t,e=t.__k=cl(dl,null,[e]),r||nl,nl,t.namespaceURI,r?null:t.firstChild?zo.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,i),xl(s,e,i)}zo=rl.slice,Ko={__e:function(e,t,n,r){for(var s,i,o;t=t.__;)if((s=t.__c)&&!s.__)try{if((i=s.constructor)&&null!=i.getDerivedStateFromError&&(s.setState(i.getDerivedStateFromError(e)),o=s.__d),null!=s.componentDidCatch&&(s.componentDidCatch(e,r||{}),o=s.__d),o)return s.__E=s}catch(t){e=t}throw e}},Jo=0,ul.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=ol({},this.state),"function"==typeof e&&(e=e(ol({},n),this.props)),e&&ol(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),pl(this))},ul.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),pl(this))},ul.prototype.render=dl,qo=[],Yo="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Qo=function(e,t){return e.__v.__b-t.__v.__b},gl.__r=0,Xo=/(PointerCapture)$|Capture$/i,Zo=0,el=_l(!1),tl=_l(!0);const Tl={Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center",padding:"16px",boxSizing:"border-box"},DialogInner:{position:"relative",color:"#222",backgroundColor:"#fff",padding:"24px",marginBottom:"2em",maxWidth:"400px",width:"100%",maxHeight:"90%",overflowY:"auto",border:"3px solid #3d3d5d",borderRadius:"8px",boxShadow:"0 0 80px 10px #666",fontFamily:"sans-serif",boxSizing:"border-box"},Input:{height:"35px",width:"100%",maxWidth:"100%",borderColor:"#ccf4",outline:"none",fontSize:"16px",padding:"8px",boxSizing:"border-box",backgroundColor:"#f9f9f9",borderRadius:"4px",border:"1px solid #ccc",marginTop:"6px",fontFamily:"inherit"},Button:{padding:"10px 20px",margin:"0 4px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease"},PrimaryButton:{padding:"10px 20px",margin:"0 4px",border:"1px solid #3b82f6",borderRadius:"6px",backgroundColor:"#3b82f6",color:"white",cursor:"pointer",fontSize:"14px",fontWeight:"500",transition:"all 0.2s ease"},ButtonsDiv:{display:"flex",justifyContent:"flex-end",gap:"12px",marginTop:"24px",paddingTop:"20px"},Label:{display:"block",marginBottom:"12px",fontSize:"14px",fontWeight:"500",color:"#333"},WindowHeader:{margin:"0 0 20px 0",fontSize:"18px",fontWeight:"600",color:"#333",borderBottom:"1px solid #eee",paddingBottom:"10px"},ProviderButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",marginBottom:"10px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#ffffff",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"},ProviderButtonIcon:{width:"20px",height:"20px",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center"},ProviderButtonText:{flex:1,textAlign:"left"},ProviderGoogle:{backgroundColor:"#ffffff",border:"1px solid #dadce0",color:"#3c4043"},ProviderGitHub:{backgroundColor:"#24292e",border:"1px solid #24292e",color:"#ffffff"},ProviderMicrosoft:{backgroundColor:"#ffffff",border:"1px solid #8c8c8c",color:"#5e5e5e"},ProviderApple:{backgroundColor:"#000000",border:"1px solid #000000",color:"#ffffff"},ProviderCustom:{backgroundColor:"#4f46e5",border:"1px solid #4f46e5",color:"#ffffff"},Divider:{display:"flex",alignItems:"center",margin:"20px 0",color:"#6b7280",fontSize:"13px"},DividerLine:{flex:1,height:"1px",backgroundColor:"#e5e7eb"},DividerText:{padding:"0 12px",color:"#9ca3af"},OtpButton:{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",padding:"12px 16px",border:"1px solid #d1d5db",borderRadius:"6px",backgroundColor:"#f9fafb",cursor:"pointer",fontSize:"14px",fontWeight:"500",color:"#374151",transition:"all 0.2s ease",gap:"12px"}};function Ul({children:e,className:t}){return cl("div",{className:`dexie-dialog ${t||""}`},cl("div",{style:Tl.Darken}),cl("div",{style:Tl.DialogOuter},cl("div",{style:Tl.DialogInner},e)))}var jl,Ll,Pl,Rl,Ml=0,$l=[],Nl=Ko,Bl=Nl.__b,Fl=Nl.__r,Wl=Nl.diffed,Hl=Nl.__c,Vl=Nl.unmount,zl=Nl.__;function Kl(e,t){Nl.__h&&Nl.__h(Ll,e,Ml||t),Ml=0;var n=Ll.__H||(Ll.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function Jl(e){return Ml=1,function(e,t){var n=Kl(jl++,2);if(n.t=e,!n.__c&&(n.__=[tc(void 0,t),function(e){var t=n.__N?n.__N[0]:n.__[0],r=n.t(t,e);t!==r&&(n.__N=[r,n.__[1]],n.__c.setState({}))}],n.__c=Ll,!Ll.__f)){var r=function(e,t,r){if(!n.__c.__H)return!0;var i=n.__c.__H.__.filter(function(e){return!!e.__c});if(i.every(function(e){return!e.__N}))return!s||s.call(this,e,t,r);var o=n.__c.props!==e;return i.forEach(function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}}),s&&s.call(this,e,t,r)||o};Ll.__f=!0;var s=Ll.shouldComponentUpdate,i=Ll.componentWillUpdate;Ll.componentWillUpdate=function(e,t,n){if(this.__e){var o=s;s=void 0,r(e,t,n),s=o}i&&i.call(this,e,t,n)},Ll.shouldComponentUpdate=r}return n.__N||n.__}(tc,e)}function ql(e){return Ml=5,function(e,t){var n=Kl(jl++,7);return ec(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}(function(){return{current:e}},[])}function Gl(){for(var e;e=$l.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Xl),e.__H.__h.forEach(Zl),e.__H.__h=[]}catch(t){e.__H.__h=[],Nl.__e(t,e.__v)}}Nl.__b=function(e){Ll=null,Bl&&Bl(e)},Nl.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),zl&&zl(e,t)},Nl.__r=function(e){Fl&&Fl(e),jl=0;var t=(Ll=e.__c).__H;t&&(Pl===Ll?(t.__h=[],Ll.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Xl),t.__h.forEach(Zl),t.__h=[],jl=0)),Pl=Ll},Nl.diffed=function(e){Wl&&Wl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==$l.push(t)&&Rl===Nl.requestAnimationFrame||((Rl=Nl.requestAnimationFrame)||Ql)(Gl)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),Pl=Ll=null},Nl.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Xl),e.__h=e.__h.filter(function(e){return!e.__||Zl(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],Nl.__e(n,e.__v)}}),Hl&&Hl(e,t)},Nl.unmount=function(e){Vl&&Vl(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Xl(e)}catch(e){t=e}}),n.__H=void 0,t&&Nl.__e(t,n.__v))};var Yl="function"==typeof requestAnimationFrame;function Ql(e){var t,n=function(){clearTimeout(r),Yl&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);Yl&&(t=requestAnimationFrame(n))}function Xl(e){var t=Ll,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Ll=t}function Zl(e){var t=Ll;e.__c=e.__(),Ll=t}function ec(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function tc(e,t){return"function"==typeof t?t(e):t}function nc({option:e,onClick:t}){const{displayName:n,iconUrl:r,iconSvg:s,styleHint:i,value:o}=e,l=function(e){const t=Object.assign({},Tl.ProviderButton);if(!e)return t;switch(e){case"google":return Object.assign(Object.assign({},t),Tl.ProviderGoogle);case"github":return Object.assign(Object.assign({},t),Tl.ProviderGitHub);case"microsoft":return Object.assign(Object.assign({},t),Tl.ProviderMicrosoft);case"apple":return Object.assign(Object.assign({},t),Tl.ProviderApple);case"otp":return Object.assign({},Tl.OtpButton);case"custom-oauth2":return Object.assign(Object.assign({},t),Tl.ProviderCustom);default:return t}}(i),c=l.color||"#000000",a=s?s.replace(/fill="currentColor"/gi,`fill="${c}"`).replace(/fill='currentColor'/gi,`fill='${c}'`).replace(/stroke="currentColor"/gi,`stroke="${c}"`).replace(/stroke='currentColor'/gi,`stroke='${c}'`):null;return cl("button",{type:"button",style:l,onClick:t,class:"dxc-option-btn"+(i?` dxc-option-${i}`:""),"aria-label":n},a?cl("span",{style:Tl.ProviderButtonIcon,"aria-hidden":"true",dangerouslySetInnerHTML:{__html:a}}):r?cl("img",{src:r,alt:"",style:Tl.ProviderButtonIcon,"aria-hidden":"true"}):null,cl("span",{style:Tl.ProviderButtonText},n))}function rc(){return cl("div",{style:Tl.Divider},cl("div",{style:Tl.DividerLine}),cl("span",{style:Tl.DividerText},"or"),cl("div",{style:Tl.DividerLine}))}function sc({title:e,alerts:t,fields:n,options:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=Jl({}),d=ql(null);!function(e,t){var n=Kl(jl++,4);!Nl.__s&&ec(n.__H,t)&&(n.__=e,n.u=t,Ll.__h.push(n))}(()=>{var e;return null===(e=d.current)||void 0===e?void 0:e.focus()},[]);const u=Object.entries(n||{}),h=u.length>0,f=r&&r.length>0,p=new Map;if(r)for(const e of r){const t=p.get(e.name)||[];t.push(e),p.set(e.name,t)}const g=p.size>1,y=e=>{l({[e.name]:e.value})};return cl(Ul,{className:"dxc-login-dlg"},cl(dl,null,cl("h3",{style:Tl.WindowHeader},e),t.map((e,t)=>cl("p",{key:t,style:Tl.Alert[e.type]},function({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,e=>n[e.substring(1,e.length-1)])}(e))),f&&cl("div",{class:"dxc-options"},g?Array.from(p.entries()).map(([e,t],n)=>cl(dl,{key:e},n>0&&cl(rc,null),t.map(e=>cl(nc,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)})))):r.map(e=>cl(nc,{key:`${e.name}-${e.value}`,option:e,onClick:()=>y(e)}))),f&&h&&cl(rc,null),h&&cl("form",{onSubmit:e=>{e.preventDefault(),l(c)}},u.map(([e,{type:t,label:n,placeholder:r}],s)=>cl("label",{style:Tl.Label,key:s},n?`${n}: `:"",cl("input",{ref:0===s?d:void 0,type:t,name:e,autoComplete:"on",style:Tl.Input,autoFocus:!0,placeholder:r,value:c[e]||"",onInput:n=>{var r;const s=function(e,t){switch(e){case"email":return t.toLowerCase();case"otp":return t.toUpperCase();default:return t}}(t,null===(r=n.target)||void 0===r?void 0:r.value);let i=Object.assign(Object.assign({},c),{[e]:s});a(i),"otp"===t&&8===(null==s?void 0:s.trim().length)&&l(i)}}))))),cl("div",{style:Tl.ButtonsDiv},cl(dl,null,s&&(h||!f&&!h)&&cl("button",{type:"submit",style:Tl.PrimaryButton,onClick:()=>l(c)},s),i&&cl("button",{style:Tl.Button,onClick:o},i))))}class ic extends ul{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=t.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?cl(sc,Object.assign({},t)):null}}function oc(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const lc=oc(e=>new t.BehaviorSubject(c));function cc(e,n){let r=n,s=t.from(e).pipe(t.map(e=>r=e),t.share({resetOnRefCountZero:()=>t.timer(1e3)}));const i=new t.Observable(e=>{let t=!1;const n=s.subscribe({next(n){t=!0,e.next(n)},error(t){e.error(t)},complete(){e.complete()}});return t||n.closed||e.next(r),n});return i.getValue=()=>r,i}const ac=oc(t=>cc(e.liveQuery(()=>t.roles.where({realmId:"rlm-public"}).toArray().then(e=>{const t={};for(const n of e.slice().sort((e,t)=>(e.sortOrder||0)-(t.sortOrder||0)))t[n.name]=n;return t})),{})),dc=oc(t=>cc(lc(t._novip).pipe(n.switchMap(n=>e.liveQuery(()=>t.transaction("r","realms","members",()=>Promise.all([t.members.where({userId:n.userId}).toArray(),t.realms.toArray(),n.userId]).then(([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))),{selfMembers:[],realms:[],get userId(){return t.cloud.currentUserId}}));function uc(...e){if(0===e.length)return{};const t=e.reduce((e,t)=>{const n=Object.assign({},e);for(const[e,r]of Object.entries(t))if(e in n&&n[e]){if("*"===n[e])continue;if("*"===r)n[e]="*";else if(Array.isArray(r)&&Array.isArray(n[e])){const t=n,s=t[e];t[e]=[...new Set([...s,...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 hc=oc(e=>function(e,n){let r;const s=e.pipe(t.map(e=>r=n(e)));return s.getValue=()=>void 0!==r?r:r=n(e.getValue()),s}(cc(t.combineLatest([dc(e._novip),ac(e._novip)]).pipe(n.map(([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r}))),{selfMembers:[],realms:[],userId:c.userId,globalRoles:{}}),({selfMembers:e,realms:t,userId:n,globalRoles:r})=>{const s=t.map(t=>{const s=e.filter(e=>e.realmId===t.realmId),i=s.map(e=>e.permissions).filter(e=>e),o=C(s.map(e=>e.roles).filter(e=>e)).map(e=>r[e]).filter(e=>e).map(e=>e.permissions);return Object.assign(Object.assign({},t),{permissions:t.owner===n?{manage:"*"}:uc(...i,...o)})}).reduce((e,t)=>Object.assign(Object.assign({},e),{[t.realmId]:t}),{[n]:{realmId:n,owner:n,name:n,permissions:{manage:"*"}}});return s}));class fc{constructor(e,t,n){this.permissions=e||{},this.tableName=t,this.isOwner=n}add(...e){var t;return"*"===this.permissions.manage||(!!(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))||("*"===this.permissions.add||!!e.every(e=>{var t;return null===(t=this.permissions.add)||void 0===t?void 0:t.includes(e)})))}update(...e){var t,n;if(this.isOwner||"*"===this.permissions.manage)return!0;if(null===(t=this.permissions.manage)||void 0===t?void 0:t.includes(this.tableName))return!0;if("*"===this.permissions.update)return e.every(e=>"owner"!==e);const r=null===(n=this.permissions.update)||void 0===n?void 0:n[this.tableName];return"*"===r?e.every(e=>"owner"!==e):e.every(e=>null==r?void 0:r.some(t=>t===e||"*"===t&&"owner"!==e))}delete(){var e;return!(!this.isOwner&&"*"!==this.permissions.manage)||!!(null===(e=this.permissions.manage)||void 0===e?void 0:e.includes(this.tableName))}}const pc=oc(s=>{const i=lc(s._novip).pipe(n.switchMap(t=>e.liveQuery(()=>s.members.where({email:t.email||""}).toArray()))),o=hc(s._novip),l=dc(s._novip);return cc(t.combineLatest([i,l,o]).pipe(n.map(([e,t,n])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:n[t.realmId]})}),o=e.reduce(i,{}),l=t.selfMembers.reduce(i,o);return Object.values(l).filter(e=>!e.accepted).map(e=>Object.assign(Object.assign({},e),{accept(){return r(this,void 0,void 0,function*(){yield s.members.update(e.id,{accepted:new Date})})},reject(){return r(this,void 0,void 0,function*(){yield s.members.update(e.id,{rejected:new Date})})}}))})),[])});function gc(n){return s=>{var i;const o=s.doc;if(!o)throw new Error("Internal error: DexieYProvider.createYHandler called without a doc. This is unexpected.");const{parentTable:l}=o.meta||{};if(!(null===(i=n.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(s,"awareness",{get:()=>c||(c=function(n,s,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=s.meta,d=new To(s),u=Lo(s);return d.on("update",({added:e,updated:t,removed:r},l)=>{const a=e.concat(t).concat(r),u=n.cloud.currentUser.value;if("server"!==l&&u.isLoggedIn&&!vo(n)){const e=((e,t,n=e.states)=>{const r=t.length,s=ie();ae(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,l=e.meta.get(r).clock;ae(s,r),ae(s,l),fe(s,JSON.stringify(o))}return oe(s)})(d,a);n.messageProducer.next({type:"aware",table:o,prop:c,k:s.meta.parentId,u:e}),i.destroyed&&n.messageProducer.next({type:"doc-close",table:o,prop:c,k:s.meta.parentId})}}),d.on("destroy",()=>{Uo(d,[s.clientID],"provider destroyed")}),(()=>{r(this,void 0,void 0,function*(){if(i.destroyed)return;let s=!1,d=1;const h=t.combineLatest([n.cloud.webSocketStatus,u.pipe(t.startWith(null))]).subscribe(([e])=>{if(i.destroyed)return;s="connected"===e;const t=n.cloud.currentUser.value;"connected"===e&&t.isLoggedIn&&!vo(n)&&(++d,f().catch(e=>{}))});function f(){return r(this,void 0,void 0,function*(){const t=d,u=n.table(a),h=n.$syncState,[f,p]=yield n.transaction("r",h,u,()=>r(this,void 0,void 0,function*(){const e=yield u.get(qt),t=yield h.get("syncState");return[(null==e?void 0:e.receivedUntil)||0,(null==t?void 0:t.yServerRevision)||(null==t?void 0:t.serverRevision)]}));if(i.destroyed||d!==t||!s)return;const g={type:"doc-open",table:o,prop:c,k:l,serverRev:p},y=yield u.where("i").between(f,1/0,!1).filter(t=>0===e.cmp(t.k,l)&&!(1&(t.f||0))).toArray();if(!i.destroyed&&d===t&&s){if(y.length>0){const e=$r(y.map(e=>e.u)),t=Rr(e);g.sv=t}n.messageProducer.next(g)}})}i.addCleanupHandler(h)})})(),d}(n,o,s),Do.set(o,c),c)})}}function yc(e){const t="undefined"!=typeof window?window.location.href:"";if(!t)return null;const n=new URL(t).searchParams.get("dxc-auth");if(!n)return null;let r;try{const e=function(e){const t=(e+"=".repeat((4-e.length%4)%4)).replace(/-/g,"+").replace(/_/g,"/");return atob(t)}(n);r=JSON.parse(e)}catch(e){return null}const{code:s,provider:i,state:o,error:l}=r;if(l){if(l.toLowerCase().includes("access_denied")||l.toLowerCase().includes("access denied"))throw new Ki("access_denied",i,l);if(l.toLowerCase().includes("email")&&l.toLowerCase().includes("verif"))throw new Ki("email_not_verified",i,l);throw new Ki("provider_error",i,l)}return s&&i&&o?{code:s,provider:i,state:o}:null}function mc(){var e;if("undefined"==typeof window||!(null===(e=window.history)||void 0===e?void 0:e.replaceState))return;const t=new URL(window.location.href);if(!t.searchParams.has("dxc-auth"))return;t.searchParams.delete("dxc-auth");const n=t.pathname+(t.searchParams.toString()?`?${t.searchParams.toString()}`:"")+t.hash;window.history.replaceState(null,"",n)}const vc={nameSuffix:!0};function bc(s){const i=s.name,o=lc(s),l=[];let a=!1,d=null,u=null,h=null;s.on("ready",s=>r(this,void 0,void 0,function*(){try{yield function(s){return r(this,void 0,void 0,function*(){var i,c,v,b,w,k,S;f=!1;const x=$i(s);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=x.cloud.options)||void 0===i?void 0:i.customLoginGui)||l.push(function(e){let t=!1;const n=document.createElement("div");return document.body?(document.body.appendChild(n),Al(cl(ic,{db:e.vip}),n)):addEventListener("DOMContentLoaded",()=>{t||(document.body.appendChild(n),Al(cl(ic,{db:e.vip}),n))}),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(s))),x.cloud.isServiceWorkerDB||l.push(function(e){let r=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(n.switchMap(e=>{const s=r;r=e;const i=t.of(e);switch(e){case"disconnected":return ko.value?i.pipe(n.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(n.debounceTime(4e3));default:return i}}));return t.combineLatest([s,e.syncStateChangedEvent.pipe(n.startWith({phase:"initial"})),lc(e.dx._novip),So]).pipe(n.map(([t,n,r,s])=>{var i;if((null===(i=r.license)||void 0===i?void 0:i.status)&&"ok"!==r.license.status)return{phase:"offline",status:"offline",license:r.license.status};let{phase:o,error:l,progress:c}=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"),s||(a="disconnected"),{phase:o,error:l,progress:c,status:Ht?a:"offline",license:"ok"}}))}(x).subscribe(s.cloud.syncState)),l.push(x.syncCompleteEvent.subscribe(m)),x.tables.every(e=>e.core)||function(){throw new e.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const E="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[C,I]=yield x.transaction("rw",x.$syncState,()=>r(this,void 0,void 0,function*(){var e,t;const{options:n,schema:r}=x.cloud,[s,i,o]=yield Promise.all([x.getOptions(),x.getSchema(),x.getPersistedSyncState()]);if(a){if(!s||JSON.stringify(s)!==JSON.stringify(n)){if(!n)throw new Error("Internal error");const e=Object.assign({},n);delete e.fetchTokens,delete e.awarenessProtocol,yield x.$syncState.put(e,"options")}}else x.cloud.options=s||null;if((null===(e=x.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&E.length>0&&!no?x.cloud.usingServiceWorker=!0:((null===(t=x.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&x.cloud.isServiceWorkerDB,x.cloud.usingServiceWorker=!1),Vo(r,x.cloud.options),Vo(i,x.cloud.options),r){if(!i||JSON.stringify(i)!==JSON.stringify(r)){const e=i||{};for(const[t,n]of Object.entries(r)){const r=e[t];r?(r.markedForSync=n.markedForSync,n.deleted=r.deleted,r.generatedGlobalId=n.generatedGlobalId):e[t]=Object.assign({},n)}yield x.$syncState.put(e,"schema"),Object.assign(r,e)}}else x.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}));if(C&&x.setInitiallySynced(!0),function(t){var n,r;for(const s of t.tables)if(null===(r=null===(n=t.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new e.SchemaError(`Table ${s.name} is both autoIncremented and synced. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`);if(!s.schema.primKey.keyPath)throw new e.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(x),p(),!x.cloud.isServiceWorkerDB){l.push(e.liveQuery(()=>x.getCurrentUser()).subscribe(o)),l.push(e.liveQuery(()=>x.getPersistedSyncState()).subscribe(x.cloud.persistedSyncState)),yield t.firstValueFrom(t.combineLatest([o.pipe(n.skip(1),n.take(1)),x.cloud.persistedSyncState.pipe(n.skip(1),n.take(1))]));const r=gc(x);Ii.on.new.subscribe(r),x.dx.once("close",()=>{Ii.on.new.unsubscribe(r)})}let O=!1,D=yield x.getCurrentUser();if(u&&!x.cloud.isServiceWorkerDB){const e=u;u=null,yield Ze(x.cloud.userInteraction,"Authentication Error",{type:"error",messageCode:"GENERIC_ERROR",message:e.message,messageParams:{provider:e.provider||"unknown"}})}if(d&&!x.cloud.isServiceWorkerDB){const{code:e,provider:t}=d;d=null;try{O=yield Xi(x,{oauthCode:e,provider:t}),D=yield x.getCurrentUser()}catch(e){}}const A=null===(c=x.cloud.options)||void 0===c?void 0:c.requireAuth;A&&(x.cloud.isServiceWorkerDB?yield t.firstValueFrom(o.pipe(n.filter(e=>!!e.isLoggedIn),n.take(1))):"object"==typeof A?(!D.isLoggedIn||A.userId&&D.userId!==A.userId||A.email&&D.email!==A.email)&&(O=yield Xi(x,A)):D.isLoggedIn||(O=yield Xi(x))),!D.isLoggedIn||I&&I.includes(D.userId)||(O=!0),h&&h.stop(),h=null,p();const T=(null===(v=x.cloud.options)||void 0===v?void 0:v.databaseUrl)&&(!C||O);T&&(yield function(e,t,n){return r(this,void 0,void 0,function*(){yield _o(e,Ai,()=>Ti(e,t,n,{isInitialSync:!0}))})}(x,x.cloud.options,x.cloud.schema),x.setInitiallySynced(!0)),p(),x.cloud.usingServiceWorker&&(null===(b=x.cloud.options)||void 0===b?void 0:b.databaseUrl)?(T||g(x,"push").catch(()=>{}),function(e){return r(this,void 0,void 0,function*(){var t;try{const{periodicSync:n}=yield navigator.serviceWorker.ready;if(n)try{yield n.register(`dexie-cloud:${e.name}`,null===(t=e.cloud.options)||void 0===t?void 0:t.periodicSync)}catch(e){}}catch(e){}})}(x).catch(()=>{})):(null===(w=x.cloud.options)||void 0===w?void 0:w.databaseUrl)&&x.cloud.schema&&!x.cloud.isServiceWorkerDB&&(h=Ho(x,x.cloud.options,x.cloud.schema),h.start(),T||y(x,"push")),p(),x.cloud.isServiceWorkerDB||l.push(t.fromEvent(self,"online").subscribe(()=>{x.syncStateChangedEvent.next({phase:"not-in-sync"}),vo(x)||y(x,"push")}),t.fromEvent(self,"offline").subscribe(()=>{x.syncStateChangedEvent.next({phase:"offline"})})),!(null===(k=x.cloud.options)||void 0===k?void 0:k.databaseUrl)||(null===(S=x.cloud.options)||void 0===S?void 0:S.disableWebSocket)||ro||l.push(function(e){var s;if(!(null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(n.filter(e=>e),n.switchMap(()=>e.getPersistedSyncState()),n.filter(e=>e&&e.serverRevision),n.switchMap(e=>r(this,void 0,void 0,function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield _(e)}}))),o=t.merge(i,e.messageProducer);return function s(){return e.cloud.persistedSyncState.pipe(n.filter(e=>null==e?void 0:e.serverRevision),n.take(1),n.switchMap(t=>e.cloud.currentUser.pipe(n.map(e=>[e,t]))),n.switchMap(([e,t])=>So.pipe(n.map(n=>[n?e:null,t]))),n.switchMap(([r,s])=>(null==r?void 0:r.isLoggedIn)&&!(null==s?void 0:s.realms.includes(r.userId))?e.cloud.persistedSyncState.pipe(n.filter(e=>(null==e?void 0:e.realms.includes(r.userId))||!1),n.take(1),n.map(e=>[r,e])):new t.BehaviorSubject([r,s])),n.switchMap(e=>r(this,[e],void 0,function*([e,t]){return[e,yield _(t)]})),n.distinctUntilChanged(([e,t],[n,r])=>e===n&&t===r),n.switchMap(([n,r])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?n?new Po(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,r,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,n):t.from([]):s()}),n.catchError(i=>"TokenExpiredError"===(null==i?void 0:i.name)?t.of(!0).pipe(n.switchMap(()=>r(this,void 0,void 0,function*(){const t=yield e.getCurrentUser(),n=yield it(e.cloud.options.databaseUrl,t);yield e.table("$logins").update(t.userId,{accessToken:n.accessToken,accessTokenExpiration:n.accessTokenExpiration,claims:n.claims,license:n.license,data:n.data})})),n.switchMap(()=>s())):t.throwError(()=>i)),n.catchError(r=>(e.cloud.webSocketStatus.next("error"),r instanceof $o?t.throwError(()=>r):t.from(No()).pipe(n.switchMap(()=>s())))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(x))})}(s)}catch(e){}}),!0);let f=!1;function p(){if(f)throw new e.DatabaseClosedError}s.once("close",()=>{l.forEach(e=>e.unsubscribe()),l.splice(0,l.length),f=!0,h&&h.stop(),h=null,o.next(c)});const m=new t.Subject;var v;s.cloud={version:"4.3.3",options:Object.assign({},vc),schema:null,get currentUserId(){return o.value.userId||c.userId},currentUser:o,syncState:new t.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:m},persistedSyncState:new t.BehaviorSubject(void 0),userInteraction:new t.BehaviorSubject(void 0),webSocketStatus:new t.BehaviorSubject("not-started"),login(e){return r(this,void 0,void 0,function*(){const t=$i(s);yield t.cloud.sync(),yield Xi(t,e)})},invites:pc(s),roles:ac(s),configure(e){if(e=s.cloud.options=Object.assign(Object.assign({},s.cloud.options),e),a=!0,e.databaseUrl&&e.nameSuffix&&(s.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(e.databaseUrl)}`,$i(s).reconfigure()),Vo(s.cloud.schema,s.cloud.options),"undefined"!=typeof window&&window.location)try{const e=yc();e&&(mc(),d={code:e.code,provider:e.provider})}catch(e){mc(),e instanceof Ki&&(u=e)}},logout(){return r(this,arguments,void 0,function*({force:e}={}){e?yield Vi($i(s),{deleteUnsyncedData:!0}):yield Hi($i(s))})},sync(){return r(this,arguments,void 0,function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=$i(s);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield rt(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(y(c,o),i){const r=yield t.firstValueFrom(c.cloud.persistedSyncState.pipe(n.filter(t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))));if(null==r?void 0:r.error)throw new Error("Sync error: "+r.error)}}else if(yield Bo(c)){const s=c.cloud.persistedSyncState.value;y(c,o),i&&(yield t.firstValueFrom(t.from(e.liveQuery(()=>r(this,void 0,void 0,function*(){const e=yield Bo(c),t=yield c.getPersistedSyncState();if((null==t?void 0:t.timestamp)!==(null==s?void 0:s.timestamp)&&(null==t?void 0:t.error))throw new Error("Sync error: "+t.error);return e}))).pipe(n.filter(e=>!e))))}})},permissions:(e,t)=>function(e,t,r){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!r){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");r=t.table()}const o=hc(e),l=t=>{const n=t[i||e.cloud.currentUserId];return n?new fc(n.permissions,r,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new fc({},r,!s||s===e.cloud.currentUserId)},c=o.pipe(n.map(l));return c.getValue=()=>l(o.getValue()),c}(s._novip,e,t)},s.Version.prototype._parseStoresSpec=e.override(s.Version.prototype._parseStoresSpec,e=>wo(e,s)),s.Table.prototype.newId=function({colocateWith:e}={}){const t=e&&e.substr(e.length-3);return ho(s.cloud.schema[this.name].idPrefix||"",t)},s.Table.prototype.idPrefix=function(){var e,t;return(null===(t=null===(e=this.db.cloud.schema)||void 0===e?void 0:e[this.name])||void 0===t?void 0:t.idPrefix)||""},s.use(bo({currentUserObservable:s.cloud.currentUser,db:$i(s)})),s.use((v=$i(s),{stack:"dbcore",name:"implicitPropSetterMiddleware",level:1,create:e=>Object.assign(Object.assign({},e),{table:t=>{const n=e.table(t);return Object.assign(Object.assign({},n),{mutate:e=>{var r,s,i,o,l,a;const d=e.trans;if(d.disableChangeTracking)return n.mutate(e);const u=null!==(s=null===(r=d.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:c.userId;if((null===(o=null===(i=v.cloud.schema)||void 0===i?void 0:i[t])||void 0===o?void 0:o.markedForSync)&&("add"===e.type||"put"===e.type)){if("members"===t)for(const t of e.values)"string"==typeof t.email&&(t.email=t.email.trim().toLowerCase());for(const t of e.values){t.owner||(t.owner=u),t.realmId||(t.realmId=u);const r=null===(a=(l=n.schema.primaryKey).extractKey)||void 0===a?void 0:a.call(l,t);"string"==typeof r&&"#"===r[0]&&"put"===e.type&&(delete e.criteria,delete e.changeSpec,e.upsert||delete e.updates,t.$ts=Date.now())}}return n.mutate(e)}})}})})),s.use(fo($i(s)))}bc.version="4.3.3",e.Cloud=bc;const wc=new Map;function _c(e){return e.startsWith("dexie-cloud:")&&e.split(":")[1]}const kc=new Map;function Sc(t,n){let s=kc.get(t+"/"+n);return s||(s=function t(n,s){return r(this,void 0,void 0,function*(){var r;let i=wc.get(n);if(!i){const r=new e(n,{addons:[bc]});if(i=$i(r),i.cloud.isServiceWorkerDB=!0,r.on("versionchange",o),yield i.dx.open(),wc.get(n))return i.close(),yield t(n,s);wc.set(n,i)}if((null===(r=i.cloud.options)||void 0===r?void 0:r.databaseUrl)&&i.cloud.schema)try{yield Wo(i,i.cloud.options,i.cloud.schema,{retryImmediatelyOnFetchError:!0,purpose:s})}catch(t){if(o(),t.name!==e.errnames.NoSuchDatabase)throw t}function o(){return i.dx.on.versionchange.unsubscribe(o),wc.get(i.name)===i&&wc.delete(i.name),i.dx.close(),!1}})}(t,n).then(()=>{kc.delete(t+"/"+n)}).catch(e=>(kc.delete(t+"/"+n),Promise.reject(e))),kc.set(t+"/"+n,s)),s}no||(self.addEventListener("sync",e=>{const t=_c(e.tag);t&&e.waitUntil(Sc(t,"push"))}),self.addEventListener("periodicsync",e=>{const t=_c(e.tag);t&&e.waitUntil(Sc(t,"pull"))}),self.addEventListener("message",e=>{if("dexie-cloud-sync"===e.data.type){const{dbName:t}=e.data,n=(s=1)=>Sc(t,e.data.purpose||"pull").catch(e=>r(void 0,void 0,void 0,function*(){if(3===s)throw e;var t;yield(t=6e4,new Promise(e=>setTimeout(e,t))),n(s+1)}));"waitUntil"in e?e.waitUntil(n().catch(e=>{})):n().catch(e=>{})}}))});
|
|
2
2
|
//# sourceMappingURL=service-worker.min.js.map
|