dexie-cloud-addon 4.2.4 → 4.3.0
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/TODO-SOCIALAUTH.md +545 -0
- package/dexie-cloud-import.json +2 -1
- package/dist/modern/DexieCloudAPI.d.ts +4 -0
- package/dist/modern/DexieCloudOptions.d.ts +20 -0
- package/dist/modern/authentication/exchangeOAuthCode.d.ts +23 -0
- package/dist/modern/authentication/fetchAuthProviders.d.ts +14 -0
- package/dist/modern/authentication/handleOAuthCallback.d.ts +57 -0
- package/dist/modern/authentication/interactWithUser.d.ts +19 -0
- package/dist/modern/authentication/oauthLogin.d.ts +37 -0
- package/dist/modern/default-ui/AuthProviderButton.d.ts +21 -0
- package/dist/modern/default-ui/LoginDialog.d.ts +5 -2
- package/dist/modern/default-ui/ProviderSelectionDialog.d.ts +7 -0
- package/dist/modern/dexie-cloud-addon.js +719 -169
- 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.gz +0 -0
- package/dist/modern/dexie-cloud-addon.min.js.map +1 -1
- package/dist/modern/errors/OAuthError.d.ts +10 -0
- package/dist/modern/service-worker.js +720 -170
- package/dist/modern/service-worker.js.map +1 -1
- package/dist/modern/service-worker.min.js +1 -1
- package/dist/modern/service-worker.min.js.map +1 -1
- package/dist/modern/types/DXCUserInteraction.d.ts +24 -1
- package/dist/umd/dexie-cloud-addon.js +2181 -2444
- package/dist/umd/dexie-cloud-addon.js.gz +0 -0
- 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.gz +0 -0
- package/dist/umd/dexie-cloud-addon.min.js.map +1 -1
- package/dist/umd/service-worker.js +2029 -2292
- 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/oauth_flow.md +299 -0
- package/package.json +10 -7
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DexieCloud={},e.Dexie,e.rxjs,e.rxjs.operators)}(this,(function(e,t,n,r){"use strict";function s(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 i(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 o(e){return this instanceof o?(this.v=e,this):new o(e)}function l(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),i=[];return r={},l("next"),l("throw"),l("return"),r[Symbol.asyncIterator]=function(){return this},r;function l(e){s[e]&&(r[e]=function(t){return new Promise((function(n,r){i.push([e,t,n,r])>1||c(e,t)}))})}function c(e,t){try{!function(e){e.value instanceof o?Promise.resolve(e.value.v).then(a,u):d(i[0][2],e)}(s[e](t))}catch(e){d(i[0][3],e)}}function a(e){c("next",e)}function u(e){c("throw",e)}function d(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}}function c(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=i(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)}))}}}const a={}.hasOwnProperty;function u(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)u(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 a.call(e,t)}(e,o)||(c=e[o]={}),u(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const d="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=h)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function h(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function f(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some((e=>f(e)))&&e.every(p))}function p(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(p)}function g(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))u(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 y(e,t){for(const{table:n,muts:r}of t)for(const t of r)g(e,n,t)}const m=Math.floor,b=Math.abs,v=(e,t)=>e>t?e:t,w=128,_=127,k=Number.MAX_SAFE_INTEGER,S=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&m(e)===e),x=Array.isArray,E="undefined"!=typeof TextEncoder?new TextEncoder:null,C=E?e=>E.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 I="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});I&&1===I.decode(new Uint8Array).length&&(I=null);let D=class{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}};const A=(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},O=(e,t)=>{for(;t>_;)A(e,w|_&t),t=m(t/128);A(e,_&t)},T=new Uint8Array(3e4),U=T.length/3,j=E&&E.encodeInto?(e,t)=>{if(t.length<U){const n=E.encodeInto(t,T).written||0;O(e,n);for(let t=0;t<n;t++)A(e,T[t])}else L(e,C(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;O(e,r);for(let t=0;t<r;t++)A(e,n.codePointAt(t))},L=(e,t)=>{O(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,s=((e,t)=>e<t?e:t)(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(v(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)})(e,t)},P=(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*v(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},R=(e,t)=>P(e,8).setBigUint64(0,t,!1),M=new DataView(new ArrayBuffer(4)),N=(e,t)=>{switch(typeof t){case"string":A(e,119),j(e,t);break;case"number":S(t)&&b(t)<=2147483647?(A(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),A(e,(t>63?w:0)|(n?64:0)|63&t),t=m(t/64);t>0;)A(e,(t>_?w:0)|_&t),t=m(t/128)})(e,t)):(n=t,M.setFloat32(0,n),M.getFloat32(0)===n?(A(e,124),((e,t)=>{P(e,4).setFloat32(0,t,!1)})(e,t)):(A(e,123),((e,t)=>{P(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":A(e,122),((e,t)=>{P(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)A(e,126);else if(x(t)){A(e,117),O(e,t.length);for(let n=0;n<t.length;n++)N(e,t[n])}else if(t instanceof Uint8Array)A(e,116),L(e,t);else{A(e,118);const n=Object.keys(t);O(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];j(e,s),N(e,t[s])}}break;case"boolean":A(e,t?120:121);break;default:A(e,127)}var n};function $(e){const t=new D;switch(j(t,e.type),"table"in e&&j(t,e.table),"prop"in e&&j(t,e.prop),e.type){case"u-ack":case"u-reject":R(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":j(t,e.yServerRev);break;default:switch(N(t,e.k),e.type){case"aware":L(t,e.u);break;case"doc-open":N(t,e.serverRev),N(t,e.sv);break;case"doc-close":break;case"sv":L(t,e.sv);break;case"u-c":L(t,e.u),R(t,BigInt(e.i));break;case"u-s":L(t,e.u),j(t,e.r||"")}}return(e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const s=e.bufs[r];t.set(s,n),n+=s.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t})(t)}const B=e=>new Error(e),F=B("Unexpected end of array"),W=B("Integer out of Range");let V=class{constructor(e){this.arr=e,this.pos=0}};const K=e=>e.pos!==e.arr.length,z=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,J(e)),H=e=>e.arr[e.pos++],J=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&_)*n,n*=128,r<w)return t;if(t>k)throw W}throw F},q=I?e=>I.decode(z(e)):e=>{let t=J(e);if(0===t)return"";{let n=String.fromCodePoint(H(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(H(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))}},Y=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},G=e=>Y(e,8).getBigUint64(0,!1),Q=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(64&t)>0?-1:1;if(0==(t&w))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&_)*r,r*=128,t<w)return s*n;if(n>k)throw W}throw F},e=>Y(e,4).getFloat32(0,!1),e=>Y(e,8).getFloat64(0,!1),e=>Y(e,8).getBigInt64(0,!1),e=>!1,e=>!0,q,e=>{const t=J(e),n={};for(let r=0;r<t;r++){n[q(e)]=X(e)}return n},e=>{const t=J(e),n=[];for(let r=0;r<t;r++)n.push(X(e));return n},z],X=e=>Q[127-H(e)](e);function Z(e){return l(this,arguments,(function*(){var t,n,r,s;let i=0,l=new Uint8Array(4),a=0,u=[],d=0;try{for(var h,f=!0,p=c(e);!(t=(h=yield o(p.next())).done);f=!0){s=h.value,f=!1;const e=s,t=new DataView(e.buffer,e.byteOffset,e.byteLength);let n=0;for(;n<e.byteLength;)switch(i){case 0:if(n+4>e.byteLength){for(const t of e.slice(n)){if(4===a)break;l[a++]=t,++n}if(a<4)break}else if(a>0&&a<4)for(const t of e.slice(n,n+4-a))l[a++]=t,++n;case 1:d=4===a?new DataView(l.buffer,0,4).getUint32(0,!1):t.getUint32(n,!1),a?a=0:n+=4;case 2:if(n>=e.byteLength){i=2;break}if(n+d>e.byteLength)u.push(e.slice(n)),d-=e.byteLength-n,i=2,n=e.byteLength;else{if(u.length>0){const t=new Uint8Array(u.reduce(((e,t)=>e+t.byteLength),d));let r=0;for(const e of u)t.set(e,r),r+=e.byteLength;t.set(e.slice(n,n+d),r),u=[],yield yield o(t)}else yield yield o(e.slice(n,n+d));n+=d,i=0}}}}catch(e){n={error:e}}finally{try{f||t||!(r=p.return)||(yield o(r.call(p)))}finally{if(n)throw n.error}}}))}let ee=!1;function te(e,t){return s(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){ee||(ee=!0)}}))}function ne(e,t){e.cloud.usingServiceWorker?te(e,t):e.localSyncEvent.next({purpose:t})}const re="fromBase64"in Uint8Array,se="toBase64"in Uint8Array.prototype,ie="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):re?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},oe="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):se?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(""))};class le extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function ce(e,n){return new Promise(((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:t=>{e.next(void 0),r(t)},onCancel:()=>{e.next(void 0),s(new t.AbortError("User cancelled"))}});e.next(i)}))}function ae(e,t,...n){return ce(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function ue(e,t,n){return s(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 ce(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 de(e,t,n){return s(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 ce(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s}))}function he(e){return s(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 u=yield pe(e.cloud.options.databaseUrl,s);return yield e.table("$logins").update(a.sub,{accessToken:u.accessToken,accessTokenExpiration:u.accessTokenExpiration,claims:u.claims,license:u.license,data:u.data}),u}))}function fe(e,n,r,i,o){return s(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 pe(e,n):yield function(e,n,r,i){return s(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:s,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(!s||!o)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=s;const l=function(e){const t=oe(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));e.publicKey=o;try{const t=yield n({public_key:l,hints:i});if("error"===t.type)throw new le(t);if("tokens"!==t.type)throw new Error(`Unexpected response type from token endpoint: ${t.type}`);return e.accessToken=t.accessToken,e.accessTokenExpiration=new Date(t.accessTokenExpiration),e.refreshToken=t.refreshToken,t.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(t.refreshTokenExpiration)),e.userId=t.claims.sub,e.email=t.claims.email,e.name=t.claims.name,e.claims=t.claims,e.license={type:t.userType,status:t.claims.license||"ok"},e.data=t.data,null!=t.evalDaysLeft&&(e.license.evalDaysLeft=t.evalDaysLeft),null!=t.userValidUntil&&(e.license.validUntil=new Date(t.userValidUntil)),t.alerts&&t.alerts.length>0&&(yield ce(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof le)throw yield ae(r,e.title,{type:"error",messageCode:e.messageCode,message:e.message,messageParams:{}}),e;let n="We're having a problem authenticating right now.";if(e instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":t.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 ae(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch((()=>{}))}throw e}}))}(n,r,i,o)}))}function pe(e,t){return s(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=oe(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 le(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 ge=new WeakMap;class ye{constructor(e,t){ge.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then((n=>new ye(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)})))}save(){return s(this,void 0,void 0,(function*(){ge.get(this).table("$logins").put(this)}))}}const me={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(me),Object.freeze(me.claims)}catch(e){}function be(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function ve(e){return s(this,void 0,void 0,(function*(){const t=yield we(e);if(t){if(!(yield function(e,t,n){return s(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 ce(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 we(e,{deleteUnsyncedData:!0})}}))}function we(e){return s(this,arguments,void 0,(function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,(n=>s(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 r&&(yield be(e.cloud.currentUser,(e=>e.userId===me.userId)),yield e.cloud.sync({purpose:"pull",wait:!0})),n}))}class _e extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}function ke(e,...t){globalThis.console[e](...t)}function Se(e,t){return s(this,void 0,void 0,(function*(){var n;const r=yield e.getCurrentUser(),i=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield he(e),!1}const o=new ye(e,{claims:{},lastLogin:new Date(0)});return yield fe(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||function(e){const{userInteraction:t}=e.cloud;return function(n){return s(this,arguments,void 0,(function*({public_key:n,hints:r}){var s;let i;const o=null===(s=e.cloud.options)||void 0===s?void 0:s.databaseUrl;if(!o)throw new Error("No database URL given.");if("demo"===(null==r?void 0:r.grant_type))i={demo_user:yield ue(t,"Enter a demo user email",(null==r?void 0:r.email)||(null==r?void 0:r.userId)),grant_type:"demo",scopes:["ACCESS_DB"],public_key:n};else if((null==r?void 0:r.otpId)&&r.otp)i={grant_type:"otp",otp_id:r.otpId,otp:r.otp,scopes:["ACCESS_DB"],public_key:n};else{const e=yield ue(t,"Enter email address",null==r?void 0:r.email);i=/@demo.local$/.test(e)?{demo_user:e,grant_type:"demo",scopes:["ACCESS_DB"],public_key:n}:{email:e,grant_type:"otp",scopes:["ACCESS_DB"]}}const l=yield fetch(`${o}/token`,{body:JSON.stringify(i),method:"post",headers:{"Content-Type":"application/json",mode:"cors"}});if(200!==l.status){const e=yield l.text();throw yield ae(t,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch((()=>{})),new _e(l,e)}const c=yield l.json();if("tokens"===c.type||"error"===c.type)return c;if("otp"===i.grant_type&&"email"in i){if("otp-sent"!==c.type)throw new Error(`Unexpected response from ${o}/token`);const e=yield de(t,i.email),r=Object.assign(Object.assign({},i),{otp:e||"",otp_id:c.otp_id,public_key:n});let s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===s.status;){const e=yield s.text();r.otp=yield de(t,i.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${o}/token`,{body:JSON.stringify(r),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield s.text();throw new _e(s,e)}return yield s.json()}throw new Error(`Unexpected response from ${o}/token`)}))}}(e),e.cloud.userInteraction,t),i!==me.userId&&o.userId!==i&&(yield ve(e)),yield function(e,t){return s(this,void 0,void 0,(function*(){const n=e.table("$logins");yield e.transaction("rw",n,(e=>s(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&&(ke("debug","Login context property names:",Object.keys(t)),ke("debug","Login context property names:",Object.keys(t)),ke("debug","Login context:",t),ke("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})))),yield be(e.cloud.currentUser,(e=>e.userId===t.userId))}))}(e,o),ne(e,"pull"),o.userId!==i}))}const xe={},Ee="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;Ee&&Ee.ready.then((e=>xe.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 Ce{constructor(e){this.name=e}subscribe(e){if(!Ee)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 Ee.addEventListener("message",t),()=>Ee.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}))):xe.registration&&(null===(t=xe.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const Ie=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class De extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new Ce(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){Ie.has(e)?Ie.get(e).push(t):Ie.set(e,[t])}(`lbc-${e}`,r);try{t instanceof Ce?i=t.subscribe((e=>n.next(e))):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=Ie.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof Ce?i():t.removeEventListener("message",s)}})),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=Ie.get(e.type);t&&t.forEach((t=>{try{t(e)}catch(e){}}))}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function Ae(e){return s(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 oe(s)}))}function Oe(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 Te(e){return`$${e}_mutations`}function Ue(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 je=[].concat;function Le(e){return je.apply([],e)}function Pe(e,t){return s(this,arguments,void 0,(function*(e,t,{since:n={},limit:r=1/0}={}){const i=yield Promise.all(e.map((e=>s(this,void 0,void 0,(function*(){const t=Ue(e.name),s=n[t];let i=s?e.where("rev").above(s):e;r<1/0&&(i=i.limit(r));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=new Set(Object.keys(e.changeSpecs[0])),r=""+e.keys[0],s=t.get(r);for(let t=s.length-1;t>=0;--t){const{txid:r,updateSpec:i}=s[t];if(r===e.txid)break;for(const e of Object.keys(i))n.delete(e)}return 0!==n.size})),e}(o);return o.map((e=>({table:t,mut:e})))}))))),o=Le(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 Re(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:Me}={};const Ne={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 $e(...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 Ne;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,Me.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:Ne),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 Be={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 Fe={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 We={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var Ve={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Ke={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},ze={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const He="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Je=["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=He[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}})),{});function qe(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=Qe[e[n]];return t}(oe(e))}function Ye(e){return ie(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+=Ge[e[n]];return t}(e))}const Ge={"-":"=",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:"+","|":"/"},Qe={};for(const e of Object.keys(Ge))Qe[Ge[e]]=e;var Xe={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:qe(e)}),revive:({v:e})=>{const t=Ye(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Ze{constructor(e,t){this.buf=e,this.type=t}}function et(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 tt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var nt={Blob:{test:(e,t)=>"Blob"===t||e instanceof Ze,replace:e=>({$t:"Blob",v:oe(e instanceof Ze?e.buf:tt(et(e))),type:e.type}),revive:({type:e,v:t})=>{const n=ie(t);return void 0!==typeof Blob?new Blob([n]):new Ze(n.buffer,e)}}};const rt={...Fe,...We,...Ve,...Ke,...ze,...Je,...Xe,...nt};function st(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:oe(tt(et(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=ie(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const lt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class ct{toString(){return this.v}constructor(e){this.v=e}}const at=lt?{}:{bigint:{test:e=>e instanceof ct,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new ct(e)}},ut=Object.assign(Object.assign(Object.assign(Object.assign({},it),at),ot),{PropModification:{test:e=>e instanceof t.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var n=function(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var 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}(e,["$t"]);return new t.PropModification(n)}}}),dt=$e(rt,ut),ht=function(...e){const t=$e(rt,Be,...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),s=new Blob(n.map((e=>{const t=new ArrayBuffer(4);return new DataView(t).setUint32(0,"byteLength"in e?e.byteLength:e.size),new Blob([t,e])})));return[s,r]},async parse(e,n){let r=0;const s=[],i=await st(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 st(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);function ft(e,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=e.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(((e,r)=>{const s=!c.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach(((e,o)=>{if(Array.isArray(e)){a===i&&(a=pt(i,s));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===i&&(a=pt(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const u=`${e}:${n.userId}`;l.keys[o]=u,s&&t.setByKeyPath(l.values[o],c.keyPath,u)}}))})),s.push(a)}return s}function pt(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 gt=new WeakMap;function yt(e){return s(this,void 0,void 0,(function*(){var t,n;const r=(null!==(n=null===(t=gt.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 mt(e,t,n,r,i,o,l,c,a){return s(this,void 0,void 0,(function*(){const s={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},u=yield he(i),d=null==u?void 0:u.accessToken;d&&(s.Authorization=`Bearer ${d}`);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:r,changes:ft(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=dt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:s,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));gt.set(e,new Date(Date.now()+1e3*t))}else gt.delete(e)}}(i,p),!p.ok)throw new _e(p);if("application/x-bison"===p.headers.get("content-type"))return ht.fromBinary(yield p.blob());{const e=yield p.text();return dt.parse(e)}}))}function bt(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let vt=!1;function wt(e,t,n,r){return s(this,void 0,void 0,(function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter((e=>t[e].markedForSync)).map((e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r})))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter((e=>t[e].markedForSync))).delete()}))}function _t(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(e,n,r){return s(this,void 0,void 0,(function*(){const s=yield e.bulkGet(n),i=[],o=[];n.forEach(((n,l)=>{const c=s[l];if(c){for(const[s,i]of Object.entries(r[l]))if(s===e.schema.primKey.keyPath){if(0!==t.cmp(i,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(c,s,i);i.push(n),o.push(c)}})),yield null==e.schema.primKey.keyPath?e.bulkPut(o,i):e.bulkPut(o)}))}function St(e,n){return s(this,void 0,void 0,(function*(){for(const{table:r,muts:s}of e){if(!n.dx._allTables[r])continue;const e=n.table(r),{primaryKey:i}=e.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 e.bulkAdd(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)})),yield e.bulkAdd(n.values));break;case"upsert":i.outbound?yield e.bulkPut(n.values,r):(r.forEach(((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)})),yield e.bulkPut(n.values));break;case"modify":1===r.length?yield e.update(r[0],n.changeSpec):yield e.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield kt(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}}))}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(vt=navigator.onLine,self.addEventListener("online",(()=>vt=!0)),self.addEventListener("offline",(()=>vt=!1)));const xt="dexie-cloud-syncer";function Et(e,t){return e.where("i").between(t,1/0,!0).toArray()}const Ct=()=>new Map,It=e=>{const t=Ct();return e.forEach(((e,n)=>{t.set(n,e)})),t},Dt=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},At=()=>new Set,Ot=e=>e[e.length-1],Tt=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},Ut=Array.from,jt=Array.isArray;class Lt{constructor(){this._observers=Ct()}on(e,t){return Dt(this._observers,e,At).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 Ut((this._observers.get(e)||Ct()).values()).forEach((e=>e(...t)))}destroy(){this._observers=Ct()}}class Pt{constructor(){this._observers=Ct()}on(e,t){Dt(this._observers,e,At).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 Ut((this._observers.get(e)||Ct()).values()).forEach((e=>e(...t)))}destroy(){this._observers=Ct()}}const Rt=Math.floor,Mt=Math.abs,Nt=(e,t)=>e<t?e:t,$t=(e,t)=>e>t?e:t,Bt=e=>0!==e?e<0:1/e<0,Ft=64,Wt=128,Vt=127,Kt=Number.MAX_SAFE_INTEGER,zt=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&Rt(e)===e),Ht=/^\s*/g,Jt=/([A-Z])/g,qt=(e,t)=>(e=>e.replace(Ht,""))(e.replace(Jt,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),Yt="undefined"!=typeof TextEncoder?new TextEncoder:null,Gt=Yt?e=>Yt.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 Qt="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Qt&&1===Qt.decode(new Uint8Array).length&&(Qt=null);class Xt{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Zt=()=>new Xt,en=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},tn=(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},nn=tn,rn=(e,t)=>{for(;t>Vt;)tn(e,Wt|Vt&t),t=Rt(t/128);tn(e,Vt&t)},sn=(e,t)=>{const n=Bt(t);for(n&&(t=-t),tn(e,(t>63?Wt:0)|(n?Ft:0)|63&t),t=Rt(t/64);t>0;)tn(e,(t>Vt?Wt:0)|Vt&t),t=Rt(t/128)},on=new Uint8Array(3e4),ln=on.length/3,cn=Yt&&Yt.encodeInto?(e,t)=>{if(t.length<ln){const n=Yt.encodeInto(t,on).written||0;rn(e,n);for(let t=0;t<n;t++)tn(e,on[t])}else un(e,Gt(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;rn(e,r);for(let t=0;t<r;t++)tn(e,n.codePointAt(t))},an=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=Nt(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($t(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},un=(e,t)=>{rn(e,t.byteLength),an(e,t)},dn=(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*$t(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},hn=new DataView(new ArrayBuffer(4)),fn=(e,t)=>{switch(typeof t){case"string":tn(e,119),cn(e,t);break;case"number":zt(t)&&Mt(t)<=2147483647?(tn(e,125),sn(e,t)):(n=t,hn.setFloat32(0,n),hn.getFloat32(0)===n?(tn(e,124),((e,t)=>{dn(e,4).setFloat32(0,t,!1)})(e,t)):(tn(e,123),((e,t)=>{dn(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":tn(e,122),((e,t)=>{dn(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)tn(e,126);else if(jt(t)){tn(e,117),rn(e,t.length);for(let n=0;n<t.length;n++)fn(e,t[n])}else if(t instanceof Uint8Array)tn(e,116),un(e,t);else{tn(e,118);const n=Object.keys(t);rn(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];cn(e,s),fn(e,t[s])}}break;case"boolean":tn(e,t?120:121);break;default:tn(e,127)}var n};class pn extends Xt{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&rn(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const gn=e=>{e.count>0&&(sn(e.encoder,1===e.count?e.s:-e.s),e.count>1&&rn(e.encoder,e.count-2))};class yn{constructor(){this.encoder=new Xt,this.s=0,this.count=0}write(e){this.s===e?this.count++:(gn(this),this.count=1,this.s=e)}toUint8Array(){return gn(this),en(this.encoder)}}const mn=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);sn(e.encoder,t),e.count>1&&rn(e.encoder,e.count-2)}};class bn{constructor(){this.encoder=new Xt,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(mn(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return mn(this),en(this.encoder)}}class vn{constructor(){this.sarr=[],this.s="",this.lensE=new yn}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 Xt;return this.sarr.push(this.s),this.s="",cn(e,this.sarr.join("")),an(e,this.lensE.toUint8Array()),en(e)}}const wn=e=>new Error(e),_n=()=>{throw wn("Method unimplemented")},kn=()=>{throw wn("Unexpected case")},Sn=wn("Unexpected end of array"),xn=wn("Integer out of Range");class En{constructor(e){this.arr=e,this.pos=0}}const Cn=e=>new En(e),In=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,An(e)),Dn=e=>e.arr[e.pos++],An=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&Vt)*n,n*=128,r<Wt)return t;if(t>Kt)throw xn}throw Sn},On=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&Ft)>0?-1:1;if(0==(t&Wt))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&Vt)*r,r*=128,t<Wt)return s*n;if(n>Kt)throw xn}throw Sn},Tn=Qt?e=>Qt.decode(In(e)):e=>{let t=An(e);if(0===t)return"";{let n=String.fromCodePoint(Dn(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Dn(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))}},Un=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},jn=[e=>{},e=>null,On,e=>Un(e,4).getFloat32(0,!1),e=>Un(e,8).getFloat64(0,!1),e=>Un(e,8).getBigInt64(0,!1),e=>!1,e=>!0,Tn,e=>{const t=An(e),n={};for(let r=0;r<t;r++){n[Tn(e)]=Ln(e)}return n},e=>{const t=An(e),n=[];for(let r=0;r<t;r++)n.push(Ln(e));return n},In],Ln=e=>jn[127-Dn(e)](e);class Pn extends En{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){var e;return 0===this.count&&(this.s=this.reader(this),(e=this).pos!==e.arr.length?this.count=An(this)+1:this.count=-1),this.count--,this.s}}class Rn extends En{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=On(this);const e=Bt(this.s);this.count=1,e&&(this.s=-this.s,this.count=An(this)+2)}return this.count--,this.s}}class Mn extends En{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=On(this),t=1&e;this.diff=Rt(e/2),this.count=1,t&&(this.count=An(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Nn{constructor(e){this.decoder=new Rn(e),this.str=Tn(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}}const $n=crypto.getRandomValues.bind(crypto),Bn=()=>$n(new Uint32Array(1))[0],Fn=[1e7]+-1e3+-4e3+-8e3+-1e11,Wn=()=>Fn.replace(/[018]/g,(e=>(e^Bn()&15>>e/4).toString(16))),Vn=Date.now,Kn=e=>new Promise(e);Promise.all.bind(Promise);const zn=e=>void 0===e?null:e;let Hn=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},Jn=!0;try{"undefined"!=typeof localStorage&&localStorage&&(Hn=localStorage,Jn=!1)}catch(ic){}const qn=Hn,Yn=Object.assign,Gn=Object.keys,Qn=e=>Gn(e).length,Xn=e=>Gn(e).length,Zn=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),er=Object.freeze,tr=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||tr(e[t])}return er(e)},nr=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&nr(e,t,n+1)}},rr=(e,t)=>{if(null==e||null==t)return((e,t)=>e===t)(e,t);if(e.constructor!==t.constructor)return!1;if(e===t)return!0;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)||!rr(e.get(n),t.get(n)))return!1;break;case Object:if(Qn(e)!==Qn(t))return!1;for(const n in e)if(!Zn(e,n)||!rr(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(!rr(e[n],t[n]))return!1;break;default:return!1}return!0},sr="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let ir;const or=e=>(()=>{if(void 0===ir)if(sr){ir=Ct();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&ir.set(t,""),t=r):null!==t&&(ir.set(t,r),t=null)}null!==t&&ir.set(t,"")}else"object"==typeof location?(ir=Ct(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");ir.set(`--${qt(t,"-")}`,n),ir.set(`-${qt(t,"-")}`,n)}}))):ir=Ct();return ir})().has(e),lr=e=>zn(sr?process.env[e.toUpperCase().replaceAll("-","_")]:qn.getItem(e)),cr=e=>or("--"+e)||null!==lr(e);cr("production");var ar;sr&&(ar=process.env.FORCE_COLOR,["true","1","2"].includes(ar))||!or("--no-colors")&&!cr("no-color")&&(!sr||process.stdout.isTTY)&&(!sr||or("--color")||null!==lr("COLORTERM")||(lr("TERM")||"").includes("color"));class ur{constructor(e,t){this.left=e,this.right=t}}const dr=(e,t)=>new ur(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const hr=Symbol,fr=hr(),pr=hr(),gr=hr(),yr=hr(),mr=hr(),br=hr(),vr=hr(),wr=hr(),_r=hr(),kr=(dr("font-weight","bold"),dr("font-weight","normal"),dr("color","blue"),dr("color","green"),dr("color","grey"),dr("color","red"),dr("color","purple"),dr("color","orange"),dr("color","black"),At()),Sr=e=>({[Symbol.iterator](){return this},next:e}),xr=(e,t)=>Sr((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}}));class Er{constructor(e,t){this.clock=e,this.len=t}}class Cr{constructor(){this.clients=new Map}}const Ir=(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])as(e,s,o.clock,o.len,n)}})),Dr=(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=Rt((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)},Ar=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=$t(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n}))},Or=(e,t,n,r)=>{Dt(e.clients,t,(()=>[])).push(new Er(n,r))},Tr=(e,t)=>{rn(e.restEncoder,t.clients.size),Ut(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),rn(e.restEncoder,t);const r=n.length;rn(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},Ur=(e,t,n)=>{const r=new Cr,s=An(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=An(e.restDecoder),i=An(e.restDecoder),o=n.clients.get(s)||[],l=ns(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&Or(r,s,l,i-l);let e=ss(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Ki(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,Ki(t,c,i-c.id.clock)),c.delete(t))}else Or(r,s,n,i-n)}}if(r.clients.size>0){const e=new Br;return rn(e.restEncoder,0),Tr(e,r),e.toUint8Array()}return null},jr=Bn;class Lr extends Lt{constructor({guid:e=Wn(),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=jr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new es,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=Kn((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const l=()=>Kn((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||gs(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(Ut(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return gs(this,e,t)}get(e,t=Ls){const n=Dt(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==Ls&&r!==t){if(r===Ls){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,Xs)}getText(e=""){return this.get(e,yi)}getMap(e=""){return this.get(e,ei)}getXmlElement(e=""){return this.get(e,vi)}getXmlFragment(e=""){return this.get(e,bi)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){this.isDestroyed=!0,Ut(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new Lr({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,gs(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 Pr{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=An(this.restDecoder),this.dsCurrVal}readDsLen(){const e=An(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class Rr extends Pr{constructor(e){super(e),this.keys=[],An(e),this.keyClockDecoder=new Mn(In(e)),this.clientDecoder=new Rn(In(e)),this.leftClockDecoder=new Mn(In(e)),this.rightClockDecoder=new Mn(In(e)),this.infoDecoder=new Pn(In(e),Dn),this.stringDecoder=new Nn(In(e)),this.parentInfoDecoder=new Pn(In(e),Dn),this.typeRefDecoder=new Rn(In(e)),this.lenDecoder=new Rn(In(e))}readLeftID(){return new Yr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Yr(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 Ln(this.restDecoder)}readBuf(){return In(this.restDecoder)}readJSON(){return Ln(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 Mr{constructor(){this.restEncoder=Zt()}toUint8Array(){return en(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){rn(this.restEncoder,e)}writeDsLen(e){rn(this.restEncoder,e)}}class Nr extends Mr{writeLeftID(e){rn(this.restEncoder,e.client),rn(this.restEncoder,e.clock)}writeRightID(e){rn(this.restEncoder,e.client),rn(this.restEncoder,e.clock)}writeClient(e){rn(this.restEncoder,e)}writeInfo(e){nn(this.restEncoder,e)}writeString(e){cn(this.restEncoder,e)}writeParentInfo(e){rn(this.restEncoder,e?1:0)}writeTypeRef(e){rn(this.restEncoder,e)}writeLen(e){rn(this.restEncoder,e)}writeAny(e){fn(this.restEncoder,e)}writeBuf(e){un(this.restEncoder,e)}writeJSON(e){cn(this.restEncoder,JSON.stringify(e))}writeKey(e){cn(this.restEncoder,e)}}class $r{constructor(){this.restEncoder=Zt(),this.dsCurrVal=0}toUint8Array(){return en(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,rn(this.restEncoder,t)}writeDsLen(e){0===e&&kn(),rn(this.restEncoder,e-1),this.dsCurrVal+=e}}class Br extends $r{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new bn,this.clientEncoder=new yn,this.leftClockEncoder=new bn,this.rightClockEncoder=new bn,this.infoEncoder=new pn(nn),this.stringEncoder=new vn,this.parentInfoEncoder=new pn(nn),this.typeRefEncoder=new yn,this.lenEncoder=new yn}toUint8Array(){const e=Zt();return rn(e,0),un(e,this.keyClockEncoder.toUint8Array()),un(e,this.clientEncoder.toUint8Array()),un(e,this.leftClockEncoder.toUint8Array()),un(e,this.rightClockEncoder.toUint8Array()),un(e,en(this.infoEncoder)),un(e,this.stringEncoder.toUint8Array()),un(e,en(this.parentInfoEncoder)),un(e,this.typeRefEncoder.toUint8Array()),un(e,this.lenEncoder.toUint8Array()),an(e,en(this.restEncoder)),en(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){fn(this.restEncoder,e)}writeBuf(e){un(this.restEncoder,e)}writeJSON(e){fn(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 Fr=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{ns(t,n)>e&&r.set(n,e)})),ts(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),rn(e.restEncoder,r.size),Ut(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=$t(r,t[0].id.clock);const s=ss(t,r);rn(e.restEncoder,t.length-s),e.writeClient(n),rn(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)}))},Wr=(e,t,n,r=new Rr(e))=>gs(t,(e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=Ct(),r=An(e.restDecoder);for(let s=0;s<r;s++){const r=An(e.restDecoder),s=new Array(r),i=e.readClient();let o=An(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 xi(Qr(i,o),t),o+=t;break}case 10:{const t=An(e.restDecoder);s[n]=new qi(Qr(i,o),t),o+=t;break}default:{const l=0==(192&r),c=new zi(Qr(i,o),null,(r&Wt)===Wt?e.readLeftID():null,null,(r&Ft)===Ft?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,l&&32==(32&r)?e.readString():null,Hi(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=Ut(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 es,c=new Map,a=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let u=o.refs[o.i++];const d=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(u.constructor!==qi){const s=Dt(d,u.id.client,(()=>ns(t,u.id.client)))-u.id.clock;if(s<0)r.push(u),a(u.id.client,u.id.clock-1),h();else{const i=u.getMissing(e,t);if(null!==i){r.push(u);const e=n.get(i)||{refs:[],i:0};if(e.refs.length!==e.i){u=e.refs[e.i++];continue}a(i,ns(t,i)),h()}else(0===s||s<u.length)&&(u.integrate(e,s),d.set(u.id.client,u.id.clock+u.length))}}if(r.length>0)u=r.pop();else if(null!==o&&o.i<o.refs.length)u=o.refs[o.i++];else{if(o=i(),null===o)break;u=o.refs[o.i++]}}if(l.clients.size>0){const e=new Br;return Fr(e,l,new Map),rn(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<ns(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=ws([l.update,o.update])}}else s.pendingStructs=o;const c=Ur(r,e,s);if(s.pendingDs){const t=new Rr(Cn(s.pendingDs));An(t.restDecoder);const n=Ur(t,e,s);s.pendingDs=c&&n?ws([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,Vr(e.doc,t)}}),n,!1),Vr=(e,t,n,r=Rr)=>{const s=Cn(t);Wr(s,e,n,new r(s))};class Kr{constructor(){this.l=[]}}const zr=()=>new Kr,Hr=(e,t)=>e.l.push(t),Jr=(e,t)=>{const n=e.l;n.length;e.l=n.filter((e=>t!==e)),e.l.length},qr=(e,t,n)=>nr(e.l,[t,n]);class Yr{constructor(e,t){this.client=e,this.clock=t}}const Gr=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Qr=(e,t)=>new Yr(e,t),Xr=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!Dr(t.ds,e.id),Zr=(e,t)=>{const n=Dt(e.meta,Zr,At),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<ns(r,n)&&ls(e,Qr(n,t))})),Ir(e,t.ds,(e=>{})),n.add(t))};class es{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const ts=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},ns=(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},rs=(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 kn()}n.push(t)},ss=(e,t)=>{let n=0,r=e.length-1,s=e[r],i=s.id.clock;if(i===t)return r;let o=Rt(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=Rt((n+r)/2)}throw kn()},is=(e,t)=>{const n=e.clients.get(t.client);return n[ss(n,t.clock)]},os=(e,t,n)=>{const r=ss(t,n),s=t[r];return s.id.clock<n&&s instanceof zi?(t.splice(r+1,0,Ki(e,s,n-s.id.clock)),r+1):r},ls=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[os(e,n,t.clock)]},cs=(e,t,n)=>{const r=t.clients.get(n.client),s=ss(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==xi&&r.splice(s+1,0,Ki(e,i,n.clock-i.id.clock+1)),i},as=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=os(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&os(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class us{constructor(e,t,n){this.doc=e,this.deleteSet=new Cr,this.beforeState=ts(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 ds=(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)))&&(Ar(t.deleteSet),((e,t)=>{Fr(e,t.doc.store,t.beforeState)})(e,t),Tr(e,t.deleteSet),!0),hs=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Dt(e.changed,t,At).add(n)},fs=(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 zi&&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},ps=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{Ar(i),n.afterState=ts(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)),qr(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),nr(e,[]),n._needFormattingCleanup&&fi(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=ss(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 zi&&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=Nt(r.length-1,1+ss(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+fs(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=$t(ss(e,r),1);for(let t=e.length-1;t>=n;)t-=1+fs(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=ss(r,n);i+1<r.length&&fs(r,i+1)>1||i>0&&fs(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{kr.forEach((t=>t.print(e)))})(wr,fr,"[yjs] ",pr,br,"Changed the client-id because another client seems to be using it."),r.clientID=jr()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new Nr;ds(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Br;ds(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])):ps(e,t+1)}}},gs=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new us(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&&ps(s,0)}}return o};class ys{constructor(e,t){this.gen=function*(e){const t=An(e.restDecoder);for(let n=0;n<t;n++){const t=An(e.restDecoder),n=e.readClient();let r=An(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=An(e.restDecoder);yield new qi(Qr(n,r),t),r+=t}else if(0!=(31&t)){const s=0==(192&t),i=new zi(Qr(n,r),null,(t&Wt)===Wt?e.readLeftID():null,null,(t&Ft)===Ft?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,s&&32==(32&t)?e.readString():null,Hi(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new xi(Qr(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===qi);return this.curr}}class ms{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const bs=(e,t=$r,n=Rr)=>{const r=new t,s=new ys(new n(Cn(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++,rn(r.restEncoder,t),rn(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===qi&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,rn(r.restEncoder,t),rn(r.restEncoder,o));const l=Zt();return rn(l,e),((e,t)=>{an(e,en(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return rn(r.restEncoder,0),r.toUint8Array()},vs=(e,t)=>{if(e.constructor===xi){const{client:n,clock:r}=e.id;return new xi(Qr(n,r+t),e.length-t)}if(e.constructor===qi){const{client:n,clock:r}=e.id;return new qi(Qr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new zi(Qr(r,s+t),null,Qr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},ws=(e,t=Rr,n=Br)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(Cn(e))));let s=r.map((e=>new ys(e,!0))),i=null;const o=new n,l=new ms(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===qi?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)ks(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===qi)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{ks(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new qi(Qr(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===qi?i.struct.length-=t:n=vs(n,t)),i.struct.mergeWith(n)||(ks(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!==qi;n=e.next())ks(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(ks(l,i.struct,i.offset),i=null),Ss(l);const c=r.map((e=>(e=>{const t=new Cr,n=An(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=An(e.restDecoder),r=An(e.restDecoder);if(r>0){const s=Dt(t.clients,n,(()=>[]));for(let t=0;t<r;t++)s.push(new Er(e.readDsClock(),e.readDsLen()))}}return t})(e))),a=(e=>{const t=new Cr;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++)Tt(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}}));return Ar(t),t})(c);return Tr(o,a),o.toUint8Array()},_s=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:en(e.encoder.restEncoder)}),e.encoder.restEncoder=Zt(),e.written=0)},ks=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&_s(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),rn(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Ss=e=>{_s(e);const t=e.encoder.restEncoder;rn(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];rn(t,r.written),an(t,r.restEncoder)}},xs="You must not compute changes after the event-handler fired.";class Es{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=Cs(this.currentTarget,this.target))}deletes(e){return Dr(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw wn(xs);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=Ot(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=Ot(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=Ot(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 wn(xs);const t=this.target,n=At(),r=At(),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 Cs=(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},Is=()=>{((...e)=>{e.unshift(wr),kr.forEach((t=>t.print(e)))})("Invalid access: Add Yjs type to a document before reading data.")};let Ds=0;class As{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=Ds++}}const Os=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=Ds++},Ts=(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)=>Mt(t-e.index)<Mt(t-n.index)?e:n));let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=Ds++})(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&&Mt(n.index-s)<r.parent.length/80?(Os(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return Os(r,t,n),r}{const r=new As(t,n);return e.push(r),r}})(e._searchMarker,r,s)},Us=(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=$t(t,s.index+n))}},js=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;Dt(s,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;qr(r._eH,n,t)};class Ls{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=zr(),this._dEH=zr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw _n()}clone(){throw _n()}_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){Hr(this._eH,e)}observeDeep(e){Hr(this._dEH,e)}unobserve(e){Jr(this._eH,e)}unobserveDeep(e){Jr(this._dEH,e)}toJSON(){}}const Ps=(e,t,n)=>{e.doc??Is(),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},Rs=e=>{e.doc??Is();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},Ms=(e,t)=>{let n=0,r=e._start;for(e.doc??Is();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 Ms(e,((r,s)=>{n.push(t(r,s,e))})),n},$s=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}}}},Bs=(e,t)=>{e.doc??Is();const n=Ts(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}},Fs=(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 u=()=>{a.length>0&&(s=new zi(Qr(o,ns(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new ji(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(u(),n.constructor){case Uint8Array:case ArrayBuffer:s=new zi(Qr(o,ns(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Ei(new Uint8Array(n))),s.integrate(e,0);break;case Lr:s=new zi(Qr(o,ns(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Di(n)),s.integrate(e,0);break;default:if(!(n instanceof Ls))throw new Error("Unexpected content type in insert operation");s=new zi(Qr(o,ns(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new Vi(n)),s.integrate(e,0)}}})),u()},Ws=()=>wn("Length exceeded!"),Vs=(e,t,n,r)=>{if(n>t._length)throw Ws();if(0===n)return t._searchMarker&&Us(t._searchMarker,n,r.length),Fs(e,t,null,r);const s=n,i=Ts(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&&ls(e,Qr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&Us(t._searchMarker,s,r.length),Fs(e,t,o,r)},Ks=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=Ts(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&&ls(e,Qr(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&ls(e,Qr(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw Ws();t._searchMarker&&Us(t._searchMarker,s,-i+r)},zs=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Hs=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new ji([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ji([r]);break;case Uint8Array:l=new Ei(r);break;case Lr:l=new Di(r);break;default:if(!(r instanceof Ls))throw new Error("Unexpected content type");l=new Vi(r)}new zi(Qr(o,ns(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},Js=(e,t)=>{e.doc??Is();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},qs=e=>{const t={};return e.doc??Is(),e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Ys=(e,t)=>{e.doc??Is();const n=e._map.get(t);return void 0!==n&&!n.deleted},Gs=e=>{return e.doc??Is(),t=e._map.entries(),n=e=>!e[1].deleted,Sr((()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e}));var t,n};class Qs extends Es{}class Xs extends Ls{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Xs;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Xs}clone(){const e=new Xs;return e.insert(0,this.toArray().map((e=>e instanceof Ls?e.clone():e))),e}get length(){return this.doc??Is(),this._length}_callObserver(e,t){super._callObserver(e,t),js(this,e,new Qs(this,e))}insert(e,t){null!==this.doc?gs(this.doc,(n=>{Vs(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?gs(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;Fs(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?gs(this.doc,(n=>{Ks(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return Bs(this,e)}toArray(){return Rs(this)}slice(e=0,t=this.length){return Ps(this,e,t)}toJSON(){return this.map((e=>e instanceof Ls?e.toJSON():e))}map(e){return Ns(this,e)}forEach(e){Ms(this,e)}[Symbol.iterator](){return $s(this)}_write(e){e.writeTypeRef(Ri)}}class Zs extends Es{constructor(e,t,n){super(e,t),this.keysChanged=n}}class ei extends Ls{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 ei}clone(){const e=new ei;return this.forEach(((t,n)=>{e.set(n,t instanceof Ls?t.clone():t)})),e}_callObserver(e,t){js(this,e,new Zs(this,e,t))}toJSON(){this.doc??Is();const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof Ls?r.toJSON():r}})),e}get size(){return[...Gs(this)].length}keys(){return xr(Gs(this),(e=>e[0]))}values(){return xr(Gs(this),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return xr(Gs(this),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this.doc??Is(),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?gs(this.doc,(t=>{zs(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?gs(this.doc,(n=>{Hs(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return Js(this,e)}has(e){return Ys(this,e)}clear(){null!==this.doc?gs(this.doc,(e=>{this.forEach((function(t,n,r){zs(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(Mi)}}const ti=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||Xn(e)===Xn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,((e,n)=>(void 0!==e||Zn(t,n))&&t[n]===e)))(e,t);class ni{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&kn(),this.right.content.constructor===Oi)this.right.deleted||oi(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const ri=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===Oi)t.right.deleted||oi(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&ls(e,Qr(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},si=(e,t,n,r)=>{const s=new Map,i=r?Ts(t,n):null;if(i){const t=new ni(i.p.left,i.p,i.index,s);return ri(e,t,n-i.index)}{const r=new ni(null,t._start,0,s);return ri(e,r,n)}},ii=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===Oi&&ti(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 zi(Qr(i,ns(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new Oi(o,r));a.integrate(e,0),n.right=a,n.forward()}))},oi=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},li=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===Oi&&ti(t[e.right.content.key]??null,e.right.content.value));)e.forward()},ci=(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(!ti(a,c)){o.set(l,a);const{left:r,right:u}=n;n.right=new zi(Qr(i,ns(s.store,i)),r,r&&r.lastId,u,u&&u.id,t,null,new Oi(l,c)),n.right.integrate(e,0),n.forward()}}return o},ai=(e,t,n,r,s)=>{n.currentAttributes.forEach(((e,t)=>{void 0===s[t]&&(s[t]=null)}));const i=e.doc,o=i.clientID;li(n,s);const l=ci(e,t,n,s),c=r.constructor===String?new Li(r):r instanceof Ls?new Vi(r):new Ai(r);let{left:a,right:u,index:d}=n;t._searchMarker&&Us(t._searchMarker,n.index,c.getLength()),u=new zi(Qr(o,ns(i.store,o)),a,a&&a.lastId,u,u&&u.id,t,null,c),u.integrate(e,0),n.right=u,n.index=d,n.forward(),ii(e,t,n,l)},ui=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;li(n,s);const l=ci(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===Oi));){if(!n.right.deleted)switch(n.right.content.constructor){case Oi:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(ti(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&&ls(e,Qr(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 zi(Qr(o,ns(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new Li(s)),n.right.integrate(e,0),n.forward()}ii(e,t,n,l)},di=(e,t,n,r,s)=>{let i=t;const o=Ct();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===Oi){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 Oi:{const{key:i,value:a}=n,u=r.get(i)??null;o.get(i)===n&&u!==a||(t.delete(e),l++,c||(s.get(i)??null)!==a||u===a||(null===u?s.delete(i):s.set(i,u))),c||t.deleted||oi(s,n);break}}}t=t.right}return l},hi=e=>{let t=0;return gs(e.doc,(n=>{let r=e._start,s=e._start,i=Ct();const o=It(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===Oi)oi(o,s.content);else t+=di(n,r,s,i,o),i=It(o),r=s;s=s.right}})),t},fi=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&&as(e,n.store.clients.get(r),i,s,(e=>{e.deleted||e.content.constructor!==Oi||e.constructor===xi||t.add(e.parent)}))}gs(n,(n=>{Ir(e,e.deleteSet,(e=>{if(e instanceof xi||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===Oi?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===Oi){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)hi(e)}))},pi=(e,t,n)=>{const r=n,s=It(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Vi:case Ai:case Li:n<t.right.length&&ls(e,Qr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&di(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&Us(o._searchMarker,t.index,-r+n),t};class gi extends Es{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=[];gs(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 u=()=>{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=Yn({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case Vi:case Ai:this.adds(s)?this.deletes(s)||(u(),i="insert",l=s.content.getContent()[0],u()):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=1):s.deleted||("retain"!==i&&(u(),i="retain"),c+=1);break;case Li:this.adds(s)?this.deletes(s)||("insert"!==i&&(u(),i="insert"),l+=s.content.str):this.deletes(s)?("delete"!==i&&(u(),i="delete"),a+=s.length):s.deleted||("retain"!==i&&(u(),i="retain"),c+=s.length);break;case Oi:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;ti(c,l)?null!==l&&s.delete(e):("retain"===i&&u(),ti(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;ti(e,l)||("retain"===i&&u(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(ti(n,l)?null!==n&&s.delete(e):("retain"===i&&u(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&u(),oi(n,s.content));break}}s=s.right}for(u();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 yi extends Ls{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??Is(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){}this._pending=null}_copy(){return new yi}clone(){const e=new yi;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new gi(this,e,t);js(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??Is();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===Li&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?gs(this.doc,(n=>{const r=new ni(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)&&ai(n,this,r,o,i.attributes||{})}else void 0!==i.retain?ui(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&pi(n,r,i.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){this.doc??Is();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(Xr(l,e)||void 0!==t&&Xr(l,t))switch(l.content.constructor){case Li:{const r=s.get("ychange");void 0===e||Xr(l,e)?void 0===t||Xr(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 Vi:case Ai:{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 Oi:Xr(l,e)&&(c(),oi(s,l.content))}l=l.right}c()};return e||t?gs(i,(n=>{e&&Zr(n,e),t&&Zr(n,t),a()}),"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?gs(r,(r=>{const s=si(r,this,e,!n);n||(n={},s.currentAttributes.forEach(((e,t)=>{n[t]=e}))),ai(r,this,s,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n){const r=this.doc;null!==r?gs(r,(r=>{const s=si(r,this,e,!n);ai(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?gs(n,(n=>{pi(n,si(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?gs(r,(r=>{const s=si(r,this,e,!1);null!==s.right&&ui(r,this,s,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?gs(this.doc,(t=>{zs(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?gs(this.doc,(n=>{Hs(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return Js(this,e)}getAttributes(){return qs(this)}_write(e){e.writeTypeRef(Ni)}}class mi{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??Is()}[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!==vi&&t.constructor!==bi||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 bi extends Ls{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 bi}clone(){const e=new bi;return e.insert(0,this.toArray().map((e=>e instanceof Ls?e.clone():e))),e}get length(){return this.doc??Is(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new mi(this,e)}querySelector(e){e=e.toUpperCase();const t=new mi(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),Ut(new mi(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){js(this,e,new wi(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),Ms(this,(s=>{r.insertBefore(s.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?gs(this.doc,(n=>{Vs(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)gs(this.doc,(n=>{const r=e&&e instanceof Ls?e._item:e;Fs(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 wn("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?gs(this.doc,(n=>{Ks(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return Rs(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Bs(this,e)}slice(e=0,t=this.length){return Ps(this,e,t)}forEach(e){Ms(this,e)}_write(e){e.writeTypeRef(Bi)}}class vi extends bi{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 vi(this.nodeName)}clone(){const e=new vi(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 Ls?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?gs(this.doc,(t=>{zs(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?gs(this.doc,(n=>{Hs(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return Js(this,e)}hasAttribute(e){return Ys(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&&Xr(s,t)&&(n[r]=s.content.getContent()[s.length-1])})),n})(this,e):qs(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 Ms(this,(s=>{r.appendChild(s.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef($i),e.writeKey(this.nodeName)}}class wi extends Es{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 _i extends ei{constructor(e){super(),this.hookName=e}_copy(){return new _i(this.hookName)}clone(){const e=new _i(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(Fi),e.writeKey(this.hookName)}}class ki extends yi{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 ki}clone(){const e=new ki;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(Wi)}}class Si{constructor(e,t){this.id=e,this.length=t}get deleted(){throw _n()}mergeWith(e){return!1}write(e,t,n){throw _n()}integrate(e,t){throw _n()}}class xi extends Si{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),rs(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class Ei{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new Ei(this.content)}splice(e){throw _n()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class Ci{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new Ci(this.len)}splice(e){const t=new Ci(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){Or(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 Ii=(e,t)=>new Lr({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class Di{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 Di(Ii(this.doc.guid,this.opts))}splice(e){throw _n()}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 Ai{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new Ai(this.embed)}splice(e){throw _n()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class Oi{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new Oi(this.key,this.value)}splice(e){throw _n()}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 Ti{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ti(this.arr)}splice(e){const t=new Ti(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 Ui="development"===lr("node_env");class ji{constructor(e){this.arr=e,Ui&&tr(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new ji(this.arr)}splice(e){const t=new ji(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 Li{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new Li(this.str)}splice(e){const t=new Li(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 Pi=[e=>new Xs,e=>new ei,e=>new yi,e=>new vi(e.readKey()),e=>new bi,e=>new _i(e.readKey()),e=>new ki],Ri=0,Mi=1,Ni=2,$i=3,Bi=4,Fi=5,Wi=6;class Vi{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Vi(this.type._copy())}splice(e){throw _n()}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 Ki=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new zi(Qr(r,s+n),t,Qr(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=Qr(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 zi extends Si{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>=ns(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=ns(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Yr&&this.id.client!==this.parent.client&&this.parent.clock>=ns(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=cs(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=ls(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===xi||this.right&&this.right.constructor===xi)this.parent=null;else if(this.parent){if(this.parent.constructor===Yr){const e=is(t,this.parent);e.constructor===xi?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===zi?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===zi&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=cs(e,e.doc.store,Qr(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),Gr(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Gr(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(is(e.doc.store,t.origin)))break;r.has(is(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),rs(e.doc.store,this),this.content.integrate(e,this),hs(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new xi(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:Qr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Gr(e.origin,this.lastId)&&this.right===e&&Gr(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(),Or(e.deleteSet,this.id.client,this.id.clock,this.length),hs(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw kn();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[ss(r,t.id.clock)]=n})(e,this,new xi(this.id,this.length)):this.content=new Ci(this.length)}write(e,t){const n=t>0?Qr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:Wt)|(null===r?0:Ft)|(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 kn()})(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===Yr?(e.writeParentInfo(!1),e.writeLeftID(t)):kn();null!==s&&e.writeString(s)}this.content.write(e,t)}}const Hi=(e,t)=>Ji[31&t](e),Ji=[()=>{kn()},e=>new Ci(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 Ti(n)},e=>new Ei(e.readBuf()),e=>new Li(e.readString()),e=>new Ai(e.readJSON()),e=>new Oi(e.readKey(),e.readJSON()),e=>new Vi(Pi[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ji(n)},e=>new Di(Ii(e.readString(),e.readAny())),()=>{kn()}];class qi extends Si{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){kn()}write(e,t){e.writeInfo(10),rn(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Yi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Gi="__ $YJS$ __";function Qi(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}Yi[Gi],Yi[Gi]=!0;const Xi=new FinalizationRegistry((({cache:e,key:t})=>{delete e[t]}));function Zi(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=no(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=no(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&Xi.unregister(o),this.cache[i]=new WeakRef(e),Xi.register(e,{cache:this.cache,key:i},e)},delete(e){Xi.unregister(e);const t=no(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 eo=new WeakSet;function to(e){if(eo.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function no(e,t,n){return`${e}[${t}].${n}`}let ro=null;function so(e){ro=e}function io(){}const oo=new WeakMap;function lo(){return t.Dexie.Events(null,"load","sync","error")}class co{static getOrCreateDocument(e,t,n,r){var s,i;const o=Zi(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 Lr({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",(()=>{eo.add(o),t.delete(o)})),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=oo.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 co(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,oo.set(e,r)),r}static release(e){if(!e||eo.has(e))return;const t=oo.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(co.on("beforeunload").fire(this)).finally((()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())}))}static for(e){return oo.get(e)}static get currentUpdateRow(){return ro}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise(((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):eo.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.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(((e,n)=>{this.doc?this.doc.isSynced?e():this._error?n(this._error):eo.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",e),this.on("error",n),this.doc.on("destroy",(()=>n(new t.Dexie.AbortError("Document was destroyed before synced"))))):n(new Error("No Y.Doc associated with this provider"))}))),this._whenSynced}constructor(e){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=lo(),this.doc=e,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]=()=>co.release(e)),e.on("load",(()=>this.on("load").fire())),e.on("sync",(e=>!1!==e&&this.on("sync").fire())),e.on("destroy",this.destroy.bind(this)),this.on("error",(e=>{this._error=e}));const{db:n,parentTable:r,parentId:s,updatesTable:i}=e.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`);to(e),this.stopObserving=function(e,n,r,s,i,o){let l=0,c=!0;const a=t.liveQuery((()=>{to(n);const e=r.table(i);return Promise.all([(l>0?e.where("i").between(l,1/0,!1).toArray().then((e=>e.filter((e=>0===t.cmp(e.k,o))))):e.where({k:o}).toArray()).then((e=>e)),r.table(s).where(":id").equals(o).toArray()])})).subscribe((([t,r])=>{t.length>0&&(l=t[t.length-1].i),0!==r.length?(to(n),t.length>0&&gs(n,(()=>{t.forEach((e=>{try{so(e),Vr(n,e.u)}finally{so(null)}}))}),e,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()}),(t=>{e.on("error").fire(t)})),u=(t,n)=>{n!==e&&r.table(i).add({k:o,u:t,f:1}).then((e=>{e===l-1&&++l})).catch((t=>{e.on("error").fire(t)}))},d=()=>{a.unsubscribe(),n.off("updateV2",u),n.off("destroy",d)};return n.on("updateV2",u),n.on("destroy",d),d}(this,e,n,r,i,s),co.on("new").fire(this)}destroy(){var e;oo.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=lo(),this.cleanupHandlers.forEach((e=>e()))}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function ao(e,n){return s(this,void 0,void 0,(function*(){var r;const i={};let o,l=!1;for(const c of e)try{switch(c.type){case"u-s":{const e=Qi(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=Qi(n,c.table,c.prop);e&&(yield n.transaction("rw",e,(t=>s(this,void 0,void 0,(function*(){let n=yield t.table(e.name).get(xt);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:xt}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})))));break}case"u-reject":{const e=Qi(n,c.table,c.prop);if(!e)break;const s=null===(r=yield e.get(c.i))||void 0===r?void 0:r.k;if(null!=s){yield n.transaction("rw",e,(n=>(n.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(c.i).filter((e=>0===t.cmp(e.k,s)&&1==(1&(e.f||0)))).delete())));const r=co.getDocCache(n.dx).find(c.table,s,c.prop);r&&r.destroy()}break}case"in-sync":{const e=co.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}}))}co.on=t.Dexie.Events(null,{new:[function(e,t){return e===io?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===io?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)}}]}),co.getDocCache=Zi,t.Dexie.DexieYProvider?co=t.Dexie.DexieYProvider||co:t.Dexie.DexieYProvider=co;const uo=1,ho=2,fo=3;function po(e,n,r){return s(this,arguments,void 0,(function*(e,n,{yDownloadedRealms:r,realms:i}){if(r&&i&&i.every((e=>"*"===r[e])))return;const a=yield he(e),u={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(u.Authorization=`Bearer ${a.accessToken}`);const d=yield fetch(`${n}/y/download`,{body:dt.stringify({downloadedRealms:r||{}}),method:"POST",headers:u,credentials:"include"});if(!d.ok)throw new Error(`Failed to download Yjs documents from server. Status: ${d.status}`);yield async function(e,...t){var n,r,s;let i=e();for(let e=0;e<t.length;e++)i=t[e](i);try{for(var o,l=!0,a=c(i);!(n=(o=await a.next()).done);l=!0)o.value,l=!1}catch(e){r={error:e}}finally{try{l||n||!(s=a.return)||await s.call(a)}finally{if(r)throw r.error}}}(function(e){return function(){return l(this,arguments,(function*(){if(!e.body)throw new Error("Response body is not readable");const t=e.body.getReader();try{for(;;){const{done:e,value:n}=yield o(t.read());if(e)return yield o(void 0);yield yield o(n)}}finally{t.releaseLock()}}))}}(d),Z,(function(r){return l(this,arguments,(function*(){var i,l,a,u;let d=null,h=null,f=null,p=[];function g(t){return s(this,void 0,void 0,(function*(){const r=p[p.length-1];if(p.length>0){if(!d||!h||!f)throw new Error(`Protocol error from ${n}/y/download`);const t=Qi(e,h,f);t&&(yield t.bulkAdd(p)),p=[]}d&&(h&&f&&r||t)&&(yield e.$syncState.update("syncState",(e=>{const n=e.yDownloadedRealms||{};n[d]=t?"*":{tbl:h,prop:f,key:r.k},e.yDownloadedRealms=n})))}))}try{try{for(var y,m=!0,b=c(r);!(i=(y=yield o(b.next())).done);m=!0){u=y.value,m=!1;const e=new V(u);for(;K(e);)switch(H(e)){case uo:yield o(g(!0)),d=q(e);break;case ho:yield o(g(!1)),h=q(e),f=q(e);break;case fo:{const t=X(e),n=z(e);p.push({k:t,u:n});break}}yield o(g(!1))}}catch(e){l={error:e}}finally{try{m||i||!(a=b.return)||(yield o(a.call(b)))}finally{if(l)throw l.error}}yield o(g(!0))}catch(e){throw e instanceof t.DexieError||(yield o(g(!1))),e}}))}))}))}const go="currentSyncWorker";function yo(e,t,n,r){return mo(e,t,n,r).then((t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t))).catch((i=>s(this,void 0,void 0,(function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):vt&&(null==r?void 0:r.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 yo(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:vt?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))))}function mo(e,t,n){return s(this,arguments,void 0,(function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:l}={isInitialSync:!1}){var c;if(!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,u=yield e.getCurrentUser(),h=u.isLoggedIn?Oe(e):[],p=h.map((t=>e.table(Te(t.name)))),g=yield e.getPersistedSyncState(),y=u.isLoggedIn,m=y?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return Oe(e).filter((e=>!n.includes(e.name)))}(e,g):[];bt(i);const b=m.length>0;if(b){if(o)return!0;yield e.transaction("rw",m,(e=>s(this,void 0,void 0,(function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return s(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!==me.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!==me.userId||(e.owner=t.userId)})):yield n.toCollection().modify((e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==me.userId||(e.owner=t.userId),e.realmId&&e.realmId!==me.userId||(e.realmId=t.userId))})))}))}(m,u,null==g?void 0:g.realms)})))),bt(i)}const[v,w,_,{yMessages:k,lastUpdateIds:S}]=yield e.transaction("r",e.tables,(()=>s(this,void 0,void 0,(function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter((e=>h.some((t=>t.name===e.tableName))));let o=yield Pe(p,e);const l=yield function(e,t){return s(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(xt),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),u=yield Et(i,a);u.length>0&&(r[i.name]=u[u.length-1].i);const d={};for(const e of u){const t=1==(1&(e.f||0));if(t&&e.i<l)continue;const n=JSON.stringify(e.k)+"/"+t;let r=d[n];r?(r.u.push(e.u),r.i=Math.max(e.i,r.i)):(d[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(d)){const l=1===i.length?i[0]:ws(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=bs(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}}))}(e,h);if(bt(i),b){const e=[...(null==g?void 0:g.realms)||[],...(null==g?void 0:g.inviteRealms)||[]],c=yield function(e,t,n,r){return s(this,void 0,void 0,(function*(){const i=`upload-${Re(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(yield Promise.all(e.map((e=>s(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||"")&&f(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[]}))}(m,u,n,e);return bt(i),o=o.concat(c),[o,t,r,l]}return[o,t,r,l]})))),x=v.some((e=>e.muts.some((e=>e.keys.length>0))))||k.some((e=>"u-c"===e.type));if(o)return x;if("push"===l&&!x)return!1;const E=_t(v,null==w?void 0:w.latestRevisions),C=(null==w?void 0:w.clientIdentity)||d(16);bt(i);const I=yield mt(v,k,w,_,e,a,n,C,u),{done:D,newSyncState:A}=yield e.transaction("rw",e.tables,(t=>s(this,void 0,void 0,(function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))I.schema[e]&&(n[e]=I.schema[e]);yield e.$syncState.put(n,"schema");const r=yield Pe(p,e,{since:E});for(const t of p){const n=Ue(t.name);if(r.some((e=>e.table===n&&e.muts.length>0))){if(E[n]){const r=E[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()])}_t(r,E),yield wt(e,n,E,I.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return s(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=Oe(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,I,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:C};y&&(o.syncedTables=h.map((e=>e.name)).concat(m.map((e=>e.name)))),o.latestRevisions=E,o.remoteDbId=I.dbId,o.initiallySynced=!0,o.realms=I.realms,o.inviteRealms=I.inviteRealms,o.serverRevision=I.serverRevision,o.yServerRevision=I.serverRevision,o.timestamp=new Date,delete o.error;const l=bo(I.changes,r);if(yield St(l,e),I.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield ao(I.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,(function*(){var r,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(r=a[t])&&void 0!==r||(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 u=Object.values(n.dx._dbSchema).filter((e=>e.yProps)).map((e=>e.yProps.map((e=>e.updatesTable)))).flat();for(const e of u){const t=a[e],r=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,(()=>s(this,void 0,void 0,(function*(){const t=yield n.table(e).get(xt);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:xt,unsentFrom:r,receivedUntil:i})}))))}}))}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}))));if(!D)return yield yt(e),yield mo(e,t,n,{isInitialSync:r,cancelToken:i});const O=Object.values(n).some((e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length})),T=!!I.yMessages;if(O&&T)try{yield po(e,a,A)}catch(e){}return e.syncCompleteEvent.next(),!1}))}function bo(e,t){const n={};y(n,e);const r={};return y(r,t),function(e,t){var n,r,s;for(const[i,o]of Object.entries(t))for(const[t,l]of Object.entries(o))switch(l.type){case"ups":{const r=null===(n=e[i])||void 0===n?void 0:n[t];if(r)switch(r.type){case"ups":case"upd":delete e[i][t]}}break;case"del":null===(r=e[i])||void 0===r||delete r[t];break;case"upd":{const n=null===(s=e[i])||void 0===s?void 0:s[t];if(n)switch(n.type){case"ups":for(const[e,t]of Object.entries(l.mod))u(n.val,e,t);break;case"del":break;case"upd":for(const e of Object.keys(l.mod))delete n.mod[e]}break}}}(n,r),function(e,t=""){t||(t=d(16));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(Object.assign({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)}const vo=10,wo=1e4,_o=1e3;function ko(e){const i=[],o=new n.BehaviorSubject(!0),l=new n.BehaviorSubject(null);let c=!1,a=new Array(vo).fill(0);return l.subscribe((()=>s(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 s(this,void 0,void 0,(function*(){for(var o,l,c,a,u,d;i.length>0;){const h=i.shift();try{yield n.firstValueFrom(e.cloud.syncState.pipe(r.filter((({phase:e})=>"in-sync"===e||"error"===e))));const i=e.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const n=e.cloud.currentUser.value,r=yield pe(e.cloud.options.databaseUrl,n);yield e.table("$logins").update(n.userId,{accessToken:r.accessToken,accessTokenExpiration:r.accessTokenExpiration,claims:r.claims,license:r.license,data:r.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 e.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 e.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===(u=null==i?void 0:i.inviteRealms)||void 0===u?void 0:u.includes(h.realm)))&&(yield e.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield e.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(d=e.cloud.syncState.value)||void 0===d?void 0:d.phase)){ne(e,"pull");break}yield e.transaction("rw",e.dx.tables,(n=>s(this,void 0,void 0,(function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,s,i]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(!s||!r||!i)return;if(h.baseRev!==s.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||ne(e,"pull"));if((yield t.waitFor(Ae(s)))!==h.realmSetHash)return void ne(e,"pull");let o=[];if(i.isLoggedIn){const t=Oe(e).map((t=>e.table(Te(t.name))));o=yield Pe(t,e)}if(h.changes.length>0){const t=bo(h.changes,o);yield St(t,e)}s.latestRevisions=_t(o,s.latestRevisions),s.serverRevision=h.newRev,yield wt(e,r,s.latestRevisions,h.newRev),yield e.$syncState.put(s,"syncState")}))))}}catch(e){}}}))}()}finally{a[a.length-1]-a[0]<wo&&(yield new Promise((e=>setTimeout(e,_o)))),c=!1,o.next(!0)}}})))),{enqueue:function(e){i.push(e),l.next(null)},readyToServe:o}}const So=new WeakMap,xo={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let Eo=0;function Co(e){"vip"in e&&(e=e.vip);let t=So.get(e.cloud);if(!t){const r=new n.Subject;let s=new De(`syncstatechanged-${e.name}`),i=new De(`synccomplete-${e.name}`);r.id=++Eo;let o=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>t.$logins.toArray().then((e=>e.find((e=>e.isLoggedIn))||me)),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then((e=>{if(e)for(const r of t.tables)r.schema.primKey&&r.schema.primKey.keyPath&&e[r.name]&&(e[r.name].primaryKey="string"==typeof(n=r.schema.primKey.keyPath)?n:n?"["+[].join.call(n,"+")+"]":"");var n;return e})),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new De(`syncstatechanged-${e.name}`),i=new De(`synccomplete-${e.name}`)}};Object.assign(t,l),t.messageConsumer=ko(t),t.messageProducer=new n.Subject,So.set(e.cloud,t)}return t}const Io="undefined"!=typeof InstallTrigger,Do="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Ao=Do?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,Oo=Do&&Ao<=605||Io,To="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:Uo}={};function jo(e){return Uo.call(e).slice(8,-1)}function Lo(e,t){var n;return"delete"===t.type?t.keys:(null===(n=t.keys)||void 0===n?void 0:n.slice())||t.values.map(e.extractKey)}const Po=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;let Ro=0;function Mo(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();Ro>=s?++Ro:Ro=s,r[0]=Ro/1099511627776,r[1]=Ro/4294967296,r[2]=Ro/16777216,r[3]=Ro/65536,r[4]=Ro/256,r[5]=Ro;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+qe(new Uint8Array(n.buffer))+(t||"")}function No(e){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=e.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=Lo(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=Lo(s.schema.primaryKey,n);return l.forEach(((c,a)=>{if(void 0===c){const r=n.values[a].realmId||e.cloud.currentUserId,c=r.substr(r.length-3);l[a]=Mo(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new t.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){Lo(s.schema.primaryKey,n).forEach(((e,n)=>{if(!f(e)){const n=Array.isArray(e)?e.map(jo).join(","):jo(e);throw new t.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 $o=0;function Bo(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 Fo(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 Wo=new n.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 Ko({currentUserObservable:e,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:(t,s)=>{let i;if("readwrite"===s){const e=t.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=>Te(e)));i=r.transaction([...t,...e],s)}else i=r.transaction(t,s);if("readwrite"===s){i.txid=Re(16),i.opCount=0,i.currentUser=e.value,Wo.value.add(i),Wo.next(Wo.value);const t=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",t),i.removeEventListener("abort",t),Wo.value.delete(i),Wo.next(Wo.value)},r=()=>{i.mutationsAdded&&!Vo(n)&&ne(n,"push"),t()};i.addEventListener("complete",r),i.addEventListener("error",t),i.addEventListener("abort",t)}return i},table:e=>{const s=r.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===e?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(e);return l?function(e){const t="$lock"+ ++$o;return Object.assign(Object.assign({},e),{count:Bo(e.count,t),get:Bo(e.get,t),getMany:Bo(e.getMany,t),openCursor:Bo(e.openCursor,t),query:Bo(e.query,t),mutate:Fo(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:t=>{var r,o,l;const a=t.trans;return a.txid?a.disableChangeTracking?s.mutate(t):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[e])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===t.type?s.query({query:{range:t.range,index:i.primaryKey},trans:t.trans,values:!1}).then((e=>c({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}}))):c(t):s.mutate(t):s.mutate(t)}})):s;function c(r){var o,c;const a=r.trans,u=null===(c=null===(o=n.cloud.options)||void 0===o?void 0:o.unsyncedProperties)||void 0===c?void 0:c[e],{txid:d,currentUser:{userId:h}}=a,{type:f}=r,p=++a.opCount;function g(e){if(!u)return e;let t=e;for(const n of Object.keys(e))u.some((e=>n===e||n.startsWith(e+".")))&&(t===e&&(t=Object.assign({},e)),delete t[n]);return t}return s.mutate(r).then((e=>{var n;const{numFailures:s,failures:o}=e;let c="delete"===f?r.keys:e.results,y="values"in r?r.values:[],m="changeSpec"in r?r.changeSpec:void 0,b="updates"in r?r.updates:void 0,v=!(!b||!("upsert"in r))&&r.upsert;if(s&&(c=c.filter(((e,t)=>!o[t])),y=y.filter(((e,t)=>!o[t]))),u){if(y=y.map((e=>{const t=Object.assign({},e);for(const e of u)delete t[e];return t})),m&&(m=g(m),0===Object.keys(m).length))return e;if(b){let e=b.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new t.RangeSet;let s=!1;if(!v){for(let t=0,i=e.length;t<i;++t)Object.keys(e[t]).length>0?(n.keys.push(b.keys[t]),n.changeSpecs.push(e[t]),r.addKey(b.keys[t])):s=!0;if(b=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(u&&(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==u?void 0:u.includes(e)))&&(_=void 0)}const k="delete"===r.type?{type:"delete",ts:w,opNo:p,keys:c,criteria:_,txid:d,userId:h}:"add"===r.type?{type:"insert",ts:w,opNo:p,keys:c,txid:d,userId:h,values:y}:v&&b?{type:"upsert",ts:w,opNo:p,keys:c,values:y,changeSpecs:b.changeSpecs.filter(((e,t)=>!o[t])),txid:d,userId:h}:_&&m?{type:"modify",ts:w,opNo:p,keys:c,criteria:_,changeSpec:m,txid:d,userId:h}:m?{type:"update",ts:w,opNo:p,keys:c,changeSpecs:c.map((()=>m)),txid:d,userId:h}:b?{type:"update",ts:w,opNo:p,keys:b.keys,changeSpecs:b.changeSpecs,txid:d,userId:h}:{type:"upsert",ts:w,opNo:p,keys:c,values:y,txid:d,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,e))):e}))}}})}}}function zo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},xo),n);Object.keys(xo).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=xo[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(xo[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=>{const t=i[e],n=o[e]||(o[e]={});null!=t?(/^\@/.test(t)&&(i[e]=i[e].substr(1),n.generatedGlobalId=!0,n.idPrefix=function(e,t){let n=e[0].toLocaleLowerCase();for(let t=1,s=e.length;t<s&&n.length<3;++t)(Po.test(e[t])||(r=e[t])>="A"&&r<="Z")&&(n+=e[t].toLowerCase());for(var r,s,i;t.has(n);){if(/\d/g.test(n)){if(n=n.substr(0,n.length-1)+(n[n.length-1]+1),!(n.length>3))continue;n=n.substr(0,3)}else if(n.length<3){n+="2";continue}let e=1,r=n;for(;t.has(r)&&e<8;)s=n,r=(1&(i=e)?s[0].toUpperCase():s[0].toLowerCase())+(2&i?s[1].toUpperCase():s[1].toLowerCase())+(4&i?s[2].toUpperCase():s[2].toLowerCase()),++e;if(e<8)n=r;else{let e=n.charCodeAt(2)+1&127;n=n.substr(0,2)+String.fromCharCode(e)}}return n}(e,l),l.add(n.idPrefix)),/^\$/.test(e)||(i[`$${e}_mutations`]="++rev",n.markedForSync=!0),n.deleted&&(n.deleted=!1)):(n.deleted=!0,n.markedForSync=!1,i[`$${e}_mutations`]=null)}));const c=e.call(this,i,r);for(const[e,t]of Object.entries(r))if(null===(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 Ho(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,(()=>n())):n()}const Jo=new n.BehaviorSubject(!0),qo=new n.BehaviorSubject(!0);Jo.pipe(r.switchMap((e=>e?n.of(!0):n.of(!1).pipe(r.delay(2e4)))),r.distinctUntilChanged()).subscribe(qo);const Yo="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),Go=Yo.pipe(r.filter((()=>"hidden"===document.visibilityState))),Qo=Yo.pipe(r.filter((()=>"visible"===document.visibilityState))),Xo="undefined"!=typeof window?n.merge(Qo,n.fromEvent(window,"mousedown"),n.fromEvent(window,"mousemove"),n.fromEvent(window,"keydown"),n.fromEvent(window,"wheel"),n.fromEvent(window,"touchmove")):n.of({});"undefined"!=typeof document&&n.merge(n.of(!0),Go,Xo).pipe(r.map((()=>"visible"===document.visibilityState)),r.tap((e=>{Jo.value!==e&&Jo.next(e)})),r.switchMap((e=>e?n.of(0).pipe(r.delay(16e4),r.tap((()=>Jo.next(!1)))):n.of(0)))).subscribe((()=>{}));class Zo extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const el=new WeakMap,tl=3e4;class nl extends Pt{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const e=Vn();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&&tl<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)})),t.length>0&&rl(this,t,"timeout")}),Rt(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:Vn()});const i=[],o=[],l=[],c=[];null===e?c.push(t):null==s?null!=e&&i.push(t):(o.push(t),rr(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 rl=(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:Vn()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},sl=(e,t,n=e.states)=>{const r=t.length,s=Zt();rn(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,l=e.meta.get(r).clock;rn(s,r),rn(s,l),cn(s,JSON.stringify(o))}return en(s)},il=new WeakMap;function ol(e){let t=il.get(e);return t||(t=new n.Subject,il.set(e,t)),t}class ll extends n.Observable{constructor(e,t,n,r,s,i,o,l){super((c=>new al(e,t,n,r,s,l,c,i,o)))}}let cl=0;class al extends n.Subscription{constructor(e,t,n,r,s,i,o,l,c){super((()=>this.teardown())),this.id=++cl,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 s(this,void 0,void 0,(function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new Zo);this.webSocketStatus.next("connecting"),this.pinger=setInterval((()=>s(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 r=new URL(this.databaseUrl);r.protocol="http:"===r.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(`${r}/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?dt.parse(e.data):function(e){const t=new V(e),n=q(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:q(t)};const r=q(t),s=q(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(G(t))};default:{const e=X(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:z(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:X(t),sv:X(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:z(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:z(t),i:Number(G(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:z(t),r:t.pos<t.arr.length&&q(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=co.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>el.get(e))(e);n&&((e,t,n)=>{const r=Cn(t),s=Vn(),i=[],o=[],l=[],c=[],a=An(r);for(let t=0;t<a;t++){const t=An(r);let n=An(r);const a=JSON.parse(Tn(r)),u=e.meta.get(t),d=e.states.get(t),h=void 0===u?0:u.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===u&&null!==a?i.push(t):void 0!==u&&null===a?c.push(t):null!==a&&(rr(a,d)||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=co.getDocCache(this.db.dx).find(t.table,t.k,t.prop);e&&ol(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?ao([t],this.db).then((e=>s(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=Qi(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(xt,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})))):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise(((t,n)=>{o.onopen=n=>{e=!0,t(null)},o.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}})),this.subscriptions.add(this.messageProducer.subscribe((e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(dt.stringify(e))):null===(n=this.ws)||void 0===n||n.send($(e)))}))),this.user.isLoggedIn&&!Vo(this.db)&&this.subscriptions.add(function(e){const r=Le(e.tables.filter((t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps})).map((e=>e.schema.yProps.map((t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))))));return n.merge(...r.map((({table:r,ydocProp:i,updatesTable:o})=>{const l=e.table(o);return n.from(l.get(xt)).pipe(n.switchMap((e=>{let o=(null==e?void 0:e.unsentFrom)||1;return n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){return(yield Et(l,o)).filter((e=>e.f&&1&e.f)).map((e=>({type:"u-c",table:r,prop:i,k:e.k,u:e.u,i:e.i})))}))))).pipe(n.tap((e=>{e.length>0&&(o=e.at(-1).i+1)})))})))}))).pipe(n.mergeMap((e=>e)))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}}))}}class ul extends Error{constructor(e){super("expired"===e?"License expired":"deactivated"===e?"User deactivated":"Invalid license"),this.name="InvalidLicenseError",e&&(this.license=e)}}function dl(e){return s(this,void 0,void 0,(function*(){var e;yield(e=3e3,new Promise((t=>setTimeout(t,e)))),yield n.firstValueFrom(Xo)}))}function hl(e){return s(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 yo(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))}))}const fl=new WeakMap;function pl(e,t,n,r){const i=fl.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return i.promise;{let s=!1;const o=e.cloud.syncState.subscribe((e=>{"pulling"===e.phase&&(s=!0)}));return i.promise.then((()=>{o.unsubscribe()})).catch((e=>(o.unsubscribe(),Promise.reject(e)))).then((()=>{if(!s)return pl(e,t,n,r)}))}}const o=function(){return s(this,void 0,void 0,(function*(){try{yield yt(e),yield Ho(e,go,(()=>yo(e,t,n,r))),fl.delete(e)}catch(t){throw fl.delete(e),t}}))}();return fl.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}const gl=1e3;function yl(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout((()=>{const h=c?"pull":"push";o=Date.now(),pl(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:h}).then((()=>{if(s.cancelled)d();else if(c||a)return c=!1,a=!1,l();u=!1,i=0,o=0})).catch((e=>{if(s.cancelled)d(),u=!1,i=0,o=0;else if(r<5){const e=[0,20,40,300,900][r]*gl;i=Date.now()+e,o=0,setTimeout((()=>l(r+1)),e)}else u=!1,i=0,o=0}))}),0)}let c=!1,a=!1,u=!1;const d=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe((({purpose:e})=>{(e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),u?i||o>0&&Date.now():(u=!0,l()))})(e||"pull")}))},stop:d}}function ml(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var bl,vl,wl,_l,kl,Sl={},xl=[],El=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i;function Cl(e,t){for(var n in t)e[n]=t[n];return e}function Il(e){var t=e.parentNode;t&&t.removeChild(e)}function Dl(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?bl.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,__d:void 0,__c:null,__h:null,constructor:void 0,__v:null==s?++wl:s};return null==s&&null!=vl.vnode&&vl.vnode(i),i}function Ol(e){return e.children}function Tl(e,t){this.props=e,this.context=t}function Ul(e,t){if(null==t)return e.__?Ul(e.__,e.__.__k.indexOf(e)+1):null;for(var n;t<e.__k.length;t++)if(null!=(n=e.__k[t])&&null!=n.__e)return n.__e;return"function"==typeof e.type?Ul(e):null}function jl(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 jl(e)}}function Ll(e){(!e.__d&&(e.__d=!0)&&_l.push(e)&&!Pl.__r++||kl!==vl.debounceRendering)&&((kl=vl.debounceRendering)||setTimeout)(Pl)}function Pl(){for(var e;Pl.__r=_l.length;)e=_l.sort((function(e,t){return e.__v.__b-t.__v.__b})),_l=[],e.some((function(e){var t,n,r,s,i,o;e.__d&&(i=(s=(t=e).__v).__e,(o=t.__P)&&(n=[],(r=Cl({},s)).__v=s.__v+1,Vl(o,s,r,t.__n,void 0!==o.ownerSVGElement,null!=s.__h?[i]:null,n,null==i?Ul(s):i,s.__h),Kl(n,s),s.__e!=i&&jl(s)))}))}function Rl(e,t,n,r,s,i,o,l,c,a){var u,d,h,f,p,g,y,m=r&&r.__k||xl,b=m.length;for(n.__k=[],u=0;u<t.length;u++)if(null!=(f=n.__k[u]=null==(f=t[u])||"boolean"==typeof f?null:"string"==typeof f||"number"==typeof f||"bigint"==typeof f?Al(null,f,null,null,f):Array.isArray(f)?Al(Ol,{children:f},null,null,null):f.__b>0?Al(f.type,f.props,f.key,null,f.__v):f)){if(f.__=n,f.__b=n.__b+1,null===(h=m[u])||h&&f.key==h.key&&f.type===h.type)m[u]=void 0;else for(d=0;d<b;d++){if((h=m[d])&&f.key==h.key&&f.type===h.type){m[d]=void 0;break}h=null}Vl(e,f,h=h||Sl,s,i,o,l,c,a),p=f.__e,(d=f.ref)&&h.ref!=d&&(y||(y=[]),h.ref&&y.push(h.ref,null,f),y.push(d,f.__c||p,f)),null!=p?(null==g&&(g=p),"function"==typeof f.type&&f.__k===h.__k?f.__d=c=Ml(f,c,e):c=Nl(e,f,h,m,p,c),"function"==typeof n.type&&(n.__d=c)):c&&h.__e==c&&c.parentNode!=e&&(c=Ul(h))}for(n.__e=g,u=b;u--;)null!=m[u]&&("function"==typeof n.type&&null!=m[u].__e&&m[u].__e==n.__d&&(n.__d=Ul(r,u+1)),Jl(m[u],m[u]));if(y)for(u=0;u<y.length;u++)Hl(y[u],y[++u],y[++u])}function Ml(e,t,n){for(var r,s=e.__k,i=0;s&&i<s.length;i++)(r=s[i])&&(r.__=e,t="function"==typeof r.type?Ml(r,t,n):Nl(n,r,r,s,r.__e,t));return t}function Nl(e,t,n,r,s,i){var o,l,c;if(void 0!==t.__d)o=t.__d,t.__d=void 0;else if(null==n||s!=i||null==s.parentNode)e:if(null==i||i.parentNode!==e)e.appendChild(s),o=null;else{for(l=i,c=0;(l=l.nextSibling)&&c<r.length;c+=2)if(l==s)break e;e.insertBefore(s,i),o=i}return void 0!==o?o:s.nextSibling}function $l(e,t,n){"-"===t[0]?e.setProperty(t,n):e[t]=null==n?"":"number"!=typeof n||El.test(t)?n:n+"px"}function Bl(e,t,n,r,s){var i;e:if("style"===t)if("string"==typeof n)e.style.cssText=n;else{if("string"==typeof r&&(e.style.cssText=r=""),r)for(t in r)n&&t in n||$l(e.style,t,"");if(n)for(t in n)r&&n[t]===r[t]||$l(e.style,t,n[t])}else if("o"===t[0]&&"n"===t[1])i=t!==(t=t.replace(/Capture$/,"")),t=t.toLowerCase()in e?t.toLowerCase().slice(2):t.slice(2),e.l||(e.l={}),e.l[t+i]=n,n?r||e.addEventListener(t,i?Wl:Fl,i):e.removeEventListener(t,i?Wl:Fl,i);else if("dangerouslySetInnerHTML"!==t){if(s)t=t.replace(/xlink(H|:h)/,"h").replace(/sName$/,"s");else if("href"!==t&&"list"!==t&&"form"!==t&&"tabIndex"!==t&&"download"!==t&&t in e)try{e[t]=null==n?"":n;break e}catch(e){}"function"==typeof n||(null!=n&&(!1!==n||"a"===t[0]&&"r"===t[1])?e.setAttribute(t,n):e.removeAttribute(t))}}function Fl(e){this.l[e.type+!1](vl.event?vl.event(e):e)}function Wl(e){this.l[e.type+!0](vl.event?vl.event(e):e)}function Vl(e,t,n,r,s,i,o,l,c){var a,u,d,h,f,p,g,y,m,b,v,w,_,k=t.type;if(void 0!==t.constructor)return null;null!=n.__h&&(c=n.__h,l=t.__e=n.__e,t.__h=null,i=[l]),(a=vl.__b)&&a(t);try{e:if("function"==typeof k){if(y=t.props,m=(a=k.contextType)&&r[a.__c],b=a?m?m.props.value:a.__:r,n.__c?g=(u=t.__c=n.__c).__=u.__E:("prototype"in k&&k.prototype.render?t.__c=u=new k(y,b):(t.__c=u=new Tl(y,b),u.constructor=k,u.render=ql),m&&m.sub(u),u.props=y,u.state||(u.state={}),u.context=b,u.__n=r,d=u.__d=!0,u.__h=[]),null==u.__s&&(u.__s=u.state),null!=k.getDerivedStateFromProps&&(u.__s==u.state&&(u.__s=Cl({},u.__s)),Cl(u.__s,k.getDerivedStateFromProps(y,u.__s))),h=u.props,f=u.state,d)null==k.getDerivedStateFromProps&&null!=u.componentWillMount&&u.componentWillMount(),null!=u.componentDidMount&&u.__h.push(u.componentDidMount);else{if(null==k.getDerivedStateFromProps&&y!==h&&null!=u.componentWillReceiveProps&&u.componentWillReceiveProps(y,b),!u.__e&&null!=u.shouldComponentUpdate&&!1===u.shouldComponentUpdate(y,u.__s,b)||t.__v===n.__v){u.props=y,u.state=u.__s,t.__v!==n.__v&&(u.__d=!1),u.__v=t,t.__e=n.__e,t.__k=n.__k,t.__k.forEach((function(e){e&&(e.__=t)})),u.__h.length&&o.push(u);break e}null!=u.componentWillUpdate&&u.componentWillUpdate(y,u.__s,b),null!=u.componentDidUpdate&&u.__h.push((function(){u.componentDidUpdate(h,f,p)}))}if(u.context=b,u.props=y,u.__v=t,u.__P=e,v=vl.__r,w=0,"prototype"in k&&k.prototype.render)u.state=u.__s,u.__d=!1,v&&v(t),a=u.render(u.props,u.state,u.context);else do{u.__d=!1,v&&v(t),a=u.render(u.props,u.state,u.context),u.state=u.__s}while(u.__d&&++w<25);u.state=u.__s,null!=u.getChildContext&&(r=Cl(Cl({},r),u.getChildContext())),d||null==u.getSnapshotBeforeUpdate||(p=u.getSnapshotBeforeUpdate(h,f)),_=null!=a&&a.type===Ol&&null==a.key?a.props.children:a,Rl(e,Array.isArray(_)?_:[_],t,n,r,s,i,o,l,c),u.base=t.__e,t.__h=null,u.__h.length&&o.push(u),g&&(u.__E=u.__=null),u.__e=!1}else null==i&&t.__v===n.__v?(t.__k=n.__k,t.__e=n.__e):t.__e=zl(n.__e,t,n,r,s,i,o,c);(a=vl.diffed)&&a(t)}catch(e){t.__v=null,(c||null!=i)&&(t.__e=l,t.__h=!!c,i[i.indexOf(l)]=null),vl.__e(e,t,n)}}function Kl(e,t){vl.__c&&vl.__c(t,e),e.some((function(t){try{e=t.__h,t.__h=[],e.some((function(e){e.call(t)}))}catch(e){vl.__e(e,t.__v)}}))}function zl(e,t,n,r,s,i,o,l){var c,a,u,d=n.props,h=t.props,f=t.type,p=0;if("svg"===f&&(s=!0),null!=i)for(;p<i.length;p++)if((c=i[p])&&"setAttribute"in c==!!f&&(f?c.localName===f:3===c.nodeType)){e=c,i[p]=null;break}if(null==e){if(null===f)return document.createTextNode(h);e=s?document.createElementNS("http://www.w3.org/2000/svg",f):document.createElement(f,h.is&&h),i=null,l=!1}if(null===f)d===h||l&&e.data===h||(e.data=h);else{if(i=i&&bl.call(e.childNodes),a=(d=n.props||Sl).dangerouslySetInnerHTML,u=h.dangerouslySetInnerHTML,!l){if(null!=i)for(d={},p=0;p<e.attributes.length;p++)d[e.attributes[p].name]=e.attributes[p].value;(u||a)&&(u&&(a&&u.__html==a.__html||u.__html===e.innerHTML)||(e.innerHTML=u&&u.__html||""))}if(function(e,t,n,r,s){var i;for(i in n)"children"===i||"key"===i||i in t||Bl(e,i,null,n[i],r);for(i in t)s&&"function"!=typeof t[i]||"children"===i||"key"===i||"value"===i||"checked"===i||n[i]===t[i]||Bl(e,i,t[i],n[i],r)}(e,h,d,s,l),u)t.__k=[];else if(p=t.props.children,Rl(e,Array.isArray(p)?p:[p],t,n,r,s&&"foreignObject"!==f,i,o,i?i[0]:n.__k&&Ul(n,0),l),null!=i)for(p=i.length;p--;)null!=i[p]&&Il(i[p]);l||("value"in h&&void 0!==(p=h.value)&&(p!==e.value||"progress"===f&&!p||"option"===f&&p!==d.value)&&Bl(e,"value",p,d.value,!1),"checked"in h&&void 0!==(p=h.checked)&&p!==e.checked&&Bl(e,"checked",p,d.checked,!1))}return e}function Hl(e,t,n){try{"function"==typeof e?e(t):e.current=t}catch(e){vl.__e(e,n)}}function Jl(e,t,n){var r,s;if(vl.unmount&&vl.unmount(e),(r=e.ref)&&(r.current&&r.current!==e.__e||Hl(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){vl.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Jl(r[s],t,"function"!=typeof e.type);n||null==e.__e||Il(e.__e),e.__e=e.__d=void 0}function ql(e,t,n){return this.constructor(e,n)}function Yl(e,t,n){var r,s,i;vl.__&&vl.__(e,t),s=(r="function"==typeof n)?null:n&&n.__k||t.__k,i=[],Vl(t,e=(!r&&n||t).__k=Dl(Ol,null,[e]),s||Sl,Sl,void 0!==t.ownerSVGElement,!r&&n?[n]:s?null:t.firstChild?bl.call(t.childNodes):null,i,!r&&n?n:s?s.__e:t.firstChild,r),Kl(i,e)}bl=xl.slice,vl={__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}},wl=0,Tl.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!==this.state?this.__s:this.__s=Cl({},this.state),"function"==typeof e&&(e=e(Cl({},n),this.props)),e&&Cl(n,e),null!=e&&this.__v&&(t&&this.__h.push(t),Ll(this))},Tl.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),Ll(this))},Tl.prototype.render=Ol,_l=[],Pl.__r=0;const Gl={Error:{color:"red"},Alert:{error:{color:"red",fontWeight:"bold"},warning:{color:"#f80",fontWeight:"bold"},info:{color:"black"}},Darken:{position:"fixed",top:0,left:0,opacity:.5,backgroundColor:"#000",width:"100vw",height:"100vh",zIndex:150,webkitBackdropFilter:"blur(2px)",backdropFilter:"blur(2px)"},DialogOuter:{position:"fixed",top:0,left:0,width:"100vw",height:"100vh",zIndex:150,alignItems:"center",display:"flex",justifyContent:"center",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"}};function Ql({children:e,className:t}){return Dl("div",{className:`dexie-dialog ${t||""}`},Dl("div",{style:Gl.Darken}),Dl("div",{style:Gl.DialogOuter},Dl("div",{style:Gl.DialogInner},e)))}var Xl,Zl,ec,tc,nc=0,rc=[],sc=[],ic=vl.__b,oc=vl.__r,lc=vl.diffed,cc=vl.__c,ac=vl.unmount;function uc(e,t){vl.__h&&vl.__h(Zl,e,nc||t),nc=0;var n=Zl.__H||(Zl.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({__V:sc}),n.__[e]}function dc(e){return nc=1,function(e,t,n){var r=uc(Xl++,2);if(r.t=e,!r.__c&&(r.__=[n?n(t):bc(void 0,t),function(e){var t=r.__N?r.__N[0]:r.__[0],n=r.t(t,e);t!==n&&(r.__N=[n,r.__[1]],r.__c.setState({}))}],r.__c=Zl,!Zl.u)){Zl.u=!0;var s=Zl.shouldComponentUpdate;Zl.shouldComponentUpdate=function(e,t,n){if(!r.__c.__H)return!0;var i=r.__c.__H.__.filter((function(e){return e.__c}));if(i.every((function(e){return!e.__N})))return!s||s.call(this,e,t,n);var o=!1;return i.forEach((function(e){if(e.__N){var t=e.__[0];e.__=e.__N,e.__N=void 0,t!==e.__[0]&&(o=!0)}})),!!o&&(!s||s.call(this,e,t,n))}}return r.__N||r.__}(bc,e)}function hc(e){return nc=5,function(e,t){var n=uc(Xl++,7);return mc(n.__H,t)?(n.__V=e(),n.i=t,n.__h=e,n.__V):n.__}((function(){return{current:e}}),[])}function fc(){for(var e;e=rc.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(gc),e.__H.__h.forEach(yc),e.__H.__h=[]}catch(t){e.__H.__h=[],vl.__e(t,e.__v)}}vl.__b=function(e){Zl=null,ic&&ic(e)},vl.__r=function(e){oc&&oc(e),Xl=0;var t=(Zl=e.__c).__H;t&&(ec===Zl?(t.__h=[],Zl.__h=[],t.__.forEach((function(e){e.__N&&(e.__=e.__N),e.__V=sc,e.__N=e.i=void 0}))):(t.__h.forEach(gc),t.__h.forEach(yc),t.__h=[])),ec=Zl},vl.diffed=function(e){lc&&lc(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==rc.push(t)&&tc===vl.requestAnimationFrame||((tc=vl.requestAnimationFrame)||function(e){var t,n=function(){clearTimeout(r),pc&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,100);pc&&(t=requestAnimationFrame(n))})(fc)),t.__H.__.forEach((function(e){e.i&&(e.__H=e.i),e.__V!==sc&&(e.__=e.__V),e.i=void 0,e.__V=sc}))),ec=Zl=null},vl.__c=function(e,t){t.some((function(e){try{e.__h.forEach(gc),e.__h=e.__h.filter((function(e){return!e.__||yc(e)}))}catch(n){t.some((function(e){e.__h&&(e.__h=[])})),t=[],vl.__e(n,e.__v)}})),cc&&cc(e,t)},vl.unmount=function(e){ac&&ac(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach((function(e){try{gc(e)}catch(e){t=e}})),t&&vl.__e(t,n.__v))};var pc="function"==typeof requestAnimationFrame;function gc(e){var t=Zl,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),Zl=t}function yc(e){var t=Zl;e.__c=e.__(),Zl=t}function mc(e,t){return!e||e.length!==t.length||t.some((function(t,n){return t!==e[n]}))}function bc(e,t){return"function"==typeof t?t(e):t}function vc({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,(e=>n[e.substring(1,e.length-1)]))}function wc({title:e,type:t,alerts:n,fields:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=dc({}),u=hc(null);return function(e,t){var n=uc(Xl++,4);!vl.__s&&mc(n.__H,t)&&(n.__=e,n.i=t,Zl.__h.push(n))}((()=>{var e;return null===(e=u.current)||void 0===e?void 0:e.focus()}),[]),Dl(Ql,{className:"dxc-login-dlg"},Dl(Ol,null,Dl("h3",{style:Gl.WindowHeader},e),n.map((e=>Dl("p",{style:Gl.Alert[e.type]},vc(e)))),Dl("form",{onSubmit:e=>{e.preventDefault(),l(c)}},Object.entries(r).map((([e,{type:t,label:n,placeholder:r}],s)=>Dl("label",{style:Gl.Label,key:s},n?`${n}: `:"",Dl("input",{ref:0===s?u:void 0,type:t,name:e,autoComplete:"on",style:Gl.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)}})))))),Dl("div",{style:Gl.ButtonsDiv},Dl(Ol,null,Dl("button",{type:"submit",style:Gl.PrimaryButton,onClick:()=>l(c)},s),i&&Dl("button",{style:Gl.Button,onClick:o},i))))}class _c extends Tl{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=n.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?Dl(wc,Object.assign({},t)):null}}function kc(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const Sc=kc((e=>new n.BehaviorSubject(me)));function xc(e,t){let r=t,s=n.from(e).pipe(n.map((e=>r=e)),n.share({resetOnRefCountZero:()=>n.timer(1e3)}));const i=new n.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 Ec=kc((e=>xc(t.liveQuery((()=>e.roles.where({realmId:"rlm-public"}).toArray().then((e=>{const t={};for(const n of e.slice().sort(((e,t)=>(e.sortOrder||0)-(t.sortOrder||0))))t[n.name]=n;return t})))),{}))),Cc=kc((e=>xc(Sc(e._novip).pipe(r.switchMap((n=>t.liveQuery((()=>e.transaction("r","realms","members",(()=>Promise.all([e.members.where({userId:n.userId}).toArray(),e.realms.toArray(),n.userId]).then((([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}})));function Ic(...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 Dc=kc((e=>function(e,t){let r;const s=e.pipe(n.map((e=>r=t(e))));return s.getValue=()=>void 0!==r?r:r=t(e.getValue()),s}(xc(n.combineLatest([Cc(e._novip),Ec(e._novip)]).pipe(r.map((([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r})))),{selfMembers:[],realms:[],userId:me.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=Le(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:"*"}:Ic(...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 Ac{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 Oc=kc((e=>{const i=Sc(e._novip).pipe(r.switchMap((n=>t.liveQuery((()=>e.members.where({email:n.email||""}).toArray()))))),o=Dc(e._novip),l=Cc(e._novip);return xc(n.combineLatest([i,l,o]).pipe(r.map((([t,n,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),o=t.reduce(i,{}),l=n.selfMembers.reduce(i,o);return Object.values(l).filter((e=>!e.accepted)).map((t=>Object.assign(Object.assign({},t),{accept(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{accepted:new Date})}))},reject(){return s(this,void 0,void 0,(function*(){yield e.members.update(t.id,{rejected:new Date})}))}})))}))),[])}));function Tc(e){return r=>{var i;const o=r.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=e.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(r,"awareness",{get:()=>c||(c=function(e,r,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=r.meta,u=new nl(r),d=ol(r);return u.on("update",(({added:t,updated:n,removed:s},l)=>{const a=t.concat(n).concat(s),d=e.cloud.currentUser.value;if("server"!==l&&d.isLoggedIn&&!Vo(e)){const t=sl(u,a);e.messageProducer.next({type:"aware",table:o,prop:c,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:c,k:r.meta.parentId})}})),u.on("destroy",(()=>{rl(u,[r.clientID],"provider destroyed")})),(()=>{s(this,void 0,void 0,(function*(){if(i.destroyed)return;let r=!1,u=1;const h=n.combineLatest([e.cloud.webSocketStatus,d.pipe(n.startWith(null))]).subscribe((([t])=>{if(i.destroyed)return;r="connected"===t;const n=e.cloud.currentUser.value;"connected"===t&&n.isLoggedIn&&!Vo(e)&&(++u,f().catch((e=>{})))}));function f(){return s(this,void 0,void 0,(function*(){const n=u,d=e.table(a),h=e.$syncState,[f,p]=yield e.transaction("r",h,d,(()=>s(this,void 0,void 0,(function*(){const e=yield d.get(xt),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||u!==n||!r)return;const g={type:"doc-open",table:o,prop:c,k:l,serverRev:p},y=yield d.where("i").between(f,1/0,!1).filter((e=>0===t.cmp(e.k,l)&&0==(1&(e.f||0)))).toArray();if(!i.destroyed&&u===n&&r){if(y.length>0){const e=ws(y.map((e=>e.u))),t=bs(e);g.sv=t}e.messageProducer.next(g)}}))}i.addCleanupHandler(h)}))})(),u}(e,o,r),el.set(o,c),c)})}}const Uc={},jc=new WeakMap,Lc=Rc("tx"),Pc=Rc("unload");function Rc(e){let t=null,n=!1,r=new Map;return{name:e,run(){return s(this,void 0,void 0,(function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch((()=>{}))),setTimeout((()=>{n=!1;const e=r;r=new Map,t=function(e){return s(this,void 0,void 0,(function*(){for(const{db:t,parentId:n,triggers:r,parentTable:s,prop:i}of e.values()){const e=co.getOrCreateDocument(t,s,i,n);try{const t=co.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{co.release(e)}}}))}(e).finally((()=>{t=null}))}),0))}))},enqueue(e,t,n,s,i){const o=`${e.name}:${t}:${n}:${s}`;let l=r.get(o);l||(l={db:e,parentTable:t,parentId:n,prop:s,triggers:new Set},r.set(o,l)),l.triggers.add(i)}}}function Mc(){Lc.run()}function Nc(){Pc.run()}const $c={nameSuffix:!0};function Bc(e){const i=e.name,o=Sc(e),l=[];let c=!1,a=null;e.on("ready",(e=>s(this,void 0,void 0,(function*(){try{yield function(e){return s(this,void 0,void 0,(function*(){var i,f,p,g,y,m,b;u=!1;const v=Co(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=v.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),Yl(Dl(_c,{db:e.vip}),n)):addEventListener("DOMContentLoaded",(()=>{t||(document.body.appendChild(n),Yl(Dl(_c,{db:e.vip}),n))})),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),v.cloud.isServiceWorkerDB||l.push(function(e){let t=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(r.switchMap((e=>{const s=t;t=e;const i=n.of(e);switch(e){case"disconnected":return Jo.value?i.pipe(r.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(r.debounceTime(4e3));default:return i}})));return n.combineLatest([s,e.syncStateChangedEvent.pipe(r.startWith({phase:"initial"})),Sc(e.dx._novip),qo]).pipe(r.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:vt?a:"offline",license:"ok"}})))}(v).subscribe(e.cloud.syncState)),l.push(v.syncCompleteEvent.subscribe(h)),v.tables.every((e=>e.core))||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const w="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[_,k]=yield v.transaction("rw",v.$syncState,(()=>s(this,void 0,void 0,(function*(){var e,t;const{options:n,schema:r}=v.cloud,[s,i,o]=yield Promise.all([v.getOptions(),v.getSchema(),v.getPersistedSyncState()]);if(c){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 v.$syncState.put(e,"options")}}else v.cloud.options=s||null;if((null===(e=v.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&w.length>0&&!Oo?v.cloud.usingServiceWorker=!0:((null===(t=v.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&v.cloud.isServiceWorkerDB,v.cloud.usingServiceWorker=!1),ml(r,v.cloud.options),ml(i,v.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 v.$syncState.put(e,"schema"),Object.assign(r,e)}}else v.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}))));if(_&&v.setInitiallySynced(!0),function(e){var n,r;for(const s of e.tables)if(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new t.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 t.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(v),d(),!v.cloud.isServiceWorkerDB){l.push(t.liveQuery((()=>v.getCurrentUser())).subscribe(o)),l.push(t.liveQuery((()=>v.getPersistedSyncState())).subscribe(v.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([o.pipe(r.skip(1),r.take(1)),v.cloud.persistedSyncState.pipe(r.skip(1),r.take(1))]));const e=Tc(v);co.on.new.subscribe(e),v.dx.once("close",(()=>{co.on.new.unsubscribe(e)}))}let S=!1;const x=yield v.getCurrentUser(),E=null===(f=v.cloud.options)||void 0===f?void 0:f.requireAuth;E&&(v.cloud.isServiceWorkerDB?yield n.firstValueFrom(o.pipe(r.filter((e=>!!e.isLoggedIn)),r.take(1))):"object"==typeof E?(!x.isLoggedIn||E.userId&&x.userId!==E.userId||E.email&&x.email!==E.email)&&(S=yield Se(v,E)):x.isLoggedIn||(S=yield Se(v))),!x.isLoggedIn||k&&k.includes(x.userId)||(S=!0),a&&a.stop(),a=null,d();const C=(null===(p=v.cloud.options)||void 0===p?void 0:p.databaseUrl)&&(!_||S);C&&(yield function(e,t,n){return s(this,void 0,void 0,(function*(){yield Ho(e,go,(()=>yo(e,t,n,{isInitialSync:!0})))}))}(v,v.cloud.options,v.cloud.schema),v.setInitiallySynced(!0)),d(),v.cloud.usingServiceWorker&&(null===(g=v.cloud.options)||void 0===g?void 0:g.databaseUrl)?(C||te(v,"push").catch((()=>{})),function(e){return s(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){}}))}(v).catch((()=>{}))):(null===(y=v.cloud.options)||void 0===y?void 0:y.databaseUrl)&&v.cloud.schema&&!v.cloud.isServiceWorkerDB&&(a=yl(v,v.cloud.options,v.cloud.schema),a.start(),C||ne(v,"push")),d(),v.cloud.isServiceWorkerDB||l.push(n.fromEvent(self,"online").subscribe((()=>{v.syncStateChangedEvent.next({phase:"not-in-sync"}),Vo(v)||ne(v,"push")})),n.fromEvent(self,"offline").subscribe((()=>{v.syncStateChangedEvent.next({phase:"offline"})}))),!(null===(m=v.cloud.options)||void 0===m?void 0:m.databaseUrl)||(null===(b=v.cloud.options)||void 0===b?void 0:b.disableWebSocket)||To||l.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(r.filter((e=>e)),r.switchMap((()=>e.getPersistedSyncState())),r.filter((e=>e&&e.serverRevision)),r.switchMap((e=>s(this,void 0,void 0,(function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield Ae(e)}}))))),o=n.merge(i,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(r.filter((e=>null==e?void 0:e.serverRevision)),r.take(1),r.switchMap((t=>e.cloud.currentUser.pipe(r.map((e=>[e,t]))))),r.switchMap((([e,t])=>qo.pipe(r.map((n=>[n?e:null,t]))))),r.switchMap((([t,s])=>(null==t?void 0:t.isLoggedIn)&&!(null==s?void 0:s.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(r.filter((e=>(null==e?void 0:e.realms.includes(t.userId))||!1)),r.take(1),r.map((e=>[t,e]))):new n.BehaviorSubject([t,s]))),r.switchMap((e=>s(this,[e],void 0,(function*([e,t]){return[e,yield Ae(t)]})))),r.distinctUntilChanged((([e,t],[n,r])=>e===n&&t===r)),r.switchMap((([r,s])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?r?new ll(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,s,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,r):n.from([]):t()})),r.catchError((i=>"TokenExpiredError"===(null==i?void 0:i.name)?n.of(!0).pipe(r.switchMap((()=>s(this,void 0,void 0,(function*(){const t=yield e.getCurrentUser(),n=yield pe(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})})))),r.switchMap((()=>t()))):n.throwError((()=>i)))),r.catchError((s=>(e.cloud.webSocketStatus.next("error"),s instanceof ul?n.throwError((()=>s)):n.from(dl()).pipe(r.switchMap((()=>t())))))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(v))}))}(e)}catch(e){}}))),!0);let u=!1;function d(){if(u)throw new t.DatabaseClosedError}e.once("close",(()=>{l.forEach((e=>e.unsubscribe())),l.splice(0,l.length),u=!0,a&&a.stop(),a=null,o.next(me)}));const h=new n.Subject;var f;e.cloud={version:"4.2.4",options:Object.assign({},$c),schema:null,get currentUserId(){return o.value.userId||me.userId},currentUser:o,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:h},persistedSyncState:new n.BehaviorSubject(void 0),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,(function*(){const n=Co(e);yield n.cloud.sync(),yield Se(n,t)}))},invites:Oc(e),roles:Ec(e),configure(t){t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),c=!0,t.databaseUrl&&t.nameSuffix&&(e.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(t.databaseUrl)}`,Co(e).reconfigure()),ml(e.cloud.schema,e.cloud.options)},logout(){return s(this,arguments,void 0,(function*({force:t}={}){t?yield we(Co(e),{deleteUnsyncedData:!0}):yield ve(Co(e))}))},sync(){return s(this,arguments,void 0,(function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=Co(e);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield he(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(ne(c,o),i){const t=yield n.firstValueFrom(c.cloud.persistedSyncState.pipe(r.filter((t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp)))));if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield hl(c)){const e=c.cloud.persistedSyncState.value;ne(c,o),i&&(yield n.firstValueFrom(n.from(t.liveQuery((()=>s(this,void 0,void 0,(function*(){const t=yield hl(c),n=yield c.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==e?void 0:e.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return t}))))).pipe(r.filter((e=>!e)))))}}))},permissions:(t,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const o=Dc(e),l=t=>{const r=t[i||e.cloud.currentUserId];return r?new Ac(r.permissions,n,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new Ac({},n,!s||s===e.cloud.currentUserId)},c=o.pipe(r.map(l));return c.getValue=()=>l(o.getValue()),c}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,(t=>zo(t,e))),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return Mo(e.cloud.schema[this.name].idPrefix||"",n)},e.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)||""},e.use(Ko({currentUserObservable:e.cloud.currentUser,db:Co(e)})),e.use((f=Co(e),{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,c;const a=e.trans;if(a.disableChangeTracking)return n.mutate(e);const u=null!==(s=null===(r=a.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:me.userId;if((null===(o=null===(i=f.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===(c=(l=n.schema.primaryKey).extractKey)||void 0===c?void 0:c.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)}})}})})),e.use(No(Co(e)))}Bc.version="4.2.4",t.Cloud=Bc,e.default=Bc,e.defineYDocTrigger=function(e,n,r){var s,i;const o=null===(i=null===(s=e.schema.yProps)||void 0===s?void 0:s.find((e=>e.prop===n)))||void 0===i?void 0:i.updatesTable;if(!o)throw new Error(`Table ${e.name} does not have a Yjs property named ${n}`);Uc[o]={trigger:r,parentTable:e.name,prop:n};const l=e.db._novip;let c=jc.get(l);c||(c=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:n=>Object.assign(Object.assign({},n),{transaction:(e,t,r)=>{const s=n.transaction(e,t,r);return"readonly"===t?s:e.some((e=>Uc[e]))?(s.addEventListener("complete",Mc),s):s},table:r=>{const s=n.table(r),i=Uc[r];if(!i)return s;const{trigger:o,parentTable:l,prop:c}=i;return Object.assign(Object.assign({},s),{mutate(n){var r;switch(n.type){case"add":for(const t of n.values){if(null==t.k)continue;const n=t.k,s=co.getDocCache(e).find(l,n,c);(s&&(null===(r=co.for(s))||void 0===r?void 0:r.refCount)?Pc:Lc).enqueue(e,l,n,c,o)}break;case"delete":n.trans._rejecting_y_ypdate&&s.getMany({keys:n.keys,trans:n.trans,cache:"immutable"}).then((n=>{const r=new t.RangeSet;for(const{k:e}of n)null!=e&&r.addKey(e);for(const t of r)Lc.enqueue(e,l,t.from,c,o)}))}return s.mutate(n)}})}})}))(l),jc.set(l,c)),l.use(c),co.on("beforeunload",Nc)},e.dexieCloud=Bc,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=vc,Object.defineProperty(e,"__esModule",{value:!0})}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("dexie"),require("rxjs"),require("rxjs/operators")):"function"==typeof define&&define.amd?define(["exports","dexie","rxjs","rxjs/operators"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).DexieCloud={},e.Dexie,e.rxjs,e.rxjs.operators)}(this,function(e,t,n,r){"use strict";function s(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 i(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 o(e){return this instanceof o?(this.v=e,this):new o(e)}function l(e,t,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r,s=n.apply(e,t||[]),i=[];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){i.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 o?Promise.resolve(e.value.v).then(a,d):u(i[0][2],e)}(s[e](t))}catch(e){u(i[0][3],e)}}function a(e){c("next",e)}function d(e){c("throw",e)}function u(e,t){e(t),i.shift(),i.length&&c(i[0][0],i[0][1])}}function c(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=i(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 a={}.hasOwnProperty;function d(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)d(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 a.call(e,t)}(e,o)||(c=e[o]={}),d(c,l,n)}}else void 0===n?Array.isArray(e)&&!isNaN(parseInt(t))?e.splice(t,1):delete e[t]:e[t]=n}}const u="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=h)=>{const n=Buffer.alloc(e);return t(n),n.toString("base64")}:()=>{throw new Error("No implementation of randomString was found")};function h(e){for(let t=0;t<e.length;++t)e[t]=Math.floor(256*Math.random())}function f(e){return"string"==typeof e||!!(Array.isArray(e)&&e.some(e=>f(e))&&e.every(p))}function p(e){return"string"==typeof e||"number"==typeof e||Array.isArray(e)&&e.every(p)}function g(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))d(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 y(e,t){for(const{table:n,muts:r}of t)for(const t of r)g(e,n,t)}const m=Math.floor,v=Math.abs,b=(e,t)=>e<t?e:t,w=(e,t)=>e>t?e:t,_=e=>0!==e?e<0:1/e<0,k=64,S=128,x=127,E=Number.MAX_SAFE_INTEGER,C=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&m(e)===e),I=()=>new Set,O=e=>e[e.length-1],D=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},A=Array.from,T=Array.isArray,j=/^\s*/g,U=/([A-Z])/g,P=(e,t)=>(e=>e.replace(j,""))(e.replace(U,e=>`${t}${(e=>e.toLowerCase())(e)}`)),L="undefined"!=typeof TextEncoder?new TextEncoder:null,M=L?e=>L.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 R="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});R&&1===R.decode(new Uint8Array).length&&(R=null);class ${constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const N=()=>new $,B=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},F=(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},W=F,H=(e,t)=>{for(;t>x;)F(e,S|x&t),t=m(t/128);F(e,x&t)},V=(e,t)=>{const n=_(t);for(n&&(t=-t),F(e,(t>63?S:0)|(n?k:0)|63&t),t=m(t/64);t>0;)F(e,(t>x?S:0)|x&t),t=m(t/128)},z=new Uint8Array(3e4),K=z.length/3,J=L&&L.encodeInto?(e,t)=>{if(t.length<K){const n=L.encodeInto(t,z).written||0;H(e,n);for(let t=0;t<n;t++)F(e,z[t])}else Y(e,M(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;H(e,r);for(let t=0;t<r;t++)F(e,n.codePointAt(t))},q=(e,t)=>{const n=e.cbuf.length,r=e.cpos,s=b(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(w(2*n,i)),e.cbuf.set(t.subarray(s)),e.cpos=i)},Y=(e,t)=>{H(e,t.byteLength),q(e,t)},G=(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*w(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Q=(e,t)=>G(e,8).setBigUint64(0,t,!1),X=new DataView(new ArrayBuffer(4)),Z=(e,t)=>{switch(typeof t){case"string":F(e,119),J(e,t);break;case"number":C(t)&&v(t)<=2147483647?(F(e,125),V(e,t)):(n=t,X.setFloat32(0,n),X.getFloat32(0)===n?(F(e,124),((e,t)=>{G(e,4).setFloat32(0,t,!1)})(e,t)):(F(e,123),((e,t)=>{G(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":F(e,122),((e,t)=>{G(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)F(e,126);else if(T(t)){F(e,117),H(e,t.length);for(let n=0;n<t.length;n++)Z(e,t[n])}else if(t instanceof Uint8Array)F(e,116),Y(e,t);else{F(e,118);const n=Object.keys(t);H(e,n.length);for(let r=0;r<n.length;r++){const s=n[r];J(e,s),Z(e,t[s])}}break;case"boolean":F(e,t?120:121);break;default:F(e,127)}var n};class ee extends ${constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&H(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const te=e=>{e.count>0&&(V(e.encoder,1===e.count?e.s:-e.s),e.count>1&&H(e.encoder,e.count-2))};class ne{constructor(){this.encoder=new $,this.s=0,this.count=0}write(e){this.s===e?this.count++:(te(this),this.count=1,this.s=e)}toUint8Array(){return te(this),B(this.encoder)}}const re=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);V(e.encoder,t),e.count>1&&H(e.encoder,e.count-2)}};class se{constructor(){this.encoder=new $,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(re(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return re(this),B(this.encoder)}}class ie{constructor(){this.sarr=[],this.s="",this.lensE=new ne}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 $;return this.sarr.push(this.s),this.s="",J(e,this.sarr.join("")),q(e,this.lensE.toUint8Array()),B(e)}}const oe=e=>new Error(e),le=()=>{throw oe("Method unimplemented")},ce=()=>{throw oe("Unexpected case")},ae=oe("Unexpected end of array"),de=oe("Integer out of Range");class ue{constructor(e){this.arr=e,this.pos=0}}const he=e=>new ue(e),fe=e=>e.pos!==e.arr.length,pe=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,ye(e)),ge=e=>e.arr[e.pos++],ye=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&x)*n,n*=128,r<S)return t;if(t>E)throw de}throw ae},me=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const s=(t&k)>0?-1:1;if(0===(t&S))return s*n;const i=e.arr.length;for(;e.pos<i;){if(t=e.arr[e.pos++],n+=(t&x)*r,r*=128,t<S)return s*n;if(n>E)throw de}throw ae},ve=R?e=>R.decode(pe(e)):e=>{let t=ye(e);if(0===t)return"";{let n=String.fromCodePoint(ge(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(ge(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))}},be=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},we=e=>be(e,8).getBigUint64(0,!1),_e=[e=>{},e=>null,me,e=>be(e,4).getFloat32(0,!1),e=>be(e,8).getFloat64(0,!1),e=>be(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ve,e=>{const t=ye(e),n={};for(let r=0;r<t;r++){n[ve(e)]=ke(e)}return n},e=>{const t=ye(e),n=[];for(let r=0;r<t;r++)n.push(ke(e));return n},pe],ke=e=>_e[127-ge(e)](e);class Se extends ue{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return 0===this.count&&(this.s=this.reader(this),fe(this)?this.count=ye(this)+1:this.count=-1),this.count--,this.s}}class xe extends ue{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=me(this);const e=_(this.s);this.count=1,e&&(this.s=-this.s,this.count=ye(this)+2)}return this.count--,this.s}}class Ee extends ue{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=ye(this)+2)}return this.s+=this.diff,this.count--,this.s}}class Ce{constructor(e){this.decoder=new xe(e),this.str=ve(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*Ie(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}}}}let Oe=!1;function De(e,t){return s(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){Oe||(Oe=!0)}})}function Ae(e,t){e.cloud.usingServiceWorker?De(e,t):e.localSyncEvent.next({purpose:t})}const Te="fromBase64"in Uint8Array,je="toBase64"in Uint8Array.prototype,Ue="undefined"!=typeof Buffer?e=>Buffer.from(e,"base64"):Te?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},Pe="undefined"!=typeof Buffer?e=>ArrayBuffer.isView(e)?Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"):Buffer.from(e).toString("base64"):je?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(""))};class Le extends Error{constructor({title:e,message:t,messageCode:n,messageParams:r}){super(t),this.name="TokenErrorResponseError",this.title=e,this.messageCode=n,this.messageParams=r}}function Me(e,n){return new Promise((r,s)=>{const i=Object.assign(Object.assign({submitLabel:"Submit",cancelLabel:"Cancel"},n),{onSubmit:t=>{e.next(void 0),r(t)},onCancel:()=>{e.next(void 0),s(new t.AbortError("User cancelled"))}});e.next(i)})}function Re(e,t,...n){return Me(e,{type:"message-alert",title:t,alerts:n,fields:{},submitLabel:"OK",cancelLabel:null})}function $e(e,t,n){return s(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 Me(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 Ne(e,t,n){return s(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 Me(e,{type:"otp",title:"Enter OTP",alerts:r,fields:{otp:{type:"otp",label:"OTP",placeholder:"Paste OTP here"}}});return s})}function Be(e){return s(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 We(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 Fe(e,n,r,i,o){return s(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 We(e,n):yield function(e,n,r,i){return s(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:s,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(!s||!o)throw new Error("Could not generate RSA keypair");e.nonExportablePrivateKey=s;const l=function(e){const t=Pe(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));e.publicKey=o;try{const t=yield n({public_key:l,hints:i});if("error"===t.type)throw new Le(t);if("tokens"!==t.type)throw new Error(`Unexpected response type from token endpoint: ${t.type}`);return e.accessToken=t.accessToken,e.accessTokenExpiration=new Date(t.accessTokenExpiration),e.refreshToken=t.refreshToken,t.refreshTokenExpiration&&(e.refreshTokenExpiration=new Date(t.refreshTokenExpiration)),e.userId=t.claims.sub,e.email=t.claims.email,e.name=t.claims.name,e.claims=t.claims,e.license={type:t.userType,status:t.claims.license||"ok"},e.data=t.data,null!=t.evalDaysLeft&&(e.license.evalDaysLeft=t.evalDaysLeft),null!=t.userValidUntil&&(e.license.validUntil=new Date(t.userValidUntil)),t.alerts&&t.alerts.length>0&&(yield Me(r,{type:"message-alert",title:"Authentication Alert",fields:{},alerts:t.alerts})),e}catch(e){if(e instanceof Le)throw yield Re(r,e.title,{type:"error",messageCode:e.messageCode,message:e.message,messageParams:{}}),e;let n="We're having a problem authenticating right now.";if(e instanceof TypeError){n=void 0!==typeof navigator&&!navigator.onLine?"You seem to be offline. Please connect to the internet and try again.":t.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 Re(r,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:n,messageParams:{}}).catch(()=>{})}throw e}})}(n,r,i,o)})}function We(e,t){return s(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=Pe(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 Le(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 He=new WeakMap;class Ve{constructor(e,t){He.set(this,e),Object.assign(this,t)}static load(e,t){return e.table("$logins").get(t).then(n=>new Ve(e,n||{userId:t,claims:{sub:t},lastLogin:new Date(0)}))}save(){return s(this,void 0,void 0,function*(){He.get(this).table("$logins").put(this)})}}const ze={userId:"unauthorized",name:"Unauthorized",claims:{sub:"unauthorized"},lastLogin:new Date(0)};try{Object.freeze(ze),Object.freeze(ze.claims)}catch(e){}function Ke(e,t){return n.firstValueFrom(n.from(e).pipe(n.filter(t)))}function Je(e){return s(this,void 0,void 0,function*(){const t=yield qe(e);if(t){if(!(yield function(e,t,n){return s(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 Me(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 qe(e,{deleteUnsyncedData:!0})}})}function qe(e){return s(this,arguments,void 0,function*(e,{deleteUnsyncedData:t=!1}={}){const[n,r]=yield e.dx.transaction("rw",e.dx.tables,n=>s(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 r&&(yield Ke(e.cloud.currentUser,e=>e.userId===ze.userId),yield e.cloud.sync({purpose:"pull",wait:!0})),n})}class Ye extends Error{constructor(e,t){super(t||`${e.status} ${e.statusText}`),this.httpStatus=e.status}get name(){return"HttpError"}}const Ge={popup_blocked:"The login popup was blocked by your browser. Please allow popups for this site and try again.",popup_closed:"The login popup was closed before completing authentication.",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 Qe extends Error{constructor(e,t,n){super(n||Ge[e]),this.name="OAuthError",this.code=e,this.provider=t}get userMessage(){return Ge[this.code]||this.message}}function Xe(e){return s(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 Qe("expired_code",void 0,t.message);throw new Le(t)}}catch(e){if(e instanceof Qe||e instanceof Le)throw e}const t=yield e.text().catch(()=>e.statusText);throw new Qe("provider_error",void 0,`Token exchange failed: ${e.status} ${t}`)}const n=yield e.json();if("error"===n.type)throw new Le(n);if("tokens"!==n.type)throw new Qe("provider_error",void 0,`Unexpected response type: ${n.type}`);return n}catch(e){if(e instanceof Qe||e instanceof Le)throw e;if(e instanceof TypeError)throw new Qe("network_error");throw e}})}const Ze={providers:[],otpEnabled:!0};function et(e){return s(this,void 0,void 0,function*(){const{databaseUrl:t,provider:n,usePopup:r=!0}=e;if(!r)throw new Error("Non-popup OAuth flow requires handleOAuthCallback after redirect");const s=function(){const e=new Uint8Array(32);return crypto.getRandomValues(e),Array.from(e,e=>e.toString(16).padStart(2,"0")).join("")}(),i=function(e,t){const n=new URL(`${e.databaseUrl}/oauth/login/${e.provider}`);n.searchParams.set("state",t);const r=e.redirectUri||("undefined"!=typeof window?window.location.origin:"");return r&&n.searchParams.set("redirect_uri",r),n.toString()}(e,s),{left:o,top:l}=function(e,t){var n,r,s,i,o,l;const c=null!==(n=window.screenLeft)&&void 0!==n?n:window.screenX,a=null!==(r=window.screenTop)&&void 0!==r?r:window.screenY,d=c+((null!==(i=null!==(s=window.innerWidth)&&void 0!==s?s:document.documentElement.clientWidth)&&void 0!==i?i:screen.width)-e)/2,u=a+((null!==(l=null!==(o=window.innerHeight)&&void 0!==o?o:document.documentElement.clientHeight)&&void 0!==l?l:screen.height)-t)/2;return{left:Math.max(0,d),top:Math.max(0,u)}}(500,600),c=window.open(i,"dexie-cloud-oauth",`width=500,height=600,left=${o},top=${l},menubar=no,toolbar=no,location=yes,status=no`);if(!c)throw new Qe("popup_blocked",n);return new Promise((e,r)=>{let i=!1;const o=o=>{const l=new URL(t).origin;if(o.origin!==l)return;if("object"!=typeof(c=o.data)||null===c||"dexie:oauthResult"!==c.type||"string"!=typeof c.provider||"string"!=typeof c.state)return;var c;const d=o.data;if(d.state===s){if(a(),i=!0,d.error){const e=function(e){const t=e.toLowerCase();if(t.includes("access_denied")||t.includes("access denied"))return"access_denied";if(t.includes("email")&&t.includes("verif"))return"email_not_verified";if(t.includes("expired"))return"expired_code";if(t.includes("state"))return"invalid_state";return"provider_error"}(d.error);return void r(new Qe(e,n,d.error))}d.code?e({code:d.code,provider:d.provider,state:d.state}):r(new Qe("provider_error",n,"No authorization code received"))}},l=setInterval(()=>{c.closed&&!i&&(a(),r(new Qe("popup_closed",n)))},500),a=()=>{window.removeEventListener("message",o),clearInterval(l);try{c.closed||c.close()}catch(e){}};window.addEventListener("message",o)})})}function tt(e){const{userInteraction:n}=e.cloud;return function(r){return s(this,arguments,void 0,function*({public_key:r,hints:i}){var o,l;let c;const a=null===(o=e.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 Xe({databaseUrl:a,code:i.oauthCode,publicKey:r,scopes:["ACCESS_DB"]});if(null==i?void 0:i.provider)return yield nt(e,r,i.provider);if("demo"===(null==i?void 0:i.grant_type)){c={demo_user:yield $e(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:r}}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:r};else{const o=!1!==(null===(l=e.cloud.options)||void 0===l?void 0:l.socialAuth),d=yield function(e){return s(this,arguments,void 0,function*(e,t=!0){if(!t)return Ze;try{const t=yield fetch(`${e}/auth-providers`,{method:"GET",headers:{Accept:"application/json"},mode:"cors"});return 404===t.status?Ze:t.ok?yield t.json():Ze}catch(e){return Ze}})}(a,o);if(d.providers.length>0){const s=yield function(e,n,r,s="Choose login method",i=[]){return new Promise((o,l)=>{const c={type:"provider-selection",title:s,alerts:i,providers:n,otpEnabled:r,fields:{},submitLabel:void 0,cancelLabel:"Cancel",onSelectProvider:t=>{e.next(void 0),o({type:"provider",provider:t})},onSelectOtp:()=>{e.next(void 0),o({type:"otp"})},onCancel:()=>{e.next(void 0),l(new t.AbortError("User cancelled"))}};e.next(c)})}(n,d.providers,d.otpEnabled,"Sign in");if("provider"===s.type)return yield nt(e,r,s.provider)}const u=yield $e(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:r}:{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 Re(n,"Token request failed",{type:"error",messageCode:"GENERIC_ERROR",message:e,messageParams:{}}).catch(()=>{}),new Ye(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 Ne(n,c.email),t=Object.assign(Object.assign({},c),{otp:e||"",otp_id:u.otp_id,public_key:r});let s=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"});for(;401===s.status;){const e=yield s.text();t.otp=yield Ne(n,c.email,{type:"error",messageCode:"INVALID_OTP",message:e,messageParams:{}}),s=yield fetch(`${a}/token`,{body:JSON.stringify(t),method:"post",headers:{"Content-Type":"application/json"},mode:"cors"})}if(200!==s.status){const e=yield s.text();throw new Ye(s,e)}return yield s.json()}throw new Error(`Unexpected response from ${a}/token`)})}}function nt(e,t,n){return s(this,void 0,void 0,function*(){var r,s,i;const o=null===(r=e.cloud.options)||void 0===r?void 0:r.databaseUrl;if(!o)throw new Error("No database URL given.");const{userInteraction:l}=e.cloud,c=!1!==(null===(s=e.cloud.options)||void 0===s?void 0:s.oauthPopup),a=(null===(i=e.cloud.options)||void 0===i?void 0:i.oauthRedirectUri)||("undefined"!=typeof window?window.location.origin:void 0);try{const e=yield et({databaseUrl:o,provider:n,redirectUri:a,usePopup:c});return yield Xe({databaseUrl:o,code:e.code,publicKey:t,scopes:["ACCESS_DB"]})}catch(e){throw e instanceof Qe&&(yield Re(l,"Authentication Failed",{type:"error",messageCode:"GENERIC_ERROR",message:e.userMessage,messageParams:{}}).catch(()=>{})),e}})}function rt(e,...t){globalThis.console[e](...t)}function st(e,t){return s(this,void 0,void 0,function*(){var n;const r=yield e.getCurrentUser(),i=r.userId;if(r.isLoggedIn&&(!t||!t.email&&!t.userId)){if("ok"===((null===(n=r.license)||void 0===n?void 0:n.status)||"ok")&&r.accessToken&&(!r.accessTokenExpiration||r.accessTokenExpiration.getTime()>Date.now()))return!1;if(r.refreshToken&&(!r.refreshTokenExpiration||r.refreshTokenExpiration.getTime()>Date.now()))return yield Be(e),!1}const o=new Ve(e,{claims:{},lastLogin:new Date(0)});return yield Fe(e.cloud.options.databaseUrl,o,e.cloud.options.fetchTokens||tt(e),e.cloud.userInteraction,t),i!==ze.userId&&o.userId!==i&&(yield Je(e)),yield function(e,t){return s(this,void 0,void 0,function*(){const n=e.table("$logins");yield e.transaction("rw",n,e=>s(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&&(rt("debug","Login context property names:",Object.keys(t)),rt("debug","Login context property names:",Object.keys(t)),rt("debug","Login context:",t),rt("debug","Login context JSON:",JSON.stringify(t)))}catch(e){}throw e}})),yield Ke(e.cloud.currentUser,e=>e.userId===t.userId)})}(e,o),Ae(e,"pull"),o.userId!==i})}const it={},ot="undefined"!=typeof self&&self.document&&"undefined"!=typeof navigator&&navigator.serviceWorker;ot&&ot.ready.then(e=>it.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 lt{constructor(e){this.name=e}subscribe(e){if(!ot)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 ot.addEventListener("message",t),()=>ot.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})):it.registration&&(null===(t=it.registration.active)||void 0===t||t.postMessage({type:`sw-broadcast-${this.name}`,message:e}))}}const ct=globalThis["lbc-events"]||(globalThis["lbc-events"]=new Map);class at extends n.Observable{constructor(e){const t="undefined"==typeof BroadcastChannel?new lt(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){ct.has(e)?ct.get(e).push(t):ct.set(e,[t])}(`lbc-${e}`,r);try{t instanceof lt?i=t.subscribe(e=>n.next(e)):t.addEventListener("message",s)}catch(e){}return()=>{!function(e,t){const n=ct.get(e);if(n){const e=n.indexOf(t);-1!==e&&n.splice(e,1)}}(`lbc-${e}`,r),t instanceof lt?i():t.removeEventListener("message",s)}}),this.name=e,this.bc=t}next(e){this.bc.postMessage(e);!function(e){const t=ct.get(e.type);t&&t.forEach(t=>{try{t(e)}catch(e){}})}(new CustomEvent(`lbc-${this.name}`,{detail:e}))}}function dt(e){return s(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 Pe(s)})}function ut(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 ht(e){return`$${e}_mutations`}function ft(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 pt=[].concat;function gt(e){return pt.apply([],e)}function yt(e,t){return s(this,arguments,void 0,function*(e,t,{since:n={},limit:r=1/0}={}){const i=yield Promise.all(e.map(e=>s(this,void 0,void 0,function*(){const t=ft(e.name),s=n[t];let i=s?e.where("rev").above(s):e;r<1/0&&(i=i.limit(r));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=gt(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 mt(e){const t=new Uint8Array(e);if("undefined"!=typeof crypto)crypto.getRandomValues(t);else for(let n=0;n<e;n++)t[n]=Math.floor(256*Math.random());if("undefined"!=typeof Buffer&&Buffer.from)return Buffer.from(t).toString("base64");if("undefined"!=typeof btoa)return btoa(String.fromCharCode.apply(null,t));throw new Error("No btoa or Buffer available")}const{toString:vt}={};const bt={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 wt(...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 bt;let i=n.get(r);if(void 0!==i)return i;const o=(s=e,vt.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:bt),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 _t={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 kt={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 St={bigint:{replace:e=>({$t:"bigint",v:""+e}),revive:e=>BigInt(e.v)}};var xt={Date:{replace:e=>({$t:"Date",v:isNaN(e.getTime())?"NaN":e.toISOString()}),revive:({v:e})=>new Date("NaN"===e?NaN:Date.parse(e))}},Et={Set:{replace:e=>({$t:"Set",v:Array.from(e.entries())}),revive:({v:e})=>new Set(e)}},Ct={Map:{replace:e=>({$t:"Map",v:Array.from(e.entries())}),revive:({v:e})=>new Map(e)}};const It="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof global?global:void 0;var Ot=["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=It[t];return s&&new s(r.ArrayBuffer.revive({v:e},n,r))}}}),{});function Dt(e){return function(e){for(var t="",n=0,r=e.length;n<r;n++)t+=jt[e[n]];return t}(Pe(e))}function At(e){return Ue(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+=Tt[e[n]];return t}(e))}const Tt={"-":"=",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:"+","|":"/"},jt={};for(const e of Object.keys(Tt))jt[Tt[e]]=e;var Ut={ArrayBuffer:{replace:e=>({$t:"ArrayBuffer",v:Dt(e)}),revive:({v:e})=>{const t=At(e);return t.buffer.byteLength===t.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}}};class Pt{constructor(e,t){this.buf=e,this.type=t}}function Lt(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 Mt(e){const t=new Uint8Array(e.length);for(let n=0;n<e.length;++n)t[n]=e.charCodeAt(n);return t.buffer}var Rt={Blob:{test:(e,t)=>"Blob"===t||e instanceof Pt,replace:e=>({$t:"Blob",v:Pe(e instanceof Pt?e.buf:Mt(Lt(e))),type:e.type}),revive:({type:e,v:t})=>{const n=Ue(t);return void 0!==typeof Blob?new Blob([n]):new Pt(n.buffer,e)}}};const $t={...kt,...St,...xt,...Et,...Ct,...Ot,...Ut,...Rt};function Nt(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 Bt={undefined:{replace:()=>({$t:"undefined"}),revive:()=>{}}},Ft={File:{test:(e,t)=>"File"===t,replace:e=>({$t:"File",v:Pe(Mt(Lt(e))),type:e.type,name:e.name,lastModified:new Date(e.lastModified).toISOString()}),revive:({type:e,v:t,name:n,lastModified:r})=>{const s=Ue(t);return new File([s],n,{type:e,lastModified:new Date(r).getTime()})}}};const Wt="function"==typeof BigInt&&"bigint"==typeof BigInt(0);class Ht{toString(){return this.v}constructor(e){this.v=e}}const Vt=Wt?{}:{bigint:{test:e=>e instanceof Ht,replace:e=>Object.assign({$t:"bigint"},e),revive:({v:e})=>new Ht(e)}},zt=Object.assign(Object.assign(Object.assign(Object.assign({},Bt),Vt),Ft),{PropModification:{test:e=>e instanceof t.PropModification,replace:e=>Object.assign({$t:"PropModification"},e["@@propmod"]),revive:e=>{var{$t:n}=e,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}(e,["$t"]);return new t.PropModification(r)}}}),Kt=wt($t,zt),Jt=function(...e){const t=wt($t,_t,...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 Nt(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 Nt(e.slice(0,4))).getUint32(0),n=e.slice(4,t+4),r=await function(e){return new Promise((t,n)=>{const r=new FileReader;r.onabort=e=>n(new Error("file read aborted")),r.onerror=e=>n(e.target.error),r.onload=e=>t(e.target.result),r.readAsText(e)})}(e.slice(t+4));return await this.parse(r,n)}}}(zt);function qt(e,n,r){const s=[];for(let i of r){const{table:r,muts:o}=i,l=e.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((e,r)=>{const s=!c.outbound&&("upsert"===e.type||"insert"===e.type);e.keys.forEach((e,o)=>{if(Array.isArray(e)){a===i&&(a=Yt(i,s));const t=a.muts[r],n=JSON.stringify(e);t.keys[o]=n}else if("#"===e[0]){a===i&&(a=Yt(i,s));const l=a.muts[r];if(!n.isLoggedIn)throw new Error("Internal error: Cannot sync private IDs before authenticated");const d=`${e}:${n.userId}`;l.keys[o]=d,s&&t.setByKeyPath(l.values[o],c.keyPath,d)}})}),s.push(a)}return s}function Yt(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 Gt=new WeakMap;function Qt(e){return s(this,void 0,void 0,function*(){var t,n;const r=(null!==(n=null===(t=Gt.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 Xt(e,t,n,r,i,o,l,c,a){return s(this,void 0,void 0,function*(){const s={Accept:"application/json, application/x-bison, application/x-bison-stream","Content-Type":"application/tson"},d=yield Be(i),u=null==d?void 0:d.accessToken;u&&(s.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:r,changes:qt(i.dx.core.schema,a,e),y:t,dxcv:i.cloud.version};i.syncStateChangedEvent.next({phase:"pushing"});const f=Kt.stringify(h),p=yield fetch(`${o}/sync`,{method:"post",headers:s,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));Gt.set(e,new Date(Date.now()+1e3*t))}else Gt.delete(e)}}(i,p),!p.ok)throw new Ye(p);if("application/x-bison"===p.headers.get("content-type"))return Jt.fromBinary(yield p.blob());{const e=yield p.text();return Kt.parse(e)}})}function Zt(e){if(null==e?void 0:e.cancelled)throw new t.AbortError("Operation was cancelled")}let en=!1;function tn(e,t,n,r){return s(this,void 0,void 0,function*(){yield e.$baseRevs.bulkPut(Object.keys(t).filter(e=>t[e].markedForSync).map(e=>({tableName:e,clientRev:(n[e]||0)+1,serverRev:r}))),yield e.$baseRevs.where("tableName").noneOf(Object.keys(t).filter(e=>t[e].markedForSync)).delete()})}function nn(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 rn(e,n,r){return s(this,void 0,void 0,function*(){const s=yield e.bulkGet(n),i=[],o=[];n.forEach((n,l)=>{const c=s[l];if(c){for(const[s,i]of Object.entries(r[l]))if(s===e.schema.primKey.keyPath){if(0!==t.cmp(i,n))throw new Error("Cannot change primary key")}else t.setByKeyPath(c,s,i);i.push(n),o.push(c)}}),yield null==e.schema.primKey.keyPath?e.bulkPut(o,i):e.bulkPut(o)})}function sn(e,n){return s(this,void 0,void 0,function*(){for(const{table:r,muts:s}of e){if(!n.dx._allTables[r])continue;const e=n.table(r),{primaryKey:i}=e.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 e.bulkAdd(n.values,r):(r.forEach((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)}),yield e.bulkAdd(n.values));break;case"upsert":i.outbound?yield e.bulkPut(n.values,r):(r.forEach((e,r)=>{t.setByKeyPath(n.values[r],i.keyPath,e)}),yield e.bulkPut(n.values));break;case"modify":1===r.length?yield e.update(r[0],n.changeSpec):yield e.where(":id").anyOf(r).modify(n.changeSpec);break;case"update":yield rn(e,r,n.changeSpecs);break;case"delete":yield e.bulkDelete(r)}}}})}"undefined"!=typeof self&&"undefined"!=typeof navigator&&(en=navigator.onLine,self.addEventListener("online",()=>en=!0),self.addEventListener("offline",()=>en=!1));const on="dexie-cloud-syncer";function ln(e,t){return e.where("i").between(t,1/0,!0).toArray()}const cn=()=>new Map,an=e=>{const t=cn();return e.forEach((e,n)=>{t.set(n,e)}),t},dn=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};class un{constructor(){this._observers=cn()}on(e,t){return dn(this._observers,e,I).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 A((this._observers.get(e)||cn()).values()).forEach(e=>e(...t))}destroy(){this._observers=cn()}}class hn{constructor(){this._observers=cn()}on(e,t){dn(this._observers,e,I).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 A((this._observers.get(e)||cn()).values()).forEach(e=>e(...t))}destroy(){this._observers=cn()}}const fn=crypto.getRandomValues.bind(crypto),pn=()=>fn(new Uint32Array(1))[0],gn=[1e7]+-1e3+-4e3+-8e3+-1e11,yn=()=>gn.replace(/[018]/g,e=>(e^pn()&15>>e/4).toString(16)),mn=Date.now,vn=e=>new Promise(e);Promise.all.bind(Promise);const bn=e=>void 0===e?null:e;let wn=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},_n=!0;try{"undefined"!=typeof localStorage&&localStorage&&(wn=localStorage,_n=!1)}catch($l){}const kn=wn,Sn=Object.assign,xn=Object.keys,En=e=>xn(e).length,Cn=e=>xn(e).length,In=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),On=Object.freeze,Dn=e=>{for(const t in e){const n=e[t];"object"!=typeof n&&"function"!=typeof n||Dn(e[t])}return On(e)},An=Symbol("Equality"),Tn=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&Tn(e,t,n+1)}},jn=(e,t)=>{if(e===t)return!0;if(null==e||null==t||e.constructor!==t.constructor)return!1;if(null!=e[An])return e[An](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)||!jn(e.get(n),t.get(n)))return!1;break;case Object:if(En(e)!==En(t))return!1;for(const n in e)if(!In(e,n)||!jn(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(!jn(e[n],t[n]))return!1;break;default:return!1}return!0},Un="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Pn;const Ln=e=>(()=>{if(void 0===Pn)if(Un){Pn=cn();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Pn.set(t,""),t=r):null!==t&&(Pn.set(t,r),t=null)}null!==t&&Pn.set(t,"")}else"object"==typeof location?(Pn=cn(),(location.search||"?").slice(1).split("&").forEach(e=>{if(0!==e.length){const[t,n]=e.split("=");Pn.set(`--${P(t,"-")}`,n),Pn.set(`-${P(t,"-")}`,n)}})):Pn=cn();return Pn})().has(e),Mn=e=>bn(Un?process.env[e.toUpperCase().replaceAll("-","_")]:kn.getItem(e)),Rn=e=>Ln("--"+e)||null!==Mn(e);Rn("production");var $n;Un&&($n=process.env.FORCE_COLOR,["true","1","2"].includes($n))||!Ln("--no-colors")&&!Rn("no-color")&&(!Un||process.stdout.isTTY)&&(!Un||Ln("--color")||null!==Mn("COLORTERM")||(Mn("TERM")||"").includes("color"));class Nn{constructor(e,t){this.left=e,this.right=t}}const Bn=(e,t)=>new Nn(e,t);"undefined"!=typeof DOMParser&&new DOMParser;const Fn=Symbol,Wn=Fn(),Hn=Fn(),Vn=Fn(),zn=Fn(),Kn=Fn(),Jn=Fn(),qn=Fn(),Yn=Fn(),Gn=Fn(),Qn=(Bn("font-weight","bold"),Bn("font-weight","normal"),Bn("color","blue"),Bn("color","green"),Bn("color","grey"),Bn("color","red"),Bn("color","purple"),Bn("color","orange"),Bn("color","black"),I()),Xn=e=>({[Symbol.iterator](){return this},next:e}),Zn=(e,t)=>Xn(()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}});class er{constructor(e,t){this.clock=e,this.len=t}}class tr{constructor(){this.clients=new Map}}const nr=(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])$r(e,s,o.clock,o.len,n)}}),rr=(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)},sr=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=w(r.len,s.clock+s.len-r.clock):(n<t&&(e[n]=s),n++)}e.length=n})},ir=(e,t,n,r)=>{dn(e.clients,t,()=>[]).push(new er(n,r))},or=(e,t)=>{H(e.restEncoder,t.clients.size),A(t.clients.entries()).sort((e,t)=>t[0]-e[0]).forEach(([t,n])=>{e.resetDsCurVal(),H(e.restEncoder,t);const r=n.length;H(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}})},lr=(e,t,n)=>{const r=new tr,s=ye(e.restDecoder);for(let i=0;i<s;i++){e.resetDsCurVal();const s=ye(e.restDecoder),i=ye(e.restDecoder),o=n.clients.get(s)||[],l=Tr(n,s);for(let n=0;n<i;n++){const n=e.readDsClock(),i=n+e.readDsLen();if(n<l){l<i&&ir(r,s,l,i-l);let e=Ur(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,bi(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,bi(t,c,i-c.id.clock)),c.delete(t))}else ir(r,s,n,i-n)}}if(r.clients.size>0){const e=new gr;return H(e.restEncoder,0),or(e,r),e.toUint8Array()}return null},cr=pn;class ar extends un{constructor({guid:e=yn(),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=cr(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new Dr,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=vn(e=>{this.on("load",()=>{this.isLoaded=!0,e(this)})});const l=()=>vn(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||Vr(e.parent.doc,e=>{e.subdocsLoaded.add(this)},null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(A(this.subdocs).map(e=>e.guid))}transact(e,t=null){return Vr(this,e,t)}get(e,t=as){const n=dn(this.share,e,()=>{const e=new t;return e._integrate(this,null),e}),r=n.constructor;if(t!==as&&r!==t){if(r===as){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,Is)}getText(e=""){return this.get(e,zs)}getMap(e=""){return this.get(e,Ds)}getXmlElement(e=""){return this.get(e,qs)}getXmlFragment(e=""){return this.get(e,Js)}toJSON(){const e={};return this.share.forEach((t,n)=>{e[n]=t.toJSON()}),e}destroy(){this.isDestroyed=!0,A(this.subdocs).forEach(e=>e.destroy());const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new ar({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Vr(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 dr{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=ye(this.restDecoder),this.dsCurrVal}readDsLen(){const e=ye(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ur extends dr{constructor(e){super(e),this.keys=[],ye(e),this.keyClockDecoder=new Ee(pe(e)),this.clientDecoder=new xe(pe(e)),this.leftClockDecoder=new Ee(pe(e)),this.rightClockDecoder=new Ee(pe(e)),this.infoDecoder=new Se(pe(e),ge),this.stringDecoder=new Ce(pe(e)),this.parentInfoDecoder=new Se(pe(e),ge),this.typeRefDecoder=new xe(pe(e)),this.lenDecoder=new xe(pe(e))}readLeftID(){return new xr(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new xr(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 ke(this.restDecoder)}readBuf(){return pe(this.restDecoder)}readJSON(){return ke(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 hr{constructor(){this.restEncoder=N()}toUint8Array(){return B(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){H(this.restEncoder,e)}writeDsLen(e){H(this.restEncoder,e)}}class fr extends hr{writeLeftID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeRightID(e){H(this.restEncoder,e.client),H(this.restEncoder,e.clock)}writeClient(e){H(this.restEncoder,e)}writeInfo(e){W(this.restEncoder,e)}writeString(e){J(this.restEncoder,e)}writeParentInfo(e){H(this.restEncoder,e?1:0)}writeTypeRef(e){H(this.restEncoder,e)}writeLen(e){H(this.restEncoder,e)}writeAny(e){Z(this.restEncoder,e)}writeBuf(e){Y(this.restEncoder,e)}writeJSON(e){J(this.restEncoder,JSON.stringify(e))}writeKey(e){J(this.restEncoder,e)}}class pr{constructor(){this.restEncoder=N(),this.dsCurrVal=0}toUint8Array(){return B(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,H(this.restEncoder,t)}writeDsLen(e){0===e&&ce(),H(this.restEncoder,e-1),this.dsCurrVal+=e}}class gr extends pr{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new se,this.clientEncoder=new ne,this.leftClockEncoder=new se,this.rightClockEncoder=new se,this.infoEncoder=new ee(W),this.stringEncoder=new ie,this.parentInfoEncoder=new ee(W),this.typeRefEncoder=new ne,this.lenEncoder=new ne}toUint8Array(){const e=N();return H(e,0),Y(e,this.keyClockEncoder.toUint8Array()),Y(e,this.clientEncoder.toUint8Array()),Y(e,this.leftClockEncoder.toUint8Array()),Y(e,this.rightClockEncoder.toUint8Array()),Y(e,B(this.infoEncoder)),Y(e,this.stringEncoder.toUint8Array()),Y(e,B(this.parentInfoEncoder)),Y(e,this.typeRefEncoder.toUint8Array()),Y(e,this.lenEncoder.toUint8Array()),q(e,B(this.restEncoder)),B(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){Z(this.restEncoder,e)}writeBuf(e){Y(this.restEncoder,e)}writeJSON(e){Z(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 yr=(e,t,n)=>{const r=new Map;n.forEach((e,n)=>{Tr(t,n)>e&&r.set(n,e)}),Ar(t).forEach((e,t)=>{n.has(t)||r.set(t,0)}),H(e.restEncoder,r.size),A(r.entries()).sort((e,t)=>t[0]-e[0]).forEach(([n,r])=>{((e,t,n,r)=>{r=w(r,t[0].id.clock);const s=Ur(t,r);H(e.restEncoder,t.length-s),e.writeClient(n),H(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)})},mr=(e,t,n,r=new ur(e))=>Vr(t,e=>{e.local=!1;let t=!1;const n=e.doc,s=n.store,i=((e,t)=>{const n=cn(),r=ye(e.restDecoder);for(let s=0;s<r;s++){const r=ye(e.restDecoder),s=new Array(r),i=e.readClient();let o=ye(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 Zs(Cr(i,o),t),o+=t;break}case 10:{const t=ye(e.restDecoder);s[n]=new Si(Cr(i,o),t),o+=t;break}default:{const l=!(192&r),c=new wi(Cr(i,o),null,(r&S)===S?e.readLeftID():null,null,(r&k)===k?e.readRightID():null,l?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,!l||32&~r?null:e.readString(),_i(e,r));s[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let s=A(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 Dr,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!==Si){const s=dn(u,d.id.client,()=>Tr(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,Tr(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 gr;return yr(e,l,new Map),H(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<Tr(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=Yr([l.update,o.update])}}else s.pendingStructs=o;const c=lr(r,e,s);if(s.pendingDs){const t=new ur(he(s.pendingDs));ye(t.restDecoder);const n=lr(t,e,s);s.pendingDs=c&&n?Yr([c,n]):c||n}else s.pendingDs=c;if(t){const t=s.pendingStructs.update;s.pendingStructs=null,vr(e.doc,t)}},n,!1),vr=(e,t,n,r=ur)=>{const s=he(t);mr(s,e,n,new r(s))};class br{constructor(){this.l=[]}}const wr=()=>new br,_r=(e,t)=>e.l.push(t),kr=(e,t)=>{const n=e.l;n.length;e.l=n.filter(e=>t!==e),e.l.length},Sr=(e,t,n)=>Tn(e.l,[t,n]);class xr{constructor(e,t){this.client=e,this.clock=t}}const Er=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Cr=(e,t)=>new xr(e,t),Ir=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!rr(t.ds,e.id),Or=(e,t)=>{const n=dn(e.meta,Or,I),r=e.doc.store;n.has(t)||(t.sv.forEach((t,n)=>{t<Tr(r,n)&&Mr(e,Cr(n,t))}),nr(e,t.ds,e=>{}),n.add(t))};class Dr{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const Ar=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},Tr=(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},jr=(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 ce()}n.push(t)},Ur=(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 ce()},Pr=(e,t)=>{const n=e.clients.get(t.client);return n[Ur(n,t.clock)]},Lr=(e,t,n)=>{const r=Ur(t,n),s=t[r];return s.id.clock<n&&s instanceof wi?(t.splice(r+1,0,bi(e,s,n-s.id.clock)),r+1):r},Mr=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[Lr(e,n,t.clock)]},Rr=(e,t,n)=>{const r=t.clients.get(n.client),s=Ur(r,n.clock),i=r[s];return n.clock!==i.id.clock+i.length-1&&i.constructor!==Zs&&r.splice(s+1,0,bi(e,i,n.clock-i.id.clock+1)),i},$r=(e,t,n,r,s)=>{if(0===r)return;const i=n+r;let o,l=Lr(e,t,n);do{o=t[l++],i<o.id.clock+o.length&&Lr(e,t,i),s(o)}while(l<t.length&&t[l].id.clock<i)};class Nr{constructor(e,t,n){this.doc=e,this.deleteSet=new tr,this.beforeState=Ar(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 Br=(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))&&(sr(t.deleteSet),((e,t)=>{yr(e,t.doc.store,t.beforeState)})(e,t),or(e,t.deleteSet),!0),Fr=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&dn(e.changed,t,I).add(n)},Wr=(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 wi&&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},Hr=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,s=r.store,i=n.deleteSet,o=n._mergeStructs;try{sr(i),n.afterState=Ar(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),Sr(t._dEH,e,n))})}),e.push(()=>r.emit("afterTransaction",[n,r])),Tn(e,[]),n._needFormattingCleanup&&Ws(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=Ur(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 wi&&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=b(r.length-1,1+Ur(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Wr(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=w(Ur(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Wr(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=Ur(r,n);i+1<r.length&&Wr(r,i+1)>1||i>0&&Wr(r,i)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(((...e)=>{Qn.forEach(t=>t.print(e))})(Yn,Wn,"[yjs] ",Hn,Jn,"Changed the client-id because another client seems to be using it."),r.clientID=cr()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new fr;Br(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new gr;Br(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])):Hr(e,t+1)}}},Vr=(e,t,n=null,r=!0)=>{const s=e._transactionCleanups;let i=!1,o=null;null===e._transaction&&(i=!0,e._transaction=new Nr(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&&Hr(s,0)}}return o};class zr{constructor(e,t){this.gen=function*(e){const t=ye(e.restDecoder);for(let n=0;n<t;n++){const t=ye(e.restDecoder),n=e.readClient();let r=ye(e.restDecoder);for(let s=0;s<t;s++){const t=e.readInfo();if(10===t){const t=ye(e.restDecoder);yield new Si(Cr(n,r),t),r+=t}else if(31&t){const s=!(192&t),i=new wi(Cr(n,r),null,(t&S)===S?e.readLeftID():null,null,(t&k)===k?e.readRightID():null,s?e.readParentInfo()?e.readString():e.readLeftID():null,!s||32&~t?null:e.readString(),_i(e,t));yield i,r+=i.length}else{const t=e.readLen();yield new Zs(Cr(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===Si);return this.curr}}class Kr{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Jr=(e,t=pr,n=ur)=>{const r=new t,s=new zr(new n(he(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++,H(r.restEncoder,t),H(r.restEncoder,o)),t=i.id.client,o=0,n=0!==i.id.clock),i.constructor===Si&&(n=!0),n||(o=i.id.clock+i.length);0!==o&&(e++,H(r.restEncoder,t),H(r.restEncoder,o));const l=N();return H(l,e),((e,t)=>{q(e,B(t))})(l,r.restEncoder),r.restEncoder=l,r.toUint8Array()}return H(r.restEncoder,0),r.toUint8Array()},qr=(e,t)=>{if(e.constructor===Zs){const{client:n,clock:r}=e.id;return new Zs(Cr(n,r+t),e.length-t)}if(e.constructor===Si){const{client:n,clock:r}=e.id;return new Si(Cr(n,r+t),e.length-t)}{const n=e,{client:r,clock:s}=n.id;return new wi(Cr(r,s+t),null,Cr(r,s+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Yr=(e,t=ur,n=gr)=>{if(1===e.length)return e[0];const r=e.map(e=>new t(he(e)));let s=r.map(e=>new zr(e,!0)),i=null;const o=new n,l=new Kr(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===Si?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)Qr(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===Si)i.struct.length=n.id.clock+n.length-i.struct.id.clock;else{Qr(l,i.struct,i.offset);const e=n.id.clock-i.struct.id.clock-i.struct.length;i={struct:new Si(Cr(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===Si?i.struct.length-=t:n=qr(n,t)),i.struct.mergeWith(n)||(Qr(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!==Si;n=e.next())Qr(l,i.struct,i.offset),i={struct:n,offset:0}}null!==i&&(Qr(l,i.struct,i.offset),i=null),Xr(l);const c=r.map(e=>(e=>{const t=new tr,n=ye(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=ye(e.restDecoder),r=ye(e.restDecoder);if(r>0){const s=dn(t.clients,n,()=>[]);for(let t=0;t<r;t++)s.push(new er(e.readDsClock(),e.readDsLen()))}}return t})(e)),a=(e=>{const t=new tr;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++)D(i,e[t].clients.get(s)||[]);t.clients.set(s,i)}});return sr(t),t})(c);return or(o,a),o.toUint8Array()},Gr=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:B(e.encoder.restEncoder)}),e.encoder.restEncoder=N(),e.written=0)},Qr=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&Gr(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),H(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},Xr=e=>{Gr(e);const t=e.encoder.restEncoder;H(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];H(t,r.written),q(t,r.restEncoder)}},Zr="You must not compute changes after the event-handler fired.";class es{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=ts(this.currentTarget,this.target))}deletes(e){return rr(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw oe(Zr);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=O(e.content.getContent())}else null!==e&&this.deletes(e)?(s="update",i=O(e.content.getContent())):(s="add",i=void 0)}else{if(!this.deletes(r))return;s="delete",i=O(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 oe(Zr);const t=this.target,n=I(),r=I(),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 ts=(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},ns=()=>{((...e)=>{e.unshift(Yn),Qn.forEach(t=>t.print(e))})("Invalid access: Add Yjs type to a document before reading data.")};let rs=0;class ss{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=rs++}}const is=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=rs++},os=(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)=>v(t-e.index)<v(t-n.index)?e:n);let r=e._start,s=0;for(null!==n&&(r=n.p,s=n.index,(e=>{e.timestamp=rs++})(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&&v(n.index-s)<r.parent.length/80?(is(n,r,s),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce((e,t)=>e.timestamp<t.timestamp?e:t);return is(r,t,n),r}{const r=new ss(t,n);return e.push(r),r}})(e._searchMarker,r,s)},ls=(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=w(t,s.index+n))}},cs=(e,t,n)=>{const r=e,s=t.changedParentTypes;for(;dn(s,e,()=>[]).push(n),null!==e._item;)e=e._item.parent;Sr(r._eH,n,t)};class as{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=wr(),this._dEH=wr(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw le()}clone(){throw le()}_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){_r(this._eH,e)}observeDeep(e){_r(this._dEH,e)}unobserve(e){kr(this._eH,e)}unobserveDeep(e){kr(this._dEH,e)}toJSON(){}}const ds=(e,t,n)=>{e.doc??ns(),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},us=e=>{e.doc??ns();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},hs=(e,t)=>{let n=0,r=e._start;for(e.doc??ns();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}},fs=(e,t)=>{const n=[];return hs(e,(r,s)=>{n.push(t(r,s,e))}),n},ps=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}}}},gs=(e,t)=>{e.doc??ns();const n=os(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}},ys=(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 wi(Cr(o,Tr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new ci(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 wi(Cr(o,Tr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new ei(new Uint8Array(n))),s.integrate(e,0);break;case ar:s=new wi(Cr(o,Tr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new ri(n)),s.integrate(e,0);break;default:if(!(n instanceof as))throw new Error("Unexpected content type in insert operation");s=new wi(Cr(o,Tr(l,o)),s,s&&s.lastId,c,c&&c.id,t,null,new vi(n)),s.integrate(e,0)}}}),d()},ms=()=>oe("Length exceeded!"),vs=(e,t,n,r)=>{if(n>t._length)throw ms();if(0===n)return t._searchMarker&&ls(t._searchMarker,n,r.length),ys(e,t,null,r);const s=n,i=os(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&&Mr(e,Cr(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ls(t._searchMarker,s,r.length),ys(e,t,o,r)},bs=(e,t,n,r)=>{if(0===r)return;const s=n,i=r,o=os(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&&Mr(e,Cr(l.id.client,l.id.clock+n)),n-=l.length);for(;r>0&&null!==l;)l.deleted||(r<l.length&&Mr(e,Cr(l.id.client,l.id.clock+r)),l.delete(e),r-=l.length),l=l.right;if(r>0)throw ms();t._searchMarker&&ls(t._searchMarker,s,-i+r)},ws=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},_s=(e,t,n,r)=>{const s=t._map.get(n)||null,i=e.doc,o=i.clientID;let l;if(null==r)l=new ci([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:case Date:case BigInt:l=new ci([r]);break;case Uint8Array:l=new ei(r);break;case ar:l=new ri(r);break;default:if(!(r instanceof as))throw new Error("Unexpected content type");l=new vi(r)}new wi(Cr(o,Tr(i.store,o)),s,s&&s.lastId,null,null,t,n,l).integrate(e,0)},ks=(e,t)=>{e.doc??ns();const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},Ss=e=>{const t={};return e.doc??ns(),e._map.forEach((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])}),t},xs=(e,t)=>{e.doc??ns();const n=e._map.get(t);return void 0!==n&&!n.deleted},Es=e=>{return e.doc??ns(),t=e._map.entries(),n=e=>!e[1].deleted,Xn(()=>{let e;do{e=t.next()}while(!e.done&&!n(e.value));return e});var t,n};class Cs extends es{}class Is extends as{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Is;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Is}clone(){const e=new Is;return e.insert(0,this.toArray().map(e=>e instanceof as?e.clone():e)),e}get length(){return this.doc??ns(),this._length}_callObserver(e,t){super._callObserver(e,t),cs(this,e,new Cs(this,e))}insert(e,t){null!==this.doc?Vr(this.doc,n=>{vs(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Vr(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;ys(e,t,r,n)})(t,this,e)}):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Vr(this.doc,n=>{bs(n,this,e,t)}):this._prelimContent.splice(e,t)}get(e){return gs(this,e)}toArray(){return us(this)}slice(e=0,t=this.length){return ds(this,e,t)}toJSON(){return this.map(e=>e instanceof as?e.toJSON():e)}map(e){return fs(this,e)}forEach(e){hs(this,e)}[Symbol.iterator](){return ps(this)}_write(e){e.writeTypeRef(ui)}}class Os extends es{constructor(e,t,n){super(e,t),this.keysChanged=n}}class Ds extends as{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 Ds}clone(){const e=new Ds;return this.forEach((t,n)=>{e.set(n,t instanceof as?t.clone():t)}),e}_callObserver(e,t){cs(this,e,new Os(this,e,t))}toJSON(){this.doc??ns();const e={};return this._map.forEach((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof as?r.toJSON():r}}),e}get size(){return[...Es(this)].length}keys(){return Zn(Es(this),e=>e[0])}values(){return Zn(Es(this),e=>e[1].content.getContent()[e[1].length-1])}entries(){return Zn(Es(this),e=>[e[0],e[1].content.getContent()[e[1].length-1]])}forEach(e){this.doc??ns(),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?Vr(this.doc,t=>{ws(t,this,e)}):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Vr(this.doc,n=>{_s(n,this,e,t)}):this._prelimContent.set(e,t),t}get(e){return ks(this,e)}has(e){return xs(this,e)}clear(){null!==this.doc?Vr(this.doc,e=>{this.forEach(function(t,n,r){ws(e,r,n)})}):this._prelimContent.clear()}_write(e){e.writeTypeRef(hi)}}const As=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||Cn(e)===Cn(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,(e,n)=>(void 0!==e||In(t,n))&&t[n]===e))(e,t);class Ts{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){if(null===this.right&&ce(),this.right.content.constructor===ii)this.right.deleted||Ls(this.currentAttributes,this.right.content);else this.right.deleted||(this.index+=this.right.length);this.left=this.right,this.right=this.right.right}}const js=(e,t,n)=>{for(;null!==t.right&&n>0;){if(t.right.content.constructor===ii)t.right.deleted||Ls(t.currentAttributes,t.right.content);else t.right.deleted||(n<t.right.length&&Mr(e,Cr(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},Us=(e,t,n,r)=>{const s=new Map,i=r?os(t,n):null;if(i){const t=new Ts(i.p.left,i.p,i.index,s);return js(e,t,n-i.index)}{const r=new Ts(null,t._start,0,s);return js(e,r,n)}},Ps=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===ii&&As(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 wi(Cr(i,Tr(s.store,i)),l,l&&l.lastId,c,c&&c.id,t,null,new ii(o,r));a.integrate(e,0),n.right=a,n.forward()})},Ls=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Ms=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===ii&&As(t[e.right.content.key]??null,e.right.content.value));)e.forward()},Rs=(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(!As(a,c)){o.set(l,a);const{left:r,right:d}=n;n.right=new wi(Cr(i,Tr(s.store,i)),r,r&&r.lastId,d,d&&d.id,t,null,new ii(l,c)),n.right.integrate(e,0),n.forward()}}return o},$s=(e,t,n,r,s)=>{n.currentAttributes.forEach((e,t)=>{void 0===s[t]&&(s[t]=null)});const i=e.doc,o=i.clientID;Ms(n,s);const l=Rs(e,t,n,s),c=r.constructor===String?new ai(r):r instanceof as?new vi(r):new si(r);let{left:a,right:d,index:u}=n;t._searchMarker&&ls(t._searchMarker,n.index,c.getLength()),d=new wi(Cr(o,Tr(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(),Ps(e,t,n,l)},Ns=(e,t,n,r,s)=>{const i=e.doc,o=i.clientID;Ms(n,s);const l=Rs(e,t,n,s);e:for(;null!==n.right&&(r>0||l.size>0&&(n.right.deleted||n.right.content.constructor===ii));){if(!n.right.deleted)switch(n.right.content.constructor){case ii:{const{key:t,value:i}=n.right.content,o=s[t];if(void 0!==o){if(As(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&&Mr(e,Cr(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 wi(Cr(o,Tr(i.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new ai(s)),n.right.integrate(e,0),n.forward()}Ps(e,t,n,l)},Bs=(e,t,n,r,s)=>{let i=t;const o=cn();for(;i&&(!i.countable||i.deleted);){if(!i.deleted&&i.content.constructor===ii){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 ii:{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||Ls(s,n);break}}}t=t.right}return l},Fs=e=>{let t=0;return Vr(e.doc,n=>{let r=e._start,s=e._start,i=cn();const o=an(i);for(;s;){if(!1===s.deleted)if(s.content.constructor===ii)Ls(o,s.content);else t+=Bs(n,r,s,i,o),i=an(o),r=s;s=s.right}}),t},Ws=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&&$r(e,n.store.clients.get(r),i,s,e=>{e.deleted||e.content.constructor!==ii||e.constructor===Zs||t.add(e.parent)})}Vr(n,n=>{nr(e,e.deleteSet,e=>{if(e instanceof Zs||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===ii?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===ii){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)});for(const e of t)Fs(e)})},Hs=(e,t,n)=>{const r=n,s=an(t.currentAttributes),i=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case vi:case si:case ai:n<t.right.length&&Mr(e,Cr(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}i&&Bs(e,i,t.right,s,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&ls(o._searchMarker,t.index,-r+n),t};class Vs extends es{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=[];Vr(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=Sn({},o))),c=0}e&&t.push(e),i=null}};for(;null!==s;){switch(s.content.constructor){case vi:case si: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 ai: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 ii:{const{key:t,value:l}=s.content;if(this.adds(s)){if(!this.deletes(s)){const c=n.get(t)??null;As(c,l)?null!==l&&s.delete(e):("retain"===i&&d(),As(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;As(e,l)||("retain"===i&&d(),o[t]=e)}else if(!s.deleted){r.set(t,l);const n=o[t];void 0!==n&&(As(n,l)?null!==n&&s.delete(e):("retain"===i&&d(),null===l?delete o[t]:o[t]=l))}s.deleted||("insert"===i&&d(),Ls(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 zs extends as{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this.doc??ns(),this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach(e=>e())}catch(e){}this._pending=null}_copy(){return new zs}clone(){const e=new zs;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new Vs(this,e,t);cs(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){this.doc??ns();let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===ai&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Vr(this.doc,n=>{const r=new Ts(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)&&$s(n,this,r,o,i.attributes||{})}else void 0!==i.retain?Ns(n,this,r,i.retain,i.attributes||{}):void 0!==i.delete&&Hs(n,r,i.delete)}}):this._pending.push(()=>this.applyDelta(e))}toDelta(e,t,n){this.doc??ns();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(Ir(l,e)||void 0!==t&&Ir(l,t))switch(l.content.constructor){case ai:{const r=s.get("ychange");void 0===e||Ir(l,e)?void 0===t||Ir(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 vi:case si:{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 ii:Ir(l,e)&&(c(),Ls(s,l.content))}l=l.right}c()};return e||t?Vr(i,n=>{e&&Or(n,e),t&&Or(n,t),a()},"cleanup"):a(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Vr(r,r=>{const s=Us(r,this,e,!n);n||(n={},s.currentAttributes.forEach((e,t)=>{n[t]=e})),$s(r,this,s,t,n)}):this._pending.push(()=>this.insert(e,t,n))}insertEmbed(e,t,n){const r=this.doc;null!==r?Vr(r,r=>{const s=Us(r,this,e,!n);$s(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?Vr(n,n=>{Hs(n,Us(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?Vr(r,r=>{const s=Us(r,this,e,!1);null!==s.right&&Ns(r,this,s,t,n)}):this._pending.push(()=>this.format(e,t,n))}removeAttribute(e){null!==this.doc?Vr(this.doc,t=>{ws(t,this,e)}):this._pending.push(()=>this.removeAttribute(e))}setAttribute(e,t){null!==this.doc?Vr(this.doc,n=>{_s(n,this,e,t)}):this._pending.push(()=>this.setAttribute(e,t))}getAttribute(e){return ks(this,e)}getAttributes(){return Ss(this)}_write(e){e.writeTypeRef(fi)}}class Ks{constructor(e,t=()=>!0){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0,e.doc??ns()}[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!==qs&&t.constructor!==Js||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 Js extends as{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 Js}clone(){const e=new Js;return e.insert(0,this.toArray().map(e=>e instanceof as?e.clone():e)),e}get length(){return this.doc??ns(),null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new Ks(this,e)}querySelector(e){e=e.toUpperCase();const t=new Ks(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),A(new Ks(this,t=>t.nodeName&&t.nodeName.toUpperCase()===e))}_callObserver(e,t){cs(this,e,new Ys(this,t,e))}toString(){return fs(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),hs(this,s=>{r.insertBefore(s.toDOM(e,t,n),null)}),r}insert(e,t){null!==this.doc?Vr(this.doc,n=>{vs(n,this,e,t)}):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Vr(this.doc,n=>{const r=e&&e instanceof as?e._item:e;ys(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 oe("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Vr(this.doc,n=>{bs(n,this,e,t)}):this._prelimContent.splice(e,t)}toArray(){return us(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return gs(this,e)}slice(e=0,t=this.length){return ds(this,e,t)}forEach(e){hs(this,e)}_write(e){e.writeTypeRef(gi)}}class qs extends Js{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 qs(this.nodeName)}clone(){const e=new qs(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 as?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?Vr(this.doc,t=>{ws(t,this,e)}):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Vr(this.doc,n=>{_s(n,this,e,t)}):this._prelimAttrs.set(e,t)}getAttribute(e){return ks(this,e)}hasAttribute(e){return xs(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&&Ir(s,t)&&(n[r]=s.content.getContent()[s.length-1])}),n})(this,e):Ss(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 hs(this,s=>{r.appendChild(s.toDOM(e,t,n))}),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(pi),e.writeKey(this.nodeName)}}class Ys extends es{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 Gs extends Ds{constructor(e){super(),this.hookName=e}_copy(){return new Gs(this.hookName)}clone(){const e=new Gs(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(yi),e.writeKey(this.hookName)}}class Qs extends zs{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 Qs}clone(){const e=new Qs;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(mi)}}class Xs{constructor(e,t){this.id=e,this.length=t}get deleted(){throw le()}mergeWith(e){return!1}write(e,t,n){throw le()}integrate(e,t){throw le()}}class Zs extends Xs{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),jr(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class ei{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new ei(this.content)}splice(e){throw le()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class ti{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new ti(this.len)}splice(e){const t=new ti(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){ir(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 ni=(e,t)=>new ar({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class ri{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 ri(ni(this.doc.guid,this.opts))}splice(e){throw le()}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 si{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new si(this.embed)}splice(e){throw le()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class ii{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new ii(this.key,this.value)}splice(e){throw le()}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 oi{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new oi(this.arr)}splice(e){const t=new oi(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 li="development"===Mn("node_env");class ci{constructor(e){this.arr=e,li&&Dn(e)}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new ci(this.arr)}splice(e){const t=new ci(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 ai{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new ai(this.str)}splice(e){const t=new ai(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 di=[e=>new Is,e=>new Ds,e=>new zs,e=>new qs(e.readKey()),e=>new Js,e=>new Gs(e.readKey()),e=>new Qs],ui=0,hi=1,fi=2,pi=3,gi=4,yi=5,mi=6;class vi{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new vi(this.type._copy())}splice(e){throw le()}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 bi=(e,t,n)=>{const{client:r,clock:s}=t.id,i=new wi(Cr(r,s+n),t,Cr(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=Cr(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 wi extends Xs{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>=Tr(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=Tr(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===xr&&this.id.client!==this.parent.client&&this.parent.clock>=Tr(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=Rr(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Mr(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===Zs||this.right&&this.right.constructor===Zs)this.parent=null;else if(this.parent){if(this.parent.constructor===xr){const e=Pr(t,this.parent);e.constructor===Zs?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===wi?(this.parent=this.left.parent,this.parentSub=this.left.parentSub):this.right&&this.right.constructor===wi&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=Rr(e,e.doc.store,Cr(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),Er(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(Er(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!s.has(Pr(e.doc.store,t.origin)))break;r.has(Pr(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),jr(e.doc.store,this),this.content.integrate(e,this),Fr(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new Zs(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:Cr(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&Er(e.origin,this.lastId)&&this.right===e&&Er(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(),ir(e.deleteSet,this.id.client,this.id.clock,this.length),Fr(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw ce();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[Ur(r,t.id.clock)]=n})(e,this,new Zs(this.id,this.length)):this.content=new ti(this.length)}write(e,t){const n=t>0?Cr(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,s=this.parentSub,i=31&this.content.getRef()|(null===n?0:S)|(null===r?0:k)|(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 ce()})(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===xr?(e.writeParentInfo(!1),e.writeLeftID(t)):ce();null!==s&&e.writeString(s)}this.content.write(e,t)}}const _i=(e,t)=>ki[31&t](e),ki=[()=>{ce()},e=>new ti(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 oi(n)},e=>new ei(e.readBuf()),e=>new ai(e.readString()),e=>new si(e.readJSON()),e=>new ii(e.readKey(),e.readJSON()),e=>new vi(di[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new ci(n)},e=>new ri(ni(e.readString(),e.readAny())),()=>{ce()}];class Si extends Xs{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){ce()}write(e,t){e.writeInfo(10),H(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const xi="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},Ei="__ $YJS$ __";function Ci(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}xi[Ei],xi[Ei]=!0;const Ii=new FinalizationRegistry(({cache:e,key:t})=>{delete e[t]});function Oi(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=Ti(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=Ti(n,r,s),o=null===(t=this.cache[i])||void 0===t?void 0:t.deref();o&&Ii.unregister(o),this.cache[i]=new WeakRef(e),Ii.register(e,{cache:this.cache,key:i},e)},delete(e){Ii.unregister(e);const t=Ti(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 Di=new WeakSet;function Ai(e){if(Di.has(e))throw new Error(`Y.Doc ${e.meta.parentId} has been destroyed`)}function Ti(e,t,n){return`${e}[${t}].${n}`}const{getByKeyPath:ji}=t.Dexie;let Ui=null;function Pi(e){Ui=e}function Li(){}const Mi=new WeakMap;function Ri(){return t.Dexie.Events(null,"load","sync","error")}class $i{static getOrCreateDocument(e,t,n,r){var s,i;const o=Oi(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 ar({meta:{db:e,updatesTable:s,parentProp:r,parentTable:n,parentId:i}}),t.add(o),o.on("destroy",()=>{Di.add(o),t.delete(o)}),o)}(e,o,t,n,l,r)}static load(e,t){var n;let r=Mi.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 $i(e),r.graceTimeout=null!==(n=null==t?void 0:t.gracePeriod)&&void 0!==n?n:-1,Mi.set(e,r)),r}static release(e){if(!e||Di.has(e))return;const t=Mi.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($i.on("beforeunload").fire(this)).finally(()=>{var e;0===this.refCount&&(null===(e=this.doc)||void 0===e||e.destroy())})}static for(e){return Mi.get(e)}static get currentUpdateRow(){return Ui}get whenLoaded(){return this._whenLoaded||(this._whenLoaded=new Promise((e,n)=>{this.doc?this.doc.isLoaded?e():this._error?n(this._error):Di.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before loaded")):(this.on("load",e),this.on("error",n),this.doc.on("destroy",()=>n(new t.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((e,n)=>{this.doc?this.doc.isSynced?e():this._error?n(this._error):Di.has(this.doc)?n(new t.Dexie.AbortError("Document was destroyed before synced")):(this.on("sync",e),this.on("error",n),this.doc.on("destroy",()=>n(new t.Dexie.AbortError("Document was destroyed before synced")))):n(new Error("No Y.Doc associated with this provider"))})),this._whenSynced}constructor(e){this.refCount=1,this.cleanupHandlers=[],this.graceTimeout=-1,this.doc=null,this.destroyed=!1,this.on=Ri(),this.doc=e,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]=()=>$i.release(e)),e.on("load",()=>this.on("load").fire()),e.on("sync",e=>!1!==e&&this.on("sync").fire()),e.on("destroy",this.destroy.bind(this)),this.on("error",e=>{this._error=e});const{db:n,parentTable:r,parentId:s,updatesTable:i}=e.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`);Ai(e),this.stopObserving=function(e,n,r,s,i,o){let l=0,c=!0;const a=t.liveQuery(()=>{Ai(n);const e=r.table(i);return Promise.all([(l>0?e.where("i").between(l,1/0,!1).toArray().then(e=>e.filter(e=>0===t.cmp(e.k,o))):e.where({k:o}).toArray()).then(e=>e),r.table(s).where(":id").equals(o).toArray()])}).subscribe(([t,r])=>{t.length>0&&(l=t[t.length-1].i),0!==r.length?(Ai(n),t.length>0&&Vr(n,()=>{t.forEach(e=>{try{Pi(e),vr(n,e.u)}finally{Pi(null)}})},e,!1),c&&(c=!1,n.emit("load",[n]))):n.destroy()},t=>{e.on("error").fire(t)}),d=(t,n)=>{n!==e&&r.table(i).add({k:o,u:t,f:1}).then(e=>{e===l-1&&++l}).catch(t=>{e.on("error").fire(t)})},u=()=>{a.unsubscribe(),n.off("updateV2",d),n.off("destroy",u)};return n.on("updateV2",d),n.on("destroy",u),u}(this,e,n,r,i,s),$i.on("new").fire(this)}destroy(){var e;Mi.delete(this.doc),this.doc=null,this.destroyed=!0,this.refCount=0,null===(e=this.stopObserving)||void 0===e||e.call(this),this.on=Ri(),this.cleanupHandlers.forEach(e=>e())}addCleanupHandler(e){this.cleanupHandlers.push("function"==typeof e?e:()=>e.unsubscribe())}}function Ni(e,n){return s(this,void 0,void 0,function*(){var r;const i={};let o,l=!1;for(const c of e)try{switch(c.type){case"u-s":{const e=Ci(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=Ci(n,c.table,c.prop);e&&(yield n.transaction("rw",e,t=>s(this,void 0,void 0,function*(){let n=yield t.table(e.name).get(on);yield t.table(e.name).put(Object.assign(Object.assign({},n||{i:on}),{unsentFrom:Math.max((null==n?void 0:n.unsentFrom)||1,c.i+1)}))})));break}case"u-reject":{const e=Ci(n,c.table,c.prop);if(!e)break;const s=null===(r=yield e.get(c.i))||void 0===r?void 0:r.k;if(null!=s){yield n.transaction("rw",e,n=>(n.idbtrans._rejecting_y_ypdate=!0,e.where("i").aboveOrEqual(c.i).filter(e=>0===t.cmp(e.k,s)&&!(1&~(e.f||0))).delete()));const r=$i.getDocCache(n.dx).find(c.table,s,c.prop);r&&r.destroy()}break}case"in-sync":{const e=$i.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}})}$i.on=t.Dexie.Events(null,{new:[function(e,t){return e===Li?t:function(){e.apply(this,arguments),t.apply(this,arguments)}}],beforeunload:[function(e,t){return e===Li?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)}}]}),$i.getDocCache=Oi,t.Dexie.DexieYProvider?$i=t.Dexie.DexieYProvider||$i:t.Dexie.DexieYProvider=$i;function Bi(e,n,r){return s(this,arguments,void 0,function*(e,n,{yDownloadedRealms:r,realms:i}){if(r&&i&&i.every(e=>"*"===r[e]))return;const a=yield Be(e),d={"Content-Type":"application/json",Accept:"application/octet-stream"};a&&(d.Authorization=`Bearer ${a.accessToken}`);const u=yield fetch(`${n}/y/download`,{body:Kt.stringify({downloadedRealms:r||{}}),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),Ie,function(r){return l(this,arguments,function*(){var i,l,a,d;let u=null,h=null,f=null,p=[];function g(t){return s(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 t=Ci(e,h,f);t&&(yield t.bulkAdd(p)),p=[]}u&&(h&&f&&r||t)&&(yield e.$syncState.update("syncState",e=>{const n=e.yDownloadedRealms||{};n[u]=t?"*":{tbl:h,prop:f,key:r.k},e.yDownloadedRealms=n}))})}try{try{for(var y,m=!0,v=c(r);!(i=(y=yield o(v.next())).done);m=!0){d=y.value,m=!1;const e=new ue(d);for(;fe(e);)switch(ge(e)){case 1:yield o(g(!0)),u=ve(e);break;case 2:yield o(g(!1)),h=ve(e),f=ve(e);break;case 3:{const t=ke(e),n=pe(e);p.push({k:t,u:n});break}}yield o(g(!1))}}catch(e){l={error:e}}finally{try{m||i||!(a=v.return)||(yield o(a.call(v)))}finally{if(l)throw l.error}}yield o(g(!0))}catch(e){throw e instanceof t.DexieError||(yield o(g(!1))),e}})})})}const Fi="currentSyncWorker";function Wi(e,t,n,r){return Hi(e,t,n,r).then(t=>((null==r?void 0:r.justCheckIfNeeded)||e.syncStateChangedEvent.next({phase:"in-sync"}),t)).catch(i=>s(this,void 0,void 0,function*(){return(null==r?void 0:r.justCheckIfNeeded)?Promise.reject(i):en&&(null==r?void 0:r.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 Wi(e,t,n,Object.assign(Object.assign({},r),{retryImmediatelyOnFetchError:!1}))):(yield e.$syncState.update("syncState",{timestamp:new Date,error:""+i}),e.syncStateChangedEvent.next({phase:en?"error":"offline",error:new Error(""+(null==i?void 0:i.message)||i)}),Promise.reject(i))}))}function Hi(e,t,n){return s(this,arguments,void 0,function*(e,t,n,{isInitialSync:r,cancelToken:i,justCheckIfNeeded:o,purpose:l}={isInitialSync:!1}){var c;if(!(null===(c=e.cloud.options)||void 0===c?void 0:c.databaseUrl))throw new Error("Internal error: sync must not be called when no databaseUrl is configured");const{databaseUrl:a}=t,d=yield e.getCurrentUser(),h=d.isLoggedIn?ut(e):[],p=h.map(t=>e.table(ht(t.name))),g=yield e.getPersistedSyncState(),y=d.isLoggedIn,m=y?function(e,t){const n=(null==t?void 0:t.syncedTables)||[];return ut(e).filter(e=>!n.includes(e.name))}(e,g):[];Zt(i);const v=m.length>0;if(v){if(o)return!0;yield e.transaction("rw",m,e=>s(this,void 0,void 0,function*(){e.idbtrans.disableChangeTracking=!0,e.idbtrans.disableAccessControl=!0,yield function(e,t,n){return s(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!==ze.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!==ze.userId||(e.owner=t.userId)}):yield n.toCollection().modify(e=>{e.realmId&&r.has(e.realmId)||(e.owner&&e.owner!==ze.userId||(e.owner=t.userId),e.realmId&&e.realmId!==ze.userId||(e.realmId=t.userId))}))})}(m,d,null==g?void 0:g.realms)})),Zt(i)}const[b,w,_,{yMessages:k,lastUpdateIds:S}]=yield e.transaction("r",e.tables,()=>s(this,void 0,void 0,function*(){const t=yield e.getPersistedSyncState();let r=yield e.$baseRevs.toArray();r=r.filter(e=>h.some(t=>t.name===e.tableName));let o=yield yt(p,e);const l=yield function(e,t){return s(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(on),l=(null==o?void 0:o.unsentFrom)||1,c=(null==o?void 0:o.receivedUntil)||0,a=Math.min(l,c+1),d=yield ln(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]:Yr(i);if(r)n.push({type:"u-c",table:s.name,prop:t.prop,k:e,u:l,i:o});else{const r=Jr(l);n.push({type:"sv",table:s.name,prop:t.prop,k:e,sv:r})}}}return{yMessages:n,lastUpdateIds:r}})}(e,h);if(Zt(i),v){const e=[...(null==g?void 0:g.realms)||[],...(null==g?void 0:g.inviteRealms)||[]],c=yield function(e,t,n,r){return s(this,void 0,void 0,function*(){const i=`upload-${mt(8)}`;if(t.isLoggedIn&&e.length>0){const o=new Set(r||[]);return(yield Promise.all(e.map(e=>s(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||"")&&f(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[]})}(m,d,n,e);return Zt(i),o=o.concat(c),[o,t,r,l]}return[o,t,r,l]})),x=b.some(e=>e.muts.some(e=>e.keys.length>0))||k.some(e=>"u-c"===e.type);if(o)return x;if("push"===l&&!x)return!1;const E=nn(b,null==w?void 0:w.latestRevisions),C=(null==w?void 0:w.clientIdentity)||u(16);Zt(i);const I=yield Xt(b,k,w,_,e,a,n,C,d),{done:O,newSyncState:D}=yield e.transaction("rw",e.tables,t=>s(this,void 0,void 0,function*(){t.idbtrans.disableChangeTracking=!0,t.idbtrans.disableAccessControl=!0;for(const e of Object.keys(n))I.schema[e]&&(n[e]=I.schema[e]);yield e.$syncState.put(n,"schema");const r=yield yt(p,e,{since:E});for(const t of p){const n=ft(t.name);if(r.some(e=>e.table===n&&e.muts.length>0)){if(E[n]){const r=E[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()])}nn(r,E),yield tn(e,n,E,I.serverRevision);const i=yield e.getPersistedSyncState();yield function(e,t,n){return s(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=ut(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,I,i);const o=i||{syncedTables:[],latestRevisions:{},realms:[],inviteRealms:[],clientIdentity:C};y&&(o.syncedTables=h.map(e=>e.name).concat(m.map(e=>e.name))),o.latestRevisions=E,o.remoteDbId=I.dbId,o.initiallySynced=!0,o.realms=I.realms,o.inviteRealms=I.inviteRealms,o.serverRevision=I.serverRevision,o.yServerRevision=I.serverRevision,o.timestamp=new Date,delete o.error;const l=Vi(I.changes,r);if(yield sn(l,e),I.yMessages){const{receivedUntils:t,resyncNeeded:n,yServerRevision:r}=yield Ni(I.yMessages,e);r&&(o.yServerRevision=r),yield function(e,t,n){return s(this,void 0,void 0,function*(){var r,i,o,l,c;const a={};for(const[t,n]of Object.entries(e))null!==(r=a[t])&&void 0!==r||(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],r=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,()=>s(this,void 0,void 0,function*(){const t=yield n.table(e).get(on);t?(t.unsentFrom=Math.max(r,t.unsentFrom||1),t.receivedUntil=Math.max(i,t.receivedUntil||0),yield n.table(e).put(t)):yield n.table(e).add({i:on,unsentFrom:r,receivedUntil:i})}))}})}(S,t,e),n&&(o.yDownloadedRealms={})}return e.$syncState.put(o,"syncState"),{done:0===r.length,newSyncState:o}}));if(!O)return yield Qt(e),yield Hi(e,t,n,{isInitialSync:r,cancelToken:i});const A=Object.values(n).some(e=>{var t;return null===(t=e.yProps)||void 0===t?void 0:t.length}),T=!!I.yMessages;if(A&&T)try{yield Bi(e,a,D)}catch(e){}return e.syncCompleteEvent.next(),!1})}function Vi(e,t){const n={};y(n,e);const r={};return y(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))d(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 zi(e){const i=[],o=new n.BehaviorSubject(!0),l=new n.BehaviorSubject(null);let c=!1,a=new Array(10).fill(0);return l.subscribe(()=>s(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 s(this,void 0,void 0,function*(){for(var o,l,c,a,d,u;i.length>0;){const h=i.shift();try{yield n.firstValueFrom(e.cloud.syncState.pipe(r.filter(({phase:e})=>"in-sync"===e||"error"===e)));const i=e.cloud.persistedSyncState.value;if(!h)continue;switch(h.type){case"token-expired":const n=e.cloud.currentUser.value,r=yield We(e.cloud.options.databaseUrl,n);yield e.table("$logins").update(n.userId,{accessToken:r.accessToken,accessTokenExpiration:r.accessTokenExpiration,claims:r.claims,license:r.license,data:r.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 e.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 e.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 e.cloud.sync({purpose:"pull",wait:!0}));break;case"realms-changed":yield e.cloud.sync({purpose:"pull",wait:!0});break;case"changes":if("error"===(null===(u=e.cloud.syncState.value)||void 0===u?void 0:u.phase)){Ae(e,"pull");break}yield e.transaction("rw",e.dx.tables,n=>s(this,void 0,void 0,function*(){n.idbtrans.disableChangeTracking=!0,n.idbtrans.disableAccessControl=!0;const[r,s,i]=yield Promise.all([e.getSchema(),e.getPersistedSyncState(),e.getCurrentUser()]);if(!s||!r||!i)return;if(h.baseRev!==s.serverRevision)return void("string"!=typeof h.baseRev||"bigint"!=typeof s.serverRevision&&"object"!=typeof s.serverRevision||Ae(e,"pull"));if((yield t.waitFor(dt(s)))!==h.realmSetHash)return void Ae(e,"pull");let o=[];if(i.isLoggedIn){const t=ut(e).map(t=>e.table(ht(t.name)));o=yield yt(t,e)}if(h.changes.length>0){const t=Vi(h.changes,o);yield sn(t,e)}s.latestRevisions=nn(o,s.latestRevisions),s.serverRevision=h.newRev,yield tn(e,r,s.latestRevisions,h.newRev),yield e.$syncState.put(s,"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 Ki=new WeakMap,Ji={members:"@id, [userId+realmId], [email+realmId], realmId",roles:"[realmId+name]",realms:"@realmId",$jobs:"",$syncState:"",$baseRevs:"[tableName+clientRev]",$logins:"claims.sub, lastLogin"};let qi=0;function Yi(e){"vip"in e&&(e=e.vip);let t=Ki.get(e.cloud);if(!t){const r=new n.Subject;let s=new at(`syncstatechanged-${e.name}`),i=new at(`synccomplete-${e.name}`);r.id=++qi;let o=!1;t={get name(){return e.name},close:()=>e.close(),transaction:e.transaction.bind(e),table:e.table.bind(e),get tables(){return e.tables},cloud:e.cloud,get $jobs(){return e.table("$jobs")},get $syncState(){return e.table("$syncState")},get $baseRevs(){return e.table("$baseRevs")},get $logins(){return e.table("$logins")},get realms(){return e.realms},get members(){return e.members},get roles(){return e.roles},get initiallySynced(){return o},localSyncEvent:r,get syncStateChangedEvent(){return s},get syncCompleteEvent(){return i},dx:e};const l={getCurrentUser:()=>t.$logins.toArray().then(e=>e.find(e=>e.isLoggedIn)||ze),getPersistedSyncState:()=>t.$syncState.get("syncState"),getSchema:()=>t.$syncState.get("schema").then(e=>{if(e)for(const n of t.tables)n.schema.primKey&&n.schema.primKey.keyPath&&e[n.name]&&(e[n.name].primaryKey=Gi(n.schema.primKey.keyPath));return e}),getOptions:()=>t.$syncState.get("options"),setInitiallySynced(e){o=e},reconfigure(){s=new at(`syncstatechanged-${e.name}`),i=new at(`synccomplete-${e.name}`)}};Object.assign(t,l),t.messageConsumer=zi(t),t.messageProducer=new n.Subject,Ki.set(e.cloud,t)}return t}function Gi(e){return"string"==typeof e?e:e?"["+[].join.call(e,"+")+"]":""}const Qi="undefined"!=typeof InstallTrigger,Xi="undefined"!=typeof navigator&&/Safari\//.test(navigator.userAgent)&&!/Chrom(e|ium)\/|Edge\//.test(navigator.userAgent),Zi=Xi?[].concat(navigator.userAgent.match(/Safari\/(\d*)/))[1]:NaN,eo=Xi&&Zi<=605||Qi,to="undefined"!=typeof self&&"clients"in self&&!self.document;const{toString:no}={};function ro(e){return no.call(e).slice(8,-1)}function so(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 io(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 oo=/b|c|d|f|g|h|j|k|l|m|n|p|q|r|s|t|v|x|y|z/i;function lo(e){return e>="A"&&e<="Z"}let co=0;function ao(e,t){const n=new Uint8Array(18),r=new Uint8Array(n.buffer,0,6),s=Date.now();co>=s?++co:co=s,r[0]=co/1099511627776,r[1]=co/4294967296,r[2]=co/16777216,r[3]=co/65536,r[4]=co/256,r[5]=co;const i=new Uint8Array(n.buffer,6);crypto.getRandomValues(i);return e+Dt(new Uint8Array(n.buffer))+(t||"")}function uo(e){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=e.cloud.schema)||void 0===i?void 0:i[r];if(null==l?void 0:l.generatedGlobalId){if((null===(o=e.cloud.options)||void 0===o?void 0:o.databaseUrl)&&!e.initiallySynced){const e=so(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=so(s.schema.primaryKey,n);return l.forEach((c,a)=>{if(void 0===c){const r=n.values[a].realmId||e.cloud.currentUserId,c=r.substr(r.length-3);l[a]=ao(i,c),s.schema.primaryKey.outbound||(o||(o=n.values.slice()),o[a]=t.deepClone(o[a]),t.setByKeyPath(o[a],s.schema.primaryKey.keyPath,l[a]))}else if("string"!=typeof c||!c.startsWith(i)&&!c.startsWith("#"+i))throw new t.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){so(s.schema.primaryKey,n).forEach((e,n)=>{if(!f(e)){const n=Array.isArray(e)?e.map(ro).join(","):ro(e);throw new t.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 ho=0;function fo(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 po(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 go=new n.BehaviorSubject(new Set);function yo(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 mo({currentUserObservable:e,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:(t,s)=>{let i;if("readwrite"===s){const e=t.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=>ht(e));i=r.transaction([...t,...e],s)}else i=r.transaction(t,s);if("readwrite"===s){i.txid=mt(16),i.opCount=0,i.currentUser=e.value,go.value.add(i),go.next(go.value);const t=()=>{i.removeEventListener("complete",r),i.removeEventListener("error",t),i.removeEventListener("abort",t),go.value.delete(i),go.next(go.value)},r=()=>{i.mutationsAdded&&!yo(n)&&Ae(n,"push"),t()};i.addEventListener("complete",r),i.addEventListener("error",t),i.addEventListener("abort",t)}return i},table:e=>{const s=r.table(e);if(/^\$/.test(e))return e.endsWith("_mutations")?Object.assign(Object.assign({},s),{mutate:e=>("add"!==e.type&&"put"!==e.type||(e.trans.mutationsAdded=!0),s.mutate(e))}):"$logins"===e?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(e);return l?function(e){const t="$lock"+ ++ho;return Object.assign(Object.assign({},e),{count:fo(e.count,t),get:fo(e.get,t),getMany:fo(e.getMany,t),openCursor:fo(e.openCursor,t),query:fo(e.query,t),mutate:po(e.mutate,t)})}(Object.assign(Object.assign({},s),{mutate:t=>{var r,o,l;const a=t.trans;return a.txid?a.disableChangeTracking?s.mutate(t):(null===(o=null===(r=n.cloud.schema)||void 0===r?void 0:r[e])||void 0===o?void 0:o.markedForSync)&&(null===(l=a.currentUser)||void 0===l?void 0:l.isLoggedIn)?"deleteRange"===t.type?s.query({query:{range:t.range,index:i.primaryKey},trans:t.trans,values:!1}).then(e=>c({type:"delete",keys:e.result,trans:t.trans,criteria:{index:null,range:t.range}})):c(t):s.mutate(t):s.mutate(t)}})):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[e],{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(e=>{var n;const{numFailures:s,failures:o}=e;let c="delete"===f?r.keys:e.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 e;if(v){let e=v.changeSpecs.map(g),n={keys:[],changeSpecs:[]};const r=new t.RangeSet;let s=!1;if(!b){for(let t=0,i=e.length;t<i;++t)Object.keys(e[t]).length>0?(n.keys.push(v.keys[t]),n.changeSpecs.push(e[t]),r.addKey(v.keys[t])):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,e)):e})}}})}}}function vo(e,t){return function(n,r){var s;const i=Object.assign(Object.assign({},Ji),n);Object.keys(Ji).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=Ji[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(Ji[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)(oo.test(e[t])||lo(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=io(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 bo(e,t,n){return"undefined"!=typeof navigator&&navigator.locks?navigator.locks.request(e.name+"|"+t,n):n()}const wo=new n.BehaviorSubject(!0),_o=new n.BehaviorSubject(!0);wo.pipe(r.switchMap(e=>e?n.of(!0):n.of(!1).pipe(r.delay(2e4))),r.distinctUntilChanged()).subscribe(_o);const ko="undefined"!=typeof document?n.fromEvent(document,"visibilitychange"):n.of({}),So=ko.pipe(r.filter(()=>"hidden"===document.visibilityState)),xo=ko.pipe(r.filter(()=>"visible"===document.visibilityState)),Eo="undefined"!=typeof window?n.merge(xo,n.fromEvent(window,"mousedown"),n.fromEvent(window,"mousemove"),n.fromEvent(window,"keydown"),n.fromEvent(window,"wheel"),n.fromEvent(window,"touchmove")):n.of({});"undefined"!=typeof document&&n.merge(n.of(!0),So,Eo).pipe(r.map(()=>"visible"===document.visibilityState),r.tap(e=>{wo.value!==e&&wo.next(e)}),r.switchMap(e=>e?n.of(0).pipe(r.delay(16e4),r.tap(()=>wo.next(!1))):n.of(0))).subscribe(()=>{});class Co extends Error{constructor(){super(...arguments),this.name="TokenExpiredError"}}const Io=new WeakMap,Oo=3e4;class Do extends hn{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval(()=>{const e=mn();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&&Oo<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)}),t.length>0&&Ao(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:mn()});const i=[],o=[],l=[],c=[];null===e?c.push(t):null==s?null!=e&&i.push(t):(o.push(t),jn(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 Ao=(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:mn()})}r.push(s)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},To=new WeakMap;function jo(e){let t=To.get(e);return t||(t=new n.Subject,To.set(e,t)),t}class Uo extends n.Observable{constructor(e,t,n,r,s,i,o,l){super(c=>new Lo(e,t,n,r,s,l,c,i,o))}}let Po=0;class Lo extends n.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 s(this,void 0,void 0,function*(){if(this.lastServerActivity=new Date,this.pauseUntil&&this.pauseUntil>new Date)return;if(this.ws)throw new Error("Called connect() when a connection is already open");if(!this.databaseUrl)throw new Error("Cannot connect without a database URL");if(this.closed)return;const e=this.user.accessTokenExpiration;if(e&&e<new Date)return void this.subscriber.error(new Co);this.webSocketStatus.next("connecting"),this.pinger=setInterval(()=>s(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 r=new URL(this.databaseUrl);r.protocol="http:"===r.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(`${r}/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?Kt.parse(e.data):function(e){const t=new ue(e),n=ve(t);if("outdated-server-rev"===n)return{type:n};if("y-complete-sync-done"===n)return{type:n,yServerRev:ve(t)};const r=ve(t),s=ve(t);switch(n){case"u-ack":case"u-reject":return{type:n,table:r,prop:s,i:Number(we(t))};default:{const e=ke(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:pe(t)};case"doc-open":return{type:n,table:r,prop:s,k:e,serverRev:ke(t),sv:ke(t)};case"sv":return{type:n,table:r,prop:s,k:e,sv:pe(t)};case"u-c":return{type:n,table:r,prop:s,k:e,u:pe(t),i:Number(we(t))};case"u-s":return{type:n,table:r,prop:s,k:e,u:pe(t),r:t.pos<t.arr.length&&ve(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=$i.getDocCache(this.db.dx).find(t.table,t.k,t.prop);if(e){const n=(e=>Io.get(e))(e);n&&((e,t,n)=>{const r=he(t),s=mn(),i=[],o=[],l=[],c=[],a=ye(r);for(let t=0;t<a;t++){const t=ye(r);let n=ye(r);const a=JSON.parse(ve(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&&(jn(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=$i.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?Ni([t],this.db).then(e=>s(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=Ci(this.db,t.table,t.prop);if(e){const t=r[e.name];t&&(yield e.update(on,{receivedUntil:t}))}}e&&(yield this.db.cloud.sync({purpose:"pull",wait:!0}))})):this.subscriber.next(t)}catch(e){this.subscriber.error(e)}}};try{let e=!1;yield new Promise((t,n)=>{o.onopen=n=>{e=!0,t(null)},o.onerror=t=>{if(e)this.reconnect();else{const e=t.error||new Error("WebSocket Error");this.subscriber.error(e),this.webSocketStatus.next("error"),n(e)}}}),this.subscriptions.add(this.messageProducer.subscribe(e=>{var t,n;this.closed||("ready"===e.type&&"connected"!==this.webSocketStatus.value&&this.webSocketStatus.next("connected"),"ready"===e.type?(this.rev=e.rev,null===(t=this.ws)||void 0===t||t.send(Kt.stringify(e))):null===(n=this.ws)||void 0===n||n.send(function(e){const t=new $;switch(J(t,e.type),"table"in e&&J(t,e.table),"prop"in e&&J(t,e.prop),e.type){case"u-ack":case"u-reject":Q(t,BigInt(e.i));break;case"outdated-server-rev":break;case"y-complete-sync-done":J(t,e.yServerRev);break;default:switch(Z(t,e.k),e.type){case"aware":Y(t,e.u);break;case"doc-open":Z(t,e.serverRev),Z(t,e.sv);break;case"doc-close":break;case"sv":Y(t,e.sv);break;case"u-c":Y(t,e.u),Q(t,BigInt(e.i));break;case"u-s":Y(t,e.u),J(t,e.r||"")}}return B(t)}(e)))})),this.user.isLoggedIn&&!yo(this.db)&&this.subscriptions.add(function(e){const r=gt(e.tables.filter(t=>{var n,r;return(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[t.name])||void 0===r?void 0:r.markedForSync)&&t.schema.yProps}).map(e=>e.schema.yProps.map(t=>({table:e.name,ydocProp:t.prop,updatesTable:t.updatesTable}))));return n.merge(...r.map(({table:r,ydocProp:i,updatesTable:o})=>{const l=e.table(o);return n.from(l.get(on)).pipe(n.switchMap(e=>{let o=(null==e?void 0:e.unsentFrom)||1;return n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){return(yield ln(l,o)).filter(e=>e.f&&1&e.f).map(e=>({type:"u-c",table:r,prop:i,k:e.k,u:e.u,i:e.i}))}))).pipe(n.tap(e=>{e.length>0&&(o=e.at(-1).i+1)}))}))})).pipe(n.mergeMap(e=>e))}(this.db).subscribe(this.db.messageProducer))}catch(e){this.pauseUntil=new Date(Date.now()+6e4)}})}}class Mo 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 s(this,void 0,void 0,function*(){var e;yield(e=3e3,new Promise(t=>setTimeout(t,e))),yield n.firstValueFrom(Eo)})}function $o(e){return s(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 Wi(e,e.cloud.options,e.cloud.schema,{justCheckIfNeeded:!0}))})}const No=new WeakMap;function Bo(e,t,n,r){const i=No.get(e);if(i){if(i.pull||"push"===(null==r?void 0:r.purpose))return i.promise;{let s=!1;const o=e.cloud.syncState.subscribe(e=>{"pulling"===e.phase&&(s=!0)});return i.promise.then(()=>{o.unsubscribe()}).catch(e=>(o.unsubscribe(),Promise.reject(e))).then(()=>{if(!s)return Bo(e,t,n,r)})}}const o=function(){return s(this,void 0,void 0,function*(){try{yield Qt(e),yield bo(e,Fi,()=>Wi(e,t,n,r)),No.delete(e)}catch(t){throw No.delete(e),t}})}();return No.set(e,{promise:o,pull:"push"!==(null==r?void 0:r.purpose)}),o}function Fo(e,t,n){let r=null,s={cancelled:!1},i=0,o=0;function l(r=1){setTimeout(()=>{const h=c?"pull":"push";o=Date.now(),Bo(e,t,n,{cancelToken:s,retryImmediatelyOnFetchError:!0,purpose:h}).then(()=>{if(s.cancelled)u();else if(c||a)return c=!1,a=!1,l();d=!1,i=0,o=0}).catch(e=>{if(s.cancelled)u(),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=()=>{s.cancelled=!0,r&&r.unsubscribe()};return{start:()=>{r=e.localSyncEvent.subscribe(({purpose:e})=>{(e=>{s.cancelled||("pull"===e&&(c=!0),"push"===e&&(a=!0),d?i||o>0&&Date.now():(d=!0,l()))})(e||"pull")})},stop:u}}function Wo(e,t){if(e&&t&&t.unsyncedTables)for(const n of t.unsyncedTables)e[n]&&(e[n].markedForSync=!1)}var Ho,Vo,zo,Ko,Jo,qo,Yo,Go,Qo,Xo,Zo,el={},tl=[],nl=/acit|ex(?:s|g|n|p|$)|rph|grid|ows|mnc|ntw|ine[ch]|zoo|^ord|itera/i,rl=Array.isArray;function sl(e,t){for(var n in t)e[n]=t[n];return e}function il(e){e&&e.parentNode&&e.parentNode.removeChild(e)}function ol(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?Ho.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 ll(e,o,r,s,null)}function ll(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?++zo:s,__i:-1,__u:0};return null==s&&null!=Vo.vnode&&Vo.vnode(i),i}function cl(e){return e.children}function al(e,t){this.props=e,this.context=t}function dl(e,t){if(null==t)return e.__?dl(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?dl(e):null}function ul(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 ul(e)}}function hl(e){(!e.__d&&(e.__d=!0)&&Ko.push(e)&&!fl.__r++||Jo!=Vo.debounceRendering)&&((Jo=Vo.debounceRendering)||qo)(fl)}function fl(){for(var e,t,n,r,s,i,o,l=1;Ko.length;)Ko.length>l&&Ko.sort(Yo),e=Ko.shift(),l=Ko.length,e.__d&&(n=void 0,r=void 0,s=(r=(t=e).__v).__e,i=[],o=[],t.__P&&((n=sl({},r)).__v=r.__v+1,Vo.vnode&&Vo.vnode(n),wl(t.__P,n,r,t.__n,t.__P.namespaceURI,32&r.__u?[s]:null,i,null==s?dl(r):s,!!(32&r.__u),o),n.__v=r.__v,n.__.__k[n.__i]=n,kl(i,n,o),r.__e=r.__=null,n.__e!=s&&ul(n)));fl.__r=0}function pl(e,t,n,r,s,i,o,l,c,a,d){var u,h,f,p,g,y,m,v=r&&r.__k||tl,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]=ll(null,o,null,null,null):rl(o)?o=e.__k[i]=ll(cl,{children:o},null,null,null):null==o.constructor&&o.__b>0?o=e.__k[i]=ll(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=yl(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=dl(l)),Cl(l,l));return r}(n,t,v,c,b),u=0;u<b;u++)null!=(f=n.__k[u])&&(h=-1==f.__i?el:v[f.__i]||el,f.__i=u,y=wl(e,f,h,s,i,o,l,c,a,d),p=f.__e,f.ref&&h.ref!=f.ref&&(h.ref&&El(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=gl(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 gl(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=gl(s[i],t,n,r));return t}e.__e!=t&&(r&&(t&&e.type&&!t.parentNode&&(t=dl(e)),n.insertBefore(e.__e,t||null)),t=e.__e);do{t=t&&t.nextSibling}while(null!=t&&8==t.nodeType);return t}function yl(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 ml(e,t,n){"-"==t[0]?e.setProperty(t,null==n?"":n):e[t]=null==n?"":"number"!=typeof n||nl.test(t)?n:n+"px"}function vl(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||ml(e.style,t,"");if(n)for(t in n)r&&n[t]==r[t]||ml(e.style,t,n[t])}else if("o"==t[0]&&"n"==t[1])i=t!=(t=t.replace(Go,"$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=Qo,e.addEventListener(t,i?Zo:Xo,i)):e.removeEventListener(t,i?Zo:Xo,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 bl(e){return function(t){if(this.l){var n=this.l[t.type+e];if(null==t.t)t.t=Qo++;else if(t.t<n.u)return;return n(Vo.event?Vo.event(t):t)}}}function wl(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=Vo.__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 al(m,w),u.constructor=I,u.render=Il),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=sl({},u.__s)),sl(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=Vo.__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=sl(sl({},r),u.getChildContext())),v&&!h&&null!=u.getSnapshotBeforeUpdate&&(g=u.getSnapshotBeforeUpdate(f,p)),E=d,null!=d&&d.type===cl&&null==d.key&&(E=Sl(d.props.children)),l=pl(e,rl(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--;)il(i[C]);_l(t)}else t.__e=n.__e,t.__k=n.__k,e.then||_l(t);Vo.__e(e,t,n)}else null==i&&t.__v==n.__v?(t.__k=n.__k,t.__e=n.__e):l=t.__e=xl(n.__e,t,n,r,s,i,o,c,a);return(d=Vo.diffed)&&d(t),128&t.__u?void 0:l}function _l(e){e&&e.__c&&(e.__c.__e=!0),e&&e.__k&&e.__k.forEach(_l)}function kl(e,t,n){for(var r=0;r<n.length;r++)El(n[r],n[++r],n[++r]);Vo.__c&&Vo.__c(t,e),e.some(function(t){try{e=t.__h,t.__h=[],e.some(function(e){e.call(t)})}catch(e){Vo.__e(e,t.__v)}})}function Sl(e){return"object"!=typeof e||null==e||e.__b&&e.__b>0?e:rl(e)?e.map(Sl):sl({},e)}function xl(e,t,n,r,s,i,o,l,c){var a,d,u,h,f,p,g,y=n.props||el,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&&(Vo.__m&&Vo.__m(t,i),l=!1),i=null}if(null==v)y===m||l&&e.data==m||(e.data=m);else{if(i=i&&Ho.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;vl(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||vl(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=""),pl("template"==t.type?e.content:e,rl(h)?h:[h],t,n,r,"foreignObject"==v?"http://www.w3.org/1999/xhtml":s,i,o,i?i[0]:n.__k&&dl(n,0),l,c),null!=i)for(a=i.length;a--;)il(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])&&vl(e,a,p,y[a],s),a="checked",null!=g&&g!=e[a]&&vl(e,a,g,y[a],s))}return e}function El(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){Vo.__e(e,n)}}function Cl(e,t,n){var r,s;if(Vo.unmount&&Vo.unmount(e),(r=e.ref)&&(r.current&&r.current!=e.__e||El(r,null,t)),null!=(r=e.__c)){if(r.componentWillUnmount)try{r.componentWillUnmount()}catch(e){Vo.__e(e,t)}r.base=r.__P=null}if(r=e.__k)for(s=0;s<r.length;s++)r[s]&&Cl(r[s],t,n||"function"!=typeof e.type);n||il(e.__e),e.__c=e.__=e.__e=void 0}function Il(e,t,n){return this.constructor(e,n)}function Ol(e,t,n){var r,s,i;t==document&&(t=document.documentElement),Vo.__&&Vo.__(e,t),r=!1?null:t.__k,s=[],i=[],wl(t,e=t.__k=ol(cl,null,[e]),r||el,el,t.namespaceURI,r?null:t.firstChild?Ho.call(t.childNodes):null,s,r?r.__e:t.firstChild,false,i),kl(s,e,i)}Ho=tl.slice,Vo={__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}},zo=0,al.prototype.setState=function(e,t){var n;n=null!=this.__s&&this.__s!=this.state?this.__s:this.__s=sl({},this.state),"function"==typeof e&&(e=e(sl({},n),this.props)),e&&sl(n,e),null!=e&&this.__v&&(t&&this._sb.push(t),hl(this))},al.prototype.forceUpdate=function(e){this.__v&&(this.__e=!0,e&&this.__h.push(e),hl(this))},al.prototype.render=cl,Ko=[],qo="function"==typeof Promise?Promise.prototype.then.bind(Promise.resolve()):setTimeout,Yo=function(e,t){return e.__v.__b-t.__v.__b},fl.__r=0,Go=/(PointerCapture)$|Capture$/i,Qo=0,Xo=bl(!1),Zo=bl(!0);const Dl={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},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"},CancelButtonRow:{display:"flex",justifyContent:"center",marginTop:"16px"}};function Al({children:e,className:t}){return ol("div",{className:`dexie-dialog ${t||""}`},ol("div",{style:Dl.Darken}),ol("div",{style:Dl.DialogOuter},ol("div",{style:Dl.DialogInner},e)))}var Tl,jl,Ul,Pl,Ll=0,Ml=[],Rl=Vo,$l=Rl.__b,Nl=Rl.__r,Bl=Rl.diffed,Fl=Rl.__c,Wl=Rl.unmount,Hl=Rl.__;function Vl(e,t){Rl.__h&&Rl.__h(jl,e,Ll||t),Ll=0;var n=jl.__H||(jl.__H={__:[],__h:[]});return e>=n.__.length&&n.__.push({}),n.__[e]}function zl(e){return Ll=1,function(e,t){var n=Vl(Tl++,2);if(n.t=e,!n.__c&&(n.__=[Zl(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.__}(Zl,e)}function Kl(e){return Ll=5,function(e,t){var n=Vl(Tl++,7);return Xl(n.__H,t)&&(n.__=e(),n.__H=t,n.__h=e),n.__}(function(){return{current:e}},[])}function Jl(){for(var e;e=Ml.shift();)if(e.__P&&e.__H)try{e.__H.__h.forEach(Gl),e.__H.__h.forEach(Ql),e.__H.__h=[]}catch(t){e.__H.__h=[],Rl.__e(t,e.__v)}}Rl.__b=function(e){jl=null,$l&&$l(e)},Rl.__=function(e,t){e&&t.__k&&t.__k.__m&&(e.__m=t.__k.__m),Hl&&Hl(e,t)},Rl.__r=function(e){Nl&&Nl(e),Tl=0;var t=(jl=e.__c).__H;t&&(Ul===jl?(t.__h=[],jl.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.u=e.__N=void 0})):(t.__h.forEach(Gl),t.__h.forEach(Ql),t.__h=[],Tl=0)),Ul=jl},Rl.diffed=function(e){Bl&&Bl(e);var t=e.__c;t&&t.__H&&(t.__H.__h.length&&(1!==Ml.push(t)&&Pl===Rl.requestAnimationFrame||((Pl=Rl.requestAnimationFrame)||Yl)(Jl)),t.__H.__.forEach(function(e){e.u&&(e.__H=e.u),e.u=void 0})),Ul=jl=null},Rl.__c=function(e,t){t.some(function(e){try{e.__h.forEach(Gl),e.__h=e.__h.filter(function(e){return!e.__||Ql(e)})}catch(n){t.some(function(e){e.__h&&(e.__h=[])}),t=[],Rl.__e(n,e.__v)}}),Fl&&Fl(e,t)},Rl.unmount=function(e){Wl&&Wl(e);var t,n=e.__c;n&&n.__H&&(n.__H.__.forEach(function(e){try{Gl(e)}catch(e){t=e}}),n.__H=void 0,t&&Rl.__e(t,n.__v))};var ql="function"==typeof requestAnimationFrame;function Yl(e){var t,n=function(){clearTimeout(r),ql&&cancelAnimationFrame(t),setTimeout(e)},r=setTimeout(n,35);ql&&(t=requestAnimationFrame(n))}function Gl(e){var t=jl,n=e.__c;"function"==typeof n&&(e.__c=void 0,n()),jl=t}function Ql(e){var t=jl;e.__c=e.__(),jl=t}function Xl(e,t){return!e||e.length!==t.length||t.some(function(t,n){return t!==e[n]})}function Zl(e,t){return"function"==typeof t?t(e):t}function ec({message:e,messageCode:t,messageParams:n}){return e.replace(/\{\w+\}/gi,e=>n[e.substring(1,e.length-1)])}function tc({title:e,type:t,alerts:n,fields:r,submitLabel:s,cancelLabel:i,onCancel:o,onSubmit:l}){const[c,a]=zl({}),d=Kl(null);return function(e,t){var n=Vl(Tl++,4);!Rl.__s&&Xl(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()},[]),ol(Al,{className:"dxc-login-dlg"},ol(cl,null,ol("h3",{style:Dl.WindowHeader},e),n.map(e=>ol("p",{style:Dl.Alert[e.type]},ec(e))),ol("form",{onSubmit:e=>{e.preventDefault(),l(c)}},Object.entries(r).map(([e,{type:t,label:n,placeholder:r}],s)=>ol("label",{style:Dl.Label,key:s},n?`${n}: `:"",ol("input",{ref:0===s?d:void 0,type:t,name:e,autoComplete:"on",style:Dl.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)}}))))),ol("div",{style:Dl.ButtonsDiv},ol(cl,null,ol("button",{type:"submit",style:Dl.PrimaryButton,onClick:()=>l(c)},s),i&&ol("button",{style:Dl.Button,onClick:o},i))))}const nc={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 rc({provider:e,onClick:t}){const{type:n,name:r,displayName:s,iconUrl:i}=e,o=function(e){const t=Object.assign({},Dl.ProviderButton);switch(e){case"google":return Object.assign(Object.assign({},t),Dl.ProviderGoogle);case"github":return Object.assign(Object.assign({},t),Dl.ProviderGitHub);case"microsoft":return Object.assign(Object.assign({},t),Dl.ProviderMicrosoft);case"apple":return Object.assign(Object.assign({},t),Dl.ProviderApple);default:return Object.assign(Object.assign({},t),Dl.ProviderCustom)}}(n),l=`Continue with ${s}`,c=nc[n]||"";return ol("button",{type:"button",style:o,onClick:t,class:`dxc-provider-btn dxc-provider-${n}`,"aria-label":l},i?ol("img",{src:i,alt:"",style:Dl.ProviderButtonIcon,"aria-hidden":"true"}):c?ol("span",{style:Dl.ProviderButtonIcon,"aria-hidden":"true",dangerouslySetInnerHTML:{__html:c}}):null,ol("span",{style:Dl.ProviderButtonText},l))}function sc({onClick:e}){return ol("button",{type:"button",style:Dl.OtpButton,onClick:e,class:"dxc-otp-btn","aria-label":"Continue with email"},ol("span",{style:Dl.ProviderButtonIcon,"aria-hidden":"true",dangerouslySetInnerHTML:{__html:'<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>'}}),ol("span",{style:Dl.ProviderButtonText},"Continue with email"))}function ic(){return ol("div",{style:Dl.Divider},ol("div",{style:Dl.DividerLine}),ol("span",{style:Dl.DividerText},"or"),ol("div",{style:Dl.DividerLine}))}function oc({title:e,alerts:t,providers:n,otpEnabled:r,cancelLabel:s,onSelectProvider:i,onSelectOtp:o,onCancel:l}){return ol(Al,{className:"dxc-provider-selection-dlg"},ol(cl,null,ol("h3",{style:Dl.WindowHeader},e),t.map((e,t)=>ol("p",{key:t,style:Dl.Alert[e.type]},ec(e))),ol("div",{class:"dxc-providers"},n.map(e=>ol(rc,{key:e.name,provider:e,onClick:()=>i(e.name)}))),r&&n.length>0&&ol(cl,null,ol(ic,null),ol(sc,{onClick:o})),r&&0===n.length&&ol(sc,{onClick:o}),s&&ol("div",{style:Dl.CancelButtonRow},ol("button",{type:"button",style:Dl.Button,onClick:l},s))))}class lc extends al{constructor(e){super(e),this.observer=e=>this.setState({userInteraction:e}),this.state={userInteraction:void 0}}componentDidMount(){this.subscription=n.from(this.props.db.cloud.userInteraction).subscribe(this.observer)}componentWillUnmount(){this.subscription&&(this.subscription.unsubscribe(),delete this.subscription)}render(e,{userInteraction:t}){return t?"provider-selection"===t.type?ol(oc,Object.assign({},t)):ol(tc,Object.assign({},t)):null}}function cc(e){const t=new WeakMap;return n=>{let r=t.get(n);return r||(r=e(n),t.set(n,r)),r}}const ac=cc(e=>new n.BehaviorSubject(ze));function dc(e,t){let r=t,s=n.from(e).pipe(n.map(e=>r=e),n.share({resetOnRefCountZero:()=>n.timer(1e3)}));const i=new n.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 uc=cc(e=>dc(t.liveQuery(()=>e.roles.where({realmId:"rlm-public"}).toArray().then(e=>{const t={};for(const n of e.slice().sort((e,t)=>(e.sortOrder||0)-(t.sortOrder||0)))t[n.name]=n;return t})),{})),hc=cc(e=>dc(ac(e._novip).pipe(r.switchMap(n=>t.liveQuery(()=>e.transaction("r","realms","members",()=>Promise.all([e.members.where({userId:n.userId}).toArray(),e.realms.toArray(),n.userId]).then(([e,t,n])=>({selfMembers:e,realms:t,userId:n})))))),{selfMembers:[],realms:[],get userId(){return e.cloud.currentUserId}}));function fc(...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 pc=cc(e=>function(e,t){let r;const s=e.pipe(n.map(e=>r=t(e)));return s.getValue=()=>void 0!==r?r:r=t(e.getValue()),s}(dc(n.combineLatest([hc(e._novip),uc(e._novip)]).pipe(r.map(([{selfMembers:e,realms:t,userId:n},r])=>({selfMembers:e,realms:t,userId:n,globalRoles:r}))),{selfMembers:[],realms:[],userId:ze.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=gt(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:"*"}:fc(...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 gc{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 yc=cc(e=>{const i=ac(e._novip).pipe(r.switchMap(n=>t.liveQuery(()=>e.members.where({email:n.email||""}).toArray()))),o=pc(e._novip),l=hc(e._novip);return dc(n.combineLatest([i,l,o]).pipe(r.map(([t,n,r])=>{const i=(e,t)=>Object.assign(Object.assign({},e),{[t.id]:Object.assign(Object.assign({},t),{realm:r[t.realmId]})}),o=t.reduce(i,{}),l=n.selfMembers.reduce(i,o);return Object.values(l).filter(e=>!e.accepted).map(t=>Object.assign(Object.assign({},t),{accept(){return s(this,void 0,void 0,function*(){yield e.members.update(t.id,{accepted:new Date})})},reject(){return s(this,void 0,void 0,function*(){yield e.members.update(t.id,{rejected:new Date})})}}))})),[])});function mc(e){return r=>{var i;const o=r.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=e.cloud.schema)||void 0===i?void 0:i[l].markedForSync))return;let c;Object.defineProperty(r,"awareness",{get:()=>c||(c=function(e,r,i){const{parentTable:o,parentId:l,parentProp:c,updatesTable:a}=r.meta,d=new Do(r),u=jo(r);return d.on("update",({added:t,updated:n,removed:s},l)=>{const a=t.concat(n).concat(s),u=e.cloud.currentUser.value;if("server"!==l&&u.isLoggedIn&&!yo(e)){const t=((e,t,n=e.states)=>{const r=t.length,s=N();H(s,r);for(let i=0;i<r;i++){const r=t[i],o=n.get(r)||null,l=e.meta.get(r).clock;H(s,r),H(s,l),J(s,JSON.stringify(o))}return B(s)})(d,a);e.messageProducer.next({type:"aware",table:o,prop:c,k:r.meta.parentId,u:t}),i.destroyed&&e.messageProducer.next({type:"doc-close",table:o,prop:c,k:r.meta.parentId})}}),d.on("destroy",()=>{Ao(d,[r.clientID],"provider destroyed")}),(()=>{s(this,void 0,void 0,function*(){if(i.destroyed)return;let r=!1,d=1;const h=n.combineLatest([e.cloud.webSocketStatus,u.pipe(n.startWith(null))]).subscribe(([t])=>{if(i.destroyed)return;r="connected"===t;const n=e.cloud.currentUser.value;"connected"===t&&n.isLoggedIn&&!yo(e)&&(++d,f().catch(e=>{}))});function f(){return s(this,void 0,void 0,function*(){const n=d,u=e.table(a),h=e.$syncState,[f,p]=yield e.transaction("r",h,u,()=>s(this,void 0,void 0,function*(){const e=yield u.get(on),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!==n||!r)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(e=>0===t.cmp(e.k,l)&&!(1&(e.f||0))).toArray();if(!i.destroyed&&d===n&&r){if(y.length>0){const e=Yr(y.map(e=>e.u)),t=Jr(e);g.sv=t}e.messageProducer.next(g)}})}i.addCleanupHandler(h)})})(),d}(e,o,r),Io.set(o,c),c)})}}const vc={},bc=new WeakMap,wc=kc("tx"),_c=kc("unload");function kc(e){let t=null,n=!1,r=new Map;return{name:e,run(){return s(this,void 0,void 0,function*(){!n&&r.size>0&&(n=!0,t&&(yield t.catch(()=>{})),setTimeout(()=>{n=!1;const e=r;r=new Map,t=function(e){return s(this,void 0,void 0,function*(){for(const{db:t,parentId:n,triggers:r,parentTable:s,prop:i}of e.values()){const e=$i.getOrCreateDocument(t,s,i,n);try{const t=$i.load(e);yield t.whenLoaded;for(const t of r)yield t(e,n)}catch(e){null==e||e.name}finally{$i.release(e)}}})}(e).finally(()=>{t=null})},0))})},enqueue(e,t,n,s,i){const o=`${e.name}:${t}:${n}:${s}`;let l=r.get(o);l||(l={db:e,parentTable:t,parentId:n,prop:s,triggers:new Set},r.set(o,l)),l.triggers.add(i)}}}function Sc(){wc.run()}function xc(){_c.run()}const Ec={nameSuffix:!0};function Cc(e){const i=e.name,o=ac(e),l=[];let c=!1,a=null;e.on("ready",e=>s(this,void 0,void 0,function*(){try{yield function(e){return s(this,void 0,void 0,function*(){var i,f,p,g,y,m,v;d=!1;const b=Yi(e);"undefined"!=typeof window&&"undefined"!=typeof document&&((null===(i=b.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),Ol(ol(lc,{db:e.vip}),n)):addEventListener("DOMContentLoaded",()=>{t||(document.body.appendChild(n),Ol(ol(lc,{db:e.vip}),n))}),{unsubscribe(){try{n.remove()}catch(e){}t=!0},get closed(){return t}}}(e))),b.cloud.isServiceWorkerDB||l.push(function(e){let t=e.cloud.webSocketStatus.value;const s=e.cloud.webSocketStatus.pipe(r.switchMap(e=>{const s=t;t=e;const i=n.of(e);switch(e){case"disconnected":return wo.value?i.pipe(r.debounceTime(500)):i;case"connecting":return"not-started"===s||"error"===s?i:i.pipe(r.debounceTime(4e3));default:return i}}));return n.combineLatest([s,e.syncStateChangedEvent.pipe(r.startWith({phase:"initial"})),ac(e.dx._novip),_o]).pipe(r.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:en?a:"offline",license:"ok"}}))}(b).subscribe(e.cloud.syncState)),l.push(b.syncCompleteEvent.subscribe(h)),b.tables.every(e=>e.core)||function(){throw new t.SchemaError("Version increment needed to allow dexie-cloud change tracking")}();const w="serviceWorker"in navigator?yield navigator.serviceWorker.getRegistrations():[],[_,k]=yield b.transaction("rw",b.$syncState,()=>s(this,void 0,void 0,function*(){var e,t;const{options:n,schema:r}=b.cloud,[s,i,o]=yield Promise.all([b.getOptions(),b.getSchema(),b.getPersistedSyncState()]);if(c){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 b.$syncState.put(e,"options")}}else b.cloud.options=s||null;if((null===(e=b.cloud.options)||void 0===e?void 0:e.tryUseServiceWorker)&&"serviceWorker"in navigator&&w.length>0&&!eo?b.cloud.usingServiceWorker=!0:((null===(t=b.cloud.options)||void 0===t?void 0:t.tryUseServiceWorker)&&b.cloud.isServiceWorkerDB,b.cloud.usingServiceWorker=!1),Wo(r,b.cloud.options),Wo(i,b.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 b.$syncState.put(e,"schema"),Object.assign(r,e)}}else b.cloud.schema=i||null;return[null==o?void 0:o.initiallySynced,null==o?void 0:o.realms]}));if(_&&b.setInitiallySynced(!0),function(e){var n,r;for(const s of e.tables)if(null===(r=null===(n=e.cloud.schema)||void 0===n?void 0:n[s.name])||void 0===r?void 0:r.markedForSync){if(s.schema.primKey.auto)throw new t.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 t.SchemaError(`Table ${s.name} cannot be both synced and outbound. Use db.cloud.configure({unsyncedTables: [${JSON.stringify(s.name)}]}) to blacklist it from sync`)}}(b),u(),!b.cloud.isServiceWorkerDB){l.push(t.liveQuery(()=>b.getCurrentUser()).subscribe(o)),l.push(t.liveQuery(()=>b.getPersistedSyncState()).subscribe(b.cloud.persistedSyncState)),yield n.firstValueFrom(n.combineLatest([o.pipe(r.skip(1),r.take(1)),b.cloud.persistedSyncState.pipe(r.skip(1),r.take(1))]));const e=mc(b);$i.on.new.subscribe(e),b.dx.once("close",()=>{$i.on.new.unsubscribe(e)})}let S=!1;const x=yield b.getCurrentUser(),E=null===(f=b.cloud.options)||void 0===f?void 0:f.requireAuth;E&&(b.cloud.isServiceWorkerDB?yield n.firstValueFrom(o.pipe(r.filter(e=>!!e.isLoggedIn),r.take(1))):"object"==typeof E?(!x.isLoggedIn||E.userId&&x.userId!==E.userId||E.email&&x.email!==E.email)&&(S=yield st(b,E)):x.isLoggedIn||(S=yield st(b))),!x.isLoggedIn||k&&k.includes(x.userId)||(S=!0),a&&a.stop(),a=null,u();const C=(null===(p=b.cloud.options)||void 0===p?void 0:p.databaseUrl)&&(!_||S);C&&(yield function(e,t,n){return s(this,void 0,void 0,function*(){yield bo(e,Fi,()=>Wi(e,t,n,{isInitialSync:!0}))})}(b,b.cloud.options,b.cloud.schema),b.setInitiallySynced(!0)),u(),b.cloud.usingServiceWorker&&(null===(g=b.cloud.options)||void 0===g?void 0:g.databaseUrl)?(C||De(b,"push").catch(()=>{}),function(e){return s(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){}})}(b).catch(()=>{})):(null===(y=b.cloud.options)||void 0===y?void 0:y.databaseUrl)&&b.cloud.schema&&!b.cloud.isServiceWorkerDB&&(a=Fo(b,b.cloud.options,b.cloud.schema),a.start(),C||Ae(b,"push")),u(),b.cloud.isServiceWorkerDB||l.push(n.fromEvent(self,"online").subscribe(()=>{b.syncStateChangedEvent.next({phase:"not-in-sync"}),yo(b)||Ae(b,"push")}),n.fromEvent(self,"offline").subscribe(()=>{b.syncStateChangedEvent.next({phase:"offline"})})),!(null===(m=b.cloud.options)||void 0===m?void 0:m.databaseUrl)||(null===(v=b.cloud.options)||void 0===v?void 0:v.disableWebSocket)||to||l.push(function(e){var t;if(!(null===(t=e.cloud.options)||void 0===t?void 0:t.databaseUrl))throw new Error("No database URL to connect WebSocket to");const i=e.messageConsumer.readyToServe.pipe(r.filter(e=>e),r.switchMap(()=>e.getPersistedSyncState()),r.filter(e=>e&&e.serverRevision),r.switchMap(e=>s(this,void 0,void 0,function*(){return{type:"ready",rev:e.serverRevision,realmSetHash:yield dt(e)}}))),o=n.merge(i,e.messageProducer);return function t(){return e.cloud.persistedSyncState.pipe(r.filter(e=>null==e?void 0:e.serverRevision),r.take(1),r.switchMap(t=>e.cloud.currentUser.pipe(r.map(e=>[e,t]))),r.switchMap(([e,t])=>_o.pipe(r.map(n=>[n?e:null,t]))),r.switchMap(([t,s])=>(null==t?void 0:t.isLoggedIn)&&!(null==s?void 0:s.realms.includes(t.userId))?e.cloud.persistedSyncState.pipe(r.filter(e=>(null==e?void 0:e.realms.includes(t.userId))||!1),r.take(1),r.map(e=>[t,e])):new n.BehaviorSubject([t,s])),r.switchMap(e=>s(this,[e],void 0,function*([e,t]){return[e,yield dt(t)]})),r.distinctUntilChanged(([e,t],[n,r])=>e===n&&t===r),r.switchMap(([r,s])=>{var i;return(null===(i=e.cloud.persistedSyncState)||void 0===i?void 0:i.value)?r?new Uo(e,e.cloud.persistedSyncState.value.serverRevision,e.cloud.persistedSyncState.value.yServerRevision,s,e.cloud.persistedSyncState.value.clientIdentity,o,e.cloud.webSocketStatus,r):n.from([]):t()}),r.catchError(i=>"TokenExpiredError"===(null==i?void 0:i.name)?n.of(!0).pipe(r.switchMap(()=>s(this,void 0,void 0,function*(){const t=yield e.getCurrentUser(),n=yield We(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})})),r.switchMap(()=>t())):n.throwError(()=>i)),r.catchError(s=>(e.cloud.webSocketStatus.next("error"),s instanceof Mo?n.throwError(()=>s):n.from(Ro()).pipe(r.switchMap(()=>t())))))}().subscribe({next:t=>{t&&e.messageConsumer.enqueue(t)},error:e=>{},complete:()=>{}})}(b))})}(e)}catch(e){}}),!0);let d=!1;function u(){if(d)throw new t.DatabaseClosedError}e.once("close",()=>{l.forEach(e=>e.unsubscribe()),l.splice(0,l.length),d=!0,a&&a.stop(),a=null,o.next(ze)});const h=new n.Subject;var f;e.cloud={version:"4.3.0",options:Object.assign({},Ec),schema:null,get currentUserId(){return o.value.userId||ze.userId},currentUser:o,syncState:new n.BehaviorSubject({phase:"initial",status:"not-started"}),events:{syncComplete:h},persistedSyncState:new n.BehaviorSubject(void 0),userInteraction:new n.BehaviorSubject(void 0),webSocketStatus:new n.BehaviorSubject("not-started"),login(t){return s(this,void 0,void 0,function*(){const n=Yi(e);yield n.cloud.sync(),yield st(n,t)})},invites:yc(e),roles:uc(e),configure(t){t=e.cloud.options=Object.assign(Object.assign({},e.cloud.options),t),c=!0,t.databaseUrl&&t.nameSuffix&&(e.name=`${i}-${function(e){const t=new URL(e);return"/"===t.pathname?t.hostname.split(".")[0]:t.pathname.split("/")[1]}(t.databaseUrl)}`,Yi(e).reconfigure()),Wo(e.cloud.schema,e.cloud.options)},logout(){return s(this,arguments,void 0,function*({force:t}={}){t?yield qe(Yi(e),{deleteUnsyncedData:!0}):yield Je(Yi(e))})},sync(){return s(this,arguments,void 0,function*({wait:i,purpose:o}={wait:!0,purpose:"push"}){var l;void 0===i&&(i=!0);const c=Yi(e);if("ok"!==((null===(l=c.cloud.currentUser.value.license)||void 0===l?void 0:l.status)||"ok")&&(yield Be(c)),"pull"===o){const e=c.cloud.persistedSyncState.value;if(Ae(c,o),i){const t=yield n.firstValueFrom(c.cloud.persistedSyncState.pipe(r.filter(t=>null!=(null==t?void 0:t.timestamp)&&(!e||t.timestamp>e.timestamp))));if(null==t?void 0:t.error)throw new Error("Sync error: "+t.error)}}else if(yield $o(c)){const e=c.cloud.persistedSyncState.value;Ae(c,o),i&&(yield n.firstValueFrom(n.from(t.liveQuery(()=>s(this,void 0,void 0,function*(){const t=yield $o(c),n=yield c.getPersistedSyncState();if((null==n?void 0:n.timestamp)!==(null==e?void 0:e.timestamp)&&(null==n?void 0:n.error))throw new Error("Sync error: "+n.error);return t}))).pipe(r.filter(e=>!e))))}})},permissions:(t,n)=>function(e,t,n){if(!t)throw new TypeError("Cannot check permissions of undefined or null. A Dexie Cloud object with realmId and owner expected.");const{owner:s,realmId:i}=t;if(!n){if("function"!=typeof t.table)throw new TypeError("Missing 'table' argument to permissions and table could not be extracted from entity");n=t.table()}const o=pc(e),l=t=>{const r=t[i||e.cloud.currentUserId];return r?new gc(r.permissions,n,void 0===i||i===e.cloud.currentUserId||s===e.cloud.currentUserId):new gc({},n,!s||s===e.cloud.currentUserId)},c=o.pipe(r.map(l));return c.getValue=()=>l(o.getValue()),c}(e._novip,t,n)},e.Version.prototype._parseStoresSpec=t.override(e.Version.prototype._parseStoresSpec,t=>vo(t,e)),e.Table.prototype.newId=function({colocateWith:t}={}){const n=t&&t.substr(t.length-3);return ao(e.cloud.schema[this.name].idPrefix||"",n)},e.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)||""},e.use(mo({currentUserObservable:e.cloud.currentUser,db:Yi(e)})),e.use((f=Yi(e),{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,c;const a=e.trans;if(a.disableChangeTracking)return n.mutate(e);const d=null!==(s=null===(r=a.currentUser)||void 0===r?void 0:r.userId)&&void 0!==s?s:ze.userId;if((null===(o=null===(i=f.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=d),t.realmId||(t.realmId=d);const r=null===(c=(l=n.schema.primaryKey).extractKey)||void 0===c?void 0:c.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)}})}})})),e.use(uo(Yi(e)))}Cc.version="4.3.0",t.Cloud=Cc,e.default=Cc,e.defineYDocTrigger=function(e,n,r){var s,i;const o=null===(i=null===(s=e.schema.yProps)||void 0===s?void 0:s.find(e=>e.prop===n))||void 0===i?void 0:i.updatesTable;if(!o)throw new Error(`Table ${e.name} does not have a Yjs property named ${n}`);vc[o]={trigger:r,parentTable:e.name,prop:n};const l=e.db._novip;let c=bc.get(l);c||(c=(e=>({stack:"dbcore",level:10,name:"yTriggerMiddleware",create:n=>Object.assign(Object.assign({},n),{transaction:(e,t,r)=>{const s=n.transaction(e,t,r);return"readonly"===t?s:e.some(e=>vc[e])?(s.addEventListener("complete",Sc),s):s},table:r=>{const s=n.table(r),i=vc[r];if(!i)return s;const{trigger:o,parentTable:l,prop:c}=i;return Object.assign(Object.assign({},s),{mutate(n){var r;switch(n.type){case"add":for(const t of n.values){if(null==t.k)continue;const n=t.k,s=$i.getDocCache(e).find(l,n,c);(s&&(null===(r=$i.for(s))||void 0===r?void 0:r.refCount)?_c:wc).enqueue(e,l,n,c,o)}break;case"delete":n.trans._rejecting_y_ypdate&&s.getMany({keys:n.keys,trans:n.trans,cache:"immutable"}).then(n=>{const r=new t.RangeSet;for(const{k:e}of n)null!=e&&r.addKey(e);for(const t of r)wc.enqueue(e,l,t.from,c,o)})}return s.mutate(n)}})}})}))(l),bc.set(l,c)),l.use(c),$i.on("beforeunload",xc)},e.dexieCloud=Cc,e.getTiedObjectId=function(e){return e.startsWith("rlm~")?e.substr(4):null},e.getTiedRealmId=function(e){return"rlm~"+e},e.resolveText=ec,Object.defineProperty(e,"__esModule",{value:!0})});
|
|
2
2
|
//# sourceMappingURL=dexie-cloud-addon.min.js.map
|